max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,444 |
<reponame>GabrielSturtevant/mage
package mage.cards.a;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.GainLifeControllerTriggeredAbility;
import mage.abilities.effects.common.counter.AddCountersAllEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.abilities.keyword.LifelinkAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.counters.CounterType;
import mage.filter.StaticFilters;
/**
*
* @author Plopman
*/
public final class ArchangelOfThune extends CardImpl {
public ArchangelOfThune(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{W}{W}");
this.subtype.add(SubType.ANGEL);
this.power = new MageInt(3);
this.toughness = new MageInt(4);
// Flying
this.addAbility(FlyingAbility.getInstance());
// Lifelink
this.addAbility(LifelinkAbility.getInstance());
// Whenever you gain life, put a +1/+1 counter on each creature you control.
this.addAbility(new GainLifeControllerTriggeredAbility(
new AddCountersAllEffect(
CounterType.P1P1.createInstance(),
StaticFilters.FILTER_CONTROLLED_CREATURES
), false
));
}
private ArchangelOfThune(final ArchangelOfThune card) {
super(card);
}
@Override
public ArchangelOfThune copy() {
return new ArchangelOfThune(this);
}
}
| 621 |
3,269 |
<reponame>jaiskid/LeetCode-Solutions<filename>C++/distinct-echo-substrings.cpp
// Time: O(n^2 + d), d is the duplicated of result substrings size
// Space: O(r), r is the size of result substrings set
class Solution {
public:
int distinctEchoSubstrings(string text) {
unordered_set<string> result;
int l = text.length() - 1;
for (int i = 0; i < l; ++i) { // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcdefabcdefabcdef
const auto& substr_len = KMP(text, i, &result);
if (substr_len != numeric_limits<int>::max()) {
l = min(l, i + substr_len);
}
}
return result.size();
}
private:
int KMP(const string& text, int l, unordered_set<string> *result) {
vector<int> prefix(text.length() - l, -1);
int j = -1;
for (int i = 1; i < prefix.size(); ++i) {
while (j > -1 && text[l + j + 1] != text[l + i]) {
j = prefix[j];
}
if (text[l + j + 1] == text[l + i]) {
++j;
}
prefix[i] = j;
if ((j + 1) && (i + 1) % ((i + 1) - (j + 1)) == 0 &&
(i + 1) / ((i + 1) - (j + 1)) % 2 == 0) {
result->emplace(text.substr(l, i + 1));
}
}
return (prefix.back() + 1 && (prefix.size() % (prefix.size() - (prefix.back() + 1)) == 0))
? (prefix.size() - (prefix.back() + 1))
: numeric_limits<int>::max();
}
};
// Time: O(n^2 + d), d is the duplicated of result substrings size
// Space: O(r), r is the size of result substrings set
class Solution2 {
public:
int distinctEchoSubstrings(string text) {
unordered_set<string> result;
for (int l = 1; l <= text.length() / 2; ++l) {
int count = 0;
for (int i = 0; i < l; ++i) {
count += int(text[i] == text[i + l]);
}
for (int i = 0; i < text.length() - 2 * l; ++i) {
if (count == l) {
result.emplace(text.substr(i, l));
}
count += int(text[i + l] == text[i + l + l]) - int(text[i] == text[i + l]);
}
if (count == l) {
result.emplace(text.substr(text.length() - 2 * l, l));
}
}
return result.size();
}
};
// Time: O(n^2 + d), d is the duplicated of result substrings size
// Space: O(r), r is the size of result substrings set
class Solution3 {
public:
int distinctEchoSubstrings(string text) {
static int MOD = 1e9 + 7;
int D = 27; // a-z and ''
unordered_set<uint64_t> result;
for (int i = 0; i < text.length(); ++i) {
uint64_t left = 0, right = 0, pow_D = 1;
for (int l = 1; l < min(i + 2, int(text.length()) - i); ++l) {
left = (D * left + text[i - l + 1] - 'a' + 1) % MOD;
right = (pow_D * (text[i + l] - 'a' + 1) % MOD + right) % MOD;
if (left == right) { // assumed no collision
result.emplace(left);
}
pow_D = (pow_D * D) % MOD;
}
}
return result.size();
}
};
// Time: O(n^3 + d), d is the duplicated of result substrings size
// Space: O(r), r is the size of result substrings set
class Solution_TLE {
public:
int distinctEchoSubstrings(string text) {
static int MOD = 1e9 + 7;
int D = 27; // a-z and ''
unordered_set<string> result;
for (int i = 0; i < text.length(); ++i) {
uint64_t left = 0, right = 0, pow_D = 1;
for (int l = 1; l < min(i + 2, int(text.length()) - i); ++l) {
left = (D * left + text[i - l + 1] - 'a' + 1) % MOD;
right = (pow_D * (text[i + l] - 'a' + 1) % MOD + right) % MOD;
if (left == right && compare(text, l, i - l + 1, i + 1)) {
result.emplace(text.substr(i + 1, l));
}
pow_D = (pow_D * D) % MOD;
}
}
return result.size();
}
private:
bool compare(const string& text, size_t l, int s1, int s2) {
for (int i = 0; i < l; ++i) {
if (text[s1 + i] != text[s2 + i]) {
return false;
}
}
return true;
}
};
| 2,296 |
746 |
package org.protege.editor.owl.ui.ontology.wizard.move;
import org.protege.editor.owl.OWLEditorKit;
import javax.swing.*;
import java.awt.*;
/*
* Copyright (C) 2008, University of Manchester
*
*
*/
/**
* Author: <NAME><br> The University Of Manchester<br> Information Management Group<br> Date:
* 19-Sep-2008<br><br>
*/
public class MoveAxiomsWizardKitConfigurationPanel extends AbstractMoveAxiomsWizardPanel {
private MoveAxiomsKitConfigurationPanel content;
private Object prevId;
private Object nextId;
private JPanel holder;
public MoveAxiomsWizardKitConfigurationPanel(Object prevId, Object nextId, MoveAxiomsKitConfigurationPanel content, OWLEditorKit owlEditorKit) {
super(content.getID(), content.getTitle(), owlEditorKit);
this.content = content;
this.prevId = prevId;
this.nextId = nextId;
holder.add(content);
setInstructions(content.getInstructions());
}
protected void createUI(JComponent parent) {
parent.setLayout(new BorderLayout());
parent.add(holder = new JPanel(new BorderLayout()));
}
public void aboutToDisplayPanel() {
super.aboutToDisplayPanel();
content.update();
setComponentTransparency(content);
}
public void aboutToHidePanel() {
super.aboutToHidePanel();
content.commit();
}
public Object getBackPanelDescriptor() {
return prevId;
}
public Object getNextPanelDescriptor() {
return nextId;
}
}
| 566 |
575 |
// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GPU_VULKAN_VULKAN_IMPLEMENTATION_H_
#define GPU_VULKAN_VULKAN_IMPLEMENTATION_H_
#include <vulkan/vulkan.h>
#include <memory>
#include <vector>
#include "base/component_export.h"
#include "base/macros.h"
#include "base/optional.h"
#include "build/build_config.h"
#include "gpu/vulkan/semaphore_handle.h"
#include "ui/gfx/buffer_types.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/gpu_memory_buffer.h"
#include "ui/gfx/native_widget_types.h"
#if defined(OS_ANDROID)
#include "base/android/scoped_hardware_buffer_handle.h"
#include "ui/gfx/geometry/size.h"
#endif
namespace gfx {
class GpuFence;
struct GpuMemoryBufferHandle;
} // namespace gfx
namespace gpu {
class VulkanDeviceQueue;
class VulkanSurface;
class VulkanImage;
class VulkanInstance;
struct GPUInfo;
struct VulkanYCbCrInfo;
#if defined(OS_FUCHSIA)
class SysmemBufferCollection {
public:
virtual ~SysmemBufferCollection() {}
};
#endif // defined(OS_FUCHSIA)
// Base class which provides functions for creating vulkan objects for different
// platforms that use platform-specific extensions (e.g. for creation of
// VkSurfaceKHR objects). It also provides helper/utility functions.
class COMPONENT_EXPORT(VULKAN) VulkanImplementation {
public:
VulkanImplementation(bool use_swiftshader = false,
bool allow_protected_memory = false,
bool enforce_protected_memory = false);
virtual ~VulkanImplementation();
// Initialize VulkanInstance. If using_surface, VK_KHR_surface instance
// extension will be required when initialize VkInstance. This extension is
// required for presenting with VkSwapchain API.
virtual bool InitializeVulkanInstance(bool using_surface = true) = 0;
virtual VulkanInstance* GetVulkanInstance() = 0;
virtual std::unique_ptr<VulkanSurface> CreateViewSurface(
gfx::AcceleratedWidget window) = 0;
virtual bool GetPhysicalDevicePresentationSupport(
VkPhysicalDevice device,
const std::vector<VkQueueFamilyProperties>& queue_family_properties,
uint32_t queue_family_index) = 0;
virtual std::vector<const char*> GetRequiredDeviceExtensions() = 0;
virtual std::vector<const char*> GetOptionalDeviceExtensions() = 0;
// Creates a VkFence that is exportable to a gfx::GpuFence.
virtual VkFence CreateVkFenceForGpuFence(VkDevice vk_device) = 0;
// Exports a VkFence to a gfx::GpuFence.
//
// The fence should have been created via CreateVkFenceForGpuFence().
virtual std::unique_ptr<gfx::GpuFence> ExportVkFenceToGpuFence(
VkDevice vk_device,
VkFence vk_fence) = 0;
// Creates a semaphore that can be exported using GetSemaphoreHandle().
virtual VkSemaphore CreateExternalSemaphore(VkDevice vk_device) = 0;
// Import a VkSemaphore from a platform-specific handle.
// Handle types that don't allow permanent import are imported with
// temporary permanence (VK_SEMAPHORE_IMPORT_TEMPORARY_BIT).
virtual VkSemaphore ImportSemaphoreHandle(VkDevice vk_device,
SemaphoreHandle handle) = 0;
// Export a platform-specific handle for a Vulkan semaphore. Returns a null
// handle in case of a failure.
virtual SemaphoreHandle GetSemaphoreHandle(VkDevice vk_device,
VkSemaphore vk_semaphore) = 0;
// Returns VkExternalMemoryHandleTypeFlagBits that should be set when creating
// external images and memory.
virtual VkExternalMemoryHandleTypeFlagBits GetExternalImageHandleType() = 0;
// Returns true if the GpuMemoryBuffer of the specified type can be imported
// into VkImage using CreateImageFromGpuMemoryHandle().
virtual bool CanImportGpuMemoryBuffer(
gfx::GpuMemoryBufferType memory_buffer_type) = 0;
// Creates a VkImage from a GpuMemoryBuffer. If successful it initializes
// |vk_image|, |vk_image_info|, |vk_device_memory| and |mem_allocation_size|.
// Implementation must verify that the specified |size| fits in the size
// specified when |gmb_handle| was allocated.
virtual std::unique_ptr<VulkanImage> CreateImageFromGpuMemoryHandle(
VulkanDeviceQueue* device_queue,
gfx::GpuMemoryBufferHandle gmb_handle,
gfx::Size size,
VkFormat vk_formae) = 0;
#if defined(OS_ANDROID)
// Get the sampler ycbcr conversion information from the AHB.
virtual bool GetSamplerYcbcrConversionInfo(
const VkDevice& vk_device,
base::android::ScopedHardwareBufferHandle ahb_handle,
VulkanYCbCrInfo* ycbcr_info) = 0;
#endif
#if defined(OS_FUCHSIA)
// Registers as sysmem buffer collection. The collection can be released by
// destroying the returned SysmemBufferCollection object. Once a collection is
// registered the individual buffers in the collection can be referenced by
// using the |id| as |buffer_collection_id| in |gmb_handle| passed to
// CreateImageFromGpuMemoryHandle().
virtual std::unique_ptr<SysmemBufferCollection>
RegisterSysmemBufferCollection(VkDevice device,
gfx::SysmemBufferCollectionId id,
zx::channel token,
gfx::BufferFormat format,
gfx::BufferUsage usage,
gfx::Size size,
size_t min_buffer_count,
bool register_with_image_pipe) = 0;
#endif // defined(OS_FUCHSIA)
bool use_swiftshader() const { return use_swiftshader_; }
bool allow_protected_memory() const { return allow_protected_memory_; }
bool enforce_protected_memory() const { return enforce_protected_memory_; }
private:
const bool use_swiftshader_;
const bool allow_protected_memory_;
const bool enforce_protected_memory_;
DISALLOW_COPY_AND_ASSIGN(VulkanImplementation);
};
COMPONENT_EXPORT(VULKAN)
std::unique_ptr<VulkanDeviceQueue> CreateVulkanDeviceQueue(
VulkanImplementation* vulkan_implementation,
uint32_t option,
const GPUInfo* gpu_info = nullptr,
uint32_t heap_memory_limit = 0);
} // namespace gpu
#endif // GPU_VULKAN_VULKAN_IMPLEMENTATION_H_
| 2,310 |
420 |
<reponame>johalun/wlc<filename>src/resources/resources.h<gh_stars>100-1000
#ifndef _WLC_RESOURCES_H_
#define _WLC_RESOURCES_H_
#include <wlc/wlc.h>
#include <stdint.h>
#include <stdbool.h>
#include <chck/pool/pool.h>
#include <wayland-server.h>
typedef uintptr_t wlc_resource;
/** Storage for handles / resources. */
struct wlc_source {
const char *name;
struct chck_pool pool;
bool (*constructor)();
void (*destructor)();
};
/** Use this empty struct for resources that don't need their own container. */
struct wlc_resource {};
/** Generic destructor that can be passed to various wl interface implementations. */
WLC_NONULL static inline void
wlc_cb_resource_destructor(struct wl_client *client, struct wl_resource *resource)
{
(void)client;
wl_resource_destroy(resource);
}
/** Helper for creating wayland resources with version support check. */
WLC_NONULL struct wl_resource* wl_resource_create_checked(struct wl_client *client, const struct wl_interface *interface, uint32_t version, uint32_t supported, uint32_t id);
/** Init resource management */
bool wlc_resources_init(void);
/** Terminate resource management */
void wlc_resources_terminate(void);
/**
* Initialize source.
* name should be type name of the handle/resource source will be carrying.
* grow defines the reallocation step for source.
* member defines the size of item the source will be carrying.
*/
WLC_NONULLV(1,2) bool wlc_source(struct wlc_source *source, const char *name, bool (*constructor)(), void (*destructor)(), size_t grow, size_t member);
/**
* Release source and all the handles/resources it contains.
*/
void wlc_source_release(struct wlc_source *source);
/** Converts pointer back to handle, use the convert_to_<foo> macros instead. */
wlc_handle convert_to_handle(void *ptr, size_t size);
/**
* Create new wlc_handle into given source pool.
* wlc handles are types that are not tied to wayland resource.
* For example wlc_view and wlc_output.
*/
WLC_NONULL void* wlc_handle_create(struct wlc_source *source);
/**
* Convert from wlc_handle back to the pointer.
* name should be same as the name in source, otherwise NULL is returned.
*/
void* convert_from_wlc_handle(wlc_handle handle, const char *name, size_t line, const char *file, const char *function);
#define convert_from_wlc_handle(x, y) convert_from_wlc_handle(x, y, __LINE__, WLC_FILE, __func__)
/**
* Convert pointer back to wlc_handle.
* NOTE: The sizeof(*x), use this only when compiler can know the size.
* void *ptr, won't work.
*/
#define convert_to_wlc_handle(x) convert_to_handle(x, sizeof(*x))
/**
* Release wlc_handle.
*/
void wlc_handle_release(wlc_handle handle);
/**
* Create new wlc_resource into given source pool.
* wlc_resources are types that are tied to wayland resource.
* Thus their lifetime is also dictated by the wayland resource.
*
* Implementation for these types should go in resources/types/
*/
WLC_NONULL wlc_resource wlc_resource_create(struct wlc_source *source, struct wl_client *client, const struct wl_interface *interface, uint32_t version, uint32_t supported, uint32_t id);
/** Create new wlc_resource from existing wayland resource. */
WLC_NONULL wlc_resource wlc_resource_create_from(struct wlc_source *source, struct wl_resource *resource);
/** Implement wlc_resource. */
void wlc_resource_implement(wlc_resource resource, const void *implementation, void *userdata);
/** Convert to wlc_resource from wayland resource. */
wlc_resource wlc_resource_from_wl_resource(struct wl_resource *resource);
/** Convert to wayland resource from wlc_resource. */
struct wl_resource* wl_resource_from_wlc_resource(wlc_resource resource, const char *name, size_t line, const char *file, const char *function);
#define wl_resource_from_wlc_resource(x, y) wl_resource_from_wlc_resource(x, y, __LINE__, WLC_FILE, __func__)
/** Get wayland resource for client from source. */
WLC_NONULL struct wl_resource* wl_resource_for_client(struct wlc_source *source, struct wl_client *client);
/** Convert to pointer from wlc_resource. */
void* convert_from_wlc_resource(wlc_resource resource, const char *name, size_t line, const char *file, const char *function);
#define convert_from_wlc_resource(x, y) convert_from_wlc_resource(x, y, __LINE__, WLC_FILE, __func__)
/** Convert to pointer from wayland resource. */
void* convert_from_wl_resource(struct wl_resource *resource, const char *name, size_t line, const char *file, const char *function);
#define convert_from_wl_resource(x, y) convert_from_wl_resource(x, y, __LINE__, WLC_FILE, __func__)
/**
* Convert to wlc_resource from pointer.
* NOTE: The sizeof(*x), use this only when compiler can know the size.
* void *ptr, won't work.
*/
#define convert_to_wlc_resource(x) (wlc_resource)convert_to_handle(x, sizeof(*x))
/**
* Convert to wayland resource from pointer.
* NOTE: The sizeof(*x), use this only when compiler can know the size.
* void *ptr, won't work.
*/
#define convert_to_wl_resource(x, y) wl_resource_from_wlc_resource((wlc_resource)convert_to_handle(x, sizeof(*x)), y)
/**
* Invalidate the wayland resource for the wlc_resource.
* only wlc_buffer uses this right now, since it needs to release the wayland resource in queue.
*/
void wlc_resource_invalidate(wlc_resource resource);
/** Release resource. */
void wlc_resource_release(wlc_resource resource);
/** Release pointer to wlc_handle, useful for chck_<foo>_for_each_call mainly. */
static inline void
wlc_handle_release_ptr(wlc_handle *handle)
{
wlc_handle_release(*handle);
}
/** Release pointer to wlc_resource, useful for chck_<foo>_for_each_call mainly. */
static inline void
wlc_resource_release_ptr(wlc_resource *resource)
{
wlc_resource_release(*resource);
}
#endif /* _WLC_RESOURCES_H_ */
| 1,868 |
1,169 |
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.components.runtime.util;
import android.app.Activity;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.util.Log;
import android.os.Handler;
/**
* Wrapper class for Android's {@link android.speech.tts.TextToSpeech} class, which doesn't exist on
* pre-1.6 devices.
*
* We need to wrap this because the Dalvik class loader will fail to verify a class that contains
* references to non-existence classes and therefore we arrange for the failure to occur in this
* class, rather than the component class which references this. The component class can figure
* out whether it wants to use this wrapper class or not depending on the SDK level.
*
* See http://android-developers.blogspot.com/2009/04/backward-compatibility-for-android.html for
* some more about this.
*
* @author <EMAIL> (<NAME>)
*/
public class InternalTextToSpeech implements ITextToSpeech {
private static final String LOG_TAG = "InternalTTS";
private final Activity activity;
private final TextToSpeechCallback callback;
private TextToSpeech tts;
private volatile boolean isTtsInitialized;
private Handler mHandler = new Handler();
private int nextUtteranceId = 1;
// time (ms) to delay before retrying speak when tts not yet initialized
private int ttsRetryDelay = 500;
// max number of retries waiting for initialization before speak fails
// This is very long, but it's better to get a long delay than simply have
// no speech in the case of initialization slowness
private int ttsMaxRetries = 20;
public InternalTextToSpeech(Activity activity, TextToSpeechCallback callback) {
this.activity = activity;
this.callback = callback;
initializeTts();
}
private void initializeTts() {
if (tts == null) {
Log.d(LOG_TAG, "INTERNAL TTS is reinitializing");
tts = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
isTtsInitialized = true;
}
}
});
}
}
@Override
public void speak(final String message, final Locale loc) {
Log.d(LOG_TAG, "Internal TTS got speak");
speak(message, loc, 0);
}
public boolean isInitialized() {
return isTtsInitialized;
}
private void speak(final String message, final Locale loc, final int retries) {
Log.d(LOG_TAG, "InternalTTS speak called, message = " + message);
if (retries > ttsMaxRetries) {
Log.d(LOG_TAG, "max number of speak retries exceeded: speak will fail");
callback.onFailure();
}
// If speak was called before initialization was complete, we retry after a delay.
// Keep track of the number of retries and fail if there are too many.
if (isTtsInitialized) {
Log.d(LOG_TAG, "TTS initialized after " + retries + " retries.");
tts.setLanguage(loc);
tts.setOnUtteranceCompletedListener(
new TextToSpeech.OnUtteranceCompletedListener() {
@Override
public void onUtteranceCompleted(String utteranceId) {
// onUtteranceCompleted is not called on the UI thread, so we use
// Activity.runOnUiThread() to call callback.onSuccess().
activity.runOnUiThread(new Runnable() {
public void run() {
callback.onSuccess();
}
});
}
});
// We need to provide an utterance id. Otherwise onUtteranceCompleted won't be called.
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, Integer.toString(nextUtteranceId++));
int result = tts.speak(message, tts.QUEUE_FLUSH, params);
if (result == TextToSpeech.ERROR) {
Log.d(LOG_TAG, "speak called and tts.speak result was an error");
callback.onFailure();
}
} else {
Log.d(LOG_TAG, "speak called when TTS not initialized");
mHandler.postDelayed(new Runnable() {
public void run() {
Log.d(LOG_TAG,
"delaying call to speak. Retries is: " + retries + " Message is: " + message);
speak(message, loc, retries + 1);
}
}, ttsRetryDelay);
}
}
@Override
public void onStop() {
Log.d(LOG_TAG, "Internal TTS got onStop");
// do nothing. Resources will be cleaned up in onDestroy
}
@Override
public void onDestroy() {
Log.d(LOG_TAG, "Internal TTS got onDestroy");
if (tts != null) {
tts.shutdown();
isTtsInitialized = false;
tts = null;
}
}
@Override
public void onResume() {
Log.d(LOG_TAG, "Internal TTS got onResume");
initializeTts();
}
@Override
public void setPitch(float pitch) {
tts.setPitch(pitch);
}
@Override
public void setSpeechRate(float speechRate) {
tts.setSpeechRate(speechRate);
}
// This is for use by the higher level TextToSpeech component
public int isLanguageAvailable(Locale loc) {
return tts.isLanguageAvailable(loc);
}
}
| 1,965 |
348 |
<gh_stars>100-1000
{"nom":"Mazan-l'Abbaye","circ":"3ème circonscription","dpt":"Ardèche","inscrits":192,"abs":87,"votants":105,"blancs":10,"nuls":3,"exp":92,"res":[{"nuance":"LR","nom":"<NAME>","voix":60},{"nuance":"REM","nom":"<NAME>","voix":32}]}
| 105 |
5,079 |
import datetime
def _get_duration_components(duration):
days = duration.days
seconds = duration.seconds
microseconds = duration.microseconds
minutes = seconds // 60
seconds = seconds % 60
hours = minutes // 60
minutes = minutes % 60
return days, hours, minutes, seconds, microseconds
def duration_string(duration):
"""Version of str(timedelta) which is not English specific."""
days, hours, minutes, seconds, microseconds = _get_duration_components(duration)
string = '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
if days:
string = '{} '.format(days) + string
if microseconds:
string += '.{:06d}'.format(microseconds)
return string
def duration_iso_string(duration):
if duration < datetime.timedelta(0):
sign = '-'
duration *= -1
else:
sign = ''
days, hours, minutes, seconds, microseconds = _get_duration_components(duration)
ms = '.{:06d}'.format(microseconds) if microseconds else ""
return '{}P{}DT{:02d}H{:02d}M{:02d}{}S'.format(sign, days, hours, minutes, seconds, ms)
| 408 |
11,699 |
<reponame>kxxt/taichi
#include "taichi/python/snode_registry.h"
#include "taichi/ir/snode.h"
namespace taichi {
namespace lang {
SNode *SNodeRegistry::create_root() {
auto n = std::make_unique<SNode>(/*depth=*/0, SNodeType::root);
auto *res = n.get();
snodes_.push_back(std::move(n));
return res;
}
std::unique_ptr<SNode> SNodeRegistry::finalize(const SNode *snode) {
for (auto it = snodes_.begin(); it != snodes_.end(); ++it) {
if (it->get() == snode) {
auto res = std::move(*it);
snodes_.erase(it);
return res;
}
}
return nullptr;
}
} // namespace lang
} // namespace taichi
| 262 |
852 |
<reponame>ckamtsikis/cmssw
#ifndef RecoMET_METPUSubtraction_noPileUpMEtAuxFunctions_h
#define RecoMET_METPUSubtraction_noPileUpMEtAuxFunctions_h
#include "DataFormats/Common/interface/AssociationMap.h"
#include "DataFormats/Common/interface/OneToManyWithQuality.h"
#include "DataFormats/Common/interface/Ref.h"
#include "DataFormats/Candidate/interface/Candidate.h"
#include "DataFormats/Candidate/interface/CandidateFwd.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
#include "DataFormats/VertexReco/interface/VertexFwd.h"
#include "CommonTools/RecoUtils/interface/PFCand_AssoMapAlgos.h"
// 0 = neutral particle,
// 1 = charged particle not associated to any vertex
// 2 = charged particle associated to pile-up vertex
// 3 = charged particle associated to vertex of hard-scatter event
namespace noPuUtils {
enum { kNeutral = 0, kChNoAssoc, kChPUAssoc, kChHSAssoc };
typedef std::vector<std::pair<reco::PFCandidateRef, int> > CandQualityPairVector;
typedef std::vector<std::pair<reco::VertexRef, int> > VertexQualityPairVector;
typedef edm::AssociationMap<edm::OneToManyWithQuality<reco::PFCandidateCollection, reco::VertexCollection, int> >
reversedPFCandToVertexAssMap;
// check if the pf candidate is associated with a vertex,
// return the type of association
int isVertexAssociated(const reco::PFCandidatePtr&,
const PFCandToVertexAssMap&,
const reco::VertexCollection&,
double);
// reverse the vertex-pfcandidate association map
noPuUtils::reversedPFCandToVertexAssMap reversePFCandToVertexAssociation(const PFCandToVertexAssMap&);
// check if the pf candidate is associated with a vertex,
// based over references keys
// return the type of association
int isVertexAssociated_fast(const reco::PFCandidateRef&,
const noPuUtils::reversedPFCandToVertexAssMap&,
const reco::VertexCollection&,
double,
int&,
int);
//promote a low quality association to a better level
// if dz justifies it
void promoteAssocToHSAssoc(
int quality, double z, const reco::VertexCollection& vertices, double dZ, int& vtxAssociationType, bool checkdR2);
} // namespace noPuUtils
#endif
| 997 |
486 |
package edu.tum.cup2.parser.tables;
import edu.tum.cup2.generator.terminals.ITerminalSeq;
import edu.tum.cup2.grammar.Grammar;
import edu.tum.cup2.grammar.SpecialTerminals;
import edu.tum.cup2.grammar.Terminal;
import edu.tum.cup2.util.KTreeMap;
/**
* This class realises the association between a set of {@link ITerminalSeq} (first/follow sets of a grammar) and a
* generic parameter V
*
* @author Gero
* @param <V>
*/
public class TerminalTreeMap<V> extends KTreeMap<ITerminalSeq, Terminal, V>
{
private static final TerminalEnumerator TERMINAL_ENUMERATOR = new TerminalEnumerator();
/**
* @param pureTerminalsSize Number of grammars terminals w/o EndOfInputStream!
*/
public TerminalTreeMap(Grammar gr)
{
this(terminalsSize(gr));
}
/**
* @param terminalsSize (w/o {@link SpecialTerminals#EndOfInputStream}!!!)
*/
public TerminalTreeMap(int terminalsSize)
{
super(terminalsSize + 2, TERMINAL_ENUMERATOR);
}
private static int terminalsSize(Grammar gr)
{
if (gr.getTerminals().contains(SpecialTerminals.EndOfInputStream))
{
return gr.getTerminals().size() - 1;
} else {
return gr.getTerminals().size();
}
}
private static class TerminalEnumerator implements IEnumerator<Terminal>
{
public int ordinal(Terminal keypart, int maxOrdinal)
{
if (keypart == SpecialTerminals.Epsilon)
{
return maxOrdinal; // max = place for Epsilon
} else if (keypart == SpecialTerminals.EndOfInputStream)
{
return maxOrdinal - 1; // max - 1 = place for EndOfInputStream
} else
{
return keypart.ordinal();
}
}
}
}
| 685 |
3,269 |
// Time: O(n^2)
// Space: O(n)
class Solution {
public:
int countTriples(int n) {
unordered_set<int> lookup;
for (int i = 1; i <= n; ++i) {
lookup.emplace(i * i);
}
int result = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
result += lookup.count(i * i + j * j);
}
}
return result;
}
};
| 243 |
531 |
<gh_stars>100-1000
/**
* Copyright (c) 2011-2021, JFXtras
* 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 the organization 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 JFXTRAS 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 jfxtras.scene.layout;
import javafx.scene.Node;
class GenericLayoutConstraints
{
/**
* The layout constraints
*
*/
public static class C<T>
{
// minWidth
public T minWidth(double value) { this.minWidth = value; return (T)this; }
double minWidth = -1;
double minWidthReset = UNKNOWN;
// prefWidth
public T prefWidth(double value) { this.prefWidth = value; return (T)this; }
double prefWidth = -1;
double prefWidthReset = UNKNOWN;
// maxWidth
public T maxWidth(double value) { this.maxWidth = value; return (T)this; }
double maxWidth = -1;
double maxWidthReset = UNKNOWN;
// minHeight
public T minHeight(double value) { this.minHeight = value; return (T)this; }
double minHeight = -1;
double minHeightReset = UNKNOWN;
// prefHeight
public T prefHeight(double value) { this.prefHeight = value; return (T)this; }
double prefHeight = -1;
double prefHeightReset = UNKNOWN;
// maxHeight
public T maxHeight(double value) { this.maxHeight = value; return (T)this; }
double maxHeight = -1;
double maxHeightReset = UNKNOWN;
/**
* @param node
*/
protected void rememberResetValues(Node node)
{
if (node instanceof javafx.scene.layout.Region)
{
javafx.scene.layout.Region lRegion = (javafx.scene.layout.Region)node;
// setup the reset values on the first apply
if (minWidthReset == UNKNOWN) minWidthReset = lRegion.getMinWidth();
if (prefWidthReset == UNKNOWN) prefWidthReset = lRegion.getPrefWidth();
if (maxWidthReset == UNKNOWN) maxWidthReset = lRegion.getMaxWidth();
if (minHeightReset == UNKNOWN) minHeightReset = lRegion.getMinHeight();
if (prefHeightReset == UNKNOWN) prefHeightReset = lRegion.getPrefHeight();
if (maxHeightReset == UNKNOWN) maxHeightReset = lRegion.getMaxHeight();
}
}
/**
* @param node
*/
protected void apply(Node node)
{
if (node instanceof javafx.scene.layout.Region)
{
javafx.scene.layout.Region lRegion = (javafx.scene.layout.Region)node;
// setup the reset values on the first apply
rememberResetValues(lRegion);
// either set or reset values
lRegion.setMinWidth(minWidth >= 0 ? minWidth : minWidthReset);
lRegion.setPrefWidth(prefWidth >= 0 ? prefWidth : prefWidthReset);
lRegion.setMaxWidth(maxWidth >= 0 ? maxWidth : maxWidthReset);
lRegion.setMinHeight(minHeight >= 0 ? minHeight : minHeightReset);
lRegion.setPrefHeight(prefHeight >= 0 ? prefHeight : prefHeightReset);
lRegion.setMaxHeight(maxHeight >= 0 ? maxHeight : maxHeightReset);
}
}
}
static final double UNKNOWN = -Double.MIN_NORMAL + 10.0;
/**
*
*/
static public void overrideMaxWidth(Node node, C c)
{
// just to prevent problems
if (node == null) return;
// make max issues go away
if (node instanceof javafx.scene.layout.Region)
{
javafx.scene.layout.Region lRegion = (javafx.scene.layout.Region)node;
lRegion.setMaxWidth( c.maxWidth >= 0 ? c.maxWidth : Double.MAX_VALUE);
}
}
/**
*
*/
static public void overrideMaxHeight(Node node, C c)
{
// just to prevent problems
if (node == null) return;
// make max issues go away
if (node instanceof javafx.scene.layout.Region)
{
javafx.scene.layout.Region lRegion = (javafx.scene.layout.Region)node;
lRegion.setMaxHeight( c.maxHeight >= 0 ? c.maxHeight : Double.MAX_VALUE);
}
}
}
| 1,908 |
535 |
<gh_stars>100-1000
/**
******************************************************************************
* @file stm32f1xx_ll_adc.c
* @author MCD Application Team
* @version V1.1.1
* @date 12-May-2017
* @brief ADC LL module driver
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_ll_adc.h"
#include "stm32f1xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F1xx_LL_Driver
* @{
*/
#if defined (ADC1) || defined (ADC2) || defined (ADC3)
/** @addtogroup ADC_LL ADC
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup ADC_LL_Private_Macros
* @{
*/
/* Check of parameters for configuration of ADC hierarchical scope: */
/* common to several ADC instances. */
/* Check of parameters for configuration of ADC hierarchical scope: */
/* ADC instance. */
#define IS_LL_ADC_DATA_ALIGN(__DATA_ALIGN__) \
( ((__DATA_ALIGN__) == LL_ADC_DATA_ALIGN_RIGHT) \
|| ((__DATA_ALIGN__) == LL_ADC_DATA_ALIGN_LEFT) \
)
#define IS_LL_ADC_SCAN_SELECTION(__SCAN_SELECTION__) \
( ((__SCAN_SELECTION__) == LL_ADC_SEQ_SCAN_DISABLE) \
|| ((__SCAN_SELECTION__) == LL_ADC_SEQ_SCAN_ENABLE) \
)
#define IS_LL_ADC_SEQ_SCAN_MODE(__SEQ_SCAN_MODE__) \
( ((__SCAN_MODE__) == LL_ADC_SEQ_SCAN_DISABLE) \
|| ((__SCAN_MODE__) == LL_ADC_SEQ_SCAN_ENABLE) \
)
/* Check of parameters for configuration of ADC hierarchical scope: */
/* ADC group regular */
#if defined(ADC3)
#define IS_LL_ADC_REG_TRIG_SOURCE(__ADC_INSTANCE__, __REG_TRIG_SOURCE__) \
((((__ADC_INSTANCE__) == ADC1) || ((__ADC_INSTANCE__) == ADC2)) \
? ( ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_TRGO) \
) \
: \
( ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_TRGO_ADC3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM5_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM5_CH3) \
) \
)
#else
#if defined (STM32F101xE) || defined (STM32F105xC) || defined (STM32F107xC)
#define IS_LL_ADC_REG_TRIG_SOURCE(__REG_TRIG_SOURCE__) \
( ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_TRGO) \
)
#else
#define IS_LL_ADC_REG_TRIG_SOURCE(__REG_TRIG_SOURCE__) \
( ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH1) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH2) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \
|| ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \
)
#endif
#endif
#define IS_LL_ADC_REG_CONTINUOUS_MODE(__REG_CONTINUOUS_MODE__) \
( ((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_SINGLE) \
|| ((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_CONTINUOUS) \
)
#define IS_LL_ADC_REG_DMA_TRANSFER(__REG_DMA_TRANSFER__) \
( ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_NONE) \
|| ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_UNLIMITED) \
)
#define IS_LL_ADC_REG_SEQ_SCAN_LENGTH(__REG_SEQ_SCAN_LENGTH__) \
( ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_DISABLE) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_9RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_10RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_12RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_13RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_14RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS) \
|| ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS) \
)
#define IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(__REG_SEQ_DISCONT_MODE__) \
( ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_DISABLE) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_1RANK) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_2RANKS) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_3RANKS) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_4RANKS) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_5RANKS) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_6RANKS) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_7RANKS) \
|| ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_8RANKS) \
)
/* Check of parameters for configuration of ADC hierarchical scope: */
/* ADC group injected */
#if defined(ADC3)
#define IS_LL_ADC_INJ_TRIG_SOURCE(__ADC_INSTANCE__, __INJ_TRIG_SOURCE__) \
((((__ADC_INSTANCE__) == ADC1) || ((__ADC_INSTANCE__) == ADC2)) \
? ( ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_CH4) \
) \
: \
( ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_CH3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_CH2) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_CH4_ADC3) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM5_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM5_CH4) \
) \
)
#else
#if defined (STM32F101xE) || defined (STM32F105xC) || defined (STM32F107xC)
#define IS_LL_ADC_INJ_TRIG_SOURCE(__INJ_TRIG_SOURCE__) \
( ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_CH4) \
)
#else
#define IS_LL_ADC_INJ_TRIG_SOURCE(__INJ_TRIG_SOURCE__) \
( ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH4) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) \
|| ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \
)
#endif
#endif
#define IS_LL_ADC_INJ_TRIG_AUTO(__INJ_TRIG_AUTO__) \
( ((__INJ_TRIG_AUTO__) == LL_ADC_INJ_TRIG_INDEPENDENT) \
|| ((__INJ_TRIG_AUTO__) == LL_ADC_INJ_TRIG_FROM_GRP_REGULAR) \
)
#define IS_LL_ADC_INJ_SEQ_SCAN_LENGTH(__INJ_SEQ_SCAN_LENGTH__) \
( ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_DISABLE) \
|| ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS) \
|| ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS) \
|| ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS) \
)
#define IS_LL_ADC_INJ_SEQ_SCAN_DISCONT_MODE(__INJ_SEQ_DISCONT_MODE__) \
( ((__INJ_SEQ_DISCONT_MODE__) == LL_ADC_INJ_SEQ_DISCONT_DISABLE) \
|| ((__INJ_SEQ_DISCONT_MODE__) == LL_ADC_INJ_SEQ_DISCONT_1RANK) \
)
#if defined(ADC_MULTIMODE_SUPPORT)
/* Check of parameters for configuration of ADC hierarchical scope: */
/* multimode. */
#define IS_LL_ADC_MULTI_MODE(__MULTI_MODE__) \
( ((__MULTI_MODE__) == LL_ADC_MULTI_INDEPENDENT) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIMULT) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INTERL_FAST) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INTERL_SLOW) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_INJ_SIMULT) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_INJ_ALTERN) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INTFAST_INJ_SIM) \
|| ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INTSLOW_INJ_SIM) \
)
#define IS_LL_ADC_MULTI_MASTER_SLAVE(__MULTI_MASTER_SLAVE__) \
( ((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_MASTER) \
|| ((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_SLAVE) \
|| ((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_MASTER_SLAVE) \
)
#endif /* ADC_MULTIMODE_SUPPORT */
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup ADC_LL_Exported_Functions
* @{
*/
/** @addtogroup ADC_LL_EF_Init
* @{
*/
/**
* @brief De-initialize registers of all ADC instances belonging to
* the same ADC common instance to their default reset values.
* @param ADCxy_COMMON ADC common instance
* (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() )
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ADC common registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_ADC_CommonDeInit(ADC_Common_TypeDef *ADCxy_COMMON)
{
/* Check the parameters */
assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON));
/* Force reset of ADC clock (core clock) */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_ADC1);
/* Release reset of ADC clock (core clock) */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_ADC1);
return SUCCESS;
}
/**
* @brief Initialize some features of ADC common parameters
* (all ADC instances belonging to the same ADC common instance)
* and multimode (for devices with several ADC instances available).
* @note The setting of ADC common parameters is conditioned to
* ADC instances state:
* All ADC instances belonging to the same ADC common instance
* must be disabled.
* @param ADCxy_COMMON ADC common instance
* (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() )
* @param ADC_CommonInitStruct Pointer to a @ref LL_ADC_CommonInitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ADC common registers are initialized
* - ERROR: ADC common registers are not initialized
*/
ErrorStatus LL_ADC_CommonInit(ADC_Common_TypeDef *ADCxy_COMMON, LL_ADC_CommonInitTypeDef *ADC_CommonInitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON));
#if defined(ADC_MULTIMODE_SUPPORT)
assert_param(IS_LL_ADC_MULTI_MODE(ADC_CommonInitStruct->Multimode));
#endif /* ADC_MULTIMODE_SUPPORT */
/* Note: Hardware constraint (refer to description of functions */
/* "LL_ADC_SetCommonXXX()" and "LL_ADC_SetMultiXXX()"): */
/* On this STM32 serie, setting of these features is conditioned to */
/* ADC state: */
/* All ADC instances of the ADC common group must be disabled. */
if(__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(ADCxy_COMMON) == 0U)
{
/* Configuration of ADC hierarchical scope: */
/* - common to several ADC */
/* (all ADC instances belonging to the same ADC common instance) */
/* - multimode (if several ADC instances available on the */
/* selected device) */
/* - Set ADC multimode configuration */
/* - Set ADC multimode DMA transfer */
/* - Set ADC multimode: delay between 2 sampling phases */
#if defined(ADC_MULTIMODE_SUPPORT)
if(ADC_CommonInitStruct->Multimode != LL_ADC_MULTI_INDEPENDENT)
{
MODIFY_REG(ADCxy_COMMON->CR1,
ADC_CR1_DUALMOD,
ADC_CommonInitStruct->Multimode
);
}
else
{
MODIFY_REG(ADCxy_COMMON->CR1,
ADC_CR1_DUALMOD,
LL_ADC_MULTI_INDEPENDENT
);
}
#endif
}
else
{
/* Initialization error: One or several ADC instances belonging to */
/* the same ADC common instance are not disabled. */
status = ERROR;
}
return status;
}
/**
* @brief Set each @ref LL_ADC_CommonInitTypeDef field to default value.
* @param ADC_CommonInitStruct Pointer to a @ref LL_ADC_CommonInitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_ADC_CommonStructInit(LL_ADC_CommonInitTypeDef *ADC_CommonInitStruct)
{
/* Set ADC_CommonInitStruct fields to default values */
/* Set fields of ADC common */
/* (all ADC instances belonging to the same ADC common instance) */
#if defined(ADC_MULTIMODE_SUPPORT)
/* Set fields of ADC multimode */
ADC_CommonInitStruct->Multimode = LL_ADC_MULTI_INDEPENDENT;
#endif /* ADC_MULTIMODE_SUPPORT */
}
/**
* @brief De-initialize registers of the selected ADC instance
* to their default reset values.
* @note To reset all ADC instances quickly (perform a hard reset),
* use function @ref LL_ADC_CommonDeInit().
* @param ADCx ADC instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ADC registers are de-initialized
* - ERROR: ADC registers are not de-initialized
*/
ErrorStatus LL_ADC_DeInit(ADC_TypeDef *ADCx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(ADCx));
/* Disable ADC instance if not already disabled. */
if(LL_ADC_IsEnabled(ADCx) == 1U)
{
/* Set ADC group regular trigger source to SW start to ensure to not */
/* have an external trigger event occurring during the conversion stop */
/* ADC disable process. */
LL_ADC_REG_SetTriggerSource(ADCx, LL_ADC_REG_TRIG_SOFTWARE);
/* Set ADC group injected trigger source to SW start to ensure to not */
/* have an external trigger event occurring during the conversion stop */
/* ADC disable process. */
LL_ADC_INJ_SetTriggerSource(ADCx, LL_ADC_INJ_TRIG_SOFTWARE);
/* Disable the ADC instance */
LL_ADC_Disable(ADCx);
}
/* Check whether ADC state is compliant with expected state */
/* (hardware requirements of bits state to reset registers below) */
if(READ_BIT(ADCx->CR2, ADC_CR2_ADON) == 0U)
{
/* ========== Reset ADC registers ========== */
/* Reset register SR */
CLEAR_BIT(ADCx->SR,
( LL_ADC_FLAG_STRT
| LL_ADC_FLAG_JSTRT
| LL_ADC_FLAG_EOS
| LL_ADC_FLAG_JEOS
| LL_ADC_FLAG_AWD1 )
);
/* Reset register CR1 */
#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG)
CLEAR_BIT(ADCx->CR1,
( ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DUALMOD
| ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN
| ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN
| ADC_CR1_JEOCIE | ADC_CR1_AWDIE | ADC_CR1_EOCIE
| ADC_CR1_AWDCH )
);
#else
CLEAR_BIT(ADCx->CR1,
( ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM
| ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO
| ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE
| ADC_CR1_AWDIE | ADC_CR1_EOCIE | ADC_CR1_AWDCH )
);
#endif
/* Reset register CR2 */
CLEAR_BIT(ADCx->CR2,
( ADC_CR2_TSVREFE
| ADC_CR2_SWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL
| ADC_CR2_JSWSTART | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL
| ADC_CR2_ALIGN | ADC_CR2_DMA
| ADC_CR2_RSTCAL | ADC_CR2_CAL
| ADC_CR2_CONT | ADC_CR2_ADON )
);
/* Reset register SMPR1 */
CLEAR_BIT(ADCx->SMPR1,
( ADC_SMPR1_SMP17 | ADC_SMPR1_SMP16
| ADC_SMPR1_SMP15 | ADC_SMPR1_SMP14 | ADC_SMPR1_SMP13
| ADC_SMPR1_SMP12 | ADC_SMPR1_SMP11 | ADC_SMPR1_SMP10)
);
/* Reset register SMPR2 */
CLEAR_BIT(ADCx->SMPR2,
( ADC_SMPR2_SMP9
| ADC_SMPR2_SMP8 | ADC_SMPR2_SMP7 | ADC_SMPR2_SMP6
| ADC_SMPR2_SMP5 | ADC_SMPR2_SMP4 | ADC_SMPR2_SMP3
| ADC_SMPR2_SMP2 | ADC_SMPR2_SMP1 | ADC_SMPR2_SMP0)
);
/* Reset register JOFR1 */
CLEAR_BIT(ADCx->JOFR1, ADC_JOFR1_JOFFSET1);
/* Reset register JOFR2 */
CLEAR_BIT(ADCx->JOFR2, ADC_JOFR2_JOFFSET2);
/* Reset register JOFR3 */
CLEAR_BIT(ADCx->JOFR3, ADC_JOFR3_JOFFSET3);
/* Reset register JOFR4 */
CLEAR_BIT(ADCx->JOFR4, ADC_JOFR4_JOFFSET4);
/* Reset register HTR */
SET_BIT(ADCx->HTR, ADC_HTR_HT);
/* Reset register LTR */
CLEAR_BIT(ADCx->LTR, ADC_LTR_LT);
/* Reset register SQR1 */
CLEAR_BIT(ADCx->SQR1,
( ADC_SQR1_L
| ADC_SQR1_SQ16
| ADC_SQR1_SQ15 | ADC_SQR1_SQ14 | ADC_SQR1_SQ13)
);
/* Reset register SQR2 */
CLEAR_BIT(ADCx->SQR2,
( ADC_SQR2_SQ12 | ADC_SQR2_SQ11 | ADC_SQR2_SQ10
| ADC_SQR2_SQ9 | ADC_SQR2_SQ8 | ADC_SQR2_SQ7)
);
/* Reset register JSQR */
CLEAR_BIT(ADCx->JSQR,
( ADC_JSQR_JL
| ADC_JSQR_JSQ4 | ADC_JSQR_JSQ3
| ADC_JSQR_JSQ2 | ADC_JSQR_JSQ1 )
);
/* Reset register DR */
/* bits in access mode read only, no direct reset applicable */
/* Reset registers JDR1, JDR2, JDR3, JDR4 */
/* bits in access mode read only, no direct reset applicable */
}
return status;
}
/**
* @brief Initialize some features of ADC instance.
* @note These parameters have an impact on ADC scope: ADC instance.
* Affects both group regular and group injected (availability
* of ADC group injected depends on STM32 families).
* Refer to corresponding unitary functions into
* @ref ADC_LL_EF_Configuration_ADC_Instance .
* @note The setting of these parameters by function @ref LL_ADC_Init()
* is conditioned to ADC state:
* ADC instance must be disabled.
* This condition is applied to all ADC features, for efficiency
* and compatibility over all STM32 families. However, the different
* features can be set under different ADC state conditions
* (setting possible with ADC enabled without conversion on going,
* ADC enabled with conversion on going, ...)
* Each feature can be updated afterwards with a unitary function
* and potentially with ADC in a different state than disabled,
* refer to description of each function for setting
* conditioned to ADC state.
* @note After using this function, some other features must be configured
* using LL unitary functions.
* The minimum configuration remaining to be done is:
* - Set ADC group regular or group injected sequencer:
* map channel on the selected sequencer rank.
* Refer to function @ref LL_ADC_REG_SetSequencerRanks().
* - Set ADC channel sampling time
* Refer to function LL_ADC_SetChannelSamplingTime();
* @param ADCx ADC instance
* @param ADC_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ADC registers are initialized
* - ERROR: ADC registers are not initialized
*/
ErrorStatus LL_ADC_Init(ADC_TypeDef *ADCx, LL_ADC_InitTypeDef *ADC_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(ADCx));
assert_param(IS_LL_ADC_DATA_ALIGN(ADC_InitStruct->DataAlignment));
assert_param(IS_LL_ADC_SCAN_SELECTION(ADC_InitStruct->SequencersScanMode));
/* Note: Hardware constraint (refer to description of this function): */
/* ADC instance must be disabled. */
if(LL_ADC_IsEnabled(ADCx) == 0U)
{
/* Configuration of ADC hierarchical scope: */
/* - ADC instance */
/* - Set ADC conversion data alignment */
MODIFY_REG(ADCx->CR1,
ADC_CR1_SCAN
,
ADC_InitStruct->SequencersScanMode
);
MODIFY_REG(ADCx->CR2,
ADC_CR2_ALIGN
,
ADC_InitStruct->DataAlignment
);
}
else
{
/* Initialization error: ADC instance is not disabled. */
status = ERROR;
}
return status;
}
/**
* @brief Set each @ref LL_ADC_InitTypeDef field to default value.
* @param ADC_InitStruct Pointer to a @ref LL_ADC_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_ADC_StructInit(LL_ADC_InitTypeDef *ADC_InitStruct)
{
/* Set ADC_InitStruct fields to default values */
/* Set fields of ADC instance */
ADC_InitStruct->DataAlignment = LL_ADC_DATA_ALIGN_RIGHT;
/* Enable scan mode to have a generic behavior with ADC of other */
/* STM32 families, without this setting available: */
/* ADC group regular sequencer and ADC group injected sequencer depend */
/* only of their own configuration. */
ADC_InitStruct->SequencersScanMode = LL_ADC_SEQ_SCAN_ENABLE;
}
/**
* @brief Initialize some features of ADC group regular.
* @note These parameters have an impact on ADC scope: ADC group regular.
* Refer to corresponding unitary functions into
* @ref ADC_LL_EF_Configuration_ADC_Group_Regular
* (functions with prefix "REG").
* @note The setting of these parameters by function @ref LL_ADC_Init()
* is conditioned to ADC state:
* ADC instance must be disabled.
* This condition is applied to all ADC features, for efficiency
* and compatibility over all STM32 families. However, the different
* features can be set under different ADC state conditions
* (setting possible with ADC enabled without conversion on going,
* ADC enabled with conversion on going, ...)
* Each feature can be updated afterwards with a unitary function
* and potentially with ADC in a different state than disabled,
* refer to description of each function for setting
* conditioned to ADC state.
* @note After using this function, other features must be configured
* using LL unitary functions.
* The minimum configuration remaining to be done is:
* - Set ADC group regular or group injected sequencer:
* map channel on the selected sequencer rank.
* Refer to function @ref LL_ADC_REG_SetSequencerRanks().
* - Set ADC channel sampling time
* Refer to function LL_ADC_SetChannelSamplingTime();
* @param ADCx ADC instance
* @param ADC_REG_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ADC registers are initialized
* - ERROR: ADC registers are not initialized
*/
ErrorStatus LL_ADC_REG_Init(ADC_TypeDef *ADCx, LL_ADC_REG_InitTypeDef *ADC_REG_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(ADCx));
#if defined(ADC3)
assert_param(IS_LL_ADC_REG_TRIG_SOURCE(ADCx, ADC_REG_InitStruct->TriggerSource));
#else
assert_param(IS_LL_ADC_REG_TRIG_SOURCE(ADC_REG_InitStruct->TriggerSource));
#endif
assert_param(IS_LL_ADC_REG_SEQ_SCAN_LENGTH(ADC_REG_InitStruct->SequencerLength));
if(ADC_REG_InitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE)
{
assert_param(IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(ADC_REG_InitStruct->SequencerDiscont));
}
assert_param(IS_LL_ADC_REG_CONTINUOUS_MODE(ADC_REG_InitStruct->ContinuousMode));
assert_param(IS_LL_ADC_REG_DMA_TRANSFER(ADC_REG_InitStruct->DMATransfer));
/* Note: Hardware constraint (refer to description of this function): */
/* ADC instance must be disabled. */
if(LL_ADC_IsEnabled(ADCx) == 0U)
{
/* Configuration of ADC hierarchical scope: */
/* - ADC group regular */
/* - Set ADC group regular trigger source */
/* - Set ADC group regular sequencer length */
/* - Set ADC group regular sequencer discontinuous mode */
/* - Set ADC group regular continuous mode */
/* - Set ADC group regular conversion data transfer: no transfer or */
/* transfer by DMA, and DMA requests mode */
/* Note: On this STM32 serie, ADC trigger edge is set when starting */
/* ADC conversion. */
/* Refer to function @ref LL_ADC_REG_StartConversionExtTrig(). */
if(ADC_REG_InitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE)
{
MODIFY_REG(ADCx->CR1,
ADC_CR1_DISCEN
| ADC_CR1_DISCNUM
,
ADC_REG_InitStruct->SequencerLength
| ADC_REG_InitStruct->SequencerDiscont
);
}
else
{
MODIFY_REG(ADCx->CR1,
ADC_CR1_DISCEN
| ADC_CR1_DISCNUM
,
ADC_REG_InitStruct->SequencerLength
| LL_ADC_REG_SEQ_DISCONT_DISABLE
);
}
MODIFY_REG(ADCx->CR2,
ADC_CR2_EXTSEL
| ADC_CR2_CONT
| ADC_CR2_DMA
,
ADC_REG_InitStruct->TriggerSource
| ADC_REG_InitStruct->ContinuousMode
| ADC_REG_InitStruct->DMATransfer
);
/* Set ADC group regular sequencer length and scan direction */
/* Note: Hardware constraint (refer to description of this function): */
/* Note: If ADC instance feature scan mode is disabled */
/* (refer to ADC instance initialization structure */
/* parameter @ref SequencersScanMode */
/* or function @ref LL_ADC_SetSequencersScanMode() ), */
/* this parameter is discarded. */
LL_ADC_REG_SetSequencerLength(ADCx, ADC_REG_InitStruct->SequencerLength);
}
else
{
/* Initialization error: ADC instance is not disabled. */
status = ERROR;
}
return status;
}
/**
* @brief Set each @ref LL_ADC_REG_InitTypeDef field to default value.
* @param ADC_REG_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_ADC_REG_StructInit(LL_ADC_REG_InitTypeDef *ADC_REG_InitStruct)
{
/* Set ADC_REG_InitStruct fields to default values */
/* Set fields of ADC group regular */
/* Note: On this STM32 serie, ADC trigger edge is set when starting */
/* ADC conversion. */
/* Refer to function @ref LL_ADC_REG_StartConversionExtTrig(). */
ADC_REG_InitStruct->TriggerSource = LL_ADC_REG_TRIG_SOFTWARE;
ADC_REG_InitStruct->SequencerLength = LL_ADC_REG_SEQ_SCAN_DISABLE;
ADC_REG_InitStruct->SequencerDiscont = LL_ADC_REG_SEQ_DISCONT_DISABLE;
ADC_REG_InitStruct->ContinuousMode = LL_ADC_REG_CONV_SINGLE;
ADC_REG_InitStruct->DMATransfer = LL_ADC_REG_DMA_TRANSFER_NONE;
}
/**
* @brief Initialize some features of ADC group injected.
* @note These parameters have an impact on ADC scope: ADC group injected.
* Refer to corresponding unitary functions into
* @ref ADC_LL_EF_Configuration_ADC_Group_Regular
* (functions with prefix "INJ").
* @note The setting of these parameters by function @ref LL_ADC_Init()
* is conditioned to ADC state:
* ADC instance must be disabled.
* This condition is applied to all ADC features, for efficiency
* and compatibility over all STM32 families. However, the different
* features can be set under different ADC state conditions
* (setting possible with ADC enabled without conversion on going,
* ADC enabled with conversion on going, ...)
* Each feature can be updated afterwards with a unitary function
* and potentially with ADC in a different state than disabled,
* refer to description of each function for setting
* conditioned to ADC state.
* @note After using this function, other features must be configured
* using LL unitary functions.
* The minimum configuration remaining to be done is:
* - Set ADC group injected sequencer:
* map channel on the selected sequencer rank.
* Refer to function @ref LL_ADC_INJ_SetSequencerRanks().
* - Set ADC channel sampling time
* Refer to function LL_ADC_SetChannelSamplingTime();
* @param ADCx ADC instance
* @param ADC_INJ_InitStruct Pointer to a @ref LL_ADC_INJ_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ADC registers are initialized
* - ERROR: ADC registers are not initialized
*/
ErrorStatus LL_ADC_INJ_Init(ADC_TypeDef *ADCx, LL_ADC_INJ_InitTypeDef *ADC_INJ_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(ADCx));
#if defined(ADC3)
assert_param(IS_LL_ADC_INJ_TRIG_SOURCE(ADCx, ADC_INJ_InitStruct->TriggerSource));
#else
assert_param(IS_LL_ADC_INJ_TRIG_SOURCE(ADC_INJ_InitStruct->TriggerSource));
#endif
assert_param(IS_LL_ADC_INJ_SEQ_SCAN_LENGTH(ADC_INJ_InitStruct->SequencerLength));
if(ADC_INJ_InitStruct->SequencerLength != LL_ADC_INJ_SEQ_SCAN_DISABLE)
{
assert_param(IS_LL_ADC_INJ_SEQ_SCAN_DISCONT_MODE(ADC_INJ_InitStruct->SequencerDiscont));
}
assert_param(IS_LL_ADC_INJ_TRIG_AUTO(ADC_INJ_InitStruct->TrigAuto));
/* Note: Hardware constraint (refer to description of this function): */
/* ADC instance must be disabled. */
if(LL_ADC_IsEnabled(ADCx) == 0U)
{
/* Configuration of ADC hierarchical scope: */
/* - ADC group injected */
/* - Set ADC group injected trigger source */
/* - Set ADC group injected sequencer length */
/* - Set ADC group injected sequencer discontinuous mode */
/* - Set ADC group injected conversion trigger: independent or */
/* from ADC group regular */
/* Note: On this STM32 serie, ADC trigger edge is set when starting */
/* ADC conversion. */
/* Refer to function @ref LL_ADC_INJ_StartConversionExtTrig(). */
if(ADC_INJ_InitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE)
{
MODIFY_REG(ADCx->CR1,
ADC_CR1_JDISCEN
| ADC_CR1_JAUTO
,
ADC_INJ_InitStruct->SequencerDiscont
| ADC_INJ_InitStruct->TrigAuto
);
}
else
{
MODIFY_REG(ADCx->CR1,
ADC_CR1_JDISCEN
| ADC_CR1_JAUTO
,
LL_ADC_REG_SEQ_DISCONT_DISABLE
| ADC_INJ_InitStruct->TrigAuto
);
}
MODIFY_REG(ADCx->CR2,
ADC_CR2_JEXTSEL
,
ADC_INJ_InitStruct->TriggerSource
);
/* Note: Hardware constraint (refer to description of this function): */
/* Note: If ADC instance feature scan mode is disabled */
/* (refer to ADC instance initialization structure */
/* parameter @ref SequencersScanMode */
/* or function @ref LL_ADC_SetSequencersScanMode() ), */
/* this parameter is discarded. */
LL_ADC_INJ_SetSequencerLength(ADCx, ADC_INJ_InitStruct->SequencerLength);
}
else
{
/* Initialization error: ADC instance is not disabled. */
status = ERROR;
}
return status;
}
/**
* @brief Set each @ref LL_ADC_INJ_InitTypeDef field to default value.
* @param ADC_INJ_InitStruct Pointer to a @ref LL_ADC_INJ_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_ADC_INJ_StructInit(LL_ADC_INJ_InitTypeDef *ADC_INJ_InitStruct)
{
/* Set ADC_INJ_InitStruct fields to default values */
/* Set fields of ADC group injected */
ADC_INJ_InitStruct->TriggerSource = LL_ADC_INJ_TRIG_SOFTWARE;
ADC_INJ_InitStruct->SequencerLength = LL_ADC_INJ_SEQ_SCAN_DISABLE;
ADC_INJ_InitStruct->SequencerDiscont = LL_ADC_INJ_SEQ_DISCONT_DISABLE;
ADC_INJ_InitStruct->TrigAuto = LL_ADC_INJ_TRIG_INDEPENDENT;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* ADC1 || ADC2 || ADC3 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 22,368 |
1,338 |
<filename>src/system/libroot/posix/unistd/directory.c
/*
* Copyright 2002-2009, <NAME>, <EMAIL>.
* Distributed under the terms of the MIT License.
*/
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno_private.h>
#include <syscalls.h>
#include <syscall_utils.h>
int
chdir(const char *path)
{
RETURN_AND_SET_ERRNO(_kern_setcwd(-1, path));
}
int
fchdir(int fd)
{
RETURN_AND_SET_ERRNO(_kern_setcwd(fd, NULL));
}
char *
getcwd(char *buffer, size_t size)
{
bool allocated = false;
status_t status;
if (buffer == NULL) {
buffer = malloc(size = PATH_MAX);
if (buffer == NULL) {
__set_errno(B_NO_MEMORY);
return NULL;
}
allocated = true;
}
status = _kern_getcwd(buffer, size);
if (status < B_OK) {
if (allocated)
free(buffer);
__set_errno(status);
return NULL;
}
return buffer;
}
int
rmdir(const char *path)
{
RETURN_AND_SET_ERRNO(_kern_remove_dir(-1, path));
}
| 411 |
482 |
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nutz.boot.starter.seata.aop.trans;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import org.nutz.aop.InterceptorChain;
import org.nutz.aop.MethodInterceptor;
import io.seata.common.exception.ShouldNeverHappenException;
import io.seata.common.util.StringUtils;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.DefaultFailureHandlerImpl;
import io.seata.tm.api.FailureHandler;
import io.seata.tm.api.TransactionalExecutor;
import io.seata.tm.api.TransactionalTemplate;
import io.seata.tm.api.transaction.NoRollbackRule;
import io.seata.tm.api.transaction.RollbackRule;
import io.seata.tm.api.transaction.TransactionInfo;
/**
* The type Global transactional interceptor. 全局事务拦截器
*/
public class SeataTransInterceptor implements MethodInterceptor {
private static final FailureHandler DEFAULT_FAIL_HANDLER = new DefaultFailureHandlerImpl();
private final TransactionalTemplate transactionalTemplate = new TransactionalTemplate();
private final FailureHandler failureHandler;
private GlobalTransactional globalTrxAnno;
private String name;
/**
* Instantiates a new Global transactional interceptor.
*
* @param failureHandler the failure handler
*/
public SeataTransInterceptor(FailureHandler failureHandler, GlobalTransactional globalTrxAnno, Method method) {
if (null == failureHandler) {
failureHandler = DEFAULT_FAIL_HANDLER;
}
this.failureHandler = failureHandler;
this.globalTrxAnno = globalTrxAnno;
String name = globalTrxAnno.name();
if (!StringUtils.isNullOrEmpty(name)) {
this.name = name;
}
else
this.name = formatMethod(method);
}
@Override
public void filter(InterceptorChain chain) throws Throwable {
try {
transactionalTemplate.execute(new TransactionalExecutor() {
@Override
public Object execute() throws Throwable {
return chain.doChain();
}
public String name() {
return name;
}
@Override
public TransactionInfo getTransactionInfo() {
TransactionInfo transactionInfo = new TransactionInfo();
transactionInfo.setTimeOut(globalTrxAnno.timeoutMills());
transactionInfo.setName(name());
Set<RollbackRule> rollbackRules = new LinkedHashSet<>();
for (Class<?> rbRule : globalTrxAnno.rollbackFor()) {
rollbackRules.add(new RollbackRule(rbRule));
}
for (String rbRule : globalTrxAnno.rollbackForClassName()) {
rollbackRules.add(new RollbackRule(rbRule));
}
for (Class<?> rbRule : globalTrxAnno.noRollbackFor()) {
rollbackRules.add(new NoRollbackRule(rbRule));
}
for (String rbRule : globalTrxAnno.noRollbackForClassName()) {
rollbackRules.add(new NoRollbackRule(rbRule));
}
transactionInfo.setRollbackRules(rollbackRules);
return transactionInfo;
}
});
} catch (TransactionalExecutor.ExecutionException e) {
TransactionalExecutor.Code code = e.getCode();
switch (code) {
case RollbackDone:
throw e.getOriginalException();
case BeginFailure:
failureHandler.onBeginFailure(e.getTransaction(), e.getCause());
throw e.getCause();
case CommitFailure:
failureHandler.onCommitFailure(e.getTransaction(), e.getCause());
throw e.getCause();
case RollbackFailure:
failureHandler.onRollbackFailure(e.getTransaction(), e.getCause());
throw e.getCause();
default:
throw new ShouldNeverHappenException("Unknown TransactionalExecutor.Code: " + code);
}
}
}
public static String formatMethod(Method method) {
String paramTypes = Arrays.stream(method.getParameterTypes())
.map(Class::getName)
.reduce((p1, p2) -> String.format("%s, %s", p1, p2))
.orElse("");
return method.getName() + "(" + paramTypes + ")";
}
}
| 2,304 |
1,346 |
<filename>Trakttv.bundle/Contents/Libraries/Shared/plugin/models/migrations/000_initial.py
from plugin.models.core import db
from exception_wrappers.libraries.playhouse.apsw_ext import *
def migrate(migrator, database):
migrator.create_tables(
#
# Plex
#
PlexAccount,
PlexBasicCredential,
#
# Sync
#
SyncStatus,
SyncResult,
SyncResultError,
SyncResultException,
#
# Trakt
#
TraktAccount,
TraktBasicCredential,
TraktOAuthCredential,
#
# Main
#
Account,
Exception,
Message,
Session,
ConfigurationOption,
ActionHistory,
ActionQueue,
Client,
ClientRule,
User,
UserRule
)
class Account(Model):
class Meta:
database = db
name = CharField(null=True, unique=True)
thumb = TextField(null=True)
class Client(Model):
class Meta:
database = db
db_table = 'session.client'
account = ForeignKeyField(Account, 'clients', null=True)
# Identification
key = CharField(unique=True)
name = CharField(null=True)
# Device
device_class = CharField(null=True)
platform = CharField(null=True)
product = CharField(null=True)
version = CharField(null=True)
# Network
host = CharField(null=True)
address = CharField(null=True)
port = IntegerField(null=True)
# Protocol
protocol = CharField(null=True)
protocol_capabilities = CharField(null=True)
protocol_version = CharField(null=True)
class ClientRule(Model):
class Meta:
database = db
db_table = 'session.client.rule'
account = ForeignKeyField(Account, 'client_rules')
key = CharField(null=True)
name = CharField(null=True)
address = CharField(null=True)
priority = IntegerField()
class User(Model):
class Meta:
database = db
db_table = 'session.user'
account = ForeignKeyField(Account, 'users', null=True)
# Identification
key = IntegerField(unique=True)
name = CharField(null=True)
thumb = CharField(null=True)
class UserRule(Model):
class Meta:
database = db
db_table = 'session.user.rule'
account = ForeignKeyField(Account, 'user_rules')
name = CharField(null=True)
priority = IntegerField()
class Session(Model):
class Meta:
database = db
account = ForeignKeyField(Account, 'sessions', null=True)
client = ForeignKeyField(Client, 'sessions', to_field='key', null=True)
user = ForeignKeyField(User, 'sessions', to_field='key', null=True)
rating_key = IntegerField(null=True)
session_key = TextField(null=True, unique=True)
state = CharField(null=True)
progress = FloatField(null=True)
duration = IntegerField(null=True)
view_offset = IntegerField(null=True)
class ConfigurationOption(Model):
class Meta:
database = db
db_table = 'configuration.option'
primary_key = CompositeKey('account', 'key')
account = ForeignKeyField(Account, 'sync_configuration')
key = CharField(max_length=60)
value = BlobField()
#
# Action
#
class ActionHistory(Model):
class Meta:
database = db
db_table = 'action.history'
account = ForeignKeyField(Account, 'action_history')
session = ForeignKeyField(Session, 'action_history', null=True)
event = CharField()
performed = CharField(null=True)
queued_at = DateTimeField()
sent_at = DateTimeField()
class ActionQueue(Model):
class Meta:
database = db
db_table = 'action.queue'
primary_key = CompositeKey('session', 'event')
account = ForeignKeyField(Account, 'action_queue')
session = ForeignKeyField(Session, 'action_queue', null=True)
event = CharField()
request = BlobField()
queued_at = DateTimeField()
#
# Exception / Message
#
class Message(Model):
class Meta:
database = db
db_table = 'message'
code = IntegerField(null=True)
type = IntegerField()
last_logged_at = DateTimeField()
last_viewed_at = DateTimeField(null=True)
# Tracking data
exception_hash = CharField(null=True, unique=True, max_length=32)
revision = IntegerField(null=True)
version_base = CharField(max_length=12)
version_branch = CharField(max_length=42)
# User-friendly explanation
summary = CharField(null=True, max_length=160) # Short single-line summary
description = TextField(null=True) # Extra related details
class Exception(Model):
class Meta:
database = db
db_table = 'exception'
error = ForeignKeyField(Message, 'exceptions', null=True)
type = TextField()
message = TextField()
traceback = TextField()
hash = CharField(null=True, max_length=32)
timestamp = DateTimeField()
version_base = CharField(max_length=12)
version_branch = CharField(max_length=42)
#
# Plex
#
class PlexAccount(Model):
class Meta:
database = db
db_table = 'plex.account'
account = ForeignKeyField(Account, 'plex_accounts', unique=True)
username = CharField(null=True, unique=True)
thumb = TextField(null=True)
class PlexBasicCredential(Model):
class Meta:
database = db
db_table = 'plex.credential.basic'
account = ForeignKeyField(PlexAccount, 'basic_credentials', unique=True)
password = CharField(null=True)
# Authorization
token = CharField(null=True)
#
# Trakt
#
class TraktAccount(Model):
class Meta:
database = db
db_table = 'trakt.account'
account = ForeignKeyField(Account, 'trakt_accounts', unique=True)
username = CharField(null=True, unique=True)
thumb = TextField(null=True)
cover = TextField(null=True)
timezone = TextField(null=True)
refreshed_at = DateTimeField(null=True)
class TraktBasicCredential(Model):
class Meta:
database = db
db_table = 'trakt.credential.basic'
account = ForeignKeyField(TraktAccount, 'basic_credentials', unique=True)
password = CharField(null=True)
# Authorization
token = CharField(null=True)
class TraktOAuthCredential(Model):
class Meta:
database = db
db_table = 'trakt.credential.oauth'
account = ForeignKeyField(TraktAccount, 'oauth_credentials', unique=True)
code = CharField(null=True)
# Authorization
access_token = CharField(null=True)
refresh_token = CharField(null=True)
created_at = IntegerField(null=True)
expires_in = IntegerField(null=True)
token_type = CharField(null=True)
scope = CharField(null=True)
#
# Sync
#
class SyncStatus(Model):
class Meta:
database = db
db_table = 'sync.status'
account = ForeignKeyField(Account, 'sync_status')
mode = IntegerField()
section = CharField(null=True, max_length=3)
class SyncResult(Model):
class Meta:
database = db
db_table = 'sync.result'
status = ForeignKeyField(SyncStatus, 'history')
# Timestamps
started_at = DateTimeField(null=True)
ended_at = DateTimeField(null=True)
# Result
success = BooleanField(null=True)
class SyncResultError(Model):
class Meta:
database = db
db_table = 'sync.result.error'
result = ForeignKeyField(SyncResult, 'errors')
error = ForeignKeyField(Message, 'results')
class SyncResultException(Model):
class Meta:
database = db
db_table = 'sync.result.exception'
result = ForeignKeyField(SyncResult, 'exceptions')
exception = ForeignKeyField(Exception, 'results')
#
# Schema specification (for migration verification)
#
SPEC = {
#
# Account
#
'account': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'name': 'VARCHAR(255)',
'thumb': 'TEXT'
},
'plex.account': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'account_id': 'INTEGER NOT NULL',
'username': 'VARCHAR(255)',
'thumb': 'TEXT'
},
'plex.credential.basic': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'account_id': 'INTEGER NOT NULL',
'password': 'VARCHAR(255)',
'token': 'VARCHAR(255)'
},
'trakt.account': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'account_id': 'INTEGER NOT NULL',
'username': 'VARCHAR(255)',
'thumb': 'TEXT',
'cover': 'TEXT',
'timezone': 'TEXT',
'refreshed_at': 'DATETIME'
},
'trakt.credential.basic': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'account_id': 'INTEGER NOT NULL',
'password': '<PASSWORD>(<PASSWORD>)',
'token': 'VARCHAR(255)'
},
'trakt.credential.oauth': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'account_id': 'INTEGER NOT NULL',
'code': 'VARCHAR(255)',
'access_token': 'VARCHAR(255)',
'refresh_token': 'VARCHAR(255)',
'created_at': 'INTEGER',
'expires_in': 'INTEGER',
'token_type': 'VARCHAR(255)',
'scope': 'VARCHAR(255)'
},
#
# Session
#
'session': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'account_id': 'INTEGER',
'client_id': 'VARCHAR(255)',
'user_id': 'INTEGER',
'rating_key': 'INTEGER',
'session_key': 'TEXT',
'state': 'VARCHAR(255)',
'progress': 'REAL',
'duration': 'INTEGER',
'view_offset': 'INTEGER'
},
'session.client': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'account_id': 'INTEGER',
'key': 'VARCHAR(255) NOT NULL',
'name': 'VARCHAR(255)',
'device_class': 'VARCHAR(255)',
'platform': 'VARCHAR(255)',
'product': 'VARCHAR(255)',
'version': 'VARCHAR(255)',
'host': 'VARCHAR(255)',
'address': 'VARCHAR(255)',
'port': 'INTEGER',
'protocol': 'VARCHAR(255)',
'protocol_capabilities': 'VARCHAR(255)',
'protocol_version': 'VARCHAR(255)'
},
'session.client.rule': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'account_id': 'INTEGER NOT NULL',
'key': 'VARCHAR(255)',
'name': 'VARCHAR(255)',
'address': 'VARCHAR(255)',
'priority': 'INTEGER NOT NULL'
},
'session.user': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'account_id': 'INTEGER',
'key': 'INTEGER NOT NULL',
'name': 'VARCHAR(255)',
'thumb': 'VARCHAR(255)',
},
'session.user.rule': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'account_id': 'INTEGER NOT NULL',
'name': 'VARCHAR(255)',
'priority': 'INTEGER NOT NULL'
},
#
# Configuration
#
'configuration.option': {
'key': 'VARCHAR(60) PRIMARY KEY NOT NULL',
'account_id': 'INTEGER PRIMARY KEY NOT NULL',
'value': 'BLOB NOT NULL'
},
#
# Actions
#
'action.history': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'account_id': 'INTEGER NOT NULL',
'session_id': 'INTEGER',
'event': 'VARCHAR(255) NOT NULL',
'performed': 'VARCHAR(255)',
'queued_at': 'DATETIME NOT NULL',
'sent_at': 'DATETIME NOT NULL'
},
'action.queue': {
'account_id': 'INTEGER NOT NULL',
'session_id': 'INTEGER PRIMARY KEY',
'event': 'VARCHAR(255) PRIMARY KEY NOT NULL',
'request': 'BLOB NOT NULL',
'queued_at': 'DATETIME NOT NULL',
},
#
# Messages/Exceptions
#
'message': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'code': 'INTEGER',
'type': 'INTEGER NOT NULL',
'last_logged_at': 'DATETIME NOT NULL',
'last_viewed_at': 'DATETIME',
'exception_hash': 'VARCHAR(32)',
'revision': 'INTEGER',
'version_base': 'VARCHAR(12) NOT NULL',
'version_branch': 'VARCHAR(42) NOT NULL',
'summary': 'VARCHAR(160)',
'description': 'TEXT'
},
'exception': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'error_id': 'INTEGER',
'type': 'TEXT NOT NULL',
'message': 'TEXT NOT NULL',
'traceback': 'TEXT NOT NULL',
'hash': 'VARCHAR(32)',
'timestamp': 'DATETIME NOT NULL',
'version_base': 'VARCHAR(12) NOT NULL',
'version_branch': 'VARCHAR(42) NOT NULL',
},
#
# Syncing
#
'sync.status': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'account_id': 'INTEGER NOT NULL',
'mode': 'INTEGER NOT NULL',
'section': 'VARCHAR(3)'
},
'sync.result': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'status_id': 'INTEGER NOT NULL',
'started_at': 'DATETIME',
'ended_at': 'DATETIME',
'success': 'SMALLINT'
},
'sync.result.error': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'result_id': 'INTEGER NOT NULL',
'error_id': 'INTEGER NOT NULL'
},
'sync.result.exception': {
'id': 'INTEGER PRIMARY KEY NOT NULL',
'result_id': 'INTEGER NOT NULL',
'exception_id': 'INTEGER NOT NULL'
},
}
| 7,822 |
2,606 |
<reponame>sxqsfun/weixin-popular
package weixin.popular.bean.paymch;
import java.io.Serializable;
/**
*
* 微信代扣小程序纯签约包装数据
* @author LiYi
*
*/
public class WxaEntrustwebData implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String appId;
private PapayEntrustweb extraData;
private String path;
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public PapayEntrustweb getExtraData() {
return extraData;
}
public void setExtraData(PapayEntrustweb extraData) {
this.extraData = extraData;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
| 353 |
1,165 |
/*******************************************************************************
* Copyright 2018 T Mobile, 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. 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.tmobile.pacman.api.admin.domain;
import java.util.List;
/**
* UpdateAssetGroupDetails Domain Class
*/
public class UpdateAssetGroupDetails extends CreateUpdateAssetGroupDetails {
private String groupId;
private List<TargetTypesProjection> remainingTargetTypes;
private List<TargetTypesDetails> remainingTargetTypesFullDetails;
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public List<TargetTypesProjection> getRemainingTargetTypes() {
return remainingTargetTypes;
}
public void setRemainingTargetTypes(List<TargetTypesProjection> remainingTargetTypes) {
this.remainingTargetTypes = remainingTargetTypes;
}
public List<TargetTypesDetails> getRemainingTargetTypesFullDetails() {
return remainingTargetTypesFullDetails;
}
public void setRemainingTargetTypesFullDetails(List<TargetTypesDetails> remainingTargetTypesFullDetails) {
this.remainingTargetTypesFullDetails = remainingTargetTypesFullDetails;
}
}
| 454 |
354 |
<reponame>muehleisen/OpenStudio<filename>src/model/GeneratorFuelCellPowerModule.cpp
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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.
***********************************************************************************************************************/
#include "Model.hpp"
#include "Model_Impl.hpp"
#include "GeneratorFuelCell.hpp"
#include "GeneratorFuelCell_Impl.hpp"
#include "GeneratorFuelCellPowerModule.hpp"
#include "GeneratorFuelCellPowerModule_Impl.hpp"
#include "CurveQuadratic.hpp"
#include "CurveQuadratic_Impl.hpp"
#include "ThermalZone.hpp"
#include "ThermalZone_Impl.hpp"
#include "Node.hpp"
#include "Node_Impl.hpp"
#include <utilities/idd/IddFactory.hxx>
#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/OS_Generator_FuelCell_PowerModule_FieldEnums.hxx>
#include "../utilities/units/Unit.hpp"
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail {
GeneratorFuelCellPowerModule_Impl::GeneratorFuelCellPowerModule_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle)
: ModelObject_Impl(idfObject, model, keepHandle) {
OS_ASSERT(idfObject.iddObject().type() == GeneratorFuelCellPowerModule::iddObjectType());
}
GeneratorFuelCellPowerModule_Impl::GeneratorFuelCellPowerModule_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model,
bool keepHandle)
: ModelObject_Impl(other, model, keepHandle) {
OS_ASSERT(other.iddObject().type() == GeneratorFuelCellPowerModule::iddObjectType());
}
GeneratorFuelCellPowerModule_Impl::GeneratorFuelCellPowerModule_Impl(const GeneratorFuelCellPowerModule_Impl& other, Model_Impl* model,
bool keepHandle)
: ModelObject_Impl(other, model, keepHandle) {}
const std::vector<std::string>& GeneratorFuelCellPowerModule_Impl::outputVariableNames() const {
static const std::vector<std::string> result;
return result;
}
IddObjectType GeneratorFuelCellPowerModule_Impl::iddObjectType() const {
return GeneratorFuelCellPowerModule::iddObjectType();
}
std::vector<IddObjectType> GeneratorFuelCellPowerModule_Impl::allowableChildTypes() const {
std::vector<IddObjectType> result;
result.push_back(IddObjectType::OS_Curve_Quadratic);
return result;
}
// Returns the children object
std::vector<ModelObject> GeneratorFuelCellPowerModule_Impl::children() const {
std::vector<ModelObject> result;
boost::optional<CurveQuadratic> curveQ;
if ((curveQ = efficiencyCurve())) {
result.push_back(curveQ.get());
}
if ((curveQ = skinLossQuadraticCurve())) {
result.push_back(curveQ.get());
}
return result;
}
// Get the parent GeneratorFuelCell
boost::optional<GeneratorFuelCell> GeneratorFuelCellPowerModule_Impl::fuelCell() const {
boost::optional<GeneratorFuelCell> fc;
// We use getModelObjectSources to check if more than one
std::vector<GeneratorFuelCell> fcs = getObject<ModelObject>().getModelObjectSources<GeneratorFuelCell>(GeneratorFuelCell::iddObjectType());
if (fcs.size() > 0u) {
if (fcs.size() > 1u) {
LOG(Error, briefDescription() << " is referenced by more than one GeneratorFuelCell, returning the first");
}
fc = fcs[0];
}
return fc;
}
std::string GeneratorFuelCellPowerModule_Impl::efficiencyCurveMode() const {
boost::optional<std::string> value = getString(OS_Generator_FuelCell_PowerModuleFields::EfficiencyCurveMode, true);
if (!value) {
LOG_AND_THROW(" does not have an Efficiency Curve Mode defined.");
}
return value.get();
}
CurveQuadratic GeneratorFuelCellPowerModule_Impl::efficiencyCurve() const {
boost::optional<CurveQuadratic> value = optionalEfficiencyCurve();
if (!value) {
LOG_AND_THROW(" does not have an Efficiency Curve attached.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::nominalEfficiency() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::NominalEfficiency, true);
if (!value) {
LOG_AND_THROW(" does not have an Nominal Efficiency.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::nominalElectricalPower() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::NominalElectricalPower, true);
if (!value) {
LOG_AND_THROW(" does not have an Nominal Electrical Power.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::numberofStopsatStartofSimulation() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::NumberofStopsatStartofSimulation, true);
if (!value) {
LOG_AND_THROW(" does not have numberofStopsatStartofSimulation.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::cyclingPerformanceDegradationCoefficient() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::CyclingPerformanceDegradationCoefficient, true);
if (!value) {
LOG_AND_THROW(" does not have cyclingPerformanceDegradationCoefficient.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::numberofRunHoursatBeginningofSimulation() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::NumberofRunHoursatBeginningofSimulation, true);
if (!value) {
LOG_AND_THROW(" does not have numberofRunHoursatBeginningofSimulation.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::accumulatedRunTimeDegradationCoefficient() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::AccumulatedRunTimeDegradationCoefficient, true);
if (!value) {
LOG_AND_THROW(" does not have accumulatedRunTimeDegradationCoefficient.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::runTimeDegradationInitiationTimeThreshold() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::RunTimeDegradationInitiationTimeThreshold, true);
if (!value) {
LOG_AND_THROW(" does not have runTimeDegradationInitiationTimeThreshold.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::powerUpTransientLimit() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::PowerUpTransientLimit, true);
if (!value) {
LOG_AND_THROW(" does not have powerUpTransientLimit.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::powerDownTransientLimit() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::PowerDownTransientLimit, true);
if (!value) {
LOG_AND_THROW(" does not have powerDownTransientLimit.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::startUpTime() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::StartUpTime, true);
if (!value) {
LOG_AND_THROW(" does not have startUpTime.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::startUpFuel() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::StartUpFuel, true);
if (!value) {
LOG_AND_THROW(" does not have startUpFuel.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::startUpElectricityConsumption() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::StartUpElectricityConsumption, true);
if (!value) {
LOG_AND_THROW(" does not have startUpElectricityConsumption.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::startUpElectricityProduced() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::StartUpElectricityProduced, true);
if (!value) {
LOG_AND_THROW(" does not have startUpElectricityProduced.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::shutDownTime() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::ShutDownTime, true);
if (!value) {
LOG_AND_THROW(" does not have shutDownTime.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::shutDownFuel() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::ShutDownFuel, true);
if (!value) {
LOG_AND_THROW(" does not have shutDownFuel.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::shutDownElectricityConsumption() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::ShutDownElectricityConsumption, true);
if (!value) {
LOG_AND_THROW(" does not have shutDownElectricityConsumption.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::ancillaryElectricityConstantTerm() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::AncillaryElectricityConstantTerm, true);
if (!value) {
LOG_AND_THROW(" does not have ancillaryElectricityConstantTerm.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::ancillaryElectricityLinearTerm() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::AncillaryElectricityLinearTerm, true);
if (!value) {
LOG_AND_THROW(" does not have ancillaryElectricityLinearTerm.");
}
return value.get();
}
std::string GeneratorFuelCellPowerModule_Impl::skinLossCalculationMode() const {
boost::optional<std::string> value = getString(OS_Generator_FuelCell_PowerModuleFields::SkinLossCalculationMode, true);
if (!value) {
LOG_AND_THROW(" does not have skinLossCalculationMode.");
}
return value.get();
}
boost::optional<ThermalZone> GeneratorFuelCellPowerModule_Impl::zone() const {
return getObject<ModelObject>().getModelObjectTarget<ThermalZone>(OS_Generator_FuelCell_PowerModuleFields::ZoneName);
}
double GeneratorFuelCellPowerModule_Impl::skinLossRadiativeFraction() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::SkinLossRadiativeFraction, true);
if (!value) {
LOG_AND_THROW(" does not have skinLossRadiativeFraction.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::constantSkinLossRate() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::ConstantSkinLossRate, true);
if (!value) {
LOG_AND_THROW(" does not have constantSkinLossRate.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::skinLossUFactorTimesAreaTerm() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::SkinLossUFactorTimesAreaTerm, true);
if (!value) {
LOG_AND_THROW(" does not have skinLossUFactorTimesAreaTerm.");
}
return value.get();
}
boost::optional<CurveQuadratic> GeneratorFuelCellPowerModule_Impl::skinLossQuadraticCurve() const {
return getObject<ModelObject>().getModelObjectTarget<CurveQuadratic>(OS_Generator_FuelCell_PowerModuleFields::SkinLossQuadraticCurveName);
}
double GeneratorFuelCellPowerModule_Impl::dilutionAirFlowRate() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::DilutionAirFlowRate, true);
if (!value) {
LOG_AND_THROW(" does not have dilutionAirFlowRate.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::stackHeatlosstoDilutionAir() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::StackHeatlosstoDilutionAir, true);
if (!value) {
LOG_AND_THROW(" does not have stackHeatlosstoDilutionAir.");
}
return value.get();
}
boost::optional<Node> GeneratorFuelCellPowerModule_Impl::dilutionInletAirNode() const {
return getObject<ModelObject>().getModelObjectTarget<Node>(OS_Generator_FuelCell_PowerModuleFields::DilutionInletAirNodeName);
}
boost::optional<Node> GeneratorFuelCellPowerModule_Impl::dilutionOutletAirNode() const {
return getObject<ModelObject>().getModelObjectTarget<Node>(OS_Generator_FuelCell_PowerModuleFields::DilutionOutletAirNodeName);
}
double GeneratorFuelCellPowerModule_Impl::minimumOperatingPoint() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::MinimumOperatingPoint, true);
if (!value) {
LOG_AND_THROW(" does not have minimumOperatingPoint.");
}
return value.get();
}
double GeneratorFuelCellPowerModule_Impl::maximumOperatingPoint() const {
boost::optional<double> value = getDouble(OS_Generator_FuelCell_PowerModuleFields::MaximumOperatingPoint, true);
if (!value) {
LOG_AND_THROW(" does not have maximumOperatingPoint.");
}
return value.get();
}
bool GeneratorFuelCellPowerModule_Impl::setEfficiencyCurveMode(const std::string& efficiencyCurveMode) {
bool result = setString(OS_Generator_FuelCell_PowerModuleFields::EfficiencyCurveMode, efficiencyCurveMode);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetEfficiencyCurveMode() {
bool result = setString(OS_Generator_FuelCell_PowerModuleFields::EfficiencyCurveMode, "Annex42");
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setEfficiencyCurve(const CurveQuadratic& quadraticCurve) {
bool result = setPointer(OS_Generator_FuelCell_PowerModuleFields::EfficiencyCurveName, quadraticCurve.handle());
return result;
}
bool GeneratorFuelCellPowerModule_Impl::setNominalEfficiency(double nominalEfficiency) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::NominalEfficiency, nominalEfficiency);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetNominalEfficiency() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::NominalEfficiency, 1);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setNominalElectricalPower(double nominalElectricalPower) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::NominalElectricalPower, nominalElectricalPower);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetNominalElectricalPower() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::NominalElectricalPower, 3400);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setNumberofStopsatStartofSimulation(double numberofStopsatStartofSimulation) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::NumberofStopsatStartofSimulation, numberofStopsatStartofSimulation);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetNumberofStopsatStartofSimulation() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::NumberofStopsatStartofSimulation, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setCyclingPerformanceDegradationCoefficient(double cyclingPerformanceDegradationCoefficient) {
bool result =
setDouble(OS_Generator_FuelCell_PowerModuleFields::CyclingPerformanceDegradationCoefficient, cyclingPerformanceDegradationCoefficient);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetCyclingPerformanceDegradationCoefficient() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::CyclingPerformanceDegradationCoefficient, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setNumberofRunHoursatBeginningofSimulation(double numberofRunHoursatBeginningofSimulation) {
bool result =
setDouble(OS_Generator_FuelCell_PowerModuleFields::NumberofRunHoursatBeginningofSimulation, numberofRunHoursatBeginningofSimulation);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetNumberofRunHoursatBeginningofSimulation() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::NumberofRunHoursatBeginningofSimulation, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setAccumulatedRunTimeDegradationCoefficient(double accumulatedRunTimeDegradationCoefficient) {
bool result =
setDouble(OS_Generator_FuelCell_PowerModuleFields::AccumulatedRunTimeDegradationCoefficient, accumulatedRunTimeDegradationCoefficient);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetAccumulatedRunTimeDegradationCoefficient() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::AccumulatedRunTimeDegradationCoefficient, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setRunTimeDegradationInitiationTimeThreshold(double runTimeDegradationInitiationTimeThreshold) {
bool result =
setDouble(OS_Generator_FuelCell_PowerModuleFields::RunTimeDegradationInitiationTimeThreshold, runTimeDegradationInitiationTimeThreshold);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetRunTimeDegradationInitiationTimeThreshold() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::RunTimeDegradationInitiationTimeThreshold, 10000);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setPowerUpTransientLimit(double powerUpTransientLimit) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::PowerUpTransientLimit, powerUpTransientLimit);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetPowerUpTransientLimit() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::PowerUpTransientLimit, 1.4);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setPowerDownTransientLimit(double powerDownTransientLimit) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::PowerDownTransientLimit, powerDownTransientLimit);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetPowerDownTransientLimit() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::PowerDownTransientLimit, 0.2);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setStartUpTime(double startUpTime) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::StartUpTime, startUpTime);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetStartUpTime() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::StartUpTime, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setStartUpFuel(double startUpFuel) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::StartUpFuel, startUpFuel);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetStartUpFuel() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::StartUpFuel, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setStartUpElectricityConsumption(double startUpElectricityConsumption) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::StartUpElectricityConsumption, startUpElectricityConsumption);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetStartUpElectricityConsumption() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::StartUpElectricityConsumption, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setStartUpElectricityProduced(double startUpElectricityProduced) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::StartUpElectricityProduced, startUpElectricityProduced);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetStartUpElectricityProduced() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::StartUpElectricityProduced, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setShutDownTime(double shutDownTime) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::ShutDownTime, shutDownTime);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetShutDownTime() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::ShutDownTime, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setShutDownFuel(double shutDownFuel) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::ShutDownFuel, shutDownFuel);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetShutDownFuel() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::ShutDownFuel, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setShutDownElectricityConsumption(double shutDownElectricityConsumption) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::ShutDownElectricityConsumption, shutDownElectricityConsumption);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetShutDownElectricityConsumption() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::ShutDownElectricityConsumption, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setAncillaryElectricityConstantTerm(double ancillaryElectricityConstantTerm) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::AncillaryElectricityConstantTerm, ancillaryElectricityConstantTerm);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetAncillaryElectricityConstantTerm() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::AncillaryElectricityConstantTerm, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setAncillaryElectricityLinearTerm(double ancillaryElectricityLinearTerm) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::AncillaryElectricityLinearTerm, ancillaryElectricityLinearTerm);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetAncillaryElectricityLinearTerm() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::AncillaryElectricityLinearTerm, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setSkinLossCalculationMode(const std::string& skinLossCalculationMode) {
bool result = setString(OS_Generator_FuelCell_PowerModuleFields::SkinLossCalculationMode, skinLossCalculationMode);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetSkinLossCalculationMode() {
bool result = setString(OS_Generator_FuelCell_PowerModuleFields::SkinLossCalculationMode, "ConstantRate");
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setZone(const ThermalZone& zone) {
bool result = setPointer(OS_Generator_FuelCell_PowerModuleFields::ZoneName, zone.handle());
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetZone() {
bool result = setString(OS_Generator_FuelCell_PowerModuleFields::ZoneName, "");
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setSkinLossRadiativeFraction(double skinLossRadiativeFraction) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::SkinLossRadiativeFraction, skinLossRadiativeFraction);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetSkinLossRadiativeFraction() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::SkinLossRadiativeFraction, 1);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setConstantSkinLossRate(double constantSkinLossRate) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::ConstantSkinLossRate, constantSkinLossRate);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetConstantSkinLossRate() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::ConstantSkinLossRate, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setSkinLossUFactorTimesAreaTerm(double skinLossUFactorTimesAreaTerm) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::SkinLossUFactorTimesAreaTerm, skinLossUFactorTimesAreaTerm);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetSkinLossUFactorTimesAreaTerm() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::SkinLossUFactorTimesAreaTerm, 1);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setSkinLossQuadraticCurve(const CurveQuadratic& quadraticCurves) {
bool result = setPointer(OS_Generator_FuelCell_PowerModuleFields::SkinLossQuadraticCurveName, quadraticCurves.handle());
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetSkinLossQuadraticCurve() {
bool result = setString(OS_Generator_FuelCell_PowerModuleFields::SkinLossQuadraticCurveName, "");
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setDilutionAirFlowRate(double dilutionAirFlowRate) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::DilutionAirFlowRate, dilutionAirFlowRate);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetDilutionAirFlowRate() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::DilutionAirFlowRate, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setStackHeatlosstoDilutionAir(double stackHeatlosstoDilutionAir) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::StackHeatlosstoDilutionAir, stackHeatlosstoDilutionAir);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetStackHeatlosstoDilutionAir() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::StackHeatlosstoDilutionAir, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setDilutionInletAirNode(const Node& node) {
bool result = setPointer(OS_Generator_FuelCell_PowerModuleFields::DilutionInletAirNodeName, node.handle());
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetDilutionInletAirNode() {
bool result = setString(OS_Generator_FuelCell_PowerModuleFields::DilutionInletAirNodeName, "");
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setDilutionOutletAirNode(const Node& node) {
bool result = setPointer(OS_Generator_FuelCell_PowerModuleFields::DilutionOutletAirNodeName, node.handle());
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetDilutionOutletAirNode() {
bool result = setString(OS_Generator_FuelCell_PowerModuleFields::DilutionOutletAirNodeName, "");
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setMinimumOperatingPoint(double minimumOperatingPoint) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::MinimumOperatingPoint, minimumOperatingPoint);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetMinimumOperatingPoint() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::MinimumOperatingPoint, 0);
OS_ASSERT(result);
}
bool GeneratorFuelCellPowerModule_Impl::setMaximumOperatingPoint(double maximumOperatingPoint) {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::MaximumOperatingPoint, maximumOperatingPoint);
OS_ASSERT(result);
return result;
}
void GeneratorFuelCellPowerModule_Impl::resetMaximumOperatingPoint() {
bool result = setDouble(OS_Generator_FuelCell_PowerModuleFields::MaximumOperatingPoint, 0);
OS_ASSERT(result);
}
boost::optional<CurveQuadratic> GeneratorFuelCellPowerModule_Impl::optionalEfficiencyCurve() const {
return getObject<ModelObject>().getModelObjectTarget<CurveQuadratic>(OS_Generator_FuelCell_PowerModuleFields::EfficiencyCurveName);
}
} // namespace detail
GeneratorFuelCellPowerModule::GeneratorFuelCellPowerModule(const Model& model, const ThermalZone& heatlossZone, const Node& dilutionInletAirNode,
const Node& dilutionOutletAirNode)
: ModelObject(GeneratorFuelCellPowerModule::iddObjectType(), model) {
OS_ASSERT(getImpl<detail::GeneratorFuelCellPowerModule_Impl>());
setEfficiencyCurveMode("Annex42");
//create default curve
CurveQuadratic curveQuadratic(model);
curveQuadratic.setCoefficient1Constant(1);
curveQuadratic.setCoefficient2x(0);
curveQuadratic.setCoefficient3xPOW2(0);
curveQuadratic.setMinimumValueofx(0);
curveQuadratic.setMaximumValueofx(1);
bool ok = setEfficiencyCurve(curveQuadratic);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s efficiencyCurve to " << curveQuadratic.briefDescription() << ".");
}
setNominalEfficiency(1.0);
setNominalElectricalPower(3400);
setNumberofStopsatStartofSimulation(0);
setCyclingPerformanceDegradationCoefficient(0.0);
setNumberofRunHoursatBeginningofSimulation(0);
setAccumulatedRunTimeDegradationCoefficient(0.0);
setRunTimeDegradationInitiationTimeThreshold(10000);
setPowerUpTransientLimit(1.4);
setPowerDownTransientLimit(0.2);
setStartUpTime(0.0);
setStartUpFuel(0.2);
setStartUpElectricityConsumption(0);
setStartUpElectricityProduced(0.0);
setShutDownTime(0.0);
setShutDownFuel(0.2);
setShutDownElectricityConsumption(0);
setAncillaryElectricityConstantTerm(0.0);
setAncillaryElectricityLinearTerm(0.0);
ok = setZone(heatlossZone);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s heat loss zone to " << heatlossZone.briefDescription() << ".");
}
setSkinLossCalculationMode("ConstantRate");
setSkinLossRadiativeFraction(0.6392);
setConstantSkinLossRate(729);
setSkinLossUFactorTimesAreaTerm(0.0);
ok = setSkinLossQuadraticCurve(curveQuadratic);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s skin Loss Curve to " << curveQuadratic.briefDescription() << ".");
}
setDilutionAirFlowRate(0.006156);
setStackHeatlosstoDilutionAir(2307);
ok = setDilutionInletAirNode(dilutionInletAirNode);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s dilution inlet air node to " << dilutionInletAirNode.briefDescription() << ".");
}
ok = setDilutionOutletAirNode(dilutionOutletAirNode);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s dilution outlet air node to " << dilutionOutletAirNode.briefDescription() << ".");
}
setMinimumOperatingPoint(3010);
setMaximumOperatingPoint(3728);
}
GeneratorFuelCellPowerModule::GeneratorFuelCellPowerModule(const Model& model, const CurveQuadratic& efficiencyCurve,
const ThermalZone& heatlossZone, const Node& dilutionInletAirNode,
const Node& dilutionOutletAirNode, const CurveQuadratic& skinlossCurve)
: ModelObject(GeneratorFuelCellPowerModule::iddObjectType(), model) {
OS_ASSERT(getImpl<detail::GeneratorFuelCellPowerModule_Impl>());
setEfficiencyCurveMode("Annex42");
bool ok = setEfficiencyCurve(efficiencyCurve);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s efficiencyCurve to " << efficiencyCurve.briefDescription() << ".");
}
setNominalEfficiency(1.0);
setNominalElectricalPower(3400);
setNumberofStopsatStartofSimulation(0);
setCyclingPerformanceDegradationCoefficient(0.0);
setNumberofRunHoursatBeginningofSimulation(0);
setAccumulatedRunTimeDegradationCoefficient(0.0);
setRunTimeDegradationInitiationTimeThreshold(10000);
setPowerUpTransientLimit(1.4);
setPowerDownTransientLimit(0.2);
setStartUpTime(0.0);
setStartUpFuel(0.2);
setStartUpElectricityConsumption(0);
setStartUpElectricityProduced(0.0);
setShutDownTime(0.0);
setShutDownFuel(0.2);
setShutDownElectricityConsumption(0);
setAncillaryElectricityConstantTerm(0.0);
setAncillaryElectricityLinearTerm(0.0);
ok = setZone(heatlossZone);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s heatloss zone to " << heatlossZone.briefDescription() << ".");
}
setSkinLossCalculationMode("ConstantRate");
setSkinLossRadiativeFraction(0.6392);
setConstantSkinLossRate(729);
setSkinLossUFactorTimesAreaTerm(0.0);
ok = setSkinLossQuadraticCurve(skinlossCurve);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s skin loss curve to " << skinlossCurve.briefDescription() << ".");
}
setDilutionAirFlowRate(0.006156);
setStackHeatlosstoDilutionAir(2307);
ok = setDilutionInletAirNode(dilutionInletAirNode);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s dilution inlet air node to " << dilutionInletAirNode.briefDescription() << ".");
}
ok = setDilutionOutletAirNode(dilutionOutletAirNode);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s dilution outlet air node to " << dilutionOutletAirNode.briefDescription() << ".");
}
setMinimumOperatingPoint(3010);
setMaximumOperatingPoint(3728);
}
GeneratorFuelCellPowerModule::GeneratorFuelCellPowerModule(const Model& model, const CurveQuadratic& efficiencyCurve,
const ThermalZone& heatlossZone, const Node& dilutionInletAirNode,
const Node& dilutionOutletAirNode)
: ModelObject(GeneratorFuelCellPowerModule::iddObjectType(), model) {
OS_ASSERT(getImpl<detail::GeneratorFuelCellPowerModule_Impl>());
setEfficiencyCurveMode("Annex42");
bool ok = setEfficiencyCurve(efficiencyCurve);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s efficiencyCurve to " << efficiencyCurve.briefDescription() << ".");
}
setNominalEfficiency(1.0);
setNominalElectricalPower(3400);
setNumberofStopsatStartofSimulation(0);
setCyclingPerformanceDegradationCoefficient(0.0);
setNumberofRunHoursatBeginningofSimulation(0);
setAccumulatedRunTimeDegradationCoefficient(0.0);
setRunTimeDegradationInitiationTimeThreshold(10000);
setPowerUpTransientLimit(1.4);
setPowerDownTransientLimit(0.2);
setStartUpTime(0.0);
setStartUpFuel(0.2);
setStartUpElectricityConsumption(0);
setStartUpElectricityProduced(0.0);
setShutDownTime(0.0);
setShutDownFuel(0.2);
setShutDownElectricityConsumption(0);
setAncillaryElectricityConstantTerm(0.0);
setAncillaryElectricityLinearTerm(0.0);
ok = setZone(heatlossZone);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s heat loss zone to " << heatlossZone.briefDescription() << ".");
}
setSkinLossCalculationMode("ConstantRate");
setSkinLossRadiativeFraction(0.6392);
setConstantSkinLossRate(729);
setSkinLossUFactorTimesAreaTerm(0.0);
setDilutionAirFlowRate(0.006156);
setStackHeatlosstoDilutionAir(2307);
ok = setDilutionInletAirNode(dilutionInletAirNode);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s dilution inlet air node to " << dilutionInletAirNode.briefDescription() << ".");
}
ok = setDilutionOutletAirNode(dilutionOutletAirNode);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s dilution outlet air node to " << dilutionOutletAirNode.briefDescription() << ".");
}
setMinimumOperatingPoint(3010);
setMaximumOperatingPoint(3728);
}
GeneratorFuelCellPowerModule::GeneratorFuelCellPowerModule(const Model& model, const CurveQuadratic& efficiencyCurve)
: ModelObject(GeneratorFuelCellPowerModule::iddObjectType(), model) {
OS_ASSERT(getImpl<detail::GeneratorFuelCellPowerModule_Impl>());
setEfficiencyCurveMode("Annex42");
bool ok = setEfficiencyCurve(efficiencyCurve);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s efficiencyCurve to " << efficiencyCurve.briefDescription() << ".");
}
setNominalEfficiency(1.0);
setNominalElectricalPower(3400);
setNumberofStopsatStartofSimulation(0);
setCyclingPerformanceDegradationCoefficient(0.0);
setNumberofRunHoursatBeginningofSimulation(0);
setAccumulatedRunTimeDegradationCoefficient(0.0);
setRunTimeDegradationInitiationTimeThreshold(10000);
setPowerUpTransientLimit(1.4);
setPowerDownTransientLimit(0.2);
setStartUpTime(0.0);
setStartUpFuel(0.2);
setStartUpElectricityConsumption(0);
setStartUpElectricityProduced(0.0);
setShutDownTime(0.0);
setShutDownFuel(0.2);
setShutDownElectricityConsumption(0);
setAncillaryElectricityConstantTerm(0.0);
setAncillaryElectricityLinearTerm(0.0);
//TODO
//setZone();
setSkinLossCalculationMode("ConstantRate");
setSkinLossRadiativeFraction(0.6392);
setConstantSkinLossRate(729);
setSkinLossUFactorTimesAreaTerm(0.0);
setDilutionAirFlowRate(0.006156);
setStackHeatlosstoDilutionAir(2307);
//TODO
//setDilutionInletAirNode();
//setDilutionOutletAirNode();
setMinimumOperatingPoint(3010);
setMaximumOperatingPoint(3728);
}
GeneratorFuelCellPowerModule::GeneratorFuelCellPowerModule(const Model& model) : ModelObject(GeneratorFuelCellPowerModule::iddObjectType(), model) {
OS_ASSERT(getImpl<detail::GeneratorFuelCellPowerModule_Impl>());
setEfficiencyCurveMode("Annex42");
//create default curve
CurveQuadratic curveQuadratic(model);
curveQuadratic.setCoefficient1Constant(0.642388);
curveQuadratic.setCoefficient2x(-0.0001619);
curveQuadratic.setCoefficient3xPOW2(0.0000000226);
curveQuadratic.setMinimumValueofx(0);
curveQuadratic.setMaximumValueofx(10000);
curveQuadratic.setName("Power Module Efficiency Curve");
bool ok = setEfficiencyCurve(curveQuadratic);
if (!ok) {
remove();
LOG_AND_THROW("Unable to set " << briefDescription() << "'s efficiencyCurve to " << curveQuadratic.briefDescription() << ".");
}
setNominalEfficiency(1.0);
setNominalElectricalPower(3400);
setNumberofStopsatStartofSimulation(0);
setCyclingPerformanceDegradationCoefficient(0.0);
setNumberofRunHoursatBeginningofSimulation(0);
setAccumulatedRunTimeDegradationCoefficient(0.0);
setRunTimeDegradationInitiationTimeThreshold(10000);
setPowerUpTransientLimit(1.4);
setPowerDownTransientLimit(0.2);
setStartUpTime(0.0);
setStartUpFuel(0.2);
setStartUpElectricityConsumption(0);
setStartUpElectricityProduced(0.0);
setShutDownTime(0.0);
setShutDownFuel(0.2);
setShutDownElectricityConsumption(0);
setAncillaryElectricityConstantTerm(0.0);
setAncillaryElectricityLinearTerm(0.0);
//TODO
//setZone();
setSkinLossCalculationMode("ConstantRate");
setSkinLossRadiativeFraction(0.6392);
setConstantSkinLossRate(729);
setSkinLossUFactorTimesAreaTerm(0.0);
setDilutionAirFlowRate(0.006156);
setStackHeatlosstoDilutionAir(2307);
//TODO
//setDilutionInletAirNode();
//setDilutionOutletAirNode();
setMinimumOperatingPoint(3010);
setMaximumOperatingPoint(3728);
CurveQuadratic curveQ2(model);
curveQ2.setCoefficient1Constant(0);
curveQ2.setCoefficient2x(0);
curveQ2.setCoefficient3xPOW2(0);
curveQ2.setMinimumValueofx(-1.0e10);
curveQ2.setMaximumValueofx(1.0e10);
curveQ2.setName("Skin Loss Curve");
setSkinLossQuadraticCurve(curveQ2);
}
IddObjectType GeneratorFuelCellPowerModule::iddObjectType() {
return IddObjectType(IddObjectType::OS_Generator_FuelCell_PowerModule);
}
std::vector<std::string> GeneratorFuelCellPowerModule::efficiencyCurveModeValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_Generator_FuelCell_PowerModuleFields::EfficiencyCurveMode);
}
std::vector<std::string> GeneratorFuelCellPowerModule::skinLossCalculationModeValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_Generator_FuelCell_PowerModuleFields::SkinLossCalculationMode);
}
std::string GeneratorFuelCellPowerModule::efficiencyCurveMode() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->efficiencyCurveMode();
}
CurveQuadratic GeneratorFuelCellPowerModule::efficiencyCurve() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->efficiencyCurve();
}
double GeneratorFuelCellPowerModule::nominalEfficiency() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->nominalEfficiency();
}
double GeneratorFuelCellPowerModule::nominalElectricalPower() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->nominalElectricalPower();
}
double GeneratorFuelCellPowerModule::numberofStopsatStartofSimulation() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->numberofStopsatStartofSimulation();
}
double GeneratorFuelCellPowerModule::cyclingPerformanceDegradationCoefficient() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->cyclingPerformanceDegradationCoefficient();
}
double GeneratorFuelCellPowerModule::numberofRunHoursatBeginningofSimulation() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->numberofRunHoursatBeginningofSimulation();
}
double GeneratorFuelCellPowerModule::accumulatedRunTimeDegradationCoefficient() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->accumulatedRunTimeDegradationCoefficient();
}
double GeneratorFuelCellPowerModule::runTimeDegradationInitiationTimeThreshold() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->runTimeDegradationInitiationTimeThreshold();
}
double GeneratorFuelCellPowerModule::powerUpTransientLimit() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->powerUpTransientLimit();
}
double GeneratorFuelCellPowerModule::powerDownTransientLimit() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->powerDownTransientLimit();
}
double GeneratorFuelCellPowerModule::startUpTime() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->startUpTime();
}
double GeneratorFuelCellPowerModule::startUpFuel() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->startUpFuel();
}
double GeneratorFuelCellPowerModule::startUpElectricityConsumption() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->startUpElectricityConsumption();
}
double GeneratorFuelCellPowerModule::startUpElectricityProduced() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->startUpElectricityProduced();
}
double GeneratorFuelCellPowerModule::shutDownTime() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->shutDownTime();
}
double GeneratorFuelCellPowerModule::shutDownFuel() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->shutDownFuel();
}
double GeneratorFuelCellPowerModule::shutDownElectricityConsumption() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->shutDownElectricityConsumption();
}
double GeneratorFuelCellPowerModule::ancillaryElectricityConstantTerm() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->ancillaryElectricityConstantTerm();
}
double GeneratorFuelCellPowerModule::ancillaryElectricityLinearTerm() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->ancillaryElectricityLinearTerm();
}
std::string GeneratorFuelCellPowerModule::skinLossCalculationMode() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->skinLossCalculationMode();
}
boost::optional<ThermalZone> GeneratorFuelCellPowerModule::zone() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->zone();
}
double GeneratorFuelCellPowerModule::skinLossRadiativeFraction() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->skinLossRadiativeFraction();
}
double GeneratorFuelCellPowerModule::constantSkinLossRate() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->constantSkinLossRate();
}
double GeneratorFuelCellPowerModule::skinLossUFactorTimesAreaTerm() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->skinLossUFactorTimesAreaTerm();
}
boost::optional<CurveQuadratic> GeneratorFuelCellPowerModule::skinLossQuadraticCurve() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->skinLossQuadraticCurve();
}
double GeneratorFuelCellPowerModule::dilutionAirFlowRate() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->dilutionAirFlowRate();
}
double GeneratorFuelCellPowerModule::stackHeatlosstoDilutionAir() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->stackHeatlosstoDilutionAir();
}
boost::optional<Node> GeneratorFuelCellPowerModule::dilutionInletAirNode() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->dilutionInletAirNode();
}
boost::optional<Node> GeneratorFuelCellPowerModule::dilutionOutletAirNode() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->dilutionOutletAirNode();
}
double GeneratorFuelCellPowerModule::minimumOperatingPoint() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->minimumOperatingPoint();
}
double GeneratorFuelCellPowerModule::maximumOperatingPoint() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->maximumOperatingPoint();
}
bool GeneratorFuelCellPowerModule::setEfficiencyCurveMode(const std::string& efficiencyCurveMode) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setEfficiencyCurveMode(efficiencyCurveMode);
}
void GeneratorFuelCellPowerModule::resetEfficiencyCurveMode() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetEfficiencyCurveMode();
}
bool GeneratorFuelCellPowerModule::setEfficiencyCurve(const CurveQuadratic& quadraticCurve) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setEfficiencyCurve(quadraticCurve);
}
bool GeneratorFuelCellPowerModule::setNominalEfficiency(double nominalEfficiency) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setNominalEfficiency(nominalEfficiency);
}
void GeneratorFuelCellPowerModule::resetNominalEfficiency() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetNominalEfficiency();
}
bool GeneratorFuelCellPowerModule::setNominalElectricalPower(double nominalElectricalPower) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setNominalElectricalPower(nominalElectricalPower);
}
void GeneratorFuelCellPowerModule::resetNominalElectricalPower() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetNominalElectricalPower();
}
bool GeneratorFuelCellPowerModule::setNumberofStopsatStartofSimulation(double numberofStopsatStartofSimulation) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setNumberofStopsatStartofSimulation(numberofStopsatStartofSimulation);
}
void GeneratorFuelCellPowerModule::resetNumberofStopsatStartofSimulation() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetNumberofStopsatStartofSimulation();
}
bool GeneratorFuelCellPowerModule::setCyclingPerformanceDegradationCoefficient(double cyclingPerformanceDegradationCoefficient) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setCyclingPerformanceDegradationCoefficient(
cyclingPerformanceDegradationCoefficient);
}
void GeneratorFuelCellPowerModule::resetCyclingPerformanceDegradationCoefficient() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetCyclingPerformanceDegradationCoefficient();
}
bool GeneratorFuelCellPowerModule::setNumberofRunHoursatBeginningofSimulation(double numberofRunHoursatBeginningofSimulation) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setNumberofRunHoursatBeginningofSimulation(numberofRunHoursatBeginningofSimulation);
}
void GeneratorFuelCellPowerModule::resetNumberofRunHoursatBeginningofSimulation() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetNumberofRunHoursatBeginningofSimulation();
}
bool GeneratorFuelCellPowerModule::setAccumulatedRunTimeDegradationCoefficient(double accumulatedRunTimeDegradationCoefficient) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setAccumulatedRunTimeDegradationCoefficient(
accumulatedRunTimeDegradationCoefficient);
}
void GeneratorFuelCellPowerModule::resetAccumulatedRunTimeDegradationCoefficient() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetAccumulatedRunTimeDegradationCoefficient();
}
bool GeneratorFuelCellPowerModule::setRunTimeDegradationInitiationTimeThreshold(double runTimeDegradationInitiationTimeThreshold) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setRunTimeDegradationInitiationTimeThreshold(
runTimeDegradationInitiationTimeThreshold);
}
void GeneratorFuelCellPowerModule::resetRunTimeDegradationInitiationTimeThreshold() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetRunTimeDegradationInitiationTimeThreshold();
}
bool GeneratorFuelCellPowerModule::setPowerUpTransientLimit(double powerUpTransientLimit) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setPowerUpTransientLimit(powerUpTransientLimit);
}
void GeneratorFuelCellPowerModule::resetPowerUpTransientLimit() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetPowerUpTransientLimit();
}
bool GeneratorFuelCellPowerModule::setPowerDownTransientLimit(double powerDownTransientLimit) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setPowerDownTransientLimit(powerDownTransientLimit);
}
void GeneratorFuelCellPowerModule::resetPowerDownTransientLimit() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetPowerDownTransientLimit();
}
bool GeneratorFuelCellPowerModule::setStartUpTime(double startUpTime) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setStartUpTime(startUpTime);
}
void GeneratorFuelCellPowerModule::resetStartUpTime() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetStartUpTime();
}
bool GeneratorFuelCellPowerModule::setStartUpFuel(double startUpFuel) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setStartUpFuel(startUpFuel);
}
void GeneratorFuelCellPowerModule::resetStartUpFuel() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetStartUpFuel();
}
bool GeneratorFuelCellPowerModule::setStartUpElectricityConsumption(double startUpElectricityConsumption) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setStartUpElectricityConsumption(startUpElectricityConsumption);
}
void GeneratorFuelCellPowerModule::resetStartUpElectricityConsumption() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetStartUpElectricityConsumption();
}
bool GeneratorFuelCellPowerModule::setStartUpElectricityProduced(double startUpElectricityProduced) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setStartUpElectricityProduced(startUpElectricityProduced);
}
void GeneratorFuelCellPowerModule::resetStartUpElectricityProduced() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetStartUpElectricityProduced();
}
bool GeneratorFuelCellPowerModule::setShutDownTime(double shutDownTime) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setShutDownTime(shutDownTime);
}
void GeneratorFuelCellPowerModule::resetShutDownTime() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetShutDownTime();
}
bool GeneratorFuelCellPowerModule::setShutDownFuel(double shutDownFuel) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setShutDownFuel(shutDownFuel);
}
void GeneratorFuelCellPowerModule::resetShutDownFuel() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetShutDownFuel();
}
bool GeneratorFuelCellPowerModule::setShutDownElectricityConsumption(double shutDownElectricityConsumption) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setShutDownElectricityConsumption(shutDownElectricityConsumption);
}
void GeneratorFuelCellPowerModule::resetShutDownElectricityConsumption() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetShutDownElectricityConsumption();
}
bool GeneratorFuelCellPowerModule::setAncillaryElectricityConstantTerm(double ancillaryElectricityConstantTerm) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setAncillaryElectricityConstantTerm(ancillaryElectricityConstantTerm);
}
void GeneratorFuelCellPowerModule::resetAncillaryElectricityConstantTerm() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetAncillaryElectricityConstantTerm();
}
bool GeneratorFuelCellPowerModule::setAncillaryElectricityLinearTerm(double ancillaryElectricityLinearTerm) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setAncillaryElectricityLinearTerm(ancillaryElectricityLinearTerm);
}
void GeneratorFuelCellPowerModule::resetAncillaryElectricityLinearTerm() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetAncillaryElectricityLinearTerm();
}
bool GeneratorFuelCellPowerModule::setSkinLossCalculationMode(const std::string& skinLossCalculationMode) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setSkinLossCalculationMode(skinLossCalculationMode);
}
void GeneratorFuelCellPowerModule::resetSkinLossCalculationMode() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetSkinLossCalculationMode();
}
bool GeneratorFuelCellPowerModule::setZone(const ThermalZone& zone) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setZone(zone);
}
void GeneratorFuelCellPowerModule::resetZone() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetZone();
}
bool GeneratorFuelCellPowerModule::setSkinLossRadiativeFraction(double skinLossRadiativeFraction) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setSkinLossRadiativeFraction(skinLossRadiativeFraction);
}
void GeneratorFuelCellPowerModule::resetSkinLossRadiativeFraction() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetSkinLossRadiativeFraction();
}
bool GeneratorFuelCellPowerModule::setConstantSkinLossRate(double constantSkinLossRate) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setConstantSkinLossRate(constantSkinLossRate);
}
void GeneratorFuelCellPowerModule::resetConstantSkinLossRate() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetConstantSkinLossRate();
}
bool GeneratorFuelCellPowerModule::setSkinLossUFactorTimesAreaTerm(double skinLossUFactorTimesAreaTerm) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setSkinLossUFactorTimesAreaTerm(skinLossUFactorTimesAreaTerm);
}
void GeneratorFuelCellPowerModule::resetSkinLossUFactorTimesAreaTerm() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetSkinLossUFactorTimesAreaTerm();
}
bool GeneratorFuelCellPowerModule::setSkinLossQuadraticCurve(const CurveQuadratic& quadraticCurves) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setSkinLossQuadraticCurve(quadraticCurves);
}
void GeneratorFuelCellPowerModule::resetSkinLossQuadraticCurve() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetSkinLossQuadraticCurve();
}
bool GeneratorFuelCellPowerModule::setDilutionAirFlowRate(double dilutionAirFlowRate) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setDilutionAirFlowRate(dilutionAirFlowRate);
}
void GeneratorFuelCellPowerModule::resetDilutionAirFlowRate() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetDilutionAirFlowRate();
}
bool GeneratorFuelCellPowerModule::setStackHeatlosstoDilutionAir(double stackHeatlosstoDilutionAir) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setStackHeatlosstoDilutionAir(stackHeatlosstoDilutionAir);
}
void GeneratorFuelCellPowerModule::resetStackHeatlosstoDilutionAir() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetStackHeatlosstoDilutionAir();
}
bool GeneratorFuelCellPowerModule::setDilutionInletAirNode(const Node& node) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setDilutionInletAirNode(node);
}
void GeneratorFuelCellPowerModule::resetDilutionInletAirNode() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetDilutionInletAirNode();
}
bool GeneratorFuelCellPowerModule::setDilutionOutletAirNode(const Node& node) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setDilutionOutletAirNode(node);
}
void GeneratorFuelCellPowerModule::resetDilutionOutletAirNode() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetDilutionOutletAirNode();
}
bool GeneratorFuelCellPowerModule::setMinimumOperatingPoint(double minimumOperatingPoint) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setMinimumOperatingPoint(minimumOperatingPoint);
}
void GeneratorFuelCellPowerModule::resetMinimumOperatingPoint() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetMinimumOperatingPoint();
}
bool GeneratorFuelCellPowerModule::setMaximumOperatingPoint(double maximumOperatingPoint) {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->setMaximumOperatingPoint(maximumOperatingPoint);
}
void GeneratorFuelCellPowerModule::resetMaximumOperatingPoint() {
getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->resetMaximumOperatingPoint();
}
boost::optional<GeneratorFuelCell> GeneratorFuelCellPowerModule::fuelCell() const {
return getImpl<detail::GeneratorFuelCellPowerModule_Impl>()->fuelCell();
}
/// @cond
GeneratorFuelCellPowerModule::GeneratorFuelCellPowerModule(std::shared_ptr<detail::GeneratorFuelCellPowerModule_Impl> impl)
: ModelObject(std::move(impl)) {}
/// @endcond
} // namespace model
} // namespace openstudio
| 21,486 |
746 |
from pyspark.sql import SparkSession
from pyspark.sql.types import *
import random
import string
import shutil
spark = SparkSession.builder.master("local").appName("Spark rdd to table").getOrCreate()
spark.sparkContext.setLogLevel('info')
letters = string.ascii_lowercase
def rand_word():
return ''.join(random.choice(letters) for i in range(random.randint(4, 10)))
def tuple_to_csv(x):
return ','.join([str(i) for i in x])
list_of_things = [(rand_word() + " " + rand_word(), random.randint(1, 100)) for i in range(100)]
rdd = spark.sparkContext.parallelize(list_of_things)
rdd.setName("list of random words and numbers")
csvDir = '/test_data/rdd_to_csv_output/'
try:
shutil.rmtree(csvDir)
except OSError as e:
print("output directory does not exist")
rdd.map(tuple_to_csv).saveAsTextFile(csvDir)
schema = StructType([StructField('name', StringType(), False), StructField('age', IntegerType(), False)])
spark.read.option('header', False).schema(schema)\
.csv(csvDir)\
.registerTempTable("test_people")
spark.sql('SELECT * FROM test_people WHERE age > 20 AND age < 65')\
.write\
.mode('overwrite')\
.parquet('/test_data/rdd_to_table/')
| 422 |
303 |
from django.conf.urls import patterns, url
from .views import CeleryHealthCheckView
urlpatterns = patterns('',
url(r"^celery/healthcheck.html",
CeleryHealthCheckView, name="celery-healthcheck"),
)
| 133 |
640 |
/*
Based on the SG C Tools 1.7
(C) 1993 <NAME>
$Id: restorevdc.c,v 1.1 2008-06-23 17:34:34 stefano Exp $
*/
#include <c128/vdc.h>
/* save and restore key vdc registers */
extern uchar vdcRegsToSave[];
extern uchar vdcRegs[];
void restorevdc(void)
{
uchar I;
// for(I = 0; I < sizeof(vdcRegs); I++) /* restore vdc regs saved with savevdc() */
for(I = 0; I < 36; I++) /* restore vdc regs saved with savevdc() */
outvdc(vdcRegsToSave[I],vdcRegs[I]);
}
| 209 |
311 |
<gh_stars>100-1000
/**
* Copyright 2019 The JoyQueue 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
*
* 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.joyqueue.nsr.sql.converter;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.joyqueue.domain.Broker;
import org.joyqueue.nsr.sql.domain.BrokerDTO;
import java.util.Collections;
import java.util.List;
/**
* BrokerConverter
* author: gaohaoxiang
* date: 2019/8/16
*/
public class BrokerConverter {
public static BrokerDTO convert(Broker broker) {
if (broker == null) {
return null;
}
BrokerDTO brokerDTO = new BrokerDTO();
brokerDTO.setId(Long.valueOf(broker.getId()));
brokerDTO.setIp(broker.getIp());
brokerDTO.setPort(broker.getPort());
brokerDTO.setDataCenter(broker.getDataCenter());
brokerDTO.setRetryType(broker.getRetryType());
brokerDTO.setPermission(broker.getPermission().getName());
return brokerDTO;
}
public static Broker convert(BrokerDTO brokerDTO) {
if (brokerDTO == null) {
return null;
}
Broker broker = new Broker();
broker.setId(Integer.valueOf(String.valueOf(brokerDTO.getId())));
broker.setIp(brokerDTO.getIp());
broker.setPort(brokerDTO.getPort());
broker.setDataCenter(brokerDTO.getDataCenter());
broker.setRetryType(brokerDTO.getRetryType());
broker.setPermission(Broker.PermissionEnum.value(brokerDTO.getPermission()));
return broker;
}
public static List<Broker> convert(List<BrokerDTO> brokerDTOList) {
if (CollectionUtils.isEmpty(brokerDTOList)) {
return Collections.emptyList();
}
List<Broker> result = Lists.newArrayListWithCapacity(brokerDTOList.size());
for (BrokerDTO brokerDTO : brokerDTOList) {
result.add(convert(brokerDTO));
}
return result;
}
}
| 975 |
1,346 |
<filename>dal-dao-gen/src/main/java/com/ctrip/platform/dal/daogen/generator/java/JavaDalGenerator.java
package com.ctrip.platform.dal.daogen.generator.java;
import com.ctrip.platform.dal.daogen.CodeGenContext;
import com.ctrip.platform.dal.daogen.DalGenerator;
import com.ctrip.platform.dal.daogen.entity.Progress;
import com.ctrip.platform.dal.daogen.entity.Project;
import com.ctrip.platform.dal.daogen.generator.processor.java.*;
import com.ctrip.platform.dal.daogen.host.DalConfigHost;
import com.ctrip.platform.dal.daogen.log.LoggerManager;
import com.ctrip.platform.dal.daogen.utils.BeanGetter;
import java.util.ArrayList;
import java.util.List;
public class JavaDalGenerator implements DalGenerator {
@Override
public CodeGenContext createContext(int projectId, boolean regenerate, Progress progress, boolean newPojo,
boolean ignoreApproveStatus) throws Exception {
JavaCodeGenContext ctx = null;
try {
ctx = new JavaCodeGenContext(projectId, regenerate, progress);
Project project = BeanGetter.getDaoOfProject().getProjectByID(projectId);
DalConfigHost dalConfigHost = null;
if (project.getDal_config_name() != null && !project.getDal_config_name().isEmpty()) {
dalConfigHost = new DalConfigHost(project.getDal_config_name());
} else if (project.getNamespace() != null && !project.getNamespace().isEmpty()) {
dalConfigHost = new DalConfigHost(project.getNamespace());
} else {
dalConfigHost = new DalConfigHost("");
}
ctx.setDalConfigHost(dalConfigHost);
ctx.setNamespace(project.getNamespace());
} catch (Exception e) {
LoggerManager.getInstance().error(e);
throw e;
}
return ctx;
}
@Override
public void prepareDirectory(CodeGenContext context) throws Exception {
try {
JavaCodeGenContext ctx = (JavaCodeGenContext) context;
LoggerManager.getInstance()
.info(String.format("Begin to prepare java directory for project %s", ctx.getProjectId()));
new JavaDirectoryPreparerProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Prepare java directory for project %s completed.", ctx.getProjectId()));
} catch (Exception e) {
LoggerManager.getInstance().error(e);
throw e;
}
}
@Override
public void prepareData(CodeGenContext context) throws Exception {
List<String> exceptions = new ArrayList<>();
JavaCodeGenContext ctx = (JavaCodeGenContext) context;
try {
LoggerManager.getInstance()
.info(String.format("Begin to prepare java table data for project %s", ctx.getProjectId()));
new JavaDataPreparerOfTableViewSpProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Prepare java table data for project %s completed.", ctx.getProjectId()));
} catch (Exception e) {
LoggerManager.getInstance().error(e);
exceptions.add(e.getMessage());
}
try {
LoggerManager.getInstance()
.info(String.format("Begin to prepare java sqlbuilder data for project %s", ctx.getProjectId()));
new JavaDataPreparerOfSqlBuilderProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Prepare java sqlbuilder data for project %s completed.", ctx.getProjectId()));
} catch (Throwable e) {
LoggerManager.getInstance().error(e);
exceptions.add(e.getMessage());
}
try {
LoggerManager.getInstance()
.info(String.format("Begin to prepare java freesql data for project %s", ctx.getProjectId()));
new JavaDataPreparerOfFreeSqlProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Prepare java freesql data for project %s completed.", ctx.getProjectId()));
} catch (Throwable e) {
LoggerManager.getInstance().error(e);
exceptions.add(e.getMessage());
}
if (exceptions.size() > 0) {
StringBuilder sb = new StringBuilder();
for (String exception : exceptions) {
sb.append(exception);
}
throw new RuntimeException(sb.toString());
}
}
@Override
public void generateCode(CodeGenContext context) throws Exception {
JavaCodeGenContext ctx = (JavaCodeGenContext) context;
try {
LoggerManager.getInstance()
.info(String.format("Begin to generate java table code for project %s", ctx.getProjectId()));
new JavaCodeGeneratorOfTableProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Generate java table code for project %s completed.", ctx.getProjectId()));
LoggerManager.getInstance()
.info(String.format("Begin to generate java view code for project %s", ctx.getProjectId()));
new JavaCodeGeneratorOfViewProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Generate java view code for project %s completed.", ctx.getProjectId()));
LoggerManager.getInstance()
.info(String.format("Begin to generate java sp code for project %s", ctx.getProjectId()));
new JavaCodeGeneratorOfSpProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Generate java sp code for project %s completed.", ctx.getProjectId()));
LoggerManager.getInstance()
.info(String.format("Begin to generate java freesql code for project %s", ctx.getProjectId()));
new JavaCodeGeneratorOfFreeSqlProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Generate java freesql code for project %s completed.", ctx.getProjectId()));
LoggerManager.getInstance()
.info(String.format("Begin to generate java other code for project %s", ctx.getProjectId()));
new JavaCodeGeneratorOfOthersProcessor().process(ctx);
LoggerManager.getInstance()
.info(String.format("Generate java other code for project %s completed.", ctx.getProjectId()));
} catch (Exception e) {
LoggerManager.getInstance().error(e);
throw e;
}
}
}
| 2,850 |
640 |
class Candlestick:
def __init__(self):
self.startTime = 0
self.closeTime = 0
self.symbol = ""
self.interval = ""
self.firstTradeId = 0
self.lastTradeId = 0
self.open = 0.0
self.close = 0.0
self.high = 0.0
self.low = 0.0
self.volume = 0.0
self.numTrades = 0
self.isClosed = False
self.baseVolume = 0.0
self.takerBuyQuoteAssetVolume = 0.0
self.takerBuyBaseAssetVolume = 0.0
self.ignore = 0.0
@staticmethod
def json_parse(json_data):
data_obj = Candlestick()
data_obj.startTime = json_data.get_int("t")
data_obj.closeTime = json_data.get_int("T")
data_obj.symbol = json_data.get_string("s")
data_obj.interval = json_data.get_string("i")
data_obj.firstTradeId = json_data.get_int("f")
data_obj.lastTradeId = json_data.get_int("L")
data_obj.open = json_data.get_float("o")
data_obj.close = json_data.get_float("c")
data_obj.high = json_data.get_float("h")
data_obj.low = json_data.get_float("l")
data_obj.volume = json_data.get_float("v")
data_obj.numTrades = json_data.get_int("n")
data_obj.isClosed = json_data.get_boolean("x")
data_obj.baseVolume = json_data.get_float("q")
data_obj.takerBuyQuoteAssetVolume = json_data.get_float("V")
data_obj.takerBuyBaseAssetVolume = json_data.get_float("Q")
data_obj.ignore = json_data.get_int("B")
return data_obj
class CandlestickEvent:
def __init__(self):
self.eventType = ""
self.eventTime = 0
self.symbol = ""
self.data = Candlestick()
@staticmethod
def json_parse(json_wrapper):
candlestick_event = CandlestickEvent()
candlestick_event.eventType = json_wrapper.get_string("e")
candlestick_event.eventTime = json_wrapper.get_int("E")
candlestick_event.symbol = json_wrapper.get_string("s")
data = Candlestick.json_parse(json_wrapper.get_object("k"))
candlestick_event.data = data
return candlestick_event
| 1,083 |
348 |
{"nom":"Harare","dpt":"Français établis hors de France","inscrits":150,"abs":81,"votants":69,"blancs":2,"nuls":2,"exp":65,"res":[{"panneau":"1","voix":59},{"panneau":"2","voix":6}]}
| 73 |
1,025 |
<filename>CodeXL/Components/GpuDebugging/AMDTGpuDebuggingComponents/Include/commands/gdStartDebuggingCommand.h
//==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file gdStartDebuggingCommand.h
///
//==================================================================================
//------------------------------ gdStartDebuggingCommand.h ------------------------------
#ifndef __GDSTARTDEBUGGINGCOMMAND
#define __GDSTARTDEBUGGINGCOMMAND
// Infra:
#include <AMDTAPIClasses/Include/apDebugProjectSettings.h>
// AMDTApplicationFramework:
#include <AMDTApplicationFramework/Include/afCommand.h>
// ----------------------------------------------------------------------------------
// Class Name: gdStartDebuggingCommand : public afCommand
// General Description:
// Launches the debugged application.
//
// Author: <NAME>
// Creation Date: 1/11/2003
// ----------------------------------------------------------------------------------
class GD_API gdStartDebuggingCommand : public afCommand
{
public:
gdStartDebuggingCommand(const apDebugProjectSettings& processCreationData);
virtual ~gdStartDebuggingCommand();
// Overrides afCommand:
virtual bool canExecuteSpecificCommand();
virtual bool executeSpecificCommand();
private:
bool isHostMachineConfigurationSupported() const;
bool adjustSpiesDirectoryToBinaryType();
bool isExecutableTypeSupported(const osFilePath& exePath);
bool checkRequiredSystemLibraries() const;
bool setKernelSourceFilePaths();
/// Check if the debug settings are valid:
bool AreDebugSettingsValid(bool& exeFileExist, bool& workingFolderExist, bool& logDirExistAndAccessible, bool& arePortsLegal, bool& arePortsDistinct, bool& requiredSystemLibrariesExists);
/// Handles start debugging in case of invalid settings:
void HandleInvalidSettings(bool exeFileExist, bool workingFolderExist, bool logDirExistAndAccessible, bool arePortsLegal, bool arePortsDistinct,
bool requiredSystemLibrariesExists, bool& failedOnGlobalOption);
// Start debugging command:
bool StartDebugging();
private:
// The debugged process creation data:
apDebugProjectSettings _processCreationData;
};
#endif // __GDSTARTDEBUGGINGCOMMAND
| 685 |
14,668 |
<filename>content/browser/attribution_reporting/attribution_storage_sql_unittest.cc<gh_stars>1000+
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/attribution_reporting/attribution_storage_sql.h"
#include <functional>
#include <memory>
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/simple_test_clock.h"
#include "base/time/time.h"
#include "content/browser/attribution_reporting/attribution_report.h"
#include "content/browser/attribution_reporting/attribution_test_utils.h"
#include "content/browser/attribution_reporting/storable_source.h"
#include "content/browser/attribution_reporting/storable_trigger.h"
#include "sql/database.h"
#include "sql/meta_table.h"
#include "sql/test/scoped_error_expecter.h"
#include "sql/test/test_helpers.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
namespace {
using CreateReportStatus =
::content::AttributionStorage::CreateReportResult::Status;
using ::testing::ElementsAre;
using ::testing::IsEmpty;
using ::testing::Property;
using ::testing::SizeIs;
class AttributionStorageSqlTest : public testing::Test {
public:
AttributionStorageSqlTest() = default;
void SetUp() override { ASSERT_TRUE(temp_directory_.CreateUniqueTempDir()); }
void OpenDatabase() {
storage_.reset();
auto delegate = std::make_unique<ConfigurableStorageDelegate>();
delegate_ = delegate.get();
storage_ = std::make_unique<AttributionStorageSql>(
temp_directory_.GetPath(), std::move(delegate), &clock_);
}
void CloseDatabase() { storage_.reset(); }
void AddReportToStorage() {
storage_->StoreSource(SourceBuilder(clock()->Now()).Build());
storage_->MaybeCreateAndStoreReport(DefaultTrigger());
}
void ExpectAllTablesEmpty() {
sql::Database raw_db;
EXPECT_TRUE(raw_db.Open(db_path()));
static constexpr const char* kTables[] = {
"conversions",
"impressions",
"rate_limits",
"dedup_keys",
};
for (const char* table : kTables) {
size_t rows;
sql::test::CountTableRows(&raw_db, table, &rows);
EXPECT_EQ(0u, rows) << table;
}
}
base::FilePath db_path() {
return temp_directory_.GetPath().Append(FILE_PATH_LITERAL("Conversions"));
}
base::SimpleTestClock* clock() { return &clock_; }
AttributionStorage* storage() { return storage_.get(); }
ConfigurableStorageDelegate* delegate() { return delegate_; }
void ExpectImpressionRows(size_t expected) {
sql::Database raw_db;
EXPECT_TRUE(raw_db.Open(db_path()));
size_t rows;
sql::test::CountTableRows(&raw_db, "impressions", &rows);
EXPECT_EQ(expected, rows);
}
CreateReportStatus MaybeCreateAndStoreReport(
const StorableTrigger& conversion) {
return storage_->MaybeCreateAndStoreReport(conversion).status();
}
protected:
base::ScopedTempDir temp_directory_;
private:
std::unique_ptr<AttributionStorage> storage_;
raw_ptr<ConfigurableStorageDelegate> delegate_ = nullptr;
base::SimpleTestClock clock_;
};
} // namespace
TEST_F(AttributionStorageSqlTest,
DatabaseInitialized_TablesAndIndexesLazilyInitialized) {
base::HistogramTester histograms;
OpenDatabase();
CloseDatabase();
// An unused AttributionStorageSql instance should not create the database.
EXPECT_FALSE(base::PathExists(db_path()));
// Operations which don't need to run on an empty database should not create
// the database.
OpenDatabase();
EXPECT_THAT(storage()->GetAttributionsToReport(clock()->Now()), IsEmpty());
CloseDatabase();
EXPECT_FALSE(base::PathExists(db_path()));
// DB init UMA should not be recorded.
histograms.ExpectTotalCount("Conversions.Storage.CreationTime", 0);
histograms.ExpectTotalCount("Conversions.Storage.MigrationTime", 0);
// Storing an impression should create and initialize the database.
OpenDatabase();
storage()->StoreSource(SourceBuilder(clock()->Now()).Build());
CloseDatabase();
// DB creation histograms should be recorded.
histograms.ExpectTotalCount("Conversions.Storage.CreationTime", 1);
histograms.ExpectTotalCount("Conversions.Storage.MigrationTime", 0);
{
sql::Database raw_db;
EXPECT_TRUE(raw_db.Open(db_path()));
// [impressions], [conversions], [meta], [rate_limits], [dedup_keys],
// [sqlite_sequence] (for AUTOINCREMENT support).
EXPECT_EQ(6u, sql::test::CountSQLTables(&raw_db));
// [conversion_domain_idx], [impression_expiry_idx],
// [impression_origin_idx], [impression_site_idx],
// [conversion_report_time_idx], [conversion_impression_id_idx],
// [rate_limit_origin_type_idx], [rate_limit_conversion_time_idx],
// [rate_limit_impression_id_idx] and the meta table index.
EXPECT_EQ(10u, sql::test::CountSQLIndices(&raw_db));
}
}
TEST_F(AttributionStorageSqlTest, DatabaseReopened_DataPersisted) {
OpenDatabase();
AddReportToStorage();
EXPECT_THAT(storage()->GetAttributionsToReport(clock()->Now()), SizeIs(1));
CloseDatabase();
OpenDatabase();
EXPECT_THAT(storage()->GetAttributionsToReport(clock()->Now()), SizeIs(1));
}
TEST_F(AttributionStorageSqlTest, CorruptDatabase_RecoveredOnOpen) {
OpenDatabase();
AddReportToStorage();
EXPECT_THAT(storage()->GetAttributionsToReport(clock()->Now()), SizeIs(1));
CloseDatabase();
// Corrupt the database.
EXPECT_TRUE(sql::test::CorruptSizeInHeader(db_path()));
sql::test::ScopedErrorExpecter expecter;
expecter.ExpectError(SQLITE_CORRUPT);
// Open that database and ensure that it does not fail.
EXPECT_NO_FATAL_FAILURE(OpenDatabase());
// Data should be recovered.
EXPECT_THAT(storage()->GetAttributionsToReport(clock()->Now()), SizeIs(1));
EXPECT_TRUE(expecter.SawExpectedErrors());
}
TEST_F(AttributionStorageSqlTest, VersionTooNew_RazesDB) {
OpenDatabase();
AddReportToStorage();
ASSERT_THAT(storage()->GetAttributionsToReport(clock()->Now()), SizeIs(1));
CloseDatabase();
{
sql::Database raw_db;
EXPECT_TRUE(raw_db.Open(db_path()));
sql::MetaTable meta;
// The values here are irrelevant, as the meta table already exists.
ASSERT_TRUE(meta.Init(&raw_db, /*version=*/1, /*compatible_version=*/1));
meta.SetVersionNumber(meta.GetVersionNumber() + 1);
meta.SetCompatibleVersionNumber(meta.GetCompatibleVersionNumber() + 1);
}
// The DB should be razed because the version is too new.
ASSERT_NO_FATAL_FAILURE(OpenDatabase());
ASSERT_THAT(storage()->GetAttributionsToReport(clock()->Now()), IsEmpty());
}
// Create an impression with two conversions (C1 and C2). Craft a query that
// will target C2, which will in turn delete the impression. We should ensure
// that C1 is properly deleted (conversions should not be stored unattributed).
TEST_F(AttributionStorageSqlTest, ClearDataWithVestigialConversion) {
base::HistogramTester histograms;
OpenDatabase();
base::Time start = clock()->Now();
auto impression = SourceBuilder(start).SetExpiry(base::Days(30)).Build();
storage()->StoreSource(impression);
clock()->Advance(base::Days(1));
EXPECT_EQ(CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(DefaultTrigger()));
clock()->Advance(base::Days(1));
EXPECT_EQ(CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(DefaultTrigger()));
// Use a time range that only intersects the last conversion.
storage()->ClearData(clock()->Now(), clock()->Now(),
base::BindRepeating(std::equal_to<url::Origin>(),
impression.impression_origin()));
EXPECT_THAT(storage()->GetAttributionsToReport(base::Time::Max()), IsEmpty());
CloseDatabase();
// Verify that everything is deleted.
ExpectAllTablesEmpty();
histograms.ExpectUniqueSample(
"Conversions.ImpressionsDeletedInDataClearOperation", 1, 1);
histograms.ExpectUniqueSample(
"Conversions.ReportsDeletedInDataClearOperation", 2, 1);
}
// Same as the above test, but with a null filter.
TEST_F(AttributionStorageSqlTest, ClearAllDataWithVestigialConversion) {
base::HistogramTester histograms;
OpenDatabase();
base::Time start = clock()->Now();
auto impression = SourceBuilder(start).SetExpiry(base::Days(30)).Build();
storage()->StoreSource(impression);
clock()->Advance(base::Days(1));
EXPECT_EQ(CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(DefaultTrigger()));
clock()->Advance(base::Days(1));
EXPECT_EQ(CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(DefaultTrigger()));
// Use a time range that only intersects the last conversion.
auto null_filter = base::RepeatingCallback<bool(const url::Origin&)>();
storage()->ClearData(clock()->Now(), clock()->Now(), null_filter);
EXPECT_THAT(storage()->GetAttributionsToReport(base::Time::Max()), IsEmpty());
CloseDatabase();
// Verify that everything is deleted.
ExpectAllTablesEmpty();
histograms.ExpectUniqueSample(
"Conversions.ImpressionsDeletedInDataClearOperation", 1, 1);
histograms.ExpectUniqueSample(
"Conversions.ReportsDeletedInDataClearOperation", 2, 1);
}
// The max time range with a null filter should delete everything.
TEST_F(AttributionStorageSqlTest, DeleteEverything) {
base::HistogramTester histograms;
OpenDatabase();
base::Time start = clock()->Now();
for (int i = 0; i < 10; i++) {
auto impression = SourceBuilder(start).SetExpiry(base::Days(30)).Build();
storage()->StoreSource(impression);
clock()->Advance(base::Days(1));
}
EXPECT_EQ(CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(DefaultTrigger()));
clock()->Advance(base::Days(1));
EXPECT_EQ(CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(DefaultTrigger()));
auto null_filter = base::RepeatingCallback<bool(const url::Origin&)>();
storage()->ClearData(base::Time::Min(), base::Time::Max(), null_filter);
EXPECT_THAT(storage()->GetAttributionsToReport(base::Time::Max()), IsEmpty());
CloseDatabase();
// Verify that everything is deleted.
ExpectAllTablesEmpty();
histograms.ExpectUniqueSample(
"Conversions.ImpressionsDeletedInDataClearOperation", 1, 1);
histograms.ExpectUniqueSample(
"Conversions.ReportsDeletedInDataClearOperation", 2, 1);
}
TEST_F(AttributionStorageSqlTest, MaxSourcesPerOrigin) {
OpenDatabase();
delegate()->set_max_sources_per_origin(2);
storage()->StoreSource(SourceBuilder(clock()->Now()).Build());
storage()->StoreSource(SourceBuilder(clock()->Now()).Build());
storage()->StoreSource(SourceBuilder(clock()->Now()).Build());
EXPECT_EQ(CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(DefaultTrigger()));
CloseDatabase();
sql::Database raw_db;
EXPECT_TRUE(raw_db.Open(db_path()));
size_t impression_rows;
sql::test::CountTableRows(&raw_db, "impressions", &impression_rows);
EXPECT_EQ(1u, impression_rows);
size_t rate_limit_rows;
sql::test::CountTableRows(&raw_db, "rate_limits", &rate_limit_rows);
EXPECT_EQ(1u, rate_limit_rows);
}
TEST_F(AttributionStorageSqlTest, MaxAttributionsPerOrigin) {
OpenDatabase();
delegate()->set_max_attributions_per_origin(2);
storage()->StoreSource(SourceBuilder(clock()->Now()).Build());
EXPECT_EQ(CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(DefaultTrigger()));
EXPECT_EQ(CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(DefaultTrigger()));
EXPECT_EQ(CreateReportStatus::kNoCapacityForConversionDestination,
MaybeCreateAndStoreReport(DefaultTrigger()));
CloseDatabase();
sql::Database raw_db;
EXPECT_TRUE(raw_db.Open(db_path()));
size_t conversion_rows;
sql::test::CountTableRows(&raw_db, "conversions", &conversion_rows);
EXPECT_EQ(2u, conversion_rows);
size_t rate_limit_rows;
sql::test::CountTableRows(&raw_db, "rate_limits", &rate_limit_rows);
EXPECT_EQ(2u, rate_limit_rows);
}
TEST_F(AttributionStorageSqlTest,
DeleteRateLimitRowsForSubdomainImpressionOrigin) {
OpenDatabase();
delegate()->set_max_attributions_per_source(1);
delegate()->set_rate_limits({
.time_window = base::Days(7),
.max_contributions_per_window = INT_MAX,
});
const url::Origin impression_origin =
url::Origin::Create(GURL("https://sub.impression.example/"));
const url::Origin reporting_origin =
url::Origin::Create(GURL("https://a.example/"));
const url::Origin conversion_origin =
url::Origin::Create(GURL("https://b.example/"));
storage()->StoreSource(SourceBuilder(clock()->Now())
.SetExpiry(base::Days(30))
.SetImpressionOrigin(impression_origin)
.SetReportingOrigin(reporting_origin)
.SetConversionOrigin(conversion_origin)
.Build());
clock()->Advance(base::Days(1));
EXPECT_EQ(
CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(
TriggerBuilder()
.SetConversionDestination(net::SchemefulSite(conversion_origin))
.SetReportingOrigin(reporting_origin)
.Build()));
EXPECT_THAT(storage()->GetActiveSources(), SizeIs(1));
// Force the impression to be deactivated by ensuring that the next report is
// in a different window.
delegate()->set_report_time_ms(1);
EXPECT_EQ(
CreateReportStatus::kPriorityTooLow,
MaybeCreateAndStoreReport(
TriggerBuilder()
.SetConversionDestination(net::SchemefulSite(conversion_origin))
.SetReportingOrigin(reporting_origin)
.Build()));
EXPECT_THAT(storage()->GetActiveSources(), IsEmpty());
clock()->Advance(base::Days(1));
EXPECT_TRUE(storage()->DeleteReport(AttributionReport::Id(1)));
storage()->ClearData(
base::Time::Min(), base::Time::Max(),
base::BindRepeating(std::equal_to<url::Origin>(), impression_origin));
CloseDatabase();
sql::Database raw_db;
EXPECT_TRUE(raw_db.Open(db_path()));
size_t conversion_rows;
sql::test::CountTableRows(&raw_db, "conversions", &conversion_rows);
EXPECT_EQ(0u, conversion_rows);
size_t rate_limit_rows;
sql::test::CountTableRows(&raw_db, "rate_limits", &rate_limit_rows);
EXPECT_EQ(0u, rate_limit_rows);
}
TEST_F(AttributionStorageSqlTest,
DeleteRateLimitRowsForSubdomainConversionOrigin) {
OpenDatabase();
delegate()->set_max_attributions_per_source(1);
delegate()->set_rate_limits({
.time_window = base::Days(7),
.max_contributions_per_window = INT_MAX,
});
const url::Origin impression_origin =
url::Origin::Create(GURL("https://b.example/"));
const url::Origin reporting_origin =
url::Origin::Create(GURL("https://a.example/"));
const url::Origin conversion_origin =
url::Origin::Create(GURL("https://sub.impression.example/"));
storage()->StoreSource(SourceBuilder(clock()->Now())
.SetExpiry(base::Days(30))
.SetImpressionOrigin(impression_origin)
.SetReportingOrigin(reporting_origin)
.SetConversionOrigin(conversion_origin)
.Build());
clock()->Advance(base::Days(1));
EXPECT_EQ(
CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(
TriggerBuilder()
.SetConversionDestination(net::SchemefulSite(conversion_origin))
.SetReportingOrigin(reporting_origin)
.Build()));
EXPECT_THAT(storage()->GetActiveSources(), SizeIs(1));
// Force the impression to be deactivated by ensuring that the next report is
// in a different window.
delegate()->set_report_time_ms(1);
EXPECT_EQ(
CreateReportStatus::kPriorityTooLow,
MaybeCreateAndStoreReport(
TriggerBuilder()
.SetConversionDestination(net::SchemefulSite(conversion_origin))
.SetReportingOrigin(reporting_origin)
.Build()));
EXPECT_THAT(storage()->GetActiveSources(), IsEmpty());
clock()->Advance(base::Days(1));
EXPECT_TRUE(storage()->DeleteReport(AttributionReport::Id(1)));
storage()->ClearData(
base::Time::Min(), base::Time::Max(),
base::BindRepeating(std::equal_to<url::Origin>(), conversion_origin));
CloseDatabase();
sql::Database raw_db;
EXPECT_TRUE(raw_db.Open(db_path()));
size_t conversion_rows;
sql::test::CountTableRows(&raw_db, "conversions", &conversion_rows);
EXPECT_EQ(0u, conversion_rows);
size_t rate_limit_rows;
sql::test::CountTableRows(&raw_db, "rate_limits", &rate_limit_rows);
EXPECT_EQ(0u, rate_limit_rows);
}
TEST_F(AttributionStorageSqlTest, CantOpenDb_FailsSilentlyInRelease) {
base::CreateDirectoryAndGetError(db_path(), nullptr);
auto sql_storage = std::make_unique<AttributionStorageSql>(
temp_directory_.GetPath(),
std::make_unique<ConfigurableStorageDelegate>(), clock());
sql_storage->set_ignore_errors_for_testing(true);
std::unique_ptr<AttributionStorage> storage = std::move(sql_storage);
// These calls should be no-ops.
storage->StoreSource(SourceBuilder(clock()->Now()).Build());
EXPECT_EQ(CreateReportStatus::kNoMatchingImpressions,
storage->MaybeCreateAndStoreReport(DefaultTrigger()).status());
}
TEST_F(AttributionStorageSqlTest, DatabaseDirDoesExist_CreateDirAndOpenDB) {
// Give the storage layer a database directory that doesn't exist.
std::unique_ptr<AttributionStorage> storage =
std::make_unique<AttributionStorageSql>(
temp_directory_.GetPath().Append(
FILE_PATH_LITERAL("ConversionFolder/")),
std::make_unique<ConfigurableStorageDelegate>(), clock());
// The directory should be created, and the database opened.
storage->StoreSource(SourceBuilder(clock()->Now()).Build());
EXPECT_EQ(CreateReportStatus::kSuccess,
storage->MaybeCreateAndStoreReport(DefaultTrigger()).status());
}
TEST_F(AttributionStorageSqlTest, DBinitializationSucceeds_HistogramRecorded) {
base::HistogramTester histograms;
OpenDatabase();
storage()->StoreSource(SourceBuilder(clock()->Now()).Build());
CloseDatabase();
histograms.ExpectUniqueSample("Conversions.Storage.Sql.InitStatus2",
AttributionStorageSql::InitStatus::kSuccess, 1);
}
TEST_F(AttributionStorageSqlTest, MaxUint64StorageSucceeds) {
constexpr uint64_t kMaxUint64 = std::numeric_limits<uint64_t>::max();
OpenDatabase();
// Ensure that reading and writing `uint64_t` fields via
// `sql::Statement::ColumnInt64()` and `sql::Statement::BindInt64()` works
// with the maximum value.
const auto impression =
SourceBuilder(clock()->Now()).SetSourceEventId(kMaxUint64).Build();
storage()->StoreSource(impression);
EXPECT_THAT(storage()->GetActiveSources(), ElementsAre(impression));
EXPECT_EQ(
CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(
TriggerBuilder()
.SetTriggerData(kMaxUint64)
.SetConversionDestination(impression.ConversionDestination())
.SetReportingOrigin(impression.reporting_origin())
.Build()));
EXPECT_THAT(
storage()->GetAttributionsToReport(clock()->Now()),
ElementsAre(Property(&AttributionReport::trigger_data, kMaxUint64)));
}
TEST_F(AttributionStorageSqlTest, ImpressionNotExpired_NotDeleted) {
OpenDatabase();
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(3)).Build());
// Store another impression to trigger the expiry logic.
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(3)).Build());
CloseDatabase();
ExpectImpressionRows(2u);
}
TEST_F(AttributionStorageSqlTest, ImpressionExpired_Deleted) {
OpenDatabase();
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(3)).Build());
clock()->Advance(base::Milliseconds(3));
// Store another impression to trigger the expiry logic.
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(3)).Build());
CloseDatabase();
ExpectImpressionRows(1u);
}
TEST_F(AttributionStorageSqlTest, ImpressionExpired_TooFrequent_NotDeleted) {
OpenDatabase();
delegate()->set_delete_expired_sources_frequency(base::Milliseconds(4));
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(3)).Build());
clock()->Advance(base::Milliseconds(3));
// Store another impression to trigger the expiry logic.
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(3)).Build());
CloseDatabase();
ExpectImpressionRows(2u);
}
TEST_F(AttributionStorageSqlTest,
ExpiredImpressionWithPendingConversion_NotDeleted) {
OpenDatabase();
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(3)).Build());
EXPECT_EQ(CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(DefaultTrigger()));
clock()->Advance(base::Milliseconds(3));
// Store another impression to trigger the expiry logic.
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(3)).Build());
CloseDatabase();
ExpectImpressionRows(2u);
}
TEST_F(AttributionStorageSqlTest, TwoImpressionsOneExpired_OneDeleted) {
OpenDatabase();
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(3)).Build());
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(4)).Build());
clock()->Advance(base::Milliseconds(3));
// Store another impression to trigger the expiry logic.
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(3)).Build());
CloseDatabase();
ExpectImpressionRows(2u);
}
TEST_F(AttributionStorageSqlTest, ExpiredImpressionWithSentConversion_Deleted) {
OpenDatabase();
const int kReportTime = 5;
delegate()->set_report_time_ms(kReportTime);
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(3)).Build());
EXPECT_EQ(CreateReportStatus::kSuccess,
MaybeCreateAndStoreReport(DefaultTrigger()));
clock()->Advance(base::Milliseconds(3));
// Advance past the default report time.
clock()->Advance(base::Milliseconds(kReportTime));
std::vector<AttributionReport> reports =
storage()->GetAttributionsToReport(clock()->Now());
EXPECT_THAT(reports, SizeIs(1));
EXPECT_TRUE(storage()->DeleteReport(*reports[0].report_id()));
// Store another impression to trigger the expiry logic.
storage()->StoreSource(
SourceBuilder(clock()->Now()).SetExpiry(base::Milliseconds(3)).Build());
CloseDatabase();
ExpectImpressionRows(1u);
}
} // namespace content
| 8,301 |
2,206 |
/*
*
* Copyright (c) 2006-2020, Speedment, 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.speedment.common.codegenxml.internal.view;
import com.speedment.common.codegen.Generator;
import com.speedment.common.codegen.Transform;
import com.speedment.common.codegenxml.TagElement;
import com.speedment.common.codegenxml.internal.view.trait.HasAttributesView;
import com.speedment.common.codegenxml.internal.view.trait.HasElementsView;
import com.speedment.common.codegenxml.internal.view.trait.HasNameView;
import java.util.Optional;
/**
*
* @author <NAME>
*/
public class TagElementView implements Transform<TagElement, String>,
HasNameView<TagElement>,
HasElementsView<TagElement>,
HasAttributesView<TagElement> {
@Override
public Optional<String> transform(Generator gen, TagElement model) {
return Optional.of("<" +
transformName(model) +
transformAttributes(gen, model) +
(model.elements().isEmpty() ? '/' : "") +
'>' +
transformElements(gen, model) +
(model.elements().isEmpty() ? "" : new StringBuilder()
.append("</")
.append(transformName(model))
.append('>'))
);
}
}
| 641 |
939 |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Adapter for CleverHans v3.1.0 to be run in TensorFlow 2.x environment.
The multi-representation adversary experiments are run in TensorFlow 2, but
depend on a version of the CleverHans package which expects TensorFlow 1. This
adapter glues them together by importing needed parts from CleverHans and
assigning their TensorFlow references to `tensorflow.compat.v1`.
"""
# pylint: disable=g-bad-import-order
import tensorflow as tf
import tensorflow.compat.v1 as tfv1
# Expose the symbols used in function interfaces. This has to be done before
# actually importing CleverHans.
tf.GraphKeys = tfv1.GraphKeys
# pylint: disable=g-import-not-at-top
from cleverhans import compat
from cleverhans import utils_tf
from cleverhans.attacks import sparse_l1_descent
# pylint: enable=g-import-not-at-top
# pylint: enable=g-bad-import-order
# Bind the expected TensorFlow version.
compat.tf = tfv1
utils_tf.tf = tfv1
sparse_l1_descent.tf = tfv1
| 451 |
945 |
/* Helper functions to work around issues with clang builtins
* Copyright (C) 2021 IBM Corporation
*
* Authors:
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
*
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#ifndef POWER_BUILTINS_H
#define POWER_BUILTINS_H
/*
* These stubs fix clang incompatibilities with GCC builtins.
*/
#ifndef __builtin_crypto_vpmsumw
#define __builtin_crypto_vpmsumw __builtin_crypto_vpmsumb
#endif
#ifndef __builtin_crypto_vpmsumd
#define __builtin_crypto_vpmsumd __builtin_crypto_vpmsumb
#endif
static inline __vector unsigned long long __attribute__((overloadable))
vec_ld(int __a, const __vector unsigned long long* __b) {
return (__vector unsigned long long)__builtin_altivec_lvx(__a, __b);
}
#endif
| 288 |
9,657 |
# coding=utf-8
from torch.utils.data import Dataset
import numpy as np
from datautil.util import Nmax
from datautil.imgdata.util import rgb_loader, l_loader
from torchvision.datasets import ImageFolder
class ImageDataset(object):
def __init__(self, dataset, task, root_dir, domain_name, domain_label=-1, labels=None, transform=None, target_transform=None, indices=None, test_envs=[], mode='RGB'):
self.imgs = ImageFolder(root_dir+domain_name).imgs
self.domain_num = 0
self.task = task
self.dataset = dataset
imgs = [item[0] for item in self.imgs]
labels = [item[1] for item in self.imgs]
self.labels = np.array(labels)
self.x = imgs
self.transform = transform
self.target_transform = target_transform
if indices is None:
self.indices = np.arange(len(imgs))
else:
self.indices = indices
if mode == 'RGB':
self.loader = rgb_loader
elif mode == 'L':
self.loader = l_loader
self.dlabels = np.ones(self.labels.shape) * \
(domain_label-Nmax(test_envs, domain_label))
def set_labels(self, tlabels=None, label_type='domain_label'):
assert len(tlabels) == len(self.x)
if label_type == 'domain_label':
self.dlabels = tlabels
elif label_type == 'class_label':
self.labels = tlabels
def target_trans(self, y):
if self.target_transform is not None:
return self.target_transform(y)
else:
return y
def input_trans(self, x):
if self.transform is not None:
return self.transform(x)
else:
return x
def __getitem__(self, index):
index = self.indices[index]
img = self.input_trans(self.loader(self.x[index]))
ctarget = self.target_trans(self.labels[index])
dtarget = self.target_trans(self.dlabels[index])
return img, ctarget, dtarget
def __len__(self):
return len(self.indices)
| 925 |
421 |
<filename>samples/snippets/cpp/VS_Snippets_Winforms/IDesignerEventServiceExample/CPP/source.cpp
//<Snippet1>
#using <system.dll>
#using <system.design.dll>
#using <system.windows.forms.dll>
#using <system.drawing.dll>
using namespace System;
using namespace System::ComponentModel;
using namespace System::ComponentModel::Design;
using namespace System::Collections;
using namespace System::Drawing;
using namespace System::Windows::Forms;
using namespace System::Windows::Forms::Design;
namespace DesignerEventServiceExample
{
ref class DesignerMonitorDesigner;
// DesignerMonitor provides a display for designer event notifications.
[Designer(DesignerEventServiceExample::DesignerMonitorDesigner::typeid)]
public ref class DesignerMonitor: public UserControl
{
public:
// List to contain strings that describe designer events.
ArrayList^ updates;
bool monitoring_events;
DesignerMonitor()
{
monitoring_events = false;
updates = gcnew ArrayList;
this->BackColor = Color::White;
this->Size = System::Drawing::Size( 450, 300 );
}
protected:
// Display the message for the current mode, and any event messages if event monitoring is active.
virtual void OnPaint( PaintEventArgs^ e ) override
{
e->Graphics->DrawString( "IDesignerEventService DesignerMonitor Control", gcnew System::Drawing::Font( FontFamily::GenericMonospace,10 ), gcnew SolidBrush( Color::Blue ), 5, 4 );
int yoffset = 10;
if ( !monitoring_events )
{
yoffset += 10;
e->Graphics->DrawString( "Currently not monitoring designer events.", gcnew System::Drawing::Font( FontFamily::GenericMonospace,10 ), gcnew SolidBrush( Color::Black ), 5.f, yoffset + 10.f );
e->Graphics->DrawString( "Use the shortcut menu commands", gcnew System::Drawing::Font( FontFamily::GenericMonospace,10 ), gcnew SolidBrush( Color::Black ), 5.f, yoffset + 30.f );
e->Graphics->DrawString( "provided by an associated DesignerMonitorDesigner", gcnew System::Drawing::Font( FontFamily::GenericMonospace,10 ), gcnew SolidBrush( Color::Black ), 5.f, yoffset + 40.f );
e->Graphics->DrawString( "to start or stop monitoring.", gcnew System::Drawing::Font( FontFamily::GenericMonospace,10 ), gcnew SolidBrush( Color::Black ), 5.f, yoffset + 50.f );
}
else
{
e->Graphics->DrawString( "Currently monitoring designer events.", gcnew System::Drawing::Font( FontFamily::GenericMonospace,10 ), gcnew SolidBrush( Color::DarkBlue ), 5.f, yoffset + 10.f );
e->Graphics->DrawString( "Designer created, changed and disposed events:", gcnew System::Drawing::Font( FontFamily::GenericMonospace,9 ), gcnew SolidBrush( Color::Brown ), 5.f, yoffset + 35.f );
for ( int i = 0; i < updates->Count; i++ )
{
e->Graphics->DrawString( static_cast<String^>(updates[ i ]), gcnew System::Drawing::Font( FontFamily::GenericMonospace,8 ), gcnew SolidBrush( Color::Black ), 5.f, yoffset + 55.f + (10 * i) );
yoffset += 10;
}
}
}
};
// DesignerMonitorDesigner uses the IDesignerEventService to send event information
// to an associated DesignerMonitor control's updates collection.
public ref class DesignerMonitorDesigner: public ControlDesigner
{
private:
DesignerMonitor^ dm;
DesignerVerbCollection^ dvc;
int eventcount;
void StopMonitoring( Object^ /*sender*/, EventArgs^ /*e*/ )
{
IDesignerEventService^ des = dynamic_cast<IDesignerEventService^>(this->Control->Site->GetService( IDesignerEventService::typeid ));
if ( des != nullptr )
{
// Remove event handlers for event notification methods.
des->DesignerCreated -= gcnew DesignerEventHandler( this, &DesignerMonitorDesigner::DesignerCreated );
des->DesignerDisposed -= gcnew DesignerEventHandler( this, &DesignerMonitorDesigner::DesignerDisposed );
des->ActiveDesignerChanged -= gcnew ActiveDesignerEventHandler( this, &DesignerMonitorDesigner::DesignerChanged );
des->SelectionChanged -= gcnew EventHandler( this, &DesignerMonitorDesigner::SelectionChanged );
dm->monitoring_events = false;
// Rebuild menu with "Start monitoring" command.
array<DesignerVerb^>^myArray = {gcnew DesignerVerb( "Start monitoring",gcnew EventHandler( this, &DesignerMonitorDesigner::StartMonitoring ) )};
dvc = gcnew DesignerVerbCollection( myArray );
dm->Refresh();
}
}
void StartMonitoring( Object^ /*sender*/, EventArgs^ /*e*/ )
{
IDesignerEventService^ des = dynamic_cast<IDesignerEventService^>(this->Control->Site->GetService( IDesignerEventService::typeid ));
if ( des != nullptr )
{
// Add event handlers for event notification methods.
des->DesignerCreated += gcnew DesignerEventHandler( this, &DesignerMonitorDesigner::DesignerCreated );
des->DesignerDisposed += gcnew DesignerEventHandler( this, &DesignerMonitorDesigner::DesignerDisposed );
des->ActiveDesignerChanged += gcnew ActiveDesignerEventHandler( this, &DesignerMonitorDesigner::DesignerChanged );
des->SelectionChanged += gcnew EventHandler( this, &DesignerMonitorDesigner::SelectionChanged );
dm->monitoring_events = false;
// Rebuild menu with "Stop monitoring" command.
array<DesignerVerb^>^myArray = {gcnew DesignerVerb( "Stop monitoring",gcnew EventHandler( this, &DesignerMonitorDesigner::StopMonitoring ) )};
dvc = gcnew DesignerVerbCollection( myArray );
dm->Refresh();
}
}
void DesignerCreated( Object^ /*sender*/, DesignerEventArgs^ e )
{
UpdateStatus( "Designer for " + e->Designer->RootComponent->Site->Name + " was created." );
}
void DesignerDisposed( Object^ /*sender*/, DesignerEventArgs^ e )
{
UpdateStatus( "Designer for " + e->Designer->RootComponent->Site->Name + " was disposed." );
}
void DesignerChanged( Object^ /*sender*/, ActiveDesignerEventArgs^ e )
{
UpdateStatus( "Active designer moved from " + e->OldDesigner->RootComponent->Site->Name + " to " + e->NewDesigner->RootComponent->Site->Name + "." );
}
void SelectionChanged( Object^ /*sender*/, EventArgs^ /*e*/ )
{
UpdateStatus("A component selection was changed.");
}
// Update message buffer on DesignerMonitor control.
void UpdateStatus( String^ newmsg )
{
if ( dm->updates->Count > 10 )
dm->updates->RemoveAt( 10 );
dm->updates->Insert( 0, "Event #" + eventcount.ToString() + ": " + newmsg );
eventcount++;
dm->Refresh();
}
};
}
//</Snippet1>
| 2,760 |
814 |
<gh_stars>100-1000
"""Roots of polynomials"""
from puzzle_generator import PuzzleGenerator, Tags
from typing import List
# See https://github.com/microsoft/PythonProgrammingPuzzles/wiki/How-to-add-a-puzzle to learn about adding puzzles
class QuadraticRoot(PuzzleGenerator):
"""See [quadratic equations](https://en.wikipedia.org/wiki/Quadratic_formula)"""
tags = [Tags.math, Tags.famous]
@staticmethod
def sat(x: float, coeffs=[2.5, 1.3, -0.5]):
"""
Find any (real) solution to: a x^2 + b x + c where coeffs = [a, b, c].
For example, since x^2 - 3x + 2 has a root at 1, sat(x = 1., coeffs = [1., -3., 2.]) is True.
"""
a, b, c = coeffs
return abs(a * x ** 2 + b * x + c) < 1e-6
@staticmethod
def sol(coeffs):
a, b, c = coeffs
if a == 0:
ans = -c / b if b != 0 else 0.0
else:
ans = ((-b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a))
return ans
@staticmethod
def sol2(coeffs):
a, b, c = coeffs
if a == 0:
ans = -c / b if b != 0 else 0.0
else:
ans = (-b - (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)
return ans
def gen_random(self):
x, a, b = [self.random.heavy_tail_float() for _ in range(3)]
c = -(a * x ** 2 + b * x) # make sure it has a real-valued solution
coeffs = [a, b, c]
self.add(dict(coeffs=coeffs))
class AllQuadraticRoots(PuzzleGenerator):
"""See [quadratic equations](https://en.wikipedia.org/wiki/Quadratic_formula)."""
tags = [Tags.math, Tags.famous]
@staticmethod
def sat(roots: List[float], coeffs=[1.3, -0.5]):
"""Find all (real) solutions to: x^2 + b x + c (i.e., factor into roots), here coeffs = [b, c]"""
b, c = coeffs
r1, r2 = roots
return abs(r1 + r2 + b) + abs(r1 * r2 - c) < 1e-6
@staticmethod
def sol(coeffs):
b, c = coeffs
delta = (b ** 2 - 4 * c) ** 0.5
return [(-b + delta) / 2, (-b - delta) / 2]
def gen_random(self):
x, b = [self.random.heavy_tail_float() for _ in range(2)]
c = -(x ** 2 + b * x) # make sure it has a real-valued solution
coeffs = [b, c]
self.add(dict(coeffs=coeffs))
class CubicRoot(PuzzleGenerator):
"""See [cubic equation](https://en.wikipedia.org/wiki/Cubic_formula)."""
tags = [Tags.math, Tags.famous]
@staticmethod
def sat(x: float, coeffs=[2.0, 1.0, 0.0, 8.0]):
"""
Find any (real) solution to: a x^3 + b x^2 + c x + d where coeffs = [a, b, c, d]
For example, since (x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x - 6, sat(x = 1., coeffs = [-6., 11., -6.]) is True.
"""
return abs(sum(c * x ** (3 - i) for i, c in enumerate(coeffs))) < 1e-6
@staticmethod
def sol(coeffs):
a2, a1, a0 = [c / coeffs[0] for c in coeffs[1:]]
p = (3 * a1 - a2 ** 2) / 3
q = (9 * a1 * a2 - 27 * a0 - 2 * a2 ** 3) / 27
delta = (q ** 2 + 4 * p ** 3 / 27) ** 0.5
omega = (-(-1) ** (1 / 3))
for cube in [(q + delta) / 2, (q - delta) / 2]:
c = cube ** (1 / 3)
for w in [c, c * omega, c * omega.conjugate()]:
if w != 0:
x = complex(w - p / (3 * w) - a2 / 3).real
if abs(sum(c * x ** (3 - i) for i, c in enumerate(coeffs))) < 1e-6:
return x
def gen_random(self):
x, a, b, c = [self.random.heavy_tail_float() for _ in range(4)]
d = -(a * x ** 3 + b * x ** 2 + c * x) # make sure it has a real-valued solution
coeffs = [a, b, c, d]
if self.sol(coeffs) is not None:
self.add(dict(coeffs=coeffs))
class AllCubicRoots(PuzzleGenerator):
"""See [cubic equation](https://en.wikipedia.org/wiki/Cubic_formula)."""
tags = [Tags.math, Tags.famous]
@staticmethod
def sat(roots: List[float], coeffs=[1.0, -2.0, -1.0]):
"""Find all 3 distinct real roots of x^3 + a x^2 + b x + c, i.e., factor into (x-r1)(x-r2)(x-r3).
coeffs = [a, b, c]. For example, since (x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x - 6,
sat(roots = [1., 2., 3.], coeffs = [-6., 11., -6.]) is True.
"""
r1, r2, r3 = roots
a, b, c = coeffs
return abs(r1 + r2 + r3 + a) + abs(r1 * r2 + r1 * r3 + r2 * r3 - b) + abs(r1 * r2 * r3 + c) < 1e-6
@staticmethod
def sol(coeffs):
a, b, c = coeffs
p = (3 * b - a ** 2) / 3
q = (9 * b * a - 27 * c - 2 * a ** 3) / 27
delta = (q ** 2 + 4 * p ** 3 / 27) ** 0.5
omega = (-(-1) ** (1 / 3))
ans = []
for cube in [(q + delta) / 2, (q - delta) / 2]:
v = cube ** (1 / 3)
for w in [v, v * omega, v * omega.conjugate()]:
if w != 0.0:
x = complex(w - p / (3 * w) - a / 3).real
if abs(x ** 3 + a * x ** 2 + b * x + c) < 1e-4:
if not ans or min(abs(z - x) for z in ans) > 1e-6:
ans.append(x)
if len(ans) == 3:
return ans
def gen_random(self):
r1, r2, r3 = [self.random.heavy_tail_float() for _ in range(3)]
coeffs = [-r1 - r2 - r3, r1 * r2 + r1 * r3 + r2 * r3, -r1 * r2 * r3] # to ensure solvability
if self.sol(coeffs) is not None:
self.add(dict(coeffs=coeffs)) # won't add duplicates
if __name__ == "__main__":
PuzzleGenerator.debug_problems()
| 2,849 |
429 |
<reponame>seanjunheng2/PlasmaPy
"""
Decorator to convert units of functions in /physics methods
"""
__all__ = ["angular_freq_to_hz"]
import astropy.units as u
import functools
import inspect
from plasmapy.utils.decorators.helpers import preserve_signature
def angular_freq_to_hz(fn):
"""
A decorator that adds to a function the ability to convert the function's return from
angular frequency (rad/s) to frequency (Hz).
A kwarg `to_hz` is added to the function's signature, with a default value of `False`.
The keyword is also added to the function's docstring under the **"Other Parameters"**
heading.
Parameters
----------
fn : function
The function to be decorated
Raises
------
ValueError
If `fn` has already defined a kwarg `to_hz`
Returns
-------
callable
The decorated function
Notes
-----
* If `angular_freq_to_hz` is used with decorator
:func:`~plasmapy.utils.decorators.validate_quantities`, then
`angular_freq_to_hz` should be used inside
:func:`~plasmapy.utils.decorators.validate_quantities` but special
consideration is needed for setup. The following is an example of an
appropriate setup::
import astropy.units as u
from plasmapy.utils.decorators.converter import angular_freq_to_hz
from plasmapy.utils.decorators.validators import validate_quantities
@validate_quantities(validations_on_return={'units': [u.rad / u.s, u.Hz]})
@angular_freq_to_hz
def foo(x: u.rad / u.s) -> u.rad / u.s
return x
Adding `u.Hz` to the allowed units allows the converted quantity to pass
the validations.
Examples
--------
>>> import astropy.units as u
>>> from plasmapy.utils.decorators.converter import angular_freq_to_hz
>>>
>>> @angular_freq_to_hz
... def foo(x):
... return x
>>>
>>> foo(5 * u.rad / u.s, to_hz=True)
<Quantity 0.79577472 Hz>
>>>
>>> foo(-1 * u.rad / u.s, to_hz=True)
<Quantity -0.15915494 Hz>
Decoration also works with methods
>>> class Foo:
... def __init__(self, x):
... self.x = x
...
... @angular_freq_to_hz
... def bar(self):
... return self.x
>>>
>>> foo = Foo(0.5 * u.rad / u.s)
>>> foo.bar(to_hz=True)
<Quantity 0.07957747 Hz>
"""
# raise exception if fn uses the 'to_hz' kwarg
sig = inspect.signature(fn)
if "to_hz" in sig.parameters:
raise ValueError(
f"Wrapped function '{fn.__name__}' can not use keyword 'to_hz'."
f" Keyword reserved for decorator functionality."
)
# make new signature for fn
new_params = sig.parameters.copy()
new_params["to_hz"] = inspect.Parameter(
"to_hz", inspect.Parameter.POSITIONAL_OR_KEYWORD, default=False
)
new_sig = inspect.Signature(
parameters=new_params.values(), return_annotation=sig.return_annotation
)
fn.__signature__ = new_sig
@preserve_signature
@functools.wraps(fn)
def wrapper(*args, to_hz=False, **kwargs):
_result = fn(*args, **kwargs)
if to_hz:
return _result.to(u.Hz, equivalencies=[(u.cy / u.s, u.Hz)])
return _result
added_doc_bit = """
Other Parameters
----------------
to_hz: bool
Set `True` to to convert function output from angular frequency to Hz
"""
if wrapper.__doc__ is not None:
wrapper.__doc__ += added_doc_bit
else:
wrapper.__doc__ = added_doc_bit
return wrapper
| 1,583 |
32,544 |
<reponame>DBatOWL/tutorials<gh_stars>1000+
package com.baeldung.patterns.escqrs.aggregates;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import com.baeldung.patterns.cqrs.commands.CreateUserCommand;
import com.baeldung.patterns.cqrs.commands.UpdateUserCommand;
import com.baeldung.patterns.domain.Address;
import com.baeldung.patterns.domain.Contact;
import com.baeldung.patterns.domain.User;
import com.baeldung.patterns.es.events.Event;
import com.baeldung.patterns.es.events.UserAddressAddedEvent;
import com.baeldung.patterns.es.events.UserAddressRemovedEvent;
import com.baeldung.patterns.es.events.UserContactAddedEvent;
import com.baeldung.patterns.es.events.UserContactRemovedEvent;
import com.baeldung.patterns.es.events.UserCreatedEvent;
import com.baeldung.patterns.es.repository.EventStore;
import com.baeldung.patterns.es.service.UserUtility;
public class UserAggregate {
private EventStore writeRepository;
public UserAggregate(EventStore repository) {
this.writeRepository = repository;
}
public List<Event> handleCreateUserCommand(CreateUserCommand command) {
UserCreatedEvent event = new UserCreatedEvent(command.getUserId(), command.getFirstName(), command.getLastName());
writeRepository.addEvent(command.getUserId(), event);
return Arrays.asList(event);
}
public List<Event> handleUpdateUserCommand(UpdateUserCommand command) {
User user = UserUtility.recreateUserState(writeRepository, command.getUserId());
List<Event> events = new ArrayList<>();
List<Contact> contactsToRemove = user.getContacts()
.stream()
.filter(c -> !command.getContacts()
.contains(c))
.collect(Collectors.toList());
for (Contact contact : contactsToRemove) {
UserContactRemovedEvent contactRemovedEvent = new UserContactRemovedEvent(contact.getType(), contact.getDetail());
events.add(contactRemovedEvent);
writeRepository.addEvent(command.getUserId(), contactRemovedEvent);
}
List<Contact> contactsToAdd = command.getContacts()
.stream()
.filter(c -> !user.getContacts()
.contains(c))
.collect(Collectors.toList());
for (Contact contact : contactsToAdd) {
UserContactAddedEvent contactAddedEvent = new UserContactAddedEvent(contact.getType(), contact.getDetail());
events.add(contactAddedEvent);
writeRepository.addEvent(command.getUserId(), contactAddedEvent);
}
List<Address> addressesToRemove = user.getAddresses()
.stream()
.filter(a -> !command.getAddresses()
.contains(a))
.collect(Collectors.toList());
for (Address address : addressesToRemove) {
UserAddressRemovedEvent addressRemovedEvent = new UserAddressRemovedEvent(address.getCity(), address.getState(), address.getPostcode());
events.add(addressRemovedEvent);
writeRepository.addEvent(command.getUserId(), addressRemovedEvent);
}
List<Address> addressesToAdd = command.getAddresses()
.stream()
.filter(a -> !user.getAddresses()
.contains(a))
.collect(Collectors.toList());
for (Address address : addressesToAdd) {
UserAddressAddedEvent addressAddedEvent = new UserAddressAddedEvent(address.getCity(), address.getState(), address.getPostcode());
events.add(addressAddedEvent);
writeRepository.addEvent(command.getUserId(), addressAddedEvent);
}
return events;
}
}
| 1,459 |
1,444 |
<filename>Mage.Tests/src/test/java/org/mage/test/cards/triggers/dies/ChildOfAlaraTest.java
package org.mage.test.cards.triggers.dies;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import org.junit.Test;
import org.mage.test.serverside.base.CardTestPlayerBase;
/**
*
* @author escplan9
*/
public class ChildOfAlaraTest extends CardTestPlayerBase {
@Test
public void testChildOfAlaraOblivionRingInteraction() {
/*
Child of Alara {W}{U}{B}{R}{G}
Legendary Creature — Avatar 6/6
Trample
When Child of Alara dies, destroy all nonland permanents. They can't be regenerated.
*/
String childAlara = "Child of Alara";
/*
Oblivion Ring {2}{W}
Enchantment
When Oblivion Ring enters the battlefield, exile another target nonland permanent.
When Oblivion Ring leaves the battlefield, return the exiled card to the battlefield under its owner's control.
*/
String oRing = "Oblivion Ring";
/*
Tamiyo, Field Research {1}{G}{W}{U}
Planeswalker - Tamiyo
+1: Choose up to two target creatures. Until your next turn, whenever either of those creatures deals combat damage, you draw a card.
−2: Tap up to two target nonland permanents. They don't untap during their controller's next untap step.
−7: Draw three cards. You get an emblem with "You may cast spells from your hand without paying their mana costs."
*/
String tamiyo = "Tamiyo, Field Researcher";
String memnite = "Memnite"; // {0} 1/1
String hGiant = "Hill Giant"; // {3}{R} 3/3
String dDemolition = "Daring Demolition"; // {2}{B}{B} sorcery: destroy target creature or vehicle
addCard(Zone.HAND, playerA, tamiyo);
addCard(Zone.BATTLEFIELD, playerA, "Plains", 2);
addCard(Zone.BATTLEFIELD, playerA, "Island", 2);
addCard(Zone.BATTLEFIELD, playerA, "Forest", 2);
addCard(Zone.BATTLEFIELD, playerA, hGiant);
addCard(Zone.BATTLEFIELD, playerA, childAlara);
addCard(Zone.HAND, playerB, dDemolition);
addCard(Zone.HAND, playerB, oRing);
addCard(Zone.BATTLEFIELD, playerB, "Swamp", 4);
addCard(Zone.BATTLEFIELD, playerB, "Plains", 4);
addCard(Zone.BATTLEFIELD, playerB, memnite);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, tamiyo);
castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, oRing);
addTarget(playerB, tamiyo);
castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, dDemolition, childAlara);
setStopAt(2, PhaseStep.BEGIN_COMBAT);
execute();
assertGraveyardCount(playerB, dDemolition, 1);
assertGraveyardCount(playerA, childAlara, 1);
assertGraveyardCount(playerB, oRing, 1); // destroyed by child
assertGraveyardCount(playerB, memnite, 1);
assertGraveyardCount(playerA, hGiant, 1);
assertPermanentCount(playerA, tamiyo, 1); // o-ring destroyed returns Tamiyo to battlefield
}
}
| 1,461 |
2,869 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.undertow.servlet.util;
import io.undertow.servlet.UndertowServletLogger;
import io.undertow.servlet.api.SessionPersistenceManager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Session persistence implementation that simply stores session information in memory.
*
* @author <NAME>
*/
public class InMemorySessionPersistence implements SessionPersistenceManager {
private static final Map<String, Map<String, SessionEntry>> data = new ConcurrentHashMap<>();
@Override
public void persistSessions(String deploymentName, Map<String, PersistentSession> sessionData) {
try {
final Map<String, SessionEntry> serializedData = new HashMap<>();
for (Map.Entry<String, PersistentSession> sessionEntry : sessionData.entrySet()) {
Map<String, byte[]> data = new HashMap<>();
for (Map.Entry<String, Object> sessionAttribute : sessionEntry.getValue().getSessionData().entrySet()) {
try {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
objectOutputStream.writeObject(sessionAttribute.getValue());
objectOutputStream.close();
data.put(sessionAttribute.getKey(), out.toByteArray());
} catch (Exception e) {
UndertowServletLogger.ROOT_LOGGER.failedToPersistSessionAttribute(sessionAttribute.getKey(), sessionAttribute.getValue(), sessionEntry.getKey(), e);
}
}
serializedData.put(sessionEntry.getKey(), new SessionEntry(sessionEntry.getValue().getExpiration(), data));
}
data.put(deploymentName, serializedData);
} catch (Exception e) {
UndertowServletLogger.ROOT_LOGGER.failedToPersistSessions(e);
}
}
@Override
public Map<String, PersistentSession> loadSessionAttributes(String deploymentName, final ClassLoader classLoader) {
try {
long time = System.currentTimeMillis();
Map<String, SessionEntry> data = this.data.remove(deploymentName);
if (data != null) {
Map<String, PersistentSession> ret = new HashMap<>();
for (Map.Entry<String, SessionEntry> sessionEntry : data.entrySet()) {
if (sessionEntry.getValue().expiry.getTime() > time) {
Map<String, Object> session = new HashMap<>();
for (Map.Entry<String, byte[]> sessionAttribute : sessionEntry.getValue().data.entrySet()) {
final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(sessionAttribute.getValue()));
session.put(sessionAttribute.getKey(), in.readObject());
}
ret.put(sessionEntry.getKey(), new PersistentSession(sessionEntry.getValue().expiry, session));
}
}
return ret;
}
} catch (Exception e) {
UndertowServletLogger.ROOT_LOGGER.failedtoLoadPersistentSessions(e);
}
return null;
}
@Override
public void clear(String deploymentName) {
}
static final class SessionEntry {
private final Date expiry;
private final Map<String, byte[]> data;
private SessionEntry(Date expiry, Map<String, byte[]> data) {
this.expiry = expiry;
this.data = data;
}
}
}
| 1,825 |
335 |
{
"word": "Unframed",
"definitions": [
"(especially of a picture) not having a frame."
],
"parts-of-speech": "Adjective"
}
| 64 |
1,559 |
# coding:utf-8
import fasttext
from smartnlp.utils.clean_text import clean_zh_text, clean_en_text
import os
from smartnlp.utils.basic_log import Log
import logging
log = Log(logging.INFO)
class FastTextClassifier:
"""
需要安装包:pip install fasttext
利用fasttext来对文本进行分类
"""
def __init__(self, model_path,
train=False,
file_path=None):
"""
初始化
:param file_path: 训练数据路径
:param model_path: 模型保存路径
"""
self.model_path = model_path
if not train:
self.model = self.load(self.model_path)
assert self.model is not None, '训练模型无法获取'
else:
assert file_path is not None, '训练时, file_path不能为None'
self.train_path = os.path.join(file_path, 'train.txt')
self.test_path = os.path.join(file_path, 'test.txt')
self.model = self.train()
def train(self):
"""
训练:参数可以针对性修改,进行调优
"""
model = fasttext.supervised(self.train_path,
self.model_path,
label_prefix="__label__",
epoch=100,
dim=256,
silent=False,
lr=0.01)
test_result = model.test(self.test_path)
print('准确率: ', test_result.precision)
return model
def predict(self, text):
"""
预测一条数据,由于fasttext获取的参数是列表,如果只是简单输入字符串,会将字符串按空格拆分组成列表进行推理
:param text: 待分类的数据
:return: 分类后的结果
"""
if isinstance(text, list):
output = self.model.predict(text, )
else:
output = self.model.predict([text], )
print('predict:', output)
return output
def load(self, model_path):
"""
加载训练好的模型
:param model_path: 训练好的模型路径
:return:
"""
if os.path.exists(self.model_path + '.bin'):
return fasttext.load_model(model_path + '.bin')
else:
return None
def clean(file_path):
"""
清理文本, 然后利用清理后的文本进行训练
"""
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
lines_clean = []
for line in lines:
line_list = line.split('__label__')
lines_clean.append(clean_en_text(line_list[0]) + ' __label__' + line_list[1])
with open(file_path, 'w', encoding='utf-8') as f:
f.writelines(lines_clean)
| 1,629 |
372 |
package org.sunger.net.view;
import org.sunger.net.entity.SimpleUserEntity;
import java.util.List;
/**
* Created by sunger on 2015/11/30.
*/
public interface FriendshipsView {
void showError();
void showFriends(List<SimpleUserEntity> data);
}
| 87 |
4,438 |
<filename>lib/android/src/main/java/com/wix/reactnativeuilib/utils/LogForwarder.java
package com.wix.reactnativeuilib.utils;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
public class LogForwarder {
public enum LogType {
log,
warn,
error
}
private DeviceEventManagerModule.RCTDeviceEventEmitter eventEmitter;
public LogForwarder(ReactContext reactContext) {
eventEmitter = reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class);
}
@SuppressWarnings("unused")
public void e(String TAG, String text) {
log(LogType.error, TAG, text);
}
@SuppressWarnings("unused")
public void w(String TAG, String text) {
log(LogType.warn, TAG, text);
}
@SuppressWarnings("unused")
public void d(String TAG, String text) {
log(LogType.log, TAG, text);
}
private void log(LogType logType, String TAG, String text) {
WritableMap payload = Arguments.createMap();
payload.putString("LogType", logType.name());
payload.putString("TAG", TAG);
payload.putString("text", text);
eventEmitter.emit("log", payload);
}
}
| 509 |
5,169 |
{
"name": "UPVideoCarousel",
"version": "1.0",
"summary": "UPVideoCarousel is video Carousel for ios",
"swift_versions": "5.0",
"description": "UPVideoCarousel is very easy to use and light weight Carousel control for ios, developed in Swift",
"homepage": "https://github.com/erbittuu/UPVideoCarousel",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"erbittuu": "<EMAIL>"
},
"source": {
"git": "https://github.com/erbittuu/UPVideoCarousel.git",
"tag": "1.0"
},
"social_media_url": "https://twitter.com/erbittuu",
"platforms": {
"ios": "11.3"
},
"source_files": "UPVideoCarousel/Classes/**/*",
"dependencies": {
"ASPVideoPlayer": [
]
},
"swift_version": "5.0"
}
| 305 |
741 |
package com.qingshop.mall.modules.system.entity;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.qingshop.mall.framework.annotation.Excel;
import com.qingshop.mall.framework.annotation.Excel.Type;
/**
* 部门表
*/
@TableName("sys_dept")
public class SysDept implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId("dept_id")
@Excel(name = "部门编号", type = Type.IMPORT)
private Long deptId;
/**
* 部门名称
*/
@TableField("dept_name")
@Excel(name = "部门名称")
private String deptName;
/**
* 描述
*/
@TableField("dept_desc")
@Excel(name = "部门描述")
private String deptDesc;
/**
* 创建时间
*/
@TableField("create_time")
private Date createTime;
/**
* 更新时间
*/
@TableField("update_time")
private Date updateTime;
public Long getDeptId() {
return deptId;
}
public void setDeptId(Long deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getDeptDesc() {
return deptDesc;
}
public void setDeptDesc(String deptDesc) {
this.deptDesc = deptDesc;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
| 784 |
1,874 |
# Copyright 2016 Rackspace Australia
# 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.
"""Render vendordata as stored fetched from REST microservices."""
import sys
from keystoneauth1 import exceptions as ks_exceptions
from keystoneauth1 import loading as ks_loading
from oslo_log import log as logging
from oslo_serialization import jsonutils
from nova.api.metadata import vendordata
import nova.conf
CONF = nova.conf.CONF
LOG = logging.getLogger(__name__)
_SESSION = None
_ADMIN_AUTH = None
def _load_ks_session(conf):
"""Load session.
This is either an authenticated session or a requests session, depending on
what's configured.
"""
global _ADMIN_AUTH
global _SESSION
if not _ADMIN_AUTH:
_ADMIN_AUTH = ks_loading.load_auth_from_conf_options(
conf, nova.conf.vendordata.vendordata_group.name)
if not _ADMIN_AUTH:
LOG.warning('Passing insecure dynamic vendordata requests '
'because of missing or incorrect service account '
'configuration.')
if not _SESSION:
_SESSION = ks_loading.load_session_from_conf_options(
conf, nova.conf.vendordata.vendordata_group.name,
auth=_ADMIN_AUTH)
return _SESSION
class DynamicVendorData(vendordata.VendorDataDriver):
def __init__(self, instance):
self.instance = instance
# We only create the session if we make a request.
self.session = None
def _do_request(self, service_name, url):
if self.session is None:
self.session = _load_ks_session(CONF)
try:
body = {'project-id': self.instance.project_id,
'instance-id': self.instance.uuid,
'image-id': self.instance.image_ref,
'user-data': self.instance.user_data,
'hostname': self.instance.hostname,
'metadata': self.instance.metadata,
'boot-roles': self.instance.system_metadata.get(
'boot_roles', '')}
headers = {'Content-Type': 'application/json',
'Accept': 'application/json',
'User-Agent': 'openstack-nova-vendordata'}
# SSL verification
verify = url.startswith('https://')
if verify and CONF.api.vendordata_dynamic_ssl_certfile:
verify = CONF.api.vendordata_dynamic_ssl_certfile
timeout = (CONF.api.vendordata_dynamic_connect_timeout,
CONF.api.vendordata_dynamic_read_timeout)
res = self.session.request(url, 'POST', data=jsonutils.dumps(body),
verify=verify, headers=headers,
timeout=timeout)
if res and res.text:
# TODO(mikal): Use the Cache-Control response header to do some
# sensible form of caching here.
return jsonutils.loads(res.text)
return {}
except (TypeError, ValueError,
ks_exceptions.connection.ConnectionError,
ks_exceptions.http.HttpError) as e:
LOG.warning('Error from dynamic vendordata service '
'%(service_name)s at %(url)s: %(error)s',
{'service_name': service_name,
'url': url,
'error': e},
instance=self.instance)
if CONF.api.vendordata_dynamic_failure_fatal:
raise e.with_traceback(sys.exc_info()[2])
return {}
def get(self):
j = {}
for target in CONF.api.vendordata_dynamic_targets:
# NOTE(mikal): a target is composed of the following:
# name@url
# where name is the name to use in the metadata handed to
# instances, and url is the URL to fetch it from
if target.find('@') == -1:
LOG.warning('Vendordata target %(target)s lacks a name. '
'Skipping',
{'target': target}, instance=self.instance)
continue
tokens = target.split('@')
name = tokens[0]
url = '@'.join(tokens[1:])
if name in j:
LOG.warning('Vendordata already contains an entry named '
'%(target)s. Skipping',
{'target': target}, instance=self.instance)
continue
j[name] = self._do_request(name, url)
return j
| 2,453 |
611 |
from huobi.client.algo import AlgoClient
from huobi.constant import *
from huobi.utils import *
symbol_test = "adausdt"
account_id = g_account_id
algo_client = AlgoClient(api_key=g_api_key, secret_key=g_secret_key)
result = algo_client.get_order_history(symbol_test, AlgoOrderStatus.TRIGGERED)
LogInfo.output_list(result)
| 125 |
8,865 |
/* ===-- fixunstfsi.c - Implement __fixunstfsi -----------------------------===
*
* The LLVM Compiler Infrastructure
*
* This file is dual licensed under the MIT and the University of Illinois Open
* Source Licenses. See LICENSE.TXT for details.
*
* ===----------------------------------------------------------------------===
*/
#define QUAD_PRECISION
#include "fp_lib.h"
#if defined(CRT_HAS_128BIT) && defined(CRT_LDBL_128BIT)
typedef su_int fixuint_t;
#include "fp_fixuint_impl.inc"
COMPILER_RT_ABI su_int
__fixunstfsi(fp_t a) {
return __fixuint(a);
}
#endif
| 211 |
357 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.03.02 at 03:10:45 PM EET
//
package org.oasis_open.docs.ws_sx.ws_trust._200512;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>
* Java class for BinaryExchangeType complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType name="BinaryExchangeType">
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="ValueType" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* <attribute name="EncodingType" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BinaryExchangeType", propOrder = { "value" })
public class BinaryExchangeType {
@XmlValue
protected String value;
@XmlAttribute(name = "ValueType", required = true)
@XmlSchemaType(name = "anyURI")
protected String valueType;
@XmlAttribute(name = "EncodingType", required = true)
@XmlSchemaType(name = "anyURI")
protected String encodingType;
/**
* Gets the value of the value property.
*
* @return possible object is {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the valueType property.
*
* @return possible object is {@link String }
*
*/
public String getValueType() {
return valueType;
}
/**
* Sets the value of the valueType property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setValueType(String value) {
this.valueType = value;
}
/**
* Gets the value of the encodingType property.
*
* @return possible object is {@link String }
*
*/
public String getEncodingType() {
return encodingType;
}
/**
* Sets the value of the encodingType property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setEncodingType(String value) {
this.encodingType = value;
}
}
| 1,226 |
852 |
<reponame>ckamtsikis/cmssw<gh_stars>100-1000
#ifndef _TrimmedVertexFitter_H_
#define _TrimmedVertexFitter_H_
#include "RecoVertex/VertexPrimitives/interface/VertexFitter.h"
#include "RecoVertex/TrimmedKalmanVertexFinder/interface/KalmanTrimmedVertexFinder.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/BeamSpot/interface/BeamSpot.h"
/*
* Turn the TrimmedVertexFinder into a VertexFitter.
*/
class TrimmedVertexFitter : public VertexFitter<5> {
public:
typedef CachingVertex<5>::RefCountedVertexTrack RefCountedVertexTrack;
typedef ReferenceCountingPointer<LinearizedTrackState<5> > RefCountedLinearizedTrackState;
TrimmedVertexFitter();
TrimmedVertexFitter(const edm::ParameterSet& pSet);
~TrimmedVertexFitter() override {}
CachingVertex<5> vertex(const std::vector<reco::TransientTrack>& tracks) const override;
CachingVertex<5> vertex(const std::vector<RefCountedVertexTrack>& tracks) const override;
CachingVertex<5> vertex(const std::vector<RefCountedVertexTrack>& tracks, const reco::BeamSpot& spot) const override;
CachingVertex<5> vertex(const std::vector<reco::TransientTrack>& tracks, const GlobalPoint& linPoint) const override;
CachingVertex<5> vertex(const std::vector<reco::TransientTrack>& tracks,
const GlobalPoint& priorPos,
const GlobalError& priorError) const override;
CachingVertex<5> vertex(const std::vector<RefCountedVertexTrack>& tracks,
const GlobalPoint& priorPos,
const GlobalError& priorError) const override;
CachingVertex<5> vertex(const std::vector<reco::TransientTrack>& tracks,
const reco::BeamSpot& beamSpot) const override;
// Clone method
TrimmedVertexFitter* clone() const override;
void setPtCut(float cut);
void setTrackCompatibilityCut(float cut);
void setVertexFitProbabilityCut(float cut);
private:
KalmanTrimmedVertexFinder theRector;
double ptcut;
};
#endif
| 767 |
358 |
<reponame>isabella232/qfs<filename>src/cc/meta/Replay.cc<gh_stars>100-1000
/*!
* $Id$
*
* \file Replay.cc
* \brief transaction log replay
* \author <NAME> (Kosmix Corp.)
* <NAME>
*
* Copyright 2008-2012,2016 Quantcast Corporation. All rights reserved.
* Copyright 2006-2008 Kosmix Corp.
*
* This file is part of Kosmos File System (KFS).
*
* Licensed under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "Replay.h"
#include "LogWriter.h"
#include "Restorer.h"
#include "util.h"
#include "DiskEntry.h"
#include "kfstree.h"
#include "LayoutManager.h"
#include "MetaVrSM.h"
#include "MetaVrOps.h"
#include "MetaDataStore.h"
#include "common/MdStream.h"
#include "common/MsgLogger.h"
#include "common/StdAllocator.h"
#include "common/kfserrno.h"
#include "common/RequestParser.h"
#include "common/juliantime.h"
#include "common/StBuffer.h"
#include "kfsio/checksum.h"
#include "qcdio/QCUtils.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <cassert>
#include <cstdlib>
#include <sstream>
#include <iomanip>
#include <deque>
#include <set>
namespace KFS
{
using std::ostringstream;
using std::deque;
using std::set;
using std::less;
using std::hex;
using std::dec;
using std::streamoff;
inline void
Replay::setRollSeeds(int64_t roll)
{
rollSeeds = roll;
}
class ReplayState
{
public:
// Commit entry other than "op" are intended to debugging error checksum
// mismatches, after series of ops are committed.
class CommitQueueEntry
{
public:
CommitQueueEntry(
const MetaVrLogSeq& ls = MetaVrLogSeq(),
int s = 0,
fid_t fs = -1,
int64_t ek = 0,
MetaRequest* o = 0)
: logSeq(ls),
seed(fs),
errChecksum(ek),
status(s),
op(o)
{}
MetaVrLogSeq logSeq;
fid_t seed;
int64_t errChecksum;
int status;
MetaRequest* op;
};
typedef deque<
CommitQueueEntry
> CommitQueue;
class EnterAndLeave;
friend class EnterAndLeave;
ReplayState(
Replay* replay,
bool* enqueueFlagPtr)
: mCommitQueue(),
mCheckpointCommitted(0, 0, 0),
mLastNonLogCommit(),
mCheckpointFileIdSeed(0),
mCheckpointErrChksum(0),
mLastCommittedSeq(0, 0, 0),
mLastBlockCommittedSeq(0, 0, 0),
mViewStartSeq(0, 0, 0),
mBlockStartLogSeq(0, 0, 0),
mLastBlockSeq(-1),
mLastLogAheadSeq(0, 0, 0),
mLastNonEmptyViewEndSeq(0, 0, 0),
mLogAheadErrChksum(0),
mSubEntryCount(0),
mLogSegmentTimeUsec(0),
mLastBlockSeed(0),
mLastBlockStatus(0),
mLastBlockErrChecksum(0),
mLastCommittedStatus(0),
mRestoreTimeCount(0),
mUpdateLogWriterFlag(false),
mReplayer(replay),
mEnqueueFlagFlagPtr(enqueueFlagPtr),
mCurOp(0),
mRecursionCount(0)
{
if (! mEnqueueFlagFlagPtr && mReplayer) {
panic("invalid replay stae arguments");
}
}
~ReplayState()
{
if (mCurOp) {
mCurOp->replayFlag = false;
MetaRequest::Release(mCurOp);
}
for (CommitQueue::iterator it = mCommitQueue.begin();
mCommitQueue.end() != it;
++it) {
if (it->op) {
it->op->replayFlag = false;
MetaRequest::Release(it->op);
it->op = 0;
}
}
}
bool runCommitQueue(
const MetaVrLogSeq& logSeq,
seq_t seed,
int64_t status,
int64_t errChecksum);
bool incSeq()
{
if (0 != mSubEntryCount) {
return false;
}
curOpDone();
mLastLogAheadSeq.mLogSeq++;
if (mLastLogAheadSeq.IsPastViewStart()) {
mLastNonEmptyViewEndSeq = mLastLogAheadSeq;
}
return true;
}
bool subEntry()
{
if (--mSubEntryCount <= 0) {
return incSeq();
}
return true;
}
inline static ReplayState& get(const DETokenizer& c);
bool handle()
{
if (! mCurOp) {
panic("replay: no current op");
return false;
}
if (mReplayer) {
if (META_VR_LOG_START_VIEW == mCurOp->op) {
handleOp(*mCurOp);
if (mCurOp) {
const bool ok = 0 == mCurOp->status;
curOpDone();
return ok;
}
} else {
mCommitQueue.push_back(ReplayState::CommitQueueEntry(
mCurOp->logseq.IsValid() ?
mCurOp->logseq : mLastLogAheadSeq, 0, 0, 0, mCurOp));
mCurOp = 0;
*mEnqueueFlagFlagPtr = true;
}
} else {
handleOp(*mCurOp);
}
return true;
}
bool isCurOpLogSeqValid() const
{
if (! mReplayer || ! mCurOp) {
return true;
}
if (META_VR_LOG_START_VIEW == mCurOp->op) {
return true;
}
MetaVrLogSeq next = mLastLogAheadSeq;
next.mLogSeq++;
if (next == mCurOp->logseq) {
return true;
}
KFS_LOG_STREAM_ERROR <<
"replay logseq mismatch:"
" expected: " << next <<
" actual: " << mCurOp->logseq <<
" " << mCurOp->Show() <<
KFS_LOG_EOM;
return false;
}
void replayCurOp()
{
if (! mCurOp || 1 != mSubEntryCount) {
panic("invalid replay current op invocation");
return;
}
if (! isCurOpLogSeqValid()) {
panic("invalid current op log sequence");
return;
}
handle();
}
void commit(CommitQueueEntry& entry)
{
if (! entry.op) {
return;
}
MetaRequest& op = *entry.op;
bool updateCommittedFlag = op.logseq.IsValid();
if (! updateCommittedFlag && op.replayFlag) {
panic("replay: commit invalid op log sequence");
return;
}
if (! op.replayFlag) {
update();
}
if (updateCommittedFlag && op.logseq <= mViewStartSeq) {
// Set failure status for the remaining ops from the previous view.
// The op is effectively canceled.
updateCommittedFlag = false;
op.status = -EVRNOTPRIMARY;
if (op.replayFlag) {
op.statusMsg = "primary node might have changed";
}
// No effect on error checksum, set etnry status to 0.
entry.status = 0;
// Invalidate the log sequence, as the start view has effectively
// deleted the op from the log.
op.logseq = MetaVrLogSeq();
if (! op.replayFlag) {
handleOp(op);
}
} else {
handleOp(op);
}
if (updateCommittedFlag && META_VR_LOG_START_VIEW != op.op) {
const int status = op.status < 0 ? SysToKfsErrno(-op.status) : 0;
mLastCommittedSeq = op.logseq;
mLastCommittedStatus = status;
mLogAheadErrChksum += status;
entry.status = status;
}
entry.logSeq = op.logseq;
entry.seed = fileID.getseed();
entry.errChecksum = mLogAheadErrChksum;
entry.op = 0;
if (&op != mCurOp && (! op.suspended || ! op.replayFlag)) {
opDone(op);
}
}
void handleOp(MetaRequest& op)
{
if (op.replayFlag) {
op.seqno = MetaRequest::GetLogWriter().GetNextSeq();
op.handle();
} else {
if (! op.SubmitBegin()) {
panic("replay: invalid submit begin status");
}
}
KFS_LOG_STREAM_DEBUG <<
(mReplayer ? (op.replayFlag ? "replay:" : "commit") : "handle:") <<
" logseq: " << op.logseq <<
" x " << hex << op.logseq << dec <<
" status: " << op.status <<
" " << op.statusMsg <<
" " << op.Show() <<
KFS_LOG_EOM;
if (op.suspended && &op == mCurOp) {
mCurOp = 0;
}
}
bool commitAll()
{
if (0 != mSubEntryCount || ! mReplayer) {
return false;
}
if (mCommitQueue.empty()) {
return true;
}
for (CommitQueue::iterator it = mCommitQueue.begin();
mCommitQueue.end() != it;
++it) {
commit(*it);
}
mCommitQueue.clear();
mBlockStartLogSeq = mLastCommittedSeq;
return true;
}
void getReplayCommitQueue(
Replay::CommitQueue& queue) const
{
queue.clear();
queue.reserve(mCommitQueue.size());
for (CommitQueue::const_iterator it = mCommitQueue.begin();
mCommitQueue.end() != it;
++it) {
if (! it->op || ! it->op->logseq.IsValid() || ! it->op->replayFlag ||
0 != it->op->status) {
continue;
}
queue.push_back(it->op);
}
}
void curOpDone()
{
if (! mCurOp) {
return;
}
MetaRequest& op = *mCurOp;
mCurOp = 0;
opDone(op);
}
void opDone(MetaRequest& op)
{
if (op.replayFlag) {
op.replayFlag = false;
MetaRequest::Release(&op);
} else {
op.SubmitEnd();
}
}
void handleStartView(MetaVrLogStartView& op)
{
if (! mReplayer) {
panic("replay: invalid start view invocation");
return;
}
if (0 != op.status) {
KFS_LOG_STREAM_ERROR <<
" status: " << op.status <<
" " << op.statusMsg <<
" logseq: " << op.logseq <<
" " << op.Show() <<
KFS_LOG_EOM;
return;
}
if (! op.Validate()) {
op.status = -EINVAL;
op.statusMsg = "invalid log start view op";
return;
}
CommitQueue::iterator it = mCommitQueue.begin();
while (mCommitQueue.end() != it && it->logSeq <= op.mCommittedSeq) {
commit(*it);
++it;
}
mCommitQueue.erase(mCommitQueue.begin(), it);
if (op.mCommittedSeq != mLastCommittedSeq) {
op.status = -EINVAL;
op.statusMsg = "invalid committed sequence";
return;
}
mViewStartSeq = op.mNewLogSeq;
mLastLogAheadSeq = op.mNewLogSeq;
mBlockStartLogSeq = op.mNewLogSeq;
mBlockStartLogSeq.mLogSeq--;
if (! runCommitQueue(
op.mCommittedSeq,
fileID.getseed(),
mLastCommittedStatus,
mLogAheadErrChksum) ||
op.mCommittedSeq != mLastCommittedSeq ||
! mCommitQueue.empty()) {
op.status = -EINVAL;
op.statusMsg = "run commit queue failure";
return;
}
}
void setReplayState(
const MetaVrLogSeq& committed,
const MetaVrLogSeq& viewStartSeq,
seq_t seed,
int status,
int64_t errChecksum,
MetaRequest* commitQueue,
const MetaVrLogSeq& lastBlockCommitted,
fid_t lastBlockSeed,
int lastBlockStatus,
int64_t lastBlockErrChecksum,
const MetaVrLogSeq& lastNonEmptyViewEndSeq)
{
if (mCurOp || ! mReplayer || ! committed.IsValid() ||
(commitQueue && commitQueue->logseq.IsValid() &&
commitQueue->logseq <= committed)) {
panic("replay: set replay state invalid arguments");
return;
}
if (! mCommitQueue.empty() && ! runCommitQueue(
committed,
seed,
status,
errChecksum)) {
panic("replay: set replay state run commit queue failure");
return;
}
if (mBlockStartLogSeq < committed) {
mBlockStartLogSeq = committed;
}
if (mLastLogAheadSeq < committed) {
mLastLogAheadSeq = committed;
}
if (mViewStartSeq < viewStartSeq) {
mViewStartSeq = viewStartSeq;
}
mLastBlockCommittedSeq = lastBlockCommitted;
mLastBlockSeed = lastBlockSeed;
mLastBlockStatus = lastBlockStatus,
mLastBlockErrChecksum = lastBlockErrChecksum;
mLastCommittedSeq = committed;
mLastCommittedStatus = status;
mLastNonEmptyViewEndSeq = lastNonEmptyViewEndSeq;
mLogAheadErrChksum = errChecksum;
mSubEntryCount = 0;
MetaRequest* next = commitQueue;
while (next) {
MetaRequest& op = *next;
next = op.next;
op.next = 0;
if (! enqueueSelf(op)) {
submit_request(&op);
}
}
if (! runCommitQueue(
mLastCommittedSeq,
fileID.getseed(),
mLastCommittedStatus,
mLogAheadErrChksum)) {
panic("replay: set replay state run commit queue failure");
}
}
bool enqueue(MetaRequest& req)
{
if (! mReplayer) {
panic("replay: invalid enqueue attempt");
return false;
}
if (mCommitQueue.empty()) {
return false;
}
return enqueueSelf(req);
}
bool enqueueSelf(MetaRequest& req)
{
if (mCurOp) {
panic("replay: invalid enqueue attempt: has pending op");
return false;
}
if (req.replayBypassFlag || IsMetaLogWriteOrVrError(req.status)) {
return false;
}
mCurOp = &req;
MetaVrLogSeq const nextSeq = mCurOp->logseq;
if (nextSeq.IsValid() && ! isCurOpLogSeqValid()) {
panic("replay: invalid enqueue log sequence");
}
if (handle()) {
if (mLastLogAheadSeq < nextSeq) {
mLastLogAheadSeq = nextSeq;
}
} else {
panic("replay: enqueue: invalid handle completion");
return false;
}
return true;
}
void update()
{
if (mUpdateLogWriterFlag) {
*mEnqueueFlagFlagPtr = ! mCommitQueue.empty();
MetaRequest::GetLogWriter().SetCommitted(
mLastCommittedSeq,
mLogAheadErrChksum,
fileID.getseed(),
mLastCommittedStatus,
mLastLogAheadSeq,
mViewStartSeq
);
}
}
CommitQueue mCommitQueue;
MetaVrLogSeq mCheckpointCommitted;
MetaVrLogSeq mLastNonLogCommit;
fid_t mCheckpointFileIdSeed;
int64_t mCheckpointErrChksum;
MetaVrLogSeq mLastCommittedSeq;
MetaVrLogSeq mLastBlockCommittedSeq;
MetaVrLogSeq mViewStartSeq;
MetaVrLogSeq mBlockStartLogSeq;
seq_t mLastBlockSeq;
MetaVrLogSeq mLastLogAheadSeq;
MetaVrLogSeq mLastNonEmptyViewEndSeq;
int64_t mLogAheadErrChksum;
int64_t mSubEntryCount;
int64_t mLogSegmentTimeUsec;
fid_t mLastBlockSeed;
int mLastBlockStatus;
int64_t mLastBlockErrChecksum;
int mLastCommittedStatus;
int mRestoreTimeCount;
bool mUpdateLogWriterFlag;
Replay* const mReplayer;
bool* const mEnqueueFlagFlagPtr;
MetaRequest* mCurOp;
private:
int mRecursionCount;
private:
ReplayState(const ReplayState&);
ReplayState& operator=(const ReplayState&);
};
class ReplayState::EnterAndLeave
{
public:
EnterAndLeave(ReplayState& state, int targetCnt = 0)
: mState(state),
mTargetCount(targetCnt)
{
if (mTargetCount != mState.mRecursionCount) {
panic("replay: invalid recursion");
}
mState.mRecursionCount++;
}
~EnterAndLeave()
{
if (mTargetCount + 1 != mState.mRecursionCount) {
panic("replay: invalid recursion count");
}
mState.mRecursionCount--;
mState.update();
}
private:
ReplayState& mState;
const int mTargetCount;
private:
EnterAndLeave(const EnterAndLeave&);
EnterAndLeave& operator=(const EnterAndLeave&);
};
class Replay::State : public ReplayState
{
public:
State(
Replay* replay,
bool* flag)
: ReplayState(replay, flag)
{}
static State& get(const DETokenizer& c)
{ return *reinterpret_cast<State*>(c.getUserData()); }
};
/* static */ inline
ReplayState& ReplayState::get(const DETokenizer& c)
{ return Replay::State::get(c); }
static bool
parse_vr_log_seq(DETokenizer& c, MetaVrLogSeq& outSeq)
{
if (c.empty()) {
return false;
}
const char* cur = c.front().ptr;
return (
16 == c.getIntBase() ?
outSeq.Parse<HexIntParser>(cur, c.front().len) :
outSeq.Parse<DecIntParser>(cur, c.front().len)
);
}
/*!
* \brief open saved log file for replay
* \param[in] p a path in the form "<logdir>/log.<number>"
*/
int
Replay::openlog(const string& name)
{
if (file.is_open()) {
file.close();
}
string::size_type pos = name.rfind('/');
if (string::npos == pos) {
pos = 0;
} else {
pos++;
}
if (logdir.empty()) {
tmplogname.assign(name.data(), name.size());
} else {
tmplogname.assign(logdir.data(), logdir.size());
tmplogname += name.data() + pos;
pos = logdir.size();
}
KFS_LOG_STREAM_INFO <<
"open log file: " << name << " => " << tmplogname <<
KFS_LOG_EOM;
int64_t num = -1;
const string::size_type dot = tmplogname.rfind('.');
if (string::npos == dot || dot < pos ||
(num = toNumber(tmplogname.c_str() + dot + 1)) < 0) {
KFS_LOG_STREAM_FATAL <<
tmplogname << ": invalid log file name" <<
KFS_LOG_EOM;
tmplogname.clear();
return -EINVAL;
}
file.open(tmplogname.c_str(), ifstream::in | ifstream::binary);
if (file.fail()) {
const int err = errno;
KFS_LOG_STREAM_FATAL <<
tmplogname << ": " << QCUtils::SysError(err) <<
KFS_LOG_EOM;
tmplogname.clear();
return (err > 0 ? -err : (err == 0 ? -1 : err));
}
number = num;
path.assign(tmplogname.data(), tmplogname.size());
tmplogname.clear();
return 0;
}
void
Replay::setLogDir(const char* dir)
{
if (dir && *dir) {
logdir = dir;
if ('/' != *logdir.rbegin()) {
logdir += '/';
}
} else {
logdir.clear();
}
}
const string&
Replay::logfile(seq_t num)
{
if (tmplogname.empty()) {
string::size_type name = path.rfind('/');
if (string::npos == name) {
name = 0;
} else {
name++;
}
const string::size_type dot = path.find('.', name);
if (dot == string::npos) {
tmplogname = path + ".";
} else {
tmplogname = path.substr(0, dot + 1);
}
tmplogprefixlen = tmplogname.length();
}
tmplogname.erase(tmplogprefixlen);
if (logSegmentHasLogSeq(num)) {
AppendDecIntToString(tmplogname, lastLogSeq.mEpochSeq);
tmplogname += '.';
AppendDecIntToString(tmplogname, lastLogSeq.mViewSeq);
tmplogname += '.';
AppendDecIntToString(tmplogname, lastLogSeq.mLogSeq);
tmplogname += '.';
}
AppendDecIntToString(tmplogname, num);
return tmplogname;
}
string
Replay::getLastLog()
{
const char* kLast = MetaDataStore::GetLogSegmentLastFileNamePtr();
const string::size_type pos = path.rfind('/');
if (string::npos != pos) {
return path.substr(0, pos + 1) + kLast;
}
return kLast;
}
/*!
* \brief check log version
* format: version/<number>
*/
static bool
replay_version(DETokenizer& c)
{
fid_t vers;
bool ok = pop_fid(vers, "version", c, true);
return (ok && vers == LogWriter::VERSION);
}
/*!
* \brief handle common prefix for all log records
*/
static bool
pop_parent(fid_t &id, DETokenizer& c)
{
c.pop_front(); // get rid of record type
return pop_fid(id, "dir", c, true);
}
/*!
* \brief update the seed of a UniqueID with what is passed in.
* Since this function is called in the context of log replay, it
* better be the case that the seed passed in is higher than
* the id's seed (which was set from a checkpoint file).
*/
static void
updateSeed(UniqueID &id, seqid_t seed)
{
if (seed < id.getseed()) {
ostringstream os;
os << "seed from log: " << seed <<
" < id's seed: " << id.getseed();
panic(os.str(), false);
}
id.setseed(seed);
}
/*!
* \brief replay a file create
* format: create/dir/<parentID>/name/<name>/id/<myID>{/ctime/<time>}
*/
static bool
replay_create(DETokenizer& c)
{
fid_t parent, me;
string myname;
int status = 0;
int16_t numReplicas;
int64_t ctime;
bool ok = pop_parent(parent, c);
ok = pop_name(myname, "name", c, ok);
ok = pop_fid(me, "id", c, ok);
ok = pop_short(numReplicas, "numReplicas", c, ok);
// if the log has the ctime, pass it thru
const bool gottime = pop_time(ctime, "ctime", c, ok);
chunkOff_t t = KFS_STRIPED_FILE_TYPE_NONE, n = 0, nr = 0, ss = 0;
if (ok && gottime && pop_offset(t, "striperType", c, true)) {
ok = pop_offset(n, "numStripes", c, true) &&
pop_offset(nr, "numRecoveryStripes", c, true) &&
pop_offset(ss, "stripeSize", c, true);
}
if (! ok) {
return false;
}
fid_t todumpster = -1;
if (! pop_fid(todumpster, "todumpster", c, ok)) {
todumpster = -1;
}
kfsUid_t user = kKfsUserNone;
kfsUid_t group = kKfsGroupNone;
kfsMode_t mode = 0;
int64_t k = user;
kfsSTier_t minSTier = kKfsSTierMax;
kfsSTier_t maxSTier = kKfsSTierMax;
if (! c.empty()) {
if (! pop_num(k, "user", c, ok)) {
return false;
}
user = (kfsUid_t)k;
if (user == kKfsUserNone) {
return false;
}
k = group;
if (! pop_num(k, "group", c, ok)) {
return false;
}
group = (kfsGid_t)k;
if (group == kKfsGroupNone) {
return false;
}
k = mode;
if (! pop_num(k, "mode", c, ok)) {
return false;
}
mode = (kfsMode_t)k;
if (! c.empty()) {
if (! pop_num(k, "minTier", c, ok)) {
return false;
}
minSTier = (kfsSTier_t)k;
if (! pop_num(k, "maxTier", c, ok)) {
return false;
}
maxSTier = (kfsSTier_t)k;
}
} else {
user = gLayoutManager.GetDefaultLoadUser();
group = gLayoutManager.GetDefaultLoadGroup();
mode = gLayoutManager.GetDefaultLoadFileMode();
}
if (user == kKfsUserNone || group == kKfsGroupNone ||
mode == kKfsModeUndef) {
return false;
}
if (maxSTier < minSTier ||
! IsValidSTier(minSTier) ||
! IsValidSTier(maxSTier)) {
return false;
}
// for all creates that were successful during normal operation,
// when we replay it should work; so, exclusive = false
MetaFattr* fa = 0;
status = metatree.create(parent, myname, &me, numReplicas, false,
t, n, nr, ss, user, group, mode,
kKfsUserRoot, kKfsGroupRoot, &fa,
gottime ? ctime : ReplayState::get(c).mLogSegmentTimeUsec,
0 < todumpster);
if (0 == status) {
assert(fa);
updateSeed(fileID, me);
if (gottime) {
fa->mtime = fa->ctime = fa->atime = ctime;
if (fa->IsStriped()) {
fa->filesize = 0;
}
}
if (minSTier < kKfsSTierMax) {
fa->minSTier = minSTier;
fa->maxSTier = maxSTier;
}
}
KFS_LOG_STREAM_DEBUG << "replay create:"
" name: " << myname <<
" id: " << me <<
KFS_LOG_EOM;
return (0 == status);
}
/*!
* \brief replay mkdir
* format: mkdir/dir/<parentID>/name/<name>/id/<myID>{/ctime/<time>}
*/
static bool
replay_mkdir(DETokenizer& c)
{
fid_t parent, me;
string myname;
int status = 0;
int64_t ctime;
bool ok = pop_parent(parent, c);
ok = pop_name(myname, "name", c, ok);
ok = pop_fid(me, "id", c, ok);
if (! ok) {
return false;
}
// if the log has the ctime, pass it thru
const bool gottime = pop_time(ctime, "ctime", c, ok);
kfsUid_t user = kKfsUserNone;
kfsUid_t group = kKfsGroupNone;
kfsMode_t mode = 0;
int64_t k = user;
if (pop_num(k, "user", c, ok)) {
user = (kfsUid_t)k;
if (user == kKfsUserNone) {
return false;
}
k = group;
if (! pop_num(k, "group", c, ok)) {
return false;
}
group = (kfsGid_t)k;
if (group == kKfsGroupNone) {
return false;
}
k = mode;
if (! pop_num(k, "mode", c, ok)) {
return false;
}
mode = (kfsMode_t)k;
} else {
user = gLayoutManager.GetDefaultLoadUser();
group = gLayoutManager.GetDefaultLoadGroup();
mode = gLayoutManager.GetDefaultLoadFileMode();
}
if (user == kKfsUserNone || group == kKfsGroupNone ||
mode == kKfsModeUndef) {
return false;
}
int64_t mtime;
if (! pop_time(mtime, "mtime", c, ok)) {
mtime = ReplayState::get(c).mLogSegmentTimeUsec;
}
MetaFattr* fa = 0;
status = metatree.mkdir(parent, myname, user, group, mode,
kKfsUserRoot, kKfsGroupRoot, &me, &fa, mtime);
if (0 == status) {
assert(fa);
updateSeed(fileID, me);
if (gottime) {
fa->mtime = fa->ctime = fa->atime = ctime;
}
}
KFS_LOG_STREAM_DEBUG << "replay mkdir: "
" name: " << myname <<
" id: " << me <<
KFS_LOG_EOM;
return (ok && 0 == status);
}
/*!
* \brief replay remove
* format: remove/dir/<parentID>/name/<name>
*/
static bool
replay_remove(DETokenizer& c)
{
fid_t parent;
string myname;
int status = 0;
bool ok = pop_parent(parent, c);
ok = pop_name(myname, "name", c, ok);
fid_t todumpster = -1;
if (! pop_fid(todumpster, "todumpster", c, ok)) {
todumpster = -1;
}
if (ok) {
int64_t mtime;
if (! pop_time(mtime, "mtime", c, ok)) {
mtime = ReplayState::get(c).mLogSegmentTimeUsec;
}
status = metatree.remove(parent, myname, "",
kKfsUserRoot, kKfsGroupRoot, mtime, 0 < todumpster);
}
return (ok && 0 == status);
}
/*!
* \brief replay rmdir
* format: rmdir/dir/<parentID>/name/<name>
*/
static bool
replay_rmdir(DETokenizer& c)
{
fid_t parent;
string myname;
int status = 0;
bool ok = pop_parent(parent, c);
ok = pop_name(myname, "name", c, ok);
if (ok) {
int64_t mtime;
if (! pop_time(mtime, "mtime", c, ok)) {
mtime = ReplayState::get(c).mLogSegmentTimeUsec;
}
status = metatree.rmdir(parent, myname, "",
kKfsUserRoot, kKfsGroupRoot, mtime);
}
return (ok && 0 == status);
}
/*!
* \brief replay rename
* format: rename/dir/<parentID>/old/<oldname>/new/<newpath>
* NOTE: <oldname> is the name of file/dir in parent. This
* will never contain any slashes.
* <newpath> is the full path of file/dir. This may contain slashes.
* Since it is the last component, everything after new is <newpath>.
* So, unlike <oldname> which just requires taking one element out,
* we need to take everything after "new" for the <newpath>.
*
*/
static bool
replay_rename(DETokenizer& c)
{
fid_t parent;
string oldname, newpath;
int status = 0;
bool ok = pop_parent(parent, c);
ok = pop_name(oldname, "old", c, ok);
ok = pop_path(newpath, "new", c, ok);
fid_t todumpster = -1;
if (! pop_fid(todumpster, "todumpster", c, ok))
todumpster = -1;
if (ok) {
int64_t mtime;
if (! pop_time(mtime, "mtime", c, ok)) {
mtime = ReplayState::get(c).mLogSegmentTimeUsec;
}
string oldpath;
status = metatree.rename(parent, oldname, newpath, oldpath,
true, kKfsUserRoot, kKfsGroupRoot, mtime, 0, 0 < todumpster);
}
return (ok && 0 == status);
}
/*!
* \brief replay allocate
* format: allocate/file/<fileID>/offset/<offset>/chunkId/<chunkID>/
* chunkVersion/<chunkVersion>/{mtime/<time>}{/append/<1|0>}
*/
static bool
replay_allocate(DETokenizer& c)
{
fid_t fid;
chunkId_t cid, logChunkId;
chunkOff_t offset, tmp = 0;
seq_t chunkVersion = -1, logChunkVersion;
int status = 0;
int64_t mtime;
c.pop_front();
bool ok = pop_fid(fid, "file", c, true);
ok = pop_fid(offset, "offset", c, ok);
ok = pop_fid(logChunkId, "chunkId", c, ok);
ok = pop_fid(logChunkVersion, "chunkVersion", c, ok);
// if the log has the mtime, pass it thru
const bool gottime = pop_time(mtime, "mtime", c, ok);
const bool append = pop_fid(tmp, "append", c, ok) && tmp != 0;
// during normal operation, if a file that has a valid
// lease is removed, we move the file to the dumpster and log it.
// a subsequent allocation on that file will succeed.
// the remove/allocation is recorded in the logs in that order.
// during replay, we do the remove first and then we try to
// replay allocation; for the allocation, we won't find
// the file attributes. we move on...when the chunkservers
// that has the associated chunks for the file contacts us, we won't
// find the fid and so those chunks will get nuked as stale.
MetaFattr* const fa = metatree.getFattr(fid);
if (! fa) {
return ok;
}
if (ok) {
// if the log has the mtime, set it up in the FA
if (gottime) {
fa->mtime = max(fa->mtime, mtime);
}
cid = logChunkId;
bool stripedFile = false;
status = metatree.allocateChunkId(fid, offset, &cid,
&chunkVersion, NULL, &stripedFile);
if (stripedFile && append) {
return false; // append is not supported with striped files
}
const bool chunkExists = status == -EEXIST;
if (chunkExists) {
if (cid != logChunkId) {
return false;
}
if (chunkVersion == logChunkVersion) {
return true;
}
status = 0;
}
if (0 == status) {
assert(cid == logChunkId);
status = metatree.assignChunkId(fid, offset,
cid, logChunkVersion, fa->mtime, 0, 0, append);
if (0 == status) {
fid_t cfid = 0;
if (chunkExists &&
(! gLayoutManager.GetChunkFileId(
cid, cfid) ||
fid != cfid)) {
panic("missing chunk mapping", false);
}
MetaLogChunkAllocate logAlloc;
logAlloc.replayFlag = true;
logAlloc.status = 0;
logAlloc.fid = fid;
logAlloc.offset = offset;
logAlloc.chunkId = logChunkId;
logAlloc.chunkVersion = logChunkVersion;
logAlloc.appendChunk = append;
logAlloc.invalidateAllFlag = false;
logAlloc.objectStoreFileFlag = 0 == fa->numReplicas;
logAlloc.initialChunkVersion = chunkVersion;
logAlloc.mtime = gottime ? mtime : fa->mtime;
gLayoutManager.CommitOrRollBackChunkVersion(logAlloc);
status = logAlloc.status;
// assign updates the mtime; so, set it to what is in the log.
if (0 == status && gottime) {
fa->mtime = mtime;
}
if (chunkID.getseed() < cid) {
// Update here should only be executed for old style write
// behind log. Write append id update should be executed by
// log chunk in flight op handler.
chunkID.setseed(cid);
}
}
}
}
return (ok && 0 == status);
}
/*!
* \brief replay coalesce (do the cleanup/accounting actions)
* format: coalesce/old/<srcFid>/new/<dstFid>/count/<# of blocks coalesced>
*/
static bool
replay_coalesce(DETokenizer& c)
{
fid_t srcFid, dstFid;
size_t count;
int64_t mtime;
c.pop_front();
bool ok = pop_fid(srcFid, "old", c, true);
ok = pop_fid(dstFid, "new", c, ok);
ok = pop_size(count, "count", c, ok);
const bool gottime = pop_time(mtime, "mtime", c, ok);
fid_t retSrcFid = -1;
fid_t retDstFid = -1;
chunkOff_t dstStartOffset = -1;
size_t numChunksMoved = 0;
ok = ok && metatree.coalesceBlocks(
metatree.getFattr(srcFid), metatree.getFattr(dstFid),
retSrcFid, retDstFid, dstStartOffset,
gottime ? mtime : ReplayState::get(c).mLogSegmentTimeUsec,
numChunksMoved,
kKfsUserRoot, kKfsGroupRoot) == 0;
return (
ok &&
retSrcFid == srcFid && retDstFid == dstFid &&
numChunksMoved == count
);
}
/*!
* \brief replay truncate
* format: truncate/file/<fileID>/offset/<offset>{/mtime/<time>}
*/
static bool
replay_truncate(DETokenizer& c)
{
fid_t fid;
chunkOff_t offset;
chunkOff_t endOffset;
int status = 0;
int64_t mtime;
c.pop_front();
bool ok = pop_fid(fid, "file", c, true);
ok = pop_offset(offset, "offset", c, ok);
// if the log has the mtime, pass it thru
const bool gottime = pop_time(mtime, "mtime", c, ok);
if (! gottime || ! pop_offset(endOffset, "endoff", c, ok)) {
endOffset = -1;
}
if (ok) {
const bool kSetEofHintFlag = true;
status = metatree.truncate(fid, offset,
gottime ? mtime : ReplayState::get(c).mLogSegmentTimeUsec,
kKfsUserRoot, kKfsGroupRoot, endOffset, kSetEofHintFlag, -1, -1, 0);
}
return (ok && 0 == status);
}
/*!
* \brief replay prune blks from head of file
* format: pruneFromHead/file/<fileID>/offset/<offset>{/mtime/<time>}
*/
static bool
replay_pruneFromHead(DETokenizer& c)
{
fid_t fid;
chunkOff_t offset;
int status = 0;
int64_t mtime;
c.pop_front();
bool ok = pop_fid(fid, "file", c, true);
ok = pop_fid(offset, "offset", c, ok);
// if the log has the mtime, pass it thru
bool gottime = pop_time(mtime, "mtime", c, ok);
if (ok) {
status = metatree.pruneFromHead(fid, offset,
gottime ? mtime : ReplayState::get(c).mLogSegmentTimeUsec,
kKfsUserRoot, kKfsGroupRoot, -1, -1, 0);
}
return (ok && 0 == status);
}
/*!
* \brief replay size
* format: size/file/<fileID>/filesize/<filesize>
*/
static bool
replay_size(DETokenizer& c)
{
fid_t fid;
chunkOff_t filesize;
c.pop_front();
bool ok = pop_fid(fid, "file", c, true);
ok = pop_offset(filesize, "filesize", c, ok);
if (ok) {
MetaFattr* const fa = metatree.getFattr(fid);
if (fa) {
if (filesize >= 0) {
metatree.setFileSize(fa, filesize);
} else {
metatree.setFileSize(fa, 0);
metatree.invalidateFileSize(fa);
}
}
}
return true;
}
/*!
* Replay a change file replication RPC.
* format: setrep/file/<fid>/replicas/<#>
*/
static bool
replay_setrep(DETokenizer& c)
{
c.pop_front();
fid_t fid;
bool ok = pop_fid(fid, "file", c, true);
int16_t numReplicas;
ok = pop_short(numReplicas, "replicas", c, ok);
kfsSTier_t minSTier = kKfsSTierUndef;
kfsSTier_t maxSTier = kKfsSTierUndef;
if (! c.empty()) {
int64_t k;
if (! pop_num(k, "minTier", c, ok)) {
return false;
}
minSTier = (kfsSTier_t)k;
if (! pop_num(k, "maxTier", c, ok)) {
return false;
}
maxSTier = (kfsSTier_t)k;
}
if (! ok) {
return ok;
}
MetaFattr* const fa = metatree.getFattr(fid);
return (fa && metatree.changeFileReplication(
fa, numReplicas, minSTier, maxSTier) == 0);
}
/*!
* \brief replay setmtime
* format: setmtime/file/<fileID>/mtime/<time>
*/
static bool
replay_setmtime(DETokenizer& c)
{
fid_t fid;
int64_t mtime;
c.pop_front();
bool ok = pop_fid(fid, "file", c, true);
ok = pop_time(mtime, "mtime", c, ok);
if (ok) {
MetaFattr *fa = metatree.getFattr(fid);
// If the fa isn't there that isn't fatal.
if (fa != NULL)
fa->mtime = mtime;
}
return ok;
}
/*!
* \brief restore time
* format: time/<time>
*/
static bool
replay_time(DETokenizer& c)
{
c.pop_front();
if (c.empty()) {
return false;
}
// 2016-02-06T04:11:44.429777Z
const char* ptr = c.front().ptr;
int year = 0;
int mon = 0;
int mday = 0;
int hour = 0;
int minute = 0;
int sec = 0;
int64_t usec = 0;
if (27 == c.front().len &&
DecIntParser::Parse(ptr, 4, year) &&
'-' == *ptr &&
DecIntParser::Parse(++ptr, 2, mon) &&
'-' == *ptr &&
1 <= mon && mon <= 12 &&
DecIntParser::Parse(++ptr, 2, mday) &&
1 <= mday && mday <= 31 &&
'T' == *ptr &&
DecIntParser::Parse(++ptr, 2, hour) &&
0 <= hour && hour <= 23 &&
':' == *ptr &&
DecIntParser::Parse(++ptr, 2, minute) &&
0 <= minute && minute <= 59 &&
':' == *ptr &&
DecIntParser::Parse(++ptr, 2, sec) &&
0 <= sec && sec <= 59 &&
'.' == *ptr &&
DecIntParser::Parse(++ptr, 6, usec) &&
0 <= usec && usec <= 999999 &&
'Z' == *ptr) {
ReplayState::get(c).mLogSegmentTimeUsec =
ToUnixTime(year, mon, mday, hour, minute, sec) * 1000000 + usec;
} else {
ReplayState::get(c).mLogSegmentTimeUsec = microseconds();
}
KFS_LOG_STREAM_INFO << "log time: " << c.front() << KFS_LOG_EOM;
ReplayState::get(c).mRestoreTimeCount++;
return true;
}
/*!
* \brief restore make chunk stable
* format:
* "mkstable{done}/fileId/" << fid <<
* "/chunkId/" << chunkId <<
* "/chunkVersion/" << chunkVersion <<
* "/size/" << chunkSize <<
* "/checksum/" << chunkChecksum <<
* "/hasChecksum/" << (hasChunkChecksum ? 1 : 0)
*/
static bool
replay_makechunkstable(DETokenizer& c, bool addFlag)
{
fid_t fid;
chunkId_t chunkId;
seq_t chunkVersion;
chunkOff_t chunkSize;
string str;
fid_t tmp;
uint32_t checksum;
bool hasChecksum;
c.pop_front();
bool ok = pop_fid(fid, "fileId", c, true);
ok = pop_fid(chunkId, "chunkId", c, ok);
ok = pop_fid(chunkVersion, "chunkVersion", c, ok);
int64_t num = -1;
ok = pop_num(num, "size", c, ok);
chunkSize = chunkOff_t(num);
ok = pop_fid(tmp, "checksum", c, ok);
checksum = (uint32_t)tmp;
ok = pop_fid(tmp, "hasChecksum", c, ok);
hasChecksum = tmp != 0;
if (!ok) {
KFS_LOG_STREAM_ERROR << "ignore log line for mkstable <"
<< fid << ',' << chunkId << ',' << chunkVersion
<< ">" <<
KFS_LOG_EOM;
return true;
}
if (ok) {
gLayoutManager.ReplayPendingMakeStable(
chunkId, chunkVersion, chunkSize,
hasChecksum, checksum, addFlag);
}
return ok;
}
static bool
replay_mkstable(DETokenizer& c)
{
return replay_makechunkstable(c, true);
}
static bool
replay_mkstabledone(DETokenizer& c)
{
return replay_makechunkstable(c, false);
}
static bool
replay_beginchunkversionchange(DETokenizer& c)
{
fid_t fid;
chunkId_t chunkId;
seq_t chunkVersion;
c.pop_front();
bool ok = pop_fid(fid, "file", c, true);
ok = pop_fid (chunkId, "chunkId", c, ok);
ok = pop_fid (chunkVersion, "chunkVersion", c, ok);
if (! ok) {
return false;
}
const bool kPanicOnInvalidVersionFlag = false;
string* const kStatusMsg = 0;
const int ret = gLayoutManager.ProcessBeginChangeChunkVersion(
fid, chunkId, chunkVersion, kStatusMsg, kPanicOnInvalidVersionFlag);
return (0 == ret || -ENOENT == ret);
}
/*
DEPRECATED, DO NOT USE.
Meta server now maintains chunk server inventory, and stores in flight
chunk (ID) allocations in checkpoint and transaction log, therefore highest
used chunk ID is now maintained the same way as file ID.
*/
static bool
replay_rollseeds(DETokenizer& c)
{
c.pop_front();
if (c.empty()) {
return false;
}
ReplayState& state = ReplayState::get(c);
if (! state.mReplayer || state.mReplayer->logSegmentHasLogSeq()) {
KFS_LOG_STREAM_ERROR <<
"DEPRECATED: rollseeds is no longer required and cannot be used"
" with the current transaction log format" <<
KFS_LOG_EOM;
return false;
}
int64_t roll = c.toNumber();
if (roll == 0) {
roll = 2000000; // Default 2M
}
if (roll < 0 ||
chunkID.getseed() + roll < chunkID.getseed() ||
fileID.getseed() + roll < fileID.getseed()) {
KFS_LOG_STREAM_ERROR <<
"invalid seed roll value: " << roll <<
KFS_LOG_EOM;
return false;
}
chunkID.setseed(chunkID.getseed() + roll);
fileID.setseed(fileID.getseed() + roll);
state.mReplayer->setRollSeeds(roll);
return true;
}
static bool
replay_chmod(DETokenizer& c)
{
c.pop_front();
if (c.empty()) {
return false;
}
fid_t fid = -1;
if (! pop_fid(fid, "file", c, true)) {
return false;
}
int64_t n = 0;
if (! pop_num(n, "mode", c, true)){
return false;
}
const kfsMode_t mode = (kfsMode_t)n;
MetaFattr* const fa = metatree.getFattr(fid);
if (! fa) {
return false;
}
fa->mode = mode;
return true;
}
static bool
replay_chown(DETokenizer& c)
{
c.pop_front();
if (c.empty()) {
return false;
}
fid_t fid = -1;
if (! pop_fid(fid, "file", c, true)) {
return false;
}
int64_t n = kKfsUserNone;
if (! pop_num(n, "user", c, true)) {
return false;
}
const kfsUid_t user = (kfsUid_t)n;
n = kKfsGroupNone;
if (! pop_num(n, "group", c, true)) {
return false;
}
const kfsGid_t group = (kfsGid_t)n;
if (user == kKfsUserNone && group == kKfsGroupNone) {
return false;
}
MetaFattr* const fa = metatree.getFattr(fid);
if (! fa) {
return false;
}
if (user != kKfsUserNone) {
fa->user = user;
}
if (group != kKfsGroupNone) {
fa->user = group;
}
return true;
}
static bool
replay_inc_seq(DETokenizer& c)
{
return ReplayState::get(c).incSeq();
}
static bool
replay_sub_entry(DETokenizer& c)
{
return ReplayState::get(c).subEntry();
}
bool
ReplayState::runCommitQueue(
const MetaVrLogSeq& logSeq,
seq_t seed,
int64_t status,
int64_t errChecksum)
{
if (logSeq <= mCheckpointCommitted) {
// Checkpoint has no info about the last op status.
if ((logSeq == mCheckpointCommitted ?
(errChecksum == mCheckpointErrChksum &&
mCheckpointFileIdSeed == seed) :
(mCommitQueue.empty() ||
logSeq < mCommitQueue.front().logSeq))) {
if (mViewStartSeq < logSeq) {
return true;
}
} else {
KFS_LOG_STREAM_ERROR <<
"commit"
" sequence: " << logSeq <<
" checkpoint: " << mCheckpointCommitted <<
" error checksum:"
" log: " << errChecksum <<
" actual: " << mCheckpointErrChksum <<
" seed:"
" log: " << seed <<
" actual: " << mCheckpointFileIdSeed <<
" view start: " << mViewStartSeq <<
" queue:"
" size: " << mCommitQueue.size() <<
" front: " << (mCommitQueue.empty() ?
MetaVrLogSeq() : mCommitQueue.front().logSeq) <<
KFS_LOG_EOM;
return false;
}
}
if (logSeq < mLastNonLogCommit) {
return true;
}
const MetaVrLogSeq endSeq = max(logSeq, mViewStartSeq);
CommitQueue::iterator it = mCommitQueue.begin();
bool foundFlag = false;
while (mCommitQueue.end() != it) {
CommitQueueEntry& f = *it;
if (endSeq < f.logSeq) {
break;
}
commit(f);
if (logSeq == f.logSeq) {
foundFlag = true;
if (mViewStartSeq <= logSeq &&
(f.status != status ||
f.seed != seed ||
f.errChecksum != errChecksum)) {
for (CommitQueue::const_iterator cit = mCommitQueue.begin();
; ++cit) {
KFS_LOG_STREAM_ERROR <<
"commit"
" sequence: " << cit->logSeq <<
" x " << hex << cit->logSeq << dec <<
" seed: " << cit->seed <<
" error checksum: " << cit->errChecksum <<
" status: " << cit->status <<
" [" << (0 == cit->status ? string("OK") :
ErrorCodeToString(-KfsToSysErrno(cit->status))) <<
"]" <<
KFS_LOG_EOM;
if (cit == it) {
break;
}
}
KFS_LOG_STREAM_ERROR <<
"log commit:"
" sequence: " << logSeq <<
" x " << hex << logSeq << dec <<
" status mismatch"
" log: " << status <<
" [" << ErrorCodeToString(-KfsToSysErrno(status)) << "]"
" actual: " << f.status <<
" [" << ErrorCodeToString(-KfsToSysErrno(f.status)) <<
"]" <<
" seed:"
" log: " << seed <<
" actual: " << f.seed <<
" error checksum:"
" log: " << errChecksum <<
" actual: " << f.errChecksum <<
KFS_LOG_EOM;
return false;
}
}
++it;
}
mCommitQueue.erase(mCommitQueue.begin(), it);
// Commit sequence must always be at the log block end.
if (! foundFlag && mViewStartSeq <= logSeq &&
(fileID.getseed() != seed ||
mLastCommittedStatus != status ||
mLogAheadErrChksum != errChecksum)) {
KFS_LOG_STREAM_ERROR <<
"invliad log commit:"
" sequence: " << logSeq <<
" x " << hex << logSeq << dec <<
" / " << (mCommitQueue.empty() ?
MetaVrLogSeq() : mCommitQueue.front().logSeq) <<
" status: " << status <<
" [" << ErrorCodeToString(-KfsToSysErrno(status)) << "]" <<
" expected: " << mLastCommittedStatus <<
" [" << ErrorCodeToString(
-KfsToSysErrno(mLastCommittedStatus)) << "]" <<
" seed:"
" log: " << seed <<
" actual: " << fileID.getseed() <<
" error checksum:"
" log: " << errChecksum <<
" actual: " << mLogAheadErrChksum <<
" commit queue: " << mCommitQueue.size() <<
KFS_LOG_EOM;
return false;
}
return true;
}
static bool
replay_log_ahead_entry(DETokenizer& c)
{
ReplayState& state = ReplayState::get(c);
if (0 != state.mSubEntryCount || state.mCurOp) {
KFS_LOG_STREAM_ERROR <<
"invalid replay state:"
" sub entry count: " << state.mSubEntryCount <<
" cur op: " << MetaRequest::ShowReq(state.mCurOp) <<
KFS_LOG_EOM;
return false;
}
c.pop_front();
if (c.empty()) {
return false;
}
const DETokenizer::Token& token = c.front();
state.mCurOp = MetaRequest::ReadReplay(token.ptr, token.len);
if (! state.mCurOp) {
KFS_LOG_STREAM_ERROR <<
"replay parse failure:"
" logseq: " << state.mLastLogAheadSeq <<
" " << token <<
KFS_LOG_EOM;
return false;
}
if (! state.isCurOpLogSeqValid()) {
return false;
}
state.mCurOp->replayFlag = true;
return (state.handle() && state.incSeq());
}
static bool
replay_log_commit_entry(DETokenizer& c, Replay::BlockChecksum& blockChecksum)
{
if (c.size() < 9) {
return false;
}
ReplayState& state = ReplayState::get(c);
if (state.mCurOp) {
KFS_LOG_STREAM_ERROR <<
"replay invalid state:"
" non null current op at the end of log block: " <<
state.mCurOp->Show() <<
KFS_LOG_EOM;
return false;
}
const char* const ptr = c.front().ptr;
const size_t len = c.back().ptr - ptr;
const size_t skip = len + c.back().len;
blockChecksum.write(ptr, len);
c.pop_front();
MetaVrLogSeq commitSeq;
if (! parse_vr_log_seq(c, commitSeq) || ! commitSeq.IsValid()) {
return false;
}
c.pop_front();
const int64_t seed = c.toNumber();
if (! c.isLastOk()) {
return false;
}
c.pop_front();
const int64_t errchksum = c.toNumber();
if (! c.isLastOk()) {
return false;
}
c.pop_front();
const int64_t status = c.toNumber();
if (! c.isLastOk() || status < 0) {
return false;
}
c.pop_front();
MetaVrLogSeq logSeq;
if (! parse_vr_log_seq(c, logSeq) || logSeq != state.mLastLogAheadSeq) {
return false;
}
c.pop_front();
const int64_t blockLen = c.toNumber();
if (! c.isLastOk() || blockLen < 0 ||
state.mBlockStartLogSeq.mLogSeq + blockLen != logSeq.mLogSeq) {
return false;
}
c.pop_front();
const int64_t blockSeq = c.toNumber();
if (! c.isLastOk() || blockSeq != state.mLastBlockSeq + 1) {
return false;
}
c.pop_front();
const int64_t checksum = c.toNumber();
if (! c.isLastOk() || checksum < 0) {
return false;
}
const uint32_t expectedChecksum = blockChecksum.blockEnd(skip);
if ((int64_t)expectedChecksum != checksum) {
KFS_LOG_STREAM_ERROR <<
"record block checksum mismatch:"
" expected: " << expectedChecksum <<
" actual: " << checksum <<
KFS_LOG_EOM;
return false;
}
if (commitSeq < state.mLastBlockCommittedSeq ||
(commitSeq < state.mLastCommittedSeq &&
state.mCheckpointCommitted <= commitSeq &&
state.mLastNonLogCommit <= commitSeq &&
state.mViewStartSeq < commitSeq) ||
state.mLastLogAheadSeq < commitSeq ||
(state.mViewStartSeq == commitSeq &&
state.mViewStartSeq != MetaVrLogSeq(0, 0, 0))) {
KFS_LOG_STREAM_ERROR <<
"committed:"
" expected range: [" << state.mLastCommittedSeq <<
"," << state.mLastLogAheadSeq << "]"
" view start: " << state.mViewStartSeq <<
" actual: " << commitSeq <<
" previous: " << state.mLastBlockCommittedSeq <<
KFS_LOG_EOM;
return false;
}
if (! state.runCommitQueue(commitSeq, seed, status, errchksum)) {
return false;
}
if (0 != state.mSubEntryCount) {
return false;
}
state.mBlockStartLogSeq = logSeq;
state.mLastBlockSeq = blockSeq;
state.mLastBlockCommittedSeq = commitSeq;
state.mLastBlockSeed = seed;
state.mLastBlockStatus = status;
state.mLastBlockErrChecksum = errchksum;
if (state.mLastCommittedSeq < commitSeq) {
state.mLastCommittedSeq = commitSeq;
}
return true;
}
static bool
replay_group_users_reset(DETokenizer& c)
{
ReplayState& state = ReplayState::get(c);
if (c.empty() || state.mCurOp || ! state.mLastLogAheadSeq.IsValid()) {
return false;
}
c.pop_front();
if (c.empty()) {
return false;
}
const int64_t n = c.toNumber();
if (! c.isLastOk() || n < 0) {
return false;
}
c.pop_front();
state.mSubEntryCount = n;
state.mCurOp = new MetaSetGroupUsers(16 == c.getIntBase());
state.mCurOp->logseq = state.mLastLogAheadSeq;
state.mCurOp->logseq.mLogSeq++;
state.mCurOp->replayFlag = true;
if (state.mSubEntryCount <= 0) {
state.mSubEntryCount = 1;
state.replayCurOp();
return replay_sub_entry(c);
}
return true;
}
static bool
replay_group_users(DETokenizer& c)
{
ReplayState& state = ReplayState::get(c);
if (c.empty() || ! state.mCurOp ||
META_SET_GROUP_USERS != state.mCurOp->op) {
return false;
}
const bool appendFlag = 3 == c.front().len;
c.pop_front();
if (c.empty()) {
return false;
}
const DETokenizer::Token& token = c.front();
MetaSetGroupUsers& op = *static_cast<MetaSetGroupUsers*>(state.mCurOp);
op.AddEntry(appendFlag, token.ptr, token.len);
if (1 == state.mSubEntryCount) {
state.replayCurOp();
}
return replay_sub_entry(c);
}
static bool
replay_clear_obj_store_delete(DETokenizer& c)
{
c.pop_front();
gLayoutManager.ClearObjStoreDelete();
return true;
}
static bool
replay_cs_hello(DETokenizer& c)
{
const DETokenizer::Token& verb = c.front();
ReplayState& state = ReplayState::get(c);
MetaHello* op;
if (3 == verb.len) {
if (0 != state.mSubEntryCount) {
return false;
}
c.pop_front();
int64_t n;
if (! pop_num(n, "e", c, true) || n <= 0) {
return false;
}
if ("l" != c.front()) {
return false;
}
c.pop_front();
state.mSubEntryCount = n;
op = new MetaHello();
state.mCurOp = op;
op->replayFlag = true;
const DETokenizer::Token& loc = c.front();
if (! op->location.FromString(loc.ptr, loc.len, 16 == c.getIntBase())) {
return false;
}
c.pop_front();
if (! pop_num(n, "s", c, true) || n < 0) {
return false;
}
op->numChunks = (int)n;
if (! pop_num(n, "n", c, true) || n < 0) {
return false;
}
op->numNotStableChunks = (int)n;
if (! pop_num(n, "a", c, true) || n < 0) {
return false;
}
op->numNotStableAppendChunks = (int)n;
if (! pop_num(n, "m", c, true) || n < 0) {
return false;
}
op->numMissingChunks = (int)n;
if (pop_num(n, "p", c, true)) {
if (n < 0) {
return false;
}
op->numPendingStaleChunks = (int)n;
} else {
op->numPendingStaleChunks = 0;
}
if (! pop_num(n, "d", c, true) || n < 0) {
return false;
}
op->deletedCount = (size_t)n;
if (! pop_num(n, "r", c, true)) {
return false;
}
op->resumeStep = (int)n;
if (! pop_num(n, "t", c, true)) {
return false;
}
op->timeUsec = n;
if (! pop_num(n, "r", c, true)) {
return false;
}
op->rackId = (int)n;
if (! pop_num(n, "P", c, true)) {
return false;
}
op->pendingNotifyFlag = 0 != n;
n = 0;
if (! pop_num(n, "R", c, true)) {
return false;
}
op->supportsResumeFlag = 0 != n;
if (c.empty() || 1 != c.front().len || 'z' != c.front().ptr[0]) {
return false;
}
c.pop_front();
if (! parse_vr_log_seq(c, op->logseq) || ! op->logseq.IsValid()) {
return false;
}
c.pop_front();
if (state.mReplayer) {
MetaVrLogSeq next = state.mLastLogAheadSeq;
next.mLogSeq++;
if (op->logseq != next) {
return false;
}
}
op->chunks.reserve(op->numChunks);
op->notStableChunks.reserve(op->numNotStableChunks);
op->notStableAppendChunks.reserve(op->numNotStableAppendChunks);
op->missingChunks.reserve(op->numMissingChunks);
} else {
if (4 != verb.len || ! state.mCurOp) {
return false;
}
op = static_cast<MetaHello*>(state.mCurOp);
if ('c' == verb.ptr[3]) {
c.pop_front();
if (c.empty()) {
return false;
}
MetaHello::ChunkInfo info;
while (! c.empty()) {
info.chunkId = c.toNumber();
if (! c.isLastOk() || info.chunkId < 0) {
return false;
}
c.pop_front();
if (c.empty()) {
return false;
}
info.chunkVersion = c.toNumber();
if (! c.isLastOk() || info.chunkVersion < 0) {
return false;
}
c.pop_front();
if (op->chunks.size() < (size_t)op->numChunks) {
op->chunks.push_back(info);
} else if (op->notStableChunks.size() <
(size_t)op->numNotStableChunks) {
op->notStableChunks.push_back(info);
} else if (op->notStableAppendChunks.size() <
(size_t)op->numNotStableAppendChunks) {
op->notStableAppendChunks.push_back(info);
} else {
return false;
}
}
} else {
const int type = verb.ptr[3] & 0xFF;
if ('m' != type && 'p' != type) {
return false;
}
c.pop_front();
if (c.empty()) {
return false;
}
MetaHello::ChunkIdList& list = 'm' == type ?
op->missingChunks : op->pendingStaleChunks;
const size_t cnt = max(0, 'm' == type ?
op->numMissingChunks : op->numPendingStaleChunks);
while (! c.empty()) {
const int64_t n = c.toNumber();
if (! c.isLastOk() || n < 0) {
return false;
}
c.pop_front();
if (cnt <= list.size()) {
return false;
}
list.push_back(n);
}
}
}
if (1 == state.mSubEntryCount) {
if (op->chunks.size() != (size_t)op->numChunks ||
op->notStableChunks.size() != (size_t)op->numNotStableChunks ||
op->notStableAppendChunks.size() !=
(size_t)op->numNotStableAppendChunks ||
op->missingChunks.size() != (size_t)op->numMissingChunks ||
op->pendingStaleChunks.size() !=
(size_t)op->numPendingStaleChunks) {
return false;
}
state.replayCurOp();
}
return replay_sub_entry(c);
}
static bool
replay_cs_inflight(DETokenizer& c)
{
const DETokenizer::Token& verb = c.front();
ReplayState& state = ReplayState::get(c);
MetaChunkLogInFlight* op;
if (3 == verb.len && 's' == verb.ptr[2]) {
op = static_cast<MetaChunkLogInFlight*>(state.mCurOp);
if (! op) {
return false;
}
c.pop_front();
while (! c.empty()) {
const int64_t n = c.toNumber();
if (! c.isLastOk() || n < 0) {
return false;
}
c.pop_front();
if ((size_t)op->idCount <= op->chunkIds.Size()) {
return false;
}
op->chunkIds.Insert(n);
}
if (1 == state.mSubEntryCount &&
(size_t)op->idCount != op->chunkIds.Size()) {
return false;
}
} else {
if (0 != state.mSubEntryCount || state.mCurOp) {
return false;
}
c.pop_front();
int64_t n;
if (! pop_num(n, "e", c, true) || n <= 0) {
return false;
}
if ("l" != c.front()) {
return false;
}
c.pop_front();
state.mSubEntryCount = n;
op = new MetaChunkLogInFlight();
state.mCurOp = op;
op->replayFlag = true;
const DETokenizer::Token& loc = c.front();
if (! op->location.FromString(loc.ptr, loc.len, 16 == c.getIntBase())) {
return false;
}
c.pop_front();
if (! pop_num(n, "s", c, true) || n < 0) {
return false;
}
op->idCount = n;
if (! pop_num(n, "c", c, true) || (0 < op->idCount && 0 <= n)) {
return false;
}
op->chunkId = n;
if (! pop_num(n, "x", c, true) || n < 0) {
return false;
}
op->removeServerFlag = 0 != n;
if ("r" != c.front()) {
return false;
}
c.pop_front();
if (c.empty()) {
return false;
}
// Original request type, presently used for debugging.
const DETokenizer::Token& rtype = c.front();
op->reqType = MetaChunkLogInFlight::GetReqId(rtype.ptr, rtype.len);
c.pop_front();
if (! c.empty() && 'p' == c.front().ptr[0]) {
op->hadPendingChunkOpFlag = true;
c.pop_front();
}
if (1 != c.front().len || 'z' != c.front().ptr[0]) {
return false;
}
c.pop_front();
if (! parse_vr_log_seq(c, op->logseq) || ! op->logseq.IsValid()) {
return false;
}
c.pop_front();
if (state.mReplayer) {
MetaVrLogSeq next = state.mLastLogAheadSeq;
next.mLogSeq++;
if (next != op->logseq) {
return false;
}
}
}
if (1 == state.mSubEntryCount) {
state.replayCurOp();
}
return replay_sub_entry(c);
}
bool
restore_chunk_server_end(DETokenizer& c)
{
return replay_inc_seq(c);
}
static const DiskEntry&
get_entry_map()
{
static bool initied = false;
static DiskEntry e;
if (initied) {
return e;
}
e.add_parser("setintbase", &restore_setintbase);
e.add_parser("version", &replay_version);
e.add_parser("create", &replay_create);
e.add_parser("mkdir", &replay_mkdir);
e.add_parser("remove", &replay_remove);
e.add_parser("rmdir", &replay_rmdir);
e.add_parser("rename", &replay_rename);
e.add_parser("allocate", &replay_allocate);
e.add_parser("truncate", &replay_truncate);
e.add_parser("coalesce", &replay_coalesce);
e.add_parser("pruneFromHead", &replay_pruneFromHead);
e.add_parser("setrep", &replay_setrep);
e.add_parser("size", &replay_size);
e.add_parser("setmtime", &replay_setmtime);
e.add_parser("chunkVersionInc", &restore_chunkVersionInc);
e.add_parser("time", &replay_time);
e.add_parser("mkstable", &replay_mkstable);
e.add_parser("mkstabledone", &replay_mkstabledone);
e.add_parser("beginchunkversionchange", &replay_beginchunkversionchange);
e.add_parser("checksum", &restore_checksum);
e.add_parser("rollseeds", &replay_rollseeds);
e.add_parser("chmod", &replay_chmod);
e.add_parser("chown", &replay_chown);
e.add_parser("delegatecancel", &restore_delegate_cancel);
e.add_parser("filesysteminfo", &restore_filesystem_info);
e.add_parser("clearobjstoredelete", &replay_clear_obj_store_delete);
// Write ahead log entries.
e.add_parser("gur", &replay_group_users_reset);
e.add_parser("gu", &replay_group_users);
e.add_parser("guc", &replay_group_users);
e.add_parser("csh", &replay_cs_hello);
e.add_parser("cshc", &replay_cs_hello);
e.add_parser("cshm", &replay_cs_hello);
e.add_parser("cshp", &replay_cs_hello);
e.add_parser("cif", &replay_cs_inflight);
e.add_parser("cis", &replay_cs_inflight);
initied = true;
return e;
}
/* static */ void
Replay::AddRestotreEntries(DiskEntry& e)
{
e.add_parser("cif", &replay_cs_inflight);
e.add_parser("cis", &replay_cs_inflight);
}
Replay::BlockChecksum::BlockChecksum()
: skip(0),
checksum(kKfsNullChecksum)
{}
uint32_t
Replay::BlockChecksum::blockEnd(size_t s)
{
skip = s;
const uint32_t ret = checksum;
checksum = kKfsNullChecksum;
return ret;
}
bool
Replay::BlockChecksum::write(const char* buf, size_t len)
{
if (len <= skip) {
skip -= len;
} else {
checksum = ComputeBlockChecksum(checksum, buf + skip, len - skip);
skip = 0;
}
return true;
}
Replay::Tokenizer::Tokenizer(
istream& file, Replay* replay, bool* enqueueFlag)
: state(*(new Replay::State(replay, enqueueFlag))),
tokenizer(*(new DETokenizer(file, &state)))
{}
Replay::Tokenizer::~Tokenizer()
{
delete &tokenizer;
delete &state;
}
const DETokenizer::Token kAheadLogEntry ("a", 1);
const DETokenizer::Token kCommitLogEntry("c", 1);
Replay::Replay()
: file(),
path(),
number(-1),
lastLogNum(-1),
lastLogIntBase(-1),
appendToLastLogFlag(false),
verifyAllLogSegmentsPresetFlag(false),
enqueueFlag(false),
replayTokenizer(file, this, &enqueueFlag),
checkpointCommitted(replayTokenizer.GetState().mCheckpointCommitted),
committed(replayTokenizer.GetState().mLastCommittedSeq),
lastLogStart(checkpointCommitted),
lastLogSeq(replayTokenizer.GetState().mLastLogAheadSeq),
viewStartSeq(replayTokenizer.GetState().mViewStartSeq),
lastBlockSeq(replayTokenizer.GetState().mLastBlockSeq),
errChecksum(replayTokenizer.GetState().mLogAheadErrChksum),
lastCommittedStatus(replayTokenizer.GetState().mLastCommittedStatus),
rollSeeds(0),
tmplogprefixlen(0),
tmplogname(),
logdir(),
mds(),
entrymap(get_entry_map()),
blockChecksum(),
maxLogNum(-1),
logSeqStartNum(-1),
primaryNodeId(-1),
buffer()
{
buffer.Reserve(16 << 10);
}
Replay::~Replay()
{}
int
Replay::playLine(const char* line, int len, seq_t blockSeq)
{
if (len <= 0) {
return 0;
}
DETokenizer& tokenizer = replayTokenizer.Get();
ReplayState& state = replayTokenizer.GetState();
ReplayState::EnterAndLeave enterAndLeave(state);
tokenizer.setIntBase(16);
if (0 <= blockSeq) {
state.mLastBlockSeq = blockSeq - 1;
}
int status = 0;
if (! tokenizer.next(line, len)) {
status = -EINVAL;
}
if (0 == status && ! tokenizer.empty()) {
if (! (kAheadLogEntry == tokenizer.front() ?
replay_log_ahead_entry(tokenizer) :
(kCommitLogEntry == tokenizer.front() ?
replay_log_commit_entry(tokenizer, blockChecksum) :
entrymap.parse(tokenizer)))) {
KFS_LOG_STREAM_ERROR <<
"error block seq: " << blockSeq <<
":" << tokenizer.getEntryCount() <<
":" << tokenizer.getEntry() <<
KFS_LOG_EOM;
status = -EINVAL;
}
}
if (0 <= blockSeq || 0 != status) {
blockChecksum.blockEnd(0);
blockChecksum.write("\n", 1);
if (state.mSubEntryCount != 0 && 0 == status) {
KFS_LOG_STREAM_ERROR <<
"invalid block commit:"
" sub entry count: " << state.mSubEntryCount <<
KFS_LOG_EOM;
state.mSubEntryCount = 0;
status = -EINVAL;
// Next block implicitly includes leading new line.
tokenizer.resetEntryCount();
}
} else {
blockChecksum.write(line, len);
}
return status;
}
/*!
* \brief replay contents of log file
* \return zero if replay successful, negative otherwise
*/
int
Replay::playlog(bool& lastEntryChecksumFlag)
{
restoreChecksum.clear();
lastLineChecksumFlag = false;
lastEntryChecksumFlag = false;
blockChecksum.blockEnd(0);
mds.Reset(&blockChecksum);
mds.SetWriteTrough(true);
if (! file.is_open()) {
//!< no log...so, reset the # to 0.
number = 0;
return 0;
}
ReplayState& state = replayTokenizer.GetState();
lastLogStart = state.mLastLogAheadSeq;
state.mLastBlockSeq = -1;
state.mSubEntryCount = 0;
int status = 0;
DETokenizer& tokenizer = replayTokenizer.Get();
tokenizer.reset();
while (tokenizer.next(&mds)) {
if (tokenizer.empty()) {
continue;
}
if (! (kAheadLogEntry == tokenizer.front() ?
replay_log_ahead_entry(tokenizer) :
(kCommitLogEntry == tokenizer.front() ?
replay_log_commit_entry(tokenizer, blockChecksum) :
entrymap.parse(tokenizer)))) {
KFS_LOG_STREAM_FATAL <<
"error " << path <<
":" << tokenizer.getEntryCount() <<
":" << tokenizer.getEntry() <<
KFS_LOG_EOM;
status = -EINVAL;
break;
}
lastEntryChecksumFlag = ! restoreChecksum.empty();
if (lastEntryChecksumFlag) {
const string md = mds.GetMd();
if (md != restoreChecksum) {
KFS_LOG_STREAM_FATAL <<
"error " << path <<
":" << tokenizer.getEntryCount() <<
":" << tokenizer.getEntry() <<
": checksum mismatch:"
" expectd:" << restoreChecksum <<
" computed: " << md <<
KFS_LOG_EOM;
status = -EINVAL;
break;
}
restoreChecksum.clear();
}
}
if (0 == status && 0 != state.mSubEntryCount) {
KFS_LOG_STREAM_FATAL <<
"error " << path <<
" invalid sub entry count: " << state.mSubEntryCount <<
KFS_LOG_EOM;
status = -EIO;
}
if (0 == status && ! file.eof()) {
KFS_LOG_STREAM_FATAL <<
"error " << path <<
":" << tokenizer.getEntryCount() <<
":" << tokenizer.getEntry() <<
KFS_LOG_EOM;
status = -EIO;
}
if (0 == status) {
lastLogIntBase = tokenizer.getIntBase();
mds.SetStream(0);
}
file.close();
blockChecksum.blockEnd(0);
blockChecksum.write("\n", 1);
tokenizer.resetEntryCount();
return status;
}
/*!
* \brief replay contents of all log files since CP
* \return zero if replay successful, negative otherwise
*/
int
Replay::playLogs(bool includeLastLogFlag)
{
if (number < 0) {
//!< no log...so, reset the # to 0.
number = 0;
appendToLastLogFlag = false;
return 0;
}
gLayoutManager.SetPrimary(false);
gLayoutManager.StopServicing();
const int status = getLastLogNum();
return (0 == status ?
playLogs(lastLogNum, includeLastLogFlag) : status);
}
int
Replay::playLogs(seq_t last, bool includeLastLogFlag)
{
ReplayState& state = replayTokenizer.GetState();
ReplayState::EnterAndLeave enterAndLeave(state);
appendToLastLogFlag = false;
lastLineChecksumFlag = false;
lastLogIntBase = -1;
bool lastEntryChecksumFlag = false;
bool completeSegmentFlag = true;
int status = 0;
state.mCheckpointFileIdSeed = fileID.getseed();
state.mCheckpointErrChksum = errChecksum;
state.mBlockStartLogSeq = checkpointCommitted;
state.mLastNonEmptyViewEndSeq = checkpointCommitted;
state.mUpdateLogWriterFlag = false; // Turn off updates in initial replay.
for (seq_t i = number; ; i++) {
if (! includeLastLogFlag && last < i) {
break;
}
// Check if the next log segment exists prior to loading current log
// segment in order to allow fsck to load all segments while meta server
// is running. The meta server might close the current segment, and
// create the new segment after reading / loading tail of the current
// segment, in which case the last read might not have the last checksum
// line.
if (last < i && maxLogNum <= i) {
completeSegmentFlag = ! logSegmentHasLogSeq(i + 1) &&
file_exists(logfile(i + 1));
if (! completeSegmentFlag && maxLogNum < i &&
! file_exists(logfile(i))) {
break;
}
}
state.mRestoreTimeCount = 0;
const string logfn = logfile(i);
if ((status = openlog(logfn)) != 0 ||
(status = playlog(lastEntryChecksumFlag)) != 0) {
break;
}
if (state.mRestoreTimeCount <= 0) {
// "time/" is the last line of the header.
// Each valid log even last partial must have
// complete header.
KFS_LOG_STREAM_FATAL <<
logfn <<
": missing \"time\" line" <<
KFS_LOG_EOM;
status = -EINVAL;
break;
}
if (lastLineChecksumFlag &&
(! lastEntryChecksumFlag && completeSegmentFlag)) {
KFS_LOG_STREAM_FATAL <<
logfn <<
": missing last line checksum" <<
KFS_LOG_EOM;
status = -EINVAL;
break;
}
number = i;
if (last < i && ! lastEntryChecksumFlag) {
appendToLastLogFlag = true;
break;
}
}
// Enable updates, and reset primary node id at the end of replay.
state.mUpdateLogWriterFlag = true;
primaryNodeId = -1;
if (0 == status) {
if (state.mCommitQueue.empty() &&
state.mLastBlockCommittedSeq == MetaVrLogSeq(0, 0, 0) &&
state.mLastLogAheadSeq == state.mLastCommittedSeq &&
state.mLastBlockCommittedSeq <= state.mLastCommittedSeq &&
0 == state.mLastBlockSeed &&
0 == state.mLastBlockErrChecksum &&
0 == state.mLastBlockStatus) {
// Set commit state, when converting from prior log version.
state.mLastBlockSeed = fileID.getseed();
state.mLastBlockCommittedSeq = state.mLastCommittedSeq;
appendToLastLogFlag = false;
}
} else {
appendToLastLogFlag = false;
}
return status;
}
static int
ValidateLogSegmentTrailer(
const char* name,
bool completeSegmentFlag)
{
int ret = 0;
streamoff const kTailSize = 1 << 10;
streamoff pos = -1;
ifstream fs(name, ifstream::in | ifstream::binary);
if (fs && fs.seekg(0, ifstream::end) && 0 <= (pos = fs.tellg())) {
streamoff sz;
if (kTailSize < pos) {
sz = kTailSize;
pos -= kTailSize;
} else {
sz = pos;
pos = 0;
}
StBufferT<char, 1> buf;
char* const ptr = buf.Resize(sz + streamoff(1));
if (fs.seekg(pos, ifstream::beg) && fs.read(ptr, sz)) {
if (sz != fs.gcount()) {
KFS_LOG_STREAM_FATAL <<
name << ": "
"invalid read size:"
" actual: " << fs.gcount() <<
" expected: " << sz <<
KFS_LOG_EOM;
ret = -EIO;
} else {
ptr[sz] = 0;
const char* p = ptr + sz - 1;
const char* const b = ptr;
if (p <= b || '\n' != *p) {
ret = -EINVAL;
KFS_LOG_STREAM_FATAL <<
name << ": no trailing new line: " <<
ptr <<
KFS_LOG_EOM;
} else {
// Last line must start with log block trailer
// if segment is not complete / closed or checksum line
// otherwise.
--p;
while (b < p && '\n' != *p) {
--p;
}
if (p <= b ||
((completeSegmentFlag || ptr + sz < p + 3 ||
0 != memcmp("c/", p + 1, 2)) &&
(ptr + sz < p + 10 ||
0 != memcmp("checksum/", p + 1, 9)))) {
KFS_LOG_STREAM_FATAL <<
name << ": invalid log segment trailer: " <<
(p + 1) <<
KFS_LOG_EOM;
ret = -EINVAL;
}
}
}
}
}
if (0 == ret && (! fs || pos < 0)) {
const int err = errno;
KFS_LOG_STREAM_FATAL <<
name << ": " << QCUtils::SysError(err) <<
KFS_LOG_EOM;
ret = 0 < err ? -err : (err == 0 ? -EIO : err);
}
fs.close();
return ret;
}
typedef map<
seq_t,
string,
less<seq_t>,
StdFastAllocator<pair<const seq_t, string> >
> LogSegmentNumbers;
int
Replay::getLastLogNum()
{
if (0 <= lastLogNum) {
return 0;
}
lastLogNum = number;
maxLogNum = -1;
logSeqStartNum = -1;
if (lastLogNum < 0) {
// no logs, to replay.
return 0;
}
// Get last complete log number. All log files before and including this
// won't ever be written to again.
// Get the inode # for the last file
const string lastlog = getLastLog();
struct stat lastst = {0};
if (stat(lastlog.c_str(), &lastst)) {
const int err = errno;
if (ENOENT == err) {
lastLogNum = -1; // Checkpoint with single log segment.
} else {
KFS_LOG_STREAM_FATAL <<
lastlog <<
": " << QCUtils::SysError(err) <<
KFS_LOG_EOM;
return (0 < err ? -err : (err == 0 ? -EIO : err));
}
}
if (0 <= lastLogNum && lastst.st_nlink != 2) {
KFS_LOG_STREAM_FATAL <<
lastlog <<
": invalid link count: " << lastst.st_nlink <<
" this must be \"hard\" link to the last complete log"
" segment (usually the last log segment with last line starting"
" with \"checksum/\" prefix), and therefore must have link"
" count 2" <<
KFS_LOG_EOM;
return -EINVAL;
}
string dirName = lastlog;
string::size_type pos = dirName.rfind('/');
const char* lastName = lastlog.c_str();
if (string::npos != pos) {
lastName += pos + 1;
if (pos <= 0) {
dirName = "/";
} else {
dirName.erase(pos);
}
} else {
dirName = ".";
}
DIR* const dir = opendir(dirName.c_str());
if (! dir) {
const int err = errno;
KFS_LOG_STREAM_FATAL <<
dirName << ": " << QCUtils::SysError(err) <<
KFS_LOG_EOM;
return (err > 0 ? -err : (err == 0 ? -1 : err));
}
int ret = 0;
LogSegmentNumbers logNums;
const struct dirent* ent;
while ((ent = readdir(dir))) {
if (strcmp(ent->d_name, lastName) == 0) {
continue;
}
const char* const p = strrchr(ent->d_name, '.');
const int64_t num = p ? toNumber(p + 1) : int64_t(-1);
if (0 <= lastLogNum && lastst.st_ino == ent->d_ino) {
lastLogNum = num;
if (num < 0) {
KFS_LOG_STREAM_FATAL <<
"invalid log segment name: " <<
dirName << "/" << ent->d_name <<
KFS_LOG_EOM;
ret = -EINVAL;
break;
}
}
if (num < 0) {
continue;
}
// Find first, if any, log segment number in the form
// log.<log sequence>.<log number>
const char* s = p;
while (ent->d_name <= --s) {
const int sym = *s & 0xFF;
if ('.' == sym) {
if (s + 1 < p && p <= s + 22) {
logSeqStartNum = logSeqStartNum < 0 ? num :
min(num, logSeqStartNum);
}
break;
}
if (sym < '0' || '9' < sym) {
break;
}
}
if (lastLogNum < 0 && number < num) {
KFS_LOG_STREAM_FATAL <<
"no link to last complete log segment: " << lastlog <<
KFS_LOG_EOM;
ret = -EINVAL;
break;
}
if ((verifyAllLogSegmentsPresetFlag || number <= num) &&
! logNums.insert(make_pair(num, ent->d_name)).second) {
KFS_LOG_STREAM_FATAL <<
"duplicate log segment number: " << num <<
" " << dirName << "/" << ent->d_name <<
KFS_LOG_EOM;
ret = -EINVAL;
break;
}
if (maxLogNum < num) {
maxLogNum = num;
}
}
closedir(dir);
if (0 == ret && maxLogNum < 0) {
KFS_LOG_STREAM_FATAL <<
"no log segments found: " << dirName <<
KFS_LOG_EOM;
ret = -EINVAL;
}
LogSegmentNumbers::const_iterator it = logNums.begin();
if (logNums.end() == it || (verifyAllLogSegmentsPresetFlag ?
logNums.find(number) == logNums.end() : it->first != number)) {
KFS_LOG_STREAM_FATAL <<
"missing log segmnet: " << number <<
KFS_LOG_EOM;
ret = -EINVAL;
} else {
seq_t n = it->first;
while (logNums.end() != ++it) {
if (++n != it->first) {
KFS_LOG_STREAM_FATAL <<
"missing log segmnets:"
" from: " << n <<
" to: " << it->first <<
KFS_LOG_EOM;
n = it->first;
ret = -EINVAL;
}
}
}
if (0 == ret && 0 <= logSeqStartNum) {
it = logNums.find(logSeqStartNum);
string name;
while (logNums.end() != it) {
name = dirName + "/" + it->second;
++it;
if (0 != (ret = ValidateLogSegmentTrailer(
name.c_str(), logNums.end() != it))) {
break;
}
}
}
return ret;
}
void
Replay::handle(MetaVrLogStartView& op)
{
if (op.mHandledFlag) {
return;
}
op.mHandledFlag = true;
if (0 != op.status) {
if (op.replayFlag) {
return;
}
if (! IsMetaLogWriteOrVrError(op.status)) {
panic("replay: invalid start view op status");
}
return;
}
ReplayState& state = replayTokenizer.GetState();
ReplayState::EnterAndLeave enterAndLeave(state,
(op.replayFlag || enqueueFlag) ? 1 : 0);
state.handleStartView(op);
if (op.replayFlag) {
if (0 == op.status) {
gLayoutManager.SetPrimary(false);
gLayoutManager.StopServicing();
primaryNodeId = op.mNodeId;
if (state.mLastLogAheadSeq == op.mNewLogSeq) {
// Decrement to account incSeq() at the end of state handle
// method
state.mLastLogAheadSeq.mLogSeq--;
}
}
} else {
if (0 != op.status || ! op.Validate() ||
state.mViewStartSeq != op.mNewLogSeq ||
! state.mCommitQueue.empty()) {
panic("replay: invalid start view op completion");
return;
}
gLayoutManager.SetPrimary(true);
gLayoutManager.StartServicing();
primaryNodeId = -1;
}
}
void
Replay::setReplayState(
const MetaVrLogSeq& committed,
const MetaVrLogSeq& viewStartSeq,
seq_t seed,
int status,
int64_t errChecksum,
MetaRequest* commitQueue,
const MetaVrLogSeq& lastBlockCommitted,
fid_t lastBlockSeed,
int lastBlockStatus,
int64_t lastBlockErrChecksum,
const MetaVrLogSeq& lastNonEmptyViewEndSeq)
{
ReplayState& state = replayTokenizer.GetState();
ReplayState::EnterAndLeave enterAndLeave(state);
// Enqeue all new ops into replay.
// Log start view recursion counter now must be 1 when entering
// handle(MetaVrLogStartView&)
enqueueFlag = true;
gLayoutManager.SetPrimary(false);
gLayoutManager.StopServicing();
state.setReplayState(
committed,
viewStartSeq,
seed,
status,
errChecksum,
commitQueue,
lastBlockCommitted,
lastBlockSeed,
lastBlockStatus,
lastBlockErrChecksum,
lastNonEmptyViewEndSeq
);
}
bool
Replay::runCommitQueue(
const MetaVrLogSeq& committed,
seq_t seed,
int64_t status,
int64_t errChecksum)
{
ReplayState& state = replayTokenizer.GetState();
ReplayState::EnterAndLeave enterAndLeave(state);
const bool okFlag = state.runCommitQueue(
committed, seed, status, errChecksum);
if (okFlag) {
state.mLastNonLogCommit = state.mLastCommittedSeq;
}
return okFlag;
}
bool
Replay::commitAll()
{
ReplayState& state = replayTokenizer.GetState();
ReplayState::EnterAndLeave enterAndLeave(state);
gLayoutManager.SetPrimary(true);
return replayTokenizer.GetState().commitAll();
}
bool
Replay::enqueue(MetaRequest& req)
{
ReplayState& state = replayTokenizer.GetState();
ReplayState::EnterAndLeave enterAndLeave(state);
return state.enqueue(req);
}
void
Replay::handle(MetaLogWriterControl& op)
{
if (0 != op.status || MetaLogWriterControl::kWriteBlock != op.type) {
return;
}
KFS_LOG_STREAM_DEBUG <<
"replaying: " << op.Show() <<
KFS_LOG_EOM;
const int* lenPtr = op.blockLines.GetPtr();
const int* const lendEndPtr = lenPtr + op.blockLines.GetSize();
while (lenPtr < lendEndPtr) {
int lineLen = *lenPtr++;
IOBuffer::BufPos len = lineLen;
const char* linePtr;
int trLen;
if (lendEndPtr == lenPtr && 0 < (trLen = op.blockTrailer[0] & 0xFF)) {
if (sizeof(op.blockTrailer) <= (size_t)trLen) {
const char* const kErrMsg =
"replay: invalid write op trailer length";
panic(kErrMsg);
op.status = -EFAULT;
op.statusMsg = kErrMsg;
break;
}
if (lineLen <= 0) {
linePtr = op.blockTrailer + 1;
len = trLen;
lineLen = trLen;
} else {
lineLen += trLen;
char* const ptr = buffer.Reserve(lineLen);
len = op.blockData.CopyOut(ptr, len);
memcpy(ptr + len, op.blockTrailer + 1, trLen);
len += trLen;
linePtr = ptr;
}
} else {
if (len <= 0) {
continue;
}
trLen = 0;
linePtr = op.blockData.CopyOutOrGetBufPtr(
buffer.Reserve(lineLen), len);
}
if (len != lineLen) {
const char* const kErrMsg = "replay: invalid write op line length";
panic(kErrMsg);
op.status = -EFAULT;
op.statusMsg = kErrMsg;
break;
}
const int status = playLine(
linePtr,
len,
lenPtr < lendEndPtr ? seq_t(-1) : op.blockSeq
);
if (status != 0) {
char* const trailerPtr = buffer.Reserve(trLen + 1);
memcpy(trailerPtr, op.blockTrailer + 1, trLen);
trailerPtr[trLen] = 0;
const char* const kErrMsg = "replay: log block apply failure";
KFS_LOG_STREAM_FATAL <<
kErrMsg << ":"
" " << op.Show() <<
" commit: " << op.blockCommitted <<
" status: " << status <<
" line: " <<
IOBuffer::DisplayData(op.blockData, len - trLen) <<
trailerPtr <<
KFS_LOG_EOM;
panic(kErrMsg);
op.status = -EFAULT;
op.statusMsg = kErrMsg;
}
op.blockData.Consume(len);
}
}
void
Replay::getLastLogBlockCommitted(
MetaVrLogSeq& outCommitted,
fid_t& outSeed,
int& outStatus,
int64_t& outErrChecksum) const
{
const ReplayState& state = replayTokenizer.GetState();
outCommitted = state.mLastBlockCommittedSeq;
outSeed = state.mLastBlockSeed;
outStatus = state.mLastBlockStatus;
outErrChecksum = state.mLastBlockErrChecksum;
}
MetaVrLogSeq
Replay::getLastNonEmptyViewEndSeq() const
{
const ReplayState& state = replayTokenizer.GetState();
return state.mLastNonEmptyViewEndSeq;
}
void
Replay::getReplayCommitQueue(Replay::CommitQueue& queue) const
{
const ReplayState& state = replayTokenizer.GetState();
return state.getReplayCommitQueue(queue);
}
void
Replay::updateLastBlockSeed()
{
ReplayState& state = replayTokenizer.GetState();
state.mLastBlockSeed = fileID.getseed();
}
} // namespace KFS
| 48,497 |
421 |
<reponame>hamarb123/dotnet-api-docs
//<Snippet1>
#using <System.Drawing.dll>
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
//<Snippet2>
public ref class CustomizedTreeView: public TreeView
{
public:
CustomizedTreeView()
{
// Customize the TreeView control by setting various properties.
BackColor = System::Drawing::Color::CadetBlue;
FullRowSelect = true;
HotTracking = true;
Indent = 34;
ShowPlusMinus = false;
// The ShowLines property must be false for the FullRowSelect
// property to work.
ShowLines = false;
}
protected:
virtual void OnAfterSelect( TreeViewEventArgs^ e ) override
{
// Confirm that the user initiated the selection.
// This prevents the first node from expanding when it is
// automatically selected during the initialization of
// the TreeView control.
if ( e->Action != TreeViewAction::Unknown )
{
if ( e->Node->IsExpanded )
{
e->Node->Collapse();
}
else
{
e->Node->Expand();
}
}
// Remove the selection. This allows the same node to be
// clicked twice in succession to toggle the expansion state.
SelectedNode = nullptr;
}
};
//</Snippet2>
public ref class Form1: public System::Windows::Forms::Form
{
public:
Form1()
{
// Initialize myTreeView.
CustomizedTreeView^ myTreeView = gcnew CustomizedTreeView;
myTreeView->Dock = DockStyle::Fill;
// Add nodes to myTreeView.
TreeNode^ node;
for ( int x = 0; x < 3; ++x )
{
// Add a root node.
node = myTreeView->Nodes->Add( String::Format( "Node{0}", x * 4 ) );
for ( int y = 1; y < 4; ++y )
{
// Add a node as a child of the previously added node.
node = node->Nodes->Add( String::Format( "Node{0}", x * 4 + y ) );
}
}
// Add myTreeView to the form.
this->Controls->Add( myTreeView );
}
};
int main()
{
Application::Run( gcnew Form1 );
}
//</Snippet1>
| 1,012 |
480 |
<reponame>weicao/galaxysql
/*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.druid.sql.ast.statement;
import com.alibaba.polardbx.druid.sql.ast.SQLExpr;
import com.alibaba.polardbx.druid.sql.ast.SQLName;
import com.alibaba.polardbx.druid.sql.ast.SQLStatementImpl;
import com.alibaba.polardbx.druid.sql.visitor.SQLASTVisitor;
import java.util.ArrayList;
import java.util.List;
public class SQLCopyFromStatement extends SQLStatementImpl {
private SQLExprTableSource table;
private final List<SQLName> columns = new ArrayList<SQLName>();
private SQLExpr from;
private SQLExpr accessKeyId;
private SQLExpr accessKeySecret;
private final List<SQLAssignItem> options = new ArrayList<SQLAssignItem>();
private final List<SQLAssignItem> partitions = new ArrayList<SQLAssignItem>();
@Override
protected void accept0(SQLASTVisitor v) {
if (v.visit(this)) {
acceptChild(v, table);
acceptChild(v, columns);
acceptChild(v, partitions);
acceptChild(v, from);
acceptChild(v, options);
}
v.endVisit(this);
}
public SQLExprTableSource getTable() {
return table;
}
public void setTable(SQLExprTableSource x) {
if (x != null) {
x.setParent(this);
}
this.table = x;
}
public List<SQLName> getColumns() {
return columns;
}
public SQLExpr getFrom() {
return from;
}
public void setFrom(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.from = x;
}
public SQLExpr getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.accessKeyId = x;
}
public SQLExpr getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.accessKeySecret = x;
}
public List<SQLAssignItem> getOptions() {
return options;
}
public List<SQLAssignItem> getPartitions() {
return partitions;
}
}
| 1,164 |
716 |
<filename>runtime/libpgmath/lib/generic/rpowr.c
/*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*/
#include "mthdecls.h"
float
__mth_i_rpowr(float arg1, float arg2)
{
float f;
f = powf(arg1, arg2);
return f;
}
| 151 |
374 |
/* $OpenBSD: scheduler_proc.c,v 1.9 2021/06/14 17:58:16 eric Exp $ */
/*
* Copyright (c) 2013 <NAME> <<EMAIL>>
*
* 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 DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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 "includes.h"
#include <sys/types.h>
#include <sys/queue.h>
#include <sys/tree.h>
#include <sys/socket.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>
#include "smtpd.h"
#include "log.h"
static struct imsgbuf ibuf;
static struct imsg imsg;
static size_t rlen;
static char *rdata;
static void
scheduler_proc_call(void)
{
ssize_t n;
if (imsg_flush(&ibuf) == -1) {
log_warn("warn: scheduler-proc: imsg_flush");
fatalx("scheduler-proc: exiting");
}
while (1) {
if ((n = imsg_get(&ibuf, &imsg)) == -1) {
log_warn("warn: scheduler-proc: imsg_get");
break;
}
if (n) {
rlen = imsg.hdr.len - IMSG_HEADER_SIZE;
rdata = imsg.data;
if (imsg.hdr.type != PROC_SCHEDULER_OK) {
log_warnx("warn: scheduler-proc: bad response");
break;
}
return;
}
if ((n = imsg_read(&ibuf)) == -1 && errno != EAGAIN) {
log_warn("warn: scheduler-proc: imsg_read");
break;
}
if (n == 0) {
log_warnx("warn: scheduler-proc: pipe closed");
break;
}
}
fatalx("scheduler-proc: exiting");
}
static void
scheduler_proc_read(void *dst, size_t len)
{
if (len > rlen) {
log_warnx("warn: scheduler-proc: bad msg len");
fatalx("scheduler-proc: exiting");
}
memmove(dst, rdata, len);
rlen -= len;
rdata += len;
}
static void
scheduler_proc_end(void)
{
if (rlen) {
log_warnx("warn: scheduler-proc: bogus data");
fatalx("scheduler-proc: exiting");
}
imsg_free(&imsg);
}
/*
* API
*/
static int
scheduler_proc_init(const char *conf)
{
int fd, r;
uint32_t version;
fd = fork_proc_backend("scheduler", conf, "scheduler-proc");
if (fd == -1)
fatalx("scheduler-proc: exiting");
imsg_init(&ibuf, fd);
version = PROC_SCHEDULER_API_VERSION;
imsg_compose(&ibuf, PROC_SCHEDULER_INIT, 0, 0, -1,
&version, sizeof(version));
scheduler_proc_call();
scheduler_proc_read(&r, sizeof(r));
scheduler_proc_end();
return (1);
}
static int
scheduler_proc_insert(struct scheduler_info *si)
{
int r;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_INSERT");
imsg_compose(&ibuf, PROC_SCHEDULER_INSERT, 0, 0, -1, si, sizeof(*si));
scheduler_proc_call();
scheduler_proc_read(&r, sizeof(r));
scheduler_proc_end();
return (r);
}
static size_t
scheduler_proc_commit(uint32_t msgid)
{
size_t s;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_COMMIT");
imsg_compose(&ibuf, PROC_SCHEDULER_COMMIT, 0, 0, -1,
&msgid, sizeof(msgid));
scheduler_proc_call();
scheduler_proc_read(&s, sizeof(s));
scheduler_proc_end();
return (s);
}
static size_t
scheduler_proc_rollback(uint32_t msgid)
{
size_t s;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_ROLLBACK");
imsg_compose(&ibuf, PROC_SCHEDULER_ROLLBACK, 0, 0, -1,
&msgid, sizeof(msgid));
scheduler_proc_call();
scheduler_proc_read(&s, sizeof(s));
scheduler_proc_end();
return (s);
}
static int
scheduler_proc_update(struct scheduler_info *si)
{
int r;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_UPDATE");
imsg_compose(&ibuf, PROC_SCHEDULER_UPDATE, 0, 0, -1, si, sizeof(*si));
scheduler_proc_call();
scheduler_proc_read(&r, sizeof(r));
if (r == 1)
scheduler_proc_read(si, sizeof(*si));
scheduler_proc_end();
return (r);
}
static int
scheduler_proc_delete(uint64_t evpid)
{
int r;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_DELETE");
imsg_compose(&ibuf, PROC_SCHEDULER_DELETE, 0, 0, -1,
&evpid, sizeof(evpid));
scheduler_proc_call();
scheduler_proc_read(&r, sizeof(r));
scheduler_proc_end();
return (r);
}
static int
scheduler_proc_hold(uint64_t evpid, uint64_t holdq)
{
struct ibuf *buf;
int r;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_HOLD");
buf = imsg_create(&ibuf, PROC_SCHEDULER_HOLD, 0, 0,
sizeof(evpid) + sizeof(holdq));
if (buf == NULL)
return (-1);
if (imsg_add(buf, &evpid, sizeof(evpid)) == -1)
return (-1);
if (imsg_add(buf, &holdq, sizeof(holdq)) == -1)
return (-1);
imsg_close(&ibuf, buf);
scheduler_proc_call();
scheduler_proc_read(&r, sizeof(r));
scheduler_proc_end();
return (r);
}
static int
scheduler_proc_release(int type, uint64_t holdq, int n)
{
struct ibuf *buf;
int r;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_RELEASE");
buf = imsg_create(&ibuf, PROC_SCHEDULER_RELEASE, 0, 0,
sizeof(holdq) + sizeof(n));
if (buf == NULL)
return (-1);
if (imsg_add(buf, &type, sizeof(type)) == -1)
return (-1);
if (imsg_add(buf, &holdq, sizeof(holdq)) == -1)
return (-1);
if (imsg_add(buf, &n, sizeof(n)) == -1)
return (-1);
imsg_close(&ibuf, buf);
scheduler_proc_call();
scheduler_proc_read(&r, sizeof(r));
scheduler_proc_end();
return (r);
}
static int
scheduler_proc_batch(int typemask, int *delay, size_t *count, uint64_t *evpids, int *types)
{
struct ibuf *buf;
int r;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_BATCH");
buf = imsg_create(&ibuf, PROC_SCHEDULER_BATCH, 0, 0,
sizeof(typemask) + sizeof(*count));
if (buf == NULL)
return (-1);
if (imsg_add(buf, &typemask, sizeof(typemask)) == -1)
return (-1);
if (imsg_add(buf, count, sizeof(*count)) == -1)
return (-1);
imsg_close(&ibuf, buf);
scheduler_proc_call();
scheduler_proc_read(&r, sizeof(r));
scheduler_proc_read(delay, sizeof(*delay));
scheduler_proc_read(count, sizeof(*count));
if (r > 0) {
scheduler_proc_read(evpids, sizeof(*evpids) * (*count));
scheduler_proc_read(types, sizeof(*types) * (*count));
}
scheduler_proc_end();
return (r);
}
static size_t
scheduler_proc_messages(uint32_t from, uint32_t *dst, size_t size)
{
struct ibuf *buf;
size_t s;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_MESSAGES");
buf = imsg_create(&ibuf, PROC_SCHEDULER_MESSAGES, 0, 0,
sizeof(from) + sizeof(size));
if (buf == NULL)
return (-1);
if (imsg_add(buf, &from, sizeof(from)) == -1)
return (-1);
if (imsg_add(buf, &size, sizeof(size)) == -1)
return (-1);
imsg_close(&ibuf, buf);
scheduler_proc_call();
s = rlen / sizeof(*dst);
scheduler_proc_read(dst, s * sizeof(*dst));
scheduler_proc_end();
return (s);
}
static size_t
scheduler_proc_envelopes(uint64_t from, struct evpstate *dst, size_t size)
{
struct ibuf *buf;
size_t s;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_ENVELOPES");
buf = imsg_create(&ibuf, PROC_SCHEDULER_ENVELOPES, 0, 0,
sizeof(from) + sizeof(size));
if (buf == NULL)
return (-1);
if (imsg_add(buf, &from, sizeof(from)) == -1)
return (-1);
if (imsg_add(buf, &size, sizeof(size)) == -1)
return (-1);
imsg_close(&ibuf, buf);
scheduler_proc_call();
s = rlen / sizeof(*dst);
scheduler_proc_read(dst, s * sizeof(*dst));
scheduler_proc_end();
return (s);
}
static int
scheduler_proc_schedule(uint64_t evpid)
{
int r;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_SCHEDULE");
imsg_compose(&ibuf, PROC_SCHEDULER_SCHEDULE, 0, 0, -1,
&evpid, sizeof(evpid));
scheduler_proc_call();
scheduler_proc_read(&r, sizeof(r));
scheduler_proc_end();
return (r);
}
static int
scheduler_proc_remove(uint64_t evpid)
{
int r;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_REMOVE");
imsg_compose(&ibuf, PROC_SCHEDULER_REMOVE, 0, 0, -1,
&evpid, sizeof(evpid));
scheduler_proc_call();
scheduler_proc_read(&r, sizeof(r));
scheduler_proc_end();
return (r);
}
static int
scheduler_proc_suspend(uint64_t evpid)
{
int r;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_SUSPEND");
imsg_compose(&ibuf, PROC_SCHEDULER_SUSPEND, 0, 0, -1,
&evpid, sizeof(evpid));
scheduler_proc_call();
scheduler_proc_read(&r, sizeof(r));
scheduler_proc_end();
return (r);
}
static int
scheduler_proc_resume(uint64_t evpid)
{
int r;
log_debug("debug: scheduler-proc: PROC_SCHEDULER_RESUME");
imsg_compose(&ibuf, PROC_SCHEDULER_RESUME, 0, 0, -1,
&evpid, sizeof(evpid));
scheduler_proc_call();
scheduler_proc_read(&r, sizeof(r));
scheduler_proc_end();
return (r);
}
struct scheduler_backend scheduler_backend_proc = {
scheduler_proc_init,
scheduler_proc_insert,
scheduler_proc_commit,
scheduler_proc_rollback,
scheduler_proc_update,
scheduler_proc_delete,
scheduler_proc_hold,
scheduler_proc_release,
scheduler_proc_batch,
scheduler_proc_messages,
scheduler_proc_envelopes,
scheduler_proc_schedule,
scheduler_proc_remove,
scheduler_proc_suspend,
scheduler_proc_resume,
};
| 4,002 |
777 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// MSVC++ requires this to be set before any other includes to get M_PI.
#define _USE_MATH_DEFINES
#include "content/browser/renderer_host/input/motion_event_web.h"
#include <cmath>
#include "base/logging.h"
#include "content/common/input/web_touch_event_traits.h"
#include "ui/events/blink/blink_event_util.h"
using blink::WebInputEvent;
using blink::WebPointerProperties;
using blink::WebTouchEvent;
using blink::WebTouchPoint;
namespace content {
namespace {
ui::MotionEvent::Action GetActionFrom(const WebTouchEvent& event) {
DCHECK(event.touchesLength);
switch (event.type()) {
case WebInputEvent::TouchStart:
if (WebTouchEventTraits::AllTouchPointsHaveState(
event, WebTouchPoint::StatePressed))
return ui::MotionEvent::ACTION_DOWN;
else
return ui::MotionEvent::ACTION_POINTER_DOWN;
case WebInputEvent::TouchEnd:
if (WebTouchEventTraits::AllTouchPointsHaveState(
event, WebTouchPoint::StateReleased))
return ui::MotionEvent::ACTION_UP;
else
return ui::MotionEvent::ACTION_POINTER_UP;
case WebInputEvent::TouchCancel:
DCHECK(WebTouchEventTraits::AllTouchPointsHaveState(
event, WebTouchPoint::StateCancelled));
return ui::MotionEvent::ACTION_CANCEL;
case WebInputEvent::TouchMove:
return ui::MotionEvent::ACTION_MOVE;
default:
break;
};
NOTREACHED()
<< "Unable to derive a valid MotionEvent::Action from the WebTouchEvent.";
return ui::MotionEvent::ACTION_CANCEL;
}
int GetActionIndexFrom(const WebTouchEvent& event) {
for (size_t i = 0; i < event.touchesLength; ++i) {
if (event.touches[i].state != WebTouchPoint::StateUndefined &&
event.touches[i].state != WebTouchPoint::StateStationary)
return i;
}
return -1;
}
} // namespace
MotionEventWeb::MotionEventWeb(const WebTouchEvent& event)
: event_(event),
cached_action_(GetActionFrom(event)),
cached_action_index_(GetActionIndexFrom(event)),
unique_event_id_(event.uniqueTouchEventId) {
DCHECK_GT(GetPointerCount(), 0U);
}
MotionEventWeb::~MotionEventWeb() {}
uint32_t MotionEventWeb::GetUniqueEventId() const {
return unique_event_id_;
}
MotionEventWeb::Action MotionEventWeb::GetAction() const {
return cached_action_;
}
int MotionEventWeb::GetActionIndex() const {
DCHECK(cached_action_ == ACTION_POINTER_UP ||
cached_action_ == ACTION_POINTER_DOWN)
<< "Invalid action for GetActionIndex(): " << cached_action_;
DCHECK_GE(cached_action_index_, 0);
DCHECK_LT(cached_action_index_, static_cast<int>(event_.touchesLength));
return cached_action_index_;
}
size_t MotionEventWeb::GetPointerCount() const { return event_.touchesLength; }
int MotionEventWeb::GetPointerId(size_t pointer_index) const {
DCHECK_LT(pointer_index, GetPointerCount());
return event_.touches[pointer_index].id;
}
float MotionEventWeb::GetX(size_t pointer_index) const {
DCHECK_LT(pointer_index, GetPointerCount());
return event_.touches[pointer_index].position.x;
}
float MotionEventWeb::GetY(size_t pointer_index) const {
DCHECK_LT(pointer_index, GetPointerCount());
return event_.touches[pointer_index].position.y;
}
float MotionEventWeb::GetRawX(size_t pointer_index) const {
DCHECK_LT(pointer_index, GetPointerCount());
return event_.touches[pointer_index].screenPosition.x;
}
float MotionEventWeb::GetRawY(size_t pointer_index) const {
DCHECK_LT(pointer_index, GetPointerCount());
return event_.touches[pointer_index].screenPosition.y;
}
float MotionEventWeb::GetTouchMajor(size_t pointer_index) const {
DCHECK_LT(pointer_index, GetPointerCount());
return 2.f * std::max(event_.touches[pointer_index].radiusX,
event_.touches[pointer_index].radiusY);
}
float MotionEventWeb::GetTouchMinor(size_t pointer_index) const {
DCHECK_LT(pointer_index, GetPointerCount());
return 2.f * std::min(event_.touches[pointer_index].radiusX,
event_.touches[pointer_index].radiusY);
}
float MotionEventWeb::GetOrientation(size_t pointer_index) const {
DCHECK_LT(pointer_index, GetPointerCount());
float orientation_rad = event_.touches[pointer_index].rotationAngle
* M_PI / 180.f;
DCHECK(0 <= orientation_rad && orientation_rad <= M_PI_2)
<< "Unexpected touch rotation angle";
if (GetToolType(pointer_index) == TOOL_TYPE_STYLUS) {
const WebPointerProperties& pointer = event_.touches[pointer_index];
if (pointer.tiltY <= 0 && pointer.tiltX < 0) {
// Stylus is tilted to the left away from the user or straight
// to the left thus the orientation should be within [pi/2,pi).
orientation_rad += static_cast<float>(M_PI_2);
} else if (pointer.tiltY < 0 && pointer.tiltX >= 0) {
// Stylus is tilted to the right away from the user or straight away
// from the user thus the orientation should be within [-pi,-pi/2).
orientation_rad -= static_cast<float>(M_PI);
} else if (pointer.tiltY >= 0 && pointer.tiltX > 0) {
// Stylus is tilted to the right towards the user or straight
// to the right thus the orientation should be within [-pi/2,0).
orientation_rad -= static_cast<float>(M_PI_2);
}
} else if (event_.touches[pointer_index].radiusX
> event_.touches[pointer_index].radiusY) {
// The case radiusX == radiusY is omitted from here on purpose: for circles,
// we want to pass the angle (which could be any value in such cases but
// always seems to be set to zero) unchanged.
orientation_rad -= static_cast<float>(M_PI_2);
}
return orientation_rad;
}
float MotionEventWeb::GetPressure(size_t pointer_index) const {
return 0.f;
}
float MotionEventWeb::GetTilt(size_t pointer_index) const {
DCHECK_LT(pointer_index, GetPointerCount());
if (GetToolType(pointer_index) != TOOL_TYPE_STYLUS)
return 0.f;
const WebPointerProperties& pointer = event_.touches[pointer_index];
float tilt_x_r = sin(pointer.tiltX * M_PI / 180.f);
float tilt_x_z = cos(pointer.tiltX * M_PI / 180.f);
float tilt_y_r = sin(pointer.tiltY * M_PI / 180.f);
float tilt_y_z = cos(pointer.tiltY * M_PI / 180.f);
float r_x = tilt_x_r * tilt_y_z;
float r_y = tilt_y_r * tilt_x_z;
float r = sqrt(r_x * r_x + r_y * r_y);
float z = tilt_x_z * tilt_y_z;
return atan2(r, z);
}
base::TimeTicks MotionEventWeb::GetEventTime() const {
return base::TimeTicks() +
base::TimeDelta::FromMicroseconds(event_.timeStampSeconds() *
base::Time::kMicrosecondsPerSecond);
}
ui::MotionEvent::ToolType MotionEventWeb::GetToolType(
size_t pointer_index) const {
DCHECK_LT(pointer_index, GetPointerCount());
const WebPointerProperties& pointer = event_.touches[pointer_index];
switch (pointer.pointerType) {
case WebPointerProperties::PointerType::Unknown:
return TOOL_TYPE_UNKNOWN;
case WebPointerProperties::PointerType::Mouse:
return TOOL_TYPE_MOUSE;
case WebPointerProperties::PointerType::Pen:
return TOOL_TYPE_STYLUS;
case WebPointerProperties::PointerType::Eraser:
return TOOL_TYPE_ERASER;
case WebPointerProperties::PointerType::Touch:
return TOOL_TYPE_FINGER;
}
NOTREACHED() << "Unexpected pointerType";
return TOOL_TYPE_UNKNOWN;
}
int MotionEventWeb::GetButtonState() const {
return 0;
}
int MotionEventWeb::GetFlags() const {
return ui::WebEventModifiersToEventFlags(event_.modifiers());
}
} // namespace content
| 2,845 |
2,989 |
package com.linkedin.databus2.core.container.request;
/*
*
* Copyright 2013 LinkedIn Corp. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.DownstreamMessageEvent;
import com.linkedin.databus.core.util.JsonUtils;
public abstract class SimpleDatabusResponse implements IDatabusResponse
{
protected final byte _protocolVersion;
public SimpleDatabusResponse(byte protocolVersion)
{
_protocolVersion = protocolVersion;
}
public abstract ChannelBuffer serializeToBinary();
@Override
public void writeToChannelAsBinary(ChannelHandlerContext ctx, ChannelFuture future)
{
ChannelFuture realFuture = (null != future) ? future : Channels.future(ctx.getChannel());
ChannelBuffer serializedResponse = serializeToBinary();
DownstreamMessageEvent e = new DownstreamMessageEvent(ctx.getChannel(), realFuture,
serializedResponse,
ctx.getChannel().getRemoteAddress());
ctx.sendDownstream(e);
}
public byte getProtocolVersion()
{
return _protocolVersion;
}
@Override
public String toJsonString(boolean pretty)
{
return JsonUtils.toJsonStringSilent(this, pretty);
}
@Override
public String toString()
{
//default somewhat expensive implementation
return toJsonString(false);
}
}
| 694 |
5,169 |
<reponame>morizotter/Specs
{
"name": "RUMSlidingMenu",
"version": "1.1.0",
"summary": "A generic sliding menu component, that supports a left- and right-handside background menus.",
"description": " Based on the [RayWenderlich](http://www.raywenderlich.com/32054/how-to-create-a-slide-out-navigation-like-facebook-and-path\" How to Create a Slide-Out Navigation Panel\") tutorial, \n but improved to be less coupled to the displayed UIViewControllers, for easier integration to other projects.\n",
"homepage": "https://github.com/timsearle/RUMSlidingMenu",
"license": "MIT",
"authors": {
"<NAME>": ""
},
"source": {
"git": "https://github.com/timsearle/RUMSlidingMenu.git",
"tag": "1.1.0"
},
"platforms": {
"ios": "7.0"
},
"requires_arc": true,
"source_files": "Classes/*.{h,m}"
}
| 356 |
331 |
<gh_stars>100-1000
package org.fordes.subview.utils.submerge.subtitle.ass;
import org.fordes.subview.utils.submerge.subtitle.common.SubtitleTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
/**
* The class <code>ASSTime</code> represents a SubStation Alpha time : meaning the time at
* which the text will appear and disappear onscreen
*
*/
public class ASSTime extends SubtitleTime {
/**
* Serial
*/
private static final long serialVersionUID = -8393452818120120069L;
/**
* The time pattern
*/
public static final String TIME_PATTERN = "H:mm:ss.SS";
/**
* The time pattern formatter
*/
public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(TIME_PATTERN);
/**
* Constructor
*/
public ASSTime(LocalTime start, LocalTime end) {
super(start, end);
}
/**
* Constructor
*/
public ASSTime() {
super();
}
/**
* Convert a <code>LocalTime</code> to string
*
* @param time: the time to format
* @return the formatted time
*/
public static String format(LocalTime time) {
return time.format(FORMATTER);
}
/**
* Convert a string pattern to a Local time
*
* @param time
* @see ASSTime.PATTERN
* @return
* @throws DateTimeParseException
*/
public static LocalTime fromString(String time) {
return LocalTime.parse(time.replace(',', '.'), FORMATTER);
}
}
| 484 |
3,418 |
#include "hero.h"
void Hero::set_strength(int m_strength)
{
strength = m_strength;
}
| 34 |
310 |
<reponame>dreeves/usesthis<filename>gear/hardware/e/ef-600mm-f4l-is-usm.json
{
"name": "EF 600mm f/4L IS USM",
"description": "A super telephoto lens for cameras.",
"url": "http://usa.canon.com/cusa/consumer/products/cameras/ef_lens_lineup/ef_600mm_f_4l_is_usm"
}
| 120 |
456 |
package com.swingfrog.summer.db.repository;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class TableValueBuilder {
private static final Logger log = LoggerFactory.getLogger(TableValueBuilder.class);
@FunctionalInterface
interface ThreeConsumer<T, U, O> {
void accept(T t, U u, O o);
}
private static final Map<Type, ThreeConsumer<Field, Object, Long>> primaryFieldMap = Maps.newHashMap();
static {
ThreeConsumer<Field, Object, Long> fieldLong = (field, obj, primaryValue) -> {
try {
field.setLong(obj, primaryValue);
} catch (IllegalAccessException e) {
log.error(e.getMessage(), e);
}
};
ThreeConsumer<Field, Object, Long> fieldInt = (field, obj, primaryValue) -> {
try {
field.setInt(obj, primaryValue.intValue());
} catch (IllegalAccessException e) {
log.error(e.getMessage(), e);
}
};
ThreeConsumer<Field, Object, Long> fieldShort = (field, obj, primaryValue) -> {
try {
field.setShort(obj, primaryValue.shortValue());
} catch (IllegalAccessException e) {
log.error(e.getMessage(), e);
}
};
ThreeConsumer<Field, Object, Long> fieldByte = (field, obj, primaryValue) -> {
try {
field.setByte(obj, primaryValue.byteValue());
} catch (IllegalAccessException e) {
log.error(e.getMessage(), e);
}
};
primaryFieldMap.put(long.class, fieldLong);
primaryFieldMap.put(Long.class, fieldLong);
primaryFieldMap.put(int.class, fieldInt);
primaryFieldMap.put(Integer.class, fieldInt);
primaryFieldMap.put(short.class, fieldShort);
primaryFieldMap.put(Short.class, fieldShort);
primaryFieldMap.put(byte.class, fieldByte);
primaryFieldMap.put(Byte.class, fieldByte);
}
public static Object convert(Object obj, Type target) {
if (TableSupport.isJavaBean(target)) {
return JSON.toJSONString(obj);
} else {
return obj;
}
}
public static Object getFieldValue(Field field, Object obj) {
Object res = null;
try {
res = field.get(obj);
res = convert(res, field.getGenericType());
} catch (IllegalAccessException e) {
log.error(e.getMessage(), e);
}
return res;
}
public static void jsonConvertJavaBean(Field field, Object obj) {
try {
field.set(obj, JSON.parseObject(JSON.toJSONString(field.get(obj)), field.getGenericType()));
} catch (IllegalAccessException e) {
log.error(e.getMessage(), e);
}
}
public static boolean isEqualsColumnValue(TableMeta.ColumnMeta columnMeta, Object obj, Object value) {
Object columnValue = getColumnValue(columnMeta, obj);
if (columnValue.equals(value)) {
return true;
}
return columnValue.toString().equals(value.toString());
}
public static Object getColumnValue(TableMeta.ColumnMeta columnMeta, Object obj) {
return getFieldValue(columnMeta.getField(), obj);
}
public static Object getPrimaryKeyValue(TableMeta tableMeta, Object obj) {
return getColumnValue(tableMeta.getPrimaryColumn(), obj);
}
public static void setPrimaryKeyIntNumberValue(TableMeta tableMeta, Object obj, long primaryValue) {
Field field = tableMeta.getPrimaryColumn().getField();
Type type = field.getGenericType();
ThreeConsumer<Field, Object, Long> consumer = primaryFieldMap.get(type);
if (consumer != null) {
consumer.accept(field, obj, primaryValue);
} else {
throw new UnsupportedOperationException("primary key must be number");
}
}
public static List<String> listValidFieldByOptional(TableMeta tableMeta, Map<String, Object> optional) {
return optional.keySet().stream().filter(tableMeta.getColumnMetaMap()::containsKey).collect(Collectors.toList());
}
public static Object[] listValidValueByOptional(TableMeta tableMeta, Map<String, Object> optional, List<String> fields) {
return fields.stream().map(field -> {
TableMeta.ColumnMeta columnMeta = tableMeta.getColumnMetaMap().get(field);
return convert(optional.get(field), columnMeta.getField().getGenericType());
}).toArray();
}
public static Object[] listUpdateValue(TableMeta tableMeta, Object obj) {
List<Object> list = tableMeta.getColumns().stream()
.filter(columnMeta -> !columnMeta.isReadOnly())
.map(columnMeta -> getColumnValue(columnMeta, obj))
.collect(Collectors.toList());
list.add(getPrimaryKeyValue(tableMeta, obj));
return list.toArray();
}
public static Object[] listInsertValue(TableMeta tableMeta, Object obj) {
List<Object> list = tableMeta.getColumns().stream()
.map(columnMeta -> getColumnValue(columnMeta, obj))
.collect(Collectors.toList());
list.add(0, getPrimaryKeyValue(tableMeta, obj));
return list.toArray();
}
public static Object[] listInsertValue(TableMeta tableMeta, Object obj, Object primaryKey) {
List<Object> list = tableMeta.getColumns().stream()
.map(columnMeta -> getColumnValue(columnMeta, obj))
.collect(Collectors.toList());
list.add(0, primaryKey);
return list.toArray();
}
}
| 2,414 |
454 |
from gazette.spiders.base.fecam import FecamGazetteSpider
class ScBlumenauSpider(FecamGazetteSpider):
name = "sc_blumenau"
FECAM_QUERY = "cod_entidade:41"
TERRITORY_ID = "4202404"
| 87 |
675 |
<gh_stars>100-1000
/*
* Copyright 2020 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.python.run;
import com.google.idea.common.experiments.BoolExperiment;
import com.intellij.application.Topics;
import com.intellij.ide.AppLifecycleListener;
import com.intellij.openapi.components.BaseComponent;
import com.intellij.openapi.project.Project;
import com.jetbrains.python.run.PyTracebackParser;
import com.jetbrains.python.traceBackParsers.LinkInTrace;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import javax.annotation.Nullable;
/** Hacky override for upstream {@link PyTracebackParser}. */
public class BlazePyTracebackParser extends PyTracebackParser {
private static final BoolExperiment enabled =
new BoolExperiment("blaze.py.traceback.override.enabled", true);
@Override
protected LinkInTrace findLinkInTrace(String line, Matcher matchedMatcher) {
if (!enabled.getValue()) {
return super.findLinkInTrace(line, matchedMatcher);
}
final String fileName = matchedMatcher.group(1).replace('\\', '/');
final int lineNumber = Integer.parseInt(matchedMatcher.group(2));
final int startPos = line.indexOf('\"') + 1;
final int endPos = line.indexOf('\"', startPos);
return new LinkInTrace(getCanonicalFilePath(fileName), lineNumber, startPos, endPos);
}
private static String getCanonicalFilePath(String filePath) {
File file = new File(filePath);
try {
return file.getCanonicalPath();
} catch (IOException e) {
// fall back to original path
return filePath;
}
}
static class OverrideUpstreamParser implements BaseComponent {
@Override
public void initComponent() {
Topics.subscribe(
AppLifecycleListener.TOPIC,
/* disposable= */ null,
new AppLifecycleListener() {
@Override
public void appStarting(@Nullable Project projectFromCommandLine) {
if (enabled.getValue()) {
PARSERS[1] = new BlazePyTracebackParser();
}
}
});
}
}
}
| 925 |
563 |
<gh_stars>100-1000
package com.gentics.mesh.core.data.s3binary.impl;
import com.gentics.mesh.core.data.s3binary.S3Binaries;
import com.gentics.mesh.core.data.s3binary.S3Binary;
import com.gentics.mesh.core.data.s3binary.S3HibBinary;
import com.gentics.mesh.graphdb.spi.Database;
import com.gentics.mesh.graphdb.spi.Transactional;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.stream.Stream;
import static com.gentics.mesh.util.StreamUtil.toStream;
/**
* This class manages the {@link S3HibBinary} instances that have been persisted.
*/
@Singleton
public class S3BinariesImpl implements S3Binaries {
private final Database database;
@Inject
public S3BinariesImpl(Database database) {
this.database = database;
}
@Override
public Transactional<S3HibBinary> create(String uuid, String objectKey, String fileName) {
return database.transactional(tx -> {
S3HibBinary binary = tx.getGraph().addFramedVertex(S3BinaryImpl.class);
binary.setS3ObjectKey(objectKey);
binary.setUuid(uuid);
binary.setFileName(fileName);
return binary;
});
}
@Override
public Transactional<S3HibBinary> findByS3ObjectKey(String s3ObjectKey) {
return database.transactional(tx -> database.getVerticesTraversal(S3BinaryImpl.class, S3Binary.S3_AWS_OBJECT_KEY, s3ObjectKey).nextOrNull());
}
@Override
public Transactional<Stream<S3HibBinary>> findAll() {
return database.transactional(tx -> toStream(database.getVerticesForType(S3BinaryImpl.class)));
}
}
| 563 |
577 |
<reponame>StefanPenndorf/FluentLenium
package org.fluentlenium.core;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.fluentlenium.configuration.Configuration;
import org.fluentlenium.core.wait.FluentWait;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.time.Duration;
/**
* Unit test for {@link FluentDriverWait}.
*/
@RunWith(MockitoJUnitRunner.class)
public class FluentDriverWaitTest {
@Mock
private Configuration configuration;
@Mock
private FluentControl fluentControl;
private FluentDriverWait fluentDriverWait;
@Before
public void setup() {
fluentDriverWait = new FluentDriverWait(configuration);
}
@Test
public void shouldConfigureAtMost() {
when(configuration.getAwaitAtMost()).thenReturn(2L);
when(configuration.getAwaitPollingEvery()).thenReturn(null);
Duration defaultSeleniumInterval = Duration.ofMillis(500L);
FluentWait fluentWait = fluentDriverWait.await(fluentControl);
assertThat(fluentWait.getWait()).hasFieldOrPropertyWithValue("timeout", Duration.ofMillis(2L));
assertThat(fluentWait.getWait()).hasFieldOrPropertyWithValue("interval", defaultSeleniumInterval);
}
@Test
public void shouldConfigurePollingEvery() {
when(configuration.getAwaitAtMost()).thenReturn(null);
when(configuration.getAwaitPollingEvery()).thenReturn(2L);
Duration defaultSeleniumTimeout = Duration.ofSeconds(5L);
FluentWait fluentWait = fluentDriverWait.await(fluentControl);
assertThat(fluentWait.getWait()).hasFieldOrPropertyWithValue("timeout", defaultSeleniumTimeout);
assertThat(fluentWait.getWait()).hasFieldOrPropertyWithValue("interval", Duration.ofMillis(2L));
}
}
| 685 |
428 |
from django.apps import AppConfig
class Apiv1Config(AppConfig):
name = 'apiv1'
| 31 |
2,144 |
/**
* 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.pinot.segment.local.segment.index.readers.forward;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.pinot.segment.spi.index.reader.ForwardIndexReaderContext;
import org.apache.pinot.segment.spi.memory.CleanerUtil;
/**
* Context for the chunk-based forward index readers.
* <p>Information saved in the context can be used by subsequent reads as cache:
* <ul>
* <li>
* Chunk Buffer from the previous read. Useful if the subsequent read is from the same buffer, as it avoids extra
* chunk decompression.
* </li>
* <li>Id for the chunk</li>
* </ul>
*/
public class ChunkReaderContext implements ForwardIndexReaderContext {
private final ByteBuffer _chunkBuffer;
private int _chunkId;
public ChunkReaderContext(int maxChunkSize) {
_chunkBuffer = ByteBuffer.allocateDirect(maxChunkSize);
_chunkId = -1;
}
public ByteBuffer getChunkBuffer() {
return _chunkBuffer;
}
public int getChunkId() {
return _chunkId;
}
public void setChunkId(int chunkId) {
_chunkId = chunkId;
}
@Override
public void close()
throws IOException {
if (CleanerUtil.UNMAP_SUPPORTED) {
CleanerUtil.getCleaner().freeBuffer(_chunkBuffer);
}
}
}
| 630 |
2,461 |
<reponame>leezu/gluon-nlp
# 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.
"""
Bert Model
@article{devlin2018bert,
title={BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding},
author={<NAME> <NAME> and <NAME>},
journal={arXiv preprint arXiv:1810.04805},
year={2018}
}
"""
__all__ = ['BertModel', 'BertForMLM', 'QTBertForPretrain', 'init_weights']
import logging
import torch as th
from ..attention_cell import gen_self_attn_mask
from .transformer import TransformerEncoderLayer
from ..layers import get_activation, sequence_mask
from ...utils.registry import Registry
from ...models.bert import bert_cfg_reg # TODO CFG.INITIALIZER not supported and handled via def init_weights
class BertTransformer(th.nn.Module):
def __init__(self, units: int = 512, hidden_size: int = 2048, num_layers: int = 6,
num_heads: int = 8, attention_dropout_prob: float = 0.,
hidden_dropout_prob: float = 0., output_attention: bool = False,
output_all_encodings: bool = False, layer_norm_eps: float = 1E-12,
activation='gelu', layout='NT'):
super().__init__()
assert units % num_heads == 0,\
'In BertTransformer, The units should be divided exactly ' \
'by the number of heads. Received units={}, num_heads={}' \
.format(units, num_heads)
self._num_layers = num_layers
self._output_attention = output_attention
self._output_all_encodings = output_all_encodings
self._layout = layout
self.all_layers = th.nn.ModuleList([
TransformerEncoderLayer(units=units, hidden_size=hidden_size, num_heads=num_heads,
attention_dropout_prob=attention_dropout_prob,
hidden_dropout_prob=hidden_dropout_prob,
layer_norm_eps=layer_norm_eps, activation=activation,
layout=layout) for _ in range(num_layers)
])
@property
def layout(self):
return self._layout
def forward(self, data, valid_length):
"""
Generate the representation given the inputs.
This is used in training or fine-tuning a bert model.
Parameters
----------
F
data
- layout = 'NT'
Shape (batch_size, seq_length, C)
- layout = 'TN'
Shape (seq_length, batch_size, C)
valid_length
Shape (batch_size,)
Returns
-------
out
- layout = 'NT'
Shape (batch_size, seq_length, C_out)
- layout = 'TN'
Shape (seq_length, batch_size, C_out)
"""
if self.layout == 'NT':
time_axis, batch_axis = 1, 0
else:
time_axis, batch_axis = 0, 1
# 1. Embed the data
attn_mask = gen_self_attn_mask(data, valid_length, attn_type='full', layout=self.layout)
out = data
all_encodings_outputs = []
additional_outputs = []
for layer_idx in range(self._num_layers):
layer = self.all_layers[layer_idx]
out, attention_weights = layer(out, attn_mask)
# out : [batch_size, seq_len, units] or [seq_len, batch_size, units]
# attention_weights : [batch_size, num_heads, seq_len, seq_len]
if self._output_all_encodings:
out = sequence_mask(out, valid_len=valid_length, axis=time_axis)
all_encodings_outputs.append(out)
if self._output_attention:
additional_outputs.append(attention_weights)
if not self._output_all_encodings:
# if self._output_all_encodings, SequenceMask is already applied above
out = sequence_mask(out, valid_len=valid_length, axis=time_axis)
return out, additional_outputs
else:
return all_encodings_outputs, additional_outputs
class BertModel(th.nn.Module):
def __init__(self, vocab_size=30000, units=768, hidden_size=3072, num_layers=12, num_heads=12,
max_length=512, hidden_dropout_prob=0., attention_dropout_prob=0.,
num_token_types=2, pos_embed_type='learned', activation='gelu',
layer_norm_eps=1E-12, use_pooler=True, layout='NT', compute_layout='auto'):
super().__init__()
self.use_pooler = use_pooler
self.pos_embed_type = pos_embed_type
self.num_token_types = num_token_types
self.vocab_size = vocab_size
self.units = units
self.max_length = max_length
self.activation = activation
self.layer_norm_eps = layer_norm_eps
self._layout = layout
if compute_layout is None or compute_layout == 'auto':
self._compute_layout = layout
else:
self._compute_layout = compute_layout
# Construct BertTransformer
self.encoder = BertTransformer(
units=units, hidden_size=hidden_size, num_layers=num_layers, num_heads=num_heads,
attention_dropout_prob=attention_dropout_prob, hidden_dropout_prob=hidden_dropout_prob,
output_attention=False, output_all_encodings=False, activation=activation,
layer_norm_eps=layer_norm_eps, layout=self._compute_layout)
# Construct word embedding
self.word_embed = th.nn.Embedding(num_embeddings=vocab_size, embedding_dim=units)
self.embed_layer_norm = th.nn.LayerNorm(units, eps=self.layer_norm_eps)
self.embed_dropout = th.nn.Dropout(hidden_dropout_prob)
# Construct token type embedding
self.token_type_embed = th.nn.Embedding(num_embeddings=num_token_types, embedding_dim=units)
assert pos_embed_type == 'learned'
self.token_pos_embed = th.nn.Embedding(num_embeddings=max_length, embedding_dim=units)
if self.use_pooler:
# Construct pooler
self.pooler = th.nn.Linear(out_features=units, in_features=units)
@property
def layout(self):
return self._layout
def forward(self, inputs, token_types, valid_length):
# pylint: disable=arguments-differ
"""Generate the representation given the inputs.
This is used in training or fine-tuning a bert model.
Parameters
----------
inputs
- layout = 'NT'
Shape (batch_size, seq_length)
- layout = 'TN'
Shape (seq_length, batch_size)
token_types
- layout = 'NT'
Shape (batch_size, seq_length)
- layout = 'TN'
Shape (batch_size, seq_length)
If the inputs contain two sequences, we will set different token types for the first
sentence and the second sentence.
valid_length :
The valid length of each sequence
Shape (batch_size,)
Returns
-------
contextual_embedding
- layout = 'NT'
Shape (batch_size, seq_length, units).
- layout = 'TN'
Shape (seq_length, batch_size, units).
pooled_output :
This is optional. Shape (batch_size, units)
"""
if token_types is None:
token_types = th.zeros_like(inputs)
initial_embedding = self.get_initial_embedding(inputs, token_types)
prev_out = initial_embedding
outputs = []
if self._compute_layout != self._layout:
# Swap the axes if the compute_layout and layout mismatch
contextual_embeddings, additional_outputs = self.encoder(th.transpose(prev_out, 0, 1),
valid_length)
contextual_embeddings = th.transpose(contextual_embeddings, 0, 1)
else:
contextual_embeddings, additional_outputs = self.encoder(prev_out, valid_length)
outputs.append(contextual_embeddings)
if self.use_pooler:
pooled_out = self.apply_pooling(contextual_embeddings)
outputs.append(pooled_out)
return tuple(outputs) if len(outputs) > 1 else outputs[0]
def get_initial_embedding(self, inputs, token_types=None):
"""Get the initial token embeddings that considers the token type and positional embeddings
Parameters
----------
inputs
- layout = 'NT'
Shape (batch_size, seq_length)
- layout = 'TN'
Shape (seq_length, batch_size)
token_types
- layout = 'NT'
Shape (batch_size, seq_length)
- layout = 'TN'
Shape (seq_length, batch_size)
If None, it will be initialized as all zero
Returns
-------
embedding
The initial embedding that will be fed into the encoder
- layout = 'NT'
Shape (batch_size, seq_length, C_emb)
- layout = 'TN'
Shape (seq_length, batch_size, C_emb)
"""
if self.layout == 'NT':
time_axis, batch_axis = 1, 0
else:
time_axis, batch_axis = 0, 1
embedding = self.word_embed(inputs)
if token_types is None:
token_types = th.zeros_like(inputs)
type_embedding = self.token_type_embed(token_types)
embedding = embedding + type_embedding
if self.pos_embed_type is not None:
positional_embedding = self.token_pos_embed(
th.arange(end=inputs.shape[time_axis], device=inputs.device))
positional_embedding = th.unsqueeze(positional_embedding, dim=batch_axis)
embedding = embedding + positional_embedding
# Extra layer normalization plus dropout
embedding = self.embed_layer_norm(embedding)
embedding = self.embed_dropout(embedding)
return embedding
def apply_pooling(self, sequence):
"""Generate the representation given the inputs.
This is used for pre-training or fine-tuning a bert model.
Get the first token of the whole sequence which is [CLS]
sequence
- layout = 'NT'
Shape (batch_size, sequence_length, units)
- layout = 'TN'
Shape (sequence_length, batch_size, units)
return:
Shape (batch_size, units)
"""
if self.layout == 'NT':
outputs = sequence[:, 0, :]
else:
outputs = sequence[0, :, :]
return th.tanh(self.pooler(outputs))
@staticmethod
def get_cfg(key=None):
if key is not None:
return bert_cfg_reg.create(key)
else:
return bert_cfg_reg.create('google_en_uncased_bert_base')
@classmethod
def from_cfg(cls, cfg, use_pooler=True) -> 'BertModel':
"""
Parameters
----------
cfg
Configuration
use_pooler
Whether to output the pooled feature
Returns
-------
ret
The constructed BertModel
"""
cfg = BertModel.get_cfg().clone_merge(cfg)
assert cfg.VERSION == 1, 'Wrong version!'
return cls(vocab_size=cfg.MODEL.vocab_size, units=cfg.MODEL.units,
hidden_size=cfg.MODEL.hidden_size, num_layers=cfg.MODEL.num_layers,
num_heads=cfg.MODEL.num_heads, max_length=cfg.MODEL.max_length,
hidden_dropout_prob=cfg.MODEL.hidden_dropout_prob,
attention_dropout_prob=cfg.MODEL.attention_dropout_prob,
num_token_types=cfg.MODEL.num_token_types,
pos_embed_type=cfg.MODEL.pos_embed_type, activation=cfg.MODEL.activation,
layer_norm_eps=cfg.MODEL.layer_norm_eps, use_pooler=use_pooler,
layout=cfg.MODEL.layout, compute_layout=cfg.MODEL.compute_layout)
class BertForMLM(th.nn.Module):
def __init__(self, backbone_cfg):
"""
Parameters
----------
backbone_cfg
"""
super().__init__()
self.backbone_model = BertModel.from_cfg(backbone_cfg)
self.mlm_decoder = th.nn.Sequential(
th.nn.Linear(out_features=self.backbone_model.units,
in_features=self.backbone_model.units),
get_activation(self.backbone_model.activation),
th.nn.LayerNorm(self.backbone_model.units, eps=self.backbone_model.layer_norm_eps),
th.nn.Linear(out_features=self.backbone_model.vocab_size,
in_features=self.backbone_model.units))
# TODO such weight sharing not supported in torchscript
self.mlm_decoder[-1].weight = self.backbone_model.word_embed.weight
@property
def layout(self):
return self.backbone_model.layout
def forward(self, inputs, token_types, valid_length, masked_positions):
"""Getting the scores of the masked positions.
Parameters
----------
inputs
- layout = 'NT'
Shape (batch_size, seq_length)
- layout = 'TN'
Shape (seq_length, batch_size)
token_types
If the inputs contain two sequences, we will set different token types for the first
sentence and the second sentence.
- layout = 'NT'
Shape (batch_size, seq_length)
- layout = 'TN'
Shape (seq_length, batch_size)
valid_length :
The valid length of each sequence
Shape (batch_size,)
masked_positions :
The masked position of the sequence
Shape (batch_size, num_masked_positions).
Returns
-------
contextual_embedding
- layout = 'NT'
Shape (batch_size, seq_length, units).
- layout = 'TN'
Shape (seq_length, batch_size, units)
pooled_out
Shape (batch_size, units)
mlm_scores :
Shape (batch_size, num_masked_positions, vocab_size)
"""
contextual_embeddings, pooled_out = self.backbone_model(inputs, token_types, valid_length)
if self.layout == 'NT':
mlm_features = contextual_embeddings[
th.arange(contextual_embeddings.shape[0]).unsqueeze(1), masked_positions]
else:
contextual_embeddings_t = th.transpose(contextual_embeddings, 0, 1)
mlm_features = contextual_embeddings_t[
th.arange(contextual_embeddings_t.shape[0]).unsqueeze(1), masked_positions]
mlm_scores = self.mlm_decoder(mlm_features)
return contextual_embeddings, pooled_out, mlm_scores
class BertForPretrain(th.nn.Module):
def __init__(self, backbone_cfg):
"""
Parameters
----------
backbone_cfg
The cfg of the backbone model
"""
super().__init__()
self.backbone_model = BertModel.from_cfg(backbone_cfg)
# Construct nsp_classifier for next sentence prediction
self.nsp_classifier = th.nn.Linear(out_features=2, in_features=self.backbone_model.units)
self.mlm_decoder = th.nn.Sequential(
th.nn.Linear(out_features=self.backbone_model.units,
in_features=self.backbone_model.units),
get_activation(self.backbone_model.activation),
th.nn.LayerNorm(self.backbone_model.units, eps=self.backbone_model.layer_norm_eps),
th.nn.Linear(out_features=self.backbone_model.vocab_size,
in_features=self.backbone_model.units))
# TODO such weight sharing not supported in torchscript
self.mlm_decoder[-1].weight = self.backbone_model.word_embed.weight
@property
def layout(self):
return self.backbone_model.layout
def forward(self, inputs, token_types, valid_length, masked_positions):
"""Generate the representation given the inputs.
This is used in training or fine-tuning a bert model.
Parameters
----------
inputs
- layout = 'NT'
Shape (batch_size, seq_length)
- layout = 'TN'
Shape (seq_length, batch_size)
token_types
- layout = 'NT'
Shape (batch_size, seq_length)
- layout = 'TN'
Shape (seq_length, batch_size)
If the inputs contain two sequences, we will set different token types for the first
sentence and the second sentence.
valid_length
The valid length of each sequence
Shape (batch_size,)
masked_positions
The masked position of the sequence
Shape (batch_size, num_masked_positions).
Returns
-------
contextual_embedding
- layout = 'NT'
Shape (batch_size, seq_length, units).
- layout = 'TN'
Shape (seq_length, batch_size, units).
pooled_out
Shape (batch_size, units)
nsp_score :
Shape (batch_size, 2)
mlm_scores :
Shape (batch_size, num_masked_positions, vocab_size)
"""
contextual_embeddings, pooled_out = self.backbone_model(inputs, token_types, valid_length)
nsp_score = self.nsp_classifier(pooled_out)
if self.layout == 'NT':
mlm_features = contextual_embeddings[
th.arange(contextual_embeddings.shape[0]).unsqueeze(1), masked_positions]
else:
mlm_features = th.transpose(contextual_embeddings, 0,
1)[th.arange(contextual_embeddings.shape[1]).unsqueeze(1),
masked_positions]
mlm_scores = self.mlm_decoder(mlm_features)
return contextual_embeddings, pooled_out, nsp_score, mlm_scores
class QTBertForPretrain(th.nn.Module):
def __init__(self, backbone_cfg):
"""
Parameters
----------
backbone_cfg
The cfg of the backbone model
"""
super().__init__()
self.backbone_model = BertModel.from_cfg(backbone_cfg)
self.quickthought = th.nn.Sequential(
th.nn.Linear(out_features=self.backbone_model.units,
in_features=self.backbone_model.units),
get_activation(self.backbone_model.activation),
th.nn.LayerNorm(self.backbone_model.units, eps=self.backbone_model.layer_norm_eps))
self.mlm_decoder = th.nn.Sequential(
th.nn.Linear(out_features=self.backbone_model.units,
in_features=self.backbone_model.units),
get_activation(self.backbone_model.activation),
th.nn.LayerNorm(self.backbone_model.units, eps=self.backbone_model.layer_norm_eps),
th.nn.Linear(out_features=self.backbone_model.vocab_size,
in_features=self.backbone_model.units))
# TODO such weight sharing not supported in torchscript
self.mlm_decoder[-1].weight = self.backbone_model.word_embed.weight
@property
def layout(self):
return self.backbone_model.layout
def forward(self, inputs, token_types, valid_length, masked_positions):
"""Generate the representation given the inputs.
This is used in training or fine-tuning a bert model.
Parameters
----------
inputs
- layout = 'NT'
Shape (batch_size, seq_length)
- layout = 'TN'
Shape (seq_length, batch_size)
token_types
- layout = 'NT'
Shape (batch_size, seq_length)
- layout = 'TN'
Shape (seq_length, batch_size)
If the inputs contain two sequences, we will set different token types for the first
sentence and the second sentence.
valid_length
The valid length of each sequence
Shape (batch_size,)
masked_positions
The masked position of the sequence with respect to flattened batch
Shape (N, ) for N masked positions across whole batch.
Returns
-------
contextual_embedding
- layout = 'NT'
Shape (batch_size, seq_length, units).
- layout = 'TN'
Shape (seq_length, batch_size, units).
pooled_out
Shape (batch_size, units)
mlm_scores :
Shape (N, vocab_size)
"""
assert len(inputs) % 2 == 0, 'Model expects QuickThought paired inputs'
contextual_embeddings, pooled_out = self.backbone_model(inputs, token_types, valid_length)
if self.layout == 'NT':
mlm_features = contextual_embeddings.flatten(0, 1)[masked_positions]
else:
mlm_features = th.transpose(contextual_embeddings, 0, 1).flatten(0, 1)[masked_positions]
mlm_scores = self.mlm_decoder(mlm_features)
qt_embeddings = self.quickthought(pooled_out)
qt_similarity = self._cosine_similarity(qt_embeddings[:len(inputs) // 2],
qt_embeddings[len(inputs) // 2:])
return contextual_embeddings, pooled_out, mlm_scores, qt_similarity
def _cosine_similarity(self, a, b):
a_norm = a / a.norm(dim=1)[:, None]
b_norm = b / b.norm(dim=1)[:, None]
return th.mm(a_norm, b_norm.transpose(0, 1))
def init_weights(module):
if type(module) in (th.nn.Linear, th.nn.Embedding):
th.nn.init.trunc_normal_(module.weight, mean=0, std=0.02, a=-0.04, b=0.04)
if type(module) == th.nn.Linear and module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, th.nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
else:
logging.debug(f'Not performing custom initialization for {type(module)}')
| 10,617 |
307 |
/*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
#include "anim/animplay.h"
#include "anim/packunpack.h"
#include "freespace.h"
#include "gamesequence/gamesequence.h"
#include "menuui/fishtank.h"
// fish
typedef struct fish {
float x, y; // x and y coords
float x_speed, y_speed; // x and y speed
int left; // left or right
anim_instance *a; // tha animation
int onscreen;
int swimming; // whee
} fish;
#define MAX_FISH 12
fish Fish[MAX_FISH];
// fish anim name
#define FISH_LEFT_ANIM_NAME "f_left.ani"
#define FISH_RIGHT_ANIM_NAME "f_right.ani"
#define FISH_ANIM_WIDTH 100
#define FISH_ANIM_HEIGHT 30
anim *Fish_left_anim = NULL;
anim *Fish_right_anim = NULL;
int Fish_inited = 0;
void fish_generate()
{
fish *f;
int idx;
if(!Fish_inited){
return;
}
// bogus anims
if((Fish_left_anim == NULL) || (Fish_right_anim == NULL)){
return;
}
// find a free fish
f = NULL;
for(idx=0; idx<MAX_FISH; idx++){
if(!Fish[idx].swimming){
f = &Fish[idx];
}
}
// no fish left
if(f == NULL){
return;
}
// left or right
f->left = frand_range(0.0f, 1.0f) < 0.5f ? 0 : 1;
// start location
if(f->left){
f->x = gr_screen.max_w_unscaled_zoomed + frand_range(0.0f, 50.0f);
} else {
f->x = frand_range(0.0f, -50.0f) - FISH_ANIM_WIDTH;
}
f->y = frand_range(-40.0f, (float)gr_screen.max_h_unscaled_zoomed + 40.0f);
// speed
if(f->left){
f->x_speed = frand_range(-1.0f, -15.0f);
} else {
f->x_speed = frand_range(1.0f, 15.0f);
}
f->y_speed = frand_range(0.0f, 1.0f) < 0.5f ? frand_range(1.0f, 4.0f) : frand_range(-1.0f, -4.0f);
// all fish start out offscreen
f->onscreen = 0;
// he's swimming
f->swimming = 1;
// anim instance
anim_play_struct aps;
if(f->left){
anim_play_init(&aps, Fish_left_anim, (int)f->x, (int)f->y);
f->a = anim_play(&aps);
// doh. cancel him
if(f->a == NULL){
f->swimming = 0;
} else {
f->a->screen_id = GS_STATE_MAIN_MENU;
f->a->looped = 1;
f->a->framerate_independent = 1;
}
} else {
anim_play_init(&aps, Fish_right_anim, (int)f->x, (int)f->y);
f->a = anim_play(&aps);
// doh. cancel him
if(f->a == NULL){
f->swimming = 0;
} else {
f->a->screen_id = GS_STATE_MAIN_MENU;
f->a->looped = 1;
f->a->framerate_independent = 1;
}
}
}
void fish_flush(fish *f)
{
// bogus
if(f == NULL){
return;
}
// release his render instance
if(f->a != NULL){
anim_release_render_instance(f->a);
f->a = NULL;
}
// no longer swimming
f->swimming = 0;
}
void fishtank_start()
{
int idx;
if(Fish_inited){
return;
}
// try and load the fish anim
Fish_left_anim = anim_load(FISH_LEFT_ANIM_NAME);
if(Fish_left_anim == NULL){
return;
}
Fish_right_anim = anim_load(FISH_RIGHT_ANIM_NAME);
if(Fish_right_anim == NULL){
return;
}
// no anim instances
for(idx=0; idx<MAX_FISH; idx++){
Fish[idx].a = NULL;
Fish[idx].swimming = 0;
}
Fish_inited = 1;
// generate a random # of fish
int count = (int)frand_range(1.0f, (float)(MAX_FISH - 1));
for(idx=0; idx<count; idx++){
fish_generate();
}
}
void fishtank_stop()
{
int idx;
if(!Fish_inited){
return;
}
// release stuff
for(idx=0; idx<MAX_FISH; idx++){
if(Fish[idx].a != NULL){
anim_release_render_instance(Fish[idx].a);
Fish[idx].a = NULL;
}
Fish[idx].swimming = 0;
}
if(Fish_left_anim != NULL){
anim_free(Fish_left_anim);
Fish_left_anim = NULL;
}
if(Fish_right_anim != NULL){
anim_free(Fish_right_anim);
Fish_right_anim = NULL;
}
Fish_inited = 0;
}
void fishtank_process()
{
int idx, onscreen;
fish *f;
if(!Fish_inited){
return;
}
// process all fish
for(idx=0; idx<MAX_FISH; idx++){
f = &Fish[idx];
// not swimming?
if(!f->swimming){
continue;
}
// move him along
f->x += f->x_speed * flFrametime;
f->y += f->y_speed * flFrametime;
// is he currently onscreen ?
onscreen = 0;
if( (f->x < (float)gr_screen.max_w_unscaled_zoomed) && ((f->x + FISH_ANIM_WIDTH) >= 0.0f) &&
(f->y < (float)gr_screen.max_h_unscaled_zoomed) && ((f->y + FISH_ANIM_HEIGHT) >= 0.0f) ){
onscreen = 1;
}
// if he was onscreen before, but is no longer, flush him and make a new fish
if(f->onscreen && !onscreen){
fish_flush(f);
fish_generate();
continue;
}
// otherwise just mark his current status
f->onscreen = onscreen;
// render
if(f->onscreen){
// set coords
f->a->x = (int)f->x;
f->a->y = (int)f->y;
anim_render_one(GS_STATE_MAIN_MENU, f->a, flFrametime);
}
}
}
| 2,225 |
412 |
package com.simpligility.maven.plugins.android.compiler;
import com.google.api.client.repackaged.com.google.common.base.Strings;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.plexus.compiler.AbstractCompiler;
import org.codehaus.plexus.compiler.CompilerConfiguration;
import org.codehaus.plexus.compiler.CompilerException;
import org.codehaus.plexus.compiler.CompilerMessage;
import org.codehaus.plexus.compiler.CompilerMessage.Kind;
import org.codehaus.plexus.compiler.CompilerOutputStyle;
import org.codehaus.plexus.compiler.CompilerResult;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.StreamConsumer;
import org.codehaus.plexus.util.cli.WriterStreamConsumer;
/**
* @plexus.component role="org.codehaus.plexus.compiler.Compiler"
* role-hint="jack"
*/
@Component( role = Compiler.class, hint = "jack" )
public class JackCompiler extends AbstractCompiler
{
private static final Log LOG = LogFactory.getLog( JackCompiler.class );
public static final String JACK_COMPILER_ID = "jack";
public JackCompiler()
{
super( CompilerOutputStyle.ONE_OUTPUT_FILE_FOR_ALL_INPUT_FILES, ".java", ".dex", null );
}
@Override
public String[] createCommandLine( CompilerConfiguration cc ) throws CompilerException
{
String androidHome = System.getenv( "ANDROID_HOME" );
String jackJarPath = androidHome + "/build-tools/24.0.2/jack.jar";
String androidJarPath = androidHome + "/platforms/android-24/android.jar";
String command =
( "java -jar " + jackJarPath + " "
+ " -D jack.java.source.version=" + cc.getSourceVersion()
+ " --classpath " + androidJarPath
+ " --output-dex " + cc.getBuildDirectory()
+ " src/main/java/ target/generated-sources/r/" );
LOG.debug( String.format( " jack command : %s", command ) );
return trim( command.split( "\\s" ) ) ;
}
@Override
public boolean canUpdateTarget( CompilerConfiguration configuration )
throws CompilerException
{
return false;
}
@Override
public CompilerResult performCompile( CompilerConfiguration configuration ) throws CompilerException
{
String[] commandLine = this.createCommandLine( configuration );
List<CompilerMessage> messages = compileOutOfProcess( configuration.getWorkingDirectory(),
configuration.getBuildDirectory(),
commandLine[ 0 ],
Arrays.copyOfRange( commandLine, 1, commandLine.length )
);
return new CompilerResult().compilerMessages( messages );
}
@Override
public String getOutputFile( CompilerConfiguration configuration ) throws CompilerException
{
return "classes.dex";
}
@SuppressWarnings( "deprecation" )
private List<CompilerMessage> compileOutOfProcess( File workingDirectory, File target, String executable,
String[] args )
throws CompilerException
{ // ----------------------------------------------------------------------
// Build the @arguments file
// ----------------------------------------------------------------------
File file;
PrintWriter output = null;
try
{
file = new File( target, "jack-argmuents" );
output = new PrintWriter( new FileWriter( file ) );
for ( String arg : args )
{
output.println( arg );
}
}
catch ( IOException e )
{
throw new CompilerException( "Error writing arguments file.", e );
}
finally
{
IOUtil.close( output );
}
// ----------------------------------------------------------------------
// Execute!
// ----------------------------------------------------------------------
Commandline cli = new Commandline();
cli.setWorkingDirectory( workingDirectory.getAbsolutePath() );
cli.setExecutable( executable );
cli.addArguments( args );
Writer stringWriter = new StringWriter();
StreamConsumer out = new WriterStreamConsumer( stringWriter );
StreamConsumer err = new WriterStreamConsumer( stringWriter );
int returnCode;
List<CompilerMessage> messages;
try
{
returnCode = CommandLineUtils.executeCommandLine( cli, out, err );
messages = parseCompilerOutput( new BufferedReader( new StringReader( stringWriter.toString() ) ) );
}
catch ( CommandLineException e )
{
throw new CompilerException( "Error while executing the external compiler.", e );
}
catch ( IOException e )
{
throw new CompilerException( "Error while executing the external compiler.", e );
}
if ( returnCode != 0 )
{
StringBuilder errorBuilder = new StringBuilder();
for ( CompilerMessage message : messages )
{
errorBuilder.append( message.getMessage() );
}
throw new CompilerException( errorBuilder.toString() );
}
return messages;
}
public static List<CompilerMessage> parseCompilerOutput( BufferedReader bufferedReader )
throws IOException
{
List<CompilerMessage> messages = new ArrayList<CompilerMessage>();
String line = bufferedReader.readLine();
while ( line != null )
{
messages.add( new CompilerMessage( line, Kind.NOTE ) );
line = bufferedReader.readLine();
}
return messages;
}
private String[] trim( String[] split )
{
Iterable<String> filtered = Iterables.filter(
Arrays.asList( split ),
new Predicate<String>()
{
@Override
public boolean apply( String t )
{
return !Strings.isNullOrEmpty( t );
}
}
);
return Iterables.toArray( filtered, String.class );
}
}
| 2,868 |
460 |
<reponame>dyzmapl/BumpTop
#include "../../../src/declarative/graphicsitems/qdeclarativeflickable_p.h"
| 44 |
2,762 |
<filename>third_party/libutil_freebsd/libutil.h
#ifndef LIBUTIL_FREEBSD_H_INCLUDED
#define LIBUTIL_FREEBSD_H_INCLUDED
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
int
flopen(const char *path, int flags, ...);
struct pidfh;
struct pidfh *
pidfile_open(const char *path, mode_t mode, pid_t *pidptr);
int
pidfile_write(struct pidfh *pfh);
int
pidfile_close(struct pidfh *pfh);
int
pidfile_remove(struct pidfh *pfh);
int
pidfile_fileno(const struct pidfh *pfh);
#ifdef __cplusplus
} /* extern "C" { */
#endif
#endif /* LIBUTIL_FREEBSD_H_INCLUDED */
| 249 |
311 |
package datadog.trace.instrumentation.grizzlyhttp232;
import java.lang.reflect.Field;
import java.lang.reflect.UndeclaredThrowableException;
import org.glassfish.grizzly.http.HttpHeader;
import org.glassfish.grizzly.http.io.InputBuffer;
/**
* Helper till we have support for invokedynamic-based caching on bytebuddy:
* https://github.com/raphw/byte-buddy/issues/1009
*/
public final class HttpHeaderFetchingHelper {
private HttpHeaderFetchingHelper() {}
private static final Field HTTP_HEADER_FIELD = prepareField();
private static Field prepareField() {
Field httpHeaderField = null;
try {
httpHeaderField = InputBuffer.class.getDeclaredField("httpHeader");
} catch (NoSuchFieldException e) {
throw new UndeclaredThrowableException(e);
}
httpHeaderField.setAccessible(true);
return httpHeaderField;
}
public static HttpHeader fetchHttpHeader(InputBuffer inputBuffer) {
try {
return (HttpHeader) HTTP_HEADER_FIELD.get(inputBuffer);
} catch (IllegalAccessException e) {
throw new UndeclaredThrowableException(e);
}
}
}
| 366 |
1,915 |
// Copyright 2018 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.casbin.jcasbin.effect;
/**
* Effector is the interface for Casbin effectors.
*/
public interface Effector {
/**
* mergeEffects merges all matching results collected by the enforcer into a single decision.
*
* @param expr the expression of [policy_effect].
* @param effects the effects of all matched rules.
* @param results the matcher results of all matched rules.
* @return the final effect.
*/
boolean mergeEffects(String expr, Effect[] effects, float[] results);
}
| 318 |
707 |
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <thread>
#include <utility>
#include <fmt/format.h>
namespace frc {
class CameraServerShared {
public:
virtual ~CameraServerShared() = default;
virtual void ReportUsbCamera(int id) = 0;
virtual void ReportAxisCamera(int id) = 0;
virtual void ReportVideoServer(int id) = 0;
virtual void SetCameraServerErrorV(fmt::string_view format,
fmt::format_args args) = 0;
virtual void SetVisionRunnerErrorV(fmt::string_view format,
fmt::format_args args) = 0;
virtual void ReportDriverStationErrorV(fmt::string_view format,
fmt::format_args args) = 0;
virtual std::pair<std::thread::id, bool> GetRobotMainThreadId() const = 0;
template <typename S, typename... Args>
inline void SetCameraServerError(const S& format, Args&&... args) {
SetCameraServerErrorV(format,
fmt::make_args_checked<Args...>(format, args...));
}
template <typename S, typename... Args>
inline void SetVisionRunnerError(const S& format, Args&&... args) {
SetVisionRunnerErrorV(format,
fmt::make_args_checked<Args...>(format, args...));
}
template <typename S, typename... Args>
inline void ReportDriverStationError(const S& format, Args&&... args) {
ReportDriverStationErrorV(format,
fmt::make_args_checked<Args...>(format, args...));
}
};
CameraServerShared* GetCameraServerShared();
} // namespace frc
extern "C" {
// Takes ownership
void CameraServer_SetCameraServerShared(frc::CameraServerShared* shared);
} // extern "C"
| 734 |
335 |
{
"word": "Nerve",
"definitions": [
"A whitish fibre or bundle of fibres in the body that transmits impulses of sensation to the brain or spinal cord, and impulses from these to the muscles and organs.",
"One's steadiness and courage in a demanding situation.",
"Impudence or audacity.",
"Feelings of nervousness.",
"A prominent unbranched rib in a leaf, especially in the midrib of the leaf of a moss."
],
"parts-of-speech": "Noun"
}
| 169 |
690 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.external_intents;
import android.Manifest.permission;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.net.Uri;
import android.os.StrictMode;
import android.os.SystemClock;
import android.provider.Browser;
import android.provider.Telephony;
import android.text.TextUtils;
import android.util.AndroidRuntimeException;
import android.util.Pair;
import android.view.WindowManager.BadTokenException;
import android.webkit.MimeTypeMap;
import android.webkit.WebView;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.app.AlertDialog;
import org.chromium.base.CommandLine;
import org.chromium.base.ContextUtils;
import org.chromium.base.IntentUtils;
import org.chromium.base.Log;
import org.chromium.base.PackageManagerUtils;
import org.chromium.base.PathUtils;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.base.supplier.Supplier;
import org.chromium.base.task.PostTask;
import org.chromium.components.embedder_support.util.UrlConstants;
import org.chromium.components.embedder_support.util.UrlUtilities;
import org.chromium.components.embedder_support.util.UrlUtilitiesJni;
import org.chromium.components.external_intents.ExternalNavigationDelegate.IntentToAutofillAllowingAppResult;
import org.chromium.components.webapk.lib.client.ChromeWebApkHostSignature;
import org.chromium.components.webapk.lib.client.WebApkValidator;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.NavigationController;
import org.chromium.content_public.browser.NavigationEntry;
import org.chromium.content_public.browser.UiThreadTaskTraits;
import org.chromium.content_public.common.ContentUrlConstants;
import org.chromium.content_public.common.Referrer;
import org.chromium.network.mojom.ReferrerPolicy;
import org.chromium.ui.base.PageTransition;
import org.chromium.ui.base.PermissionCallback;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.url.GURL;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Logic related to the URL overriding/intercepting functionality.
* This feature supports conversion of certain navigations to Android Intents allowing
* applications like Youtube to direct users clicking on a http(s) link to their native app.
*/
public class ExternalNavigationHandler {
private static final String TAG = "UrlHandler";
// Enables debug logging on a local build.
private static final boolean DEBUG = false;
private static final String WTAI_URL_PREFIX = "wtai://wp/";
private static final String WTAI_MC_URL_PREFIX = "wtai://wp/mc;";
private static final String PLAY_PACKAGE_PARAM = "id";
private static final String PLAY_REFERRER_PARAM = "referrer";
private static final String PLAY_APP_PATH = "/store/apps/details";
private static final String PLAY_HOSTNAME = "play.google.com";
private static final String PDF_EXTENSION = "pdf";
private static final String PDF_VIEWER = "com.google.android.apps.docs";
private static final String PDF_MIME = "application/pdf";
private static final String PDF_SUFFIX = ".pdf";
/**
* Records package names of external applications in the system that could have handled this
* intent.
*/
public static final String EXTRA_EXTERNAL_NAV_PACKAGES = "org.chromium.chrome.browser.eenp";
@VisibleForTesting
public static final String EXTRA_BROWSER_FALLBACK_URL = "browser_fallback_url";
// An extra that may be specified on an intent:// URL that contains an encoded value for the
// referrer field passed to the market:// URL in the case where the app is not present.
@VisibleForTesting
static final String EXTRA_MARKET_REFERRER = "market_referrer";
// A mask of flags that are safe for untrusted content to use when starting an Activity.
// This list is not exhaustive and flags not listed here are not necessarily unsafe.
@VisibleForTesting
static final int ALLOWED_INTENT_FLAGS = Intent.FLAG_EXCLUDE_STOPPED_PACKAGES
| Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_MATCH_EXTERNAL | Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_NEW_DOCUMENT
| Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT;
// These values are persisted in histograms. Please do not renumber. Append only.
@IntDef({AiaIntent.FALLBACK_USED, AiaIntent.SERP, AiaIntent.OTHER})
@Retention(RetentionPolicy.SOURCE)
private @interface AiaIntent {
int FALLBACK_USED = 0;
int SERP = 1;
int OTHER = 2;
int NUM_ENTRIES = 3;
}
// Helper class to return a boolean by reference.
private static class MutableBoolean {
private Boolean mValue;
public void set(boolean value) {
mValue = value;
}
public Boolean get() {
return mValue;
}
}
// Used to ensure we only call queryIntentActivities when we really need to.
private class ResolveInfoSupplier implements Supplier<List<ResolveInfo>> {
private List<ResolveInfo> mValue;
private Intent mIntent;
public ResolveInfoSupplier(Intent intent) {
mIntent = intent;
}
@Override
public List<ResolveInfo> get() {
if (mValue == null) mValue = queryIntentActivities(mIntent);
return mValue;
}
@Override
public boolean hasValue() {
return true;
}
}
private final ExternalNavigationDelegate mDelegate;
/**
* Result types for checking if we should override URL loading.
* NOTE: this enum is used in UMA, do not reorder values. Changes should be append only.
* Values should be numerated from 0 and can't have gaps.
*/
@IntDef({OverrideUrlLoadingResultType.OVERRIDE_WITH_EXTERNAL_INTENT,
OverrideUrlLoadingResultType.OVERRIDE_WITH_CLOBBERING_TAB,
OverrideUrlLoadingResultType.OVERRIDE_WITH_ASYNC_ACTION,
OverrideUrlLoadingResultType.NO_OVERRIDE})
@Retention(RetentionPolicy.SOURCE)
public @interface OverrideUrlLoadingResultType {
/* We should override the URL loading and launch an intent. */
int OVERRIDE_WITH_EXTERNAL_INTENT = 0;
/* We should override the URL loading and clobber the current tab. */
int OVERRIDE_WITH_CLOBBERING_TAB = 1;
/* We should override the URL loading. The desired action will be determined
* asynchronously (e.g. by requiring user confirmation). */
int OVERRIDE_WITH_ASYNC_ACTION = 2;
/* We shouldn't override the URL loading. */
int NO_OVERRIDE = 3;
int NUM_ENTRIES = 4;
}
/**
* Types of async action that can be taken for a navigation.
*/
@IntDef({OverrideUrlLoadingAsyncActionType.UI_GATING_BROWSER_NAVIGATION,
OverrideUrlLoadingAsyncActionType.UI_GATING_INTENT_LAUNCH,
OverrideUrlLoadingAsyncActionType.NO_ASYNC_ACTION})
@Retention(RetentionPolicy.SOURCE)
public @interface OverrideUrlLoadingAsyncActionType {
/* The user has been presented with a consent dialog gating a browser navigation. */
int UI_GATING_BROWSER_NAVIGATION = 0;
/* The user has been presented with a consent dialog gating an intent launch. */
int UI_GATING_INTENT_LAUNCH = 1;
/* No async action has been taken. */
int NO_ASYNC_ACTION = 2;
int NUM_ENTRIES = 3;
}
/**
* Packages information about the result of a check of whether we should override URL loading.
*/
public static class OverrideUrlLoadingResult {
@OverrideUrlLoadingResultType
int mResultType;
@OverrideUrlLoadingAsyncActionType
int mAsyncActionType;
OverrideUrlLoadingResult(@OverrideUrlLoadingResultType int resultType) {
this(resultType, OverrideUrlLoadingAsyncActionType.NO_ASYNC_ACTION);
}
OverrideUrlLoadingResult(@OverrideUrlLoadingResultType int resultType,
@OverrideUrlLoadingAsyncActionType int asyncActionType) {
// The async action type should be set only for async actions...
assert (asyncActionType == OverrideUrlLoadingAsyncActionType.NO_ASYNC_ACTION
|| resultType == OverrideUrlLoadingResultType.OVERRIDE_WITH_ASYNC_ACTION);
// ...and it *must* be set for async actions.
assert (!(asyncActionType == OverrideUrlLoadingAsyncActionType.NO_ASYNC_ACTION
&& resultType == OverrideUrlLoadingResultType.OVERRIDE_WITH_ASYNC_ACTION));
mResultType = resultType;
mAsyncActionType = asyncActionType;
}
public @OverrideUrlLoadingResultType int getResultType() {
return mResultType;
}
public @OverrideUrlLoadingAsyncActionType int getAsyncActionType() {
return mAsyncActionType;
}
public static OverrideUrlLoadingResult forAsyncAction(
@OverrideUrlLoadingAsyncActionType int asyncActionType) {
return new OverrideUrlLoadingResult(
OverrideUrlLoadingResultType.OVERRIDE_WITH_ASYNC_ACTION, asyncActionType);
}
public static OverrideUrlLoadingResult forNoOverride() {
return new OverrideUrlLoadingResult(OverrideUrlLoadingResultType.NO_OVERRIDE);
}
public static OverrideUrlLoadingResult forClobberingTab() {
return new OverrideUrlLoadingResult(
OverrideUrlLoadingResultType.OVERRIDE_WITH_CLOBBERING_TAB);
}
public static OverrideUrlLoadingResult forExternalIntent() {
return new OverrideUrlLoadingResult(
OverrideUrlLoadingResultType.OVERRIDE_WITH_EXTERNAL_INTENT);
}
}
/**
* Constructs a new instance of {@link ExternalNavigationHandler}, using the injected
* {@link ExternalNavigationDelegate}.
*/
public ExternalNavigationHandler(ExternalNavigationDelegate delegate) {
mDelegate = delegate;
}
/**
* Determines whether the URL needs to be sent as an intent to the system,
* and sends it, if appropriate.
* @return Whether the URL generated an intent, caused a navigation in
* current tab, or wasn't handled at all.
*/
public OverrideUrlLoadingResult shouldOverrideUrlLoading(ExternalNavigationParams params) {
if (DEBUG) Log.i(TAG, "shouldOverrideUrlLoading called on " + params.getUrl().getSpec());
Intent targetIntent;
// Perform generic parsing of the URI to turn it into an Intent.
if (UrlUtilities.hasIntentScheme(params.getUrl())) {
try {
targetIntent = Intent.parseUri(params.getUrl().getSpec(), Intent.URI_INTENT_SCHEME);
} catch (Exception ex) {
Log.w(TAG, "Bad URI %s", params.getUrl().getSpec(), ex);
return OverrideUrlLoadingResult.forNoOverride();
}
} else {
targetIntent = new Intent(Intent.ACTION_VIEW);
targetIntent.setData(Uri.parse(params.getUrl().getSpec()));
}
GURL browserFallbackUrl =
new GURL(IntentUtils.safeGetStringExtra(targetIntent, EXTRA_BROWSER_FALLBACK_URL));
if (!browserFallbackUrl.isValid() || !UrlUtilities.isHttpOrHttps(browserFallbackUrl)) {
browserFallbackUrl = GURL.emptyGURL();
}
// TODO(https://crbug.com/1096099): Refactor shouldOverrideUrlLoadingInternal, splitting it
// up to separate out the notions wanting to fire an external intent vs being able to.
MutableBoolean canLaunchExternalFallbackResult = new MutableBoolean();
long time = SystemClock.elapsedRealtime();
OverrideUrlLoadingResult result = shouldOverrideUrlLoadingInternal(
params, targetIntent, browserFallbackUrl, canLaunchExternalFallbackResult);
assert canLaunchExternalFallbackResult.get() != null;
RecordHistogram.recordTimesHistogram(
"Android.StrictMode.OverrideUrlLoadingTime", SystemClock.elapsedRealtime() - time);
if (result.getResultType() != OverrideUrlLoadingResultType.NO_OVERRIDE) {
int pageTransitionCore = params.getPageTransition() & PageTransition.CORE_MASK;
boolean isFormSubmit = pageTransitionCore == PageTransition.FORM_SUBMIT;
boolean isRedirectFromFormSubmit = isFormSubmit && params.isRedirect();
if (isRedirectFromFormSubmit) {
RecordHistogram.recordBooleanHistogram(
"Android.Intent.LaunchExternalAppFormSubmitHasUserGesture",
params.hasUserGesture());
}
} else {
result = handleFallbackUrl(params, targetIntent, browserFallbackUrl,
canLaunchExternalFallbackResult.get());
}
if (DEBUG) printDebugShouldOverrideUrlLoadingResultType(result);
return result;
}
private OverrideUrlLoadingResult handleFallbackUrl(ExternalNavigationParams params,
Intent targetIntent, GURL browserFallbackUrl, boolean canLaunchExternalFallback) {
if (browserFallbackUrl.isEmpty()
|| (params.getRedirectHandler() != null
// For instance, if this is a chained fallback URL, we ignore it.
&& params.getRedirectHandler().shouldNotOverrideUrlLoading())) {
return OverrideUrlLoadingResult.forNoOverride();
}
if (mDelegate.isIntentToInstantApp(targetIntent)) {
RecordHistogram.recordEnumeratedHistogram("Android.InstantApps.DirectInstantAppsIntent",
AiaIntent.FALLBACK_USED, AiaIntent.NUM_ENTRIES);
}
if (canLaunchExternalFallback) {
if (shouldBlockAllExternalAppLaunches(params)) {
throw new SecurityException("Context is not allowed to launch an external app.");
}
if (!params.isIncognito()) {
// Launch WebAPK if it can handle the URL.
try {
Intent intent =
Intent.parseUri(browserFallbackUrl.getSpec(), Intent.URI_INTENT_SCHEME);
sanitizeQueryIntentActivitiesIntent(intent);
List<ResolveInfo> resolvingInfos = queryIntentActivities(intent);
if (!isAlreadyInTargetWebApk(resolvingInfos, params)
&& launchWebApkIfSoleIntentHandler(resolvingInfos, intent)) {
return OverrideUrlLoadingResult.forExternalIntent();
}
} catch (Exception e) {
if (DEBUG) Log.i(TAG, "Could not parse fallback url as intent");
}
}
// If the fallback URL is a link to Play Store, send the user to Play Store app
// instead: crbug.com/638672.
Pair<String, String> appInfo = maybeGetPlayStoreAppIdAndReferrer(browserFallbackUrl);
if (appInfo != null) {
String marketReferrer = TextUtils.isEmpty(appInfo.second)
? ContextUtils.getApplicationContext().getPackageName()
: appInfo.second;
return sendIntentToMarket(
appInfo.first, marketReferrer, params, browserFallbackUrl);
}
}
// For subframes, we don't support fallback url for now. If we ever do implement this, be
// careful to prevent sandbox escapes.
// http://crbug.com/364522.
if (!params.isMainFrame()) {
if (DEBUG) Log.i(TAG, "Don't support fallback url in subframes");
return OverrideUrlLoadingResult.forNoOverride();
}
// NOTE: any further redirection from fall-back URL should not override URL loading.
// Otherwise, it can be used in chain for fingerprinting multiple app installation
// status in one shot. In order to prevent this scenario, we notify redirection
// handler that redirection from the current navigation should stay in this app.
if (params.getRedirectHandler() != null
&& !params.getRedirectHandler()
.getAndClearShouldNotBlockOverrideUrlLoadingOnCurrentRedirectionChain()) {
params.getRedirectHandler().setShouldNotOverrideUrlLoadingOnCurrentRedirectChain();
}
if (DEBUG) Log.i(TAG, "clobberCurrentTab called");
return clobberCurrentTab(browserFallbackUrl, params.getReferrerUrl());
}
private void printDebugShouldOverrideUrlLoadingResultType(OverrideUrlLoadingResult result) {
String resultString;
switch (result.getResultType()) {
case OverrideUrlLoadingResultType.OVERRIDE_WITH_EXTERNAL_INTENT:
resultString = "OVERRIDE_WITH_EXTERNAL_INTENT";
break;
case OverrideUrlLoadingResultType.OVERRIDE_WITH_CLOBBERING_TAB:
resultString = "OVERRIDE_WITH_CLOBBERING_TAB";
break;
case OverrideUrlLoadingResultType.OVERRIDE_WITH_ASYNC_ACTION:
resultString = "OVERRIDE_WITH_ASYNC_ACTION";
break;
case OverrideUrlLoadingResultType.NO_OVERRIDE: // Fall through.
default:
resultString = "NO_OVERRIDE";
break;
}
Log.i(TAG, "shouldOverrideUrlLoading result: " + resultString);
}
private boolean resolversSubsetOf(List<ResolveInfo> infos, List<ResolveInfo> container) {
if (container == null) return false;
HashSet<ComponentName> containerSet = new HashSet<>();
for (ResolveInfo info : container) {
containerSet.add(
new ComponentName(info.activityInfo.packageName, info.activityInfo.name));
}
for (ResolveInfo info : infos) {
if (!containerSet.contains(
new ComponentName(info.activityInfo.packageName, info.activityInfo.name))) {
return false;
}
}
return true;
}
/**
* https://crbug.com/1094442: Don't allow any external navigation on AUTO_SUBFRAME navigation
* (eg. initial ad frame navigation).
*/
private boolean blockExternalNavFromAutoSubframe(ExternalNavigationParams params) {
int pageTransitionCore = params.getPageTransition() & PageTransition.CORE_MASK;
if (pageTransitionCore == PageTransition.AUTO_SUBFRAME) {
if (DEBUG) Log.i(TAG, "Auto navigation in subframe");
return true;
}
return false;
}
/**
* http://crbug.com/441284 : Disallow firing external intent while the app is in the background.
*/
private boolean blockExternalNavWhileBackgrounded(ExternalNavigationParams params) {
if (params.isApplicationMustBeInForeground() && !mDelegate.isApplicationInForeground()) {
if (DEBUG) Log.i(TAG, "App is not in foreground");
return true;
}
return false;
}
/** http://crbug.com/464669 : Disallow firing external intent from background tab. */
private boolean blockExternalNavFromBackgroundTab(ExternalNavigationParams params) {
if (params.isBackgroundTabNavigation()
&& !params.areIntentLaunchesAllowedInBackgroundTabs()) {
if (DEBUG) Log.i(TAG, "Navigation in background tab");
return true;
}
return false;
}
/**
* http://crbug.com/164194 . A navigation forwards or backwards should never trigger the intent
* picker.
*/
private boolean ignoreBackForwardNav(ExternalNavigationParams params) {
if ((params.getPageTransition() & PageTransition.FORWARD_BACK) != 0) {
if (DEBUG) Log.i(TAG, "Forward or back navigation");
return true;
}
return false;
}
/** http://crbug.com/605302 : Allow embedders to handle all pdf file downloads. */
private boolean isInternalPdfDownload(
boolean isExternalProtocol, ExternalNavigationParams params) {
if (!isExternalProtocol && isPdfDownload(params.getUrl())) {
if (DEBUG) Log.i(TAG, "PDF downloads are now handled internally");
return true;
}
return false;
}
/**
* If accessing a file URL, ensure that the user has granted the necessary file access
* to the app.
*/
private boolean startFileIntentIfNecessary(ExternalNavigationParams params) {
if (params.getUrl().getScheme().equals(UrlConstants.FILE_SCHEME)
&& shouldRequestFileAccess(params.getUrl())) {
startFileIntent(params);
if (DEBUG) Log.i(TAG, "Requesting filesystem access");
return true;
}
return false;
}
/**
* Trigger a UI affordance that will ask the user to grant file access. After the access
* has been granted or denied, continue loading the specified file URL.
*
* @param intent The intent to continue loading the file URL.
* @param referrerUrl The HTTP referrer URL.
* @param needsToCloseTab Whether this action should close the current tab.
*/
@VisibleForTesting
protected void startFileIntent(ExternalNavigationParams params) {
PermissionCallback permissionCallback = new PermissionCallback() {
@Override
public void onRequestPermissionsResult(String[] permissions, int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& mDelegate.hasValidTab()) {
clobberCurrentTab(params.getUrl(), params.getReferrerUrl());
} else {
// TODO(tedchoc): Show an indication to the user that the navigation failed
// instead of silently dropping it on the floor.
if (params.shouldCloseContentsOnOverrideUrlLoadingAndLaunchIntent()) {
// If the access was not granted, then close the tab if necessary.
mDelegate.closeTab();
}
}
}
};
if (!mDelegate.hasValidTab()) return;
mDelegate.getWindowAndroid().requestPermissions(
new String[] {permission.READ_EXTERNAL_STORAGE}, permissionCallback);
}
/**
* Clobber the current tab and try not to pass an intent when it should be handled internally
* so that we can deliver HTTP referrer information safely.
*
* @param url The new URL after clobbering the current tab.
* @param referrerUrl The HTTP referrer URL.
* @return OverrideUrlLoadingResultType (if the tab has been clobbered, or we're launching an
* intent.)
*/
@VisibleForTesting
protected OverrideUrlLoadingResult clobberCurrentTab(GURL url, GURL referrerUrl) {
int transitionType = PageTransition.LINK;
final LoadUrlParams loadUrlParams = new LoadUrlParams(url, transitionType);
if (!referrerUrl.isEmpty()) {
Referrer referrer = new Referrer(referrerUrl.getSpec(), ReferrerPolicy.ALWAYS);
loadUrlParams.setReferrer(referrer);
}
assert mDelegate.hasValidTab() : "clobberCurrentTab was called with an empty tab.";
// Loading URL will start a new navigation which cancels the current one
// that this clobbering is being done for. It leads to UAF. To avoid that,
// we're loading URL asynchronously. See https://crbug.com/732260.
PostTask.postTask(UiThreadTaskTraits.DEFAULT, new Runnable() {
@Override
public void run() {
mDelegate.loadUrlIfPossible(loadUrlParams);
}
});
return OverrideUrlLoadingResult.forClobberingTab();
}
private static void loadUrlWithReferrer(
final GURL url, final GURL referrerUrl, ExternalNavigationDelegate delegate) {
LoadUrlParams loadUrlParams = new LoadUrlParams(url, PageTransition.AUTO_TOPLEVEL);
if (!referrerUrl.isEmpty()) {
Referrer referrer = new Referrer(referrerUrl.getSpec(), ReferrerPolicy.ALWAYS);
loadUrlParams.setReferrer(referrer);
}
delegate.loadUrlIfPossible(loadUrlParams);
}
private boolean isTypedRedirectToExternalProtocol(
ExternalNavigationParams params, int pageTransitionCore, boolean isExternalProtocol) {
boolean isTyped = (pageTransitionCore == PageTransition.TYPED)
|| ((params.getPageTransition() & PageTransition.FROM_ADDRESS_BAR) != 0);
return isTyped && params.isRedirect() && isExternalProtocol;
}
/**
* http://crbug.com/659301: Don't stay in Chrome for Custom Tabs redirecting to Instant Apps.
*/
private boolean handleCCTRedirectsToInstantApps(ExternalNavigationParams params,
boolean isExternalProtocol, boolean incomingIntentRedirect) {
RedirectHandler handler = params.getRedirectHandler();
if (handler == null) return false;
if (handler.isFromCustomTabIntent() && !isExternalProtocol && incomingIntentRedirect
&& !handler.shouldNavigationTypeStayInApp()
&& mDelegate.maybeLaunchInstantApp(
params.getUrl(), params.getReferrerUrl(), true, isSerpReferrer())) {
if (DEBUG) {
Log.i(TAG, "Launching redirect to an instant app");
}
return true;
}
return false;
}
private boolean redirectShouldStayInApp(
ExternalNavigationParams params, boolean isExternalProtocol, Intent targetIntent) {
RedirectHandler handler = params.getRedirectHandler();
if (handler == null) return false;
boolean shouldStayInApp = handler.shouldStayInApp(
isExternalProtocol, mDelegate.isIntentForTrustedCallingApp(targetIntent));
if (shouldStayInApp || handler.shouldNotOverrideUrlLoading()) {
if (DEBUG) Log.i(TAG, "RedirectHandler decision");
return true;
}
return false;
}
/** Wrapper of check against the feature to support overriding for testing. */
@VisibleForTesting
boolean blockExternalFormRedirectsWithoutGesture() {
return ExternalIntentsFeatures.INTENT_BLOCK_EXTERNAL_FORM_REDIRECT_NO_GESTURE.isEnabled();
}
/**
* http://crbug.com/149218: We want to show the intent picker for ordinary links, providing
* the link is not an incoming intent from another application, unless it's a redirect.
*/
private boolean preferToShowIntentPicker(ExternalNavigationParams params,
int pageTransitionCore, boolean isExternalProtocol, boolean isFormSubmit,
boolean linkNotFromIntent, boolean incomingIntentRedirect, boolean isFromIntent,
ResolveInfoSupplier resolveInfos) {
// https://crbug.com/1232514: On Android S, since WebAPKs aren't verified apps they are
// never launched as the result of a suitable Intent, the user's default browser will be
// opened instead. As a temporary solution, have Chrome launch the WebAPK.
if (isFromIntent && mDelegate.shouldLaunchWebApksOnInitialIntent()) {
boolean suitableWebApk = pickWebApkIfSoleIntentHandler(resolveInfos.get()) != null;
if (suitableWebApk) return true;
}
// http://crbug.com/169549 : If you type in a URL that then redirects in server side to a
// link that cannot be rendered by the browser, we want to show the intent picker.
if (isTypedRedirectToExternalProtocol(params, pageTransitionCore, isExternalProtocol)) {
return true;
}
// http://crbug.com/181186: We need to show the intent picker when we receive a redirect
// following a form submit.
boolean isRedirectFromFormSubmit = isFormSubmit && params.isRedirect();
if (!linkNotFromIntent && !incomingIntentRedirect && !isRedirectFromFormSubmit) {
if (DEBUG) Log.i(TAG, "Incoming intent (not a redirect)");
return false;
}
// http://crbug.com/839751: Require user gestures for form submits to external
// protocols.
// TODO(tedchoc): Turn this on by default once we verify this change does
// not break the world.
if (isRedirectFromFormSubmit && !incomingIntentRedirect && !params.hasUserGesture()
&& blockExternalFormRedirectsWithoutGesture()) {
if (DEBUG) {
Log.i(TAG,
"Incoming form intent attempting to redirect without "
+ "user gesture");
}
return false;
}
// http://crbug/331571 : Do not override a navigation started from user typing.
if (params.getRedirectHandler() != null
&& params.getRedirectHandler().isNavigationFromUserTyping()) {
if (DEBUG) Log.i(TAG, "Navigation from user typing");
return false;
}
return true;
}
/**
* http://crbug.com/159153: Don't override navigation from a chrome:* url to http or https. For
* example when clicking a link in bookmarks or most visited. When navigating from such a page,
* there is clear intent to complete the navigation in Chrome.
*/
private boolean isLinkFromChromeInternalPage(ExternalNavigationParams params) {
if (params.getReferrerUrl().getScheme().equals(UrlConstants.CHROME_SCHEME)
&& UrlUtilities.isHttpOrHttps(params.getUrl())) {
if (DEBUG) Log.i(TAG, "Link from an internal chrome:// page");
return true;
}
return false;
}
private boolean handleWtaiMcProtocol(ExternalNavigationParams params) {
if (!params.getUrl().getSpec().startsWith(WTAI_MC_URL_PREFIX)) return false;
// wtai://wp/mc;number
// number=string(phone-number)
String phoneNumber = params.getUrl().getSpec().substring(WTAI_MC_URL_PREFIX.length());
startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(WebView.SCHEME_TEL + phoneNumber)), false);
if (DEBUG) Log.i(TAG, "wtai:// link handled");
RecordUserAction.record("Android.PhoneIntent");
return true;
}
private boolean isUnhandledWtaiProtocol(ExternalNavigationParams params) {
if (!params.getUrl().getSpec().startsWith(WTAI_URL_PREFIX)) return false;
if (DEBUG) Log.i(TAG, "Unsupported wtai:// link");
return true;
}
/**
* The "about:", "chrome:", "chrome-native:", and "devtools:" schemes
* are internal to the browser; don't want these to be dispatched to other apps.
*/
private boolean hasInternalScheme(GURL targetUrl, Intent targetIntent) {
if (isInternalScheme(targetUrl.getScheme())) {
if (DEBUG) Log.i(TAG, "Navigating to a chrome-internal page");
return true;
}
if (UrlUtilities.hasIntentScheme(targetUrl) && targetIntent.getData() != null
&& isInternalScheme(targetIntent.getData().getScheme())) {
if (DEBUG) Log.i(TAG, "Navigating to a chrome-internal page");
return true;
}
return false;
}
private static boolean isInternalScheme(String scheme) {
if (TextUtils.isEmpty(scheme)) return false;
return scheme.equals(ContentUrlConstants.ABOUT_SCHEME)
|| scheme.equals(UrlConstants.CHROME_SCHEME)
|| scheme.equals(UrlConstants.CHROME_NATIVE_SCHEME)
|| scheme.equals(UrlConstants.DEVTOOLS_SCHEME);
}
/**
* The "content:" scheme is disabled in Clank. Do not try to start an external activity, or
* load the URL in-browser.
*/
private boolean hasContentScheme(GURL targetUrl, Intent targetIntent) {
boolean hasContentScheme = false;
if (UrlUtilities.hasIntentScheme(targetUrl) && targetIntent.getData() != null) {
hasContentScheme =
UrlConstants.CONTENT_SCHEME.equals(targetIntent.getData().getScheme());
} else {
hasContentScheme = UrlConstants.CONTENT_SCHEME.equals(targetUrl.getScheme());
}
if (DEBUG && hasContentScheme) Log.i(TAG, "Navigation to content: URL");
return hasContentScheme;
}
/**
* Intent URIs leads to creating intents that chrome would use for firing external navigations
* via Android. Android throws an exception [1] when an application exposes a file:// Uri to
* another app.
*
* This method checks if the |targetIntent| contains the file:// scheme in its data.
*
* [1]: https://developer.android.com/reference/android/os/FileUriExposedException
*/
private boolean hasFileSchemeInIntentURI(GURL targetUrl, Intent targetIntent) {
// We are only concerned with targetIntent that was generated due to intent:// schemes only.
if (!UrlUtilities.hasIntentScheme(targetUrl)) return false;
Uri data = targetIntent.getData();
if (data == null || data.getScheme() == null) return false;
if (data.getScheme().equalsIgnoreCase(UrlConstants.FILE_SCHEME)) {
if (DEBUG) Log.i(TAG, "Intent navigation to file: URI");
return true;
}
return false;
}
/**
* Special case - It makes no sense to use an external application for a YouTube
* pairing code URL, since these match the current tab with a device (Chromecast
* or similar) it is supposed to be controlling. Using a different application
* that isn't expecting this (in particular YouTube) doesn't work.
*/
@VisibleForTesting
protected boolean isYoutubePairingCode(GURL url) {
if (url.domainIs("youtube.com")
&& !TextUtils.isEmpty(UrlUtilities.getValueForKeyInQuery(url, "pairingCode"))) {
if (DEBUG) Log.i(TAG, "YouTube URL with a pairing code");
return true;
}
return false;
}
private boolean externalIntentRequestsDisabledForUrl(ExternalNavigationParams params) {
// TODO(changwan): check if we need to handle URL even when external intent is off.
if (CommandLine.getInstance().hasSwitch(
ExternalIntentsSwitches.DISABLE_EXTERNAL_INTENT_REQUESTS)) {
Log.w(TAG, "External intent handling is disabled by a command-line flag.");
return true;
}
if (mDelegate.shouldDisableExternalIntentRequestsForUrl(params.getUrl())) {
if (DEBUG) Log.i(TAG, "Delegate disables external intent requests for URL.");
return true;
}
return false;
}
/**
* If the intent can't be resolved, we should fall back to the browserFallbackUrl, or try to
* find the app on the market if no fallback is provided.
*/
private OverrideUrlLoadingResult handleUnresolvableIntent(
ExternalNavigationParams params, Intent targetIntent, GURL browserFallbackUrl) {
// Fallback URL will be handled by the caller of shouldOverrideUrlLoadingInternal.
if (!browserFallbackUrl.isEmpty()) return OverrideUrlLoadingResult.forNoOverride();
if (targetIntent.getPackage() != null) {
return handleWithMarketIntent(params, targetIntent);
}
if (DEBUG) Log.i(TAG, "Could not find an external activity to use");
return OverrideUrlLoadingResult.forNoOverride();
}
private OverrideUrlLoadingResult handleWithMarketIntent(
ExternalNavigationParams params, Intent intent) {
String marketReferrer = IntentUtils.safeGetStringExtra(intent, EXTRA_MARKET_REFERRER);
if (TextUtils.isEmpty(marketReferrer)) {
marketReferrer = ContextUtils.getApplicationContext().getPackageName();
}
return sendIntentToMarket(intent.getPackage(), marketReferrer, params, GURL.emptyGURL());
}
private boolean maybeSetSmsPackage(Intent targetIntent) {
final Uri uri = targetIntent.getData();
if (targetIntent.getPackage() == null && uri != null
&& UrlConstants.SMS_SCHEME.equals(uri.getScheme())) {
List<ResolveInfo> resolvingInfos = queryIntentActivities(targetIntent);
targetIntent.setPackage(getDefaultSmsPackageName(resolvingInfos));
return true;
}
return false;
}
private void maybeRecordPhoneIntentMetrics(Intent targetIntent) {
final Uri uri = targetIntent.getData();
if (uri != null && UrlConstants.TEL_SCHEME.equals(uri.getScheme())
|| (Intent.ACTION_DIAL.equals(targetIntent.getAction()))
|| (Intent.ACTION_CALL.equals(targetIntent.getAction()))) {
RecordUserAction.record("Android.PhoneIntent");
}
}
/**
* In incognito mode, links that can be handled within the browser should just do so,
* without asking the user.
*/
private boolean shouldStayInIncognito(
ExternalNavigationParams params, boolean isExternalProtocol) {
if (params.isIncognito() && !isExternalProtocol) {
if (DEBUG) Log.i(TAG, "Stay incognito");
return true;
}
return false;
}
private boolean fallBackToHandlingWithInstantApp(ExternalNavigationParams params,
boolean incomingIntentRedirect, boolean linkNotFromIntent) {
if (incomingIntentRedirect
&& mDelegate.maybeLaunchInstantApp(
params.getUrl(), params.getReferrerUrl(), true, isSerpReferrer())) {
if (DEBUG) Log.i(TAG, "Launching instant Apps redirect");
return true;
} else if (linkNotFromIntent && !params.isIncognito()
&& mDelegate.maybeLaunchInstantApp(
params.getUrl(), params.getReferrerUrl(), false, isSerpReferrer())) {
if (DEBUG) Log.i(TAG, "Launching instant Apps link");
return true;
}
return false;
}
/**
* This is the catch-all path for any intent that the app can handle that doesn't have a
* specialized external app handling it.
*/
private OverrideUrlLoadingResult fallBackToHandlingInApp() {
if (DEBUG) Log.i(TAG, "No specialized handler for URL");
return OverrideUrlLoadingResult.forNoOverride();
}
/**
* Returns true if an intent is an ACTION_VIEW intent targeting browsers or browser-like apps
* (excluding the embedding app).
*/
private boolean isViewIntentToOtherBrowser(Intent targetIntent, List<ResolveInfo> resolveInfos,
boolean isIntentWithSupportedProtocol, boolean hasSpecializedHandler) {
// Note that up until at least Android S, an empty action will match any intent filter
// with with an action specified. If an intent selector is specified, then don't trust the
// action on the intent.
if (!TextUtils.isEmpty(targetIntent.getAction())
&& !targetIntent.getAction().equals(Intent.ACTION_VIEW)
&& targetIntent.getSelector() == null) {
return false;
}
if (targetIntent.getPackage() != null
&& targetIntent.getPackage().equals(
ContextUtils.getApplicationContext().getPackageName())) {
return false;
}
String selfPackageName = mDelegate.getContext().getPackageName();
boolean matchesOtherPackage = false;
for (ResolveInfo resolveInfo : resolveInfos) {
ActivityInfo info = resolveInfo.activityInfo;
if (info == null || !selfPackageName.equals(info.packageName)) {
matchesOtherPackage = true;
break;
}
}
if (!matchesOtherPackage) return false;
// Shortcut the queryIntentActivities if the scheme is a browser-supported scheme.
if (isIntentWithSupportedProtocol && !hasSpecializedHandler) return true;
// Fall back to querying for browser packages if the intent doesn't obviously match or not
// match a browser. This will catch custom URL schemes like googlechrome://.
Set<String> browserPackages = getInstalledBrowserPackages();
if (hasSpecializedHandler) {
List<String> specializedPackages = getSpecializedHandlers(resolveInfos);
for (String packageName : specializedPackages) {
// A non-browser package is specialized, so don't consider it to be targeting a
// browser.
if (!browserPackages.contains(packageName)) return false;
}
}
for (ResolveInfo resolveInfo : resolveInfos) {
ActivityInfo info = resolveInfo.activityInfo;
if (info != null && browserPackages.contains(info.packageName)) {
return true;
}
}
return false;
}
private static Set<String> getInstalledBrowserPackages() {
List<ResolveInfo> browsers = PackageManagerUtils.queryAllWebBrowsersInfo();
Set<String> packageNames = new HashSet<>();
for (ResolveInfo browser : browsers) {
if (browser.activityInfo == null) continue;
packageNames.add(browser.activityInfo.packageName);
}
return packageNames;
}
/**
* Current URL has at least one specialized handler available. For navigations
* within the same host, keep the navigation inside the browser unless the set of
* available apps to handle the new navigation is different. http://crbug.com/463138
*/
private boolean shouldStayWithinHost(ExternalNavigationParams params, boolean isLink,
boolean isFormSubmit, List<ResolveInfo> resolvingInfos, boolean isExternalProtocol) {
if (isExternalProtocol) return false;
GURL previousUrl = getLastCommittedUrl();
if (previousUrl == null) previousUrl = params.getReferrerUrl();
if (previousUrl.isEmpty() || (!isLink && !isFormSubmit)) return false;
GURL currentUrl = params.getUrl();
if (!TextUtils.equals(currentUrl.getHost(), previousUrl.getHost())) {
return false;
}
Intent previousIntent = new Intent(Intent.ACTION_VIEW);
previousIntent.setData(Uri.parse(previousUrl.getSpec()));
if (resolversSubsetOf(resolvingInfos, queryIntentActivities(previousIntent))) {
if (DEBUG) Log.i(TAG, "Same host, no new resolvers");
return true;
}
return false;
}
/**
* For security reasons, we disable all intent:// URLs to Instant Apps that are not coming from
* SERP.
*/
private boolean preventDirectInstantAppsIntent(
boolean isDirectInstantAppsIntent, boolean shouldProxyForInstantApps) {
if (!isDirectInstantAppsIntent || shouldProxyForInstantApps) return false;
if (DEBUG) Log.i(TAG, "Intent URL to an Instant App");
RecordHistogram.recordEnumeratedHistogram("Android.InstantApps.DirectInstantAppsIntent",
AiaIntent.OTHER, AiaIntent.NUM_ENTRIES);
return true;
}
/**
* Prepare the intent to be sent. This function does not change the filtering for the intent,
* so the list if resolveInfos for the intent will be the same before and after this function.
*/
private void prepareExternalIntent(Intent targetIntent, ExternalNavigationParams params,
List<ResolveInfo> resolvingInfos, boolean shouldProxyForInstantApps) {
// Set the Browser application ID to us in case the user chooses this app
// as the app. This will make sure the link is opened in the same tab
// instead of making a new one in the case of Chrome.
targetIntent.putExtra(Browser.EXTRA_APPLICATION_ID,
ContextUtils.getApplicationContext().getPackageName());
if (params.isOpenInNewTab()) targetIntent.putExtra(Browser.EXTRA_CREATE_NEW_TAB, true);
targetIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Ensure intents re-target potential caller activity when we run in CCT mode.
targetIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mDelegate.maybeSetWindowId(targetIntent);
targetIntent.putExtra(EXTRA_EXTERNAL_NAV_PACKAGES, getSpecializedHandlers(resolvingInfos));
if (!params.getReferrerUrl().isEmpty()) {
mDelegate.maybeSetPendingReferrer(targetIntent, params.getReferrerUrl());
}
if (params.isIncognito()) mDelegate.maybeSetPendingIncognitoUrl(targetIntent);
mDelegate.maybeAdjustInstantAppExtras(targetIntent, shouldProxyForInstantApps);
if (shouldProxyForInstantApps) {
RecordHistogram.recordEnumeratedHistogram("Android.InstantApps.DirectInstantAppsIntent",
AiaIntent.SERP, AiaIntent.NUM_ENTRIES);
}
mDelegate.maybeSetRequestMetadata(targetIntent, params.hasUserGesture(),
params.isRendererInitiated(), params.getInitiatorOrigin());
}
private OverrideUrlLoadingResult handleExternalIncognitoIntent(Intent targetIntent,
ExternalNavigationParams params, GURL browserFallbackUrl,
boolean shouldProxyForInstantApps) {
// This intent may leave this app. Warn the user that incognito does not carry over
// to external apps.
if (startIncognitoIntent(
params, targetIntent, browserFallbackUrl, shouldProxyForInstantApps)) {
if (DEBUG) Log.i(TAG, "Incognito navigation out");
return OverrideUrlLoadingResult.forAsyncAction(
OverrideUrlLoadingAsyncActionType.UI_GATING_INTENT_LAUNCH);
}
if (DEBUG) Log.i(TAG, "Failed to show incognito alert dialog.");
return OverrideUrlLoadingResult.forNoOverride();
}
/**
* Display a dialog warning the user that they may be leaving this app by starting this
* intent. Give the user the opportunity to cancel the action. And if it is canceled, a
* navigation will happen in this app. Catches BadTokenExceptions caused by showing the dialog
* on certain devices. (crbug.com/782602)
* @param intent The intent for external application that will be sent.
* @param referrerUrl The referrer for the current navigation.
* @param fallbackUrl The URL to load if the user doesn't proceed with external intent.
* @param needsToCloseTab Whether the current tab has to be closed after the intent is sent.
* @param proxy Whether we need to proxy the intent through AuthenticatedProxyActivity (this is
* used by Instant Apps intents.
* @return True if the function returned error free, false if it threw an exception.
*/
private boolean startIncognitoIntent(
ExternalNavigationParams params, Intent intent, GURL fallbackUrl, boolean proxy) {
Context context = mDelegate.getContext();
if (!canLaunchIncognitoIntent(intent, context)) return false;
if (mDelegate.hasCustomLeavingIncognitoDialog()) {
mDelegate.presentLeavingIncognitoModalDialog(shouldLaunch -> {
onUserDecidedWhetherToLaunchIncognitoIntent(
shouldLaunch.booleanValue(), params, intent, fallbackUrl, proxy);
});
return true;
}
try {
AlertDialog dialog =
showLeavingIncognitoAlert(context, params, intent, fallbackUrl, proxy);
return dialog != null;
} catch (BadTokenException e) {
return false;
}
}
@VisibleForTesting
protected boolean canLaunchIncognitoIntent(Intent intent, Context context) {
if (!mDelegate.hasValidTab()) return false;
if (ContextUtils.activityFromContext(context) == null) return false;
return true;
}
/**
* Shows and returns an AlertDialog asking if the user would like to leave incognito.
*/
@VisibleForTesting
protected AlertDialog showLeavingIncognitoAlert(final Context context,
final ExternalNavigationParams params, final Intent intent, final GURL fallbackUrl,
final boolean proxy) {
return new AlertDialog.Builder(context, R.style.Theme_Chromium_AlertDialog)
.setTitle(R.string.external_app_leave_incognito_warning_title)
.setMessage(R.string.external_app_leave_incognito_warning)
.setPositiveButton(R.string.external_app_leave_incognito_leave,
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
onUserDecidedWhetherToLaunchIncognitoIntent(
/*shouldLaunch=*/true, params, intent, fallbackUrl, proxy);
}
})
.setNegativeButton(R.string.external_app_leave_incognito_stay,
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
onUserDecidedWhetherToLaunchIncognitoIntent(
/*shouldLaunch=*/false, params, intent, fallbackUrl, proxy);
}
})
.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
onUserDecidedWhetherToLaunchIncognitoIntent(
/*shouldLaunch=*/false, params, intent, fallbackUrl, proxy);
}
})
.show();
}
private void onUserDecidedWhetherToLaunchIncognitoIntent(final boolean shouldLaunch,
final ExternalNavigationParams params, final Intent intent, final GURL fallbackUrl,
final boolean proxy) {
boolean closeTab = params.shouldCloseContentsOnOverrideUrlLoadingAndLaunchIntent();
if (shouldLaunch) {
try {
startActivity(intent, proxy);
if (mDelegate.canCloseTabOnIncognitoIntentLaunch() && closeTab) {
mDelegate.closeTab();
}
} catch (ActivityNotFoundException e) {
// The activity that we thought was going to handle the intent
// no longer exists, so catch the exception and assume Chrome
// can handle it.
handleFallbackUrl(params, intent, fallbackUrl, false);
}
} else {
handleFallbackUrl(params, intent, fallbackUrl, false);
}
}
/**
* If some third-party app launched this app with an intent, and the URL got redirected, and the
* user explicitly chose this app over other intent handlers, stay in the app unless there was a
* new intent handler after redirection or the app cannot handle it internally any more.
* Custom tabs are an exception to this rule, since at no point, the user sees an intent picker
* and "picking the Chrome app" is handled inside the support library.
*/
private boolean shouldKeepIntentRedirectInApp(ExternalNavigationParams params,
boolean incomingIntentRedirect, List<ResolveInfo> resolvingInfos,
boolean isExternalProtocol) {
if (params.getRedirectHandler() != null && incomingIntentRedirect && !isExternalProtocol
&& !params.getRedirectHandler().isFromCustomTabIntent()
&& !params.getRedirectHandler().hasNewResolver(
resolvingInfos, (Intent intent) -> queryIntentActivities(intent))) {
if (DEBUG) Log.i(TAG, "Custom tab redirect no handled");
return true;
}
return false;
}
/**
* @param packageName The package to check.
* @return Whether the package is a valid WebAPK package.
*/
@VisibleForTesting
protected boolean isValidWebApk(String packageName) {
// Ensure that WebApkValidator is initialized (note: this method is a no-op after the first
// time that it is invoked).
WebApkValidator.init(
ChromeWebApkHostSignature.EXPECTED_SIGNATURE, ChromeWebApkHostSignature.PUBLIC_KEY);
return WebApkValidator.isValidWebApk(ContextUtils.getApplicationContext(), packageName);
}
/**
* Returns whether the activity belongs to a WebAPK and the URL is within the scope of the
* WebAPK. The WebAPK's main activity is a bouncer that redirects to the WebAPK Activity in
* Chrome. In order to avoid bouncing indefinitely, we should not override the navigation if we
* are currently showing the WebAPK (params#nativeClientPackageName()) that we will redirect to.
*/
private boolean isAlreadyInTargetWebApk(
List<ResolveInfo> resolveInfos, ExternalNavigationParams params) {
String currentName = params.nativeClientPackageName();
if (currentName == null) return false;
for (ResolveInfo resolveInfo : resolveInfos) {
ActivityInfo info = resolveInfo.activityInfo;
if (info != null && currentName.equals(info.packageName)) {
if (DEBUG) Log.i(TAG, "Already in WebAPK");
return true;
}
}
return false;
}
// This will handle external navigations only for intent meant for Autofill Assistant.
private boolean handleWithAutofillAssistant(
ExternalNavigationParams params, Intent targetIntent, GURL browserFallbackUrl) {
if (!mDelegate.isIntentToAutofillAssistant(targetIntent)) {
return false;
}
// Launching external intents is always forbidden in incognito. Handle the intent with
// Autofill Assistant instead. Note that Autofill Assistant won't start in incognito either,
// this will only result in navigating to the browserFallbackUrl.
if (!params.isIncognito()) {
@IntentToAutofillAllowingAppResult
int intentAllowingAppResult = mDelegate.isIntentToAutofillAssistantAllowingApp(params,
targetIntent,
(intent)
-> getSpecializedHandlersWithFilter(queryIntentActivities(intent),
/* filterPackageName= */ null,
/* handlesInstantAppLaunchingInternally= */ false)
.size()
== 1);
switch (intentAllowingAppResult) {
case IntentToAutofillAllowingAppResult.DEFER_TO_APP_NOW:
if (DEBUG) {
Log.i(TAG, "Autofill Assistant passed in favour of App.");
}
return false;
case IntentToAutofillAllowingAppResult.DEFER_TO_APP_LATER:
if (params.getRedirectHandler() != null && isGoogleReferrer()) {
if (DEBUG) {
Log.i(TAG, "Autofill Assistant passed in favour of App later.");
}
params.getRedirectHandler()
.setShouldNotBlockUrlLoadingOverrideOnCurrentRedirectionChain();
return true;
}
break;
case IntentToAutofillAllowingAppResult.NONE:
break;
}
}
if (mDelegate.handleWithAutofillAssistant(
params, targetIntent, browserFallbackUrl, isGoogleReferrer())) {
if (DEBUG) Log.i(TAG, "Handled with Autofill Assistant.");
} else {
if (DEBUG) Log.i(TAG, "Not handled with Autofill Assistant.");
}
return true;
}
// Check if we're navigating under conditions that should never launch an external app.
private boolean shouldBlockAllExternalAppLaunches(ExternalNavigationParams params) {
return blockExternalNavFromAutoSubframe(params) || blockExternalNavWhileBackgrounded(params)
|| blockExternalNavFromBackgroundTab(params) || ignoreBackForwardNav(params);
}
private OverrideUrlLoadingResult shouldOverrideUrlLoadingInternal(
ExternalNavigationParams params, Intent targetIntent, GURL browserFallbackUrl,
MutableBoolean canLaunchExternalFallbackResult) {
sanitizeQueryIntentActivitiesIntent(targetIntent);
// Don't allow external fallback URLs by default.
canLaunchExternalFallbackResult.set(false);
if (shouldBlockAllExternalAppLaunches(params)) {
return OverrideUrlLoadingResult.forNoOverride();
}
if (handleWithAutofillAssistant(params, targetIntent, browserFallbackUrl)) {
return OverrideUrlLoadingResult.forNoOverride();
}
GURL intentDataUrl = new GURL(targetIntent.getDataString());
boolean isExternalProtocol = !UrlUtilities.isAcceptedScheme(params.getUrl());
// intent: URLs are considered an external protocol, but may still contain a Data URI that
// this app does support, and may still end up launching this app.
boolean isIntentWithSupportedProtocol = UrlUtilities.hasIntentScheme(params.getUrl())
&& UrlUtilities.isAcceptedScheme(intentDataUrl);
if (isInternalPdfDownload(isExternalProtocol, params)) {
return OverrideUrlLoadingResult.forNoOverride();
}
// This check should happen for reloads, navigations, etc..., which is why
// it occurs before the subsequent blocks.
if (startFileIntentIfNecessary(params)) {
return OverrideUrlLoadingResult.forAsyncAction(
OverrideUrlLoadingAsyncActionType.UI_GATING_BROWSER_NAVIGATION);
}
// This should come after file intents, but before any returns of
// OVERRIDE_WITH_EXTERNAL_INTENT.
if (externalIntentRequestsDisabledForUrl(params)) {
return OverrideUrlLoadingResult.forNoOverride();
}
int pageTransitionCore = params.getPageTransition() & PageTransition.CORE_MASK;
boolean isLink = pageTransitionCore == PageTransition.LINK;
boolean isFormSubmit = pageTransitionCore == PageTransition.FORM_SUBMIT;
boolean isFromIntent = (params.getPageTransition() & PageTransition.FROM_API) != 0;
boolean linkNotFromIntent = isLink && !isFromIntent;
boolean isOnEffectiveIntentRedirect = params.getRedirectHandler() == null
? false
: params.getRedirectHandler().isOnEffectiveIntentRedirectChain();
// http://crbug.com/170925: We need to show the intent picker when we receive an intent from
// another app that 30x redirects to a YouTube/Google Maps/Play Store/Google+ URL etc.
boolean incomingIntentRedirect =
(isLink && isFromIntent && params.isRedirect()) || isOnEffectiveIntentRedirect;
final boolean canOpenInExternalApp = ContextUtils.getAppSharedPreferences().getBoolean("open_in_external_app", false);
if (!isExternalProtocol && !canOpenInExternalApp && params.getUrl() != null && !params.getUrl().getSpec().contains("play.google.com") && !params.getUrl().getSpec().startsWith("market://")) {
return OverrideUrlLoadingResult.forNoOverride();
}
if (handleCCTRedirectsToInstantApps(params, isExternalProtocol, incomingIntentRedirect)) {
return OverrideUrlLoadingResult.forExternalIntent();
} else if (redirectShouldStayInApp(params, isExternalProtocol, targetIntent)) {
return OverrideUrlLoadingResult.forNoOverride();
}
if (!maybeSetSmsPackage(targetIntent)) maybeRecordPhoneIntentMetrics(targetIntent);
Intent debugIntent = new Intent(targetIntent);
ResolveInfoSupplier resolvingInfos = new ResolveInfoSupplier(targetIntent);
if (!preferToShowIntentPicker(params, pageTransitionCore, isExternalProtocol, isFormSubmit,
linkNotFromIntent, incomingIntentRedirect, isFromIntent, resolvingInfos)) {
return OverrideUrlLoadingResult.forNoOverride();
}
if (isLinkFromChromeInternalPage(params)) return OverrideUrlLoadingResult.forNoOverride();
if (handleWtaiMcProtocol(params)) {
return OverrideUrlLoadingResult.forExternalIntent();
}
// TODO: handle other WTAI schemes.
if (isUnhandledWtaiProtocol(params)) return OverrideUrlLoadingResult.forNoOverride();
if (hasInternalScheme(params.getUrl(), targetIntent)
|| hasContentScheme(params.getUrl(), targetIntent)
|| hasFileSchemeInIntentURI(params.getUrl(), targetIntent)) {
return OverrideUrlLoadingResult.forNoOverride();
}
if (isYoutubePairingCode(params.getUrl())) return OverrideUrlLoadingResult.forNoOverride();
if (shouldStayInIncognito(params, isExternalProtocol)) {
return OverrideUrlLoadingResult.forNoOverride();
}
// From this point on, we have determined it is safe to launch an External App from a
// fallback URL.
canLaunchExternalFallbackResult.set(true);
if (resolvingInfos.get().isEmpty()) {
return handleUnresolvableIntent(params, targetIntent, browserFallbackUrl);
}
if (!browserFallbackUrl.isEmpty()) targetIntent.removeExtra(EXTRA_BROWSER_FALLBACK_URL);
boolean hasSpecializedHandler = countSpecializedHandlers(resolvingInfos.get()) > 0;
if (!isExternalProtocol && !hasSpecializedHandler) {
if (fallBackToHandlingWithInstantApp(
params, incomingIntentRedirect, linkNotFromIntent)) {
return OverrideUrlLoadingResult.forExternalIntent();
}
return fallBackToHandlingInApp();
}
// From this point on we should only have URLs from intent URIs, or URLs for
// apps with specialized handlers (including custom schemes).
if (shouldStayWithinHost(
params, isLink, isFormSubmit, resolvingInfos.get(), isExternalProtocol)) {
return OverrideUrlLoadingResult.forNoOverride();
}
boolean isDirectInstantAppsIntent =
isExternalProtocol && mDelegate.isIntentToInstantApp(targetIntent);
boolean shouldProxyForInstantApps = isDirectInstantAppsIntent && isSerpReferrer();
if (preventDirectInstantAppsIntent(isDirectInstantAppsIntent, shouldProxyForInstantApps)) {
return OverrideUrlLoadingResult.forNoOverride();
}
prepareExternalIntent(
targetIntent, params, resolvingInfos.get(), shouldProxyForInstantApps);
// As long as our intent resolution hasn't changed, resolvingInfos won't need to be
// re-computed as it won't have changed.
assert intentResolutionMatches(debugIntent, targetIntent);
if (params.isIncognito()) {
return handleIncognitoIntent(params, targetIntent, intentDataUrl, resolvingInfos.get(),
browserFallbackUrl, shouldProxyForInstantApps);
}
if (shouldKeepIntentRedirectInApp(
params, incomingIntentRedirect, resolvingInfos.get(), isExternalProtocol)) {
return OverrideUrlLoadingResult.forNoOverride();
}
if (isAlreadyInTargetWebApk(resolvingInfos.get(), params)) {
return OverrideUrlLoadingResult.forNoOverride();
} else if (launchWebApkIfSoleIntentHandler(resolvingInfos.get(), targetIntent)) {
return OverrideUrlLoadingResult.forExternalIntent();
}
boolean requiresIntentChooser = false;
if (isViewIntentToOtherBrowser(targetIntent, resolvingInfos.get(),
isIntentWithSupportedProtocol, hasSpecializedHandler)) {
RecordHistogram.recordBooleanHistogram("Android.Intent.WebIntentToOtherBrowser", true);
requiresIntentChooser = true;
}
return startActivityIfNeeded(targetIntent, shouldProxyForInstantApps, resolvingInfos.get(),
requiresIntentChooser, browserFallbackUrl, intentDataUrl, params.getReferrerUrl());
}
private OverrideUrlLoadingResult handleIncognitoIntent(ExternalNavigationParams params,
Intent targetIntent, GURL intentDataUrl, List<ResolveInfo> resolvingInfos,
GURL browserFallbackUrl, boolean shouldProxyForInstantApps) {
boolean intentTargetedToApp = mDelegate.willAppHandleIntent(targetIntent);
GURL fallbackUrl = browserFallbackUrl;
// If we can handle the intent, then fall back to handling the target URL instead of
// the fallbackUrl if the user decides not to leave incognito.
if (resolveInfoContainsSelf(resolvingInfos)) {
GURL targetUrl =
UrlUtilities.hasIntentScheme(params.getUrl()) ? intentDataUrl : params.getUrl();
// Make sure the browser can handle this URL, in case the Intent targeted a
// non-browser component for this app.
if (UrlUtilities.isAcceptedScheme(targetUrl)) fallbackUrl = targetUrl;
}
// The user is about to potentially leave the app, so we should ask whether they want to
// leave incognito or not.
if (!intentTargetedToApp) {
return handleExternalIncognitoIntent(
targetIntent, params, fallbackUrl, shouldProxyForInstantApps);
}
// The intent is staying in the app, so we can simply navigate to the intent's URL,
// while staying in incognito.
return handleFallbackUrl(params, targetIntent, fallbackUrl, false);
}
/**
* Sanitize intent to be passed to {@link queryIntentActivities()}
* ensuring that web pages cannot bypass browser security.
*/
private void sanitizeQueryIntentActivitiesIntent(Intent intent) {
intent.setFlags(intent.getFlags() & ALLOWED_INTENT_FLAGS);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setComponent(null);
Intent selector = intent.getSelector();
if (selector != null) {
selector.addCategory(Intent.CATEGORY_BROWSABLE);
selector.setComponent(null);
}
}
/**
* @return OVERRIDE_WITH_EXTERNAL_INTENT when we successfully started market activity,
* NO_OVERRIDE otherwise.
*/
private OverrideUrlLoadingResult sendIntentToMarket(String packageName, String marketReferrer,
ExternalNavigationParams params, GURL fallbackUrl) {
Uri marketUri =
new Uri.Builder()
.scheme("market")
.authority("details")
.appendQueryParameter(PLAY_PACKAGE_PARAM, packageName)
.appendQueryParameter(PLAY_REFERRER_PARAM, Uri.decode(marketReferrer))
.build();
Intent intent = new Intent(Intent.ACTION_VIEW, marketUri);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setPackage("com.android.vending");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (!params.getReferrerUrl().isEmpty()) {
intent.putExtra(Intent.EXTRA_REFERRER, Uri.parse(params.getReferrerUrl().getSpec()));
}
if (!deviceCanHandleIntent(intent)) {
// Exit early if the Play Store isn't available. (https://crbug.com/820709)
if (DEBUG) Log.i(TAG, "Play Store not installed.");
return OverrideUrlLoadingResult.forNoOverride();
}
if (params.isIncognito()) {
if (!startIncognitoIntent(params, intent, fallbackUrl, false)) {
if (DEBUG) Log.i(TAG, "Failed to show incognito alert dialog.");
return OverrideUrlLoadingResult.forNoOverride();
}
if (DEBUG) Log.i(TAG, "Incognito intent to Play Store.");
return OverrideUrlLoadingResult.forAsyncAction(
OverrideUrlLoadingAsyncActionType.UI_GATING_INTENT_LAUNCH);
} else {
startActivity(intent, false);
if (DEBUG) Log.i(TAG, "Intent to Play Store.");
return OverrideUrlLoadingResult.forExternalIntent();
}
}
/**
* If the given URL is to Google Play, extracts the package name and referrer tracking code
* from the {@param url} and returns as a Pair in that order. Otherwise returns null.
*/
private Pair<String, String> maybeGetPlayStoreAppIdAndReferrer(GURL url) {
if (PLAY_HOSTNAME.equals(url.getHost()) && url.getPath().startsWith(PLAY_APP_PATH)) {
String playPackage = UrlUtilities.getValueForKeyInQuery(url, PLAY_PACKAGE_PARAM);
if (TextUtils.isEmpty(playPackage)) return null;
return new Pair<String, String>(
playPackage, UrlUtilities.getValueForKeyInQuery(url, PLAY_REFERRER_PARAM));
}
return null;
}
/**
* @return Whether the |url| could be handled by an external application on the system.
*/
@VisibleForTesting
boolean canExternalAppHandleUrl(GURL url) {
if (url.getSpec().startsWith(WTAI_MC_URL_PREFIX)) return true;
Intent intent;
try {
intent = Intent.parseUri(url.getSpec(), Intent.URI_INTENT_SCHEME);
} catch (Exception ex) {
// Ignore the error.
Log.w(TAG, "Bad URI %s", url, ex);
return false;
}
if (intent.getPackage() != null) return true;
List<ResolveInfo> resolvingInfos = queryIntentActivities(intent);
return resolvingInfos != null && !resolvingInfos.isEmpty();
}
/**
* Dispatch SMS intents to the default SMS application if applicable.
* Most SMS apps refuse to send SMS if not set as default SMS application.
*
* @param resolvingComponentNames The list of ComponentName that resolves the current intent.
*/
private String getDefaultSmsPackageName(List<ResolveInfo> resolvingComponentNames) {
String defaultSmsPackageName = getDefaultSmsPackageNameFromSystem();
if (defaultSmsPackageName == null) return null;
// Makes sure that the default SMS app actually resolves the intent.
for (ResolveInfo resolveInfo : resolvingComponentNames) {
if (defaultSmsPackageName.equals(resolveInfo.activityInfo.packageName)) {
return defaultSmsPackageName;
}
}
return null;
}
/**
* Launches WebAPK if the WebAPK is the sole non-browser handler for the given intent.
* @return Whether a WebAPK was launched.
*/
private boolean launchWebApkIfSoleIntentHandler(
List<ResolveInfo> resolvingInfos, Intent targetIntent) {
String packageName = pickWebApkIfSoleIntentHandler(resolvingInfos);
if (packageName == null) return false;
Intent webApkIntent = new Intent(targetIntent);
webApkIntent.setPackage(packageName);
try {
startActivity(webApkIntent, false);
if (DEBUG) Log.i(TAG, "Launched WebAPK");
return true;
} catch (ActivityNotFoundException e) {
// The WebApk must have been uninstalled/disabled since we queried for Activities to
// handle this intent.
if (DEBUG) Log.i(TAG, "WebAPK launch failed");
return false;
}
}
@Nullable
private String pickWebApkIfSoleIntentHandler(List<ResolveInfo> resolvingInfos) {
ArrayList<String> packages = getSpecializedHandlers(resolvingInfos);
if (packages.size() != 1 || !isValidWebApk(packages.get(0))) return null;
return packages.get(0);
}
/**
* Returns whether or not there's an activity available to handle the intent.
*/
private boolean deviceCanHandleIntent(Intent intent) {
List<ResolveInfo> resolveInfos = queryIntentActivities(intent);
return resolveInfos != null && !resolveInfos.isEmpty();
}
/**
* See {@link PackageManagerUtils#queryIntentActivities(Intent, int)}
*/
@NonNull
private List<ResolveInfo> queryIntentActivities(Intent intent) {
return PackageManagerUtils.queryIntentActivities(
intent, PackageManager.GET_RESOLVED_FILTER | PackageManager.MATCH_DEFAULT_ONLY);
}
private static boolean intentResolutionMatches(Intent intent, Intent other) {
return intent.filterEquals(other)
&& (intent.getSelector() == other.getSelector()
|| intent.getSelector().filterEquals(other.getSelector()));
}
/**
* @return Whether the URL is a file download.
*/
@VisibleForTesting
boolean isPdfDownload(GURL url) {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(url.getSpec());
if (TextUtils.isEmpty(fileExtension)) return false;
return PDF_EXTENSION.equals(fileExtension);
}
private static boolean isPdfIntent(Intent intent) {
if (intent == null || intent.getData() == null) return false;
String filename = intent.getData().getLastPathSegment();
return (filename != null && filename.endsWith(PDF_SUFFIX))
|| PDF_MIME.equals(intent.getType());
}
/**
* Records the dispatching of an external intent.
*/
private static void recordExternalNavigationDispatched(Intent intent) {
ArrayList<String> specializedHandlers =
intent.getStringArrayListExtra(EXTRA_EXTERNAL_NAV_PACKAGES);
if (specializedHandlers != null && specializedHandlers.size() > 0) {
RecordUserAction.record("MobileExternalNavigationDispatched");
}
}
/**
* If the intent is for a pdf, resolves intent handlers to find the platform pdf viewer if
* it is available and force is for the provided |intent| so that the user doesn't need to
* choose it from Intent picker.
*
* @param intent Intent to open.
*/
private static void forcePdfViewerAsIntentHandlerIfNeeded(Intent intent) {
if (intent == null || !isPdfIntent(intent)) return;
resolveIntent(intent, true /* allowSelfOpen (ignored) */);
}
/**
* Retrieve the best activity for the given intent. If a default activity is provided,
* choose the default one. Otherwise, return the Intent picker if there are more than one
* capable activities. If the intent is pdf type, return the platform pdf viewer if
* it is available so user don't need to choose it from Intent picker.
*
* @param intent Intent to open.
* @param allowSelfOpen Whether chrome itself is allowed to open the intent.
* @return true if the intent can be resolved, or false otherwise.
*/
public static boolean resolveIntent(Intent intent, boolean allowSelfOpen) {
Context context = ContextUtils.getApplicationContext();
ResolveInfo info =
PackageManagerUtils.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (info == null) return false;
final String packageName = context.getPackageName();
if (info.match != 0) {
// There is a default activity for this intent, use that.
return allowSelfOpen || !packageName.equals(info.activityInfo.packageName);
}
List<ResolveInfo> handlers = PackageManagerUtils.queryIntentActivities(
intent, PackageManager.MATCH_DEFAULT_ONLY);
if (handlers == null || handlers.isEmpty()) return false;
boolean canSelfOpen = false;
boolean hasPdfViewer = false;
for (ResolveInfo resolveInfo : handlers) {
String pName = resolveInfo.activityInfo.packageName;
if (packageName.equals(pName)) {
canSelfOpen = true;
} else if (PDF_VIEWER.equals(pName)) {
if (isPdfIntent(intent)) {
intent.setClassName(pName, resolveInfo.activityInfo.name);
Uri referrer = new Uri.Builder()
.scheme(IntentUtils.ANDROID_APP_REFERRER_SCHEME)
.authority(packageName)
.build();
intent.putExtra(Intent.EXTRA_REFERRER, referrer);
hasPdfViewer = true;
break;
}
}
}
return !canSelfOpen || allowSelfOpen || hasPdfViewer;
}
/**
* Start an activity for the intent. Used for intents that must be handled externally.
* @param intent The intent we want to send.
* @param proxy Whether we need to proxy the intent through AuthenticatedProxyActivity (this is
* used by Instant Apps intents).
*/
private void startActivity(Intent intent, boolean proxy) {
try {
forcePdfViewerAsIntentHandlerIfNeeded(intent);
if (proxy) {
mDelegate.dispatchAuthenticatedIntent(intent);
} else {
// Start the activity via the current activity if possible, and otherwise as a new
// task from the application context.
Context context = ContextUtils.activityFromContext(mDelegate.getContext());
if (context == null) {
context = ContextUtils.getApplicationContext();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
}
recordExternalNavigationDispatched(intent);
} catch (RuntimeException e) {
Log.e(TAG, "Could not start Activity for intent " + intent.toString(), e);
}
mDelegate.didStartActivity(intent);
}
/**
* Start an activity for the intent. Used for intents that may be handled internally or
* externally.
* @param intent The intent we want to send.
* @param proxy Whether we need to proxy the intent through AuthenticatedProxyActivity (this is
* used by Instant Apps intents).
* @param resolvingInfos The resolvingInfos |intent| matches against.
* @param requiresIntentChooser Whether, for security reasons, the Intent Chooser is required to
* be shown.
* @param browserFallbackUrl The fallback URL if the user chooses not to leave this app.
* @param intentDataUrl The URL |intent| is targeting.
* @param referrerUrl The referrer for the navigation.
* @returns The OverrideUrlLoadingResult for starting (or not starting) the Activity.
*/
private OverrideUrlLoadingResult startActivityIfNeeded(Intent intent, boolean proxy,
List<ResolveInfo> resolvingInfos, boolean requiresIntentChooser,
GURL browserFallbackUrl, GURL intentDataUrl, GURL referrerUrl) {
// Only touches disk on Kitkat. See http://crbug.com/617725 for more context.
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
try {
boolean withoutPackage = TextUtils.isEmpty(intent.getPackage());
// TODO(https://crbug.com/1251722): Rename this delegate function and require
// the delegate to defer to the code below to actually launch the Activity.
@ExternalNavigationDelegate.StartActivityIfNeededResult
int delegateResult = mDelegate.maybeHandleStartActivityIfNeeded(intent, proxy);
if (withoutPackage
&& (!TextUtils.isEmpty(intent.getPackage()) || intent.getComponent() != null)) {
// Embedder chose a package for this Intent, we no longer need to use the chooser.
requiresIntentChooser = false;
}
switch (delegateResult) {
case ExternalNavigationDelegate.StartActivityIfNeededResult
.HANDLED_WITH_ACTIVITY_START:
return OverrideUrlLoadingResult.forExternalIntent();
case ExternalNavigationDelegate.StartActivityIfNeededResult
.HANDLED_WITHOUT_ACTIVITY_START:
return OverrideUrlLoadingResult.forNoOverride();
case ExternalNavigationDelegate.StartActivityIfNeededResult.DID_NOT_HANDLE:
return startActivityIfNeededInternal(intent, proxy, resolvingInfos,
requiresIntentChooser, browserFallbackUrl, intentDataUrl, referrerUrl);
default:
assert false;
}
} catch (SecurityException e) {
// https://crbug.com/808494: Handle the URL internally if dispatching to another
// application fails with a SecurityException. This happens due to malformed
// manifests in another app.
} catch (ActivityNotFoundException e) {
// The targeted app must have been uninstalled/disabled since we queried for Activities
// to handle this intent.
if (DEBUG) Log.i(TAG, "Activity not found.");
} catch (AndroidRuntimeException e) {
// https://crbug.com/1226177: Most likely cause of this exception is Android failing
// to start the app that we previously detected could handle the Intent.
Log.e(TAG, "Could not start Activity for intent " + intent.toString(), e);
} catch (RuntimeException e) {
IntentUtils.logTransactionTooLargeOrRethrow(e, intent);
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
return OverrideUrlLoadingResult.forNoOverride();
}
/**
* Implementation of startActivityIfNeeded() that is used when the delegate does not handle the
* event.
*/
private OverrideUrlLoadingResult startActivityIfNeededInternal(Intent intent, boolean proxy,
List<ResolveInfo> resolvingInfos, boolean requiresIntentChooser,
GURL browserFallbackUrl, GURL intentDataUrl, GURL referrerUrl) {
forcePdfViewerAsIntentHandlerIfNeeded(intent);
if (proxy) {
mDelegate.dispatchAuthenticatedIntent(intent);
recordExternalNavigationDispatched(intent);
return OverrideUrlLoadingResult.forExternalIntent();
} else {
Activity activity = ContextUtils.activityFromContext(mDelegate.getContext());
if (activity == null) return OverrideUrlLoadingResult.forNoOverride();
if (requiresIntentChooser) {
return startActivityWithChooser(intent, resolvingInfos, browserFallbackUrl,
intentDataUrl, referrerUrl, activity);
}
return doStartActivityIfNeeded(intent, activity);
}
}
private OverrideUrlLoadingResult doStartActivityIfNeeded(Intent intent, Activity activity) {
if (activity.startActivityIfNeeded(intent, -1)) {
if (DEBUG) Log.i(TAG, "startActivityIfNeeded");
mDelegate.didStartActivity(intent);
recordExternalNavigationDispatched(intent);
return OverrideUrlLoadingResult.forExternalIntent();
} else {
if (DEBUG) Log.i(TAG, "The current Activity was the only targeted Activity.");
return OverrideUrlLoadingResult.forNoOverride();
}
}
@SuppressWarnings("UseCompatLoadingForDrawables")
private OverrideUrlLoadingResult startActivityWithChooser(final Intent intent,
List<ResolveInfo> resolvingInfos, GURL browserFallbackUrl, GURL intentDataUrl,
GURL referrerUrl, Activity activity) {
ResolveInfo intentResolveInfo =
PackageManagerUtils.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
// If this is null, then the intent was only previously matching
// non-default filters, so just drop it.
if (intentResolveInfo == null) return OverrideUrlLoadingResult.forNoOverride();
// If the |resolvingInfos| from queryIntentActivities don't contain the result of
// resolveActivity, it means the intent is resolving to the ResolverActivity, so the user
// will already get the option to choose the target app (as there will be multiple options)
// and we don't need to do anything. Otherwise we have to make a fake option in the chooser
// dialog that loads the URL in the embedding app.
if (!resolversSubsetOf(Arrays.asList(intentResolveInfo), resolvingInfos)) {
return doStartActivityIfNeeded(intent, activity);
}
Intent pickerIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
pickerIntent.putExtra(Intent.EXTRA_INTENT, intent);
// Add the fake entry for the embedding app. This behavior is not well documented but works
// consistently across Android since L (and at least up to S).
PackageManager pm = activity.getPackageManager();
ArrayList<ShortcutIconResource> icons = new ArrayList<>();
ArrayList<String> labels = new ArrayList<>();
String packageName = activity.getPackageName();
String label = "";
ShortcutIconResource resource = new ShortcutIconResource();
try {
ApplicationInfo applicationInfo =
pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
label = (String) pm.getApplicationLabel(applicationInfo);
Resources resources = pm.getResourcesForApplication(applicationInfo);
resource.packageName = packageName;
resource.resourceName = resources.getResourceName(applicationInfo.icon);
// This will throw a Resources.NotFoundException if the package uses resource
// name collapsing/stripping. The ActivityPicker fails to handle this exception, we have
// have to check for it here to avoid crashes.
resources.getDrawable(resources.getIdentifier(resource.resourceName, null, null), null);
} catch (NameNotFoundException | Resources.NotFoundException e) {
Log.w(TAG, "No icon resource found for package: " + packageName);
// Most likely the app doesn't have an icon and is just a test
// app. Android will just use a blank icon.
resource.packageName = "";
resource.resourceName = "";
}
labels.add(label);
icons.add(resource);
pickerIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, labels);
pickerIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icons);
// Call startActivityForResult on the PICK_ACTIVITY intent, which will set the component of
// the data result to the component of the chosen app.
mDelegate.getWindowAndroid().showCancelableIntent(
pickerIntent, new WindowAndroid.IntentCallback() {
@Override
public void onIntentCompleted(int resultCode, Intent data) {
// If |data| is null, the user backed out of the intent chooser.
if (data == null) return;
// Quirk of how we use the ActivityChooser - if the embedding app is
// chosen we get an intent back with ACTION_CREATE_SHORTCUT.
if (data.getAction().equals(Intent.ACTION_CREATE_SHORTCUT)) {
// It's pretty arbitrary whether to prefer the data URL or the fallback
// URL here. We could consider preferring the fallback URL, as the URL
// was probably intending to leave Chrome, but loading the URL the site
// was trying to load in a browser seems like the better choice and
// matches what would have happened had the regular chooser dialog shown
// up and the user selected this app.
if (UrlUtilities.isAcceptedScheme(intentDataUrl)) {
clobberCurrentTab(intentDataUrl, referrerUrl);
} else if (!browserFallbackUrl.isEmpty()) {
clobberCurrentTab(browserFallbackUrl, referrerUrl);
}
return;
}
// Set the package for the original intent to the chosen app and start
// it. Note that a selector cannot be set at the same time as a package.
intent.setSelector(null);
intent.setPackage(data.getComponent().getPackageName());
startActivity(intent, false);
}
}, null);
return OverrideUrlLoadingResult.forAsyncAction(
OverrideUrlLoadingAsyncActionType.UI_GATING_INTENT_LAUNCH);
}
/**
* Returns the number of specialized intent handlers in {@params infos}. Specialized intent
* handlers are intent handlers which handle only a few URLs (e.g. google maps or youtube).
*/
private int countSpecializedHandlers(List<ResolveInfo> infos) {
return getSpecializedHandlersWithFilter(
infos, null, mDelegate.handlesInstantAppLaunchingInternally())
.size();
}
/**
* Returns the subset of {@params infos} that are specialized intent handlers.
*/
private ArrayList<String> getSpecializedHandlers(List<ResolveInfo> infos) {
return getSpecializedHandlersWithFilter(
infos, null, mDelegate.handlesInstantAppLaunchingInternally());
}
private static boolean matchResolveInfoExceptWildCardHost(
ResolveInfo info, String filterPackageName) {
IntentFilter intentFilter = info.filter;
if (intentFilter == null) {
// Error on the side of classifying ResolveInfo as generic.
return false;
}
if (intentFilter.countDataAuthorities() == 0 && intentFilter.countDataPaths() == 0) {
// Don't count generic handlers.
return false;
}
boolean isWildCardHost = false;
Iterator<IntentFilter.AuthorityEntry> it = intentFilter.authoritiesIterator();
while (it != null && it.hasNext()) {
IntentFilter.AuthorityEntry entry = it.next();
if ("*".equals(entry.getHost())) {
isWildCardHost = true;
break;
}
}
if (isWildCardHost) {
return false;
}
if (!TextUtils.isEmpty(filterPackageName)
&& (info.activityInfo == null
|| !info.activityInfo.packageName.equals(filterPackageName))) {
return false;
}
return true;
}
public static ArrayList<String> getSpecializedHandlersWithFilter(List<ResolveInfo> infos,
String filterPackageName, boolean handlesInstantAppLaunchingInternally) {
ArrayList<String> result = new ArrayList<>();
if (infos == null) {
return result;
}
for (ResolveInfo info : infos) {
if (!matchResolveInfoExceptWildCardHost(info, filterPackageName)) {
continue;
}
if (info.activityInfo != null) {
if (handlesInstantAppLaunchingInternally
&& IntentUtils.isInstantAppResolveInfo(info)) {
// Don't add the Instant Apps launcher as a specialized handler if the embedder
// handles launching of Instant Apps itself.
continue;
}
result.add(info.activityInfo.packageName);
} else {
result.add("");
}
}
return result;
}
protected boolean resolveInfoContainsSelf(List<ResolveInfo> resolveInfos) {
String packageName = mDelegate.getContext().getPackageName();
for (ResolveInfo resolveInfo : resolveInfos) {
ActivityInfo info = resolveInfo.activityInfo;
if (info != null && packageName.equals(info.packageName)) {
return true;
}
}
return false;
}
/**
* @return Default SMS application's package name at the system level. Null if there isn't any.
*/
@VisibleForTesting
protected String getDefaultSmsPackageNameFromSystem() {
return Telephony.Sms.getDefaultSmsPackage(ContextUtils.getApplicationContext());
}
/**
* @return The last committed URL from the WebContents.
*/
@VisibleForTesting
protected GURL getLastCommittedUrl() {
if (mDelegate.getWebContents() == null) return null;
return mDelegate.getWebContents().getLastCommittedUrl();
}
/**
* @param url The requested url.
* @return Whether we should block the navigation and request file access before proceeding.
*/
@VisibleForTesting
protected boolean shouldRequestFileAccess(GURL url) {
// If the tab is null, then do not attempt to prompt for access.
if (!mDelegate.hasValidTab()) return false;
assert url.getScheme().equals(UrlConstants.FILE_SCHEME);
// If the url points inside of Chromium's data directory, no permissions are necessary.
// This is required to prevent permission prompt when uses wants to access offline pages.
if (url.getPath().startsWith(PathUtils.getDataDirectory())) return false;
return !mDelegate.getWindowAndroid().hasPermission(permission.READ_EXTERNAL_STORAGE)
&& mDelegate.getWindowAndroid().canRequestPermission(
permission.READ_EXTERNAL_STORAGE);
}
@Nullable
// TODO(https://crbug.com/1194721): Investigate whether or not we can use
// getLastCommittedUrl() instead of the NavigationController. Or maybe we can just replace this
// with ExternalNavigationParams#getReferrerUrl?
private GURL getReferrerUrl() {
if (!mDelegate.hasValidTab() || mDelegate.getWebContents() == null) return null;
NavigationController nController = mDelegate.getWebContents().getNavigationController();
int index = nController.getLastCommittedEntryIndex();
if (index == -1) return null;
NavigationEntry entry = nController.getEntryAtIndex(index);
if (entry == null) return null;
return entry.getUrl();
}
/**
* @return whether this navigation is from the search results page.
*/
@VisibleForTesting
protected boolean isSerpReferrer() {
GURL referrerUrl = getReferrerUrl();
if (referrerUrl == null || referrerUrl.isEmpty()) return false;
return UrlUtilitiesJni.get().isGoogleSearchUrl(referrerUrl.getSpec());
}
/**
* @return whether this navigation is from a Google domain.
*/
@VisibleForTesting
protected boolean isGoogleReferrer() {
GURL referrerUrl = getReferrerUrl();
if (referrerUrl == null || referrerUrl.isEmpty()) return false;
return UrlUtilitiesJni.get().isGoogleSubDomainUrl(referrerUrl.getSpec());
}
}
| 38,995 |
47,529 |
<reponame>Jawnnypoo/RxJava<filename>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableMapNotificationTest.java
/*
* Copyright (c) 2016-present, RxJava Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package io.reactivex.rxjava3.internal.operators.flowable;
import org.junit.Test;
import org.reactivestreams.*;
import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.exceptions.*;
import io.reactivex.rxjava3.functions.*;
import io.reactivex.rxjava3.internal.functions.Functions;
import io.reactivex.rxjava3.internal.operators.flowable.FlowableMapNotification.MapNotificationSubscriber;
import io.reactivex.rxjava3.internal.subscriptions.BooleanSubscription;
import io.reactivex.rxjava3.processors.PublishProcessor;
import io.reactivex.rxjava3.subscribers.TestSubscriber;
import io.reactivex.rxjava3.testsupport.*;
public class FlowableMapNotificationTest extends RxJavaTest {
@Test
public void just() {
TestSubscriber<Object> ts = new TestSubscriber<>();
Flowable.just(1)
.flatMap(
new Function<Integer, Flowable<Object>>() {
@Override
public Flowable<Object> apply(Integer item) {
return Flowable.just((Object)(item + 1));
}
},
new Function<Throwable, Flowable<Object>>() {
@Override
public Flowable<Object> apply(Throwable e) {
return Flowable.error(e);
}
},
new Supplier<Flowable<Object>>() {
@Override
public Flowable<Object> get() {
return Flowable.never();
}
}
).subscribe(ts);
ts.assertNoErrors();
ts.assertNotComplete();
ts.assertValue(2);
}
@Test
public void backpressure() {
TestSubscriber<Object> ts = TestSubscriber.create(0L);
new FlowableMapNotification<>(Flowable.range(1, 3),
new Function<Integer, Integer>() {
@Override
public Integer apply(Integer item) {
return item + 1;
}
},
new Function<Throwable, Integer>() {
@Override
public Integer apply(Throwable e) {
return 0;
}
},
new Supplier<Integer>() {
@Override
public Integer get() {
return 5;
}
}
).subscribe(ts);
ts.assertNoValues();
ts.assertNoErrors();
ts.assertNotComplete();
ts.request(3);
ts.assertValues(2, 3, 4);
ts.assertNoErrors();
ts.assertNotComplete();
ts.request(1);
ts.assertValues(2, 3, 4, 5);
ts.assertNoErrors();
ts.assertComplete();
}
@Test
public void noBackpressure() {
TestSubscriber<Object> ts = TestSubscriber.create(0L);
PublishProcessor<Integer> pp = PublishProcessor.create();
new FlowableMapNotification<>(pp,
new Function<Integer, Integer>() {
@Override
public Integer apply(Integer item) {
return item + 1;
}
},
new Function<Throwable, Integer>() {
@Override
public Integer apply(Throwable e) {
return 0;
}
},
new Supplier<Integer>() {
@Override
public Integer get() {
return 5;
}
}
).subscribe(ts);
ts.assertNoValues();
ts.assertNoErrors();
ts.assertNotComplete();
pp.onNext(1);
pp.onNext(2);
pp.onNext(3);
pp.onComplete();
ts.assertNoValues();
ts.assertNoErrors();
ts.assertNotComplete();
ts.request(1);
ts.assertValue(0);
ts.assertNoErrors();
ts.assertComplete();
}
@Test
public void dispose() {
TestHelper.checkDisposed(new Flowable<Integer>() {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected void subscribeActual(Subscriber<? super Integer> subscriber) {
MapNotificationSubscriber mn = new MapNotificationSubscriber(
subscriber,
Functions.justFunction(Flowable.just(1)),
Functions.justFunction(Flowable.just(2)),
Functions.justSupplier(Flowable.just(3))
);
mn.onSubscribe(new BooleanSubscription());
}
});
}
@Test
public void doubleOnSubscribe() {
TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Object> f) throws Exception {
return f.flatMap(
Functions.justFunction(Flowable.just(1)),
Functions.justFunction(Flowable.just(2)),
Functions.justSupplier(Flowable.just(3))
);
}
});
}
@Test
public void onErrorCrash() {
TestSubscriberEx<Integer> ts = Flowable.<Integer>error(new TestException("Outer"))
.flatMap(Functions.justFunction(Flowable.just(1)),
new Function<Throwable, Publisher<Integer>>() {
@Override
public Publisher<Integer> apply(Throwable t) throws Exception {
throw new TestException("Inner");
}
},
Functions.justSupplier(Flowable.just(3)))
.to(TestHelper.<Integer>testConsumer())
.assertFailure(CompositeException.class);
TestHelper.assertError(ts, 0, TestException.class, "Outer");
TestHelper.assertError(ts, 1, TestException.class, "Inner");
}
}
| 3,398 |
1,144 |
package de.metas.security;
import java.util.Objects;
import javax.annotation.Nullable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import de.metas.util.Check;
import de.metas.util.lang.RepoIdAware;
import lombok.Value;
/*
* #%L
* de.metas.adempiere.adempiere.base
* %%
* Copyright (C) 2019 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
@Value
public class RoleId implements RepoIdAware
{
public static final RoleId SYSTEM = new RoleId(0);
/** Used by the reports service when it accesses the REST-API */
public static final RoleId JSON_REPORTS = new RoleId(540078);
@JsonCreator
public static RoleId ofRepoId(final int repoId)
{
final RoleId roleId = ofRepoIdOrNull(repoId);
return Check.assumeNotNull(roleId, "Unable to create a roleId for repoId={}", repoId);
}
public static RoleId ofRepoIdOrNull(final int repoId)
{
if (repoId == SYSTEM.getRepoId())
{
return SYSTEM;
}
else if (repoId == JSON_REPORTS.getRepoId())
{
return JSON_REPORTS;
}
else
{
return repoId > 0 ? new RoleId(repoId) : null;
}
}
public static int toRepoId(@Nullable final RoleId id)
{
return toRepoId(id, -1);
}
public static int toRepoId(@Nullable final RoleId id, final int defaultValue)
{
return id != null ? id.getRepoId() : defaultValue;
}
public static boolean equals(final RoleId id1, final RoleId id2)
{
return Objects.equals(id1, id2);
}
int repoId;
private RoleId(final int repoId)
{
this.repoId = Check.assumeGreaterOrEqualToZero(repoId, "AD_Role_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public boolean isSystem()
{
return repoId == SYSTEM.repoId;
}
public boolean isRegular()
{
return !isSystem();
}
}
| 862 |
2,160 |
<gh_stars>1000+
#!/usr/bin/env python3
from constructs import Construct
from cdk8s import App, Chart, Helm
class MyChart(Chart):
def __init__(self, scope: Construct, ns: str):
super().__init__(scope, ns)
Helm(self, 'redis',
chart='bitnami/redis',
values={
'sentinel': {
'enabled': True
}
}
)
app = App()
MyChart(app, "hello-helm")
app.synth()
| 239 |
2,338 |
<reponame>mkinsner/llvm<filename>clang/test/CodeGenCXX/homogeneous-aggregates.cpp<gh_stars>1000+
// RUN: %clang_cc1 -triple powerpc64le-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s --check-prefix=PPC
// RUN: %clang_cc1 -mfloat-abi hard -triple armv7-unknown-linux-gnueabi -emit-llvm -o - %s | FileCheck %s --check-prefix=ARM32
// RUN: %clang_cc1 -mfloat-abi hard -triple aarch64-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s --check-prefix=ARM64
// RUN: %clang_cc1 -mfloat-abi hard -triple x86_64-unknown-windows-gnu -emit-llvm -o - %s | FileCheck %s --check-prefix=X64
// RUN: %clang_cc1 -mfloat-abi hard -triple aarch64-unknown-windows-msvc -emit-llvm -o - %s | FileCheck %s --check-prefix=WOA64
#if defined(__x86_64__)
#define CC __attribute__((vectorcall))
#else
#define CC
#endif
// Test that C++ classes are correctly classified as homogeneous aggregates.
struct Base1 {
int x;
};
struct Base2 {
double x;
};
struct Base3 {
double x;
};
struct D1 : Base1 { // non-homogeneous aggregate
double y, z;
};
struct D2 : Base2 { // homogeneous aggregate
double y, z;
};
struct D3 : Base1, Base2 { // non-homogeneous aggregate
double y, z;
};
struct D4 : Base2, Base3 { // homogeneous aggregate
double y, z;
};
struct I1 : Base2 {};
struct I2 : Base2 {};
struct I3 : Base2 {};
struct D5 : I1, I2, I3 {}; // homogeneous aggregate
// PPC: define{{.*}} void @_Z7func_D12D1(%struct.D1* noalias sret(%struct.D1) align 8 %agg.result, [3 x i64] %x.coerce)
// ARM32: define{{.*}} arm_aapcs_vfpcc void @_Z7func_D12D1(%struct.D1* noalias sret(%struct.D1) align 8 %agg.result, [3 x i64] %x.coerce)
// ARM64: define{{.*}} void @_Z7func_D12D1(%struct.D1* noalias sret(%struct.D1) align 8 %agg.result, %struct.D1* %x)
// X64: define dso_local x86_vectorcallcc void @"\01_Z7func_D12D1@@24"(%struct.D1* noalias sret(%struct.D1) align 8 %agg.result, %struct.D1* %x)
D1 CC func_D1(D1 x) { return x; }
// PPC: define{{.*}} [3 x double] @_Z7func_D22D2([3 x double] %x.coerce)
// ARM32: define{{.*}} arm_aapcs_vfpcc %struct.D2 @_Z7func_D22D2(%struct.D2 %x.coerce)
// ARM64: define{{.*}} %struct.D2 @_Z7func_D22D2([3 x double] %x.coerce)
// X64: define dso_local x86_vectorcallcc %struct.D2 @"\01_Z7func_D22D2@@24"(%struct.D2 inreg %x.coerce)
D2 CC func_D2(D2 x) { return x; }
// PPC: define{{.*}} void @_Z7func_D32D3(%struct.D3* noalias sret(%struct.D3) align 8 %agg.result, [4 x i64] %x.coerce)
// ARM32: define{{.*}} arm_aapcs_vfpcc void @_Z7func_D32D3(%struct.D3* noalias sret(%struct.D3) align 8 %agg.result, [4 x i64] %x.coerce)
// ARM64: define{{.*}} void @_Z7func_D32D3(%struct.D3* noalias sret(%struct.D3) align 8 %agg.result, %struct.D3* %x)
D3 CC func_D3(D3 x) { return x; }
// PPC: define{{.*}} [4 x double] @_Z7func_D42D4([4 x double] %x.coerce)
// ARM32: define{{.*}} arm_aapcs_vfpcc %struct.D4 @_Z7func_D42D4(%struct.D4 %x.coerce)
// ARM64: define{{.*}} %struct.D4 @_Z7func_D42D4([4 x double] %x.coerce)
D4 CC func_D4(D4 x) { return x; }
D5 CC func_D5(D5 x) { return x; }
// PPC: define{{.*}} [3 x double] @_Z7func_D52D5([3 x double] %x.coerce)
// ARM32: define{{.*}} arm_aapcs_vfpcc %struct.D5 @_Z7func_D52D5(%struct.D5 %x.coerce)
// The C++ multiple inheritance expansion case is a little more complicated, so
// do some extra checking.
//
// ARM64-LABEL: define{{.*}} %struct.D5 @_Z7func_D52D5([3 x double] %x.coerce)
// ARM64: bitcast %struct.D5* %{{.*}} to [3 x double]*
// ARM64: store [3 x double] %x.coerce, [3 x double]*
void call_D5(D5 *p) {
func_D5(*p);
}
// Check the call site.
//
// ARM64-LABEL: define{{.*}} void @_Z7call_D5P2D5(%struct.D5* %p)
// ARM64: load [3 x double], [3 x double]*
// ARM64: call %struct.D5 @_Z7func_D52D5([3 x double] %{{.*}})
struct Empty { };
struct Float1 { float x; };
struct Float2 { float y; };
struct HVAWithEmptyBase : Float1, Empty, Float2 { float z; };
// PPC: define{{.*}} void @_Z15with_empty_base16HVAWithEmptyBase([3 x float] %a.coerce)
// ARM64: define{{.*}} void @_Z15with_empty_base16HVAWithEmptyBase([3 x float] %a.coerce)
// ARM32: define{{.*}} arm_aapcs_vfpcc void @_Z15with_empty_base16HVAWithEmptyBase(%struct.HVAWithEmptyBase %a.coerce)
void CC with_empty_base(HVAWithEmptyBase a) {}
// FIXME: MSVC doesn't consider this an HVA because of the empty base.
// X64: define dso_local x86_vectorcallcc void @"\01_Z15with_empty_base16HVAWithEmptyBase@@16"(%struct.HVAWithEmptyBase inreg %a.coerce)
struct HVAWithEmptyBitField : Float1, Float2 {
int : 0; // Takes no space.
float z;
};
// PPC: define{{.*}} void @_Z19with_empty_bitfield20HVAWithEmptyBitField([3 x float] %a.coerce)
// ARM64: define{{.*}} void @_Z19with_empty_bitfield20HVAWithEmptyBitField([3 x float] %a.coerce)
// ARM32: define{{.*}} arm_aapcs_vfpcc void @_Z19with_empty_bitfield20HVAWithEmptyBitField(%struct.HVAWithEmptyBitField %a.coerce)
// X64: define dso_local x86_vectorcallcc void @"\01_Z19with_empty_bitfield20HVAWithEmptyBitField@@16"(%struct.HVAWithEmptyBitField inreg %a.coerce)
void CC with_empty_bitfield(HVAWithEmptyBitField a) {}
namespace pr47611 {
// MSVC on Arm includes "isCXX14Aggregate" as part of its definition of
// Homogeneous Floating-point Aggregate (HFA). Additionally, it has a different
// handling of C++14 aggregates, which can lead to confusion.
// Pod is a trivial HFA.
struct Pod {
double b[2];
};
// Not an aggregate according to C++14 spec => not HFA according to MSVC.
struct NotCXX14Aggregate {
NotCXX14Aggregate();
Pod p;
};
// NotPod is a C++14 aggregate. But not HFA, because it contains
// NotCXX14Aggregate (which itself is not HFA because it's not a C++14
// aggregate).
struct NotPod {
NotCXX14Aggregate x;
};
struct Empty {};
// A class with a base is returned using the sret calling convetion by MSVC.
struct HasEmptyBase : public Empty {
double b[2];
};
struct HasPodBase : public Pod {};
// WOA64-LABEL: define dso_local %"struct.pr47611::Pod" @"?copy@pr47611@@YA?AUPod@1@PEAU21@@Z"(%"struct.pr47611::Pod"* %x)
Pod copy(Pod *x) { return *x; } // MSVC: ldp d0,d1,[x0], Clang: ldp d0,d1,[x0]
// WOA64-LABEL: define dso_local void @"?copy@pr47611@@YA?AUNotCXX14Aggregate@1@PEAU21@@Z"(%"struct.pr47611::NotCXX14Aggregate"* inreg noalias sret(%"struct.pr47611::NotCXX14Aggregate") align 8 %agg.result, %"struct.pr47611::NotCXX14Aggregate"* %x)
NotCXX14Aggregate copy(NotCXX14Aggregate *x) { return *x; } // MSVC: stp x8,x9,[x0], Clang: str q0,[x0]
// WOA64-LABEL: define dso_local [2 x i64] @"?copy@pr47611@@YA?AUNotPod@1@PEAU21@@Z"(%"struct.pr47611::NotPod"* %x)
NotPod copy(NotPod *x) { return *x; }
// WOA64-LABEL: define dso_local void @"?copy@pr47611@@YA?AUHasEmptyBase@1@PEAU21@@Z"(%"struct.pr47611::HasEmptyBase"* inreg noalias sret(%"struct.pr47611::HasEmptyBase") align 8 %agg.result, %"struct.pr47611::HasEmptyBase"* %x)
HasEmptyBase copy(HasEmptyBase *x) { return *x; }
// WOA64-LABEL: define dso_local void @"?copy@pr47611@@YA?AUHasPodBase@1@PEAU21@@Z"(%"struct.pr47611::HasPodBase"* inreg noalias sret(%"struct.pr47611::HasPodBase") align 8 %agg.result, %"struct.pr47611::HasPodBase"* %x)
HasPodBase copy(HasPodBase *x) { return *x; }
void call_copy_pod(Pod *pod) {
*pod = copy(pod);
// WOA64-LABEL: define dso_local void @"?call_copy_pod@pr47611@@YAXPEAUPod@1@@Z"
// WOA64: %{{.*}} = call %"struct.pr47611::Pod" @"?copy@pr47611@@YA?AUPod@1@PEAU21@@Z"(%"struct.pr47611::Pod"* %{{.*}})
}
void call_copy_notcxx14aggregate(NotCXX14Aggregate *notcxx14aggregate) {
*notcxx14aggregate = copy(notcxx14aggregate);
// WOA64-LABEL: define dso_local void @"?call_copy_notcxx14aggregate@pr47611@@YAXPEAUNotCXX14Aggregate@1@@Z"
// WOA64: call void @"?copy@pr47611@@YA?AUNotCXX14Aggregate@1@PEAU21@@Z"(%"struct.pr47611::NotCXX14Aggregate"* inreg sret(%"struct.pr47611::NotCXX14Aggregate") align 8 %{{.*}}, %"struct.pr47611::NotCXX14Aggregate"* %{{.*}})
}
void call_copy_notpod(NotPod *notPod) {
*notPod = copy(notPod);
// WOA64-LABEL: define dso_local void @"?call_copy_notpod@pr47611@@YAXPEAUNotPod@1@@Z"
// WOA64: %{{.*}} = call [2 x i64] @"?copy@pr47611@@YA?AUNotPod@1@PEAU21@@Z"(%"struct.pr47611::NotPod"* %{{.*}})
}
void call_copy_hasemptybase(HasEmptyBase *hasEmptyBase) {
*hasEmptyBase = copy(hasEmptyBase);
// WOA64-LABEL: define dso_local void @"?call_copy_hasemptybase@pr47611@@YAXPEAUHasEmptyBase@1@@Z"
// WOA64: call void @"?copy@pr47611@@YA?AUHasEmptyBase@1@PEAU21@@Z"(%"struct.pr47611::HasEmptyBase"* inreg sret(%"struct.pr47611::HasEmptyBase") align 8 %{{.*}}, %"struct.pr47611::HasEmptyBase"* %{{.*}})
}
void call_copy_haspodbase(HasPodBase *hasPodBase) {
*hasPodBase = copy(hasPodBase);
// WOA64-LABEL: define dso_local void @"?call_copy_haspodbase@pr47611@@YAXPEAUHasPodBase@1@@Z"
// WOA64: call void @"?copy@pr47611@@YA?AUHasPodBase@1@PEAU21@@Z"(%"struct.pr47611::HasPodBase"* inreg sret(%"struct.pr47611::HasPodBase") align 8 %{{.*}}, %"struct.pr47611::HasPodBase"* %{{.*}})
}
}; // namespace pr47611
| 3,723 |
3,603 |
<reponame>asantoz/trino<gh_stars>1000+
/*
* 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.trino.execution.scheduler;
import io.airlift.configuration.Config;
import io.airlift.configuration.validation.FileExists;
import io.airlift.units.Duration;
import io.airlift.units.MinDuration;
import java.io.File;
import static java.util.concurrent.TimeUnit.MINUTES;
public class TopologyFileConfig
{
private File networkTopologyFile;
private Duration refreshPeriod = new Duration(5, MINUTES);
@FileExists
public File getNetworkTopologyFile()
{
return networkTopologyFile;
}
@Config("node-scheduler.network-topology.file")
public TopologyFileConfig setNetworkTopologyFile(File networkTopologyFile)
{
this.networkTopologyFile = networkTopologyFile;
return this;
}
@MinDuration("1ms")
public Duration getRefreshPeriod()
{
return refreshPeriod;
}
@Config("node-scheduler.network-topology.refresh-period")
public TopologyFileConfig setRefreshPeriod(Duration refreshPeriod)
{
this.refreshPeriod = refreshPeriod;
return this;
}
}
| 553 |
2,542 |
// ------------------------------------------------------------
// 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
namespace Api
{
class ComFabricTransportMessageDisposeJobItem
{
DENY_COPY(ComFabricTransportMessageDisposeJobItem);
public:
ComFabricTransportMessageDisposeJobItem() {}
ComFabricTransportMessageDisposeJobItem(ComPointer<IFabricTransportMessage> && message)
: message_(move(message)) {
}
ComFabricTransportMessageDisposeJobItem(ComFabricTransportMessageDisposeJobItem && other)
: message_(move(other.message_))
{
}
ComFabricTransportMessageDisposeJobItem& operator=(ComFabricTransportMessageDisposeJobItem && other)
{
if (this != &other)
{
message_ = move(other.message_);
}
return *this;
}
bool ProcessJob(ComponentRoot &)
{
this->message_->Dispose();
return true;
}
private:
ComPointer<IFabricTransportMessage> message_;
};
}
| 515 |
571 |
/**
* @file getBoardObjectAndImagePoints.cpp
* @brief mex interface for cv::aruco::getBoardObjectAndImagePoints
* @ingroup aruco
* @author Amro
* @date 2017
*/
#include "mexopencv.hpp"
#include "mexopencv_aruco.hpp"
#include "opencv2/aruco.hpp"
using namespace std;
using namespace cv;
using namespace cv::aruco;
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Check the number of arguments
nargchk(nrhs==3 && nlhs<=2);
// Argument vector
vector<MxArray> rhs(prhs, prhs + nrhs);
// Process
Ptr<Board> board = MxArrayToBoard(rhs[0]);
vector<vector<Point2f> > corners(MxArrayToVectorVectorPoint<float>(rhs[1]));
vector<int> ids(rhs[2].toVector<int>());
vector<Point3f> objPoints;
vector<Point2f> imgPoints;
getBoardObjectAndImagePoints(board, corners, ids, objPoints, imgPoints);
plhs[0] = MxArray(objPoints);
if (nlhs > 1)
plhs[1] = MxArray(imgPoints);
}
| 476 |
335 |
{
"word": "Wringing",
"definitions": [
"Extremely wet; soaked."
],
"parts-of-speech": "Adjective"
}
| 60 |
372 |
<gh_stars>100-1000
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.content.model;
/**
* Response message for the `ListReturnPolicyOnline` method.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class ListReturnPolicyOnlineResponse extends com.google.api.client.json.GenericJson {
/**
* The retrieved return policies.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<ReturnPolicyOnline> returnPolicies;
/**
* The retrieved return policies.
* @return value or {@code null} for none
*/
public java.util.List<ReturnPolicyOnline> getReturnPolicies() {
return returnPolicies;
}
/**
* The retrieved return policies.
* @param returnPolicies returnPolicies or {@code null} for none
*/
public ListReturnPolicyOnlineResponse setReturnPolicies(java.util.List<ReturnPolicyOnline> returnPolicies) {
this.returnPolicies = returnPolicies;
return this;
}
@Override
public ListReturnPolicyOnlineResponse set(String fieldName, Object value) {
return (ListReturnPolicyOnlineResponse) super.set(fieldName, value);
}
@Override
public ListReturnPolicyOnlineResponse clone() {
return (ListReturnPolicyOnlineResponse) super.clone();
}
}
| 684 |
348 |
{"nom":"Grandrif","circ":"5ème circonscription","dpt":"Puy-de-Dôme","inscrits":210,"abs":102,"votants":108,"blancs":2,"nuls":2,"exp":104,"res":[{"nuance":"COM","nom":"M. <NAME>","voix":68},{"nuance":"REM","nom":"<NAME>","voix":36}]}
| 96 |
335 |
{
"word": "Impotence",
"definitions": [
"Inability to take effective action; helplessness.",
"Inability in a man to achieve an erection or orgasm."
],
"parts-of-speech": "Noun"
}
| 84 |
3,710 |
/*
* usage : lzodecompress.exe <output-size> <input-size>
*
* lzodecompress reads <input-size> bytes from stdin, decompress them and write the result to stdout
* the decompressed buffer must be <output-size> bytes
*
* errors are logged to stderr
* return == 0 iff no errors
*/
#include "lzo/lzoconf.h"
#include "lzo/lzo1x.h"
/* portability layer */
#define WANT_LZO_MALLOC 1
#include "lzo/lzoutil.h"
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#if defined(_WIN32)
#include <io.h>
#endif
int main(int argc, char *argv[])
{
lzo_uint src_len, dst_len;
lzo_bytep src;
lzo_bytep dst;
lzo_bytep wrkmem;
int r;
#if defined(_WIN32)
/* stdin/stdout must be binary streams */
r = _setmode(_fileno(stdout), _O_BINARY);
r = _setmode(_fileno(stdin), _O_BINARY);
#endif
if(argc != 3)
{
fprintf(stderr, "Usage : %s <output-size> <input-size>\n"
" <output-size> is the decompressed buffer size in bytes\n"
" <input-size> is the compressed buffer size in bytes\n", argv[0]);
return -1;
}
dst_len = atoi(argv[1]);
src_len = atoi(argv[2]);
if (lzo_init() != LZO_E_OK)
{
fprintf(stderr, "Couldn't initialize lzo\n");
return -2;
}
/* allocate and read input buffer */
src = (lzo_bytep) lzo_malloc(src_len);
fread(src, 1, src_len, stdin);
/* allocate the buffer for the decompressed data */
dst = (lzo_bytep) lzo_malloc(dst_len);
/* allocate the working memory for lzo */
wrkmem = (lzo_bytep) lzo_malloc(LZO1X_1_MEM_COMPRESS);
/* decompress data (note: lzo1x_decompress_safe does not throw exception. It instead can return error codes) */
r = lzo1x_decompress_safe(src, src_len, dst, &dst_len, wrkmem);
if (r == LZO_E_OK)
{
/* write compressed data */
fwrite(dst, 1, dst_len, stdout);
}
else
{
fprintf(stderr, "Compression failed : code = %d\n", r);
}
/* free the memory */
lzo_free(wrkmem);
lzo_free(dst);
lzo_free(src);
/* return code */
if (r == LZO_E_OK)
return 0;
else
return -3;
}
| 939 |
335 |
<filename>A/Atlas_noun.json
{
"word": "Atlas",
"definitions": [
"A book of maps or charts.",
"The topmost vertebra of the backbone, articulating with the occipital bone of the skull.",
"A stone carving of a male figure, used as a column to support the entablature of a Greek or Greek-style building."
],
"parts-of-speech": "Noun"
}
| 138 |
788 |
<filename>library/src/main/cpp/player/queue.c
//
// queue.c
// player
//
// Created by wlanjie on 2019/11/20.
// Copyright © 2019 com.trinity.player. All rights reserved.
//
#include "queue.h"
#include <pthread.h>
static void get_frame_defaults(AVFrame *frame) {
// from ffmpeg libavutil frame.c
if (frame->extended_data != frame->data) {
av_freep(&frame->extended_data);
}
memset(frame, 0, sizeof(*frame));
frame->pts =
frame->pkt_dts = AV_NOPTS_VALUE;
frame->best_effort_timestamp = AV_NOPTS_VALUE;
frame->pkt_duration = 0;
frame->pkt_pos = -1;
frame->pkt_size = -1;
frame->key_frame = 1;
frame->sample_aspect_ratio = (AVRational){ 0, 1 };
frame->format = -1; /* unknown */
frame->extended_data = frame->data;
frame->color_primaries = AVCOL_PRI_UNSPECIFIED;
frame->color_trc = AVCOL_TRC_UNSPECIFIED;
frame->colorspace = AVCOL_SPC_UNSPECIFIED;
frame->color_range = AVCOL_RANGE_UNSPECIFIED;
frame->chroma_location = AVCHROMA_LOC_UNSPECIFIED;
frame->flags = 0;
frame->width = 0;
frame->height = 0;
}
FramePool* frame_pool_create(int size){
LOGE("frame_pool_create");
FramePool* pool = (FramePool *)malloc(sizeof(FramePool));
pool->size = size;
pool->count = 0;
pool->index = 0;
pool->frames = (AVFrame *)av_mallocz(sizeof(AVFrame) * size);
for(int i = 0; i < size; i++){
get_frame_defaults(&pool->frames[i]);
}
return pool;
}
void frame_pool_release(FramePool *pool) {
LOGE("frame_pool_release");
av_free(pool->frames);
free(pool);
}
AVFrame* frame_pool_get_frame(FramePool *pool){
AVFrame* p = &pool->frames[pool->index];
pool->index = (pool->index + 1) % pool->size;
pool->count++;
return p;
}
void frame_pool_unref_frame(FramePool *pool, AVFrame *frame){
av_frame_unref(frame);
pool->count--;
}
FrameQueue* frame_queue_create(unsigned int size){
FrameQueue* queue = (FrameQueue *)malloc(sizeof(FrameQueue));
queue->mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
queue->cond = (pthread_cond_t *)malloc(sizeof(pthread_cond_t));
pthread_mutex_init(queue->mutex, NULL);
pthread_cond_init(queue->cond, NULL);
queue->read_index = 0;
queue->write_index = 0;
queue->count = 0;
queue->size = size;
queue->frames = (AVFrame **)malloc(sizeof(AVFrame *) * size);
return queue;
}
void frame_queue_free(FrameQueue *queue){
pthread_mutex_destroy(queue->mutex);
pthread_cond_destroy(queue->cond);
free(queue->mutex);
free(queue->cond);
free(queue->frames);
free(queue);
}
int frame_queue_put(FrameQueue *queue, AVFrame *frame){
pthread_mutex_lock(queue->mutex);
while(queue->count == queue->size){
pthread_cond_wait(queue->cond, queue->mutex);
}
queue->frames[queue->write_index] = frame;
queue->write_index = (queue->write_index + 1) % queue->size;
queue->count++;
pthread_mutex_unlock(queue->mutex);
return 0;
}
AVFrame* frame_queue_get(FrameQueue *queue){
pthread_mutex_lock(queue->mutex);
if (queue->count == 0) {
pthread_mutex_unlock(queue->mutex);
return NULL;
}
AVFrame* frame = queue->frames[queue->read_index];
queue->read_index = (queue->read_index + 1) % queue->size;
queue->count--;
pthread_cond_signal(queue->cond);
pthread_mutex_unlock(queue->mutex);
return frame;
}
AVFrame* frame_queue_peek(FrameQueue* queue) {
pthread_mutex_lock(queue->mutex);
if (queue->count == 0) {
pthread_mutex_unlock(queue->mutex);
return NULL;
}
AVFrame* frame = queue->frames[queue->read_index];
pthread_mutex_unlock(queue->mutex);
return frame;
}
AVFrame* frame_queue_peek_last(FrameQueue* queue) {
pthread_mutex_lock(queue->mutex);
if (queue->count == 0) {
pthread_mutex_unlock(queue->mutex);
return NULL;
}
AVFrame* frame = queue->frames[queue->read_index];
pthread_mutex_unlock(queue->mutex);
return frame;
}
void frame_queue_flush(FrameQueue *queue, FramePool *pool){
pthread_mutex_lock(queue->mutex);
while (queue->count > 0) {
AVFrame* frame = queue->frames[queue->read_index];
if (frame != &queue->flush_frame) {
frame_pool_unref_frame(pool, frame);
}
queue->read_index = (queue->read_index + 1) % queue->size;
queue->count--;
}
queue->read_index = 0;
queue->frames[0] = &queue->flush_frame;
queue->write_index = 1;
queue->count = 1;
pthread_cond_signal(queue->cond);
pthread_mutex_unlock(queue->mutex);
}
static void packet_pool_double_size(PacketPool * pool) {
// step1 malloc new memery space to store pointers |________________|
AVPacket** temp_packets = (AVPacket **) av_malloc(sizeof(AVPacket *) * pool->size * 2);
// step2 copy old pointers to new space |XXXXXXXX________|
memcpy(temp_packets, pool->packets, sizeof(AVPacket *) * pool->size);
// step3 fill rest space with av_packet_alloc |XXXXXXXXOOOOOOOO|
for (int i = pool->size; i < pool->size * 2; i++) {
temp_packets[i] = av_packet_alloc();
}
// step4 free old pointers space
free(pool->packets);
pool->packets = temp_packets;
// step5 当前指针位置移动到后半部分
pool->index = pool->size;
pool->size *= 2;
LOGI("packet pool double size. new size ==> %d", pool->size);
}
PacketPool* packet_pool_create(int size) {
PacketPool* pool = (PacketPool *)malloc(sizeof(PacketPool));
pool->size = size;
pool->packets = (AVPacket **)av_malloc(sizeof(AVPacket *) * size);
for (int i = 0; i < pool->size; i++){
pool->packets[i] = av_packet_alloc();
}
return pool;
}
void packet_pool_reset(PacketPool *pool) {
pool->count = 0;
pool->index = 0;
}
void packet_pool_release(PacketPool *pool) {
for (int i = 0; i < pool->size; i++) {
AVPacket * p = pool->packets[i];
av_packet_free(&p);
}
free(pool->packets);
free(pool);
}
AVPacket* packet_pool_get_packet(PacketPool *pool) {
if (pool->count > pool->size / 2) {
packet_pool_double_size(pool);
}
AVPacket* p = pool->packets[pool->index];
pool->index = (pool->index + 1) % pool->size;
pool->count++;
return p;
}
void packet_pool_unref_packet(PacketPool *pool, AVPacket *packet) {
av_packet_unref(packet);
pool->count--;
}
static void packet_double_size(PacketQueue *queue) {
AVPacket **temp_packets = (AVPacket **) malloc(sizeof(AVPacket *) * queue->size * 2);
if (queue->write_index == 0) {
memcpy(temp_packets, queue->packets, sizeof(AVPacket *) * queue->size);
queue->write_index = queue->size;
} else {
memcpy(temp_packets, queue->packets, sizeof(AVPacket *) * queue->write_index);
memcpy(temp_packets + (queue->write_index + queue->size), queue->packets + queue->write_index,
sizeof(AVPacket *) * (queue->size - queue->read_index));
queue->read_index += queue->size;
}
free(queue->packets);
queue->packets = temp_packets;
queue->size *= 2;
}
PacketQueue* queue_create(unsigned int size) {
PacketQueue *queue = (PacketQueue *) malloc(sizeof(PacketQueue));
queue->mutex = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
queue->cond = (pthread_cond_t *) malloc(sizeof(pthread_cond_t));
pthread_mutex_init(queue->mutex, NULL);
pthread_cond_init(queue->cond, NULL);
queue->read_index = 0;
queue->write_index = 0;
queue->count = 0;
queue->size = size;
queue->duration = 0;
queue->max_duration = 0;
queue->total_bytes = 0;
queue->flush_packet.duration = 0;
queue->flush_packet.size = 0;
queue->packets = (AVPacket **) malloc(sizeof(AVPacket *) * size);
queue->full_cb = NULL;
queue->empty_cb = NULL;
return queue;
}
void queue_set_duration(PacketQueue *queue, uint64_t max_duration) {
queue->max_duration = max_duration;
}
void packet_queue_free(PacketQueue *queue) {
pthread_mutex_destroy(queue->mutex);
pthread_cond_destroy(queue->cond);
free(queue->mutex);
free(queue->cond);
free(queue->packets);
free(queue);
}
int packet_queue_put(PacketQueue *queue, AVPacket *packet) {
pthread_mutex_lock(queue->mutex);
if (queue->max_duration > 0 && queue->duration + packet->duration > queue->max_duration) {
if (queue->full_cb != NULL) {
queue->full_cb(queue->cb_data);
}
pthread_cond_wait(queue->cond, queue->mutex);
}
if (queue->count == queue->size) {
packet_double_size(queue);
}
queue->duration += packet->duration;
queue->packets[queue->write_index] = packet;
queue->write_index = (queue->write_index + 1) % queue->size;
queue->count++;
queue->total_bytes += packet->size;
pthread_mutex_unlock(queue->mutex);
return 0;
}
AVPacket* packet_queue_get(PacketQueue *queue) {
pthread_mutex_lock(queue->mutex);
if (queue->count == 0) {
pthread_mutex_unlock(queue->mutex);
if (queue->empty_cb != NULL) {
queue->empty_cb(queue->cb_data);
}
return NULL;
}
AVPacket *packet = queue->packets[queue->read_index];
queue->read_index = (queue->read_index + 1) % queue->size;
queue->count--;
queue->duration -= packet->duration;
queue->total_bytes -= packet->size;
pthread_cond_signal(queue->cond);
pthread_mutex_unlock(queue->mutex);
return packet;
}
AVPacket* packet_queue_peek(PacketQueue* queue) {
pthread_mutex_lock(queue->mutex);
if (queue->count == 0) {
pthread_mutex_unlock(queue->mutex);
return NULL;
}
AVPacket* packet = queue->packets[queue->read_index];
pthread_mutex_unlock(queue->mutex);
return packet;
}
AVPacket* packet_queue_peek_last(PacketQueue* queue) {
pthread_mutex_lock(queue->mutex);
if (queue->count == 0) {
pthread_mutex_unlock(queue->mutex);
return NULL;
}
AVPacket* packet = queue->packets[queue->write_index - 1];
pthread_mutex_unlock(queue->mutex);
return packet;
}
void packet_queue_flush(PacketQueue *queue, PacketPool *pool) {
pthread_mutex_lock(queue->mutex);
while (queue->count > 0) {
AVPacket *packet = queue->packets[queue->read_index];
if (packet != &queue->flush_packet) {
packet_pool_unref_packet(pool, packet);
}
queue->read_index = (queue->read_index + 1) % queue->size;
queue->count--;
}
queue->read_index = 0;
queue->duration = 0;
queue->total_bytes = 0;
queue->packets[0] = &queue->flush_packet;
queue->write_index = 1;
queue->count = 1;
pthread_cond_signal(queue->cond);
pthread_mutex_unlock(queue->mutex);
}
| 4,754 |
1,024 |
<reponame>LisonFan/GKPhotoBrowser
//
// GKTest03ViewController.h
// GKPhotoBrowser
//
// Created by QuintGao on 2017/10/27.
// Copyright © 2017年 QuintGao. All rights reserved.
//
#import "GKBaseViewController.h"
@interface GKTest03ViewController : GKBaseViewController
@end
| 102 |
575 |
<filename>components/feed/core/v2/offline_page_spy.cc
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/feed/core/v2/offline_page_spy.h"
#include <algorithm>
#include <tuple>
#include <utility>
#include "base/bind.h"
#include "base/containers/flat_set.h"
#include "components/feed/core/v2/algorithm.h"
#include "components/feed/core/v2/surface_updater.h"
namespace feed {
namespace {
std::vector<OfflinePageSpy::BadgeInfo> GetBadgesInStream(
StreamModel* stream_model) {
std::vector<OfflinePageSpy::BadgeInfo> badges;
for (ContentRevision content_rev : stream_model->GetContentList()) {
const feedstore::Content* content = stream_model->FindContent(content_rev);
if (!content)
continue;
for (const feedwire::PrefetchMetadata& prefetch_metadata :
content->prefetch_metadata()) {
const std::string& badge_id = prefetch_metadata.badge_id();
if (badge_id.empty())
continue;
GURL url(prefetch_metadata.uri());
if (url.is_empty() || !url.is_valid())
continue;
badges.emplace_back(url, badge_id);
}
}
return badges;
}
base::flat_set<GURL> OfflineItemsToUrlSet(
const std::vector<offline_pages::OfflinePageItem>& items) {
std::vector<GURL> url_list;
for (const auto& item : items) {
url_list.push_back(item.GetOriginalUrl());
}
return url_list;
}
} // namespace
OfflinePageSpy::BadgeInfo::BadgeInfo() = default;
OfflinePageSpy::BadgeInfo::BadgeInfo(const GURL& url,
const std::string& badge_id)
: url(url), badge_id(badge_id) {}
bool OfflinePageSpy::BadgeInfo::operator<(const BadgeInfo& rhs) const {
return std::tie(url, badge_id) < std::tie(rhs.url, rhs.badge_id);
}
OfflinePageSpy::OfflinePageSpy(
SurfaceUpdater* surface_updater,
offline_pages::OfflinePageModel* offline_page_model)
: surface_updater_(surface_updater),
offline_page_model_(offline_page_model) {
offline_page_model_->AddObserver(this);
}
OfflinePageSpy::~OfflinePageSpy() {
offline_page_model_->RemoveObserver(this);
}
void OfflinePageSpy::SetModel(StreamModel* stream_model) {
if (stream_model_) {
stream_model_->RemoveObserver(this);
stream_model_ = nullptr;
}
if (stream_model) {
stream_model_ = stream_model;
stream_model_->AddObserver(this);
UpdateWatchedPages();
} else {
for (const BadgeInfo& badge : badges_) {
if (badge.available_offline) {
surface_updater_->SetOfflinePageAvailability(badge.badge_id, false);
}
}
badges_.clear();
}
}
void OfflinePageSpy::SetAvailability(const base::flat_set<GURL>& urls,
bool available) {
for (BadgeInfo& badge : badges_) {
if (badge.available_offline != available && urls.contains(badge.url)) {
badge.available_offline = available;
surface_updater_->SetOfflinePageAvailability(badge.badge_id, available);
}
}
}
void OfflinePageSpy::GetPagesDone(
const std::vector<offline_pages::OfflinePageItem>& items) {
SetAvailability(OfflineItemsToUrlSet(items), true);
}
void OfflinePageSpy::OfflinePageAdded(
offline_pages::OfflinePageModel* model,
const offline_pages::OfflinePageItem& added_page) {
SetAvailability({added_page.GetOriginalUrl()}, true);
}
void OfflinePageSpy::OfflinePageDeleted(
const offline_pages::OfflinePageItem& deleted_page) {
SetAvailability({deleted_page.GetOriginalUrl()}, false);
}
void OfflinePageSpy::OnUiUpdate(const StreamModel::UiUpdate& update) {
DCHECK(stream_model_);
if (update.content_list_changed)
UpdateWatchedPages();
}
void OfflinePageSpy::UpdateWatchedPages() {
std::vector<BadgeInfo> badges = GetBadgesInStream(stream_model_);
// Both lists need to be sorted. |badges_| should already be sorted.
std::sort(badges.begin(), badges.end());
DCHECK(std::is_sorted(badges_.begin(), badges_.end()));
// Compare new and old lists. We need to inform SurfaceUpdater of removed
// badges, and collect new URLs.
std::vector<GURL> new_urls;
auto differ = [&](BadgeInfo* new_badge, BadgeInfo* old_badge) {
if (!old_badge) { // Added a page.
new_urls.push_back(new_badge->url);
return;
}
if (!new_badge) { // Removed a page.
surface_updater_->SetOfflinePageAvailability(old_badge->badge_id, false);
return;
}
// Page remains, update |badges|.
new_badge->available_offline = old_badge->available_offline;
};
DiffSortedRange(badges.begin(), badges.end(), badges_.begin(), badges_.end(),
differ);
badges_ = std::move(badges);
RequestOfflinePageStatus(std::move(new_urls));
}
void OfflinePageSpy::RequestOfflinePageStatus(std::vector<GURL> new_urls) {
if (new_urls.empty())
return;
offline_pages::PageCriteria criteria;
criteria.exclude_tab_bound_pages = true;
criteria.additional_criteria = base::BindRepeating(
[](const base::flat_set<GURL>& url_set,
const offline_pages::OfflinePageItem& item) {
return url_set.count(item.GetOriginalUrl()) > 0;
},
std::move(new_urls));
offline_page_model_->GetPagesWithCriteria(
criteria, base::BindOnce(&OfflinePageSpy::GetPagesDone, GetWeakPtr()));
}
} // namespace feed
| 2,056 |
2,342 |
/***********************************************************************
Vczh Library++ 3.0
Developer: <NAME>(vczh)
GacUI::Composition System
Interfaces:
***********************************************************************/
#ifndef VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSFLOWCOMPOSITION
#define VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSFLOWCOMPOSITION
#include "IncludeForward.h"
#include "GuiGraphicsAxis.h"
namespace vl
{
namespace presentation
{
namespace compositions
{
/***********************************************************************
Flow Compositions
***********************************************************************/
/// <summary>
/// Alignment for a row in a flow layout
/// </summary>
enum class FlowAlignment
{
/// <summary>Align to the left.</summary>
Left,
/// <summary>Align to the center.</summary>
Center,
/// <summary>Extend to the entire row.</summary>
Extend,
};
/// <summary>
/// Represents a flow composition.
/// </summary>
class GuiFlowComposition : public GuiBoundsComposition, public Description<GuiFlowComposition>
{
friend class GuiFlowItemComposition;
typedef collections::List<GuiFlowItemComposition*> ItemCompositionList;
protected:
Margin extraMargin;
vint rowPadding = 0;
vint columnPadding = 0;
FlowAlignment alignment = FlowAlignment::Left;
Ptr<IGuiAxis> axis;
ItemCompositionList flowItems;
collections::Array<Rect> flowItemBounds;
Rect bounds;
vint minHeight = 0;
bool needUpdate = false;
void UpdateFlowItemBounds(bool forceUpdate);
void OnBoundsChanged(GuiGraphicsComposition* sender, GuiEventArgs& arguments);
void OnChildInserted(GuiGraphicsComposition* child)override;
void OnChildRemoved(GuiGraphicsComposition* child)override;
public:
GuiFlowComposition();
~GuiFlowComposition();
/// <summary>Get all flow items inside the flow composition.</summary>
/// <returns>All flow items inside the flow composition.</returns>
const ItemCompositionList& GetFlowItems();
/// <summary>Insert a flow item at a specified position.</summary>
/// <returns>Returns true if this operation succeeded.</returns>
/// <param name="index">The position.</param>
/// <param name="item">The flow item to insert.</param>
bool InsertFlowItem(vint index, GuiFlowItemComposition* item);
/// <summary>Get the extra margin inside the flow composition.</summary>
/// <returns>The extra margin inside the flow composition.</returns>
Margin GetExtraMargin();
/// <summary>Set the extra margin inside the flow composition.</summary>
/// <param name="value">The extra margin inside the flow composition.</param>
void SetExtraMargin(Margin value);
/// <summary>Get the distance between rows.</summary>
/// <returns>The distance between rows.</returns>
vint GetRowPadding();
/// <summary>Set the distance between rows.</summary>
/// <param name="value">The distance between rows.</param>
void SetRowPadding(vint value);
/// <summary>Get the distance between columns.</summary>
/// <returns>The distance between columns.</returns>
vint GetColumnPadding();
/// <summary>Set the distance between columns.</summary>
/// <param name="value">The distance between columns.</param>
void SetColumnPadding(vint value);
/// <summary>Get the axis of the layout.</summary>
/// <returns>The axis.</returns>
Ptr<IGuiAxis> GetAxis();
/// <summary>Set the axis of the layout.</summary>
/// <param name="value">The axis.</param>
void SetAxis(Ptr<IGuiAxis> value);
/// <summary>Get the alignment for rows.</summary>
/// <returns>The alignment.</returns>
FlowAlignment GetAlignment();
/// <summary>Set the alignment for rows.</summary>
/// <param name="value">The alignment.</param>
void SetAlignment(FlowAlignment value);
void ForceCalculateSizeImmediately()override;
Size GetMinPreferredClientSize()override;
Rect GetBounds()override;
};
/// <summary>
/// Represnets a base line configuration for a flow item.
/// </summary>
struct GuiFlowOption
{
/// <summary>Base line calculation algorithm</summary>
enum BaselineType
{
/// <summary>By percentage of the height from the top.</summary>
Percentage,
/// <summary>By a distance from the top.</summary>
FromTop,
/// <summary>By a distance from the bottom.</summary>
FromBottom,
};
/// <summary>The base line calculation algorithm.</summary>
BaselineType baseline = FromBottom;
/// <summary>The percentage value.</summary>
double percentage = 0.0;
/// <summary>The distance value.</summary>
vint distance = 0;
};
/// <summary>
/// Represents a flow item composition of a <see cref="GuiFlowComposition"/>.
/// </summary>
class GuiFlowItemComposition : public GuiGraphicsSite, public Description<GuiFlowItemComposition>
{
friend class GuiFlowComposition;
protected:
GuiFlowComposition* flowParent;
Rect bounds;
Margin extraMargin;
GuiFlowOption option;
void OnParentChanged(GuiGraphicsComposition* oldParent, GuiGraphicsComposition* newParent)override;
Size GetMinSize();
public:
GuiFlowItemComposition();
~GuiFlowItemComposition();
bool IsSizeAffectParent()override;
Rect GetBounds()override;
void SetBounds(Rect value);
/// <summary>Get the extra margin for this flow item. An extra margin is used to enlarge the bounds of the flow item, but only the non-extra part will be used for deciding the flow item layout.</summary>
/// <returns>The extra margin for this flow item.</returns>
Margin GetExtraMargin();
/// <summary>Set the extra margin for this flow item. An extra margin is used to enlarge the bounds of the flow item, but only the non-extra part will be used for deciding the flow item layout.</summary>
/// <param name="value">The extra margin for this flow item.</param>
void SetExtraMargin(Margin value);
/// <summary>Get the base line option for this flow item.</summary>
/// <returns>The base line option.</returns>
GuiFlowOption GetFlowOption();
/// <summary>Set the base line option for this flow item.</summary>
/// <param name="value">The base line option.</param>
void SetFlowOption(GuiFlowOption value);
};
}
}
}
#endif
| 2,548 |
387 |
#include "drawable.h"
| 8 |
415 |
#!/usr/bin/env python3
"""
Simple wrapper for zerotier-cli
"""
import json
import logging
import platform
import shutil
import subprocess
import sys
from two1.commands.util import uxstring
logger = logging.getLogger(__name__)
def is_installed():
""" Checks the system whether zerotier-one is installed
Returns:
bool: True if zerotier-one is installed, False otherwise
"""
return shutil.which('zerotier-cli') is not None
def cli(*args):
""" Runs zerotier-cli as superuser and returns the results
Args:
*args: List of string arguments to zerotier-cli
Returns:
str: A string with the entire output of the shell command.
Raises:
ValueError: if any of the args are not strings.
CalledProcessError: If the cli call failed.
"""
if not is_installed():
logger.info(uxstring.UxString.install_zerotier)
sys.exit(1)
if not all([isinstance(arg, str) for arg in args]):
raise ValueError("Error: args can only be strings")
return subprocess.check_output(("sudo", "zerotier-cli") + args)
def cli_json(*args):
""" Runs zerotier-cli as superuser and returns the results in json format
Args:
*args: List of string arguments to zerotier-cli
Returns:
dict: A dict with the json parsed results of the command.
Raises:
CalledProcessError: If the cli call failed.
ValueError: if any of the args are not strings.
json.decoder.JSONDecodeError: If the json string could not be successfully
parsed into a dict.
"""
result = cli(*(args + ("-j",)))
text = result.decode('utf-8')
return json.loads(text)
def is_valid(id_str, id_len=16):
""" Simple check for a valid zerotier network_id
Args:
id_str (str): Zerotier network id or address
Returns:
bool: True if the id_str is valid, False otherwise
"""
if len(id_str) != id_len:
return False
try:
# expected to be valid hexadecmal string
int(id_str, 16)
except ValueError:
return False
return True
def info():
""" zerotier-cli info command
Returns:
dict: A dict with the json parsed results of the command.
Raises:
CalledProcessError: If the cli call failed.
ValueError: If the json string could not be successfully parsed into a dict.
"""
return dict(cli_json('info'))
def device_address():
""" Returns Zerotier device id
Returns:
str: Zerotier device id
Raises:
CalledProcessError: If the cli call failed.
ValueError: If the json string could not be successfully parsed into a dict.
ValueError: If the address from info is not valid
"""
address = info()['address']
if not is_valid(address, id_len=10):
raise ValueError("Error: address from info() is not valid")
return address
def list_networks():
""" zerotier-cli listnetworks command
Returns:
list: A list of networks (dict) that the device is connected to.
Raises:
CalledProcessError: If the cli call failed.
ValueError: If the json string could not be successfully parsed into a dict.
"""
return cli_json('listnetworks')
def list_peers():
""" zerotier-cli listpeers command
Returns:
list: A list of peers (dict) that the device can see.
Raises:
CalledProcessError: If the cli call failed.
ValueError: If the json string could not be successfully parsed into a dict.
"""
return cli_json('listpeers')
def join_network(network_id):
""" Join the provided zerotier network
Args:
network_id (str): Zerotier network id to connect to.
Returns:
str: Result from the zerotier-cli join call.
Raises:
CalledProcessError: If the cli call failed.
ValueError: If the given network_id is invalid.
"""
if not is_valid(network_id, id_len=16):
raise ValueError("Error network_id ({}) is not valid")
return cli('join', network_id)
def leave_network(network_id):
""" Leave the provided zerotier network
Args:
network_id (str): Network id fo the Zerotier network to leave.
Returns:
str: Result from the zerotier-cli leave call.
Raises:
CalledProcessError: If the cli call failed.
ValueError: If the given network_id is invalid.
"""
if not is_valid(network_id, id_len=16):
raise ValueError("Error network_id ({}) is not valid")
return cli('leave', network_id)
def start_daemon():
""" Starts the zerotier daemon if it is installed on your system
Returns:
str: output of the subprocess call to check_output
Raises:
EnvironmentError: if you your ststem is not yet supported.
CalledProcessError: if the command to start the daemon failed.
"""
if not is_installed():
logger.info(uxstring.UxString.install_zerotier)
sys.exit(1)
if platform.system() in "Linux":
if shutil.which("systemctl"):
cmd = ('sudo', 'systemctl', 'start', 'zerotier-one.service')
elif shutil.which("service"):
cmd = ('sudo', 'service', 'zerotier-one', 'start')
else:
raise EnvironmentError("Do not know how to start zerotier deamon on your system")
elif platform.system() in "Darwin":
# ZT post install for Macs already load the daemon
return ""
else:
raise EnvironmentError("Do not know how to start zerotier deamon on your system")
return subprocess.call(cmd) # Command errors if already started
def get_address(network_name):
""" Gets the IP address of the given network name
Returns:
str: an IP address in string format if the network given exists and has
an assigned address, None otherwise.
"""
all_addresses = get_all_addresses()
if network_name in all_addresses:
return all_addresses[network_name]
return None
def get_address_by_id(network_id):
""" Returns the IP address and network mask for the provided Zerotier network.
Args:
network_id (str): Zerotier network id for which the IP address is desired.
Returns:
list (IP, mask): Returns the IP and the mask. e.g. [u'172.23.15.14', u'16']
Raises:
RuntimeError: if the network_id given is not a valid network id or an IP address
has not been assigned yet.
"""
networks = list_networks()
if not networks:
raise RuntimeError("Error: not connected to any networks")
for network in networks:
# found a match
if network_id and network_id in network['nwid']:
if len(network["assignedAddresses"]) > 0:
return network["assignedAddresses"][0].split("/")
raise RuntimeError("Error in looking up Zerotier IP for %s" % network_id)
def get_all_addresses():
""" Gets all addresses in a dictionary format with the network names as keys
Returns:
dict: a dictionary of IP addresses with network names as keys, or an empty dict
if no networks are found.
"""
result = {}
networks = list_networks()
for network in networks:
if len(network["assignedAddresses"]) > 0:
for ip_address in network["assignedAddresses"]:
# Remove the address range (e.g. the "/24" in "1.2.3.4/24")
address = ip_address.split("/")[0]
# Preferentially return first IPv6 address (indicated
# by its containing a colon). If there are no IPv6
# addresses found, the last IPv4 address will be returned
if ":" in address:
break
else:
address = ""
result[network["name"]] = address
return result
def get_network_id(network_name):
return {
network['name']: network['nwid'] for network in list_networks()}[network_name]
def leave_all():
if not is_installed():
return
logger.info('Leaving all ZeroTier networks.')
for network, address in get_all_addresses().items():
logger.info('Leaving %s.' % network)
nwid = get_network_id(network)
leave_network(nwid)
| 3,160 |
852 |
#include "RecoVertex/VertexTools/interface/LinearizationPointFinder.h"
#include "TrackingTools/TrajectoryState/interface/FreeTrajectoryState.h"
#include "TrackingTools/TransientTrack/interface/TransientTrackFromFTSFactory.h"
GlobalPoint LinearizationPointFinder::getLinearizationPoint(const std::vector<FreeTrajectoryState>& ftses) const {
std::vector<reco::TransientTrack> rectracks;
TransientTrackFromFTSFactory factory;
for (std::vector<FreeTrajectoryState>::const_iterator fts = ftses.begin(); fts != ftses.end(); ++fts)
rectracks.push_back(factory.build(*fts));
return getLinearizationPoint(rectracks);
}
| 205 |
356 |
<gh_stars>100-1000
package com.zjb.volley.core.stack;
import java.io.IOException;
import java.util.Map;
import com.zjb.volley.core.exception.VolleyError;
import com.zjb.volley.core.request.Request;
import com.zjb.volley.core.response.CustomResponse;
/**
* time: 2015/8/19
* description:
*
* @author sunjianfei
*/
public interface HttpStack {
CustomResponse performRequest(Request<?> request, Map<String, String> params) throws IOException, VolleyError;
}
| 166 |
903 |
#include "../../../src/gui/kernel/qt_s60_p.h"
| 23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.