max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
303
<reponame>poalimWeb/webauthndemo // Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.webauthn.gaedemo.objects; import com.googlecode.objectify.annotation.Subclass; import co.nstant.in.cbor.CborException; import co.nstant.in.cbor.model.DataItem; import co.nstant.in.cbor.model.Map; @Subclass public final class NoneAttestationStatement extends AttestationStatement { public NoneAttestationStatement() {} @Override DataItem encode() throws CborException { Map result = new Map(); return result; } @Override public int hashCode() { return 0; } @Override public boolean equals(Object obj) { if (obj instanceof NoneAttestationStatement) return true; return false; } @Override public String getName() { return "NONE ATTESTATION"; } }
409
373
<filename>lib/replay_memory.py from __future__ import print_function, division import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import sqlite3 import states from config import Config import random import numpy as np class ReplayMemory(object): #instances = dict() def __init__(self, filepath, max_size, max_size_tolerance): self.filepath = filepath self.conn = sqlite3.connect(filepath, detect_types=sqlite3.PARSE_DECLTYPES) self.max_size = max_size self.max_size_tolerance = max_size_tolerance self.conn.execute(""" CREATE TABLE IF NOT EXISTS states ( id INTEGER PRIMARY KEY AUTOINCREMENT, from_datetime TIMESTAMP NOT NULL, screenshot_rs_jpg BLOB NOT NULL, speed INTEGER, is_reverse INTEGER(1), is_offence_shown INTEGER(1), is_damage_shown INTEGER(1), reward REAL NOT NULL, action_left_right VARCHAR(3), action_up_down VARCHAR(3), p_explore REAL NOT NULL, steering_wheel REAL, steering_wheel_raw_one REAL, steering_wheel_raw_two REAL, steering_wheel_cnn REAL, steering_wheel_raw_cnn REAL ) """) self.size = 0 self.nb_states_added = 0 self.id_min = None self.id_max = None self.update_caches() """ @staticmethod def get_instance(name, filepath, max_size, max_size_tolerance): if not name in ReplayMemory.instances: ReplayMemory.instances[name] = ReplayMemory(filepath=filepath, max_size=max_size, max_size_tolerance=max_size_tolerance) return ReplayMemory.instances[name] @staticmethod def get_instance_supervised(): return ReplayMemory.get_instance( name="supervised", filepath=Config.REPLAY_MEMORY_SUPERVISED_FILEPATH, max_size=Config.REPLAY_MEMORY_SUPERVISED_MAX_SIZE, max_size_tolerance=Config.REPLAY_MEMORY_SUPERVISED_MAX_SIZE_TOLERANCE ) @staticmethod def get_instance_reinforced(): return ReplayMemory.get_instance( name="reinforced", filepath=Config.REPLAY_MEMORY_REINFORCED_FILEPATH, max_size=Config.REPLAY_MEMORY_REINFORCED_MAX_SIZE, max_size_tolerance=Config.REPLAY_MEMORY_REINFORCED_MAX_SIZE_TOLERANCE ) """ @staticmethod def create_instance_supervised(val=False): return ReplayMemory.create_instance_by_config("supervised%s" % ("-val" if val else "-train",)) @staticmethod def create_instance_reinforced(val=False): return ReplayMemory.create_instance_by_config("reinforced%s" % ("-val" if val else "-train",)) @staticmethod def create_instance_by_config(cfg_name): return ReplayMemory( filepath=Config.REPLAY_MEMORY_CFGS[cfg_name]["filepath"], max_size=Config.REPLAY_MEMORY_CFGS[cfg_name]["max_size"], max_size_tolerance=Config.REPLAY_MEMORY_CFGS[cfg_name]["max_size_tolerance"] ) def add_states(self, states, shrink=True): for state in states: self.add_state(state, commit=False, shrink=False) if shrink: self.shrink_to_max_size() self.commit() def add_state(self, state, commit=True, shrink=True): idx = self.id_max + 1 if self.id_max is not None else 1 from_datetime = state.from_datetime #scr_rs = state.screenshot_rs scr_rs_jpg = sqlite3.Binary(state.screenshot_rs_jpg) speed = state.speed is_reverse = state.is_reverse is_offence_shown = state.is_offence_shown is_damage_shown = state.is_damage_shown reward = state.reward action_left_right = state.action_left_right action_up_down = state.action_up_down p_explore = state.p_explore steering_wheel_classical = state.steering_wheel_classical steering_wheel_raw_one_classical = state.steering_wheel_raw_one_classical steering_wheel_raw_two_classical = state.steering_wheel_raw_two_classical steering_wheel_cnn = state.steering_wheel_cnn steering_wheel_raw_cnn = state.steering_wheel_raw_cnn stmt = """ INSERT INTO states (id, from_datetime, screenshot_rs_jpg, speed, is_reverse, is_offence_shown, is_damage_shown, reward, action_left_right, action_up_down, p_explore, steering_wheel, steering_wheel_raw_one, steering_wheel_raw_two, steering_wheel_cnn, steering_wheel_raw_cnn) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """ assert isinstance(action_left_right, str) assert isinstance(action_up_down, str) self.conn.execute(stmt, ( idx, from_datetime, scr_rs_jpg, speed, is_reverse, is_offence_shown, is_damage_shown, reward, action_left_right, action_up_down, p_explore, steering_wheel_classical, steering_wheel_raw_one_classical, steering_wheel_raw_two_classical, steering_wheel_cnn, steering_wheel_raw_cnn )) self.id_max = idx self.size += 1 self.nb_states_added += 1 #print("[ReplayMemory] Added state (new size: %d)" % (self.size,)) if commit: self.commit() if shrink: self.shrink_to_max_size() def update_state(self, idx, state, commit=True): new_idx = idx old_idx = state.idx from_datetime = state.from_datetime scr_rs_jpg = sqlite3.Binary(state.screenshot_rs_jpg) speed = state.speed is_reverse = state.is_reverse is_offence_shown = state.is_offence_shown is_damage_shown = state.is_damage_shown reward = state.reward action_left_right = state.action_left_right action_up_down = state.action_up_down p_explore = state.p_explore steering_wheel_classical = state.steering_wheel_classical steering_wheel_raw_one_classical = state.steering_wheel_raw_one_classical steering_wheel_raw_two_classical = state.steering_wheel_raw_two_classical steering_wheel_cnn = state.steering_wheel_cnn steering_wheel_raw_cnn = state.steering_wheel_raw_cnn stmt = """ UPDATE states SET id=?, from_datetime=?, screenshot_rs_jpg=?, speed=?, is_reverse=?, is_offence_shown=?, is_damage_shown=?, reward=?, action_left_right=?, action_up_down=?, p_explore=?, steering_wheel=?, steering_wheel_raw_one=?, steering_wheel_raw_two=?, steering_wheel_cnn=?, steering_wheel_raw_cnn=? WHERE id=? """ assert isinstance(action_left_right, str) assert isinstance(action_up_down, str) self.conn.execute(stmt, ( new_idx, from_datetime, scr_rs_jpg, speed, is_reverse, is_offence_shown, is_damage_shown, reward, action_left_right, action_up_down, p_explore, steering_wheel_classical, steering_wheel_raw_one_classical, steering_wheel_raw_two_classical, steering_wheel_cnn, steering_wheel_raw_cnn, old_idx)) if commit: self.commit() def get_state_by_id(self, idx): cur = self.conn.cursor() cur.execute(""" SELECT id, from_datetime, screenshot_rs_jpg, speed, is_reverse, is_offence_shown, is_damage_shown, reward, action_up_down, action_left_right, p_explore, steering_wheel, steering_wheel_raw_one, steering_wheel_raw_two, steering_wheel_cnn, steering_wheel_raw_cnn FROM states WHERE id=? """, (idx,)) rows = cur.fetchall() result = [] for row in rows: result.append(states.State.from_row(row)) if len(result) == 0: return None else: assert len(result) == 1 return result[0] def get_states_by_ids(self, ids): id_to_pos = dict([(idx, i) for i, idx in enumerate(ids)]) cur = self.conn.cursor() cur.execute(""" SELECT id, from_datetime, screenshot_rs_jpg, speed, is_reverse, is_offence_shown, is_damage_shown, reward, action_up_down, action_left_right, p_explore, steering_wheel, steering_wheel_raw_one, steering_wheel_raw_two, steering_wheel_cnn, steering_wheel_raw_cnn FROM states WHERE id IN (%s) """ % (", ".join([str(idx) for idx in ids]),)) rows = cur.fetchall() result = [None] * len(ids) for row in rows: state = states.State.from_row(row) pos = id_to_pos[state.idx] result[pos] = state return result def get_random_states(self, count): assert self.size > 0 id_min = self.id_min id_max = self.id_max ids = [str(v) for v in np.random.randint(id_min, id_max, size=(count,))] cur = self.conn.cursor() cur.execute(""" SELECT id, from_datetime, screenshot_rs_jpg, speed, is_reverse, is_offence_shown, is_damage_shown, reward, action_up_down, action_left_right, p_explore, steering_wheel, steering_wheel_raw_one, steering_wheel_raw_two, steering_wheel_cnn, steering_wheel_raw_cnn FROM states WHERE id IN (%s) """ % (", ".join(ids))) rows = cur.fetchall() result = [] for row in rows: result.append(states.State.from_row(row)) while len(result) < count: result.append(random.choice(result)) return result def get_states_range(self, pos_start, length): assert self.id_min is not None assert pos_start is not None id_start = self.id_min + pos_start id_end = id_start + length #print("[get_states_range] pos_start", pos_start, "length", length, "id_start", id_start, "id_end", id_end) cur = self.conn.cursor() cur.execute(""" SELECT id, from_datetime, screenshot_rs_jpg, speed, is_reverse, is_offence_shown, is_damage_shown, reward, action_up_down, action_left_right, p_explore, steering_wheel, steering_wheel_raw_one, steering_wheel_raw_two, steering_wheel_cnn, steering_wheel_raw_cnn FROM states WHERE id >= ? and id < ? ORDER BY id ASC """, (id_start, id_end)) rows = cur.fetchall() result = [] for row in rows: result.append(states.State.from_row(row)) #print("[get_states_range]", self.filepath, [state.idx for state in result]) assert len(result) == length, "Wrong number of states found: pos_start=%d length=%d id_start=%d id_end=%d id_min=%d id_max=%d size=%d" % (pos_start, length, id_start, id_end, self.id_min, self.id_max, self.size) return result def get_random_state_chain(self, length, from_pos_range=None): #print("[get_random_state_chain] from_pos_range", from_pos_range) if length > self.size: raise Exception("Requested state chain length is larger than size of replay memory. Gather more experiences/states.") from_pos_range = list(from_pos_range) if from_pos_range is not None else [0, self.size] if from_pos_range[0] is None: from_pos_range[0] = 0 #else: # from_pos_range[0] = from_pos_range[0] if from_pos_range[0] >= self.id_min else self.id_min if from_pos_range[1] is None: from_pos_range[1] = self.size else: from_pos_range[1] = from_pos_range[1] if from_pos_range[1] <= self.size else self.size if length > (from_pos_range[1] - from_pos_range[0]): raise Exception("Requested state chain length is larger than allowed id range.") start_pos_min = from_pos_range[0] start_pos_max = from_pos_range[1] - length start_pos = random.randint(start_pos_min, start_pos_max) #print("get_random_state_chain", self.filepath, start_pos, length, start_pos_min, start_pos_max) return self.get_states_range(pos_start=start_pos, length=length) def get_random_state_chain_timediff(self, length, max_timediff_ms=500, depth=50): states = self.get_random_state_chain(length) maxdiff = 0 last_time = states[0].from_datetime for state in states[1:]: if last_time < state.from_datetime: timediff = state.from_datetime - last_time timediff = timediff.total_seconds() * 1000 else: print("[WARNING] load_random_state_chain: state from datetime %s is after state %s, expected reversed order" % (last_time, state.from_datetime)) timediff = max_timediff_ms + 1 maxdiff = max(timediff, maxdiff) last_time = state.from_datetime #print("maxdiff:", maxdiff) if maxdiff > max_timediff_ms: if depth == 0: print("[WARNING] reached max depth in load_random_state_chain", from_pos_range) return states else: return self.get_random_state_chain_timediff(length, max_timediff_ms=max_timediff_ms, depth=depth-1) else: return states def update_caches(self): cur = self.conn.cursor() cur.execute("SELECT COUNT(*) as c FROM states") row = cur.fetchone() count = row[0] if count > 0: cur = self.conn.cursor() cur.execute("SELECT MIN(id) as id_min, MAX(id) as id_max FROM states") row = cur.fetchone() id_min = row[0] id_max = row[1] else: id_min = None id_max = None self.size = count self.id_min = id_min self.id_max = id_max def is_above_tolerance(self): return self.size > (self.max_size + self.max_size_tolerance) def shrink_to_max_size(self, force=False): is_over_size = (self.size > self.max_size) #is_over_tolerance = (self.size > self.max_size + self.max_size_tolerance) if self.is_above_tolerance() or (is_over_size and force): print("[ReplayMemory] Shrink to size (from %d to %d)" % (self.size, self.max_size)) diff = self.size - self.max_size del_start = self.id_min del_end = self.id_min + diff cur = self.conn.cursor() cur.execute("DELETE FROM states WHERE id >= ? AND id < ?", (del_start, del_end)) self.commit() #self.size -= diff #self.id_min += diff self.update_caches() print("[ReplayMemory] New size is %d" % (self.size,)) def commit(self): self.conn.commit() def close(self): self.conn.close() def connect(self): self.conn = sqlite3.connect(self.filepath, detect_types=sqlite3.PARSE_DECLTYPES)
7,619
1,025
//===================================================================== // Copyright (c) 2012 Advanced Micro Devices, Inc. All rights reserved. // /// \author GPU Developer Tools /// \file $File: //devtools/main/CodeXL/Components/GpuProfiling/AMDTGpuProfiling/ProfileParam.h $ /// \version $Revision: #5 $ /// \brief : This file contains Profile parameters // //===================================================================== // $Id: //devtools/main/CodeXL/Components/GpuProfiling/AMDTGpuProfiling/ProfileParam.h#5 $ // Last checkin: $DateTime: 2015/08/31 01:56:31 $ // Last edited by: $Author: salgrana $ // Change list: $Change: 538740 $ //===================================================================== #ifndef _PROFILE_PARAM_H_ #define _PROFILE_PARAM_H_ // Qt #include <qtIgnoreCompilerWarnings.h> #include <QtCore> #include <QtWidgets> #include "ProfileSettingData.h" #include <AMDTGpuProfiling/Util.h> /// Profile parameter class ProfileParam { public: /// Initializes a new instance of the ProfileParam class ProfileParam(); /// Destructor ~ProfileParam(); /// Gets the project name /// \return the project name QString ProjectName() { return m_strProjectName; } /// Gets the session directory /// \return the session directory QString SessionDir() { return m_strSessionDir; } /// Gets the output directory /// \return the output directory QString OutputDirectory() { return m_strOutputDirectory; } /// Gets the session file name /// \return the session file name QString SessionFile() { return m_strSessionFile; } /// Gets the session name /// \return the session name QString SessionName() { return m_strSessionName; } /// Gets the profile type /// \return the profile type GPUProfileType ProfileTypeValue() { return m_profileTypeValue; } /// Gets the current profile setting data /// \return the current profile setting data ProfileSettingData* CurrentProfileData() { return m_currentProfileData; } /// Sets the project name /// \param strValue the new project name void SetProjectName(const QString& strValue) { m_strProjectName = strValue; } /// Sets the session directory /// \param strValue the new session directory void SetSessionDir(const QString& strValue) { m_strSessionDir = strValue; } /// Sets the output directory /// \param strValue the new output directory void SetOutputDirectory(const QString& strValue) { m_strOutputDirectory = strValue; } /// Sets the session file name /// \param strValue the new session file name void SetSessionFile(const QString& strValue) { m_strSessionFile = strValue; } /// Sets the session name /// \param strValue the new session name void SetSessionName(const QString& strValue) { m_strSessionName = strValue; } /// Sets the profile type /// \param value the new profile type void SetProfileTypeValue(const GPUProfileType& value) { m_profileTypeValue = value; } private: /// Disabled copy constructor ProfileParam(const ProfileParam&); /// Disabled assignment operator ProfileParam& operator=(const ProfileParam&); QString m_strProjectName; ///< Project name QString m_strSessionDir; ///< Directory of the session QString m_strOutputDirectory; ///< Output of the session QString m_strSessionFile; ///< Output file of the session QString m_strSessionName; ///< Name of the session GPUProfileType m_profileTypeValue; ///< Profile type ProfileSettingData* m_currentProfileData; ///< Profile data }; #endif // _PROFILE_PARAM_H_
1,170
530
package org.carlspring.strongbox.storage.repository; import org.carlspring.strongbox.api.Describable; /** * @author mtodorov */ public enum RepositoryTypeEnum implements Describable { HOSTED("hosted"), PROXY("proxy"), GROUP("group"), VIRTUAL("virtual"); // Unsupported private String type; RepositoryTypeEnum(String type) { this.type = type; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String describe() { return getType(); } }
261
418
package krasa.formatter.eclipse; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.ui.SortedComboBoxModel; import krasa.formatter.exception.FileDoesNotExistsException; import krasa.formatter.exception.ParsingFailedException; import krasa.formatter.plugin.ProjectSettingsForm; import krasa.formatter.utils.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Properties; @SuppressWarnings("rawtypes") public class ConfigFileLocator { private static final Logger LOG = Logger.getInstance(ConfigFileLocator.class.getName()); private static IModuleResolverStrategy moduleResolver = new DefaultModuleResolverStrategy(); private static VirtualFile mostRecentFormatterFile = null; private final List<String> CONVENTIONFILENAMES = Arrays.asList(// ".settings/org.eclipse.jdt.core.prefs", // ".settings/mechanic-formatter.epf", // "mechanic-formatter.epf", // "eclipse-code-formatter.xml" // ); public String resolveConfigFilePath(String path) { File file = new File(path); if (!file.exists()) { throw new FileDoesNotExistsException(file); } if (file.isDirectory()) { File resolve = resolveFolder(file); if (resolve != null) return resolve.getAbsolutePath(); throw new FileDoesNotExistsException("Invalid config location: " + path); } return path; } public void validate(ProjectSettingsForm projectSettingsForm, SortedComboBoxModel profilesModel, String path) { if (StringUtils.isBlank(path)) { return; } File file = new File(path); JComboBox comboBox = projectSettingsForm.javaFormatterProfile; comboBox.setEnabled(true); comboBox.setBorder(projectSettingsForm.normalBorder); try { if (!file.exists()) { invalid("invalid location", profilesModel, comboBox); return; } if (file.isDirectory()) { file = resolveFolder(file); if (file == null) { invalid("invalid location", profilesModel, comboBox); return; } } String lowerCaseName = file.getName().toLowerCase().trim(); if (lowerCaseName.equals("org.eclipse.jdt.ui.prefs")) { processWorkspaceConfig(profilesModel, comboBox, file); } else if (lowerCaseName.endsWith(".prefs")) { processPrefs(projectSettingsForm, profilesModel, comboBox, file); } else if (lowerCaseName.endsWith(".epf")) { processEPF(projectSettingsForm, profilesModel, file, comboBox); } else if (lowerCaseName.endsWith(".xml")) { processXml(profilesModel, file, comboBox); } else { // lets assume it is properties processPrefs(projectSettingsForm, profilesModel, comboBox, file); } } catch (IOException e) { invalid("Plugin error:" + e.toString(), profilesModel, comboBox); throw new RuntimeException(e); } catch (FileDoesNotExistsException e) { invalid("invalid location", profilesModel, comboBox); } } @Nullable private File resolveFolder(File folder) { File mechanicFormatterEpf = org.apache.commons.io.FileUtils.getFile(folder, ".settings", "mechanic-formatter.epf"); if (mechanicFormatterEpf.exists()) { return mechanicFormatterEpf; } File corePrefs = org.apache.commons.io.FileUtils.getFile(folder, ".settings", "org.eclipse.jdt.core.prefs"); if (corePrefs.exists()) { return corePrefs; } File uiPrefs = org.apache.commons.io.FileUtils.getFile(folder, ".metadata", ".plugins", "org.eclipse.core.runtime", ".settings", "org.eclipse.jdt.ui.prefs"); if (uiPrefs.exists()) { return uiPrefs; } return null; } private void processWorkspaceConfig(SortedComboBoxModel profilesModel, JComboBox comboBox, File uiPrefs) throws IOException { Properties properties = FileUtils.readPropertiesFile(uiPrefs); String xml = properties.getProperty("org.eclipse.jdt.ui.formatterprofiles"); InputStream s = IOUtils.toInputStream(xml, "UTF-8"); List<String> profileNamesFromConfigXML = FileUtils.getProfileNamesFromConfigXML(s); if (profileNamesFromConfigXML.isEmpty()) { invalid("Workspace does not contain custom formatter profiles!", profilesModel, comboBox); } else { profilesModel.addAll(profileNamesFromConfigXML); String formatter_profile1 = properties.getProperty("formatter_profile"); String substring = formatter_profile1.substring(1); if (new HashSet<>(profileNamesFromConfigXML).contains(substring)) { profilesModel.setSelectedItem(substring); } } } private void processEPF(ProjectSettingsForm projectSettingsForm, SortedComboBoxModel profilesModel, File file, JComboBox comboBox) { if (isValidEPF(file)) { valid("valid EPF config", projectSettingsForm, profilesModel, comboBox); } else { invalid("Invalid EPF config, should contain 100+ 'org.eclipse.jdt.core.formatter' properties", profilesModel, comboBox); } } private boolean isValidEPF(File file) { Properties properties = FileUtils.readPropertiesFile(file); Properties result = FileUtils.convertEPF(properties, new Properties()); return result.size() > 100; } private void processXml(SortedComboBoxModel profilesModel, File file, JComboBox comboBox) { try { profilesModel.addAll(FileUtils.getProfileNamesFromConfigXML(file)); if (profilesModel.getSize() == 0) { invalid(ProjectSettingsForm.CONTAINS_NO_PROFILES, profilesModel, comboBox); } } catch (ParsingFailedException e) { invalid(ProjectSettingsForm.PARSING_FAILED, profilesModel, comboBox); } } private void processPrefs(@NotNull ProjectSettingsForm projectSettingsForm, @NotNull SortedComboBoxModel profilesModel, @NotNull JComboBox comboBox, @NotNull File file) { if (isValidCorePrefs(file)) { valid("valid '" + file.getName() + "' config", projectSettingsForm, profilesModel, comboBox); } else { invalid("Enable 'Project Specific Settings' in Eclipse!", profilesModel, comboBox); } } private boolean isValidCorePrefs(@NotNull File file) { Properties properties = FileUtils.readPropertiesFile(file); return properties.size() > 100; } private void valid(String valid_config, ProjectSettingsForm projectSettingsForm, SortedComboBoxModel profilesModel, JComboBox comboBox) { profilesModel.add(valid_config); comboBox.setEnabled(false); comboBox.setBorder(projectSettingsForm.normalBorder); } private void invalid(String text, SortedComboBoxModel profilesModel, JComboBox comboBox) { profilesModel.add(text); comboBox.setEnabled(false); comboBox.setBorder(ProjectSettingsForm.ERROR_BORDER); } @Nullable VirtualFile traverseToFindConfigurationFileByConvention(PsiFile psiFile, Project project) { int i = 0; VirtualFile moduleFileDir = getModuleDirForFile(psiFile.getVirtualFile(), project); while (moduleFileDir != null) { if (++i > 1000) { throw new IllegalStateException("loop bug: " + moduleFileDir.getPath()); } if (LOG.isDebugEnabled()) { LOG.debug("moduleFileDir=" + moduleFileDir.getPath()); } for (String conventionFileName : CONVENTIONFILENAMES) { VirtualFile fileByRelativePath = moduleFileDir.findFileByRelativePath(conventionFileName); if (fileByRelativePath != null && fileByRelativePath.exists()) { if (!isValid(fileByRelativePath)) { LOG.info("Found a config file, but is invalid, skipping. " + fileByRelativePath); continue; } mostRecentFormatterFile = fileByRelativePath; return fileByRelativePath; } } moduleFileDir = getNextParentModuleDirectory(moduleFileDir, project); } return null; } private boolean isValid(VirtualFile virtualFile) { try { if ("org.eclipse.jdt.core.prefs".equals(virtualFile.getName())) { return isValidCorePrefs(new File(virtualFile.getPath())); } if (virtualFile.getName().endsWith(".epf")) { return isValidEPF(new File(virtualFile.getPath())); } if ("eclipse-code-formatter.xml".equals(virtualFile.getName())) { List<String> profileNamesFromConfigXML = FileUtils.getProfileNamesFromConfigXML( new File(virtualFile.getPath())); return profileNamesFromConfigXML.size() == 1; } return true; } catch (Throwable e) { LOG.error(e); return false; } } private VirtualFile getModuleDirForFile(VirtualFile virtualFile, Project project) { // delegate to a strategy which can be overriden in unit tests return moduleResolver.getModuleDirForFile(virtualFile, project); } private VirtualFile getNextParentModuleDirectory(VirtualFile currentModuleDir, Project project) { int i = 0; // Jump outside the current project VirtualFile parent = currentModuleDir.getParent(); while (parent != null && parent.exists()) { if (++i > 1000) { throw new IllegalStateException("loop bug: " + parent.getPath()); } // the file/dir outside the project may be within another loaded module // NOTE all modules must be loaded for detecting the parent module of the current one VirtualFile dirOfParentModule = getModuleDirForFile(parent, project); if (dirOfParentModule == null) { return null; } // module file can be is some subfolder, so find a parent which is actually from a different module if (dirOfParentModule.equals(currentModuleDir)) { parent = parent.getParent(); continue; } return dirOfParentModule; } return null; } public interface IModuleResolverStrategy { VirtualFile getModuleDirForFile(VirtualFile virtualFile, Project project); } static class DefaultModuleResolverStrategy implements IModuleResolverStrategy { @Override public VirtualFile getModuleDirForFile(VirtualFile virtualFile, Project project) { Module moduleForFile = ModuleUtil.findModuleForFile(virtualFile, project); if (moduleForFile != null) { VirtualFile moduleFile = moduleForFile.getModuleFile(); if (moduleFile != null) { return moduleFile.getParent(); } } return null; } } /** * VisibleForTesting */ @Deprecated public static void TESTING_setModuleResolver(IModuleResolverStrategy otherModuleResolver) { moduleResolver = otherModuleResolver; } /** * VisibleForTesting */ @Deprecated public static IModuleResolverStrategy TESTING_getModuleResolver() { return moduleResolver; } /** * VisibleForTesting */ @Deprecated public static VirtualFile TESTING_getMostRecentFormatterFile() { return mostRecentFormatterFile; } }
3,743
441
<gh_stars>100-1000 /* * Original work: Copyright (c) 2014, Oculus VR, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * RakNet License.txt file in the licenses directory of this source tree. An additional grant * of patent rights can be found in the RakNet Patents.txt file in the same directory. * * * Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt) * * This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style * license found in the license.txt file in the root directory of this source tree. */ #include "slikenet/memoryoverride.h" #include "slikenet/assert.h" #include <stdlib.h> #ifdef _RAKNET_SUPPORT_DL_MALLOC #include "rdlmalloc.h" #endif using namespace SLNet; #if _USE_RAK_MEMORY_OVERRIDE==1 #if defined(malloc) #pragma push_macro("malloc") #undef malloc #define RMO_MALLOC_UNDEF #endif #if defined(realloc) #pragma push_macro("realloc") #undef realloc #define RMO_REALLOC_UNDEF #endif #if defined(free) #pragma push_macro("free") #undef free #define RMO_FREE_UNDEF #endif #endif void DefaultOutOfMemoryHandler(const char *file, const long line) { (void) file; (void) line; RakAssert(0); } void * (*rakMalloc) (size_t size) = SLNet::_RakMalloc; void* (*rakRealloc) (void *p, size_t size) = SLNet::_RakRealloc; void (*rakFree) (void *p) = SLNet::_RakFree; void* (*rakMalloc_Ex) (size_t size, const char *file, unsigned int line) = SLNet::_RakMalloc_Ex; void* (*rakRealloc_Ex) (void *p, size_t size, const char *file, unsigned int line) = SLNet::_RakRealloc_Ex; void (*rakFree_Ex) (void *p, const char *file, unsigned int line) = SLNet::_RakFree_Ex; void (*notifyOutOfMemory) (const char *file, const long line)=DefaultOutOfMemoryHandler; void * (*dlMallocMMap) (size_t size) = SLNet::_DLMallocMMap; void * (*dlMallocDirectMMap) (size_t size) = SLNet::_DLMallocDirectMMap; int (*dlMallocMUnmap) (void* ptr, size_t size) = SLNet::_DLMallocMUnmap; void SetMalloc( void* (*userFunction)(size_t size) ) { rakMalloc=userFunction; } void SetRealloc( void* (*userFunction)(void *p, size_t size) ) { rakRealloc=userFunction; } void SetFree( void (*userFunction)(void *p) ) { rakFree=userFunction; } void SetMalloc_Ex( void* (*userFunction)(size_t size, const char *file, unsigned int line) ) { rakMalloc_Ex=userFunction; } void SetRealloc_Ex( void* (*userFunction)(void *p, size_t size, const char *file, unsigned int line) ) { rakRealloc_Ex=userFunction; } void SetFree_Ex( void (*userFunction)(void *p, const char *file, unsigned int line) ) { rakFree_Ex=userFunction; } void SetNotifyOutOfMemory( void (*userFunction)(const char *file, const long line) ) { notifyOutOfMemory=userFunction; } void SetDLMallocMMap( void* (*userFunction)(size_t size) ) { dlMallocMMap=userFunction; } void SetDLMallocDirectMMap( void* (*userFunction)(size_t size) ) { dlMallocDirectMMap=userFunction; } void SetDLMallocMUnmap( int (*userFunction)(void* ptr, size_t size) ) { dlMallocMUnmap=userFunction; } void * (*GetMalloc()) (size_t size) { return rakMalloc; } void * (*GetRealloc()) (void *p, size_t size) { return rakRealloc; } void (*GetFree()) (void *p) { return rakFree; } void * (*GetMalloc_Ex()) (size_t size, const char *file, unsigned int line) { return rakMalloc_Ex; } void * (*GetRealloc_Ex()) (void *p, size_t size, const char *file, unsigned int line) { return rakRealloc_Ex; } void (*GetFree_Ex()) (void *p, const char *file, unsigned int line) { return rakFree_Ex; } void *(*GetDLMallocMMap())(size_t size) { return dlMallocMMap; } void *(*GetDLMallocDirectMMap())(size_t size) { return dlMallocDirectMMap; } int (*GetDLMallocMUnmap())(void* ptr, size_t size) { return dlMallocMUnmap; } void* SLNet::_RakMalloc (size_t size) { return malloc(size); } void* SLNet::_RakRealloc (void *p, size_t size) { return realloc(p,size); } void SLNet::_RakFree (void *p) { free(p); } void* SLNet::_RakMalloc_Ex (size_t size, const char *file, unsigned int line) { (void) file; (void) line; return malloc(size); } void* SLNet::_RakRealloc_Ex (void *p, size_t size, const char *file, unsigned int line) { (void) file; (void) line; return realloc(p,size); } void SLNet::_RakFree_Ex (void *p, const char *file, unsigned int line) { (void) file; (void) line; free(p); } #ifdef _RAKNET_SUPPORT_DL_MALLOC void * SLNet::_DLMallocMMap (size_t size) { return RAK_MMAP_DEFAULT(size); } void * SLNet::_DLMallocDirectMMap (size_t size) { return RAK_DIRECT_MMAP_DEFAULT(size); } int SLNet::_DLMallocMUnmap (void *p, size_t size) { return RAK_MUNMAP_DEFAULT(p,size); } static mspace rakNetFixedHeapMSpace=0; void* _DLMalloc(size_t size) { return rak_mspace_malloc(rakNetFixedHeapMSpace,size); } void* _DLRealloc(void *p, size_t size) { return rak_mspace_realloc(rakNetFixedHeapMSpace,p,size); } void _DLFree(void *p) { if (p) rak_mspace_free(rakNetFixedHeapMSpace,p); } void* _DLMalloc_Ex (size_t size, const char *file, unsigned int line) { (void) file; (void) line; return rak_mspace_malloc(rakNetFixedHeapMSpace,size); } void* _DLRealloc_Ex (void *p, size_t size, const char *file, unsigned int line) { (void) file; (void) line; return rak_mspace_realloc(rakNetFixedHeapMSpace,p,size); } void _DLFree_Ex (void *p, const char *file, unsigned int line) { (void) file; (void) line; if (p) rak_mspace_free(rakNetFixedHeapMSpace,p); } void UseRaknetFixedHeap(size_t initialCapacity, void * (*yourMMapFunction) (size_t size), void * (*yourDirectMMapFunction) (size_t size), int (*yourMUnmapFunction) (void *p, size_t size)) { SetDLMallocMMap(yourMMapFunction); SetDLMallocDirectMMap(yourDirectMMapFunction); SetDLMallocMUnmap(yourMUnmapFunction); SetMalloc(_DLMalloc); SetRealloc(_DLRealloc); SetFree(_DLFree); SetMalloc_Ex(_DLMalloc_Ex); SetRealloc_Ex(_DLRealloc_Ex); SetFree_Ex(_DLFree_Ex); rakNetFixedHeapMSpace=rak_create_mspace(initialCapacity, 0); } void FreeRakNetFixedHeap(void) { if (rakNetFixedHeapMSpace) { rak_destroy_mspace(rakNetFixedHeapMSpace); rakNetFixedHeapMSpace=0; } SetMalloc(_RakMalloc); SetRealloc(_RakRealloc); SetFree(_RakFree); SetMalloc_Ex(_RakMalloc_Ex); SetRealloc_Ex(_RakRealloc_Ex); SetFree_Ex(_RakFree_Ex); } #else void * SLNet::_DLMallocMMap (size_t size) {(void) size; return 0;} void * SLNet::_DLMallocDirectMMap (size_t size) {(void) size; return 0;} int SLNet::_DLMallocMUnmap (void *p, size_t size) {(void) size; (void) p; return 0;} void* _DLMalloc(size_t size) {(void) size; return 0;} void* _DLRealloc(void *p, size_t size) {(void) p; (void) size; return 0;} void _DLFree(void *p) {(void) p;} void* _DLMalloc_Ex (size_t size, const char *file, unsigned int line) {(void) size; (void) file; (void) line; return 0;} void* _DLRealloc_Ex (void *p, size_t size, const char *file, unsigned int line) {(void) p; (void) size; (void) file; (void) line; return 0;} void _DLFree_Ex (void *p, const char *file, unsigned int line) {(void) p; (void) file; (void) line;} void UseRaknetFixedHeap(size_t initialCapacity, void * (*yourMMapFunction) (size_t size), void * (*yourDirectMMapFunction) (size_t size), int (*yourMUnmapFunction) (void *p, size_t size)) { (void) initialCapacity; (void) yourMMapFunction; (void) yourDirectMMapFunction; (void) yourMUnmapFunction; } void FreeRakNetFixedHeap(void) {} #endif #if _USE_RAK_MEMORY_OVERRIDE==1 #if defined(RMO_MALLOC_UNDEF) #pragma pop_macro("malloc") #undef RMO_MALLOC_UNDEF #endif #if defined(RMO_REALLOC_UNDEF) #pragma pop_macro("realloc") #undef RMO_REALLOC_UNDEF #endif #if defined(RMO_FREE_UNDEF) #pragma pop_macro("free") #undef RMO_FREE_UNDEF #endif #endif
3,137
16,461
// Copyright 2018-present 650 Industries. All rights reserved. #import <React/RCTBridgeModule.h> #import <ExpoModulesCore/EXModuleRegistryProvider.h> // An "adapter" over module registry, for given RCTBridge and NSString // is able to provide an array of exported RCTBridgeModules. Override // it and use in your AppDelegate to export different bridge modules // for different experiences. NS_SWIFT_NAME(ModuleRegistryAdapter) @interface EXModuleRegistryAdapter : NSObject @property (nonnull, nonatomic, readonly) EXModuleRegistryProvider *moduleRegistryProvider; - (instancetype)initWithModuleRegistryProvider:(nonnull EXModuleRegistryProvider *)moduleRegistryProvider __deprecated_msg("Expo modules are now automatically registered. You can remove this method call."); - (nonnull NSArray<id<RCTBridgeModule>> *)extraModulesForModuleRegistry:(nonnull EXModuleRegistry *)moduleRegistry; - (nonnull NSArray<id<RCTBridgeModule>> *)extraModulesForBridge:(nonnull RCTBridge *)bridge __deprecated_msg("Expo modules are now automatically registered. You can replace this with an empty array."); @end
301
892
{ "schema_version": "1.2.0", "id": "GHSA-9cxr-7vrj-vpj8", "modified": "2022-05-01T18:34:55Z", "published": "2022-05-01T18:34:55Z", "aliases": [ "CVE-2007-5589" ], "details": "Multiple cross-site scripting (XSS) vulnerabilities in phpMyAdmin before 2.11.1.2 allow remote attackers to inject arbitrary web script or HTML via certain input available in (1) PHP_SELF in (a) server_status.php, and (b) grab_globals.lib.php, (c) display_change_password.lib.php, and (d) common.lib.php in libraries/; and certain input available in PHP_SELF and (2) PATH_INFO in libraries/common.inc.php. NOTE: there might also be other vectors related to (3) REQUEST_URI.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2007-5589" }, { "type": "WEB", "url": "https://bugzilla.redhat.com/show_bug.cgi?id=333661" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/37292" }, { "type": "WEB", "url": "https://www.redhat.com/archives/fedora-package-announce/2007-November/msg00040.html" }, { "type": "WEB", "url": "http://lists.opensuse.org/opensuse-security-announce/2008-03/msg00004.html" }, { "type": "WEB", "url": "http://osvdb.org/37939" }, { "type": "WEB", "url": "http://phpmyadmin.svn.sourceforge.net/viewvc/phpmyadmin/branches/MAINT_2_11_1/phpMyAdmin/ChangeLog?r1=10796&r2=10795&pathrev=10796" }, { "type": "WEB", "url": "http://phpmyadmin.svn.sourceforge.net/viewvc/phpmyadmin?view=rev&revision=10796" }, { "type": "WEB", "url": "http://secunia.com/advisories/27246" }, { "type": "WEB", "url": "http://secunia.com/advisories/27506" }, { "type": "WEB", "url": "http://secunia.com/advisories/27595" }, { "type": "WEB", "url": "http://secunia.com/advisories/29323" }, { "type": "WEB", "url": "http://www.debian.org/security/2007/dsa-1403" }, { "type": "WEB", "url": "http://www.digitrustgroup.com/advisories/TDG-advisory071015a.html" }, { "type": "WEB", "url": "http://www.mandriva.com/security/advisories?name=MDKSA-2007:199" }, { "type": "WEB", "url": "http://www.phpmyadmin.net/home_page/security.php?issue=PMASA-2007-6" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/26301" }, { "type": "WEB", "url": "http://www.vupen.com/english/advisories/2007/3535" } ], "database_specific": { "cwe_ids": [ "CWE-79" ], "severity": "MODERATE", "github_reviewed": false } }
1,342
3,690
#define CATCH_CONFIG_MAIN #include "../Catch/single_include/catch.hpp" #include "solution.h" TEST_CASE("Permutation Sequence", "[getPermutation]") { Solution s; REQUIRE( s.getPermutation(3, 5) == "312" ); REQUIRE( s.getPermutation(8, 31492) == "72641583" ); }
118
8,805
<filename>ios/Pods/boost-for-react-native/boost/fusion/adapted/struct/define_struct_inline.hpp /*============================================================================= Copyright (c) 2012 <NAME> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef BOOST_FUSION_ADAPTED_STRUCT_DEFINE_STRUCT_INLINE_HPP #define BOOST_FUSION_ADAPTED_STRUCT_DEFINE_STRUCT_INLINE_HPP #include <boost/fusion/support/config.hpp> #include <boost/fusion/adapted/struct/adapt_struct.hpp> #include <boost/fusion/adapted/struct/detail/define_struct_inline.hpp> #define BOOST_FUSION_DEFINE_TPL_STRUCT_INLINE( \ TEMPLATE_PARAMS_SEQ, NAME, ATTRIBUTES) \ \ BOOST_FUSION_DEFINE_TPL_STRUCT_INLINE_IMPL( \ TEMPLATE_PARAMS_SEQ, \ NAME, \ ATTRIBUTES) #define BOOST_FUSION_DEFINE_STRUCT_INLINE(NAME, ATTRIBUTES) \ BOOST_FUSION_DEFINE_STRUCT_INLINE_IMPL(NAME, ATTRIBUTES) \ #endif
782
1,093
<gh_stars>1000+ /* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.config.xml; import org.w3c.dom.Element; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.util.StringUtils; /** * Base class for url-based outbound gateway parsers. * * @author <NAME> * @author <NAME> */ public abstract class AbstractOutboundGatewayParser extends AbstractConsumerEndpointParser { protected abstract String getGatewayClassName(Element element); @Override protected String getInputChannelAttributeName() { return "request-channel"; } @Override protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(this.getGatewayClassName(element)); String url = this.parseUrl(element, parserContext); builder.addConstructorArgValue(url); String replyChannel = element.getAttribute("reply-channel"); if (StringUtils.hasText(replyChannel)) { builder.addPropertyReference("replyChannel", replyChannel); } IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "requires-reply"); this.postProcessGateway(builder, element, parserContext); return builder; } protected String parseUrl(Element element, ParserContext parserContext) { String url = element.getAttribute("url"); if (!StringUtils.hasText(url)) { parserContext.getReaderContext().error("The 'url' attribute is required.", element); } return url; } /** * Subclasses may override this method for additional configuration. * @param builder The builder. * @param element The element. * @param parserContext The parser context. */ protected void postProcessGateway(BeanDefinitionBuilder builder, Element element, ParserContext parserContext) { } }
682
543
<gh_stars>100-1000 package com.riiablo.net; import com.riiablo.net.packet.mcp.CreateGame; import com.riiablo.net.packet.mcp.JoinGame; import com.riiablo.net.packet.msi.StartInstance; public class GameSession { public String name; public String password; public String desc; public int numPlayers; public int ip; public short port; public GameSession() {} public GameSession(com.riiablo.net.packet.mcp.GameSession game) { name = game.name(); desc = game.desc(); } public GameSession(CreateGame game) { name = game.gameName(); desc = game.description(); } GameSession(Builder builder) { name = builder.name; password = <PASSWORD>; desc = builder.desc; } public GameSession setConnectInfo(StartInstance info) { ip = info.ip(); port = info.port(); return this; } public GameSession setConnectInfo(JoinGame info) { ip = info.ip(); port = info.port(); return this; } @Override public String toString() { return name; } public static Builder builder() { return new Builder(); } public static class Builder { public String name; public String password; public String desc; public GameSession build() { return new GameSession(this); } } }
452
840
#ifndef SLOT_H #define SLOT_H #include <stdint.h> #include "parser.h" #include "socket.h" #define MAX_DESC_PART_LEN 64 #define MAX_NODE_LIST 16 #define MAX_SLAVE_NODES 64 #define REDIS_CLUSTER_SLOTS 16384 struct context; enum { SLOT_UPDATE_UNKNOWN, SLOT_UPDATE_INIT, SLOT_UPDATE, SLOT_RELOAD, SLOT_UPDATER_QUIT, }; struct desc_part { char data[MAX_DESC_PART_LEN]; uint8_t len; }; struct node_desc { struct desc_part *parts; uint16_t index, len; }; struct node_info { char name[64]; // contains master and slaves of one shard struct address nodes[MAX_SLAVE_NODES + 1]; size_t index; // length of `nodes` above int refcount; // for parsing slots of a master node struct desc_part *slot_spec; int spec_length; }; uint16_t slot_get(struct pos_array *pos); void node_list_get(char *dest); bool slot_get_node_addr(uint16_t slot, struct node_info *info); void slot_create_job(int type); int slot_start_manager(struct context *ctx); #endif /* end of include guard: SLOT_H */
431
310
<reponame>niansa/skylicht-engine /* !@ MIT License Copyright (c) 2021 Skylicht Technology CO., LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the Rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This file is part of the "Skylicht Engine". https://github.com/skylicht-lab/skylicht-engine !# */ #pragma once #include "Utils/CGameSingleton.h" #include "CSelectObject.h" namespace Skylicht { namespace Editor { class CSelection : public CGameSingleton<CSelection> { protected: std::vector<CSelectObject*> m_selected; public: CSelection(); virtual ~CSelection(); std::vector<CSelectObject*>& getSelected() { return m_selected; } std::vector<CSelectObject*> getSelectedByType(CSelectObject::ESelectType type); void clear(); CSelectObject* getLastSelected(); CSelectObject* getSelected(CGameObject* obj); CSelectObject* addSelect(CGameObject* obj); void notify(CGameObject* obj, IObserver *from); void addSelect(const std::vector<CGameObject*>& obj); void unSelect(CGameObject* obj); void unSelect(const std::vector<CGameObject*>& obj); }; } }
645
1,907
<reponame>oktomus/appleseed<filename>src/thirdparty/bcd/bcd/SpikeRemovalFilter.h<gh_stars>1000+ // This file comes from the original BCD implementation, // with minor changes to remove dependencies, unused code // and re-formatting. Original license follows: // This file is part of the reference implementation for the paper // Bayesian Collaborative Denoising for Monte-Carlo Rendering // <NAME> and <NAME>. // Computer Graphics Forum (Proc. EGSR 2017), vol. 36, no. 4, p. 137-153, 2017 // // All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.txt file. #ifndef SPIKE_REMOVAL_FILTER_H #define SPIKE_REMOVAL_FILTER_H // Standard headers. #include <vector> namespace bcd { template<typename T> class DeepImage; class SpikeRemovalFilter { public: static void filter( DeepImage<float>& io_rInputColorImage, DeepImage<float>& io_rInputNbOfSamplesImage, DeepImage<float>& io_rInputHistogramImage, DeepImage<float>& io_rInputCovImage, float i_thresholdStDevFactor = 2.f); static void filter( DeepImage<float>& io_rInputColorImage, float i_thresholdStDevFactor = 2.f); private: static void computeAverageAndStandardDeviation( float& o_rAverage, float& o_rStandardDeviation, const std::vector<float>& i_rData); // Simple and expensive (quadratic) implementation of multi-dimensional // median as the minimizer of L1 distance among elements static int compute3DMedianIndex( const std::vector<float>& i_rDataR, const std::vector<float>& i_rDataG, const std::vector<float>& i_rDataB); }; } // namespace bcd #endif
774
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.applicationinsights.generated; import com.azure.core.util.Context; import com.azure.resourcemanager.applicationinsights.models.WorkbookTemplate; /** Samples for WorkbookTemplates Update. */ public final class WorkbookTemplatesUpdateSamples { /* * x-ms-original-file: specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2020-11-20/examples/WorkbookTemplateUpdate.json */ /** * Sample code: WorkbookTemplateUpdate. * * @param manager Entry point to ApplicationInsightsManager. */ public static void workbookTemplateUpdate( com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { WorkbookTemplate resource = manager .workbookTemplates() .getByResourceGroupWithResponse("my-resource-group", "my-template-resource", Context.NONE) .getValue(); resource.update().apply(); } }
386
513
void make(vector<int>& A, int curr, vector<bool> visited, vector<int> temp, vector<vector<int> >& ans){ int n = A.size(); curr = curr%n; for(int i = curr; i < n; i++){ if(!visited[i]){ vector<int> temp1(temp); vector<bool> visited1(visited); temp1.push_back(A[i]); visited1[i] = true; make(A, i+1, visited1, temp1, ans); } } for(int i = 0; i < curr; i++){ if(!visited[i]){ vector<int> temp1(temp); vector<bool> visited1(visited); temp1.push_back(A[i]); visited1[i] = true; make(A, i+1, visited1, temp1, ans); } } if(temp.size() == n){ ans.push_back(temp); } } vector<vector<int> > Solution::permute(vector<int> &A) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details vector<vector<int> > ans; vector<bool> visited(A.size(), false); vector<int> temp; make(A, 0, visited, temp, ans); return ans; }
610
3,428
{"id":"00863","group":"easy-ham-1","checksum":{"type":"MD5","value":"f20cfe969a2e3162ce6ce19fd80188bd"},"text":"From <EMAIL> Thu Oct 3 12:55:28 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 2F78D16F16\n\tfor <jm@localhost>; Thu, 3 Oct 2002 12:53:37 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Thu, 03 Oct 2002 12:53:37 +0100 (IST)\nReceived: from xent.com ([64.161.22.236]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g92LeEK30274 for <<EMAIL>>;\n Wed, 2 Oct 2002 22:40:16 +0100\nReceived: from lair.xent.com (localhost [1172.16.58.3]) by xent.com (Postfix)\n with ESMTP id B2ECD2940CE; Wed, 2 Oct 2002 14:40:03 -0700 (PDT)\nDelivered-To: <EMAIL>\nReceived: from crank.slack.net (slack.net [166.84.151.181]) by xent.com\n (Postfix) with ESMTP id 1075A29409C for <<EMAIL>>; Wed,\n 2 Oct 2002 14:39:38 -0700 (PDT)\nReceived: by crank.slack.net (Postfix, from userid 596) id 9EF443ECAE;\n Wed, 2 Oct 2002 17:44:24 -0400 (EDT)\nReceived: from localhost (localhost [127.0.0.1]) by crank.slack.net\n (Postfix) with ESMTP id 9D4D23EC76; Wed, 2 Oct 2002 17:44:24 -0400 (EDT)\nFrom: Tom <<EMAIL>>\nTo: <NAME> <<EMAIL>>\nCc: <EMAIL>\nSubject: Re: Wifi query\nIn-Reply-To: <<EMAIL>>\nMessage-Id: <<EMAIL>.4.44.02100217312<EMAIL>-<EMAIL>>\nMIME-Version: 1.0\nContent-Type: TEXT/PLAIN; charset=US-ASCII\nSender: [email protected]\nErrors-To: [email protected]\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of <NAME> <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: Wed, 2 Oct 2002 17:44:24 -0400 (EDT)\n\nOn Wed, 2 Oct 2002, <NAME> wrote:\n--]<NAME> wrote:\n--]> 802.11b - 11Mbps per channel over three channels in the 2.4GHz range\n--]> (also shared with microwaves and cordless phones)\n--]\n--]Microwaves, cordless phones and video-based baby monitors....\n\nWell I dont have to worry about microwavers in the house. Ours died a week\nor so ago and due to doing some research we will nto be getting anysuch\ndevice in the near or far future. I mean even if one half of the crap it\nis reported to do is true it s just not worth it for a quick cup or warm\nchai.\n\nWhich brings me to the fact that finding a good Convection only (not combo\nwith a microwaver) oven of any good size is dang near impossible unless\nyou go up to the bizness sizes. thankfully there is Dehlongi of which\ncostco has thru thier online store.\n\nNow of course the question is do we get it delivered to the old house or\nthe new one (yep we got our offer approved and are in the short run down\nto a long mortage:) we close on oct 31. though the realestate agent says\nt happens like that a lot, I still find it incrediably jolting to have\nfound a house inthe hood I want with the space dawn wants on sunday and we\nare signing papers on tuesday night with a close at the end of the month.\n\nWhich of course means....wifi land for wsmf:)- )\n\nSo far I like the Linksys dsl/cable router all in one wifi ap. The Dlink\nhas the funky 22mb stuff IF you use all thier stuff across the net and the\nway things go I cant say thats gonna happen for sure. Pluse the Linksys\nstuff is all over the mass market sotres so I cna walk home with parts at\nany time.\n\nThe fun now comes with a realization that with ATTbi cable as my main hose\ntot he net offering up bwf might be a tad problematic....So i am thinking\nof ways around/through/under that. the setup of the particualrs are far\nform set in stone...any ideas would be welcome.\n\nAlso any portlanders.....party time.\n\n\n-tom\n\n\n\n\n"}
1,495
389
<reponame>puradawid/aem-core-wcm-components /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2021 Adobe ~ ~ 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.adobe.cq.wcm.core.components.commons.editor.dialog; import org.apache.sling.testing.mock.sling.servlet.MockRequestPathInfo; import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import com.adobe.cq.wcm.core.components.commons.editor.dialog.inherited.PageImageThumbnail; import com.adobe.cq.wcm.core.components.context.CoreComponentTestContext; import com.google.common.collect.ImmutableMap; import io.wcm.testing.mock.aem.junit5.AemContext; import io.wcm.testing.mock.aem.junit5.AemContextExtension; import static org.junit.jupiter.api.Assertions.*; @ExtendWith(AemContextExtension.class) public class PageImageThumbnailTest { private static final String TEST_BASE = "/commons/editor/dialog/pageimagethumbnail"; private static final String CONTENT_ROOT = "/content"; private static final String RESOURCE1 = CONTENT_ROOT + "/page/jcr:content/root/responsivegrid/image"; private static final String RESOURCE2 = CONTENT_ROOT + "/page/jcr:content/root/responsivegrid/image1"; private final AemContext context = CoreComponentTestContext.newAemContext(); @BeforeEach void setUp() throws Exception { context.load().json(TEST_BASE + "/test-content.json", CONTENT_ROOT); } @Test void testPageImageThumbnailWithSuffix() { context.currentResource(RESOURCE1); MockSlingHttpServletRequest request = context.request(); MockRequestPathInfo requestPathInfo = (MockRequestPathInfo) request.getRequestPathInfo(); requestPathInfo.setSuffix(RESOURCE1); requestPathInfo.setResourcePath(RESOURCE1); PageImageThumbnail pageImageThumbnail = request.adaptTo(PageImageThumbnail.class); if (pageImageThumbnail != null) { assertEquals("featured image alt", pageImageThumbnail.getAlt(), "getAlt()"); assertEquals("/content/page/_jcr_content/_cq_featuredimage.coreimg.png", pageImageThumbnail.getSrc(), "getSrc()"); assertEquals("/content/page/jcr:content/root/responsivegrid/image", pageImageThumbnail.getComponentPath(), "getComponentPath()"); assertEquals("/content/page/jcr:content/root/responsivegrid/image", pageImageThumbnail.getConfigPath(), "getConfigPath()"); assertEquals("/content/page", pageImageThumbnail.getCurrentPagePath(), "getCurrentPagePath()"); } else { fail("can't create page image thumnbail model"); } } @Test void testPageImageThumbnailWithParam() { context.currentResource(RESOURCE1); MockSlingHttpServletRequest request = context.request(); request.setParameterMap(ImmutableMap.of("item", RESOURCE1)); PageImageThumbnail pageImageThumbnail = request.adaptTo(PageImageThumbnail.class); if (pageImageThumbnail != null) { assertEquals("featured image alt", pageImageThumbnail.getAlt(), "getAlt()"); assertEquals("/content/page/_jcr_content/_cq_featuredimage.coreimg.png", pageImageThumbnail.getSrc(), "getSrc()"); } } @Test void testPageImageThumbnailWithLinkURL() { context.currentResource(RESOURCE1); MockSlingHttpServletRequest request = context.request(); request.setParameterMap(ImmutableMap.of("item", RESOURCE1, "linkURL", "/content/page1")); PageImageThumbnail pageImageThumbnail = request.adaptTo(PageImageThumbnail.class); if (pageImageThumbnail != null) { assertEquals("featured image alt for page 1", pageImageThumbnail.getAlt(), "getAlt()"); assertEquals("/content/page1/_jcr_content/_cq_featuredimage.coreimg.png", pageImageThumbnail.getSrc(), "getSrc()"); } } @Test void testPageImageThumbnailWithoutParam() { context.currentResource(RESOURCE1); MockSlingHttpServletRequest request = context.request(); PageImageThumbnail pageImageThumbnail = request.adaptTo(PageImageThumbnail.class); if (pageImageThumbnail != null) { assertNull(pageImageThumbnail.getAlt(), "getAlt()"); assertNull(pageImageThumbnail.getSrc(), "getSrc()"); } } @Test void testPageImageThumbnailWithNonExistingResource() { MockSlingHttpServletRequest request = context.request(); MockRequestPathInfo requestPathInfo = (MockRequestPathInfo) request.getRequestPathInfo(); requestPathInfo.setSuffix(RESOURCE2); PageImageThumbnail pageImageThumbnail = request.adaptTo(PageImageThumbnail.class); if (pageImageThumbnail != null) { assertNull(pageImageThumbnail.getAlt(), "getAlt()"); assertNull(pageImageThumbnail.getSrc(), "getSrc()"); } } }
1,951
1,338
/* * Copyright 2008 <NAME>, oliver.ruiz.dorantes_at_gmail.com * Copyright 2008 <NAME> * Copyright 2019-2020 Haiku, Inc. * All rights reserved. Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> */ // https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers const char* bluetoothManufacturers[] = { "Ericsson Technology Licensing", "Nokia Mobile Phones", "Intel Corp.", "IBM Corp.", "Toshiba Corp.", "3Com", "Microsoft", "Lucent", "Motorola", "Infineon Technologies AG", "Cambridge Silicon Radio", "Silicon Wave", "Digianswer A/S", "Texas Instruments Inc.", "Parthus Technologies Inc.", "Broadcom Corporation", "Mitel Semiconductor", "Widcomm, Inc.", "Zeevo, Inc.", "Atmel Corporation", "Mitsubishi Electric Corporation", "RTX Telecom A/S", "KC Technology Inc.", "Newlogic", "Transilica, Inc.", "Rohde & Schwarz GmbH & Co. KG", "TTPCom Limited", "Signia Technologies, Inc.", "Conexant Systems Inc.", "Qualcomm", "Inventel", "AVM Berlin", "BandSpeed, Inc.", "Mansella Ltd", "NEC Corporation", "WavePlus Technology Co., Ltd.", "Alcatel", "NXP Semiconductors (formerly Philips Semiconductors)", "C Technologies", "Open Interface", "R F Micro Devices", "Hitachi Ltd", "Symbol Technologies, Inc.", "Tenovis", "Macronix International Co. Ltd.", "GCT Semiconductor", "Norwood Systems", "MewTel Technology Inc.", "ST Microelectronics", "Synopsys, Inc.", "Red-M (Communications) Ltd", "Commil Ltd", "Computer Access Technology Corporation (CATC)", "Eclipse (HQ Espana) S.L.", "Renesas Electronics Corporation", "Mobilian Corporation", "Terax", "Integrated System Solution Corp.", "Matsushita Electric Industrial Co., Ltd.", "Gennum Corporation", "BlackBerry Limited (formerly Research In Motion)", "IPextreme, Inc.", "Systems and Chips, Inc", "Bluetooth SIG, Inc", "Seiko Epson Corporation", "Integrated Silicon Solution Taiwan, Inc.", "CONWISE Technology Corporation Ltd", "PARROT SA", "Socket Mobile", "Atheros Communications, Inc.", "MediaTek, Inc.", "Bluegiga", "Marvell Technology Group Ltd.", "3DSP Corporation", "Accel Semiconductor Ltd.", "Continental Automotive Systems", "Apple, Inc.", "Staccato Communications, Inc.", "Avago Technologies", "APT Ltd.", "SiRF Technology, Inc.", "Tzero Technologies, Inc.", "J&M Corporation", "Free2move AB", "3DiJoy Corporation", "Plantronics, Inc.", "Sony Ericsson Mobile Communications", "Harman International Industries, Inc.", "Vizio, Inc.", "Nordic Semiconductor ASA", "EM Microelectronic-Marin SA", "Ralink Technology Corporation", "Belkin International, Inc.", "Realtek Semiconductor Corporation", "Stonestreet One, LLC", "Wicentric, Inc.", "RivieraWaves S.A.S", "RDA Microelectronics", "<NAME>", "MiCommand Inc.", "Band XI International, LLC", "Hewlett-Packard Company", "9Solutions Oy", "GN Netcom A/S", "General Motors", "A&D Engineering, Inc.", "MindTree Ltd.", "Polar Electro OY", "Beautiful Enterprise Co., Ltd.", "BriarTek, Inc", "Summit Data Communications, Inc.", "Sound ID", "Monster, LLC", "connectBlue AB", "ShangHai Super Smart Electronics Co. Ltd.", "Group Sense Ltd.", "Zomm, LLC", "Samsung Electronics Co. Ltd.", "Creative Technology Ltd.", "Laird Technologies", "Nike, Inc.", "lesswire AG", "MStar Semiconductor, Inc.", "Hanlynn Technologies", "A & R Cambridge", "Seers Technology Co., Ltd.", "Sports Tracking Technologies Ltd.", "Autonet Mobile", "DeLorme Publishing Company, Inc.", "<NAME>", "Sennheiser Communications A/S", "TimeKeeping Systems, Inc.", "Ludus Helsinki Ltd.", "BlueRadios, Inc.", "Equinux AG", "Garmin International, Inc.", "Ecotest", "GN ReSound A/S", "Jawbone", "Topcon Positioning Systems, LLC", "Gimbal Inc. (formerly Qualcomm Labs, Inc. and Qualcomm Retail Solutions, Inc.)", "Zscan Software", "Quintic Corp", "Telit Wireless Solutions GmbH (formerly Stollmann E+V GmbH)", "Funai Electric Co., Ltd.", "Advanced PANMOBIL systems GmbH & Co. KG", "ThinkOptics, Inc.", "Universal Electronics, Inc.", "Airoha Technology Corp.", "NEC Lighting, Ltd.", "ODM Technology, Inc.", "ConnecteDevice Ltd.", "zero1.tv GmbH", "i.Tech Dynamic Global Distribution Ltd.", "Alpwise", "Jiangsu Toppower Automotive Electronics Co., Ltd.", "Colorfy, Inc.", "Geoforce Inc.", "Bose Corporation", "Su<NAME>", "Kensington Computer Products Group", "SR-Medizinelektronik", "Vertu Corporation Limited", "Meta Watch Ltd.", "LINAK A/S", "OTL Dynamics LLC", "Panda Ocean Inc.", "Visteon Corporation", "ARP Devices Limited", "<NAME> S.p.A", "CAEN RFID srl", "Ingenieur-Systemgruppe Zahn GmbH", "Green Throttle Games", "Peter Systemtechnik GmbH", "Omegawave Oy", "Cinetix", "Passif Semiconductor Corp", "Saris Cycling Group, Inc", "Bekey A/S", "Clarinox Technologies Pty. Ltd.", "BDE Technology Co., Ltd.", "Swirl Networks", "Meso international", "TreLab Ltd", "Qualcomm Innovation Center, Inc. (QuIC)", "Johnson Controls, Inc.", "Starkey Laboratories Inc.", "S-Power Electronics Limited", "Ace Sensor Inc", "Aplix Corporation", "AAMP of America", "Stalmart Technology Limited", "AMICCOM Electronics Corporation", "Shenzhen Excelsecu Data Technology Co.,Ltd", "Geneq Inc.", "adidas AG", "LG Electronics", "Onset Computer Corporation", "Selfly BV", "Quuppa Oy.", "GeLo Inc", "Evluma", "MC10", "Binauric SE", "Beats Electronics", "Microchip Technology Inc.", "Elgato Systems GmbH", "ARCHOS SA", "Dexcom, Inc.", "Polar Electro Europe B.V.", "Dialog Semiconductor B.V.", "Taixingbang Technology (HK) Co,. LTD.", "Kawantech", "Austco Communication Systems", "Timex Group USA, Inc.", "Qualcomm Technologies, Inc.", "Qualcomm Connected Experiences, Inc.", "Voyetra Turtle Beach", "txtr GmbH", "Biosentronics", "Procter & Gamble", "Hosiden Corporation", "Muzik LLC", "Misfit Wearables Corp", "Google", "Danlers Ltd", "Semilink Inc", "inMusic Brands, Inc", "L.S. Research Inc.", "Eden Software Consultants Ltd.", "Freshtemp", "KS Technologies", "ACTS Technologies", "Vtrack Systems", "Nielsen-Kellerman Company", "Server Technology Inc.", "BioResarch Associates", "Jolly Logic, LLC", "Above Average Outcomes, Inc.", "Bitsplitters GmbH", "PayPal, Inc.", "Witron Technology Limited", "Morse Project Inc.", "Kent Displays Inc.", "Nautilus Inc.", "Smartifier Oy", "Elcometer Limited", "VSN Technologies, Inc.", "AceUni Corp., Ltd.", "StickNFind", "Crystal Code AB", "KOUKAAM a.s.", "Delphi Corporation", "ValenceTech Limited", "Stan<NAME>cker", "Typo Products, LLC", "TomTom International BV", "Fugoo, Inc.", "Keiser Corporation", "Bang & Olufsen S/A", "PLUS Location Systems Pty Ltd", "Ubiquitous Computing Technology Corporation", "Innovative Yachtter Solutions", "<NAME>ant Holding A/S", "Chicony Electronics Co., Ltd.", "Atus BV", "Codegate Ltd", "ERi, Inc", "Transducers Direct, LLC", "Fujitsu Ten LImited", "Audi AG", "HiSilicon Technologies Col, Ltd.", "Nippon Seiki Co., Ltd.", "Steelseries ApS", "Visybl Inc.", "Openbrain Technologies, Co., Ltd.", "Xensr", "e.solutions", "10AK Technologies", "Wimoto Technologies Inc", "Radius Networks, Inc.", "Wize Technology Co., Ltd.", "Qualcomm Labs, Inc.", "Aruba Networks", "Baidu", "Arendi AG", "Skoda Auto a.s.", "Volkwagon AG", "Porsche AG", "Sino Wealth Electronic Ltd.", "AirTurn, Inc.", "Kinsa, Inc", "HID Global", "SEAT es", "Promethean Ltd.", "Salutica Allied Solutions", "GPSI Group Pty Ltd", "Nimble Devices Oy", "Changzhou Yongse Infotech Co., Ltd.", "SportIQ", "TEMEC Instruments B.V.", "Sony Corporation", "ASSA ABLOY", "Clarion Co. Inc.", "Warehouse Innovations", "Cypress Semiconductor", "MADS Inc", "Blue Maestro Limited", "Resolution Products, Ltd.", "Aireware LLC", "Seed Labs, Inc. (formerly ETC sp. z.o.o.)", "Prestigio Plaza Ltd.", "NTEO Inc.", "Focus Systems Corporation", "Tencent Holdings Ltd.", "Allegion", "Murata Manufacturing Co., Ltd.", "WirelessWERX", "Nod, Inc.", "B&B Manufacturing Company", "Alpine Electronics (China) Co., Ltd", "FedEx Services", "Grape Systems Inc.", "Bkon Connect", "Lintech GmbH", "Novatel Wireless", "Ciright", "Mighty Cast, Inc.", "Ambimat Electronics", "Perytons Ltd.", "Tivoli Audio, LLC", "Master Lock", "Mesh-Net Ltd", "HUIZHOU DESAY SV AUTOMOTIVE CO., LTD.", "Tangerine, Inc.", "B&W Group Ltd.", "Pioneer Corporation", "OnBeep", "Vernier Software & Technology", "ROL Ergo", "Pebble Technology", "NETATMO", "Accumulate AB", "Anhui Huami Information Technology Co., Ltd.", "Inmite s.r.o.", "ChefSteps, Inc.", "micas AG", "Biomedical Research Ltd.", "Pitius Tec S.L.", "Estimote, Inc.", "Unikey Technologies, Inc.", "Timer Cap Co.", "AwoX", "yikes", "MADSGlobalNZ Ltd.", "PCH International", "Qingdao Yeelink Information Technology Co., Ltd.", "Milwaukee Tool (Formally Milwaukee Electric Tools)", "MISHIK Pte Ltd", "Bayer HealthCare", "Spicebox LLC", "emberlight", "Cooper-Atkins Corporation", "Qblinks", "MYSPHERA", "LifeScan Inc", "Volantic AB", "Podo Labs, Inc", "Roche Diabetes Care AG", "Amazon Fulfillment Service", "Connovate Technology Private Limited", "Kocomojo, LLC", "EveryKey LLC", "Dynamic Controls", "SentriLock", "I-SYST inc.", "CASIO COMPUTER CO., LTD.", "LAPIS Semiconductor Co., Ltd.", "Telemonitor, Inc.", "taskit GmbH", "Daimler AG", "BatAndCat", "BluDotz Ltd", "XTel ApS", "Gigaset Communications GmbH", "Gecko Health Innovations, Inc.", "HOP Ubiquitous", "<NAME>", "Nectar", "bel'apps LLC", "CORE Lighting Ltd", "Seraphim Sense Ltd", "Unico RBC", "Physical Enterprises Inc.", "Able Trend Technology Limited", "Konica Minolta, Inc.", "Wilo SE", "Extron Design Services", "Fitbit, Inc.", "Fireflies Systems", "Intelletto Technologies Inc.", "FDK CORPORATION", "Cloudleaf, Inc", "Maveric Automation LLC", "Acoustic Stream Corporation", "Zuli", "Paxton Access Ltd", "WiSilica Inc.", "<NAME>", "SALTO SYSTEMS S.L.", "TRON Forum (formerly T-Engine Forum)", "CUBETECH s.r.o.", "Cokiya Incorporated", "CVS Health", "Ceruus", "Strainstall Ltd", "Channel Enterprises (HK) Ltd.", "FIAMM", "GIGALANE.CO.,LTD", "EROAD", "Mine Safety Appliances", "Icon Health and Fitness", "Asandoo GmbH", "ENERGOUS CORPORATION", "Taobao", "Canon Inc.", "Geophysical Technology Inc.", "Facebook, Inc.", "Nipro Diagnostics, Inc.", "FlightSafety International", "Earlens Corporation", "Sunrise Micro Devices, Inc.", "Star Micronics Co., Ltd.", "Netizens Sp. z o.o.", "Nymi Inc.", "Nytec, Inc.", "Trineo Sp. z o.o.", "Nest Labs Inc.", "LM Technologies Ltd", "General Electric Company", "i+D3 S.L.", "<NAME>", "Stages Cycling LLC", "Cochlear Bone Anchored Solutions AB", "SenionLab AB", "Syszone Co., Ltd", "Pulsate Mobile Ltd.", "Hong Kong HunterSun Electronic Limited", "pironex GmbH", "BRADATECH Corp.", "Transenergooil AG", "Bunch", "DME Microelectronics", "Bitcraze AB", "HASWARE Inc.", "Abiogenix Inc.", "Poly-Control ApS", "Avi-on", "Laerdal Medical AS", "Fetch My Pet", "Sam Labs Ltd.", "Chengdu Synwing Technology Ltd", "HOUWA SYSTEM DESIGN, k.k.", "BSH", "Primus Inter Pares Ltd", "August Home, Inc", "Gill Electronics", "Sky Wave Design", "Newlab S.r.l.", "ELAD srl", "G-wearables inc.", "Squadrone Systems Inc.", "Code Corporation", "Savant Systems LLC", "Logitech International SA", "Innblue Consulting", "iParking Ltd.", "Koninklijke Philips Electronics N.V.", "Minelab Electronics Pty Limited", "Bison Group Ltd.", "Widex A/S", "Jolla Ltd", "Lectronix, Inc.", "Caterpillar Inc", "Freedom Innovations", "Dynamic Devices Ltd", "Technology Solutions (UK) Ltd", "IPS Group Inc.", "STIR", "Sano, Inc.", "Advanced Application Design, Inc.", "AutoMap LLC", "Spreadtrum Communications Shanghai Ltd", "CuteCircuit LTD", "Valeo Service", "Fullpower Technologies, Inc.", "KloudNation", "Zebra Technologies Corporation", "Itron, Inc.", "The University of Tokyo", "UTC Fire and Security", "Cool Webthings Limited", "DJO Global", "Gelliner Limited", "Anyka (Guangzhou) Microelectronics Technology Co, LTD", "Medtronic Inc.", "Gozio Inc.", "Form Lifting, LLC", "Wahoo Fitness, LLC", "Kontakt Micro-Location Sp. z o.o.", "Radio Systems Corporation", "Freescale Semiconductor, Inc.", "Verifone Systems Pte Ltd. Taiwan Branch", "AR Timing", "Rigado LLC", "Kemppi Oy", "Tapcentive Inc.", "Smartbotics Inc.", "Otter Products, LLC", "STEMP Inc.", "LumiGeek LLC", "InvisionHeart Inc.", "Macnica Inc.", "Jaguar Land Rover Limited", "CoroWare Technologies, Inc", "Simplo Technology Co., LTD", "Omron Healthcare Co., LTD", "Comodule GMBH", "ikeGPS", "Telink Semiconductor Co. Ltd", "Interplan Co., Ltd", "Wyler AG", "IK Multimedia Production srl", "Lukoton Experience Oy", "MTI Ltd", "Tech4home, Lda", "Hiotech AB", "DOTT Limited", "Blue Speck Labs, LLC", "Cisco Systems, Inc", "Mobicomm Inc", "Edamic", "Goodnet, Ltd", "Luster Leaf Products Inc", "<NAME> BV", "Mobiquity Networks Inc", "Praxis Dynamics", "Philip Morris Products S.A.", "Comarch SA", "<NAME> S.A.", "<NAME>", "LifeBEAM Technologies", "Twocanoes Labs, LLC", "Muoverti Limited", "Stamer Musikanlagen GMBH", "Tesla Motors", "Pharynks Corporation", "Lupine", "Siemens AG", "Huami (Shanghai) Culture Communication CO., LTD", "Foster Electric Company, Ltd", "ETA SA", "x-Senso Solutions Kft", "Shenzhen SuLong Communication Ltd", "FengFan (BeiJing) Technology Co, Ltd", "Qrio Inc", "Pitpatpet Ltd", "MSHeli s.r.l.", "Trakm8 Ltd", "JIN CO, Ltd", "Alatech Tehnology", "Beijing CarePulse Electronic Technology Co, Ltd", "Awarepoint", "ViCentra B.V.", "Raven Industries", "WaveWare Technologies Inc.", "Argenox Technologies", "Bragi GmbH", "16Lab Inc", "Masimo Corp", "Iotera Inc", "Endress+Hauser", "ACKme Networks, Inc.", "FiftyThree Inc.", "Parker Hannifin Corp", "Transcranial Ltd", "Uwatec AG", "Orlan LLC", "Blue Clover Devices", "M-Way Solutions GmbH", "Microtronics Engineering GmbH", "Schneider Schreibgerte GmbH", "Sapphire Circuits LLC", "Lumo Bodytech Inc.", "UKC Technosolution", "Xicato Inc.", "Playbrush", "Dai Nippon Printing Co., Ltd.", "G24 Power Limited", "AdBabble Local Commerce Inc.", "Devialet SA", "ALTYOR", "University of Applied Sciences Valais/Haute Ecole Valaisanne", "Five Interactive, LLC dba Zendo", "NetEaseHangzhouNetwork co.Ltd.", "Lexmark International Inc.", "Fluke Corporation", "Yardarm Technologies", "SensaRx", "SECVRE GmbH", "Glacial Ridge Technologies", "Identiv, Inc.", "DDS, Inc.", "SMK Corporation", "Schawbel Technologies LLC", "XMI Systems SA", "Cerevo", "Torrox GmbH & Co KG", "Gemalto", "DEKA Research & Development Corp.", "<NAME>", "Technogym SPA", "FLEURBAEY BVBA", "Aptcode Solutions", "LSI ADL Technology", "Animas Corp", "Alps Electric Co., Ltd.", "OCEASOFT", "Motsai Research", "Geotab", "E.G.O. Elektro-Gertebau GmbH", "bewhere inc", "Johnson Outdoors Inc", "steute Schaltgerate GmbH & Co. KG", "Ekomini inc.", "DEFA AS", "Aseptika Ltd", "HUAWEI Technologies Co., Ltd. ( )", "HabitAware, LLC", "ruwido austria gmbh", "ITEC corporation", "StoneL", "Sonova AG", "Maven Machines, Inc.", "Synapse Electronics", "Standard Innovation Inc.", "RF Code, Inc.", "Wally Ventures S.L.", "Willowbank Electronics Ltd", "SK Telecom", "Jetro AS", "Code Gears LTD", "NANOLINK APS", "IF, LLC", "RF Digital Corp", "Church & Dwight Co., Inc", "Mult<NAME>", "CliniCloud Inc", "SwiftSensors", "Blue Bite", "ELIAS GmbH", "Sivantos GmbH", "Petzl", "storm power ltd", "EISST Ltd", "Inexess Technology Simma KG", "Currant, Inc.", "C2 Development, Inc.", "Blue Sky Scientific, LLC", "ALOTTAZS LABS, LLC", "Kupson spol. s r.o.", "Areus Engineering GmbH", "Impossible Camera GmbH", "InventureTrack Systems", "LockedUp", "Itude", "Pacific Lock Company", "Tendyron Corporation ( )", "<NAME> GmbH", "Illuxtron international B.V.", "miSport Ltd.", "Chargelib", "Doppler Lab", "BBPOS Limited", "RTB Elektronik GmbH & Co. KG", "Rx Networks, Inc.", "WeatherFlow, Inc.", "Technicolor USA Inc.", "Bestechnic(Shanghai),Ltd", "Raden Inc", "<NAME>", "CLABER S.P.A.", "Hyginex, Inc.", "HANSHIN ELECTRIC RAILWAY CO.,LTD.", "Schneider Electric", "Oort Technologies LLC", "Chrono Therapeutics", "Rinnai Corporation", "Swissprime Technologies AG", "Koha.,Co.Ltd", "Genevac Ltd", "Chemtronics", "Seguro Technology Sp. z o.o.", "Redbird Flight Simulations", "Dash Robotics", "LINE Corporation", "Guillemot Corporation", "Techtronic Power Tools Technology Limited", "Wilson Sporting Goods", "Lenovo (Singapore) Pte Ltd. ( )", "Ayatan Sensors", "Electronics Tomorrow Limited", "VASCO Data Security International, Inc.", "PayRange Inc.", "ABOV Semiconductor", "AINA-Wireless Inc.", "Eijkelkamp Soil & Water", "BMA ergonomics b.v.", "Teva Branded Pharmaceutical Products R&D, Inc.", "Anima", "3M", "Empatica Srl", "Afero, Inc.", "Powercast Corporation", "Secuyou ApS", "OMRON Corporation", "Send Solutions", "NIPPON SYSTEMWARE CO.,LTD.", "Neosfar", "Fliegl Agrartechnik GmbH", "Gilvader", "Digi International Inc (R)", "DeWalch Technologies, Inc.", "Flint Rehabilitation Devices, LLC", "Samsung SDS Co., Ltd.", "Blur Product Development", "University of Michigan", "Victron Energy BV", "NTT docomo", "Carmanah Technologies Corp.", "Bytestorm Ltd.", "Espressif Incorporated ( () )", "Unwire", "Connected Yard, Inc.", "American Music Environments", "Sensogram Technologies, Inc.", "Fujitsu Limited", "Ardic Technology", "Delta Systems, Inc", "HTC Corporation", "Citizen Holdings Co., Ltd.", "SMART-INNOVATION.inc", "Blackrat Software", "The Idea Cave, LLC", "GoPro, Inc.", "AuthAir, Inc", "Vensi, Inc.", "Indagem Tech LLC", "Intemo Technologies", "DreamVisions co., Ltd.", "Runteq Oy Ltd", "IMAGINATION TECHNOLOGIES LTD", "CoSTAR TEchnologies", "Clarius Mobile Health Corp.", "Shanghai Frequen Microelectronics Co., Ltd.", "Uwanna, Inc.", "Lierda Science & Technology Group Co., Ltd.", "Silicon Laboratories", "World Moto Inc.", "Giatec Scientific Inc.", "Loop Devices, Inc", "IACA electronique", "Martians Inc", "Swipp ApS", "Life Laboratory Inc.", "FUJI INDUSTRIAL CO.,LTD.", "Surefire, LLC", "Dolby Labs", "Ellisys", "Magnitude Lighting Converters", "Hilti AG", "Devdata S.r.l.", "Deviceworx", "Shortcut Labs", "SGL Italia S.r.l.", "PEEQ DATA", "Ducere Technologies Pvt Ltd", "DiveNav, Inc.", "RIIG AI Sp. z o.o.", "Thermo Fisher Scientific", "AG Measurematics Pvt. Ltd.", "CHUO Electronics CO., LTD.", "Aspenta International", "Eugster Frismag AG", "Amber wireless GmbH", "HQ Inc", "Lab Sensor Solutions", "Enterlab ApS", "Eyefi, Inc.", "MetaSystem S.p.A.", "SONO ELECTRONICS. CO., LTD", "Jewelbots", "Compumedics Limited", "Rotor Bike Components", "Astro, Inc.", "Amotus Solutions", "Healthwear Technologies (Changzhou)Ltd", "Essex Electronics", "Grundfos A/S", "Eargo, Inc.", "Electronic Design Lab", "ESYLUX", "NIPPON SMT.CO.,Ltd", "BM innovations GmbH", "indoormap", "OttoQ Inc", "North Pole Engineering", "3flares Technologies Inc.", "Electrocompaniet A.S.", "Mul-T-Lock", "Corentium AS", "Enlighted Inc", "GISTIC", "AJP2 Holdings, LLC", "COBI GmbH", "Blue Sky Scientific, LLC", "Appception, Inc.", "Courtney Thorne Limited", "Virtuosys", "TPV Technology Limited", "Monitra SA", "Automation Components, Inc.", "Letsense s.r.l.", "Etesian Technologies LLC", "GERTEC BRASIL LTDA.", "Drekker Development Pty. Ltd.", "Whirl Inc", "Locus Positioning", "Acuity Brands Lighting, Inc", "Prevent Biometrics", "Arioneo", "VersaMe", "Vaddio", "Libratone A/S", "HM Electronics, Inc.", "TASER International, Inc.", "SafeTrust Inc.", "Heartland Payment Systems", "Bitstrata Systems Inc.", "Pieps GmbH", "iRiding(Xiamen)Technology Co.,Ltd.", "Alpha Audiotronics, Inc.", "TOPPAN FORMS CO.,LTD.", "Sigma Designs, Inc.", "Spectrum Brands, Inc.", "Polymap Wireless", "MagniWare Ltd.", "Novotec Medical GmbH", "Medicom Innovation Partner a/s", "Matrix Inc.", "Eaton Corporation", "KYS", "Naya Health, Inc.", "Acromag", "Insulet Corporation", "Wellinks Inc.", "ON Semiconductor", "FREELAP SA", "Favero Electronics Srl", "BioMech Sensor LLC", "BOLTT Sports technologies Private limited", "Saphe International", "Metormote AB", "littleBits", "SetPoint Medical", "BRControls Products BV", "Zipcar", "AirBolt Pty Ltd", "KeepTruckin Inc", "Motiv, Inc.", "Wazombi Labs O", "ORBCOMM", "Nixie Labs, Inc.", "AppNearMe Ltd", "Holman Industries", "Expain AS", "Electronic Temperature Instruments Ltd", "Plejd AB", "Propeller Health", "Shenzhen iMCO Electronic Technology Co.,Ltd", "Algoria", "Apption Labs Inc.", "Cronologics Corporation", "MICRODIA Ltd.", "lulabytes S.L.", "Nestec S.A.", "LLC MEGA - F service", "Sharp Corporation", "Precision Outcomes Ltd", "Kronos Incorporated", "OCOSMOS Co., Ltd.", "Embedded Electronic Solutions Ltd. dba e2Solutions", "Aterica Inc.", "BluStor PMC, Inc.", "Kapsch TrafficCom AB", "ActiveBlu Corporation", "Kohler Mira Limited", "Noke", "Appion Inc.", "Resmed Ltd", "Crownstone B.V.", "Xiaomi Inc.", "INFOTECH s.r.o.", "Thingsquare AB", "T&D", "LAVAZZA S.p.A.", "Netclearance Systems, Inc.", "SDATAWAY", "BLOKS GmbH", "LEGO System A/S", "Thetatronics Ltd", "Nikon Corporation", "NeST", "South Silicon Valley Microelectronics", "ALE International", "CareView Communications, Inc.", "SchoolBoard Limited", "Molex Corporation", "IVT Wireless Limited", "Alpine Labs LLC", "Candura Instruments", "SmartMovt Technology Co., Ltd", "Token Zero Ltd", "ACE CAD Enterprise Co., Ltd. (ACECAD)", "Medela, Inc", "AeroScout", "Esrille Inc.", "THINKERLY SRL", "Exon Sp. z o.o.", "Meizu Technology Co., Ltd.", "Smablo LTD", "XiQ", "Allswell Inc.", "Comm-N-Sense Corp DBA Verigo", "VIBRADORM GmbH", "Otodata Wireless Network Inc.", "Propagation Systems Limited", "Midwest Instruments & Controls", "Alpha Nodus, inc.", "petPOMM, Inc", "Mattel", "Airbly Inc.", "A-Safe Limited", "FREDERIQUE CONSTANT SA", "Maxscend Microelectronics Company Limited", "Abbott Diabetes Care", "ASB Bank Ltd", "amadas", "Applied Science, Inc.", "iLumi Solutions Inc.", "Arch Systems Inc.", "Ember Technologies, Inc.", "Snapchat Inc", "Casambi Technologies Oy", "Pico Technology Inc.", "St. Jude Medical, Inc.", "Intricon", "Structural Health Systems, Inc.", "Avvel International", "Gallagher Group", "In2things Automation Pvt. Ltd.", "SYSDEV Srl", "Vonkil Technologies Ltd", "Wynd Technologies, Inc.", "CONTRINEX S.A.", "MIRA, Inc.", "Watteam Ltd", "Density Inc.", "IOT Pot India Private Limited", "Sigma Connectivity AB", "PEG PEREGO SPA", "Wyzelink Systems Inc.", "Yota Devices LTD", "FINSECUR", "Zen-Me Labs Ltd", "3IWare Co., Ltd.", "EnOcean GmbH", "Instabeat, Inc", "Nima Labs", "And<NAME>hl AG & Co. KG", "Nathan Rhoades LLC", "Grob Technologies, LLC", "Actions (Zhuhai) Technology Co., Limited", "SPD Development Company Ltd", "<NAME>", "Qualcomm Life Inc", "Chip-ing AG", "ffly4u", "IoT Instruments Oy", "TRUE Fitness Technology", "Reiner Kartengeraete GmbH & Co. KG.", "SHENZHEN LEMONJOY TECHNOLOGY CO., LTD.", "Hello Inc.", "Evollve Inc.", "Jigowatts Inc.", "BASIC MICRO.COM,INC.", "CUBE TECHNOLOGIES", "foolography GmbH", "CLINK", "Hestan Smart Cooking Inc.", "WindowMaster A/S", "Flowscape AB", "PAL Technologies Ltd", "WHERE, Inc.", "Iton Technology Corp.", "Owl Labs Inc.", "Rockford Corp.", "Becon Technologies Co.,Ltd.", "Vyassoft Technologies Inc", "Nox Medical", "Kimberly-Clark", "Trimble Navigation Ltd.", "Littelfuse", "Withings", "i-developer IT Beratung UG", "", "Sears Holdings Corporation", "Gantner Electronic GmbH", "Authomate Inc", "Vertex International, Inc.", "Airtago", "Swiss Audio SA", "ToGetHome Inc.", "AXIS", "Openmatics", "Jana Care Inc.", "Senix Corporation", "NorthStar Battery Company, LLC", "SKF (U.K.) Limited", "CO-AX Technology, Inc.", "Fender Musical Instruments", "Luidia Inc", "SEFAM", "Wireless Cables Inc", "Lightning Protection International Pty Ltd", "Uber Technologies Inc", "SODA GmbH", "Fatigue Science", "Alpine Electronics Inc.", "Novalogy LTD", "Friday Labs Limited", "OrthoAccel Technologies", "WaterGuru, Inc.", "Benning Elektrotechnik und Elektronik GmbH & Co. KG", "Dell Computer Corporation", "Kopin Corporation", "TecBakery GmbH", "Backbone Labs, Inc.", "DELSEY SA", "Chargifi Limited", "Trainesense Ltd.", "Unify Software and Solutions GmbH & Co. KG", "Husqvarna AB", "Focus fleet and fuel management inc", "SmallLoop, LLC", "Prolon Inc.", "BD Medical", "iMicroMed Incorporated", "Ticto N.V.", "Meshtech AS", "MemCachier Inc.", "<NAME>/S", "SnapStyk Inc.", "Amyway Corporation", "Silk Labs, Inc.", "Pillsy Inc.", "Hatch Baby, Inc.", "Blocks Wearables Ltd.", "Drayson Technologies (Europe) Limited", "eBest IOT Inc.", "Helvar Ltd", "Radiance Technologies", "Nuheara Limited", "Appside co., ltd.", "DeLaval", "Coiler Corporation", "Thermomedics, Inc.", "Tentacle Sync GmbH", "Valencell, Inc.", "iProtoXi Oy", "SECOM CO., LTD.", "Tucker International LLC", "Metanate Limited", "Kobian Canada Inc.", "NETGEAR, Inc.", "Fabtronics Australia Pty Ltd", "Grand Centrix GmbH", "1UP USA.com llc", "SHIMANO INC.", "Nain Inc.", "LifeStyle Lock, LLC", "<NAME>", "Xtrava Inc.", "TTS Tooltechnic Systems AG & Co. KG", "Teenage Engineering AB", "Tunstall Nordic AB", "Svep Design Center AB", "GreenPeak Technologies BV", "Sphinx Electronics GmbH & Co KG", "Atomation", "Nemik Consulting Inc", "RF INNOVATION", "Mini Solution Co., Ltd.", "Lumenetix, Inc", "2048450 Ontario Inc", "SPACEEK LTD", "Delta T Corporation", "Boston Scientific Corporation", "Nuviz, Inc.", "Real Time Automation, Inc.", "Kolibree", "vhf elektronik GmbH", "Bonsai Systems GmbH", "Fathom Systems Inc.", "<NAME>", "International Forte Group LLC", "CycleLabs Solutions inc.", "Codenex Oy", "Kynesim Ltd", "Palago AB", "INSIGMA INC.", "PMD Solutions", "Qingdao Realtime Technology Co., Ltd.", "BE<NAME>-Leuchten KG", "Pambor Ltd." };
10,354
5,169
<filename>Specs/6/e/f/ButtonWheel/0.1.1/ButtonWheel.podspec.json { "name": "ButtonWheel", "version": "0.1.1", "summary": "A wheel shaped object that holds a collection of buttons for iOS", "description": "A wheel shaped object that holds a collection of buttons for iOS", "homepage": "https://github.com/kysomers/ButtonWheel", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/kysomers/ButtonWheel.git", "tag": "0.1.1" }, "platforms": { "ios": "10.0" }, "source_files": "ButtonWheel/ButtonWheel/PodFiles/*.swift", "pushed_with_swift_version": "3.1" }
271
412
<filename>regression/cbmc/null7/main.c<gh_stars>100-1000 #include <stdlib.h> _Bool nondet_bool(); int main() { char *s = NULL; char A[3]; _Bool s_is_set = 0; if(nondet_bool()) { s = A; s_is_set = 1; } if(s_is_set) { unsigned len; __CPROVER_assume(len < 3); s += len; } if(s) *s = 42; return 0; }
184
14,668
<reponame>zealoussnow/chromium // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/public/browser/swap_metrics_driver.h" #include <memory> #include "base/notreached.h" #include "base/time/time.h" namespace content { // static std::unique_ptr<SwapMetricsDriver> SwapMetricsDriver::Create( std::unique_ptr<Delegate> delegate, const base::TimeDelta update_interval) { // TODO(crbug.com/1234304): Implement the driver on Fuchsia. NOTIMPLEMENTED_LOG_ONCE(); return nullptr; } } // namespace content
218
301
/****************************************************************** * * Copyright 2016 Samsung Electronics 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. * ******************************************************************/ #ifndef __GTEST_CUSTOM_H__ #define __GTEST_CUSTOM_H__ //extern void WriteTestingLog(const char* format, ...); #define SET_FAILURE(message) do {\ char buffer[15];\ time_t t = time(0);\ struct tm * now = localtime(&t);\ strftime(buffer, 15, "%I:%M:%S", now);\ ADD_FAILURE_AT(__FILE__, __LINE__) << "[" << buffer << "] " << message; \ }while(0) #endif //__GTEST_CUSTOM_H__
333
479
/** * 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.apache.aurora.scheduler.storage.log; import javax.inject.Singleton; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.inject.AbstractModule; import org.apache.aurora.common.quantity.Time; import org.apache.aurora.scheduler.SchedulerServicesModule; import org.apache.aurora.scheduler.config.types.TimeAmount; import org.apache.aurora.scheduler.storage.SnapshotStore; import org.apache.aurora.scheduler.storage.log.SnapshotService.Settings; /** * Binding for a snapshot store and period snapshotting service. */ public class SnapshotModule extends AbstractModule { @Parameters(separators = "=") public static class Options { @Parameter(names = "-dlog_snapshot_interval", description = "Specifies the frequency at which snapshots of local storage are taken and " + "written to the log.") public TimeAmount snapshotInterval = new TimeAmount(1, Time.HOURS); } private final Options options; public SnapshotModule(Options options) { this.options = options; } @Override protected void configure() { bind(Settings.class).toInstance(new Settings(options.snapshotInterval)); bind(SnapshotStore.class).to(SnapshotService.class); bind(SnapshotService.class).in(Singleton.class); SchedulerServicesModule.addSchedulerActiveServiceBinding(binder()).to(SnapshotService.class); } }
584
2,151
<gh_stars>1000+ // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #include "headless/public/headless_shell.h" #if defined(OS_WIN) #include "content/public/app/sandbox_helper_win.h" #include "sandbox/win/src/sandbox_types.h" #endif int main(int argc, const char** argv) { #if defined(OS_WIN) sandbox::SandboxInterfaceInfo sandbox_info = {0}; content::InitializeSandboxInfo(&sandbox_info); return headless::HeadlessShellMain(0, &sandbox_info); #else return headless::HeadlessShellMain(argc, argv); #endif // defined(OS_WIN) }
236
314
<reponame>NeilsC/prestige<gh_stars>100-1000 import json from http import HTTPStatus from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse APPLICATION_JSON = "application/json" class SignupTests(TestCase): fixtures = ["users.json"] def test_signup_valid(self): response = self.client.post( reverse("signup"), content_type=APPLICATION_JSON, data=json.dumps({ "email": "<EMAIL>", "password": "<PASSWORD>", }) ) self.assertEqual(response.status_code, HTTPStatus.CREATED) self.assertEqual(get_user_model().objects.filter(email="<EMAIL>").count(), 1) def test_signup_duplicate_email(self): response = self.client.post( reverse("signup"), content_type=APPLICATION_JSON, data=json.dumps({ "email": "<EMAIL>", "password": "<PASSWORD>", }) ) self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) self.assertEqual(response.json(), { "error": { "code": "email-duplicate", "message": "This email already has an account.", }, }) def test_signup_duplicate_username(self): response = self.client.post( reverse("signup"), content_type=APPLICATION_JSON, data=json.dumps({ "email": "<EMAIL>", "password": "<PASSWORD>", "username": "u1", }), ) self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) self.assertEqual(response.json(), { "error": { "code": "username-duplicate", "message": "This username already has an account.", }, }) def test_missing_email(self): response = self.client.post( reverse("signup"), content_type=APPLICATION_JSON, data=json.dumps({ "password": "<PASSWORD>", }), ) self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) self.assertEqual(response.json(), { "error": { "message": "Missing/empty email field in body.", }, }) self.assertEqual(get_user_model().objects.filter(email="<EMAIL>").count(), 0) def test_missing_password(self): response = self.client.post( reverse("signup"), content_type=APPLICATION_JSON, data=json.dumps({ "email": "<EMAIL>", }), ) self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) self.assertEqual(response.json(), { "error": { "message": "Missing/empty password field in body.", }, }) self.assertEqual(get_user_model().objects.filter(email="<EMAIL>").count(), 0) def test_missing_username(self): response = self.client.post( reverse("signup"), content_type=APPLICATION_JSON, data=json.dumps({ "email": "<EMAIL>", "password": "<PASSWORD>", }), ) self.assertEqual(response.status_code, HTTPStatus.CREATED) self.assertEqual(response.json(), { 'user': { 'email': '<EMAIL>', 'username': '<EMAIL>', 'isGitHubConnected': False, }, }) self.assertEqual(get_user_model().objects.filter(email="<EMAIL>").count(), 1) def test_empty_username(self): response = self.client.post( reverse("signup"), content_type=APPLICATION_JSON, data=json.dumps({ "email": "<EMAIL>", "password": "<PASSWORD>", "username": "", }), ) self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) self.assertEqual(response.json(), { "error": { "message": "Empty username field in body.", }, }) self.assertEqual(get_user_model().objects.filter(email="<EMAIL>").count(), 0)
1,405
4,339
/* * 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.ignite.internal.commandline.encryption; import java.util.logging.Logger; import org.apache.ignite.internal.client.GridClient; import org.apache.ignite.internal.client.GridClientConfiguration; import org.apache.ignite.internal.commandline.AbstractCommand; import org.apache.ignite.internal.commandline.Command; import org.apache.ignite.internal.commandline.CommandArgIterator; import org.apache.ignite.internal.commandline.CommandLogger; import org.apache.ignite.internal.visor.encryption.VisorCacheGroupEncryptionTaskArg; import org.apache.ignite.internal.visor.encryption.VisorChangeCacheGroupKeyTask; import static org.apache.ignite.internal.commandline.CommandList.ENCRYPTION; import static org.apache.ignite.internal.commandline.TaskExecutor.executeTaskByNameOnNode; import static org.apache.ignite.internal.commandline.encryption.EncryptionSubcommands.CHANGE_CACHE_GROUP_KEY; /** * Change cache group key encryption subcommand. */ public class ChangeCacheGroupKeyCommand extends AbstractCommand<VisorCacheGroupEncryptionTaskArg> { /** Change cache group key task argument. */ private VisorCacheGroupEncryptionTaskArg taskArg; /** {@inheritDoc} */ @Override public Object execute(GridClientConfiguration clientCfg, Logger log) throws Exception { try (GridClient client = Command.startClient(clientCfg)) { executeTaskByNameOnNode( client, VisorChangeCacheGroupKeyTask.class.getName(), taskArg, null, clientCfg ); log.info("The encryption key has been changed for the cache group \"" + taskArg.groupName() + "\"."); return null; } catch (Throwable e) { log.severe("Failed to perform operation."); log.severe(CommandLogger.errorMessage(e)); throw e; } } /** {@inheritDoc} */ @Override public String confirmationPrompt() { return "Warning: the command will change the encryption key of the cache group. Joining a node during " + "the key change process is prohibited and will be rejected."; } /** {@inheritDoc} */ @Override public VisorCacheGroupEncryptionTaskArg arg() { return taskArg; } /** {@inheritDoc} */ @Override public void parseArguments(CommandArgIterator argIter) { String argCacheGrpName = argIter.nextArg("Сache group name is expected."); taskArg = new VisorCacheGroupEncryptionTaskArg(argCacheGrpName); if (argIter.hasNextSubArg()) throw new IllegalArgumentException("Unexpected command argument: " + argIter.peekNextArg()); } /** {@inheritDoc} */ @Override public void printUsage(Logger log) { usage(log, "Change the encryption key of the cache group:", ENCRYPTION, CHANGE_CACHE_GROUP_KEY.toString(), "cacheGroupName"); } /** {@inheritDoc} */ @Override public String name() { return CHANGE_CACHE_GROUP_KEY.text().toUpperCase(); } }
1,305
30,023
<filename>homeassistant/components/broadlink/__init__.py """The Broadlink integration.""" from __future__ import annotations from dataclasses import dataclass, field from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.typing import ConfigType from .const import DOMAIN from .device import BroadlinkDevice from .heartbeat import BroadlinkHeartbeat @dataclass class BroadlinkData: """Class for sharing data within the Broadlink integration.""" devices: dict = field(default_factory=dict) platforms: dict = field(default_factory=dict) heartbeat: BroadlinkHeartbeat | None = None async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Broadlink integration.""" hass.data[DOMAIN] = BroadlinkData() return True async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up a Broadlink device from a config entry.""" data = hass.data[DOMAIN] if data.heartbeat is None: data.heartbeat = BroadlinkHeartbeat(hass) hass.async_create_task(data.heartbeat.async_setup()) device = BroadlinkDevice(hass, entry) return await device.async_setup() async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" data = hass.data[DOMAIN] device = data.devices.pop(entry.entry_id) result = await device.async_unload() if not data.devices: await data.heartbeat.async_unload() data.heartbeat = None return result
525
313
<gh_stars>100-1000 /* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.fit; import java.util.function.Supplier; import com.netflix.titus.common.framework.fit.internal.ActiveFitFramework; import com.netflix.titus.common.framework.fit.internal.DefaultFitRegistry; import com.netflix.titus.common.framework.fit.internal.InactiveFitFramework; import com.netflix.titus.common.framework.fit.internal.action.FitErrorAction; import com.netflix.titus.common.framework.fit.internal.action.FitLatencyAction; import com.netflix.titus.common.util.tuple.Pair; import static java.util.Arrays.asList; /** * Factory methods for the FIT (Failure Injection Testing) framework. */ public abstract class FitFramework { /** * Returns true if FIT framework is activated. */ public abstract boolean isActive(); /** * Returns the default FIT action registry, with the predefined/standard action set. */ public abstract FitRegistry getFitRegistry(); /** * Top level FIT component. */ public abstract FitComponent getRootComponent(); /** * Creates a new, empty FIT component. */ public abstract FitInjection.Builder newFitInjectionBuilder(String id); /** * Creates an interface proxy with methods instrumented using the provided {@link FitInjection} instance: * <ul> * <li> * All methods returning {@link java.util.concurrent.CompletableFuture} are wrapped with * {@link FitInjection#aroundCompletableFuture(String, Supplier)} operator. * </li> * <li> * All methods returning {@link com.google.common.util.concurrent.ListenableFuture} are wrapped with * {@link FitInjection#aroundListenableFuture(String, Supplier)} operator. * </li> * <li> * All methods returning {@link rx.Observable} are wrapped with * {@link FitInjection#aroundObservable(String, Supplier)} operator. * </li> * <li> * All the remaining interface methods are assumed to be blocking, and are wrapped with * {@link FitInjection#beforeImmediate(String)}, and {@link FitInjection#afterImmediate(String)} handlers. * </li> * </ul> */ public abstract <I> I newFitProxy(I interf, FitInjection injection); /** * New active FIT framework. */ public static FitFramework newFitFramework() { return new ActiveFitFramework(newDefaultRegistry()); } /** * New inactive FIT framework. All {@link FitFramework} API methods throw an exception if called, except {@link #isActive()} * method, which can be called to check the activation status. */ public static FitFramework inactiveFitFramework() { return new InactiveFitFramework(); } private static DefaultFitRegistry newDefaultRegistry() { return new DefaultFitRegistry( asList( Pair.of(FitErrorAction.DESCRIPTOR, (id, properties) -> injection -> new FitErrorAction(id, properties, injection)), Pair.of(FitLatencyAction.DESCRIPTOR, (id, properties) -> injection -> new FitLatencyAction(id, properties, injection)) ) ); } }
1,256
11,356
// Copyright <NAME>, 2016-2017. // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/stacktrace/stacktrace_fwd.hpp> #include <boost/stacktrace.hpp> #include <stdexcept> #include <iostream> #include <sstream> #include <boost/core/lightweight_test.hpp> #include <boost/functional/hash.hpp> using boost::stacktrace::stacktrace; using boost::stacktrace::frame; #ifdef BOOST_STACKTRACE_DYN_LINK # define BOOST_ST_API BOOST_SYMBOL_IMPORT #else # define BOOST_ST_API #endif #if (defined(BOOST_GCC) && defined(BOOST_WINDOWS) && !defined(BOOST_STACKTRACE_USE_BACKTRACE) && !defined(BOOST_STACKTRACE_USE_ADDR2LINE)) \ || defined(BOOST_STACKTRACE_TEST_NO_DEBUG_AT_ALL) # define BOOST_STACKTRACE_SYMNAME 0 #else # define BOOST_STACKTRACE_SYMNAME 1 #endif typedef std::pair<stacktrace, stacktrace> (*foo1_t)(int i); BOOST_ST_API std::pair<stacktrace, stacktrace> foo2(int i, foo1_t foo1); BOOST_ST_API stacktrace return_from_nested_namespaces(); BOOST_ST_API boost::stacktrace::stacktrace bar1(); BOOST_ST_API boost::stacktrace::stacktrace bar2(); BOOST_NOINLINE std::pair<stacktrace, stacktrace> foo1(int i) { if (i) { return foo2(i - 1, foo1); } std::pair<stacktrace, stacktrace> ret; try { throw std::logic_error("test"); } catch (const std::logic_error& /*e*/) { ret.second = stacktrace(); return ret; } } void test_deeply_nested_namespaces() { std::stringstream ss; ss << return_from_nested_namespaces(); std::cout << ss.str() << '\n'; #if BOOST_STACKTRACE_SYMNAME BOOST_TEST(ss.str().find("main") != std::string::npos); BOOST_TEST(ss.str().find("get_backtrace_from_nested_namespaces") != std::string::npos || ss.str().find("1# return_from_nested_namespaces") != std::string::npos); // GCC with -O1 has strange inlining, so this line is true while the prev one is false. BOOST_TEST(ss.str().find("return_from_nested_namespaces") != std::string::npos); #endif stacktrace ns1 = return_from_nested_namespaces(); BOOST_TEST(ns1 != return_from_nested_namespaces()); // Different addresses in test_deeply_nested_namespaces() function } // Template parameter Depth is to produce different functions on each Depth. This simplifies debugging when one of the tests catches error template <std::size_t Depth> void test_nested() { std::pair<stacktrace, stacktrace> res = foo2(Depth, foo1); std::stringstream ss1, ss2; ss1 << res.first; ss2 << res.second; std::cout << "'" << ss1.str() << "'\n\n" << ss2.str() << std::endl; BOOST_TEST(!ss1.str().empty()); BOOST_TEST(!ss2.str().empty()); BOOST_TEST(ss1.str().find(" 0# ") != std::string::npos); BOOST_TEST(ss2.str().find(" 0# ") != std::string::npos); BOOST_TEST(ss1.str().find(" 1# ") != std::string::npos); BOOST_TEST(ss2.str().find(" 1# ") != std::string::npos); BOOST_TEST(ss1.str().find(" in ") != std::string::npos); BOOST_TEST(ss2.str().find(" in ") != std::string::npos); #if BOOST_STACKTRACE_SYMNAME BOOST_TEST(ss1.str().find("main") != std::string::npos); BOOST_TEST(ss2.str().find("main") != std::string::npos); BOOST_TEST(ss1.str().find("foo2") != std::string::npos); BOOST_TEST(ss2.str().find("foo2") != std::string::npos); BOOST_TEST(ss1.str().find("foo1") != std::string::npos); BOOST_TEST(ss2.str().find("foo1") != std::string::npos); #endif //BOOST_TEST(false); } template <class Bt> void test_comparisons_base(Bt nst, Bt st) { Bt cst(st); st = st; cst = cst; BOOST_TEST(nst); BOOST_TEST(st); #if !defined(BOOST_MSVC) && !defined(BOOST_STACKTRACE_USE_WINDBG) // This is very dependent on compiler and link flags. No sane way to make it work, because // BOOST_NOINLINE could be ignored by MSVC compiler if link-time optimization is enabled. BOOST_TEST(nst[0] != st[0]); #endif BOOST_TEST(nst != st); BOOST_TEST(st != nst); BOOST_TEST(st == st); BOOST_TEST(nst == nst); BOOST_TEST(nst != cst); BOOST_TEST(cst != nst); BOOST_TEST(cst == st); BOOST_TEST(cst == cst); BOOST_TEST(nst < st || nst > st); BOOST_TEST(st < nst || nst < st); BOOST_TEST(st <= st); BOOST_TEST(nst <= nst); BOOST_TEST(st >= st); BOOST_TEST(nst >= nst); BOOST_TEST(nst < cst || cst < nst); BOOST_TEST(nst > cst || cst > nst); BOOST_TEST(hash_value(nst) == hash_value(nst)); BOOST_TEST(hash_value(cst) == hash_value(st)); BOOST_TEST(hash_value(nst) != hash_value(cst)); BOOST_TEST(hash_value(st) != hash_value(nst)); } void test_comparisons() { stacktrace nst = return_from_nested_namespaces(); stacktrace st; test_comparisons_base(nst, st); } void test_iterators() { stacktrace st; BOOST_TEST(st.begin() == st.begin()); BOOST_TEST(st.cbegin() == st.cbegin()); BOOST_TEST(st.crbegin() == st.crbegin()); BOOST_TEST(st.rbegin() == st.rbegin()); BOOST_TEST(st.begin() + 1 == st.begin() + 1); BOOST_TEST(st.cbegin() + 1 == st.cbegin() + 1); BOOST_TEST(st.crbegin() + 1 == st.crbegin() + 1); BOOST_TEST(st.rbegin() + 1 == st.rbegin() + 1); BOOST_TEST(st.end() == st.end()); BOOST_TEST(st.cend() == st.cend()); BOOST_TEST(st.crend() == st.crend()); BOOST_TEST(st.rend() == st.rend()); BOOST_TEST(st.end() > st.begin()); BOOST_TEST(st.end() > st.cbegin()); BOOST_TEST(st.cend() > st.cbegin()); BOOST_TEST(st.cend() > st.begin()); BOOST_TEST(st.size() == static_cast<std::size_t>(st.end() - st.begin())); BOOST_TEST(st.size() == static_cast<std::size_t>(st.end() - st.cbegin())); BOOST_TEST(st.size() == static_cast<std::size_t>(st.cend() - st.cbegin())); BOOST_TEST(st.size() == static_cast<std::size_t>(st.cend() - st.begin())); BOOST_TEST(st.size() == static_cast<std::size_t>(std::distance(st.rbegin(), st.rend()))); BOOST_TEST(st.size() == static_cast<std::size_t>(std::distance(st.crbegin(), st.rend()))); BOOST_TEST(st.size() == static_cast<std::size_t>(std::distance(st.crbegin(), st.crend()))); BOOST_TEST(st.size() == static_cast<std::size_t>(std::distance(st.rbegin(), st.crend()))); boost::stacktrace::stacktrace::iterator it = st.begin(); ++ it; BOOST_TEST(it == st.begin() + 1); } void test_frame() { stacktrace nst = return_from_nested_namespaces(); stacktrace st; const std::size_t min_size = (nst.size() < st.size() ? nst.size() : st.size()); BOOST_TEST(min_size > 2); for (std::size_t i = 0; i < min_size; ++i) { BOOST_TEST(st[i] == st[i]); BOOST_TEST(st[i].source_file() == st[i].source_file()); BOOST_TEST(st[i].source_line() == st[i].source_line()); BOOST_TEST(st[i] <= st[i]); BOOST_TEST(st[i] >= st[i]); frame fv = nst[i]; BOOST_TEST(fv); if (i > 1 && i < min_size - 3) { // Begin ...and end of the trace may match, skipping BOOST_TEST(st[i] != fv); #if !(defined(BOOST_STACKTRACE_TEST_NO_DEBUG_AT_ALL) && defined(BOOST_MSVC)) // MSVC can not get function name withhout debug symbols even if it is exported BOOST_TEST(st[i].name() != fv.name()); BOOST_TEST(st[i] != fv); BOOST_TEST(st[i] < fv || st[i] > fv); BOOST_TEST(hash_value(st[i]) != hash_value(fv)); #endif if (st[i].source_line()) { BOOST_TEST(st[i].source_file() != fv.source_file() || st[i].source_line() != fv.source_line()); } BOOST_TEST(st[i]); } fv = st[i]; BOOST_TEST(hash_value(st[i]) == hash_value(fv)); } boost::stacktrace::frame empty_frame; BOOST_TEST(!empty_frame); BOOST_TEST(empty_frame.source_file() == ""); BOOST_TEST(empty_frame.name() == ""); BOOST_TEST(empty_frame.source_line() == 0); } // Template parameter bool BySkip is to produce different functions on each BySkip. This simplifies debugging when one of the tests catches error template <bool BySkip> void test_empty_basic_stacktrace() { typedef boost::stacktrace::stacktrace st_t; st_t st = BySkip ? st_t(100500, 1024) : st_t(0, 0); BOOST_TEST(!st); BOOST_TEST(st.empty()); BOOST_TEST(st.size() == 0); BOOST_TEST(st.begin() == st.end()); BOOST_TEST(st.cbegin() == st.end()); BOOST_TEST(st.cbegin() == st.cend()); BOOST_TEST(st.begin() == st.cend()); BOOST_TEST(st.rbegin() == st.rend()); BOOST_TEST(st.crbegin() == st.rend()); BOOST_TEST(st.crbegin() == st.crend()); BOOST_TEST(st.rbegin() == st.crend()); BOOST_TEST(hash_value(st) == hash_value(st_t(0, 0))); BOOST_TEST(st == st_t(0, 0)); BOOST_TEST(!(st < st_t(0, 0))); BOOST_TEST(!(st > st_t(0, 0))); } int main() { test_deeply_nested_namespaces(); test_nested<15>(); test_comparisons(); test_iterators(); test_frame(); test_empty_basic_stacktrace<true>(); test_empty_basic_stacktrace<false>(); BOOST_TEST(&bar1 != &bar2); boost::stacktrace::stacktrace b1 = bar1(); BOOST_TEST(b1.size() == 4); boost::stacktrace::stacktrace b2 = bar2(); BOOST_TEST(b2.size() == 4); test_comparisons_base(bar1(), bar2()); test_nested<300>(); BOOST_TEST(boost::stacktrace::stacktrace(0, 1).size() == 1); BOOST_TEST(boost::stacktrace::stacktrace(1, 1).size() == 1); return boost::report_errors(); }
4,366
333
<reponame>JustinKyleJames/irods #ifndef RS_DATA_OBJ_PHYMV_HPP #define RS_DATA_OBJ_PHYMV_HPP #include "rcConnect.h" #include "dataObjInpOut.h" #include "objInfo.h" int rsDataObjPhymv( rsComm_t *rsComm, dataObjInp_t *dataObjInp, transferStat_t **transferStat ); int _rsDataObjPhymv( rsComm_t *rsComm, dataObjInp_t *dataObjInp, dataObjInfo_t *srcDataObjInfoHead, const char *resc_name, transferStat_t *transStat, int multiCopyFlag ); #endif
184
2,360
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyAenum(PythonPackage): """Advanced Enumerations (compatible with Python's stdlib Enum), NamedTuples, and NamedConstants.""" homepage = "https://github.com/ethanfurman/aenum" pypi = "aenum/aenum-2.1.2.tar.gz" version('2.1.2', sha256='a3208e4b28db3a7b232ff69b934aef2ea1bf27286d9978e1e597d46f490e4687') depends_on('py-setuptools', type='build')
228
2,811
import os import pytest import tox from tox._quickstart import ( ALTERNATIVE_CONFIG_NAME, QUICKSTART_CONF, list_modificator, main, post_process_input, prepare_content, ) ALL_PY_ENVS_AS_STRING = ", ".join(tox.PYTHON.QUICKSTART_PY_ENVS) ALL_PY_ENVS_WO_LAST_AS_STRING = ", ".join(tox.PYTHON.QUICKSTART_PY_ENVS[:-1]) SIGNS_OF_SANITY = ( "tox.readthedocs.io", "[tox]", "[testenv]", "envlist = ", "deps =", "commands =", ) # A bunch of elements to be expected in the generated config as marker for basic sanity class _answers: """Simulate a series of terminal inputs by popping them from a list if called.""" def __init__(self, inputs): self._inputs = [str(i) for i in inputs] def extend(self, items): self._inputs.extend(items) def __str__(self): return "|".join(self._inputs) def __call__(self, prompt): print("prompt: '{}'".format(prompt)) try: answer = self._inputs.pop(0) print("user answer: '{}'".format(answer)) return answer except IndexError: pytest.fail("missing user answer for '{}'".format(prompt)) class _cnf: """Handle files and args for different test scenarios.""" SOME_CONTENT = "dontcare" def __init__(self, exists=False, names=None, pass_path=False): self.original_name = tox.INFO.DEFAULT_CONFIG_NAME self.names = names or [ALTERNATIVE_CONFIG_NAME] self.exists = exists self.pass_path = pass_path def __str__(self): return self.original_name if not self.exists else str(self.names) @property def argv(self): argv = ["tox-quickstart"] if self.pass_path: argv.append(os.getcwd()) return argv @property def dpath(self): return os.getcwd() if self.pass_path else "" def create(self): paths_to_create = {self._original_path} for name in self.names[:-1]: paths_to_create.add(os.path.join(self.dpath, name)) for path in paths_to_create: with open(path, "w") as f: f.write(self.SOME_CONTENT) @property def generated_content(self): return self._alternative_content if self.exists else self._original_content @property def already_existing_content(self): if not self.exists: if os.path.exists(self._alternative_path): pytest.fail("alternative path should never exist here") pytest.fail("checking for already existing content makes not sense here") return self._original_content @property def path_to_generated(self): return os.path.join(os.getcwd(), self.names[-1] if self.exists else self.original_name) @property def _original_path(self): return os.path.join(self.dpath, self.original_name) @property def _alternative_path(self): return os.path.join(self.dpath, self.names[-1]) @property def _original_content(self): with open(self._original_path) as f: return f.read() @property def _alternative_content(self): with open(self._alternative_path) as f: return f.read() class _exp: """Holds test expectations and a user scenario description.""" STANDARD_EPECTATIONS = [ALL_PY_ENVS_AS_STRING, "pytest", "pytest"] def __init__(self, name, exp=None): self.name = name exp = exp or self.STANDARD_EPECTATIONS # NOTE extra mangling here ensures formatting is the same in file and exp map_ = {"deps": list_modificator(exp[1]), "commands": list_modificator(exp[2])} post_process_input(map_) map_["envlist"] = exp[0] self.content = prepare_content(QUICKSTART_CONF.format(**map_)) def __str__(self): return self.name @pytest.mark.usefixtures("work_in_clean_dir") @pytest.mark.parametrize( argnames="answers, exp, cnf", ids=lambda param: str(param), argvalues=( ( _answers([4, "Y", "Y", "Y", "Y", "Y", "N", "pytest", "pytest"]), _exp( "choose versions individually and use pytest", [ALL_PY_ENVS_WO_LAST_AS_STRING, "pytest", "pytest"], ), _cnf(), ), ( _answers([4, "Y", "Y", "Y", "Y", "Y", "N", "py.test", ""]), _exp( "choose versions individually and use old fashioned py.test", [ALL_PY_ENVS_WO_LAST_AS_STRING, "pytest", "py.test"], ), _cnf(), ), ( _answers([1, "pytest", ""]), _exp( "choose current release Python and pytest with defaut deps", [tox.PYTHON.CURRENT_RELEASE_ENV, "pytest", "pytest"], ), _cnf(), ), ( _answers([1, "pytest -n auto", "pytest-xdist"]), _exp( "choose current release Python and pytest with xdist and some args", [tox.PYTHON.CURRENT_RELEASE_ENV, "pytest, pytest-xdist", "pytest -n auto"], ), _cnf(), ), ( _answers([2, "pytest", ""]), _exp( "choose py27, current release Python and pytest with defaut deps", ["py27, {}".format(tox.PYTHON.CURRENT_RELEASE_ENV), "pytest", "pytest"], ), _cnf(), ), ( _answers([3, "pytest", ""]), _exp("choose all supported version and pytest with defaut deps"), _cnf(), ), ( _answers([4, "Y", "Y", "Y", "Y", "Y", "N", "py.test", ""]), _exp( "choose versions individually and use old fashioned py.test", [ALL_PY_ENVS_WO_LAST_AS_STRING, "pytest", "py.test"], ), _cnf(), ), ( _answers([4, "", "", "", "", "", "", "", ""]), _exp("choose no version individually and defaults"), _cnf(), ), ( _answers([4, "Y", "Y", "Y", "Y", "Y", "N", "python -m unittest discover", ""]), _exp( "choose versions individually and use nose with default deps", [ALL_PY_ENVS_WO_LAST_AS_STRING, "", "python -m unittest discover"], ), _cnf(), ), ( _answers([4, "Y", "Y", "Y", "Y", "Y", "N", "nosetests", "nose"]), _exp( "choose versions individually and use nose with default deps", [ALL_PY_ENVS_WO_LAST_AS_STRING, "nose", "nosetests"], ), _cnf(), ), ( _answers([4, "Y", "Y", "Y", "Y", "Y", "N", "trial", ""]), _exp( "choose versions individually and use twisted tests with default deps", [ALL_PY_ENVS_WO_LAST_AS_STRING, "twisted", "trial"], ), _cnf(), ), ( _answers([4, "", "", "", "", "", "", "", ""]), _exp("existing not overridden, generated to alternative with default name"), _cnf(exists=True), ), ( _answers([4, "", "", "", "", "", "", "", ""]), _exp("existing not overridden, generated to alternative with custom name"), _cnf(exists=True, names=["some-other.ini"]), ), ( _answers([4, "", "", "", "", "", "", "", ""]), _exp("existing not override, generated to alternative"), _cnf(exists=True, names=["tox.ini", "some-other.ini"]), ), ( _answers([4, "", "", "", "", "", "", "", ""]), _exp("existing alternatives are not overridden, generated to alternative"), _cnf(exists=True, names=["tox.ini", "setup.py", "some-other.ini"]), ), ), ) def test_quickstart(answers, cnf, exp, monkeypatch): """Test quickstart script using some little helpers. :param _answers answers: user interaction simulation :param _cnf cnf: helper for args and config file paths and contents :param _exp exp: expectation helper """ monkeypatch.setattr("six.moves.input", answers) monkeypatch.setattr("sys.argv", cnf.argv) if cnf.exists: answers.extend(cnf.names) cnf.create() main() print("generated config at {}:\n{}\n".format(cnf.path_to_generated, cnf.generated_content)) check_basic_sanity(cnf.generated_content, SIGNS_OF_SANITY) assert cnf.generated_content == exp.content if cnf.exists: assert cnf.already_existing_content == cnf.SOME_CONTENT def check_basic_sanity(content, signs): for sign in signs: if sign not in content: pytest.fail("{} not in\n{}".format(sign, content))
4,351
3,673
<filename>test/posix/integration/stat/test.py<gh_stars>1000+ #!/usr/bin/env python3 from __future__ import print_function from builtins import str import sys import os from subprocess import call from vmrunner import vmrunner vm = vmrunner.vms[0] num_outputs = 0 def increment(line): global num_outputs num_outputs += 1 print("num_outputs after increment: ", num_outputs) def check_num_outputs(line): assert(num_outputs == 18) vmrunner.vms[0].exit(0, "All tests passed", keep_running = True) vm.on_output("stat\(\) with nullptr buffer fails with EFAULT", increment) vm.on_output("stat\(\) of folder that exists is ok", increment) vm.on_output("stat\(\) of folder that does not exist fails", increment) vm.on_output("stat\(\) of file that does not exist fails", increment) vm.on_output("chdir\(nullptr\) should fail", increment) vm.on_output("chdir\(\"\"\) should fail", increment) vm.on_output("chdir\(\) to a file should fail", increment) vm.on_output("chdir \(absolute\) to folder that exists is ok", increment) vm.on_output("chdir\(\".\"\) is ok", increment) vm.on_output("chdir to subfolder of cwd is ok", increment) vm.on_output("getcwd\(\) with 0-size buffer should fail", increment) vm.on_output("getcwd\(\) with nullptr buffer should fail", increment) vm.on_output("getcwd\(\) with too small buffer should fail", increment) vm.on_output("getcwd\(\) with adequate buffer is ok", increment) vm.on_output("chmod\(\) should fail on read-only memdisk", increment) vm.on_output("fchmod\(\) on non-open FD should fail", increment) vm.on_output("fchmodat\(\) on non-open FD should fail", increment) vm.on_output("nftw\(\) visits a directory before the directory's files", increment) vm.on_output("nftw\(\) visits the directory's files before the directory when FTW_DEPTH is specified", increment) vm.on_output("fstatat\(\) of file that exists is ok", increment) vm.on_output("All done!", check_num_outputs) # Boot the VM, taking a timeout as parameter if len(sys.argv) > 1: vm.boot(20,image_name=str(sys.argv[1])) else: vm.cmake() vm.boot(20,image_name='posix_stat').clean()
715
17,809
<filename>Release/samples/OAuth2Live/pch.h /*** * Copyright (C) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. * ****/ #pragma once #include "App.xaml.h" #include "MainPage.xaml.h" #include <collection.h> #include <cpprest/http_client.h> #include <cpprest/oauth2.h> #include <cpprest/uri.h> #include <ppltasks.h>
147
2,542
/*++ Copyright (c) Microsoft Corporation Module Name: DescTest.c Abstract: KXM Descriptor tests. --*/ #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <sys/ioctl.h> #include <linux/types.h> #include <ctype.h> #include <stdarg.h> #include <malloc.h> #include <errno.h> #include <pthread.h> #include "KUShared.h" #include "KXMApi.h" #define EXIT_ON_ERROR(condition, msg, args...) if((condition)) { printf("[%s@%d]:" msg "\n", __FUNCTION__, __LINE__, ##args); exit(-1);} void dump_usage() { printf("DescriptorTest - Opens specified number of descriptor simultaneously.\n"); printf(" This is to test the KXM dynamic descriptor management layer.\n\n"); printf("DescriptorTest\n"); printf(" -n:<Number of descriptors port to open.>\n"); } void DoDescOpenCloseTest(HANDLE DevFD, int NumFD) { NTSTATUS status; HANDLE *handle; int i; handle = (HANDLE *)malloc(sizeof(HANDLE)*NumFD); EXIT_ON_ERROR(handle == NULL, "Couldn't allocate memory for handle."); printf("Opening %d descriptors..\n", NumFD); for(i=0; i<NumFD; i++) { handle[i] = KXMCreateIoCompletionPort(DevFD, INVALID_HANDLE_VALUE, NULL, 0ULL, 0); EXIT_ON_ERROR(handle[i] == NULL, "Couldn't open descriptor %d", i); } printf("Opened %d descriptors..\n", NumFD); printf("Closing %d descriptors..\n", NumFD); for(i=0; i<NumFD; i++) { KXMCloseIoCompletionPort(DevFD, handle[i]); } printf("Closed %d descriptors..\n", NumFD); printf("Test Passed!\n"); return; } int main(int argc, char *argv[]) { int numCompPorts=(1<<16); //64K ports HANDLE dev_fd = INVALID_HANDLE_VALUE; int option = 0; //Parse parameter. while((option = getopt(argc, argv, "hn:")) != -1) { switch (option) { case 'n': numCompPorts = atoi(optarg); break; case 'h': default: dump_usage(); return 0; } } printf("Running test with numDescOpen %d\n", numCompPorts); //Open device file. dev_fd = KXMOpenDev(); EXIT_ON_ERROR((long)dev_fd <= (long)INVALID_HANDLE_VALUE, "Unable to open device file %s", KXM_DEVICE_FILE); DoDescOpenCloseTest(dev_fd, numCompPorts); KXMCloseDev(dev_fd); printf("TEST COMPLETED SUCCESSFULLY\n"); return 0; }
1,167
2,338
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++03, c++11, c++14, c++17 // template <class T> // constexpr allocator<T>::~allocator(); #include <memory> template <typename T> constexpr bool test() { std::allocator<T> alloc; (void)alloc; // destructor called here return true; } int main(int, char**) { test<int>(); test<void>(); #ifdef _LIBCPP_VERSION // extension test<int const>(); #endif // _LIBCPP_VERSION static_assert(test<int>()); static_assert(test<void>()); #ifdef _LIBCPP_VERSION // extension static_assert(test<int const>()); #endif // _LIBCPP_VERSION return 0; }
322
12,278
#ifndef TEST_OPENCL_HEADER_HH #define TEST_OPENCL_HEADER_HH #include <stdio.h> #define BOOST_UBLAS_ENABLE_OPENCL #include <boost/numeric/ublas/opencl.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <time.h> #include <math.h> namespace ublas = boost::numeric::ublas; namespace opencl = boost::numeric::ublas::opencl; namespace compute = boost::compute; template <class T, class F = ublas::basic_row_major<>> class test_opencl { public: static bool compare(ublas::matrix<T, F>& a, ublas::matrix<T, F>& b) { typedef typename ublas::matrix<T, F>::size_type size_type; if ((a.size1() != b.size1()) || (a.size2() != b.size2())) return false; for (size_type i = 0; i<a.size1(); i++) for (size_type j = 0; j<a.size2(); j++) if (a(i, j) != b(i, j)) { return false; } return true; } static bool compare(ublas::vector<T>& a, ublas::vector<T>& b) { typedef typename ublas::vector<T>::size_type size_type; if (a.size() != b.size()) return false; for (size_type i = 0; i<a.size(); i++) if ((a[i] != b[i])) { return false; } return true; } static void init_matrix(ublas::matrix<T, F>& m, int max_value) { typedef typename ublas::matrix<T, F>::size_type size_type; for (size_type i = 0; i < m.size1(); i++) { for (size_type j = 0; j<m.size2(); j++) m(i, j) = (std::rand() % max_value) + 1; } } static void init_vector(ublas::vector<T>& v, int max_value) { typedef typename ublas::vector<T>::size_type size_type; for (size_type i = 0; i <v.size(); i++) { v[i] = (std::rand() % max_value) + 1; } } virtual void run() { } }; #endif
744
1,088
{ "name": "ivolo/disposable-email-domains", "description": "disposable domains list", "keywords": ["disposable", "domains"], "license": "MIT", "authors": [ { "name": "<NAME>", "email": "<EMAIL>", "role": "Maintainer" } ] }
150
324
<reponame>mortend/fuse-studio #pragma once #include <string> bool acquire_lock(const std::string& lockfilename, std::chrono::seconds timeout);
49
312
/* * Copyright 2020 Rockchip Electronics Co. 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. */ #define MODULE_TAG "hal_h265d_api" #include <stdio.h> #include <string.h> #include "mpp_env.h" #include "mpp_log.h" #include "mpp_mem.h" #include "hal_h265d_ctx.h" #include "hal_h265d_api.h" #include "hal_h265d_rkv.h" #include "hal_h265d_vdpu34x.h" RK_U32 hal_h265d_debug = 0; MPP_RET hal_h265d_init(void *ctx, MppHalCfg *cfg) { MPP_RET ret = MPP_NOK; HalH265dCtx *p = (HalH265dCtx *)ctx; MppClientType client_type = VPU_CLIENT_BUTT; RK_U32 vcodec_type = mpp_get_vcodec_type(); RK_U32 hw_id = 0; if (!(vcodec_type & (HAVE_RKVDEC | HAVE_HEVC_DEC))) { mpp_err_f("Can not found valid H.265 decoder hardware on platform %08x\n", vcodec_type); return ret; } client_type = (vcodec_type & HAVE_HEVC_DEC) ? VPU_CLIENT_HEVC_DEC : VPU_CLIENT_RKVDEC; ret = mpp_dev_init(&cfg->dev, client_type); if (ret) { mpp_err("mpp_dev_init failed ret: %d\n", ret); return ret; } hw_id = mpp_get_client_hw_id(client_type); p->dev = cfg->dev; p->is_v345 = (hw_id == HWID_VDPU345); p->is_v34x = (hw_id == HWID_VDPU34X); p->client_type = client_type; if (hw_id == HWID_VDPU34X) p->api = &hal_h265d_vdpu34x; else p->api = &hal_h265d_rkv; p->slots = cfg->frame_slots; p->dec_cb = cfg->dec_cb; p->fast_mode = cfg->cfg->base.fast_parse; p->packet_slots = cfg->packet_slots; mpp_env_get_u32("hal_h265d_debug", &hal_h265d_debug, 0); ret = p->api->init(ctx, cfg); return ret; } MPP_RET hal_h265d_deinit(void *ctx) { MPP_RET ret = MPP_NOK; HalH265dCtx *p = (HalH265dCtx *)ctx; if (p && p->api && p->api->deinit) ret = p->api->deinit(ctx); if (p->dev) { mpp_dev_deinit(p->dev); p->dev = NULL; } return ret; } MPP_RET hal_h265d_gen_regs(void *ctx, HalTaskInfo *task) { MPP_RET ret = MPP_NOK; HalH265dCtx *p = (HalH265dCtx *)ctx; if (p && p->api && p->api->reg_gen) ret = p->api->reg_gen(ctx, task); return ret; } MPP_RET hal_h265d_start(void *ctx, HalTaskInfo *task) { MPP_RET ret = MPP_NOK; HalH265dCtx *p = (HalH265dCtx *)ctx; if (p && p->api && p->api->start) ret = p->api->start(ctx, task); return ret; } MPP_RET hal_h265d_wait(void *ctx, HalTaskInfo *task) { MPP_RET ret = MPP_NOK; HalH265dCtx *p = (HalH265dCtx *)ctx; if (p && p->api && p->api->wait) ret = p->api->wait(ctx, task); return ret; } MPP_RET hal_h265d_reset(void *ctx) { MPP_RET ret = MPP_NOK; HalH265dCtx *p = (HalH265dCtx *)ctx; if (p && p->api && p->api->reset) ret = p->api->reset(ctx); return ret; } MPP_RET hal_h265d_flush(void *ctx) { MPP_RET ret = MPP_NOK; HalH265dCtx *p = (HalH265dCtx *)ctx; if (p && p->api && p->api->flush) ret = p->api->flush(ctx); return ret; } MPP_RET hal_h265d_control(void *ctx, MpiCmd cmd, void *param) { MPP_RET ret = MPP_OK; HalH265dCtx *p = (HalH265dCtx *)ctx; if (p && p->api && p->api->control) ret = p->api->control(ctx, cmd, param); return ret; } const MppHalApi hal_api_h265d = { .name = "h265d_rkdec", .type = MPP_CTX_DEC, .coding = MPP_VIDEO_CodingHEVC, .ctx_size = sizeof(HalH265dCtx), .flag = 0, .init = hal_h265d_init, .deinit = hal_h265d_deinit, .reg_gen = hal_h265d_gen_regs, .start = hal_h265d_start, .wait = hal_h265d_wait, .reset = hal_h265d_reset, .flush = hal_h265d_flush, .control = hal_h265d_control, };
2,007
977
#include <cstddef> #include <limits> #include <zlib.h> #include <zconf.h> // for zlib #include <realm/sync/noinst/compression.hpp> #include <realm/util/assert.hpp> #include <realm/util/aes_cryptor.hpp> namespace { constexpr std::size_t g_max_stream_avail = (sizeof(uInt) < sizeof(size_t)) ? std::numeric_limits<uInt>::max() : std::numeric_limits<std::size_t>::max(); class ErrorCategoryImpl : public std::error_category { public: const char* name() const noexcept override final { return "realm::_impl::compression::error"; } std::string message(int err) const override final { using error = realm::_impl::compression::error; error e = error(err); switch (e) { case error::out_of_memory: return "Out of memory"; case error::compress_buffer_too_small: return "Compression buffer too small"; case error::compress_error: return "Compression error"; case error::corrupt_input: return "Corrupt input data"; case error::incorrect_decompressed_size: return "Decompressed data size not equal to expected size"; case error::decompress_error: return "Decompression error"; case error::source_file_is_not_readable: return "Source file is not readable"; case error::destination_path_is_not_writable: return "Destination path is not writable"; case error::invalid_input: return "Invalid input"; case error::decryption_error: return "Decryption error"; case error::missing_block_header: return "Missing block header"; case error::invalid_block_size: return "Invalid block size"; } REALM_UNREACHABLE(); } }; ErrorCategoryImpl g_error_category; void* custom_alloc(void* opaque, unsigned int cnt, unsigned int size) { using Alloc = realm::_impl::compression::Alloc; Alloc& alloc = *static_cast<Alloc*>(opaque); std::size_t accum_size = cnt * std::size_t(size); return alloc.alloc(accum_size); } void custom_free(void* opaque, void* addr) { using Alloc = realm::_impl::compression::Alloc; Alloc& alloc = *static_cast<Alloc*>(opaque); return alloc.free(addr); } } // unnamed namespace using namespace realm; using namespace _impl; const std::error_category& compression::error_category() noexcept { return g_error_category; } std::error_code compression::make_error_code(error error_code) noexcept { return std::error_code(int(error_code), g_error_category); } // zlib compression level: 1-9, 1 fastest. // zlib deflateBound() std::error_code compression::compress_bound(const char* uncompressed_buf, std::size_t uncompressed_size, std::size_t& bound, int compression_level) { z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.next_in = reinterpret_cast<unsigned char*>(const_cast<char*>(uncompressed_buf)); strm.avail_in = uInt(uncompressed_size); int rc = deflateInit(&strm, compression_level); if (rc == Z_MEM_ERROR) return error::out_of_memory; if (rc != Z_OK) return error::compress_error; unsigned long zlib_bound = deflateBound(&strm, uLong(uncompressed_size)); rc = deflateEnd(&strm); if (rc != Z_OK) return error::compress_error; bound = zlib_bound; return std::error_code{}; } // zlib deflate() std::error_code compression::compress(const char* uncompressed_buf, std::size_t uncompressed_size, char* compressed_buf, std::size_t compressed_buf_size, std::size_t& compressed_size, int compression_level, Alloc* custom_allocator) { z_stream strm; strm.opaque = Z_NULL; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; if (custom_allocator) { strm.opaque = custom_allocator; strm.zalloc = &custom_alloc; strm.zfree = &custom_free; } int rc = deflateInit(&strm, compression_level); if (rc == Z_MEM_ERROR) return error::out_of_memory; if (rc != Z_OK) return error::compress_error; strm.next_in = reinterpret_cast<unsigned char*>(const_cast<char*>(uncompressed_buf)); strm.avail_in = 0; strm.next_out = reinterpret_cast<unsigned char*>(compressed_buf); strm.avail_out = 0; std::size_t next_in_ndx = 0; std::size_t next_out_ndx = 0; REALM_ASSERT(rc == Z_OK); while (rc == Z_OK || rc == Z_BUF_ERROR) { REALM_ASSERT(const_cast<const char*>(reinterpret_cast<char*>(strm.next_in + strm.avail_in)) == uncompressed_buf + next_in_ndx); REALM_ASSERT(const_cast<const char*>(reinterpret_cast<char*>(strm.next_out + strm.avail_out)) == compressed_buf + next_out_ndx); bool stream_updated = false; if (strm.avail_in == 0 && next_in_ndx < uncompressed_size) { std::size_t in_size = std::min(uncompressed_size - next_in_ndx, g_max_stream_avail); next_in_ndx += in_size; strm.avail_in = uInt(in_size); stream_updated = true; } if (strm.avail_out == 0 && next_out_ndx < compressed_buf_size) { std::size_t out_size = std::min(compressed_buf_size - next_out_ndx, g_max_stream_avail); next_out_ndx += out_size; strm.avail_out = uInt(out_size); stream_updated = true; } if (rc == Z_BUF_ERROR && !stream_updated) { deflateEnd(&strm); return error::compress_buffer_too_small; } int flush = (next_in_ndx == uncompressed_size) ? Z_FINISH : Z_NO_FLUSH; rc = deflate(&strm, flush); REALM_ASSERT(rc != Z_STREAM_END || flush == Z_FINISH); } if (rc != Z_STREAM_END) { deflateEnd(&strm); return error::compress_error; } compressed_size = next_out_ndx - strm.avail_out; rc = deflateEnd(&strm); if (rc != Z_OK) return error::compress_error; return std::error_code{}; } // zlib inflate std::error_code compression::decompress(const char* compressed_buf, std::size_t compressed_size, char* decompressed_buf, std::size_t decompressed_size) { z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; std::size_t next_in_ndx = 0; std::size_t next_out_ndx = 0; strm.next_in = reinterpret_cast<unsigned char*>(const_cast<char*>(compressed_buf)); next_in_ndx = std::min(compressed_size - next_in_ndx, g_max_stream_avail); strm.avail_in = uInt(next_in_ndx); strm.next_out = reinterpret_cast<unsigned char*>(const_cast<char*>(decompressed_buf)); strm.avail_out = 0; int rc = inflateInit(&strm); if (rc != Z_OK) return error::decompress_error; REALM_ASSERT(rc == Z_OK); while (rc == Z_OK || rc == Z_BUF_ERROR) { REALM_ASSERT(const_cast<const char*>(reinterpret_cast<char*>(strm.next_in + strm.avail_in)) == compressed_buf + next_in_ndx); REALM_ASSERT(const_cast<const char*>(reinterpret_cast<char*>(strm.next_out + strm.avail_out)) == decompressed_buf + next_out_ndx); bool stream_updated = false; if (strm.avail_in == 0 && next_in_ndx < compressed_size) { REALM_ASSERT(const_cast<const char*>(reinterpret_cast<char*>(strm.next_in)) == compressed_buf + next_in_ndx); std::size_t in_size = std::min(compressed_size - next_in_ndx, g_max_stream_avail); next_in_ndx += in_size; strm.avail_in = uInt(in_size); stream_updated = true; } if (strm.avail_out == 0 && next_out_ndx < decompressed_size) { REALM_ASSERT(const_cast<const char*>(reinterpret_cast<char*>(strm.next_out)) == decompressed_buf + next_out_ndx); std::size_t out_size = std::min(decompressed_size - next_out_ndx, g_max_stream_avail); next_out_ndx += out_size; strm.avail_out = uInt(out_size); stream_updated = true; } if (rc == Z_BUF_ERROR && !stream_updated) { inflateEnd(&strm); return error::incorrect_decompressed_size; } int flush = (next_in_ndx == compressed_size) ? Z_FINISH : Z_NO_FLUSH; rc = inflate(&strm, flush); REALM_ASSERT(rc != Z_STREAM_END || flush == Z_FINISH); } if (rc != Z_STREAM_END) { inflateEnd(&strm); return error::corrupt_input; } rc = inflateEnd(&strm); if (rc != Z_OK) return error::decompress_error; return std::error_code{}; } std::size_t compression::allocate_and_compress(CompressMemoryArena& compress_memory_arena, BinaryData uncompressed_buf, std::vector<char>& compressed_buf) { const int compression_level = 1; std::size_t compressed_size = 0; compress_memory_arena.reset(); if (compressed_buf.size() < 256) compressed_buf.resize(256); // Throws for (;;) { std::error_code ec = compression::compress(uncompressed_buf.data(), uncompressed_buf.size(), compressed_buf.data(), compressed_buf.size(), compressed_size, compression_level, &compress_memory_arena); if (REALM_UNLIKELY(ec)) { if (ec == compression::error::compress_buffer_too_small) { std::size_t n = compressed_buf.size(); REALM_ASSERT(n != std::numeric_limits<std::size_t>::max()); if (util::int_multiply_with_overflow_detect(n, 2)) n = std::numeric_limits<std::size_t>::max(); compressed_buf.resize(n); // Throws continue; } if (ec == compression::error::out_of_memory) { std::size_t n = compress_memory_arena.size(); if (n == 0) { // About 256KiB according to ZLIB documentation (about // 1MiB in reality, strangely) n = 256 * 1024; } else { REALM_ASSERT(n != std::numeric_limits<std::size_t>::max()); if (util::int_multiply_with_overflow_detect(n, 2)) n = std::numeric_limits<std::size_t>::max(); } compress_memory_arena.resize(n); // Throws continue; } throw std::system_error(ec); } break; } return compressed_size; } namespace { std::error_code do_compress_file(const std::string& src_path, const std::string& dst_path, util::File::SizeType& src_size, util::File::SizeType& dst_size, std::size_t memory_usage) { util::File src_file; try { src_file.open(src_path); } catch (util::File::AccessError&) { return compression::error::source_file_is_not_readable; } src_size = src_file.get_size(); util::File dst_file; try { dst_file.open(dst_path, util::File::mode_Write); } catch (util::File::AccessError&) { return compression::error::destination_path_is_not_writable; } z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.data_type = Z_BINARY; int compression_level = Z_DEFAULT_COMPRESSION; int rc = deflateInit(&strm, compression_level); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; if (rc != Z_OK) return compression::error::compress_error; const std::size_t buf_size = memory_usage; std::unique_ptr<char[]> in_buf = std::make_unique<char[]>(buf_size); std::unique_ptr<char[]> out_buf = std::make_unique<char[]>(buf_size); bool eof = false; strm.avail_in = 0; strm.next_out = reinterpret_cast<Bytef*>(out_buf.get()); strm.avail_out = uInt(buf_size); while (rc != Z_STREAM_END) { if (strm.avail_in == 0 && !eof) { std::size_t nread = src_file.read(in_buf.get(), buf_size); if (nread < buf_size) eof = true; strm.next_in = reinterpret_cast<Bytef*>(in_buf.get()); strm.avail_in = uInt(nread); } int flush = eof ? Z_FINISH : Z_NO_FLUSH; rc = deflate(&strm, flush); if (rc != Z_OK && rc != Z_BUF_ERROR && rc != Z_STREAM_END) { deflateEnd(&strm); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; return compression::error::compress_error; } REALM_ASSERT(rc != Z_STREAM_END || flush == Z_FINISH); if (strm.avail_out == 0 || rc == Z_STREAM_END) { std::size_t nwrite = buf_size - strm.avail_out; dst_file.write(out_buf.get(), nwrite); strm.next_out = reinterpret_cast<Bytef*>(out_buf.get()); strm.avail_out = uInt(buf_size); } } REALM_ASSERT(eof && strm.avail_in == 0 && strm.avail_out == buf_size); rc = deflateEnd(&strm); if (rc != Z_OK) return compression::error::compress_error; dst_size = dst_file.get_size(); return std::error_code{}; } std::error_code do_decompress_file(const std::string& src_path, const std::string& dst_path, util::File::SizeType& src_size, util::File::SizeType& dst_size, std::size_t memory_usage) { util::File src_file; try { src_file.open(src_path); } catch (util::File::AccessError&) { return compression::error::source_file_is_not_readable; } src_size = src_file.get_size(); util::File dst_file; try { dst_file.open(dst_path, util::File::mode_Write); } catch (util::File::AccessError&) { return compression::error::destination_path_is_not_writable; } z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.data_type = Z_BINARY; int rc = inflateInit(&strm); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; if (rc != Z_OK) return compression::error::decompress_error; std::size_t buf_size = memory_usage; std::unique_ptr<char[]> in_buf = std::make_unique<char[]>(buf_size); std::unique_ptr<char[]> out_buf = std::make_unique<char[]>(buf_size); bool eof = false; strm.avail_in = 0; strm.next_out = reinterpret_cast<Bytef*>(out_buf.get()); strm.avail_out = uInt(buf_size); while (rc != Z_STREAM_END) { if (strm.avail_in == 0 && !eof) { std::size_t nread = src_file.read(in_buf.get(), buf_size); if (nread < buf_size) eof = true; strm.next_in = reinterpret_cast<Bytef*>(in_buf.get()); strm.avail_in = uInt(nread); } int flush = eof ? Z_FINISH : Z_NO_FLUSH; rc = inflate(&strm, flush); if (rc != Z_OK && rc != Z_BUF_ERROR && rc != Z_STREAM_END) { inflateEnd(&strm); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; return compression::error::corrupt_input; } REALM_ASSERT(rc != Z_STREAM_END || flush == Z_FINISH); if (strm.avail_out == 0 || rc == Z_STREAM_END) { std::size_t nwrite = buf_size - strm.avail_out; dst_file.write(out_buf.get(), nwrite); strm.next_out = reinterpret_cast<Bytef*>(out_buf.get()); strm.avail_out = uInt(buf_size); } } REALM_ASSERT(eof && strm.avail_in == 0 && strm.avail_out == buf_size); rc = inflateEnd(&strm); if (rc != Z_OK) return compression::error::decompress_error; dst_size = dst_file.get_size(); return std::error_code{}; } } // namespace std::error_code compression::compress_file(const std::string& src_path, const std::string& dst_path, util::File::SizeType& src_size, util::File::SizeType& dst_size) { std::size_t memory_usage = 1 << 20; std::error_code ec = do_compress_file(src_path, dst_path, src_size, dst_size, memory_usage); return ec; } std::error_code compression::decompress_file(const std::string& src_path, const std::string& dst_path, util::File::SizeType& src_size, util::File::SizeType& dst_size) { std::size_t memory_usage = 1 << 20; std::error_code ec = do_decompress_file(src_path, dst_path, src_size, dst_size, memory_usage); return ec; } std::error_code compression::compress_block_with_header(const char* uncompressed_buf, std::size_t uncompressed_size, char* compressed_buf, std::size_t compressed_buf_size, std::size_t& compressed_size) { _impl::compression::CompressMemoryArena allocator; // The allocator supplied to zlib allocates at most 8 MB. Observations show // that zlib asks for less than 300 KB. There is no reason that 8 MB should // not be enough to compress 256 KB. We return with an out of memory error // if this is not enough, instead of allocating more memory. const std::size_t memory_usage = 1 << 23; allocator.resize(memory_usage); z_stream strm; strm.zalloc = &custom_alloc; strm.zfree = &custom_free; strm.opaque = &allocator; strm.data_type = Z_BINARY; int compression_level = Z_DEFAULT_COMPRESSION; int rc = deflateInit(&strm, compression_level); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; if (rc != Z_OK) return compression::error::compress_error; strm.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(uncompressed_buf)); strm.avail_in = uInt(uncompressed_size); // Make space for the 4 byte prefix. strm.next_out = reinterpret_cast<Bytef*>(compressed_buf + 4); REALM_ASSERT(compressed_buf_size > 4); strm.avail_out = uInt(compressed_buf_size - 4); int flush = Z_FINISH; rc = deflate(&strm, flush); if (rc != Z_STREAM_END) { deflateEnd(&strm); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; return compression::error::compress_error; } std::size_t compressed_size_without_header = compressed_buf_size - 4 - strm.avail_out; deflateEnd(&strm); // Make prefix std::size_t prefix = compressed_size_without_header; for (int i = 3; i >= 0; --i) { compressed_buf[i] = static_cast<unsigned char>(prefix & 255); prefix >>= 8; } // compressed_size includes the 4 byte header. compressed_size = compressed_size_without_header + 4; return std::error_code{}; } std::error_code compression::integrate_compressed_blocks_in_realm_file( const char* blocks, std::size_t blocks_size, const std::string& dst_path, const util::Optional<std::array<char, 64>>& encryption_key, std::uint_fast64_t& dst_size) { #if REALM_ENABLE_ENCRYPTION std::unique_ptr<util::AESCryptor> aes_cryptor; if (encryption_key) aes_cryptor.reset( new util::AESCryptor(reinterpret_cast<unsigned char*>(const_cast<char*>(encryption_key->data())))); #else REALM_ASSERT(!encryption_key); #endif // A decompressed block is guaranteed to have size below 256 KB. const std::size_t buf_size = 1 << 18; std::unique_ptr<char[]> buf{new char[buf_size]}; util::File file; { bool was_created; file.open(dst_path, was_created); file.seek(file.get_size()); } #if REALM_ENABLE_ENCRYPTION const std::size_t encryption_block_size = 4096; const std::size_t blocks_per_metadata_block = 64; std::uint_fast64_t decrypted_file_size = 0; if (encryption_key) { std::uint_fast64_t file_size = file.get_size(); REALM_ASSERT(file_size % encryption_block_size == 0); std::uint_fast64_t number_of_metadata_blocks = (file_size / encryption_block_size + blocks_per_metadata_block) / (blocks_per_metadata_block + 1); decrypted_file_size = file_size - number_of_metadata_blocks * encryption_block_size; } #endif z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.data_type = Z_BINARY; int rc = inflateInit(&strm); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; if (rc != Z_OK) return compression::error::decompress_error; std::size_t ndx = 0; while (ndx < blocks_size) { if (ndx + 4 > blocks_size) { inflateEnd(&strm); return error::missing_block_header; } uInt block_size = 0; for (int i = 0; i < 4; ++i) { block_size <<= 8; block_size += std::uint8_t(blocks[ndx]); ndx++; } if (ndx + block_size > blocks_size) { inflateEnd(&strm); return error::invalid_block_size; } inflateReset(&strm); strm.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(blocks + ndx)); strm.avail_in = uInt(block_size); strm.next_out = reinterpret_cast<Bytef*>(buf.get()); strm.avail_out = buf_size; int flush = Z_FINISH; rc = inflate(&strm, flush); if (rc != Z_STREAM_END) { inflateEnd(&strm); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; return compression::error::corrupt_input; } std::size_t decompressed_size = buf_size - strm.avail_out; #if REALM_ENABLE_ENCRYPTION if (encryption_key) { REALM_ASSERT(aes_cryptor); std::size_t next_decrypted_file_size = std::size_t(decrypted_file_size + decompressed_size); aes_cryptor->set_file_size(off_t(next_decrypted_file_size)); aes_cryptor->write(file.get_descriptor(), off_t(decrypted_file_size), buf.get(), decompressed_size); decrypted_file_size = next_decrypted_file_size; } #endif if (!encryption_key) { file.write(buf.get(), decompressed_size); } ndx += block_size; } inflateEnd(&strm); dst_size = file.get_size(); return std::error_code{}; } std::error_code compression::compress_file_in_blocks(const char* src_path, const char* dst_path, size_t& src_size, size_t& dst_size) { util::File src_file; try { src_file.open(src_path); } catch (util::File::AccessError&) { return compression::error::source_file_is_not_readable; } src_size = size_t(src_file.get_size()); util::File dst_file; try { dst_file.open(dst_path, util::File::mode_Write); } catch (util::File::AccessError&) { return compression::error::destination_path_is_not_writable; } _impl::compression::CompressMemoryArena allocator; // The allocator supplied to zlib allocates at most 8 MB. Observations show // that zlib asks for less than 300 KB. There is no reason that 8 MB should // not be enough to compress 256 KB. We return with an out of memory error // if this is not enough, instead of allocating more memory. const std::size_t memory_usage = 1 << 23; allocator.resize(memory_usage); const std::size_t in_buf_size = 1 << 18; // 256 KB std::unique_ptr<char[]> in_buf = std::make_unique<char[]>(in_buf_size); const std::size_t out_buf_size = 1 << 20; // 1 MB std::unique_ptr<char[]> out_buf = std::make_unique<char[]>(out_buf_size); z_stream strm; strm.zalloc = &custom_alloc; strm.zfree = &custom_free; strm.opaque = &allocator; strm.data_type = Z_BINARY; int compression_level = Z_DEFAULT_COMPRESSION; int rc = deflateInit(&strm, compression_level); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; if (rc != Z_OK) return compression::error::compress_error; bool eof = false; while (!eof) { rc = deflateReset(&strm); if (rc != Z_OK) return compression::error::compress_error; std::size_t nread = src_file.read(in_buf.get(), in_buf_size); if (nread < in_buf_size) eof = true; if (nread == 0) { rc = deflateEnd(&strm); if (rc != Z_OK) return compression::error::compress_error; break; } strm.next_in = reinterpret_cast<Bytef*>(in_buf.get()); strm.avail_in = uInt(nread); // Make space for the 4 byte prefix. strm.next_out = reinterpret_cast<Bytef*>(out_buf.get() + 4); strm.avail_out = out_buf_size - 4; int flush = Z_FINISH; rc = deflate(&strm, flush); if (rc != Z_STREAM_END) { deflateEnd(&strm); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; return compression::error::compress_error; } std::size_t compressed_size = out_buf_size - 4 - strm.avail_out; // Make prefix std::size_t prefix = compressed_size; for (int i = 3; i >= 0; --i) { out_buf[i] = static_cast<unsigned char>(prefix & 255); prefix >>= 8; } dst_file.write(out_buf.get(), compressed_size + 4); } REALM_ASSERT(eof); deflateEnd(&strm); dst_size = size_t(dst_file.get_size()); return std::error_code{}; } std::error_code compression::decompress_file_from_blocks(const char* src_path, const char* dst_path, util::File::SizeType& src_size, util::File::SizeType& dst_size) { util::File src_file; try { src_file.open(src_path); } catch (util::File::AccessError&) { return compression::error::source_file_is_not_readable; } src_size = src_file.get_size(); util::File dst_file; try { dst_file.open(dst_path, util::File::mode_Write); } catch (util::File::AccessError&) { return compression::error::destination_path_is_not_writable; } _impl::compression::CompressMemoryArena allocator; // The allocator supplied to zlib allocates at most 8 MB. Observations show // that zlib asks for less than 300 KB. There is no reason that 8 MB should // not be enough to compress 256 KB. We return with an out of memory error // if this is not enough, instead of allocating more memory. const std::size_t memory_usage = 1 << 23; allocator.resize(memory_usage); unsigned char prefix[4]; const std::size_t in_buf_size = 1 << 20; std::unique_ptr<char[]> in_buf = std::make_unique<char[]>(in_buf_size); const std::size_t out_buf_size = 1 << 18; std::unique_ptr<char[]> out_buf = std::make_unique<char[]>(out_buf_size); z_stream strm; strm.zalloc = &custom_alloc; strm.zfree = &custom_free; strm.opaque = &allocator; strm.data_type = Z_BINARY; int rc = inflateInit(&strm); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; if (rc != Z_OK) return compression::error::decompress_error; while (true) { inflateReset(&strm); std::size_t nread = src_file.read(reinterpret_cast<char*>(prefix), 4); if (nread == 0) { inflateEnd(&strm); break; } if (nread < 4) { inflateEnd(&strm); return compression::error::corrupt_input; } uInt block_size = 0; for (int i = 0; i < 4; ++i) { block_size <<= 8; block_size += std::uint8_t(prefix[i]); } if (block_size > in_buf_size) { inflateEnd(&strm); return compression::error::corrupt_input; } nread = src_file.read(in_buf.get(), block_size); if (nread < block_size) { inflateEnd(&strm); return compression::error::corrupt_input; } strm.next_in = reinterpret_cast<Bytef*>(in_buf.get()); strm.avail_in = uInt(nread); // Make space for the 4 byte prefix. strm.next_out = reinterpret_cast<Bytef*>(out_buf.get()); strm.avail_out = out_buf_size; int flush = Z_FINISH; rc = inflate(&strm, flush); if (rc != Z_STREAM_END) { inflateEnd(&strm); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; return compression::error::corrupt_input; } std::size_t decompressed_size = out_buf_size - strm.avail_out; dst_file.write(out_buf.get(), decompressed_size); } inflateEnd(&strm); dst_size = dst_file.get_size(); return std::error_code{}; } std::error_code compression::decompress_block(const char* compressed_buf, std::size_t compressed_size, char* decompressed_buf, std::size_t& decompressed_size) { z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.data_type = Z_BINARY; int rc = inflateInit(&strm); if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; if (rc != Z_OK) return compression::error::decompress_error; REALM_ASSERT_RELEASE(compressed_size <= std::numeric_limits<uInt>::max()); strm.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(compressed_buf)); strm.avail_in = uInt(compressed_size); // Guaranteed by caller. const std::size_t out_buf_size = 1 << 18; strm.next_out = reinterpret_cast<Bytef*>(decompressed_buf); strm.avail_out = out_buf_size; int flush = Z_FINISH; rc = inflate(&strm, flush); inflateEnd(&strm); if (rc != Z_STREAM_END) { if (rc == Z_MEM_ERROR) return compression::error::out_of_memory; return compression::error::corrupt_input; } decompressed_size = out_buf_size - strm.avail_out; return std::error_code{}; } std::error_code compression::extract_blocks_from_file(const std::string& path, const util::Optional<std::array<char, 64>>& encryption_key, std::uint_fast64_t current_offset, std::uint_fast64_t& next_offset, std::uint_fast64_t& max_offset, char* buf, std::size_t buf_size, std::size_t& blocks_size) { if (encryption_key) { #if REALM_ENABLE_ENCRYPTION return extract_blocks_from_encrypted_realm(path, *encryption_key, current_offset, next_offset, max_offset, buf, buf_size, blocks_size); #endif } else { return extract_blocks_from_unencrypted_block_file(path, current_offset, next_offset, max_offset, buf, buf_size, blocks_size); } } std::error_code compression::extract_blocks_from_unencrypted_block_file( const std::string& path, std::uint_fast64_t current_offset, std::uint_fast64_t& next_offset, std::uint_fast64_t& max_offset, char* buf, std::size_t buf_size, std::size_t& blocks_size) { util::File file; try { file.open(path); } catch (util::File::AccessError&) { return compression::error::source_file_is_not_readable; } std::uint_fast64_t file_size = std::uint_fast64_t(file.get_size()); max_offset = file_size; if (current_offset > max_offset) return error::invalid_input; if (current_offset == max_offset) { next_offset = max_offset; blocks_size = 0; return std::error_code{}; } file.seek(current_offset); std::size_t blocks_size_2 = 0; while (current_offset + blocks_size_2 + 4 <= max_offset) { unsigned char prefix[4]; std::size_t nread = file.read(reinterpret_cast<char*>(prefix), 4); REALM_ASSERT(nread == 4); std::size_t block_size = 0; for (int i = 0; i < 4; ++i) { block_size <<= 8; block_size += std::size_t(prefix[i]); } if (current_offset + blocks_size_2 + 4 + block_size > max_offset) return error::corrupt_input; if (blocks_size_2 + 4 + block_size > buf_size) break; std::memcpy(buf + blocks_size_2, prefix, 4); nread = file.read(buf + blocks_size_2 + 4, block_size); REALM_ASSERT(nread == block_size); blocks_size_2 += 4 + block_size; } blocks_size = blocks_size_2; next_offset = current_offset + blocks_size_2; return std::error_code{}; } #if REALM_ENABLE_ENCRYPTION std::error_code compression::extract_blocks_from_encrypted_realm(const std::string& path, const std::array<char, 64>& encryption_key, std::uint_fast64_t current_offset, std::uint_fast64_t& next_offset, std::uint_fast64_t& max_offset, char* buf, std::size_t buf_size, std::size_t& blocks_size) { // More blocks will only be compressed as long as the buffer has more space // than threshold_buf_size left. const std::size_t threshold_buf_size = (1 << 19); REALM_ASSERT(buf_size >= threshold_buf_size); util::File file; try { file.open(path); } catch (util::File::AccessError&) { return compression::error::source_file_is_not_readable; } std::uint_fast64_t file_size = std::uint_fast64_t(file.get_size()); // Constants from the encryption format. const std::size_t encryption_block_size = 4096; const std::size_t blocks_per_metadata_block = 64; REALM_ASSERT(file_size % encryption_block_size == 0); bool file_ends_with_metadata_block = (file_size / encryption_block_size) % (blocks_per_metadata_block + 1) == 1; // Ignore a final useless metadata block. std::uint_fast64_t effective_file_size = file_size - (file_ends_with_metadata_block ? encryption_block_size : 0); const std::uint_fast64_t number_of_metadata_blocks = (effective_file_size / encryption_block_size + blocks_per_metadata_block) / (blocks_per_metadata_block + 1); REALM_ASSERT(number_of_metadata_blocks > 0); // The offset is a position in the encrypted Realm. The offset is always placed at the // beginning of a metadata block, except for max_offset. max_offset is the effective file // size. max_offset = effective_file_size; if (current_offset > max_offset) return error::invalid_input; if (current_offset == max_offset) { next_offset = max_offset; blocks_size = 0; return std::error_code{}; } if (current_offset % (encryption_block_size * (blocks_per_metadata_block + 1)) != 0) return compression::error::invalid_input; const std::uint_fast64_t decrypted_src_size = effective_file_size - number_of_metadata_blocks * encryption_block_size; util::AESCryptor aes_cryptor{reinterpret_cast<const unsigned char*>(encryption_key.data())}; aes_cryptor.set_file_size(off_t(decrypted_src_size)); const std::size_t unencrypted_buf_size = blocks_per_metadata_block * encryption_block_size; std::unique_ptr<char[]> unencrypted_buf{new char[unencrypted_buf_size]}; std::size_t buf_pos = 0; std::uint_fast64_t offset = current_offset; while (offset < max_offset && (buf_size - buf_pos) >= threshold_buf_size) { std::uint_fast64_t decrypted_offset = (offset / (blocks_per_metadata_block + 1)) * blocks_per_metadata_block; REALM_ASSERT(decrypted_offset < decrypted_src_size); std::size_t size_to_read = std::size_t(std::min(std::uint_fast64_t(blocks_per_metadata_block * encryption_block_size), decrypted_src_size - decrypted_offset)); REALM_ASSERT(size_to_read % encryption_block_size == 0); REALM_ASSERT(decrypted_src_size % encryption_block_size == 0); REALM_ASSERT(decrypted_offset % encryption_block_size == 0); // We loop over all individual encryption blocks because aes_cryptor.read() returns false // for uninitialized blocks. Those blocks are not used by any Realm data structures but they // must be included in the file as well. for (std::size_t pos = 0; pos < size_to_read; pos += encryption_block_size) { bool success = aes_cryptor.read(file.get_descriptor(), off_t(decrypted_offset + pos), unencrypted_buf.get() + pos, encryption_block_size); if (!success) { // zero out the content. std::memset(unencrypted_buf.get() + pos, 0, encryption_block_size); } // The logic here is strange, because we capture uninitialized blocks, but blocks that // fail authentication are accepted. We rely on the server's files not being tampered with. // The consequence of an unauthenticated Realm is that the client will end up with // zero blocks. This is acceptable, but not ideal. The situation could be remedied by // introducing a slightly different read function than aes_cryptor.read. } std::size_t compressed_size_3; std::error_code ec = compress_block_with_header(unencrypted_buf.get(), size_to_read, buf + buf_pos, buf_size - buf_pos, compressed_size_3); if (ec) return ec; REALM_ASSERT(buf_pos + compressed_size_3 <= buf_size); buf_pos += compressed_size_3; offset += size_to_read + encryption_block_size; } blocks_size = buf_pos; next_offset = offset; REALM_ASSERT(next_offset > current_offset); REALM_ASSERT(next_offset <= max_offset); return std::error_code{}; } #endif
17,953
411
<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.giraph.comm.aggregators; import java.util.AbstractMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import org.apache.giraph.reducers.ReduceOperation; import org.apache.giraph.reducers.Reducer; import org.apache.giraph.utils.TaskIdsPermitsBarrier; import org.apache.hadoop.io.Writable; import org.apache.hadoop.util.Progressable; import org.apache.log4j.Logger; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; /** * Class for holding aggregators which current worker owns, * and aggregating partial aggregator values from workers. * * Protocol: * 1. Before the beginning of superstep, worker receives its aggregators * from master, and these aggregators will be registered to this class. * Multiple registrations can be called concurrently. * 2. During the superstep, whenever a worker finishes computation, * it will send partial aggregated values to worker owner. This class is used * to help deserialize the arriving aggregator values, and aggregate the values * at the destination owner worker; these can happen concurrently. * (we know step 1. is finished before anything from step 2. happens because * other workers can't start computation before they receive aggregators * which this worker owns) * 3. This class also tracks the number of partial aggregator requests which * worker received. In the end of superstep, getMyAggregatorValuesWhenReady * will be called to ensure everything was received and get the values which * need to be sent to master. * Because of this counting, in step 2. even if worker owns no aggregators, * it will still send a message without aggregator data. * 4. In the end we reset to prepare for the next superstep. */ public class OwnerAggregatorServerData { /** Class logger */ private static final Logger LOG = Logger.getLogger(OwnerAggregatorServerData.class); /** Map of aggregators which current worker owns */ private final ConcurrentMap<String, Reducer<Object, Writable>> myReducerMap = Maps.newConcurrentMap(); /** * Counts the requests with partial aggregated values from other workers. * It uses GlobalCommType.SPECIAL_COUNT to know how many requests it * has to receive. */ private final TaskIdsPermitsBarrier workersBarrier; /** Progressable used to report progress */ private final Progressable progressable; /** * Constructor * * @param progressable Progressable used to report progress */ public OwnerAggregatorServerData(Progressable progressable) { this.progressable = progressable; workersBarrier = new TaskIdsPermitsBarrier(progressable); } /** * Register a reducer which current worker owns. Thread-safe. * * @param name Name of aggregator * @param reduceOp Reduce operation */ public void registerReducer(String name, ReduceOperation<Object, Writable> reduceOp) { if (LOG.isDebugEnabled() && myReducerMap.isEmpty()) { LOG.debug("registerAggregator: The first registration after a reset()"); } myReducerMap.putIfAbsent(name, new Reducer<>(reduceOp)); progressable.progress(); } /** * Reduce partial value of one of current worker's reducers. * * Thread-safe. Call only after reducers have been registered. * * @param name Name of the reducer * @param value Value to reduce to it */ public void reduce(String name, Writable value) { Reducer<Object, Writable> reducer = myReducerMap.get(name); synchronized (reducer) { reducer.reduceMerge(value); } progressable.progress(); } /** * Create initial value for a reducer. Used so requests * would be able to deserialize data. * * Thread-safe. Call only after reducer has been registered. * * @param name Name of the reducer * @return Empty value */ public Writable createInitialValue(String name) { Reducer<Object, Writable> reducer = myReducerMap.get(name); synchronized (reducer) { return reducer.createInitialValue(); } } /** * Notify this object that a partial aggregated values request from some * worker have been received. Thread-safe. */ public void receivedRequestFromWorker() { workersBarrier.releaseOnePermit(); } /** * Notify this object about the total number of requests which should * arrive from one of the workers. Thread-safe. * * @param requestCount Number of requests which should arrive * @param taskId Task id of that worker */ public void receivedRequestCountFromWorker(long requestCount, int taskId) { workersBarrier.requirePermits(requestCount, taskId); } /** * This function will wait until all partial aggregated values from all * workers are ready and aggregated, and return final aggregated values * afterwards. * * @param workerIds All workers in the job apart from the current one * @return Iterable through final aggregated values which this worker owns */ public Iterable<Map.Entry<String, Writable>> getMyReducedValuesWhenReady(Set<Integer> workerIds) { workersBarrier.waitForRequiredPermits(workerIds); if (LOG.isDebugEnabled()) { LOG.debug("getMyAggregatorValuesWhenReady: Values ready"); } return Iterables.transform(myReducerMap.entrySet(), new Function<Map.Entry<String, Reducer<Object, Writable>>, Map.Entry<String, Writable>>() { @Override public Map.Entry<String, Writable> apply( Map.Entry<String, Reducer<Object, Writable>> aggregator) { return new AbstractMap.SimpleEntry<String, Writable>( aggregator.getKey(), aggregator.getValue().getCurrentValue()); } }); } /** * Prepare for next superstep */ public void reset() { myReducerMap.clear(); if (LOG.isDebugEnabled()) { LOG.debug("reset: Ready for next superstep"); } } }
2,067
359
<filename>hack/bin/deps.bzl # Copyright 2021 The cert-manager 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. load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file", "http_archive") load("@bazel_gazelle//:deps.bzl", "go_repository") def install(): install_integration_test_dependencies() install_staticcheck() install_helm() install_kubectl() install_oc3() install_kind() install_ytt() install_yq() # Install golang.org/x/build as kubernetes/repo-infra requires it for the # build-tar bazel target. go_repository( name = "org_golang_x_build", build_file_generation = "on", build_file_proto_mode = "disable", importpath = "golang.org/x/build", sum = "h1:hXVePvSFG7tPGX4Pwk1d10ePFfoTCc0QmISfpKOHsS8=", version = "v0.0.0-20190927031335-2835ba2e683f", ) def install_staticcheck(): http_archive( name = "co_honnef_go_tools_staticcheck_linux", sha256 = "1ffaa079089ce8209f0c89a5d8726d06b8632eb2682e57016ff07f7e29e912dc", urls = ["https://github.com/dominikh/go-tools/releases/download/2021.1/staticcheck_linux_amd64.tar.gz"], build_file_content = """ filegroup( name = "file", srcs = [ "staticcheck/staticcheck", ], visibility = ["//visibility:public"], ) """, ) http_archive( name = "co_honnef_go_tools_staticcheck_osx", sha256 = "7fb41768b8e68aaad397f666d7d5eb9c31abcc4180b5cb6fa7d091cef987eb77", urls = ["https://github.com/dominikh/go-tools/releases/download/2021.1/staticcheck_darwin_amd64.tar.gz"], build_file_content = """ filegroup( name = "file", srcs = [ "staticcheck/staticcheck", ], visibility = ["//visibility:public"], ) """, ) # Install dependencies used by the controller-runtime integration test framework # Use these links to check for new versions: # https://console.developers.google.com/storage/kubebuilder-tools/ def install_integration_test_dependencies(): http_archive( name = "kubebuilder-tools_linux_amd64", sha256 = "25daf3c5d7e8b63ea933e11cd6ca157868d71a12885aba97d1e7e1a15510713e", urls = ["https://storage.googleapis.com/kubebuilder-tools/kubebuilder-tools-1.22.0-linux-amd64.tar.gz"], build_file_content = """ filegroup( name = "kube-apiserver", srcs = [ "kubebuilder/bin/kube-apiserver", ], visibility = ["//visibility:public"], ) filegroup( name = "etcd", srcs = [ "kubebuilder/bin/etcd", ], visibility = ["//visibility:public"], ) """, ) http_archive( name = "kubebuilder-tools_darwin_amd64", sha256 = "bb27efb1d2ee43749475293408fc80b923324ab876e5da54e58594bbe2969c42", urls = ["https://storage.googleapis.com/kubebuilder-tools/kubebuilder-tools-1.22.0-darwin-amd64.tar.gz"], build_file_content = """ filegroup( name = "kube-apiserver", srcs = [ "kubebuilder/bin/kube-apiserver", ], visibility = ["//visibility:public"], ) filegroup( name = "etcd", srcs = [ "kubebuilder/bin/etcd", ], visibility = ["//visibility:public"], ) """, ) # Install Helm targets def install_helm(): ## Fetch helm for use in template generation and testing ## You can bump the version of Helm used during e2e tests by tweaking ## the version numbers in these rules. http_archive( name = "helm_darwin", sha256 = "84a1ff17dd03340652d96e8be5172a921c97825fd278a2113c8233a4e8db5236", urls = ["https://get.helm.sh/helm-v3.6.3-darwin-amd64.tar.gz"], build_file_content = """ filegroup( name = "file", srcs = [ "darwin-amd64/helm", ], visibility = ["//visibility:public"], ) """, ) http_archive( name = "helm_darwin_arm", sha256 = "a50b499dbd0bbec90761d50974bf1e67cc6d503ea20d03b4a1275884065b7e9e", urls = ["https://get.helm.sh/helm-v3.6.3-darwin-arm64.tar.gz"], build_file_content = """ filegroup( name = "file", srcs = [ "darwin-arm64/helm", ], visibility = ["//visibility:public"], ) """, ) http_archive( name = "helm_linux", sha256 = "07c100849925623dc1913209cd1a30f0a9b80a5b4d6ff2153c609d11b043e262", urls = ["https://get.helm.sh/helm-v3.6.3-linux-amd64.tar.gz"], build_file_content = """ filegroup( name = "file", srcs = [ "linux-amd64/helm", ], visibility = ["//visibility:public"], ) """, ) # Define rules for different kubectl versions def install_kubectl(): http_file( name = "kubectl_1_22_darwin", executable = 1, sha256 = "00bb3947ac6ff15690f90ee1a732d0a9a44360fc7743dbfee4cba5a8f6a31413", urls = ["https://storage.googleapis.com/kubernetes-release/release/v1.22.1/bin/darwin/amd64/kubectl"], ) http_file( name = "kubectl_1_22_darwin_arm", executable = 1, sha256 = "c81a314ab7f0827a5376f8ffd6d47f913df046275d44c562915a822229819d77", urls = ["https://storage.googleapis.com/kubernetes-release/release/v1.22.1/bin/darwin/arm64/kubectl"], ) http_file( name = "kubectl_1_22_linux", executable = 1, sha256 = "78178a8337fc6c76780f60541fca7199f0f1a2e9c41806bded280a4a5ef665c9", urls = ["https://storage.googleapis.com/kubernetes-release/release/v1.22.1/bin/linux/amd64/kubectl"], ) # Define rules for different oc versions def install_oc3(): http_archive( name = "oc_3_11_linux", sha256 = "4b0f07428ba854174c58d2e38287e5402964c9a9355f6c359d1242efd0990da3", urls = ["https://github.com/openshift/origin/releases/download/v3.11.0/openshift-origin-client-tools-v3.11.0-0cbc58b-linux-64bit.tar.gz"], build_file_content = """ filegroup( name = "file", srcs = [ "openshift-origin-client-tools-v3.11.0-0cbc58b-linux-64bit/oc", ], visibility = ["//visibility:public"], ) """, ) http_archive( name = "oc_3_11_mac", sha256 = "75d58500aec1a2cee9473dfa826c81199669dbc0f49806e31a13626b5e4cfcf0", urls = ["https://github.com/openshift/origin/releases/download/v3.11.0/openshift-origin-client-tools-v3.11.0-0cbc58b-mac.zip"], build_file_content = """ filegroup( name = "file", srcs = [ "oc", ], visibility = ["//visibility:public"], ) """, ) ## Fetch kind images used during e2e tests def install_kind(): # install kind binary http_file( name = "kind_darwin", executable = 1, sha256 = "fdf7209e5f92651ee5d55b78eb4ee5efded0d28c3f3ab8a4a163b6ffd92becfd", urls = ["https://github.com/kubernetes-sigs/kind/releases/download/v0.14.0/kind-darwin-amd64"], ) http_file( name = "kind_darwin_arm", executable = 1, sha256 = "bdbb6e94bc8c846b0a6a1df9f962fe58950d92b26852fd6ebdc48fabb229932c", urls = ["https://github.com/kubernetes-sigs/kind/releases/download/v0.14.0/kind-darwin-arm64"], ) http_file( name = "kind_linux", executable = 1, sha256 = "af5e8331f2165feab52ec2ae07c427c7b66f4ad044d09f253004a20252524c8b", urls = ["https://github.com/kubernetes-sigs/kind/releases/download/v0.14.0/kind-linux-amd64"], ) # ytt is a yaml interpolator from the Carvel toolchain https://carvel.dev/. def install_ytt(): http_file( name = "ytt_darwin", executable = 1, sha256 = "9662e3f8e30333726a03f7a5ae6231fbfb2cebb6c1aa3f545b253d7c695487e6", urls = ["https://github.com/vmware-tanzu/carvel-ytt/releases/download/v0.36.0/ytt-darwin-amd64"], ) http_file( name = "ytt_darwin_arm", executable = 1, sha256 = "c970b2c13d4059f0bee3bf3ceaa09bd0674a62c24550453d90b284d885a06b7b", urls = ["https://github.com/vmware-tanzu/carvel-ytt/releases/download/v0.36.0/ytt-darwin-arm64"], ) http_file( name = "ytt_linux", executable = 1, sha256 = "d81ecf6c47209f6ac527e503a6fd85e999c3c2f8369e972794047bddc7e5fbe2", urls = ["https://github.com/vmware-tanzu/carvel-ytt/releases/download/v0.36.0/ytt-linux-amd64"], ) # yq is jq for yaml def install_yq(): http_file( name = "yq_darwin", executable = 1, sha256 = "5af6162d858b1adc4ad23ef11dff19ede5565d8841ac611b09500f6741ff7f46", urls = ["https://github.com/mikefarah/yq/releases/download/v4.11.2/yq_darwin_amd64"], ) http_file( name = "yq_darwin_arm", executable = 1, sha256 = "665ae1af7c73866cba74dd878c12ac49c091b66e46c9ed57d168b43955f5dd69", urls = ["https://github.com/mikefarah/yq/releases/download/v4.12.0/yq_darwin_arm64"], ) http_file( name = "yq_linux", executable = 1, sha256 = "6b891fd5bb13820b2f6c1027b613220a690ce0ef4fc2b6c76ec5f643d5535e61", urls = ["https://github.com/mikefarah/yq/releases/download/v4.11.2/yq_linux_amd64"], )
4,663
879
package org.zstack.sdk; public class DetachTagFromResourcesResult { }
25
679
<reponame>Grosskopf/openoffice /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef SD_WINDOW_HXX #define SD_WINDOW_HXX #include <tools/gen.hxx> #include <vcl/window.hxx> #include <svtools/transfer.hxx> namespace sd { class ViewShell; // Since we removed all old SV-stuff, there is no brush any more // and so there is no BRUSH_SIZE defined in VCL. // So I define it here // #i2237# // removed old stuff here which still forced zoom to be // %BRUSH_SIZE which is outdated now //#define BRUSH_SIZE 8 /** An SdWindow contains the actual working area of ViewShell. <p>The zoom factor used by this class controls how much the page and the shapes on it are scaled down (<100%) or up (>100%) when displayed on the output device represented by the <type>OutputDevice</type>base class. A zoom factor of 100% would result (with a correctly set DPI value for an output device) in a one to one mapping of the internal coordinates that are stored in 100th of mm. The zoom factor is stored in the map mode member of the <type>OutputDevice</type> base class. It is calculated to be an integer percent value. */ class Window : public ::Window, public ::DropTargetHelper { public: Window (::Window* pParent); virtual ~Window (void); void SetViewShell (ViewShell* pViewSh); /** Set the zoom factor to the specified value and center the display area around the zoom center. @param nZoom The zoom factor is given as integral percent value. */ void SetZoomIntegral(long nZoom); /** This internally used method performs the actual adaption of the window's map mode to the specified zoom factor. @param nZoom The zoom factor is given as integral percent value. @return When the given zoom factor lies outside the valid range enclosed by the minimal zoom factor previously calculated by <member>CalcMinZoom</member> and a constant upper value it is forced into that interval. Therefore the returned value is a valid zoom factor. */ long SetZoomFactor(long nZoom); /** This method is called when the whole page shall be displayed in the window. Position and zoom factor are set so that the given rectangle is displayed as large as possible in the window while at the same time maintaining the rectangle's aspect ratio and adding a small space at all its four sides (about 3% of width and height). The map mode is adapted accordingly. @param rZoomRect The rectangle is expected to be given relative to the upper left corner of the window in logical coordinates (100th of mm). @return The new zoom factor is returned as integral percent value. */ long SetZoomRect (const Rectangle& rZoomRect); long GetZoomForRect( const Rectangle& rZoomRect ); void SetMinZoomAutoCalc (bool bAuto); void SetCalcMinZoomByMinSide (bool bMin); /** Calculate the minimal zoom factor as the value at which the application area would completely fill the window. All values set manually or programatically are set to this value if they are smaller. If the currently used zoom factor is smaller than the minimal zoom factor than set the minimal zoom factor as the new current zoom factor. <p>This calculation is performed only when the <member>bMinZoomAutoCalc</member> is set (to <TRUE/>).</p> */ void CalcMinZoom (void); void SetMinZoom (long int nMin); long GetMinZoom (void) const; void SetMaxZoom (long int nMax); long GetMaxZoom (void) const; long GetZoom (void) const; Point GetWinViewPos (void) const; Point GetViewOrigin (void) const; Size GetViewSize (void) const; void SetWinViewPos(const Point& rPnt); void SetViewOrigin(const Point& rPnt); void SetViewSize(const Size& rSize); void SetCenterAllowed (bool bIsAllowed); /** Calculate origin of the map mode according to the size of the view and window (its size in model coordinates; that takes the zoom factor into account), and the bCenterAllowed flag. When it is not set then nothing is changed. When in any direction the window is larger than the view or the value of aWinPos in this direction is -1 then the window is centered in this direction. */ void UpdateMapOrigin (sal_Bool bInvalidate = sal_True); void UpdateMapMode (void); double GetVisibleX(); // Interface fuer ScrollBars double GetVisibleY(); void SetVisibleXY(double fX, double fY); double GetVisibleWidth(); double GetVisibleHeight(); double GetScrlLineWidth(); double GetScrlLineHeight(); double GetScrlPageWidth(); double GetScrlPageHeight(); virtual void GrabFocus(); virtual void DataChanged( const DataChangedEvent& rDCEvt ); // DropTargetHelper virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt ); /** The DropScroll() method is used by AcceptDrop() to scroll the content of the window while dragging and dropping. With this method you can control whether DropScroll() shall be used. */ void SetUseDropScroll (bool bUseDropScroll); void DropScroll (const Point& rMousePos); protected: ::sd::Window* mpShareWin; Point maWinPos; Point maViewOrigin; Size maViewSize; sal_uInt16 mnMinZoom; sal_uInt16 mnMaxZoom; /** This flag tells whether to re-calculate the minimal zoom factor depening on the current zoom factor. According to task #105436# its default value is now sal_False. */ bool mbMinZoomAutoCalc; bool mbCalcMinZoomByMinSide; bool mbCenterAllowed; long mnTicks; bool mbDraggedFrom; ViewShell* mpViewShell; bool mbUseDropScroll; virtual void Resize(); virtual void PrePaint(); virtual void Paint(const Rectangle& rRect); virtual void KeyInput(const KeyEvent& rKEvt); virtual void MouseMove(const MouseEvent& rMEvt); virtual void MouseButtonUp(const MouseEvent& rMEvt); virtual void MouseButtonDown(const MouseEvent& rMEvt); virtual void Command(const CommandEvent& rCEvt); virtual void RequestHelp( const HelpEvent& rEvt ); virtual void LoseFocus(); virtual long Notify( NotifyEvent& rNEvt ); /** Create an accessibility object that makes this window accessible. @return The returned reference is empty if an accessible object could not be created. */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> CreateAccessible (void); virtual void SwitchView(); XubString GetSurroundingText() const; Selection GetSurroundingTextSelection() const; }; } // end of namespace sd #endif
2,511
1,085
/* * Copyright (C) 2017-2019 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.exec.work; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import com.dremio.common.DeferredException; import com.dremio.exec.proto.CoordExecRPC.NodeStatResp; import com.dremio.exec.store.sys.NodeInstance; import io.grpc.stub.StreamObserver; /** * Allows a set of node statistic responses to be collected and considered upon completion. */ public class NodeStatsListener implements StreamObserver<NodeStatResp> { private static final int TIMEOUT = 15; private final CountDownLatch latch; private final DeferredException ex; private final ConcurrentHashMap<String, NodeInstance> stats; public NodeStatsListener(int numEndPoints) { this.latch = new CountDownLatch(numEndPoints); this.ex = new DeferredException(); this.stats = new ConcurrentHashMap<>(); } public void waitForFinish() throws Exception { boolean succeed = latch.await(TIMEOUT, TimeUnit.SECONDS); if (!succeed) { ex.addException(new TimeoutException("Failed to collect node statistics within timeout")); } ex.close(); } public ConcurrentHashMap<String, NodeInstance> getResult() { return stats; } @Override public void onNext(NodeStatResp nodeStatResp) { stats.put(nodeStatResp.getNodeStats().getName() + ":" + nodeStatResp.getNodeStats().getPort(), NodeInstance.fromStats(nodeStatResp.getNodeStats(), nodeStatResp.getEndpoint())); } @Override public void onError(Throwable throwable) { ex.addException((Exception) throwable); latch.countDown(); } @Override public void onCompleted() { latch.countDown(); } }
709
1,010
[ { "name": "Apache Pulsar Source and Sink", "version": "0.1", "docs": "https://github.com/hazelcast/hazelcast-jet-contrib/tree/master/pulsar", "filename": "hazelcast-jet-contrib-pulsar-0.1.tar.gz", "download": "https://github.com/hazelcast/hazelcast-jet-contrib/releases/download/module-jars/hazelcast-jet-contrib-pulsar-0.1.tar.gz", "size": 30.6, "contrib": true }, { "name": "InfluxDB Source and Sink", "version": "0.2", "docs": "https://github.com/hazelcast/hazelcast-jet-contrib/tree/master/influxdb", "filename": "hazelcast-jet-contrib-influxdb-0.2.tar.gz", "download": "https://github.com/hazelcast/hazelcast-jet-contrib/releases/download/module-jars/hazelcast-jet-contrib-influxdb-0.2.tar.gz", "size": 0.9, "contrib": true }, { "name": "MongoDB Source and Sink", "version": "0.2", "docs": "https://github.com/hazelcast/hazelcast-jet-contrib/tree/master/mongodb", "filename": "hazelcast-jet-contrib-mongodb-0.2.tar.gz", "download": "https://github.com/hazelcast/hazelcast-jet-contrib/releases/download/module-jars/hazelcast-jet-contrib-mongodb-0.2.tar.gz", "size": 1.8, "contrib": true }, { "name": "Twitter Source", "version": "0.1", "docs": "https://github.com/hazelcast/hazelcast-jet-contrib/tree/master/twitter", "filename": "hazelcast-jet-contrib-twitter-0.1.tar.gz", "download": "https://github.com/hazelcast/hazelcast-jet-contrib/releases/download/module-jars/hazelcast-jet-contrib-twitter-0.1.tar.gz", "size": 3.1, "contrib": true } ]
827
362
<filename>whois-query/src/main/java/net/ripe/db/whois/query/dao/AbuseValidationStatusDao.java package net.ripe.db.whois.query.dao; import net.ripe.db.whois.common.domain.CIString; public interface AbuseValidationStatusDao { boolean isSuspect(final CIString email); }
103
974
<filename>3rdparty/blend2d/src/blend2d/piperuntime_p.h<gh_stars>100-1000 // Blend2D - 2D Vector Graphics Powered by a JIT Compiler // // * Official Blend2D Home Page: https://blend2d.com // * Official Github Repository: https://github.com/blend2d/blend2d // // Copyright (c) 2017-2020 The Blend2D Authors // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #ifndef BLEND2D_PIPE_P_H_INCLUDED #define BLEND2D_PIPE_P_H_INCLUDED #include "./api-internal_p.h" #include "./pipedefs_p.h" #include "./simd_p.h" //! \cond INTERNAL //! \addtogroup blend2d_internal //! \{ // ============================================================================ // [Forward Declarations] // ============================================================================ struct BLPipeRuntime; struct BLPipeProvider; struct BLPipeLookupCache; // ============================================================================ // [Constants] // ============================================================================ enum BLPipeRuntimeType : uint32_t { //! Fixed runtime that doesn't use JIT (can be either reference or optimized). BL_PIPE_RUNTIME_TYPE_FIXED = 0, //! Runtime that uses PipeGen - JIT optimized pipelines. BL_PIPE_RUNTIME_TYPE_PIPEGEN = 1, //! Count of pipeline runtime types. BL_PIPE_RUNTIME_TYPE_COUNT }; enum BLPipeRuntimeFlags : uint32_t { BL_PIPE_RUNTIME_FLAG_ISOLATED = 0x00000001 }; // ============================================================================ // [BLPipeRuntime] // ============================================================================ //! This is a base class used by either `BLPipeGenRuntime` (for dynamic piplines) //! or `BLFixedPipeRuntime` for static pipelines. The purpose of this class is //! to create an interface that is used by the rendering context so it doesn't //! have to know which kind of pipelines it uses. struct BLPipeRuntime { //! Type of the runtime, see `BLPipeRuntimeType`. uint8_t _runtimeType; //! Reserved for future use. uint8_t _reserved; //! Size of this runtime in bytes. uint16_t _runtimeSize; //! Runtime flags, see `BLPipeRuntimeFlags`. uint32_t _runtimeFlags; //! Runtime destructor. void (BL_CDECL* _destroy)(BLPipeRuntime* self) BL_NOEXCEPT; //! Functions exposed by the runtime that are copied to `BLPipeProvider` to //! make them local in the rendering context. It seems hacky, but this removes //! one extra indirection that would be needed if they were virtual. struct Funcs { BLPipeFillFunc (BL_CDECL* get)(BLPipeRuntime* self, uint32_t signature, BLPipeLookupCache* cache) BL_NOEXCEPT; BLPipeFillFunc (BL_CDECL* test)(BLPipeRuntime* self, uint32_t signature, BLPipeLookupCache* cache) BL_NOEXCEPT; } _funcs; BL_INLINE uint32_t runtimeType() const noexcept { return _runtimeType; } BL_INLINE uint32_t runtimeFlags() const noexcept { return _runtimeFlags; } BL_INLINE uint32_t runtimeSize() const noexcept { return _runtimeSize; } BL_INLINE void destroy() noexcept { _destroy(this); } }; // ============================================================================ // [BLPipeProvider] // ============================================================================ struct BLPipeProvider { BLPipeRuntime* _runtime; BLPipeRuntime::Funcs _funcs; BL_INLINE BLPipeProvider() noexcept : _runtime(nullptr), _funcs {} {} BL_INLINE bool isInitialized() const noexcept { return _runtime != nullptr; } BL_INLINE void init(BLPipeRuntime* runtime) noexcept { _runtime = runtime; _funcs = runtime->_funcs; } BL_INLINE void reset() noexcept { memset(this, 0, sizeof(*this)); } BL_INLINE BLPipeRuntime* runtime() const noexcept { return _runtime; } BL_INLINE BLPipeFillFunc get(uint32_t signature, BLPipeLookupCache* cache = nullptr) const noexcept { return _funcs.get(_runtime, signature, cache); } BL_INLINE BLPipeFillFunc test(uint32_t signature, BLPipeLookupCache* cache = nullptr) const noexcept { return _funcs.test(_runtime, signature, cache); } }; // ============================================================================ // [BLPipeLookupCache] // ============================================================================ //! Pipe lookup cache is a local cache used by the rendering engine to store //! `N` recently used pipelines so it doesn't have to use `BLPipeProvider` that //! that has a considerably higher overhead. struct BLPipeLookupCache { // Number of cached pipelines, must be multiply of 4. #if BL_TARGET_ARCH_X86 static const uint32_t N = 16; // SSE2 friendly option. #else static const uint32_t N = 8; #endif struct IndexMatch { size_t _index; BL_INLINE bool isValid() const noexcept { return _index < N; } BL_INLINE size_t index() const noexcept { return _index; } }; struct BitMatch { uint32_t _bits; BL_INLINE bool isValid() const noexcept { return _bits != 0; } BL_INLINE size_t index() const noexcept { return blBitCtz(_bits); } }; //! Array of signatures for the lookup, uninitialized signatures are zero. uint32_t _signatures[N]; //! Array of functions matching signatures stored in `_signatures` array. void* _funcs[N]; //! Index where the next signature will be written (incremental, wraps to zero). size_t _currentIndex; BL_INLINE void reset() { memset(this, 0, sizeof(*this)); } #if defined(BL_TARGET_OPT_SSE2) typedef BitMatch MatchType; BL_INLINE MatchType match(uint32_t signature) const noexcept { static_assert(N == 4 || N == 8 || N == 16, "This code is written for N == 4|8|16"); using namespace SIMD; Vec128I vSign = v_fill_i128_u32(signature); switch (N) { case 4: { Vec128I vec0 = v_cmp_eq_i32(v_loadu_i128(_signatures + 0), vSign); return BitMatch { uint32_t(_mm_movemask_ps(v_cast<Vec128F>(vec0))) }; } case 8: { Vec128I vec0 = v_cmp_eq_i32(v_loadu_i128(_signatures + 0), vSign); Vec128I vec1 = v_cmp_eq_i32(v_loadu_i128(_signatures + 4), vSign); Vec128I vecm = v_packs_i16_i8(v_packs_i32_i16(vec0, vec1)); return BitMatch { uint32_t(_mm_movemask_epi8(vecm)) }; } case 16: { Vec128I vec0 = v_cmp_eq_i32(v_loadu_i128(_signatures + 0), vSign); Vec128I vec1 = v_cmp_eq_i32(v_loadu_i128(_signatures + 4), vSign); Vec128I vec2 = v_cmp_eq_i32(v_loadu_i128(_signatures + 8), vSign); Vec128I vec3 = v_cmp_eq_i32(v_loadu_i128(_signatures + 12), vSign); Vec128I vecm = v_packs_i16_i8(v_packs_i32_i16(vec0, vec1), v_packs_i32_i16(vec2, vec3)); return BitMatch { uint32_t(_mm_movemask_epi8(vecm)) }; } default: return BitMatch { 0 }; } } #else typedef IndexMatch MatchType; BL_INLINE MatchType match(uint32_t signature) const noexcept { size_t i; for (i = 0; i < N; i++) if (_signatures[i] == signature) break; return IndexMatch { i }; } #endif BL_INLINE void _store(uint32_t signature, void* func) noexcept { _signatures[_currentIndex] = signature; _funcs[_currentIndex] = func; _currentIndex = (_currentIndex + 1) % N; } template<typename Func, typename MatchT> BL_INLINE Func getMatch(const MatchT& match) const noexcept { BL_ASSERT(match.isValid()); return (Func)_funcs[match.index()]; } template<typename Func> BL_INLINE Func lookup(uint32_t signature) const noexcept { BL_ASSERT(signature != 0); MatchType m = match(signature); return (Func)(m.isValid() ? _funcs[m.index()] : nullptr); } template<typename Func> BL_INLINE void store(uint32_t signature, Func func) noexcept { BL_ASSERT(signature != 0); BL_ASSERT((void*)func != nullptr); _store(signature, (void*)func); } }; //! \} //! \endcond #endif // BLEND2D_PIPE_P_H_INCLUDED
2,930
348
<gh_stars>100-1000 {"nom":"Mennouveaux","circ":"1ère circonscription","dpt":"Haute-Marne","inscrits":76,"abs":37,"votants":39,"blancs":5,"nuls":4,"exp":30,"res":[{"nuance":"LR","nom":"<NAME>","voix":20},{"nuance":"REM","nom":"<NAME>","voix":10}]}
101
3,138
# Lint as: python3 # Copyright 2019 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. """Tests for Quasi Monte-Carlo utils.""" import tensorflow.compat.v2 as tf import tf_quant_finance as tff from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import utils = tff.math.qmc.utils @test_util.run_all_in_graph_and_eager_modes class UtilsTest(tf.test.TestCase): def test_exp2_without_overflow(self): test_cases = [ tf.uint8, tf.int8, tf.uint16, tf.int16, tf.uint32, tf.int32, tf.uint64, tf.int64 ] for dtype in test_cases: expected = tf.constant([2, 4, 8, 16, 32, 64], dtype=dtype) actual = utils.exp2(tf.constant([1, 2, 3, 4, 5, 6], dtype=dtype)) with self.subTest('Values'): self.assertAllEqual(self.evaluate(actual), self.evaluate(expected)) with self.subTest('DType'): self.assertEqual(actual.dtype, expected.dtype) def test_exp2_with_overflow(self): test_cases = [(tf.uint8, 9), (tf.int8, 8), (tf.uint16, 17), (tf.int16, 16), (tf.uint32, 33), (tf.int32, 32), (tf.uint64, 65), (tf.int64, 64)] for dtype, value in test_cases: expected = tf.constant([dtype.max, dtype.max], dtype=dtype) actual = utils.exp2(tf.constant([value, value + 1], dtype=dtype)) with self.subTest('Values'): self.assertAllEqual(self.evaluate(actual), self.evaluate(expected)) with self.subTest('DType'): self.assertEqual(actual.dtype, expected.dtype) def test_log2(self): test_cases = [(tf.float16, 1e-3), (tf.float32, 1e-6), (tf.float64, 1e-12)] for dtype, tolerance in test_cases: expected = tf.constant([1, 2, 3, 4, 5, 6], dtype=dtype) actual = utils.log2(tf.constant([2, 4, 8, 16, 32, 64], dtype=dtype)) with self.subTest('Values'): self.assertAllClose( self.evaluate(actual), self.evaluate(expected), rtol=tolerance) with self.subTest('DType'): self.assertEqual(actual.dtype, expected.dtype) def test_tent_transform(self): test_cases = [(tf.float16, 5e-3), (tf.float32, 1e-6), (tf.float64, 1e-12)] for dtype, tolerance in test_cases: expected = tf.constant([0, .2, .4, .6, .8, 1., .8, .6, .4, .2, 0.], dtype=dtype) actual = utils.tent_transform( tf.constant([0, .1, .2, .3, .4, .5, .6, .7, .8, .9, 1], dtype=dtype)) with self.subTest('Values'): self.assertAllClose( self.evaluate(actual), self.evaluate(expected), rtol=tolerance) with self.subTest('DType'): self.assertEqual(actual.dtype, expected.dtype) def test_filter_tensor(self): test_cases = [ tf.uint8, tf.int8, tf.uint16, tf.int16, tf.uint32, tf.int32, tf.uint64, tf.int64 ] for dtype in test_cases: # Should only retain values for which given bits in the bit mask are set. expected = tf.constant([[6, 5, 0], [3, 0, 1]], dtype=dtype) actual = utils.filter_tensor( # Tensor to filter tf.constant([[6, 5, 4], [3, 2, 1]], dtype=dtype), # Bit mask tf.constant([[1, 2, 11], [3, 5, 4]], dtype=dtype), # Indices (in LSB 0 order) of bits in the mask used for filtering tf.constant([[0, 1, 2], [0, 1, 2]], dtype=dtype)) with self.subTest('Values'): self.assertAllEqual(self.evaluate(actual), self.evaluate(expected)) with self.subTest('DType'): self.assertEqual(actual.dtype, expected.dtype) if __name__ == '__main__': tf.test.main()
1,778
524
<reponame>Qt-Widgets/im-desktop-imported #pragma once #include "fetch_event.h" #include "../persons_packet.h" namespace core { namespace wim { class contactlist; typedef std::map<std::string, std::shared_ptr<contactlist>> diffs_map; class fetch_event_diff : public fetch_event, public persons_packet { std::shared_ptr<diffs_map> diff_; std::shared_ptr<core::archive::persons_map> persons_; public: fetch_event_diff(); virtual ~fetch_event_diff(); std::shared_ptr<diffs_map> get_diff() const { return diff_; } virtual int32_t parse(const rapidjson::Value& _node_event_data) override; virtual void on_im(std::shared_ptr<core::wim::im> _im, std::shared_ptr<auto_callback> _on_complete) override; const std::shared_ptr<core::archive::persons_map>& get_persons() const override { return persons_; } }; } }
429
1,444
package org.mage.test.cards.single.khm; import mage.cards.Card; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Assert; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; /** * @author JayDi85 */ public class MoritteOfTheFrostTest extends CardTestPlayerBase { @Test public void test_MustBeAnyTypeInHand() { // bug: can't cast by mana from Myr Reservoir // {T}: Add {C}{C}. Spend this mana only to cast Myr spells or activate abilities of Myr. addCard(Zone.BATTLEFIELD, playerA, "Myr Reservoir"); // // Changeling (This card is every creature type.) addCard(Zone.HAND, playerA, "Moritte of the Frost");// {2}{G}{U}{U} addCard(Zone.BATTLEFIELD, playerA, "Forest", 1); addCard(Zone.BATTLEFIELD, playerA, "Island", 2); // prepare mana activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{T}: Add {C}{C}"); // cast myr and remove to to graveyard due 0/0 checkPlayableAbility("before", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Moritte of the Frost", true); castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Moritte of the Frost"); setChoice(playerA, false); // no copy setStrictChooseMode(true); setStopAt(1, PhaseStep.END_TURN); execute(); assertAllCommandsUsed(); assertGraveyardCount(playerA, "Moritte of the Frost", 1); // removed to graveyard due 0/0 } @Test public void test_MustBeAnyTypeOnBattlefield() { // {T}: Add {C}{C}. Spend this mana only to cast Myr spells or activate abilities of Myr. addCard(Zone.BATTLEFIELD, playerA, "Myr Reservoir"); // // Changeling (This card is every creature type.) addCard(Zone.HAND, playerA, "Moritte of the Frost");// {2}{G}{U}{U} addCard(Zone.BATTLEFIELD, playerA, "Forest", 1); addCard(Zone.BATTLEFIELD, playerA, "Island", 2); // // Minion creatures get +1/+1. addCard(Zone.BATTLEFIELD, playerA, "Balthor the Defiled", 1); // prepare mana activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{T}: Add {C}{C}"); // cast myr and keep on battlefield due boost checkPlayableAbility("before", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Moritte of the Frost", true); castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Moritte of the Frost"); setChoice(playerA, false); // no copy setStrictChooseMode(true); setStopAt(1, PhaseStep.END_TURN); execute(); assertAllCommandsUsed(); assertPermanentCount(playerA, "Moritte of the Frost", 1); // boosted +1/+1 } @Test public void test_MustBeAnyTypeAfterCopy() { // {T}: Add {C}{C}. Spend this mana only to cast Myr spells or activate abilities of Myr. addCard(Zone.BATTLEFIELD, playerA, "Myr Reservoir"); // // Changeling (This card is every creature type.) // You may have Moritte of the Frost enter the battlefield as a copy of a permanent you control, // except it's legendary and snow in addition to its other types and, if it's a creature, it enters // with two additional +1/+1 counters on it and has changeling. addCard(Zone.HAND, playerA, "Moritte of the Frost");// {2}{G}{U}{U} addCard(Zone.BATTLEFIELD, playerA, "Forest", 1); addCard(Zone.BATTLEFIELD, playerA, "Island", 2); // // Minion creatures get +1/+1. addCard(Zone.BATTLEFIELD, playerA, "Balthor the Defiled", 1); // addCard(Zone.BATTLEFIELD, playerA, "<NAME>", 1); // 2/2 // prepare mana activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{T}: Add {C}{C}"); // cast myr and copy checkPlayableAbility("before", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Moritte of the Frost", true); castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Moritte of the Frost"); setChoice(playerA, true); // use copy setChoice(playerA, "<NAME>"); // copy target setStrictChooseMode(true); setStopAt(1, PhaseStep.END_TURN); execute(); assertAllCommandsUsed(); assertPermanentCount(playerA, "Grizzly Bears", 2); // boosted by copy and balthor Card card = currentGame.getBattlefield().getAllActivePermanents().stream().filter(p -> p.isCopy()).findFirst().orElse(null); Assert.assertNotNull("Can't find copy", card); Assert.assertEquals("Copy power", 2 + 2 + 1, card.getPower().getValue()); Assert.assertEquals("Copy Toughness", 2 + 2 + 1, card.getToughness().getValue()); } }
1,886
930
<gh_stars>100-1000 package vip.mate.system.strategy; import lombok.AllArgsConstructor; import org.springframework.stereotype.Component; import vip.mate.core.database.enums.DataScopeTypeEnum; import vip.mate.system.dto.RoleDTO; import vip.mate.system.service.ISysDepartService; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * 自定义数据范围 * * @author pangu */ @Component("4") @AllArgsConstructor public class CustomizeDataScope implements AbstractDataScopeHandler { private final ISysDepartService sysDepartService; @Override public List<Long> getDeptIds(RoleDTO roleDto, DataScopeTypeEnum dataScopeTypeEnum) { List<Long> roleDeptIds = roleDto.getRoleDepts(); List<Long> ids = new ArrayList<>(); for (Long deptId : roleDeptIds) { ids.addAll(sysDepartService.selectDeptIds(deptId)); } Set<Long> set = new HashSet<>(ids); ids.clear(); ids.addAll(set); return ids; } }
370
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- #include "scitems.hxx" #include <sfx2/app.hxx> #include <sfx2/docfile.hxx> #include <sfx2/objsh.hxx> #include <basic/sbmeth.hxx> #include <basic/sbmod.hxx> #include <basic/sbstar.hxx> #include <basic/basmgr.hxx> #include <basic/sbx.hxx> #include <svl/zforlist.hxx> #include <vcl/msgbox.hxx> #include <tools/urlobj.hxx> #include <rtl/math.hxx> #include "validat.hxx" #include "document.hxx" #include "cell.hxx" #include "patattr.hxx" #include "rechead.hxx" #include "globstr.hrc" #include "rangenam.hxx" #include "dbcolect.hxx" #include <math.h> #include <memory> using namespace formula; //------------------------------------------------------------------------ SV_IMPL_OP_PTRARR_SORT( ScValidationEntries_Impl, ScValidationDataPtr ); //------------------------------------------------------------------------ // // Eintrag fuer Gueltigkeit (es gibt nur eine Bedingung) // ScValidationData::ScValidationData( ScValidationMode eMode, ScConditionMode eOper, const String& rExpr1, const String& rExpr2, ScDocument* pDocument, const ScAddress& rPos, const String& rExprNmsp1, const String& rExprNmsp2, FormulaGrammar::Grammar eGrammar1, FormulaGrammar::Grammar eGrammar2 ) : ScConditionEntry( eOper, rExpr1, rExpr2, pDocument, rPos, rExprNmsp1, rExprNmsp2, eGrammar1, eGrammar2 ), nKey( 0 ), eDataMode( eMode ), eErrorStyle( SC_VALERR_STOP ), mnListType( ValidListType::UNSORTED ) { bShowInput = bShowError = sal_False; } ScValidationData::ScValidationData( ScValidationMode eMode, ScConditionMode eOper, const ScTokenArray* pArr1, const ScTokenArray* pArr2, ScDocument* pDocument, const ScAddress& rPos ) : ScConditionEntry( eOper, pArr1, pArr2, pDocument, rPos ), nKey( 0 ), eDataMode( eMode ), eErrorStyle( SC_VALERR_STOP ), mnListType( ValidListType::UNSORTED ) { bShowInput = bShowError = sal_False; } ScValidationData::ScValidationData( const ScValidationData& r ) : ScConditionEntry( r ), nKey( r.nKey ), eDataMode( r.eDataMode ), bShowInput( r.bShowInput ), bShowError( r.bShowError ), eErrorStyle( r.eErrorStyle ), mnListType( r.mnListType ), aInputTitle( r.aInputTitle ), aInputMessage( r.aInputMessage ), aErrorTitle( r.aErrorTitle ), aErrorMessage( r.aErrorMessage ) { // Formeln per RefCount kopiert } ScValidationData::ScValidationData( ScDocument* pDocument, const ScValidationData& r ) : ScConditionEntry( pDocument, r ), nKey( r.nKey ), eDataMode( r.eDataMode ), bShowInput( r.bShowInput ), bShowError( r.bShowError ), eErrorStyle( r.eErrorStyle ), mnListType( r.mnListType ), aInputTitle( r.aInputTitle ), aInputMessage( r.aInputMessage ), aErrorTitle( r.aErrorTitle ), aErrorMessage( r.aErrorMessage ) { // Formeln wirklich kopiert } ScValidationData::~ScValidationData() { } sal_Bool ScValidationData::IsEmpty() const { String aEmpty; ScValidationData aDefault( SC_VALID_ANY, SC_COND_EQUAL, aEmpty, aEmpty, GetDocument(), ScAddress() ); return EqualEntries( aDefault ); } sal_Bool ScValidationData::EqualEntries( const ScValidationData& r ) const { // gleiche Parameter eingestellt (ohne Key) return ScConditionEntry::operator==(r) && eDataMode == r.eDataMode && bShowInput == r.bShowInput && bShowError == r.bShowError && eErrorStyle == r.eErrorStyle && mnListType == r.mnListType && aInputTitle == r.aInputTitle && aInputMessage == r.aInputMessage && aErrorTitle == r.aErrorTitle && aErrorMessage == r.aErrorMessage; } void ScValidationData::ResetInput() { bShowInput = sal_False; } void ScValidationData::ResetError() { bShowError = sal_False; } void ScValidationData::SetInput( const String& rTitle, const String& rMsg ) { bShowInput = sal_True; aInputTitle = rTitle; aInputMessage = rMsg; } void ScValidationData::SetError( const String& rTitle, const String& rMsg, ScValidErrorStyle eStyle ) { bShowError = sal_True; eErrorStyle = eStyle; aErrorTitle = rTitle; aErrorMessage = rMsg; } sal_Bool ScValidationData::GetErrMsg( String& rTitle, String& rMsg, ScValidErrorStyle& rStyle ) const { rTitle = aErrorTitle; rMsg = aErrorMessage; rStyle = eErrorStyle; return bShowError; } sal_Bool ScValidationData::DoScript( const ScAddress& rPos, const String& rInput, ScFormulaCell* pCell, Window* pParent ) const { ScDocument* pDocument = GetDocument(); SfxObjectShell* pDocSh = pDocument->GetDocumentShell(); if ( !pDocSh || !pDocument->CheckMacroWarn() ) return sal_False; sal_Bool bScriptReturnedFalse = sal_False; // Standard: kein Abbruch // Set up parameters ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > aParams(2); // 1) eingegebener / berechneter Wert String aValStr = rInput; double nValue; sal_Bool bIsValue = sal_False; if ( pCell ) // wenn Zelle gesetzt, aus Interpret gerufen { bIsValue = pCell->IsValue(); if ( bIsValue ) nValue = pCell->GetValue(); else pCell->GetString( aValStr ); } if ( bIsValue ) aParams[0] = ::com::sun::star::uno::makeAny( nValue ); else aParams[0] = ::com::sun::star::uno::makeAny( ::rtl::OUString( aValStr ) ); // 2) Position der Zelle String aPosStr; rPos.Format( aPosStr, SCA_VALID | SCA_TAB_3D, pDocument, pDocument->GetAddressConvention() ); aParams[1] = ::com::sun::star::uno::makeAny( ::rtl::OUString( aPosStr ) ); // use link-update flag to prevent closing the document // while the macro is running sal_Bool bWasInLinkUpdate = pDocument->IsInLinkUpdate(); if ( !bWasInLinkUpdate ) pDocument->SetInLinkUpdate( sal_True ); if ( pCell ) pDocument->LockTable( rPos.Tab() ); ::com::sun::star::uno::Any aRet; ::com::sun::star::uno::Sequence< sal_Int16 > aOutArgsIndex; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > aOutArgs; ErrCode eRet = pDocSh->CallXScript( aErrorTitle, aParams, aRet, aOutArgsIndex, aOutArgs ); if ( pCell ) pDocument->UnlockTable( rPos.Tab() ); if ( !bWasInLinkUpdate ) pDocument->SetInLinkUpdate( sal_False ); // Check the return value from the script // The contents of the cell get reset if the script returns false sal_Bool bTmp = sal_False; if ( eRet == ERRCODE_NONE && aRet.getValueType() == getCppuBooleanType() && sal_True == ( aRet >>= bTmp ) && bTmp == sal_False ) { bScriptReturnedFalse = sal_True; } if ( eRet == ERRCODE_BASIC_METHOD_NOT_FOUND && !pCell ) // Makro nicht gefunden (nur bei Eingabe) { //! andere Fehlermeldung, wenn gefunden, aber nicht bAllowed ?? ErrorBox aBox( pParent, WinBits(WB_OK), ScGlobal::GetRscString( STR_VALID_MACRONOTFOUND ) ); aBox.Execute(); } return bScriptReturnedFalse; } // sal_True -> Abbruch sal_Bool ScValidationData::DoMacro( const ScAddress& rPos, const String& rInput, ScFormulaCell* pCell, Window* pParent ) const { if ( SfxApplication::IsXScriptURL( aErrorTitle ) ) { return DoScript( rPos, rInput, pCell, pParent ); } ScDocument* pDocument = GetDocument(); SfxObjectShell* pDocSh = pDocument->GetDocumentShell(); if ( !pDocSh || !pDocument->CheckMacroWarn() ) return sal_False; sal_Bool bDone = sal_False; sal_Bool bRet = sal_False; // Standard: kein Abbruch // Wenn das Dok waehrend eines Basic-Calls geladen wurde, // ist das Sbx-Objekt evtl. nicht angelegt (?) // pDocSh->GetSbxObject(); // keine Sicherheitsabfrage mehr vorneweg (nur CheckMacroWarn), das passiert im CallBasic #if 0 // Makro-Name liegt in folgender Form vor: // "Macroname.Modulname.Libname.Dokumentname" oder // "Macroname.Modulname.Libname.Applikationsname" String aMacroName = aErrorTitle.GetToken(0, '.'); String aModulName = aErrorTitle.GetToken(1, '.'); String aLibName = aErrorTitle.GetToken(2, '.'); String aDocName = aErrorTitle.GetToken(3, '.'); #endif // Funktion ueber den einfachen Namen suchen, // dann aBasicStr, aMacroStr fuer SfxObjectShell::CallBasic zusammenbauen StarBASIC* pRoot = pDocSh->GetBasic(); SbxVariable* pVar = pRoot->Find( aErrorTitle, SbxCLASS_METHOD ); if ( pVar && pVar->ISA(SbMethod) ) { SbMethod* pMethod = (SbMethod*)pVar; SbModule* pModule = pMethod->GetModule(); SbxObject* pObject = pModule->GetParent(); String aMacroStr = pObject->GetName(); aMacroStr += '.'; aMacroStr += pModule->GetName(); aMacroStr += '.'; aMacroStr += pMethod->GetName(); String aBasicStr; // #95867# the distinction between document- and app-basic has to be done // by checking the parent (as in ScInterpreter::ScMacro), not by looping // over all open documents, because this may be called from within loading, // when SfxObjectShell::GetFirst/GetNext won't find the document. if ( pObject->GetParent() ) aBasicStr = pObject->GetParent()->GetName(); // Dokumentenbasic else aBasicStr = SFX_APP()->GetName(); // Applikationsbasic // Parameter fuer Makro SbxArrayRef refPar = new SbxArray; // 1) eingegebener / berechneter Wert String aValStr = rInput; double nValue = 0.0; sal_Bool bIsValue = sal_False; if ( pCell ) // wenn Zelle gesetzt, aus Interpret gerufen { bIsValue = pCell->IsValue(); if ( bIsValue ) nValue = pCell->GetValue(); else pCell->GetString( aValStr ); } if ( bIsValue ) refPar->Get(1)->PutDouble( nValue ); else refPar->Get(1)->PutString( aValStr ); // 2) Position der Zelle String aPosStr; rPos.Format( aPosStr, SCA_VALID | SCA_TAB_3D, pDocument, pDocument->GetAddressConvention() ); refPar->Get(2)->PutString( aPosStr ); // use link-update flag to prevent closing the document // while the macro is running sal_Bool bWasInLinkUpdate = pDocument->IsInLinkUpdate(); if ( !bWasInLinkUpdate ) pDocument->SetInLinkUpdate( sal_True ); if ( pCell ) pDocument->LockTable( rPos.Tab() ); SbxVariableRef refRes = new SbxVariable; ErrCode eRet = pDocSh->CallBasic( aMacroStr, aBasicStr, refPar, refRes ); if ( pCell ) pDocument->UnlockTable( rPos.Tab() ); if ( !bWasInLinkUpdate ) pDocument->SetInLinkUpdate( sal_False ); // Eingabe abbrechen, wenn Basic-Makro sal_False zurueckgibt if ( eRet == ERRCODE_NONE && refRes->GetType() == SbxBOOL && refRes->GetBool() == sal_False ) bRet = sal_True; bDone = sal_True; } if ( !bDone && !pCell ) // Makro nicht gefunden (nur bei Eingabe) { //! andere Fehlermeldung, wenn gefunden, aber nicht bAllowed ?? ErrorBox aBox( pParent, WinBits(WB_OK), ScGlobal::GetRscString( STR_VALID_MACRONOTFOUND ) ); aBox.Execute(); } return bRet; } void ScValidationData::DoCalcError( ScFormulaCell* pCell ) const { if ( eErrorStyle == SC_VALERR_MACRO ) DoMacro( pCell->aPos, EMPTY_STRING, pCell, NULL ); } // sal_True -> Abbruch sal_Bool ScValidationData::DoError( Window* pParent, const String& rInput, const ScAddress& rPos ) const { if ( eErrorStyle == SC_VALERR_MACRO ) return DoMacro( rPos, rInput, NULL, pParent ); // Fehlermeldung ausgeben String aTitle = aErrorTitle; if (!aTitle.Len()) aTitle = ScGlobal::GetRscString( STR_MSSG_DOSUBTOTALS_0 ); // application title String aMessage = aErrorMessage; if (!aMessage.Len()) aMessage = ScGlobal::GetRscString( STR_VALID_DEFERROR ); //! ErrorBox / WarningBox / InfoBox ? //! (bei InfoBox immer nur OK-Button) WinBits nStyle = 0; switch (eErrorStyle) { case SC_VALERR_STOP: nStyle = WB_OK | WB_DEF_OK; break; case SC_VALERR_WARNING: nStyle = WB_OK_CANCEL | WB_DEF_CANCEL; break; case SC_VALERR_INFO: nStyle = WB_OK_CANCEL | WB_DEF_OK; break; default: { // added to avoid warnings } } MessBox aBox( pParent, WinBits(nStyle), aTitle, aMessage ); sal_uInt16 nRet = aBox.Execute(); return ( eErrorStyle == SC_VALERR_STOP || nRet == RET_CANCEL ); } sal_Bool ScValidationData::IsDataValid( const String& rTest, const ScPatternAttr& rPattern, const ScAddress& rPos ) const { if ( eDataMode == SC_VALID_ANY ) // check if any cell content is allowed return sal_True; if ( rTest.GetChar(0) == '=' ) // formulas do not pass the validity test return sal_False; if ( !rTest.Len() ) // check whether empty cells are allowed return IsIgnoreBlank(); SvNumberFormatter* pFormatter = GetDocument()->GetFormatTable(); // get the value if any sal_uInt32 nFormat = rPattern.GetNumberFormat( pFormatter ); double nVal; sal_Bool bIsVal = pFormatter->IsNumberFormat( rTest, nFormat, nVal ); ScBaseCell* pCell; if (bIsVal) pCell = new ScValueCell( nVal ); else pCell = new ScStringCell( rTest ); sal_Bool bRet; if (SC_VALID_TEXTLEN == eDataMode) { const double nLenVal = static_cast<double>( rTest.Len() ); ScValueCell aTmpCell( nLenVal ); bRet = IsCellValid( &aTmpCell, rPos ); } else bRet = IsDataValid( pCell, rPos ); pCell->Delete(); return bRet; } sal_Bool ScValidationData::IsDataValid( ScBaseCell* pCell, const ScAddress& rPos ) const { if( eDataMode == SC_VALID_LIST ) return IsListValid( pCell, rPos ); double nVal = 0.0; String aString; sal_Bool bIsVal = sal_True; switch (pCell->GetCellType()) { case CELLTYPE_VALUE: nVal = ((ScValueCell*)pCell)->GetValue(); break; case CELLTYPE_STRING: ((ScStringCell*)pCell)->GetString( aString ); bIsVal = sal_False; break; case CELLTYPE_EDIT: ((ScEditCell*)pCell)->GetString( aString ); bIsVal = sal_False; break; case CELLTYPE_FORMULA: { ScFormulaCell* pFCell = (ScFormulaCell*)pCell; bIsVal = pFCell->IsValue(); if ( bIsVal ) nVal = pFCell->GetValue(); else pFCell->GetString( aString ); } break; default: // Notizen, Broadcaster return IsIgnoreBlank(); // wie eingestellt } sal_Bool bOk = sal_True; switch (eDataMode) { // SC_VALID_ANY schon oben case SC_VALID_WHOLE: case SC_VALID_DECIMAL: case SC_VALID_DATE: // Date/Time ist nur Formatierung case SC_VALID_TIME: bOk = bIsVal; if ( bOk && eDataMode == SC_VALID_WHOLE ) bOk = ::rtl::math::approxEqual( nVal, floor(nVal+0.5) ); // ganze Zahlen if ( bOk ) bOk = IsCellValid( pCell, rPos ); break; case SC_VALID_CUSTOM: // fuer Custom muss eOp == SC_COND_DIRECT sein //! der Wert muss im Dokument stehen !!!!!!!!!!!!!!!!!!!! bOk = IsCellValid( pCell, rPos ); break; case SC_VALID_TEXTLEN: bOk = !bIsVal; // nur Text if ( bOk ) { double nLenVal = (double) aString.Len(); ScValueCell aTmpCell( nLenVal ); bOk = IsCellValid( &aTmpCell, rPos ); } break; default: DBG_ERROR("hammanochnich"); break; } return bOk; } // ---------------------------------------------------------------------------- namespace { /** Token array helper. Iterates over all string tokens. @descr The token array must contain separated string tokens only. @param bSkipEmpty true = Ignores string tokens with empty strings. */ class ScStringTokenIterator { public: inline explicit ScStringTokenIterator( ScTokenArray& rTokArr, bool bSkipEmpty = true ) : mrTokArr( rTokArr ), mbSkipEmpty( bSkipEmpty ), mbOk( true ) {} /** Returns the string of the first string token or NULL on error or empty token array. */ const String* First(); /** Returns the string of the next string token or NULL on error or end of token array. */ const String* Next(); /** Returns false, if a wrong token has been found. Does NOT return false on end of token array. */ inline bool Ok() const { return mbOk; } private: ScTokenArray& mrTokArr; /// The token array for iteration. bool mbSkipEmpty; /// Ignore empty strings. bool mbOk; /// true = correct token or end of token array. }; const String* ScStringTokenIterator::First() { mrTokArr.Reset(); mbOk = true; return Next(); } const String* ScStringTokenIterator::Next() { if( !mbOk ) return NULL; // seek to next non-separator token const FormulaToken* pToken = mrTokArr.NextNoSpaces(); while( pToken && (pToken->GetOpCode() == ocSep) ) pToken = mrTokArr.NextNoSpaces(); mbOk = !pToken || (pToken->GetType() == formula::svString); const String* pString = (mbOk && pToken) ? &pToken->GetString() : NULL; // string found but empty -> get next token; otherwise return it return (mbSkipEmpty && pString && !pString->Len()) ? Next() : pString; } // ---------------------------------------------------------------------------- /** Returns the number format of the passed cell, or the standard format. */ sal_uLong lclGetCellFormat( ScDocument& rDoc, const ScAddress& rPos ) { const ScPatternAttr* pPattern = rDoc.GetPattern( rPos.Col(), rPos.Row(), rPos.Tab() ); if( !pPattern ) pPattern = rDoc.GetDefPattern(); return pPattern->GetNumberFormat( rDoc.GetFormatTable() ); } /** Inserts the passed string object. Always takes ownership. pData is invalid after this call! */ void lclInsertStringToCollection( TypedScStrCollection& rStrColl, TypedStrData* pData, bool bSorted ) { if( !(bSorted ? rStrColl.Insert( pData ) : rStrColl.AtInsert( rStrColl.GetCount(), pData )) ) delete pData; } } // namespace // ---------------------------------------------------------------------------- bool ScValidationData::HasSelectionList() const { return (eDataMode == SC_VALID_LIST) && (mnListType != ValidListType::INVISIBLE); } bool ScValidationData::GetSelectionFromFormula( TypedScStrCollection* pStrings, ScBaseCell* pCell, const ScAddress& rPos, const ScTokenArray& rTokArr, int& rMatch ) const { bool bOk = true; // pDoc is private in condition, use an accessor and a long winded name. ScDocument* pDocument = GetDocument(); if( NULL == pDocument ) return false; ScFormulaCell aValidationSrc( pDocument, rPos, &rTokArr, formula::FormulaGrammar::GRAM_DEFAULT, MM_FORMULA); // Make sure the formula gets interpreted and a result is delivered, // regardless of the AutoCalc setting. aValidationSrc.Interpret(); ScMatrixRef xMatRef; const ScMatrix *pValues = aValidationSrc.GetMatrix(); if (!pValues) { // The somewhat nasty case of either an error occurred, or the // dereferenced value of a single cell reference or an immediate result // is stored as a single value. // Use an interim matrix to create the TypedStrData below. xMatRef = new ScMatrix(1,1); sal_uInt16 nErrCode = aValidationSrc.GetErrCode(); if (nErrCode) { /* TODO : to use later in an alert box? * String rStrResult = "..."; * rStrResult += ScGlobal::GetLongErrorString(nErrCode); */ xMatRef->PutError( nErrCode, 0); bOk = false; } else if (aValidationSrc.HasValueData()) xMatRef->PutDouble( aValidationSrc.GetValue(), 0); else { String aStr; aValidationSrc.GetString( aStr); xMatRef->PutString( aStr, 0); } pValues = xMatRef; } // which index matched. We will want it eventually to pre-select that item. rMatch = -1; SvNumberFormatter* pFormatter = GetDocument()->GetFormatTable(); bool bSortList = (mnListType == ValidListType::SORTEDASCENDING); SCSIZE nCol, nRow, nCols, nRows, n = 0; pValues->GetDimensions( nCols, nRows ); sal_Bool bRef = sal_False; ScRange aRange; ScTokenArray* pArr = (ScTokenArray*) &rTokArr; pArr->Reset(); ScToken* t = NULL; if (pArr->GetLen() == 1 && (t = static_cast<ScToken*>(pArr->GetNextReferenceOrName())) != NULL) { if (t->GetOpCode() == ocDBArea) { if( ScDBData* pDBData = pDocument->GetDBCollection()->FindIndex( t->GetIndex() ) ) { pDBData->GetArea(aRange); bRef = sal_True; } } else if (t->GetOpCode() == ocName) { ScRangeData* pName = pDocument->GetRangeName()->FindIndex( t->GetIndex() ); if (pName && pName->IsReference(aRange)) { bRef = sal_True; } } else if (t->GetType() != svIndex) { t->CalcAbsIfRel(rPos); if (pArr->IsValidReference(aRange)) { bRef = sal_True; } } } /* XL artificially limits things to a single col or row in the UI but does * not list the constraint in MOOXml. If a defined name or INDIRECT * resulting in 1D is entered in the UI and the definition later modified * to 2D, it is evaluated fine and also stored and loaded. Lets get ahead * of the curve and support 2d. In XL, values are listed row-wise, do the * same. */ for( nRow = 0; nRow < nRows ; nRow++ ) { for( nCol = 0; nCol < nCols ; nCol++ ) { ScTokenArray aCondTokArr; TypedStrData* pEntry = NULL; ScMatValType nMatValType; String aValStr; const ScMatrixValue* pMatVal = pValues->Get( nCol, nRow, nMatValType); // strings and empties if( NULL == pMatVal || ScMatrix::IsNonValueType( nMatValType ) ) { if( NULL != pMatVal ) aValStr = pMatVal->GetString(); if( NULL != pStrings ) pEntry = new TypedStrData( aValStr, 0.0, SC_STRTYPE_STANDARD); if( pCell && rMatch < 0 ) aCondTokArr.AddString( aValStr ); } else { sal_uInt16 nErr = pMatVal->GetError(); if( 0 != nErr ) { aValStr = ScGlobal::GetErrorString( nErr ); } else { // FIXME FIXME FIXME // Feature regression. Date formats are lost passing through the matrix //pFormatter->GetInputLineString( pMatVal->fVal, 0, aValStr ); //For external reference and a formula that results in an area or array, date formats are still lost. if ( bRef ) { pDocument->GetInputString((SCCOL)(nCol+aRange.aStart.Col()), (SCROW)(nRow+aRange.aStart.Row()), aRange.aStart.Tab() , aValStr); } else pFormatter->GetInputLineString( pMatVal->fVal, 0, aValStr ); } if( pCell && rMatch < 0 ) { // I am not sure errors will work here, but a user can no // manually enter an error yet so the point is somewhat moot. aCondTokArr.AddDouble( pMatVal->fVal ); } if( NULL != pStrings ) pEntry = new TypedStrData( aValStr, pMatVal->fVal, SC_STRTYPE_VALUE); } if( rMatch < 0 && NULL != pCell && IsEqualToTokenArray( pCell, rPos, aCondTokArr ) ) { rMatch = n; // short circuit on the first match if not filling the list if( NULL == pStrings ) return true; } if( NULL != pEntry ) { lclInsertStringToCollection( *pStrings, pEntry, bSortList ); n++; } } } // In case of no match needed and an error occurred, return that error // entry as valid instead of silently failing. return bOk || NULL == pCell; } bool ScValidationData::FillSelectionList( TypedScStrCollection& rStrColl, const ScAddress& rPos ) const { bool bOk = false; if( HasSelectionList() ) { ::std::auto_ptr< ScTokenArray > pTokArr( CreateTokenArry( 0 ) ); // *** try if formula is a string list *** bool bSortList = (mnListType == ValidListType::SORTEDASCENDING); sal_uInt32 nFormat = lclGetCellFormat( *GetDocument(), rPos ); ScStringTokenIterator aIt( *pTokArr ); for( const String* pString = aIt.First(); pString && aIt.Ok(); pString = aIt.Next() ) { double fValue; bool bIsValue = GetDocument()->GetFormatTable()->IsNumberFormat( *pString, nFormat, fValue ); TypedStrData* pData = new TypedStrData( *pString, fValue, bIsValue ? SC_STRTYPE_VALUE : SC_STRTYPE_STANDARD ); lclInsertStringToCollection( rStrColl, pData, bSortList ); } bOk = aIt.Ok(); // *** if not a string list, try if formula results in a cell range or // anything else we recognize as valid *** if (!bOk) { int nMatch; bOk = GetSelectionFromFormula( &rStrColl, NULL, rPos, *pTokArr, nMatch ); } } return bOk; } // ---------------------------------------------------------------------------- bool ScValidationData::IsEqualToTokenArray( ScBaseCell* pCell, const ScAddress& rPos, const ScTokenArray& rTokArr ) const { // create a condition entry that tests on equality and set the passed token array ScConditionEntry aCondEntry( SC_COND_EQUAL, &rTokArr, NULL, GetDocument(), rPos ); return aCondEntry.IsCellValid( pCell, rPos ); } bool ScValidationData::IsListValid( ScBaseCell* pCell, const ScAddress& rPos ) const { bool bIsValid = false; /* Compare input cell with all supported tokens from the formula. Currently a formula may contain: 1) A list of strings (at least one string). 2) A single cell or range reference. 3) A single defined name (must contain a cell/range reference, another name, or DB range, or a formula resulting in a cell/range reference or matrix/array). 4) A single database range. 5) A formula resulting in a cell/range reference or matrix/array. */ ::std::auto_ptr< ScTokenArray > pTokArr( CreateTokenArry( 0 ) ); // *** try if formula is a string list *** sal_uInt32 nFormat = lclGetCellFormat( *GetDocument(), rPos ); ScStringTokenIterator aIt( *pTokArr ); for( const String* pString = aIt.First(); pString && aIt.Ok(); pString = aIt.Next() ) { /* Do not break the loop, if a valid string has been found. This is to find invalid tokens following in the formula. */ if( !bIsValid ) { // create a formula containing a single string or number ScTokenArray aCondTokArr; double fValue; if( GetDocument()->GetFormatTable()->IsNumberFormat( *pString, nFormat, fValue ) ) aCondTokArr.AddDouble( fValue ); else aCondTokArr.AddString( *pString ); bIsValid = IsEqualToTokenArray( pCell, rPos, aCondTokArr ); } } if( !aIt.Ok() ) bIsValid = false; // *** if not a string list, try if formula results in a cell range or // anything else we recognize as valid *** if (!bIsValid) { int nMatch; bIsValid = GetSelectionFromFormula( NULL, pCell, rPos, *pTokArr, nMatch ); bIsValid = bIsValid && nMatch >= 0; } return bIsValid; } // ============================================================================ // ============================================================================ ScValidationDataList::ScValidationDataList(const ScValidationDataList& rList) : ScValidationEntries_Impl() { // fuer Ref-Undo - echte Kopie mit neuen Tokens! sal_uInt16 nCount = rList.Count(); for (sal_uInt16 i=0; i<nCount; i++) InsertNew( rList[i]->Clone() ); //! sortierte Eintraege aus rList schneller einfuegen ??? } ScValidationDataList::ScValidationDataList(ScDocument* pNewDoc, const ScValidationDataList& rList) { // fuer neues Dokument - echte Kopie mit neuen Tokens! sal_uInt16 nCount = rList.Count(); for (sal_uInt16 i=0; i<nCount; i++) InsertNew( rList[i]->Clone(pNewDoc) ); //! sortierte Eintraege aus rList schneller einfuegen ??? } ScValidationData* ScValidationDataList::GetData( sal_uInt32 nKey ) { //! binaer suchen sal_uInt16 nCount = Count(); for (sal_uInt16 i=0; i<nCount; i++) if ((*this)[i]->GetKey() == nKey) return (*this)[i]; DBG_ERROR("ScValidationDataList: Eintrag nicht gefunden"); return NULL; } void ScValidationDataList::CompileXML() { sal_uInt16 nCount = Count(); for (sal_uInt16 i=0; i<nCount; i++) (*this)[i]->CompileXML(); } void ScValidationDataList::UpdateReference( UpdateRefMode eUpdateRefMode, const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz ) { sal_uInt16 nCount = Count(); for (sal_uInt16 i=0; i<nCount; i++) (*this)[i]->UpdateReference( eUpdateRefMode, rRange, nDx, nDy, nDz); } void ScValidationDataList::UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos ) { sal_uInt16 nCount = Count(); for (sal_uInt16 i=0; i<nCount; i++) (*this)[i]->UpdateMoveTab( nOldPos, nNewPos ); } bool ScValidationDataList::MarkUsedExternalReferences() const { bool bAllMarked = false; sal_uInt16 nCount = Count(); for (sal_uInt16 i=0; !bAllMarked && i<nCount; i++) bAllMarked = (*this)[i]->MarkUsedExternalReferences(); return bAllMarked; } sal_Bool ScValidationDataList::operator==( const ScValidationDataList& r ) const { // fuer Ref-Undo - interne Variablen werden nicht verglichen sal_uInt16 nCount = Count(); sal_Bool bEqual = ( nCount == r.Count() ); for (sal_uInt16 i=0; i<nCount && bEqual; i++) // Eintraege sind sortiert if ( !(*this)[i]->EqualEntries(*r[i]) ) // Eintraege unterschiedlich ? bEqual = sal_False; return bEqual; }
13,198
984
<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.phoenix.expression; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.sql.SQLException; import java.util.List; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.io.WritableUtils; import org.apache.phoenix.expression.visitor.ExpressionVisitor; import org.apache.phoenix.schema.SortOrder; import org.apache.phoenix.schema.tuple.Tuple; import org.apache.phoenix.schema.types.PDataType; import org.apache.phoenix.thirdparty.com.google.common.base.Preconditions; import org.apache.phoenix.thirdparty.com.google.common.collect.ImmutableList; public class CoerceExpression extends BaseSingleExpression { private PDataType toType; private SortOrder toSortOrder; private Integer maxLength; private boolean rowKeyOrderOptimizable; public CoerceExpression() { } public static Expression create(Expression expression, PDataType toType) throws SQLException { if (toType == expression.getDataType()) { return expression; } return new CoerceExpression(expression, toType); } public static Expression create(Expression expression, PDataType toType, SortOrder toSortOrder, Integer maxLength) throws SQLException { return create(expression, toType, toSortOrder, maxLength, true); } public static Expression create(Expression expression, PDataType toType, SortOrder toSortOrder, Integer maxLength, boolean rowKeyOrderOptimizable) throws SQLException { if ( toType == expression.getDataType() && toSortOrder == expression.getSortOrder() && (maxLength == null || maxLength.equals(expression.getMaxLength())) ) { return expression; } return new CoerceExpression(expression, toType, toSortOrder, maxLength, rowKeyOrderOptimizable); } //Package protected for tests CoerceExpression(Expression expression, PDataType toType) { this(expression, toType, expression.getSortOrder(), null, true); } CoerceExpression(Expression expression, PDataType toType, SortOrder toSortOrder, Integer maxLength, boolean rowKeyOrderOptimizable) { this(ImmutableList.of(expression), toType, toSortOrder, maxLength, rowKeyOrderOptimizable); } public CoerceExpression(List<Expression> children, PDataType toType, SortOrder toSortOrder, Integer maxLength, boolean rowKeyOrderOptimizable) { super(children); Preconditions.checkNotNull(toSortOrder); this.toType = toType; this.toSortOrder = toSortOrder; this.maxLength = maxLength; this.rowKeyOrderOptimizable = rowKeyOrderOptimizable; } public CoerceExpression clone(List<Expression> children) { return new CoerceExpression(children, this.getDataType(), this.getSortOrder(), this.getMaxLength(), this.rowKeyOrderOptimizable); } @Override public Integer getMaxLength() { return maxLength; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((maxLength == null) ? 0 : maxLength.hashCode()); result = prime * result + ((toSortOrder == null) ? 0 : toSortOrder.hashCode()); result = prime * result + ((toType == null) ? 0 : toType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; CoerceExpression other = (CoerceExpression)obj; if (maxLength == null) { if (other.maxLength != null) return false; } else if (!maxLength.equals(other.maxLength)) return false; if (toSortOrder != other.toSortOrder) return false; if (toType == null) { if (other.toType != null) return false; } else if (!toType.equals(other.toType)) return false; return rowKeyOrderOptimizable == other.rowKeyOrderOptimizable; } @Override public void readFields(DataInput input) throws IOException { super.readFields(input); int ordinal = WritableUtils.readVInt(input); rowKeyOrderOptimizable = false; if (ordinal < 0) { rowKeyOrderOptimizable = true; ordinal = -(ordinal+1); } toType = PDataType.values()[ordinal]; toSortOrder = SortOrder.fromSystemValue(WritableUtils.readVInt(input)); int byteSize = WritableUtils.readVInt(input); this.maxLength = byteSize == -1 ? null : byteSize; } @Override public void write(DataOutput output) throws IOException { super.write(output); if (rowKeyOrderOptimizable) { WritableUtils.writeVInt(output, -(toType.ordinal()+1)); } else { WritableUtils.writeVInt(output, toType.ordinal()); } WritableUtils.writeVInt(output, toSortOrder.getSystemValue()); WritableUtils.writeVInt(output, maxLength == null ? -1 : maxLength); } @Override public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (getChild().evaluate(tuple, ptr)) { getDataType().coerceBytes(ptr, null, getChild().getDataType(), getChild().getMaxLength(), null, getChild().getSortOrder(), maxLength, null, getSortOrder(), rowKeyOrderOptimizable); return true; } return false; } @Override public PDataType getDataType() { return toType; } @Override public SortOrder getSortOrder() { return toSortOrder; } @Override public <T> T accept(ExpressionVisitor<T> visitor) { List<T> l = acceptChildren(visitor, visitor.visitEnter(this)); T t = visitor.visitLeave(this, l); if (t == null) { t = visitor.defaultReturn(this, l); } return t; } @Override public String toString() { StringBuilder buf = new StringBuilder("TO_" + toType.toString() + "("); for (int i = 0; i < children.size() - 1; i++) { buf.append(children.get(i) + ", "); } buf.append(children.get(children.size()-1) + ")"); return buf.toString(); } }
2,748
1,603
<reponame>pramodbiligiri/datahub<gh_stars>1000+ package com.linkedin.mxe; import com.linkedin.pegasus2avro.mxe.FailedMetadataChangeEvent; import com.linkedin.pegasus2avro.mxe.MetadataAuditEvent; import com.linkedin.pegasus2avro.mxe.MetadataChangeEvent; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.avro.Schema; public class Configs { public static final Map<String, String> FABRIC_SCHEMA_REGISTRY_MAP = Collections.unmodifiableMap(new HashMap<String, String>() { { put("ei", "http://1.schemaregistry.ei4.atd.int.linkedin.com:10252"); put("corp", "http://1.schemaregistry.corp-lca1.atd.corp.linkedin.com:10252"); } }); public static final Map<String, Schema> TOPIC_SCHEMA_MAP = Collections.unmodifiableMap(new HashMap<String, Schema>() { { put(Topics.METADATA_AUDIT_EVENT, MetadataAuditEvent.SCHEMA$); put(Topics.METADATA_CHANGE_EVENT, MetadataChangeEvent.SCHEMA$); put(Topics.FAILED_METADATA_CHANGE_EVENT, FailedMetadataChangeEvent.SCHEMA$); put(Topics.DEV_METADATA_AUDIT_EVENT, MetadataAuditEvent.SCHEMA$); put(Topics.DEV_METADATA_CHANGE_EVENT, MetadataChangeEvent.SCHEMA$); put(Topics.DEV_FAILED_METADATA_CHANGE_EVENT, FailedMetadataChangeEvent.SCHEMA$); } }); private Configs() { // Util class } }
575
369
<reponame>bitigchi/MuditaOS // Copyright (c) 2017-2021, Mudita <NAME>.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include "DBMessage.hpp" #include <MessageType.hpp> #include <cstdint> #include <string> class DBServiceMessageBackup : public DBMessage { public: DBServiceMessageBackup(MessageType messageType, std::string backupPath); std::string backupPath; }; class DBServiceResponseMessage : public DBResponseMessage { public: DBServiceResponseMessage(uint32_t retCode = 0, uint32_t count = 0, MessageType respTo = MessageType::MessageTypeUninitialized); };
293
3,301
package com.alibaba.alink.params.regression; import com.alibaba.alink.params.shared.colname.HasVectorColDefaultAsNull; /** * parameters of linear regression predictor. */ public interface LinearRegPredictParams<T> extends RegPredictParams <T>, HasVectorColDefaultAsNull <T> { }
90
6,035
<reponame>okasurya/react-native-code-push<gh_stars>1000+ // // JWTAlgorithmESBase.h // Pods // // Created by <NAME> on 12.02.17. // // #import <Foundation/Foundation.h> #import "JWTRSAlgorithm.h" extern NSString *const JWTAlgorithmNameES256; extern NSString *const JWTAlgorithmNameES384; extern NSString *const JWTAlgorithmNameES512; @interface JWTAlgorithmESBase : NSObject @end @interface JWTAlgorithmESBase (JWTAsymmetricKeysAlgorithm) <JWTAsymmetricKeysAlgorithm> @end @interface JWTAlgorithmESBase (Create) + (instancetype)algorithm256; + (instancetype)algorithm384; + (instancetype)algorithm512; @end
234
310
<gh_stars>100-1000 { "name": "ThinkPad X220i", "description": "A 12.5 inch PC laptop.", "url": "http://www.thinkwiki.org/wiki/Category:X220i" }
61
1,738
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include "PanelDisplayHide.h" #include "DisplaySettings.h" #include <ui_PanelDisplayHide.h> ///////////////////////////////////////////////////////////////////////////// // CPanelDisplayHide dialog CPanelDisplayHide::CPanelDisplayHide(QWidget* pParent /*=nullptr*/) : QWidget(pParent) , ui(new Ui::CPanelDisplayHide) , m_initialized(false) { ui->setupUi(this); connect(ui->HIDE_ALL, &QPushButton::clicked, this, &CPanelDisplayHide::OnHideAll); connect(ui->HIDE_NONE, &QPushButton::clicked, this, &CPanelDisplayHide::OnHideNone); connect(ui->HIDE_INVERT, &QPushButton::clicked, this, &CPanelDisplayHide::OnHideInvert); connect(ui->HIDE_ENTITY, &QCheckBox::clicked, this, &CPanelDisplayHide::OnChangeHideMask); connect(ui->HIDE_PREFABS, &QCheckBox::clicked, this, &CPanelDisplayHide::OnChangeHideMask); connect(ui->HIDE_GROUP, &QCheckBox::clicked, this, &CPanelDisplayHide::OnChangeHideMask); connect(ui->HIDE_PATH, &QCheckBox::clicked, this, &CPanelDisplayHide::OnChangeHideMask); connect(ui->HIDE_TAGPOINT, &QCheckBox::clicked, this, &CPanelDisplayHide::OnChangeHideMask); connect(ui->HIDE_VOLUME, &QCheckBox::clicked, this, &CPanelDisplayHide::OnChangeHideMask); connect(ui->HIDE_BRUSH, &QCheckBox::clicked, this, &CPanelDisplayHide::OnChangeHideMask); connect(ui->HIDE_DECALS, &QCheckBox::clicked, this, &CPanelDisplayHide::OnChangeHideMask); connect(ui->HIDE_SOLIDS, &QCheckBox::clicked, this, &CPanelDisplayHide::OnChangeHideMask); connect(ui->HIDE_GEOMCACHES, &QCheckBox::clicked, this, &CPanelDisplayHide::OnChangeHideMask); connect(ui->HIDE_ROADS, &QCheckBox::clicked, this, &CPanelDisplayHide::OnChangeHideMask); connect(ui->HIDE_OTHER, &QCheckBox::clicked, this, &CPanelDisplayHide::OnChangeHideMask); //KDAB--no resource found for these checkboxes. //connect(ui->HIDE_BUILDING, &QCheckBox::toggled, this, &CPanelDisplayHide::OnChangeHideMask); //connect(ui->HIDE_SOUND, &QCheckBox::toggled, this, &CPanelDisplayHide::OnChangeHideMask); //connect(ui->HIDE_STATOBJ, &QCheckBox::toggled, this, &CPanelDisplayHide::OnChangeHideMask); GetIEditor()->RegisterNotifyListener(this); } CPanelDisplayHide::~CPanelDisplayHide() { GetIEditor()->UnregisterNotifyListener(this); } ///////////////////////////////////////////////////////////////////////////// // CPanelDisplayHide message handlers void CPanelDisplayHide::showEvent(QShowEvent* e) { QWidget::showEvent(e); if (!m_initialized) { m_initialized = true; m_mask = GetIEditor()->GetDisplaySettings()->GetObjectHideMask(); SetCheckButtons(); } } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayHide::SetMask() { GetIEditor()->GetDisplaySettings()->SetObjectHideMask(m_mask); GetIEditor()->GetObjectManager()->InvalidateVisibleList(); GetIEditor()->UpdateViews(eUpdateObjects); } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayHide::OnHideAll() { m_mask = 0xFFFFFFFF; SetCheckButtons(); SetMask(); } void CPanelDisplayHide::OnHideNone() { m_mask = 0; SetCheckButtons(); SetMask(); } void CPanelDisplayHide::OnHideInvert() { m_mask = ~m_mask; SetCheckButtons(); SetMask(); } void CPanelDisplayHide::SetCheckButtons() { // Check or uncheck buttons. ui->HIDE_ENTITY->setChecked(m_mask & OBJTYPE_ENTITY); ui->HIDE_PREFABS->setChecked(m_mask & OBJTYPE_PREFAB); ui->HIDE_GROUP->setChecked(m_mask & OBJTYPE_GROUP); ui->HIDE_TAGPOINT->setChecked(m_mask & OBJTYPE_TAGPOINT); ui->HIDE_PATH->setChecked(m_mask & OBJTYPE_SHAPE); ui->HIDE_VOLUME->setChecked(m_mask & OBJTYPE_VOLUME); ui->HIDE_BRUSH->setChecked(m_mask & OBJTYPE_BRUSH); ui->HIDE_AIPOINT->setChecked(m_mask & OBJTYPE_AIPOINT); ui->HIDE_DECALS->setChecked(m_mask & OBJTYPE_DECAL); ui->HIDE_SOLIDS->setChecked((m_mask & OBJTYPE_SOLID) | (m_mask & OBJTYPE_VOLUMESOLID)); ui->HIDE_ROADS->setChecked(m_mask & OBJTYPE_ROAD); ui->HIDE_GEOMCACHES->setChecked(m_mask & OBJTYPE_GEOMCACHE); ui->HIDE_OTHER->setChecked(m_mask & OBJTYPE_OTHER); } void CPanelDisplayHide::OnChangeHideMask() { // TODO: Add your control notification handler code here m_mask = 0; // Check or uncheck buttons. m_mask |= ui->HIDE_ENTITY->isChecked() ? OBJTYPE_ENTITY : 0; m_mask |= ui->HIDE_PREFABS->isChecked() ? OBJTYPE_PREFAB : 0; m_mask |= ui->HIDE_GROUP->isChecked() ? OBJTYPE_GROUP : 0; m_mask |= ui->HIDE_TAGPOINT->isChecked() ? OBJTYPE_TAGPOINT : 0; m_mask |= ui->HIDE_AIPOINT->isChecked() ? OBJTYPE_AIPOINT : 0; m_mask |= ui->HIDE_PATH->isChecked() ? OBJTYPE_SHAPE : 0; m_mask |= ui->HIDE_VOLUME->isChecked() ? OBJTYPE_VOLUME : 0; m_mask |= ui->HIDE_BRUSH->isChecked() ? OBJTYPE_BRUSH : 0; m_mask |= ui->HIDE_DECALS->isChecked() ? OBJTYPE_DECAL : 0; m_mask |= ui->HIDE_SOLIDS->isChecked() ? OBJTYPE_SOLID | OBJTYPE_VOLUMESOLID : 0; m_mask |= ui->HIDE_ROADS->isChecked() ? OBJTYPE_ROAD : 0; m_mask |= ui->HIDE_GEOMCACHES->isChecked() ? OBJTYPE_GEOMCACHE : 0; m_mask |= ui->HIDE_OTHER->isChecked() ? OBJTYPE_OTHER : 0; SetMask(); } void CPanelDisplayHide::OnEditorNotifyEvent(EEditorNotifyEvent event) { switch (event) { case eNotify_OnDisplayRenderUpdate: m_mask = GetIEditor()->GetDisplaySettings()->GetObjectHideMask(); SetCheckButtons(); break; } } #include <PanelDisplayHide.moc>
2,391
305
// // Copyright(c) 2016-2017 benikabocha. // Distributed under the MIT License (http://opensource.org/licenses/MIT) // #ifndef SABA_VIEWER_SHADOWMAP_H_ #define SABA_VIEWER_SHADOWMAP_H_ #include <Saba/GL/GLObject.h> #include <Saba/GL/GLSLUtil.h> #include <vector> #include <glm/mat4x4.hpp> namespace saba { class Camera; class Light; class ViewerContext; struct ShadowMapShader { GLProgramObject m_prog; // attribute GLint m_inPos; // uniform GLint m_uWVP; void Initialize(); }; class ShadowMap { public: ShadowMap(); ShadowMap(const ShadowMap&) = delete; ShadowMap& operator = (const ShadowMap&) = delete; bool InitializeShader(ViewerContext* ctxt); bool Setup(int width, int height, size_t splitCount); void CalcShadowMap(const Camera* camera, const Light* light); const glm::mat4 GetShadowViewMatrix() const { return m_view; } struct ClipSpace { float m_nearClip; float m_farClip; glm::mat4 m_projection; GLTextureObject m_shadomap; GLFramebufferObject m_shadowmapFBO; }; size_t GetClipSpaceCount() const; const ClipSpace& GetClipSpace(size_t i) const; const ShadowMapShader* GetShader() const; int GetWidth() const; int GetHeight() const; size_t GetShadowMapCount() const; void SetClip(float nearClip, float farClip); float GetNearClip() const; float GetFarClip() const; size_t GetSplitPositionCount() const; const float* GetSplitPositions() const; void SetBias(float bias); float GetBias() const; private: void CalcSplitPositions(float nearClip, float farClip, float lamda); private: glm::mat4 m_view; std::vector<ClipSpace> m_clipSpaces; std::vector<float> m_splitPositions; size_t m_splitCount; ShadowMapShader m_shader; int m_width; int m_height; float m_nearClip; float m_farClip; float m_bias; }; } #endif // !SABA_VIEWER_SHADOWMAP_H_
810
1,615
/** * Created by MomoLuaNative. * Copyright (c) 2019, Momo Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.immomo.mls.global; import android.content.Context; import java.io.File; /** * Created by XiongFangyu on 2018/6/19. */ public class LVConfigBuilder { private Context context; private File rootDir; private File cacheDir; private File imageDir; private File sdcardDir; private String globalResourceDir; public LVConfigBuilder(Context context) { this.context = context.getApplicationContext(); } public LVConfigBuilder setRootDir(String path) { this.rootDir = new File(path); return this; } public LVConfigBuilder setCacheDir(String path) { this.cacheDir = new File(path); return this; } public LVConfigBuilder setImageDir(String path) { this.imageDir = new File(path); return this; } public LVConfigBuilder setGlobalResourceDir(String dir) { this.globalResourceDir = dir; return this; } public LVConfigBuilder setSdcardDir(String dir) { sdcardDir = new File(dir); return this; } public LVConfig build() { LVConfig config = new LVConfig(); config.context = context; config.rootDir = rootDir; config.cacheDir = cacheDir; config.imageDir = imageDir; config.globalResourceDir = globalResourceDir; config.sdcardDir = sdcardDir; return config; } }
614
602
package org.corfudb.runtime.utils; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; import static org.corfudb.runtime.view.Layout.ReplicationMode.CHAIN_REPLICATION; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableMap; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.stream.LongStream; import lombok.Data; import org.corfudb.protocols.wireprotocol.StreamsAddressResponse; import org.corfudb.protocols.wireprotocol.TailsResponse; import org.corfudb.runtime.clients.LogUnitClient; import org.corfudb.runtime.exceptions.WrongEpochException; import org.corfudb.runtime.view.Layout; import org.corfudb.runtime.view.RuntimeLayout; import org.corfudb.runtime.view.stream.StreamAddressSpace; import org.corfudb.util.Utils; import org.junit.Test; public class UtilsTest { private static String nodeA = "nodeA"; private static String nodeB = "nodeB"; private static String nodeC = "nodeC"; @Data class Context { private final Map<String, LogUnitClient> clientMap; private final RuntimeLayout runtimeLayout; public LogUnitClient getLogUnitClient(String node) { return clientMap.get(node); } } private Layout getLayout() { long epoch = 1; UUID uuid = UUID.randomUUID(); Layout.LayoutStripe stripe = new Layout.LayoutStripe(Arrays.asList(nodeA, nodeB, nodeC)); Layout.LayoutSegment segment = new Layout.LayoutSegment(CHAIN_REPLICATION, 0L, -1L, Collections.singletonList(stripe)); return new Layout( Arrays.asList(nodeA, nodeB, nodeC), Arrays.asList(nodeA, nodeB, nodeC), Collections.singletonList(segment), Collections.EMPTY_LIST, epoch, uuid); } @SuppressWarnings("checkstyle:magicnumber") private Layout getSegmentedLayout() { long epoch = 1; UUID uuid = UUID.randomUUID(); Layout.LayoutStripe seg1Strip = new Layout.LayoutStripe(Arrays.asList(nodeA)); Layout.LayoutStripe seg2Strip = new Layout.LayoutStripe(Arrays.asList(nodeA, nodeB)); Layout.LayoutStripe seg3Strip = new Layout.LayoutStripe(Arrays.asList(nodeB, nodeA)); Layout.LayoutSegment segment1 = new Layout.LayoutSegment( CHAIN_REPLICATION, 0L, 100L, Collections.singletonList(seg1Strip)); Layout.LayoutSegment segment2 = new Layout.LayoutSegment( CHAIN_REPLICATION, 100L, 200L, Collections.singletonList(seg2Strip)); Layout.LayoutSegment segment3 = new Layout.LayoutSegment( CHAIN_REPLICATION, 200L, -1L, Collections.singletonList(seg3Strip)); return new Layout( Arrays.asList(nodeA, nodeB, nodeC), Arrays.asList(nodeA, nodeB, nodeC), Arrays.asList(segment1, segment2, segment3), Collections.singletonList(nodeC), epoch, uuid); } @SuppressWarnings("checkstyle:magicnumber") private Context getContext(Layout layout) { RuntimeLayout runtimeLayout = mock(RuntimeLayout.class); when(runtimeLayout.getLayout()).thenReturn(layout); Map<String, LogUnitClient> clientMap = new HashMap<>(); layout.getAllLogServers().forEach(lu -> clientMap.put(lu, mock(LogUnitClient.class))); when(runtimeLayout.getLogUnitClient(anyString())) .then( invokation -> { String node = (String) invokation.getArguments()[0]; if (!clientMap.containsKey(node)) { throw new IllegalStateException("not expecting a call to " + node); } return clientMap.get(node); }); return new Context(clientMap, runtimeLayout); } private CompletableFuture<TailsResponse> getTailsResponse( long globalTail, Map<UUID, Long> streamTails, long epoch) { CompletableFuture<TailsResponse> cf = new CompletableFuture<>(); TailsResponse resp = new TailsResponse(globalTail, streamTails); resp.setEpoch(epoch); cf.complete(resp); return cf; } private CompletableFuture<StreamsAddressResponse> getLogAddressSpaceResponse( long globalTail, Map<UUID, StreamAddressSpace> streamTails, long epoch) { CompletableFuture<StreamsAddressResponse> cf = new CompletableFuture<>(); StreamsAddressResponse resp = new StreamsAddressResponse(globalTail, streamTails); resp.setEpoch(epoch); // TODO(Maithem) add epoch? cf.complete(resp); return cf; } private CompletableFuture<TailsResponse> getTailsResponse(long globalTail, long epoch) { return getTailsResponse(globalTail, Collections.EMPTY_MAP, epoch); } @Test @SuppressWarnings("checkstyle:magicnumber") public void getLogTailSingleSegmentTest() { Layout layout = getLayout(); Context ctx = getContext(layout); final long globalTail = 5; when(ctx.getLogUnitClient(nodeA).getLogTail()) .thenReturn(getTailsResponse(globalTail, layout.getEpoch())); long logTail = Utils.getLogTail(ctx.getRuntimeLayout()); assertThat(logTail).isEqualTo(globalTail); verify(ctx.getLogUnitClient(nodeA), times(1)).getLogTail(); verify(ctx.getRuntimeLayout(), times(1)).getLogUnitClient(nodeA); verify(ctx.getRuntimeLayout(), times(0)).getLogUnitClient(nodeB); verify(ctx.getRuntimeLayout(), times(0)).getLogUnitClient(nodeC); final long invalidEpoch = layout.getEpoch() + 1; when(ctx.getLogUnitClient(nodeA).getLogTail()) .thenReturn(getTailsResponse(globalTail, invalidEpoch)); assertThatThrownBy(() -> Utils.getLogTail(ctx.getRuntimeLayout())) .isInstanceOf(WrongEpochException.class); } @Test @SuppressWarnings("checkstyle:magicnumber") public void getLogTailMultiSegmentTest() { Layout layout = getSegmentedLayout(); Context ctx = getContext(layout); final long nodeAGlobalTail = 5; final long nodeBGlobalTail = 150; when(ctx.getLogUnitClient(nodeA).getLogTail()) .thenReturn(getTailsResponse(nodeAGlobalTail, layout.getEpoch())); when(ctx.getLogUnitClient(nodeB).getLogTail()) .thenReturn(getTailsResponse(nodeBGlobalTail, layout.getEpoch())); final long logTail = Utils.getLogTail(ctx.getRuntimeLayout()); assertThat(logTail).isEqualTo(nodeBGlobalTail); verify(ctx.getLogUnitClient(nodeA), times(1)).getLogTail(); verify(ctx.getRuntimeLayout(), times(1)).getLogUnitClient(nodeA); // Since we coalesce the same node on multiple segments and nodeB is the head of segment2 // and segment3 we need to verify that it is only queried once verify(ctx.getLogUnitClient(nodeB), times(1)).getLogTail(); verify(ctx.getRuntimeLayout(), times(1)).getLogUnitClient(nodeB); verify(ctx.getRuntimeLayout(), times(0)).getLogUnitClient(nodeC); when(ctx.getLogUnitClient(nodeA).getLogTail()) .thenReturn(getTailsResponse(nodeAGlobalTail, layout.getEpoch() + 1)); assertThatThrownBy(() -> Utils.getLogTail(ctx.getRuntimeLayout())) .isInstanceOf(WrongEpochException.class); } @Test @SuppressWarnings("checkstyle:magicnumber") public void getAllTailsSingleSegmentTest() { Layout layout = getLayout(); Context ctx = getContext(layout); final long globalTail = 20; Map<UUID, Long> streamTails = ImmutableMap.of(UUID.randomUUID(), 5L, UUID.randomUUID(), 10L, UUID.randomUUID(), 15L); when(ctx.getLogUnitClient(nodeA).getAllTails()) .thenReturn(getTailsResponse(globalTail, streamTails, layout.getEpoch())); TailsResponse tails = Utils.getAllTails(ctx.getRuntimeLayout()); assertThat(tails.getLogTail()).isEqualTo(globalTail); assertThat(tails.getStreamTails()).isEqualTo(streamTails); assertThat(tails.getEpoch()).isEqualTo(layout.getEpoch()); verify(ctx.getLogUnitClient(nodeA), times(1)).getAllTails(); verify(ctx.getRuntimeLayout(), times(1)).getLogUnitClient(nodeA); verify(ctx.getRuntimeLayout(), times(0)).getLogUnitClient(nodeB); verify(ctx.getRuntimeLayout(), times(0)).getLogUnitClient(nodeC); when(ctx.getLogUnitClient(nodeA).getAllTails()) .thenReturn(getTailsResponse(globalTail, streamTails, layout.getEpoch() + 1)); assertThatThrownBy(() -> Utils.getAllTails(ctx.getRuntimeLayout())) .isInstanceOf(WrongEpochException.class); } @Test @SuppressWarnings("checkstyle:magicnumber") public void getAllTailsMultiSegmentTest() { Layout layout = getSegmentedLayout(); Context ctx = getContext(layout); final long nodeAGlobalTail = 15; final long nodeBGlobalTail = 215; UUID s1Id = UUID.randomUUID(); UUID s2Id = UUID.randomUUID(); UUID s3Id = UUID.randomUUID(); UUID s4Id = UUID.randomUUID(); Map<UUID, Long> nodeAStreamTails = ImmutableMap.of(s1Id, 5L, s2Id, 10L, s4Id, 12L); Map<UUID, Long> nodeBStreamTails = ImmutableMap.of(s1Id, 5L, s2Id, 103L, s3Id, 210L); when(ctx.getLogUnitClient(nodeA).getAllTails()) .thenReturn(getTailsResponse(nodeAGlobalTail, nodeAStreamTails, layout.getEpoch())); when(ctx.getLogUnitClient(nodeB).getAllTails()) .thenReturn(getTailsResponse(nodeBGlobalTail, nodeBStreamTails, layout.getEpoch())); TailsResponse tails = Utils.getAllTails(ctx.getRuntimeLayout()); assertThat(tails.getLogTail()).isEqualTo(nodeBGlobalTail); assertThat(tails.getStreamTails()) .isEqualTo(ImmutableMap.of(s1Id, 5L, s2Id, 103L, s3Id, 210L, s4Id, 12L)); assertThat(tails.getEpoch()).isEqualTo(layout.getEpoch()); verify(ctx.getLogUnitClient(nodeA), times(1)).getAllTails(); verify(ctx.getRuntimeLayout(), times(1)).getLogUnitClient(nodeA); verify(ctx.getLogUnitClient(nodeB), times(1)).getAllTails(); verify(ctx.getRuntimeLayout(), times(1)).getLogUnitClient(nodeB); verify(ctx.getRuntimeLayout(), times(0)).getLogUnitClient(nodeC); when(ctx.getLogUnitClient(nodeA).getAllTails()) .thenReturn(getTailsResponse(nodeAGlobalTail, nodeAStreamTails, layout.getEpoch() + 1)); assertThatThrownBy(() -> Utils.getAllTails(ctx.getRuntimeLayout())) .isInstanceOf(WrongEpochException.class); } private StreamAddressSpace getRandomStreamSpace(long max) { StreamAddressSpace streamA = new StreamAddressSpace(); LongStream.range(0, max) .forEach(address -> streamA.addAddress(((address & 0x1) == 1) ? 0 : address)); return streamA; } @Test @SuppressWarnings("checkstyle:magicnumber") public void getLogAddressSpaceSingleSegmentTest() { Layout layout = getLayout(); Context ctx = getContext(layout); final long nodeAGlobalTail = 50; UUID s1Id = UUID.randomUUID(); UUID s2Id = UUID.randomUUID(); Map<UUID, StreamAddressSpace> nodeALogAddressSpace = ImmutableMap.of( s1Id, getRandomStreamSpace(nodeAGlobalTail - 1), s2Id, getRandomStreamSpace(nodeAGlobalTail - 1)); when(ctx.getLogUnitClient(nodeA).getLogAddressSpace()) .thenReturn( getLogAddressSpaceResponse(nodeAGlobalTail, nodeALogAddressSpace, layout.getEpoch())); StreamsAddressResponse resp = Utils.getLogAddressSpace(ctx.getRuntimeLayout()); assertThat(resp.getLogTail()).isEqualTo(nodeAGlobalTail); assertThat(resp.getAddressMap()).isEqualTo(nodeALogAddressSpace); verify(ctx.getLogUnitClient(nodeA), times(1)).getLogAddressSpace(); verify(ctx.getRuntimeLayout(), times(1)).getLogUnitClient(nodeA); verify(ctx.getRuntimeLayout(), times(0)).getLogUnitClient(nodeB); verify(ctx.getRuntimeLayout(), times(0)).getLogUnitClient(nodeC); when(ctx.getLogUnitClient(nodeA).getLogAddressSpace()) .thenReturn( getLogAddressSpaceResponse( nodeAGlobalTail, nodeALogAddressSpace, layout.getEpoch() + 1)); assertThatThrownBy(() -> Utils.getLogAddressSpace(ctx.getRuntimeLayout())) .isInstanceOf(WrongEpochException.class); } @Test @SuppressWarnings("checkstyle:magicnumber") public void getLogAddressSpaceMultiSegmentTest() { Layout layout = getSegmentedLayout(); Context ctx = getContext(layout); final long nodeAGlobalTail = 50; UUID s1Id = UUID.randomUUID(); UUID s2Id = UUID.randomUUID(); Map<UUID, StreamAddressSpace> nodeALogAddressSpace = ImmutableMap.of( s1Id, getRandomStreamSpace(nodeAGlobalTail - 1), s2Id, getRandomStreamSpace(nodeAGlobalTail - 1)); UUID s3Id = UUID.randomUUID(); final long nodeBGlobalTail = 205; StreamAddressSpace s2IdPartial = nodeALogAddressSpace.get(s2Id).copy(); s2IdPartial.trim(30L); s2IdPartial.addAddress(201L); s2IdPartial.addAddress(202L); s2IdPartial.addAddress(203L); Map<UUID, StreamAddressSpace> nodeBLogAddressSpace = ImmutableMap.of(s2Id, s2IdPartial, s3Id, getRandomStreamSpace(nodeAGlobalTail - 1)); when(ctx.getLogUnitClient(nodeA).getLogAddressSpace()) .thenReturn( getLogAddressSpaceResponse(nodeAGlobalTail, nodeALogAddressSpace, layout.getEpoch())); when(ctx.getLogUnitClient(nodeB).getLogAddressSpace()) .thenReturn( getLogAddressSpaceResponse(nodeBGlobalTail, nodeBLogAddressSpace, layout.getEpoch())); StreamsAddressResponse resp = Utils.getLogAddressSpace(ctx.getRuntimeLayout()); assertThat(resp.getLogTail()).isEqualTo(nodeBGlobalTail); Map<UUID, StreamAddressSpace> expectedMergedTails = ImmutableMap.of( s1Id, nodeALogAddressSpace.get(s1Id), s2Id, s2IdPartial, s3Id, nodeBLogAddressSpace.get(s3Id)); assertThat(resp.getAddressMap()).isEqualTo(expectedMergedTails); verify(ctx.getLogUnitClient(nodeA), times(1)).getLogAddressSpace(); verify(ctx.getLogUnitClient(nodeB), times(1)).getLogAddressSpace(); verify(ctx.getRuntimeLayout(), times(1)).getLogUnitClient(nodeA); verify(ctx.getRuntimeLayout(), times(1)).getLogUnitClient(nodeB); verify(ctx.getRuntimeLayout(), times(0)).getLogUnitClient(nodeC); when(ctx.getLogUnitClient(nodeA).getLogAddressSpace()) .thenReturn( getLogAddressSpaceResponse( nodeAGlobalTail, nodeALogAddressSpace, layout.getEpoch() + 1)); assertThatThrownBy(() -> Utils.getLogAddressSpace(ctx.getRuntimeLayout())) .isInstanceOf(WrongEpochException.class); } }
5,972
2,145
from spektral.utils import misc def test_misc(): l = [1, [2, 3], [4]] flattened = misc.flatten_list(l) assert flattened == [1, 2, 3, 4]
64
2,494
<reponame>jxcore/jxcore<gh_stars>1000+ // Copyright & License details are available under JXCORE_LICENSE file #ifndef SRC_JX_PROXY_H_ #define SRC_JX_PROXY_H_ #include <string> #include <stdlib.h> #if defined(__ANDROID__) && defined(JXCORE_EMBEDDED) #ifndef JXCORE_ALOG_TAG #define JXCORE_ALOG_TAG "jxcore-log" #endif #include <android/log.h> #define log_console(...) \ __android_log_print(ANDROID_LOG_INFO, JXCORE_ALOG_TAG, __VA_ARGS__) #define flush_console(...) \ __android_log_print(ANDROID_LOG_INFO, JXCORE_ALOG_TAG, __VA_ARGS__) #define error_console(...) \ __android_log_print(ANDROID_LOG_ERROR, JXCORE_ALOG_TAG, __VA_ARGS__) #define warn_console(...) \ __android_log_print(ANDROID_LOG_WARN, JXCORE_ALOG_TAG, __VA_ARGS__) #elif defined(WINONECORE) #include <windows.h> static inline void DebuggerOutput_(const char* ctstr, ...) { char *str = (char*) malloc(65536 * sizeof(char)); if (str == NULL) { if (IsDebuggerPresent()) { OutputDebugStringA("jxcore :: Unable to log (Out of memory)"); } else { printf("jxcore :: Unable to log (Out of memory)\n"); } return; } va_list ap; va_start(ap, ctstr); const unsigned pos = vsnprintf(str, 65536, ctstr, ap); va_end(ap); str[pos] = '\0'; if (IsDebuggerPresent()) { OutputDebugStringA(str); free(str); } else { CHAR Buffer[256]; DWORD length = GetTempPathA(256, Buffer); if (length == 0) { printf("jxcore :: Could not get the temp folder\n"); free(str); return; } memcpy(Buffer + length, "\\jxcore-windows.log", sizeof(CHAR) * 19); Buffer[length + 19] = CHAR(0); HANDLE hFile = CreateFile(Buffer, FILE_APPEND_DATA, // open for writing FILE_SHARE_READ, // allow multiple readers NULL, // no security OPEN_ALWAYS, // open or create FILE_ATTRIBUTE_NORMAL, // normal file NULL); if (hFile == INVALID_HANDLE_VALUE) { printf("jxcore :: Could not open jxcore-windows.log file\n"); free(str); return; } DWORD dwBytesWritten; unsigned size_left = pos; char *tmp = str; while (size_left > 0) { WriteFile(hFile, str, size_left, &dwBytesWritten, NULL); size_left -= dwBytesWritten; str += dwBytesWritten; } free(tmp); CloseHandle(hFile); } } #define log_console(...) DebuggerOutput_(__VA_ARGS__) #define warn_console(...) DebuggerOutput_(__VA_ARGS__) #define error_console(...) DebuggerOutput_(__VA_ARGS__) #define flush_console(...) DebuggerOutput_(__VA_ARGS__) #else #define log_console(...) fprintf(stdout, __VA_ARGS__) #define flush_console(...) \ do { \ fprintf(stdout, __VA_ARGS__); \ fflush(stdout); \ } while (0) #define error_console(...) fprintf(stderr, __VA_ARGS__) #define warn_console(...) fprintf(stderr, __VA_ARGS__) #endif #endif
1,288
1,056
<reponame>timfel/netbeans /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.test.java.editor.codegeneration; import junit.framework.Test; import junit.textui.TestRunner; import org.netbeans.jellytools.EditorOperator; import org.netbeans.jellytools.modules.java.editor.GenerateCodeOperator; import org.netbeans.jemmy.operators.JTreeOperator; import org.netbeans.junit.NbModuleSuite; import org.netbeans.test.java.editor.jelly.GenerateGettersAndSettersOperator; /** * * @author jp159440 */ public class CreateGetterSetterTest extends GenerateCodeTestCase { public CreateGetterSetterTest(String testMethodName) { super(testMethodName); } public void testAvailableGettersSetters() { openSourceFile("org.netbeans.test.java.editor.codegeneration", "CreateGetterSetter"); editor = new EditorOperator("CreateGetterSetter"); txtOper = editor.txtEditorPane(); try { editor.requestFocus(); editor.setCaretPosition(11, 1); GenerateCodeOperator.openDialog(GenerateCodeOperator.GENERATE_GETTER_SETTER,editor); GenerateGettersAndSettersOperator ggso = new GenerateGettersAndSettersOperator(GenerateGettersAndSettersOperator.GETTERS_AND_SETTERS); JTreeOperator jto = ggso.treeTreeView$ExplorerTree(); int rowCount = jto.getRowCount(); ggso.cancel(); assertEquals("Wrong number of rows",5,rowCount); } finally { editor.close(false); } } public void testAvailableGetters() { openSourceFile("org.netbeans.test.java.editor.codegeneration", "CreateGetterSetter"); editor = new EditorOperator("CreateGetterSetter"); txtOper = editor.txtEditorPane(); try { editor.requestFocus(); editor.setCaretPosition(11, 1); GenerateCodeOperator.openDialog(GenerateCodeOperator.GENERATE_GETTER, editor); GenerateGettersAndSettersOperator ggso = new GenerateGettersAndSettersOperator(GenerateGettersAndSettersOperator.GETTERS_ONLY); JTreeOperator jto = ggso.treeTreeView$ExplorerTree(); int rowCount = jto.getRowCount(); ggso.cancel(); assertEquals("Wrong number of rows",6,rowCount); } finally { editor.close(false); } } public void testAvailableSetters() { openSourceFile("org.netbeans.test.java.editor.codegeneration", "CreateGetterSetter"); editor = new EditorOperator("CreateGetterSetter"); txtOper = editor.txtEditorPane(); try { editor.requestFocus(); editor.setCaretPosition(11, 1); GenerateCodeOperator.openDialog(GenerateCodeOperator.GENERATE_SETTER,editor); GenerateGettersAndSettersOperator ggso = new GenerateGettersAndSettersOperator(GenerateGettersAndSettersOperator.SETTERS_ONLY); JTreeOperator jto = ggso.treeTreeView$ExplorerTree(); int rowCount = jto.getRowCount(); ggso.cancel(); assertEquals("Wrong number of rows",6,rowCount); } finally { editor.close(false); } } public void testPrimitiveType() { openSourceFile("org.netbeans.test.java.editor.codegeneration", "CreateGetterSetter"); editor = new EditorOperator("CreateGetterSetter"); txtOper = editor.txtEditorPane(); try { editor.requestFocus(); editor.setCaretPosition(11, 1); GenerateCodeOperator.openDialog(GenerateCodeOperator.GENERATE_GETTER_SETTER,editor); GenerateGettersAndSettersOperator ggso = new GenerateGettersAndSettersOperator(GenerateGettersAndSettersOperator.GETTERS_AND_SETTERS); JTreeOperator jto = ggso.treeTreeView$ExplorerTree(); jto.selectRow(2); ggso.generate(); String expected = "" + " public int getNum() {\n"+ " return num;\n"+ " }\n"+ "\n"+ " public void setNum(int num) {\n"+ " this.num = num;\n"+ " }\n"; waitAndCompare(expected); } finally { editor.close(false); } } public void testObjectType() { openSourceFile("org.netbeans.test.java.editor.codegeneration", "CreateGetterSetter"); editor = new EditorOperator("CreateGetterSetter"); txtOper = editor.txtEditorPane(); try { editor.requestFocus(); editor.setCaretPosition(11, 1); GenerateCodeOperator.openDialog(GenerateCodeOperator.GENERATE_GETTER_SETTER,editor); GenerateGettersAndSettersOperator ggso = new GenerateGettersAndSettersOperator(GenerateGettersAndSettersOperator.GETTERS_AND_SETTERS); JTreeOperator jto = ggso.treeTreeView$ExplorerTree(); jto.selectRow(4); ggso.generate(); String expected = "" + " public List<? extends Thread> getThreads() {\n"+ " return threads;\n"+ " }\n"+ "\n"+ " public void setThreads(List<? extends Thread> threads) {\n"+ " this.threads = threads;\n"+ " }\n"; waitAndCompare(expected); } finally { editor.close(false); } } public void testBooleanType() { openSourceFile("org.netbeans.test.java.editor.codegeneration", "CreateGetterSetter"); editor = new EditorOperator("CreateGetterSetter"); txtOper = editor.txtEditorPane(); try { editor.requestFocus(); editor.setCaretPosition(11, 1); GenerateCodeOperator.openDialog(GenerateCodeOperator.GENERATE_GETTER_SETTER,editor); GenerateGettersAndSettersOperator ggso = new GenerateGettersAndSettersOperator(GenerateGettersAndSettersOperator.GETTERS_AND_SETTERS); JTreeOperator jto = ggso.treeTreeView$ExplorerTree(); jto.selectRow(1); ggso.generate(); String expected = "" + " public boolean isBool() {\n"+ " return bool;\n"+ " }\n"+ "\n"+ " public void setBool(boolean bool) {\n"+ " this.bool = bool;\n"+ " }\n"; waitAndCompare(expected); } finally { editor.close(false); } } public void testStaticType() { openSourceFile("org.netbeans.test.java.editor.codegeneration", "CreateGetterSetter"); editor = new EditorOperator("CreateGetterSetter"); txtOper = editor.txtEditorPane(); try { editor.requestFocus(); editor.setCaretPosition(11, 1); GenerateCodeOperator.openDialog(GenerateCodeOperator.GENERATE_GETTER_SETTER,editor); GenerateGettersAndSettersOperator ggso = new GenerateGettersAndSettersOperator(GenerateGettersAndSettersOperator.GETTERS_AND_SETTERS); JTreeOperator jto = ggso.treeTreeView$ExplorerTree(); jto.selectRow(3); ggso.generate(); String expected = "" + " public static int getStatField() {\n"+ " return statField;\n"+ " }\n"+ "\n"+ " public static void setStatField(int statField) {\n"+ " CreateGetterSetter.statField = statField;\n"+ " }\n"; waitAndCompare(expected); } finally { editor.close(false); } } public void testMultipleSetter() { openSourceFile("org.netbeans.test.java.editor.codegeneration", "CreateGetterSetter"); editor = new EditorOperator("CreateGetterSetter"); txtOper = editor.txtEditorPane(); try { editor.requestFocus(); editor.setCaretPosition(11, 1); GenerateCodeOperator.openDialog(GenerateCodeOperator.GENERATE_SETTER, editor); GenerateGettersAndSettersOperator ggso = new GenerateGettersAndSettersOperator(GenerateGettersAndSettersOperator.SETTERS_ONLY); JTreeOperator jto = ggso.treeTreeView$ExplorerTree(); jto.selectRow(3); jto.selectRow(2); jto.selectRow(1); ggso.generate(); String expected = "" + " public void setNum(int num) {\n"+ " this.num = num;\n"+ " }\n"+ "\n"+ " public void setBool(boolean bool) {\n"+ " this.bool = bool;\n"+ " }\n"+ "\n"+ " public void setHasGetter(int hasGetter) {\n"+ " this.hasGetter = hasGetter;\n"+ " }\n"; waitAndCompare(expected); } finally { editor.close(false); } } public void testMultipleGetter() { openSourceFile("org.netbeans.test.java.editor.codegeneration", "CreateGetterSetter"); editor = new EditorOperator("CreateGetterSetter"); txtOper = editor.txtEditorPane(); try { editor.requestFocus(); editor.setCaretPosition(11, 1); GenerateCodeOperator.openDialog(GenerateCodeOperator.GENERATE_GETTER, editor); GenerateGettersAndSettersOperator ggso = new GenerateGettersAndSettersOperator(GenerateGettersAndSettersOperator.GETTERS_ONLY); JTreeOperator jto = ggso.treeTreeView$ExplorerTree(); jto.selectRow(1); jto.selectRow(2); jto.selectRow(3); ggso.generate(); String expected = "" + " public int getNum() {\n"+ " return num;\n"+ " }\n"+ "\n"+ " public boolean isBool() {\n"+ " return bool;\n"+ " }\n"+ "\n"+ " public int getHasSetter() {\n"+ " return hasSetter;\n"+ " }\n"; waitAndCompare(expected); } finally { editor.close(false); } } public void testArray() { openSourceFile("org.netbeans.test.java.editor.codegeneration", "CreateGetterSetter"); editor = new EditorOperator("CreateGetterSetter"); txtOper = editor.txtEditorPane(); try { editor.requestFocus(); editor.setCaretPosition(11, 1); editor.txtEditorPane().typeText("int [] pole;"); GenerateCodeOperator.openDialog(GenerateCodeOperator.GENERATE_GETTER_SETTER, editor); GenerateGettersAndSettersOperator ggso = new GenerateGettersAndSettersOperator(GenerateGettersAndSettersOperator.GETTERS_AND_SETTERS); JTreeOperator jto = ggso.treeTreeView$ExplorerTree(); jto.selectRow(3); ggso.generate(); String expected = "" + " public int[] getPole() {\n"+ " return pole;\n"+ " }\n"+ "\n"+ " public void setPole(int[] pole) {\n"+ " this.pole = pole;\n"+ " }\n"; waitAndCompare(expected); } finally { editor.close(false); } } public static void main(String[] args) { TestRunner.run(CreateGetterSetterTest.class); } public static Test suite() { return NbModuleSuite.create( NbModuleSuite.createConfiguration(CreateGetterSetterTest.class).enableModules(".*").clusters(".*")); } }
5,673
1,223
/* Copyright 2016 Nidium Inc. All rights reserved. Use of this source code is governed by a MIT license that can be found in the LICENSE file. */ #ifndef net_http_h__ #define net_http_h__ #include <string> #include <http_parser.h> #include <ape_netlib.h> #include <ape_array.h> #define HTTP_MAX_CL (1024ULL * 1024ULL * 1024ULL * 2ULL) #define HTTP_DEFAULT_TIMEOUT 15000 #include "Core/Messages.h" namespace Nidium { namespace Net { // {{{ HTTPRequest class HTTPRequest { public: enum HTTPMethod { kHTTPMethod_Get, kHTTPMethod_Post, kHTTPMethod_Head, kHTTPMethod_Put, kHTTPMethod_Delete } m_Method; explicit HTTPRequest(const char *url); ~HTTPRequest() { ape_array_destroy(m_Headers); if (m_Data != NULL && m_Datafree != NULL) { m_Datafree(m_Data); } free(m_Host); free(m_Path); }; void recycle() { ape_array_destroy(m_Headers); m_Headers = ape_array_new(8); if (m_Data != NULL && m_Datafree != NULL) { m_Datafree(m_Data); } m_Data = NULL; m_DataLen = 0; m_Method = kHTTPMethod_Get; setDefaultHeaders(); } void setHeader(const char *key, const char *val) { ape_array_add_camelkey_n(m_Headers, key, strlen(key), val, strlen(val)); } const char *getHeader(const char *key) { buffer *ret = ape_array_lookup(m_Headers, key, strlen(key)); return ret ? reinterpret_cast<const char *>(ret->data) : NULL; } buffer *getHeadersData() const; const bool isValid() const { return (m_Host[0] != 0); } const char *getHost() const { return m_Host; } const char *getPath() const { return m_Path; } void setPath(const char *lpath) { if (m_Path && lpath != m_Path) { free(m_Path); } m_Path = strdup(lpath); } u_short getPort() const { return m_Port; } ape_array_t *getHeaders() const { return m_Headers; } void setData(char *data, size_t len) { m_Data = data; m_DataLen = len; } const char *getData() const { return m_Data; } size_t getDataLength() const { return m_DataLen; } void setDataReleaser(void (*datafree)(void *)) { m_Datafree = datafree; } bool isSSL() const { return m_isSSL; } bool resetURL(const char *url); private: void setDefaultHeaders(); char *m_Host; char *m_Path; char *m_Data; size_t m_DataLen; void (*m_Datafree)(void *); u_short m_Port; ape_array_t *m_Headers; bool m_isSSL; }; // }}} // {{{ HTTP class HTTPDelegate; class HTTP : public Nidium::Core::Messages { private: void *m_Ptr; public: enum DataType { DATA_STRING = 1, DATA_BINARY, DATA_IMAGE, DATA_AUDIO, DATA_JSON, DATA_NULL, DATA_END } nidium_http_data_type; enum HTTPError { ERROR_NOERR, ERROR_TIMEOUT, ERROR_RESPONSE, ERROR_DISCONNECTED, ERROR_SOCKET, ERROR_HTTPCODE, ERROR_REDIRECTMAX, _ERROR_END_ }; const static char *HTTPErrorDescription[]; enum PrevState { PSTATE_NOTHING, PSTATE_FIELD, PSTATE_VALUE }; ape_global *m_Net; ape_socket *m_CurrentSock; int m_Err; uint32_t m_Timeout; uint64_t m_TimeoutTimer; HTTPDelegate *m_Delegate; struct HTTPData { http_parser parser; bool parser_rdy; struct { ape_array_t *list; buffer *tkey; buffer *tval; PrevState prevstate; } m_Headers; buffer *m_Data; int m_Ended; uint64_t m_ContentLength; } m_HTTP; static int ParseURI(char *url, size_t url_len, char *host, u_short *port, char *file, const char *prefix = "http://", u_short default_port = 80); void requestEnded(); void headerEnded(); void stopRequest(bool timeout = false); void clearTimeout(); void onData(size_t offset, size_t len); void setPrivate(void *ptr); void *getPrivate(); void parsing(bool val) { m_isParsing = val; } bool isParsing() const { return m_isParsing; } void resetData() { if (m_HTTP.m_Data == NULL) { return; } m_HTTP.m_Data->used = 0; } uint64_t getFileSize() const { return m_FileSize; } uint16_t getStatusCode() const { return m_HTTP.parser.status_code; } HTTPRequest *getRequest() const { return m_Request; } const char *getHeader(const char *key); void close(bool now = false) { if (m_CurrentSock) { if (now) { APE_socket_shutdown_now(m_CurrentSock); } else { APE_socket_shutdown(m_CurrentSock); } } } void clearState(); bool request(HTTPRequest *req, HTTPDelegate *delegate, bool forceNewConnection = false); bool isKeepAlive(); bool canDoRequest() const { return m_CanDoRequest && !hasPendingError(); } bool canDoRequest(bool val) { m_CanDoRequest = val; return canDoRequest(); } void setPendingError(HTTP::HTTPError err) { m_PendingError = err; } void clearPendingError() { m_PendingError = ERROR_NOERR; } bool hasPendingError() const { return (m_PendingError != ERROR_NOERR); } void setMaxRedirect(int max) { m_MaxRedirect = max; } void setFollowLocation(bool toggle) { m_FollowLocation = toggle; } const char *getPath() const { return m_Path.c_str(); } HTTP(ape_global *n); ~HTTP(); private: void reportPendingError(); bool createConnection(); uint64_t m_FileSize; bool m_isParsing; // http_parser_execute is working HTTPRequest *m_Request; bool m_CanDoRequest; HTTPError m_PendingError; int m_MaxRedirect; bool m_FollowLocation; std::string m_Path; struct { const char *to; bool enabled; int count; } m_Redirect; }; // }}} // {{{ HTTPDelegate class HTTPDelegate { public: virtual void onRequest(HTTP::HTTPData *h, HTTP::DataType) = 0; virtual void onProgress(size_t offset, size_t len, HTTP::HTTPData *h, HTTP::DataType) = 0; virtual void onError(HTTP::HTTPError err) = 0; virtual void onHeader() = 0; HTTP *m_HTTPRef; }; // }}} } /* namespace Core */ } /* namespace Nidium */ #endif
3,481
1,043
package app.custom.binder.resource.objects; import javax.ws.rs.GET; import javax.ws.rs.Path; import com.oath.micro.server.auto.discovery.Rest; @Rest @Path("/test") public class SimpleApp { @GET public String myEndPoint(){ return "hello world!"; } }
104
471
<filename>forest-core/src/test/java/com/dtflys/test/http/retry/TestRetryWhen.java package com.dtflys.test.http.retry; import com.dtflys.forest.callback.RetryWhen; import com.dtflys.forest.http.ForestRequest; import com.dtflys.forest.http.ForestResponse; public class TestRetryWhen implements RetryWhen { /** * 请求重试条件 * @param request Forest请求对象 * @param response Forest响应对象 * @return 是否重试 */ @Override public boolean retryWhen(ForestRequest request, ForestResponse response) { return response.statusIs(203); } }
245
2,542
<filename>src/prod/src/ServiceModel/RemoteReplicatorAcknowledgementDetail.h // ------------------------------------------------------------ // 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 ServiceModel { class RemoteReplicatorAcknowledgementDetail : public Serialization::FabricSerializable , public Common::IFabricJsonSerializable { public: RemoteReplicatorAcknowledgementDetail(); RemoteReplicatorAcknowledgementDetail( int64 avgReplicationReceiveAckDuration, int64 avgReplicationApplyAckDuration, FABRIC_SEQUENCE_NUMBER notReceivedReplicationCount, FABRIC_SEQUENCE_NUMBER receivedAndNotAppliedReplicationCount); RemoteReplicatorAcknowledgementDetail(RemoteReplicatorAcknowledgementDetail && other); RemoteReplicatorAcknowledgementDetail & operator=(RemoteReplicatorAcknowledgementDetail && other); Common::ErrorCode ToPublicApi( __in Common::ScopedHeap & heap, __out FABRIC_REMOTE_REPLICATOR_ACKNOWLEDGEMENT_DETAIL & publicResult) const ; Common::ErrorCode FromPublicApi( __in FABRIC_REMOTE_REPLICATOR_ACKNOWLEDGEMENT_DETAIL & publicResult) ; void WriteTo(Common::TextWriter&, Common::FormatOptions const &) const; std::wstring ToString() const; FABRIC_FIELDS_04( avgReceiveAckDuration_, avgApplyAckDuration_, notReceivedCount_, receivedAndNotAppliedCount_); BEGIN_JSON_SERIALIZABLE_PROPERTIES() SERIALIZABLE_PROPERTY(Constants::AverageReceiveDuration, avgReceiveAckDuration_) SERIALIZABLE_PROPERTY(Constants::AverageApplyDuration, avgApplyAckDuration_) SERIALIZABLE_PROPERTY(Constants::NotReceivedCount, notReceivedCount_) SERIALIZABLE_PROPERTY(Constants::ReceivedAndNotAppliedCount, receivedAndNotAppliedCount_) END_JSON_SERIALIZABLE_PROPERTIES() private: int64 avgReceiveAckDuration_; int64 avgApplyAckDuration_; FABRIC_SEQUENCE_NUMBER notReceivedCount_; FABRIC_SEQUENCE_NUMBER receivedAndNotAppliedCount_; }; } DEFINE_USER_ARRAY_UTILITY(ServiceModel::RemoteReplicatorAcknowledgementDetail);
934
1,444
package mage.target.common; import mage.ObjectColor; import mage.abilities.Ability; import mage.abilities.dynamicvalue.common.ColorAssignment; import mage.cards.Cards; import mage.cards.CardsImpl; import mage.filter.common.FilterControlledCreaturePermanent; import mage.filter.common.FilterControlledPermanent; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.ColorPredicate; import mage.game.Game; import mage.game.permanent.Permanent; import mage.util.CardUtil; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; /** * @author TheElk801 */ public class TargetControlledCreatureEachColor extends TargetControlledPermanent { private final ColorAssignment colorAssigner; private static final FilterControlledPermanent makeFilter(String colors) { List<ObjectColor> objectColors = Arrays.stream(colors.split("")) .map(ObjectColor::new) .collect(Collectors.toList()); FilterControlledPermanent filter = new FilterControlledCreaturePermanent(CardUtil.concatWithAnd( objectColors .stream() .map(ObjectColor::getDescription) .map(s -> CardUtil.addArticle(s) + " creature") .collect(Collectors.toList()) )); filter.add(Predicates.or(objectColors.stream().map(ColorPredicate::new).collect(Collectors.toList()))); return filter; } public TargetControlledCreatureEachColor(String colors) { super(colors.length(), makeFilter(colors)); colorAssigner = new ColorAssignment(colors.split("")); } private TargetControlledCreatureEachColor(final TargetControlledCreatureEachColor target) { super(target); this.colorAssigner = target.colorAssigner; } @Override public boolean canTarget(UUID playerId, UUID id, Ability source, Game game) { if (!super.canTarget(playerId, id, source, game)) { return false; } Permanent permanent = game.getPermanent(id); if (permanent == null) { return false; } if (this.getTargets().isEmpty()) { return true; } Cards cards = new CardsImpl(this.getTargets()); cards.add(permanent); return colorAssigner.getRoleCount(cards, game) >= cards.size(); } @Override public TargetControlledCreatureEachColor copy() { return new TargetControlledCreatureEachColor(this); } }
1,042
3,075
<filename>powermock-core/src/main/java/org/powermock/core/transformers/MethodSignatures.java package org.powermock.core.transformers; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import net.bytebuddy.description.method.MethodDescription; import org.powermock.PowerMockInternalException; import java.lang.reflect.Method; public enum MethodSignatures { ByteBuddy { @Override public MethodSignatureWriter<MethodDescription> methodSignatureWriter() { return new ByteBuddyMethodSignatureWriterWriter(); } }, Javassist { @Override public MethodSignatureWriter<CtMethod> methodSignatureWriter() { return new JavassistMethodSignatureWriterWriter(); } }; public abstract <T> MethodSignatureWriter<T> methodSignatureWriter(); private static class ByteBuddyMethodSignatureWriterWriter implements MethodSignatureWriter<MethodDescription> { @Override public String signatureFor(final MethodDescription method) { return method.toGenericString(); } @Override public String signatureForReflection(final Method method) { return method.toString(); } } private static class JavassistMethodSignatureWriterWriter implements MethodSignatureWriter<CtMethod> { @Override public String signatureFor(final CtMethod m) { try { CtClass[] paramTypes = m.getParameterTypes(); String[] paramTypeNames = new String[paramTypes.length]; for (int i = 0; i < paramTypeNames.length; ++i) { paramTypeNames[i] = paramTypes[i].getSimpleName(); } return createSignature( m.getDeclaringClass().getSimpleName(), m.getReturnType().getSimpleName(), m.getName(), paramTypeNames); } catch (NotFoundException e) { throw new PowerMockInternalException(e); } } @Override public String signatureForReflection(final Method m) { Class[] paramTypes = m.getParameterTypes(); String[] paramTypeNames = new String[paramTypes.length]; for (int i = 0; i < paramTypeNames.length; ++i) { paramTypeNames[i] = paramTypes[i].getSimpleName(); } return createSignature( m.getDeclaringClass().getSimpleName(), m.getReturnType().getSimpleName(), m.getName(), paramTypeNames); } private String createSignature( String testClass, String returnType, String methodName, String[] paramTypes) { StringBuilder builder = new StringBuilder(testClass) .append('\n').append(returnType) .append('\n').append(methodName); for (String param : paramTypes) { builder.append('\n').append(param); } return builder.toString(); } } }
1,436
388
<reponame>Fl4v/botbuilder-python<filename>libraries/botbuilder-ai/botbuilder/ai/qna/utils/http_request_utils.py # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import json import platform from typing import Any import requests from aiohttp import ClientResponse, ClientSession, ClientTimeout from ... import __title__, __version__ from ..qnamaker_endpoint import QnAMakerEndpoint class HttpRequestUtils: """ HTTP request utils class. Parameters: ----------- http_client: Client to make HTTP requests with. Default client used in the SDK is `aiohttp.ClientSession`. """ def __init__(self, http_client: Any): self._http_client = http_client async def execute_http_request( self, request_url: str, payload_body: object, endpoint: QnAMakerEndpoint, timeout: float = None, ) -> Any: """ Execute HTTP request. Parameters: ----------- request_url: HTTP request URL. payload_body: HTTP request body. endpoint: QnA Maker endpoint details. timeout: Timeout for HTTP call (milliseconds). """ if not request_url: raise TypeError( "HttpRequestUtils.execute_http_request(): request_url cannot be None." ) if not payload_body: raise TypeError( "HttpRequestUtils.execute_http_request(): question cannot be None." ) if not endpoint: raise TypeError( "HttpRequestUtils.execute_http_request(): endpoint cannot be None." ) serialized_payload_body = json.dumps(payload_body.serialize()) headers = self._get_headers(endpoint) if isinstance(self._http_client, ClientSession): response: ClientResponse = await self._make_request_with_aiohttp( request_url, serialized_payload_body, headers, timeout ) elif self._is_using_requests_module(): response: requests.Response = self._make_request_with_requests( request_url, serialized_payload_body, headers, timeout ) else: response = await self._http_client.post( request_url, data=serialized_payload_body, headers=headers ) return response def _get_headers(self, endpoint: QnAMakerEndpoint): headers = { "Content-Type": "application/json", "User-Agent": self._get_user_agent(), "Authorization": f"EndpointKey {endpoint.endpoint_key}", "Ocp-Apim-Subscription-Key": f"EndpointKey {endpoint.endpoint_key}", } return headers def _get_user_agent(self): package_user_agent = f"{__title__}/{__version__}" uname = platform.uname() os_version = f"{uname.machine}-{uname.system}-{uname.version}" py_version = f"Python,Version={platform.python_version()}" platform_user_agent = f"({os_version}; {py_version})" user_agent = f"{package_user_agent} {platform_user_agent}" return user_agent def _is_using_requests_module(self) -> bool: return (type(self._http_client).__name__ == "module") and ( self._http_client.__name__ == "requests" ) async def _make_request_with_aiohttp( self, request_url: str, payload_body: str, headers: dict, timeout: float ) -> ClientResponse: if timeout: # aiohttp.ClientSession's timeouts are in seconds timeout_in_seconds = ClientTimeout(total=timeout / 1000) return await self._http_client.post( request_url, data=payload_body, headers=headers, timeout=timeout_in_seconds, ) return await self._http_client.post( request_url, data=payload_body, headers=headers ) def _make_request_with_requests( self, request_url: str, payload_body: str, headers: dict, timeout: float ) -> requests.Response: if timeout: # requests' timeouts are in seconds timeout_in_seconds = timeout / 1000 return self._http_client.post( request_url, data=payload_body, headers=headers, timeout=timeout_in_seconds, ) return self._http_client.post(request_url, data=payload_body, headers=headers)
2,138
504
package org.dayatang.domain.ioc; public interface Service2 { String sayHello(); }
28
460
/* * TinyJS * * A single-file Javascript-alike engine * * Authored By <NAME> <<EMAIL>> * * Copyright (C) 2009 Pur3 Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /* Version 0.1 : (gw) First published on Google Code Version 0.11 : Making sure the 'root' variable never changes 'symbol_base' added for the current base of the sybmbol table Version 0.12 : Added findChildOrCreate, changed string passing to use references Fixed broken string encoding in getJSString() Removed getInitCode and added getJSON instead Added nil Added rough JSON parsing Improved example app Version 0.13 : Added tokenEnd/tokenLastEnd to lexer to avoid parsing whitespace Ability to define functions without names Can now do "var mine = function(a,b) { ... };" Slightly better 'trace' function Added findChildOrCreateByPath function Added simple test suite Added skipping of blocks when not executing Version 0.14 : Added parsing of more number types Added parsing of string defined with ' Changed nil to null as per spec, added 'undefined' Now set variables with the correct scope, and treat unknown as 'undefined' rather than failing Added proper (I hope) handling of null and undefined Added === check Version 0.15 : Fix for possible memory leaks Version 0.16 : Removal of un-needed findRecursive calls symbol_base removed and replaced with 'scopes' stack Added reference counting a proper tree structure (Allowing pass by reference) Allowed JSON output to output IDs, not strings Added get/set for array indices Changed Callbacks to include user data pointer Added some support for objects Added more Java-esque builtin functions Version 0.17 : Now we don't deepCopy the parent object of the class Added JSON.stringify and eval() Nicer JSON indenting Fixed function output in JSON Added evaluateComplex Fixed some reentrancy issues with evaluate/execute Version 0.18 : Fixed some issues with code being executed when it shouldn't Version 0.19 : Added array.length Changed '__parent' to 'prototype' to bring it more in line with javascript Version 0.20 : Added '%' operator Version 0.21 : Added array type String.length() no more - now String.length Added extra constructors to reduce confusion Fixed checks against undefined Version 0.22 : First part of ardi's changes: sprintf -> sprintf_s extra tokens parsed array memory leak fixed Fixed memory leak in evaluateComplex Fixed memory leak in FOR loops Fixed memory leak for unary minus Version 0.23 : Allowed evaluate[Complex] to take in semi-colon separated statements and then only return the value from the last one. Also checks to make sure *everything* was parsed. Ints + doubles are now stored in binary form (faster + more precise) Version 0.24 : More useful error for maths ops Don't dump everything on a match error. Version 0.25 : Better string escaping Version 0.26 : Add CScriptVar::equals Add built-in array functions Version 0.27 : Added OZLB's TinyJS.setVariable (with some tweaks) Added OZLB's Maths Functions Version 0.28 : Ternary operator Rudimentary call stack on error Added String Character functions Added shift operators Version 0.29 : Added new object via functions Fixed getString() for double on some platforms Version 0.30 : <NAME>'s patch for Math Functions on VC++ Version 0.31 : Add exec() to TinyJS functions Now print quoted JSON that can be read by PHP/Python parsers Fixed postfix increment operator Version 0.32 : Fixed Math.randInt on 32 bit PCs, where it was broken Version 0.33 : Fixed Memory leak + brokenness on === comparison NOTE: Constructing an array with an initial length 'Array(5)' doesn't work Recursive loops of data such as a.foo = a; fail to be garbage collected length variable cannot be set The postfix increment operator returns the current value, not the previous as it should. There is no prefix increment operator Arrays are implemented as a linked list - hence a lookup time is O(n) TODO: Utility va-args style function in TinyJS for executing a function directly Merge the parsing of expressions/statements so eval("statement") works like we'd expect. Move 'shift' implementation into mathsOp */ #include "TinyJS.h" #include <assert.h> #define ASSERT(X) assert(X) /* Frees the given link IF it isn't owned by anything else */ #define CLEAN(x) { CScriptVarLink *__v = x; if (__v && !__v->owned) { delete __v; } } /* Create a LINK to point to VAR and free the old link. * BUT this is more clever - it tries to keep the old link if it's not owned to save allocations */ #define CREATE_LINK(LINK, VAR) { if (!LINK || LINK->owned) LINK = new CScriptVarLink(VAR); else LINK->replaceWith(VAR); } #include <string> #include <string.h> #include <sstream> #include <cstdlib> #include <stdio.h> using namespace std; #ifdef _WIN32 #ifdef _DEBUG #ifndef DBG_NEW #define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ ) #define new DBG_NEW #endif #endif #endif #ifdef __GNUC__ #define vsprintf_s vsnprintf #define sprintf_s snprintf #define _strdup strdup #endif // ----------------------------------------------------------------------------------- Memory Debug #define DEBUG_MEMORY 0 #if DEBUG_MEMORY vector<CScriptVar*> allocatedVars; vector<CScriptVarLink*> allocatedLinks; void mark_allocated(CScriptVar *v) { allocatedVars.push_back(v); } void mark_deallocated(CScriptVar *v) { for (size_t i=0;i<allocatedVars.size();i++) { if (allocatedVars[i] == v) { allocatedVars.erase(allocatedVars.begin()+i); break; } } } void mark_allocated(CScriptVarLink *v) { allocatedLinks.push_back(v); } void mark_deallocated(CScriptVarLink *v) { for (size_t i=0;i<allocatedLinks.size();i++) { if (allocatedLinks[i] == v) { allocatedLinks.erase(allocatedLinks.begin()+i); break; } } } void show_allocated() { for (size_t i=0;i<allocatedVars.size();i++) { printf("ALLOCATED, %d refs\n", allocatedVars[i]->getRefs()); allocatedVars[i]->trace(" "); } for (size_t i=0;i<allocatedLinks.size();i++) { printf("ALLOCATED LINK %s, allocated[%d] to \n", allocatedLinks[i]->name.c_str(), allocatedLinks[i]->var->getRefs()); allocatedLinks[i]->var->trace(" "); } allocatedVars.clear(); allocatedLinks.clear(); } #endif // ----------------------------------------------------------------------------------- Utils bool isWhitespace(char ch) { return (ch==' ') || (ch=='\t') || (ch=='\n') || (ch=='\r'); } bool isNumeric(char ch) { return (ch>='0') && (ch<='9'); } bool isNumber(const string &str) { for (size_t i=0;i<str.size();i++) if (!isNumeric(str[i])) return false; return true; } bool isHexadecimal(char ch) { return ((ch>='0') && (ch<='9')) || ((ch>='a') && (ch<='f')) || ((ch>='A') && (ch<='F')); } bool isAlpha(char ch) { return ((ch>='a') && (ch<='z')) || ((ch>='A') && (ch<='Z')) || ch=='_'; } bool isIDString(const char *s) { if (!isAlpha(*s)) return false; while (*s) { if (!(isAlpha(*s) || isNumeric(*s))) return false; s++; } return true; } void replace(string &str, char textFrom, const char *textTo) { int sLen = strlen(textTo); size_t p = str.find(textFrom); while (p != string::npos) { str = str.substr(0, p) + textTo + str.substr(p+1); p = str.find(textFrom, p+sLen); } } /// convert the given string into a quoted string suitable for javascript std::string getJSString(const std::string &str) { std::string nStr = str; for (size_t i=0;i<nStr.size();i++) { const char *replaceWith = ""; bool replace = true; switch (nStr[i]) { case '\\': replaceWith = "\\\\"; break; case '\n': replaceWith = "\\n"; break; case '\r': replaceWith = "\\r"; break; case '\a': replaceWith = "\\a"; break; case '"': replaceWith = "\\\""; break; default: { int nCh = ((int)nStr[i]) &0xFF; if (nCh<32 || nCh>127) { char buffer[5]; sprintf_s(buffer, 5, "\\x%02X", nCh); replaceWith = buffer; } else replace=false; } } if (replace) { nStr = nStr.substr(0, i) + replaceWith + nStr.substr(i+1); i += strlen(replaceWith)-1; } } return "\"" + nStr + "\""; } /** Is the string alphanumeric */ bool isAlphaNum(const std::string &str) { if (str.size()==0) return true; if (!isAlpha(str[0])) return false; for (size_t i=0;i<str.size();i++) if (!(isAlpha(str[i]) || isNumeric(str[i]))) return false; return true; } // ----------------------------------------------------------------------------------- CSCRIPTEXCEPTION CScriptException::CScriptException(const string &exceptionText) { text = exceptionText; } // ----------------------------------------------------------------------------------- CSCRIPTLEX CScriptLex::CScriptLex(const string &input) { data = _strdup(input.c_str()); dataOwned = true; dataStart = 0; dataEnd = strlen(data); reset(); } CScriptLex::CScriptLex(CScriptLex *owner, int startChar, int endChar) { data = owner->data; dataOwned = false; dataStart = startChar; dataEnd = endChar; reset(); } CScriptLex::~CScriptLex(void) { if (dataOwned) free((void*)data); } void CScriptLex::reset() { dataPos = dataStart; tokenStart = 0; tokenEnd = 0; tokenLastEnd = 0; tk = 0; tkStr = ""; getNextCh(); getNextCh(); getNextToken(); } void CScriptLex::match(int expected_tk) { if (tk!=expected_tk) { ostringstream errorString; errorString << "Got " << getTokenStr(tk) << " expected " << getTokenStr(expected_tk) << " at " << getPosition(tokenStart); throw new CScriptException(errorString.str()); } getNextToken(); } string CScriptLex::getTokenStr(int token) { if (token>32 && token<128) { char buf[4] = "' '"; buf[1] = (char)token; return buf; } switch (token) { case LEX_EOF : return "EOF"; case LEX_ID : return "ID"; case LEX_INT : return "INT"; case LEX_FLOAT : return "FLOAT"; case LEX_STR : return "STRING"; case LEX_EQUAL : return "=="; case LEX_TYPEEQUAL : return "==="; case LEX_NEQUAL : return "!="; case LEX_NTYPEEQUAL : return "!=="; case LEX_LEQUAL : return "<="; case LEX_LSHIFT : return "<<"; case LEX_LSHIFTEQUAL : return "<<="; case LEX_GEQUAL : return ">="; case LEX_RSHIFT : return ">>"; case LEX_RSHIFTUNSIGNED : return ">>"; case LEX_RSHIFTEQUAL : return ">>="; case LEX_PLUSEQUAL : return "+="; case LEX_MINUSEQUAL : return "-="; case LEX_PLUSPLUS : return "++"; case LEX_MINUSMINUS : return "--"; case LEX_ANDEQUAL : return "&="; case LEX_ANDAND : return "&&"; case LEX_OREQUAL : return "|="; case LEX_OROR : return "||"; case LEX_XOREQUAL : return "^="; // reserved words case LEX_R_IF : return "if"; case LEX_R_ELSE : return "else"; case LEX_R_DO : return "do"; case LEX_R_WHILE : return "while"; case LEX_R_FOR : return "for"; case LEX_R_BREAK : return "break"; case LEX_R_CONTINUE : return "continue"; case LEX_R_FUNCTION : return "function"; case LEX_R_RETURN : return "return"; case LEX_R_VAR : return "var"; case LEX_R_TRUE : return "true"; case LEX_R_FALSE : return "false"; case LEX_R_NULL : return "null"; case LEX_R_UNDEFINED : return "undefined"; case LEX_R_NEW : return "new"; } ostringstream msg; msg << "?[" << token << "]"; return msg.str(); } void CScriptLex::getNextCh() { currCh = nextCh; if (dataPos < dataEnd) nextCh = data[dataPos]; else nextCh = 0; dataPos++; } void CScriptLex::getNextToken() { tk = LEX_EOF; tkStr.clear(); while (currCh && isWhitespace(currCh)) getNextCh(); // newline comments if (currCh=='/' && nextCh=='/') { while (currCh && currCh!='\n') getNextCh(); getNextCh(); getNextToken(); return; } // block comments if (currCh=='/' && nextCh=='*') { while (currCh && (currCh!='*' || nextCh!='/')) getNextCh(); getNextCh(); getNextCh(); getNextToken(); return; } // record beginning of this token tokenStart = dataPos-2; // tokens if (isAlpha(currCh)) { // IDs while (isAlpha(currCh) || isNumeric(currCh)) { tkStr += currCh; getNextCh(); } tk = LEX_ID; if (tkStr=="if") tk = LEX_R_IF; else if (tkStr=="else") tk = LEX_R_ELSE; else if (tkStr=="do") tk = LEX_R_DO; else if (tkStr=="while") tk = LEX_R_WHILE; else if (tkStr=="for") tk = LEX_R_FOR; else if (tkStr=="break") tk = LEX_R_BREAK; else if (tkStr=="continue") tk = LEX_R_CONTINUE; else if (tkStr=="function") tk = LEX_R_FUNCTION; else if (tkStr=="return") tk = LEX_R_RETURN; else if (tkStr=="var") tk = LEX_R_VAR; else if (tkStr=="true") tk = LEX_R_TRUE; else if (tkStr=="false") tk = LEX_R_FALSE; else if (tkStr=="null") tk = LEX_R_NULL; else if (tkStr=="undefined") tk = LEX_R_UNDEFINED; else if (tkStr=="new") tk = LEX_R_NEW; } else if (isNumeric(currCh)) { // Numbers bool isHex = false; if (currCh=='0') { tkStr += currCh; getNextCh(); } if (currCh=='x') { isHex = true; tkStr += currCh; getNextCh(); } tk = LEX_INT; while (isNumeric(currCh) || (isHex && isHexadecimal(currCh))) { tkStr += currCh; getNextCh(); } if (!isHex && currCh=='.') { tk = LEX_FLOAT; tkStr += '.'; getNextCh(); while (isNumeric(currCh)) { tkStr += currCh; getNextCh(); } } // do fancy e-style floating point if (!isHex && (currCh=='e'||currCh=='E')) { tk = LEX_FLOAT; tkStr += currCh; getNextCh(); if (currCh=='-') { tkStr += currCh; getNextCh(); } while (isNumeric(currCh)) { tkStr += currCh; getNextCh(); } } } else if (currCh=='"') { // strings... getNextCh(); while (currCh && currCh!='"') { if (currCh == '\\') { getNextCh(); switch (currCh) { case 'n' : tkStr += '\n'; break; case '"' : tkStr += '"'; break; case '\\' : tkStr += '\\'; break; default: tkStr += currCh; } } else { tkStr += currCh; } getNextCh(); } getNextCh(); tk = LEX_STR; } else if (currCh=='\'') { // strings again... getNextCh(); while (currCh && currCh!='\'') { if (currCh == '\\') { getNextCh(); switch (currCh) { case 'n' : tkStr += '\n'; break; case 'a' : tkStr += '\a'; break; case 'r' : tkStr += '\r'; break; case 't' : tkStr += '\t'; break; case '\'' : tkStr += '\''; break; case '\\' : tkStr += '\\'; break; case 'x' : { // hex digits char buf[3] = "??"; getNextCh(); buf[0] = currCh; getNextCh(); buf[1] = currCh; tkStr += (char)strtol(buf,0,16); } break; default: if (currCh>='0' && currCh<='7') { // octal digits char buf[4] = "???"; buf[0] = currCh; getNextCh(); buf[1] = currCh; getNextCh(); buf[2] = currCh; tkStr += (char)strtol(buf,0,8); } else tkStr += currCh; } } else { tkStr += currCh; } getNextCh(); } getNextCh(); tk = LEX_STR; } else { // single chars tk = currCh; if (currCh) getNextCh(); if (tk=='=' && currCh=='=') { // == tk = LEX_EQUAL; getNextCh(); if (currCh=='=') { // === tk = LEX_TYPEEQUAL; getNextCh(); } } else if (tk=='!' && currCh=='=') { // != tk = LEX_NEQUAL; getNextCh(); if (currCh=='=') { // !== tk = LEX_NTYPEEQUAL; getNextCh(); } } else if (tk=='<' && currCh=='=') { tk = LEX_LEQUAL; getNextCh(); } else if (tk=='<' && currCh=='<') { tk = LEX_LSHIFT; getNextCh(); if (currCh=='=') { // <<= tk = LEX_LSHIFTEQUAL; getNextCh(); } } else if (tk=='>' && currCh=='=') { tk = LEX_GEQUAL; getNextCh(); } else if (tk=='>' && currCh=='>') { tk = LEX_RSHIFT; getNextCh(); if (currCh=='=') { // >>= tk = LEX_RSHIFTEQUAL; getNextCh(); } else if (currCh=='>') { // >>> tk = LEX_RSHIFTUNSIGNED; getNextCh(); } } else if (tk=='+' && currCh=='=') { tk = LEX_PLUSEQUAL; getNextCh(); } else if (tk=='-' && currCh=='=') { tk = LEX_MINUSEQUAL; getNextCh(); } else if (tk=='+' && currCh=='+') { tk = LEX_PLUSPLUS; getNextCh(); } else if (tk=='-' && currCh=='-') { tk = LEX_MINUSMINUS; getNextCh(); } else if (tk=='&' && currCh=='=') { tk = LEX_ANDEQUAL; getNextCh(); } else if (tk=='&' && currCh=='&') { tk = LEX_ANDAND; getNextCh(); } else if (tk=='|' && currCh=='=') { tk = LEX_OREQUAL; getNextCh(); } else if (tk=='|' && currCh=='|') { tk = LEX_OROR; getNextCh(); } else if (tk=='^' && currCh=='=') { tk = LEX_XOREQUAL; getNextCh(); } } /* This isn't quite right yet */ tokenLastEnd = tokenEnd; tokenEnd = dataPos-3; } string CScriptLex::getSubString(int lastPosition) { int lastCharIdx = tokenLastEnd+1; if (lastCharIdx < dataEnd) { /* save a memory alloc by using our data array to create the substring */ char old = data[lastCharIdx]; data[lastCharIdx] = 0; std::string value = &data[lastPosition]; data[lastCharIdx] = old; return value; } else { return std::string(&data[lastPosition]); } } CScriptLex *CScriptLex::getSubLex(int lastPosition) { int lastCharIdx = tokenLastEnd+1; if (lastCharIdx < dataEnd) return new CScriptLex(this, lastPosition, lastCharIdx); else return new CScriptLex(this, lastPosition, dataEnd ); } string CScriptLex::getPosition(int pos) { if (pos<0) pos=tokenLastEnd; int line = 1,col = 1; for (int i=0;i<pos;i++) { char ch; if (i < dataEnd) ch = data[i]; else ch = 0; col++; if (ch=='\n') { line++; col = 0; } } char buf[256]; sprintf_s(buf, 256, "(line: %d, col: %d)", line, col); return buf; } // ----------------------------------------------------------------------------------- CSCRIPTVARLINK CScriptVarLink::CScriptVarLink(CScriptVar *var, const std::string &name) { #if DEBUG_MEMORY mark_allocated(this); #endif this->name = name; this->nextSibling = 0; this->prevSibling = 0; this->var = var->ref(); this->owned = false; } CScriptVarLink::CScriptVarLink(const CScriptVarLink &link) { // Copy constructor #if DEBUG_MEMORY mark_allocated(this); #endif this->name = link.name; this->nextSibling = 0; this->prevSibling = 0; this->var = link.var->ref(); this->owned = false; } CScriptVarLink::~CScriptVarLink() { #if DEBUG_MEMORY mark_deallocated(this); #endif var->unref(); } void CScriptVarLink::replaceWith(CScriptVar *newVar) { CScriptVar *oldVar = var; var = newVar->ref(); oldVar->unref(); } void CScriptVarLink::replaceWith(CScriptVarLink *newVar) { if (newVar) replaceWith(newVar->var); else replaceWith(new CScriptVar()); } int CScriptVarLink::getIntName() { return atoi(name.c_str()); } void CScriptVarLink::setIntName(int n) { char sIdx[64]; sprintf_s(sIdx, sizeof(sIdx), "%d", n); name = sIdx; } // ----------------------------------------------------------------------------------- CSCRIPTVAR CScriptVar::CScriptVar() { refs = 0; #if DEBUG_MEMORY mark_allocated(this); #endif init(); flags = SCRIPTVAR_UNDEFINED; } CScriptVar::CScriptVar(const string &str) { refs = 0; #if DEBUG_MEMORY mark_allocated(this); #endif init(); flags = SCRIPTVAR_STRING; data = str; } CScriptVar::CScriptVar(const string &varData, int varFlags) { refs = 0; #if DEBUG_MEMORY mark_allocated(this); #endif init(); flags = varFlags; if (varFlags & SCRIPTVAR_INTEGER) { intData = strtol(varData.c_str(),0,0); } else if (varFlags & SCRIPTVAR_DOUBLE) { doubleData = strtod(varData.c_str(),0); } else data = varData; } CScriptVar::CScriptVar(double val) { refs = 0; #if DEBUG_MEMORY mark_allocated(this); #endif init(); setDouble(val); } CScriptVar::CScriptVar(int val) { refs = 0; #if DEBUG_MEMORY mark_allocated(this); #endif init(); setInt(val); } CScriptVar::~CScriptVar(void) { #if DEBUG_MEMORY mark_deallocated(this); #endif removeAllChildren(); } void CScriptVar::init() { firstChild = 0; lastChild = 0; flags = 0; jsCallback = 0; jsCallbackUserData = 0; data = TINYJS_BLANK_DATA; intData = 0; doubleData = 0; } CScriptVar *CScriptVar::getReturnVar() { return getParameter(TINYJS_RETURN_VAR); } void CScriptVar::setReturnVar(CScriptVar *var) { findChildOrCreate(TINYJS_RETURN_VAR)->replaceWith(var); } CScriptVar *CScriptVar::getParameter(const std::string &name) { return findChildOrCreate(name)->var; } CScriptVarLink *CScriptVar::findChild(const string &childName) { CScriptVarLink *v = firstChild; while (v) { if (v->name.compare(childName)==0) return v; v = v->nextSibling; } return 0; } CScriptVarLink *CScriptVar::findChildOrCreate(const string &childName, int varFlags) { CScriptVarLink *l = findChild(childName); if (l) return l; return addChild(childName, new CScriptVar(TINYJS_BLANK_DATA, varFlags)); } CScriptVarLink *CScriptVar::findChildOrCreateByPath(const std::string &path) { size_t p = path.find('.'); if (p == string::npos) return findChildOrCreate(path); return findChildOrCreate(path.substr(0,p), SCRIPTVAR_OBJECT)->var-> findChildOrCreateByPath(path.substr(p+1)); } CScriptVarLink *CScriptVar::addChild(const std::string &childName, CScriptVar *child) { if (isUndefined()) { flags = SCRIPTVAR_OBJECT; } // if no child supplied, create one if (!child) child = new CScriptVar(); CScriptVarLink *link = new CScriptVarLink(child, childName); link->owned = true; if (lastChild) { lastChild->nextSibling = link; link->prevSibling = lastChild; lastChild = link; } else { firstChild = link; lastChild = link; } return link; } CScriptVarLink *CScriptVar::addChildNoDup(const std::string &childName, CScriptVar *child) { // if no child supplied, create one if (!child) child = new CScriptVar(); CScriptVarLink *v = findChild(childName); if (v) { v->replaceWith(child); } else { v = addChild(childName, child); } return v; } void CScriptVar::removeChild(CScriptVar *child) { CScriptVarLink *link = firstChild; while (link) { if (link->var == child) break; link = link->nextSibling; } ASSERT(link); removeLink(link); } void CScriptVar::removeLink(CScriptVarLink *link) { if (!link) return; if (link->nextSibling) link->nextSibling->prevSibling = link->prevSibling; if (link->prevSibling) link->prevSibling->nextSibling = link->nextSibling; if (lastChild == link) lastChild = link->prevSibling; if (firstChild == link) firstChild = link->nextSibling; delete link; } void CScriptVar::removeAllChildren() { CScriptVarLink *c = firstChild; while (c) { CScriptVarLink *t = c->nextSibling; delete c; c = t; } firstChild = 0; lastChild = 0; } CScriptVar *CScriptVar::getArrayIndex(int idx) { char sIdx[64]; sprintf_s(sIdx, sizeof(sIdx), "%d", idx); CScriptVarLink *link = findChild(sIdx); if (link) return link->var; else return new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_NULL); // undefined } void CScriptVar::setArrayIndex(int idx, CScriptVar *value) { char sIdx[64]; sprintf_s(sIdx, sizeof(sIdx), "%d", idx); CScriptVarLink *link = findChild(sIdx); if (link) { if (value->isUndefined()) removeLink(link); else link->replaceWith(value); } else { if (!value->isUndefined()) addChild(sIdx, value); } } int CScriptVar::getArrayLength() { int highest = -1; if (!isArray()) return 0; CScriptVarLink *link = firstChild; while (link) { if (isNumber(link->name)) { int val = atoi(link->name.c_str()); if (val > highest) highest = val; } link = link->nextSibling; } return highest+1; } int CScriptVar::getChildren() { int n = 0; CScriptVarLink *link = firstChild; while (link) { n++; link = link->nextSibling; } return n; } int CScriptVar::getInt() { /* strtol understands about hex and octal */ if (isInt()) return intData; if (isNull()) return 0; if (isUndefined()) return 0; if (isDouble()) return (int)doubleData; return 0; } double CScriptVar::getDouble() { if (isDouble()) return doubleData; if (isInt()) return intData; if (isNull()) return 0; if (isUndefined()) return 0; return 0; /* or NaN? */ } const string &CScriptVar::getString() { /* Because we can't return a string that is generated on demand. * I should really just use char* :) */ static string s_null = "null"; static string s_undefined = "undefined"; if (isInt()) { char buffer[32]; sprintf_s(buffer, sizeof(buffer), "%ld", intData); data = buffer; return data; } if (isDouble()) { char buffer[32]; sprintf_s(buffer, sizeof(buffer), "%f", doubleData); data = buffer; return data; } if (isNull()) return s_null; if (isUndefined()) return s_undefined; // are we just a string here? return data; } void CScriptVar::setInt(int val) { flags = (flags&~SCRIPTVAR_VARTYPEMASK) | SCRIPTVAR_INTEGER; intData = val; doubleData = 0; data = TINYJS_BLANK_DATA; } void CScriptVar::setDouble(double val) { flags = (flags&~SCRIPTVAR_VARTYPEMASK) | SCRIPTVAR_DOUBLE; doubleData = val; intData = 0; data = TINYJS_BLANK_DATA; } void CScriptVar::setString(const string &str) { // name sure it's not still a number or integer flags = (flags&~SCRIPTVAR_VARTYPEMASK) | SCRIPTVAR_STRING; data = str; intData = 0; doubleData = 0; } void CScriptVar::setUndefined() { // name sure it's not still a number or integer flags = (flags&~SCRIPTVAR_VARTYPEMASK) | SCRIPTVAR_UNDEFINED; data = TINYJS_BLANK_DATA; intData = 0; doubleData = 0; removeAllChildren(); } void CScriptVar::setArray() { // name sure it's not still a number or integer flags = (flags&~SCRIPTVAR_VARTYPEMASK) | SCRIPTVAR_ARRAY; data = TINYJS_BLANK_DATA; intData = 0; doubleData = 0; removeAllChildren(); } bool CScriptVar::equals(CScriptVar *v) { CScriptVar *resV = mathsOp(v, LEX_EQUAL); bool res = resV->getBool(); delete resV; return res; } CScriptVar *CScriptVar::mathsOp(CScriptVar *b, int op) { CScriptVar *a = this; // Type equality check if (op == LEX_TYPEEQUAL || op == LEX_NTYPEEQUAL) { // check type first, then call again to check data bool eql = ((a->flags & SCRIPTVAR_VARTYPEMASK) == (b->flags & SCRIPTVAR_VARTYPEMASK)); if (eql) { CScriptVar *contents = a->mathsOp(b, LEX_EQUAL); if (!contents->getBool()) eql = false; if (!contents->refs) delete contents; } ; if (op == LEX_TYPEEQUAL) return new CScriptVar(eql); else return new CScriptVar(!eql); } // do maths... if (a->isUndefined() && b->isUndefined()) { if (op == LEX_EQUAL) return new CScriptVar(true); else if (op == LEX_NEQUAL) return new CScriptVar(false); else return new CScriptVar(); // undefined } else if ((a->isNumeric() || a->isUndefined()) && (b->isNumeric() || b->isUndefined())) { if (!a->isDouble() && !b->isDouble()) { // use ints int da = a->getInt(); int db = b->getInt(); switch (op) { case '+': return new CScriptVar(da+db); case '-': return new CScriptVar(da-db); case '*': return new CScriptVar(da*db); case '/': return new CScriptVar(da/db); case '&': return new CScriptVar(da&db); case '|': return new CScriptVar(da|db); case '^': return new CScriptVar(da^db); case '%': return new CScriptVar(da%db); case LEX_EQUAL: return new CScriptVar(da==db); case LEX_NEQUAL: return new CScriptVar(da!=db); case '<': return new CScriptVar(da<db); case LEX_LEQUAL: return new CScriptVar(da<=db); case '>': return new CScriptVar(da>db); case LEX_GEQUAL: return new CScriptVar(da>=db); default: throw new CScriptException("Operation "+CScriptLex::getTokenStr(op)+" not supported on the Int datatype"); } } else { // use doubles double da = a->getDouble(); double db = b->getDouble(); switch (op) { case '+': return new CScriptVar(da+db); case '-': return new CScriptVar(da-db); case '*': return new CScriptVar(da*db); case '/': return new CScriptVar(da/db); case LEX_EQUAL: return new CScriptVar(da==db); case LEX_NEQUAL: return new CScriptVar(da!=db); case '<': return new CScriptVar(da<db); case LEX_LEQUAL: return new CScriptVar(da<=db); case '>': return new CScriptVar(da>db); case LEX_GEQUAL: return new CScriptVar(da>=db); default: throw new CScriptException("Operation "+CScriptLex::getTokenStr(op)+" not supported on the Double datatype"); } } } else if (a->isArray()) { /* Just check pointers */ switch (op) { case LEX_EQUAL: return new CScriptVar(a==b); case LEX_NEQUAL: return new CScriptVar(a!=b); default: throw new CScriptException("Operation "+CScriptLex::getTokenStr(op)+" not supported on the Array datatype"); } } else if (a->isObject()) { /* Just check pointers */ switch (op) { case LEX_EQUAL: return new CScriptVar(a==b); case LEX_NEQUAL: return new CScriptVar(a!=b); default: throw new CScriptException("Operation "+CScriptLex::getTokenStr(op)+" not supported on the Object datatype"); } } else { string da = a->getString(); string db = b->getString(); // use strings switch (op) { case '+': return new CScriptVar(da+db, SCRIPTVAR_STRING); case LEX_EQUAL: return new CScriptVar(da==db); case LEX_NEQUAL: return new CScriptVar(da!=db); case '<': return new CScriptVar(da<db); case LEX_LEQUAL: return new CScriptVar(da<=db); case '>': return new CScriptVar(da>db); case LEX_GEQUAL: return new CScriptVar(da>=db); default: throw new CScriptException("Operation "+CScriptLex::getTokenStr(op)+" not supported on the string datatype"); } } ASSERT(0); return 0; } void CScriptVar::copySimpleData(CScriptVar *val) { data = val->data; intData = val->intData; doubleData = val->doubleData; flags = (flags & ~SCRIPTVAR_VARTYPEMASK) | (val->flags & SCRIPTVAR_VARTYPEMASK); } void CScriptVar::copyValue(CScriptVar *val) { if (val) { copySimpleData(val); // remove all current children removeAllChildren(); // copy children of 'val' CScriptVarLink *child = val->firstChild; while (child) { CScriptVar *copied; // don't copy the 'parent' object... if (child->name != TINYJS_PROTOTYPE_CLASS) copied = child->var->deepCopy(); else copied = child->var; addChild(child->name, copied); child = child->nextSibling; } } else { setUndefined(); } } CScriptVar *CScriptVar::deepCopy() { CScriptVar *newVar = new CScriptVar(); newVar->copySimpleData(this); // copy children CScriptVarLink *child = firstChild; while (child) { CScriptVar *copied; // don't copy the 'parent' object... if (child->name != TINYJS_PROTOTYPE_CLASS) copied = child->var->deepCopy(); else copied = child->var; newVar->addChild(child->name, copied); child = child->nextSibling; } return newVar; } void CScriptVar::trace(string indentStr, const string &name) { TRACE("%s'%s' = '%s' %s\n", indentStr.c_str(), name.c_str(), getString().c_str(), getFlagsAsString().c_str()); string indent = indentStr+" "; CScriptVarLink *link = firstChild; while (link) { link->var->trace(indent, link->name); link = link->nextSibling; } } string CScriptVar::getFlagsAsString() { string flagstr = ""; if (flags&SCRIPTVAR_FUNCTION) flagstr = flagstr + "FUNCTION "; if (flags&SCRIPTVAR_OBJECT) flagstr = flagstr + "OBJECT "; if (flags&SCRIPTVAR_ARRAY) flagstr = flagstr + "ARRAY "; if (flags&SCRIPTVAR_NATIVE) flagstr = flagstr + "NATIVE "; if (flags&SCRIPTVAR_DOUBLE) flagstr = flagstr + "DOUBLE "; if (flags&SCRIPTVAR_INTEGER) flagstr = flagstr + "INTEGER "; if (flags&SCRIPTVAR_STRING) flagstr = flagstr + "STRING "; return flagstr; } string CScriptVar::getParsableString() { // Numbers can just be put in directly if (isNumeric()) return getString(); if (isFunction()) { ostringstream funcStr; funcStr << "function ("; // get list of parameters CScriptVarLink *link = firstChild; while (link) { funcStr << link->name; if (link->nextSibling) funcStr << ","; link = link->nextSibling; } // add function body funcStr << ") " << getString(); return funcStr.str(); } // if it is a string then we quote it if (isString()) return getJSString(getString()); if (isNull()) return "null"; return "undefined"; } void CScriptVar::getJSON(ostringstream &destination, const string linePrefix) { if (isObject()) { string indentedLinePrefix = linePrefix+" "; // children - handle with bracketed list destination << "{ \n"; CScriptVarLink *link = firstChild; while (link) { destination << indentedLinePrefix; destination << getJSString(link->name); destination << " : "; link->var->getJSON(destination, indentedLinePrefix); link = link->nextSibling; if (link) { destination << ",\n"; } } destination << "\n" << linePrefix << "}"; } else if (isArray()) { string indentedLinePrefix = linePrefix+" "; destination << "[\n"; int len = getArrayLength(); if (len>10000) len=10000; // we don't want to get stuck here! for (int i=0;i<len;i++) { getArrayIndex(i)->getJSON(destination, indentedLinePrefix); if (i<len-1) destination << ",\n"; } destination << "\n" << linePrefix << "]"; } else { // no children or a function... just write value directly destination << getParsableString(); } } void CScriptVar::setCallback(JSCallback callback, void *userdata) { jsCallback = callback; jsCallbackUserData = userdata; } CScriptVar *CScriptVar::ref() { refs++; return this; } void CScriptVar::unref() { if (refs<=0) printf("OMFG, we have unreffed too far!\n"); if ((--refs)==0) { delete this; } } int CScriptVar::getRefs() { return refs; } // ----------------------------------------------------------------------------------- CSCRIPT CTinyJS::CTinyJS() { l = 0; root = (new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_OBJECT))->ref(); // Add built-in classes stringClass = (new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_OBJECT))->ref(); arrayClass = (new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_OBJECT))->ref(); objectClass = (new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_OBJECT))->ref(); root->addChild("String", stringClass); root->addChild("Array", arrayClass); root->addChild("Object", objectClass); } CTinyJS::~CTinyJS() { ASSERT(!l); scopes.clear(); stringClass->unref(); arrayClass->unref(); objectClass->unref(); root->unref(); #if DEBUG_MEMORY show_allocated(); #endif } void CTinyJS::trace() { root->trace(); } void CTinyJS::execute(const string &code) { CScriptLex *oldLex = l; vector<CScriptVar*> oldScopes = scopes; l = new CScriptLex(code); #ifdef TINYJS_CALL_STACK call_stack.clear(); #endif scopes.clear(); scopes.push_back(root); try { bool execute = true; while (l->tk) statement(execute); } catch (CScriptException *e) { ostringstream msg; msg << "Error " << e->text; #ifdef TINYJS_CALL_STACK for (int i=(int)call_stack.size()-1;i>=0;i--) msg << "\n" << i << ": " << call_stack.at(i); #endif msg << " at " << l->getPosition(); delete l; l = oldLex; throw new CScriptException(msg.str()); } delete l; l = oldLex; scopes = oldScopes; } CScriptVarLink CTinyJS::evaluateComplex(const string &code) { CScriptLex *oldLex = l; vector<CScriptVar*> oldScopes = scopes; l = new CScriptLex(code); #ifdef TINYJS_CALL_STACK call_stack.clear(); #endif scopes.clear(); scopes.push_back(root); CScriptVarLink *v = 0; try { bool execute = true; do { CLEAN(v); v = base(execute); if (l->tk!=LEX_EOF) l->match(';'); } while (l->tk!=LEX_EOF); } catch (CScriptException *e) { ostringstream msg; msg << "Error " << e->text; #ifdef TINYJS_CALL_STACK for (int i=(int)call_stack.size()-1;i>=0;i--) msg << "\n" << i << ": " << call_stack.at(i); #endif msg << " at " << l->getPosition(); delete l; l = oldLex; throw new CScriptException(msg.str()); } delete l; l = oldLex; scopes = oldScopes; if (v) { CScriptVarLink r = *v; CLEAN(v); return r; } // return undefined... return CScriptVarLink(new CScriptVar()); } string CTinyJS::evaluate(const string &code) { return evaluateComplex(code).var->getString(); } void CTinyJS::parseFunctionArguments(CScriptVar *funcVar) { l->match('('); while (l->tk!=')') { funcVar->addChildNoDup(l->tkStr); l->match(LEX_ID); if (l->tk!=')') l->match(','); } l->match(')'); } void CTinyJS::addNative(const string &funcDesc, JSCallback ptr, void *userdata) { CScriptLex *oldLex = l; l = new CScriptLex(funcDesc); CScriptVar *base = root; l->match(LEX_R_FUNCTION); string funcName = l->tkStr; l->match(LEX_ID); /* Check for dots, we might want to do something like function String.substring ... */ while (l->tk == '.') { l->match('.'); CScriptVarLink *link = base->findChild(funcName); // if it doesn't exist, make an object class if (!link) link = base->addChild(funcName, new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_OBJECT)); base = link->var; funcName = l->tkStr; l->match(LEX_ID); } CScriptVar *funcVar = new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_FUNCTION | SCRIPTVAR_NATIVE); funcVar->setCallback(ptr, userdata); parseFunctionArguments(funcVar); delete l; l = oldLex; base->addChild(funcName, funcVar); } CScriptVarLink *CTinyJS::parseFunctionDefinition() { // actually parse a function... l->match(LEX_R_FUNCTION); string funcName = TINYJS_TEMP_NAME; /* we can have functions without names */ if (l->tk==LEX_ID) { funcName = l->tkStr; l->match(LEX_ID); } CScriptVarLink *funcVar = new CScriptVarLink(new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_FUNCTION), funcName); parseFunctionArguments(funcVar->var); int funcBegin = l->tokenStart; bool noexecute = false; block(noexecute); funcVar->var->data = l->getSubString(funcBegin); return funcVar; } /** Handle a function call (assumes we've parsed the function name and we're * on the start bracket). 'parent' is the object that contains this method, * if there was one (otherwise it's just a normnal function). */ CScriptVarLink *CTinyJS::functionCall(bool &execute, CScriptVarLink *function, CScriptVar *parent) { if (execute) { if (!function->var->isFunction()) { string errorMsg = "Expecting '"; errorMsg = errorMsg + function->name + "' to be a function"; throw new CScriptException(errorMsg.c_str()); } l->match('('); // create a new symbol table entry for execution of this function CScriptVar *functionRoot = new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_FUNCTION); if (parent) functionRoot->addChildNoDup("this", parent); // grab in all parameters CScriptVarLink *v = function->var->firstChild; while (v) { CScriptVarLink *value = base(execute); if (execute) { if (value->var->isBasic()) { // pass by value functionRoot->addChild(v->name, value->var->deepCopy()); } else { // pass by reference functionRoot->addChild(v->name, value->var); } } CLEAN(value); if (l->tk!=')') l->match(','); v = v->nextSibling; } l->match(')'); // setup a return variable CScriptVarLink *returnVar = NULL; // execute function! // add the function's execute space to the symbol table so we can recurse CScriptVarLink *returnVarLink = functionRoot->addChild(TINYJS_RETURN_VAR); scopes.push_back(functionRoot); #ifdef TINYJS_CALL_STACK call_stack.push_back(function->name + " from " + l->getPosition()); #endif if (function->var->isNative()) { ASSERT(function->var->jsCallback); function->var->jsCallback(functionRoot, function->var->jsCallbackUserData); } else { /* we just want to execute the block, but something could * have messed up and left us with the wrong ScriptLex, so * we want to be careful here... */ CScriptException *exception = 0; CScriptLex *oldLex = l; CScriptLex *newLex = new CScriptLex(function->var->getString()); l = newLex; try { block(execute); // because return will probably have called this, and set execute to false execute = true; } catch (CScriptException *e) { exception = e; } delete newLex; l = oldLex; if (exception) throw exception; } #ifdef TINYJS_CALL_STACK if (!call_stack.empty()) call_stack.pop_back(); #endif scopes.pop_back(); /* get the real return var before we remove it from our function */ returnVar = new CScriptVarLink(returnVarLink->var); functionRoot->removeLink(returnVarLink); delete functionRoot; if (returnVar) return returnVar; else return new CScriptVarLink(new CScriptVar()); } else { // function, but not executing - just parse args and be done l->match('('); while (l->tk != ')') { CScriptVarLink *value = base(execute); CLEAN(value); if (l->tk!=')') l->match(','); } l->match(')'); if (l->tk == '{') { // TODO: why is this here? block(execute); } /* function will be a blank scriptvarlink if we're not executing, * so just return it rather than an alloc/free */ return function; } } CScriptVarLink *CTinyJS::factor(bool &execute) { if (l->tk=='(') { l->match('('); CScriptVarLink *a = base(execute); l->match(')'); return a; } if (l->tk==LEX_R_TRUE) { l->match(LEX_R_TRUE); return new CScriptVarLink(new CScriptVar(1)); } if (l->tk==LEX_R_FALSE) { l->match(LEX_R_FALSE); return new CScriptVarLink(new CScriptVar(0)); } if (l->tk==LEX_R_NULL) { l->match(LEX_R_NULL); return new CScriptVarLink(new CScriptVar(TINYJS_BLANK_DATA,SCRIPTVAR_NULL)); } if (l->tk==LEX_R_UNDEFINED) { l->match(LEX_R_UNDEFINED); return new CScriptVarLink(new CScriptVar(TINYJS_BLANK_DATA,SCRIPTVAR_UNDEFINED)); } if (l->tk==LEX_ID) { CScriptVarLink *a = execute ? findInScopes(l->tkStr) : new CScriptVarLink(new CScriptVar()); //printf("0x%08X for %s at %s\n", (unsigned int)a, l->tkStr.c_str(), l->getPosition().c_str()); /* The parent if we're executing a method call */ CScriptVar *parent = 0; if (execute && !a) { /* Variable doesn't exist! JavaScript says we should create it * (we won't add it here. This is done in the assignment operator)*/ a = new CScriptVarLink(new CScriptVar(), l->tkStr); } l->match(LEX_ID); while (l->tk=='(' || l->tk=='.' || l->tk=='[') { if (l->tk=='(') { // ------------------------------------- Function Call a = functionCall(execute, a, parent); } else if (l->tk == '.') { // ------------------------------------- Record Access l->match('.'); if (execute) { const string &name = l->tkStr; CScriptVarLink *child = a->var->findChild(name); if (!child) child = findInParentClasses(a->var, name); if (!child) { /* if we haven't found this defined yet, use the built-in 'length' properly */ if (a->var->isArray() && name == "length") { int l = a->var->getArrayLength(); child = new CScriptVarLink(new CScriptVar(l)); } else if (a->var->isString() && name == "length") { int l = a->var->getString().size(); child = new CScriptVarLink(new CScriptVar(l)); } else { child = a->var->addChild(name); } } parent = a->var; a = child; } l->match(LEX_ID); } else if (l->tk == '[') { // ------------------------------------- Array Access l->match('['); CScriptVarLink *index = base(execute); l->match(']'); if (execute) { CScriptVarLink *child = a->var->findChildOrCreate(index->var->getString()); parent = a->var; a = child; } CLEAN(index); } else ASSERT(0); } return a; } if (l->tk==LEX_INT || l->tk==LEX_FLOAT) { CScriptVar *a = new CScriptVar(l->tkStr, ((l->tk==LEX_INT)?SCRIPTVAR_INTEGER:SCRIPTVAR_DOUBLE)); l->match(l->tk); return new CScriptVarLink(a); } if (l->tk==LEX_STR) { CScriptVar *a = new CScriptVar(l->tkStr, SCRIPTVAR_STRING); l->match(LEX_STR); return new CScriptVarLink(a); } if (l->tk=='{') { CScriptVar *contents = new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_OBJECT); /* JSON-style object definition */ l->match('{'); while (l->tk != '}') { string id = l->tkStr; // we only allow strings or IDs on the left hand side of an initialisation if (l->tk==LEX_STR) l->match(LEX_STR); else l->match(LEX_ID); l->match(':'); if (execute) { CScriptVarLink *a = base(execute); contents->addChild(id, a->var); CLEAN(a); } // no need to clean here, as it will definitely be used if (l->tk != '}') l->match(','); } l->match('}'); return new CScriptVarLink(contents); } if (l->tk=='[') { CScriptVar *contents = new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_ARRAY); /* JSON-style array */ l->match('['); int idx = 0; while (l->tk != ']') { if (execute) { char idx_str[16]; // big enough for 2^32 sprintf_s(idx_str, sizeof(idx_str), "%d",idx); CScriptVarLink *a = base(execute); contents->addChild(idx_str, a->var); CLEAN(a); } // no need to clean here, as it will definitely be used if (l->tk != ']') l->match(','); idx++; } l->match(']'); return new CScriptVarLink(contents); } if (l->tk==LEX_R_FUNCTION) { CScriptVarLink *funcVar = parseFunctionDefinition(); if (funcVar->name != TINYJS_TEMP_NAME) TRACE("Functions not defined at statement-level are not meant to have a name"); return funcVar; } if (l->tk==LEX_R_NEW) { // new -> create a new object l->match(LEX_R_NEW); const string &className = l->tkStr; if (execute) { CScriptVarLink *objClassOrFunc = findInScopes(className); if (!objClassOrFunc) { TRACE("%s is not a valid class name", className.c_str()); return new CScriptVarLink(new CScriptVar()); } l->match(LEX_ID); CScriptVar *obj = new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_OBJECT); CScriptVarLink *objLink = new CScriptVarLink(obj); if (objClassOrFunc->var->isFunction()) { CLEAN(functionCall(execute, objClassOrFunc, obj)); } else { obj->addChild(TINYJS_PROTOTYPE_CLASS, objClassOrFunc->var); if (l->tk == '(') { l->match('('); l->match(')'); } } return objLink; } else { l->match(LEX_ID); if (l->tk == '(') { l->match('('); l->match(')'); } } } // Nothing we can do here... just hope it's the end... l->match(LEX_EOF); return 0; } CScriptVarLink *CTinyJS::unary(bool &execute) { CScriptVarLink *a; if (l->tk=='!') { l->match('!'); // binary not a = factor(execute); if (execute) { CScriptVar zero(0); CScriptVar *res = a->var->mathsOp(&zero, LEX_EQUAL); CREATE_LINK(a, res); } } else a = factor(execute); return a; } CScriptVarLink *CTinyJS::term(bool &execute) { CScriptVarLink *a = unary(execute); while (l->tk=='*' || l->tk=='/' || l->tk=='%') { int op = l->tk; l->match(l->tk); CScriptVarLink *b = unary(execute); if (execute) { CScriptVar *res = a->var->mathsOp(b->var, op); CREATE_LINK(a, res); } CLEAN(b); } return a; } CScriptVarLink *CTinyJS::expression(bool &execute) { bool negate = false; if (l->tk=='-') { l->match('-'); negate = true; } CScriptVarLink *a = term(execute); if (negate) { CScriptVar zero(0); CScriptVar *res = zero.mathsOp(a->var, '-'); CREATE_LINK(a, res); } while (l->tk=='+' || l->tk=='-' || l->tk==LEX_PLUSPLUS || l->tk==LEX_MINUSMINUS) { int op = l->tk; l->match(l->tk); if (op==LEX_PLUSPLUS || op==LEX_MINUSMINUS) { if (execute) { CScriptVar one(1); CScriptVar *res = a->var->mathsOp(&one, op==LEX_PLUSPLUS ? '+' : '-'); CScriptVarLink *oldValue = new CScriptVarLink(a->var); // in-place add/subtract a->replaceWith(res); CLEAN(a); a = oldValue; } } else { CScriptVarLink *b = term(execute); if (execute) { // not in-place, so just replace CScriptVar *res = a->var->mathsOp(b->var, op); CREATE_LINK(a, res); } CLEAN(b); } } return a; } CScriptVarLink *CTinyJS::shift(bool &execute) { CScriptVarLink *a = expression(execute); if (l->tk==LEX_LSHIFT || l->tk==LEX_RSHIFT || l->tk==LEX_RSHIFTUNSIGNED) { int op = l->tk; l->match(op); CScriptVarLink *b = base(execute); int shift = execute ? b->var->getInt() : 0; CLEAN(b); if (execute) { if (op==LEX_LSHIFT) a->var->setInt(a->var->getInt() << shift); if (op==LEX_RSHIFT) a->var->setInt(a->var->getInt() >> shift); if (op==LEX_RSHIFTUNSIGNED) a->var->setInt(((unsigned int)a->var->getInt()) >> shift); } } return a; } CScriptVarLink *CTinyJS::condition(bool &execute) { CScriptVarLink *a = shift(execute); CScriptVarLink *b; while (l->tk==LEX_EQUAL || l->tk==LEX_NEQUAL || l->tk==LEX_TYPEEQUAL || l->tk==LEX_NTYPEEQUAL || l->tk==LEX_LEQUAL || l->tk==LEX_GEQUAL || l->tk=='<' || l->tk=='>') { int op = l->tk; l->match(l->tk); b = shift(execute); if (execute) { CScriptVar *res = a->var->mathsOp(b->var, op); CREATE_LINK(a,res); } CLEAN(b); } return a; } CScriptVarLink *CTinyJS::logic(bool &execute) { CScriptVarLink *a = condition(execute); CScriptVarLink *b; while (l->tk=='&' || l->tk=='|' || l->tk=='^' || l->tk==LEX_ANDAND || l->tk==LEX_OROR) { bool noexecute = false; int op = l->tk; l->match(l->tk); bool shortCircuit = false; bool boolean = false; // if we have short-circuit ops, then if we know the outcome // we don't bother to execute the other op. Even if not // we need to tell mathsOp it's an & or | if (op==LEX_ANDAND) { op = '&'; shortCircuit = !a->var->getBool(); boolean = true; } else if (op==LEX_OROR) { op = '|'; shortCircuit = a->var->getBool(); boolean = true; } b = condition(shortCircuit ? noexecute : execute); if (execute && !shortCircuit) { if (boolean) { CScriptVar *newa = new CScriptVar(a->var->getBool()); CScriptVar *newb = new CScriptVar(b->var->getBool()); CREATE_LINK(a, newa); CREATE_LINK(b, newb); } CScriptVar *res = a->var->mathsOp(b->var, op); CREATE_LINK(a, res); } CLEAN(b); } return a; } CScriptVarLink *CTinyJS::ternary(bool &execute) { CScriptVarLink *lhs = logic(execute); bool noexec = false; if (l->tk=='?') { l->match('?'); if (!execute) { CLEAN(lhs); CLEAN(base(noexec)); l->match(':'); CLEAN(base(noexec)); } else { bool first = lhs->var->getBool(); CLEAN(lhs); if (first) { lhs = base(execute); l->match(':'); CLEAN(base(noexec)); } else { CLEAN(base(noexec)); l->match(':'); lhs = base(execute); } } } return lhs; } CScriptVarLink *CTinyJS::base(bool &execute) { CScriptVarLink *lhs = ternary(execute); if (l->tk=='=' || l->tk==LEX_PLUSEQUAL || l->tk==LEX_MINUSEQUAL) { /* If we're assigning to this and we don't have a parent, * add it to the symbol table root as per JavaScript. */ if (execute && !lhs->owned) { if (lhs->name.length()>0) { CScriptVarLink *realLhs = root->addChildNoDup(lhs->name, lhs->var); CLEAN(lhs); lhs = realLhs; } else TRACE("Trying to assign to an un-named type\n"); } int op = l->tk; l->match(l->tk); CScriptVarLink *rhs = base(execute); if (execute) { if (op=='=') { lhs->replaceWith(rhs); } else if (op==LEX_PLUSEQUAL) { CScriptVar *res = lhs->var->mathsOp(rhs->var, '+'); lhs->replaceWith(res); } else if (op==LEX_MINUSEQUAL) { CScriptVar *res = lhs->var->mathsOp(rhs->var, '-'); lhs->replaceWith(res); } else ASSERT(0); } CLEAN(rhs); } return lhs; } void CTinyJS::block(bool &execute) { l->match('{'); if (execute) { while (l->tk && l->tk!='}') statement(execute); l->match('}'); } else { // fast skip of blocks int brackets = 1; while (l->tk && brackets) { if (l->tk == '{') brackets++; if (l->tk == '}') brackets--; l->match(l->tk); } } } void CTinyJS::statement(bool &execute) { if (l->tk==LEX_ID || l->tk==LEX_INT || l->tk==LEX_FLOAT || l->tk==LEX_STR || l->tk=='-') { /* Execute a simple statement that only contains basic arithmetic... */ CLEAN(base(execute)); l->match(';'); } else if (l->tk=='{') { /* A block of code */ block(execute); } else if (l->tk==';') { /* Empty statement - to allow things like ;;; */ l->match(';'); } else if (l->tk==LEX_R_VAR) { /* variable creation. TODO - we need a better way of parsing the left * hand side. Maybe just have a flag called can_create_var that we * set and then we parse as if we're doing a normal equals.*/ l->match(LEX_R_VAR); while (l->tk != ';') { CScriptVarLink *a = 0; if (execute) a = scopes.back()->findChildOrCreate(l->tkStr); l->match(LEX_ID); // now do stuff defined with dots while (l->tk == '.') { l->match('.'); if (execute) { CScriptVarLink *lastA = a; a = lastA->var->findChildOrCreate(l->tkStr); } l->match(LEX_ID); } // sort out initialiser if (l->tk == '=') { l->match('='); CScriptVarLink *var = base(execute); if (execute) a->replaceWith(var); CLEAN(var); } if (l->tk != ';') l->match(','); } l->match(';'); } else if (l->tk==LEX_R_IF) { l->match(LEX_R_IF); l->match('('); CScriptVarLink *var = base(execute); l->match(')'); bool cond = execute && var->var->getBool(); CLEAN(var); bool noexecute = false; // because we need to be abl;e to write to it statement(cond ? execute : noexecute); if (l->tk==LEX_R_ELSE) { l->match(LEX_R_ELSE); statement(cond ? noexecute : execute); } } else if (l->tk==LEX_R_WHILE) { // We do repetition by pulling out the string representing our statement // there's definitely some opportunity for optimisation here l->match(LEX_R_WHILE); l->match('('); int whileCondStart = l->tokenStart; bool noexecute = false; CScriptVarLink *cond = base(execute); bool loopCond = execute && cond->var->getBool(); CLEAN(cond); CScriptLex *whileCond = l->getSubLex(whileCondStart); l->match(')'); int whileBodyStart = l->tokenStart; statement(loopCond ? execute : noexecute); CScriptLex *whileBody = l->getSubLex(whileBodyStart); CScriptLex *oldLex = l; int loopCount = TINYJS_LOOP_MAX_ITERATIONS; while (loopCond && loopCount-->0) { whileCond->reset(); l = whileCond; cond = base(execute); loopCond = execute && cond->var->getBool(); CLEAN(cond); if (loopCond) { whileBody->reset(); l = whileBody; statement(execute); } } l = oldLex; delete whileCond; delete whileBody; if (loopCount<=0) { root->trace(); TRACE("WHILE Loop exceeded %d iterations at %s\n", TINYJS_LOOP_MAX_ITERATIONS, l->getPosition().c_str()); throw new CScriptException("LOOP_ERROR"); } } else if (l->tk==LEX_R_FOR) { l->match(LEX_R_FOR); l->match('('); statement(execute); // initialisation //l->match(';'); int forCondStart = l->tokenStart; bool noexecute = false; CScriptVarLink *cond = base(execute); // condition bool loopCond = execute && cond->var->getBool(); CLEAN(cond); CScriptLex *forCond = l->getSubLex(forCondStart); l->match(';'); int forIterStart = l->tokenStart; CLEAN(base(noexecute)); // iterator CScriptLex *forIter = l->getSubLex(forIterStart); l->match(')'); int forBodyStart = l->tokenStart; statement(loopCond ? execute : noexecute); CScriptLex *forBody = l->getSubLex(forBodyStart); CScriptLex *oldLex = l; if (loopCond) { forIter->reset(); l = forIter; CLEAN(base(execute)); } int loopCount = TINYJS_LOOP_MAX_ITERATIONS; while (execute && loopCond && loopCount-->0) { forCond->reset(); l = forCond; cond = base(execute); loopCond = cond->var->getBool(); CLEAN(cond); if (execute && loopCond) { forBody->reset(); l = forBody; statement(execute); } if (execute && loopCond) { forIter->reset(); l = forIter; CLEAN(base(execute)); } } l = oldLex; delete forCond; delete forIter; delete forBody; if (loopCount<=0) { root->trace(); TRACE("FOR Loop exceeded %d iterations at %s\n", TINYJS_LOOP_MAX_ITERATIONS, l->getPosition().c_str()); throw new CScriptException("LOOP_ERROR"); } } else if (l->tk==LEX_R_RETURN) { l->match(LEX_R_RETURN); CScriptVarLink *result = 0; if (l->tk != ';') result = base(execute); if (execute) { CScriptVarLink *resultVar = scopes.back()->findChild(TINYJS_RETURN_VAR); if (resultVar) resultVar->replaceWith(result); else TRACE("RETURN statement, but not in a function.\n"); execute = false; } CLEAN(result); l->match(';'); } else if (l->tk==LEX_R_FUNCTION) { CScriptVarLink *funcVar = parseFunctionDefinition(); if (execute) { if (funcVar->name == TINYJS_TEMP_NAME) TRACE("Functions defined at statement-level are meant to have a name\n"); else scopes.back()->addChildNoDup(funcVar->name, funcVar->var); } CLEAN(funcVar); } else l->match(LEX_EOF); } /// Get the given variable specified by a path (var1.var2.etc), or return 0 CScriptVar *CTinyJS::getScriptVariable(const string &path) { // traverse path size_t prevIdx = 0; size_t thisIdx = path.find('.'); if (thisIdx == string::npos) thisIdx = path.length(); CScriptVar *var = root; while (var && prevIdx<path.length()) { string el = path.substr(prevIdx, thisIdx-prevIdx); CScriptVarLink *varl = var->findChild(el); var = varl?varl->var:0; prevIdx = thisIdx+1; thisIdx = path.find('.', prevIdx); if (thisIdx == string::npos) thisIdx = path.length(); } return var; } /// Get the value of the given variable, or return 0 const string *CTinyJS::getVariable(const string &path) { CScriptVar *var = getScriptVariable(path); // return result if (var) return &var->getString(); else return 0; } /// set the value of the given variable, return trur if it exists and gets set bool CTinyJS::setVariable(const std::string &path, const std::string &varData) { CScriptVar *var = getScriptVariable(path); // return result if (var) { if (var->isInt()) var->setInt((int)strtol(varData.c_str(),0,0)); else if (var->isDouble()) var->setDouble(strtod(varData.c_str(),0)); else var->setString(varData.c_str()); return true; } else return false; } /// Finds a child, looking recursively up the scopes CScriptVarLink *CTinyJS::findInScopes(const std::string &childName) { for (int s=scopes.size()-1;s>=0;s--) { CScriptVarLink *v = scopes[s]->findChild(childName); if (v) return v; } return NULL; } /// Look up in any parent classes of the given object CScriptVarLink *CTinyJS::findInParentClasses(CScriptVar *object, const std::string &name) { // Look for links to actual parent classes CScriptVarLink *parentClass = object->findChild(TINYJS_PROTOTYPE_CLASS); while (parentClass) { CScriptVarLink *implementation = parentClass->var->findChild(name); if (implementation) return implementation; parentClass = parentClass->var->findChild(TINYJS_PROTOTYPE_CLASS); } // else fake it for strings and finally objects if (object->isString()) { CScriptVarLink *implementation = stringClass->findChild(name); if (implementation) return implementation; } if (object->isArray()) { CScriptVarLink *implementation = arrayClass->findChild(name); if (implementation) return implementation; } CScriptVarLink *implementation = objectClass->findChild(name); if (implementation) return implementation; return 0; }
33,030
323
<gh_stars>100-1000 #include "register_types.h" #include "image_frames.h" #include "image_frames_loader.h" #include "image_frames_loader_gif.h" #ifdef TOOLS_ENABLED #include "editor/import/resource_importer_animated_texture.h" #include "editor/import/resource_importer_sprite_frames.h" #endif static ImageFramesLoaderGIF *image_frames_loader_gif = nullptr; static Ref<ResourceFormatLoaderImageFrames> resource_format_image_frames; static Ref<ResourceFormatLoaderAnimatedTexture> resource_format_animated_texture; static Ref<ResourceFormatLoaderSpriteFrames> resource_format_sprite_frames; void register_gif_types() { image_frames_loader_gif = memnew(ImageFramesLoaderGIF); ImageFramesLoader::add_image_frames_format_loader(image_frames_loader_gif); resource_format_image_frames.instance(); ResourceLoader::add_resource_format_loader(resource_format_image_frames); resource_format_animated_texture.instance(); ResourceLoader::add_resource_format_loader(resource_format_animated_texture); resource_format_sprite_frames.instance(); ResourceLoader::add_resource_format_loader(resource_format_sprite_frames); ClassDB::register_class<ImageFrames>(); #ifdef TOOLS_ENABLED Ref<ResourceImporterAnimatedTexture> import_animated_texture; import_animated_texture.instance(); ResourceFormatImporter::get_singleton()->add_importer(import_animated_texture); Ref<ResourceImporterSpriteFrames> import_sprite_frames; import_sprite_frames.instance(); ResourceFormatImporter::get_singleton()->add_importer(import_sprite_frames); #endif } void unregister_gif_types() { ImageFramesLoader::remove_image_frames_format_loader(image_frames_loader_gif); if (image_frames_loader_gif) { memdelete(image_frames_loader_gif); } ResourceLoader::remove_resource_format_loader(resource_format_image_frames); resource_format_image_frames.unref(); ResourceLoader::remove_resource_format_loader(resource_format_animated_texture); resource_format_animated_texture.unref(); ResourceLoader::remove_resource_format_loader(resource_format_sprite_frames); resource_format_sprite_frames.unref(); }
657
475
// Copyright (c) 2015-2016 <NAME> // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 // http://vittorioromeo.info | <EMAIL> #pragma once #define ECST_IMPL_NAMESPACE namespace ecst #define ECST_IMPL_NAMESPACE_END /// @macro Opens the `ecst` namespace. #define ECST_NAMESPACE ECST_IMPL_NAMESPACE /// @macro Closes the `ecst` namespace. #define ECST_NAMESPACE_END ECST_IMPL_NAMESPACE_END
180
367
#include <pybind11/pybind11.h> namespace py = pybind11; namespace { void overloadedFunction(int, float) {} void overloadedFunction(int) {} } PYBIND11_MODULE(pybind, m) { m .def("overloaded_function", static_cast<void(*)(int, float)>(&overloadedFunction)) .def("overloaded_function", static_cast<void(*)(int)>(&overloadedFunction)); }
139
60,067
#pragma once #include <istream> #include "c10/macros/Macros.h" #include "caffe2/serialize/read_adapter_interface.h" namespace caffe2 { namespace serialize { // this is a reader implemented by std::istream class TORCH_API IStreamAdapter final : public ReadAdapterInterface { public: C10_DISABLE_COPY_AND_ASSIGN(IStreamAdapter); explicit IStreamAdapter(std::istream* istream); size_t size() const override; size_t read(uint64_t pos, void* buf, size_t n, const char* what = "") const override; ~IStreamAdapter() override; private: std::istream* istream_; void validate(const char* what) const; }; } // namespace serialize } // namespace caffe2
231
2,542
<reponame>AnthonyM/service-fabric // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace ServiceModel; using namespace Hosting2; ActivateContainerRequest::ActivateContainerRequest() : activationArgs_() , timeoutTicks_() { } ActivateContainerRequest::ActivateContainerRequest( ContainerActivationArgs && activationArgs, int64 timeoutTicks) : activationArgs_(move(activationArgs)) , timeoutTicks_(timeoutTicks) { } void ActivateContainerRequest::WriteTo(TextWriter & w, FormatOptions const &) const { w.Write("ActivateContainerRequest { "); w.Write("ActivationArgs = {0}", activationArgs_); w.Write("TimeoutTicks = {0}", timeoutTicks_); w.Write("}"); }
284
746
// Copyright (c) OpenMMLab. All rights reserved. #ifndef MMDEPLOY_CSRC_EXPERIMENTAL_EXECUTION_INFERENCE_H_ #define MMDEPLOY_CSRC_EXPERIMENTAL_EXECUTION_INFERENCE_H_ #include "pipeline.h" namespace mmdeploy::graph { class Inference : public Node { friend class InferenceParser; public: Sender<Value> Process(Sender<Value> input) override { return pipeline_->Process(std::move(input)); } unique_ptr<Pipeline> pipeline_; }; class InferenceParser { public: static Result<unique_ptr<Inference>> Parse(const Value& config); }; } // namespace mmdeploy::graph #endif // MMDEPLOY_CSRC_EXPERIMENTAL_EXECUTION_INFERENCE_H_
238
739
<reponame>gregomebije1/ZtM-Job-Board<gh_stars>100-1000 { "name": "<NAME>", "img": "", "email": "<EMAIL>", "links": { "website": "", "linkedin": "https://www.linkedin.com/in/joel-dominic-lobo-99184a125", "github": "https://github.com/jdominiclobo" }, "jobTitle": "Full-Stack Developer(MERN)", "location": { "city": "Bangalore", "state": "Karnataka", "country": "India" } }
216
1,144
<reponame>google-admin/mozc # -*- coding: utf-8 -*- # Copyright 2010-2021, Google Inc. # 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 Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. r"""Copy Qt frameworks to the target application's frameworks directory. Typical usage: % python copy_qt_frameworks.py --qtdir=/path/to/qtdir/ \ --target=/path/to/target.app/Contents/Frameworks/ """ __author__ = "horo" import optparse import os from copy_file import CopyFiles from util import PrintErrorAndExit from util import RunOrDie def ParseOption(): """Parse command line options.""" parser = optparse.OptionParser() parser.add_option('--qtdir', dest='qtdir') parser.add_option('--target', dest='target') (opts, _) = parser.parse_args() return opts def GetFrameworkPath(name): """Return path to the library in the framework.""" return '%s.framework/Versions/5/%s' % (name, name) def Symlink(src, dst): if os.path.exists(dst): return os.symlink(src, dst) def CopyQt(qtdir, qtlib, target): """Copy a Qt framework from qtdir to target.""" srcdir = '%s/lib/%s.framework/Versions/5/' % (qtdir, qtlib) dstdir = '%s/%s.framework/' % (target, qtlib) # This function creates the following file, directory and symbolic links. # # QtCore.framework/Versions/5/QtCore # QtCore.framework/Versions/5/Resources/ # QtCore.framwwork/QtCore@ -> Versions/5/QtCore # QtCore.framwwork/Resources@ -> Versions/5/Resources # QtCore.framework/Versions/Current -> 5 # cp {qtdir}/lib/QtCore.framework/Versions/5/QtCore # {target}/QtCore.framework/Versions/5/QtCore CopyFiles([srcdir + qtlib], dstdir + 'Versions/5/' + qtlib) # Copies Resources of QtGui # cp -r {qtdir}/lib/QtCore.framework/Resources # {target}/QtCore.framework/Versions/5/Resources CopyFiles([srcdir + 'Resources'], dstdir + 'Versions/5/Resources', recursive=True) # ln -s 5 {target}/QtCore.framework/Versions/Current Symlink('5', dstdir + 'Versions/Current') # ln -s Versions/Current/QtCore {target}/QtCore.framework/QtCore Symlink('Versions/Current/' + qtlib, dstdir + qtlib) # ln -s Versions/Current/Resources {target}/QtCore.framework/Resources Symlink('Versions/Current/Resources', dstdir + 'Resources') def ChangeReferences(path, target, ref_to, references=None): """Change the references of frameworks, by using install_name_tool.""" # Change id cmd = ['install_name_tool', '-id', '%s/%s' % (ref_to, path), '%s/%s' % (target, path)] RunOrDie(cmd) if not references: return # Change references for ref in references: ref_framework_path = GetFrameworkPath(ref) change_cmd = ['install_name_tool', '-change', '@rpath/%s' % ref_framework_path, '%s/%s' % (ref_to, ref_framework_path), '%s/%s' % (target, path)] RunOrDie(change_cmd) def main(): opt = ParseOption() if not opt.qtdir: PrintErrorAndExit('--qtdir option is mandatory.') if not opt.target: PrintErrorAndExit('--target option is mandatory.') qtdir = os.path.abspath(opt.qtdir) target = os.path.abspath(opt.target) ref_to = '@executable_path/../../../ConfigDialog.app/Contents/Frameworks' CopyQt(qtdir, 'QtCore', target) CopyQt(qtdir, 'QtGui', target) CopyQt(qtdir, 'QtWidgets', target) CopyQt(qtdir, 'QtPrintSupport', target) qtcore_fpath = GetFrameworkPath('QtCore') qtgui_fpath = GetFrameworkPath('QtGui') qtwidgets_fpath = GetFrameworkPath('QtWidgets') qtprint_fpath = GetFrameworkPath('QtPrintSupport') ChangeReferences(qtcore_fpath, target, ref_to) ChangeReferences(qtgui_fpath, target, ref_to, references=['QtCore']) ChangeReferences( qtwidgets_fpath, target, ref_to, references=['QtCore', 'QtGui']) ChangeReferences( qtprint_fpath, target, ref_to, references=['QtCore', 'QtGui', 'QtWidgets']) libqcocoa = 'QtCore.framework/Resources/plugins/platforms/libqcocoa.dylib' CopyFiles(['%s/plugins/platforms/libqcocoa.dylib' % qtdir], '%s/%s' % (target, libqcocoa)) ChangeReferences(libqcocoa, target, ref_to, references=['QtCore', 'QtGui', 'QtWidgets', 'QtPrintSupport']) if __name__ == '__main__': main()
2,127
313
<gh_stars>100-1000 //------------------------------------------------------------------------------ // GB_Semiring_new.h: definitions for GB_Semiring_new //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, <NAME>, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #ifndef GB_SEMIRING_NEW_H #define GB_SEMIRING_NEW_H GrB_Info GB_Semiring_new // create a semiring ( GrB_Semiring semiring, // semiring to create GrB_Monoid add, // additive monoid of the semiring GrB_BinaryOp multiply // multiply operator of the semiring ) ; #endif
237
3,710
<filename>toonz/sources/include/tcg/hpp/mesh.hpp #pragma once #ifndef TCG_MESH_HPP #define TCG_MESH_HPP // tcg includes #include "../mesh.h" namespace tcg { //************************************************************************ // Polygon Mesh methods //************************************************************************ template <typename V, typename E, typename F> int Mesh<V, E, F>::edgeInciding(int vIdx1, int vIdx2, int n) const { const V &v1 = vertex(vIdx1); const tcg::list<int> &incidingV1 = v1.edges(); tcg::list<int>::const_iterator it; for (it = incidingV1.begin(); it != incidingV1.end(); ++it) { const E &e = edge(*it); if (e.otherVertex(vIdx1) == vIdx2 && n-- == 0) break; } return (it == incidingV1.end()) ? -1 : (*it); } //------------------------------------------------------------------------- template <typename V, typename E, typename F> int Mesh<V, E, F>::addEdge(const E &ed) { int e = int(m_edges.push_back(ed)); m_edges[e].setIndex(e); // Add the edge index to the edge's vertices typename edge_traits<E>::vertices_const_iterator it, end(ed.verticesEnd()); for (it = ed.verticesBegin(); it != end; ++it) m_vertices[*it].addEdge(e); return e; } //--------------------------------------------------------------------------------------------- template <typename V, typename E, typename F> int Mesh<V, E, F>::addFace(const F &fc) { int f = int(m_faces.push_back(fc)); m_faces[f].setIndex(f); // Add the face index to the face's edges typename face_traits<F>::edges_const_iterator it, end = fc.edgesEnd(); for (it = fc.edgesBegin(); it != end; ++it) m_edges[*it].addFace(f); return f; } //--------------------------------------------------------------------------------------------- template <typename V, typename E, typename F> void Mesh<V, E, F>::removeVertex(int v) { V &vx = vertex(v); // As long as there are incident edges, remove them while (vx.edgesCount() > 0) removeEdge(vx.edges().front()); m_vertices.erase(v); } //--------------------------------------------------------------------------------------------- template <typename V, typename E, typename F> void Mesh<V, E, F>::removeEdge(int e) { E &ed = edge(e); // Remove all the associated faces typename edge_traits<E>::faces_iterator ft; while ((ft = ed.facesBegin()) != ed.facesEnd()) // current iterator could be erased here! removeFace(*ft); // Remove the edge from the associated vertices typename edge_traits<E>::vertices_iterator vt, vEnd = ed.verticesEnd(); for (vt = ed.verticesBegin(); vt != vEnd; ++vt) { V &vx = vertex(*vt); typename vertex_traits<V>::edges_iterator et = std::find(vx.edgesBegin(), vx.edgesEnd(), e); assert(et != vx.edgesEnd()); vx.eraseEdge(et); } m_edges.erase(e); } //--------------------------------------------------------------------------------------------- template <typename V, typename E, typename F> void Mesh<V, E, F>::removeFace(int f) { F &fc = face(f); // Remove the face from all adjacent edges typename face_traits<F>::edges_iterator et, eEnd = fc.edgesEnd(); for (et = fc.edgesBegin(); et != eEnd; ++et) { E &ed = edge(*et); typename edge_traits<E>::faces_iterator ft = std::find(ed.facesBegin(), ed.facesEnd(), f); assert(ft != ed.facesEnd()); ed.eraseFace(ft); } m_faces.erase(f); } //--------------------------------------------------------------------------------------------- /*! \brief Remaps the mesh indices in a natural order, removing unused cells in the internal container model, for minimum memory consumption. \warning This is a slow operation, compared to all the others in the Mesh class. */ template <typename V, typename E, typename F> void Mesh<V, E, F>::squeeze() { // Build new indices for remapping. typename tcg::list<F>::iterator it, endI(m_faces.end()); int i; for (i = 0, it = m_faces.begin(); it != endI; ++i, ++it) it->setIndex(i); typename tcg::list<E>::iterator jt, endJ(m_edges.end()); for (i = 0, jt = m_edges.begin(); jt != endJ; ++i, ++jt) jt->setIndex(i); typename tcg::list<V>::iterator kt, endK(m_vertices.end()); for (i = 0, kt = m_vertices.begin(); kt != endK; ++i, ++kt) kt->setIndex(i); // Update stored indices for (it = m_faces.begin(); it != endI; ++it) { F &face = *it; typename face_traits<F>::edges_iterator et, eEnd = face.edgesEnd(); for (et = face.edgesBegin(); et != eEnd; ++et) *et = edge(*et).getIndex(); } for (jt = m_edges.begin(); jt != endJ; ++jt) { E &edge = *jt; typename edge_traits<E>::vertices_iterator vt, vEnd = edge.verticesEnd(); for (vt = edge.verticesBegin(); vt != vEnd; ++vt) *vt = vertex(*vt).getIndex(); typename edge_traits<E>::faces_iterator ft, fEnd = edge.facesEnd(); for (ft = edge.facesBegin(); ft != fEnd; ++ft) *ft = face(*ft).getIndex(); } tcg::list<int>::iterator lt; for (kt = m_vertices.begin(); kt != endK; ++kt) { V &vertex = *kt; typename vertex_traits<V>::edges_iterator et, eEnd = vertex.edgesEnd(); for (et = vertex.edgesBegin(); et != eEnd; ++et) *et = edge(*et).getIndex(); } // Finally, rebuild the actual containers if (!m_faces.empty()) { tcg::list<F> temp(m_faces.begin(), m_faces.end()); std::swap(m_faces, temp); } if (!m_edges.empty()) { tcg::list<E> temp(m_edges.begin(), m_edges.end()); std::swap(m_edges, temp); } if (!m_vertices.empty()) { tcg::list<V> temp(m_vertices.begin(), m_vertices.end()); std::swap(m_vertices, temp); } } //************************************************************************ // Triangular Mesh methods //************************************************************************ template <typename V, typename E, typename F> TriMesh<V, E, F>::TriMesh(int verticesHint) { int edgesHint = (3 * verticesHint) / 2; m_vertices.reserve(verticesHint); m_edges.reserve(edgesHint); m_faces.reserve(edgesHint + 1); // Since V - E + F = 1 for planar graphs (no // outer face), and vMin == 0 } //--------------------------------------------------------------------------------------------- template <typename V, typename E, typename F> int TriMesh<V, E, F>::addFace(V &vx1, V &vx2, V &vx3) { int v1 = vx1.getIndex(), v2 = vx2.getIndex(), v3 = vx3.getIndex(); // Retrieve the edges having v1, v2, v3 in common int e1, e2, e3; e1 = this->edgeInciding(v1, v2); e2 = this->edgeInciding(v2, v3); e3 = this->edgeInciding(v3, v1); if (e1 < 0) e1 = this->addEdge(E(v1, v2)); if (e2 < 0) e2 = this->addEdge(E(v2, v3)); if (e3 < 0) e3 = this->addEdge(E(v3, v1)); F fc; fc.addEdge(e1), fc.addEdge(e2), fc.addEdge(e3); int f = int(m_faces.push_back(fc)); m_faces[f].setIndex(f); E &E1 = this->edge(e1); E1.addFace(f); E &E2 = this->edge(e2); E2.addFace(f); E &E3 = this->edge(e3); E3.addFace(f); return f; } //--------------------------------------------------------------------------------------------- template <typename V, typename E, typename F> int TriMesh<V, E, F>::otherFaceVertex(int f, int e) const { const F &face = Mesh<V, E, F>::face(f); const E &otherEdge = face.edge(0) == e ? this->edge(face.edge(1)) : this->edge(face.edge(0)); int v1 = this->edge(e).vertex(0), v2 = this->edge(e).vertex(1), v3 = otherEdge.otherVertex(v1); return (v3 == v2) ? otherEdge.otherVertex(v2) : v3; } //--------------------------------------------------------------------------------------------- template <typename V, typename E, typename F> int TriMesh<V, E, F>::otherFaceEdge(int f, int v) const { const F &face = Mesh<V, E, F>::face(f); { const E &ed = this->edge(face.edge(0)); if (ed.vertex(0) != v && ed.vertex(1) != v) return face.edge(0); } { const E &ed = this->edge(face.edge(1)); if (ed.vertex(0) != v && ed.vertex(1) != v) return face.edge(1); } return face.edge(2); } //--------------------------------------------------------------------------------------------- template <typename V, typename E, typename F> int TriMesh<V, E, F>::swapEdge(int e) { E &ed = this->edge(e); if (ed.facesCount() < 2) return -1; int f1 = ed.face(0), f2 = ed.face(1); // Retrieve the 2 vertices not belonging to e in the adjacent faces int v1 = ed.vertex(0), v2 = ed.vertex(1); int v3 = otherFaceVertex(f1, e), v4 = otherFaceVertex(f2, e); assert(this->edgeInciding(v3, v4) < 0); // Remove e this->removeEdge(e); // Insert the new faces addFace(v1, v3, v4); // Inserts edge E(v3, v4) addFace(v2, v4, v3); return this->edgeInciding(v3, v4); } //--------------------------------------------------------------------------------------------- /* *---*---* Common case * FORBIDDEN case: / \ / x / \ /|\ note that the collapsed edge *---*-x-X---* /_*_\ have 3 (possibly more) other vertices \ / \ x \ / *--X--* with edges inciding both the collapsed *---*---* \ / edge's extremes. \ / * This cannot be processed, since the unexpected merged edge would either have more than 2 adjacent faces, or a hole. */ template <typename V, typename E, typename F> int TriMesh<V, E, F>::collapseEdge(int e) { E &ed = this->edge(e); // First, retrieve ed's adjacent vertices int vKeep = ed.vertex(0), vDelete = ed.vertex(1); V &vxKeep = this->vertex(vKeep), &vxDelete = this->vertex(vDelete); // Then, retrieve the 2 vertices not belonging to e in the adjacent faces int f, fCount = ed.facesCount(); int otherV[2]; for (f = 0; f != fCount; ++f) otherV[f] = otherFaceVertex(ed.face(f), e); // Remove e this->removeEdge(e); // Merge edges inciding vDelete and otherV with the corresponding inciding // vKeep and otherV for (f = 0; f != fCount; ++f) { int srcE = this->edgeInciding(vDelete, otherV[f]), dstE = this->edgeInciding(vKeep, otherV[f]); E &srcEd = this->edge(srcE), &dstEd = this->edge(dstE); typename edge_traits<E>::faces_iterator ft = srcEd.facesBegin(); while (ft != srcEd.facesEnd()) // current iterator will be erased { F &fc = this->face(*ft); (fc.edge(0) == srcE) ? fc.setEdge(0, dstE) : (fc.edge(1) == srcE) ? fc.setEdge(1, dstE) : fc.setEdge(2, dstE); dstEd.addFace(*ft); ft = srcEd.eraseFace(ft); // here } this->removeEdge(srcE); } // Move further edges adjacent to vDelete to vKeep typename vertex_traits<V>::edges_iterator et = vxDelete.edgesBegin(); while (et != vxDelete.edgesEnd()) // current iterator will be erased { E &ed = this->edge(*et); // Ensure that there is no remaining edge which would be duplicated // after vDelete and vKeep merge /* FIXME: edgeInciding がないと言われるのでとりあえず省略 */ #if 0 assert("Detected vertex adjacent to collapsed edge's endpoints, but not to its faces." && edgeInciding(ed.otherVertex(vDelete), vKeep) < 0); #endif (ed.vertex(0) == vDelete) ? ed.setVertex(0, vKeep) : ed.setVertex(1, vKeep); vxKeep.addEdge(*et); et = vxDelete.eraseEdge(et); // here } // Finally, update vKeep's position and remove vDelete vxKeep.P() = 0.5 * (vxKeep.P() + vxDelete.P()); m_vertices.erase(vDelete); return vKeep; } //--------------------------------------------------------------------------------------------- template <typename V, typename E, typename F> int TriMesh<V, E, F>::splitEdge(int e) { E &ed = this->edge(e); // Build a new vertex on the middle of e int v1 = ed.vertex(0), v2 = ed.vertex(1); V &vx1 = this->vertex(v1), &vx2 = this->vertex(v2); V v(0.5 * (vx1.P() + vx2.P())); int vIdx = this->addVertex(v); // Retrieve opposite vertices int otherV[2]; // NOTE: If ever extended to support edges with int f, fCount = ed.facesCount(); // MORE than 2 adjacent faces, the new faces // should be inserted BEFORE removing the split for (f = 0; f != fCount; ++f) // edge. otherV[f] = otherFaceVertex(ed.face(f), e); // Remove e this->removeEdge(e); // Add the new edges this->addEdge(E(v1, vIdx)); this->addEdge(E(vIdx, v2)); // Add the new faces for (f = 0; f != fCount; ++f) addFace(v1, vIdx, otherV[f]), addFace(vIdx, v2, otherV[f]); return vIdx; } } // namespace tcg #endif // TCG_MESH_HPP
5,075
647
/********************************* TRICK HEADER ******************************* PURPOSE: ( Test scheduling ) REFERENCE: ( None ) ASSUMPTIONS AND LIMITATIONS: ( None ) CLASS: ( environment ) LIBRARY DEPENDENCY: ( sched_environment.o ) PROGRAMMERS: ( (<NAME>) (Titan) (8-20-2002) ) *******************************************************************************/ #include "../include/sched.h" int sched_environment( /* RETURN: -- Always return zero */ SCHEDULE *S ) /* INOUT: -- Schedule struct */ { S->mass = S->mass*1.000005 + 0.000005 ; /* Mass growing, dust collection :-) */ return( 0 ); }
287
453
<reponame>amyspark/libjxl // Copyright (c) the JPEG XL Project Authors. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This C++ example decodes a JPEG XL image progressively (input bytes are // passed in chunks). The example outputs the intermediate steps to PAM files. #include <inttypes.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <vector> #include "jxl/decode.h" #include "jxl/decode_cxx.h" #include "jxl/resizable_parallel_runner.h" #include "jxl/resizable_parallel_runner_cxx.h" bool WritePAM(const char* filename, const uint8_t* buffer, size_t w, size_t h) { FILE* fp = fopen(filename, "wb"); if (!fp) { fprintf(stderr, "Could not open %s for writing", filename); return false; } fprintf(fp, "P7\nWIDTH %" PRIu64 "\nHEIGHT %" PRIu64 "\nDEPTH 4\nMAXVAL 255\nTUPLTYPE " "RGB_ALPHA\nENDHDR\n", static_cast<uint64_t>(w), static_cast<uint64_t>(h)); fwrite(buffer, 1, w * h * 4, fp); if (fclose(fp) != 0) { return false; } return true; } /** Decodes JPEG XL image to 8-bit integer RGBA pixels and an ICC Profile, in a * progressive way, saving the intermediate steps. */ bool DecodeJpegXlProgressive(const uint8_t* jxl, size_t size, const char* filename, size_t chunksize) { std::vector<uint8_t> pixels; std::vector<uint8_t> icc_profile; size_t xsize = 0, ysize = 0; // Multi-threaded parallel runner. auto runner = JxlResizableParallelRunnerMake(nullptr); auto dec = JxlDecoderMake(nullptr); if (JXL_DEC_SUCCESS != JxlDecoderSubscribeEvents(dec.get(), JXL_DEC_BASIC_INFO | JXL_DEC_COLOR_ENCODING | JXL_DEC_FULL_IMAGE)) { fprintf(stderr, "JxlDecoderSubscribeEvents failed\n"); return false; } if (JXL_DEC_SUCCESS != JxlDecoderSetParallelRunner(dec.get(), JxlResizableParallelRunner, runner.get())) { fprintf(stderr, "JxlDecoderSetParallelRunner failed\n"); return false; } JxlBasicInfo info; JxlPixelFormat format = {4, JXL_TYPE_UINT8, JXL_NATIVE_ENDIAN, 0}; size_t seen = 0; JxlDecoderSetInput(dec.get(), jxl, chunksize); size_t remaining = chunksize; for (;;) { JxlDecoderStatus status = JxlDecoderProcessInput(dec.get()); if (status == JXL_DEC_ERROR) { fprintf(stderr, "Decoder error\n"); return false; } else if (status == JXL_DEC_NEED_MORE_INPUT || status == JXL_DEC_SUCCESS || status == JXL_DEC_FULL_IMAGE) { seen += remaining - JxlDecoderReleaseInput(dec.get()); printf("Flushing after %" PRIu64 " bytes\n", static_cast<uint64_t>(seen)); if (status == JXL_DEC_NEED_MORE_INPUT && JXL_DEC_SUCCESS != JxlDecoderFlushImage(dec.get())) { printf("flush error (no preview yet)\n"); } else { char fname[1024]; if (snprintf(fname, 1024, "%s-%" PRIu64 ".pam", filename, static_cast<uint64_t>(seen)) >= 1024) { fprintf(stderr, "Filename too long\n"); return false; }; if (!WritePAM(fname, pixels.data(), xsize, ysize)) { fprintf(stderr, "Error writing progressive output\n"); } } remaining = size - seen; if (remaining > chunksize) remaining = chunksize; if (remaining == 0) { if (status == JXL_DEC_NEED_MORE_INPUT) { fprintf(stderr, "Error, already provided all input\n"); return false; } else { return true; } } JxlDecoderSetInput(dec.get(), jxl + seen, remaining); } else if (status == JXL_DEC_BASIC_INFO) { if (JXL_DEC_SUCCESS != JxlDecoderGetBasicInfo(dec.get(), &info)) { fprintf(stderr, "JxlDecoderGetBasicInfo failed\n"); return false; } xsize = info.xsize; ysize = info.ysize; JxlResizableParallelRunnerSetThreads( runner.get(), JxlResizableParallelRunnerSuggestThreads(info.xsize, info.ysize)); } else if (status == JXL_DEC_COLOR_ENCODING) { // Get the ICC color profile of the pixel data size_t icc_size; if (JXL_DEC_SUCCESS != JxlDecoderGetICCProfileSize(dec.get(), &format, JXL_COLOR_PROFILE_TARGET_ORIGINAL, &icc_size)) { fprintf(stderr, "JxlDecoderGetICCProfileSize failed\n"); return false; } icc_profile.resize(icc_size); if (JXL_DEC_SUCCESS != JxlDecoderGetColorAsICCProfile( dec.get(), &format, JXL_COLOR_PROFILE_TARGET_ORIGINAL, icc_profile.data(), icc_profile.size())) { fprintf(stderr, "JxlDecoderGetColorAsICCProfile failed\n"); return false; } } else if (status == JXL_DEC_NEED_IMAGE_OUT_BUFFER) { size_t buffer_size; if (JXL_DEC_SUCCESS != JxlDecoderImageOutBufferSize(dec.get(), &format, &buffer_size)) { fprintf(stderr, "JxlDecoderImageOutBufferSize failed\n"); return false; } if (buffer_size != xsize * ysize * 4) { fprintf(stderr, "Invalid out buffer size %" PRIu64 " != %" PRIu64 "\n", static_cast<uint64_t>(buffer_size), static_cast<uint64_t>(xsize * ysize * 4)); return false; } pixels.resize(xsize * ysize * 4); void* pixels_buffer = (void*)pixels.data(); size_t pixels_buffer_size = pixels.size() * sizeof(float); if (JXL_DEC_SUCCESS != JxlDecoderSetImageOutBuffer(dec.get(), &format, pixels_buffer, pixels_buffer_size)) { fprintf(stderr, "JxlDecoderSetImageOutBuffer failed\n"); return false; } } else { fprintf(stderr, "Unknown decoder status\n"); return false; } } } bool LoadFile(const char* filename, std::vector<uint8_t>* out) { FILE* file = fopen(filename, "rb"); if (!file) { return false; } if (fseek(file, 0, SEEK_END) != 0) { fclose(file); return false; } long size = ftell(file); // Avoid invalid file or directory. if (size >= LONG_MAX || size < 0) { fclose(file); return false; } if (fseek(file, 0, SEEK_SET) != 0) { fclose(file); return false; } out->resize(size); size_t readsize = fread(out->data(), 1, size, file); if (fclose(file) != 0) { return false; } return readsize == static_cast<size_t>(size); } int main(int argc, char* argv[]) { if (argc < 3) { fprintf( stderr, "Usage: %s <jxl> <basename> [chunksize]\n" "Where:\n" " jxl = input JPEG XL image filename\n" " basename = prefix of output filenames\n" " chunksize = loads chunksize bytes at a time and writes\n" " intermediate results to basename-[bytes loaded].pam\n" "Output files will be overwritten.\n", argv[0]); return 1; } const char* jxl_filename = argv[1]; const char* png_filename = argv[2]; std::vector<uint8_t> jxl; if (!LoadFile(jxl_filename, &jxl)) { fprintf(stderr, "couldn't load %s\n", jxl_filename); return 1; } size_t chunksize = jxl.size(); if (argc > 3) { long cs = atol(argv[3]); if (cs < 100) { fprintf(stderr, "Chunk size is too low, try at least 100 bytes\n"); return 1; } chunksize = cs; } if (!DecodeJpegXlProgressive(jxl.data(), jxl.size(), png_filename, chunksize)) { fprintf(stderr, "Error while decoding the jxl file\n"); return 1; } return 0; }
3,834
1,346
<reponame>disrupted/Trakttv.bundle from plugin.core.backup import BackupManager from plugin.modules.scheduler.handlers.core.base import Handler class BackupMaintenanceIntervalHandler(Handler): key = 'backup.interval' def run(self, job): # Trigger backup maintenance BackupManager.maintenance(block=False) return True
121
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.bvt.sql.mysql.select; import com.alibaba.polardbx.druid.DbType; import com.alibaba.polardbx.druid.sql.MysqlTest; import com.alibaba.polardbx.druid.sql.SQLUtils; import com.alibaba.polardbx.druid.sql.ast.SQLStatement; /** * @version 1.0 * @ClassName MySqlSelectTest_307_not_in_is * @description * @Author zzy * @Date 2020/2/19 15:42 */ public class MySqlSelectTest_307_not_in_is extends MysqlTest { public void test_0() throws Exception { String sql = "select NOT(( ((3,4)) in ((16 + tinyint_1bit_test,( LPAD('bar', 75,'foobarbar' )) ),( double_test,(((23)<<(71) ))))) )is NULL,((PI( )is NULL)&(integer_test DIV smallint_test MOD bigint_test) )from corona_select_multi_db_multi_tb where( ~(tinyint_1bit_test)) order by pk;"; SQLStatement stmt = SQLUtils.parseSingleStatement(sql, DbType.mysql); assertEquals("SELECT NOT ((3, 4) IN ((16 + tinyint_1bit_test, LPAD('bar', 75, 'foobarbar')), (double_test, 23 << 71)) IS NULL)\n" + "\t, (PI() IS NULL) & integer_test DIV smallint_test % bigint_test\n" + "FROM corona_select_multi_db_multi_tb\n" + "WHERE ~tinyint_1bit_test\n" + "ORDER BY pk;", stmt.toString()); } }
732
627
/* Copyright 2016 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * * Standalone utility to parse EC panicinfo. */ #include <stdint.h> #include <stdio.h> #include "ec_panicinfo.h" int main(int argc, char *argv[]) { struct panic_data pdata; if (fread(&pdata, sizeof(pdata), 1, stdin) != 1) { fprintf(stderr, "Error reading panicinfo from stdin.\n"); return 1; } return parse_panic_info(&pdata) ? 1 : 0; }
187
2,462
package com.sanshengshui.persistence; import com.google.common.util.concurrent.ListenableFuture; import java.util.List; /** * @author <NAME> * @date 18-12-25 下午4:10 */ public interface Dao<T> { List<T> find(); T findById(Long id); ListenableFuture<T> findByIdAsync(Long id); T save(T t); boolean removeById(Long id); }
140
1,609
package com.mossle.spi.rpc; public class RpcConfiguration { private String baseUrl; private String accessKey; private String accessSecret; private RpcAuthHelper rpcAuthHelper; public String getBaseUrl() { return baseUrl; } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getAccessSecret() { return accessSecret; } public void setAccessSecret(String accessSecret) { this.accessSecret = accessSecret; } public RpcAuthHelper getRpcAuthHelper() { return rpcAuthHelper; } public void setRpcAuthHelper(RpcAuthHelper rpcAuthHelper) { this.rpcAuthHelper = rpcAuthHelper; } }
339
654
/* * Copyright (c) 2015-2021 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Attribution Notice under the terms of the Apache License 2.0 * * This work was created by the collective efforts of the openCypher community. * Without limiting the terms of Section 6, any Derivative Work that is not * approved by the public consensus process of the openCypher Implementers Group * should not be described as “Cypher” (and Cypher® is a registered trademark of * Neo4j Inc.) or as "openCypher". Extensions by implementers or prototypes or * proposals for change that have been documented or implemented should only be * described as "implementation extensions to Cypher" or as "proposed changes to * Cypher that are not yet approved by the openCypher community". */ package org.opencypher.tools.io; class LineNumberingOutput implements Output { private final Output output; boolean newLine = true; private int lineNo; LineNumberingOutput( Output output ) { this.output = output; } @Override public Output append( char x ) { if ( newLine ) { output.format( "%5d: ", lineNo ); newLine = false; } output.append( x ); if ( x == '\n' ) { newLine = true; lineNo++; } return this; } }
625
1,375
/* This code is written by kerukuro and released into public domain. */ #ifndef DIGESTPP_MIXIN_SHAKE_HPP #define DIGESTPP_MIXIN_SHAKE_HPP namespace digestpp { namespace mixin { /** * \brief Defines additional public functions for cSHAKE128 and cSHAKE256. * \sa hasher, cshake128, cshake256 */ template<typename T> class cshake_mixin { public: /** * \brief Set NIST function name from std::string * * \param[in] function_name NIST function name string * \return Reference to hasher */ inline hasher<T, mixin::cshake_mixin>& set_function_name(const std::string& function_name) { auto& shake = static_cast<hasher<T, mixin::cshake_mixin>&>(*this); shake.provider.set_function_name(function_name); shake.provider.init(); return shake; } /** * \brief Set NIST function name from raw buffer * * \param[in] function_name Pointer to NIST function name bytes * \param[in] function_name_len NIST function name length (in bytes) * \return Reference to hasher */ template<typename C, typename std::enable_if<detail::is_byte<C>::value>::type* = nullptr> inline hasher<T, mixin::cshake_mixin>& set_function_name(const C* function_name, size_t function_name_len) { return set_function_name(std::string(reinterpret_cast<const char*>(function_name), function_name_len)); } /** * \brief Set customization from std::string * * \param[in] customization Customization string * \return Reference to hasher */ inline hasher<T, mixin::cshake_mixin>& set_customization(const std::string& customization) { auto& shake = static_cast<hasher<T, mixin::cshake_mixin>&>(*this); shake.provider.set_customization(customization); shake.provider.init(); return shake; } /** * \brief Set customization from raw buffer * * \param[in] customization Pointer to customization bytes * \param[in] customization_len Customization length (in bytes) * \return Reference to hasher */ template<typename C, typename std::enable_if<detail::is_byte<C>::value>::type* = nullptr> inline hasher<T, mixin::cshake_mixin>& set_customization(const C* customization, size_t customization_len) { return set_customization(std::string(reinterpret_cast<const char*>(customization), customization_len)); } }; } // namespace mixin } // namespace digestpp #endif // DIGESTPP_MIXIN_SHAKE_HPP
811
563
<gh_stars>100-1000 /* src/checkbox.cpp -- Two-state check box widget NanoGUI was developed by <NAME> <<EMAIL>>. The widget drawing code is based on the NanoVG demo application by <NAME>. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE.txt file. */ #include <nanogui/checkbox.h> #include <nanogui/opengl.h> #include <nanogui/theme.h> #include <nanogui/entypo.h> #include <nanogui/serializer/core.h> NAMESPACE_BEGIN(nanogui) CheckBox::CheckBox(Widget *parent, const std::string &caption, const std::function<void(bool) > &callback) : Widget(parent), mCaption(caption), mPushed(false), mChecked(false), mCallback(callback) { } bool CheckBox::mouseButtonEvent(const Vector2i &p, int button, bool down, int modifiers) { Widget::mouseButtonEvent(p, button, down, modifiers); if (!mEnabled) return false; if (button == GLFW_MOUSE_BUTTON_1) { if (down) { mPushed = true; } else if (mPushed) { if (contains(p)) { mChecked = !mChecked; if (mCallback) mCallback(mChecked); } mPushed = false; } return true; } return false; } Vector2i CheckBox::preferredSize(NVGcontext *ctx) const { if (mFixedSize != Vector2i::Zero()) return mFixedSize; nvgFontSize(ctx, fontSize()); nvgFontFace(ctx, "sans"); return Vector2i( nvgTextBounds(ctx, 0, 0, mCaption.c_str(), nullptr, nullptr) + 1.8f * fontSize(), fontSize() * 1.3f); } void CheckBox::draw(NVGcontext *ctx) { Widget::draw(ctx); nvgFontSize(ctx, fontSize()); nvgFontFace(ctx, "sans"); nvgFillColor(ctx, mEnabled ? mTheme->mTextColor : mTheme->mDisabledTextColor); nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE); nvgText(ctx, mPos.x() + 1.6f * fontSize(), mPos.y() + mSize.y() * 0.5f, mCaption.c_str(), nullptr); NVGpaint bg = nvgBoxGradient(ctx, mPos.x() + 1.5f, mPos.y() + 1.5f, mSize.y() - 2.0f, mSize.y() - 2.0f, 3, 3, mPushed ? Color(0, 100) : Color(0, 32), Color(0, 0, 0, 180)); nvgBeginPath(ctx); nvgRoundedRect(ctx, mPos.x() + 1.0f, mPos.y() + 1.0f, mSize.y() - 2.0f, mSize.y() - 2.0f, 3); nvgFillPaint(ctx, bg); nvgFill(ctx); if (mChecked) { nvgFontSize(ctx, 1.8 * mSize.y()); nvgFontFace(ctx, "icons"); nvgFillColor(ctx, mEnabled ? mTheme->mIconColor : mTheme->mDisabledTextColor); nvgTextAlign(ctx, NVG_ALIGN_CENTER | NVG_ALIGN_MIDDLE); nvgText(ctx, mPos.x() + mSize.y() * 0.5f + 1, mPos.y() + mSize.y() * 0.5f, utf8(ENTYPO_ICON_CHECK).data(), nullptr); } } void CheckBox::save(Serializer &s) const { Widget::save(s); s.set("caption", mCaption); s.set("pushed", mPushed); s.set("checked", mChecked); } bool CheckBox::load(Serializer &s) { if (!Widget::load(s)) return false; if (!s.get("caption", mCaption)) return false; if (!s.get("pushed", mPushed)) return false; if (!s.get("checked", mChecked)) return false; return true; } NAMESPACE_END(nanogui)
1,716
20,190
<filename>tests/test_models/test_dense_heads/test_dense_heads_attr.py # Copyright (c) OpenMMLab. All rights reserved. import warnings from terminaltables import AsciiTable from mmdet.models import dense_heads from mmdet.models.dense_heads import * # noqa: F401,F403 def test_dense_heads_test_attr(): """Tests inference methods such as simple_test and aug_test.""" # make list of dense heads exceptions = ['FeatureAdaption'] # module used in head all_dense_heads = [m for m in dense_heads.__all__ if m not in exceptions] # search attributes check_attributes = [ 'simple_test', 'aug_test', 'simple_test_bboxes', 'simple_test_rpn', 'aug_test_rpn' ] table_header = ['head name'] + check_attributes table_data = [table_header] not_found = {k: [] for k in check_attributes} for target_head_name in all_dense_heads: target_head = globals()[target_head_name] target_head_attributes = dir(target_head) check_results = [target_head_name] for check_attribute in check_attributes: found = check_attribute in target_head_attributes check_results.append(found) if not found: not_found[check_attribute].append(target_head_name) table_data.append(check_results) table = AsciiTable(table_data) print() print(table.table) # NOTE: this test just checks attributes. # simple_test of RPN heads will not work now. assert len(not_found['simple_test']) == 0, \ f'simple_test not found in {not_found["simple_test"]}' if len(not_found['aug_test']) != 0: warnings.warn(f'aug_test not found in {not_found["aug_test"]}. ' 'Please implement it or raise NotImplementedError.')
705