max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
377
<filename>public/locales/pt/offers.json { "Send a message": "Enviar uma mensagem", "At most {{count}} guests.": "No máximo, um hóspede.", "At most {{count}} guests._plural": "No máximo, {{count}} hóspedes.", "Accommodation": "Alojamento", "Travelling? Organising an event? Just making a dinner and would like to invite people over?": "Viajando? Organizando um evento? Apenas fazendo um jantar e gostaria de convidar pessoas?", "Travelling? Organising an event?": "Viajando? Organizando um evento?", "Start hosting travellers": "Começar a hospedar viajantes", "Sorry, user is not hosting currently.": "Desculpe, o usuário não está hospedando atualmente.", "Open on device": "Abrir no dispositivo", "Offering hospitality and welcoming “strangers” to our homes strengthens our faith in each other.": "Oferecer hospitalidade e acolher \"estranhos\" em nossas casas fortalece nossa fé uns nos outros.", "No guests.": "Nenhum hóspede.", "Modify hosting offer": "Modificar oferta de hospedagem", "Might be able to host": "Talvez possa hospedar", "Meetups stay visible on map at most one month.": "Encontros permanecem visíveis no mapa por no máximo um mês.", "Meet people": "Conhecer pessoas", "Just making a dinner and would like to invite people over?": "Apenas preparando um jantar e gostaria de convidar pessoas para participar?", "Cannot host currently": "Não posso hospedar agora", "Can host": "Posso hospedar", "Bigger map": "Mapa ampliado", "Add it to map!": "Adicionar ao mapa!", "Change": "Alterar" }
583
3,102
<gh_stars>1000+ // RUN: %clang_cc1 -E -verify %s #define FOO 1 // The error message should be on the #include line, not the 1. // expected-error@+1 {{expected "FILENAME" or <FILENAME>}} #include FOO #define BAR BAZ // expected-error@+1 {{expected "FILENAME" or <FILENAME>}} #include BAR
111
5,156
<gh_stars>1000+ /* -*- Mode: C; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */ #include "util.h" static void* do_thread(__attribute__((unused)) void* p) { atomic_puts("EXIT-SUCCESS"); return NULL; } int main(void) { pthread_t thread; struct rlimit limit; int ret = getrlimit(RLIMIT_NOFILE, &limit); int new_fd; rlim_t initial_limit = limit.rlim_cur; test_assert(ret >= 0); if (initial_limit + 10 > limit.rlim_max) { atomic_puts("Current soft limit cannot be increased enough, skipping test"); atomic_puts("EXIT-SUCCESS"); return 0; } /* Increase soft limit. */ limit.rlim_cur += 10; ret = setrlimit(RLIMIT_NOFILE, &limit); test_assert(ret >= 0); /* Consume file descriptors until we've allocated all previously available descriptors (plus one). */ do { new_fd = open("/dev/null", O_RDONLY); test_assert(new_fd >= 0); } while (new_fd < (int)initial_limit); /* This will allocate new fds for thread stack and syscallbuf stuff */ pthread_create(&thread, NULL, do_thread, NULL); pthread_join(thread, NULL); return 0; }
413
515
<reponame>kraehlit/CTK /*============================================================================= Library: CTK Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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 CTKSERVICETRACKERTESTSUITE_P_H #define CTKSERVICETRACKERTESTSUITE_P_H #include <QObject> #include <QThread> #include <ctkTestSuiteInterface.h> #include <ctkServiceEvent.h> class ctkPlugin; class ctkPluginContext; class ctkServiceTrackerTestSuite : public QObject, public ctkTestSuiteInterface { Q_OBJECT Q_INTERFACES(ctkTestSuiteInterface) public: ctkServiceTrackerTestSuite(ctkPluginContext* pc); private Q_SLOTS: void initTestCase(); void cleanupTestCase(); // test functions // Checks that the correct service events // are sent to a registered service listener. // Case where the plugin does not unregister its // service in the stop()-method. void runTest(); Q_SIGNALS: void serviceControl(int service, const QString operation, long rank); private: ctkPluginContext* pc; QSharedPointer<ctkPlugin> p; QSharedPointer<ctkPlugin> pS; }; class ctkServiceTrackerTestWorker : public QThread { Q_OBJECT public: ctkServiceTrackerTestWorker(ctkPluginContext* pc); bool waitSuccess; protected: void run(); private: ctkPluginContext* pc; }; #endif // CTKSERVICETRACKERTESTSUITE_P_H
622
455
<reponame>zmxdream/FlexFlow # Copyright 2020 Stanford University, Los Alamos National Laboratory # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import flexflow.core as ff from flexflow.core.flexflow_logger import fflogger from .base_layer import Layer from .input_layer import Input from flexflow.keras.models.tensor import Tensor class _Merge(Layer): def __init__(self, default_name, layer_type): super(_Merge, self).__init__(default_name, layer_type) def verify_meta_data(self): pass def get_summary(self): summary = "%s%s%s\n"%(self._get_summary_name(), self.output_shape, self._get_summary_connected_to()) return summary def __call__(self, input_tensors): return self._connect_layer_n_input_1_output(input_tensors) def _verify_inout_tensor_shape(self, input_tensors, output_tensor): assert self.__check_duplications(input_tensors) == False, "[Merge]: dunpicated input_tensors is not supported" for input_tensor in input_tensors: assert input_tensor.num_dims == len(self.input_shape), "[Merge]: check input tensor dims" for i in range (1, input_tensor.num_dims): if isinstance(self, Concatenate) and self.axis == i: continue assert input_tensor.batch_shape[i] == self.input_shape[i] assert output_tensor.num_dims == len(self.output_shape), "[Merge]: check output tensor dims" for i in range (1, output_tensor.num_dims): assert output_tensor.batch_shape[i] == self.output_shape[i] def _reset_layer(self): pass def __check_duplications(self, input_tensors): if len(input_tensors) == len(set(input_tensors)): return False else: return True def concatenate(input_tensors, _axis=1): return Concatenate(axis=_axis)(input_tensors) class Concatenate(_Merge): __slots__ = ['axis'] def __init__(self, axis, **kwargs): super(Concatenate, self).__init__("concatenate", "Concatenate", **kwargs) self.axis = axis def _calculate_inout_shape(self, input_tensors): if (input_tensors[0].num_dims == 2): output_shape = [input_tensors[0].batch_shape[0], 0] for input_tensor in input_tensors: output_shape[self.axis] += input_tensor.batch_shape[self.axis] self.output_shape = (output_shape[0], output_shape[1]) elif (input_tensors[0].num_dims == 4): output_shape = [input_tensors[0].batch_shape[0], 0, input_tensors[0].batch_shape[2], input_tensors[0].batch_shape[3]] for input_tensor in input_tensors: output_shape[self.axis] += input_tensor.batch_shape[self.axis] self.output_shape = (output_shape[0], output_shape[1], output_shape[2], output_shape[3]) else: assert 0, "un-supported dims" fflogger.debug("concat output %s" %( str(self.output_shape))) self.input_shape = input_tensors[0].batch_shape def add(input_tensors): return Add()(input_tensors) class Add(_Merge): def __init__(self, **kwargs): super(Add, self).__init__("add", "Add", **kwargs) def _calculate_inout_shape(self, input_tensors): assert len(input_tensors) == 2, "check input_tensors" self.input_shape = input_tensors[0].batch_shape self.output_shape = input_tensors[0].batch_shape fflogger.debug("add output %s" %( str(self.output_shape))) def subtract(input_tensors): return Subtract()(input_tensors) class Subtract(_Merge): def __init__(self, **kwargs): super(Subtract, self).__init__("subtract", "Subtract", **kwargs) def _calculate_inout_shape(self, input_tensors): assert len(input_tensors) == 2, "check input_tensors" self.input_shape = input_tensors[0].batch_shape self.output_shape = input_tensors[0].batch_shape fflogger.debug("subtract output %s" %( str(self.output_shape))) def multiply(input_tensors): return Multiply()(input_tensors) class Multiply(_Merge): def __init__(self, **kwargs): super(Multiply, self).__init__("multiply", "Multiply", **kwargs) def _calculate_inout_shape(self, input_tensors): assert len(input_tensors) == 2, "check input_tensors" self.input_shape = input_tensors[0].batch_shape self.output_shape = input_tensors[0].batch_shape fflogger.debug("multiply output %s" %( str(self.output_shape)))
1,909
352
<filename>plugins/crawloverview-plugin/src/test/java/com/crawljax/plugins/crawloverview/BeanToReadableMapTest.java package com.crawljax.plugins.crawloverview; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import java.util.Map; import org.junit.Test; public class BeanToReadableMapTest { @Test public void test() { Map<String, String> map = BeanToReadableMap.toMap(new TestBean()); assertThat(map.size(), is(4)); assertThat(map, hasEntry("Some String", "A")); assertThat(map, hasEntry("Some Int", "123")); assertThat(map, hasEntry("String List", "<ul><li>A</li><li>B</li></ul>")); assertThat(map, hasEntry("Object List", "<ul><li>42</li></ul>")); } }
288
1,444
<gh_stars>1000+ package mage.cards.d; import mage.abilities.Ability; import mage.abilities.dynamicvalue.common.StaticValue; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.DrawCardSourceControllerEffect; import mage.abilities.effects.common.ReturnToHandFromBattlefieldAllEffect; import mage.abilities.effects.common.discard.DiscardEachPlayerEffect; import mage.abilities.effects.keyword.SurveilEffect; import mage.cards.CardSetInfo; import mage.cards.SplitCard; import mage.constants.*; import mage.filter.FilterPermanent; import mage.filter.common.FilterNonlandPermanent; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.ManaValuePredicate; import mage.filter.predicate.permanent.ControllerIdPredicate; import mage.filter.predicate.permanent.PermanentIdPredicate; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; import mage.target.Target; import mage.target.TargetPermanent; import java.util.HashSet; import java.util.Set; import java.util.UUID; /** * @author TheElk801 */ public final class DiscoveryDispersal extends SplitCard { public DiscoveryDispersal(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, new CardType[]{CardType.INSTANT}, "{1}{U/B}", "{3}{U}{B}", SpellAbilityType.SPLIT); // Discovery // Surveil 2, then draw a card. this.getLeftHalfCard().getSpellAbility().addEffect( new SurveilEffect(2).setText("Surveil 2,") ); this.getLeftHalfCard().getSpellAbility().addEffect( new DrawCardSourceControllerEffect(1 ).setText("then draw a card. <i>(To surveil 2, " + "look at the top two cards of your library, " + "then put any number of them into your graveyard " + "and the rest on top of your library " + "in any order.)</i>") ); // Dispersal // Each opponent returns a nonland permanent they control with the highest converted mana cost among permanents they control to its owner’s hand, then discards a card. this.getRightHalfCard().getSpellAbility().addEffect(new DispersalEffect()); } private DiscoveryDispersal(final DiscoveryDispersal card) { super(card); } @Override public DiscoveryDispersal copy() { return new DiscoveryDispersal(this); } } class DispersalEffect extends OneShotEffect { DispersalEffect() { super(Outcome.Benefit); this.staticText = "Each opponent returns a nonland permanent " + "they control with the highest mana value " + "among permanents they control to its owner's hand, " + "then discards a card."; } private DispersalEffect(final DispersalEffect effect) { super(effect); } @Override public DispersalEffect copy() { return new DispersalEffect(this); } @Override public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getControllerId()); if (player == null) { return false; } Set<PermanentIdPredicate> permsToReturn = new HashSet<>(); for (UUID opponentId : game.getOpponents(player.getId())) { Player opponent = game.getPlayer(opponentId); if (opponent == null) { continue; } int highestCMC = 0; for (Permanent permanent : game.getBattlefield().getAllActivePermanents(opponentId)) { if (permanent != null) { highestCMC = Math.max(highestCMC, permanent.getManaValue()); } } FilterPermanent filter = new FilterNonlandPermanent("permanent you control with mana value " + highestCMC); filter.add(new ManaValuePredicate(ComparisonType.EQUAL_TO, highestCMC)); filter.add(new ControllerIdPredicate(opponentId)); Target target = new TargetPermanent(1, 1, filter, true); if (opponent.choose(outcome, target, source.getSourceId(), game)) { if (target.getFirstTarget() == null) { continue; } permsToReturn.add(new PermanentIdPredicate(target.getFirstTarget())); } } FilterPermanent filter = new FilterPermanent(); filter.add(Predicates.or(permsToReturn)); new ReturnToHandFromBattlefieldAllEffect(filter).apply(game, source); new DiscardEachPlayerEffect( StaticValue.get(1), false, TargetController.OPPONENT ).apply(game, source); return true; } }
1,922
407
<gh_stars>100-1000 // MIT License // // Copyright (c) 2019 <NAME>, Chair for Embedded Security. All Rights reserved. // Copyright (c) 2021 Max Planck Institute for Security and Privacy. All Rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include "hal_core/defines.h" #include "hal_core/netlist/net.h" #include "hal_core/netlist/netlist.h" #include "hal_core/utilities/log.h" #include "z3++.h" #include <iostream> #include <map> namespace hal { struct FsmTransition { FsmTransition(const z3::expr& start, const z3::expr& end, const std::map<u32, u8>& inputs); // FsmTransition(const u64& start, const u64& end, const std::map<u32, u8>& inputs); FsmTransition merge(const FsmTransition& other) const; std::string to_string() const; std::string to_dot_string(const Netlist* nl, const u32 state_size) const; z3::expr starting_state_expr; z3::expr end_state_expr; u64 starting_state; u64 end_state; // vector of all input mappings that lead to this transition std::vector<std::map<u32, u8>> input_ids_to_values; }; } // namespace hal
742
1,345
from functools import lru_cache import numpy as np def interpolate_coordinates(old_coord, new_coord, brush_size): """Interpolates coordinates depending on brush size. Useful for ensuring painting is continuous in labels layer. Parameters ---------- old_coord : np.ndarray, 1x2 Last position of cursor. new_coord : np.ndarray, 1x2 Current position of cursor. brush_size : float Size of brush, which determines spacing of interpolation. Returns ------- coords : np.array, Nx2 List of coordinates to ensure painting is continuous """ if old_coord is None: old_coord = new_coord if new_coord is None: new_coord = old_coord num_step = round( max(abs(np.array(new_coord) - np.array(old_coord))) / brush_size * 4 ) coords = [ np.linspace(old_coord[i], new_coord[i], num=int(num_step + 1)) for i in range(len(new_coord)) ] coords = np.stack(coords).T if len(coords) > 1: coords = coords[1:] return coords @lru_cache(maxsize=64) def sphere_indices(radius, scale): """Generate centered indices within circle or n-dim ellipsoid. Parameters ------- radius : float Radius of circle/sphere scale : tuple of float The scaling to apply to the sphere along each axis Returns ------- mask_indices : array Centered indices within circle/sphere """ ndim = len(scale) abs_scale = np.abs(scale) scale_normalized = np.asarray(abs_scale, dtype=float) / np.min(abs_scale) # Create multi-dimensional grid to check for # circle/membership around center r_normalized = radius / scale_normalized + 0.5 slices = [ slice(-int(np.ceil(r)), int(np.floor(r)) + 1) for r in r_normalized ] indices = np.mgrid[slices].T.reshape(-1, ndim) distances_sq = np.sum((indices * scale_normalized) ** 2, axis=1) # Use distances within desired radius to mask indices in grid mask_indices = indices[distances_sq <= radius ** 2].astype(int) return mask_indices def indices_in_shape(idxs, shape): """Return idxs after filtering out indices that are not in given shape. Parameters ---------- idxs : tuple of array of int, or 2D array of int The input coordinates. These should be in one of two formats: - a tuple of 1D arrays, as for NumPy fancy indexing, or - a 2D array of shape (ncoords, ndim), as a list of coordinates shape : tuple of int The shape in which all indices must fit. Returns ------- idxs_filtered : tuple of array of int, or 2D array of int The subset of the input idxs that falls within shape. Examples -------- >>> idxs0 = (np.array([5, 45, 2]), np.array([6, 5, -5])) >>> indices_in_shape(idxs0, (10, 10)) (array([5]), array([6])) >>> idxs1 = np.transpose(idxs0) >>> indices_in_shape(idxs1, (10, 10)) array([[5, 6]]) """ np_index = isinstance(idxs, tuple) if np_index: # normalize to 2D coords array idxs = np.transpose(idxs) keep_coords = np.logical_and( np.all(idxs >= 0, axis=1), np.all(idxs < np.array(shape), axis=1) ) filtered = idxs[keep_coords] if np_index: # convert back to original format filtered = tuple(filtered.T) return filtered def get_dtype(layer): """Returns dtype of layer data Parameters ---------- layer : Labels Labels layer (may be multiscale) Returns ------- dtype dtype of Layer data """ layer_data = layer.data if not isinstance(layer_data, list): layer_data = [layer_data] layer_data_level = layer_data[0] if hasattr(layer_data_level, 'dtype'): layer_dtype = layer_data_level[0].dtype else: layer_dtype = type(layer_data_level) return layer_dtype def first_nonzero_coordinate(data, start_point, end_point): """Coordinate of the first nonzero element between start and end points. Parameters ---------- data : nD array, shape (N1, N2, ..., ND) A data volume. start_point : array, shape (D,) The start coordinate to check. end_point : array, shape (D,) The end coordinate to check. Returns ------- coordinates : array of int, shape (D,) The coordinates of the first nonzero element along the ray, or None. """ shape = np.asarray(data.shape) length = np.linalg.norm(end_point - start_point) length_int = np.round(length).astype(int) coords = np.linspace(start_point, end_point, length_int + 1, endpoint=True) clipped_coords = np.clip(np.round(coords), 0, shape - 1).astype(int) nonzero = np.flatnonzero(data[tuple(clipped_coords.T)]) if len(nonzero) == 0: return None else: return clipped_coords[nonzero[0]] def mouse_event_to_labels_coordinate(layer, event): """Return the data coordinate of a Labels layer mouse event in 2D or 3D. In 2D, this is just the event's position transformed by the layer's world_to_data transform. In 3D, a ray is cast in data coordinates, and the coordinate of the first nonzero value along that ray is returned. If the ray only contains zeros, None is returned. Parameters ---------- layer : napari.layers.Labels The Labels layer. event : vispy MouseEvent The mouse event, containing position and view direction attributes. Returns ------- coordinates : array of int or None The data coordinates for the mouse event. """ ndim = len(layer._dims_displayed) if ndim == 2: coordinates = layer.world_to_data(event.position) else: # 3d start, end = layer.get_ray_intersections( position=event.position, view_direction=event.view_direction, dims_displayed=layer._dims_displayed, world=True, ) if start is None and end is None: return None coordinates = first_nonzero_coordinate(layer.data, start, end) return coordinates
2,414
821
/* * Copyright (C) 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.caliper.runner.worker; import com.google.caliper.bridge.AbstractLogMessageVisitor; import com.google.caliper.bridge.FailureLogMessage; /** * A {@link AbstractLogMessageVisitor} that handles {@link FailureLogMessage}s by throwing a {@link * ProxyWorkerException}. */ public final class FailureLogMessageVisitor extends AbstractLogMessageVisitor { public static final FailureLogMessageVisitor INSTANCE = new FailureLogMessageVisitor(); @Override public void visit(FailureLogMessage logMessage) { throw new ProxyWorkerException( logMessage.exceptionType(), logMessage.message(), logMessage.stackTrace()); } }
338
764
// 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 _ST_HPC_PPL_NN_PARAMS_PARAM_UTILS_MANAGER_H_ #define _ST_HPC_PPL_NN_PARAMS_PARAM_UTILS_MANAGER_H_ #include "ppl/nn/utils/op_info_manager.h" namespace ppl { namespace nn { struct ParamUtils final { bool (*equal)(const void* param_0, const void* param_1); }; class ParamUtilsManager final { public: static ParamUtilsManager* Instance() { static ParamUtilsManager mgr; return &mgr; } ppl::common::RetCode Register(const std::string& domain, const std::string& type, const utils::VersionRange& ver, const ParamUtils& item) { return mgr_.Register(domain, type, ver, item); } const ParamUtils* Find(const std::string& domain, const std::string& type, uint64_t version) const { return mgr_.Find(domain, type, version); } private: utils::OpInfoManager<ParamUtils> mgr_; private: ParamUtilsManager() {} }; }} // namespace ppl::nn #endif
591
367
#import "MBEMesh.h" @import Metal; @interface MBECubeMesh : MBEMesh - (instancetype)initWithDevice:(id<MTLDevice>) device; @end
53
618
<reponame>xuejike/hprose-java_rl<filename>src/main/java/hprose/io/serialize/java8/OffsetDateTimeSerializer.java /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * OffsetDateTimeSerializer.java * * * * OffsetDateTime serializer class for Java. * * * * LastModified: Aug 6, 2016 * * Author: <NAME> <<EMAIL>> * * * \**********************************************************/ package hprose.io.serialize.java8; import hprose.io.serialize.ReferenceSerializer; import hprose.io.serialize.ValueWriter; import hprose.io.serialize.Writer; import static hprose.io.HproseTags.TagString; import static hprose.io.HproseTags.TagUTC; import java.io.IOException; import java.io.OutputStream; import java.time.OffsetDateTime; import java.time.ZoneOffset; public final class OffsetDateTimeSerializer extends ReferenceSerializer<OffsetDateTime> { public final static OffsetDateTimeSerializer instance = new OffsetDateTimeSerializer(); @Override public final void serialize(Writer writer, OffsetDateTime datetime) throws IOException { super.serialize(writer, datetime); OutputStream stream = writer.stream; if (!(datetime.getOffset().equals(ZoneOffset.UTC))) { stream.write(TagString); ValueWriter.write(stream, datetime.toString()); } else { int year = datetime.getYear(); if (year > 9999 || year < 1) { stream.write(TagString); ValueWriter.write(stream, datetime.toString()); } else { ValueWriter.writeDate(stream, year, datetime.getMonthValue(), datetime.getDayOfMonth()); ValueWriter.writeTime(stream, datetime.getHour(), datetime.getMinute(), datetime.getSecond(), 0, false, true); ValueWriter.writeNano(stream, datetime.getNano()); stream.write(TagUTC); } } } }
1,377
831
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Context.h" #include <cstring> #include <memory> #include <assert.h> #include "OutboundCallChannel.h" #include "InboundCallChannel.h" #include "ExceptionThrowers.h" #include "common/finalization-registry.h" #include "quickjs/quickjs.h" std::string getName(JNIEnv* env, jobject javaClass) { auto classType = env->GetObjectClass(javaClass); const jmethodID method = env->GetMethodID(classType, "getName", "()Ljava/lang/String;"); auto javaString = static_cast<jstring>(env->CallObjectMethod(javaClass, method)); const auto s = env->GetStringUTFChars(javaString, nullptr); std::string str(s); env->ReleaseStringUTFChars(javaString, s); env->DeleteLocalRef(javaString); env->DeleteLocalRef(classType); return str; } /** * This signature satisfies the JSInterruptHandler typedef. It is always installed but only does * work if a Kotlin InterruptHandler is configured. */ int jsInterruptHandlerPoll(JSRuntime* jsRuntime, void *opaque) { auto context = reinterpret_cast<Context*>(opaque); auto interruptHandler = context->interruptHandler; if (interruptHandler == nullptr) return 0; JS_SetInterruptHandler(context->jsRuntime, NULL, NULL); // Suppress re-enter. auto env = context->getEnv(); const jboolean halt = env->CallBooleanMethod(interruptHandler, context->interruptHandlerPoll); JS_SetInterruptHandler(context->jsRuntime, &jsInterruptHandlerPoll, context); // Restore handler. // TODO: propagate the interrupt handler's exceptions through JS. return halt; } namespace { void jsFinalizeOutboundCallChannel(JSRuntime* jsRuntime, JSValue val) { auto context = reinterpret_cast<const Context*>(JS_GetRuntimeOpaque(jsRuntime)); if (context) { delete reinterpret_cast<OutboundCallChannel*>( JS_GetOpaque(val, context->outboundCallChannelClassId)); } } struct JniThreadDetacher { JavaVM& javaVm; JniThreadDetacher(JavaVM* javaVm) : javaVm(*javaVm) { } ~JniThreadDetacher() { javaVm.DetachCurrentThread(); } }; } // anonymous namespace Context::Context(JNIEnv* env) : jniVersion(env->GetVersion()), jsRuntime(JS_NewRuntime()), jsContext(JS_NewContext(jsRuntime)), outboundCallChannelClassId(0), lengthAtom(JS_NewAtom(jsContext, "length")), serviceNamesArrayAtom(JS_NewAtom(jsContext, "serviceNamesArray")), callAtom(JS_NewAtom(jsContext, "call")), disconnectAtom(JS_NewAtom(jsContext, "disconnect")), booleanClass(static_cast<jclass>(env->NewGlobalRef(env->FindClass("java/lang/Boolean")))), integerClass(static_cast<jclass>(env->NewGlobalRef(env->FindClass("java/lang/Integer")))), doubleClass(static_cast<jclass>(env->NewGlobalRef(env->FindClass("java/lang/Double")))), objectClass(static_cast<jclass>(env->NewGlobalRef(env->FindClass("java/lang/Object")))), stringClass(static_cast<jclass>(env->NewGlobalRef(env->FindClass("java/lang/String")))), stringUtf8(static_cast<jstring>(env->NewGlobalRef(env->NewStringUTF("UTF-8")))), quickJsExceptionClass(static_cast<jclass>(env->NewGlobalRef( env->FindClass("app/cash/zipline/QuickJsException")))), booleanValueOf(env->GetStaticMethodID(booleanClass, "valueOf", "(Z)Ljava/lang/Boolean;")), integerValueOf(env->GetStaticMethodID(integerClass, "valueOf", "(I)Ljava/lang/Integer;")), doubleValueOf(env->GetStaticMethodID(doubleClass, "valueOf", "(D)Ljava/lang/Double;")), stringGetBytes(env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B")), stringConstructor(env->GetMethodID(stringClass, "<init>", "([BLjava/lang/String;)V")), quickJsExceptionConstructor(env->GetMethodID(quickJsExceptionClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V")), interruptHandlerClass(static_cast<jclass>(env->NewGlobalRef(env->FindClass("app/cash/zipline/InterruptHandler")))), interruptHandlerPoll(env->GetMethodID(interruptHandlerClass, "poll", "()Z")), interruptHandler(nullptr) { env->GetJavaVM(&javaVm); JS_SetRuntimeOpaque(jsRuntime, this); JS_SetInterruptHandler(jsRuntime, &jsInterruptHandlerPoll, this); if (installFinalizationRegistry(jsContext) < 0) { throwJavaException(env, "java/lang/IllegalStateException", "Failed to install FinalizationRegistry"); } } Context::~Context() { for (auto callChannel : callChannels) { delete callChannel; } auto env = getEnv(); for (auto refs : globalReferences) { env->DeleteGlobalRef(refs.second); } if (interruptHandler != nullptr) { env->DeleteGlobalRef(interruptHandler); } env->DeleteGlobalRef(interruptHandlerClass); env->DeleteGlobalRef(quickJsExceptionClass); env->DeleteGlobalRef(stringUtf8); env->DeleteGlobalRef(stringClass); env->DeleteGlobalRef(objectClass); env->DeleteGlobalRef(doubleClass); env->DeleteGlobalRef(integerClass); env->DeleteGlobalRef(booleanClass); JS_FreeAtom(jsContext, lengthAtom); JS_FreeAtom(jsContext, serviceNamesArrayAtom); JS_FreeAtom(jsContext, callAtom); JS_FreeAtom(jsContext, disconnectAtom); JS_FreeContext(jsContext); JS_FreeRuntime(jsRuntime); } jobject Context::execute(JNIEnv* env, jbyteArray byteCode) { const auto buffer = env->GetByteArrayElements(byteCode, nullptr); const auto bufferLength = env->GetArrayLength(byteCode); const auto flags = JS_READ_OBJ_BYTECODE | JS_READ_OBJ_REFERENCE; auto obj = JS_ReadObject(jsContext, reinterpret_cast<const uint8_t*>(buffer), bufferLength, flags); env->ReleaseByteArrayElements(byteCode, buffer, JNI_ABORT); if (JS_IsException(obj)) { throwJsException(env, obj); return nullptr; } if (JS_ResolveModule(jsContext, obj)) { throwJsExceptionFmt(env, this, "Failed to resolve JS module"); return nullptr; } auto val = JS_EvalFunction(jsContext, obj); jobject result; if (!JS_IsException(val)) { result = toJavaObject(env, val, false); } else { result = nullptr; throwJsException(env, val); } JS_FreeValue(jsContext, val); return result; } jbyteArray Context::compile(JNIEnv* env, jstring source, jstring file) { const auto sourceCode = env->GetStringUTFChars(source, 0); const auto fileName = env->GetStringUTFChars(file, 0); auto compiled = JS_Eval(jsContext, sourceCode, strlen(sourceCode), fileName, JS_EVAL_FLAG_COMPILE_ONLY); env->ReleaseStringUTFChars(file, fileName); env->ReleaseStringUTFChars(source, sourceCode); if (JS_IsException(compiled)) { // TODO: figure out how to get the failing line number into the exception. throwJsException(env, compiled); JS_FreeValue(jsContext, compiled); return nullptr; } size_t bufferLength = 0; auto buffer = JS_WriteObject(jsContext, &bufferLength, compiled, JS_WRITE_OBJ_BYTECODE | JS_WRITE_OBJ_REFERENCE); auto result = buffer && bufferLength > 0 ? env->NewByteArray(bufferLength) : nullptr; if (result) { env->SetByteArrayRegion(result, 0, bufferLength, reinterpret_cast<const jbyte*>(buffer)); } else { throwJsException(env, compiled); } JS_FreeValue(jsContext, compiled); js_free(jsContext, buffer); return result; } void Context::setInterruptHandler(JNIEnv* env, jobject newInterruptHandler) { jobject oldInterruptHandler = interruptHandler; if (oldInterruptHandler != nullptr) { env->DeleteGlobalRef(oldInterruptHandler); } interruptHandler = env->NewGlobalRef(newInterruptHandler); } jobject Context::memoryUsage(JNIEnv* env) { auto memoryUsageClass = env->FindClass("app/cash/zipline/MemoryUsage"); if (!memoryUsageClass) { // Should be impossible. If R8 removed the type then this function can never be invoked. return nullptr; } auto memoryUsageConstructor = env->GetMethodID(memoryUsageClass, "<init>", "(JJJJJJJJJJJJJJJJJJJJJJJJJJ)V"); if (!memoryUsageConstructor) { // Should be impossible. If R8 removed the type then this function can never be invoked. return nullptr; } JSMemoryUsage jsMemoryUsage; JS_ComputeMemoryUsage(jsRuntime, &jsMemoryUsage); return static_cast<jstring>(env->NewObject( memoryUsageClass, memoryUsageConstructor, jsMemoryUsage.malloc_count, jsMemoryUsage.malloc_size, jsMemoryUsage.malloc_limit, jsMemoryUsage.memory_used_count, jsMemoryUsage.memory_used_size, jsMemoryUsage.atom_count, jsMemoryUsage.atom_size, jsMemoryUsage.str_count, jsMemoryUsage.str_size, jsMemoryUsage.obj_count, jsMemoryUsage.obj_size, jsMemoryUsage.prop_count, jsMemoryUsage.prop_size, jsMemoryUsage.shape_count, jsMemoryUsage.shape_size, jsMemoryUsage.js_func_count, jsMemoryUsage.js_func_size, jsMemoryUsage.js_func_code_size, jsMemoryUsage.js_func_pc2line_count, jsMemoryUsage.js_func_pc2line_size, jsMemoryUsage.c_func_count, jsMemoryUsage.array_count, jsMemoryUsage.fast_array_count, jsMemoryUsage.fast_array_elements, jsMemoryUsage.binary_object_count, jsMemoryUsage.binary_object_size )); } void Context::setMemoryLimit(JNIEnv* env, jlong limit) { JS_SetMemoryLimit(jsRuntime, limit); } void Context::setGcThreshold(JNIEnv* env, jlong gcThreshold) { JS_SetGCThreshold(jsRuntime, gcThreshold); } void Context::setMaxStackSize(JNIEnv* env, jlong stackSize) { JS_SetMaxStackSize(jsRuntime, stackSize); } void Context::gc(JNIEnv* env) { JS_RunGC(jsRuntime); } InboundCallChannel* Context::getInboundCallChannel(JNIEnv* env, jstring name) { JSValue global = JS_GetGlobalObject(jsContext); const char* nameStr = env->GetStringUTFChars(name, 0); JSValue obj = JS_GetPropertyStr(jsContext, global, nameStr); InboundCallChannel* inboundCallChannel = nullptr; if (JS_IsObject(obj)) { inboundCallChannel = new InboundCallChannel(jsContext, nameStr); if (!env->ExceptionCheck()) { callChannels.push_back(inboundCallChannel); } else { delete inboundCallChannel; inboundCallChannel = nullptr; } } else if (JS_IsException(obj)) { throwJsException(env, obj); } else { const char* msg = JS_IsUndefined(obj) ? "A global JavaScript object called %s was not found" : "JavaScript global called %s is not an object"; throwJavaException(env, "java/lang/IllegalStateException", msg, nameStr); } JS_FreeValue(jsContext, obj); env->ReleaseStringUTFChars(name, nameStr); JS_FreeValue(jsContext, global); return inboundCallChannel; } void Context::setOutboundCallChannel(JNIEnv* env, jstring name, jobject callChannel) { auto global = JS_GetGlobalObject(jsContext); const char* nameStr = env->GetStringUTFChars(name, 0); const auto objName = JS_NewAtom(jsContext, nameStr); if (!JS_HasProperty(jsContext, global, objName)) { if (outboundCallChannelClassId == 0) { JS_NewClassID(&outboundCallChannelClassId); JSClassDef classDef; memset(&classDef, 0, sizeof(JSClassDef)); classDef.class_name = "OutboundCallChannel"; classDef.finalizer = jsFinalizeOutboundCallChannel; if (JS_NewClass(jsRuntime, outboundCallChannelClassId, &classDef) < 0) { outboundCallChannelClassId = 0; throwJavaException(env, "java/lang/NullPointerException", "Failed to allocate JavaScript OutboundCallChannel class"); } } if (outboundCallChannelClassId != 0) { auto jsOutboundCallChannel = JS_NewObjectClass(jsContext, outboundCallChannelClassId); if (JS_IsException(jsOutboundCallChannel) || JS_SetProperty(jsContext, global, objName, jsOutboundCallChannel) <= 0) { throwJsException(env, jsOutboundCallChannel); } else { std::unique_ptr<OutboundCallChannel> javaObject(new OutboundCallChannel(this, env, nameStr, callChannel, jsOutboundCallChannel)); if (!env->ExceptionCheck()) { JS_SetOpaque(jsOutboundCallChannel, javaObject.release()); } } } } else { throwJavaException(env, "java/lang/IllegalArgumentException", "A global object called %s already exists", nameStr); } JS_FreeAtom(jsContext, objName); env->ReleaseStringUTFChars(name, nameStr); JS_FreeValue(jsContext, global); } jobject Context::toJavaObject(JNIEnv* env, const JSValueConst& value, bool throwOnUnsupportedType) { jobject result; switch (JS_VALUE_GET_NORM_TAG(value)) { case JS_TAG_EXCEPTION: { throwJsException(env, value); result = nullptr; break; } case JS_TAG_STRING: { result = toJavaString(env, value); break; } case JS_TAG_BOOL: { jvalue v; v.z = static_cast<jboolean>(JS_VALUE_GET_BOOL(value)); result = env->CallStaticObjectMethodA(booleanClass, booleanValueOf, &v); break; } case JS_TAG_INT: { jvalue v; v.j = static_cast<jint>(JS_VALUE_GET_INT(value)); result = env->CallStaticObjectMethodA(integerClass, integerValueOf, &v); break; } case JS_TAG_FLOAT64: { jvalue v; v.d = static_cast<jdouble>(JS_VALUE_GET_FLOAT64(value)); result = env->CallStaticObjectMethodA(doubleClass, doubleValueOf, &v); break; } case JS_TAG_NULL: case JS_TAG_UNDEFINED: result = nullptr; break; case JS_TAG_OBJECT: if (JS_IsArray(jsContext, value)) { auto arrayLengthProperty = JS_GetPropertyStr(jsContext, value, "length"); const auto arrayLength = JS_VALUE_GET_INT(arrayLengthProperty); JS_FreeValue(jsContext, arrayLengthProperty); result = env->NewObjectArray(arrayLength, objectClass, nullptr); for (int i = 0; i < arrayLength && !env->ExceptionCheck(); i++) { auto element = JS_GetPropertyUint32(jsContext, value, i); auto javaElement = toJavaObject(env, element); if (!env->ExceptionCheck()) { env->SetObjectArrayElement(static_cast<jobjectArray>(result), i, javaElement); } JS_FreeValue(jsContext, element); } break; } // Fall through. default: if (throwOnUnsupportedType) { auto str = JS_ToCString(jsContext, value); throwJsExceptionFmt(env, this, "Cannot marshal value %s to Java", str); JS_FreeCString(jsContext, str); } result = nullptr; break; } return result; } jobject Context::eval(JNIEnv* env, jstring source, jstring file) { std::string sourceCodeString = toCppString(env, source); const char* fileName = env->GetStringUTFChars(file, 0); JSValue evalValue = JS_Eval(jsContext, sourceCodeString.c_str(), sourceCodeString.length(), fileName, 0); env->ReleaseStringUTFChars(file, fileName); jobject result = toJavaObject(env, evalValue, false); JS_FreeValue(jsContext, evalValue); return result; } void Context::throwJsException(JNIEnv* env, const JSValue& value) const { JSValue exceptionValue = JS_GetException(jsContext); JSValue messageValue = JS_GetPropertyStr(jsContext, exceptionValue, "message"); JSValue stackValue = JS_GetPropertyStr(jsContext, exceptionValue, "stack"); // If the JS does a `throw 2;`, there won't be a message property. jstring message = toJavaString(env, JS_IsUndefined(messageValue) ? exceptionValue : messageValue); JS_FreeValue(jsContext, messageValue); jstring stack = toJavaString(env, stackValue); JS_FreeValue(jsContext, stackValue); JS_FreeValue(jsContext, exceptionValue); jthrowable cause = static_cast<jthrowable>(JS_GetContextOpaque(jsContext)); JS_SetContextOpaque(jsContext, nullptr); jobject exception; if (cause) { exception = env->NewLocalRef(cause); env->DeleteGlobalRef(cause); // add the JavaScript stack to this exception. const jmethodID addJavaScriptStack = env->GetStaticMethodID(quickJsExceptionClass, "addJavaScriptStack", "(Ljava/lang/Throwable;Ljava/lang/String;)V"); env->CallStaticVoidMethod(quickJsExceptionClass, addJavaScriptStack, exception, stack); } else { exception = env->NewObject(quickJsExceptionClass, quickJsExceptionConstructor, message, stack); } env->DeleteLocalRef(stack); env->DeleteLocalRef(message); env->Throw(static_cast<jthrowable>(exception)); } JSValue Context::throwJavaExceptionFromJs(JNIEnv* env) const { assert(env->ExceptionCheck()); // There must be something to throw. assert(JS_GetContextOpaque(jsContext) == nullptr); // There can't be a pending thrown exception. auto exception = env->ExceptionOccurred(); env->ExceptionClear(); JS_SetContextOpaque(jsContext, env->NewGlobalRef(exception)); return JS_ThrowInternalError(jsContext, "Java Exception"); } JNIEnv* Context::getEnv() const { JNIEnv* env = nullptr; javaVm->GetEnv(reinterpret_cast<void**>(&env), jniVersion); if (env) { return env; } javaVm->AttachCurrentThread( #ifdef __ANDROID__ &env, #else reinterpret_cast<void**>(&env), #endif nullptr); if (env) { thread_local JniThreadDetacher detacher(javaVm); } return env; } jclass Context::getGlobalRef(JNIEnv* env, jclass clazz) { auto name = getName(env, clazz); auto i = globalReferences.find(name); if (i != globalReferences.end()) { return i->second; } auto globalRef = static_cast<jclass>(env->NewGlobalRef(clazz)); globalReferences[name] = globalRef; return globalRef; } /* * Converts `string` to UTF-8. Prefer this over `GetStringUTFChars()` for any string that might * contain non-ASCII characters because that function returns modified UTF-8. */ std::string Context::toCppString(JNIEnv* env, jstring string) const { const jbyteArray utf8BytesObject = static_cast<jbyteArray>(env->CallObjectMethod(string, stringGetBytes, stringUtf8)); size_t utf8Length = env->GetArrayLength(utf8BytesObject); jbyte* utf8Bytes = env->GetByteArrayElements(utf8BytesObject, NULL); std::string result = std::string(reinterpret_cast<char*>(utf8Bytes), utf8Length); env->ReleaseByteArrayElements(utf8BytesObject, utf8Bytes, JNI_ABORT); env->DeleteLocalRef(utf8BytesObject); return result; } JSValue Context::toJsString(JNIEnv* env, jstring javaString) const { std::string cppString = this->toCppString(env, javaString); return JS_NewString(this->jsContext, cppString.c_str()); } JSValue Context::toJsStringArray(JNIEnv* env, jobjectArray javaStringArray) const { JSValue result = JS_NewArray(this->jsContext); const auto length = env->GetArrayLength(javaStringArray); for (jsize i = 0; i < length; i++) { jstring javaString = static_cast<jstring>(env->GetObjectArrayElement(javaStringArray, i)); JS_SetPropertyUint32(this->jsContext, result, i, this->toJsString(env, javaString)); env->DeleteLocalRef(javaString); } return result; } /* * Converts `value` to a Java string. Prefer this over `NewStringUTF()` for any string that might * contain non-ASCII characters because that function expects modified UTF-8. */ jstring Context::toJavaString(JNIEnv* env, const JSValueConst& value) const { const char* string = JS_ToCString(jsContext, value); size_t utf8Length = strlen(string); jbyteArray utf8BytesObject = env->NewByteArray(utf8Length); jbyte* utf8Bytes = env->GetByteArrayElements(utf8BytesObject, NULL); std::copy(string, string + utf8Length, utf8Bytes); env->ReleaseByteArrayElements(utf8BytesObject, utf8Bytes, JNI_COMMIT); JS_FreeCString(jsContext, string); jstring result = static_cast<jstring>(env->NewObject(stringClass, stringConstructor, utf8BytesObject, stringUtf8)); env->DeleteLocalRef(utf8BytesObject); return result; } jobjectArray Context::toJavaStringArray(JNIEnv* env, const JSValueConst& value) const { auto jsContext = this->jsContext; assert(JS_IsArray(jsContext, value)); auto jsLength = JS_GetProperty(jsContext, value, this->lengthAtom); int length = 0; auto convertResult = JS_ToInt32(jsContext, &length, jsLength); assert(convertResult == 0); jobjectArray result = env->NewObjectArray(length, this->stringClass, nullptr); for (int i = 0; i < length && !env->ExceptionCheck(); i++) { auto jsElement = JS_GetPropertyUint32(jsContext, value, i); jstring element = this->toJavaString(env, jsElement); JS_FreeValue(jsContext, jsElement); if (env->ExceptionCheck()) break; env->SetObjectArrayElement(result, i, element); } JS_FreeValue(jsContext, jsLength); return result; }
7,695
2,116
{ "name": "end-to-end-instrumentation-browser", "version": "0.0.1", "description": "Following https://webpack.js.org/guides/getting-started/", "private": true, "scripts": { "lint": "npx eslint -c .eslintrc.js 'src/**/*.js' --fix", "build": "webpack" }, "author": "", "license": "ISC", "devDependencies": { "webpack": "^4.41.2", "webpack-cli": "^3.3.10" }, "dependencies": { "@opentelemetry/exporter-collector": "^0.4.0", "@opentelemetry/plugin-document-load": "^0.4.0", "@opentelemetry/plugin-xml-http-request": "^0.4.0", "@opentelemetry/scope-zone": "^0.4.0", "@opentelemetry/tracing": "^0.4.0", "@opentelemetry/web": "^0.4.0", "rxjs": "^6.5.3" } }
342
4,552
<reponame>ojmakhura/DIGITS from model import Tower from utils import model_property import tensorflow as tf import tensorflow.contrib.slim as slim import utils as digits class UserModel(Tower): @model_property def inference(self): _x = tf.reshape(self.x, shape=[-1, self.input_shape[0], self.input_shape[1], self.input_shape[2]]) # tf.image_summary(_x.op.name, _x, max_images=10, collections=[digits.GraphKeys.SUMMARIES_TRAIN]) # Split out the color channels _, model_g, model_b = tf.split(_x, 3, 3, name='split_channels') # tf.image_summary(model_g.op.name, model_g, max_images=10, collections=[digits.GraphKeys.SUMMARIES_TRAIN]) # tf.image_summary(model_b.op.name, model_b, max_images=10, collections=[digits.GraphKeys.SUMMARIES_TRAIN]) with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_initializer=tf.contrib.layers.xavier_initializer(), weights_regularizer=slim.l2_regularizer(0.0005)): with tf.variable_scope("siamese") as scope: def make_tower(net): net = slim.conv2d(net, 20, [5, 5], padding='VALID', scope='conv1') net = slim.max_pool2d(net, [2, 2], padding='VALID', scope='pool1') net = slim.conv2d(net, 50, [5, 5], padding='VALID', scope='conv2') net = slim.max_pool2d(net, [2, 2], padding='VALID', scope='pool2') net = slim.flatten(net) net = slim.fully_connected(net, 500, scope='fc1') net = slim.fully_connected(net, 2, activation_fn=None, scope='fc2') return net model_g = make_tower(model_g) model_g = tf.reshape(model_g, shape=[-1, 2]) scope.reuse_variables() model_b = make_tower(model_b) model_b = tf.reshape(model_b, shape=[-1, 2]) return [model_g, model_b] @model_property def loss(self): _y = tf.reshape(self.y, shape=[-1]) _y = tf.to_float(_y) model = self.inference return digits.constrastive_loss(model[0], model[1], _y)
1,098
4,320
/* * Copyright (c) 2019, Adam <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.http.service.ge; import java.util.Collection; import net.runelite.http.api.ge.GrandExchangeTrade; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.sql2o.Connection; import org.sql2o.Sql2o; @Service public class GrandExchangeService { private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS `ge_trades` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `user` int(11) NOT NULL,\n" + " `action` enum('BUY','SELL') NOT NULL,\n" + " `item` int(11) NOT NULL,\n" + " `quantity` int(11) NOT NULL,\n" + " `price` int(11) NOT NULL,\n" + " `time` timestamp NOT NULL DEFAULT current_timestamp(),\n" + " PRIMARY KEY (`id`),\n" + " KEY `user_time` (`user`, `time`),\n" + " KEY `time` (`time`),\n" + " CONSTRAINT `ge_trades_ibfk_1` FOREIGN KEY (`user`) REFERENCES `users` (`id`)\n" + ") ENGINE=InnoDB;"; private final Sql2o sql2o; private final int historyDays; @Autowired public GrandExchangeService( @Qualifier("Runelite SQL2O") Sql2o sql2o, @Value("${runelite.ge.history}") int historyDays ) { this.sql2o = sql2o; this.historyDays = historyDays; // Ensure necessary tables exist try (Connection con = sql2o.open()) { con.createQuery(CREATE_TABLE).executeUpdate(); } } public void add(int userId, GrandExchangeTrade grandExchangeTrade) { try (Connection con = sql2o.open()) { con.createQuery("insert into ge_trades (user, action, item, quantity, price) values (:user," + " :action, :item, :quantity, :price)") .addParameter("user", userId) .addParameter("action", grandExchangeTrade.isBuy() ? "BUY" : "SELL") .addParameter("item", grandExchangeTrade.getItemId()) .addParameter("quantity", grandExchangeTrade.getQty()) .addParameter("price", grandExchangeTrade.getSpent() / grandExchangeTrade.getQty()) .executeUpdate(); } } public Collection<TradeEntry> get(int userId, int limit, int offset) { try (Connection con = sql2o.open()) { return con.createQuery("select id, user, action, item, quantity, price, time from ge_trades where user = :user limit :limit offset :offset") .addParameter("user", userId) .addParameter("limit", limit) .addParameter("offset", offset) .executeAndFetch(TradeEntry.class); } } public void delete(int userId) { try (Connection con = sql2o.open()) { con.createQuery("delete from ge_trades where user = :user") .addParameter("user", userId) .executeUpdate(); } } @Scheduled(fixedDelay = 60 * 60 * 1000) public void expire() { try (Connection con = sql2o.open()) { con.createQuery("delete from ge_trades where time < current_timestamp - interval " + historyDays + " day") .executeUpdate(); } } }
1,544
305
<reponame>gaoxiaoyang/webrtc /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/test/wav_based_simulator.h" #include <stdio.h> #include <iostream> #include "modules/audio_processing/test/test_utils.h" #include "rtc_base/checks.h" namespace webrtc { namespace test { std::vector<WavBasedSimulator::SimulationEventType> WavBasedSimulator::GetCustomEventChain(const std::string& filename) { std::vector<WavBasedSimulator::SimulationEventType> call_chain; FILE* stream = OpenFile(filename.c_str(), "r"); RTC_CHECK(stream) << "Could not open the custom call order file, reverting " "to using the default call order"; char c; size_t num_read = fread(&c, sizeof(char), 1, stream); while (num_read > 0) { switch (c) { case 'r': call_chain.push_back(SimulationEventType::kProcessReverseStream); break; case 'c': call_chain.push_back(SimulationEventType::kProcessStream); break; case '\n': break; default: FATAL() << "Incorrect custom call order file, reverting to using the " "default call order"; fclose(stream); return WavBasedSimulator::GetDefaultEventChain(); } num_read = fread(&c, sizeof(char), 1, stream); } fclose(stream); return call_chain; } WavBasedSimulator::WavBasedSimulator( const SimulationSettings& settings, std::unique_ptr<AudioProcessingBuilder> ap_builder) : AudioProcessingSimulator(settings, std::move(ap_builder)) {} WavBasedSimulator::~WavBasedSimulator() = default; std::vector<WavBasedSimulator::SimulationEventType> WavBasedSimulator::GetDefaultEventChain() { std::vector<WavBasedSimulator::SimulationEventType> call_chain(2); call_chain[0] = SimulationEventType::kProcessStream; call_chain[1] = SimulationEventType::kProcessReverseStream; return call_chain; } void WavBasedSimulator::PrepareProcessStreamCall() { if (settings_.fixed_interface) { CopyToAudioFrame(*in_buf_, &fwd_frame_); } ap_->set_stream_key_pressed(settings_.use_ts && (*settings_.use_ts)); if (!settings_.use_stream_delay || *settings_.use_stream_delay) { RTC_CHECK_EQ(AudioProcessing::kNoError, ap_->set_stream_delay_ms( settings_.stream_delay ? *settings_.stream_delay : 0)); } } void WavBasedSimulator::PrepareReverseProcessStreamCall() { if (settings_.fixed_interface) { CopyToAudioFrame(*reverse_in_buf_, &rev_frame_); } } void WavBasedSimulator::Process() { if (settings_.call_order_input_filename) { call_chain_ = WavBasedSimulator::GetCustomEventChain( *settings_.call_order_input_filename); } else { call_chain_ = WavBasedSimulator::GetDefaultEventChain(); } CreateAudioProcessor(); Initialize(); bool samples_left_to_process = true; int call_chain_index = 0; int num_forward_chunks_processed = 0; while (samples_left_to_process) { switch (call_chain_[call_chain_index]) { case SimulationEventType::kProcessStream: samples_left_to_process = HandleProcessStreamCall(); ++num_forward_chunks_processed; break; case SimulationEventType::kProcessReverseStream: if (settings_.reverse_input_filename) { samples_left_to_process = HandleProcessReverseStreamCall(); } break; default: RTC_CHECK(false); } call_chain_index = (call_chain_index + 1) % call_chain_.size(); } DestroyAudioProcessor(); } bool WavBasedSimulator::HandleProcessStreamCall() { bool samples_left_to_process = buffer_reader_->Read(in_buf_.get()); if (samples_left_to_process) { PrepareProcessStreamCall(); ProcessStream(settings_.fixed_interface); } return samples_left_to_process; } bool WavBasedSimulator::HandleProcessReverseStreamCall() { bool samples_left_to_process = reverse_buffer_reader_->Read(reverse_in_buf_.get()); if (samples_left_to_process) { PrepareReverseProcessStreamCall(); ProcessReverseStream(settings_.fixed_interface); } return samples_left_to_process; } void WavBasedSimulator::Initialize() { std::unique_ptr<WavReader> in_file( new WavReader(settings_.input_filename->c_str())); int input_sample_rate_hz = in_file->sample_rate(); int input_num_channels = in_file->num_channels(); buffer_reader_.reset(new ChannelBufferWavReader(std::move(in_file))); int output_sample_rate_hz = settings_.output_sample_rate_hz ? *settings_.output_sample_rate_hz : input_sample_rate_hz; int output_num_channels = settings_.output_num_channels ? *settings_.output_num_channels : input_num_channels; int reverse_sample_rate_hz = 48000; int reverse_num_channels = 1; int reverse_output_sample_rate_hz = 48000; int reverse_output_num_channels = 1; if (settings_.reverse_input_filename) { std::unique_ptr<WavReader> reverse_in_file( new WavReader(settings_.reverse_input_filename->c_str())); reverse_sample_rate_hz = reverse_in_file->sample_rate(); reverse_num_channels = reverse_in_file->num_channels(); reverse_buffer_reader_.reset( new ChannelBufferWavReader(std::move(reverse_in_file))); reverse_output_sample_rate_hz = settings_.reverse_output_sample_rate_hz ? *settings_.reverse_output_sample_rate_hz : reverse_sample_rate_hz; reverse_output_num_channels = settings_.reverse_output_num_channels ? *settings_.reverse_output_num_channels : reverse_num_channels; } SetupBuffersConfigsOutputs( input_sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz, reverse_output_sample_rate_hz, input_num_channels, output_num_channels, reverse_num_channels, reverse_output_num_channels); } } // namespace test } // namespace webrtc
2,481
1,350
<filename>sdk/cosmos/azure-spring-data-cosmos-test/src/test/java/com/azure/spring/data/cosmos/domain/CourseWithEtag.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.spring.data.cosmos.domain; import com.azure.spring.data.cosmos.core.mapping.Container; import com.azure.spring.data.cosmos.core.mapping.PartitionKey; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Version; import java.util.Objects; @Container public class CourseWithEtag { @Id private String courseId; private String name; @PartitionKey private String department; @Version private String etag; public CourseWithEtag(String courseId, String name, String department) { this.courseId = courseId; this.name = name; this.department = department; } public CourseWithEtag() { } public String getCourseId() { return courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getEtag() { return this.etag; } public void setEtag(String etag) { this.etag = etag; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CourseWithEtag course = (CourseWithEtag) o; return courseId.equals(course.courseId) && name.equals(course.name) && department.equals(course.department); } @Override public int hashCode() { return Objects.hash(courseId, name, department); } @Override public String toString() { return "Course{" + "courseId='" + courseId + '\'' + ", name='" + name + '\'' + ", department='" + department + '\'' + ", etag='" + etag + '\'' + '}'; } }
1,049
826
<reponame>julescmay/LuxCore<gh_stars>100-1000 // SPDX-License-Identifier: BSD-3-Clause // Copyright Contributors to the OpenColorIO Project. #include <algorithm> #include <cmath> #include <iostream> #include <sstream> #include <OpenColorIO/OpenColorIO.h> #include "BitDepthUtils.h" #include "HashUtils.h" #include "GpuShaderUtils.h" #include "MathUtils.h" #include "ops/lut1d/Lut1DOp.h" #include "ops/lut1d/Lut1DOpCPU.h" #include "ops/lut1d/Lut1DOpGPU.h" #include "ops/matrix/MatrixOp.h" #include "ops/OpTools.h" #include "SSE.h" #include "transforms/Lut1DTransform.h" namespace OCIO_NAMESPACE { namespace { class Lut1DOp; typedef OCIO_SHARED_PTR<Lut1DOp> Lut1DOpRcPtr; typedef OCIO_SHARED_PTR<const Lut1DOp> ConstLut1DOpRcPtr; class Lut1DOp : public Op { public: Lut1DOp() = delete; Lut1DOp(const Lut1DOp &) = delete; explicit Lut1DOp(Lut1DOpDataRcPtr & lutData); virtual ~Lut1DOp(); OpRcPtr clone() const override; std::string getInfo() const override; bool isSameType(ConstOpRcPtr & op) const override; bool isInverse(ConstOpRcPtr & op) const override; bool canCombineWith(ConstOpRcPtr & op) const override; void combineWith(OpRcPtrVec & ops, ConstOpRcPtr & secondOp) const override; bool hasChannelCrosstalk() const override; void finalize() override; std::string getCacheID() const override; ConstOpCPURcPtr getCPUOp(bool fastLogExpPow) const override; bool supportedByLegacyShader() const override { return false; } void extractGpuShaderInfo(GpuShaderCreatorRcPtr & shaderCreator) const override; ConstLut1DOpDataRcPtr lut1DData() const { return DynamicPtrCast<const Lut1DOpData>(data()); } Lut1DOpDataRcPtr lut1DData() { return DynamicPtrCast<Lut1DOpData>(data()); } }; Lut1DOp::Lut1DOp(Lut1DOpDataRcPtr & lut1D) { data() = lut1D; } Lut1DOp::~Lut1DOp() { } OpRcPtr Lut1DOp::clone() const { Lut1DOpDataRcPtr lut = lut1DData()->clone(); return std::make_shared<Lut1DOp>(lut); } std::string Lut1DOp::getInfo() const { return "<Lut1DOp>"; } bool Lut1DOp::isSameType(ConstOpRcPtr & op) const { ConstLut1DOpRcPtr typedRcPtr = DynamicPtrCast<const Lut1DOp>(op); return (bool)typedRcPtr; } bool Lut1DOp::isInverse(ConstOpRcPtr & op) const { ConstLut1DOpRcPtr typedRcPtr = DynamicPtrCast<const Lut1DOp>(op); if (typedRcPtr) { ConstLut1DOpDataRcPtr lutData = typedRcPtr->lut1DData(); return lut1DData()->isInverse(lutData); } return false; } bool Lut1DOp::canCombineWith(ConstOpRcPtr & op) const { ConstLut1DOpRcPtr typedRcPtr = DynamicPtrCast<const Lut1DOp>(op); if (typedRcPtr) { ConstLut1DOpDataRcPtr lutData = typedRcPtr->lut1DData(); return lut1DData()->mayCompose(lutData); } // TODO: drop a clampIdentity Range after an Inverse LUT. return false; } void Lut1DOp::combineWith(OpRcPtrVec & ops, ConstOpRcPtr & secondOp) const { if (!canCombineWith(secondOp)) { throw Exception("Lut1DOp: canCombineWith must be checked " "before calling combineWith."); } ConstLut1DOpRcPtr typedRcPtr = DynamicPtrCast<const Lut1DOp>(secondOp); auto secondLut = typedRcPtr->lut1DData(); // We want compose to upsample the LUTs to minimize precision loss. const auto compFlag = Lut1DOpData::COMPOSE_RESAMPLE_BIG; auto thisLut = lut1DData(); Lut1DOpDataRcPtr result = Lut1DOpData::Compose(thisLut, secondLut, compFlag); auto composedOp = std::make_shared<Lut1DOp>(result); ops.push_back(composedOp); } bool Lut1DOp::hasChannelCrosstalk() const { return lut1DData()->hasChannelCrosstalk(); } void Lut1DOp::finalize() { lut1DData()->finalize(); } std::string Lut1DOp::getCacheID() const { // Rebuild the cache identifier. std::ostringstream cacheIDStream; cacheIDStream << "<Lut1D "; cacheIDStream << lut1DData()->getCacheID(); cacheIDStream << ">"; return cacheIDStream.str(); } ConstOpCPURcPtr Lut1DOp::getCPUOp(bool /*fastLogExpPow*/) const { ConstLut1DOpDataRcPtr data = lut1DData(); return GetLut1DRenderer(data, BIT_DEPTH_F32, BIT_DEPTH_F32); } void Lut1DOp::extractGpuShaderInfo(GpuShaderCreatorRcPtr & shaderCreator) const { ConstLut1DOpDataRcPtr lutData = lut1DData(); if (lutData->getDirection() == TRANSFORM_DIR_INVERSE) { // TODO: Even if the optim flags specify exact inversion, only fast inversion is supported // on the GPU. Add GPU renderer for EXACT mode. Lut1DOpDataRcPtr tmp = MakeFastLut1DFromInverse(lutData); if (!tmp) { throw Exception("Cannot apply Lut1DOp, inversion failed."); } lutData = tmp; } GetLut1DGPUShaderProgram(shaderCreator, lutData); } } void CreateLut1DOp(OpRcPtrVec & ops, Lut1DOpDataRcPtr & lut, TransformDirection direction) { // TODO: Detect if 1D LUT can be exactly approximated as y = mx + b // If so, return a mtx instead. Lut1DOpDataRcPtr lutData = lut; if (direction == TRANSFORM_DIR_INVERSE) { lutData = lut->inverse(); } ops.push_back(std::make_shared<Lut1DOp>(lutData)); } void GenerateIdentityLut1D(float* img, int numElements, int numChannels) { if(!img) return; int numChannelsToFill = std::min(3, numChannels); float scale = 1.0f / ((float) numElements - 1.0f); for(int i=0; i<numElements; i++) { for(int c=0; c<numChannelsToFill; ++c) { img[numChannels*i+c] = scale * (float)(i); } } } /////////////////////////////////////////////////////////////////////////////// void CreateLut1DTransform(GroupTransformRcPtr & group, ConstOpRcPtr & op) { auto lut = DynamicPtrCast<const Lut1DOp>(op); if (!lut) { throw Exception("CreateLut1DTransform: op has to be a Lut1DOp"); } auto lutData = DynamicPtrCast<const Lut1DOpData>(op->data()); auto lutTransform = Lut1DTransform::Create(); auto & data = dynamic_cast<Lut1DTransformImpl *>(lutTransform.get())->data(); data = *lutData; group->appendTransform(lutTransform); } void BuildLut1DOp(OpRcPtrVec & ops, const Lut1DTransform & transform, TransformDirection dir) { const auto & data = dynamic_cast<const Lut1DTransformImpl &>(transform).data(); data.validate(); auto lut = data.clone(); CreateLut1DOp(ops, lut, dir); } } // namespace OCIO_NAMESPACE
2,848
777
// 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 "core/layout/ng/ng_physical_fragment.h" #include "core/layout/ng/ng_break_token.h" #include "core/layout/ng/ng_physical_box_fragment.h" #include "core/layout/ng/ng_physical_text_fragment.h" namespace blink { NGPhysicalFragment::NGPhysicalFragment( NGPhysicalSize size, NGPhysicalSize overflow, NGFragmentType type, HeapLinkedHashSet<WeakMember<NGBlockNode>>& out_of_flow_descendants, Vector<NGStaticPosition> out_of_flow_positions, NGBreakToken* break_token) : size_(size), overflow_(overflow), break_token_(break_token), type_(type), has_been_placed_(false) { out_of_flow_descendants_.swap(out_of_flow_descendants); out_of_flow_positions_.swap(out_of_flow_positions); } DEFINE_TRACE(NGPhysicalFragment) { if (Type() == kFragmentText) static_cast<NGPhysicalTextFragment*>(this)->traceAfterDispatch(visitor); else static_cast<NGPhysicalBoxFragment*>(this)->traceAfterDispatch(visitor); } void NGPhysicalFragment::finalizeGarbageCollectedObject() { if (Type() == kFragmentText) static_cast<NGPhysicalTextFragment*>(this)->~NGPhysicalTextFragment(); else static_cast<NGPhysicalBoxFragment*>(this)->~NGPhysicalBoxFragment(); } DEFINE_TRACE_AFTER_DISPATCH(NGPhysicalFragment) { visitor->trace(out_of_flow_descendants_); visitor->trace(break_token_); } } // namespace blink
561
373
/** @file Implementation of Fsp Misc UPD Initialization. Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <PiPei.h> #include <Library/DebugLib.h> #include <Library/PciLib.h> #include <Library/PeiLib.h> #include <FspEas.h> #include <FspmUpd.h> #include <FspsUpd.h> #include <Guid/MemoryOverwriteControl.h> #include <PchAccess.h> /** Performs FSP Misc UPD initialization. @param[in][out] FspmUpd Pointer to FSPM_UPD Data. @retval EFI_SUCCESS FSP UPD Data is updated. **/ EFI_STATUS EFIAPI PeiFspMiscUpdUpdatePreMem ( IN OUT FSPM_UPD *FspmUpd ) { EFI_STATUS Status; UINTN VariableSize; VOID *FspNvsBufferPtr; UINT8 MorControl; VOID *MorControlPtr; // // Initialize S3 Data variable (S3DataPtr). It may be used for warm and fast boot paths. // FspNvsBufferPtr = NULL; VariableSize = 0; Status = PeiGetLargeVariable (L"FspNvsBuffer", &gFspNvsBufferVariableGuid, &FspNvsBufferPtr, &VariableSize); if (Status == EFI_SUCCESS) { DEBUG ((DEBUG_INFO, "Get L\"FspNvsBuffer\" gFspNvsBufferVariableGuid - %r\n", Status)); DEBUG ((DEBUG_INFO, "FspNvsBuffer Size - 0x%x\n", VariableSize)); FspmUpd->FspmArchUpd.NvsBufferPtr = FspNvsBufferPtr; } if (FspmUpd->FspmArchUpd.NvsBufferPtr != NULL) { // // Set the DISB bit in PCH (DRAM Initialization Scratchpad Bit - GEN_PMCON_A[23]), // after memory Data is saved to NVRAM. // PciOr32 ((UINTN)PCI_LIB_ADDRESS (0, PCI_DEVICE_NUMBER_PCH_PMC, PCI_FUNCTION_NUMBER_PCH_PMC, R_PCH_PMC_GEN_PMCON_A), B_PCH_PMC_GEN_PMCON_A_DISB); } // // MOR // MorControl = 0; MorControlPtr = &MorControl; VariableSize = sizeof (MorControl); Status = PeiGetVariable ( MEMORY_OVERWRITE_REQUEST_VARIABLE_NAME, &gEfiMemoryOverwriteControlDataGuid, &MorControlPtr, &VariableSize ); DEBUG ((DEBUG_INFO, "MorControl - 0x%x (%r)\n", MorControl, Status)); if (MOR_CLEAR_MEMORY_VALUE (MorControl)) { FspmUpd->FspmConfig.CleanMemory = (BOOLEAN)(MorControl & MOR_CLEAR_MEMORY_BIT_MASK); } return EFI_SUCCESS; }
1,196
545
<gh_stars>100-1000 /* Copyright (c) 2011, Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the 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 Intel Corporation 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. ******************************************************************************** * Content : Eigen bindings to Intel(R) MKL PARDISO ******************************************************************************** */ #ifndef EIGEN_PARDISOSUPPORT_H #define EIGEN_PARDISOSUPPORT_H namespace Eigen { template<typename _MatrixType> class PardisoLU; template<typename _MatrixType, int Options=Upper> class PardisoLLT; template<typename _MatrixType, int Options=Upper> class PardisoLDLT; namespace internal { template<typename Index> struct pardiso_run_selector { static Index run( _MKL_DSS_HANDLE_t pt, Index maxfct, Index mnum, Index type, Index phase, Index n, void *a, Index *ia, Index *ja, Index *perm, Index nrhs, Index *iparm, Index msglvl, void *b, void *x) { Index error = 0; ::pardiso(pt, &maxfct, &mnum, &type, &phase, &n, a, ia, ja, perm, &nrhs, iparm, &msglvl, b, x, &error); return error; } }; template<> struct pardiso_run_selector<long long int> { typedef long long int Index; static Index run( _MKL_DSS_HANDLE_t pt, Index maxfct, Index mnum, Index type, Index phase, Index n, void *a, Index *ia, Index *ja, Index *perm, Index nrhs, Index *iparm, Index msglvl, void *b, void *x) { Index error = 0; ::pardiso_64(pt, &maxfct, &mnum, &type, &phase, &n, a, ia, ja, perm, &nrhs, iparm, &msglvl, b, x, &error); return error; } }; template<class Pardiso> struct pardiso_traits; template<typename _MatrixType> struct pardiso_traits< PardisoLU<_MatrixType> > { typedef _MatrixType MatrixType; typedef typename _MatrixType::Scalar Scalar; typedef typename _MatrixType::RealScalar RealScalar; typedef typename _MatrixType::Index Index; }; template<typename _MatrixType, int Options> struct pardiso_traits< PardisoLLT<_MatrixType, Options> > { typedef _MatrixType MatrixType; typedef typename _MatrixType::Scalar Scalar; typedef typename _MatrixType::RealScalar RealScalar; typedef typename _MatrixType::Index Index; }; template<typename _MatrixType, int Options> struct pardiso_traits< PardisoLDLT<_MatrixType, Options> > { typedef _MatrixType MatrixType; typedef typename _MatrixType::Scalar Scalar; typedef typename _MatrixType::RealScalar RealScalar; typedef typename _MatrixType::Index Index; }; } template<class Derived> class PardisoImpl { typedef internal::pardiso_traits<Derived> Traits; public: typedef typename Traits::MatrixType MatrixType; typedef typename Traits::Scalar Scalar; typedef typename Traits::RealScalar RealScalar; typedef typename Traits::Index Index; typedef SparseMatrix<Scalar,RowMajor,Index> SparseMatrixType; typedef Matrix<Scalar,Dynamic,1> VectorType; typedef Matrix<Index, 1, MatrixType::ColsAtCompileTime> IntRowVectorType; typedef Matrix<Index, MatrixType::RowsAtCompileTime, 1> IntColVectorType; typedef Array<Index,64,1,DontAlign> ParameterType; enum { ScalarIsComplex = NumTraits<Scalar>::IsComplex }; PardisoImpl() { eigen_assert((sizeof(Index) >= sizeof(_INTEGER_t) && sizeof(Index) <= 8) && "Non-supported index type"); m_iparm.setZero(); m_msglvl = 0; // No output m_initialized = false; } ~PardisoImpl() { pardisoRelease(); } inline Index cols() const { return m_size; } inline Index rows() const { return m_size; } /** \brief Reports whether previous computation was successful. * * \returns \c Success if computation was succesful, * \c NumericalIssue if the matrix appears to be negative. */ ComputationInfo info() const { eigen_assert(m_initialized && "Decomposition is not initialized."); return m_info; } /** \warning for advanced usage only. * \returns a reference to the parameter array controlling PARDISO. * See the PARDISO manual to know how to use it. */ ParameterType& pardisoParameterArray() { return m_iparm; } /** Performs a symbolic decomposition on the sparcity of \a matrix. * * This function is particularly useful when solving for several problems having the same structure. * * \sa factorize() */ Derived& analyzePattern(const MatrixType& matrix); /** Performs a numeric decomposition of \a matrix * * The given matrix must has the same sparcity than the matrix on which the symbolic decomposition has been performed. * * \sa analyzePattern() */ Derived& factorize(const MatrixType& matrix); Derived& compute(const MatrixType& matrix); /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A. * * \sa compute() */ template<typename Rhs> inline const internal::solve_retval<PardisoImpl, Rhs> solve(const MatrixBase<Rhs>& b) const { eigen_assert(m_initialized && "Pardiso solver is not initialized."); eigen_assert(rows()==b.rows() && "PardisoImpl::solve(): invalid number of rows of the right hand side matrix b"); return internal::solve_retval<PardisoImpl, Rhs>(*this, b.derived()); } /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A. * * \sa compute() */ template<typename Rhs> inline const internal::sparse_solve_retval<PardisoImpl, Rhs> solve(const SparseMatrixBase<Rhs>& b) const { eigen_assert(m_initialized && "Pardiso solver is not initialized."); eigen_assert(rows()==b.rows() && "PardisoImpl::solve(): invalid number of rows of the right hand side matrix b"); return internal::sparse_solve_retval<PardisoImpl, Rhs>(*this, b.derived()); } Derived& derived() { return *static_cast<Derived*>(this); } const Derived& derived() const { return *static_cast<const Derived*>(this); } template<typename BDerived, typename XDerived> bool _solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived>& x) const; /** \internal */ template<typename Rhs, typename DestScalar, int DestOptions, typename DestIndex> void _solve_sparse(const Rhs& b, SparseMatrix<DestScalar,DestOptions,DestIndex> &dest) const { eigen_assert(m_size==b.rows()); // we process the sparse rhs per block of NbColsAtOnce columns temporarily stored into a dense matrix. static const int NbColsAtOnce = 4; int rhsCols = b.cols(); int size = b.rows(); // Pardiso cannot solve in-place, // so we need two temporaries Eigen::Matrix<DestScalar,Dynamic,Dynamic,ColMajor> tmp_rhs(size,rhsCols); Eigen::Matrix<DestScalar,Dynamic,Dynamic,ColMajor> tmp_res(size,rhsCols); for(int k=0; k<rhsCols; k+=NbColsAtOnce) { int actualCols = std::min<int>(rhsCols-k, NbColsAtOnce); tmp_rhs.leftCols(actualCols) = b.middleCols(k,actualCols); tmp_res.leftCols(actualCols) = derived().solve(tmp_rhs.leftCols(actualCols)); dest.middleCols(k,actualCols) = tmp_res.leftCols(actualCols).sparseView(); } } protected: void pardisoRelease() { if(m_initialized) // Factorization ran at least once { internal::pardiso_run_selector<Index>::run(m_pt, 1, 1, m_type, -1, m_size, 0, 0, 0, m_perm.data(), 0, m_iparm.data(), m_msglvl, 0, 0); } } void pardisoInit(int type) { m_type = type; bool symmetric = abs(m_type) < 10; m_iparm[0] = 1; // No solver default m_iparm[1] = 3; // use Metis for the ordering m_iparm[2] = 1; // Numbers of processors, value of OMP_NUM_THREADS m_iparm[3] = 0; // No iterative-direct algorithm m_iparm[4] = 0; // No user fill-in reducing permutation m_iparm[5] = 0; // Write solution into x m_iparm[6] = 0; // Not in use m_iparm[7] = 2; // Max numbers of iterative refinement steps m_iparm[8] = 0; // Not in use m_iparm[9] = 13; // Perturb the pivot elements with 1E-13 m_iparm[10] = symmetric ? 0 : 1; // Use nonsymmetric permutation and scaling MPS m_iparm[11] = 0; // Not in use m_iparm[12] = symmetric ? 0 : 1; // Maximum weighted matching algorithm is switched-off (default for symmetric). // Try m_iparm[12] = 1 in case of inappropriate accuracy m_iparm[13] = 0; // Output: Number of perturbed pivots m_iparm[14] = 0; // Not in use m_iparm[15] = 0; // Not in use m_iparm[16] = 0; // Not in use m_iparm[17] = -1; // Output: Number of nonzeros in the factor LU m_iparm[18] = -1; // Output: Mflops for LU factorization m_iparm[19] = 0; // Output: Numbers of CG Iterations m_iparm[20] = 0; // 1x1 pivoting m_iparm[26] = 0; // No matrix checker m_iparm[27] = (sizeof(RealScalar) == 4) ? 1 : 0; m_iparm[34] = 1; // C indexing m_iparm[59] = 1; // Automatic switch between In-Core and Out-of-Core modes } protected: // cached data to reduce reallocation, etc. void manageErrorCode(Index error) { switch(error) { case 0: m_info = Success; break; case -4: case -7: m_info = NumericalIssue; break; default: m_info = InvalidInput; } } mutable SparseMatrixType m_matrix; ComputationInfo m_info; bool m_initialized, m_analysisIsOk, m_factorizationIsOk; Index m_type, m_msglvl; mutable void *m_pt[64]; mutable ParameterType m_iparm; mutable IntColVectorType m_perm; Index m_size; private: PardisoImpl(PardisoImpl &) {} }; template<class Derived> Derived& PardisoImpl<Derived>::compute(const MatrixType& a) { m_size = a.rows(); eigen_assert(a.rows() == a.cols()); pardisoRelease(); memset(m_pt, 0, sizeof(m_pt)); m_perm.setZero(m_size); derived().getMatrix(a); Index error; error = internal::pardiso_run_selector<Index>::run(m_pt, 1, 1, m_type, 12, m_size, m_matrix.valuePtr(), m_matrix.outerIndexPtr(), m_matrix.innerIndexPtr(), m_perm.data(), 0, m_iparm.data(), m_msglvl, NULL, NULL); manageErrorCode(error); m_analysisIsOk = true; m_factorizationIsOk = true; m_initialized = true; return derived(); } template<class Derived> Derived& PardisoImpl<Derived>::analyzePattern(const MatrixType& a) { m_size = a.rows(); eigen_assert(m_size == a.cols()); pardisoRelease(); memset(m_pt, 0, sizeof(m_pt)); m_perm.setZero(m_size); derived().getMatrix(a); Index error; error = internal::pardiso_run_selector<Index>::run(m_pt, 1, 1, m_type, 11, m_size, m_matrix.valuePtr(), m_matrix.outerIndexPtr(), m_matrix.innerIndexPtr(), m_perm.data(), 0, m_iparm.data(), m_msglvl, NULL, NULL); manageErrorCode(error); m_analysisIsOk = true; m_factorizationIsOk = false; m_initialized = true; return derived(); } template<class Derived> Derived& PardisoImpl<Derived>::factorize(const MatrixType& a) { eigen_assert(m_analysisIsOk && "You must first call analyzePattern()"); eigen_assert(m_size == a.rows() && m_size == a.cols()); derived().getMatrix(a); Index error; error = internal::pardiso_run_selector<Index>::run(m_pt, 1, 1, m_type, 22, m_size, m_matrix.valuePtr(), m_matrix.outerIndexPtr(), m_matrix.innerIndexPtr(), m_perm.data(), 0, m_iparm.data(), m_msglvl, NULL, NULL); manageErrorCode(error); m_factorizationIsOk = true; return derived(); } template<class Base> template<typename BDerived,typename XDerived> bool PardisoImpl<Base>::_solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived>& x) const { if(m_iparm[0] == 0) // Factorization was not computed return false; //Index n = m_matrix.rows(); Index nrhs = Index(b.cols()); eigen_assert(m_size==b.rows()); eigen_assert(((MatrixBase<BDerived>::Flags & RowMajorBit) == 0 || nrhs == 1) && "Row-major right hand sides are not supported"); eigen_assert(((MatrixBase<XDerived>::Flags & RowMajorBit) == 0 || nrhs == 1) && "Row-major matrices of unknowns are not supported"); eigen_assert(((nrhs == 1) || b.outerStride() == b.rows())); // switch (transposed) { // case SvNoTrans : m_iparm[11] = 0 ; break; // case SvTranspose : m_iparm[11] = 2 ; break; // case SvAdjoint : m_iparm[11] = 1 ; break; // default: // //std::cerr << "Eigen: transposition option \"" << transposed << "\" not supported by the PARDISO backend\n"; // m_iparm[11] = 0; // } Scalar* rhs_ptr = const_cast<Scalar*>(b.derived().data()); Matrix<Scalar,Dynamic,Dynamic,ColMajor> tmp; // Pardiso cannot solve in-place if(rhs_ptr == x.derived().data()) { tmp = b; rhs_ptr = tmp.data(); } Index error; error = internal::pardiso_run_selector<Index>::run(m_pt, 1, 1, m_type, 33, m_size, m_matrix.valuePtr(), m_matrix.outerIndexPtr(), m_matrix.innerIndexPtr(), m_perm.data(), nrhs, m_iparm.data(), m_msglvl, rhs_ptr, x.derived().data()); return error==0; } /** \ingroup PardisoSupport_Module * \class PardisoLU * \brief A sparse direct LU factorization and solver based on the PARDISO library * * This class allows to solve for A.X = B sparse linear problems via a direct LU factorization * using the Intel MKL PARDISO library. The sparse matrix A must be squared and invertible. * The vectors or matrices X and B can be either dense or sparse. * * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> * * \sa \ref TutorialSparseDirectSolvers */ template<typename MatrixType> class PardisoLU : public PardisoImpl< PardisoLU<MatrixType> > { protected: typedef PardisoImpl< PardisoLU<MatrixType> > Base; typedef typename Base::Scalar Scalar; typedef typename Base::RealScalar RealScalar; using Base::pardisoInit; using Base::m_matrix; friend class PardisoImpl< PardisoLU<MatrixType> >; public: using Base::compute; using Base::solve; PardisoLU() : Base() { pardisoInit(Base::ScalarIsComplex ? 13 : 11); } PardisoLU(const MatrixType& matrix) : Base() { pardisoInit(Base::ScalarIsComplex ? 13 : 11); compute(matrix); } protected: void getMatrix(const MatrixType& matrix) { m_matrix = matrix; } private: PardisoLU(PardisoLU& ) {} }; /** \ingroup PardisoSupport_Module * \class PardisoLLT * \brief A sparse direct Cholesky (LLT) factorization and solver based on the PARDISO library * * This class allows to solve for A.X = B sparse linear problems via a LL^T Cholesky factorization * using the Intel MKL PARDISO library. The sparse matrix A must be selfajoint and positive definite. * The vectors or matrices X and B can be either dense or sparse. * * \tparam MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> * \tparam UpLo can be any bitwise combination of Upper, Lower. The default is Upper, meaning only the upper triangular part has to be used. * Upper|Lower can be used to tell both triangular parts can be used as input. * * \sa \ref TutorialSparseDirectSolvers */ template<typename MatrixType, int _UpLo> class PardisoLLT : public PardisoImpl< PardisoLLT<MatrixType,_UpLo> > { protected: typedef PardisoImpl< PardisoLLT<MatrixType,_UpLo> > Base; typedef typename Base::Scalar Scalar; typedef typename Base::Index Index; typedef typename Base::RealScalar RealScalar; using Base::pardisoInit; using Base::m_matrix; friend class PardisoImpl< PardisoLLT<MatrixType,_UpLo> >; public: enum { UpLo = _UpLo }; using Base::compute; using Base::solve; PardisoLLT() : Base() { pardisoInit(Base::ScalarIsComplex ? 4 : 2); } PardisoLLT(const MatrixType& matrix) : Base() { pardisoInit(Base::ScalarIsComplex ? 4 : 2); compute(matrix); } protected: void getMatrix(const MatrixType& matrix) { // PARDISO supports only upper, row-major matrices PermutationMatrix<Dynamic,Dynamic,Index> p_null; m_matrix.resize(matrix.rows(), matrix.cols()); m_matrix.template selfadjointView<Upper>() = matrix.template selfadjointView<UpLo>().twistedBy(p_null); } private: PardisoLLT(PardisoLLT& ) {} }; /** \ingroup PardisoSupport_Module * \class PardisoLDLT * \brief A sparse direct Cholesky (LDLT) factorization and solver based on the PARDISO library * * This class allows to solve for A.X = B sparse linear problems via a LDL^T Cholesky factorization * using the Intel MKL PARDISO library. The sparse matrix A is assumed to be selfajoint and positive definite. * For complex matrices, A can also be symmetric only, see the \a Options template parameter. * The vectors or matrices X and B can be either dense or sparse. * * \tparam MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> * \tparam Options can be any bitwise combination of Upper, Lower, and Symmetric. The default is Upper, meaning only the upper triangular part has to be used. * Symmetric can be used for symmetric, non-selfadjoint complex matrices, the default being to assume a selfadjoint matrix. * Upper|Lower can be used to tell both triangular parts can be used as input. * * \sa \ref TutorialSparseDirectSolvers */ template<typename MatrixType, int Options> class PardisoLDLT : public PardisoImpl< PardisoLDLT<MatrixType,Options> > { protected: typedef PardisoImpl< PardisoLDLT<MatrixType,Options> > Base; typedef typename Base::Scalar Scalar; typedef typename Base::Index Index; typedef typename Base::RealScalar RealScalar; using Base::pardisoInit; using Base::m_matrix; friend class PardisoImpl< PardisoLDLT<MatrixType,Options> >; public: using Base::compute; using Base::solve; enum { UpLo = Options&(Upper|Lower) }; PardisoLDLT() : Base() { pardisoInit(Base::ScalarIsComplex ? ( bool(Options&Symmetric) ? 6 : -4 ) : -2); } PardisoLDLT(const MatrixType& matrix) : Base() { pardisoInit(Base::ScalarIsComplex ? ( bool(Options&Symmetric) ? 6 : -4 ) : -2); compute(matrix); } void getMatrix(const MatrixType& matrix) { // PARDISO supports only upper, row-major matrices PermutationMatrix<Dynamic,Dynamic,Index> p_null; m_matrix.resize(matrix.rows(), matrix.cols()); m_matrix.template selfadjointView<Upper>() = matrix.template selfadjointView<UpLo>().twistedBy(p_null); } private: PardisoLDLT(PardisoLDLT& ) {} }; namespace internal { template<typename _Derived, typename Rhs> struct solve_retval<PardisoImpl<_Derived>, Rhs> : solve_retval_base<PardisoImpl<_Derived>, Rhs> { typedef PardisoImpl<_Derived> Dec; EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs) template<typename Dest> void evalTo(Dest& dst) const { dec()._solve(rhs(),dst); } }; template<typename Derived, typename Rhs> struct sparse_solve_retval<PardisoImpl<Derived>, Rhs> : sparse_solve_retval_base<PardisoImpl<Derived>, Rhs> { typedef PardisoImpl<Derived> Dec; EIGEN_MAKE_SPARSE_SOLVE_HELPERS(Dec,Rhs) template<typename Dest> void evalTo(Dest& dst) const { dec().derived()._solve_sparse(rhs(),dst); } }; } // end namespace internal } // end namespace Eigen #endif // EIGEN_PARDISOSUPPORT_H
8,710
2,113
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "gui/containers/guiTabBookCtrl.h" #include "console/engineAPI.h" #include "gui/core/guiCanvas.h" #include "gui/editor/guiEditCtrl.h" #include "gui/controls/guiPopUpCtrl.h" #include "gui/core/guiDefaultControlRender.h" #include "gfx/gfxDrawUtil.h" IMPLEMENT_CONOBJECT( GuiTabBookCtrl ); ConsoleDocClass( GuiTabBookCtrl, "@brief A container \n\n" "@tsexample\n" "// Create \n" "@endtsexample\n\n" "@note Only GuiTabPageCtrls must be added to GuiTabBookCtrls. If an object of a different " "class is added to the control, it will be reassigned to either the active page or the " "tab book's parent.\n\n" "@see GuiTabPageCtrl\n" "@ingroup GuiContainers" ); ImplementEnumType( GuiTabPosition, "Where the control should put the tab headers for selecting individual pages.\n\n" "@ingroup GuiContainers" ) { GuiTabBookCtrl::AlignTop, "Top", "Tab headers on top edge." }, { GuiTabBookCtrl::AlignBottom,"Bottom", "Tab headers on bottom edge." } EndImplementEnumType; IMPLEMENT_CALLBACK( GuiTabBookCtrl, onTabSelected, void, ( const String& text, U32 index ), ( text, index ), "Called when a new tab page is selected.\n\n" "@param text Text of the page header for the tab that is being selected.\n" "@param index Index of the tab page being selected." ); IMPLEMENT_CALLBACK( GuiTabBookCtrl, onTabRightClick, void, ( const String& text, U32 index ), ( text, index ), "Called when the user right-clicks on a tab page header.\n\n" "@param text Text of the page header for the tab that is being selected.\n" "@param index Index of the tab page being selected." ); //----------------------------------------------------------------------------- GuiTabBookCtrl::GuiTabBookCtrl() { VECTOR_SET_ASSOCIATION( mPages ); mTabHeight = 24; mTabPosition = AlignTop; mActivePage = NULL; mHoverTab = NULL; mHasTexture = false; mBitmapBounds = NULL; setExtent( 400, 300 ); mPageRect = RectI(0,0,0,0); mTabRect = RectI(0,0,0,0); mFrontTabPadding = 0; mPages.reserve(12); mTabMargin = 7; mMinTabWidth = 64; mIsContainer = true; mSelectedPageNum = -1; mDefaultPageNum = -1; mAllowReorder = false; mDraggingTab = false; mDraggingTabRect = false; mIsFirstWake = true; } //----------------------------------------------------------------------------- void GuiTabBookCtrl::initPersistFields() { addGroup( "TabBook" ); addField( "tabPosition", TYPEID< TabPosition >(), Offset( mTabPosition, GuiTabBookCtrl ), "Where to place the tab page headers." ); addField( "tabMargin", TypeS32, Offset( mTabMargin, GuiTabBookCtrl ), "Spacing to put between individual tab page headers." ); addField( "minTabWidth", TypeS32, Offset( mMinTabWidth, GuiTabBookCtrl ), "Minimum width allocated to a tab page header." ); addField( "tabHeight", TypeS32, Offset( mTabHeight, GuiTabBookCtrl ), "Height of tab page headers." ); addField( "allowReorder", TypeBool, Offset( mAllowReorder, GuiTabBookCtrl ), "Whether reordering tabs with the mouse is allowed." ); addField( "defaultPage", TypeS32, Offset( mDefaultPageNum, GuiTabBookCtrl ), "Index of page to select on first onWake() call (-1 to disable)." ); addProtectedField( "selectedPage", TypeS32, Offset( mSelectedPageNum, GuiTabBookCtrl ), &_setSelectedPage, &defaultProtectedGetFn, "Index of currently selected page." ); addField( "frontTabPadding", TypeS32, Offset( mFrontTabPadding, GuiTabBookCtrl ), "X offset of first tab page header." ); endGroup( "TabBook" ); Parent::initPersistFields(); } //----------------------------------------------------------------------------- void GuiTabBookCtrl::onChildRemoved( GuiControl* child ) { for (S32 i = 0; i < mPages.size(); i++ ) { GuiTabPageCtrl* tab = mPages[i].Page; if( tab == child ) { mPages.erase( i ); break; } } // Calculate Page Information calculatePageTabs(); // Active Index. mSelectedPageNum = getMin( mSelectedPageNum, mPages.size() - 1 ); if ( mSelectedPageNum != -1 ) { // Select Page. selectPage( mSelectedPageNum ); } } //----------------------------------------------------------------------------- void GuiTabBookCtrl::onChildAdded( GuiControl *child ) { GuiTabPageCtrl *page = dynamic_cast<GuiTabPageCtrl*>(child); if( !page ) { Con::warnf("GuiTabBookCtrl::onChildAdded - attempting to add NON GuiTabPageCtrl as child page"); SimObject *simObj = reinterpret_cast<SimObject*>(child); removeObject( simObj ); if( mActivePage ) { mActivePage->addObject( simObj ); } else { Con::warnf("GuiTabBookCtrl::onChildAdded - unable to find active page to reassign ownership of new child control to, placing on parent"); GuiControl *rent = getParent(); if( rent ) rent->addObject( simObj ); } return; } TabHeaderInfo newPage; newPage.Page = page; newPage.TabRow = -1; newPage.TabColumn = -1; mPages.push_back( newPage ); // Calculate Page Information calculatePageTabs(); if( page->getFitBook() ) fitPage( page ); // Select this Page selectPage( page ); } //----------------------------------------------------------------------------- bool GuiTabBookCtrl::reOrder(SimObject* obj, SimObject* target) { if ( !Parent::reOrder(obj, target) ) return false; // Store the Selected Page. GuiTabPageCtrl *selectedPage = NULL; if ( mSelectedPageNum != -1 ) selectedPage = mPages[mSelectedPageNum].Page; // Determine the Target Page Index. S32 targetIndex = -1; for( S32 i = 0; i < mPages.size(); i++ ) { const TabHeaderInfo &info = mPages[i]; if ( info.Page == target ) { targetIndex = i; break; } } if ( targetIndex == -1 ) { return false; } for( S32 i = 0; i < mPages.size(); i++ ) { const TabHeaderInfo &info = mPages[i]; if ( info.Page == obj ) { // Store Info. TabHeaderInfo objPage = info; // Remove. mPages.erase( i ); // Insert. mPages.insert( targetIndex, objPage ); break; } } // Update Tabs. calculatePageTabs(); // Reselect Page. selectPage( selectedPage ); return true; } //----------------------------------------------------------------------------- bool GuiTabBookCtrl::acceptsAsChild( SimObject* object ) const { // Only accept tab pages. return ( dynamic_cast< GuiTabPageCtrl* >( object ) != NULL ); } //----------------------------------------------------------------------------- bool GuiTabBookCtrl::onWake() { if (! Parent::onWake()) return false; mHasTexture = mProfile->constructBitmapArray() > 0; if( mHasTexture ) { mBitmapBounds = mProfile->mBitmapArrayRects.address(); mTabHeight = mBitmapBounds[TabSelected].extent.y; } calculatePageTabs(); if( mIsFirstWake ) { // Awaken all pages, visible or not. We need to do this so // any pages that make use of a language table for their label // are correctly initialized. for ( U32 i = 0; i < mPages.size(); ++i) { if ( !mPages[i].Page->isAwake() ) { mPages[i].Page->awaken(); } } if( mDefaultPageNum >= 0 && mDefaultPageNum < mPages.size() ) selectPage( mDefaultPageNum ); mIsFirstWake = false; } return true; } //----------------------------------------------------------------------------- void GuiTabBookCtrl::addNewPage( const char* text ) { GuiTabPageCtrl* page = new GuiTabPageCtrl(); if( text ) page->setText( text ); page->registerObject(); addObject( page ); } //----------------------------------------------------------------------------- bool GuiTabBookCtrl::resize(const Point2I &newPosition, const Point2I &newExtent) { bool result = Parent::resize( newPosition, newExtent ); calculatePageTabs(); return result; } //----------------------------------------------------------------------------- void GuiTabBookCtrl::childResized(GuiControl *child) { Parent::childResized( child ); //child->resize( mPageRect.point, mPageRect.extent ); } //----------------------------------------------------------------------------- void GuiTabBookCtrl::onMouseDown(const GuiEvent &event) { mDraggingTab = false; mDraggingTabRect = false; Point2I localMouse = globalToLocalCoord( event.mousePoint ); if( mTabRect.pointInRect( localMouse ) ) { GuiTabPageCtrl *tab = findHitTab( localMouse ); if( tab != NULL ) { selectPage( tab ); mDraggingTab = mAllowReorder; } else { mDraggingTabRect = true; } } } //----------------------------------------------------------------------------- void GuiTabBookCtrl::onMouseUp(const GuiEvent &event) { Parent::onMouseUp( event ); mDraggingTab = false; mDraggingTabRect = false; } //----------------------------------------------------------------------------- void GuiTabBookCtrl::onMouseDragged(const GuiEvent &event) { Parent::onMouseDragged( event ); if ( !mDraggingTab ) return; GuiTabPageCtrl *selectedPage = NULL; if ( mSelectedPageNum != -1 ) selectedPage = mPages[mSelectedPageNum].Page; if ( !selectedPage ) return; Point2I localMouse = globalToLocalCoord( event.mousePoint ); if( mTabRect.pointInRect( localMouse ) ) { GuiTabPageCtrl *tab = findHitTab( localMouse ); if( tab != NULL && tab != selectedPage ) { S32 targetIndex = -1; for( S32 i = 0; i < mPages.size(); i++ ) { if( mPages[i].Page == tab ) { targetIndex = i; break; } } if ( targetIndex > mSelectedPageNum ) { reOrder( tab, selectedPage ); } else { reOrder( selectedPage, tab ); } } } } //----------------------------------------------------------------------------- void GuiTabBookCtrl::onMouseMove(const GuiEvent &event) { Point2I localMouse = globalToLocalCoord( event.mousePoint ); if( mTabRect.pointInRect( localMouse ) ) { GuiTabPageCtrl *tab = findHitTab( localMouse ); if( tab != NULL && mHoverTab != tab ) mHoverTab = tab; else if ( !tab ) mHoverTab = NULL; } Parent::onMouseMove( event ); } //----------------------------------------------------------------------------- void GuiTabBookCtrl::onMouseLeave( const GuiEvent &event ) { Parent::onMouseLeave( event ); mHoverTab = NULL; } //----------------------------------------------------------------------------- bool GuiTabBookCtrl::onMouseDownEditor(const GuiEvent &event, Point2I offset) { bool handled = false; Point2I localMouse = globalToLocalCoord( event.mousePoint ); if( mTabRect.pointInRect( localMouse ) ) { GuiTabPageCtrl *tab = findHitTab( localMouse ); if( tab != NULL ) { selectPage( tab ); handled = true; } } #ifdef TORQUE_TOOLS // This shouldn't be called if it's not design time, but check just incase if ( GuiControl::smDesignTime ) { // If we clicked in the editor and our addset is the tab book // ctrl, select the child ctrl so we can edit it's properties GuiEditCtrl* edit = GuiControl::smEditorHandle; if( edit && ( edit->getAddSet() == this ) && mActivePage != NULL ) edit->select( mActivePage ); } #endif // Return whether we handled this or not. return handled; } //----------------------------------------------------------------------------- void GuiTabBookCtrl::onRightMouseUp( const GuiEvent& event ) { Point2I localMouse = globalToLocalCoord( event.mousePoint ); if( mTabRect.pointInRect( localMouse ) ) { GuiTabPageCtrl* tab = findHitTab( localMouse ); if( tab ) onTabRightClick_callback( tab->getText(), getPageNum( tab ) ); } } //----------------------------------------------------------------------------- void GuiTabBookCtrl::onRender(Point2I offset, const RectI &updateRect) { RectI tabRect = mTabRect; tabRect.point += offset; RectI pageRect = mPageRect; pageRect.point += offset; // We're so nice we'll store the old modulation before we clear it for our rendering! :) ColorI oldModulation; GFX->getDrawUtil()->getBitmapModulation( &oldModulation ); // Wipe it out GFX->getDrawUtil()->clearBitmapModulation(); Parent::onRender(offset, updateRect); // Clip to tab area RectI savedClipRect = GFX->getClipRect(); RectI clippedTabRect = tabRect; clippedTabRect.intersect( savedClipRect ); GFX->setClipRect( clippedTabRect ); // Render our tabs renderTabs( offset, tabRect ); // Restore Rect. GFX->setClipRect( savedClipRect ); // Restore old modulation GFX->getDrawUtil()->setBitmapModulation( oldModulation ); } //----------------------------------------------------------------------------- void GuiTabBookCtrl::renderTabs( const Point2I &offset, const RectI &tabRect ) { // If the tab size is zero, don't render tabs, // assuming it's a tab-less book if( mPages.empty() || mTabHeight <= 0 ) return; for( S32 i = 0; i < mPages.size(); i++ ) { const TabHeaderInfo &currentTabInfo = mPages[i]; RectI tabBounds = mPages[i].TabRect; tabBounds.point += offset; GuiTabPageCtrl *tab = mPages[i].Page; if( tab != NULL ) renderTab( tabBounds, tab ); // If we're on the last tab, draw the nice end piece if( i + 1 == mPages.size() ) { Point2I tabEndPoint = Point2I(currentTabInfo.TabRect.point.x + currentTabInfo.TabRect.extent.x + offset.x, currentTabInfo.TabRect.point.y + offset.y); Point2I tabEndExtent = Point2I((tabRect.point.x + tabRect.extent.x) - tabEndPoint.x, currentTabInfo.TabRect.extent.y); RectI tabEndRect = RectI(tabEndPoint,tabEndExtent); GFX->setClipRect( tabEndRect ); // As it turns out the last tab can be outside the viewport in which // case trying to render causes a DX assert. Could be better if // setClipRect returned a bool. if ( GFX->getViewport().isValidRect() ) renderFixedBitmapBordersFilled( tabEndRect, TabEnds + 1, mProfile ); } } } //----------------------------------------------------------------------------- void GuiTabBookCtrl::renderTab(const RectI& tabRect, GuiTabPageCtrl *tab) { StringTableEntry text = tab->getText(); ColorI oldColor; GFX->getDrawUtil()->getBitmapModulation( &oldColor ); // Is this a skinned control? if( mHasTexture && mProfile->mBitmapArrayRects.size() >= 9 ) { S32 indexMultiplier = 1; switch( mTabPosition ) { case AlignTop: case AlignBottom: if ( mActivePage == tab ) indexMultiplier += TabSelected; else if( mHoverTab == tab ) indexMultiplier += TabHover; else indexMultiplier += TabNormal; break; } renderFixedBitmapBordersFilled( tabRect, indexMultiplier, mProfile ); } else { // If this isn't a skinned control or the bitmap is simply missing, handle it WELL if ( mActivePage == tab ) GFX->getDrawUtil()->drawRectFill(tabRect, mProfile->mFillColor); else if( mHoverTab == tab ) GFX->getDrawUtil()->drawRectFill(tabRect, mProfile->mFillColorHL); else GFX->getDrawUtil()->drawRectFill(tabRect, mProfile->mFillColorNA); } GFX->getDrawUtil()->setBitmapModulation(mProfile->mFontColor); switch( mTabPosition ) { case AlignTop: case AlignBottom: renderJustifiedText( tabRect.point, tabRect.extent, text); break; } GFX->getDrawUtil()->setBitmapModulation( oldColor); } //----------------------------------------------------------------------------- void GuiTabBookCtrl::setUpdate() { Parent::setUpdate(); setUpdateRegion(Point2I(0,0), getExtent()); calculatePageTabs(); } //----------------------------------------------------------------------------- S32 GuiTabBookCtrl::calculatePageTabWidth( GuiTabPageCtrl *page ) { if( !page ) return mMinTabWidth; const char* text = page->getText(); if( !text || dStrlen(text) == 0 || mProfile == NULL || mProfile->mFont == NULL ) return mMinTabWidth; GFont *font = mProfile->mFont; return font->getStrNWidth( text, dStrlen(text) ); } //----------------------------------------------------------------------------- const RectI GuiTabBookCtrl::getClientRect() { if( !mProfile || mProfile->mBitmapArrayRects.size() < NumBitmaps ) return Parent::getClientRect(); return mPageRect; } //----------------------------------------------------------------------------- void GuiTabBookCtrl::calculatePageTabs() { // Short Circuit. // // If the tab size is zero, don't render tabs, // assuming it's a tab-less book if( mPages.empty() || mTabHeight <= 0 ) { mPageRect.point.x = 0; mPageRect.point.y = 0; mPageRect.extent.x = getWidth(); mPageRect.extent.y = getHeight(); return; } S32 currRow = 0; S32 currColumn = 0; S32 currX = mFrontTabPadding; S32 maxWidth = 0; for( S32 i = 0; i < mPages.size(); i++ ) { // Fetch Tab Width S32 tabWidth = calculatePageTabWidth( mPages[i].Page ) + ( mTabMargin * 2 ); tabWidth = getMax( tabWidth, mMinTabWidth ); TabHeaderInfo &info = mPages[i]; switch( mTabPosition ) { case AlignTop: case AlignBottom: // If we're going to go outside our bounds // with this tab move it down a row if( currX + tabWidth > getWidth() ) { // Calculate and Advance State. maxWidth = getMax( tabWidth, maxWidth ); balanceRow( currRow, currX ); info.TabRow = ++currRow; // Reset Necessaries info.TabColumn = currColumn = maxWidth = currX = 0; } else { info.TabRow = currRow; info.TabColumn = currColumn++; } // Calculate Tabs Bounding Rect info.TabRect.point.x = currX; info.TabRect.extent.x = tabWidth; info.TabRect.extent.y = mTabHeight; // Adjust Y Point based on alignment if( mTabPosition == AlignTop ) info.TabRect.point.y = ( info.TabRow * mTabHeight ); else info.TabRect.point.y = getHeight() - ( ( 1 + info.TabRow ) * mTabHeight ); currX += tabWidth; break; }; } currRow++; currColumn++; Point2I localPoint = getExtent(); // Calculate switch( mTabPosition ) { case AlignTop: localPoint.y -= getTop(); mTabRect.point.x = 0; mTabRect.extent.x = localPoint.x; mTabRect.point.y = 0; mTabRect.extent.y = currRow * mTabHeight; mPageRect.point.x = 0; mPageRect.point.y = mTabRect.extent.y; mPageRect.extent.x = mTabRect.extent.x; mPageRect.extent.y = getHeight() - mTabRect.extent.y; break; case AlignBottom: mTabRect.point.x = 0; mTabRect.extent.x = localPoint.x; mTabRect.extent.y = currRow * mTabHeight; mTabRect.point.y = getHeight() - mTabRect.extent.y; mPageRect.point.x = 0; mPageRect.point.y = 0; mPageRect.extent.x = mTabRect.extent.x; mPageRect.extent.y = localPoint.y - mTabRect.extent.y; break; } } //----------------------------------------------------------------------------- void GuiTabBookCtrl::balanceRow( S32 row, S32 totalTabWidth ) { // Short Circuit. // // If the tab size is zero, don't render tabs, // and assume it's a tab-less tab-book - JDD if( mPages.empty() || mTabHeight <= 0 ) return; Vector<TabHeaderInfo*> rowTemp; rowTemp.clear(); for( S32 i = 0; i < mPages.size(); i++ ) { TabHeaderInfo &info = mPages[i]; if(info.TabRow == row ) rowTemp.push_back( &mPages[i] ); } if( rowTemp.empty() ) return; // Balance the tabs across the remaining space S32 spaceToDivide = getWidth() - totalTabWidth; S32 pointDelta = 0; for( S32 i = 0; i < rowTemp.size(); i++ ) { TabHeaderInfo &info = *rowTemp[i]; S32 extraSpace = (S32)spaceToDivide / ( rowTemp.size() ); info.TabRect.extent.x += extraSpace; info.TabRect.point.x += pointDelta; pointDelta += extraSpace; } } //----------------------------------------------------------------------------- GuiTabPageCtrl *GuiTabBookCtrl::findHitTab( const GuiEvent &event ) { return findHitTab( event.mousePoint ); } //----------------------------------------------------------------------------- GuiTabPageCtrl *GuiTabBookCtrl::findHitTab( Point2I hitPoint ) { // Short Circuit. // // If the tab size is zero, don't render tabs, // and assume it's a tab-less tab-book - JDD if( mPages.empty() || mTabHeight <= 0 ) return NULL; for( S32 i = 0; i < mPages.size(); i++ ) { if( mPages[i].TabRect.pointInRect( hitPoint ) ) return mPages[i].Page; } return NULL; } //----------------------------------------------------------------------------- void GuiTabBookCtrl::selectPage( S32 index ) { if( mPages.empty() || index < 0 ) return; if( mPages.size() <= index ) index = mPages.size() - 1; // Select the page selectPage( mPages[ index ].Page ); } //----------------------------------------------------------------------------- void GuiTabBookCtrl::selectPage( GuiTabPageCtrl *page ) { // Return if already selected. if( mSelectedPageNum >= 0 && mSelectedPageNum < mPages.size() && mPages[ mSelectedPageNum ].Page == page ) return; mSelectedPageNum = -1; Vector<TabHeaderInfo>::iterator i = mPages.begin(); for( S32 index = 0; i != mPages.end() ; i++, index++ ) { GuiTabPageCtrl *tab = (*i).Page; if( page == tab ) { mActivePage = tab; tab->setVisible( true ); mSelectedPageNum = index; // Notify User onTabSelected_callback( tab->getText(), index ); } else tab->setVisible( false ); } setUpdateLayout( updateSelf ); } //----------------------------------------------------------------------------- bool GuiTabBookCtrl::_setSelectedPage( void *object, const char *index, const char *data ) { GuiTabBookCtrl* book = reinterpret_cast< GuiTabBookCtrl* >( object ); book->selectPage( dAtoi( data ) ); return false; } //----------------------------------------------------------------------------- bool GuiTabBookCtrl::onKeyDown(const GuiEvent &event) { // Tab = Next Page // Ctrl-Tab = Previous Page if( 0 && event.keyCode == KEY_TAB ) { if( event.modifier & SI_PRIMARY_CTRL ) selectPrevPage(); else selectNextPage(); return true; } return Parent::onKeyDown( event ); } //----------------------------------------------------------------------------- void GuiTabBookCtrl::selectNextPage() { if( mPages.empty() ) return; if( mActivePage == NULL ) mActivePage = mPages[0].Page; S32 nI = 0; for( ; nI < mPages.size(); nI++ ) { GuiTabPageCtrl *tab = mPages[ nI ].Page; if( tab == mActivePage ) { if( nI == ( mPages.size() - 1 ) ) selectPage( 0 ); else if ( nI + 1 <= ( mPages.size() - 1 ) ) selectPage( nI + 1 ); else selectPage( 0 ); return; } } } //----------------------------------------------------------------------------- void GuiTabBookCtrl::selectPrevPage() { if( mPages.empty() ) return; if( mActivePage == NULL ) mActivePage = mPages[0].Page; S32 nI = 0; for( ; nI < mPages.size(); nI++ ) { GuiTabPageCtrl *tab = mPages[ nI ].Page; if( tab == mActivePage ) { if( nI == 0 ) selectPage( mPages.size() - 1 ); else selectPage( nI - 1 ); return; } } } //----------------------------------------------------------------------------- void GuiTabBookCtrl::fitPage( GuiTabPageCtrl* page ) { page->resize( mPageRect.point, mPageRect.extent ); } //----------------------------------------------------------------------------- S32 GuiTabBookCtrl::getPageNum( GuiTabPageCtrl* page ) const { const U32 numPages = mPages.size(); for( U32 i = 0; i < numPages; ++ i ) if( mPages[ i ].Page == page ) return i; return -1; } //============================================================================= // API. //============================================================================= // MARK: ---- API ---- //----------------------------------------------------------------------------- DefineEngineMethod( GuiTabBookCtrl, addPage, void, ( const char* title ), ( "" ), "Add a new tab page to the control.\n\n" "@param title Title text for the tab page header." ) { object->addNewPage( title ); } //----------------------------------------------------------------------------- DefineEngineMethod( GuiTabBookCtrl, selectPage, void, ( S32 index ),, "Set the selected tab page.\n\n" "@param index Index of the tab page." ) { object->selectPage( index ); } //----------------------------------------------------------------------------- DefineEngineMethod( GuiTabBookCtrl, getSelectedPage, S32, (),, "Get the index of the currently selected tab page.\n\n" "@return Index of the selected tab page or -1 if no tab page is selected." ) { return object->getSelectedPageNum(); }
10,294
2,753
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: <NAME> */ #include <benchmark/benchmark.h> #include "shogun/features/DotFeatures_benchmark.h" #include "shogun/features/hashed/HashedDocDotFeatures.h" #include "shogun/lib/NGramTokenizer.h" #include "shogun/mathematics/RandomNamespace.h" #include "shogun/mathematics/UniformIntDistribution.h" #include <random> #include <vector> namespace shogun { class HDFixture : public benchmark::Fixture { public: void SetUp(const ::benchmark::State& st) { std::random_device rd; std::mt19937_64 prng(rd()); UniformIntDistribution<char> uniform_int_dist('A', 'Z'); string_list.reserve(num_strings); for (index_t i=0; i<num_strings; i++) { string_list.push_back(SGVector<char>(max_str_length)); for (index_t j=0; j<max_str_length; j++) string_list[i].vector[j] = (char) uniform_int_dist(prng); } auto string_feats = std::make_shared<StringFeatures<char>>(string_list, RAWBYTE); auto tzer = std::make_shared<NGramTokenizer>(3); f = std::make_shared<HashedDocDotFeatures>(st.range(0), string_feats, tzer); w = SGVector<float64_t>(f->get_dim_feature_space()); w.range_fill(17.0); } void TearDown(const ::benchmark::State&) { f.reset(); } std::shared_ptr<HashedDocDotFeatures> f; static constexpr index_t num_strings = 5000; static constexpr index_t max_str_length = 10000; std::vector<SGVector<char>> string_list; SGVector<float64_t> w; }; #define ADD_HASHEDDOC_ARGS(WHAT) \ WHAT->Arg(8)->Arg(10)->Arg(12)->Arg(16)->Arg(20)->Unit(benchmark::kMillisecond) ADD_HASHEDDOC_ARGS(DOTFEATURES_BENCHMARK_DENSEDOT(HDFixture, HashedDocDotFeatures_DenseDot)); ADD_HASHEDDOC_ARGS(DOTFEATURES_BENCHMARK_ADDDENSE(HDFixture, HashedDocDotFeatures_AddDense)); }
721
513
#ifdef AM_EXPORT struct am_export_flags { bool export_windows; bool export_windows64; bool export_mac; bool export_mac_app_store; bool export_linux; bool export_html; bool export_ios_xcode_proj; bool export_android_studio_proj; bool export_data_pak; bool debug; bool recurse; bool allfiles;; bool zipdir; const char *outdir; const char *outpath; am_export_flags() { export_windows = false; export_windows64 = false; export_mac = false; export_mac_app_store = false; export_linux = false; export_html = false; export_ios_xcode_proj = false; export_android_studio_proj = false; export_data_pak = false; debug = false; recurse = false; allfiles = false; zipdir = true; outdir = NULL; outpath = NULL; } int num_platforms() { return (export_windows ? 1 : 0) + (export_windows64 ? 1 : 0) + (export_mac ? 1 : 0) + (export_mac_app_store ? 1 : 0) + (export_linux ? 1 : 0) + (export_html ? 1 : 0) + (export_ios_xcode_proj ? 1 : 0) + (export_android_studio_proj ? 1 : 0) + (export_data_pak ? 1 : 0); } }; bool am_build_exports(am_export_flags *flags); #endif
667
6,958
// // SoftmaxGrad.hpp // MNN // // Created by MNN on 2019/04/22. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef SoftmaxGrad_hpp #define SoftmaxGrad_hpp #include "OpGrad.hpp" #endif /* SoftmaxGrad_hpp */
88
595
{ "shader-toy.textures": { "0": "file://C:/Users/keijiro/Documents/ShaderSketches/Images/Adventure.png" } }
59
2,109
<filename>tests/test_utils.py import pytest from click.testing import CliRunner from jupyter_book.cli.main import init as myst_init from jupyter_book.utils import init_myst_file def test_myst_init(cli: CliRunner, temp_with_override): """Test adding myst metadata to text files.""" path = temp_with_override.joinpath("tmp.md").absolute() text = "TEST" with open(path, "w") as ff: ff.write(text) init_myst_file(path, kernel="python3") # Make sure it runs properly. Default kernel should be python3 new_text = path.read_text(encoding="utf8") assert "format_name: myst" in new_text assert "TEST" == new_text.strip().split("\n")[-1] assert "name: python3" in new_text # Make sure the CLI works too with pytest.warns(None) as records: result = cli.invoke(myst_init, f"{path} --kernel python3".split()) # old versions of jupytext give: UserWarning: myst-parse failed unexpectedly assert len(records) == 0, records assert result.exit_code == 0 # Non-existent kernel with pytest.raises(Exception) as err: init_myst_file(path, kernel="blah") assert "Did not find kernel: blah" in str(err) # Missing file with pytest.raises(Exception) as err: init_myst_file(path.joinpath("MISSING"), kernel="python3") assert "Markdown file not found:" in str(err)
510
629
/* * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "base.h" namespace cherrypi { using namespace cherrypi::buildtypes; using namespace cherrypi::autobuild; class ABBOhydracheese : public ABBOBase { public: using ABBOBase::ABBOBase; virtual void preBuild2(autobuild::BuildState& bst) override { postBlackboardKey(Blackboard::kMinScoutFrameKey, 0); postBlackboardKey("TacticsAttack", armySupply >= 12 || myMutaliskCount); } virtual void buildStep2(autobuild::BuildState& bst) override { preferSafeExpansions = false; autoUpgrade = autoExpand = currentFrame > 24 * 60 * 12; bst.autoBuildRefineries = true; buildN(Zerg_Drone, 75); build(Zerg_Mutalisk); buildN(Zerg_Hydralisk, 2 * myMutaliskCount); buildN(Zerg_Drone, 45); takeNBases(bst, 5); buildN(Zerg_Hydralisk, 18); buildN(Zerg_Mutalisk, 12); buildN(Zerg_Drone, 30); takeNBases(bst, 4); buildN(Zerg_Guardian, 4); buildN(Zerg_Mutalisk, 12); upgrade(Pneumatized_Carapace); buildN(Zerg_Hydralisk, 18); buildN(Zerg_Guardian, 2); takeNBases(bst, 3); buildN(Zerg_Hive, 1); buildN(Zerg_Hydralisk, 9); buildN(Zerg_Drone, 24); upgrade(Muscular_Augments); buildN(Zerg_Hydralisk, 6); upgrade(Grooved_Spines); buildN(Zerg_Hatchery, 3); buildN(Zerg_Mutalisk, 12); buildN(Zerg_Extractor, bases); buildN(Zerg_Spire, 1); buildN(Zerg_Hydralisk, 3); if (has(bst, Zerg_Spire)) { buildN(Zerg_Mutalisk, 12); } buildN(Zerg_Drone, armySupply); if (!has(bst, Zerg_Hive)) { buildN(Zerg_Lair, 1); } buildN(Zerg_Drone, 18); buildSunkens(bst, 1); buildN(Zerg_Hydralisk_Den, 1); takeNBases(bst, 2); buildN(Zerg_Extractor, 1); buildN(Zerg_Spawning_Pool, 1); buildN(Zerg_Drone, 12); } }; REGISTER_SUBCLASS_3(ABBOBase, ABBOhydracheese, UpcId, State*, Module*); } // namespace cherrypi
886
446
<reponame>apivovarov/neo-ai-dlr package com.amazon.dlr.examples.classification.dlr; import android.app.Activity; import java.io.IOException; /** This is DLRKerasMobileNetV2. */ public class DLRKerasMobileNetV2 extends DLRModelBase { /** MobileNet requires additional normalization of the used input. */ private static final float IMAGE_MEAN = 127.5f; private static final float IMAGE_STD = 127.5f; protected static long[] inShape = new long[] {1,3,224,224}; public DLRKerasMobileNetV2(Activity activity) throws IOException { super(activity); } @Override protected long[] getInShape() { return inShape; } @Override protected boolean isNCHW() { return true; } @Override protected String getModelPath() { return "dlr_keras_mobilenet_v2"; } @Override protected void addPixelValue(int pixelValue) { imgData.putFloat((((pixelValue >> 16) & 0xFF) - IMAGE_MEAN) / IMAGE_STD); imgData.putFloat((((pixelValue >> 8) & 0xFF) - IMAGE_MEAN) / IMAGE_STD); imgData.putFloat(((pixelValue & 0xFF) - IMAGE_MEAN) / IMAGE_STD); } @Override protected String getLabelPath() { return "labels1000.txt"; } }
497
431
<reponame>FauxFaux/PuTTYTray<gh_stars>100-1000 /* * sizetip.c - resize tips for PuTTY(tel) terminal window. */ #include <stdio.h> #include <stdlib.h> #include <tchar.h> #include "putty.h" static ATOM tip_class = 0; static HFONT tip_font; static COLORREF tip_bg; static COLORREF tip_text; static LRESULT CALLBACK SizeTipWndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam) { switch (nMsg) { case WM_ERASEBKGND: return TRUE; case WM_PAINT: { HBRUSH hbr; HGDIOBJ holdbr; RECT cr; int wtlen; LPTSTR wt; HDC hdc; PAINTSTRUCT ps; hdc = BeginPaint(hWnd, &ps); SelectObject(hdc, tip_font); SelectObject(hdc, GetStockObject(BLACK_PEN)); hbr = CreateSolidBrush(tip_bg); holdbr = SelectObject(hdc, hbr); GetClientRect(hWnd, &cr); Rectangle(hdc, cr.left, cr.top, cr.right, cr.bottom); wtlen = GetWindowTextLength(hWnd); wt = (LPTSTR)snewn(wtlen + 1, TCHAR); GetWindowText(hWnd, wt, wtlen + 1); SetTextColor(hdc, tip_text); SetBkColor(hdc, tip_bg); TextOut(hdc, cr.left + 3, cr.top + 3, wt, wtlen); sfree(wt); SelectObject(hdc, holdbr); DeleteObject(hbr); EndPaint(hWnd, &ps); } return 0; case WM_NCHITTEST: return HTTRANSPARENT; case WM_DESTROY: DeleteObject(tip_font); tip_font = NULL; break; case WM_SETTEXT: { LPCTSTR str = (LPCTSTR)lParam; SIZE sz; HDC hdc = CreateCompatibleDC(NULL); SelectObject(hdc, tip_font); GetTextExtentPoint32(hdc, str, _tcslen(str), &sz); SetWindowPos(hWnd, NULL, 0, 0, sz.cx + 6, sz.cy + 6, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE); InvalidateRect(hWnd, NULL, FALSE); DeleteDC(hdc); } break; } return DefWindowProc(hWnd, nMsg, wParam, lParam); } static HWND tip_wnd = NULL; static int tip_enabled = 0; void UpdateSizeTip(HWND src, int cx, int cy) { TCHAR str[32]; if (!tip_enabled) return; if (!tip_wnd) { NONCLIENTMETRICS nci; /* First make sure the window class is registered */ if (!tip_class) { WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = SizeTipWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hinst; wc.hIcon = NULL; wc.hCursor = NULL; wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = "SizeTipClass"; tip_class = RegisterClass(&wc); } #if 0 /* Default values based on Windows Standard color scheme */ tip_font = GetStockObject(SYSTEM_FONT); tip_bg = RGB(255, 255, 225); tip_text = RGB(0, 0, 0); #endif /* Prepare other GDI objects and drawing info */ tip_bg = GetSysColor(COLOR_INFOBK); tip_text = GetSysColor(COLOR_INFOTEXT); memset(&nci, 0, sizeof(NONCLIENTMETRICS)); nci.cbSize = sizeof(NONCLIENTMETRICS); SystemParametersInfo( SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &nci, 0); tip_font = CreateFontIndirect(&nci.lfStatusFont); } /* Generate the tip text */ sprintf(str, "%dx%d", cx, cy); if (!tip_wnd) { HDC hdc; SIZE sz; RECT wr; int ix, iy; /* calculate the tip's size */ hdc = CreateCompatibleDC(NULL); GetTextExtentPoint32(hdc, str, _tcslen(str), &sz); DeleteDC(hdc); GetWindowRect(src, &wr); ix = wr.left; if (ix < 16) ix = 16; iy = wr.top - sz.cy; if (iy < 16) iy = 16; /* Create the tip window */ tip_wnd = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TOPMOST, MAKEINTRESOURCE(tip_class), str, WS_POPUP, ix, iy, sz.cx, sz.cy, NULL, NULL, hinst, NULL); ShowWindow(tip_wnd, SW_SHOWNOACTIVATE); } else { /* Tip already exists, just set the text */ SetWindowText(tip_wnd, str); } } void EnableSizeTip(int bEnable) { if (tip_wnd && !bEnable) { DestroyWindow(tip_wnd); tip_wnd = NULL; } tip_enabled = bEnable; }
2,338
1,014
<filename>Database/Funds/USD Cautious Allocation.json<gh_stars>1000+ { "0P00006HY5.SI": { "short_name": "GrowthPath Today", "long_name": "UOB GrowthPath Portfolios - UOB GrowthPath Today", "currency": "SGD", "summary": "The objective of GrowthPath Today is to provide income and short-term capital appreciation for investors planning to begin to withdraw portions of their investment in the near future.", "manager_name": "Not Disclosed", "manager_bio": "", "category": "USD Cautious Allocation", "family": "UOB Asset Management Ltd", "exchange": "SES", "market": "sg_market", "total_assets": 6307838 }, "0P0000ZQ7M.F": { "short_name": "Nuveen Global Investers Fund Pl", "long_name": "Nuveen Global Investers Fund Plc - NWQ Flexible Income Fund Class A Accumulating Euro", "currency": "EUR", "summary": "The investment objective of the Nuveen NWQ Flexible Income Fund is to seek to provide current income and capital appreciation.", "manager_name": "<NAME>", "manager_bio": "Prior to joining NWQ in 2006, Ms. Budiman was Portfolio Manager for China Life Insurance Company, Ltd. in Taiwan. Prior to the fixed income portfolio management position, Ms. Budiman was a currency exchange sales associate at Fleet National Bank in Singapore covering Asian , Euro, UK and other major currencies. Ms. Budiman graduated from the University of British Columbia with a Bachelor of Commerce degree in Finance.", "category": "USD Cautious Allocation", "family": "Nuveen Fund Advisors, LLC.", "exchange": "FRA", "market": "dr_market", "total_assets": null } }
635
6,958
<reponame>JujuDel/MNN // // PoolBufExecution.cpp // MNN // // Created by MNN on 2019/02/28. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef MNN_OPENCL_BUFFER_CLOSED #include "backend/opencl/execution/buffer/PoolBufExecution.hpp" #include "core/Macro.h" #include "core/TensorUtils.hpp" #include "backend/opencl/core/OpenCLBackend.hpp" namespace MNN { namespace OpenCL { PoolBufExecution::PoolBufExecution(const std::vector<Tensor *> &inputs, const MNN::Op *op, Backend *backend) : Execution(backend) { mOpenCLBackend = static_cast<OpenCLBackend *>(backend); mPoolParams = op->main_as_Pool(); mPoolType = mPoolParams->type(); mStrides[0] = mPoolParams->strideY(); mStrides[1] = mPoolParams->strideX(); mKernels[0] = mPoolParams->kernelY(); mKernels[1] = mPoolParams->kernelX(); mPaddings[0] = mPoolParams->padY() * 2; mPaddings[1] = mPoolParams->padX() * 2; mPadType = mPoolParams->padType(); if (mPadType == PoolPadType_VALID) { mPaddings[0] = 0; mPaddings[1] = 0; } } ErrorCode PoolBufExecution::onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) { #ifdef LOG_VERBOSE MNN_PRINT("start PoolBufExecution onResize !\n"); #endif auto input = inputs[0]; auto output = outputs[0]; if (mPoolParams->isGlobal()) { std::vector<int> inputShape = tensorShapeFormat(inputs[0]); mKernels = {inputShape.at(1), inputShape.at(2)}; mStrides = {inputShape.at(1), inputShape.at(2)}; mPaddings = {0, 0}; } if (mPadType == PoolPadType_SAME) { int padNeededHeight = std::max(0, (output->height() - 1) * mStrides[0] + mKernels[0] - input->height()); int padNeededWidth = std::max(0, (output->width() - 1) * mStrides[1] + mKernels[1] - input->width()); mPaddings[0] = padNeededHeight; mPaddings[1] = padNeededWidth; } MNN_ASSERT(mDilations[0] == 1 && mDilations[1] == 1); std::vector<int> inputShape = tensorShapeFormat(input); std::vector<int> outputShape = tensorShapeFormat(output); const int batch = outputShape.at(0); const int outputHeight = outputShape.at(1); const int outputWidth = outputShape.at(2); const int channels = outputShape.at(3); const int inputHeight = inputShape.at(1); const int inputWidth = inputShape.at(2); int channelBlocks = (channels + 3) / 4; std::set<std::string> buildOptions; std::string kernelName = "pooling"; auto runtime = mOpenCLBackend->getOpenCLRuntime(); if (mPoolType == PoolType_AVEPOOL) { buildOptions.emplace("-DPOOL_AVG"); } mKernel = runtime->buildKernel("pooling_buf", kernelName, buildOptions); mMaxWorkGroupSize = static_cast<uint32_t>(runtime->getMaxWorkGroupSize(mKernel)); mGlobalWorkSize = { static_cast<uint32_t>(outputWidth), static_cast<uint32_t>(batch * outputHeight), static_cast<uint32_t>(channelBlocks), }; int inputImageShape[2] = {inputHeight, inputWidth}; int outputImageShape[2] = {outputHeight, outputWidth}; int paddingShape[2] = {mPaddings[0] / 2, mPaddings[1] / 2}; int strideShape[2] = {mStrides[0], mStrides[1]}; int kernelShape[2] = {mKernels[0], mKernels[1]}; uint32_t idx = 0; mKernel.setArg(idx++, mGlobalWorkSize[0]); mKernel.setArg(idx++, mGlobalWorkSize[1]); mKernel.setArg(idx++, mGlobalWorkSize[2]); mKernel.setArg(idx++, openCLBuffer(input)); mKernel.setArg(idx++, sizeof(inputImageShape), inputImageShape); mKernel.setArg(idx++, sizeof(outputImageShape), outputImageShape); mKernel.setArg(idx++, sizeof(paddingShape), paddingShape); mKernel.setArg(idx++, sizeof(strideShape), strideShape); mKernel.setArg(idx++, sizeof(kernelShape), kernelShape); mKernel.setArg(idx++, openCLBuffer(output)); mKernel.setArg(idx++, channelBlocks); std::string kernelNameTune = "pooling_buf"; mLocalWorkSize = localWS3DDefault(mGlobalWorkSize, mMaxWorkGroupSize, mOpenCLBackend->getOpenCLRuntime(), kernelNameTune, mKernel).first; #ifdef LOG_VERBOSE MNN_PRINT("end PoolBufExecution onResize !\n"); #endif return NO_ERROR; } ErrorCode PoolBufExecution::onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) { #ifdef LOG_VERBOSE MNN_PRINT("start PoolBufExecution onExecute !\n"); #endif #ifdef ENABLE_OPENCL_TIME_PROFILER cl::Event event; run3DKernelDefault(mKernel, mGlobalWorkSize, mLocalWorkSize, mOpenCLBackend->getOpenCLRuntime(), &event); int costTime = (int)mOpenCLBackend->getOpenCLRuntime()->getCostTime(&event); MNN_PRINT("kernel cost:%d us Pooling\n",costTime); #else run3DKernelDefault(mKernel, mGlobalWorkSize, mLocalWorkSize, mOpenCLBackend->getOpenCLRuntime()); #endif #ifdef LOG_VERBOSE MNN_PRINT("end PoolBufExecution onExecute !\n"); #endif return NO_ERROR; } OpenCLCreatorRegister<TypedCreator<PoolBufExecution>> __PoolBuf_op(OpType_Pooling, BUFFER); } // namespace OpenCL } // namespace MNN #endif /* MNN_OPENCL_BUFFER_CLOSED */
2,293
567
<gh_stars>100-1000 // // Copyright 2020 BigQuery Utils // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "token.h" namespace bigquery::utils::zetasql_helper { absl::Status Tokenize(const std::string &query, std::vector<zetasql::ParseToken>& parse_tokens) { auto resume_location = zetasql::ParseResumeLocation::FromString(query); auto options = zetasql::ParseTokenOptions(); ZETASQL_RETURN_IF_ERROR(GetParseTokens(options, &resume_location, &parse_tokens)); return absl::OkStatus(); } // Serialize the ZetaSQL token's kind into its proto. It is used by the `serialize_token` // method. ParseTokenProto_Kind serialize_token_kind(const zetasql::ParseToken::Kind kind) { using zetasql::ParseToken; using bigquery::utils::zetasql_helper::ParseTokenProto_Kind; switch (kind) { case ParseToken::Kind::KEYWORD: return ParseTokenProto_Kind::ParseTokenProto_Kind_KEYWORD; case ParseToken::IDENTIFIER: return ParseTokenProto_Kind::ParseTokenProto_Kind_IDENTIFIER; case ParseToken::IDENTIFIER_OR_KEYWORD: return ParseTokenProto_Kind::ParseTokenProto_Kind_IDENTIFIER_OR_KEYWORD; case ParseToken::VALUE: return ParseTokenProto_Kind::ParseTokenProto_Kind_VALUE; case ParseToken::COMMENT: return ParseTokenProto_Kind::ParseTokenProto_Kind_COMMENT; case ParseToken::END_OF_INPUT: return ParseTokenProto_Kind::ParseTokenProto_Kind_END_OF_INPUT; } } ParseTokenProto serialize_token(const zetasql::ParseToken &token) { ParseTokenProto token_proto; token_proto.set_image(std::string(token.GetImage())); auto kind = serialize_token_kind(token.kind()); token_proto.set_kind(kind); auto location_range_proto = token.GetLocationRange().ToProto(); if (location_range_proto.ok()) { auto range_proto = new zetasql::ParseLocationRangeProto(location_range_proto.value()); token_proto.set_allocated_parse_location_range(range_proto); } return token_proto; } } //bigquery::utils::zetasql_helper
878
7,258
<reponame>maksimbo1/modin<filename>modin/core/storage_formats/pandas/utils.py # Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team 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. """Contains utility functions for frame partitioning.""" import numpy as np import pandas def get_default_chunksize(length, num_splits): """ Get the most equal chunksize possible based on length and number of splits. Parameters ---------- length : int The length to split (number of rows/columns). num_splits : int The number of splits. Returns ------- int Computed chunksize. """ return ( length // num_splits if length % num_splits == 0 else length // num_splits + 1 ) def compute_chunksize(df, num_splits, default_block_size=32, axis=None): """ Compute the number of rows and/or columns to include in each partition. Parameters ---------- df : pandas.DataFrame DataFrame to split. num_splits : int Number of splits to separate the DataFrame into. default_block_size : int, default: 32 Minimum number of rows/columns in a single split. axis : int, optional Axis to split across. If not specified - split accros both axes. Returns ------- int if axis was specified, tuple of ints otherwise, If axis is 1 or 0, returns an integer number of rows/columns to split the DataFrame. If axis is None, returns a tuple containing both. """ if axis == 0 or axis is None: row_chunksize = get_default_chunksize(len(df.index), num_splits) # Take the min of the default and the memory-usage chunksize first to avoid a # large amount of small partitions. row_chunksize = max(1, row_chunksize, default_block_size) if axis == 0: return row_chunksize # We always execute this because we can only get here if axis is 1 or None. col_chunksize = get_default_chunksize(len(df.columns), num_splits) # Take the min of the default and the memory-usage chunksize first to avoid a # large amount of small partitions. col_chunksize = max(1, col_chunksize, default_block_size) if axis == 1: return col_chunksize return row_chunksize, col_chunksize def split_result_of_axis_func_pandas(axis, num_splits, result, length_list=None): """ Split pandas DataFrame evenly based on the provided number of splits. Parameters ---------- axis : {0, 1} Axis to split across. 0 means index axis when 1 means column axis. num_splits : int Number of splits to separate the DataFrame into. This parameter is ignored if `length_list` is specified. result : pandas.DataFrame DataFrame to split. length_list : list of ints, optional List of slice lengths to split DataFrame into. This is used to return the DataFrame to its original partitioning schema. Returns ------- list of pandas.DataFrames Splitted dataframe represented by list of frames. """ if length_list is not None: length_list.insert(0, 0) sums = np.cumsum(length_list) if axis == 0 or isinstance(result, pandas.Series): return [result.iloc[sums[i] : sums[i + 1]] for i in range(len(sums) - 1)] else: return [result.iloc[:, sums[i] : sums[i + 1]] for i in range(len(sums) - 1)] if num_splits == 1: return [result] # We do this to restore block partitioning chunksize = compute_chunksize(result, num_splits, axis=axis) if axis == 0 or isinstance(result, pandas.Series): return [ result.iloc[chunksize * i : chunksize * (i + 1)] for i in range(num_splits) ] else: return [ result.iloc[:, chunksize * i : chunksize * (i + 1)] for i in range(num_splits) ] def length_fn_pandas(df): """ Compute number of rows of passed `pandas.DataFrame`. Parameters ---------- df : pandas.DataFrame Returns ------- int """ assert isinstance(df, pandas.DataFrame) return len(df) if len(df) > 0 else 0 def width_fn_pandas(df): """ Compute number of columns of passed `pandas.DataFrame`. Parameters ---------- df : pandas.DataFrame Returns ------- int """ assert isinstance(df, pandas.DataFrame) return len(df.columns) if len(df.columns) > 0 else 0
1,873
997
<reponame>indutny/webpack-common-shake { "name": "webpack-common-shake", "version": "2.0.2", "description": "CommonJS Tree Shake Plugin for Webpack", "main": "lib/shake.js", "scripts": { "test": "mocha --reporter=spec test/*-test.js && npm run lint", "lint": "eslint lib/*.js lib/**/*.js test/*js" }, "repository": { "type": "git", "url": "git+https://github.com/indutny/webpack-common-shake.git" }, "files": [ "lib" ], "keywords": [ "webpack", "commonjs", "tree", "shake" ], "author": "<NAME> <<EMAIL>> (http://darksi.de/)", "license": "MIT", "bugs": { "url": "https://github.com/indutny/webpack-common-shake/issues" }, "homepage": "https://github.com/indutny/webpack-common-shake#readme", "dependencies": { "acorn": "^5.2.1", "common-shake": "^2.1.0", "webpack": "^4.16.5", "webpack-sources": "^1.1.0" }, "devDependencies": { "eslint": "^4.11.0", "memory-fs": "^0.4.1", "mocha": "^3.5.3" } }
474
601
<gh_stars>100-1000 { "combine_datasets": ["clevr_question"], "combine_datasets_val": ["clevr_question"], "clevr_img_path": "", "clevr_ann_path": "CLEVR-Humans/", "split_qa_heads": 1, "clevr_variant": "humans", "no_detection": 1, "do_qa": 1 }
134
360
<gh_stars>100-1000 package uk.co.flax.luwak.benchmark; /* * Copyright (c) 2015 Lemur Consulting 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. */ import java.util.Collection; import java.util.Set; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import uk.co.flax.luwak.DocumentMatches; import uk.co.flax.luwak.Matches; import uk.co.flax.luwak.QueryMatch; public class ValidatorResults<T extends QueryMatch> extends BenchmarkResults<T> { private int correctMatches; private int total; private Multimap<String, T> missingMatches = HashMultimap.create(); private Multimap<String, T> extraMatches = HashMultimap.create(); public void add(Matches<T> matches, String docId, Set<T> expectedMatches) { super.add(matches); total++; DocumentMatches<T> docMatches = matches.getMatches(docId); if (docMatches == null) { missingMatches.putAll(docId, expectedMatches); return; } Set<T> actualMatches = Sets.newHashSet(docMatches); Sets.SetView<T> extras = Sets.difference(expectedMatches, actualMatches); Sets.SetView<T> missing = Sets.difference(actualMatches, expectedMatches); if (extras.isEmpty() && missing.isEmpty()) correctMatches++; else { missingMatches.putAll(docMatches.getDocId(), missing); extraMatches.putAll(docMatches.getDocId(), extras); } } public int getCorrectMatchCount() { return correctMatches; } public int getTotalMatchCount() { return total; } public Collection<String> getBadDocuments() { return Sets.union(missingMatches.keySet(), extraMatches.keySet()); } public Collection<T> getMissingMatches(String docId) { return missingMatches.get(docId); } public Collection<T> getExtraMatches(String docId) { return extraMatches.get(docId); } }
942
1,355
// Copyright (c) 2018 <NAME> // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #include "advection_solver.h" #include "pybind11_utils.h" #include <jet/advection_solver2.h> #include <jet/advection_solver3.h> namespace py = pybind11; using namespace jet; void addAdvectionSolver2(py::module& m) { py::class_<AdvectionSolver2, AdvectionSolver2Ptr>(m, "AdvectionSolver2", R"pbdoc( Abstract based class for 2-D grid-based advection solver. The implementation of this abstract base class should solve 2-D advection equation for scalar and vector fields. )pbdoc"); } void addAdvectionSolver3(py::module& m) { py::class_<AdvectionSolver3, AdvectionSolver3Ptr>(m, "AdvectionSolver3", R"pbdoc( Abstract based class for 3-D grid-based advection solver. The implementation of this abstract base class should solve 3-D advection equation for scalar and vector fields. )pbdoc"); }
454
1,444
<filename>Mage.Sets/src/mage/cards/f/Floodgate.java /* * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``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 BetaSteward_at_googlemail.com 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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of BetaSteward_at_googlemail.com. */ package mage.cards.f; import java.util.UUID; import mage.MageInt; import mage.ObjectColor; import mage.abilities.Ability; import mage.abilities.StateTriggeredAbility; import mage.abilities.common.LeavesBattlefieldTriggeredAbility; import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.DamageAllEffect; import mage.abilities.effects.common.SacrificeSourceEffect; import mage.constants.SubType; import mage.abilities.keyword.DefenderAbility; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.Zone; import mage.filter.common.FilterControlledPermanent; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.AbilityPredicate; import mage.filter.predicate.mageobject.ColorPredicate; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.permanent.Permanent; /** * * @author TheElk801 */ public final class Floodgate extends CardImpl { public Floodgate(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{U}"); this.subtype.add(SubType.WALL); this.power = new MageInt(0); this.toughness = new MageInt(5); // Defender this.addAbility(DefenderAbility.getInstance()); // When Floodgate has flying, sacrifice it. this.addAbility(new FloodgateHasFlyingStateTriggeredAbility()); // When Floodgate leaves the battlefield, it deals damage equal to half the number of Islands you control, rounded down, to each nonblue creature without flying. this.addAbility(new LeavesBattlefieldTriggeredAbility(new FloodgateDamageEffect(), false)); } private Floodgate(final Floodgate card) { super(card); } @Override public Floodgate copy() { return new Floodgate(this); } } class FloodgateHasFlyingStateTriggeredAbility extends StateTriggeredAbility { public FloodgateHasFlyingStateTriggeredAbility() { super(Zone.BATTLEFIELD, new SacrificeSourceEffect()); } public FloodgateHasFlyingStateTriggeredAbility(final FloodgateHasFlyingStateTriggeredAbility ability) { super(ability); } @Override public FloodgateHasFlyingStateTriggeredAbility copy() { return new FloodgateHasFlyingStateTriggeredAbility(this); } @Override public boolean checkTrigger(GameEvent event, Game game) { Permanent permanent = game.getPermanent(getSourceId()); if (permanent != null && permanent.getAbilities().contains(FlyingAbility.getInstance())) { return true; } return false; } @Override public String getRule() { return "When {this} has flying, sacrifice it."; } } class FloodgateDamageEffect extends OneShotEffect { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent(); private static final FilterControlledPermanent filter2 = new FilterControlledPermanent(); static { filter.add(Predicates.not(new ColorPredicate(ObjectColor.BLUE))); filter.add(Predicates.not(new AbilityPredicate(FlyingAbility.class))); filter2.add(SubType.ISLAND.getPredicate()); } public FloodgateDamageEffect() { super(Outcome.Benefit); this.staticText = "it deals damage equal to half the number of Islands you control, " + "rounded down, to each nonblue creature without flying"; } public FloodgateDamageEffect(final FloodgateDamageEffect effect) { super(effect); } @Override public FloodgateDamageEffect copy() { return new FloodgateDamageEffect(this); } @Override public boolean apply(Game game, Ability source) { int islandCount = new PermanentsOnBattlefieldCount(filter2).calculate(game, source, this); islandCount = Math.floorDiv(islandCount, 2); return new DamageAllEffect(islandCount, filter).apply(game, source); } }
1,906
480
/* * Copyright [2013-2021], Alibaba Group Holding Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.polardbx.optimizer.locality; import com.alibaba.polardbx.common.utils.Pair; import com.alibaba.polardbx.gms.locality.LocalityDesc; import com.alibaba.polardbx.gms.locality.PrimaryZoneInfo; import com.google.common.collect.Lists; import lombok.val; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * @author moyi * @since 2021/03 */ public class LocalityParserTest { @Test public void testParseLocality() { List<String> testCases = Arrays.asList( "dn=dn1", "dn=dn1,dn2" ); for (String testCase : testCases) { LocalityDesc desc = LocalityDesc.parse(testCase); Assert.assertEquals(testCase, desc.toString()); } } @Test public void testShowCreate() { LocalityDesc desc = LocalityDesc.parse("dn=dn1"); Assert.assertEquals("/* LOCALITY='dn=dn1' */", desc.showCreate()); } @Test public void testParsePrimaryZone() { // answers List<String> answer1 = IntStream.range(1, 10).mapToObj(x -> "az" + x + ":5").collect(Collectors.toList()); List<String> answer2 = Lists.reverse(IntStream.range(5, 10) .mapToObj(x -> "az" + x + ":" + x).collect(Collectors.toList())); List<Pair<String, PrimaryZoneInfo>> testCases = Arrays.asList( Pair.of("az1", PrimaryZoneInfo.build(Arrays.asList("az1:6"))), Pair.of("az1,az2", PrimaryZoneInfo.build(Arrays.asList("az1:5", "az2:5"))), Pair.of("az1,az2;az3", PrimaryZoneInfo.build(Arrays.asList("az1:6", "az2:6", "az3:5"))), Pair.of("az1,az2,az3,az4,az5,az6,az7,az8,az9", PrimaryZoneInfo.build(answer1)), Pair.of("az9;az8;az7;az6;az5", PrimaryZoneInfo.build(answer2)) ); for (val testCase : testCases) { PrimaryZoneInfo p = PrimaryZoneInfo.parse(testCase.getKey()); Assert.assertEquals(testCase.getValue(), p); Assert.assertEquals(testCase.getKey(), p.serialize()); } } }
1,135
1,499
# # cuneiform_python.py # # Example showing how to create a custom Unicode set for parsing # # Copyright <NAME>, 2021 # from typing import List, Tuple import pyparsing as pp class Cuneiform(pp.unicode_set): """Unicode set for Cuneiform Character Range""" _ranges: List[Tuple[int, ...]] = [ (0x10380, 0x103d5), (0x12000, 0x123FF), (0x12400, 0x1247F), ] # list out all valid identifier characters # print(Cuneiform.identchars) """ Simple Cuneiform Python language transformer Define Cuneiform "words" print: 𒄑𒉿𒅔𒋫 hello: 𒀄𒂖𒆷𒁎 world: 𒍟𒁎𒉿𒆷𒀳 def: 𒁴𒈫 """ # uncomment to show parse-time debugging # pp.enable_diag(pp.Diagnostics.enable_debug_on_named_expressions) # define a MINIMAL Python parser LPAR, RPAR, COLON, EQ = map(pp.Suppress, "():=") def_ = pp.Keyword("𒁴𒈫", ident_chars=Cuneiform.identbodychars).set_name("def") any_keyword = def_ ident = (~any_keyword) + pp.Word( Cuneiform.identchars, Cuneiform.identbodychars, asKeyword=True ) str_expr = pp.infix_notation( pp.QuotedString('"') | pp.common.integer, [ ("*", 2, pp.OpAssoc.LEFT), ("+", 2, pp.OpAssoc.LEFT), ], ) rvalue = pp.Forward() fn_call = (ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR)).set_name("fn_call") rvalue <<= fn_call | ident | str_expr | pp.common.number assignment_stmt = ident + EQ + rvalue stmt = pp.Group(fn_call | assignment_stmt).set_name("stmt") fn_def = pp.Group( def_ + ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR) + COLON ).set_name("fn_def") fn_body = pp.IndentedBlock(stmt).set_name("fn_body") fn_expr = pp.Group(fn_def + pp.Group(fn_body)) script = fn_expr[...] + stmt[...] # parse some Python written in Cuneiform cuneiform_hello_world = r""" 𒁴𒈫 𒀄𒂖𒆷𒁎(): 𒀁 = "𒀄𒂖𒆷𒁎, 𒍟𒁎𒉿𒆷𒀳!\n" * 3 𒄑𒉿𒅔𒋫(𒀁) 𒀄𒂖𒆷𒁎()""" script.parseString(cuneiform_hello_world).pprint(width=40) # use transform_string to convert keywords and builtins to runnable Python names_map = { "𒄑𒉿𒅔𒋫": "print", } ident.add_parse_action(lambda t: names_map.get(t[0], t[0])) def_.add_parse_action(lambda: "def") print("\nconvert Cuneiform Python to executable Python") transformed = ( # always put ident last (def_ | ident) .ignore(pp.quoted_string) .transform_string(cuneiform_hello_world) .strip() ) print( "=================\n" + cuneiform_hello_world.strip() + "\n=================\n" + transformed + "\n=================\n" ) print("# run transformed Python") exec(transformed)
1,170
381
<filename>pypy/tool/pytest/apptest.py<gh_stars>100-1000 # Collects and executes application-level tests. # # Classes which names start with "AppTest", or function which names # start with "app_test*" are not executed by the host Python, but # by an interpreted pypy object space. # # ...unless the -A option ('runappdirect') is passed. import py import sys, textwrap, types, gc from pypy.interpreter.gateway import app2interp_temp from pypy.interpreter.error import OperationError from pypy.interpreter.function import Method from pypy.tool.pytest import appsupport from pypy.tool.pytest.objspace import gettestobjspace from inspect import getmro class AppError(Exception): def __init__(self, excinfo): self.excinfo = excinfo class AppTestFunction(py.test.collect.Function): def _prunetraceback(self, traceback): return traceback def execute_appex(self, space, target, *args): self.space = space try: target(*args) except OperationError as e: if self.config.option.raise_operr: raise tb = sys.exc_info()[2] if e.match(space, space.w_KeyboardInterrupt): raise KeyboardInterrupt, KeyboardInterrupt(), tb appexcinfo = appsupport.AppExceptionInfo(space, e) if appexcinfo.traceback: raise AppError, AppError(appexcinfo), tb raise def runtest(self): target = self.obj if self.config.option.runappdirect: return target() space = gettestobjspace() filename = self._getdynfilename(target) func = app2interp_temp(target, filename=filename) print "executing", func self.execute_appex(space, func, space) def repr_failure(self, excinfo): if excinfo.errisinstance(AppError): excinfo = excinfo.value.excinfo return super(AppTestFunction, self).repr_failure(excinfo) def _getdynfilename(self, func): code = getattr(func, 'im_func', func).func_code return "[%s:%s]" % (code.co_filename, code.co_firstlineno) def track_allocations_collect(self): gc.collect() # must also invoke finalizers now; UserDelAction # would not run at all unless invoked explicitly if hasattr(self, 'space'): self.space.getexecutioncontext()._run_finalizers_now() class AppTestMethod(AppTestFunction): def setup(self): super(AppTestMethod, self).setup() instance = self.parent.obj w_instance = self.parent.w_instance space = instance.space for name in dir(instance): if name.startswith('w_'): if self.config.option.runappdirect: setattr(instance, name[2:], getattr(instance, name)) else: obj = getattr(instance, name) if isinstance(obj, types.MethodType): source = py.std.inspect.getsource(obj).lstrip() w_func = space.appexec([], textwrap.dedent(""" (): %s return %s """) % (source, name)) w_obj = Method(space, w_func, w_instance, space.w_None) else: w_obj = obj space.setattr(w_instance, space.wrap(name[2:]), w_obj) def runtest(self): target = self.obj if self.config.option.runappdirect: return target() space = target.im_self.space filename = self._getdynfilename(target) func = app2interp_temp(target.im_func, filename=filename) w_instance = self.parent.w_instance self.execute_appex(space, func, space, w_instance) class AppClassInstance(py.test.collect.Instance): Function = AppTestMethod def setup(self): super(AppClassInstance, self).setup() instance = self.obj space = instance.space w_class = self.parent.w_class if self.config.option.runappdirect: self.w_instance = instance else: self.w_instance = space.call_function(w_class) class AppClassCollector(py.test.Class): Instance = AppClassInstance def setup(self): super(AppClassCollector, self).setup() cls = self.obj # # <hack> for name in dir(cls): if name.startswith('test_'): func = getattr(cls, name, None) code = getattr(func, 'func_code', None) if code and code.co_flags & 32: raise AssertionError("unsupported: %r is a generator " "app-level test method" % (name,)) # </hack> # space = cls.space clsname = cls.__name__ if self.config.option.runappdirect: w_class = cls else: w_class = space.call_function(space.w_type, space.wrap(clsname), space.newtuple([]), space.newdict()) self.w_class = w_class
2,506
2,151
<gh_stars>1000+ // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCRIPT_PROMISE_RESOLVER_H_ #define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCRIPT_PROMISE_RESOLVER_H_ #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/dom/pausable_object.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/platform/bindings/scoped_persistent.h" #include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/heap/self_keep_alive.h" #include "third_party/blink/renderer/platform/timer.h" #include "v8/include/v8.h" namespace blink { // This class wraps v8::Promise::Resolver and provides the following // functionalities. // - A ScriptPromiseResolver retains a ScriptState. A caller // can call resolve or reject from outside of a V8 context. // - This class is an PausableObject and keeps track of the associated // ExecutionContext state. When the ExecutionContext is suspended, // resolve or reject will be delayed. When it is stopped, resolve or reject // will be ignored. class CORE_EXPORT ScriptPromiseResolver : public GarbageCollectedFinalized<ScriptPromiseResolver>, public PausableObject { USING_GARBAGE_COLLECTED_MIXIN(ScriptPromiseResolver); WTF_MAKE_NONCOPYABLE(ScriptPromiseResolver); public: static ScriptPromiseResolver* Create(ScriptState* script_state) { ScriptPromiseResolver* resolver = new ScriptPromiseResolver(script_state); resolver->PauseIfNeeded(); return resolver; } #if DCHECK_IS_ON() // Eagerly finalized so as to ensure valid access to getExecutionContext() // from the destructor's assert. EAGERLY_FINALIZE(); ~ScriptPromiseResolver() override { // This assertion fails if: // - promise() is called at least once and // - this resolver is destructed before it is resolved, rejected, // detached, the V8 isolate is terminated or the associated // ExecutionContext is stopped. DCHECK(state_ == kDetached || !is_promise_called_ || !GetScriptState()->ContextIsValid() || !GetExecutionContext() || GetExecutionContext()->IsContextDestroyed()); } #endif // Anything that can be passed to toV8 can be passed to this function. template <typename T> void Resolve(T value) { ResolveOrReject(value, kResolving); } // Anything that can be passed to toV8 can be passed to this function. template <typename T> void Reject(T value) { ResolveOrReject(value, kRejecting); } void Resolve() { Resolve(ToV8UndefinedGenerator()); } void Reject() { Reject(ToV8UndefinedGenerator()); } ScriptState* GetScriptState() { return script_state_.get(); } // Note that an empty ScriptPromise will be returned after resolve or // reject is called. ScriptPromise Promise() { #if DCHECK_IS_ON() is_promise_called_ = true; #endif return resolver_.Promise(); } ScriptState* GetScriptState() const { return script_state_.get(); } // PausableObject implementation. void Pause() override; void Unpause() override; void ContextDestroyed(ExecutionContext*) override { Detach(); } // Calling this function makes the resolver release its internal resources. // That means the associated promise will never be resolved or rejected // unless it's already been resolved or rejected. // Do not call this function unless you truly need the behavior. void Detach(); // Once this function is called this resolver stays alive while the // promise is pending and the associated ExecutionContext isn't stopped. void KeepAliveWhilePending(); void Trace(blink::Visitor*) override; protected: // You need to call suspendIfNeeded after the construction because // this is an PausableObject. explicit ScriptPromiseResolver(ScriptState*); private: typedef ScriptPromise::InternalResolver Resolver; enum ResolutionState { kPending, kResolving, kRejecting, kDetached, }; template <typename T> void ResolveOrReject(T value, ResolutionState new_state) { if (state_ != kPending || !GetScriptState()->ContextIsValid() || !GetExecutionContext() || GetExecutionContext()->IsContextDestroyed()) return; DCHECK(new_state == kResolving || new_state == kRejecting); state_ = new_state; ScriptState::Scope scope(script_state_.get()); // Calling ToV8 in a ScriptForbiddenScope will trigger a CHECK and // cause a crash. ToV8 just invokes a constructor for wrapper creation, // which is safe (no author script can be run). Adding AllowUserAgentScript // directly inside createWrapper could cause a perf impact (calling // isMainThread() every time a wrapper is created is expensive). Ideally, // resolveOrReject shouldn't be called inside a ScriptForbiddenScope. { ScriptForbiddenScope::AllowUserAgentScript allow_script; value_.Set(script_state_->GetIsolate(), ToV8(value, script_state_->GetContext()->Global(), script_state_->GetIsolate())); } if (GetExecutionContext()->IsContextPaused()) { // Retain this object until it is actually resolved or rejected. KeepAliveWhilePending(); return; } // TODO(esprehn): This is a hack, instead we should CHECK that // script is allowed, and v8 should be running the entry hooks below and // crashing if script is forbidden. We should then audit all users of // ScriptPromiseResolver and the related specs and switch to an async // resolve. // See: http://crbug.com/663476 if (ScriptForbiddenScope::IsScriptForbidden()) { // Retain this object until it is actually resolved or rejected. KeepAliveWhilePending(); timer_.StartOneShot(TimeDelta(), FROM_HERE); return; } ResolveOrRejectImmediately(); } void ResolveOrRejectImmediately(); void OnTimerFired(TimerBase*); ResolutionState state_; const scoped_refptr<ScriptState> script_state_; TaskRunnerTimer<ScriptPromiseResolver> timer_; Resolver resolver_; ScopedPersistent<v8::Value> value_; // To support keepAliveWhilePending(), this object needs to keep itself // alive while in that state. SelfKeepAlive<ScriptPromiseResolver> keep_alive_; #if DCHECK_IS_ON() // True if promise() is called. bool is_promise_called_ = false; #endif }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCRIPT_PROMISE_RESOLVER_H_
2,314
353
package org.nutz.integration.dwr; import org.directwebremoting.create.AbstractCreator; import org.directwebremoting.util.LocalUtil; import org.directwebremoting.util.Messages; import org.nutz.ioc.Ioc; import org.nutz.lang.Lang; import org.nutz.mvc.Mvcs; @SuppressWarnings("rawtypes") public class NutCreator extends AbstractCreator { private Class clazz; private String beanName; private Ioc ioc; @SuppressWarnings("unchecked") public Class getType() { if (clazz != null) return clazz; try { return getInstance().getClass(); } catch (Throwable e) { throw Lang.wrapThrow(e); } } @SuppressWarnings("unchecked") public Object getInstance() throws InstantiationException { Ioc ioc = this.ioc; if (ioc == null) ioc = Mvcs.getIoc(); if (beanName != null) return ioc.get(clazz, beanName); return ioc.get(clazz); } public void setClass(String classname) { try { this.clazz = LocalUtil.classForName(classname); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException(Messages.getString( "Creator.ClassNotFound", classname)); } } }
421
330
<reponame>krzjoa/torch #include <iostream> #define LANTERN_BUILD #include "lantern/lantern.h" #include <torch/torch.h> #include "utils.hpp" void *_lantern_nn_utils_rnn_pack_padded_sequence(void *input, void *lengths, bool batch_first, bool enforce_sorted) { LANTERN_FUNCTION_START auto out = torch::nn::utils::rnn::pack_padded_sequence( reinterpret_cast<LanternObject<torch::Tensor> *>(input)->get(), reinterpret_cast<LanternObject<torch::Tensor> *>(lengths)->get(), batch_first, enforce_sorted); return (void *)new LanternPtr<torch::nn::utils::rnn::PackedSequence>(out); LANTERN_FUNCTION_END } void *_lantern_nn_utils_rnn_pack_sequence(void *sequence, bool enforce_sorted) { LANTERN_FUNCTION_START auto out = torch::nn::utils::rnn::pack_sequence( reinterpret_cast<LanternObject<std::vector<torch::Tensor>> *>(sequence)->get(), enforce_sorted); return (void *)new LanternPtr<torch::nn::utils::rnn::PackedSequence>(out); LANTERN_FUNCTION_END } void *_lantern_nn_utils_rnn_pad_packed_sequence(void *sequence, bool batch_first, double padding_value, void *total_length) { LANTERN_FUNCTION_START auto out = torch::nn::utils::rnn::pad_packed_sequence( reinterpret_cast<LanternPtr<torch::nn::utils::rnn::PackedSequence> *>(sequence)->get(), batch_first, padding_value, reinterpret_cast<LanternObject<c10::optional<int64_t>> *>(total_length)->get()); std::vector<torch::Tensor> x; x.push_back(std::get<0>(out)); x.push_back(std::get<1>(out)); return (void *)new LanternObject<std::vector<torch::Tensor>>(x); LANTERN_FUNCTION_END } void *_lantern_nn_utils_rnn_pad_sequence(void *sequence, bool batch_first, double padding_value) { LANTERN_FUNCTION_START auto out = torch::nn::utils::rnn::pad_sequence( reinterpret_cast<LanternObject<std::vector<torch::Tensor>> *>(sequence)->get(), batch_first, padding_value); return (void *)new LanternObject<torch::Tensor>(out); LANTERN_FUNCTION_END } void *_lantern_nn_utils_rnn_PackedSequence_new(void *data, void *batch_sizes, void *sorted_indices, void *unsorted_indices) { LANTERN_FUNCTION_START auto out = torch::nn::utils::rnn::PackedSequence( reinterpret_cast<LanternObject<torch::Tensor> *>(data)->get(), reinterpret_cast<LanternObject<torch::Tensor> *>(batch_sizes)->get(), reinterpret_cast<LanternObject<torch::Tensor> *>(sorted_indices)->get(), reinterpret_cast<LanternObject<torch::Tensor> *>(unsorted_indices)->get()); return (void *)new LanternPtr<torch::nn::utils::rnn::PackedSequence>(out); LANTERN_FUNCTION_END } void *_lantern_nn_utils_PackedSequence_data(void *input) { LANTERN_FUNCTION_START auto x = reinterpret_cast<LanternPtr<torch::nn::utils::rnn::PackedSequence> *>(input)->get(); return (void *)new LanternObject<torch::Tensor>(x.data()); LANTERN_FUNCTION_END } void *_lantern_nn_utils_PackedSequence_batch_sizes(void *input) { LANTERN_FUNCTION_START auto x = reinterpret_cast<LanternPtr<torch::nn::utils::rnn::PackedSequence> *>(input)->get(); return (void *)new LanternObject<torch::Tensor>(x.batch_sizes()); LANTERN_FUNCTION_END } void *_lantern_nn_utils_PackedSequence_sorted_indices(void *input) { LANTERN_FUNCTION_START auto x = reinterpret_cast<LanternPtr<torch::nn::utils::rnn::PackedSequence> *>(input)->get(); return (void *)new LanternObject<torch::Tensor>(x.sorted_indices()); LANTERN_FUNCTION_END } void *_lantern_nn_utils_PackedSequence_unsorted_indices(void *input) { LANTERN_FUNCTION_START auto x = reinterpret_cast<LanternPtr<torch::nn::utils::rnn::PackedSequence> *>(input)->get(); return (void *)new LanternObject<torch::Tensor>(x.unsorted_indices()); LANTERN_FUNCTION_END }
1,638
362
/* * Copyright (c) 2005, The JUNG Authors * All rights reserved. * * This software is open-source under the BSD license; see either "license.txt" * or https://github.com/jrtom/jung/blob/master/LICENSE for a description. * * Created on Jul 21, 2005 */ package edu.uci.ics.jung.visualization.transform; import edu.uci.ics.jung.visualization.MultiLayerTransformer.Layer; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.LensTransformSupport; import edu.uci.ics.jung.visualization.control.ModalGraphMouse; import edu.uci.ics.jung.visualization.control.ModalLensGraphMouse; import edu.uci.ics.jung.visualization.control.TransformSupport; import edu.uci.ics.jung.visualization.layout.NetworkElementAccessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A class to make it easy to add an examining lens to a jung graph application. See * HyperbolicTransformerDemo for an example of how to use it. * * @author <NAME> */ public class LayoutLensSupport<N, E> extends AbstractLensSupport<N, E> implements LensSupport { private static final Logger log = LoggerFactory.getLogger(LayoutLensSupport.class); protected NetworkElementAccessor<N, E> pickSupport; public LayoutLensSupport(VisualizationViewer<N, E> vv) { this( vv, new HyperbolicTransformer( new Lens(vv.getModel().getLayoutSize()), vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT)), new ModalLensGraphMouse()); } public LayoutLensSupport(VisualizationViewer<N, E> vv, Lens lens) { this( vv, new HyperbolicTransformer( lens, vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT)), new ModalLensGraphMouse()); } /** * Create an instance with the specified parameters. * * @param vv the visualization viewer used for rendering * @param lensTransformer the lens transformer to use * @param lensGraphMouse the lens input handler */ public LayoutLensSupport( VisualizationViewer<N, E> vv, LensTransformer lensTransformer, ModalGraphMouse lensGraphMouse) { super(vv, lensGraphMouse); this.lensTransformer = lensTransformer; this.pickSupport = vv.getPickSupport(); } public void activate() { if (lensPaintable == null) { lensPaintable = new LensPaintable(lensTransformer); } if (lensControls == null) { lensControls = new LensControls(lensTransformer); } vv.getRenderContext().getMultiLayerTransformer().setTransformer(Layer.LAYOUT, lensTransformer); vv.prependPreRenderPaintable(lensPaintable); vv.addPostRenderPaintable(lensControls); vv.setGraphMouse(lensGraphMouse); vv.setToolTipText(instructions); vv.setTransformSupport(new LensTransformSupport<>()); vv.repaint(); } public void deactivate() { if (lensTransformer != null) { vv.removePreRenderPaintable(lensPaintable); vv.removePostRenderPaintable(lensControls); vv.getRenderContext() .getMultiLayerTransformer() .setTransformer(Layer.LAYOUT, lensTransformer.getDelegate()); } vv.setToolTipText(defaultToolTipText); vv.setGraphMouse(graphMouse); vv.setTransformSupport(new TransformSupport<>()); vv.repaint(); } }
1,209
445
#ifndef _WIN32 #include <LLDB/SBBreakpoint.h> #include <LLDB/SBCommandInterpreter.h> #include <LLDB/SBCommandReturnObject.h> #include <LLDB/SBDebugger.h> #include <LLDB/SBEvent.h> #include <LLDB/SBHostOS.h> #include <LLDB/SBListener.h> #include <LLDB/SBModuleSpec.h> #include <LLDB/SBProcess.h> #include <LLDB/SBStream.h> #include <LLDB/SBTarget.h> #include <LLDB/SBThread.h> #include <LLDB/SBValueList.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <map> #include "pd_backend.h" #include "pd_host.h" #include "pd_backend_messages.h" // static PDMessageFuncs* s_messageFuncs; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct Breakpoint { const char* filename; int line; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // typedef struct LLDBPlugin { lldb::SBDebugger debugger; lldb::SBTarget target; lldb::SBListener listener; lldb::SBProcess process; PDDebugState state; bool has_valid_target; uint64_t selected_thread_id; const char* targetName; std::map<lldb::tid_t, uint32_t> frameSelection; std::vector<Breakpoint> breakpoints; } LLDBPlugin; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void* create_instance(ServiceFunc* serviceFunc) { printf("lldb: create instance\n"); lldb::SBDebugger::Initialize(); LLDBPlugin* plugin = new LLDBPlugin; plugin->debugger = lldb::SBDebugger::Create(false); plugin->state = PDDebugState_NoTarget; plugin->listener = plugin->debugger.GetListener(); plugin->has_valid_target = false; plugin->selected_thread_id = 0; return plugin; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static uint32_t getThreadFrame(LLDBPlugin* plugin, lldb::tid_t threadId) { uint32_t frameIndex = 0; auto frameIter = plugin->frameSelection.find(threadId); if (frameIter != plugin->frameSelection.end()) { frameIndex = frameIter->second; } return frameIndex; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void destroy_instance(void* user_data) { LLDBPlugin* plugin = (LLDBPlugin*)user_data; delete plugin; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const bool m_verbose = true; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* static void on_stop(LLDBPlugin* plugin) { (void)plugin; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void on_break(LLDBPlugin* plugin) { (void)plugin; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void on_step(LLDBPlugin* plugin) { lldb::SBEvent evt; lldb::SBThread thread(plugin->process.GetThreadByID(plugin->selected_thread_id)); printf("thread stopReason %d\n", thread.GetStopReason()); printf("threadValid %d\n", thread.IsValid()); thread.StepInto(); plugin->state = PDDebugState_Running; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void on_step_over(LLDBPlugin* plugin) { lldb::SBEvent evt; lldb::SBThread thread(plugin->process.GetThreadByID(plugin->selected_thread_id)); printf("thread stopReason %d\n", thread.GetStopReason()); printf("threadValid %d\n", thread.IsValid()); thread.StepOver(); plugin->state = PDDebugState_Running; } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void on_run(LLDBPlugin* plugin) { // if we haven't started the executable start it here if (plugin->state == PDDebugState_NoTarget) { lldb::SBLaunchInfo launchInfo(0); lldb::SBError error; plugin->process = plugin->target.Launch(launchInfo, error); printf("try start\n"); if (!error.Success()) { // s_messageFuncs->error("Error to start executable", "The LLDB backend was unable to start the selected // executable. Currently ProDBG requires the user to run it as sudo due to the fact that debugging on Mac // needs that. This will be made a bit more friendly in the future"); printf("LLDB: Unable to start debugging %s\n", error.GetCString()); return; } if (!plugin->process.IsValid()) { printf("process not valid\n"); return; } printf("Started valid process\n"); plugin->process.GetBroadcaster().AddListener( plugin->listener, lldb::SBProcess::eBroadcastBitStateChanged | lldb::SBProcess::eBroadcastBitInterrupt); plugin->state = PDDebugState_Running; plugin->has_valid_target = true; return; } plugin->process.Continue(); plugin->state = PDDebugState_Running; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* static void setCallstack(LLDBPlugin* plugin, PDWriter* writer) { lldb::SBThread thread(plugin->process.GetThreadByID(plugin->selected_thread_id)); printf("set callstack\n"); int frameCount = (int)thread.GetNumFrames(); if (frameCount == 0) return; // TODO: Write type of callstack PDWrite_event_begin(writer, PDEventType_SetCallstack); PDWrite_array_begin(writer, "callstack"); for (int i = 0; i < frameCount; ++i) { char fileLine[2048]; char moduleName[2048]; lldb::SBFrame frame = thread.GetFrameAtIndex((uint32_t)i); lldb::SBModule module = frame.GetModule(); lldb::SBCompileUnit compileUnit = frame.GetCompileUnit(); lldb::SBSymbolContext context(frame.GetSymbolContext(0x0000006e)); lldb::SBLineEntry entry(context.GetLineEntry()); uint64_t address = (uint64_t)frame.GetPC(); module.GetFileSpec().GetPath(moduleName, sizeof(moduleName)); PDWrite_array_entry_begin(writer); if (compileUnit.GetNumSupportFiles() > 0) { char filename[2048]; lldb::SBFileSpec fileSpec = compileUnit.GetSupportFileAtIndex(0); fileSpec.GetPath(filename, sizeof(filename)); sprintf(fileLine, "%s:%d", filename, entry.GetLine()); printf("callstack %s:%d\n", fileLine, entry.GetLine()); PDWrite_string(writer, "filename", filename); PDWrite_u32(writer, "line", entry.GetLine()); } PDWrite_string(writer, "module_name", moduleName); PDWrite_u64(writer, "address", address); PDWrite_entry_end(writer); } PDWrite_array_end(writer); PDWrite_event_end(writer); } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void exception_location_reply(LLDBPlugin* plugin, PDWriter* writer) { char filename[2048] = { 0 }; // Get the filename & line of the exception/breakpoint // \todo: Right now we assume that we only got the break/exception at the first thread. lldb::SBThread thread(plugin->process.GetThreadByID(plugin->selected_thread_id)); uint32_t frameIndex = getThreadFrame(plugin, plugin->selected_thread_id); printf("frameIndex %d\n", frameIndex); lldb::SBFrame frame(thread.GetFrameAtIndex(frameIndex)); lldb::SBSymbolContext context(frame.GetSymbolContext(lldb::eSymbolContextEverything)); lldb::SBLineEntry entry(context.GetLineEntry()); uint32_t line = entry.GetLine(); entry.GetFileSpec().GetPath(filename, sizeof(filename)); // TODO: Handle binary address also flatbuffers::FlatBufferBuilder builder(1024); auto name = builder.CreateString(filename); printf("exception reply %s:%d\n", filename, line); ExceptionLocationReplyBuilder reply(builder); reply.add_filename(name); reply.add_line(line); reply.add_address(0); PDMessage_end_msg(writer, reply, builder); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* static void setTty(LLDBPlugin* plugin, PDWriter* writer) { const int bufferSize = 4 * 1024; char buffer[bufferSize]; size_t amountRead = plugin->process.GetSTDOUT(buffer, bufferSize); if (amountRead > 0) { PDWrite_event_begin(writer, PDEventType_SetTty); PDWrite_string(writer, "tty", buffer); PDWrite_event_end(writer); } } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void target_reply(LLDBPlugin* plugin, const FileTargetRequest* request, PDWriter* writer) { flatbuffers::FlatBufferBuilder builder(1024); const char* filename = request->path()->c_str(); printf("lldb_plugin: target request %s\n", filename); plugin->target = plugin->debugger.CreateTarget(filename); if (!plugin->target.IsValid()) { char error_msg[4096]; sprintf(error_msg, "LLDBPlugin: Unable to create valid target for: %s", filename); auto error_str = builder.CreateString(error_msg); TargetReplyBuilder reply(builder); reply.add_status(false); reply.add_error_message(error_str); PDMessage_end_msg(writer, reply, builder); } else { auto error_str = builder.CreateString(""); for (Breakpoint& bp : plugin->breakpoints) { lldb::SBBreakpoint breakpoint = plugin->target.BreakpointCreateByLocation(bp.filename, (uint32_t)bp.line); if (!breakpoint.IsValid()) { // TODO: Send message back that this breakpoint could't be set printf("Unable to set breakpoint %s:%d\n", bp.filename, bp.line); } } printf("LLDBPlugin: Ok target\n"); TargetReplyBuilder reply(builder); reply.add_error_message(error_str); reply.add_status(true); PDMessage_end_msg(writer, reply, builder); } //on_run(plugin); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* static void setLocals(LLDBPlugin* plugin, PDWriter* writer) { lldb::SBThread thread(plugin->process.GetThreadByID(plugin->selected_thread_id)); lldb::SBFrame frame = thread.GetSelectedFrame(); lldb::SBValueList variables = frame.GetVariables(true, true, true, false); uint32_t count = variables.GetSize(); if (count <= 0) return; PDWrite_event_begin(writer, PDEventType_SetLocals); PDWrite_array_begin(writer, "locals"); for (uint32_t i = 0; i < count; ++i) { lldb::SBValue value = variables.GetValueAtIndex(i); PDWrite_array_entry_begin(writer); PDWrite_u64(writer, "address", value.GetAddress().GetFileAddress()); if (value.GetValue()) PDWrite_string(writer, "value", value.GetValue()); if (value.GetTypeName()) PDWrite_string(writer, "type", value.GetTypeName()); if (value.GetName()) PDWrite_string(writer, "name", value.GetName()); PDWrite_entry_end(writer); } PDWrite_array_end(writer); PDWrite_event_end(writer); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void setThreads(LLDBPlugin* plugin, PDWriter* writer) { uint32_t threadCount = plugin->process.GetNumThreads(); if (threadCount == 0) return; PDWrite_event_begin(writer, PDEventType_SetThreads); PDWrite_array_begin(writer, "threads"); for (uint32_t i = 0; i < threadCount; ++i) { lldb::SBThread thread = plugin->process.GetThreadAtIndex(i); lldb::SBFrame frame = thread.GetFrameAtIndex(0); uint64_t threadId = thread.GetThreadID(); const char* threadName = thread.GetName(); const char* queueName = thread.GetQueueName(); const char* functionName = frame.GetFunctionName(); PDWrite_array_entry_begin(writer); PDWrite_u64(writer, "id", threadId); if (threadName) PDWrite_string(writer, "name", threadName); else if (queueName) PDWrite_string(writer, "name", queueName); else PDWrite_string(writer, "name", "unknown_thread"); if (functionName) PDWrite_string(writer, "function", functionName); else PDWrite_string(writer, "function", "unknown_function"); PDWrite_entry_end(writer); } PDWrite_array_end(writer); PDWrite_event_end(writer); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void setBreakpoint(LLDBPlugin* plugin, PDReader* reader, PDWriter* writer) { const char* filename; uint32_t line; PDRead_find_string(reader, &filename, "filename", 0); PDRead_find_u32(reader, &line, "line", 0); // TODO: Handle failure here lldb::SBBreakpoint breakpoint = plugin->target.BreakpointCreateByLocation(filename, line); if (!breakpoint.IsValid()) { printf("adding breakpoints to breakpoint list %s:%d\n", filename, line); // Unable to set breakpoint as the target doesn't seem to be valid. This is the usual case // if we haven't actually started an executable yet. So we save them here for later and // then set them before launching the executable Breakpoint bp = {strdup(filename), (int)line}; plugin->breakpoints.push_back(bp); return; } printf("Set breakpoint at %s:%d\n", filename, line); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void event_action(LLDBPlugin* plugin, PDReader* reader) { uint32_t action = 0; printf("LLDBPlugin; %d\n", (PDRead_find_u32(reader, &action, "action", 0) & 0xff) >> 8); printf("LLDBPlugin: got action (from event) %d\n", action); do_action(plugin, (PDAction)action); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// */ /* static const char* eventTypes[] = { "PDEventType_none", "PDEventType_getLocals", "PDEventType_setLocals", "PDEventType_getCallstack", "PDEventType_setCallstack", "PDEventType_getWatch", "PDEventType_setWatch", "PDEventType_getRegisters", "PDEventType_setRegisters", "PDEventType_getMemory", "PDEventType_setMemory", "PDEventType_getTty", "PDEventType_setTty", "PDEventType_getExceptionLocation", "PDEventType_exception_location_reply", "PDEventType_getDisassembly", "PDEventType_setDisassembly", "PDEventType_setBreakpoint", "PDEventType_getBreakpoint", "PDEventType_setExecutable", "PDEventType_attachToProcess", "PDEventType_attachToRemoteSession", "PDEventType_action", }; */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* static void selectThread(LLDBPlugin* plugin, PDReader* reader, PDWriter* writer) { uint64_t threadId; PDRead_find_u64(reader, &threadId, "thread_id", 0); printf("trying te set thread %lu\n", threadId); if (plugin->selected_thread_id == threadId) return; printf("selecting thread %lu\n", threadId); plugin->selected_thread_id = threadId; setCallstack(plugin, writer); PDWrite_event_begin(writer, PDEventType_SelectFrame); PDWrite_u32(writer, "frame", getThreadFrame(plugin, threadId)); PDWrite_event_end(writer); } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* static void select_frame(LLDBPlugin* plugin, PDReader* reader, PDWriter* writer) { uint32_t frameIndex; printf("select_frame...\n"); PDRead_find_u32(reader, &frameIndex, "frame", 0); plugin->frameSelection[plugin->selected_thread_id] = frameIndex; exception_location_reply(plugin, writer); } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* static void set_source_files(LLDBPlugin* plugin, PDWriter* writer) { if (!plugin->has_valid_target) return; PDWrite_event_begin(writer, PDEventType_SetSourceFiles); PDWrite_array_begin(writer, "files"); const uint32_t moduleCount = plugin->target.GetNumModules(); for (uint32_t im = 0; im < moduleCount; ++im) { lldb::SBModule module(plugin->target.GetModuleAtIndex(im)); const uint32_t compileUnitCount = module.GetNumCompileUnits(); for (uint32_t ic = 0; ic < compileUnitCount; ++ic) { lldb::SBCompileUnit compileUnit(module.GetCompileUnitAtIndex(ic)); const uint32_t supportFileCount = compileUnit.GetNumSupportFiles(); for (uint32_t is = 0; is < supportFileCount; ++is) { char filename[4096]; lldb::SBFileSpec fileSpec(compileUnit.GetSupportFileAtIndex(is)); filename[0] = 0; fileSpec.GetPath(filename, sizeof(filename)); if (filename[0] == 0) continue; PDWrite_array_entry_begin(writer); PDWrite_string(writer, "file", filename); PDWrite_entry_end(writer); } } } PDWrite_array_end(writer); PDWrite_event_end(writer); } */ static void do_action(LLDBPlugin* plugin, PDAction action) { switch (action) { /* case PDAction_Stop: on_stop(plugin); break; case PDAction_Break: on_break(plugin); break; */ case PDAction_Run: on_run(plugin); break; /* case PDAction_Step: on_step(plugin); break; case PDAction_StepOut: on_step_over(plugin); break; case PDAction_StepOver: on_step_over(plugin); break; */ default: break; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void process_events(LLDBPlugin* plugin, PDReader* reader, PDWriter* writer) { uint32_t event; void* data = nullptr; uint64_t size = 0; while ((event = PDRead_get_event(reader))) { // TODO: This wrapping is temporary right now PDRead_find_data(reader, &data, &size, "data", 0); const Message* msg = GetMessage(data); switch (msg->message_type()) { case MessageType_exception_location_request: { exception_location_reply(plugin, writer); break; } case MessageType_file_target_request: { target_reply(plugin, msg->message_as_file_target_request(), writer); break; } default: break; } // printf("LLDBPlugin: %d Got event %s\n", event, eventTypes[event]); /* switch (event) { case PDEventType_GetExceptionLocation: exception_location_reply(plugin, writer); break; case PDEventType_GetCallstack: setCallstack(plugin, writer); break; case PDEventType_SetExecutable: setExecutable(plugin, reader); break; case PDEventType_SelectThread: selectThread(plugin, reader, writer); break; case PDEventType_SelectFrame: select_frame(plugin, reader, writer); break; case PDEventType_GetLocals: setLocals(plugin, writer); break; case PDEventType_GetThreads: setThreads(plugin, writer); break; case PDEventType_GetSourceFiles: set_source_files(plugin, writer); break; case PDEventType_SetBreakpoint: setBreakpoint(plugin, reader, writer); break; case PDEventType_Action: event_action(plugin, reader); break; } */ } //setTty(plugin, writer); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void send_exception_state(LLDBPlugin* plugin, PDWriter* writer) { printf("sending exception state\n"); // setCallstack(plugin, writer); exception_location_reply(plugin, writer); // setLocals(plugin, writer); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void update_lldb_event(LLDBPlugin* plugin, PDWriter* writer) { if (!plugin->process.IsValid()) { printf("process invalid\n"); return; } lldb::SBEvent evt; plugin->listener.WaitForEvent(1, evt); lldb::StateType state = lldb::SBProcess::GetStateFromEvent(evt); printf("event = %s\n", lldb::SBDebugger::StateAsCString(state)); if (lldb::SBProcess::GetRestartedFromEvent(evt)) { printf("lldb::SBProcess::GetRestartedFromEvent(evt)\n"); return; } switch (state) { case lldb::eStateInvalid: case lldb::eStateDetached: case lldb::eStateCrashed: case lldb::eStateUnloaded: return; case lldb::eStateExited: return; case lldb::eStateConnected: case lldb::eStateAttaching: case lldb::eStateLaunching: case lldb::eStateRunning: case lldb::eStateStepping: return; case lldb::eStateStopped: case lldb::eStateSuspended: { // call_test_step = true; // bool fatal = false; bool selected_thread = false; for (uint32_t thread_index = 0; thread_index < plugin->process.GetNumThreads(); thread_index++) { lldb::SBThread thread(plugin->process.GetThreadAtIndex((size_t)thread_index)); lldb::SBFrame frame(thread.GetFrameAtIndex(0)); bool select_thread = false; lldb::StopReason stop_reason = thread.GetStopReason(); if (m_verbose) printf("tid = 0x%lx pc = 0x%lx ", thread.GetThreadID(), frame.GetPC()); printf("stop reason %d\n", stop_reason); switch (stop_reason) { case lldb::eStopReasonNone: { if (m_verbose) printf("none\n"); break; } case lldb::eStopReasonTrace: { select_thread = true; plugin->state = PDDebugState_Trace; if (m_verbose) printf("trace\n"); break; } case lldb::eStopReasonPlanComplete: select_thread = true; send_exception_state(plugin, writer); plugin->state = PDDebugState_Trace; if (m_verbose) printf("plan complete\n"); break; case lldb::eStopReasonThreadExiting: if (m_verbose) printf("thread exiting\n"); break; case lldb::eStopReasonExec: if (m_verbose) printf("exec\n"); break; case lldb::eStopReasonInvalid: if (m_verbose) printf("invalid\n"); break; case lldb::eStopReasonException: { select_thread = true; printf("%d %d\n", plugin->state, PDDebugState_StopException); if (plugin->state != PDDebugState_StopException) send_exception_state(plugin, writer); plugin->state = PDDebugState_StopException; if (m_verbose) printf("exception\n"); // fatal = true; break; } case lldb::eStopReasonBreakpoint: { select_thread = true; if (plugin->state != PDDebugState_StopBreakpoint) send_exception_state(plugin, writer); plugin->state = PDDebugState_StopBreakpoint; if (m_verbose) { printf("breakpoint id = %ld.%ld\n", thread.GetStopReasonDataAtIndex(0), thread.GetStopReasonDataAtIndex(1)); } break; } case lldb::eStopReasonWatchpoint: select_thread = true; if (m_verbose) printf("watchpoint id = %ld\n", thread.GetStopReasonDataAtIndex(0)); break; case lldb::eStopReasonSignal: select_thread = true; if (m_verbose) printf("signal %d\n", (int)thread.GetStopReasonDataAtIndex(0)); break; default: break; } if (select_thread && !selected_thread) { selected_thread = plugin->process.SetSelectedThread(thread); plugin->selected_thread_id = thread.GetThreadID(); if (plugin->state != PDDebugState_StopException) send_exception_state(plugin, writer); plugin->state = PDDebugState_StopException; } } } break; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static PDDebugState update(void* user_data, PDAction action, PDReader* reader, PDWriter* writer) { LLDBPlugin* plugin = (LLDBPlugin*)user_data; process_events(plugin, reader, writer); do_action(plugin, action); if (plugin->state == PDDebugState_Running) { update_lldb_event(plugin, writer); } return plugin->state; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static PDBackendPlugin plugin = { "LLDB", create_instance, destroy_instance, update, 0, // save_state 0, // load_state }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* private_data) { registerPlugin(PD_BACKEND_API_VERSION, &plugin, private_data); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif
11,302
2,577
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.engine.impl.persistence.entity; import java.util.List; import org.camunda.bpm.engine.impl.context.Context; import org.camunda.bpm.engine.impl.db.ListQueryParameterObject; import org.camunda.bpm.engine.impl.db.TenantCheck; import org.camunda.bpm.engine.impl.identity.Authentication; import org.camunda.bpm.engine.impl.persistence.AbstractManager; /** * @author <NAME> * */ public class TenantManager extends AbstractManager { public ListQueryParameterObject configureQuery(ListQueryParameterObject query) { TenantCheck tenantCheck = query.getTenantCheck(); configureTenantCheck(tenantCheck); return query; } public void configureTenantCheck(TenantCheck tenantCheck) { if (isTenantCheckEnabled()) { Authentication currentAuthentication = getCurrentAuthentication(); tenantCheck.setTenantCheckEnabled(true); tenantCheck.setAuthTenantIds(currentAuthentication.getTenantIds()); } else { tenantCheck.setTenantCheckEnabled(false); tenantCheck.setAuthTenantIds(null); } } public ListQueryParameterObject configureQuery(Object parameters) { ListQueryParameterObject queryObject = new ListQueryParameterObject(); queryObject.setParameter(parameters); return configureQuery(queryObject); } public boolean isAuthenticatedTenant(String tenantId) { if (tenantId != null && isTenantCheckEnabled()) { Authentication currentAuthentication = getCurrentAuthentication(); List<String> authenticatedTenantIds = currentAuthentication.getTenantIds(); if (authenticatedTenantIds != null) { return authenticatedTenantIds.contains(tenantId); } else { return false; } } else { return true; } } public boolean isTenantCheckEnabled() { return Context.getProcessEngineConfiguration().isTenantCheckEnabled() && Context.getCommandContext().isTenantCheckEnabled() && getCurrentAuthentication() != null && !getAuthorizationManager().isCamundaAdmin(getCurrentAuthentication()); } }
862
634
<filename>modules/base/remote-servers-impl/src/main/java/com/intellij/remoteServer/impl/runtime/ui/tree/actions/DeploymentActionBase.java package com.intellij.remoteServer.impl.runtime.ui.tree.actions; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.remoteServer.impl.runtime.ui.ServersToolWindowContent; import com.intellij.remoteServer.impl.runtime.ui.tree.DeploymentNode; import consulo.ui.image.Image; import javax.annotation.Nonnull; import java.util.Set; /** * @author nik */ public abstract class DeploymentActionBase extends ServersTreeActionBase { public DeploymentActionBase(String text, String description, Image icon) { super(text, description, icon); } protected abstract void perform(DeploymentNode node); protected abstract boolean isApplicable(DeploymentNode node); @Override public void doActionPerformed(@Nonnull ServersToolWindowContent content) { for (DeploymentNode node : content.getSelectedDeploymentNodes()) { if (isApplicable(node)) { perform(node); } } } @Override protected boolean isEnabled(@Nonnull ServersToolWindowContent content, AnActionEvent e) { Set<?> selectedElements = content.getBuilder().getSelectedElements(); if (selectedElements.isEmpty() || selectedElements.size() != content.getSelectedDeploymentNodes().size()) { return false; } for (DeploymentNode node : content.getSelectedDeploymentNodes()) { if (!isApplicable(node)) { return false; } } return true; } }
505
472
<filename>_other_languages/cpp/Maths/divisors.cpp /** * Find all divisors of a natural number * * Given a natural number n, print all distinct divisors of it. * * Examples: * Input : n = 10 * Output: 1 2 5 10 * * Input: n = 100 * Output: 1 2 4 5 10 20 25 50 100 * * Input: n = 125 * Output: 1 5 25 125 * * URL: https://www.geeksforgeeks.org/find-divisors-natural-number-set-1/ * https://www.geeksforgeeks.org/find-all-divisors-of-a-natural-number-set-2/ * */ #include <iostream> void getDivisors(int n) { for (int i = 1; i * i <= n; i++) { // time complexity: sqrt(n) if (n % i == 0) { if (n/i == i) std::cout << i << " "; else std::cout << i << " " << n/i << " "; } } } int main() { int n = 100; getDivisors(n); return 0; }
412
988
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.dbschema.jdbcimpl; import java.sql.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import org.netbeans.modules.dbschema.*; import org.netbeans.modules.dbschema.util.*; public class TableElementImpl extends DBElementImpl implements TableElement.Impl { private static final Logger LOGGER = Logger.getLogger(TableElementImpl.class.getName()); private DBElementsCollection columns; private DBElementsCollection indexes; private DBElementsCollection keys; private transient DBElementsCollection columnPairs; private String table; private boolean isTable; public TableElementImpl() { this(null); } /** Creates new TableElementImpl */ public TableElementImpl(String table) { super(table); columns = new DBElementsCollection(this, new ColumnElement[0]); // NOTE - After doing research, not sure this comment still applys? Remove it? // workaround for bug #4396371 // http://andorra.eng:8080/cgi-bin/ws.exe/bugtraq/bug.hts?where=bugid_value%3D4396371 String hc = String.valueOf(columns.hashCode()); while (DBElementsCollection.instances.contains(hc)) { columns = new DBElementsCollection(this, new ColumnElement[0]); hc = String.valueOf(columns.hashCode()); } DBElementsCollection.instances.add(hc); indexes = new DBElementsCollection(this, new IndexElement[0]); //workaround for bug #4396371 //http://andorra.eng:8080/cgi-bin/ws.exe/bugtraq/bug.hts?where=bugid_value%3D4396371 hc = String.valueOf(indexes.hashCode()); while (DBElementsCollection.instances.contains(hc)) { indexes = new DBElementsCollection(this, new IndexElement[0]); hc = String.valueOf(indexes.hashCode()); } DBElementsCollection.instances.add(hc); keys = new DBElementsCollection(this, new KeyElement[0]); //workaround for bug #4396371 //http://andorra.eng:8080/cgi-bin/ws.exe/bugtraq/bug.hts?where=bugid_value%3D4396371 hc = String.valueOf(keys.hashCode()); while (DBElementsCollection.instances.contains(hc)) { keys = new DBElementsCollection(this, new KeyElement[0]); hc = String.valueOf(keys.hashCode()); } DBElementsCollection.instances.add(hc); columnPairs = new DBElementsCollection(this, new ColumnPairElement[0]); //workaround for bug #4396371 //http://andorra.eng:8080/cgi-bin/ws.exe/bugtraq/bug.hts?where=bugid_value%3D4396371 hc = String.valueOf(columnPairs.hashCode()); while (DBElementsCollection.instances.contains(hc)) { columnPairs = new DBElementsCollection(this, new ColumnPairElement[0]); hc = String.valueOf(columnPairs.hashCode()); } DBElementsCollection.instances.add(hc); this.table = table; } /** Get the name of this element. * @return the name */ @Override public DBIdentifier getName() { if (_name.getFullName() == null) _name.setFullName(((TableElement) element).getDeclaringSchema().getName().getFullName() + "." + _name.getName()); return _name; } /** Set whether this is really a table, or a view. * @param isTable one of {@link #TABLE} or {@link #VIEW} * @throws DBException if impossible */ @Override public void setTableOrView(boolean isTable) throws DBException { this.isTable = isTable; } /** Test whether this is really a class, or an interface. * @return one of {@link #TABLE} or {@link #VIEW} */ @Override public boolean isTableOrView() { return isTable; } /** Change the set of columns. * @param elems the columns to change * @param action one of {@link #ADD}, {@link #REMOVE}, or {@link #SET} * @exception DBException if the action cannot be handled */ @Override public void changeColumns(ColumnElement[] elems,int action) throws DBException { columns.changeElements(elems, action); } /** Get all columns. * @return the columns */ @Override public ColumnElement[] getColumns() { DBElement[] dbe = columns.getElements(); return Arrays.asList(dbe).toArray(new ColumnElement[dbe.length]); } /** Find a column by name. * @param name the name for which to look * @return the column, or <code>null</code> if it does not exist */ @Override public ColumnElement getColumn(DBIdentifier name) { return (ColumnElement) columns.find(name); } protected void initColumns(ConnectionProvider cp) { if (cp != null) try { DatabaseMetaData dmd = cp.getDatabaseMetaData(); String shortTableName = getName().getName(); DDLBridge bridge = null; if (IDEUtil.isIDERunning()) bridge = new DDLBridge(cp.getConnection(), cp.getSchema(), dmd); ResultSet rs; if (bridge != null) { bridge.getDriverSpecification().getColumns(shortTableName, "%"); rs = bridge.getDriverSpecification().getResultSet(); } else // rs = dmd.getColumns(cp.getConnection().getCatalog(), dmd.getUserName().trim(), shortTableName, "%"); rs = dmd.getColumns(cp.getConnection().getCatalog(), cp.getSchema(), shortTableName, "%"); int sqlType; String sqlTypeName; String colName, colNull, colSize, colDec; String strAutoIncrement = null; if (rs != null) { Map<Integer, String> rset = new HashMap<>(); while (rs.next()) { if (bridge != null) { rset = bridge.getDriverSpecification().getRow(); Object type = rset.get(new Integer(5)); if (type != null) { sqlType = (new Integer(rset.get(new Integer(5)))).intValue(); } else { sqlType = 0; //java.sql.Types.NULL } // #192609: IllegalArgumentException: aType == null if ("PostgreSQL".equalsIgnoreCase(dmd.getDatabaseProductName())) { // NOI18N if (Types.DISTINCT == sqlType) { sqlType = (new Integer(rset.get(new Integer(22)))).intValue(); } } sqlTypeName = rset.get(new Integer(6)); colName = rset.get(new Integer(4)); colNull = rset.get(new Integer(11)); colSize = rset.get(new Integer(7)); colDec = rset.get(new Integer(9)); strAutoIncrement = rset.get(new Integer(23)); rset.clear(); } else { sqlType = rs.getInt("DATA_TYPE"); //NOI18N sqlTypeName = rs.getString("TYPE_NAME").trim(); //NOI18N colName = rs.getString("COLUMN_NAME").trim(); //NOI18N colNull = Integer.toString(rs.getInt("NULLABLE")); //NOI18N colSize = rs.getString("COLUMN_SIZE"); //NOI18N colDec = rs.getString("DECIMAL_DIGITS"); //NOI18N try { strAutoIncrement = rs.getString("IS_AUTOINCREMENT"); } catch (SQLException sqle) { LOGGER.log(Level.FINE, null, sqle); strAutoIncrement = null; } } boolean colAutoIncrement = strAutoIncrement != null && strAutoIncrement.equals("YES"); String dbProductName = dmd.getDatabaseProductName().trim(); //Oracle driver hacks if (dbProductName.indexOf("Oracle") != -1) { //NOI18N if (sqlType == 11 || ((sqlType == 1111) && sqlTypeName.startsWith("TIMESTAMP"))) sqlType = Types.TIMESTAMP; if ((sqlType == 1111) && sqlTypeName.equals("FLOAT")) //NOI18N sqlType = Types.DOUBLE; if ((sqlType == 1111) && sqlTypeName.equals("BLOB")) //NOI18N sqlType = Types.BLOB; if ((sqlType == 1111) && sqlTypeName.equals("CLOB")) //NOI18N sqlType = Types.CLOB; if ((sqlType == 1111) && sqlTypeName.equals("NVARCHAR2")) //NOI18N sqlType = Types.CHAR; } //MySQL driver hacks if (dbProductName.indexOf("MySQL") != -1) { //NOI18N if ((sqlType == 1111) && sqlTypeName.equalsIgnoreCase("BIT")) //NOI18N sqlType = Types.BIT; } //workaround for i-net Oranxo driver //value in int range is expected by JDBC API but 4294967296 is returned try { colSize = new Integer(colSize).toString(); } catch (NumberFormatException exc) { colSize = Integer.toString(Integer.MAX_VALUE); } ColumnElementImpl cei = new ColumnElementImpl(colName, Integer.toString(sqlType), colNull, colAutoIncrement, colSize, colDec); ColumnElement ce = new ColumnElement(cei, (TableElement) element); ColumnElement[] c = {ce}; changeColumns(c, DBElement.Impl.ADD); } rs.close(); } } catch (Exception exc) { LOGGER.log(Level.INFO, exc.getLocalizedMessage(), exc); } } /** Change the set of indexes. * @param elems the indexes to change * @param action one of {@link #ADD}, {@link #REMOVE}, or {@link #SET} * @exception DBException if the action cannot be handled */ @Override public void changeIndexes(IndexElement[] elems,int action) throws DBException { indexes.changeElements(elems, action); } /** Get all indexes. * @return the indexes */ @Override public IndexElement[] getIndexes() { DBElement[] dbe = indexes.getElements(); return Arrays.asList(dbe).toArray(new IndexElement[dbe.length]); } /** Find an index by name. * @param name the name for which to look * @return the index, or <code>null</code> if it does not exist */ @Override public IndexElement getIndex(DBIdentifier name) { return (IndexElement) indexes.find(name); } protected void initIndexes(ConnectionProvider cp) { initIndexes(cp, null); } protected void initIndexes(ConnectionProvider cp, String tbl) { if (cp != null) try { boolean unique; DatabaseMetaData dmd = cp.getDatabaseMetaData(); String shortTableName; if (tbl == null) shortTableName = getName().getName(); else shortTableName = tbl; DDLBridge bridge = null; if (IDEUtil.isIDERunning()) bridge = new DDLBridge(cp.getConnection(), cp.getSchema(), dmd); ResultSet rs; if (bridge != null) { bridge.getDriverSpecification().getIndexInfo(shortTableName, false, true); rs = bridge.getDriverSpecification().getResultSet(); } else // rs = dmd.getIndexInfo(cp.getConnection().getCatalog(), dmd.getUserName().trim(), shortTableName, false, true); rs = dmd.getIndexInfo(cp.getConnection().getCatalog(), cp.getSchema(), shortTableName, false, true); String name, columnName; boolean unq; LinkedList<String> idxs = new LinkedList<>(); if (rs != null) { Map<Integer, String> rset = new HashMap<>(); String uniqueStr; while (rs.next()) { if (bridge != null) { // Ignore Indices marked statistic // explizit: TYPE == DatabaseMetaData or // implizit: ORDINAL_POSITION == 0 // @see java.sql.DatabaseMetaData#getIndexInfo if (rs.getShort("TYPE") == DatabaseMetaData.tableIndexStatistic // NOI18N || rs.getInt("ORDINAL_POSITION") == 0) { // NOI18N continue; } rset = bridge.getDriverSpecification().getRow(); name = (String) rset.get(new Integer(6)); columnName = (String) rset.get(new Integer(9)); uniqueStr = (String) rset.get(new Integer(4)); if (uniqueStr == null || uniqueStr.equals("0") || uniqueStr.equalsIgnoreCase("false") || uniqueStr.equalsIgnoreCase("f")) unq = false; else unq = true; rset.clear(); } else { name = rs.getString("INDEX_NAME"); //NOI18N columnName = rs.getString("COLUMN_NAME"); //NOI18N if (columnName != null) columnName = columnName.trim(); unq = rs.getBoolean("NON_UNIQUE"); //NOI18N } // hack for PostgreSQL bug 3480: the driver returns quotes around quoted column names if (columnName != null && columnName.length() >= 2 && columnName.startsWith("\"") && columnName.endsWith("\"")) { // NOI18N columnName = columnName.substring(1, columnName.length() - 1); } if (name == null) continue; else name = name.trim(); if (unq) idxs.add(name + "." + columnName + ".false"); //NOI18N else idxs.add(name + "." + columnName + ".true"); //NOI18N } rs.close(); } String info; int start, end; for (int i = 0; i < idxs.size(); i++) { info = idxs.get(i).toString(); start = info.indexOf('.'); //NOI18N end = info.lastIndexOf('.'); //NOI18N name = info.substring(0, start); if ((info.substring(end + 1)).equals("true")) //NOI18N unique = true; else unique = false; if (indexes.find(DBIdentifier.create(name)) != null) continue; IndexElementImpl iei = new IndexElementImpl(this, name, unique); IndexElement[] ie = {new IndexElement(iei, (TableElement) element)}; iei.initColumns(idxs); changeIndexes(ie, DBElement.Impl.ADD); } } catch (Exception exc) { LOGGER.log(Level.INFO, exc.getLocalizedMessage(), exc); } } /** Change the set of keys. * @param elems the keys to change * @param action one of {@link #ADD}, {@link #REMOVE}, or {@link #SET} * @exception DBException if the action cannot be handled */ @Override public void changeKeys(KeyElement[] elems,int action) throws DBException { keys.changeElements(elems, action); } /** Get all keys. * @return the keys */ @Override public KeyElement[] getKeys() { DBElement[] dbe = keys.getElements(); return Arrays.asList(dbe).toArray(new KeyElement[dbe.length]); } /** Find a key by name. * @param name the name for which to look * @return the key, or <code>null</code> if it does not exist */ @Override public KeyElement getKey(DBIdentifier name) { return (KeyElement) keys.find(name); } protected void initKeys(ConnectionProvider cp) { initKeys(cp, 0); } protected void initKeys(ConnectionProvider cp, int id) { // id == 1 ... capture PK only // id == 2 ... capture FKs only initKeys(cp, id, null); } protected void initKeys(ConnectionProvider cp, int id, String tbl) { // id == 1 ... capture PK only // id == 2 ... capture FKs only // id == 3 ... capture FKs (and PKs), but don't expect that all related tables are provided. In other words, // tries to initializes all FKs, but doesn't fail if some table is missing. if (cp != null) try { String shortTableName; if (tbl == null) shortTableName = getName().getName(); else shortTableName = tbl; DDLBridge bridge = null; if (IDEUtil.isIDERunning()) bridge = new DDLBridge(cp.getConnection(), cp.getSchema(), cp.getDatabaseMetaData()); boolean relatedTablesProvided = id != 3; if (id != 1) initFKs(cp, bridge, shortTableName, relatedTablesProvided); if (id != 2) initPK(cp, bridge, shortTableName); } catch (Exception exc) { LOGGER.log(Level.INFO, exc.getLocalizedMessage(), exc); } } /** * @param expectRelatedTables specifies whether all related tables are expected to be provided. */ private void initFKs(ConnectionProvider cp, DDLBridge bridge, String shortTableName, boolean expectRelatedTables) throws SQLException, DBException { ResultSet rs; if (bridge != null) { bridge.getDriverSpecification().getImportedKeys(shortTableName); rs = bridge.getDriverSpecification().getResultSet(); } else rs = cp.getDatabaseMetaData().getImportedKeys(cp.getConnection().getCatalog(), cp.getSchema(), shortTableName); String name, fkColName, pkTableName, pkColName, c1, c2, s1, s2; if (rs != null) { Map<Integer, String> rset = new HashMap<>(); while (rs.next()) { if (bridge != null) { rset = bridge.getDriverSpecification().getRow(); //test references between two schemas c1 = (String) rset.get(new Integer(1)); s1 = (String) rset.get(new Integer(2)); c2 = (String) rset.get(new Integer(5)); s2 = (String) rset.get(new Integer(6)); name = (String) rset.get(new Integer(12)); fkColName = (String) rset.get(new Integer(8)); pkTableName = (String) rset.get(new Integer(3)); pkColName = (String) rset.get(new Integer(4)); rset.clear(); } else { //test references between two schemas c1 = rs.getString("PKTABLE_CAT"); //NOI18N s1 = rs.getString("PKTABLE_SCHEM"); //NOI18N c2 = rs.getString("FKTABLE_CAT"); //NOI18N s2 = rs.getString("FKTABLE_SCHEM"); //NOI18N name = rs.getString("FK_NAME"); //NOI18N fkColName = rs.getString("FKCOLUMN_NAME").trim(); //NOI18N pkTableName = rs.getString("PKTABLE_NAME").trim(); //NOI18N pkColName = rs.getString("PKCOLUMN_NAME").trim(); //NOI18N } if (comp(c1, c2)) { if (! comp(s1, s2)) continue; } else continue; ColumnPairElement cpe; if (name == null || name.trim().equals("")) name = "GENERATED_FK_" + pkTableName; else name = name.trim(); ColumnElement lce = getColumn(DBIdentifier.create(fkColName)); //NOI18N if (lce == null) //should be null only in same cases when FK is computed for view continue; SchemaElement se = ((TableElement) element).getDeclaringSchema(); TableElement fte = se.getTable(DBIdentifier.create(pkTableName)); // table could not be found since all related tables were not necessarily provided if (fte == null && !expectRelatedTables){ continue; } ColumnElement fce = fte.getColumn(DBIdentifier.create(pkColName)); ColumnPairElementImpl cpei = new ColumnPairElementImpl(lce.getName().getFullName() + ";" + fce.getName().getFullName()); //NOI18N cpe = new ColumnPairElement(cpei, lce, fce, (TableElement) element); changeColumnPairs(new ColumnPairElement[] {cpe}, DBElement.Impl.ADD); ForeignKeyElement fk = (ForeignKeyElement) keys.find(DBIdentifier.create(name)); if (fk != null) fk.addColumnPair(cpe); //add pair else { ForeignKeyElementImpl fkei = new ForeignKeyElementImpl(this, name); ForeignKeyElement fke = new ForeignKeyElement(fkei, (TableElement) element); fke.addColumnPair(cpe); changeKeys(new ForeignKeyElement[] {fke}, DBElement.Impl.ADD); } } rs.close(); } } private void initPK(ConnectionProvider cp, DDLBridge bridge, String shortTableName) throws SQLException, DBException { ResultSet rs; IndexElement[] iearr = getIndexes(); if (iearr != null) { for (int i = 0; i < iearr.length; i++) if (iearr[i].isUnique()) { UniqueKeyElementImpl ukei = new UniqueKeyElementImpl(iearr[i].getName().getName(), false); //false = not primary key (primary flag is setted later) UniqueKeyElement uke = new UniqueKeyElement(ukei, (TableElement) element, iearr[i]); uke.setColumns(iearr[i].getColumns()); changeKeys(new UniqueKeyElement[]{uke}, DBElement.Impl.ADD); } UniqueKeyElement[] ukes = ((TableElement) element).getUniqueKeys(); if (bridge != null) { bridge.getDriverSpecification().getPrimaryKeys(shortTableName); rs = bridge.getDriverSpecification().getResultSet(); } else rs = cp.getDatabaseMetaData().getPrimaryKeys(cp.getConnection().getCatalog(), cp.getSchema(), shortTableName); TreeMap cols = new TreeMap(); Object keySeq; String colName; if (rs != null) { Map<Integer, String> rset = new HashMap<>(); while (rs.next()) { if (bridge != null) { rset = bridge.getDriverSpecification().getRow(); keySeq = rset.get(new Integer(5)); colName = (String) rset.get(new Integer(4)); rset.clear(); } else { keySeq = rs.getObject("KEY_SEQ"); //NOI18N colName = rs.getString("COLUMN_NAME").trim(); //NOI18N } cols.put(keySeq, colName); //NOI18N } rs.close(); } boolean primary = false; if (cols != null && cols.size() > 0) primary = true; if (primary) { Object[] pkColNames = cols.values().toArray(); UniqueKeyElement uniqueKeyForPrimaryKey = findUniqueKeyForPrimaryKey(pkColNames, ukes); if (uniqueKeyForPrimaryKey != null) { uniqueKeyForPrimaryKey.setPrimaryKey(primary); } else { // issue 56492: no index defined for the primary key // generate a UniqueKeyElement and an IndexElement for it String indexName = "primary_key_index"; // NOI18N int i = 1; while (((TableElement)element).getIndex(DBIdentifier.create(indexName)) != null) { indexName = indexName + i; i++; } LinkedList<String> idxs = new LinkedList<>(); for (Iterator it = cols.values().iterator(); it.hasNext();) { // non-unique = false, thus the index is unique -- see initIndexes() idxs.add(indexName + "." + it.next() + ".false"); // NOI18N } IndexElementImpl iei = new IndexElementImpl(this, indexName, true); IndexElement ie = new IndexElement(iei, (TableElement) element); iei.initColumns(idxs); changeIndexes(new IndexElement[] { ie }, DBElement.Impl.ADD); UniqueKeyElementImpl ukei = new UniqueKeyElementImpl(ie.getName().getName(), true); UniqueKeyElement uke = new UniqueKeyElement(ukei, (TableElement)element, ie); uke.setColumns(ie.getColumns()); changeKeys(new UniqueKeyElement[] { uke }, DBElement.Impl.ADD); } } } } /** * Find already initialized unique key matching the primary key. * * @param columnNames Array of names of columns in the primary key, sorted * by their order in the key. * @param uKeys Already initialized unique keys. * @return The unique key that matches the primary key, or null if none can * be found. */ private UniqueKeyElement findUniqueKeyForPrimaryKey(Object[] columnNames, UniqueKeyElement[] uKeys) { for (int i = 0; i < uKeys.length; i++) { ColumnElement[] ces = uKeys[i].getColumns(); if (ces.length != columnNames.length) { continue; } else { boolean equals = true; for (int j = 0; j < ces.length; j++) { if (!columnNames[j].toString().equals( ces[j].getName().getName())) { equals = false; break; } } if (equals) { return uKeys[i]; } } } return null; } @Override public ColumnPairElement[] getColumnPairs() { DBElement[] dbe = columnPairs.getElements(); return Arrays.asList(dbe).toArray(new ColumnPairElement[dbe.length]); } @Override public ColumnPairElement getColumnPair(DBIdentifier name) { ColumnPairElement cpe = (ColumnPairElement) columnPairs.find(name); if (cpe == null) try { String fullName = name.getFullName(); if (fullName == null) { return null; } int pos = fullName.indexOf(";"); String firstHalf = fullName.substring(0, pos); String secondHalf = fullName.substring(pos + 1); ColumnElement lce = getColumn(DBIdentifier.create(firstHalf)); pos = secondHalf.lastIndexOf("."); TableElement te = ((TableElement) element).getDeclaringSchema().getTable(DBIdentifier.create(secondHalf.substring(0, pos))); if (te == null) return null; ColumnElement fce = te.getColumn(DBIdentifier.create(secondHalf)); if (lce == null || fce == null) return null; ColumnPairElementImpl cpei = new ColumnPairElementImpl(lce.getName().getFullName() + ";" + fce.getName().getFullName()); //NOI18N cpe = new ColumnPairElement(cpei, lce, fce, (TableElement) element); changeColumnPairs(new ColumnPairElement[] {cpe}, DBElement.Impl.ADD); } catch (DBException exc) { LOGGER.log(Level.INFO, exc.getLocalizedMessage(), exc); return null; } return cpe; } @Override public void changeColumnPairs(ColumnPairElement[] pairs,int action) throws DBException { columnPairs.changeElements(pairs, action); } //=============== extra methods needed for xml archiver ============== /** Returns the column collection of this table element. This method * should only be used internally and for cloning and archiving. * @return the column collection of this table element */ public DBElementsCollection getColumnCollection () { return columns; } /** Set the column collection of this table element to the supplied * collection. This method should only be used internally and for * cloning and archiving. * @param collection the column collection of this table element */ public void setColumnCollection (DBElementsCollection collection) { columns = collection; } /** Returns the index collection of this table element. This method * should only be used internally and for cloning and archiving. * @return the index collection of this table element */ public DBElementsCollection getIndexCollection () { return indexes; } /** Set the indwx collection of this table element to the supplied * collection. This method should only be used internally and for * cloning and archiving. * @param collection the index collection of this table element */ public void setIndexCollection (DBElementsCollection collection) { indexes = collection; } /** Returns the key collection of this table element. This method * should only be used internally and for cloning and archiving. * @return the key collection of this table element */ public DBElementsCollection getKeyCollection () { return keys; } /** Set the key collection of this table element to the supplied * collection. This method should only be used internally and for * cloning and archiving. * @param collection the key collection of this table element */ public void setKeyCollection (DBElementsCollection collection) { keys = collection; } }
16,455
12,718
#include "pwf.h" #include <pthread.h> struct spwd *fgetspent(FILE *f) { static char *line; static struct spwd sp; size_t size = 0; struct spwd *res = 0; int cs; pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs); if (getline(&line, &size, f) >= 0 && __parsespent(line, &sp) >= 0) res = &sp; pthread_setcancelstate(cs, 0); return res; }
155
495
from __future__ import division, print_function, absolute_import # lookup() ########## import petl as etl table1 = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]] lkp = etl.lookup(table1, 'foo', 'bar') lkp['a'] lkp['b'] # if no valuespec argument is given, defaults to the whole # row (as a tuple) lkp = etl.lookup(table1, 'foo') lkp['a'] lkp['b'] # compound keys are supported table2 = [['foo', 'bar', 'baz'], ['a', 1, True], ['b', 2, False], ['b', 3, True], ['b', 3, False]] lkp = etl.lookup(table2, ('foo', 'bar'), 'baz') lkp[('a', 1)] lkp[('b', 2)] lkp[('b', 3)] # data can be loaded into an existing dictionary-like # object, including persistent dictionaries created via the # shelve module import shelve lkp = shelve.open('example.dat', flag='n') lkp = etl.lookup(table1, 'foo', 'bar', lkp) lkp.close() lkp = shelve.open('example.dat', flag='r') lkp['a'] lkp['b'] # lookupone() ############# import petl as etl table1 = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]] # if the specified key is not unique and strict=False (default), # the first value wins lkp = etl.lookupone(table1, 'foo', 'bar') lkp['a'] lkp['b'] # if the specified key is not unique and strict=True, will raise # DuplicateKeyError try: lkp = etl.lookupone(table1, 'foo', strict=True) except etl.errors.DuplicateKeyError as e: print(e) # compound keys are supported table2 = [['foo', 'bar', 'baz'], ['a', 1, True], ['b', 2, False], ['b', 3, True], ['b', 3, False]] lkp = etl.lookupone(table2, ('foo', 'bar'), 'baz') lkp[('a', 1)] lkp[('b', 2)] lkp[('b', 3)] # data can be loaded into an existing dictionary-like # object, including persistent dictionaries created via the # shelve module import shelve lkp = shelve.open('example.dat', flag='n') lkp = etl.lookupone(table1, 'foo', 'bar', lkp) lkp.close() lkp = shelve.open('example.dat', flag='r') lkp['a'] lkp['b'] # dictlookup() ############## import petl as etl table1 = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]] lkp = etl.dictlookup(table1, 'foo') lkp['a'] lkp['b'] # compound keys are supported table2 = [['foo', 'bar', 'baz'], ['a', 1, True], ['b', 2, False], ['b', 3, True], ['b', 3, False]] lkp = etl.dictlookup(table2, ('foo', 'bar')) lkp[('a', 1)] lkp[('b', 2)] lkp[('b', 3)] # data can be loaded into an existing dictionary-like # object, including persistent dictionaries created via the # shelve module import shelve lkp = shelve.open('example.dat', flag='n') lkp = etl.dictlookup(table1, 'foo', lkp) lkp.close() lkp = shelve.open('example.dat', flag='r') lkp['a'] lkp['b'] # dictlookupone() ################# import petl as etl table1 = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]] # if the specified key is not unique and strict=False (default), # the first value wins lkp = etl.dictlookupone(table1, 'foo') lkp['a'] lkp['b'] # if the specified key is not unique and strict=True, will raise # DuplicateKeyError try: lkp = etl.dictlookupone(table1, 'foo', strict=True) except etl.errors.DuplicateKeyError as e: print(e) # compound keys are supported table2 = [['foo', 'bar', 'baz'], ['a', 1, True], ['b', 2, False], ['b', 3, True], ['b', 3, False]] lkp = etl.dictlookupone(table2, ('foo', 'bar')) lkp[('a', 1)] lkp[('b', 2)] lkp[('b', 3)] # data can be loaded into an existing dictionary-like # object, including persistent dictionaries created via the # shelve module import shelve lkp = shelve.open('example.dat', flag='n') lkp = etl.dictlookupone(table1, 'foo', lkp) lkp.close() lkp = shelve.open('example.dat', flag='r') lkp['a'] lkp['b']
1,735
648
<filename>spec/hl7.fhir.core/3.0.1/package/CodeSystem-definition-status.json<gh_stars>100-1000 {"resourceType":"CodeSystem","id":"definition-status","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"text":{"status":"generated","div":"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n <h2>DefinitionStatus</h2>\n <div>\n <p>Codes identifying the lifecycle stage of a definition</p>\n\n </div>\n <p>This code system http://hl7.org/fhir/definition-status defines the following codes:</p>\n <table class=\"codes\">\n <tr>\n <td>\n <b>Code</b>\n </td>\n <td>\n <b>Display</b>\n </td>\n <td>\n <b>Definition</b>\n </td>\n </tr>\n <tr>\n <td>draft\n <a name=\"definition-status-draft\"> </a>\n </td>\n <td>Draft</td>\n <td>The definition is in the design stage and is not yet considered to be &quot;ready for use&quot;</td>\n </tr>\n <tr>\n <td>active\n <a name=\"definition-status-active\"> </a>\n </td>\n <td>Active</td>\n <td>The definition is considered ready for use</td>\n </tr>\n <tr>\n <td>withdrawn\n <a name=\"definition-status-withdrawn\"> </a>\n </td>\n <td>Withdrawn</td>\n <td>The definition should no longer be used</td>\n </tr>\n <tr>\n <td>unknown\n <a name=\"definition-status-unknown\"> </a>\n </td>\n <td>Unknown</td>\n <td>The authoring system does not know which of the status values currently applies for this request. Note: This concept is not to be used for &quot;other&quot; - one of the listed statuses is presumed to apply, it's just not known which one.</td>\n </tr>\n </table>\n </div>"},"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/structuredefinition-ballot-status","valueString":"Informative"},{"url":"http://hl7.org/fhir/StructureDefinition/structuredefinition-fmm","valueInteger":0}],"url":"http://hl7.org/fhir/definition-status","identifier":{"system":"urn:ietf:rfc:3986","value":"urn:oid:2.16.840.1.113883.4.642.1.99"},"version":"3.0.1","name":"DefinitionStatus","status":"draft","experimental":false,"date":"2017-04-19T07:44:43+10:00","publisher":"HL7 (FHIR Project)","contact":[{"telecom":[{"system":"url","value":"http://hl7.org/fhir"},{"system":"email","value":"<EMAIL>"}]}],"description":"Codes identifying the lifecycle stage of a definition","caseSensitive":true,"valueSet":"http://hl7.org/fhir/ValueSet/definition-status","content":"complete","concept":[{"code":"draft","display":"Draft","definition":"The definition is in the design stage and is not yet considered to be \"ready for use\""},{"code":"active","display":"Active","definition":"The definition is considered ready for use"},{"code":"withdrawn","display":"Withdrawn","definition":"The definition should no longer be used"},{"code":"unknown","display":"Unknown","definition":"The authoring system does not know which of the status values currently applies for this request. Note: This concept is not to be used for \"other\" - one of the listed statuses is presumed to apply, it's just not known which one."}]}
1,629
653
#!/usr/bin/env python # Copyright (c) 2015-2017, The Kovri I2P Router Project # # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are # permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of # conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, this list # of conditions and the following disclaimer in the documentation and/or other # materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors may be # used to endorse or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL # THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import argparse import json import os import requests import sys # Configuration parser = argparse.ArgumentParser(description='Backup current grafana dashboards.') parser.add_argument('--dir', default=os.path.dirname(os.path.realpath(__file__)), help='Directory to store the dashboards (%(default)s)') parser.add_argument('--uri', default='http://admin:[email protected]:3030', help='URI to access grafana with credentials (%(default)s)') args = parser.parse_args() uri = args.uri directory = args.dir # List dashboards req = requests.get(uri + '/api/search').json() for r in req: print("Backuping... " + r['uri']) # Get dashboard dashboard = requests.get(uri + '/api/dashboards/' + r['uri']).json() # Change id with 'null' so that it can be imported dashboard['dashboard']['id'] = None # Save to file with open(directory + '/' + r['uri'][3:] + '.json', 'w') as output: output.write(json.dumps(dashboard, indent=4, sort_keys=True, separators=(',', ': ')))
835
2,519
<gh_stars>1000+ // This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited. #pragma once #include <memory> #include "common/status.h" #include "exec/parquet/types.h" #include "gen_cpp/parquet_types.h" #include "runtime/types.h" #include "utils.h" namespace starrocks { class RandomAccessFile; namespace vectorized { class Column; struct HdfsScanStats; } // namespace vectorized } // namespace starrocks namespace starrocks::parquet { class ParquetField; struct ColumnReaderOptions { vectorized::HdfsScanStats* stats = nullptr; std::string timezone; }; class ColumnReader { public: // TODO(zc): review this, // create a column reader static Status create(RandomAccessFile* file, const ParquetField* field, const tparquet::RowGroup& row_group, const TypeDescriptor& col_type, const ColumnReaderOptions& opts, int chunk_size, std::unique_ptr<ColumnReader>* reader); virtual ~ColumnReader() = default; virtual Status prepare_batch(size_t* num_records, ColumnContentType content_type, vectorized::Column* column) = 0; virtual Status finish_batch() = 0; Status next_batch(size_t* num_records, ColumnContentType content_type, vectorized::Column* column) { RETURN_IF_ERROR(prepare_batch(num_records, content_type, column)); return finish_batch(); } virtual void get_levels(level_t** def_levels, level_t** rep_levels, size_t* num_levels) = 0; virtual Status get_dict_values(vectorized::Column* column) { return Status::NotSupported("get_dict_values is not supported"); } virtual Status get_dict_values(const std::vector<int32_t>& dict_codes, vectorized::Column* column) { return Status::NotSupported("get_dict_values is not supported"); } virtual Status get_dict_codes(const std::vector<Slice>& dict_values, std::vector<int32_t>* dict_codes) { return Status::NotSupported("get_dict_codes is not supported"); } }; } // namespace starrocks::parquet
725
1,056
<filename>enterprise/maven.j2ee/src/org/netbeans/modules/maven/j2ee/execution/DeploymentLogger.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.maven.j2ee.execution; import org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment; import org.openide.windows.OutputWriter; /** * Simple implementation of the {@link Deployment.Logger} used by the infrastructure to log deployment messages. * * <p> * This class is <i>immutable</i> and thus <i>thread safe</i>. * </p> * * @author <NAME> <<EMAIL>> */ public class DeploymentLogger implements Deployment.Logger { private final OutputWriter logger; public DeploymentLogger(OutputWriter logger) { this.logger = logger; } @Override public void log(String string) { logger.println(string); } }
468
1,592
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shenyu.plugin.param.mapping.strategy; import org.apache.shenyu.common.dto.convert.rule.impl.ParamMappingRuleHandle; import org.apache.shenyu.plugin.api.ShenyuPluginChain; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import java.util.Collections; import java.util.HashSet; import java.util.Set; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; /** * Test case for {@link JsonOperator}. */ @RunWith(MockitoJUnitRunner.class) public class JsonOperatorTest { @Mock private ShenyuPluginChain chain; private ServerWebExchange exchange; private JsonOperator jsonOperator; private ParamMappingRuleHandle paramMappingRuleHandle; @Before public void setUp() { Set<String> remove = new HashSet<>(); remove.add("$.age"); ParamMappingRuleHandle.ParamMapInfo add = new ParamMappingRuleHandle.ParamMapInfo(); add.setPath("$"); add.setKey("webName"); add.setValue("SHENYU"); ParamMappingRuleHandle.ParamMapInfo replace = new ParamMappingRuleHandle.ParamMapInfo(); replace.setPath("$"); replace.setKey("name"); replace.setValue("realName"); this.paramMappingRuleHandle = new ParamMappingRuleHandle(); this.paramMappingRuleHandle.setRemoveParameterKeys(remove); this.paramMappingRuleHandle.setAddParameterKeys(Collections.singletonList(add)); this.paramMappingRuleHandle.setReplaceParameterKeys(Collections.singletonList(replace)); this.jsonOperator = new JsonOperator(); final String body = "{\"name\":\"shenyu\",\"age\":\"18\"}"; this.exchange = MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.POST, "localhost") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).body(body)); } @Test public void testApply() { when(this.chain.execute(any())).thenReturn(Mono.empty()); StepVerifier.create(jsonOperator.apply(this.exchange, this.chain, paramMappingRuleHandle)).expectSubscription().verifyComplete(); } }
1,139
775
<filename>micropolis/micropolis-java/src/micropolisj/engine/TileBehavior.java // This file is part of MicropolisJ. // Copyright (C) 2013 <NAME> // Portions Copyright (C) 1989-2007 Electronic Arts Inc. // // MicropolisJ is free software; you can redistribute it and/or modify // it under the terms of the GNU GPLv3, with additional terms. // See the README file, included in this distribution, for details. package micropolisj.engine; import java.util.Random; import static micropolisj.engine.TileConstants.*; public abstract class TileBehavior { protected final Micropolis city; protected final Random PRNG; int xpos; int ypos; int tile; protected TileBehavior(Micropolis city) { this.city = city; this.PRNG = city.PRNG; } public final void processTile(int xpos, int ypos) { this.xpos = xpos; this.ypos = ypos; this.tile = city.getTile(xpos, ypos); apply(); } /** * Activate the tile identified by xpos and ypos properties. */ public abstract void apply(); }
325
365
<filename>SpriteBuilder/CCPhysicsNode/CCBPPhysicsNode.h // // CCBPPhysicsNode.h // SpriteBuilder // // Created by Viktor on 10/4/13. // // #import "CCNode.h" @interface CCBPPhysicsNode : CCNode @property (nonatomic,assign) CGPoint gravity; @property (nonatomic,assign) float sleepTimeThreshold; @end
113
14,668
// 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. package org.chromium.chrome.browser.tabmodel; import android.app.Activity; import android.support.test.InstrumentationRegistry; import androidx.test.filters.MediumTest; import org.hamcrest.Matchers; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.ApplicationStatus; import org.chromium.base.ContextUtils; import org.chromium.base.test.util.AdvancedMockContext; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.app.tabmodel.TabWindowManagerSingleton; import org.chromium.chrome.browser.app.tabmodel.TabbedModeTabModelOrchestrator; import org.chromium.chrome.browser.tab.MockTab; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabState; import org.chromium.chrome.browser.tab.TabStateExtractor; import org.chromium.chrome.browser.tab.WebContentsState; import org.chromium.chrome.browser.tabmodel.NextTabPolicy.NextTabPolicySupplier; import org.chromium.chrome.browser.tabmodel.TabPersistentStore.TabModelSelectorMetadata; import org.chromium.chrome.browser.tabmodel.TabPersistentStore.TabPersistentStoreObserver; import org.chromium.chrome.browser.tabpersistence.TabStateDirectory; import org.chromium.chrome.browser.tabpersistence.TabStateFileManager; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.util.browser.tabmodel.MockTabModel; import org.chromium.chrome.test.util.browser.tabmodel.MockTabModelSelector; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.url.GURL; import java.nio.ByteBuffer; /** * Tests for the tabbed-mode persisitence policy. * TODO: Consider turning this into a unit test after resolving the task involving disk I/O. */ @RunWith(ChromeJUnit4ClassRunner.class) public class TabbedModeTabPersistencePolicyTest { private static final WebContentsState WEB_CONTENTS_STATE = new WebContentsState(ByteBuffer.allocateDirect(100)); private TestTabModelDirectory mMockDirectory; private AdvancedMockContext mAppContext; private static final TabModelSelectorFactory sMockTabModelSelectorFactory = new TabModelSelectorFactory() { @Override public TabModelSelector buildSelector(Activity activity, TabCreatorManager tabCreatorManager, NextTabPolicySupplier nextTabPolicySupplier, int selectorIndex) { return new MockTabModelSelector(0, 0, null); } }; @Before public void setUp() throws Exception { TabWindowManagerSingleton.setTabModelSelectorFactoryForTesting( sMockTabModelSelectorFactory); mAppContext = new AdvancedMockContext(InstrumentationRegistry.getInstrumentation() .getTargetContext() .getApplicationContext()); ContextUtils.initApplicationContextForTests(mAppContext); mMockDirectory = new TestTabModelDirectory(mAppContext, "TabbedModeTabPersistencePolicyTest", TabStateDirectory.TABBED_MODE_DIRECTORY); TabStateDirectory.setBaseStateDirectoryForTests(mMockDirectory.getBaseDirectory()); } @After public void tearDown() { mMockDirectory.tearDown(); for (Activity activity : ApplicationStatus.getRunningActivities()) { activity.finishAndRemoveTask(); } TabWindowManagerSingleton.resetTabModelSelectorFactoryForTesting(); } private TabbedModeTabModelOrchestrator buildTestTabModelSelector( int[] normalTabIds, int[] incognitoTabIds) throws Exception { final CallbackHelper callbackSignal = new CallbackHelper(); final int callCount = callbackSignal.getCallCount(); MockTabModel.MockTabModelDelegate tabModelDelegate = new MockTabModel.MockTabModelDelegate() { @Override public Tab createTab(int id, boolean incognito) { Tab tab = new MockTab(id, incognito) { @Override public GURL getUrl() { return new GURL("https://www.google.com"); } }; return tab; } }; final MockTabModel normalTabModel = TestThreadUtils.runOnUiThreadBlocking( () -> new MockTabModel(false, tabModelDelegate)); final MockTabModel incognitoTabModel = TestThreadUtils.runOnUiThreadBlocking( () -> new MockTabModel(true, tabModelDelegate)); TabbedModeTabModelOrchestrator orchestrator = TestThreadUtils.runOnUiThreadBlocking(() -> { TabbedModeTabModelOrchestrator tmpOrchestrator = new TabbedModeTabModelOrchestrator(false); tmpOrchestrator.createTabModels(new ChromeTabbedActivity(), null, null, 0); TabModelSelector selector = tmpOrchestrator.getTabModelSelector(); ((MockTabModelSelector) selector) .initializeTabModels(normalTabModel, incognitoTabModel); return tmpOrchestrator; }); TabPersistentStore store = TestThreadUtils.runOnUiThreadBlocking(() -> { TabPersistentStore tmpStore = orchestrator.getTabPersistentStoreForTesting(); tmpStore.addObserver(new TabPersistentStoreObserver() { @Override public void onMetadataSavedAsynchronously(TabModelSelectorMetadata metadata) { callbackSignal.notifyCalled(); } }); return tmpStore; }); // Adding tabs results in writing to disk running on AsyncTasks. Run on the main thread // to turn the async operations + completion callback into a synchronous operation. InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { for (int tabId : normalTabIds) { addTabToSaveQueue(store, normalTabModel, normalTabModel.addTab(tabId)); } for (int tabId : incognitoTabIds) { addTabToSaveQueue(store, incognitoTabModel, incognitoTabModel.addTab(tabId)); } TabModelUtils.setIndex(normalTabModel, 0); TabModelUtils.setIndex(incognitoTabModel, 0); }); callbackSignal.waitForCallback(callCount); return orchestrator; } private void addTabToSaveQueue(TabPersistentStore store, TabModel tabModel, Tab tab) { TabState tabState = new TabState(); tabState.contentsState = WEB_CONTENTS_STATE; TabStateExtractor.setTabStateForTesting(tab.getId(), tabState); store.addTabToSaveQueue(tab); } /** * Test the cleanup task path that deletes all the persistent state files for an instance. * Ensure tabs not used by other instances only are collected for deletion. This may not * be a real scenario likey to happen. */ @Test @Feature("TabPersistentStore") @MediumTest public void testCleanupInstanceState() throws Throwable { Assert.assertNotNull(TabStateDirectory.getOrCreateBaseStateDirectory()); // Delete instance 1. Among the tabs (4, 6, 7) (12, 14, 19), only (4, 12, 14) // are not used by any other instances, therefore will be the target for cleanup. buildTestTabModelSelector(new int[] {3, 5, 7}, new int[] {11, 13, 17}); TabbedModeTabModelOrchestrator orchestrator1 = buildTestTabModelSelector(new int[] {4, 6, 7}, new int[] {12, 14, 19}); buildTestTabModelSelector(new int[] {6, 8, 9}, new int[] {15, 18, 19}); final int id = 1; TabPersistencePolicy policy = orchestrator1.getTabPersistentStoreForTesting().getTabPersistencePolicyForTesting(); final CallbackHelper callbackSignal = new CallbackHelper(); TestThreadUtils.runOnUiThreadBlocking(() -> { policy.cleanupInstanceState(id, (result) -> { Assert.assertThat(result, Matchers.containsInAnyOrder( TabStateFileManager.getTabStateFilename(4, false), TabStateFileManager.getTabStateFilename(12, true), TabStateFileManager.getTabStateFilename(14, true))); callbackSignal.notifyCalled(); }); }); callbackSignal.waitForCallback(0); } }
3,660
861
package cn.springcloud.gray.client.plugin.dynamiclogic.configuration; import cn.springcloud.gray.GrayManager; import com.fm.compiler.dynamicbean.DefaultDynamicBeanManager; import com.fm.compiler.dynamicbean.DynamicBeanManager; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author saleson * @date 2019-12-28 11:27 */ @Configuration @ConditionalOnBean(GrayManager.class) public class DynamicBeanAutoConfigration { @Bean public DynamicBeanManager dynamicBeanManager() { return new DefaultDynamicBeanManager(); } }
217
667
#import <UIKit/UIKit.h> @interface LoginViewController : UIViewController @property (strong, nonatomic) IBOutlet UITextField *email; @property (strong, nonatomic) IBOutlet UITextField *password; @property (strong, nonatomic) IBOutlet UIButton *loginButton; @property (nonatomic, retain) NSMutableArray *entryFields; - (IBAction) login: (id) sender; - (IBAction) about: (id)sender; @end
133
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.html.editor.hints.css; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.netbeans.modules.csl.api.Hint; import org.netbeans.modules.csl.api.HintFix; import org.netbeans.modules.csl.api.OffsetRange; import org.netbeans.modules.csl.api.Rule; import org.netbeans.modules.html.editor.hints.HtmlRuleContext; import org.openide.filesystems.FileObject; /** * * @author <EMAIL> */ public class MissingCssElement extends Hint { private final HintContext hintContext; private List<HintFix> computedFixes; public MissingCssElement(Rule rule, String msg, HtmlRuleContext context, OffsetRange range, HintContext hintContext) { super(rule, msg, context.getFile(), range, Collections.<HintFix>emptyList(), 10); this.hintContext = hintContext; } @Override public synchronized List<HintFix> getFixes() { if(computedFixes == null) { computedFixes = createFixes(); } return Collections.unmodifiableList(computedFixes); } private List<HintFix> createFixes() { List<HintFix> fixes = new ArrayList<>(); FileObject sourceFile = getFile(); if (hintContext.getElement2files().get(hintContext.getPureElementName()) != null) { //1) if the class is found in one of the stylesheets in the project: // * add "Import stylesheet" hintfix for (FileObject file : hintContext.getElement2files().get(hintContext.getPureElementName())) { fixes.add(new AddStylesheetLinkHintFix(sourceFile, file)); } } else { if(!hintContext.getAllStylesheets().isEmpty()) { //2) if the class is not found in any stylesheet from the project: // * add "create in xxx stylesheet" - for all available stylesheets. // The fix will add the stylesheet reference and create the rule there for (FileObject stylesheet : hintContext.getAllStylesheets()) { fixes.add(new CreateRuleInStylesheet( sourceFile, stylesheet, hintContext.getElementName(), !hintContext.getReferredFiles().contains(stylesheet), false)); } } else { //* 3) if there's no stylesheet in the project // * create in new stylesheet // Creates stylesheet 'styles.css' in the same folder, add ref to it and put the rule inside. fixes.add(new CreateRuleInStylesheet( sourceFile, null, hintContext.getElementName(), true, true)); } } return fixes; } }
1,659
762
import numpy as np from pymoo.algorithms.soo.nonconvex.ga import FitnessSurvival, GA from pymoo.docs import parse_doc_string from pymoo.core.survival import Survival from pymoo.operators.selection.tournament import compare, TournamentSelection from pymoo.util.clearing import EpsilonClearing from pymoo.util.display import SingleObjectiveDisplay from pymoo.util.misc import norm_eucl_dist from pymoo.util.termination.constr_violation import ConstraintViolationToleranceTermination from pymoo.util.termination.default import SingleObjectiveDefaultTermination, DefaultTermination from pymoo.util.termination.f_tol_single import SingleObjectiveSpaceToleranceTermination from pymoo.util.termination.x_tol import DesignSpaceToleranceTermination # ========================================================================================================= # Display # ========================================================================================================= class NicheDisplay(SingleObjectiveDisplay): def _do(self, problem, evaluator, algorithm): super()._do(problem, evaluator, algorithm) self.output.attrs = [e for e in self.output.attrs if e[0] != "favg"] self.output.append("n_niches", len(algorithm.opt), width=10) self.output.append("favg", algorithm.opt.get("F").mean(), width=12) # ========================================================================================================= # Termination # ========================================================================================================= class NicheSingleObjectiveSpaceToleranceTermination(SingleObjectiveSpaceToleranceTermination): def _store(self, algorithm): return algorithm.opt.get("F").mean() class NicheTermination(DefaultTermination): def __init__(self, x_tol=1e-32, cv_tol=1e-6, f_tol=1e-6, nth_gen=5, n_last=20, **kwargs) -> None: super().__init__(DesignSpaceToleranceTermination(tol=x_tol, n_last=n_last), ConstraintViolationToleranceTermination(tol=cv_tol, n_last=n_last), NicheSingleObjectiveSpaceToleranceTermination(tol=f_tol, n_last=n_last, nth_gen=nth_gen), **kwargs) # ========================================================================================================= # Selection # ========================================================================================================= def comp_by_cv_and_clearing_fitness(pop, P, **kwargs): S = np.full(P.shape[0], np.nan) for i in range(P.shape[0]): a, b = P[i, 0], P[i, 1] # if at least one solution is infeasible if pop[a].CV[0] > 0.0 or pop[b].CV[0] > 0.0: S[i] = compare(a, pop[a].CV, b, pop[b].CV, method='smaller_is_better', return_random_if_equal=True) # first compare by the round the individual was selected else: S[i] = compare(a, pop[a].get("iter"), b, pop[b].get("iter"), method='smaller_is_better') # if it was the same round - then use the rank of the fitness directly if np.isnan(S[i]): S[i] = compare(a, pop[a].get("rank"), b, pop[b].get("rank"), method='smaller_is_better', return_random_if_equal=True) return S[:, None].astype(int) # ========================================================================================================= # Survival # ========================================================================================================= class EpsilonClearingSurvival(Survival): def __init__(self, epsilon, n_max_each_iter=None, norm_by_dim=False) -> None: super().__init__(False) self.epsilon = epsilon self.n_max_each_iter = n_max_each_iter self.norm_by_dim = norm_by_dim def _do(self, problem, pop, n_survive, out=None, **kwargs): F = pop.get("F") if F.shape[1] != 1: raise ValueError("FitnessSurvival can only used for single objective single!") # this basically sorts the population by constraint and objective value pop = FitnessSurvival().do(problem, pop, n_survive=len(pop)) # calculate the distance from each individual to another - pre-processing for the clearing # NOTE: the distance is normalized by the maximum distance possible X = pop.get("X").astype(float) D = norm_eucl_dist(problem, X, X) if self.norm_by_dim: D = D / (problem.n_var ** 0.5) # initialize the clearing strategy clearing = EpsilonClearing(D, self.epsilon) # initialize the iteration and rank i the beginning iter, rank = 1, 1 # also solutions that have been found in the first iteration iter_one = None # until the number of selected individuals are less than expected survivors while len(clearing.selected()) < n_survive: # get all the remaining indices remaining = clearing.remaining() # if no individuals are left because of clearing - perform a reset if len(remaining) == 0 or (self.n_max_each_iter is not None and rank > self.n_max_each_iter): # reset and retrieve the newly available indices clearing.reset() remaining = clearing.remaining() # increase the iteration counter and start over from rank 1 iter += 1 rank = 1 # get the individual of the first iteration - needed for niche assignment iter_one = np.where(pop.get("iter") == 1)[0] if iter_one is None else iter_one # since the population is ordered by F and CV it is always the first index k = remaining[0] # set the attribute to the selected individual pop[k].set("iter", iter) pop[k].set("rank", rank) # in the first iteration set the niche counter for each solution equal to rank if iter == 1: pop[k].set("niche", rank) else: closest_iter_one = iter_one[D[k][iter_one].argmin()] niche = pop[closest_iter_one].get("niche") pop[k].set("niche", niche) clearing.select(k) rank += 1 # retrieve all individuals being selected S = clearing.selected() return pop[S] # ========================================================================================================= # Algorithm # ========================================================================================================= class NicheGA(GA): def __init__(self, pop_size=100, norm_niche_size=0.05, norm_by_dim=False, return_all_opt=False, display=NicheDisplay(), **kwargs): """ Parameters ---------- norm_niche_size : float The radius in which the clearing shall be performed. The clearing is performed in the normalized design space, e.g. 0.05 corresponds to clear all solutions which have less norm euclidean distance than 5%. pop_size : {pop_size} sampling : {sampling} selection : {selection} crossover : {crossover} mutation : {mutation} eliminate_duplicates : {eliminate_duplicates} n_offsprings : {n_offsprings} """ surv = kwargs.get("survival") if surv is None: surv = EpsilonClearingSurvival(norm_niche_size, n_max_each_iter=None, norm_by_dim=norm_by_dim) selection = kwargs.get("selection") if selection is None: selection = TournamentSelection(comp_by_cv_and_clearing_fitness) super().__init__(pop_size=pop_size, selection=selection, survival=surv, display=display, advance_after_initial_infill=True, **kwargs) # self.default_termination = NicheTermination() self.default_termination = SingleObjectiveDefaultTermination() # whether with rank one after clearing or just the best should be considered as optimal self.return_all_opt = return_all_opt def _set_optimum(self, **kwargs): if self.return_all_opt: self.opt = self.pop[self.pop.get("iter") == 1] else: super()._set_optimum() parse_doc_string(NicheGA.__init__)
3,467
313
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass from pathlib import Path from typing import Collection, List, Optional, Sequence, cast from libcst import Module from libcst.testing.utils import UnitTest from fixit.cli import LintOpts, map_paths from fixit.cli.args import LintWorkers from fixit.common.base import CstLintRule, LintConfig from fixit.common.report import ( BaseLintRuleReport, LintFailureReportBase, LintSuccessReportBase, ) from fixit.rule_lint_engine import lint_file @dataclass(frozen=True) class FakeLintSuccessReport(LintSuccessReportBase): path: str status: str reports: Collection[str] @staticmethod # pyre-fixme[14]: `create_reports` overrides method defined in # `LintSuccessReportBase` inconsistently. def create_reports( path: Path, reports: Collection[BaseLintRuleReport], global_list: List[str], ) -> Sequence["FakeLintSuccessReport"]: global_list.append(str(path)) return [FakeLintSuccessReport(str(path), "success", ["fake picklable report"])] @dataclass(frozen=True) class FakeLintFailureReport(LintFailureReportBase): path: str status: str reports: Collection[str] @staticmethod # pyre-fixme[14]: `create_reports` overrides method defined in # `LintFailureReportBase` inconsistently. def create_reports( path: Path, reports: Collection[BaseLintRuleReport], global_list: List[str], ) -> Sequence["FakeLintFailureReport"]: global_list.append(str(path)) return [FakeLintFailureReport(str(path), "failure", ["fake picklable report"])] class FakeRule(CstLintRule): def visit_Module(self, node: Module) -> None: self.report(node, "Dummy message") def mock_operation( path: Path, opts: LintOpts, _=None, ) -> Sequence[FakeLintSuccessReport]: results = opts.success_report.create_reports( path, lint_file(path, b"test", rules=opts.rules, config=LintConfig()), **opts.extra, ) return cast(Sequence[FakeLintSuccessReport], results) def generate_mock_lint_opt(global_list: Optional[List[str]] = None) -> LintOpts: if global_list is None: global_list = [] return LintOpts( {FakeRule}, FakeLintSuccessReport, FakeLintFailureReport, extra={"global_list": global_list}, ) class LintOptsTest(UnitTest): def setUp(self) -> None: self.global_list = [] self.opts = generate_mock_lint_opt(global_list=self.global_list) def test_extra_opts(self) -> None: path = "path.py" results = next( map_paths( mock_operation, [path], self.opts, workers=LintWorkers.USE_CURRENT_THREAD, ) ) # Assert global list has been modified as expected. self.assertEqual(list(self.global_list), [path]) # Assert the rest of the reporting functionality is as expected self.assertEqual(len(results), 1) self.assertEqual(results[0].reports, ["fake picklable report"]) def test_extra_opts_multiple_paths(self) -> None: paths = ["path1.py", "path2.py"] results_iter = map_paths( mock_operation, paths, self.opts, workers=LintWorkers.USE_CURRENT_THREAD ) results_count = 0 paths_reported = [] for results in results_iter: for result in results: results_count += 1 paths_reported.append(result.path) self.assertEqual(len(result.reports), 1) self.assertEqual(result.reports, ["fake picklable report"]) # Assert global list has been modified as expected. self.assertCountEqual(list(self.global_list), paths) # Assert all passed in paths have been visited as expected self.assertCountEqual(paths_reported, paths)
1,673
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/iPodUI.framework/iPodUI */ #import <iPodUI/XXUnknownSuperclass.h> #import <iPodUI/IUViewControllerContext.h> #import <iPodUI/NSCoding.h> @class MPMediaQuery, IUMediaEntitySpecifier, NSString, UIImage, IUMediaDataSource; @protocol NSObject; @interface IUViewControllerContext : XXUnknownSuperclass <NSCoding> { IUMediaDataSource *_dataSource; // 4 = 0x4 unsigned _isRootController : 1; // 8 = 0x8 unsigned _showActionRowsOnAppear : 1; // 8 = 0x8 IUMediaEntitySpecifier *_specifier; // 12 = 0xc MPMediaQuery *_query; // 16 = 0x10 IUViewControllerContext *_sourceContext; // 20 = 0x14 int _style; // 24 = 0x18 unsigned _titleIgnoresHistory : 1; // 28 = 0x1c int _type; // 32 = 0x20 id<NSObject, NSCoding> _viewControllerInfo; // 36 = 0x24 NSString *_defaultPNGNameOverride; // 40 = 0x28 UIImage *_transitionImage; // 44 = 0x2c } @property(retain, nonatomic) UIImage *transitionImage; // G=0x9f899; S=0x9f8a9; @synthesize=_transitionImage @property(readonly, assign, nonatomic) BOOL startAtEndOnFirstAppear; // G=0x9f529; @property(retain, nonatomic) IUViewControllerContext *sourceContext; // G=0x9f835; S=0x9f475; @synthesize=_sourceContext @property(readonly, assign, nonatomic) IUViewControllerContext *rootContext; // G=0x9f241; @property(assign, nonatomic) BOOL showActionRowsOnAppear; // G=0x9f205; S=0x9f219; @property(retain, nonatomic) id<NSObject, NSCoding> viewControllerInfo; // G=0x9f8cd; S=0x9f8dd; @synthesize=_viewControllerInfo @property(assign, nonatomic) BOOL titleIgnoresHistory; // G=0x9f515; S=0x9f4f1; @property(assign, nonatomic) int style; // G=0x9f879; S=0x9f889; @synthesize=_style @property(copy, nonatomic) MPMediaQuery *query; // G=0x9f801; S=0x9f811; @synthesize=_query @property(retain, nonatomic) IUMediaEntitySpecifier *specifier; // G=0x9f845; S=0x9f855; @synthesize=_specifier @property(retain, nonatomic) IUMediaDataSource *dataSource; // G=0x9f095; S=0x9f7dd; @synthesize=_dataSource @property(assign, nonatomic, getter=isRootController) BOOL rootController; // G=0x9f1f1; S=0x9f451; @property(retain, nonatomic) NSString *identifier; // G=0x9f125; S=0x9f369; @property(readonly, assign, nonatomic, getter=isRestorableNavigationPathNode) BOOL restorableNavigationPathNode; // G=0x9f195; @property(readonly, assign, nonatomic, getter=isArchivable) BOOL archivable; // G=0x9f145; @property(retain, nonatomic) NSString *defaultPNGName; // G=0x9e9e1; S=0x9ea15; + (id)contextWithDataSource:(id)dataSource; // 0x9e90d // declared property setter: - (void)setViewControllerInfo:(id)info; // 0x9f8dd // declared property getter: - (id)viewControllerInfo; // 0x9f8cd // declared property setter: - (void)setTransitionImage:(id)image; // 0x9f8a9 // declared property getter: - (id)transitionImage; // 0x9f899 // declared property setter: - (void)setStyle:(int)style; // 0x9f889 // declared property getter: - (int)style; // 0x9f879 // declared property setter: - (void)setSpecifier:(id)specifier; // 0x9f855 // declared property getter: - (id)specifier; // 0x9f845 // declared property getter: - (id)sourceContext; // 0x9f835 // declared property setter: - (void)setQuery:(id)query; // 0x9f811 // declared property getter: - (id)query; // 0x9f801 // declared property setter: - (void)setDataSource:(id)source; // 0x9f7dd - (void)_reloadDataSourceFromSourceContext; // 0x9f739 - (id)_newDataSourceFromType:(int)type mediaQuery:(id)query; // 0x9f649 - (id)_newDataSourceFromType:(int)type mediaSpecifier:(id)specifier; // 0x9f559 // declared property getter: - (BOOL)startAtEndOnFirstAppear; // 0x9f529 // declared property getter: - (BOOL)titleIgnoresHistory; // 0x9f515 // declared property setter: - (void)setTitleIgnoresHistory:(BOOL)history; // 0x9f4f1 // declared property setter: - (void)setSourceContext:(id)context; // 0x9f475 // declared property setter: - (void)setRootController:(BOOL)controller; // 0x9f451 // declared property setter: - (void)setIdentifier:(id)identifier; // 0x9f369 - (void)setDataSourceFromMediaQuery:(id)mediaQuery; // 0x9f2fd - (void)setDataSourceFromMediaSpecifier:(id)mediaSpecifier; // 0x9f291 - (void)unloadReloadableData; // 0x9f271 // declared property getter: - (id)rootContext; // 0x9f241 // declared property setter: - (void)setShowActionRowsOnAppear:(BOOL)appear; // 0x9f219 // declared property getter: - (BOOL)showActionRowsOnAppear; // 0x9f205 // declared property getter: - (BOOL)isRootController; // 0x9f1f1 // declared property getter: - (BOOL)isRestorableNavigationPathNode; // 0x9f195 // declared property getter: - (BOOL)isArchivable; // 0x9f145 // declared property getter: - (id)identifier; // 0x9f125 // declared property getter: - (id)dataSource; // 0x9f095 - (void)encodeWithCoder:(id)coder; // 0x9ee21 - (id)newViewController; // 0x9eb75 - (id)copySpecifierHistory; // 0x9ea55 // declared property setter: - (void)setDefaultPNGName:(id)name; // 0x9ea15 // declared property getter: - (id)defaultPNGName; // 0x9e9e1 - (id)description; // 0x9e971 - (void)dealloc; // 0x9e811 - (id)initWithCoder:(id)coder; // 0x9e5e1 @end @interface IUViewControllerContext (Additions) - (unsigned long long)persistentPlaylistUID; // 0x67cd @end
2,047
1,056
<reponame>Antholoj/netbeans /* * * * * * * * * * * * * * * * * */ package org.netbeans.test.editor.smartcompletion; /** * * */ public class Types { /** Creates a new instance of Types */ public Types() { } }
140
368
<filename>tools/rs-sysmon/plugins/dstat_utmp.py ### Author: <NAME> <<EMAIL>> class dstat_plugin(dstat): def __init__(self): self.name = 'utmp' self.nick = ('ses', 'usr', 'adm' ) self.vars = ('sessions', 'users', 'root') self.type = 'd' self.width = 3 self.scale = 10 def check(self): try: global utmp import utmp except: raise Exception, 'Needs python-utmp module' def extract(self): for name in self.vars: self.val[name] = 0 for u in utmp.UtmpRecord(): # print '# type:%s pid:%s line:%s id:%s user:%s host:%s session:%s' % (i.ut_type, i.ut_pid, i.ut_line, i.ut_id, i.ut_user, i.ut_host, i.ut_session) if u.ut_type == utmp.USER_PROCESS: self.val['users'] = self.val['users'] + 1 if u.ut_user == 'root': self.val['root'] = self.val['root'] + 1 self.val['sessions'] = self.val['sessions'] + 1 # vim:ts=4:sw=4:et
542
20,453
<gh_stars>1000+ """ Shim for _umath_tests to allow a deprecation period for the new name. """ import warnings # 2018-04-04, numpy 1.15.0 warnings.warn(("numpy.core.umath_tests is an internal NumPy " "module and should not be imported. It will " "be removed in a future NumPy release."), category=DeprecationWarning, stacklevel=2) from ._umath_tests import *
163
4,036
package com.semmle.js.ast.jsdoc; import com.semmle.js.ast.SourceLocation; /** A non-nullable type such as <code>!string</code>. */ public class NonNullableType extends UnaryTypeConstructor { public NonNullableType(SourceLocation loc, JSDocTypeExpression expression, Boolean prefix) { super(loc, "NonNullableType", expression, prefix, "!"); } @Override public void accept(Visitor v) { v.visit(this); } }
144
608
{ "name": "seemple-monorepo", "private": true, "version": "0.0.0-by-lerna", "description": "Seemple.js framework", "main": "seemple.js", "scripts": { "test": "npm run lint && npm run unit && cat ./packages/seemple/coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js", "post-publish-test": "node test/post-publish/post-publish.js", "unit": "npm run --prefix packages/seemple npm-compile && lerna run test", "build": "lerna run build", "lint": "eslint .", "commit": "git-cz", "deploy-to-git": "shx rm -rf bundle && deploy-to-git", "upgrade": "ncu -u && npm install", "reinstall": "rm -rf package-lock.json node_modules/ && npm i", "patch": "lerna run npm-compile && lerna version patch --yes && npm run npm-deploy", "minor": "lerna run npm-compile && lerna version minor && npm run npm-deploy", "install-all": "npm install && lerna exec --concurrency 1 -- npm install", "npm-deploy": "lerna publish from-package --yes --contents npm && npm run post-publish-test" }, "repository": { "type": "git", "url": "https://github.com/finom/seemple.git" }, "author": { "name": "<NAME>", "email": "<EMAIL>" }, "license": "MIT", "bugs": { "url": "https://github.com/finom/seemple/issues" }, "config": { "deployToGit": { "repository": "<EMAIL>:finom/seemple.git", "_repository": "https://[email protected]/finom/seemple.git", "branch": "gh-pages", "folder": "bundle", "script": "npm run build", "commit": "Deploy", "user": { "email": "<EMAIL>", "name": "<NAME> (his digital clone)" } }, "commitizen": { "path": "cz-simple-conventional-changelog" }, "validate-commit-msg": { "types": [ "feat", "fix", "refactor", "perf", "test", "chore", "revert" ] }, "ghooks": { "commit-msg": "validate-commit-msg" } }, "homepage": "https://github.com/finom/seemple#readme", "devDependencies": { "@babel/cli": "^7.8.3", "@babel/core": "^7.8.3", "@babel/node": "^7.8.3", "@babel/plugin-proposal-class-properties": "^7.8.3", "@babel/plugin-transform-runtime": "^7.8.3", "@babel/polyfill": "^7.8.3", "@babel/preset-env": "^7.8.3", "@babel/runtime": "^7.8.3", "app-module-path": "^2.2.0", "babel-core": "7.0.0-bridge.0", "babel-eslint": "^10.0.3", "babel-istanbul": "^0.12.2", "babel-istanbul-loader": "^0.1.0", "babel-loader": "^8.0.6", "commitizen": "^4.0.3", "copy-webpack-plugin": "^5.1.1", "coveralls": "^3.0.9", "cz-simple-conventional-changelog": "0.0.1", "deploy-to-git": "^0.1.5", "eslint": "^6.8.0", "eslint-config-airbnb-base": "^14.0.0", "eslint-loader": "^3.0.3", "eslint-plugin-import": "^2.20.0", "eslint-plugin-output-todo-comments": "0.0.7", "ghooks": "^2.0.4", "istanbul": "^1.1.0-alpha.1", "jasmine": "^3.5.0", "jasmine-core": "^3.5.0", "jasmine-spec-reporter": "^4.2.1", "jsdom": "^16.0.1", "lerna": "^3.20.2", "module-alias": "^2.2.2", "npm-check-updates": "^4.0.1", "npm-registry-client": "^8.6.0", "optimist": "^0.6.1", "shx": "^0.3.2", "uglifyjs-webpack-plugin": "^2.2.0", "unminified-webpack-plugin": "^2.0.0", "validate-commit-msg": "^2.14.0", "webidl-conversions": "^5.0.0", "webpack": "^4.41.5", "webpack-cli": "^3.3.10", "webpack-core": "^0.6.9", "word-wrap": "^1.2.3" }, "dependencies": { "expect.js": "^0.3.1" } }
1,814
2,039
<filename>tests/repositories/helpers/methods/test_registration.py import pytest @pytest.mark.asyncio async def test_registration(repository): await repository.async_pre_registration() await repository.async_post_registration()
81
374
#import <CFNetwork/CFSocketStream.h> #import <CFNetwork/CFHost.h> #import <CFNetwork/CFNetServices.h>
39
777
<filename>chrome/installer/setup/setup_singleton_unittest.cc // 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 "chrome/installer/setup/setup_singleton.h" #include <windows.h> #include <functional> #include <string> #include <vector> #include "base/command_line.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/test/multiprocess_test.h" #include "base/test/test_timeouts.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "chrome/installer/setup/installer_state.h" #include "chrome/installer/util/installation_state.h" #include "chrome/installer/util/master_preferences.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" namespace installer { namespace { constexpr char kInstallDirSwitch[] = "install-dir"; constexpr base::FilePath::CharType kSentinelFileName[] = FILE_PATH_LITERAL("sentinel.txt"); constexpr base::char16 kTestProcessReadyEventName[] = L"Local\\ChromeSetupSingletonTestProcessReady"; enum ErrorCode { SUCCESS, SETUP_SINGLETON_ACQUISITION_FAILED, SENTINEL_FILE_CREATE_ERROR, WAIT_RETURNED_FALSE, }; base::CommandLine GetDummyCommandLine() { return base::CommandLine(base::FilePath(FILE_PATH_LITERAL("dummy.exe"))); } base::string16 HashFilePath(const base::FilePath& path) { return base::SizeTToString16( std::hash<base::FilePath::StringType>()(path.value())); } ErrorCode CreateAndDeleteSentinelFile(const base::FilePath& install_dir) { const base::FilePath sentinel_file_path = install_dir.Append(kSentinelFileName); base::File file(sentinel_file_path, base::File::FLAG_CREATE | base::File::FLAG_WRITE | base::File::FLAG_DELETE_ON_CLOSE); if (!file.IsValid()) return SENTINEL_FILE_CREATE_ERROR; base::PlatformThread::Sleep(TestTimeouts::tiny_timeout()); return SUCCESS; } MULTIPROCESS_TEST_MAIN(SetupSingletonTestExclusiveAccessProcessMain) { base::CommandLine* const command_line = base::CommandLine::ForCurrentProcess(); const base::FilePath install_dir = command_line->GetSwitchValuePath(kInstallDirSwitch); InstallationState original_state; InstallerState installer_state; installer_state.set_target_path_for_testing(install_dir); // Acquire the exclusive right to modify the Chrome installation. std::unique_ptr<SetupSingleton> setup_singleton(SetupSingleton::Acquire( GetDummyCommandLine(), MasterPreferences::ForCurrentProcess(), &original_state, &installer_state)); if (!setup_singleton) return SETUP_SINGLETON_ACQUISITION_FAILED; // Create a sentinel file and delete it after a few milliseconds. This will // fail if the sentinel file already exists (which shouldn't be the case since // we are in the scope of a SetupSingleton). return CreateAndDeleteSentinelFile(install_dir); } MULTIPROCESS_TEST_MAIN(SetupSingletonTestWaitForInterruptProcessMain) { base::CommandLine* const command_line = base::CommandLine::ForCurrentProcess(); const base::FilePath install_dir = command_line->GetSwitchValuePath(kInstallDirSwitch); InstallationState original_state; InstallerState installer_state; installer_state.set_target_path_for_testing(install_dir); // Acquire the exclusive right to modify the Chrome installation. std::unique_ptr<SetupSingleton> setup_singleton(SetupSingleton::Acquire( GetDummyCommandLine(), MasterPreferences::ForCurrentProcess(), &original_state, &installer_state)); if (!setup_singleton) return SETUP_SINGLETON_ACQUISITION_FAILED; // Signal an event to indicate that this process has acquired the // SetupSingleton. base::WaitableEvent ready_event(base::win::ScopedHandle(::CreateEvent( nullptr, FALSE, FALSE, (kTestProcessReadyEventName + HashFilePath(install_dir)).c_str()))); ready_event.Signal(); // Wait indefinitely. This should only return when another SetupSingleton is // instantiated for |install_dir|. if (!setup_singleton->WaitForInterrupt(base::TimeDelta::Max())) return WAIT_RETURNED_FALSE; // Create a sentinel file and delete it after a few milliseconds. This will // fail if the sentinel file already exists (which shouldn't be the case since // we are in the scope of a SetupSingleton). return CreateAndDeleteSentinelFile(install_dir); } class SetupSingletonTest : public base::MultiProcessTest { public: SetupSingletonTest() = default; void SetUp() override { ASSERT_TRUE(install_dir_.CreateUniqueTempDir()); } base::CommandLine MakeCmdLine(const std::string& procname) override { base::CommandLine command_line = base::MultiProcessTest::MakeCmdLine(procname); command_line.AppendSwitchPath(kInstallDirSwitch, install_dir_path()); return command_line; } base::Process SpawnChildProcess(const std::string& process_name) { base::LaunchOptions options; options.start_hidden = true; return SpawnChildWithOptions(process_name, options); } const base::FilePath& install_dir_path() const { return install_dir_.GetPath(); } private: base::ScopedTempDir install_dir_; DISALLOW_COPY_AND_ASSIGN(SetupSingletonTest); }; } // namespace // Verify that a single SetupSingleton can be active at a time for a given // Chrome installation. TEST_F(SetupSingletonTest, ExclusiveAccess) { constexpr int kNumProcesses = 10; std::vector<base::Process> processes; for (int i = 0; i < kNumProcesses; ++i) { processes.push_back( SpawnChildProcess("SetupSingletonTestExclusiveAccessProcessMain")); } for (base::Process& process : processes) { int exit_code = 0; EXPECT_TRUE(process.WaitForExit(&exit_code)); EXPECT_EQ(SUCCESS, exit_code); } } // Verify that WaitForInterrupt() returns false when its delay expires before TEST_F(SetupSingletonTest, WaitForInterruptNoInterrupt) { InstallationState original_state; InstallerState installer_state; installer_state.set_target_path_for_testing(install_dir_path()); std::unique_ptr<SetupSingleton> setup_singleton(SetupSingleton::Acquire( GetDummyCommandLine(), MasterPreferences::ForCurrentProcess(), &original_state, &installer_state)); ASSERT_TRUE(setup_singleton); EXPECT_FALSE(setup_singleton->WaitForInterrupt(TestTimeouts::tiny_timeout())); } // Verify that WaitForInterrupt() returns true immediately when another process // tries to acquire a SetupSingleton. TEST_F(SetupSingletonTest, WaitForInterruptWithInterrupt) { base::Process wait_process = SpawnChildProcess("SetupSingletonTestWaitForInterruptProcessMain"); // Wait until the other process acquires the SetupSingleton. base::WaitableEvent ready_event(base::win::ScopedHandle(::CreateEvent( nullptr, FALSE, FALSE, (kTestProcessReadyEventName + HashFilePath(install_dir_path())) .c_str()))); ready_event.Wait(); // Acquire the SetupSingleton. InstallationState original_state; InstallerState installer_state; installer_state.set_target_path_for_testing(install_dir_path()); std::unique_ptr<SetupSingleton> setup_singleton(SetupSingleton::Acquire( GetDummyCommandLine(), MasterPreferences::ForCurrentProcess(), &original_state, &installer_state)); ASSERT_TRUE(setup_singleton); // Create a sentinel file and delete it after a few milliseconds. This will // fail if the sentinel file already exists (which shouldn't be the case since // we are in the scope of a SetupSingleton). EXPECT_EQ(SUCCESS, CreateAndDeleteSentinelFile(install_dir_path())); // Join |wait_process|. int exit_code = 0; EXPECT_TRUE(wait_process.WaitForExit(&exit_code)); EXPECT_EQ(SUCCESS, exit_code); } } // namespace installer
2,663
619
<filename>src/biss0001/biss0001.hpp<gh_stars>100-1000 /* * Author: <NAME> <<EMAIL>> * <NAME> <<EMAIL>> * Copyright (c) 2014-2016 Intel Corporation. * * This program and the accompanying materials are made available under the * terms of the The MIT License which is available at * https://opensource.org/licenses/MIT. * * SPDX-License-Identifier: MIT */ #pragma once #include <interfaces/iMotion.hpp> #include <biss0001.h> #include <mraa/initio.hpp> namespace upm { /** * @brief BISS0001 Motion Sensor * @defgroup biss0001 libupm-biss0001 * @ingroup seeed gpio light tsk */ /** * @library biss0001 * @sensor biss0001 * @comname Passive Infrared (PIR) Motion Sensor * @altname Grove PIR Motion Sensor * @type light * @man seeed * @web http://www.seeedstudio.com/depot/Grove-PIR-Motion-Sensor-p-802.html * @con gpio * @kit tsk * * @brief API for the BISS0001 Motion Sensor * * PIR sensors allow you to sense motion, almost always used to detect * whether a human has moved in or out of the sensors range. They are * small, inexpensive, low-power, easy to use and don't wear out. For that * reason they are commonly found in appliances and gadgets used in homes * or businesses. They are often referred to as PIR, "Passive Infrared", * "Pyroelectric", or "IR motion" sensors. * * @image html biss0001.jpg * @snippet biss0001.cxx Interesting */ class BISS0001 : virtual public iMotion { public: /** * BISS0001 motion sensor constructor * * @param pin Digital pin to use */ BISS0001(unsigned int pin); /** * Instantiates BISS0001 Motion Sensor object based on a given string. * * @param initStr string containing specific information for BISS0001 initialization. */ BISS0001(std::string initStr); /** * BISS0001 destructor */ ~BISS0001(); /** * Gets the motion value from the sensor. * * @return true if motion was detected, false otherwise. */ bool value(); /** * Gets the motion value from the sensor. This is a more * informative method name, but we want to keep compatibility * with the original for now. Implements iMotion interface. * * @return true if motion was detected, false otherwise. */ virtual bool motionDetected(); private: /* Disable implicit copy and assignment operators */ BISS0001(const BISS0001&) = delete; BISS0001 &operator=(const BISS0001&) = delete; biss0001_context m_biss0001; mraa::MraaIo mraaIo; }; }
1,055
590
/*! @file @author <NAME> @date 07/2012 */ #include "Precompiled.h" #include "DataListBaseControl.h" #include "CommandManager.h" #include "DialogManager.h" #include "MessageBoxManager.h" #include "DataManager.h" #include "ActionManager.h" #include "ActionCreateData.h" #include "ActionCloneData.h" #include "ActionDestroyData.h" #include "ActionRenameData.h" #include "ActionChangePositionData.h" #include "PropertyUtility.h" #include "DataUtility.h" namespace tools { DataListBaseControl::DataListBaseControl() : mListBoxControl(nullptr) { } void DataListBaseControl::OnInitialise(Control* _parent, MyGUI::Widget* _place, const std::string& _layoutName) { Control::OnInitialise(_parent, _place, _layoutName); mListBoxControl = findControl<ListBoxDataControl>(); if (mListBoxControl != nullptr) { mListBoxControl->setEnableChangePosition(true); mListBoxControl->eventChangePosition.connect(this, &DataListBaseControl::notifyChangePosition); mListBoxControl->eventChangeName.connect(this, &DataListBaseControl::notifyChangeName); } } bool DataListBaseControl::checkCommand(bool _result) { if (_result) return false; if (DialogManager::getInstance().getAnyDialog()) return false; if (MessageBoxManager::getInstance().hasAny()) return false; return true; } void DataListBaseControl::commandCreateData(const MyGUI::UString& _commandName, bool& _result) { if (!checkCommand(_result)) return; DataPtr data = DataUtility::getSelectedDataByType(mParentType); if (data != nullptr) { ActionCreateData* command = new ActionCreateData(); command->setType(mCurrentType); command->setParent(data); command->setUniqueProperty(mPropertyForUnique); ActionManager::getInstance().doAction(command); } _result = true; } void DataListBaseControl::commandCloneData(const MyGUI::UString& _commandName, bool& _result) { if (!checkCommand(_result)) return; DataPtr data = DataUtility::getSelectedDataByType(mCurrentType); if (data != nullptr) { ActionCloneData* command = new ActionCloneData(); command->setPrototype(data); command->setUniqueProperty(mPropertyForUnique); ActionManager::getInstance().doAction(command); } _result = true; } void DataListBaseControl::commandDestroyData(const MyGUI::UString& _commandName, bool& _result) { if (!checkCommand(_result)) return; DataPtr data = DataUtility::getSelectedDataByType(mCurrentType); if (data != nullptr) { ActionDestroyData* command = new ActionDestroyData(); command->setData(data); command->setUniqueProperty(mPropertyForUnique); ActionManager::getInstance().doAction(command); } _result = true; } void DataListBaseControl::commandRenameData(const MyGUI::UString& _commandName, bool& _result) { if (!checkCommand(_result)) return; if (mListBoxControl != nullptr) mListBoxControl->OnRenameData(); _result = true; } void DataListBaseControl::setDataInfo(const std::string& _parentType, const std::string& _currentType, const std::string& _propertyName, const std::string& _propertyUnique) { mParentType = _parentType; mCurrentType = _currentType; mPropertyForName = _propertyName; mPropertyForUnique = _propertyUnique; if (mListBoxControl != nullptr) { mListBoxControl->setDataInfo(mParentType, mCurrentType, mPropertyForName); if (!mPropertyForUnique.empty()) mListBoxControl->addPropertyNameEnabled(mPropertyForUnique); } } void DataListBaseControl::notifyChangePosition(DataPtr _data1, DataPtr _data2) { ActionChangePositionData* command = new ActionChangePositionData(); command->setData1(_data1); command->setData2(_data2); ActionManager::getInstance().doAction(command); } void DataListBaseControl::notifyChangeName(DataPtr _data, const std::string& _name) { PropertyUtility::executeAction(_data->getProperty(mPropertyForName), _name); } const std::string& DataListBaseControl::getParentType() const { return mParentType; } const std::string& DataListBaseControl::getCurrentType() const { return mCurrentType; } const std::string& DataListBaseControl::getPropertyForUnique() const { return mPropertyForUnique; } }
1,441
1,844
<filename>usage/src/main/java/org/killbill/billing/usage/api/user/DefaultRolledUpUsage.java /* * Copyright 2010-2013 Ning, Inc. * * Ning 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.killbill.billing.usage.api.user; import java.util.List; import java.util.UUID; import org.joda.time.LocalDate; import org.killbill.billing.usage.api.RolledUpUnit; import org.killbill.billing.usage.api.RolledUpUsage; public class DefaultRolledUpUsage implements RolledUpUsage { private final UUID subscriptionId; private final LocalDate startDate; private final LocalDate endDate; private final List<RolledUpUnit> rolledUpUnits; public DefaultRolledUpUsage(final UUID subscriptionId, final LocalDate startDate, final LocalDate endDate, final List<RolledUpUnit> rolledUpUnits) { this.subscriptionId = subscriptionId; this.startDate = startDate; this.endDate = endDate; this.rolledUpUnits = rolledUpUnits; } @Override public UUID getSubscriptionId() { return subscriptionId; } @Override public LocalDate getStart() { return startDate; } @Override public LocalDate getEnd() { return endDate; } @Override public List<RolledUpUnit> getRolledUpUnits() { return rolledUpUnits; } }
616
1,408
package com.pancm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; /** * * @Title: Application * @Description: springBoot task主程序 异步调用测试 EnableAsync: 开启异步调用,异步调用的方法只需加上@Async注解即可, 一般放到启动类中,需要注意的是@Async所修饰的函数不要定义为static类型,这样异步调用不会生效 * @Version:1.0.0 * @author pancm * @date 2018年1月5日 */ @EnableAsync @SpringBootApplication public class Application { private static final Logger logger = LoggerFactory.getLogger(Application.class); /* * SpringApplication 则是用于从main方法启动Spring应用的类。默认,它会执行以下步骤: * 1.创建一个合适的ApplicationContext实例 (取决于classpath)。 * 2.注册一个CommandLinePropertySource,以便将命令行参数作为Spring properties。 3.刷新application * context,加载所有单例beans。 4.激活所有CommandLineRunner beans。 */ public static void main(String[] args) { // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件 SpringApplication.run(Application.class, args); logger.info("程序启动成功!"); } }
637
5,169
{ "name": "BCCommonModule", "version": "0.0.6", "summary": "樊登读书 公共模块", "description": "\"樊登读书\"", "homepage": "https://github.com/developeryh/BCCommonModule", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "developeyh": "<EMAIL>" }, "platforms": { "ios": "9.0" }, "source": { "git": "http://gitlab.dushuclub.io/youhui/bccommonmodule.git", "tag": "0.0.6" }, "source_files": "BCCommonModule/Common/BCCommon.h", "public_header_files": "BCCommonModule/Common/BCCommon.h", "requires_arc": true, "dependencies": { "SDWebImage": [ "4.3.3" ], "Masonry": [ "1.1.0" ], "GrowingAutoTrackKit": [ "2.8.0.1" ], "GrowingCoreKit": [ "2.8.0.1" ] }, "frameworks": [ "UIKit", "Foundation" ], "subspecs": [ { "name": "UI", "dependencies": { "SDWebImage": [ "4.3.3" ], "BCCommonModule/Category": [ ], "BCCommonModule/Macro": [ ], "GrowingAutoTrackKit": [ "2.8.0.1" ], "GrowingCoreKit": [ "2.8.0.1" ] }, "frameworks": [ "UIKit", "Foundation" ], "source_files": "BCCommonModule/Common/UI/**/*.{h,m}", "public_header_files": "BCCommonModule/Common/UI/**/*.h" }, { "name": "Cache", "source_files": "BCCommonModule/Common/Cache/*.{h,m}", "public_header_files": "BCCommonModule/Common/Cache/*.h" }, { "name": "Category", "source_files": "BCCommonModule/Common/Category/*.{h,m}", "public_header_files": "BCCommonModule/Common/Category/*.h" }, { "name": "Config", "source_files": "BCCommonModule/Common/Config/*.{h,m}", "public_header_files": "BCCommonModule/Common/Config/*.h" }, { "name": "Notification", "source_files": "BCCommonModule/Common/Notification/*.{h,m}", "public_header_files": "BCCommonModule/Common/Notification/*.h" }, { "name": "Parse", "source_files": "BCCommonModule/Common/Parse/*.{h,m}", "public_header_files": "BCCommonModule/Common/Parse/*.h" }, { "name": "Timer", "source_files": "BCCommonModule/Common/Timer/*.{h,m}", "public_header_files": "BCCommonModule/Common/Timer/*.h" }, { "name": "Macro", "source_files": "BCCommonModule/Common/Macro/*.h", "public_header_files": "BCCommonModule/Common/Macro/*.h" } ] }
1,271
1,059
<filename>sample/src/main/java/com/inforoeste/mocklocationdetector/sample/MainActivity.java package com.inforoeste.mocklocationdetector.sample; import android.location.Location; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.inforoeste.mocklocationdetector.MockLocationDetector; import java.text.DateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private GoogleApiClient mGoogleApiClient; private Location mCurrentLocation; private String mLastUpdateTime; private TextView mLatitudeTextView; private TextView mLongitudeTextView; private TextView mLastUpdateTimeTextView; private TextView mIsMockTextView; private TextView mAreMockLocationAppsPresentTextView; private TextView mIsMockLocationsOnTextView; private LocationRequest mLocationRequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLatitudeTextView = (TextView) findViewById(R.id.txt_location_latitude); mLongitudeTextView = (TextView) findViewById(R.id.txt_location_longitude); mLastUpdateTimeTextView = (TextView) findViewById(R.id.txt_location_last_update_time); mIsMockTextView = (TextView) findViewById(R.id.txt_is_mock_text); mAreMockLocationAppsPresentTextView = (TextView) findViewById(R.id.txt_are_mock_location_apps_present); mIsMockLocationsOnTextView = (TextView) findViewById(R.id.txt_is_allow_mock_locations_on); // Create an instance of GoogleAPIClient. if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } } protected void onStart() { mGoogleApiClient.connect(); super.onStart(); } protected void onStop() { stopLocationUpdates(); mGoogleApiClient.disconnect(); super.onStop(); } protected void stopLocationUpdates() { LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, this); } @Override public void onConnected(Bundle connectionHint) { createLocationRequest(); startLocationUpdates(); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } protected void createLocationRequest() { mLocationRequest = new LocationRequest(); // mLocationRequest.setInterval(10000); // mLocationRequest.setFastestInterval(5000); mLocationRequest.setInterval(2000); mLocationRequest.setFastestInterval(1000); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } protected void startLocationUpdates() { LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this); } @Override public void onLocationChanged(Location location) { mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateUI(); } private void updateUI() { mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude())); mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude())); mLastUpdateTimeTextView.setText(mLastUpdateTime); boolean isMock = MockLocationDetector.isLocationFromMockProvider(this, mCurrentLocation); mIsMockTextView.setText(String.valueOf(isMock)); if (isMock) { mIsMockTextView.setTextColor(ContextCompat.getColor(this, R.color.c_red)); } else { mIsMockTextView.setTextColor(ContextCompat.getColor(this, R.color.c_green)); } boolean mockLocationAppsPresent = MockLocationDetector.checkForAllowMockLocationsApps(this); mAreMockLocationAppsPresentTextView.setText(String.valueOf(mockLocationAppsPresent)); if (mockLocationAppsPresent) { mAreMockLocationAppsPresentTextView.setTextColor(ContextCompat.getColor(this, R.color.c_red)); } else { mAreMockLocationAppsPresentTextView.setTextColor(ContextCompat.getColor(this, R.color.c_green)); } boolean isAllowMockLocationsON = MockLocationDetector.isAllowMockLocationsOn(this); mIsMockLocationsOnTextView.setText(String.valueOf(isAllowMockLocationsON)); if (isAllowMockLocationsON) { mIsMockLocationsOnTextView.setTextColor(ContextCompat.getColor(this, R.color.c_red)); } else { mIsMockLocationsOnTextView.setTextColor(ContextCompat.getColor(this, R.color.c_green)); } } }
2,091
1,278
package de.komoot.photon.nominatim; import com.google.common.collect.ImmutableList; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.linearref.LengthIndexedLine; import de.komoot.photon.PhotonDoc; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A Nominatim result consisting of the basic PhotonDoc for the object * and a map of attached house numbers together with their respective positions. */ class NominatimResult { private PhotonDoc doc; private Map<String, Point> housenumbers; public NominatimResult(PhotonDoc baseobj) { doc = baseobj; housenumbers = null; } PhotonDoc getBaseDoc() { return doc; } boolean isUsefulForIndex() { return (housenumbers != null && !housenumbers.isEmpty()) || doc.isUsefulForIndex(); } List<PhotonDoc> getDocsWithHousenumber() { if (housenumbers == null || housenumbers.isEmpty()) { return ImmutableList.of(doc); } List<PhotonDoc> results = new ArrayList<>(housenumbers.size()); for (Map.Entry<String, Point> e : housenumbers.entrySet()) { PhotonDoc copy = new PhotonDoc(doc); copy.houseNumber(e.getKey()); copy.centroid(e.getValue()); results.add(copy); } return results; } /** * Adds house numbers from a house number string. * <p> * This may either be a single house number or multiple * house numbers delimited by a semicolon. All locations * will be set to the centroid of the doc geometry. * * @param str House number string. May be null, in which case nothing is added. */ public void addHousenumbersFromString(String str) { if (str == null || str.isEmpty()) return; if (housenumbers == null) housenumbers = new HashMap<>(); String[] parts = str.split(";"); for (String part : parts) { String h = part.trim(); if (!h.isEmpty()) housenumbers.put(h, doc.getCentroid()); } } public void addHousenumbersFromAddress(Map<String, String> address) { if (address == null) { return; } addHousenumbersFromString(address.get("housenumber")); addHousenumbersFromString(address.get("streetnumber")); addHousenumbersFromString(address.get("conscriptionnumber")); } public void addHouseNumbersFromInterpolation(long first, long last, String interpoltype, Geometry geom) { if (last <= first || (last - first) > 1000) return; if (housenumbers == null) housenumbers = new HashMap<>(); LengthIndexedLine line = new LengthIndexedLine(geom); double si = line.getStartIndex(); double ei = line.getEndIndex(); double lstep = (ei - si) / (double) (last - first); // leave out first and last, they have a distinct OSM node that is already indexed long step = 2; long num = 1; if (interpoltype.equals("odd")) { if (first % 2 == 1) ++num; } else if (interpoltype.equals("even")) { if (first % 2 == 0) ++num; } else { step = 1; } GeometryFactory fac = geom.getFactory(); for (; first + num < last; num += step) { housenumbers.put(String.valueOf(num + first), fac.createPoint(line.extractPoint(si + lstep * num))); } } }
1,563
462
<reponame>backwardn/ccs-calendarserver<gh_stars>100-1000 ## # Copyright (c) 2012-2017 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## """ Directory tools """ __all__ = [ "findRecords", "recordInfo", "recordBasicInfo", "recordGroupMembershipInfo", "recordProxyAccessInfo", ] import operator from twisted.internet.defer import succeed from twisted.internet.defer import inlineCallbacks, returnValue from calendarserver.tools.tables import Table @inlineCallbacks def findRecords(directory, terms): records = tuple((yield directory.recordsMatchingTokens(terms))) returnValue(sorted(records, key=operator.attrgetter("fullName"))) @inlineCallbacks def recordInfo(directory, record): """ Complete record information. """ info = [] def add(name, subInfo): if subInfo: info.append("%s:" % (name,)) info.append(subInfo) add("Directory record", (yield recordBasicInfo(directory, record))) add("Group memberships", (yield recordGroupMembershipInfo(directory, record))) add("Proxy access", (yield recordProxyAccessInfo(directory, record))) returnValue("\n".join(info)) def recordBasicInfo(directory, record): """ Basic information for a record. """ table = Table() def add(name, value): if value: table.addRow((name, value)) add("Service", record.service) add("Record Type", record.recordType) for shortName in record.shortNames: add("Short Name", shortName) add("GUID", record.guid) add("Full Name", record.fullName) add("First Name", record.firstName) add("Last Name", record.lastName) try: for email in record.emailAddresses: add("Email Address", email) except AttributeError: pass try: for cua in record.calendarUserAddresses: add("Calendar User Address", cua) except AttributeError: pass add("Server ID", record.serverID) add("Enabled", record.enabled) add("Enabled for Calendar", record.hasCalendars) add("Enabled for Contacts", record.hasContacts) return succeed(table.toString()) def recordGroupMembershipInfo(directory, record): """ Group membership info for a record. """ rows = [] for group in record.groups(): rows.append((group.uid, group.shortNames[0], group.fullName)) if not rows: return succeed(None) rows = sorted( rows, key=lambda row: (row[1], row[2]) ) table = Table() table.addHeader(("UID", "Short Name", "Full Name")) for row in rows: table.addRow(row) return succeed(table.toString()) @inlineCallbacks def recordProxyAccessInfo(directory, record): """ Group membership info for a record. """ # FIXME: This proxy finding logic should be in DirectoryRecord. def meAndMyGroups(record=record, groups=set((record,))): for group in record.groups(): groups.add(group) meAndMyGroups(group, groups) return groups # FIXME: This module global is really gross. from twistedcaldav.directory.calendaruserproxy import ProxyDBService rows = [] proxyInfoSeen = set() for record in meAndMyGroups(): proxyUIDs = (yield ProxyDBService.getMemberships(record.uid)) for proxyUID in proxyUIDs: # These are of the form: F153A05B-FF27-4B6C-BD6D-D1239D0082B0#calendar-proxy-read # I don't know how to get DirectoryRecord objects for the proxyUID here, so, let's cheat for now. proxyUID, proxyType = proxyUID.split("#") if (proxyUID, proxyType) not in proxyInfoSeen: proxyRecord = yield directory.recordWithUID(proxyUID) rows.append((proxyUID, proxyRecord.recordType, proxyRecord.shortNames[0], proxyRecord.fullName, proxyType)) proxyInfoSeen.add((proxyUID, proxyType)) if not rows: returnValue(None) rows = sorted( rows, key=lambda row: (row[1], row[2], row[4]) ) table = Table() table.addHeader(("UID", "Record Type", "Short Name", "Full Name", "Access")) for row in rows: table.addRow(row) returnValue(table.toString()) def summarizeRecords(directory, records): table = Table() table.addHeader(( "UID", "Record Type", "Short Names", "Email Addresses", "Full Name", )) def formatItems(items): if items: return ", ".join(items) else: return None for record in records: table.addRow(( record.uid, record.recordType, formatItems(record.shortNames), formatItems(record.emailAddresses), record.fullName, )) if table.rows: return succeed(table.toString()) else: return succeed(None)
2,100
2,757
<reponame>CEOALT1/RefindPlusUDK #ifndef Py_METAGRAMMAR_H #define Py_METAGRAMMAR_H #ifdef __cplusplus extern "C" { #endif #define MSTART 256 #define RULE 257 #define RHS 258 #define ALT 259 #define ITEM 260 #define ATOM 261 #ifdef __cplusplus } #endif #endif /* !Py_METAGRAMMAR_H */
142
5,035
#include "requestData.h" #include "epoll.h" #include "threadpool.h" #include "util.h" #include <sys/epoll.h> #include <queue> #include <sys/time.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> #include <cstdlib> #include <iostream> #include <vector> #include <unistd.h> using namespace std; const int THREADPOOL_THREAD_NUM = 4; const int QUEUE_SIZE = 65535; const int PORT = 8888; const int ASK_STATIC_FILE = 1; const int ASK_IMAGE_STITCH = 2; const string PATH = "/"; const int TIMER_TIME_OUT = 500; extern struct epoll_event* events; void acceptConnection(int listen_fd, int epoll_fd, const string &path); extern priority_queue<mytimer*, deque<mytimer*>, timerCmp> myTimerQueue; int socket_bind_listen(int port) { // 检查port值,取正确区间范围 if (port < 1024 || port > 65535) return -1; // 创建socket(IPv4 + TCP),返回监听描述符 int listen_fd = 0; if((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) return -1; // 消除bind时"Address already in use"错误 int optval = 1; if(setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1) return -1; // 设置服务器IP和Port,和监听描述副绑定 struct sockaddr_in server_addr; bzero((char*)&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons((unsigned short)port); if(bind(listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) return -1; // 开始监听,最大等待队列长为LISTENQ if(listen(listen_fd, LISTENQ) == -1) return -1; // 无效监听描述符 if(listen_fd == -1) { close(listen_fd); return -1; } return listen_fd; } void myHandler(void *args) { requestData *req_data = (requestData*)args; req_data->handleRequest(); } void acceptConnection(int listen_fd, int epoll_fd, const string &path) { struct sockaddr_in client_addr; memset(&client_addr, 0, sizeof(struct sockaddr_in)); socklen_t client_addr_len = 0; int accept_fd = 0; while((accept_fd = accept(listen_fd, (struct sockaddr*)&client_addr, &client_addr_len)) > 0) { /* // TCP的保活机制默认是关闭的 int optval = 0; socklen_t len_optval = 4; getsockopt(accept_fd, SOL_SOCKET, SO_KEEPALIVE, &optval, &len_optval); cout << "optval ==" << optval << endl; */ // 设为非阻塞模式 int ret = setSocketNonBlocking(accept_fd); if (ret < 0) { perror("Set non block failed!"); return; } requestData *req_info = new requestData(epoll_fd, accept_fd, path); // 文件描述符可以读,边缘触发(Edge Triggered)模式,保证一个socket连接在任一时刻只被一个线程处理 __uint32_t _epo_event = EPOLLIN | EPOLLET | EPOLLONESHOT; epoll_add(epoll_fd, accept_fd, static_cast<void*>(req_info), _epo_event); // 新增时间信息 mytimer *mtimer = new mytimer(req_info, TIMER_TIME_OUT); req_info->addTimer(mtimer); MutexLockGuard(); myTimerQueue.push(mtimer); } //if(accept_fd == -1) // perror("accept"); } // 分发处理函数 void handle_events(int epoll_fd, int listen_fd, struct epoll_event* events, int events_num, const string &path, threadpool_t* tp) { for(int i = 0; i < events_num; i++) { // 获取有事件产生的描述符 requestData* request = (requestData*)(events[i].data.ptr); int fd = request->getFd(); // 有事件发生的描述符为监听描述符 if(fd == listen_fd) { //cout << "This is listen_fd" << endl; acceptConnection(listen_fd, epoll_fd, path); } else { // 排除错误事件 if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN))) { printf("error event\n"); delete request; continue; } // 将请求任务加入到线程池中 // 加入线程池之前将Timer和request分离 request->seperateTimer(); int rc = threadpool_add(tp, myHandler, events[i].data.ptr, 0); } } } /* 处理逻辑是这样的~ 因为(1) 优先队列不支持随机访问 (2) 即使支持,随机删除某节点后破坏了堆的结构,需要重新更新堆结构。 所以对于被置为deleted的时间节点,会延迟到它(1)超时 或 (2)它前面的节点都被删除时,它才会被删除。 一个点被置为deleted,它最迟会在TIMER_TIME_OUT时间后被删除。 这样做有两个好处: (1) 第一个好处是不需要遍历优先队列,省时。 (2) 第二个好处是给超时时间一个容忍的时间,就是设定的超时时间是删除的下限(并不是一到超时时间就立即删除),如果监听的请求在超时后的下一次请求中又一次出现了, 就不用再重新申请requestData节点了,这样可以继续重复利用前面的requestData,减少了一次delete和一次new的时间。 */ void handle_expired_event() { MutexLockGuard(); while (!myTimerQueue.empty()) { mytimer *ptimer_now = myTimerQueue.top(); if (ptimer_now->isDeleted()) { myTimerQueue.pop(); delete ptimer_now; } else if (ptimer_now->isvalid() == false) { myTimerQueue.pop(); delete ptimer_now; } else { break; } } } int main() { handle_for_sigpipe(); int epoll_fd = epoll_init(); if (epoll_fd < 0) { perror("epoll init failed"); return 1; } threadpool_t *threadpool = threadpool_create(THREADPOOL_THREAD_NUM, QUEUE_SIZE, 0); int listen_fd = socket_bind_listen(PORT); if (listen_fd < 0) { perror("socket bind failed"); return 1; } if (setSocketNonBlocking(listen_fd) < 0) { perror("set socket non block failed"); return 1; } __uint32_t event = EPOLLIN | EPOLLET; requestData *req = new requestData(); req->setFd(listen_fd); epoll_add(epoll_fd, listen_fd, static_cast<void*>(req), event); while (true) { int events_num = my_epoll_wait(epoll_fd, events, MAXEVENTS, -1); //printf("%zu\n", myTimerQueue.size()); if (events_num == 0) continue; printf("%d\n", events_num); //printf("%zu\n", myTimerQueue.size()); // else // cout << "one connection has come!" << endl; // 遍历events数组,根据监听种类及描述符类型分发操作 handle_events(epoll_fd, listen_fd, events, events_num, PATH, threadpool); handle_expired_event(); } return 0; }
4,017
952
<reponame>samisouabni/Main { "version": "0.9.8", "description": "command line tool to download and extract data from HTML/XML pages as well as JSON APIs.", "homepage": "http://www.videlibri.de/xidel.html", "license": "GPL-3.0-or-later", "url": "https://github.com/benibela/xidel/releases/download/Xidel_0.9.8/xidel-0.9.8.win32.zip", "hash": "96854c2be1e3755f56fabb8f00d1fe567108461b9fab139039219a1b7c17e382", "bin": "xidel.exe", "checkver": { "github": "https://github.com/benibela/xidel", "regex": "xidel-([\\d.]+)\\.win32" }, "autoupdate": { "url": "https://github.com/benibela/xidel/releases/download/Xidel_$version/xidel-$version.win32.zip" } }
354
1,253
#include<stdio.h> #include<stdlib.h> int sorted (int *array, int size) { while (size >= 1) { if (array[size] < array[size-1]) return 0; size--; } return 1; } void shuffle (int *array, int size) { int i, tmp, random; for (i = 0; i < size; i++) { tmp = array[i]; random = rand()%size; array[i] = array[random]; array[random] = tmp; } } void bogosort (int *array, int size) { while (!sorted(array, size)) shuffle(array, size); } void print_array (int *array, int size) { int i; for (i = 0; i < size; i++) { printf("%d ", array[i]); } printf("\n"); } int main() { int i, size; printf("Enter array size: "); scanf("%d", &size); int array[size]; for (i = 0; i < size; i++) { array[i] = rand()%100; } printf("Original array: \n"); print_array(array, size); bogosort(array, size); printf("Sorted array: \n"); print_array(array, size); return 0; }
466
1,338
<gh_stars>1000+ /* * Copyright 2007 Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * Ramshankar, <EMAIL> * <NAME> <<EMAIL>> */ //! BCommandPipe class to handle reading shell output // (stdout/stderr) of other programs into memory. #include "CommandPipe.h" #include <stdlib.h> #include <unistd.h> #include <image.h> #include <Message.h> #include <Messenger.h> #include <String.h> BCommandPipe::BCommandPipe() : fStdOutOpen(false), fStdErrOpen(false) { } BCommandPipe::~BCommandPipe() { FlushArgs(); } status_t BCommandPipe::AddArg(const char* arg) { if (arg == NULL || arg[0] == '\0') return B_BAD_VALUE; char* argCopy = strdup(arg); if (argCopy == NULL) return B_NO_MEMORY; if (!fArgList.AddItem(reinterpret_cast<void*>(argCopy))) { free(argCopy); return B_NO_MEMORY; } return B_OK; } void BCommandPipe::PrintToStream() const { for (int32 i = 0L; i < fArgList.CountItems(); i++) printf("%s ", reinterpret_cast<char*>(fArgList.ItemAtFast(i))); printf("\n"); } void BCommandPipe::FlushArgs() { // Delete all arguments from the list for (int32 i = fArgList.CountItems() - 1; i >= 0; i--) free(fArgList.ItemAtFast(i)); fArgList.MakeEmpty(); Close(); } void BCommandPipe::Close() { if (fStdErrOpen) { close(fStdErr[0]); fStdErrOpen = false; } if (fStdOutOpen) { close(fStdOut[0]); fStdOutOpen = false; } } const char** BCommandPipe::Argv(int32& argc) const { // NOTE: Freeing is left to caller as indicated in the header! argc = fArgList.CountItems(); const char** argv = reinterpret_cast<const char**>( malloc((argc + 1) * sizeof(char*))); for (int32 i = 0; i < argc; i++) argv[i] = reinterpret_cast<const char*>(fArgList.ItemAtFast(i)); argv[argc] = NULL; return argv; } // #pragma mark - thread_id BCommandPipe::PipeAll(int* stdOutAndErr) const { // This function pipes both stdout and stderr to the same filedescriptor // (stdOut) int oldStdOut; int oldStdErr; pipe(stdOutAndErr); oldStdOut = dup(STDOUT_FILENO); oldStdErr = dup(STDERR_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); // TODO: This looks broken, using "stdOutAndErr[1]" twice! dup2(stdOutAndErr[1], STDOUT_FILENO); dup2(stdOutAndErr[1], STDERR_FILENO); // Construct the argv vector int32 argc; const char** argv = Argv(argc); // Load the app image... and pass the args thread_id appThread = load_image((int)argc, argv, const_cast<const char**>(environ)); dup2(oldStdOut, STDOUT_FILENO); dup2(oldStdErr, STDERR_FILENO); close(oldStdOut); close(oldStdErr); free(argv); return appThread; } thread_id BCommandPipe::Pipe(int* stdOut, int* stdErr) const { int oldStdOut; int oldStdErr; pipe(stdOut); pipe(stdErr); oldStdOut = dup(STDOUT_FILENO); oldStdErr = dup(STDERR_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); dup2(stdOut[1], STDOUT_FILENO); dup2(stdErr[1], STDERR_FILENO); // Construct the argv vector int32 argc; const char** argv = Argv(argc); // Load the app image... and pass the args thread_id appThread = load_image((int)argc, argv, const_cast< const char**>(environ)); dup2(oldStdOut, STDOUT_FILENO); dup2(oldStdErr, STDERR_FILENO); close(oldStdOut); close(oldStdErr); free(argv); return appThread; } thread_id BCommandPipe::Pipe(int* stdOut) const { // Redirects only output (stdout) to caller, stderr is closed int stdErr[2]; thread_id tid = Pipe(stdOut, stdErr); close(stdErr[0]); close(stdErr[1]); return tid; } thread_id BCommandPipe::PipeInto(FILE** _out, FILE** _err) { Close(); thread_id tid = Pipe(fStdOut, fStdErr); if (tid >= 0) resume_thread(tid); close(fStdErr[1]); close(fStdOut[1]); fStdOutOpen = true; fStdErrOpen = true; *_out = fdopen(fStdOut[0], "r"); *_err = fdopen(fStdErr[0], "r"); return tid; } thread_id BCommandPipe::PipeInto(FILE** _outAndErr) { Close(); thread_id tid = PipeAll(fStdOut); if (tid >= 0) resume_thread(tid); close(fStdOut[1]); fStdOutOpen = true; *_outAndErr = fdopen(fStdOut[0], "r"); return tid; } // #pragma mark - void BCommandPipe::Run() { // Runs the command without bothering to redirect streams, this is similar // to system() but uses pipes and wait_for_thread.... Synchronous. int stdOut[2], stdErr[2]; status_t exitCode; wait_for_thread(Pipe(stdOut, stdErr), &exitCode); close(stdOut[0]); close(stdErr[0]); close(stdOut[1]); close(stdErr[1]); } void BCommandPipe::RunAsync() { // Runs the command without bothering to redirect streams, this is similar // to system() but uses pipes.... Asynchronous. Close(); FILE* f = NULL; PipeInto(&f); fclose(f); } // #pragma mark - status_t BCommandPipe::ReadLines(FILE* file, LineReader* lineReader) { // Reads output of file, line by line. Each line is passed to lineReader // for inspection, and the IsCanceled() method is repeatedly called. if (file == NULL || lineReader == NULL) return B_BAD_VALUE; BString line; while (!feof(file)) { if (lineReader->IsCanceled()) return B_CANCELED; unsigned char c = fgetc(file); // TODO: fgetc() blocks, is there a way to make it timeout? if (c != 255) line << (char)c; if (c == '\n') { status_t ret = lineReader->ReadLine(line); if (ret != B_OK) return ret; line = ""; } } return B_OK; } BString BCommandPipe::ReadLines(FILE* file) { class AllLinesReader : public LineReader { public: AllLinesReader() : fResult("") { } virtual bool IsCanceled() { return false; } virtual status_t ReadLine(const BString& line) { int lineLength = line.Length(); int resultLength = fResult.Length(); fResult << line; if (fResult.Length() != lineLength + resultLength) return B_NO_MEMORY; return B_OK; } BString Result() const { return fResult; } private: BString fResult; } lineReader; ReadLines(file, &lineReader); return lineReader.Result(); } // #pragma mark - BCommandPipe& BCommandPipe::operator<<(const char* arg) { AddArg(arg); return *this; } BCommandPipe& BCommandPipe::operator<<(const BString& arg) { AddArg(arg.String()); return *this; } BCommandPipe& BCommandPipe::operator<<(const BCommandPipe& arg) { int32 argc; const char** argv = arg.Argv(argc); for (int32 i = 0; i < argc; i++) AddArg(argv[i]); free(argv); return *this; }
2,719
1,178
/* * Copyright 2020 Makani Technologies LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "avionics/loadcell/firmware/selftest.h" #include <math.h> #include <stddef.h> #include "avionics/common/avionics_messages.h" #include "avionics/firmware/identity/identity_types.h" #include "avionics/firmware/serial/aio_serial_params.h" #include "avionics/firmware/serial/loadcell_serial_params.h" #include "avionics/firmware/util/selftest.h" #include "avionics/loadcell/firmware/calib_params.h" #include "common/macros.h" static const char *CheckLoadcellCalibParams(void) { if ((kLoadcellCalibParams->pin_calib.strain_0_scale < 1.0f) || (kLoadcellCalibParams->pin_calib.strain_0_scale > 100.0f) || (kLoadcellCalibParams->pin_calib.strain_1_scale < 1.0f) || (kLoadcellCalibParams->pin_calib.strain_1_scale > 100.0f)) { return "Strain scale config param outside expected range [1.0, 100.0]."; } if (isnan(kLoadcellCalibParams->pin_calib.strain_0_scale) || isnan(kLoadcellCalibParams->pin_calib.strain_1_scale)) { return "Strain scale config param is NaN."; } if ((kLoadcellCalibParams->pin_calib.strain_0_zero < 0) || (kLoadcellCalibParams->pin_calib.strain_0_zero >= (1 << 24)) || (kLoadcellCalibParams->pin_calib.strain_1_zero < 0) || (kLoadcellCalibParams->pin_calib.strain_1_zero >= (1 << 24))) { return "Strain zero config param outside expected range [0, 2^24)"; } return NULL; } void SelfTest(void) { const HardwareSpec valid_hardware[] = { {kHardwareTypeAio, kAioHardwareRevAb}, {kHardwareTypeAio, kAioHardwareRevAc}, {kHardwareTypeAio, kAioHardwareRevAd}, {kHardwareTypeAio, kAioHardwareRevBa}, }; const CarrierHardwareSpec valid_carrier_hardware[] = { {kCarrierHardwareTypeLoadcell, kLoadcellHardwareRevAa}, {kCarrierHardwareTypeLoadcell, kLoadcellHardwareRevAb}, }; SelfTestCommon(ARRAYSIZE(valid_hardware), valid_hardware); SelfTestCarrierCommon(ARRAYSIZE(valid_carrier_hardware), valid_carrier_hardware); SelfTestCalibParameters(LoadcellCalibParamsGetTypeVersion()); const char *failure = CheckLoadcellCalibParams(); if (failure != NULL) { SelfTestFailedLoop(kSelfTestFailureInvalidCalibParams, failure); } }
1,033
380
<gh_stars>100-1000 #pragma once #include "common.h" #include "capi/random.h" #include "cng/random.h" namespace mini::crypto { using random = MINI_CRYPTO_RANDOM_NAMESPACE::random; // // TODO: // it would be great to come up with better // solution than this. // static auto& random_device = MINI_CRYPTO_RANDOM_NAMESPACE::random_device; }
135
2,151
<filename>extensions/common/extensions_aliases.cc // 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 "extensions/common/extensions_aliases.h" namespace extensions { std::vector<Alias> GetExtensionsPermissionAliases() { // In alias constructor, first value is the alias name; second value is the // real name. See also alias.h. return {Alias("alwaysOnTopWindows", "app.window.alwaysOnTop"), Alias("fullscreen", "app.window.fullscreen"), Alias("overrideEscFullscreen", "app.window.fullscreen.overrideEsc"), Alias("unlimited_storage", "unlimitedStorage")}; } } // namespace extensions
236
2,446
/* Copyright (C) 2018 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: Behavior that is used by enemies when they become frightened by the player. */ #import <GameplayKit/GameplayKit.h> #import "AAPLBaseComponent.h" #import "AAPLPlayerComponent.h" @interface AAPLScaredComponent : AAPLBaseComponent @property AAPLPlayerComponent *player; @property GKInspectable float fleeDistance; @property GKInspectable float fleeSpeed; @property GKInspectable float wanderSpeed; @property GKInspectable float mass; @property GKInspectable float maxAcceleration; @end
176
2,151
<gh_stars>1000+ // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROMECAST_BROWSER_CAST_BROWSER_PROCESS_H_ #define CHROMECAST_BROWSER_CAST_BROWSER_PROCESS_H_ #include <memory> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "build/build_config.h" class PrefService; namespace net { class NetLog; } // namespace net namespace chromecast { class CastService; class CastScreen; class ConnectivityChecker; namespace metrics { class CastMetricsServiceClient; } // namespace metrics namespace shell { class CastBrowserContext; class CastContentBrowserClient; class RemoteDebuggingServer; class CastBrowserProcess { public: // Gets the global instance of CastBrowserProcess. Does not create lazily and // assumes the instance already exists. static CastBrowserProcess* GetInstance(); CastBrowserProcess(); virtual ~CastBrowserProcess(); void SetBrowserContext(std::unique_ptr<CastBrowserContext> browser_context); void SetCastContentBrowserClient(CastContentBrowserClient* browser_client); void SetCastService(std::unique_ptr<CastService> cast_service); #if defined(USE_AURA) void SetCastScreen(std::unique_ptr<CastScreen> cast_screen); #endif // defined(USE_AURA) void SetMetricsServiceClient( std::unique_ptr<metrics::CastMetricsServiceClient> metrics_service_client); void SetPrefService(std::unique_ptr<PrefService> pref_service); void SetRemoteDebuggingServer( std::unique_ptr<RemoteDebuggingServer> remote_debugging_server); void SetConnectivityChecker( scoped_refptr<ConnectivityChecker> connectivity_checker); void SetNetLog(net::NetLog* net_log); CastContentBrowserClient* browser_client() const { return cast_content_browser_client_; } CastBrowserContext* browser_context() const { return browser_context_.get(); } CastService* cast_service() const { return cast_service_.get(); } #if defined(USE_AURA) CastScreen* cast_screen() const { return cast_screen_.get(); } #endif // defined(USE_AURA) metrics::CastMetricsServiceClient* metrics_service_client() const { return metrics_service_client_.get(); } PrefService* pref_service() const { return pref_service_.get(); } ConnectivityChecker* connectivity_checker() const { return connectivity_checker_.get(); } RemoteDebuggingServer* remote_debugging_server() const { return remote_debugging_server_.get(); } net::NetLog* net_log() const { return net_log_; } private: // Note: The following order should match the order they are set in // CastBrowserMainParts. #if defined(USE_AURA) std::unique_ptr<CastScreen> cast_screen_; #endif // defined(USE_AURA) std::unique_ptr<PrefService> pref_service_; scoped_refptr<ConnectivityChecker> connectivity_checker_; std::unique_ptr<CastBrowserContext> browser_context_; std::unique_ptr<metrics::CastMetricsServiceClient> metrics_service_client_; std::unique_ptr<RemoteDebuggingServer> remote_debugging_server_; CastContentBrowserClient* cast_content_browser_client_; net::NetLog* net_log_; // Note: CastService must be destroyed before others. std::unique_ptr<CastService> cast_service_; DISALLOW_COPY_AND_ASSIGN(CastBrowserProcess); }; } // namespace shell } // namespace chromecast #endif // CHROMECAST_BROWSER_CAST_BROWSER_PROCESS_H_
1,073
764
{ "symbol": "AEF", "address": "0xd6CD14d3BE0F72a9a7231C810417317093c3c588", "overview":{ "en": "AISI Ecosystem FOF (Hereafter AEF) is the first global tokenized fund of fund open to all community investors.", "zh": "爱思生态凭证(AEF)是面向所有社区投资者的全球第一支通证化的母基金。" }, "email": "<EMAIL>", "website": "http://www.aisi.fund/", "whitepaper": "http://www.aisi.fund/whitepaper.pdf", "state": "NORMAL", "published_on": "2018-08-02", "initial_price":{ "ETH":"0.0021727 ETH", "USD":"1 USD", "BTC":"0.0001236 BTC" }, "links": { "blog": "http://www.aisi.fund/news.html", "twitter": "https://twitter.com/aisifund", "telegram": "https://t.me/aisifund", "github": "https://github.com/aisigroup" } }
396
988
<reponame>AlexeyMochalov/firebird /* * PROGRAM: Firebird Trace Services * MODULE: TraceConfigStorage.h * DESCRIPTION: Trace API shared configurations storage * * The contents of this file are subject to the Initial * Developer's Public License Version 1.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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl. * * Software distributed under the License is distributed AS IS, * WITHOUT WARRANTY OF ANY KIND, either express or implied. * See the License for the specific language governing rights * and limitations under the License. * * The Original Code was created by <NAME> * for the Firebird Open Source RDBMS project. * * Copyright (c) 2008 <NAME> <<EMAIL>> * and all contributors signed below. * * All Rights Reserved. * Contributor(s): ______________________________________. * */ #ifndef JRD_TRACECONFIGSTORAGE_H #define JRD_TRACECONFIGSTORAGE_H #include "../../common/classes/array.h" #include "../../common/classes/fb_string.h" #include "../../common/classes/init.h" #include "../../common/isc_s_proto.h" #include "../../common/ThreadStart.h" #include "../../jrd/trace/TraceSession.h" #include "../../common/classes/RefCounted.h" namespace Jrd { /* Session ID and flags are stored within slot itself. Length of session data could be less than or equal of slot size. Slots are sorted by session id. Slot for new session is always last slot. When session is removed its slot is marked as unused. Unused slot could be reused: slot itself moved at last position in slots array, higher slots are moved down on its former place, slot data is not moved. Slot is reused with best-fit algorithm. */ struct TraceCSHeader : public Firebird::MemoryHeader { static const USHORT TRACE_STORAGE_VERSION = 2; static const USHORT TRACE_STORAGE_MAX_SLOTS = 1000; static const ULONG TRACE_STORAGE_MIN_SIZE = 64 * 1024; static const ULONG TRACE_STORAGE_MAX_SIZE = 16 * 1024 * 1024; struct Slot { ULONG offset; ULONG size; ULONG used; ULONG ses_id; ULONG ses_flags; ULONG ses_pid; }; volatile ULONG change_number; volatile ULONG session_number; ULONG cnt_uses; ULONG mem_max_size; // maximum allowed mapping size ULONG mem_allocated; // currently mapped memory ULONG mem_used; // used memory ULONG mem_offset; // never used free space begins here ULONG slots_free; // number of unused slots ULONG slots_cnt; // number of slots in use Slot slots[TRACE_STORAGE_MAX_SLOTS]; }; static_assert(sizeof(TraceCSHeader) < TraceCSHeader::TRACE_STORAGE_MIN_SIZE, "TraceCSHeader not fits TRACE_STORAGE_MIN_SIZE"); class ConfigStorage FB_FINAL : public Firebird::GlobalStorage, public Firebird::IpcObject, public Firebird::Reasons { public: enum GET_FLAGS {ALL, FLAGS, AUTH}; ConfigStorage(); ~ConfigStorage(); void addSession(Firebird::TraceSession& session); void updateFlags(Firebird::TraceSession& session); void removeSession(ULONG id); // get session by sesion id bool getSession(Firebird::TraceSession& session, GET_FLAGS getFlag); void restart(); bool getNextSession(Firebird::TraceSession& session, GET_FLAGS getFlag); ULONG getChangeNumber() const { return m_sharedMemory && m_sharedMemory->getHeader() ? m_sharedMemory->getHeader()->change_number : 0; } void acquire(); void release(); void shutdown(); Firebird::Mutex m_localMutex; private: void mutexBug(int osErrorCode, const char* text); bool initialize(Firebird::SharedMemoryBase*, bool); void checkAudit(); class TouchFile FB_FINAL : public Firebird::RefCntIface<Firebird::ITimerImpl<TouchFile, Firebird::CheckStatusWrapper> > { public: TouchFile() : fileName(*getDefaultMemoryPool()) {} void handler(); void start(const char* fName); void stop(); private: Firebird::PathName fileName; }; Firebird::RefPtr<TouchFile> m_timer; void checkDirty() { m_dirty = false; } void setDirty() { if (!m_dirty) { if (m_sharedMemory && m_sharedMemory->getHeader()) m_sharedMemory->getHeader()->change_number++; m_dirty = true; } } // items in every session record at session data enum ITEM { tagName = 1, // session Name tagAuthBlock, // with which creator logged in tagUserName, // creator user name tagConfig, // configuration tagStartTS, // date+time when started tagLogFile, // log file name, if any tagRole, // SQL role name, if any tagEnd }; // allocate slot with size >= of given slotLen, returns slot index // could remap shared memory ULONG allocSlot(ULONG slotSize); void markDeleted(TraceCSHeader::Slot * slot); // remove unused space between slots data void compact(); bool validate(); ULONG getSessionSize(const Firebird::TraceSession& session); bool findSession(ULONG sesId, ULONG& idx); bool readSession(TraceCSHeader::Slot* slot, Firebird::TraceSession& session, GET_FLAGS getFlag); class Reader { public: Reader(const void* memory, ULONG size) : m_mem(reinterpret_cast<const char*>(memory)), m_end(m_mem + size) {} // fill tag and len, returns pointer to data or NULL if data can't be read const void* read(ITEM& tag, ULONG& len); private: const char* m_mem; const char* const m_end; }; class Writer { public: Writer(void* memory, ULONG size) : m_mem(reinterpret_cast<char*>(memory)), m_end(m_mem + size) {} void write(ITEM tag, ULONG len, const void* data); private: char* m_mem; const char* const m_end; }; Firebird::AutoPtr<Firebird::SharedMemory<TraceCSHeader> > m_sharedMemory; int m_recursive; ThreadId m_mutexTID; bool m_dirty; ULONG m_nextIdx; // getNextSession() iterator index }; class StorageInstance { private: Firebird::Mutex initMtx; ConfigStorage* storage; public: explicit StorageInstance(Firebird::MemoryPool&) : storage(NULL) {} ~StorageInstance() { delete storage; } ConfigStorage* getStorage() { if (!storage) { Firebird::MutexLockGuard guard(initMtx, FB_FUNCTION); if (!storage) { storage = FB_NEW ConfigStorage; } } return storage; } }; class StorageGuard : public Firebird::MutexLockGuard { public: explicit StorageGuard(ConfigStorage* storage) : Firebird::MutexLockGuard(storage->m_localMutex, FB_FUNCTION), m_storage(storage) { m_storage->acquire(); } ~StorageGuard() { m_storage->release(); } private: ConfigStorage* m_storage; }; } #endif
2,277
360
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * ------------------------------------------------------------------------- * * cache.h * * IDENTIFICATION * src\include\client_logic\cache.h * * ------------------------------------------------------------------------- */ #ifndef CACHE_H #define CACHE_H #include "utils/syscache.h" #include "access/htup.h" HeapTuple search_syscache_cek_name(const char *key_name, Oid namespace_id); HeapTuple search_syscache_cmk_name(const char *key_name, Oid namespace_id); HeapTuple search_sys_cache_ce_col_name(Oid relid, const char *attname); HeapTuple search_sys_cache_copy_ce_col_name(Oid relid, const char *attname); bool search_sys_cache_exists_ce_col_name(Oid relid, const char *attname); #endif /* CACHE_H */
423
2,332
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State from app import sf_manager, app from panels import opportunities, cases, leads server = app.server app.layout = html.Div( [ html.Div( className="row header", children=[ html.Button(id="menu", children=dcc.Markdown("&#8801")), html.Span( className="app-title", children=[ dcc.Markdown("**CRM App**"), html.Span( id="subtitle", children=dcc.Markdown("&nbsp using Salesforce API"), style={"font-size": "1.8rem", "margin-top": "15px"}, ), ], ), html.Img(src=app.get_asset_url("logo.png")), html.A( id="learn_more", children=html.Button("Learn More"), href="https://plot.ly/dash/", ), ], ), html.Div( id="tabs", className="row tabs", children=[ dcc.Link("Opportunities", href="/"), dcc.Link("Leads", href="/"), dcc.Link("Cases", href="/"), ], ), html.Div( id="mobile_tabs", className="row tabs", style={"display": "none"}, children=[ dcc.Link("Opportunities", href="/"), dcc.Link("Leads", href="/"), dcc.Link("Cases", href="/"), ], ), dcc.Store( # opportunities df id="opportunities_df", data=sf_manager.get_opportunities().to_json(orient="split"), ), dcc.Store( # leads df id="leads_df", data=sf_manager.get_leads().to_json(orient="split") ), dcc.Store( id="cases_df", data=sf_manager.get_cases().to_json(orient="split") ), # cases df dcc.Location(id="url", refresh=False), html.Div(id="tab_content"), html.Link( href="https://use.fontawesome.com/releases/v5.2.0/css/all.css", rel="stylesheet", ), html.Link( href="https://fonts.googleapis.com/css?family=Dosis", rel="stylesheet" ), html.Link( href="https://fonts.googleapis.com/css?family=Open+Sans", rel="stylesheet" ), html.Link( href="https://fonts.googleapis.com/css?family=Ubuntu", rel="stylesheet" ), ], className="row", style={"margin": "0%"}, ) # Update the index @app.callback( [ Output("tab_content", "children"), Output("tabs", "children"), Output("mobile_tabs", "children"), ], [Input("url", "pathname")], ) def display_page(pathname): tabs = [ dcc.Link("Opportunities", href="/dash-salesforce-crm/opportunities"), dcc.Link("Leads", href="/dash-salesforce-crm/leads"), dcc.Link("Cases", href="/dash-salesforce-crm/cases"), ] if pathname == "/dash-salesforce-crm/opportunities": tabs[0] = dcc.Link( dcc.Markdown("**&#9632 Opportunities**"), href="/dash-salesforce-crm/opportunities", ) return opportunities.layout, tabs, tabs elif pathname == "/dash-salesforce-crm/cases": tabs[2] = dcc.Link( dcc.Markdown("**&#9632 Cases**"), href="/dash-salesforce-crm/cases" ) return cases.layout, tabs, tabs tabs[1] = dcc.Link( dcc.Markdown("**&#9632 Leads**"), href="/dash-salesforce-crm/leads" ) return leads.layout, tabs, tabs @app.callback( Output("mobile_tabs", "style"), [Input("menu", "n_clicks")], [State("mobile_tabs", "style")], ) def show_menu(n_clicks, tabs_style): if n_clicks: if tabs_style["display"] == "none": tabs_style["display"] = "flex" else: tabs_style["display"] = "none" return tabs_style if __name__ == "__main__": app.run_server(debug=True)
2,224
345
<reponame>ishandutta2007/sonnet<gh_stars>100-1000 # Copyright 2017 The Sonnet Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ # pylint: disable=line-too-long """Implementation of AlexNet as a Sonnet module. `AlexNet` is a Sonnet module that implements two variants of 'ImageNet Classification with Deep Convolutional Neural Networks' <NAME>, <NAME>, <NAME>, NIPS 2012 http://papers.nips.cc/paper/4824-imagenet-classification-w The two modes are FULL and MINI, corresponding to the full dual-gpu version and a cut-down version that is able to run on Cifar10. AlexNet is no longer state of the art and isn't considered a good starting point for a vision network. """ # pylint: enable=line-too-long from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports from sonnet.python.modules import base from sonnet.python.modules import basic from sonnet.python.modules import batch_norm from sonnet.python.modules import conv from sonnet.python.modules import util import tensorflow as tf class AlexNet(base.AbstractModule): """Implementation of AlexNet with full and mini versions. Based on: 'ImageNet Classification with Deep Convolutional Neural Networks' <NAME>, <NAME>, <NAME>, NIPS 2012 http://papers.nips.cc/paper/4824-imagenet-classification-w """ FULL = "FULL" MINI = "MINI" POSSIBLE_INITIALIZER_KEYS = {"w", "b"} def __init__(self, mode, use_batch_norm=False, batch_norm_config=None, initializers=None, partitioners=None, regularizers=None, bn_on_fc_layers=True, custom_getter=None, name="alex_net"): """Constructs AlexNet. Args: mode: Construction mode of network: `AlexNet.FULL` or `AlexNet.MINI`. use_batch_norm: Whether to use batch normalization between the output of a layer and the activation function. batch_norm_config: Optional mapping of additional configuration for the `snt.BatchNorm` modules. initializers: Optional dict containing ops to initialize the filters (with key 'w') or biases (with key 'b'). The default initializers are truncated normal initializers, which are commonly used when the inputs are zero centered (see https://arxiv.org/pdf/1502.03167v3.pdf). partitioners: Optional dict containing partitioners for the filters (with key 'w') and the biases (with key 'b'). As a default, no partitioners are used. regularizers: Optional dict containing regularizers for the filters (with key 'w') and the biases (with key 'b'). As a default, no regularizers are used. A regularizer should be a function that takes a single `Tensor` as an input and returns a scalar `Tensor` output, e.g. the L1 and L2 regularizers in `tf.contrib.layers`. bn_on_fc_layers: If `use_batch_norm` is True, add batch normalization to the fully-connected layers. This is deprecated. custom_getter: Callable or dictionary of callables to use as custom getters inside the module. If a dictionary, the keys correspond to regexes to match variable names. See the `tf.get_variable` documentation for information about the custom_getter API. name: Name of the module. Raises: base.Error: If the given `mode` is not one of `AlexNet.FULL`, or `AlexNet.MINI`. KeyError: If `initializers`, `partitioners` or `regularizers` contains any keys other than 'w' or 'b'. """ super(AlexNet, self).__init__(custom_getter=custom_getter, name=name) self._mode = mode self._use_batch_norm = use_batch_norm self._bn_on_fc_layers = bn_on_fc_layers if self._bn_on_fc_layers: tf.logging.warn("Using BatchNorm on the fully connected layers in " "AlexNet is not recommended. 'bn_on_fc_layers' is a " "deprecated option and will likely be removed.") self._batch_norm_config = batch_norm_config or {} if self._mode == self.FULL: # The full AlexNet, i.e. originally ran on two GPUs self._conv_layers = [ (96, (11, 4), (3, 2)), (256, (5, 1), (3, 2)), (384, (3, 1), None), (384, (3, 1), None), (256, (3, 1), (3, 2)), ] self._fc_layers = [4096, 4096] elif self._mode == self.MINI: # A cut down version of the half net for testing with Cifar10 self._conv_layers = [ (48, (3, 1), (3, 1)), (128, (3, 1), (3, 1)), (192, (3, 1), None), (192, (3, 1), None), (128, (3, 1), (3, 1)), ] self._fc_layers = [1024, 1024] else: raise base.Error("AlexNet construction mode '{}' not recognised, " "must be one of: '{}', '{}'".format( mode, self.FULL, self.MINI)) self._min_size = self._calc_min_size(self._conv_layers) self._conv_modules = [] self._linear_modules = [] # Keep old name for backwards compatibility self.possible_keys = self.POSSIBLE_INITIALIZER_KEYS self._initializers = util.check_initializers( initializers, self.POSSIBLE_INITIALIZER_KEYS) self._partitioners = util.check_partitioners( partitioners, self.POSSIBLE_INITIALIZER_KEYS) self._regularizers = util.check_regularizers( regularizers, self.POSSIBLE_INITIALIZER_KEYS) def _calc_min_size(self, conv_layers): """Calculates the minimum size of the input layer. Given a set of convolutional layers, calculate the minimum value of the `input_height` and `input_width`, i.e. such that the output has size 1x1. Assumes snt.VALID padding. Args: conv_layers: List of tuples `(output_channels, (kernel_size, stride), (pooling_size, pooling_stride))` Returns: Minimum value of input height and width. """ input_size = 1 for _, conv_params, max_pooling in reversed(conv_layers): if max_pooling is not None: kernel_size, stride = max_pooling input_size = input_size * stride + (kernel_size - stride) if conv_params is not None: kernel_size, stride = conv_params input_size = input_size * stride + (kernel_size - stride) return input_size def _build(self, inputs, keep_prob=None, is_training=None, test_local_stats=True): """Connects the AlexNet module into the graph. The is_training flag only controls the batch norm settings, if `False` it does not force no dropout by overriding any input `keep_prob`. To avoid any confusion this may cause, if `is_training=False` and `keep_prob` would cause dropout to be applied, an error is thrown. Args: inputs: A Tensor of size [batch_size, input_height, input_width, input_channels], representing a batch of input images. keep_prob: A scalar Tensor representing the dropout keep probability. When `is_training=False` this must be None or 1 to give no dropout. is_training: Boolean to indicate if we are currently training. Must be specified if batch normalization or dropout is used. test_local_stats: Boolean to indicate to `snt.BatchNorm` if batch normalization should use local batch statistics at test time. By default `True`. Returns: A Tensor of size [batch_size, output_size], where `output_size` depends on the mode the network was constructed in. Raises: base.IncompatibleShapeError: If any of the input image dimensions (input_height, input_width) are too small for the given network mode. ValueError: If `keep_prob` is not None or 1 when `is_training=False`. ValueError: If `is_training` is not explicitly specified when using batch normalization. """ # Check input shape if (self._use_batch_norm or keep_prob is not None) and is_training is None: raise ValueError("Boolean is_training flag must be explicitly specified " "when using batch normalization or dropout.") input_shape = inputs.get_shape().as_list() if input_shape[1] < self._min_size or input_shape[2] < self._min_size: raise base.IncompatibleShapeError( "Image shape too small: ({:d}, {:d}) < {:d}".format( input_shape[1], input_shape[2], self._min_size)) net = inputs # Check keep prob if keep_prob is not None: valid_inputs = tf.logical_or(is_training, tf.equal(keep_prob, 1.)) keep_prob_check = tf.assert_equal( valid_inputs, True, message="Input `keep_prob` must be None or 1 if `is_training=False`.") with tf.control_dependencies([keep_prob_check]): net = tf.identity(net) for i, params in enumerate(self._conv_layers): output_channels, conv_params, max_pooling = params kernel_size, stride = conv_params conv_mod = conv.Conv2D( name="conv_{}".format(i), output_channels=output_channels, kernel_shape=kernel_size, stride=stride, padding=conv.VALID, initializers=self._initializers, partitioners=self._partitioners, regularizers=self._regularizers) if not self.is_connected: self._conv_modules.append(conv_mod) net = conv_mod(net) if self._use_batch_norm: bn = batch_norm.BatchNorm(**self._batch_norm_config) net = bn(net, is_training, test_local_stats) net = tf.nn.relu(net) if max_pooling is not None: pooling_kernel_size, pooling_stride = max_pooling net = tf.nn.max_pool( net, ksize=[1, pooling_kernel_size, pooling_kernel_size, 1], strides=[1, pooling_stride, pooling_stride, 1], padding=conv.VALID) net = basic.BatchFlatten(name="flatten")(net) for i, output_size in enumerate(self._fc_layers): linear_mod = basic.Linear( name="fc_{}".format(i), output_size=output_size, initializers=self._initializers, partitioners=self._partitioners) if not self.is_connected: self._linear_modules.append(linear_mod) net = linear_mod(net) if self._use_batch_norm and self._bn_on_fc_layers: bn = batch_norm.BatchNorm(**self._batch_norm_config) net = bn(net, is_training, test_local_stats) net = tf.nn.relu(net) if keep_prob is not None: net = tf.nn.dropout(net, keep_prob=keep_prob) return net @property def initializers(self): return self._initializers @property def partitioners(self): return self._partitioners @property def regularizers(self): return self._regularizers @property def min_input_size(self): """Returns integer specifying the minimum width and height for the input. Note that the input can be non-square, but both the width and height must be >= this number in size. Returns: The minimum size as an integer. """ return self._min_size @property def conv_modules(self): """Returns list containing convolutional modules of network. Returns: A list containing the Conv2D modules. """ self._ensure_is_connected() return self._conv_modules @property def linear_modules(self): """Returns list containing linear modules of network. Returns: A list containing the Linear modules. """ self._ensure_is_connected() return self._linear_modules class AlexNetFull(AlexNet): """AlexNet constructed in the 'FULL' mode.""" def __init__(self, use_batch_norm=False, batch_norm_config=None, initializers=None, partitioners=None, regularizers=None, custom_getter=None, name="alex_net_full"): """Constructs AlexNet. Args: use_batch_norm: Whether to use batch normalization between the output of a layer and the activation function. batch_norm_config: Optional mapping of additional configuration for the `snt.BatchNorm` modules. initializers: Optional dict containing ops to initialize the filters (with key 'w') or biases (with key 'b'). The default initializers are truncated normal initializers, which are commonly used when the inputs are zero centered (see https://arxiv.org/pdf/1502.03167v3.pdf). partitioners: Optional dict containing partitioners for the filters (with key 'w') and the biases (with key 'b'). As a default, no partitioners are used. regularizers: Optional dict containing regularizers for the filters (with key 'w') and the biases (with key 'b'). As a default, no regularizers are used. A regularizer should be a function that takes a single `Tensor` as an input and returns a scalar `Tensor` output, e.g. the L1 and L2 regularizers in `tf.contrib.layers`. custom_getter: Callable or dictionary of callables to use as custom getters inside the module. If a dictionary, the keys correspond to regexes to match variable names. See the `tf.get_variable` documentation for information about the custom_getter API. name: Name of the module. Raises: KeyError: If `initializers`, `partitioners` or `regularizers` contains any keys other than 'w' or 'b'. """ super(AlexNetFull, self).__init__( mode=self.FULL, use_batch_norm=use_batch_norm, batch_norm_config=batch_norm_config, initializers=initializers, partitioners=partitioners, regularizers=regularizers, bn_on_fc_layers=False, custom_getter=custom_getter, name=name) class AlexNetMini(AlexNet): """AlexNet constructed in the 'MINI' mode.""" def __init__(self, use_batch_norm=False, batch_norm_config=None, initializers=None, partitioners=None, regularizers=None, custom_getter=None, name="alex_net_mini"): """Constructs AlexNet. Args: use_batch_norm: Whether to use batch normalization between the output of a layer and the activation function. batch_norm_config: Optional mapping of additional configuration for the `snt.BatchNorm` modules. initializers: Optional dict containing ops to initialize the filters (with key 'w') or biases (with key 'b'). The default initializers are truncated normal initializers, which are commonly used when the inputs are zero centered (see https://arxiv.org/pdf/1502.03167v3.pdf). partitioners: Optional dict containing partitioners for the filters (with key 'w') and the biases (with key 'b'). As a default, no partitioners are used. regularizers: Optional dict containing regularizers for the filters (with key 'w') and the biases (with key 'b'). As a default, no regularizers are used. A regularizer should be a function that takes a single `Tensor` as an input and returns a scalar `Tensor` output, e.g. the L1 and L2 regularizers in `tf.contrib.layers`. custom_getter: Callable or dictionary of callables to use as custom getters inside the module. If a dictionary, the keys correspond to regexes to match variable names. See the `tf.get_variable` documentation for information about the custom_getter API. name: Name of the module. Raises: KeyError: If `initializers`, `partitioners` or `regularizers` contains any keys other than 'w' or 'b'. """ super(AlexNetMini, self).__init__( mode=self.MINI, use_batch_norm=use_batch_norm, batch_norm_config=batch_norm_config, initializers=initializers, partitioners=partitioners, regularizers=regularizers, bn_on_fc_layers=False, custom_getter=custom_getter, name=name)
6,497