repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
axodox/Lux
Lux.Shared/Dispatcher.cpp
#include "pch.h" #include "Dispatcher.h" using namespace std; using namespace winrt; using namespace winrt::Windows::UI::Core; namespace Lux::Threading { simple_dispatcher::simple_dispatcher() : _thread([&] { run(); }, L"simple dispatcher") { } simple_dispatcher::~simple_dispatcher() { _tasks.complete(); } std::future<void> simple_dispatcher::invoke(std::function<void()>&& callback) { dispatched_task task{}; task.callback = move(callback); auto future = task.promise.get_future(); if (_thread.is_current()) { execute_task(task); } else { _tasks.add(move(task)); } return future; } bool simple_dispatcher::has_access() const { return _thread.is_current(); } void simple_dispatcher::execute_task(dispatched_task& task) { try { task.callback(); task.promise.set_value(); } catch (...) { task.promise.set_exception(current_exception()); } } void simple_dispatcher::run() { while (!_tasks.is_complete()) { dispatched_task task; if (_tasks.try_get(task)) { execute_task(task); } } } core_dispatcher::core_dispatcher(const winrt::Windows::UI::Core::CoreDispatcher& dispatcher) : _dispatcher(dispatcher) { } std::future<void> core_dispatcher::invoke(std::function<void()> && callback) { auto promise = make_unique<std::promise<void>>(); auto future = promise->get_future(); if (_dispatcher.HasThreadAccess()) { try { callback(); promise->set_value(); } catch (...) { promise->set_exception(current_exception()); } } else { _dispatcher .RunAsync(CoreDispatcherPriority::Normal, [callback = move(callback)]{ callback(); }) .Completed([promise = move(promise)](auto&, auto&) { promise->set_value(); }); } return future; } bool core_dispatcher::has_access() const { return _dispatcher.HasThreadAccess(); } }
dillonhuff/Chips-2.0
examples/example_2.py
<gh_stars>100-1000 #!/usr/bin/env python2 import subprocess import atexit from math import pi from chips.api.api import Chip, Stimulus, Response, Wire, Component try: from matplotlib import pyplot except ImportError: print "You need matplotlib to run this script!" exit(0) try: from numpy import arange except ImportError: print "You need numpy to run this script!" exit(0) def test(): run_c("taylor.c") x = [float(i) for i in open("x")] sin_x = [float(i) for i in open("sin_x")] cos_x = [float(i) for i in open("cos_x")] def test(): chip = Chip("taylor") stimulus = arange(-2*pi, 2.0*pi, pi/25) x = Stimulus(chip, "x", "double", stimulus) sin_x = Response(chip, "sin_x", "double") cos_x = Response(chip, "cos_x", "double") #create a filter component using the C code sqrt = Component("taylor.c") #add an instance to the chip sqrt( chip, inputs = { "x":x, }, outputs = { "sin_x":sin_x, "cos_x":cos_x, }, ) #run the simulation chip.simulation_reset() while len(cos_x) < len(x): chip.simulation_step() x = list(x) sin_x = list(sin_x)[:100] cos_x = list(cos_x)[:100] pyplot.xticks( [-2.0*pi, -pi, 0, pi, 2.0*pi], [r'$-2\pi$', r"$-\pi$", r'$0$', r'$\pi$', r'$2\pi$']) pyplot.plot(x, sin_x, label="sin(x)") pyplot.plot(x, cos_x, label="cos(x)") pyplot.ylim(-1.1, 1.1) pyplot.xlim(-2.2 * pi, 2.2 * pi) pyplot.title("Trig Functions") pyplot.xlabel("x (radians)") pyplot.legend(loc="upper left") pyplot.savefig("../docs/source/examples/images/example_2.png") pyplot.show() def indent(lines): return "\n ".join(lines.splitlines()) def generate_docs(): documentation = """ Approximating Sine and Cosine functions using Taylor Series =========================================================== In this example, we calculate an approximation of the cosine functions using the `Taylor series <http://en.wikipedia.org/wiki/Taylor_series>`_: .. math:: \\cos (x) = \\sum_{n=0}^{\\infty} \\frac{(-1)^n}{(2n)!} x^{2n} The following example uses the Taylor Series approximation to generate the Sine and Cosine functions. Successive terms of the taylor series are calculated until successive approximations agree to within a small degree. A Sine function is also synthesised using the identity :math:`sin(x) \\equiv cos(x-\\pi/2)` .. code-block:: c %s A simple test calculates Sine and Cosine for the range :math:`-2\\pi <= x <= 2\\pi`. .. image:: images/example_2.png """%indent(open("taylor.c").read()) document = open("../docs/source/examples/example_2.rst", "w").write(documentation) test() generate_docs()
reels-research/iOS-Private-Frameworks
PhotosImagingFoundation.framework/IPAAdjustmentVersionInfo.h
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/PhotosImagingFoundation.framework/PhotosImagingFoundation */ @interface IPAAdjustmentVersionInfo : NSObject <NSCopying> { NSString * _appVersion; NSString * _buildNumber; NSString * _platform; long long _schemaRevision; } @property (nonatomic, copy) NSString *appVersion; @property (nonatomic, copy) NSString *buildNumber; @property (nonatomic, copy) NSString *platform; @property (nonatomic) long long schemaRevision; + (id)_frameworkVersion; + (id)_systemBuildVersion; + (id)_systemVersionPlistPath; + (id)currentVersionInfo; + (id)frameworkVersion; + (id)systemBuildVersion; + (id)versionInfoFromArchivalRepresentation:(id)arg1; - (void).cxx_destruct; - (id)appVersion; - (id)archivalRepresentation; - (id)buildNumber; - (id)copyWithZone:(struct _NSZone { }*)arg1; - (id)description; - (bool)isEqual:(id)arg1; - (bool)isEqualToVersionInfo:(id)arg1; - (id)platform; - (long long)schemaRevision; - (void)setAppVersion:(id)arg1; - (void)setBuildNumber:(id)arg1; - (void)setPlatform:(id)arg1; - (void)setSchemaRevision:(long long)arg1; @end
LeDron12/c2eo
project/tests/in_progress/for_main/tests_suite/test094/testsuite_094.c
#include <stdio.h> struct S {int a; int b;}; struct S s = { .b = 2, .a = 1}; int test() { if(s.a != 1) return 1; if(s.b != 2) return 2; return 0; } int main () { int x; x = test(); printf("%d\n", x); return 0; }
dan4ik95dv/famousartists
app/src/main/java/com/github/dan4ik95dv/famousartists/ui/fragment/ArtistTracksFragment.java
package com.github.dan4ik95dv.famousartists.ui.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CoordinatorLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.RelativeLayout; import com.devspark.robototextview.widget.RobotoTextView; import com.github.dan4ik95dv.famousartists.R; import com.github.dan4ik95dv.famousartists.di.component.fragment.DaggerArtistTracksComponent; import com.github.dan4ik95dv.famousartists.di.module.fragment.ArtistsTracksModule; import com.github.dan4ik95dv.famousartists.model.yandex.artist.response.ArtistResponse; import com.github.dan4ik95dv.famousartists.ui.presenter.ArtistTracksPresenter; import com.github.dan4ik95dv.famousartists.ui.view.ArtistTracksMvpView; import com.github.dan4ik95dv.famousartists.ui.widget.DividerItemDecoration; import com.github.dan4ik95dv.famousartists.ui.widget.EmptyRecyclerView; import com.github.dan4ik95dv.famousartists.ui.widget.ItemClickSupport; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter; import rx.Observer; public class ArtistTracksFragment extends BaseFragment implements ArtistTracksMvpView, Observer<ArtistResponse> { private static final String TAG = "PromotionAddressesFragment"; @Inject ArtistTracksPresenter presenter; LinearLayoutManager mLinearLayoutManager; @Bind(R.id.listTracks) EmptyRecyclerView mListTracks; @Bind(R.id.swipeRefreshDiscounts) SwipeRefreshLayout mSwipeRefreshDiscounts; @Bind(R.id.textNoTracksMain) RobotoTextView mTextNoTracksMain; @Bind(R.id.textNoTracksSecond) RobotoTextView mTextNoTracksSecond; @Bind(R.id.layoutNoTracks) RelativeLayout mLayoutNoTracks; @Bind(R.id.progressView) FrameLayout mProgressView; @Bind(R.id.coordinatorLayout) CoordinatorLayout mCoordinatorLayout; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); DaggerArtistTracksComponent.builder().artistsTracksModule(new ArtistsTracksModule(getContext())).build().inject(this); presenter.attachView(this); presenter.init(); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { mListTracks.setAdapter(new AlphaInAnimationAdapter(presenter.getAdapter())); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false); ButterKnife.bind(this, view); initRecyclerView(inflater, container); presenter.init(); return view; } private void initRecyclerView(LayoutInflater inflater, @Nullable ViewGroup container) { mLinearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false); mListTracks.setEmptyView(inflater.inflate(R.layout.view_empty_tracks, container, false)); mListTracks.setHasFixedSize(true); mListTracks.setLayoutManager(mLinearLayoutManager); mListTracks.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST)); ItemClickSupport.addTo(mListTracks) .setOnItemClickListener(presenter.getOnItemClickListener()) .setOnItemLongClickListener(presenter.getOnItemLongClickListener()); mSwipeRefreshDiscounts.setOnRefreshListener(presenter.getRefreshListener()); mSwipeRefreshDiscounts.setColorSchemeResources( R.color.colorPrimary, R.color.colorPrimary, R.color.colorPrimary); } @Override public void hideProgress() { mProgressView.setVisibility(View.GONE); } @Override public void noTracks() { } @Override public ArtistTracksFragment getFragment() { return this; } @Override public void onCompleted() { } @Override public void onError(Throwable e) { if (mSwipeRefreshDiscounts.isRefreshing()) mSwipeRefreshDiscounts.setRefreshing(false); } @Override public void onNext(ArtistResponse artistResponse) { presenter.fillView(artistResponse); mListTracks.setVisibility(View.VISIBLE); mLayoutNoTracks.setVisibility(View.GONE); if (mSwipeRefreshDiscounts.isRefreshing()) mSwipeRefreshDiscounts.setRefreshing(false); } @Override public void updateFragment() { } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } }
ChocolateLoverRaj/dev-react
lib/__mocks__/read-create-dir.test.js
<reponame>ChocolateLoverRaj/dev-react /* eslint-env jest */ import readDir, { _reset } from './read-create-dir.js' afterEach(_reset) test('spies', async () => { await expect(readDir('dir')).resolves.toStrictEqual([]) expect(readDir.calledOnceWith('dir')).toBe(true) }) test('_reset', async () => { await readDir('dir') _reset() expect(readDir.notCalled).toBe(true) })
dmzgroup/dmz
frameworks/net/modules/basic/dmzNetModuleIdentityMapBasic.h
<filename>frameworks/net/modules/basic/dmzNetModuleIdentityMapBasic.h #ifndef DMZ_NET_MODULE_IDENTITY_MAP_BASIC_DOT_H #define DMZ_NET_MODULE_IDENTITY_MAP_BASIC_DOT_H #include <dmzNetModuleIdentityMap.h> #include <dmzRuntimeDataConverterTypesBase.h> #include <dmzRuntimeHandleAllocator.h> #include <dmzRuntimeLog.h> #include <dmzRuntimeMessaging.h> #include <dmzRuntimePlugin.h> #include <dmzTypesHashTableStringTemplate.h> #include <dmzTypesHashTableUInt32Template.h> namespace dmz { class NetModuleIdentityMapBasic : public Plugin, public NetModuleIdentityMap, public MessageObserver { public: //! \cond NetModuleIdentityMapBasic (const PluginInfo &Info, Config &local); ~NetModuleIdentityMapBasic (); // Plugin Interface virtual void update_plugin_state ( const PluginStateEnum State, const UInt32 Level) {;} virtual void discover_plugin ( const PluginDiscoverEnum Mode, const Plugin *PluginPtr) {;} // NetModuleIdentityMap Interface virtual UInt32 get_site_id (); virtual UInt32 get_host_id (); virtual Boolean create_site_host_entity ( const Handle ObjectHandle, UInt32 &site, UInt32 &host, UInt32 &entity); virtual Boolean store_site_host_entity ( const Handle ObjectHandle, const UInt32 Site, const UInt32 Host, const UInt32 Entity); virtual Boolean lookup_site_host_entity ( const Handle ObjectHandle, UInt32 &site, UInt32 &host, UInt32 &entity); virtual Boolean store_name ( const Handle ObjectHandle, const String &Name); virtual Boolean lookup_name ( const Handle ObjectHandle, String &name); virtual Boolean lookup_handle_from_name ( const String &Name, UInt32 &handle); virtual Boolean lookup_handle_from_site_host_entity ( const UInt32 Site, const UInt32 Host, const UInt32 Entity, UInt32 &handle); virtual Boolean remove_object (const Handle ObjectHandle); // MessageObserver Interface virtual void receive_message ( const Message &Msg, const UInt32 MessageSendHandle, const UInt32 TargetObserverHandle, const Data *InData, Data *outData); protected: struct EntityStruct { const Handle ObjectHandle; UInt32 site; UInt32 host; UInt32 entity; String name; Boolean entityHandleCreated; EntityStruct (const Handle TheHandle) : ObjectHandle (TheHandle), site (0), host (0), entity (0), entityHandleCreated (False) {;} }; struct HostStruct { const UInt32 Host; HashTableUInt32Template<EntityStruct> table; HostStruct (const UInt32 TheHost) : Host (TheHost) {;} ~HostStruct () { table.clear (); } }; struct SiteStruct { const UInt32 Site; HashTableUInt32Template<HostStruct> table; SiteStruct (const UInt32 TheSite) : Site (TheSite) {;} ~SiteStruct () { table.empty (); } }; void _init (Config &local); EntityStruct *_create_entity_struct (const Handle ObjectHandle); Log _log; UInt32 _site; UInt32 _host; HandleAllocator _netHandles; HashTableUInt32Template<SiteStruct> _siteTable; HashTableUInt32Template<EntityStruct> _objTable; HashTableStringTemplate<EntityStruct> _nameTable; Message _removeObjMsg; DataConverterHandle _handleConverter; //! \endcond private: NetModuleIdentityMapBasic (); NetModuleIdentityMapBasic (const NetModuleIdentityMapBasic &); NetModuleIdentityMapBasic &operator= (const NetModuleIdentityMapBasic &); }; }; #endif // DMZ_NET_MODULE_IDENTITY_MAP_BASIC_DOT_H
wrldwzrd89/older-java-games
DungeonDiver4/src/com/puttysoftware/dungeondiver4/editor/LevelPreferencesManager.java
/* DungeonDiver4: A Dungeon-Solving Game Copyright (C) 2008-2012 <NAME> Any questions should be directed to the author via email at: <EMAIL> */ package com.puttysoftware.dungeondiver4.editor; import java.awt.BorderLayout; import java.awt.Container; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.WindowConstants; import com.puttysoftware.dungeondiver4.DungeonDiver4; import com.puttysoftware.dungeondiver4.dungeon.Dungeon; import com.puttysoftware.dungeondiver4.dungeon.DungeonConstants; public class LevelPreferencesManager { // Fields private JFrame prefFrame; private JCheckBox horizontalWrap; private JCheckBox verticalWrap; private JCheckBox thirdDimensionalWrap; private JTextField levelTitle; private JTextArea levelStartMessage; private JTextArea levelEndMessage; private JTextField exploreRadius; private JCheckBox vmExplore; private JCheckBox vmLOS; private JComboBox<String> poisonPowerChoices; private String[] poisonPowerChoiceArray; private JTextField illumination; // Constructors public LevelPreferencesManager() { this.setUpGUI(); } // Methods public void showPrefs() { this.loadPrefs(); DungeonDiver4.getApplication().getEditor().disableOutput(); this.prefFrame.setVisible(true); } public void hidePrefs() { this.prefFrame.setVisible(false); DungeonDiver4.getApplication().getEditor().enableOutput(); DungeonDiver4.getApplication().getDungeonManager().setDirty(true); DungeonDiver4.getApplication().getEditor().redrawEditor(); } void setPrefs() { final Dungeon m = DungeonDiver4.getApplication().getDungeonManager() .getDungeon(); if (this.horizontalWrap.isSelected()) { m.enableHorizontalWraparound(); } else { m.disableHorizontalWraparound(); } if (this.verticalWrap.isSelected()) { m.enableVerticalWraparound(); } else { m.disableVerticalWraparound(); } if (this.thirdDimensionalWrap.isSelected()) { m.enable3rdDimensionWraparound(); } else { m.disable3rdDimensionWraparound(); } m.setLevelTitle(this.levelTitle.getText()); m.setLevelStartMessage(this.levelStartMessage.getText()); m.setLevelEndMessage(this.levelEndMessage.getText()); int newER = m.getExploreRadius(); try { newER = Integer.parseInt(this.exploreRadius.getText()); if (newER < 1 || newER > 16) { throw new NumberFormatException(); } } catch (final NumberFormatException nfe) { newER = m.getExploreRadius(); } m.setExploreRadius(newER); int newVM = DungeonConstants.VISION_MODE_NONE; if (this.vmExplore.isSelected()) { newVM = newVM | DungeonConstants.VISION_MODE_EXPLORE; } if (this.vmLOS.isSelected()) { newVM = newVM | DungeonConstants.VISION_MODE_LOS; } m.setVisionMode(newVM); m.setPoisonPower(this.poisonPowerChoices.getSelectedIndex()); int newVR = m.getVisionRadius(); try { newVR = Integer.parseInt(this.illumination.getText()); if (newVR < 1 || newVR > 16) { throw new NumberFormatException(); } } catch (final NumberFormatException nfe) { newVR = m.getVisionRadius(); } m.setVisionRadius(newVR); } private void loadPrefs() { final Dungeon m = DungeonDiver4.getApplication().getDungeonManager() .getDungeon(); this.horizontalWrap.setSelected(m.isHorizontalWraparoundEnabled()); this.verticalWrap.setSelected(m.isVerticalWraparoundEnabled()); this.thirdDimensionalWrap .setSelected(m.is3rdDimensionWraparoundEnabled()); this.levelTitle.setText(m.getLevelTitle()); this.levelStartMessage.setText(m.getLevelStartMessage()); this.levelEndMessage.setText(m.getLevelEndMessage()); this.exploreRadius.setText(Integer.toString(m.getExploreRadius())); final int vm = m.getVisionMode(); if ((vm | DungeonConstants.VISION_MODE_EXPLORE) == vm) { this.vmExplore.setSelected(true); } else { this.vmExplore.setSelected(false); } if ((vm | DungeonConstants.VISION_MODE_LOS) == vm) { this.vmLOS.setSelected(true); } else { this.vmLOS.setSelected(false); } this.poisonPowerChoices.setSelectedIndex(m.getPoisonPower()); this.illumination.setText(Integer.toString(m.getVisionRadius())); } private void setUpGUI() { final EventHandler handler = new EventHandler(); this.prefFrame = new JFrame("Level Preferences"); final Image iconlogo = DungeonDiver4.getApplication().getIconLogo(); this.prefFrame.setIconImage(iconlogo); final Container mainPrefPane = new Container(); final Container contentPane = new Container(); final Container buttonPane = new Container(); final JButton prefsOK = new JButton("OK"); prefsOK.setDefaultCapable(true); this.prefFrame.getRootPane().setDefaultButton(prefsOK); final JButton prefsCancel = new JButton("Cancel"); prefsCancel.setDefaultCapable(false); this.horizontalWrap = new JCheckBox("Enable horizontal wraparound", false); this.verticalWrap = new JCheckBox("Enable vertical wraparound", false); this.thirdDimensionalWrap = new JCheckBox( "Enable 3rd dimension wraparound", false); this.levelTitle = new JTextField(""); this.levelStartMessage = new JTextArea(""); this.levelEndMessage = new JTextArea(""); this.exploreRadius = new JTextField(""); this.vmExplore = new JCheckBox("Enable exploring vision mode"); this.vmLOS = new JCheckBox("Enable line-of-sight vision mode"); this.poisonPowerChoiceArray = new String[Dungeon.getMaxPoisonPower() + 1]; for (int x = 0; x < this.poisonPowerChoiceArray.length; x++) { if (x == 0) { this.poisonPowerChoiceArray[x] = "None"; } else if (x == 1) { this.poisonPowerChoiceArray[x] = "1 health / 1 step"; } else { this.poisonPowerChoiceArray[x] = "1 health / " + Integer.toString(x) + " steps"; } } final DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>( this.poisonPowerChoiceArray); this.poisonPowerChoices = new JComboBox<>(); this.poisonPowerChoices.setModel(model); this.illumination = new JTextField(""); this.prefFrame.setContentPane(mainPrefPane); this.prefFrame .setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); this.prefFrame.addWindowListener(handler); mainPrefPane.setLayout(new BorderLayout()); this.prefFrame.setResizable(false); contentPane.setLayout(new GridLayout(17, 1)); contentPane.add(this.horizontalWrap); contentPane.add(this.verticalWrap); contentPane.add(this.thirdDimensionalWrap); contentPane.add(new JLabel("Level Title")); contentPane.add(this.levelTitle); contentPane.add(new JLabel("Level Start Message")); contentPane.add(this.levelStartMessage); contentPane.add(new JLabel("Level End Message")); contentPane.add(this.levelEndMessage); contentPane.add(new JLabel("Exploring Mode Vision Radius (1-16)")); contentPane.add(this.exploreRadius); contentPane.add(this.vmExplore); contentPane.add(this.vmLOS); contentPane.add(new JLabel("Poison Power")); contentPane.add(this.poisonPowerChoices); contentPane.add(new JLabel("Starting Illumination (1-16)")); contentPane.add(this.illumination); buttonPane.setLayout(new FlowLayout()); buttonPane.add(prefsOK); buttonPane.add(prefsCancel); mainPrefPane.add(contentPane, BorderLayout.CENTER); mainPrefPane.add(buttonPane, BorderLayout.SOUTH); prefsOK.addActionListener(handler); prefsCancel.addActionListener(handler); this.prefFrame.pack(); } private class EventHandler implements ActionListener, WindowListener { EventHandler() { // Do nothing } // Handle buttons @Override public void actionPerformed(final ActionEvent e) { try { final LevelPreferencesManager lpm = LevelPreferencesManager.this; final String cmd = e.getActionCommand(); if (cmd.equals("OK")) { lpm.setPrefs(); lpm.hidePrefs(); } else if (cmd.equals("Cancel")) { lpm.hidePrefs(); } } catch (final Exception ex) { DungeonDiver4.getErrorLogger().logError(ex); } } // handle window @Override public void windowOpened(final WindowEvent e) { // Do nothing } @Override public void windowClosing(final WindowEvent e) { final LevelPreferencesManager pm = LevelPreferencesManager.this; pm.hidePrefs(); } @Override public void windowClosed(final WindowEvent e) { // Do nothing } @Override public void windowIconified(final WindowEvent e) { // Do nothing } @Override public void windowDeiconified(final WindowEvent e) { // Do nothing } @Override public void windowActivated(final WindowEvent e) { // Do nothing } @Override public void windowDeactivated(final WindowEvent e) { // Do nothing } } }
freemo/AetherMUD
src/main/java/com/syncleus/aethermud/game/Abilities/Druid/Chant_SummonPlants.java
/** * Copyright 2017 Syncleus, Inc. * with portions copyright 2004-2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.syncleus.aethermud.game.Abilities.Druid; import com.syncleus.aethermud.game.Abilities.interfaces.Ability; import com.syncleus.aethermud.game.Areas.interfaces.Area; import com.syncleus.aethermud.game.Common.interfaces.CMMsg; import com.syncleus.aethermud.game.Items.interfaces.Item; import com.syncleus.aethermud.game.Items.interfaces.RawMaterial; import com.syncleus.aethermud.game.Locales.interfaces.Room; import com.syncleus.aethermud.game.MOBS.interfaces.MOB; import com.syncleus.aethermud.game.core.*; import com.syncleus.aethermud.game.core.interfaces.Environmental; import com.syncleus.aethermud.game.core.interfaces.Physical; import java.util.Hashtable; import java.util.List; import java.util.Map; public class Chant_SummonPlants extends Chant { private final static String localizedName = CMLib.lang().L("Summon Plants"); protected static Map<String, long[]> plantBonuses = new Hashtable<String, long[]>(); protected Room plantsLocationR = null; protected Item littlePlantsI = null; @Override public String ID() { return "Chant_SummonPlants"; } @Override public String name() { return localizedName; } @Override public int classificationCode() { return Ability.ACODE_CHANT | Ability.DOMAIN_PLANTGROWTH; } @Override public int abstractQuality() { return Ability.QUALITY_INDIFFERENT; } @Override protected int canAffectCode() { return CAN_ITEMS; } @Override protected int canTargetCode() { return 0; } @Override public void unInvoke() { final Room plantsR = plantsLocationR; final Item plantsI = littlePlantsI; if (plantsR == null) return; if (plantsI == null) return; if (canBeUninvoked()) plantsR.showHappens(CMMsg.MSG_OK_VISUAL, L("@x1 wither@x2 away.", plantsI.name(), (plantsI.name().startsWith("s") ? "" : "s"))); super.unInvoke(); if (canBeUninvoked()) { this.littlePlantsI = null; plantsI.destroy(); plantsR.recoverRoomStats(); this.plantsLocationR = null; } } @Override public String text() { if ((miscText.length() == 0) && (invoker() != null)) miscText = invoker().Name(); return super.text(); } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { if ((msg.amITarget(littlePlantsI)) && ((msg.targetMinor() == CMMsg.TYP_GET) || (msg.targetMinor() == CMMsg.TYP_PUSH) || (msg.targetMinor() == CMMsg.TYP_PULL))) msg.addTrailerMsg(CMClass.getMsg(msg.source(), littlePlantsI, null, CMMsg.MSG_OK_VISUAL, CMMsg.MASK_ALWAYS | CMMsg.MSG_DEATH, CMMsg.NO_EFFECT, null)); } public Item buildPlant(MOB mob, Room room) { final Item newItem = CMClass.getItem("GenItem"); newItem.setMaterial(RawMaterial.RESOURCE_GREENS); switch (CMLib.dice().roll(1, 5, 0)) { case 1: newItem.setName(L("some happy flowers")); newItem.setDisplayText(L("some happy flowers are growing here.")); newItem.setDescription(L("Happy flowers with little red and yellow blooms.")); break; case 2: newItem.setName(L("some happy weeds")); newItem.setDisplayText(L("some happy weeds are growing here.")); newItem.setDescription(L("Long stalked little plants with tiny bulbs on top.")); break; case 3: newItem.setName(L("a pretty fern")); newItem.setDisplayText(L("a pretty fern is growing here.")); newItem.setDescription(L("Like a tiny bush, this dark green plant is lovely.")); break; case 4: newItem.setName(L("a patch of sunflowers")); newItem.setDisplayText(L("a patch of sunflowers is growing here.")); newItem.setDescription(L("Happy flowers with little yellow blooms.")); break; case 5: newItem.setName(L("a patch of bluebonnets")); newItem.setDisplayText(L("a patch of bluebonnets is growing here.")); newItem.setDescription(L("Happy flowers with little blue and purple blooms.")); break; } final Chant_SummonPlants newChant = new Chant_SummonPlants(); newItem.basePhyStats().setLevel(10 + (10 * newChant.getX1Level(mob))); newItem.basePhyStats().setWeight(1); newItem.setSecretIdentity(mob.Name()); newItem.setMiscText(newItem.text()); room.addItem(newItem); Druid_MyPlants.addNewPlant(mob, newItem); newItem.setExpirationDate(0); room.showHappens(CMMsg.MSG_OK_ACTION, CMLib.lang().L("Suddenly, @x1 sprout(s) up here.", newItem.name())); newChant.plantsLocationR = room; newChant.littlePlantsI = newItem; if (CMLib.law().doesOwnThisLand(mob, room)) { newChant.setInvoker(mob); newChant.setMiscText(mob.Name()); newItem.addNonUninvokableEffect(newChant); } else newChant.beneficialAffect(mob, newItem, 0, (newChant.adjustedLevel(mob, 0) * 240) + 450); room.recoverPhyStats(); return newItem; } public Item buildMyThing(MOB mob, Room room) { final Area A = room.getArea(); final boolean bonusWorthy = (Druid_MyPlants.myPlant(room, mob, 0) == null) && ((room.getGridParent() == null) || (CMLib.flags().matchedAffects(mob, room.getGridParent(), -1, Ability.ACODE_CHANT, -1).size() == 0)); final List<Room> V = Druid_MyPlants.myAreaPlantRooms(mob, room.getArea()); int pct = 0; if (A.getAreaIStats()[Area.Stats.VISITABLE_ROOMS.ordinal()] > 10) pct = (int) Math.round(100.0 * CMath.div(V.size(), A.getAreaIStats()[Area.Stats.VISITABLE_ROOMS.ordinal()])); final Item I = buildMyPlant(mob, room); if ((I != null) && ((mob.charStats().getCurrentClass().baseClass().equalsIgnoreCase("Druid")) || (CMSecurity.isASysOp(mob)))) { if (!CMLib.law().isACity(A)) { if (pct > 0) { final int newPct = (int) Math.round(100.0 * CMath.div(V.size(), A.getAreaIStats()[Area.Stats.VISITABLE_ROOMS.ordinal()])); if ((newPct >= 50) && (A.fetchEffect("Chant_DruidicConnection") == null)) { final Ability A2 = CMClass.getAbility("Chant_DruidicConnection"); if (A2 != null) A2.invoke(mob, A, true, 0); } } } else if ((bonusWorthy) && (!mob.isMonster())) { long[] num = plantBonuses.get(mob.Name() + "/" + room.getArea().Name()); if ((num == null) || (System.currentTimeMillis() - num[1] > (room.getArea().getTimeObj().getDaysInMonth() * room.getArea().getTimeObj().getHoursInDay() * CMProps.getMillisPerMudHour()))) { num = new long[2]; plantBonuses.remove(mob.Name() + "/" + room.getArea().Name()); plantBonuses.put(mob.Name() + "/" + room.getArea().Name(), num); num[1] = System.currentTimeMillis(); } if (V.size() >= num[0]) { num[0]++; if (num[0] < 19) { mob.tell(L("You have made this city greener.")); CMLib.leveler().postExperience(mob, null, null, (int) num[0], false); } } } } return I; } protected Item buildMyPlant(MOB mob, Room room) { return buildPlant(mob, room); } public boolean rightPlace(MOB mob, boolean auto) { final Room R = mob.location(); if (R == null) return false; if ((!auto) && (R.domainType() & Room.INDOORS) > 0) { mob.tell(L("You must be outdoors for this chant to work.")); return false; } if ((R.domainType() == Room.DOMAIN_OUTDOORS_CITY) || (R.domainType() == Room.DOMAIN_OUTDOORS_SPACEPORT) || (R.domainType() == Room.DOMAIN_OUTDOORS_UNDERWATER) || (R.domainType() == Room.DOMAIN_OUTDOORS_AIR) || (R.domainType() == Room.DOMAIN_OUTDOORS_WATERSURFACE)) { mob.tell(L("This magic will not work here.")); return false; } return true; } @Override public int castingQuality(MOB mob, Physical target) { if (mob != null) { if (!rightPlace(mob, false)) return Ability.QUALITY_INDIFFERENT; final Item myPlant = Druid_MyPlants.myPlant(mob.location(), mob, 0); if (myPlant == null) return super.castingQuality(mob, target, Ability.QUALITY_BENEFICIAL_SELF); } return super.castingQuality(mob, target); } @Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { if (!rightPlace(mob, auto)) return false; if (!super.invoke(mob, commands, givenTarget, auto, asLevel)) return false; // now see if it worked final boolean success = proficiencyCheck(mob, 0, auto); if (success) { final CMMsg msg = CMClass.getMsg(mob, null, this, verbalCastCode(mob, null, auto), auto ? "" : L("^S<S-NAME> chant(s) to the ground.^?")); if (mob.location().okMessage(mob, msg)) { mob.location().send(mob, msg); buildMyThing(mob, mob.location()); } } else return beneficialWordsFizzle(mob, null, L("<S-NAME> chant(s) to the ground, but nothing happens.")); // return whether it worked return success; } }
maded2/68000
software/doom/r_state.h
<reponame>maded2/68000 // Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // $Id:$ // // Copyright (C) 1993-1996 by id Software, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // DESCRIPTION: // Refresh/render internal state variables (global). // //----------------------------------------------------------------------------- #ifndef __R_STATE__ #define __R_STATE__ // Need data structure definitions. #include "d_player.h" #include "r_data.h" #ifdef __GNUG__ #pragma interface #endif // // Refresh internal data structures, // for rendering. // // needed for texture pegging extern fixed_t* textureheight; // needed for pre rendering (fracs) extern fixed_t* spritewidth; extern fixed_t* spriteoffset; extern fixed_t* spritetopoffset; extern lighttable_t* colormaps; extern int viewwidth; extern int scaledviewwidth; extern int viewheight; extern int firstflat; // for global animation extern int* flattranslation; extern int* texturetranslation; // Sprite.... extern int firstspritelump; extern int lastspritelump; extern int numspritelumps; // // Lookup tables for map data. // extern int numsprites; extern spritedef_t* sprites; extern int numvertexes; extern vertex_t* vertexes; extern int numsegs; extern seg_t* segs; extern int numsectors; extern sector_t* sectors; extern int numsubsectors; extern subsector_t* subsectors; extern int numnodes; extern node_t* nodes; extern int numlines; extern line_t* lines; extern int numsides; extern side_t* sides; // // POV data. // extern fixed_t viewx; extern fixed_t viewy; extern fixed_t viewz; extern angle_t viewangle; extern player_t* viewplayer; // ? extern angle_t clipangle; extern int viewangletox[FINEANGLES/2]; extern angle_t xtoviewangle[SCREENWIDTH+1]; //extern fixed_t finetangent[FINEANGLES/2]; extern fixed_t rw_distance; extern angle_t rw_normalangle; // angle to line origin extern int rw_angle1; // Segs count? extern int sscount; extern visplane_t* floorplane; extern visplane_t* ceilingplane; #endif //----------------------------------------------------------------------------- // // $Log:$ // //-----------------------------------------------------------------------------
shan-hu/SamsungTizenRT_Sept_2017
os/drivers/wireless/scsc/misc/scsc_mx_impl.h
/**************************************************************************** * * Copyright (c) 2014 - 2016 Samsung Electronics Co., Ltd. All rights reserved * ****************************************************************************/ #ifndef _CORE_H_ #define _CORE_H_ #include "scsc_mif_abs.h" struct device; struct scsc_mx; struct mifintrbit; struct miframman; struct mifmboxman; struct mxman; struct srvman; struct mxmgmt_transport; struct scsc_mx *scsc_mx_create(struct scsc_mif_abs *mif); void scsc_mx_destroy(struct scsc_mx *mx); struct scsc_mif_abs *scsc_mx_get_mif_abs(struct scsc_mx *mx); struct mifintrbit *scsc_mx_get_intrbit(struct scsc_mx *mx); struct mifmuxman *scsc_mx_get_muxman(struct scsc_mx *mx); struct miframman *scsc_mx_get_ramman(struct scsc_mx *mx); struct mifmboxman *scsc_mx_get_mboxman(struct scsc_mx *mx); struct mxman *scsc_mx_get_mxman(struct scsc_mx *mx); struct srvman *scsc_mx_get_srvman(struct scsc_mx *mx); struct mxmgmt_transport *scsc_mx_get_mxmgmt_transport(struct scsc_mx *mx); struct gdb_transport *scsc_mx_get_gdb_transport_r4(struct scsc_mx *mx); struct mxlog *scsc_mx_get_mxlog(struct scsc_mx *mx); struct mxlog_transport *scsc_mx_get_mxlog_transport(struct scsc_mx *mx); struct panicmon *scsc_mx_get_panicmon(struct scsc_mx *mx); struct suspendmon *scsc_mx_get_suspendmon(struct scsc_mx *mx); #endif
yifazhang/shop
shop-rest/src/main/java/com/zhangyifa/rest/controller/ContentController.java
<filename>shop-rest/src/main/java/com/zhangyifa/rest/controller/ContentController.java package com.zhangyifa.rest.controller; import com.zhangyifa.common.pojo.ShopResult; import com.zhangyifa.common.utils.ExceptionUtil; import com.zhangyifa.pojo.TbContent; import com.zhangyifa.rest.service.ContentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; /** * Created by zyf on 2017/9/18. */ @Controller @RequestMapping("/content") public class ContentController { @Autowired private ContentService contentService; @RequestMapping("/list/{contentCategoryId}") @ResponseBody public ShopResult getContentList(@PathVariable Long contentCategoryId) { try { List<TbContent> list = contentService.getContentList(contentCategoryId); return ShopResult.ok(list); } catch (Exception e) { return ShopResult.build(500, ExceptionUtil.getStackTrace(e)); } } }
petejan/LogIt
src/org/imos/abos/SerialJSSCEventGenerator.java
<gh_stars>0 package org.imos.abos; import jssc.SerialPort; import jssc.SerialPortException; import jssc.SerialPortList; import jssc.SerialPortEvent; import jssc.SerialPortEventListener; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Enumeration; import java.util.TooManyListenersException; import javax.swing.JTextArea; import jssc.SerialPortException; import jssc.SerialPortList; import ocss.nmea.api.NMEAClient; import ocss.nmea.api.NMEAEvent; import ocss.nmea.api.NMEAListener; import ocss.nmea.parser.GeoPos; import ocss.nmea.parser.StringParsers; import ocss.nmea.parser.UTC; public class SerialJSSCEventGenerator extends NMEAListener implements SerialPortEventListener { String comPort = null; OutputStream out; EventWriter send; SerialPort sp; public SerialJSSCEventGenerator(FileOutputStream out, EventWriter send) { this.out = out; this.send = send; } public void setComPort(String c) { comPort = c; } public void read() { if (System.getProperty("verbose", "false").equals("true")) System.out.println("SerialJSSCEventGenerator:: From " + this.getClass().getName() + " Reading Serial Port " + comPort); // Opening Serial port String[] portNames = SerialPortList.getPortNames(); for(int i = 0; i < portNames.length; i++) { //System.out.println("SerialJSSCEventGenerator::read() " + portNames[i]); if (comPort == null) { comPort = portNames[i]; } } //System.out.println("SerialJSSCEventGenerator::read() Found " + portNames.length + " port(s)"); sp = new SerialPort(comPort); int mask = SerialPort.MASK_RXCHAR;//Prepare mask try { sp.openPort();//Open port sp.setEventsMask(mask); sp.setParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);//Set params sp.addEventListener(this);//Add SerialPortEventListener sp.setFlowControlMode(SerialPort.FLOWCONTROL_NONE); //System.out.println("SerialJSSCEventGenerator::read() Reading serial port..."); } catch (SerialPortException e) { // TODO Auto-generated catch block e.printStackTrace(); }//Set mask // Reading on Serial Port System.out.println("SerialJSSCEventGenerator::read() Port is open..." + sp.getPortName()); } StringBuffer inputBuffer = new StringBuffer(); public void serialEvent(SerialPortEvent serialPortEvent) { if (serialPortEvent.isRXCHAR()) // If data is available { try { byte buffer[] = sp.readBytes(serialPortEvent.getEventValue()); try { inputBuffer.append(new String(buffer, "UTF-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } int i = inputBuffer.indexOf("\n"); if (i > 0) { String s = inputBuffer.subSequence(0, i-1).toString(); // i-1 removes the \n System.out.println("serial Event " + s); Event v = new Event(new Date(), pos, s); send.write(v); inputBuffer.delete(0, i+1); // delete all of the data including the \n } } catch (SerialPortException ex) { System.out.println(ex); } } } GeoPos pos; UTC ut; public void dataDetected(NMEAEvent e) { String s = e.getContent(); // System.out.println("SerialEventGenerator::Received:" + s); String key = s.substring(3, 6); if (key.equals("GGA")) { pos = (GeoPos) StringParsers.parseGGA(s).get(1); ut = (UTC) StringParsers.parseGGA(s).get(0); } } }
sancar/hazelcast
hazelcast/src/test/java/com/hazelcast/query/impl/TypeConverterTest.java
/* * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.query.impl; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import java.math.BigDecimal; import java.math.BigInteger; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class TypeConverterTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConvert_whenPassedNullValue_thenConvertToNullObject() { TypeConverters.BaseTypeConverter converter = new TypeConverters.BaseTypeConverter() { @Override Comparable convertInternal(Comparable value) { return value; } }; assertEquals(IndexImpl.NULL, converter.convert(null)); } @Test public void testBigIntegerConvert_whenPassedStringValue_thenConvertToBigInteger() { String stringValue = "3141593"; Comparable expectedBigIntValue = new BigInteger(stringValue); Comparable comparable = TypeConverters.BIG_INTEGER_CONVERTER.convert(stringValue); assertThat(comparable, allOf( is(instanceOf(BigInteger.class)), is(equalTo(expectedBigIntValue)) )); } @Test public void testBigIntegerConvert_whenPassedDoubleValue_thenConvertToBigInteger() { Double doubleValue = 3.141593; Comparable expectedBigIntValue = BigInteger.valueOf(doubleValue.longValue()); Comparable comparable = TypeConverters.BIG_INTEGER_CONVERTER.convert(doubleValue); assertThat(comparable, allOf( is(instanceOf(BigInteger.class)), is(equalTo(expectedBigIntValue)) )); } @Test public void testBigIntegerConvert_whenPassedFloatValue_thenConvertToBigInteger() { Float doubleValue = 3.141593F; Comparable expectedBigIntValue = BigInteger.valueOf(3); Comparable comparable = TypeConverters.BIG_INTEGER_CONVERTER.convert(doubleValue); assertThat(comparable, allOf( is(instanceOf(BigInteger.class)), is(equalTo(expectedBigIntValue)) )); } @Test public void testBigIntegerConvert_whenPassedLongValue_thenConvertToBigInteger() { Long longValue = 3141593L; Comparable expectedBigIntValue = BigInteger.valueOf(longValue); Comparable comparable = TypeConverters.BIG_INTEGER_CONVERTER.convert(longValue); assertThat(comparable, allOf( is(instanceOf(BigInteger.class)), is(equalTo(expectedBigIntValue)) )); } @Test public void testBigIntegerConvert_whenPassedIntegerValue_thenConvertToBigInteger() { Integer integerValue = 3141593; Comparable expectedBigIntValue = BigInteger.valueOf(integerValue.longValue()); Comparable comparable = TypeConverters.BIG_INTEGER_CONVERTER.convert(integerValue); assertThat(comparable, allOf( is(instanceOf(BigInteger.class)), is(equalTo(expectedBigIntValue)) )); } @Test public void testBigIntegerConvert_whenPassedBigDecimalValue_thenConvertToBigInteger() { BigDecimal value = BigDecimal.valueOf(4.9999); Comparable expectedBigIntValue = BigInteger.valueOf(value.longValue()); Comparable comparable = TypeConverters.BIG_INTEGER_CONVERTER.convert(value); assertThat(comparable, allOf( is(instanceOf(BigInteger.class)), is(equalTo(expectedBigIntValue)) )); } @Test public void testBigIntegerConvert_whenPassedHugeBigDecimalValue_thenConvertToBigInteger() { BigDecimal value = BigDecimal.ONE.add( BigDecimal.valueOf(Long.MAX_VALUE)); Comparable expectedBigIntValue = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE); Comparable comparable = TypeConverters.BIG_INTEGER_CONVERTER.convert(value); assertThat(comparable, allOf( is(instanceOf(BigInteger.class)), is(equalTo(expectedBigIntValue)) )); } @Test public void testBigIntegerConvert_whenPassedBigIntegerValue_thenConvertToBigInteger() { BigInteger value = BigInteger.ONE; Comparable expectedBigIntValue = BigInteger.valueOf(value.longValue()); Comparable comparable = TypeConverters.BIG_INTEGER_CONVERTER.convert(value); assertThat(comparable, allOf( is(instanceOf(BigInteger.class)), is(equalTo(expectedBigIntValue)) )); } @Test @SuppressWarnings("ConstantConditions") public void testBigIntegerConvert_whenPassedBooleanValue_thenConvertToBigInteger() { // Boolean TRUE means non-zero value, i.e. 1, FALSE means 0 Boolean value = Boolean.TRUE; Comparable trueAsNumber = BigInteger.ONE; Comparable comparable = TypeConverters.BIG_INTEGER_CONVERTER.convert(value); assertThat(comparable, allOf( is(instanceOf(BigInteger.class)), is(equalTo(trueAsNumber)) )); } @Test public void testBigIntegerConvert_whenPassedNullValue_thenConvertToBigInteger() { Comparable value = "NotANumber"; thrown.expect(NumberFormatException.class); thrown.expectMessage(startsWith("For input string: ")); TypeConverters.BIG_INTEGER_CONVERTER.convert(value); } @Test public void testBigDecimalConvert_whenPassedStringValue_thenConvertToBigDecimal() { String stringValue = "3141593"; Comparable expectedDecimal = new BigDecimal(stringValue); Comparable comparable = TypeConverters.BIG_DECIMAL_CONVERTER.convert(stringValue); assertThat(comparable, allOf( is(instanceOf(BigDecimal.class)), is(equalTo(expectedDecimal)) )); } /** * Checks that the {@link TypeConverters#BIG_DECIMAL_CONVERTER} doesn't return a rounded {@link BigDecimal}. */ @Test public void testBigDecimalConvert_whenPassedDoubleValue_thenConvertToBigDecimal() { Double doubleValue = 3.141593; Comparable expectedDecimal = BigDecimal.valueOf(doubleValue); Comparable unexpectedDecimal = new BigDecimal(doubleValue); Comparable comparable = TypeConverters.BIG_DECIMAL_CONVERTER.convert(doubleValue); assertThat(comparable, allOf( is(instanceOf(BigDecimal.class)), is(equalTo(expectedDecimal)), not(equalTo(unexpectedDecimal)) )); } /** * Checks that the {@link TypeConverters#BIG_DECIMAL_CONVERTER} doesn't return a rounded {@link BigDecimal}. */ @Test public void testBigDecimalConvert_whenPassedFloatValue_thenConvertToBigDecimal() { Float floatValue = 3.141593F; Comparable expectedDecimal = BigDecimal.valueOf(floatValue); Comparable unexpectedDecimal = new BigDecimal(floatValue); Comparable comparable = TypeConverters.BIG_DECIMAL_CONVERTER.convert(floatValue); assertThat(comparable, allOf( is(instanceOf(BigDecimal.class)), is(equalTo(expectedDecimal)), not(equalTo(unexpectedDecimal)) )); } @Test public void testBigDecimalConvert_whenPassedLongValue_thenConvertToBigDecimal() { Long longValue = 3141593L; Comparable expectedDecimal = BigDecimal.valueOf(longValue); Comparable comparable = TypeConverters.BIG_DECIMAL_CONVERTER.convert(longValue); assertThat(comparable, allOf( is(instanceOf(BigDecimal.class)), is(equalTo(expectedDecimal)) )); } @Test public void testBigDecimalConvert_whenPassedIntegerValue_thenConvertToBigDecimal() { Integer integerValue = 3141593; Comparable expectedDecimal = new BigDecimal(integerValue.toString()); Comparable comparable = TypeConverters.BIG_DECIMAL_CONVERTER.convert(integerValue); assertThat(comparable, allOf( is(instanceOf(BigDecimal.class)), is(equalTo(expectedDecimal)) )); } @Test public void testBigDecimalConvert_whenPassedHugeBigIntegerValue_thenConvertToBigDecimal() { BigInteger value = BigInteger.ONE.add(BigInteger.valueOf(Long.MAX_VALUE)); Comparable expectedDecimal = BigDecimal.valueOf(Long.MAX_VALUE).add(BigDecimal.ONE); Comparable comparable = TypeConverters.BIG_DECIMAL_CONVERTER.convert(value); assertThat(comparable, allOf( is(instanceOf(BigDecimal.class)), is(equalTo(expectedDecimal)) )); } @Test public void testBigDecimalConvert_whenPassedBigIntegerValue_thenConvertToBigDecimal() { BigInteger value = BigInteger.ONE; Comparable expectedDecimal = BigDecimal.valueOf(value.longValue()); Comparable comparable = TypeConverters.BIG_DECIMAL_CONVERTER.convert(value); assertThat(comparable, allOf( is(instanceOf(BigDecimal.class)), is(equalTo(expectedDecimal)) )); } @Test @SuppressWarnings("ConstantConditions") public void testBigDecimalConvert_whenPassedBooleanValue_thenConvertToBigDecimal() { // Boolean TRUE means non-zero value, i.e. 1, FALSE means 0 Boolean value = Boolean.TRUE; Comparable trueAsDecimal = BigDecimal.ONE; Comparable comparable = TypeConverters.BIG_DECIMAL_CONVERTER.convert(value); assertThat(comparable, allOf( is(instanceOf(BigDecimal.class)), is(equalTo(trueAsDecimal)) )); } @Test public void testBigDecimalConvert_whenPassedNullValue_thenConvertToBigDecimal() { Comparable value = "NotANumber"; thrown.expect(NumberFormatException.class); TypeConverters.BIG_DECIMAL_CONVERTER.convert(value); } @Test public void testCharConvert_whenPassedNumeric_thenConvertToChar() { Comparable value = 1; Comparable expectedCharacter = (char) 1; Comparable actualCharacter = TypeConverters.CHAR_CONVERTER.convert(value); assertThat(actualCharacter, allOf( is(instanceOf(Character.class)), is(equalTo(expectedCharacter)) )); } @Test public void testCharConvert_whenPassedString_thenConvertToChar() { Comparable value = "foo"; Comparable expectedCharacter = 'f'; Comparable actualCharacter = TypeConverters.CHAR_CONVERTER.convert(value); assertThat(actualCharacter, allOf( is(instanceOf(Character.class)), is(equalTo(expectedCharacter)) )); } @Test public void testCharConvert_whenPassedEmptyString_thenConvertToChar() { Comparable value = ""; thrown.expect(IllegalArgumentException.class); TypeConverters.CHAR_CONVERTER.convert(value); } }
folio-org/mod-inventory
src/main/java/org/folio/inventory/resources/Instances.java
package org.folio.inventory.resources; import static io.netty.util.internal.StringUtil.COMMA; import static java.lang.String.format; import static java.util.concurrent.CompletableFuture.completedFuture; import static org.folio.inventory.support.CompletableFutures.failedFuture; import static org.folio.inventory.support.EndpointFailureHandler.doExceptionally; import static org.folio.inventory.support.EndpointFailureHandler.getKnownException; import static org.folio.inventory.support.EndpointFailureHandler.handleFailure; import static org.folio.inventory.support.http.server.SuccessResponse.noContent; import static org.folio.inventory.validation.InstancesValidators.refuseWhenHridChanged; import io.vertx.core.http.HttpClient; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.folio.HttpStatus; import org.folio.inventory.common.WebContext; import org.folio.inventory.common.api.request.PagingParameters; import org.folio.inventory.common.domain.MultipleRecords; import org.folio.inventory.common.domain.Success; import org.folio.inventory.domain.instances.Instance; import org.folio.inventory.domain.instances.InstanceCollection; import org.folio.inventory.domain.instances.InstanceRelationship; import org.folio.inventory.domain.instances.InstanceRelationshipToChild; import org.folio.inventory.domain.instances.InstanceRelationshipToParent; import org.folio.inventory.domain.instances.titles.PrecedingSucceedingTitle; import org.folio.inventory.exceptions.UnprocessableEntityException; import org.folio.inventory.services.InstanceRelationshipsService; import org.folio.inventory.storage.Storage; import org.folio.inventory.storage.external.CollectionResourceClient; import org.folio.inventory.storage.external.CqlQuery; import org.folio.inventory.storage.external.MultipleRecordsFetchClient; import org.folio.inventory.support.JsonArrayHelper; import org.folio.inventory.support.http.client.Response; import org.folio.inventory.support.http.server.ClientErrorResponse; import org.folio.inventory.support.http.server.FailureResponseConsumer; import org.folio.inventory.support.http.server.JsonResponse; import org.folio.inventory.support.http.server.RedirectResponse; import org.folio.inventory.support.http.server.ServerErrorResponse; import org.folio.inventory.validation.InstancePrecedingSucceedingTitleValidators; import org.folio.inventory.validation.InstancesValidators; import org.folio.rest.client.SourceStorageRecordsClient; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; public class Instances extends AbstractInstances { private static final String INSTANCES_CONTEXT_PATH = INSTANCES_PATH + "/context"; private static final String BLOCKED_FIELDS_UPDATE_ERROR_MESSAGE = "Instance is controlled by MARC record, these fields are blocked and can not be updated: "; private static final String ID = "id"; public Instances(final Storage storage, final HttpClient client) { super(storage, client); } public void register(Router router) { router.post(INSTANCES_PATH + "*").handler(BodyHandler.create()); router.put(INSTANCES_PATH + "*").handler(BodyHandler.create()); router.get(INSTANCES_CONTEXT_PATH).handler(this::getMetadataContext); router.get(INSTANCES_PATH).handler(this::getAll); router.post(INSTANCES_PATH).handler(this::create); router.delete(INSTANCES_PATH).handler(this::deleteAll); router.get(INSTANCES_PATH + "/:id").handler(this::getById); router.put(INSTANCES_PATH + "/:id").handler(this::update); router.delete(INSTANCES_PATH + "/:id").handler(this::deleteById); } private void getMetadataContext(RoutingContext routingContext) { JsonObject representation = new JsonObject(); representation.put("@context", new JsonObject() .put("dcterms", "http://purl.org/dc/terms/") .put(Instance.TITLE_KEY, "dcterms:title")); JsonResponse.success(routingContext.response(), representation); } private void getAll(RoutingContext routingContext) { WebContext context = new WebContext(routingContext); String search = context.getStringParameter("query", null); PagingParameters pagingParameters = PagingParameters.from(context); if (pagingParameters == null) { ClientErrorResponse.badRequest(routingContext.response(), "limit and offset must be numeric when supplied"); return; } if (search == null) { storage.getInstanceCollection(context).findAll( pagingParameters, (Success<MultipleRecords<Instance>> success) -> makeInstancesResponse(success, routingContext, context), FailureResponseConsumer.serverError(routingContext.response()) ); } else { try { storage.getInstanceCollection(context).findByCql( search, pagingParameters, success -> makeInstancesResponse(success, routingContext, context), FailureResponseConsumer.serverError(routingContext.response())); } catch (UnsupportedEncodingException e) { ServerErrorResponse.internalError(routingContext.response(), e.toString()); } } } private void makeInstancesResponse(Success<MultipleRecords<Instance>> success, RoutingContext routingContext, WebContext context) { InstancesResponse instancesResponse = new InstancesResponse(); instancesResponse.setSuccess(success); completedFuture(instancesResponse) .thenCompose(response -> fetchRelationships(response, routingContext)) .thenCompose(response -> fetchPrecedingSucceedingTitles(response, routingContext, context)) .thenCompose(response -> lookUpBoundWithsForInstanceRecordSet(instancesResponse, routingContext, context)) .whenComplete((result, ex) -> { if (ex == null) { JsonResponse.success(routingContext.response(), toRepresentation(result, context)); } else { log.warn("Exception occurred", ex); handleFailure(getKnownException(ex), routingContext); } }); } private void create(RoutingContext routingContext) { WebContext context = new WebContext(routingContext); JsonObject instanceRequest = routingContext.getBodyAsJson(); if (StringUtils.isBlank(instanceRequest.getString(Instance.TITLE_KEY))) { ClientErrorResponse.badRequest(routingContext.response(), "Title must be provided for an instance"); return; } Instance newInstance = Instance.fromJson(instanceRequest); completedFuture(newInstance) .thenCompose(InstancePrecedingSucceedingTitleValidators::refuseWhenUnconnectedHasNoTitle) .thenCompose(instance -> storage.getInstanceCollection(context).add(instance)) .thenCompose(response -> { response.setParentInstances(newInstance.getParentInstances()); response.setChildInstances(newInstance.getChildInstances()); response.setPrecedingTitles(newInstance.getPrecedingTitles()); response.setSucceedingTitles(newInstance.getSucceedingTitles()); return updateRelatedRecords(routingContext, context, response).thenApply(notUsed -> response); }).thenAccept(response -> { try { URL url = context.absoluteUrl(format("%s/%s", INSTANCES_PATH, response.getId())); RedirectResponse.created(routingContext.response(), url.toString()); } catch (MalformedURLException e) { log.warn( format("Failed to create self link for instance: %s", e.toString())); } }).exceptionally(doExceptionally(routingContext)); } private void update(RoutingContext rContext) { WebContext wContext = new WebContext(rContext); JsonObject instanceRequest = rContext.getBodyAsJson(); Instance updatedInstance = Instance.fromJson(instanceRequest); InstanceCollection instanceCollection = storage.getInstanceCollection(wContext); completedFuture(updatedInstance) .thenCompose(InstancePrecedingSucceedingTitleValidators::refuseWhenUnconnectedHasNoTitle) .thenCompose(instance -> instanceCollection.findById(rContext.request().getParam("id"))) .thenCompose(InstancesValidators::refuseWhenInstanceNotFound) .thenCompose(existingInstance -> fetchPrecedingSucceedingTitles(new Success<>(existingInstance), rContext, wContext)) .thenCompose(existingInstance -> refuseWhenBlockedFieldsChanged(existingInstance, updatedInstance)) .thenCompose(existingInstance -> refuseWhenHridChanged(existingInstance, updatedInstance)) .thenAccept(existingInstance -> updateInstance(updatedInstance, rContext, wContext)) .exceptionally(doExceptionally(rContext)); } /** * Call Source record storage to update suppress from discovery flag in underlying record * * @param wContext - webContext * @param updatedInstance - Updated instance entity */ private void updateSuppressFromDiscoveryFlag(WebContext wContext, Instance updatedInstance) { try { SourceStorageRecordsClient client = new SourceStorageRecordsClient(wContext.getOkapiLocation(), wContext.getTenantId(), wContext.getToken()); client.putSourceStorageRecordsSuppressFromDiscoveryById(updatedInstance.getId(), "INSTANCE", updatedInstance.getDiscoverySuppress(), httpClientResponse -> { if (httpClientResponse.result().statusCode() == HttpStatus.HTTP_OK.toInt()) { log.info(format("Suppress from discovery flag was successfully updated for record in SRS. InstanceID: %s", updatedInstance.getId())); } else { log.error(format("Suppress from discovery wasn't changed for SRS record. InstanceID: %s StatusCode: %s", updatedInstance.getId(), httpClientResponse.result().statusCode())); } }); } catch (Exception e) { log.error("Error during updating suppress from discovery flag for record in SRS", e); } } /** * Returns true if given Instance has linked record in source-record-storage * * @param instance given instance * @return boolean */ private boolean isInstanceControlledByRecord(Instance instance) { return "MARC".equals(instance.getSource()); } /** * Updates given Instance * * @param instance instance for update * @param rContext routing context * @param wContext web context */ private void updateInstance(Instance instance, RoutingContext rContext, WebContext wContext) { InstanceCollection instanceCollection = storage.getInstanceCollection(wContext); instanceCollection.update( instance, v -> { updateRelatedRecords(rContext, wContext, instance) .whenComplete((result, ex) -> { if (ex != null) { log.warn("Exception occurred", ex); handleFailure(getKnownException(ex), rContext); } else { noContent(rContext.response()); } }); if (isInstanceControlledByRecord(instance)) { updateSuppressFromDiscoveryFlag(wContext, instance); } }, FailureResponseConsumer.serverError(rContext.response())); } /** * Compares existing instance with it's version for update, * returns true if blocked fields are changed * * @param existingInstance instance that exists in database * @param updatedInstance instance with changes for update * @return boolean */ private boolean areInstanceBlockedFieldsChanged(Instance existingInstance, Instance updatedInstance) { JsonObject existingInstanceJson = JsonObject.mapFrom(existingInstance); JsonObject updatedInstanceJson = JsonObject.mapFrom(updatedInstance); zeroingFields(existingInstanceJson.getJsonArray(Instance.PRECEDING_TITLES_KEY)); zeroingFields(existingInstanceJson.getJsonArray(Instance.SUCCEEDING_TITLES_KEY)); Map<String, Object> existingBlockedFields = new HashMap<>(); Map<String, Object> updatedBlockedFields = new HashMap<>(); for (String blockedFieldCode : config.getInstanceBlockedFields()) { existingBlockedFields.put(blockedFieldCode, existingInstanceJson.getValue(blockedFieldCode)); updatedBlockedFields.put(blockedFieldCode, updatedInstanceJson.getValue(blockedFieldCode)); } return ObjectUtils.notEqual(existingBlockedFields, updatedBlockedFields); } private void zeroingFields(JsonArray precedingSucceedingTitles) { if (precedingSucceedingTitles.isEmpty()) { return; } for (int index = 0; index < precedingSucceedingTitles.size(); index++) { JsonObject jsonObject = precedingSucceedingTitles.getJsonObject(index); jsonObject.put(ID, null); jsonObject.put(PrecedingSucceedingTitle.PRECEDING_INSTANCE_ID_KEY, null); jsonObject.put(PrecedingSucceedingTitle.SUCCEEDING_INSTANCE_ID_KEY, null); } } private void deleteAll(RoutingContext routingContext) { WebContext context = new WebContext(routingContext); storage.getInstanceCollection(context).empty( v -> noContent(routingContext.response()), FailureResponseConsumer.serverError(routingContext.response())); } private void deleteById(RoutingContext routingContext) { WebContext context = new WebContext(routingContext); storage.getInstanceCollection(context).delete( routingContext.request().getParam("id"), v -> noContent(routingContext.response()), FailureResponseConsumer.serverError(routingContext.response())); } private void getById(RoutingContext routingContext) { WebContext context = new WebContext(routingContext); storage.getInstanceCollection(context).findById( routingContext.request().getParam("id"), it -> { Instance instance = it.getResult(); if (instance != null) { completedFuture(instance) .thenCompose(response -> fetchInstanceRelationships(it, routingContext, context)) .thenCompose(response -> fetchPrecedingSucceedingTitles(it, routingContext, context)) .thenCompose(response -> setBoundWithFlag(it, routingContext, context)) .thenAccept(response -> successResponse(routingContext, context, response)); } else { ClientErrorResponse.notFound(routingContext.response()); } }, FailureResponseConsumer.serverError(routingContext.response())); } private CompletableFuture<Instance> setBoundWithFlag (Success<Instance> success, RoutingContext routingContext, WebContext webContext) { Instance instance = success.getResult(); return findBoundWithHoldingsIdsForInstanceId(instance.getId(), routingContext, webContext).thenCompose( boundWithHoldings -> { instance.setIsBoundWith(boundWithHoldings != null && !boundWithHoldings.isEmpty()); return completedFuture(instance); } ); } /** * Fetches instance relationships for multiple Instance records, populates, responds * * @param instancesResponse Multi record Instances result * @param routingContext Routing */ private CompletableFuture<InstancesResponse> fetchRelationships( InstancesResponse instancesResponse, RoutingContext routingContext) { final List<String> instanceIds = getInstanceIdsFromInstanceResult(instancesResponse.getSuccess()); return createInstanceRelationshipsService(routingContext) .fetchInstanceRelationships(instanceIds) .thenCompose(response -> withInstancesRelationships(instancesResponse, response)); } private CompletableFuture<InstancesResponse> fetchPrecedingSucceedingTitles( InstancesResponse instancesResponse, RoutingContext routingContext, WebContext context) { List<String> instanceIds = getInstanceIdsFromInstanceResult(instancesResponse.getSuccess()); return createInstanceRelationshipsService(routingContext) .fetchInstancePrecedingSucceedingTitles(instanceIds) .thenCompose(response -> withPrecedingSucceedingTitles(routingContext, context, instancesResponse, response)); } private CompletableFuture<List<JsonObject>> fetchHoldingsRecordsForInstanceRecordSet( InstancesResponse instancesResponse, RoutingContext routingContext, WebContext context) { List<String> instanceIds = getInstanceIdsFromInstanceResult(instancesResponse.getSuccess()); MultipleRecordsFetchClient holdingsFetcher = MultipleRecordsFetchClient.builder() .withCollectionPropertyName("holdingsRecords") .withExpectedStatus(200) .withCollectionResourceClient(createHoldingsStorageClient(routingContext, context)) .build(); return holdingsFetcher.find(instanceIds, this::cqlMatchAnyByInstanceIds); } /** * Retrieves a list of IDs for the holdings under the provided Instance that are part of a bound-with. * @param instanceId The ID of the Instance to find bound-with holdings for * @param routingContext Routing * @param webContext Context * @return List of IDs of holdings records that are bound-with */ private CompletableFuture<List<String>> findBoundWithHoldingsIdsForInstanceId( String instanceId, RoutingContext routingContext, WebContext webContext ) { CompletableFuture<Response> holdingsFuture = new CompletableFuture<>(); createHoldingsStorageClient(routingContext, webContext).getAll("instanceId=="+instanceId, holdingsFuture::complete); return holdingsFuture.thenCompose( response -> { List<String> holdingsRecordsList = response.getJson().getJsonArray("holdingsRecords") .stream().map(o -> ((JsonObject) o).getString("id")).collect(Collectors.toList()); return checkHoldingsForBoundWith(holdingsRecordsList, routingContext, webContext); } ); } /** * From the provided list of holdings record IDs, finds out which of them * are part of bound-withs -- if any -- and returns a list of those. * @param holdingsRecordIds holdings records to check for bound-with * @param routingContext Routing * @param webContext Context * @return List of IDs for holdings records that are bound with others. */ private CompletableFuture<List<String>> checkHoldingsForBoundWith( List<String> holdingsRecordIds, RoutingContext routingContext, WebContext webContext) { List<String> holdingsRecordsThatAreBoundWith = new ArrayList<>(); String holdingsRecordIdKey = "holdingsRecordId"; // Check if any IDs in the list of holdings appears in bound-with-parts return MultipleRecordsFetchClient .builder() .withCollectionPropertyName("boundWithParts") .withExpectedStatus(200) .withCollectionResourceClient(createBoundWithPartsClient(routingContext, webContext)) .build() .find(holdingsRecordIds, this::cqlMatchAnyByHoldingsRecordIds) .thenCompose( boundWithParts -> { holdingsRecordsThatAreBoundWith.addAll(boundWithParts.stream() .map( boundWithPart -> boundWithPart.getString( holdingsRecordIdKey )) .collect( Collectors.toList())); // Check if any of the holdings has an item that appears in bound-with-parts // First, find the holdings' items return MultipleRecordsFetchClient .builder() .withCollectionPropertyName( "items" ) .withExpectedStatus( 200 ) .withCollectionResourceClient( createItemsStorageClient( routingContext, webContext ) ) .build() .find( holdingsRecordIds, this::cqlMatchAnyByHoldingsRecordIds) .thenCompose( items -> { List<String> itemIds = new ArrayList<>(); Map<String,String> itemHoldingsMap = new HashMap<>(); for (JsonObject item : items) { itemHoldingsMap.put(item.getString( "id" ), item.getString( holdingsRecordIdKey )); itemIds.add(item.getString( "id" )); } // Then look up the items in bound-with-parts return MultipleRecordsFetchClient .builder() .withCollectionPropertyName( "boundWithParts" ) .withExpectedStatus( 200 ) .withCollectionResourceClient( createBoundWithPartsClient( routingContext, webContext ) ) .build() .find( itemIds, this::cqlMatchAnyByItemIds ) .thenCompose( boundWithParts2 -> { List<String> boundWithItemIds = boundWithParts2.stream() .map(boundWithPart2 -> boundWithPart2.getString( "itemId" )) .distinct() .collect(Collectors.toList()); for (String itemId : boundWithItemIds) { holdingsRecordsThatAreBoundWith.add(itemHoldingsMap.get(itemId)); } return completedFuture( holdingsRecordsThatAreBoundWith ); }); }); }); } /** * Checks if any holdings/items under the listed instances are parts of bound-withs * and sets a flag on each Instance in the response where that is true * @param instancesResponse Instance result set * @param routingContext Routing * @param webContext Context * @return Returns the provided result set with 0 or more Instances marked as bound-with */ private CompletableFuture<InstancesResponse> lookUpBoundWithsForInstanceRecordSet( InstancesResponse instancesResponse, RoutingContext routingContext, WebContext webContext) { if (instancesResponse.hasRecords()) { return fetchHoldingsRecordsForInstanceRecordSet(instancesResponse, routingContext, webContext) .thenCompose(holdingsRecordList -> { if (holdingsRecordList.isEmpty()) { return completedFuture(instancesResponse); } else { Map<String, String> holdingsToInstanceMap = new HashMap<>(); for (JsonObject holdingsRecord : holdingsRecordList) { holdingsToInstanceMap.put(holdingsRecord.getString("id"), holdingsRecord.getString("instanceId")); } ArrayList<String> holdingsIdsList = new ArrayList<>(holdingsToInstanceMap.keySet()); return checkHoldingsForBoundWith(holdingsIdsList, routingContext, webContext) .thenCompose(holdingsRecordIds -> { List<String> boundWithInstanceIds = new ArrayList<>(); for (String holdingsRecordId : holdingsRecordIds) { boundWithInstanceIds.add(holdingsToInstanceMap.get(holdingsRecordId)); } instancesResponse.setBoundWithInstanceIds(boundWithInstanceIds); return completedFuture(instancesResponse); } ); } }); } else { return completedFuture(instancesResponse); } } /** * Fetches instance relationships for a single Instance result, populates, responds * * @param success Single record Instance result * @param routingContext Routing * @param context Context */ private CompletableFuture<Instance> fetchInstanceRelationships( Success<Instance> success, RoutingContext routingContext, WebContext context) { Instance instance = success.getResult(); List<String> instanceIds = getInstanceIdsFromInstanceResult(success); String query = createQueryForRelatedInstances(instanceIds); CollectionResourceClient relatedInstancesClient = createInstanceRelationshipsClient(routingContext, context); if (relatedInstancesClient != null) { CompletableFuture<Response> relatedInstancesFetched = new CompletableFuture<>(); relatedInstancesClient.getMany(query, Integer.MAX_VALUE, 0, relatedInstancesFetched::complete); return relatedInstancesFetched .thenCompose(response -> withInstanceRelationships(instance, response)); } return completedFuture(null); } private void successResponse(RoutingContext routingContext, WebContext context, Instance instance) { JsonResponse.success(routingContext.response(), instance.getJsonForResponse(context)); } private CompletableFuture<InstancesResponse> withInstancesRelationships( InstancesResponse instancesResponse, List<JsonObject> relationsList) { Map<String, List<InstanceRelationshipToParent>> parentInstanceMap = new HashMap<>(); Map<String, List<InstanceRelationshipToChild>> childInstanceMap = new HashMap<>(); relationsList.forEach(rel -> { addToList(childInstanceMap, rel.getString("superInstanceId"), new InstanceRelationshipToChild(rel)); addToList(parentInstanceMap, rel.getString("subInstanceId"), new InstanceRelationshipToParent(rel)); }); instancesResponse.setChildInstanceMap(childInstanceMap); instancesResponse.setParentInstanceMap(parentInstanceMap); return CompletableFuture.completedFuture(instancesResponse); } private CompletableFuture<Instance> withInstanceRelationships(Instance instance, Response result) { List<InstanceRelationshipToParent> parentInstanceList = new ArrayList<>(); List<InstanceRelationshipToChild> childInstanceList = new ArrayList<>(); if (result.getStatusCode() == 200) { JsonObject json = result.getJson(); List<JsonObject> relationsList = JsonArrayHelper.toList(json.getJsonArray("instanceRelationships")); relationsList.forEach(rel -> { if (rel.getString(InstanceRelationship.SUPER_INSTANCE_ID_KEY).equals(instance.getId())) { childInstanceList.add(new InstanceRelationshipToChild(rel)); } else if (rel.getString(InstanceRelationship.SUB_INSTANCE_ID_KEY).equals(instance.getId())) { parentInstanceList.add(new InstanceRelationshipToParent(rel)); } }); instance.getParentInstances().addAll(parentInstanceList); instance.getChildInstances().addAll(childInstanceList); } return completedFuture(instance); } private CompletableFuture<Instance> fetchPrecedingSucceedingTitles( Success<Instance> success, RoutingContext routingContext, WebContext context) { Instance instance = success.getResult(); List<String> instanceIds = getInstanceIdsFromInstanceResult(success); String queryForPrecedingSucceedingInstances = createQueryForPrecedingSucceedingInstances(instanceIds); CollectionResourceClient precedingSucceedingTitlesClient = createPrecedingSucceedingTitlesClient(routingContext, context); CompletableFuture<Response> precedingSucceedingTitlesFetched = new CompletableFuture<>(); precedingSucceedingTitlesClient.getAll(queryForPrecedingSucceedingInstances, precedingSucceedingTitlesFetched::complete); return precedingSucceedingTitlesFetched .thenCompose(response -> withPrecedingSucceedingTitles(routingContext, context, instance, response)); } // Utilities private CqlQuery cqlMatchAnyByInstanceIds(List<String> instanceIds) { return CqlQuery.exactMatchAny("instanceId", instanceIds); } private CqlQuery cqlMatchAnyByHoldingsRecordIds(List<String> holdingsRecordIds) { return CqlQuery.exactMatchAny("holdingsRecordId", holdingsRecordIds); } private CqlQuery cqlMatchAnyByItemIds (List<String> itemIds) { return CqlQuery.exactMatchAny( "itemId", itemIds ); } private List<String> getInstanceIdsFromInstanceResult(Success success) { List<String> instanceIds = new ArrayList<>(); if (success.getResult() instanceof Instance) { instanceIds = Collections.singletonList(((Instance) success.getResult()).getId()); } else if (success.getResult() instanceof MultipleRecords) { instanceIds = (((MultipleRecords<Instance>) success.getResult()).records.stream() .map(Instance::getId) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList())); } return instanceIds; } private synchronized <T> void addToList(Map<String, List<T>> items, String mapKey, T myItem) { List<T> itemsList = items.get(mapKey); // if list does not exist create it if (itemsList == null) { itemsList = new ArrayList<>(); itemsList.add(myItem); items.put(mapKey, itemsList); } else { // add if item is not already in list if (!itemsList.contains(myItem)) { itemsList.add(myItem); } } } private CompletableFuture<InstancesResponse> withPrecedingSucceedingTitles( RoutingContext routingContext, WebContext context, InstancesResponse instancesResponse, List<JsonObject> relationsList) { Map<String, List<CompletableFuture<PrecedingSucceedingTitle>>> precedingTitlesMap = new HashMap<>(); Map<String, List<CompletableFuture<PrecedingSucceedingTitle>>> succeedingTitlesMap = new HashMap<>(); relationsList.forEach(rel -> { final String precedingInstanceId = rel.getString(PrecedingSucceedingTitle.SUCCEEDING_INSTANCE_ID_KEY); if (StringUtils.isNotBlank(precedingInstanceId)) { addToList(precedingTitlesMap, precedingInstanceId, getPrecedingSucceedingTitle(routingContext, context, rel, PrecedingSucceedingTitle.PRECEDING_INSTANCE_ID_KEY)); } final String succeedingInstanceId = rel.getString(PrecedingSucceedingTitle.PRECEDING_INSTANCE_ID_KEY); if (StringUtils.isNotBlank(succeedingInstanceId)) { addToList(succeedingTitlesMap, succeedingInstanceId, getPrecedingSucceedingTitle(routingContext, context, rel, PrecedingSucceedingTitle.SUCCEEDING_INSTANCE_ID_KEY)); } }); return completedFuture(instancesResponse) .thenCompose(r -> withPrecedingTitles(instancesResponse, precedingTitlesMap)) .thenCompose(r -> withSucceedingTitles(instancesResponse, succeedingTitlesMap)); } private CompletableFuture<Instance> withPrecedingSucceedingTitles( RoutingContext routingContext, WebContext context, Instance instance, Response result) { if (result.getStatusCode() == 200) { JsonObject json = result.getJson(); List<JsonObject> relationsList = JsonArrayHelper.toList(json.getJsonArray("precedingSucceedingTitles")); List<CompletableFuture<PrecedingSucceedingTitle>> precedingTitleCompletableFutures = relationsList.stream().filter(rel -> isPrecedingTitle(instance, rel)) .map(rel -> getPrecedingSucceedingTitle(routingContext, context, rel, PrecedingSucceedingTitle.PRECEDING_INSTANCE_ID_KEY)).collect(Collectors.toList()); List<CompletableFuture<PrecedingSucceedingTitle>> succeedingTitleCompletableFutures = relationsList.stream().filter(rel -> isSucceedingTitle(instance, rel)) .map(rel -> getPrecedingSucceedingTitle(routingContext, context, rel, PrecedingSucceedingTitle.SUCCEEDING_INSTANCE_ID_KEY)).collect(Collectors.toList()); return completedFuture(instance) .thenCompose(r -> withPrecedingTitles(instance, precedingTitleCompletableFutures)) .thenCompose(r -> withSucceedingTitles(instance, succeedingTitleCompletableFutures)); } return completedFuture(null); } private boolean isPrecedingTitle(Instance instance, JsonObject rel) { return instance.getId().equals( rel.getString(PrecedingSucceedingTitle.SUCCEEDING_INSTANCE_ID_KEY)); } private boolean isSucceedingTitle(Instance instance, JsonObject rel) { return instance.getId().equals( rel.getString(PrecedingSucceedingTitle.PRECEDING_INSTANCE_ID_KEY)); } private CompletionStage<Instance> withSucceedingTitles(Instance instance, List<CompletableFuture<PrecedingSucceedingTitle>> succeedingTitleCompletableFutures) { return allResultsOf(succeedingTitleCompletableFutures) .thenApply(instance::setSucceedingTitles); } private CompletableFuture<Instance> withPrecedingTitles(Instance instance, List<CompletableFuture<PrecedingSucceedingTitle>> precedingTitleCompletableFutures) { return allResultsOf(precedingTitleCompletableFutures) .thenApply(instance::setPrecedingTitles); } private CompletableFuture<InstancesResponse> withPrecedingTitles( InstancesResponse instance, Map<String, List<CompletableFuture<PrecedingSucceedingTitle>>> precedingTitles) { return mapToCompletableFutureMap(precedingTitles) .thenApply(instance::setPrecedingTitlesMap); } private CompletableFuture<InstancesResponse> withSucceedingTitles( InstancesResponse instance, Map<String, List<CompletableFuture<PrecedingSucceedingTitle>>> precedingTitles) { return mapToCompletableFutureMap(precedingTitles) .thenApply(instance::setSucceedingTitlesMap); } private CompletableFuture<Map<String, List<PrecedingSucceedingTitle>>> mapToCompletableFutureMap( Map<String, List<CompletableFuture<PrecedingSucceedingTitle>>> precedingTitles) { Map<String, CompletableFuture<List<PrecedingSucceedingTitle>>> map = precedingTitles.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> allResultsOf(e.getValue()))); return CompletableFuture.allOf(map.values().toArray(new CompletableFuture[0])) .thenApply(r -> map.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().join()))); } private CompletableFuture<PrecedingSucceedingTitle> getPrecedingSucceedingTitle( RoutingContext routingContext, WebContext context, JsonObject rel, String precedingSucceedingKey) { if (!StringUtils.isBlank(rel.getString(precedingSucceedingKey))) { String precedingInstanceId = rel.getString(precedingSucceedingKey); CompletableFuture<Success<Instance>> getInstanceFuture = new CompletableFuture<>(); storage .getInstanceCollection(context).findById(precedingInstanceId, getInstanceFuture::complete, FailureResponseConsumer.serverError(routingContext.response())); return getInstanceFuture.thenApply(response -> { Instance precedingInstance = response.getResult(); if (precedingInstance != null) { return PrecedingSucceedingTitle.from(rel, precedingInstance.getTitle(), precedingInstance.getHrid(), new JsonArray(precedingInstance.getIdentifiers())); } else { return null; } }); } else { return completedFuture(PrecedingSucceedingTitle.from(rel)); } } private InstanceRelationshipsService createInstanceRelationshipsService(RoutingContext routingContext) { final WebContext webContext = new WebContext(routingContext); return new InstanceRelationshipsService( createInstanceRelationshipsClient(routingContext, webContext), createPrecedingSucceedingTitlesClient(routingContext, webContext)); } private CompletionStage<Instance> refuseWhenBlockedFieldsChanged( Instance existingInstance, Instance updatedInstance) { if (isInstanceControlledByRecord(existingInstance) && areInstanceBlockedFieldsChanged(existingInstance, updatedInstance)) { String errorMessage = BLOCKED_FIELDS_UPDATE_ERROR_MESSAGE + StringUtils .join(config.getInstanceBlockedFields(), COMMA); log.error(errorMessage); return failedFuture(new UnprocessableEntityException(errorMessage, null, null)); } return completedFuture(existingInstance); } }
MaxOnNet/scopuli-core-web
Scopuli/WEB/Modules/Catalog/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright [2018] <NAME> [<EMAIL>] # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ """ from Scopuli.Interfaces.WEB.Module import WebModule import Scopuli.Interfaces.MySQL.Schema.Web.Module.Catalog as Schema from flask import request, abort from werkzeug.local import LocalProxy class WebCatalog(WebModule): _instance_name = "Catalog" _template_name = "/catalog/module.html" _routes = {} _dependency = [] filter_type = "" filter_value = "" def load(self): self.filter_type = LocalProxy(self.get_filter_type) self.filter_value = LocalProxy(self.get_filter_value) self._routes = { "{}".format(self._page.url) : 'render_root', "{}/<string:url>".format(self._page.url): 'render_child' } @staticmethod def get_filter_type(): __filter_type = getattr(request, '_4g_catalog_filter_type', None) if __filter_type is not None: return __filter_type else: return "" @staticmethod def set_filter_type(value): setattr(request, '_4g_catalog_filter_type', value) @staticmethod def get_filter_value(): __filter_value = getattr(request, '_4g_catalog_filter_value', None) if __filter_value is not None: return __filter_value else: return "" @staticmethod def set_filter_value(value): setattr(request, '_4g_catalog_filter_value', value) @property def item(self): if self.filter_type == "url": query = self._database.query(Schema.WebModuleCatalog) query = query.filter(Schema.WebModuleCatalog.cd_web_site == self._site.id) query = query.filter(Schema.WebModuleCatalog.is_published == True) query = query.filter(Schema.WebModuleCatalog.is_deleted == False) query = query.filter(Schema.WebModuleCatalog.url == self.filter_value) for item in query.all(): return item return None @property def items(self): query = self._database.query(Schema.WebModuleCatalog) query = query.filter(Schema.WebModuleCatalog.cd_web_site == self._site.id) query = query.filter(Schema.WebModuleCatalog.is_deleted == False) query = query.filter(Schema.WebModuleCatalog.is_published == True) if self.filter_type == "url": query = query.filter(Schema.WebModuleCatalog.cd_parent == self.item.id) items = [] for item in query.all(): items.append(item) return items def render_root(self, caller=None): self.set_filter_type("") self.set_filter_value("") return WebModule.render(self) def render_child(self, url=None, caller=None): self.set_filter_type("url") self.set_filter_value(url) if self.item is None: abort(404) return WebModule.render(self)
wmg2328/java-smart-parts
src/com/wmg/smartjava/patterns/builder/Employee.java
<reponame>wmg2328/java-smart-parts package com.wmg.smartjava.patterns.builder; /** * Separate the construction of a complex object from its representation. Then the same construction process * can be reused to generate different objects */ public class Employee { private long id; private String name; private String department; private double salary; private int age; private short performanceIndex; private int experience; private Employee(long id, String name, String department, double salary, int age, short performanceIndex, int experience) { this.id = id; this.name = name; this.department = department; this.salary = salary; this.age = age; this.performanceIndex = performanceIndex; this.experience = experience; } public static EmployeeBuilder builder() { return new EmployeeBuilder(); } public static class EmployeeBuilder { private long id; private String name; private String department; private double salary; private int age; private short performanceIndex; private int experience; public EmployeeBuilder id(long id) { this.id = id; return this; } public EmployeeBuilder name(String name) { this.name = name; return this; } public EmployeeBuilder department(String department) { this.department = department; return this; } public EmployeeBuilder salary(double salary) { this.salary = salary; return this; } public EmployeeBuilder age(int age) { this.age = age; return this; } public EmployeeBuilder performanceIndex(short performanceIndex) { this.performanceIndex = performanceIndex; return this; } public EmployeeBuilder experience(int experience) { this.experience = experience; return this; } public Employee build() { return new Employee(this.id, this.name, this.department, this.salary, this.age, this.performanceIndex, this.experience); } } @Override public String toString() { return "EmployeeBuilder{" + "id=" + id + ", name='" + name + '\'' + ", department='" + department + '\'' + ", salary=" + salary + ", age=" + age + ", performanceIndex=" + performanceIndex + ", experience=" + experience + '}'; } }
huberyHU2018/LightAdapter
component_basic/src/main/java/com/zfy/component/basic/app/AppActivity.java
package com.zfy.component.basic.app; import android.arch.lifecycle.Lifecycle; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.zfy.component.basic.app.view.IBaseView; import com.zfy.component.basic.app.view.IElegantView; import com.zfy.component.basic.app.view.IOnResultView; import com.zfy.component.basic.app.view.IViewInit; import com.zfy.component.basic.app.view.ViewConfig; import com.zfy.component.basic.foundation.api.Api; import org.greenrobot.eventbus.Subscribe; /** * CreateAt : 2018/10/11 * Describe : * * @author chendong */ public abstract class AppActivity extends AppCompatActivity implements IElegantView, IViewInit, IBaseView, IOnResultView { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); beforeViewInit(); getAppDelegate().bindActivity(this); init(); } protected void beforeViewInit() { } @Override public ViewConfig getViewConfig() { return null; } // elegant view @Override public Context getContext() { return this; } @Override public AppActivity getActivity() { return this; } @Override public void launchActivity(Intent data, int requestCode) { if (requestCode == 0) { startActivity(data); } else { startActivityForResult(data, requestCode); } } @Override public @NonNull Bundle getData() { return getAppDelegate().getBundle(); } @Override public Lifecycle getLifecycle() { return getAppDelegate().getLifecycle(); } @Subscribe public void ignoreEvent(AppDelegate thiz) { } @Override protected void onDestroy() { super.onDestroy(); getAppDelegate().onDestroy(); if (Api.queue() != null) { Api.queue().cancelRequest(hashCode()); } } @Override public void finishUI(Intent intent, int code) { if (intent != null) { setResult(code, intent); } finish(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); getAppDelegate().onActivityResult(requestCode, resultCode, data); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); getAppDelegate().onRequestPermissionsResult(requestCode, permissions, grantResults); } }
podsvirov/colm-suite
test/aapl.d/stress_svectsimp.cpp
<filename>test/aapl.d/stress_svectsimp.cpp /* * Copyright 2002, 2003 <NAME> <<EMAIL>> * * 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 <iostream> #include <stdio.h> #include <assert.h> #include <time.h> #include "vectsimp.h" #include "svectsimp.h" using namespace std; void processArgs( int argc, char** argv ); template class SVectSimp<char>; /* Data structure whos constructors and destructor count callings. */ struct TheData { TheData() : i(0) { } TheData(int i) : i(i) { } TheData(const TheData &d) : i(1) { } ~TheData() { } int i; }; bool operator==(const TheData &td1, const TheData &td2) { return td1.i == td2.i; } #define LEN_THRESH 1000 #define STATS_PERIOD 211 #define OUTBUFSIZE 1000 //#define NUM_ROUNDS 1e9 #define NUM_ROUNDS 100000 int curRound = 0; void expandTab( char *dst, char *src ); /* Print a statistics header. */ void printHeader() { char buf[OUTBUFSIZE]; expandTab( buf, "round\tlength" ); cout << buf << endl; } /* Replace the current stats line with new stats. For one tree. */ void printStats( VectSimp<TheData> &v1 ) { /* Print stats. */ static char buf[OUTBUFSIZE] = { 0 }; char tmpBuf[OUTBUFSIZE]; memset( buf, '\b', strlen(buf) ); cout << buf; sprintf( tmpBuf, "%i\t%li\t", curRound, v1.length() ); expandTab( buf, tmpBuf ); cout << buf; cout.flush(); } VectSimp<TheData> v1; SVectSimp<TheData> v2; VectSimp<TheData> v1Copy; SVectSimp<TheData> v2Copy; int main( int argc, char **argv ) { processArgs( argc, argv ); srandom(time(0)); printHeader(); for ( curRound = 0; ; curRound++ ) { /* Choose an action. */ int action = random() % 7; /* 0: remove * 1: setAs * 2: prepend * 3: append * 4: insert * 5: replace * 6: copy */ /* Exclude remove when already empty. */ if ( action == 0 && v1.length() == 0 ) continue; /* Exclude growing when at max len. */ if ( 3 <= action && v1.length() > LEN_THRESH ) continue; switch ( action ) { /* remove. */ case 0: { /* Get a position and length. */ int pos = random() % (v1.length()+1); int len = random() % (v1.length() - pos + 1); v1.remove( pos, len ); v2.remove( pos, len ); break; } /* setAs. */ case 1: { int len = random() % LEN_THRESH; TheData *tmpD = new TheData[len]; for ( int i = 0; i < len; i++ ) tmpD[i].i = random(); v1.setAs( tmpD, len ); v2.setAs( tmpD, len ); delete[] tmpD; break; } /* prepend. */ case 2: { int len = random() % LEN_THRESH; TheData *tmpD = new TheData[len]; for ( int i = 0; i < len; i++ ) tmpD[i].i = random(); v1.prepend( tmpD, len ); v2.prepend( tmpD, len ); delete[] tmpD; break; } /* append. */ case 3: { int len = random() % LEN_THRESH; TheData *tmpD = new TheData[len]; for ( int i = 0; i < len; i++ ) tmpD[i].i = random(); v1.append( tmpD, len ); v2.append( tmpD, len ); delete[] tmpD; break; } /* insert. */ case 4: { int pos = random() % (v1.length()+1); int len = random() % LEN_THRESH; TheData *tmpD = new TheData[len]; for ( int i = 0; i < len; i++ ) tmpD[i].i = random(); v1.insert( pos, tmpD, len ); v2.insert( pos, tmpD, len ); delete[] tmpD; break; } /* replace. */ case 5: { int pos = random() % (v1.length()+1); int len = random() % LEN_THRESH; TheData *tmpD = new TheData[len]; for ( int i = 0; i < len; i++ ) tmpD[i].i = random(); v1.replace( pos, tmpD, len ); v2.replace( pos, tmpD, len ); delete[] tmpD; break; } /* copy. */ case 6: { VectSimp<TheData> v1Loc(v1); v1Copy = v1; SVectSimp<TheData> v2Loc(v2); v2Copy = v2; } } /* Assert that the vectors are equal. */ VectSimp<TheData>::Iter v1It = v1; SVectSimp<TheData>::Iter v2It = v2; assert( v1.size() == v2.size() ); for ( int i = 0; i < v1.size(); i++, v1It++, v2It++ ) assert( *v1It == *v2It ); if ( curRound % STATS_PERIOD ) printStats( v1 ); curRound += 1; } cout << endl; return 0; }
kuailemy123/gitlab-cn.github.io
lib/banzai/reference_parser/issue_parser.rb
module Banzai module ReferenceParser class IssueParser < BaseParser self.reference_type = :issue def nodes_visible_to_user(user, nodes) # It is not possible to check access rights for external issue trackers return nodes if project && project.external_issue_tracker issues = issues_for_nodes(nodes) nodes.select do |node| issue = issue_for_node(issues, node) issue ? can?(user, :read_issue, issue) : false end end def referenced_by(nodes) issues = issues_for_nodes(nodes) nodes.map { |node| issue_for_node(issues, node) }.uniq end def issues_for_nodes(nodes) @issues_for_nodes ||= grouped_objects_for_nodes( nodes, Issue.all.includes( :author, :assignee, { # These associations are primarily used for checking permissions. # Eager loading these ensures we don't end up running dozens of # queries in this process. project: [ { namespace: :owner }, { group: [:owners, :group_members] }, :invited_groups, :project_members ] } ), self.class.data_attribute ) end private def issue_for_node(issues, node) issues[node.attr(self.class.data_attribute).to_i] end end end end
fgalar/Corewar
vm/src/loading/players.c
<reponame>fgalar/Corewar<filename>vm/src/loading/players.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* players.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ciglesia <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/26 17:09:58 by ciglesia #+# #+# */ /* Updated: 2020/09/30 20:05:48 by ciglesia ### ########.fr */ /* */ /* ************************************************************************** */ #include "vm.h" t_player *new_player(void) { t_player *new; new = NULL; if (!(new = (t_player*)malloc(sizeof(t_player)))) return (NULL); ft_memset(new->name, 0, PROG_NAME_LENGTH); ft_memset(new->comment, 0, COMMENT_LENGTH); ft_memset(new->code, 0, CHAMP_MAX_SIZE); new->nplayer = -1; new->prog_size = 0; new->exec_magic = 0; new->pc_address = 0; new->nblive = 0; new->last_live_cycle = 0; new->next = NULL; return (new); } void add_player(t_vm *vm, t_player *new) { new->next = vm->player; vm->player = new; vm->nplayers++; } void player_won(t_vm *vm, t_player *champion, int ncurses) { int color; color = 1; while (champion) { color++; if (vm->last_alive == champion->nplayer) { if (ncurses) { champion_won(vm->p_win, vm, champion, color); while (getch() != 'q') { resize_window(vm); champion_won(vm->p_win, vm, champion, color); } endwin(); return ; } ft_printf("Player %d (%s) won\n", vm->last_alive, champion->name); return ; } champion = champion->next; } (ncurses) ? endwin() : 0; } void kill_players(t_vm *vm) { t_player *champion; t_player *aux; champion = vm->player; while (champion) { (vm->verbosity) ? ft_printf(CYAN"Killing: %s\n"E0M, champion->name) : 0; aux = champion; champion = champion->next; free(aux); } vm->player = NULL; }
WoodoLee/TorchCraft
3rdparty/range-v3/doc/gh-pages/structranges_1_1v3_1_1adl__begin__end__detail_1_1crend__fn.js
var structranges_1_1v3_1_1adl__begin__end__detail_1_1crend__fn = [ [ "operator()", "structranges_1_1v3_1_1adl__begin__end__detail_1_1crend__fn.html#a30ada025265481f41f074c68c5e58c90", null ] ];
gapry/libng
libng/core/src/libng_core/math/Vector/Vec3_SSE.hpp
<reponame>gapry/libng #pragma once #include <libng_core/math/Vector/Vec3_Basic.hpp> #include <libng_core/platform/sse.hpp> namespace libng { template<class T, class M> struct Vec3_SSE_Data {}; } // namespace libng
17hao/algorithm
src/leetcode/first/Code_113_PathSUm2.java
package leetcode.first; import leetcode.tool.TreeNode; import java.util.ArrayList; import java.util.List; /** * 路径总和2 * * @since 2020-5-24 Sunday 19:59 - 21:00 */ public class Code_113_PathSUm2 { static List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); if (root == null) return res; dfs(root, sum, res, new ArrayList<>()); return res; } static void dfs(TreeNode node, int sum, List<List<Integer>> res, List<Integer> tmp) { List<Integer> list = new ArrayList<>(tmp); if (node == null) { return; } else if (node.left == null && node.right == null && (sum - node.val == 0)) { list.add(node.val); res.add(list); return; } list.add(node.val); dfs(node.left, sum - node.val, res, list); dfs(node.right, sum - node.val, res, list); // if (node == null && sum == 0 && !res.contains(tmp)) { // res.add(new ArrayList<>(tmp)); // return; // } // if (node == null) { // return; // } // List<Integer> list = new ArrayList<>(tmp); // if ((sum - node.val) != 0) { // list.add(node.val); // if (node.left != null && node.right == null) { // dfs(node.left, sum - node.val, res, list); // } else if (node.right != null && node.left == null) { // dfs(node.right, sum - node.val, res, list); // } else { // dfs(node.left, sum - node.val, res, list); // dfs(node.right, sum - node.val, res, list); // } // } } public static void main(String[] args) { TreeNode root = new TreeNode(5); root.left = new TreeNode(4); root.right = new TreeNode(8); root.left.left = new TreeNode(11); root.right.left = new TreeNode(13); root.right.right = new TreeNode(4); root.left.left.left = new TreeNode(7); root.left.left.right = new TreeNode(2); root.right.right.left = new TreeNode(5); root.right.right.right = new TreeNode(1); System.out.println(pathSum(root, 22)); // TreeNode root = new TreeNode(1); // root.right = new TreeNode(2); // System.out.println(pathSum(root, 1)); } }
VinMannie/BombSquad-Community-Mod-Manager
mods/fightOfFaith.py
<gh_stars>1-10 import bs import random def bsGetAPIVersion(): # return the api-version this script expects. # this prevents it from attempting to run in newer versions of the game # where changes have been made to the modding APIs return 4 def bsGetGames(): return [FightOfFaithGame] def bsGetLevels(): # Levels are unique named instances of a particular game with particular settings. # They show up as buttons in the co-op section, get high-score lists associated with them, etc. return [bs.Level('Fight of Faith', # globally-unique name for this level (not seen by user) displayName='${GAME}', # ${GAME} will be replaced by the results of the game's getName() call gameType=FightOfFaithGame, settings={}, # we currently dont have any settings; we'd specify them here if we did. previewTexName='courtyardPreview')] class FightOfFaithGame(bs.TeamGameActivity): # name seen by the user @classmethod def getName(cls): return 'Fight of Faith' @classmethod def getScoreInfo(cls): return {'scoreType':'milliseconds', 'lowerIsBetter':True, 'scoreName':'Time'} @classmethod def getDescription(cls,sessionType): return 'How quickly you kill THEM?' @classmethod def getSupportedMaps(cls,sessionType): # for now we're hard-coding spawn positions and whatnot # so we need to be sure to specity that we only support # a specific map.. return ['Courtyard'] @classmethod def supportsSessionType(cls,sessionType): # we currently support Co-Op only return True if issubclass(sessionType,bs.CoopSession) else False # in the constructor we should load any media we need/etc. # but not actually create anything yet. def __init__(self,settings): bs.TeamGameActivity.__init__(self,settings) self._winSound = bs.getSound("score") # called when our game is transitioning in but not ready to start.. # ..we can go ahead and start creating stuff, playing music, etc. def onTransitionIn(self): bs.TeamGameActivity.onTransitionIn(self, music='ToTheDeath') # called when our game actually starts def onBegin(self): bs.TeamGameActivity.onBegin(self) self._won = False self.setupStandardPowerupDrops() # make our on-screen timer and start it roughly when our bots appear self._timer = bs.OnScreenTimer() bs.gameTimer(4000,self._timer.start) # this wrangles our bots self._bots = bs.BotSet() # start some timers to spawn bots bs.gameTimer(2000,bs.Call(self._bots.spawnBot,bs.MelBot,pos=(3,3,-2),spawnTime=3000)) bs.gameTimer(2000,bs.Call(self._bots.spawnBot,bs.ChickBot,pos=(-3,3,-2),spawnTime=3000)) bs.gameTimer(2000,bs.Call(self._bots.spawnBot,bs.ToughGuyBotPro,pos=(5,3,-2),spawnTime=3000)) bs.gameTimer(2000,bs.Call(self._bots.spawnBot,bs.BomberBotPro,pos=(-5,3,-2),spawnTime=3000)) bs.gameTimer(2000,bs.Call(self._bots.spawnBot,bs.BomberBot,pos=(0,3,-5),spawnTime=3000)) bs.gameTimer(2000,bs.Call(self._bots.spawnBot,bs.PirateBotNoTimeLimit,pos=(0,3,1),spawnTime=10000)) # note: if spawns were spread out more we'd probably want to set some sort of flag on the # last spawn to ensure we don't inadvertantly allow a 'win' before every bot is spawned. # (ie: if bot 1, 2, and 3 got killed but 4 hadn't spawned yet, the game might end because # it sees no remaining bots. # called for each spawning player def spawnPlayer(self,player): # lets spawn close to the center spawnCenter = (0,3,-2) pos = (spawnCenter[0]+random.uniform(-1.5,1.5),spawnCenter[1],spawnCenter[2]+random.uniform(-1.5,1.5)) self.spawnPlayerSpaz(player,position=pos) def _checkIfWon(self): # simply end the game if there's no living bots.. if not self._bots.haveLivingBots(): self._won = True self.endGame() # called for miscellaneous events def handleMessage(self,m): # a player has died if isinstance(m,bs.PlayerSpazDeathMessage): bs.TeamGameActivity.handleMessage(self,m) # do standard stuff self.respawnPlayer(m.spaz.getPlayer()) # kick off a respawn # a spaz-bot has died elif isinstance(m,bs.SpazBotDeathMessage): # unfortunately the bot-set will always tell us there are living # bots if we ask here (the currently-dying bot isn't officially marked dead yet) # ..so lets push a call into the event loop to check once this guy has finished dying. bs.pushCall(self._checkIfWon) else: # let the base class handle anything we don't.. bs.TeamGameActivity.handleMessage(self,m) # when this is called, we should fill out results and end the game # *regardless* of whether is has been won. (this may be called due # to a tournament ending or other external reason) def endGame(self): # stop our on-screen timer so players can see what they got self._timer.stop() results = bs.TeamGameResults() # if we won, set our score to the elapsed time # (there should just be 1 team here since this is co-op) # ..if we didn't win, leave scores as default (None) which means we lost if self._won: elapsedTime = bs.getGameTime()-self._timer.getStartTime() self.cameraFlash() bs.playSound(self._winSound) for team in self.teams: team.celebrate() # woooo! par-tay! results.setTeamScore(team,elapsedTime) # ends this activity.. self.end(results)
pratheekk12/hr-resume-template
dist/api/modules/Utility/Services/rentCalc.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function calculatePrice(rent, quant, finalPrice) { if (quant >= 30) { finalPrice += +rent.monthlyPrice * Math.floor(quant / 30); quant = quant % 30; } else if (quant >= 7) { finalPrice += +rent.weeklyPrice * Math.floor(quant / 7); quant = quant % 7; } else if (quant >= 1) { finalPrice += +rent.dailyPrice * quant; quant = 0; } else { return finalPrice; } return calculatePrice(rent, quant, finalPrice); } exports.default = calculatePrice; //# sourceMappingURL=rentCalc.js.map
KhrapkoVasyl/open-data-manage-system
src/js/db/models/MetaDataKey.js
<filename>src/js/db/models/MetaDataKey.js<gh_stars>1-10 'use strict'; const DataTypes = require('sequelize'); const db = require('../db'); const MetaDataKey = db.define( 'metaDataKey', { id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true, allowNull: false, }, key: { type: DataTypes.STRING(255), }, description: { type: DataTypes.STRING(511), }, metaDataKey: { type: DataTypes.INTEGER, }, }, { db, timestamps: false, freezeTableName: true, } ); module.exports = MetaDataKey;
zhou7rui/litespring
src/test/java/org/litespring/test/v2/CustomNumberEditorTest.java
package org.litespring.test.v2; import org.junit.Assert; import org.junit.Test; import org.litespring.beans.propertyeditors.CustomNumberEditor; public class CustomNumberEditorTest { @Test public void testConvertString(){ CustomNumberEditor editor = new CustomNumberEditor(Integer.class, true); editor.setAsText("3"); Object value = editor.getValue(); Assert.assertTrue(value instanceof Integer); Assert.assertEquals(3,((Integer)value).intValue()); editor.setAsText(""); Assert.assertTrue(editor.getValue() == null); try { editor.setAsText("3.1"); }catch (Exception e){ return; } Assert.fail(); } }
Apex-Brasil/eoscr-components
src/lib/ArrayTextField/index.js
<filename>src/lib/ArrayTextField/index.js import React, { useEffect, useState } from 'react' import PropTypes from 'prop-types' import clsx from 'clsx' import { makeStyles } from '@material-ui/core/styles' import Box from '@material-ui/core/Box' import InputAdornment from '@material-ui/core/InputAdornment' import TextField from '@material-ui/core/TextField' import AddIcon from '@material-ui/icons/Add' import Chip from '@material-ui/core/Chip' import Styles from './styles' const useStyles = makeStyles(Styles) const ArrayTextField = ({ value, onChange, className, ChipProps = {}, ...props }) => { const classes = useStyles() const [items, setItems] = useState(value) const [item, setItem] = useState('') const handleOnAddItem = () => { if (!item) { return } const newValue = [...items, item] setItems(newValue) setItem('') onChange && onChange(newValue) } const handleDeleteItem = (index) => { items.splice(index, 1) setItems([...items]) } const handleOnKeyPress = (event) => { if (event.key !== 'Enter') { return } event.preventDefault() handleOnAddItem() } useEffect(() => { let newItems = [] if (Array.isArray(value)) { newItems = value } if (typeof value === 'string') { newItems = [value] } if (typeof value === 'object') { try { newItems = Object.values(value) } catch (error) {} } setItems(newItems) }, [value]) return ( <Box className={clsx(classes.root, className)}> <TextField {...props} value={item} onChange={(event) => setItem(event.target.value)} InputProps={{ endAdornment: ( <InputAdornment className={classes.btn} onClick={handleOnAddItem} position="end" > <AddIcon /> </InputAdornment> ) }} onKeyPress={handleOnKeyPress} /> <Box> {items.map((item, index) => ( <Chip {...ChipProps} label={item} className={classes.chip} onDelete={(a) => handleDeleteItem(index)} key={`chip-item-${item}-${index}`} /> ))} </Box> </Box> ) } ArrayTextField.propTypes = { value: PropTypes.array, onChange: PropTypes.func, className: PropTypes.string, ChipProps: PropTypes.object } ArrayTextField.defaultProps = { value: [] } export default ArrayTextField
best08618/asylo
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/s390/bswap-1.c
<gh_stars>1-10 /* { dg-do compile } */ /* { dg-options "-O3 -march=z900 -mzarch" } */ #include <stdint.h> uint64_t u64; uint32_t u32; uint16_t u16; uint64_t foo64a (uint64_t a) { return __builtin_bswap64 (a); } /* { dg-final { scan-assembler-times "lrvgr\t%r2,%r2" 1 { target lp64 } } } */ uint64_t foo64b () { return __builtin_bswap64 (u64); } /* { dg-final { scan-assembler-times "lrvg\t%r2,0\\(%r\[0-9\]*\\)" 1 { target lp64 } } } */ void foo64c (uint64_t a) { u64 = __builtin_bswap64 (a); } /* { dg-final { scan-assembler-times "strvg\t%r2,0\\(%r\[0-9\]*\\)" 1 { target lp64 } } } */ uint32_t foo32a (uint32_t a) { return __builtin_bswap32 (a); } /* { dg-final { scan-assembler-times "lrvr\t%r2,%r2" 1 } } */ uint32_t foo32b () { return __builtin_bswap32 (u32); } /* { dg-final { scan-assembler-times "lrv\t%r2,0\\(%r\[0-9\]*\\)" 1 } } */ void foo32c (uint32_t a) { u32 = __builtin_bswap32 (a); } /* { dg-final { scan-assembler-times "strv\t%r2,0\\(%r\[0-9\]*\\)" 1 } } */
dgolovin/org.jboss.tools.ssp
runtimes/tests/org.jboss.tools.rsp.server.wildfly.test/src/main/java/org/jboss/tools/rsp/server/wildfly/test/beans/ServerBeanTypeProviderTest.java
/******************************************************************************* * Copyright (c) 2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v2.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v20.html * * Contributors: Red Hat, Inc. ******************************************************************************/ package org.jboss.tools.rsp.server.wildfly.test.beans; import static org.junit.Assert.assertNotNull; import org.jboss.tools.rsp.server.spi.discovery.ServerBeanType; import org.jboss.tools.rsp.server.wildfly.impl.JBossServerBeanTypeProvider; import org.junit.Test; public class ServerBeanTypeProviderTest { @Test public void testLocateServerMockResources() { JBossServerBeanTypeProvider provider = new JBossServerBeanTypeProvider(); assertNotNull(provider); ServerBeanType[] types = provider.getServerBeanTypes(); assertNotNull(types); } }
uk-gov-mirror/hmcts.wa-task-management-api
src/main/java/uk/gov/hmcts/reform/wataskmanagementapi/domain/entities/camunda/TaskState.java
<gh_stars>0 package uk.gov.hmcts.reform.wataskmanagementapi.domain.entities.camunda; import com.fasterxml.jackson.annotation.JsonValue; public enum TaskState { UNCONFIGURED("unconfigured"), UNASSIGNED("unassigned"), CONFIGURED("configured"), ASSIGNED("assigned"), REFERRED("referred"), COMPLETED("completed"), CANCELLED("cancelled"); @JsonValue private final String value; TaskState(String value) { this.value = value; } public String value() { return this.value; } @Override public String toString() { return this.value; } }
opentext/storyteller
docplatform/distribution/py/pfdesigns/javascript/b.js
'use strict'; var share = require('share'); share.test += __filename + ': starting\n'; exports.done = false; var a = require('./a'); share.test += __filename + ': a.done = ' + a.done + '\n'; exports.done = true; share.test += __filename + ': done\n';
homehabit/dsl-json
processor/src/test/java/com/dslplatform/json/models/EnumWithCustomConstantName4.java
<filename>processor/src/test/java/com/dslplatform/json/models/EnumWithCustomConstantName4.java package com.dslplatform.json.models; import com.dslplatform.json.CompiledJson; import com.dslplatform.json.JsonValue; @CompiledJson public enum EnumWithCustomConstantName4 { FIRST(10), SECOND(20); private final int value; EnumWithCustomConstantName4(int value) { this.value = value; } @JsonValue public int getValue() { return value; } }
uk-gov-mirror/guidance-guarantee-programme.pension_guidance
app/models/telephone_appointment.rb
<reponame>uk-gov-mirror/guidance-guarantee-programme.pension_guidance class TelephoneAppointment # rubocop:disable ClassLength include ActiveModel::Model attr_accessor( :id, :step, :selected_date, :start_at, :first_name, :last_name, :email, :phone, :memorable_word, :appointment_type, :date_of_birth, :dc_pot_confirmed, :where_you_heard, :date_of_birth_year, :date_of_birth_month, :date_of_birth_day, :gdpr_consent, :accessibility_requirements, :notes, :smarter_signposted, :lloyds_signposted ) validates :start_at, presence: true validates :first_name, presence: true, format: { without: /\d+/ } validates :last_name, presence: true, format: { without: /\d+/ } validates :email, email: true validate :validate_phone validates :memorable_word, presence: true validates :date_of_birth, presence: true validates :dc_pot_confirmed, inclusion: { in: %w(yes no not-sure) } validates :where_you_heard, inclusion: { in: WhereYouHeard::OPTIONS.keys } validates :notes, length: { maximum: 160 }, allow_blank: true validates :notes, presence: true, if: :accessibility_requirements? validates :accessibility_requirements, inclusion: { in: %w(0 1) } def accessibility_requirements? accessibility_requirements == '1' end def advance! self.step += 1 yield end def reset! self.step = 1 yield end def eligible? !ineligible? end def ineligible? ineligible_pension? || ineligible_age? end def ineligible_pension? dc_pot_confirmed == 'no' end def ineligible_age? start_at.blank? || age(start_at) < 50 end def attributes # rubocop:disable Metrics/MethodLength { start_at: start_at, first_name: first_name, last_name: last_name, email: email, phone: phone, memorable_word: memorable_word, date_of_birth: date_of_birth, dc_pot_confirmed: dc_pot_confirmed == 'yes', where_you_heard: where_you_heard, gdpr_consent: gdpr_consent, accessibility_requirements: accessibility_requirements, notes: notes, smarter_signposted: smarter_signposted, lloyds_signposted: lloyds_signposted } end def date_of_birth parts = [ date_of_birth_year, date_of_birth_month, date_of_birth_day ] return unless parts.all?(&:present?) parts.map!(&:to_i) Date.new(*parts) end def selected_date Time.zone.parse(@selected_date) if @selected_date.present? end def start_at Time.zone.parse(@start_at) if @start_at.present? end def step Integer(@step || 1) end def save return unless valid? TelephoneAppointmentsApi.new.create(self) end private def validate_phone unless phone.present? && /\A([\d+\-\s\+()]+)\z/ === phone # rubocop:disable GuardClause, CaseEquality errors.add(:phone, :invalid) end end def age(at) return 0 unless date_of_birth age = at.year - date_of_birth.year age -= 1 if at.to_date < date_of_birth + age.years age end end
jaylinhong/jdk14-learn
src/jdk14-source/java.desktop/sun/java2d/WindowsSurfaceManagerFactory.java
/* * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package sun.java2d; import java.awt.GraphicsConfiguration; import sun.awt.image.BufImgVolatileSurfaceManager; import sun.awt.image.SunVolatileImage; import sun.awt.image.VolatileSurfaceManager; import sun.java2d.d3d.D3DGraphicsConfig; import sun.java2d.d3d.D3DVolatileSurfaceManager; import sun.java2d.opengl.WGLGraphicsConfig; import sun.java2d.opengl.WGLVolatileSurfaceManager; /** * The SurfaceManagerFactory that creates VolatileSurfaceManager * implementations for the Windows volatile images. */ public class WindowsSurfaceManagerFactory extends SurfaceManagerFactory { /** * Creates a new instance of a VolatileSurfaceManager given any * arbitrary SunVolatileImage. An optional context Object can be supplied * as a way for the caller to pass pipeline-specific context data to * the VolatileSurfaceManager (such as a backbuffer handle, for example). * * For Windows platforms, this method returns a Windows-specific * VolatileSurfaceManager. */ public VolatileSurfaceManager createVolatileManager(SunVolatileImage vImg, Object context) { GraphicsConfiguration gc = vImg.getGraphicsConfig(); if (gc instanceof D3DGraphicsConfig) { return new D3DVolatileSurfaceManager(vImg, context); } else if (gc instanceof WGLGraphicsConfig) { return new WGLVolatileSurfaceManager(vImg, context); } else { return new BufImgVolatileSurfaceManager(vImg, context); } } }
soldierloko/Curso-em-Video
Ex_74.py
#Crie um programa que vai gerar cinco números aleatórios e colocar em um tupla #Depois, mostra a listagem de números gerados e tambem indique o menor e o maior valor que estão na tupla from random import randint n = (randint(1,10),randint(1,10),randint(1,10),randint(1,10),randint(1,10)) print(f'Sorteei os valores {n}') print(f' O maior valor sorteado foi {max(n)}') print(f' O menor valor sorteado foi {min(n)}')
nathejk/status-app
src/actions/MsgActions.js
<reponame>nathejk/status-app<gh_stars>0 import {MSG__USER_CONNECTED, MSG__NEW_MESSAGE_RECEIVED_BULK, MSG__CONNECTED, MSG__DISCONNECTED, MSG__NAVIGATE_TO_CHANNEL, MSG__SEND_MESSAGE, MSG__NEW_MESSAGE_RECEIVED} from '../constants/actionTypes' export const connected = () => ({ type: MSG__CONNECTED }) export const disconnected = () => ({ type: MSG__DISCONNECTED }) export const userConnected = (user) => ({ type: MSG__USER_CONNECTED, payload: user }) export const openChat = (channel, id) => ({ type: MSG__NAVIGATE_TO_CHANNEL, payload: {channel: channel || 'Nathejk', id} }) export const messageRecieved = (message) => ({ type: MSG__NEW_MESSAGE_RECEIVED, payload: message }) export const multipleMessagesRecieved = (messages) => ({ type: MSG__NEW_MESSAGE_RECEIVED_BULK, payload: messages }) export const sendMessage = (message, channel) => ({ type: MSG__SEND_MESSAGE, payload: {message, channel: channel || 'Nathejk'} })
gylidian4iz7r/exasolq
src/main/java/com/exasol/adapter/document/files/SourceString.java
package com.exasol.adapter.document.files; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.exasol.errorreporting.ExaError; /** * This class parses the source string syntax. */ class SourceString { private static final Pattern IMPORT_AS_PATTERN = Pattern.compile("\\(import-as:([^\\)]+)\\)"); private final String fileTypeOverride; private final String filePattern; /** * Create a new instance of {@link SourceString}. * * @param sourceString source string */ SourceString(final String sourceString) { final Matcher importAsMatcher = IMPORT_AS_PATTERN.matcher(sourceString); if (importAsMatcher.find()) { this.fileTypeOverride = importAsMatcher.group(1); this.filePattern = importAsMatcher.replaceAll(""); } else { this.fileTypeOverride = null; this.filePattern = sourceString; } } /** * Get the file type. * * @return file type */ public String getFileType() { if (this.fileTypeOverride != null) { return this.fileTypeOverride; } else { return getFileExtension(); } } private String getFileExtension() { final int lastDotIndex = this.filePattern.lastIndexOf("."); if (lastDotIndex == -1) { throw new IllegalStateException(ExaError.messageBuilder("E-VSDF-15") .message("Invalid file name {{file name}}. This file name does not have a extension.", this.filePattern) .mitigation("Rename the file so that it has a valid extension.") .mitigation( "If you can't rename the file, add '(import-as:<TYPE>)' to the source string in your mapping definition.") .toString()); } return this.filePattern.substring(lastDotIndex + 1); } /** * Get the file pattern. * * @return file pattern */ public String getFilePattern() { return this.filePattern; } }
streamlesswaveson/multithreadinginjava
src/main/java/com/cutajarjames/multithreading/conditionVariable/StingySpendyCondVar.java
<gh_stars>1-10 package com.cutajarjames.multithreading.conditionVariable; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class StingySpendyCondVar { int money = 100; Lock mutex = new ReentrantLock(); Condition condition = mutex.newCondition(); public void stingy() { for (int i = 0; i < 1000000; i++) { mutex.lock(); this.money += 10; condition.signal(); mutex.unlock(); } System.out.println("Stingy Done"); } public void spendy() { for (int i = 0; i < 500000; i++) { mutex.lock(); while (this.money < 20) { try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } this.money -= 20; if (this.money < 0) System.out.println("Money in the bank: " + this.money); mutex.unlock(); } System.out.println("Spendy Done"); } public static void main(String[] args) throws InterruptedException { var stingySpendy = new StingySpendyCondVar(); new Thread(stingySpendy::stingy).start(); new Thread(stingySpendy::spendy).start(); TimeUnit.SECONDS.sleep(2); System.out.println("Money in the end is: " + stingySpendy.money); } }
priit/registry
app/controllers/api/v1/registrant/contacts_controller.rb
<filename>app/controllers/api/v1/registrant/contacts_controller.rb require 'serializers/registrant_api/contact' module Api module V1 module Registrant class ContactsController < ::Api::V1::Registrant::BaseController def index limit = params[:limit] || 200 offset = params[:offset] || 0 if limit.to_i > 200 || limit.to_i < 1 render(json: { errors: [{ limit: ['parameter is out of range'] }] }, status: :bad_request) && return end if offset.to_i.negative? render(json: { errors: [{ offset: ['parameter is out of range'] }] }, status: :bad_request) && return end contacts = current_user_contacts.limit(limit).offset(offset) serialized_contacts = contacts.collect { |contact| serialize_contact(contact, false) } render json: serialized_contacts end def show contact = representable_contact(params[:uuid]) links = params[:links] == 'true' if contact render json: serialize_contact(contact, links) else render json: { errors: [{ base: ['Contact not found'] }] }, status: :not_found end end def update logger.debug 'Received update request' logger.debug params contact = current_user_contacts.find_by!(uuid: params[:uuid]) contact.name = params[:name] if params[:name].present? contact.email = params[:email] if params[:email].present? contact.phone = params[:phone] if params[:phone].present? # Needed to support passing empty array, which otherwise gets parsed to nil # https://github.com/rails/rails/pull/13157 reparsed_request_json = ActiveSupport::JSON.decode(request.body.string) .with_indifferent_access logger.debug 'Reparsed request is following' logger.debug reparsed_request_json.to_s disclosed_attributes = reparsed_request_json[:disclosed_attributes] if disclosed_attributes if disclosed_attributes.present? && contact.org? error_msg = "Legal person's data is visible by default and cannot be concealed." \ ' Please remove this parameter.' render json: { errors: [{ disclosed_attributes: [error_msg] }] }, status: :bad_request return end contact.disclosed_attributes = disclosed_attributes end logger.debug "Setting.address_processing is set to #{Setting.address_processing}" if Setting.address_processing && params[:address] address = Contact::Address.new(params[:address][:street], params[:address][:zip], params[:address][:city], params[:address][:state], params[:address][:country_code]) contact.address = address end if !Setting.address_processing && params[:address] error_msg = 'Address processing is disabled and therefore cannot be updated' render json: { errors: [{ address: [error_msg] }] }, status: :bad_request and return end if ENV['fax_enabled'] == 'true' contact.fax = params[:fax] if params[:fax].present? end logger.debug "ENV['fax_enabled'] is set to #{ENV['fax_enabled']}" if ENV['fax_enabled'] != 'true' && params[:fax] error_msg = 'Fax processing is disabled and therefore cannot be updated' render json: { errors: [{ address: [error_msg] }] }, status: :bad_request and return end contact.transaction do contact.save! action = current_registrant_user.actions.create!(contact: contact, operation: :update) contact.registrar.notify(action) end render json: serialize_contact(contact, false) end private def representable_contact(uuid) country = current_registrant_user.country.alpha2 contact = Contact.find_by(uuid: uuid, ident: current_registrant_user.ident, ident_type: 'priv', ident_country_code: country) return contact if contact Contact.find_by(uuid: uuid, ident_type: 'org', ident: company_codes, ident_country_code: country) rescue CompanyRegister::NotAvailableError nil end def company_codes current_registrant_user.companies.collect(&:registration_number) end def current_user_contacts current_registrant_user.contacts(representable: false) rescue CompanyRegister::NotAvailableError current_registrant_user.direct_contacts end def serialize_contact(contact, links) Serializers::RegistrantApi::Contact.new(contact, links).to_json end def logger Rails.logger end end end end end
wesley1975/redshark
src/main/java/com/redshark/entity/Session.java
<gh_stars>10-100 package com.redshark.entity; import java.util.UUID; import java.util.concurrent.TimeUnit; import com.redshark.core.Constants; import com.redshark.event.ExecutorEventDispatcher; import com.redshark.util.DateTimeUtil; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Session { /** * session status types */ public enum Status { NOT_CONNECTED, CONNECTING, CONNECTED, CLOSED } //考虑rejoin的情况, sId没变,Channel变化 public String id; private Status status; private volatile Channel channel; private long timePoint; private boolean isAuth; //是否已经验证 private String ip; //登录Ip:Port public Session(Channel channel) { this.id = UUID.randomUUID().toString(); this.channel = channel; } public void setActive(boolean isActive) { this.timePoint = System.currentTimeMillis(); if (isAuth) { this.status = Status.CONNECTED; } } /** * 用户在线时间需要客户端定期更新 * @return */ public boolean isActive() { if( channel != null && channel.isActive()) { if(System.currentTimeMillis() - this.timePoint < Constants.ACTIVE_SESSION_TTL_MS) {return true;} } return false; } public void send(String msg) { send(msg, null); } public void send(String message, ChannelFutureListener listener) { if (null == channel || !channel.isActive()) { return; } //异步发送消息 ExecutorEventDispatcher.getInstance().getEventHandlerThreadsPool().run(new Runnable() { @Override public void run() { if (channel.isWritable()) { if (listener == null) { channel.writeAndFlush(new TextWebSocketFrame(message), channel.voidPromise()); } else { channel.writeAndFlush(new TextWebSocketFrame(message)).addListener(listener); } } else { channel.eventLoop().schedule(() -> { send(message, listener); }, 1L, TimeUnit.SECONDS); } } }); } public void close() { if (channel != null) { if (channel.isActive()) channel.close(); channel = null; } } }
DannyParker0001/Kisak-Strike
game/client/cstrike15/Scaleform/HUD/sfhudwinpanel.cpp
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #if defined( INCLUDE_SCALEFORM ) #include "sfhudwinpanel.h" #include "hud_macros.h" #include "vgui/ILocalize.h" #include "vgui/ISurface.h" #include "iclientmode.h" #include "hud.h" #include "hudelement.h" #include "hud_element_helper.h" #include "scaleformui/scaleformui.h" #include "c_playerresource.h" #include "c_cs_playerresource.h" #include "sfhudfreezepanel.h" #include "cs_player_rank_mgr.h" #include "achievements_cs.h" #include "cs_player_rank_shared.h" #include "gamestringpool.h" #include "sfhud_teamcounter.h" #include "cs_client_gamestats.h" #include "fmtstr.h" #include <engine/IEngineSound.h> #include "c_team.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" DECLARE_HUDELEMENT( SFHudWinPanel ); SFUI_BEGIN_GAME_API_DEF SFUI_END_GAME_API_DEF( SFHudWinPanel, WinPanel ); extern ConVar cl_draw_only_deathnotices; //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- SFHudWinPanel::SFHudWinPanel( const char *value ) : SFHudFlashInterface( value ), m_bVisible( false ), m_hWinPanelParent( NULL ), m_hWinner( NULL ), m_hReason( NULL ), m_hMVP( NULL ), m_hSurrender( NULL ), m_hFunFact( NULL ), m_hEloPanel( NULL ), m_hRankPanel( NULL ), m_hMedalPanel( NULL ), m_hProgressText( NULL ), m_hNextWeaponPanel( NULL ), m_nFunFactPlayer( 0 ), m_nFunfactToken( NULL ), m_nFunFactParam1( 0 ), m_nFunFactParam2( 0 ), m_nFunFactParam3( 0 ), m_bShouldSetWinPanelExtraData( false ), m_fSetWinPanelExtraDataTime( 0.0 ), m_nRoundStartELO( 0 ), m_iMVP( 0 ) { SetHiddenBits( HIDEHUD_MISCSTATUS ); } void SFHudWinPanel::LevelInit( void ) { int slot = GET_ACTIVE_SPLITSCREEN_SLOT(); if ( !FlashAPIIsValid() && slot == 0 ) { SFUI_REQUEST_ELEMENT( SF_SS_SLOT( GET_ACTIVE_SPLITSCREEN_SLOT() ), g_pScaleformUI, SFHudWinPanel, this, WinPanel ); } } void SFHudWinPanel::LevelShutdown( void ) { if ( FlashAPIIsValid() ) { RemoveFlashElement(); } } bool SFHudWinPanel::ShouldDraw( void ) { if ( IsTakingAFreezecamScreenshot() ) return false; return cl_drawhud.GetBool() && cl_draw_only_deathnotices.GetBool() == false && CHudElement::ShouldDraw(); } void SFHudWinPanel::SetActive( bool bActive ) { // if ( !bActive && m_bVisible ) // { // Hide(); // } CHudElement::SetActive( bActive ); } void SFHudWinPanel::FlashReady( void ) { if ( !m_FlashAPI ) { return; } m_hWinPanelParent = g_pScaleformUI->Value_GetMember( m_FlashAPI, "WinPanel" ); if ( m_hWinPanelParent ) { SFVALUE innerRoot = g_pScaleformUI->Value_GetMember( m_hWinPanelParent, "InnerWinPanel" ); if ( innerRoot ) { m_hWinner = g_pScaleformUI->TextObject_MakeTextObjectFromMember( innerRoot, "WinnerText" ); m_hReason = g_pScaleformUI->TextObject_MakeTextObjectFromMember( innerRoot, "WinReason" ); m_hMVP = g_pScaleformUI->TextObject_MakeTextObjectFromMember( innerRoot, "MVPText" ); m_hSurrender = g_pScaleformUI->TextObject_MakeTextObjectFromMember( innerRoot, "Surrender" ); m_hFunFact = g_pScaleformUI->TextObject_MakeTextObjectFromMember( innerRoot, "FunFact" ); m_hEloPanel = g_pScaleformUI->Value_GetMember( innerRoot, "EloPanel" ); m_hRankPanel = g_pScaleformUI->Value_GetMember( innerRoot, "RankPanel" ); m_hMedalPanel = g_pScaleformUI->Value_GetMember( innerRoot, "MedalPanel" ); m_hProgressText = g_pScaleformUI->Value_GetMember( innerRoot, "ProgressText" ); m_hNextWeaponPanel = g_pScaleformUI->Value_GetMember( innerRoot, "NextWeaponPanel" ); g_pScaleformUI->ReleaseValue( innerRoot ); } } //Tell scaleform about the constant we plan on using later WITH_SFVALUEARRAY_SLOT_LOCKED( data, 3 ) { m_pScaleformUI->ValueArray_SetElement( data, 0, WINNER_DRAW ); m_pScaleformUI->ValueArray_SetElement( data, 1, WINNER_CT ); m_pScaleformUI->ValueArray_SetElement( data, 2, WINNER_TER ); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "setResultConstants", data, 3 ); } // listen for events ListenForGameEvent( "round_start" ); ListenForGameEvent( "cs_win_panel_round" ); ListenForGameEvent( "round_mvp" ); g_pScaleformUI->AddDeviceDependentObject( this ); Hide(); } bool SFHudWinPanel::PreUnloadFlash( void ) { g_pScaleformUI->RemoveDeviceDependentObject( this ); SafeReleaseSFTextObject( m_hWinner ); SafeReleaseSFTextObject( m_hReason ); SafeReleaseSFTextObject( m_hMVP ); SafeReleaseSFTextObject( m_hSurrender ); SafeReleaseSFTextObject( m_hFunFact ); SafeReleaseSFVALUE( m_hEloPanel ); SafeReleaseSFVALUE( m_hRankPanel ); SafeReleaseSFVALUE( m_hMedalPanel ); SafeReleaseSFVALUE( m_hProgressText ); SafeReleaseSFVALUE( m_hNextWeaponPanel ); SafeReleaseSFVALUE( m_hWinPanelParent ); return true; } void SFHudWinPanel::ProcessInput( void ) { if ( m_bShouldSetWinPanelExtraData && m_fSetWinPanelExtraDataTime <= gpGlobals->curtime ) { m_bShouldSetWinPanelExtraData = false; SetWinPanelExtraData(); } } CEG_NOINLINE void SFHudWinPanel::FireGameEvent( IGameEvent* event ) { const char *pEventName = event->GetName(); if ( V_strcmp( "round_start", pEventName ) == 0 ) { if ( m_pScaleformUI ) { WITH_SLOT_LOCKED { // At the end of every round, clear the Scaleform mesh cache to recover some memory g_pScaleformUI->ClearCache(); } } // Reset MVP info when round starts SetMVP( NULL, CSMVP_UNDEFINED ); Hide(); GetViewPortInterface()->UpdateAllPanels(); } else if ( V_strcmp( "round_mvp", pEventName ) == 0 ) { C_BasePlayer *basePlayer = UTIL_PlayerByUserId( event->GetInt( "userid" ) ); if ( basePlayer ) { CSMvpReason_t mvpReason = (CSMvpReason_t)event->GetInt( "reason" ); int32 nMusicKitMVPs = event->GetInt( "musickitmvps" ); SetMVP( ToCSPlayer( basePlayer ), mvpReason, nMusicKitMVPs ); } } else if ( V_strcmp( "cs_win_panel_round", pEventName ) == 0 ) { if ( !FlashAPIIsValid() ) return; m_bShouldSetWinPanelExtraData = true; m_fSetWinPanelExtraDataTime = gpGlobals->curtime + 1.0f; int nConnectionProtocol = engine->GetConnectionDataProtocol(); int iEndEvent = event->GetInt( "final_event" ); if ( nConnectionProtocol && ( iEndEvent >= 0 ) && // backwards compatibility: we switched to consistent numbering in the enum ( nConnectionProtocol < 13500 ) ) // and older demos have one-less numbers in "final_event" before 1.35.0.0 (Sep 15, 2015 3:20 PM release BuildID 776203) ++ iEndEvent; m_nFunFactPlayer = event->GetInt( "funfact_player" ); m_nFunfactToken = AllocPooledString( event->GetString( "funfact_token", "" ) ); m_nFunFactParam1 = event->GetInt( "funfact_data1" ); m_nFunFactParam2 = event->GetInt( "funfact_data2" ); m_nFunFactParam3 = event->GetInt( "funfact_data3" ); if ( CSGameRules() && (CSGameRules()->IsPlayingGunGameProgressive() || CSGameRules()->IsPlayingGunGameDeathmatch()) ) { ShowGunGameWinPanel(); } else { // show the win panel switch ( iEndEvent ) { case Target_Bombed: case VIP_Assassinated: case Terrorists_Escaped: case Terrorists_Win: case Hostages_Not_Rescued: case VIP_Not_Escaped: case CTs_Surrender: case Terrorists_Planted: ShowTeamWinPanel( WINNER_TER, "SFUI_WinPanel_T_Win" ); break; case VIP_Escaped: case CTs_PreventEscape: case Escaping_Terrorists_Neutralized: case Bomb_Defused: case CTs_Win: case All_Hostages_Rescued: case Target_Saved: case Terrorists_Not_Escaped: case Terrorists_Surrender: case CTs_ReachedHostage: ShowTeamWinPanel( WINNER_CT, "SFUI_WinPanel_CT_Win" ); break; case Round_Draw: ShowTeamWinPanel( WINNER_DRAW, "SFUI_WinPanel_Round_Draw" ); break; default: Assert( 0 ); break; } Assert( m_pScaleformUI ); WITH_SLOT_LOCKED { // Set the MVP text. if ( m_hSurrender ) { if ( iEndEvent == CTs_Surrender ) { m_hSurrender->SetTextHTML( "#winpanel_end_cts_surrender" ); } else if ( iEndEvent == Terrorists_Surrender ) { m_hSurrender->SetTextHTML( "#winpanel_end_terrorists_surrender" ); } else { m_hSurrender->SetTextHTML( "" ); } } } //Map the round end events onto localized strings char* endEventToString[RoundEndReason_Count]; V_memset( endEventToString, 0, sizeof( endEventToString ) ); //terrorist win events endEventToString[Target_Bombed] = "#winpanel_end_target_bombed"; endEventToString[VIP_Assassinated] = "#winpanel_end_vip_assassinated"; endEventToString[Terrorists_Escaped] = "#winpanel_end_terrorists_escaped"; endEventToString[Terrorists_Win] = "#winpanel_end_terrorists__kill"; endEventToString[Hostages_Not_Rescued] = "#winpanel_end_hostages_not_rescued"; endEventToString[VIP_Not_Escaped] = "#winpanel_end_vip_not_escaped"; endEventToString[CTs_Surrender] = "#winpanel_end_cts_surrender"; endEventToString[Terrorists_Planted] = "TEMP STRING - TERRORISTS PLANTED"; //CT win events endEventToString[VIP_Escaped] = "#winpanel_end_vip_escaped"; endEventToString[CTs_PreventEscape] = "#winpanel_end_cts_prevent_escape"; endEventToString[Escaping_Terrorists_Neutralized] = "#winpanel_end_escaping_terrorists_neutralized"; endEventToString[Bomb_Defused] = "#winpanel_end_bomb_defused"; endEventToString[CTs_Win] = "#winpanel_end_cts_win"; endEventToString[All_Hostages_Rescued] = "#winpanel_end_all_hostages_rescued"; endEventToString[Target_Saved] = "#winpanel_end_target_saved"; endEventToString[Terrorists_Not_Escaped] = "#winpanel_end_terrorists_not_escaped"; endEventToString[Terrorists_Surrender] = "#winpanel_end_terrorists_surrender"; endEventToString[CTs_ReachedHostage] = "#winpanel_end_cts_reach_hostage"; //We don't show a round end panel for these endEventToString[Game_Commencing] = ""; endEventToString[Round_Draw] = ""; const wchar_t* wszEventMessage = NULL; if ( iEndEvent >= 0 && iEndEvent < RoundEndReason_Count ) { wszEventMessage = g_pVGuiLocalize->Find( endEventToString[iEndEvent] ); } Assert( m_pScaleformUI ); WITH_SLOT_LOCKED { if ( m_hReason ) { if ( wszEventMessage != NULL ) { m_hReason->SetTextHTML( wszEventMessage ); } else { m_hReason->SetTextHTML( "" ); } } } } } } void SFHudWinPanel::SetWinPanelExtraData() { if ( !FlashAPIIsValid() ) return; if ( !CSGameRules() ) return; /* WIN_EXTRATYPE_FUN = 0, WIN_EXTRATYPE_AWARD, WIN_EXTRATYPE_RANK, WIN_EXTRATYPE_ELO, WIN_EXTRATYPE_SEASONRANK, */ int nExtraPanelType = WIN_EXTRATYPE_NONE; //SetWinPanelItemDrops( index:Number, strId:String, PlayerXuid:String ) //g_PlayerRankManager.PrintRankProgressThisRound(); int nIdealProgressCatagory = MEDAL_CATEGORY_NONE; // ELO will need to be updated before this event happens so we get the right info int nEloBracket = -1; int nEloDelta = g_PlayerRankManager.GetEloBracketChange( nEloBracket ); const CUtlVector<RankIncreasedEvent_t> &medalRankIncreases = g_PlayerRankManager.GetRankIncreasesThisRound(); const CUtlVector<MedalEarnedEvent_t> &medalsAwarded = g_PlayerRankManager.GetMedalsEarnedThisRound(); CUtlVector<MedalStatEvent_t> medalStatsAwarded; g_PlayerRankManager.GetMedalStatsEarnedThisRound( medalStatsAwarded ); bool bShowProgress = false; bool bHideProgressAndFunFact = false; bool bIsWarmup = CSGameRules()->IsWarmupPeriod(); if ( !bIsWarmup && nEloBracket >= 0 && nEloDelta != 0 && m_hEloPanel ) { // tell the script to set the icon and show it // get the text needed and set the text const wchar_t *eloString; if ( nEloDelta > 0 ) eloString = g_pVGuiLocalize->Find( "#SFUI_WinPanel_elo_up_string" ); else eloString = g_pVGuiLocalize->Find( "#SFUI_WinPanel_elo_down_string" ); if ( !eloString ) { Warning( "Failed to find localization strings for elo change in win panel\n" ); } WITH_SFVALUEARRAY_SLOT_LOCKED( data, 2 ) { m_pScaleformUI->ValueArray_SetElement( data, 0, nEloBracket ); m_pScaleformUI->ValueArray_SetElement( data, 1, eloString ? eloString : L"" ); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "SetEloBracketInfo", data, 2 ); } nExtraPanelType = WIN_EXTRATYPE_ELO; // Once we display the change in rank, reset the recorded delta. g_PlayerRankManager.ResetRecordedEloBracketChange(); } else if ( !bIsWarmup && medalRankIncreases.Count() > 0 ) { // static "award" text ISFTextObject* hRankPromtText = g_pScaleformUI->TextObject_MakeTextObjectFromMember( m_hRankPanel, "RankEarned" ); ISFTextObject* hRankNameText = g_pScaleformUI->TextObject_MakeTextObjectFromMember( m_hRankPanel, "RankName" ); if ( hRankPromtText && hRankNameText ) { int nTotalRankIncreases = medalRankIncreases.Count(); //MEDAL_CATEGORY_TEAM_AND_OBJECTIVE = MEDAL_CATEGORY_START, //MEDAL_CATEGORY_COMBAT, //MEDAL_CATEGORY_WEAPON, //MEDAL_CATEGORY_MAP, //MEDAL_CATEGORY_ARSENAL, int nBestIndex = 0; int nHighestRank = 0; CUtlVector< int > tieList; // find the place where we earned the highest rank for ( int i=0; i < nTotalRankIncreases; i++ ) { nHighestRank = g_PlayerRankManager.CalculateRankForCategory( medalRankIncreases[nBestIndex].m_category ); int nCurRank = g_PlayerRankManager.CalculateRankForCategory( medalRankIncreases[i].m_category ); int nDelta = nCurRank - nHighestRank; if ( medalRankIncreases[i].m_category >= MEDAL_CATEGORY_ACHIEVEMENTS_END ) { nBestIndex = i; tieList.RemoveAll(); } else if ( nDelta == 0 ) { // keep track of the ranks of the same value nBestIndex = i; tieList.AddToTail(i); } else if ( nDelta > 0 ) { nBestIndex = i; tieList.RemoveAll(); } } if ( tieList.Count() > 0 ) { // break any ties by picking on randomly nBestIndex = tieList[ RandomInt( 0, tieList.Count()-1) ]; } bool bIsCoinLevelUp = false; MedalCategory_t nCurrentBestCatagory = medalRankIncreases[nBestIndex].m_category; int nCurrentRankForCatagory = 0; nCurrentRankForCatagory = g_PlayerRankManager.CalculateRankForCategory( medalRankIncreases[nBestIndex].m_category ); WITH_SFVALUEARRAY_SLOT_LOCKED( data, 2 ) { m_pScaleformUI->ValueArray_SetElement( data, 0, nCurrentBestCatagory ); m_pScaleformUI->ValueArray_SetElement( data, 1, nCurrentRankForCatagory ); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "SetRankUpIcon", data, 2 ); } wchar_t finalAwardText[256]; // say whether they earned a new rank, 2 new ranks, a new rank in two catagories, etc if ( hRankPromtText && ( ( nTotalRankIncreases <= 1 ) || bIsCoinLevelUp ) ) { g_pVGuiLocalize->ConstructString( finalAwardText, sizeof(finalAwardText), bIsCoinLevelUp ? "#SFUI_WinPanel_coin_awarded" : "#SFUI_WinPanel_rank_awarded", NULL ); } else { wchar_t wNum[16]; V_snwprintf( wNum, ARRAYSIZE( wNum ), L"%i", nTotalRankIncreases ); int param1 = nTotalRankIncreases; wchar_t wAnnounceText[256]; V_snwprintf( wAnnounceText, ARRAYSIZE( wAnnounceText ), L"%i", param1 ); const wchar_t *awardString = g_pVGuiLocalize->Find( "#SFUI_WinPanel_rank_awarded_multi" ); g_pVGuiLocalize->ConstructString( finalAwardText, sizeof(finalAwardText), awardString , 1, wNum ); } // set the name of the new rank that you achieved wchar_t finalRankText[256]; if ( hRankNameText ) { const wchar_t *rankString = g_pVGuiLocalize->Find( "#SFUI_WinPanel_rank_name_string" ); g_pVGuiLocalize->ConstructString( finalRankText, sizeof(finalRankText), rankString , 2, g_pVGuiLocalize->Find(g_PlayerRankManager.GetMedalCatagoryName(nCurrentBestCatagory)), g_pVGuiLocalize->Find(g_PlayerRankManager.GetMedalCatagoryRankName( bIsCoinLevelUp ? (nCurrentRankForCatagory-1) : nCurrentRankForCatagory )) ); WITH_SLOT_LOCKED { hRankNameText->SetTextHTML( finalRankText ); } } WITH_SFVALUEARRAY_SLOT_LOCKED( data, 2 ) { m_pScaleformUI->ValueArray_SetElement( data, 0, finalAwardText ); m_pScaleformUI->ValueArray_SetElement( data, 1, finalRankText ); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "SetRankUpText", data, 2 ); } if ( nHighestRank < (MEDAL_CATEGORY_COUNT-1) ) nIdealProgressCatagory = nCurrentBestCatagory; SafeReleaseSFTextObject( hRankPromtText ); SafeReleaseSFTextObject( hRankNameText ); } nExtraPanelType = WIN_EXTRATYPE_RANK; bShowProgress = true; } else if ( !bIsWarmup && medalsAwarded.Count() > 0 ) { WITH_SLOT_LOCKED { int nMaxMedals = 7; for ( int i = 0; i < nMaxMedals; i++ ) { //get the award name for slot i WITH_SFVALUEARRAY( data, 2 ) { m_pScaleformUI->ValueArray_SetElement( data, 0, i ); if ( i < medalsAwarded.Count() && medalsAwarded[i].m_pAchievement ) { CBaseAchievement *pAchievement = medalsAwarded[i].m_pAchievement; m_pScaleformUI->ValueArray_SetElement( data, 1, pAchievement->GetName() ); } else { m_pScaleformUI->ValueArray_SetElement( data, 1, "" ); } m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "SetWinPanelAwardIcon", data, 2 ); } } } nExtraPanelType = WIN_EXTRATYPE_AWARD; bShowProgress = true; } else if ( !bIsWarmup && medalStatsAwarded.Count() > 0 ) { MedalStatEvent_t *pBestStat = NULL; float flHighestCompletionPct = -1.0f; FOR_EACH_VEC( medalStatsAwarded, i ) { MedalStatEvent_t&stat = medalStatsAwarded[i]; float pct = (float)(stat.m_pAchievement->GetCount()) / (float)(stat.m_pAchievement->GetGoal()); if ( pct > flHighestCompletionPct ) { flHighestCompletionPct = pct; pBestStat = &medalStatsAwarded[i]; } } if ( pBestStat ) { const char* pszLocToken = GetLocTokenForStatId( pBestStat->m_StatType ); if ( pszLocToken && pBestStat->m_pAchievement ) { WITH_SFVALUEARRAY_SLOT_LOCKED( data, 6 ) { m_pScaleformUI->ValueArray_SetElement( data, 0, pBestStat->m_pAchievement->GetName() ); m_pScaleformUI->ValueArray_SetElement( data, 1, pBestStat->m_pAchievement->GetCount() ); m_pScaleformUI->ValueArray_SetElement( data, 2, pBestStat->m_pAchievement->GetGoal() ); const StatsCollection_t roundStats = g_CSClientGameStats.GetRoundStats(0); m_pScaleformUI->ValueArray_SetElement( data, 3, roundStats[pBestStat->m_StatType] ); m_pScaleformUI->ValueArray_SetElement( data, 4, pBestStat->m_category ); // Progress text for this stat based medal const wchar_t *progString = g_pVGuiLocalize->Find( pszLocToken ); wchar_t finalProgressText[256]; wchar_t count[8], goal[8]; V_snwprintf( count, ARRAYSIZE( count ), L"%i", pBestStat->m_pAchievement->GetCount() ); V_snwprintf( goal, ARRAYSIZE( goal ), L"%i", pBestStat->m_pAchievement->GetGoal() ); g_pVGuiLocalize->ConstructString( finalProgressText, sizeof(finalProgressText), progString, 3, count, goal, ACHIEVEMENT_LOCALIZED_NAME( pBestStat->m_pAchievement ) ); m_pScaleformUI->ValueArray_SetElement( data, 5, finalProgressText ); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "SetWinPanelStatProgress", data, 6 ); bHideProgressAndFunFact = true; } } } } else if ( !bIsWarmup && CSGameRules() && CSGameRules()->IsPlayingGunGame() ) { const char *szGrenName = NULL; C_CSPlayer *pPlayer = C_CSPlayer::GetLocalCSPlayer(); if ( pPlayer ) { int nextWeaponID = CSGameRules()->GetNextGunGameWeapon( pPlayer->GetPlayerGunGameWeaponIndex(), pPlayer->GetTeamNumber() ); const char *pchClassName = "unknown"; const char *pchPrintName = "unknown"; const CEconItemDefinition *pDef = GetItemSchema()->GetItemDefinition( nextWeaponID ); if ( pDef && pDef->GetDefinitionIndex() != 0 ) { pchClassName = pDef->GetDefinitionName(); pchPrintName = pDef->GetItemBaseName(); } else { const CCSWeaponInfo* pWeaponInfo = GetWeaponInfo( (CSWeaponID)nextWeaponID ); if ( pWeaponInfo ) { pchClassName = pWeaponInfo->szClassName; pchPrintName = pWeaponInfo->szPrintName; } } int nKillValue = pPlayer->GetNumGunGameTRKillPoints(); int nCurIndex = (float)pPlayer->GetPlayerGunGameWeaponIndex(); int nMaxIndex = CSGameRules()->GetNumProgressiveGunGameWeapons( pPlayer->GetTeamNumber() ); if ( nCurIndex != nMaxIndex && nKillValue > 0 ) { int nBonusGrenade = CSGameRules()->GetGunGameTRBonusGrenade( pPlayer ); if ( nBonusGrenade == WEAPON_MOLOTOV || nBonusGrenade == WEAPON_INCGRENADE ) { if ( pPlayer->GetTeamNumber() == TEAM_CT ) { szGrenName = "weapon_incgrenade"; } else { szGrenName = "weapon_molotov"; } } else if ( nBonusGrenade == WEAPON_FLASHBANG ) { szGrenName = "weapon_flashbang"; } else if ( nBonusGrenade == WEAPON_HEGRENADE ) { szGrenName = "weapon_hegrenade"; } wchar_t *titleString = NULL; if ( CSGameRules()->IsPlayingGunGameTRBomb() ) { titleString = g_pVGuiLocalize->Find( "#SFUI_WS_GG_YourNextWeaponIs" ); } else { titleString = g_pVGuiLocalize->Find( "#SFUI_WS_GG_NextWep" ); } WITH_SFVALUEARRAY_SLOT_LOCKED( data, 4 ) { // Scaleform cannot handle NULL as a wide string name. Make sure it always gets a valid string. wchar_t *weaponName = L""; wchar_t *newWeaponName = g_pVGuiLocalize->Find( pchPrintName ); if ( newWeaponName ) { weaponName = newWeaponName; } m_pScaleformUI->ValueArray_SetElement( data, 0, titleString ); m_pScaleformUI->ValueArray_SetElement( data, 1, weaponName ); m_pScaleformUI->ValueArray_SetElement( data, 2, pchClassName ); m_pScaleformUI->ValueArray_SetElement( data, 3, szGrenName ? szGrenName : ""); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "SetGunGamePanelData", data, 4 ); } nExtraPanelType = WIN_EXTRATYPE_GGNEXT; } } } // set the progress bar text //int nMedalsNeededToRank = 0; CUtlVector< int > nProgressCatagories; // if one of the other panel above told us to show, we should show if ( !bHideProgressAndFunFact ) { if ( bShowProgress ) { if ( nIdealProgressCatagory == -1 ) { for ( int i = 0; i < MEDAL_CATEGORY_ACHIEVEMENTS_END; i++ ) { int nTempRank = g_PlayerRankManager.CalculateRankForCategory( (MedalCategory_t)i ); if ( nTempRank < (MEDAL_RANK_COUNT-1) ) nProgressCatagories.AddToTail(i); } if ( nProgressCatagories.Count() == 0 ) { // we maxed out all of our ranks, congrats!!!! bShowProgress = false; } else { // we don't have an ideal category to show a hint, so pick one to display nIdealProgressCatagory = nProgressCatagories[ RandomInt( 0, nProgressCatagories.Count()-1 ) ]; nProgressCatagories.RemoveAll(); } } if ( bShowProgress ) { int nCurrentRank = g_PlayerRankManager.CalculateRankForCategory( (MedalCategory_t)nIdealProgressCatagory ); int nMinMedalsNeeded = g_PlayerRankManager.GetMinMedalsForRank( (MedalCategory_t)nIdealProgressCatagory, (MedalRank_t)(MIN(nCurrentRank + 1, (int)(MEDAL_RANK_COUNT-1))) ); int nMedalsAchieved = g_PlayerRankManager.CountAchievedInCategory( (MedalCategory_t)nIdealProgressCatagory ); const wchar_t *progString = g_pVGuiLocalize->Find( "#SFUI_WinPanelProg_need_in_catagory" ); wchar_t wzAwardNum[4]; _snwprintf( wzAwardNum, ARRAYSIZE(wzAwardNum), L"%d", (nMinMedalsNeeded-nMedalsAchieved) ); wchar_t finalProgressText[256]; g_pVGuiLocalize->ConstructString( finalProgressText, sizeof(finalProgressText), progString , 2, wzAwardNum, g_pVGuiLocalize->Find( g_PlayerRankManager.GetMedalCatagoryName((MedalCategory_t)nIdealProgressCatagory) ) ); SetProgressBarText( (nMinMedalsNeeded-nMedalsAchieved), finalProgressText ); //Msg( "MinMedalsNeeded = %d, MedalsAchieved = %d, NeededForNext = %d\n", nMinMedalsNeeded, nMedalsAchieved, (nMinMedalsNeeded-nMedalsAchieved) ); } } if ( bIsWarmup ) { SetFunFactLabel( L"" ); } // otherwise we show a FUN FACT! else if ( !bShowProgress ) { /* "show_timer_defend" "bool" "show_timer_attack" "bool" "timer_time" "int" "final_event" "byte" // 0 - no event, 1 - bomb exploded, 2 - flag capped, 3 - timer expired "funfact_type" "byte" //WINPANEL_FUNFACT in cs_shareddef.h "funfact_player" "byte" "funfact_data1" "long" "funfact_data2" "long" "funfact_data3" "long" */ if ( m_nFunFactPlayer == GetLocalPlayerIndex() ) { CEG_PROTECT_VIRTUAL_FUNCTION( SFHudWinPanel_FireGameEvent ); } // Final Fun Fact SetFunFactLabel( L"" ); const char *pFunFact = STRING( m_nFunfactToken ); if ( pFunFact && V_strlen( pFunFact ) > 0 ) { wchar_t funFactText[256]; wchar_t playerText[MAX_DECORATED_PLAYER_NAME_LENGTH]; wchar_t dataText1[8], dataText2[8], dataText3[8]; if ( m_nFunFactPlayer >= 1 && m_nFunFactPlayer <= MAX_PLAYERS ) { playerText[0] = L'\0'; C_CS_PlayerResource *cs_PR = dynamic_cast<C_CS_PlayerResource *>( g_PR ); if ( !cs_PR ) return; cs_PR->GetDecoratedPlayerName( m_nFunFactPlayer, playerText, sizeof( playerText ), k_EDecoratedPlayerNameFlag_Simple ); if ( playerText[0] == L'\0' ) { V_snwprintf( playerText, ARRAYSIZE( playerText ), PRI_WS_FOR_WS, g_pVGuiLocalize->Find( "#winpanel_former_player" ) ); } } else { V_snwprintf( playerText, ARRAYSIZE( playerText ), L"" ); } V_snwprintf( dataText1, ARRAYSIZE( dataText1 ), L"%i", m_nFunFactParam1 ); V_snwprintf( dataText2, ARRAYSIZE( dataText2 ), L"%i", m_nFunFactParam2 ); V_snwprintf( dataText3, ARRAYSIZE( dataText3 ), L"%i", m_nFunFactParam3 ); // Vararg support on consoles isn't complete, so use the keyvalue version of ConstructString instead so // we can support formatting like "%s2 has fired %s1 shots", etc. KeyValues *pkvFunFactVariables = new KeyValues( "variables" ); KeyValues::AutoDelete autodelete( pkvFunFactVariables ); pkvFunFactVariables->SetWString( "s1", playerText ); pkvFunFactVariables->SetWString( "s2", dataText1 ); pkvFunFactVariables->SetWString( "s3", dataText2 ); pkvFunFactVariables->SetWString( "s4", dataText3 ); g_pVGuiLocalize->ConstructString( funFactText, sizeof(funFactText), pFunFact, pkvFunFactVariables ); SetFunFactLabel( funFactText ); if( g_pVGuiLocalize->Find( pFunFact ) == NULL ) { Warning( "No valid fun fact string for %s\n", pFunFact ); } } } } ShowWinExtraDataPanel( nExtraPanelType ); } void SFHudWinPanel::SetProgressBarText( int nAmount, const wchar *wszDescText ) { if ( !FlashAPIIsValid() ) return; wchar_t wNum[16]; V_snwprintf( wNum, ARRAYSIZE( wNum ), L"%i", nAmount ); WITH_SFVALUEARRAY_SLOT_LOCKED( data, 2 ) { m_pScaleformUI->ValueArray_SetElement( data, 0, wNum ); m_pScaleformUI->ValueArray_SetElement( data, 1, wszDescText ); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "SetProgressText", data, 2 ); } } void SFHudWinPanel::SetFunFactLabel( const wchar *szFunFact ) { if ( !FlashAPIIsValid() ) return; WITH_SFVALUEARRAY_SLOT_LOCKED( data, 1 ) { m_pScaleformUI->ValueArray_SetElement( data, 0, szFunFact ); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "SetFunFactText", data, 1 ); } } void SFHudWinPanel::SetMVP( C_CSPlayer* pPlayer, CSMvpReason_t reason, int32 nMusicKitMVPs /* = 0 */ ) { if ( pPlayer ) m_iMVP = pPlayer->entindex(); if ( FlashAPIIsValid() ) { if ( g_PR && pPlayer ) { // First set the text to the name of the player. wchar_t wszPlayerName[MAX_DECORATED_PLAYER_NAME_LENGTH]; ( ( C_CS_PlayerResource* ) g_PR )->GetDecoratedPlayerName( pPlayer->entindex(), wszPlayerName, sizeof( wszPlayerName ), EDecoratedPlayerNameFlag_t( k_EDecoratedPlayerNameFlag_Simple | k_EDecoratedPlayerNameFlag_DontUseNameOfControllingPlayer ) ); // // Construct the reason text. // const char* mvpReasonToken = NULL; switch ( reason ) { case CSMVP_ELIMINATION: mvpReasonToken = "winpanel_mvp_award_kills"; break; case CSMVP_BOMBPLANT: mvpReasonToken = "winpanel_mvp_award_bombplant"; break; case CSMVP_BOMBDEFUSE: mvpReasonToken = "winpanel_mvp_award_bombdefuse"; break; case CSMVP_HOSTAGERESCUE: mvpReasonToken = "winpanel_mvp_award_rescue"; break; case CSMVP_GUNGAMEWINNER: mvpReasonToken = "winpanel_mvp_award_gungame"; break; default: mvpReasonToken = "winpanel_mvp_award"; break; } wchar_t *pReason = g_pVGuiLocalize->Find( mvpReasonToken ); if ( !pReason ) { pReason = L"%s1"; } wchar_t wszBuf[256]; g_pVGuiLocalize->ConstructString( wszBuf, sizeof( wszBuf ), pReason, 1, wszPlayerName ); // Get the player xuid. char xuidText[255]; g_PR->FillXuidText( pPlayer->entindex(), xuidText, sizeof( xuidText ) ); const int nParamCount = 5; WITH_SFVALUEARRAY_SLOT_LOCKED( data, nParamCount ) { if ( m_hMVP ) { m_hMVP->SetTextHTML( wszBuf ); } int nParamNum = 0; m_pScaleformUI->ValueArray_SetElement( data, nParamNum++, xuidText ); m_pScaleformUI->ValueArray_SetElement( data, nParamNum++, pPlayer->GetPlayerName() ); m_pScaleformUI->ValueArray_SetElement( data, nParamNum++, pPlayer->GetTeamNumber() ); m_pScaleformUI->ValueArray_SetElement( data, nParamNum++, pPlayer->IsLocalPlayer() ); m_pScaleformUI->ValueArray_SetElement( data, nParamNum++, nMusicKitMVPs ); Assert( nParamNum == nParamCount ); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "ShowAvatar", data, nParamCount ); } if ( reason == CSMVP_GUNGAMEWINNER ) { WITH_SFVALUEARRAY_SLOT_LOCKED( data, 5 ) { int nSecond = -1; int nThird = -1; SFHudTeamCounter* pTeamCounter = GET_HUDELEMENT( SFHudTeamCounter ); if ( pTeamCounter ) { for ( int i = 0 ; i < MAX_PLAYERS ; ++i) { int indx = pTeamCounter->GetPlayerEntIndexInSlot( i ); if ( pPlayer->entindex() != indx ) { if ( nSecond == -1 ) { nSecond = indx; } else { nThird = indx; break; } } } } char xuidText1[255]; g_PR->FillXuidText( nSecond, xuidText1, sizeof( xuidText1 ) ); char xuidText2[255]; g_PR->FillXuidText( nThird, xuidText2, sizeof( xuidText2 ) ); CBasePlayer* pBasePlayer1 = UTIL_PlayerByIndex( nSecond ); C_CSPlayer* pPlayer1 = ToCSPlayer( pBasePlayer1 ); CBasePlayer* pBasePlayer2 = UTIL_PlayerByIndex( nThird ); C_CSPlayer* pPlayer2 = ToCSPlayer( pBasePlayer2 ); m_pScaleformUI->ValueArray_SetElement( data, 0, wszPlayerName ); m_pScaleformUI->ValueArray_SetElement( data, 1, xuidText1 ); m_pScaleformUI->ValueArray_SetElement( data, 2, xuidText2 ); m_pScaleformUI->ValueArray_SetElement( data, 3, pPlayer1 ? pPlayer1->GetTeamNumber() : -1 ); m_pScaleformUI->ValueArray_SetElement( data, 4, pPlayer2 ? pPlayer2->GetTeamNumber() : -1 ); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "ShowGGRunnerUpAvatars", data, 5 ); } } } else { WITH_SLOT_LOCKED { // Hide the MVP text. if ( m_hMVP ) { m_hMVP->SetTextHTML( "" ); } m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "HideAvatar", NULL, 0 ); } } } } void SFHudWinPanel::ApplyYOffset( int nOffset ) { if ( FlashAPIIsValid() ) { WITH_SFVALUEARRAY_SLOT_LOCKED( data, 1 ) { m_pScaleformUI->ValueArray_SetElement( data, 0, nOffset ); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "setYOffset", data, 1 ); } } } void SFHudWinPanel::ShowTeamWinPanel( int result, const char* winnerText ) { bool bOkToDraw = true; C_CSPlayer *pLocalPlayer = C_CSPlayer::GetLocalCSPlayer(); if ( !pLocalPlayer ) return; if ( pLocalPlayer->GetTeamNumber() == TEAM_UNASSIGNED && !pLocalPlayer->IsHLTV() ) { bOkToDraw = false; } bool bShowTeamLogo = false; char szLogoString[64]; szLogoString[0] = '\0'; wchar_t wszWinnerText[1024]; wszWinnerText[0] = L'\0'; C_Team *pTeam = GetGlobalTeam( result ); if ( pTeam && !StringIsEmpty( pTeam->Get_LogoImageString() ) ) { bShowTeamLogo = true; V_snprintf( szLogoString, ARRAYSIZE( szLogoString ), TEAM_LOGO_IMG_STRING, pTeam->Get_LogoImageString() ); } wchar_t wszName[512]; if ( m_hWinPanelParent && m_hWinner && FlashAPIIsValid() && m_bActive && bOkToDraw ) { if ( CSGameRules() && CSGameRules()->IsPlayingCoopMission() ) { if ( result == TEAM_CT ) g_pVGuiLocalize->ConstructString( wszName, sizeof( wszName ), g_pVGuiLocalize->Find( "#SFUI_WinPanel_Coop_Mission_Win" ), nullptr ); else g_pVGuiLocalize->ConstructString( wszName, sizeof( wszName ), g_pVGuiLocalize->Find( "#SFUI_WinPanel_Coop_Mission_Lose" ), nullptr ); g_pScaleformUI->MakeStringSafe( wszName, wszWinnerText, sizeof( wszWinnerText ) ); } else if ( ( pTeam != NULL ) && !StringIsEmpty( pTeam->Get_ClanName() ) ) { wchar_t wszTemp[MAX_TEAM_NAME_LENGTH]; g_pVGuiLocalize->ConvertANSIToUnicode( pTeam->Get_ClanName(), wszTemp, sizeof( wszTemp ) ); // const wchar_t *winString = g_pVGuiLocalize->Find( "#SFUI_WinPanel_Team_Win_Team" ); g_pVGuiLocalize->ConstructString( wszName, sizeof( wszName ), g_pVGuiLocalize->Find( "#SFUI_WinPanel_Team_Win_Team" ), 1, wszTemp ); // we have a custom team name, convert to wide // // now make the team name string safe g_pScaleformUI->MakeStringSafe( wszName, wszWinnerText, sizeof( wszWinnerText ) ); } else { g_pVGuiLocalize->ConstructString( wszName, sizeof( wszName ), g_pVGuiLocalize->Find( winnerText ), nullptr ); g_pScaleformUI->MakeStringSafe( wszName, wszWinnerText, sizeof( wszWinnerText ) ); } WITH_SFVALUEARRAY_SLOT_LOCKED( data, 2 ) { m_hWinner->SetTextHTML( wszWinnerText ); { m_pScaleformUI->ValueArray_SetElement( data, 0, result ); m_pScaleformUI->ValueArray_SetElement( data, 1, bShowTeamLogo ? szLogoString : "" ); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "showTeamWin", data, 2 ); } } if ( GetViewPortInterface() && !pLocalPlayer->IsSpectator() && !engine->IsHLTV() ) { GetViewPortInterface()->ShowPanel( PANEL_ALL, false ); } m_bVisible = true; } } void SFHudWinPanel::ShowGunGameWinPanel( void /*int nWinner, int nSecond, int nThird*/ ) { if ( m_hWinPanelParent && m_hWinner && FlashAPIIsValid() && m_bActive ) { WITH_SLOT_LOCKED { m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "showArsenalWin", NULL, 0 ); } if ( GetViewPortInterface() ) { GetViewPortInterface()->ShowPanel( PANEL_ALL, false ); } m_bVisible = true; } } void SFHudWinPanel::ShowWinExtraDataPanel( int nExtraPanelType ) { if ( m_hWinPanelParent && m_hWinner && m_FlashAPI && m_bActive ) { C_CSPlayer *pLocalPlayer = C_CSPlayer::GetLocalCSPlayer(); if( pLocalPlayer ) { C_RecipientFilter filter; filter.AddRecipient( pLocalPlayer ); C_BaseEntity::EmitSound( filter, SOUND_FROM_WORLD, "Player.InfoPanel" ); } WITH_SLOT_LOCKED { WITH_SFVALUEARRAY( data, 1 ) { m_pScaleformUI->ValueArray_SetElement( data, 0, nExtraPanelType ); m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "showTeamWinDataPanel", data, 1 ); } } } } bool SFHudWinPanel::IsVisible( void ) { return m_bVisible; } void SFHudWinPanel::Hide( void ) { if ( m_FlashAPI && m_pScaleformUI) { WITH_SLOT_LOCKED { m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "hide", NULL, 0 ); } m_bVisible = false; } } void SFHudWinPanel::DeviceReset( void *pDevice, void *pPresentParameters, void *pHWnd ) { if ( FlashAPIIsValid() ) { WITH_SLOT_LOCKED { m_pScaleformUI->Value_InvokeWithoutReturn( m_FlashAPI, "RefreshAvatarImage", NULL, 0 ); } } } #endif // INCLUDE_SCALEFORM
xingxingso/leetcode
contains-duplicate/main.go
/* Package contains_duplicate https://leetcode-cn.com/problems/contains-duplicate/ 217. 存在重复元素 给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 ,返回 true ;如果数组中每个元素互不相同,返回 false 。 提示: 1 <= nums.length <= 10^5 -10^9 <= nums[i] <= 10^9 */ package contains_duplicate // --- 自己 /* 方法一: 哈希表 时间复杂度: 空间复杂度: */ func containsDuplicate(nums []int) bool { hash := make(map[int]bool, 0) for i := 0; i < len(nums); i++ { if hash[nums[i]] { return true } hash[nums[i]] = true } return false }
mge-engine/mge
src/mge/asset/asset_type.hpp
// mge - Modern Game Engine // Copyright (c) 2021 by <NAME> // All rights reserved. #pragma once #include "boost/boost_operators.hpp" #include "mge/asset/dllexport.hpp" #include <iosfwd> #include <string> #include <string_view> namespace mge { /** * @brief Asset type. * * An asset type helps in identifying the loader for a specific * asset. Asset types are modeled after mime types, i.e. they * have a type and a subtype. */ class MGEASSET_EXPORT asset_type : public boost::totally_ordered<asset_type> { public: /** * @brief Construct empty/unknown asset type. */ asset_type(); /** * @brief Construct asset type. * * @param type asset type * @param subtype asset subtype */ asset_type(std::string_view type, std::string_view subtype); /** * @brief Copy constructor. * @param t copied type */ asset_type(const asset_type& t) = default; /** * @brief Move constructor. * @param t moved type */ asset_type(asset_type&& t) = default; ~asset_type() = default; /** * @brief Access asset type. * * @return type */ std::string_view type() const; /** * @brief Access asset subtype. * * @return subtype */ std::string_view subtype() const; bool operator==(const asset_type& t) const; bool operator<(const asset_type& t) const; private: std::string m_type; std::string m_subtype; }; MGEASSET_EXPORT std::ostream& operator<<(std::ostream& os, const asset_type& t); namespace literals { MGEASSET_EXPORT asset_type operator""_at(const char* s, size_t l); } } // namespace mge
dios-game/dios-cocos
src/oslibs/cocos/cocos-src/tests/js-tests/src/CocoStudioTest/GUITest/UIRichTextTest/UIRichTextTest.js
/**************************************************************************** Copyright (c) 2008-2010 <NAME> Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ var UIRichTextTest = UISceneEditor.extend({ _richText:null, init: function () { if (this._super()) { //init text this._topDisplayLabel.setString(""); this._bottomDisplayLabel.setString("RichText"); var widgetSize = this._widget.getContentSize(); var button = new ccui.Button(); button.setTouchEnabled(true); button.loadTextures("ccs-res/cocosui/animationbuttonnormal.png", "ccs-res/cocosui/animationbuttonpressed.png", ""); button.setTitleText("switch"); button.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 + button.getContentSize().height * 2.5)); button.addTouchEventListener(this.touchEvent,this); this._mainNode.addChild(button); // RichText var richText = new ccui.RichText(); richText.ignoreContentAdaptWithSize(false); richText.setContentSize(cc.size(120, 100)); var re1 = new ccui.RichElementText(1, cc.color.WHITE, 255, "This color is white. ", "Helvetica", 10); var re2 = new ccui.RichElementText(2, cc.color.YELLOW, 255, "And this is yellow. ", "Helvetica", 10); var re3 = new ccui.RichElementText(3, cc.color.BLUE, 255, "This one is blue. ", "Helvetica", 10); var re4 = new ccui.RichElementText(4, cc.color.GREEN, 255, "And green. ", "Helvetica", 10); var re5 = new ccui.RichElementText(5, cc.color.RED, 255, "Last one is red ", "Helvetica", 10); var reimg = new ccui.RichElementImage(6, cc.color.WHITE, 255, "ccs-res/cocosui/sliderballnormal.png"); ccs.armatureDataManager.addArmatureFileInfo("ccs-res/cocosui/100/100.ExportJson"); var pAr = new ccs.Armature("100"); pAr.getAnimation().play("Animation1"); var recustom = new ccui.RichElementCustomNode(1, cc.color.WHITE, 255, pAr); var re6 = new ccui.RichElementText(7, cc.color.ORANGE, 255, "Have fun!! ", "Helvetica", 10); richText.pushBackElement(re1); richText.insertElement(re2, 1); richText.pushBackElement(re3); richText.pushBackElement(re4); richText.pushBackElement(re5); richText.insertElement(reimg, 2); richText.pushBackElement(recustom); richText.pushBackElement(re6); richText.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2)); this._mainNode.addChild(richText); this._richText = richText; return true; } return false; }, touchEvent: function (sender, type) { if (type == ccui.Widget.TOUCH_ENDED) { if (this._richText.isIgnoreContentAdaptWithSize()) { this._richText.ignoreContentAdaptWithSize(false); this._richText.setContentSize(cc.size(120, 100)); } else { this._richText.ignoreContentAdaptWithSize(true); } } } });
edotau/goFish
simpleio/roman.go
package simpleio import ( "log" ) // ToNumber to covert roman numeral to decimal func ToNumber(n string) int { out := 0 ln := len(n) var c, cnext string var vc, vcnext int for i := 0; i < ln; i++ { c = string(n[i]) vc = num[c] if i < ln-1 { cnext = string(n[i+1]) vcnext = LookUpRoman(cnext) if vc < vcnext { out += vcnext - vc i++ } else { out += vc } } else { out += vc } } return out } // ToRoman is to convert decimal number to roman numeral func ToRoman(n int) string { out := "" var v int for n > 0 { v = highestDecimal(n) out += InvMap(v) n -= v } return out } func highestDecimal(n int) int { for _, v := range maxTable { if v <= n { return v } } return 1 } var maxTable = []int{ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1, } func LookUpRoman(s string) int { switch s { case "I": return 1 case "V": return 5 case "X": return 10 case "L": return 50 case "C": return 100 case "M": return 1000 } log.Fatalf("Error: did not find roman string...\n") return 0 } var num = map[string]int{ "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000, } func InvMap(num int) string { switch num { case 1000: return "M" case 900: return "CM" case 500: return "D" case 400: return "CD" case 100: return "C" case 90: return "XC" case 50: return "L" case 40: return "XL" case 10: return "X" case 9: return "IX" case 5: return "V" case 4: return "IV" case 1: return "I" } log.Fatalf("Error: roman string does not exist for the given number") return "" }
lanSeFangZhou/pythonbase
python100days/Day16-20/example12.py
""" 面向对象的三大支柱:封装、继承、多态 面向对象的设计原则:SOLID原则 面向对象的设计模式:GoF设计模式(单例、工厂、代理、策略、迭代器) 月薪结算系统 - 部门经理每月15000 程序员每小时200 销售员1800底薪加销售额5%提成 """ from abc import ABCMeta, abstractmethod class Employee(metaclass=ABCMeta): '''员工(抽象类)''' def __init__(self, name): self.name = name @abstractmethod def get_salary(self): '''结算月薪(抽象方法)''' pass class Manager(Employee): '''部门经理''' def get_salary(self): return 15000.0 class Programmer(Employee): '''程序员''' def __init__(self, name, working_hour=0): self.working_hour = working_hour super().__init__(name) def get_salary(self): return 200.0 * self.working_hour class Salesman(Employee): '''销售员''' def __init__(self, name, sales=0.0): self.sales = sales super().__init__(name) def get_salary(self): return 1800.0 + self.sales * 0.05 class EmployeeFactory(): '''创建员工的工厂(工厂模式 - 通过工厂实现对象使用者和对象之间的解耦合)''' @staticmethod def create(emp_type, *args, **kwargs): '''创建员工''' emp_type = emp_type.upper() emp = None if emp_type == 'M': emp = Manager(*args, **kwargs) elif emp_type == 'P': emp = Programmer(*args, **kwargs) elif emp_type == 'S': emp = Salesman(*args, **kwargs) return emp
WcaleNieWolny/FunnyGuilds
plugin/src/main/java/net/dzikoysk/funnyguilds/nms/BlockDataChanger.java
package net.dzikoysk.funnyguilds.nms; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import net.dzikoysk.funnyguilds.FunnyGuilds; import net.dzikoysk.funnyguilds.shared.bukkit.LocationUtils; import org.bukkit.block.Block; public class BlockDataChanger { private static Class<?> craftBlockClass; private static Method setDataMethod; static { craftBlockClass = Reflections.getCraftBukkitClass("block.CraftBlock"); setDataMethod = Reflections.getMethod(craftBlockClass, "setData", byte.class); } public static void applyChanges(Block targetBlock, byte newData) { if (!Reflections.USE_PRE_13_METHODS) { return; } try { setDataMethod.invoke(targetBlock, newData); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { FunnyGuilds.getPluginLogger().error("Failed to change block data for a block at: " + LocationUtils.toString(targetBlock.getLocation()), ex); } } private BlockDataChanger() { } }
uuuugi/-
src/2439.c
#include <stdio.h> int main(void) { int line; scanf("%d", &line); for (int i = 0; i < line; i++) { for (int j = line-1; j > i; j--) printf(" "); for (int k = 0; k <=i; k++) printf("*"); if(i!=line-1) printf("\n"); } return 0; }
javrasya/zemberek-nlp
morphology/src/main/java/zemberek/morphology/lexicon/RootSuffix.java
<reponame>javrasya/zemberek-nlp package zemberek.morphology.lexicon; import zemberek.core.turkish.PrimaryPos; public class RootSuffix extends Suffix { public PrimaryPos pos; public RootSuffix(String id) { super(id); } public RootSuffix(String id, PrimaryPos pos) { super(id); this.pos = pos; } }
sagarteria/AlexaSkill---Mu-Sigma
node_modules/jovo-framework/lib/integrations/analytics/voiceLabsAnalytics.js
'use strict'; const _ = require('lodash'); const BaseApp = require('./../../app'); /** * @deprecated Implementation of Voicelabs' analytics module for alexa */ class VoiceLabsAlexa { /** * Constructor * @param {*} config */ constructor(config) { try { this.voiceLabsAlexa = require('voicelabs'); this.voiceLabsAlexa.initialize(_.get(config, 'key')); this.trackSlots = _.get(config, 'trackSlots'); this.trackSpeechText = _.get(config, 'trackSpeechText'); this.platformType = BaseApp.PLATFORM_ENUM.ALEXA_SKILL; } catch (err) { console.log('\nPlease install VoiceLabs: npm install voicelabs\n'); } } /** * Calls the voicelabs track method * @param {Jovo} app jovo app object */ track(app) { this.voiceLabsAlexa.track( app.alexaSkill().getSession(), app.getHandlerPath(), this.trackSlots ? app.alexaSkill().getRequest().getSlots() : null, this.trackSpeechText ? app.alexaSkill().getSpeechText() : null ); }; } /** * Implementation of Voicelabs' analytics module for google action */ class VoiceLabsGoogleAction { /** * Constructor * @param {*} config */ constructor(config) { try { this.voiceInsights = require('voicelabs-assistant-sdk'); this.voiceInsights.initialize(_.get(config, 'key')); this.platformType = BaseApp.PLATFORM_ENUM.GOOGLE_ACTION; } catch (err) { console.log('\nPlease install VoiceLabs: npm install voicelabs-assistant-sdk\n'); } } /** * Calls the voicelabs track method * @param {Jovo} app jovo app object */ track(app) { let request = app.googleAction().getRequest().getOriginalRequest() ? app.googleAction().getRequest().getOriginalRequest() : null; this.voiceInsights.track( app.getIntentName(), request.data, app.googleAction().getSpeechText() ); }; } module.exports.VoiceLabsAlexa = VoiceLabsAlexa; module.exports.VoiceLabsGoogleAction = VoiceLabsGoogleAction;
Samuel-Harden/SimWorldsBoids
Libs/jsoncons/include/jsoncons/json_traits.hpp
// Copyright 2013 <NAME> // Distributed under the Boost license, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See https://github.com/danielaparker/jsoncons for latest version #ifndef JSONCONS_JSON_TRAITS_HPP #define JSONCONS_JSON_TRAITS_HPP #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch" #endif #include <jsoncons/output_format.hpp> #include <jsoncons/parse_error_handler.hpp> namespace jsoncons { template <class CharT> struct json_traits { static const bool is_object_sorted = true; typedef basic_default_parse_error_handler<CharT> parse_error_handler_type; }; template <class CharT> struct ojson_traits { static const bool is_object_sorted = false; typedef basic_default_parse_error_handler<CharT> parse_error_handler_type; }; } #endif
lit-uriy/mtl4-mirror
libs/numeric/mtl/test/sparse_banded_matrix_test.cpp
// Software License for MTL // // Copyright (c) 2007 The Trustees of Indiana University. // 2008 Dresden University of Technology and the Trustees of Indiana University. // 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com. // All rights reserved. // Authors: <NAME> and <NAME> // // This file is part of the Matrix Template Library // // See also license.mtl.txt in the distribution. #define MTL_WITH_DEVELOPMENT #define MTL_VERBOSE_TEST #include <string> #include <iostream> #include <boost/numeric/mtl/mtl.hpp> #include <boost/numeric/mtl/matrix/sparse_banded.hpp> template <typename Matrix> void laplacian_test(Matrix& A, unsigned dim1, unsigned dim2, const char* name) { mtl::io::tout << "\n" << name << "\n"; laplacian_setup(A, dim1, dim2); mtl::io::tout << "Laplacian A:\n" << A << std::endl; if (dim1 > 1 && dim2 > 1) { typename Matrix::value_type four(4.0), minus_one(-1.0), zero(0.0); MTL_THROW_IF(A[0][0] != four, mtl::runtime_error("wrong diagonal")); MTL_THROW_IF(A[0][1] != minus_one, mtl::runtime_error("wrong east neighbor")); MTL_THROW_IF(A[0][dim2] != minus_one, mtl::runtime_error("wrong south neighbor")); MTL_THROW_IF(dim2 > 2 && A[0][2] != zero, mtl::runtime_error("wrong zero-element")); MTL_THROW_IF(A[1][0] != minus_one, mtl::runtime_error("wrong west neighbor")); MTL_THROW_IF(A[dim2][0] != minus_one, mtl::runtime_error("wrong north neighbor")); MTL_THROW_IF(dim2 > 2 && A[2][0] != zero, mtl::runtime_error("wrong zero-element")); } } template <typename Matrix> void rectangle_test(Matrix& A, const char* name) { { mtl::mat::inserter<Matrix> ins(A); int i= 1; unsigned nc= num_cols(A); for (unsigned r= 0; r < num_rows(A); r++) { if (r < nc - 4) ins(r, r + 4) << i++; if (r < nc) ins(r, r) << i++; if (r >= 2 && r < nc + 2) ins(r, r - 2) << i++; if (r >= 4 && r < nc + 4) ins[r][r - 4] << i++; } } mtl::io::tout << name << ": A=\n" << A << '\n'; } template <typename Matrix, typename Tag> void two_d_iteration(const Matrix & A, Tag) { namespace traits = mtl::traits; typename traits::row<Matrix>::type row(A); typename traits::col<Matrix>::type col(A); typename traits::const_value<Matrix>::type value(A); typedef typename traits::range_generator<Tag, Matrix>::type cursor_type; for (cursor_type cursor = mtl::begin<Tag>(A), cend = mtl::end<Tag>(A); cursor != cend; ++cursor) { typedef mtl::tag::nz inner_tag; mtl::io::tout << "---\n"; typedef typename traits::range_generator<inner_tag, cursor_type>::type icursor_type; for (icursor_type icursor = mtl::begin<inner_tag>(cursor), icend = mtl::end<inner_tag>(cursor); icursor != icend; ++icursor) mtl::io::tout << "A[" << row(*icursor) << ", " << col(*icursor) << "] = " << value(*icursor) << '\n'; } mtl::io::tout << "===\n\n"; } template <typename Matrix> void mat_vec_mult_test(const Matrix& A, const char* name) { typedef typename Matrix::value_type value_type; mtl::io::tout << name << " " << num_rows(A) << " by " << num_cols(A) << '\n' << A; mtl::dense_vector<value_type> v, w(num_cols(A), 3.0), v2; v= A * w; mtl::io::tout << "A * v = " << v << '\n'; mtl::compressed2D<value_type> B(A); v2= B * w; mtl::io::tout << "Should be: " << v2 << "\n\n"; v2-= v; MTL_THROW_IF(two_norm(v2) > 0.001, mtl::runtime_error("wrong result for sparse banded times vector")); } int main(int, char**) { using namespace mtl; #ifdef MTL_WITH_DEVELOPMENT unsigned dim1= 3, dim2= 4; mat::sparse_banded<double> dr, dr2(6, 11), dr3(11, 6), dr4(6, 5); laplacian_test(dr, dim1, dim2, "Dense row major"); rectangle_test(dr2, "Dense row major"); rectangle_test(dr3, "Dense row major"); rectangle_test(dr4, "Dense row major"); mat::compressed2D<double> C; laplacian_setup(C, dim1, dim2); mat::sparse_banded<double> D; D= C; mtl::io::tout << "D is\n" << D << '\n'; two_d_iteration(D, mtl::tag::row()); mat::compressed2D<double> E; E= D; mtl::io::tout << "E is\n" << E << '\n'; mat::sparse_banded<double> dr5(5, 5), dr6(5, 5); { mtl::mat::inserter<mat::sparse_banded<double> > ins5(dr5), ins6(dr6); ins5[2][0] << 1; ins5[3][1] << 2; ins5[4][2] << 3; ins5[4][0] << 4; ins6[0][2] << 1; ins6[1][3] << 2; ins6[2][4] << 3; ins6[0][4] << 4; } mat_vec_mult_test(dr2, "Dense row major"); mat_vec_mult_test(dr3, "Dense row major"); mat_vec_mult_test(dr4, "Dense row major"); mat_vec_mult_test(dr5, "Dense row major"); mat_vec_mult_test(dr6, "Dense row major"); mat_vec_mult_test(dr, "Dense row major"); #endif return 0; }
alljoyn/compliance-tests
java/components/validation-ctt/HEAD/ctt_web_server/src/test/java/com/at4wireless/security/TestCASTicketValidator.java
package com.at4wireless.security; import static org.junit.Assert.assertTrue; import java.util.Map; import org.jasig.cas.client.validation.TicketValidationException; import org.junit.Assert; import org.junit.Test; public class TestCASTicketValidator { private static final String lfCASResponse = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>" +"<cas:authenticationSuccess>" +"<cas:user>cjcollier</cas:user>" +"<cas:attributes>" +"<cas:attraStyle>Jasig</cas:attraStyle>" +"<cas:uid>85233</cas:uid>" +"<cas:mail><EMAIL></cas:mail>" +"<cas:created>1454939906</cas:created>" +"<cas:timezone>America/Los_Angeles</cas:timezone>" +"<cas:language></cas:language>" +"<cas:drupal_roles>authenticated user</cas:drupal_roles>" +"<cas:drupal_roles>administrator</cas:drupal_roles>" +"<cas:drupal_roles>lf-group-admin</cas:drupal_roles>" +"<cas:drupal_roles>group administrator</cas:drupal_roles>" +"<cas:group>lf-collab-admins</cas:group>" +"<cas:group>lf-itwiki-user</cas:group>" +"<cas:group>lf-racktables</cas:group>" +"<cas:group>lf-staff</cas:group>" +"<cas:group>lfinfra-gerrit-lfit</cas:group>" +"<cas:group>lf-mailman3-admins</cas:group>" +"<cas:group>fdio-gerrit-one-committers</cas:group>" +"<cas:group>collab-external-rt-access</cas:group>" +"<cas:group>fdio-gerrit-vppsb-committers</cas:group>" +"<cas:group>fdio-gerrit-deb_dpdk-committers</cas:group>" +"<cas:group>fdio-gerrit-ci-management-committers</cas:group>" +"<cas:group>fdio-gerrit-trex-committers</cas:group>" +"<cas:field_lf_first_name>C.J.</cas:field_lf_first_name>" +"<cas:field_lf_full_name><NAME></cas:field_lf_full_name>" +"<cas:field_lf_last_name>Collier</cas:field_lf_last_name>" +"<cas:profile_name_first>C.J.</cas:profile_name_first>" +"<cas:profile_name_last>Collier</cas:profile_name_last>" +"<cas:profile_name_full><NAME></cas:profile_name_full>" +"</cas:attributes>" +"</cas:authenticationSuccess>" +"</cas:serviceResponse>"; @Test public void testCasToCttUserParsing() { CustomCas20ServiceTicketValidator customCas20ServiceTicketValidator = new CustomCas20ServiceTicketValidator("https://identity.linuxfoundation.org/cas/serviceValidate"); final Map<String, Object> attributes = customCas20ServiceTicketValidator.extractCustomAttributes(lfCASResponse); try { final String role = customCas20ServiceTicketValidator.parseRoleFromCasToCtt(attributes); assertTrue(role.equals("ROLE_USER")); } catch (TicketValidationException e) { Assert.fail(e.getMessage()); } } }
liuyangspace/java-test
src/javase/data/array/ArrayBase.java
<filename>src/javase/data/array/ArrayBase.java<gh_stars>0 package javase.data.array; /** * Java array 数组 * * * */ class ArrayBase { /** * 数组是有序数据的集合,数组中的每个元素具有相同的数据类型,数组名和下标可惟一地确定数组中的元素。 * 一维数组: * 定义方式为:type arrayName=new type[arraySize]; * 数组元素的引用: arrayName[index] * 多维数组: * 二维数组的定义: type arrayName[][]; * 二维数组元素的引用:arrayName[index1][index2] */ int intArray1[] = new int[3]; int intArray2[] = {1,2,3,4,5}; int intArray6[] = new int[]{1,2,3}; String[] stringArray = {"a","v"}; String[] stringArray2 = new String[]{"a","v"}; int intArray3[][]=new int[2][]; int intArray4[][]=new int[2][3]; int intArray5[][]={{1,2},{3,4}}; { intArray3[0]=new int[3]; intArray3[1]=new int[3]; } public Object array(String[] args){ return new int[]{1,2,3};// } public static void main(String[] args){ ArrayBase a = new ArrayBase(); String[] b = {"a","b","c"}; for (String s:a.stringArray){ System.out.println(s); } a.array(b); } }
snaphy/generator-snaphy
generators/app/templates/common/plugins/JqueryValidate/client/scripts/validateServices.js
<reponame>snaphy/generator-snaphy /** * Created by robins on 3/12/15. */ (function(){'use strict';})(); /*jslint browser: true*/ /*global $, jQuery, angular, $snaphy , redirectOtherWise*/ angular.module($snaphy.getModuleName())
strejcik/-MERN-e-commerce
models/cart.model.js
const config = require('../config/locale'); const intlCurrency = require('intl-currency'); class Cart { constructor() { this.data = {}; this.data.items = []; this.data.totals = 0; this.data.currency = ''; this.data.locale = ''; this.data.formattedTotals = ''; } getAllItems(request) { let cartData = { cart: this.data.items, totals: this.data.totals, currency: this.data.currency, locale: this.data.locale, formattedTotals: this.data.formattedTotals, } return cartData; } inCart(productID = 0) { let found = false; this.data.items.forEach(item => { let itemId = JSON.stringify(item._id); let productId = JSON.stringify(productID); if(itemId === productId) { found = true; } }); return found; } calculateTotals() { this.data.totals = 0; this.data.items.forEach(item => { let price = item.product_price; let qty = item.product_quantity; let amount = price * qty; this.data.totals += amount; }); this.setFormattedTotals(); } setFormattedTotals() { let totals = this.data.totals; this.data.formattedTotals = intlCurrency(totals, { currency: this.data.currency, locales: this.data.locale }); } addToCart(product = null, quantity = 1) { if(!this.inCart(product._id)) { let prod = { _id: product._id, product_name: product.product_name, product_description: product.product_description, product_price: product.product_price, product_category: product.product_category, product_ean: product.product_ean, product_quantity: quantity, product_image: product.product_image, product_currency: product.product_currency, product_sku: product.product_sku, product_formattedPrice: config.formattedPrice(product).formattedPrice, product_formattedTotals: config.formattedPrice(product).formattedTotals }; this.data.items.push(prod); this.data.currency = prod.product_currency; this.data.locale = config.formattedPrice(prod).locale; this.calculateTotals(); } else { let cartItem = this.data.items.filter((cartItem) => JSON.stringify(cartItem._id) === JSON.stringify(product._id))[0]; if(cartItem.product_quantity < product.product_quantity) { cartItem.product_quantity++; cartItem.product_formattedPrice = config.formattedPrice(product).formattedPrice; cartItem.product_formattedTotals = config.formattedPrice(product, cartItem.product_quantity).formattedTotals; this.data.items.filter((cartItem) => JSON.stringify(cartItem._id) !== JSON.stringify(product._id)).push(cartItem); this.calculateTotals(); } } } saveCart(request) { if(request.session) { request.session.cart = this.data; } } removeFromCart(product, qty = 1, req) { let cartItem = this.data.items.filter((item) => JSON.stringify(product._id) === JSON.stringify(item._id))[0]; let cartItems = this.data.items.length; if(!cartItem) return; if(cartItem) { if(cartItem && cartItem.product_quantity > 1) { cartItem.product_quantity--; cartItem.product_formattedTotals = config.formattedPrice(product, cartItem.product_quantity).formattedTotals; this.calculateTotals(); } else { this.data.items = this.data.items.filter((item) => JSON.stringify(item._id) !== JSON.stringify(product._id)); this.calculateTotals(); } } if(!cartItems) { this.emptyCart(req); } } emptyCart(request) { this.data.items = []; this.data.totals = 0; this.data.formattedTotals = ''; this.data.currency = ''; this.data.locale = ''; if(request.session) { request.session.cart.items= []; request.session.cart.totals = 0; request.session.cart.formattedTotals = ''; request.session.cart.currency = ''; request.session.cart.locale = ''; } } isEmpty(request) { if(!request.session) { return true; } else { return false; } } } module.exports = new Cart();
EsupPortail/esup-ecandidat
src/main/java/fr/univlorraine/ecandidat/controllers/IndividuController.java
/** * ESUP-Portail eCandidat - Copyright (c) 2016 ESUP-Portail consortium * * * 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 fr.univlorraine.ecandidat.controllers; import java.util.List; import java.util.Set; import javax.annotation.Resource; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import com.vaadin.ui.UI; import fr.univlorraine.ecandidat.entities.ecandidat.Gestionnaire; import fr.univlorraine.ecandidat.entities.ecandidat.Individu; import fr.univlorraine.ecandidat.entities.ecandidat.SiScolUtilisateur; import fr.univlorraine.ecandidat.repositories.IndividuRepository; import fr.univlorraine.ecandidat.repositories.SiScolUtilisateurRepository; import fr.univlorraine.ecandidat.utils.CustomException; /** Gestion des individus * * @author <NAME> */ @Component public class IndividuController { /* Injections */ @Resource private transient ApplicationContext applicationContext; @Resource private transient LockController lockController; @Resource private transient IndividuRepository individuRepository; @Resource private transient SiScolUtilisateurRepository siScolUtilisateurRepository; /** Enregistre un individu * * @param individu * @return l'individu */ public Individu saveIndividu(final Individu individu) { Individu ind = individuRepository.findOne(individu.getLoginInd()); if (ind == null) { return individuRepository.save(individu); } else { ind.setLibelleInd(individu.getLibelleInd()); ind.setMailInd(individu.getMailInd()); return individuRepository.save(ind); } } /** @param user * @return le libellé de l'individu */ public String getLibIndividu(final String user) { if (user == null) { return ""; } else { Individu ind = getIndividu(user); if (ind != null && ind.getLibelleInd() != null) { return ind.getLibelleInd(); } } return user; } /** Retourne un individu * * @param login * @return l'individu */ public Individu getIndividu(final String login) { return individuRepository.findOne(login); } /** Valide un bean d'individu * * @param ind * @throws CustomException */ public void validateIndividuBean(final Individu ind) throws CustomException { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Individu>> constraintViolations = validator.validate(ind); if (constraintViolations != null && constraintViolations.size() > 0) { String erreur = ""; for (ConstraintViolation<?> violation : constraintViolations) { erreur += (" *** " + violation.getPropertyPath().toString() + " : " + violation.getMessage()); } throw new CustomException(applicationContext.getMessage("droitprofil.individu.error", null, UI.getCurrent().getLocale()) + " : " + erreur); } } /** Supprime un individu * * @param individu */ public void deleteIndividu(final Individu individu) { individuRepository.delete(individu); } /** @param gest * @param user * @return le code CGE d'un gestionnaire */ public String getCodCgeForGestionnaire(final Gestionnaire gest, final String user) { if (gest != null && user != null) { if (gest.getSiScolCentreGestion() != null) { return gest.getSiScolCentreGestion().getCodCge(); } if (gest.getLoginApoGest() != null && !gest.getLoginApoGest().equals("")) { return getCodCgeUserByLogin(gest.getLoginApoGest()); } return getCodCgeUserByLogin(user); } return null; } /** Renvoi le cod cge pour un user * * @param userName * @return le cod cge pour un user */ private String getCodCgeUserByLogin(final String userName) { List<SiScolUtilisateur> listeUser = siScolUtilisateurRepository.findByCodUtiAndTemEnSveUtiAndSiScolCentreGestionIsNotNull(userName, true); if (listeUser.size() > 0) { SiScolUtilisateur user = listeUser.get(0); if (user != null && user.getSiScolCentreGestion() != null) { return user.getSiScolCentreGestion().getCodCge(); } } return null; } }
muddessir/framework
machine/qemu/sources/u-boot/cmd/mdio.c
// SPDX-License-Identifier: GPL-2.0+ /* * (C) Copyright 2011 Freescale Semiconductor, Inc * <NAME> */ /* * MDIO Commands */ #include <common.h> #include <command.h> #include <dm.h> #include <miiphy.h> #include <phy.h> static char last_op[2]; static uint last_data; static uint last_addr_lo; static uint last_addr_hi; static uint last_devad_lo; static uint last_devad_hi; static uint last_reg_lo; static uint last_reg_hi; static int extract_range(char *input, int *plo, int *phi) { char *end; *plo = simple_strtol(input, &end, 16); if (end == input) return -1; if ((*end == '-') && *(++end)) *phi = simple_strtol(end, NULL, 16); else if (*end == '\0') *phi = *plo; else return -1; return 0; } static int mdio_write_ranges(struct mii_dev *bus, int addrlo, int addrhi, int devadlo, int devadhi, int reglo, int reghi, unsigned short data, int extended) { struct phy_device *phydev; int addr, devad, reg; int err = 0; for (addr = addrlo; addr <= addrhi; addr++) { phydev = bus->phymap[addr]; for (devad = devadlo; devad <= devadhi; devad++) { for (reg = reglo; reg <= reghi; reg++) { if (!phydev) err = bus->write(bus, addr, devad, reg, data); else if (!extended) err = phy_write_mmd(phydev, devad, reg, data); else err = phydev->drv->writeext(phydev, addr, devad, reg, data); if (err) goto err_out; } } } err_out: return err; } static int mdio_read_ranges(struct mii_dev *bus, int addrlo, int addrhi, int devadlo, int devadhi, int reglo, int reghi, int extended) { int addr, devad, reg; struct phy_device *phydev; printf("Reading from bus %s\n", bus->name); for (addr = addrlo; addr <= addrhi; addr++) { phydev = bus->phymap[addr]; printf("PHY at address %x:\n", addr); for (devad = devadlo; devad <= devadhi; devad++) { for (reg = reglo; reg <= reghi; reg++) { int val; if (!phydev) val = bus->read(bus, addr, devad, reg); else if (!extended) val = phy_read_mmd(phydev, devad, reg); else val = phydev->drv->readext(phydev, addr, devad, reg); if (val < 0) { printf("Error\n"); return val; } if (devad >= 0) printf("%d.", devad); printf("%d - 0x%x\n", reg, val & 0xffff); } } } return 0; } /* The register will be in the form [a[-b].]x[-y] */ static int extract_reg_range(char *input, int *devadlo, int *devadhi, int *reglo, int *reghi) { char *regstr; /* use strrchr to find the last string after a '.' */ regstr = strrchr(input, '.'); /* If it exists, extract the devad(s) */ if (regstr) { char devadstr[32]; strncpy(devadstr, input, regstr - input); devadstr[regstr - input] = '\0'; if (extract_range(devadstr, devadlo, devadhi)) return -1; regstr++; } else { /* Otherwise, we have no devad, and we just got regs */ *devadlo = *devadhi = MDIO_DEVAD_NONE; regstr = input; } return extract_range(regstr, reglo, reghi); } static int extract_phy_range(char *const argv[], int argc, struct mii_dev **bus, struct phy_device **phydev, int *addrlo, int *addrhi) { struct phy_device *dev = *phydev; if ((argc < 1) || (argc > 2)) return -1; /* If there are two arguments, it's busname addr */ if (argc == 2) { *bus = miiphy_get_dev_by_name(argv[0]); if (!*bus) return -1; return extract_range(argv[1], addrlo, addrhi); } /* It must be one argument, here */ /* * This argument can be one of two things: * 1) Ethernet device name * 2) Just an address (use the previously-used bus) * * We check all buses for a PHY which is connected to an ethernet * device by the given name. If none are found, we call * extract_range() on the string, and see if it's an address range. */ dev = mdio_phydev_for_ethname(argv[0]); if (dev) { *addrlo = *addrhi = dev->addr; *bus = dev->bus; return 0; } /* It's an address or nothing useful */ return extract_range(argv[0], addrlo, addrhi); } /* ---------------------------------------------------------------- */ static int do_mdio(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]) { char op[2]; int addrlo, addrhi, reglo, reghi, devadlo, devadhi; unsigned short data; int pos = argc - 1; struct mii_dev *bus; struct phy_device *phydev = NULL; int extended = 0; if (argc < 2) return CMD_RET_USAGE; #ifdef CONFIG_DM_MDIO /* probe DM MII device before any operation so they are all accesible */ dm_mdio_probe_devices(); #endif /* * We use the last specified parameters, unless new ones are * entered. */ op[0] = argv[1][0]; addrlo = last_addr_lo; addrhi = last_addr_hi; devadlo = last_devad_lo; devadhi = last_devad_hi; reglo = last_reg_lo; reghi = last_reg_hi; data = last_data; bus = mdio_get_current_dev(); if (flag & CMD_FLAG_REPEAT) op[0] = last_op[0]; if (strlen(argv[1]) > 1) { op[1] = argv[1][1]; if (op[1] == 'x') { phydev = mdio_phydev_for_ethname(argv[2]); if (phydev) { addrlo = phydev->addr; addrhi = addrlo; bus = phydev->bus; extended = 1; } else { return CMD_RET_FAILURE; } if (!phydev->drv || (!phydev->drv->writeext && (op[0] == 'w')) || (!phydev->drv->readext && (op[0] == 'r'))) { puts("PHY does not have extended functions\n"); return CMD_RET_FAILURE; } } } switch (op[0]) { case 'w': if (pos > 1) data = simple_strtoul(argv[pos--], NULL, 16); /* Intentional fall-through - Get reg for read and write */ case 'r': if (pos > 1) if (extract_reg_range(argv[pos--], &devadlo, &devadhi, &reglo, &reghi)) return CMD_RET_FAILURE; /* Intentional fall-through - Get phy for all commands */ default: if (pos > 1) if (extract_phy_range(&argv[2], pos - 1, &bus, &phydev, &addrlo, &addrhi)) return CMD_RET_FAILURE; break; } if (!bus) { puts("No MDIO bus found\n"); return CMD_RET_FAILURE; } if (op[0] == 'l') { mdio_list_devices(); return 0; } /* Save the chosen bus */ miiphy_set_current_dev(bus->name); switch (op[0]) { case 'w': mdio_write_ranges(bus, addrlo, addrhi, devadlo, devadhi, reglo, reghi, data, extended); break; case 'r': mdio_read_ranges(bus, addrlo, addrhi, devadlo, devadhi, reglo, reghi, extended); break; } /* * Save the parameters for repeats. */ last_op[0] = op[0]; last_addr_lo = addrlo; last_addr_hi = addrhi; last_devad_lo = devadlo; last_devad_hi = devadhi; last_reg_lo = reglo; last_reg_hi = reghi; last_data = data; return 0; } /***************************************************/ U_BOOT_CMD( mdio, 6, 1, do_mdio, "MDIO utility commands", "list - List MDIO buses\n" "mdio read <phydev> [<devad>.]<reg> - " "read PHY's register at <devad>.<reg>\n" "mdio write <phydev> [<devad>.]<reg> <data> - " "write PHY's register at <devad>.<reg>\n" "mdio rx <phydev> [<devad>.]<reg> - " "read PHY's extended register at <devad>.<reg>\n" "mdio wx <phydev> [<devad>.]<reg> <data> - " "write PHY's extended register at <devad>.<reg>\n" "<phydev> may be:\n" " <busname> <addr>\n" " <addr>\n" " <eth name>\n" "<addr> <devad>, and <reg> may be ranges, e.g. 1-5.4-0x1f.\n" );
windystrife/UnrealEngine_NVIDIAGameWork
Engine/Plugins/Runtime/AppleARKit/Source/AppleARKit/Private/AppleARKitModule.h
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "ModuleManager.h" #include "IHeadMountedDisplayModule.h" #include "Features/IModularFeature.h" #include "AppleARKitSystem.h" #include "AppleARKitModule.h" #include "ARHitTestingSupport.h" class APPLEARKIT_API FAppleARKitModule : public IHeadMountedDisplayModule { public: virtual TSharedPtr<class IXRTrackingSystem, ESPMode::ThreadSafe> CreateTrackingSystem() override; static TSharedPtr<class FAppleARKitSystem, ESPMode::ThreadSafe> GetARKitSystem(); FString GetModuleKeyName() const override; virtual void StartupModule() override; virtual void ShutdownModule() override; }; DECLARE_LOG_CATEGORY_EXTERN(LogAppleARKit, Log, All);
danieldkm/sis-unifil
Daniel/Laboratorio/terceiroBim/dia2907/ConsultaDiamante.java
package dia2907; public class ConsultaDiamante extends Consulta { public ConsultaDiamante() { super(); } @Override public double getValorConsulta() { double desconto = super.getValorConsulta() * 0.4; return super.getValorConsulta() - desconto; } }
brunolauze/MonoNative
MonoNative/mscorlib/System/Threading/mscorlib_System_Threading_NativeOverlapped.h
#ifndef __MONO_NATIVE_MSCORLIB_SYSTEM_THREADING_NATIVEOVERLAPPED_H #define __MONO_NATIVE_MSCORLIB_SYSTEM_THREADING_NATIVEOVERLAPPED_H #include <mscorlib/System/mscorlib_System_ValueType.h> #include <mscorlib/System/mscorlib_System_Object.h> namespace mscorlib { namespace System { class String; class Type; } } namespace mscorlib { namespace System { namespace Threading { class NativeOverlapped : public mscorlib::System::ValueType { public: NativeOverlapped(mscorlib::NativeTypeInfo *nativeTypeInfo) : mscorlib::System::ValueType(nativeTypeInfo) { }; NativeOverlapped(MonoObject *nativeObject) : mscorlib::System::ValueType(nativeObject) { }; ~NativeOverlapped() { }; NativeOverlapped & operator=(NativeOverlapped &value) { __native_object__ = value.GetNativeObject(); return value; }; bool operator==(NativeOverlapped &value) { return mscorlib::System::Object::Equals(value); }; operator MonoObject*() { return __native_object__; }; MonoObject* operator=(MonoObject* value) { return __native_object__ = value; }; virtual MonoObject* GetNativeObject() override { return __native_object__; }; //Public Fields __declspec(property(get=get_InternalLow, put=set_InternalLow)) mscorlib::System::IntPtr InternalLow; __declspec(property(get=get_InternalHigh, put=set_InternalHigh)) mscorlib::System::IntPtr InternalHigh; __declspec(property(get=get_OffsetLow, put=set_OffsetLow)) mscorlib::System::Int32 OffsetLow; __declspec(property(get=get_OffsetHigh, put=set_OffsetHigh)) mscorlib::System::Int32 OffsetHigh; __declspec(property(get=get_EventHandle, put=set_EventHandle)) mscorlib::System::IntPtr EventHandle; // Get/Set:InternalLow mscorlib::System::IntPtr get_InternalLow() const; void set_InternalLow(mscorlib::System::IntPtr value); // Get/Set:InternalHigh mscorlib::System::IntPtr get_InternalHigh() const; void set_InternalHigh(mscorlib::System::IntPtr value); // Get/Set:OffsetLow mscorlib::System::Int32 get_OffsetLow() const; void set_OffsetLow(mscorlib::System::Int32 value); // Get/Set:OffsetHigh mscorlib::System::Int32 get_OffsetHigh() const; void set_OffsetHigh(mscorlib::System::Int32 value); // Get/Set:EventHandle mscorlib::System::IntPtr get_EventHandle() const; void set_EventHandle(mscorlib::System::IntPtr value); protected: private: }; } } } #endif
dominicSchiller/ScrabbleFactory
Client/core/src/de/thb/paf/scrabblefactory/models/components/physics/PhysicsType.java
<gh_stars>0 package de.thb.paf.scrabblefactory.models.components.physics; /** * Enumeration of all applicable physic types. * * @author <NAME> - Technische Hochschule Brandenburg * @version 1.0 * @since 1.0 */ public enum PhysicsType { WORLD, RIGID_BODY }
powernic/bounced
src/reducers/index.js
<gh_stars>0 import {combineReducers} from 'redux' import {playerReducer} from './player' import {playgroundReducer} from './playground' import {boxesReducer} from "./boxes"; export const rootReducer = combineReducers({ player: playerReducer, playground: playgroundReducer, boxes: boxesReducer, });
oicr-gsi/vidarr
vidarr-pluginapi/src/main/java/ca/on/oicr/gsi/vidarr/api/WorkflowDeclaration.java
<filename>vidarr-pluginapi/src/main/java/ca/on/oicr/gsi/vidarr/api/WorkflowDeclaration.java package ca.on.oicr.gsi.vidarr.api; import ca.on.oicr.gsi.vidarr.BasicType; import ca.on.oicr.gsi.vidarr.InputType; import ca.on.oicr.gsi.vidarr.OutputType; import ca.on.oicr.gsi.vidarr.WorkflowLanguage; import java.util.Map; public final class WorkflowDeclaration { private Map<String, BasicType> labels; private WorkflowLanguage language; private Map<String, OutputType> metadata; private String name; private Map<String, InputType> parameters; private String version; public Map<String, BasicType> getLabels() { return labels; } public WorkflowLanguage getLanguage() { return language; } public Map<String, OutputType> getMetadata() { return metadata; } public String getName() { return name; } public Map<String, InputType> getParameters() { return parameters; } public String getVersion() { return version; } public void setLabels(Map<String, BasicType> labels) { this.labels = labels; } public void setLanguage(WorkflowLanguage language) { this.language = language; } public void setMetadata(Map<String, OutputType> metadata) { this.metadata = metadata; } public void setName(String name) { this.name = name; } public void setParameters(Map<String, InputType> parameters) { this.parameters = parameters; } public void setVersion(String version) { this.version = version; } }
vadim8kiselev/social-matchmaker
src/main/java/com/kiselev/matchmaker/view/serialize/implementation/csv/CSVSerializeView.java
package com.kiselev.matchmaker.view.serialize.implementation.csv; import com.google.common.collect.Lists; import com.kiselev.matchmaker.api.model.Entity; import com.kiselev.matchmaker.view.serialize.SerializeView; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; public class CSVSerializeView implements SerializeView { private static final String PATH = "export/csv/"; private static final String EXTENSION = ".csv"; @Override public <Pojo extends Entity> void serialize(List<Pojo> entities, String filePath) { validateEntities(entities); try { writeCSVToFile(entities, filePath); } catch (IOException firstException) { try { writeCSVToNewFile(entities); } catch (IOException secondException) { secondException.printStackTrace(); } } } @Override public <Pojo extends Entity> File serialize(List<Pojo> entities) { validateEntities(entities); try { return writeCSVToNewFile(entities); } catch (IOException secondException) { secondException.printStackTrace(); } return null; } private <Pojo extends Entity> File writeCSVToFile(List<Pojo> entities, String filePath) throws IOException { try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(filePath)); CSVPrinter csvPrinter = new CSVPrinter(writer, composeHeader(entities))) { List<List<String>> records = entities.stream() .map(this::composeRecord) .collect(Collectors.toList()); for (List<String> record : records) { csvPrinter.printRecord(record); } csvPrinter.flush(); } return new File(filePath); } private <Pojo extends Entity> File writeCSVToNewFile(List<Pojo> entities) throws IOException { Path path = Paths.get(PATH); if (Files.notExists(path)) { Files.createDirectories(path); } return writeCSVToFile(entities, PATH + UUID.randomUUID().toString() + EXTENSION); } private <Pojo extends Entity> CSVFormat composeHeader(List<Pojo> entities) { CSVFormat csvFormat = CSVFormat.DEFAULT; if (CollectionUtils.isNotEmpty(entities)) { Class<? extends Entity> clazz = entities.iterator().next().getClass(); String[] fieldsNames = Arrays.stream(clazz.getDeclaredFields()) .map(Field::getName) .collect(Collectors.toList()) .toArray(new String[]{}); csvFormat = csvFormat.withHeader(fieldsNames); } return csvFormat; } private <Pojo extends Entity> List<String> composeRecord(Pojo entity) { List<String> record = Lists.newArrayList(); for (Field field : entity.getClass().getDeclaredFields()) { field.setAccessible(true); try { record.add(field.get(entity).toString()); } catch (IllegalAccessException | NullPointerException e) { e.printStackTrace(); } } return record; } private <Pojo extends Entity> void validateEntities(List<Pojo> entities) { Class<? extends Entity> firstPojoClass = entities.iterator().next().getClass(); boolean allMatch = entities.stream() .map(Object::getClass) .allMatch(clazz -> clazz.equals(firstPojoClass)); if (!allMatch) { throw new RuntimeException("All entities should be same type for csv serialization!"); } } }
HadleyLab/covidimaging.admin
app/components/MoreInfo/index.js
import React from 'react' import PropTypes from 'prop-types' import { withStyles } from '@material-ui/core/styles' import trans from 'trans' import Button from '@material-ui/core/Button'; import Close from '../Img/ico-Close.svg' import colors from '../../style/colors' import Loading from '../Loading'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import ExpansionPanel from '@material-ui/core/ExpansionPanel'; import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary'; import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails'; import ListItem from '@material-ui/core/ListItem'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import Typography from '@material-ui/core/Typography' import List from '@material-ui/core/List'; import Divider from '@material-ui/core/Divider'; const styles = { modalBack: { backgroundColor: 'rgba(223, 223, 238, 0.9)', backdropFilter: 'blur(2.3px)', width: '100%', height: '100%', position: 'absolute', top: 0, zIndex: '10', display: 'flex', flexFlow: 'column', alignItems: 'center', justifyContent: 'space-between', }, title: { textAlign: 'center', fontWeight: '300', fontSize: '2em', marginTop: '0.5em', }, contentCover: { maxWidth: '100%', height: 900, backgroundColor: '#fff', overflow: 'auto', width: 800, }, button: { width: '118px', height: '54px', margin: '1em auto', textTransform: 'none', color: colors.white, fontSize: '1em', background: colors.buttonBlue, '&:hover':{ background: colors.activeMenu, }, '&:active':{ background: colors.activeMenu, }, }, topBar: { display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: '2em', width: '100%', }, bottomBar: { display: 'flex', flexFlow: 'row', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: '1em', width: '100%', }, topCenter: { textAlign: 'center', flex: 1, }, iconButton:{ width: '40px', height: '40px', background: 'rgba(255, 255, 255, 0.7)', boxShadow: '0 0 10px 0 rgba(21, 21, 49, 0.16)', '&:hover':{ background: 'rgba(255, 255, 255, 0.9)', }, '&:active':{ background: 'rgba(255, 255, 255, 0.9)', boxShadow: '0 0 10px 0 rgba(21, 21, 49, 0.25)', }, }, close: { width: '8px', height: '8px', backgroundImage: `url(${Close})`, backgroundPosition: 'center', }, flexedRow: { display: 'flex', flexFlow: 'row', alignItems: 'center', flex: 1, }, flexedColumn: { display: 'flex', flexFlow: 'column', justifyContent: 'center', alignItems: 'center', height: '100%', }, flexedRowRight: { display: 'flex', flexFlow: 'row', alignItems: 'flex-start', justifyContent: 'flex-end', flex: 1, }, panelDetails:{ backgroundColor: '#dddddd' }, paper:{ width: '100%' }, pDicoms:{ color: 'rgba(35, 35, 77, 0.6)', fontSize: 14, textAlign: 'center', }, linkButton: { background: 'transparent', textTransform: 'none', color: '#6d6d9b', fontSize: 14, boxShadow: 'none', '&:hover':{ background: 'transparent', boxShadow: 'none', color: colors.activeMenu, }, '&:active':{ background: 'transparent', boxShadow: 'none', color: colors.activeMenu, }, cover:{ margin: '2em', padding: 15, }, }, dicomName:{ color:'rgba(35, 35, 77, 0.6)', fontSize: 14, fontWeight: 100, }, TableRow:{ height: 10 } } const CustomTableCell = withStyles({ body: { color: colors.fontTable, fontWeight: '100', fontSize: 14, textAlign: 'center', padding: '0 24px', }, })(TableCell); class MoreInfo extends React.Component { render () { const {classes, onClose, study} = this.props; console.log(study) let body = (<Loading/>) if (study && study.length > 0) { body = study.map(s => ( s && <ListItem className={classes.listItem}> <ExpansionPanel className={classes.paper}> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon className={classes.iconButton}/>}> <Table className={classes.table}> <TableBody> <TableRow className={classes.row} key={s._id}> <CustomTableCell className={classes.nameRow}> <Typography>{'Study ID: '}{s.studyID}</Typography> </CustomTableCell> <CustomTableCell className={classes.nameRow}> <Typography> {s.patientId} {s.patientsName}</Typography> </CustomTableCell> </TableRow> </TableBody> </Table> </ExpansionPanelSummary> <ExpansionPanelDetails className={classes.panelDetails}> <List> <ListItem className={classes.listItem}> <Paper > <Table className={classes.table}> <TableBody> <TableRow key={s._id} className={classes.TableRow}> <TableCell>{'Study ID'}</TableCell> <TableCell>{s.studyID}</TableCell> </TableRow> <TableRow key={'files'} className={classes.TableRow}> <TableCell>{'Files to study'}</TableCell> <TableCell>{s.files.length}</TableCell> </TableRow> {s.more && _.toArray(s.more).map(n => ( n && <TableRow key={n.info} className={classes.TableRow}> <TableCell>{n.info}</TableCell> <TableCell>{(n.value) ? (n.value) : "-"}</TableCell> </TableRow> ) )} </TableBody> </Table> </Paper> </ListItem> <Divider/> </List> </ExpansionPanelDetails> </ExpansionPanel> </ListItem> ) ) } // const more = _.toArray(study.more); return ( <div onClose={onClose} className={classes.modalBack} > <div className={classes.topBar}> <Button variant="fab" className={classes.iconButton} onClick={onClose}> <div className={classes.close}/> </Button> </div> <div className={classes.contentCover}> {body} </div> <div className={classes.bottomBar}> <Button variant="contained" className={classes.linkButton} onClick={onClose}> {trans('admin.panel.DICOMs.assign.dialog.cancel')} </Button> </div> </div> ) } } MoreInfo.propTypes = { classes: PropTypes.object.isRequired, } export default (withStyles(styles))(MoreInfo)
huandrew99/LeetCode
CS-Notes/algorithm/dynamic-programming/House Robber (Medium).py
<reponame>huandrew99/LeetCode """ LC 198 You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. Example 1: Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. Example 2: Input: nums = [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. """ class Solution: def rob(self, nums) -> int: r, nr = 0, 0 # max value for robbing/not robbing for n in nums: r, nr = nr + n, max(r, nr) return max(r, nr) """ Time O(N) Space O(1) """
wufan8387/smart-orm
src/main/java/org/smart/orm/operations/type/JoinNode.java
<reponame>wufan8387/smart-orm package org.smart.orm.operations.type; import org.smart.orm.Model; import org.smart.orm.data.LogicalType; import org.smart.orm.data.NodeType; import org.smart.orm.functions.Func; import org.smart.orm.functions.PropertyGetter; import org.smart.orm.operations.AbstractSqlNode; import org.smart.orm.operations.Op; import org.smart.orm.operations.Statement; import org.smart.orm.reflect.LambdaParser; import org.smart.orm.reflect.PropertyInfo; import java.lang.reflect.Field; public class JoinNode<T extends Statement, L extends Model<L>, R extends Model<R>> extends AbstractSqlNode<T, JoinNode<T, L, R>> { private RelationNode<T, L> leftRel; private RelationNode<T, R> rightRel; private PropertyGetter<L> leftAttr; private PropertyGetter<R> rightAttr; private PropertyInfo leftProp; private PropertyInfo rightProp; private Func<String> op; private JoinNode<T, ?, ?> child; private LogicalType logicalType = null; public JoinNode(PropertyGetter<L> leftAttr , Func<String> op , PropertyGetter<R> rightAttr) { this.leftAttr = leftAttr; this.rightAttr = rightAttr; this.op = op; } public JoinNode(PropertyGetter<L> leftAttr , Func<String> op , PropertyGetter<R> rightAttr , JoinNode<T, ?, ?> parent) { this(leftAttr, op, rightAttr); if (parent != null) parent.child = this; } public JoinNode(RelationNode<T, L> leftRel , PropertyGetter<L> leftAttr , Func<String> op , RelationNode<T, R> rightRel , PropertyGetter<R> rightAttr) { this.leftRel = leftRel; this.rightRel = rightRel; this.leftAttr = leftAttr; this.rightAttr = rightAttr; this.op = op; } public JoinNode(RelationNode<T, L> leftRel , PropertyGetter<L> leftAttr , Func<String> op , RelationNode<T, R> rightRel , PropertyGetter<R> rightAttr , JoinNode<T, ?, ?> parent) { this(leftRel, leftAttr, op, rightRel, rightAttr); if (parent != null) parent.child = this; } public <NL extends Model<NL>, NR extends Model<NR>> JoinNode<T, NL, NR> and(RelationNode<T, NL> leftRel , PropertyGetter<NL> leftAttr , Func<String> op , RelationNode<T, NR> rightRel , PropertyGetter<NR> rightAttr) { return new JoinNode<>(leftRel, leftAttr, op, rightRel, rightAttr, this) .setLogicalType(LogicalType.AND) .attach(statement()); } public <NL extends Model<NL>, NR extends Model<NR>> JoinNode<T, NL, NR> and(PropertyGetter<NL> leftAttr , Func<String> op , PropertyGetter<NR> rightAttr) { return new JoinNode<>(leftAttr, op, rightAttr, this) .setLogicalType(LogicalType.AND) .attach(statement()); } public <NL extends Model<NL>, NR extends Model<NR>> JoinNode<T, NL, NR> or(RelationNode<T, NL> leftRel , PropertyGetter<NL> leftAttr , Func<String> op , RelationNode<T, NR> rightRel , PropertyGetter<NR> rightAttr) { return new JoinNode<>(leftRel, leftAttr, op, rightRel, rightAttr, this) .setLogicalType(LogicalType.OR) .attach(statement()); } public <NL extends Model<NL>, NR extends Model<NR>> JoinNode<T, NL, NR> or(PropertyGetter<NL> leftAttr , Func<String> op , PropertyGetter<NR> rightAttr) { return new JoinNode<>(leftAttr, op, rightAttr, this) .setLogicalType(LogicalType.OR) .attach(statement()); } public LogicalType getLogicalType() { return logicalType; } public JoinNode<T, L, R> setLogicalType(LogicalType logicalType) { this.logicalType = logicalType; return this; } @Override public JoinNode<T, L, R> attach(T statement) { Field leftField = LambdaParser.getGetter(leftAttr); Class<?> leftCls = leftField.getDeclaringClass(); if (leftRel == null) { leftRel = statement.findFirst(NodeType.RELATION , t -> t.getName().equals(Model.getMetaManager().findEntityInfo(leftCls).getTableName())); } leftProp = Model .getMetaManager() .findEntityInfo(leftCls) .getProp(leftField.getName()); Field rightField = LambdaParser.getGetter(rightAttr); Class<?> rightCls = rightField.getDeclaringClass(); if (rightRel == null) { rightRel = statement.findFirst(NodeType.RELATION , t -> t.getName().equals(Model.getMetaManager().findEntityInfo(rightCls).getTableName())); } rightProp = Model .getMetaManager() .findEntityInfo(rightCls) .getProp(rightField.getName()); return super.attach(statement); } @Override public int getType() { return NodeType.CONDITION_JOIN; } @Override public void toString(StringBuilder sb) { sb.append(Op.LOGICAL.apply(logicalType)); sb.append(op.apply(leftRel.getAlias() , leftProp.getColumnName() , rightRel.getAlias() , rightProp.getColumnName())); if (child != null) child.toString(sb); } }
SnaxFoundation/snax-browser-extension
src/components/Alerts/Alert.js
<reponame>SnaxFoundation/snax-browser-extension<gh_stars>1-10 import styled from 'styled-components'; import PropTypes from 'prop-types'; import constants from '../../styles/style-constants'; const propTypes = { colorScheme: PropTypes.oneOf(['success', 'error', 'default']), }; const defaultProps = { colorScheme: 'default', }; const colorMap = { default: { bgColor: constants.color.info, textColor: '#fff', }, success: { bgColor: constants.color.success, textColor: '#fff', }, error: { bgColor: constants.color.error, textColor: '#fff', }, }; const colorScheme = ({ colorScheme }) => ` background-color: ${colorMap[colorScheme].bgColor}; color: ${colorMap[colorScheme].textColor}; `; export const Alert = styled.div` width: 100%; text-align: center; padding: 0.5em; ${colorScheme}; `; Alert.propTypes = propTypes; Alert.defaultProps = defaultProps;
Flickswitch/vpp
vendor/github.com/ligato/cn-infra/utils/once/return_error.go
// Copyright (c) 2018 Cisco and/or its affiliates. // // 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 once import "sync" // ReturnError is a wrapper around sync.Once that properly handles: // func() error // instead of just // func() type ReturnError struct { once sync.Once err error } // Do provides the same functionality as sync.Once.Do(func()) but for // func() error func (owe *ReturnError) Do(f func() error) error { owe.once.Do(func() { owe.err = f() }) return owe.err }
thelvis4/buck
src-gen/com/facebook/buck/remoteexecution/proto/RESessionIDOrBuilder.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: src/com/facebook/buck/remoteexecution/proto/metadata.proto package com.facebook.buck.remoteexecution.proto; @javax.annotation.Generated(value="protoc", comments="annotations:RESessionIDOrBuilder.java.pb.meta") public interface RESessionIDOrBuilder extends // @@protoc_insertion_point(interface_extends:facebook.remote_execution.RESessionID) com.google.protobuf.MessageOrBuilder { /** * <code>string id = 1;</code> */ java.lang.String getId(); /** * <code>string id = 1;</code> */ com.google.protobuf.ByteString getIdBytes(); }
threefoldtech/threefold-forums
app/assets/javascripts/discourse/models/nav-item.js.es6
import discourseComputed from "discourse-common/utils/decorators"; import { emojiUnescape } from "discourse/lib/text"; import Category from "discourse/models/category"; import EmberObject from "@ember/object"; import { reads } from "@ember/object/computed"; import deprecated from "discourse-common/lib/deprecated"; import Site from "discourse/models/site"; import User from "discourse/models/user"; const NavItem = EmberObject.extend({ @discourseComputed("name") title(name) { const extra = {}; return I18n.t("filters." + name.replace("/", ".") + ".help", extra); }, @discourseComputed("name", "count") displayName(name, count) { count = count || 0; if ( name === "latest" && (!Site.currentProp("mobileView") || this.tagId !== undefined) ) { count = 0; } let extra = { count: count }; const titleKey = count === 0 ? ".title" : ".title_with_count"; return emojiUnescape( I18n.t(`filters.${name.replace("/", ".") + titleKey}`, extra) ); }, @discourseComputed("filterType", "category", "noSubcategories", "tagId") href(filterType, category, noSubcategories, tagId) { let customHref = null; NavItem.customNavItemHrefs.forEach(function(cb) { customHref = cb.call(this, this); if (customHref) { return false; } }, this); if (customHref) { return customHref; } const context = { category, noSubcategories, tagId }; return NavItem.pathFor(filterType, context); }, filterType: reads("name"), @discourseComputed("name", "category", "noSubcategories") filterMode(name, category, noSubcategories) { let mode = ""; if (category) { mode += "c/"; mode += Category.slugFor(category); if (noSubcategories) { mode += "/none"; } mode += "/l/"; } return mode + name.replace(" ", "-"); }, @discourseComputed("name", "category", "topicTrackingState.messageCount") count(name, category) { const state = this.topicTrackingState; if (state) { return state.lookupCount(name, category); } } }); const ExtraNavItem = NavItem.extend({ href: discourseComputed("href", { get() { if (this._href) { return this._href; } return this.href; }, set(key, value) { return (this._href = value); } }), count: 0, customFilter: null }); NavItem.reopenClass({ extraArgsCallbacks: [], customNavItemHrefs: [], extraNavItemDescriptors: [], pathFor(filterType, context) { let path = Discourse.getURL(""); let includesCategoryContext = false; let includesTagContext = false; if (filterType === "categories") { path += "/categories"; return path; } if (context.tagId && Site.currentProp("filters").includes(filterType)) { includesTagContext = true; path += "/tags"; } if (context.category) { includesCategoryContext = true; path += `/c/${Category.slugFor(context.category)}/${context.category.id}`; if (context.noSubcategories) { path += "/none"; } } if (includesTagContext) { path += `/${context.tagId}`; } if (includesTagContext || includesCategoryContext) { path += "/l"; } path += `/${filterType}`; // In the case of top, the nav item doesn't include a period because the // period has its own selector just below return path; }, // Create a nav item given a filterType. It returns null if there is not // valid nav item. The name is a historical artifact. fromText(filterType, opts) { const anonymous = !User.current(); opts = opts || {}; if (anonymous) { const topMenuItems = Site.currentProp("anonymous_top_menu_items"); if (!topMenuItems || !topMenuItems.includes(filterType)) { return null; } } if (!Category.list() && filterType === "categories") return null; if (!Site.currentProp("top_menu_items").includes(filterType)) return null; var args = { name: filterType, hasIcon: filterType === "unread" }; if (opts.category) { args.category = opts.category; } if (opts.tagId) { args.tagId = opts.tagId; } if (opts.persistedQueryParams) { args.persistedQueryParams = opts.persistedQueryParams; } if (opts.noSubcategories) { args.noSubcategories = true; } NavItem.extraArgsCallbacks.forEach(cb => _.merge(args, cb.call(this, filterType, opts)) ); const store = Discourse.__container__.lookup("service:store"); return store.createRecord("nav-item", args); }, buildList(category, args) { args = args || {}; if (category) { args.category = category; } let items = Discourse.SiteSettings.top_menu.split("|"); const filterType = (args.filterMode || "").split("/").pop(); if (!items.some(i => filterType === i)) { items.push(filterType); } items = items .map(i => NavItem.fromText(i, args)) .filter( i => i !== null && !(category && i.get("name").indexOf("categor") === 0) ); const context = { category: args.category, tagId: args.tagId, noSubcategories: args.noSubcategories }; const extraItems = NavItem.extraNavItemDescriptors .map(descriptor => ExtraNavItem.create(_.merge({}, context, descriptor))) .filter(item => { if (!item.customFilter) return true; return item.customFilter(category, args); }); let forceActive = false; extraItems.forEach(item => { if (item.init) { item.init(item, category, args); } const before = item.before; if (before) { let i = 0; for (i = 0; i < items.length; i++) { if (items[i].name === before) { break; } } items.splice(i, 0, item); } else { items.push(item); } if (item.customHref) { item.set("href", item.customHref(category, args)); } if (item.forceActive && item.forceActive(category, args)) { item.active = true; forceActive = true; } else { item.active = undefined; } }); if (forceActive) { items.forEach(i => { if (i.active === undefined) { i.active = false; } }); } return items; } }); export default NavItem; export function extraNavItemProperties(cb) { NavItem.extraArgsCallbacks.push(cb); } export function customNavItemHref(cb) { NavItem.customNavItemHrefs.push(cb); } export function addNavItem(item) { NavItem.extraNavItemDescriptors.push(item); } Object.defineProperty(Discourse, "NavItem", { get() { deprecated("Import the NavItem class instead of using Discourse.NavItem", { since: "2.4.0", dropFrom: "2.5.0" }); return NavItem; } });
shivi98g/EpilNet-EpilepsyPredictor
Mobile App/Code/sources/android/support/design/internal/BottomNavigationMenuView.java
package android.support.design.internal; import android.animation.TimeInterpolator; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.support.annotation.Dimension; import android.support.annotation.Nullable; import android.support.annotation.RestrictTo; import android.support.annotation.StyleRes; import android.support.design.C0044R; import android.support.p000v4.util.Pools; import android.support.p000v4.view.ViewCompat; import android.support.p000v4.view.animation.FastOutSlowInInterpolator; import android.support.p003v7.appcompat.C0395R; import android.support.p003v7.content.res.AppCompatResources; import android.support.p003v7.view.menu.MenuBuilder; import android.support.p003v7.view.menu.MenuItemImpl; import android.support.p003v7.view.menu.MenuView; import android.support.transition.AutoTransition; import android.support.transition.TransitionManager; import android.support.transition.TransitionSet; import android.util.AttributeSet; import android.util.TypedValue; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; @RestrictTo({RestrictTo.Scope.LIBRARY_GROUP}) public class BottomNavigationMenuView extends ViewGroup implements MenuView { private static final long ACTIVE_ANIMATION_DURATION_MS = 115; private static final int[] CHECKED_STATE_SET = {16842912}; private static final int[] DISABLED_STATE_SET = {-16842910}; private final int activeItemMaxWidth; private final int activeItemMinWidth; private BottomNavigationItemView[] buttons; private final int inactiveItemMaxWidth; private final int inactiveItemMinWidth; private Drawable itemBackground; private int itemBackgroundRes; private final int itemHeight; private boolean itemHorizontalTranslationEnabled; @Dimension private int itemIconSize; private ColorStateList itemIconTint; private final Pools.Pool<BottomNavigationItemView> itemPool; @StyleRes private int itemTextAppearanceActive; @StyleRes private int itemTextAppearanceInactive; private final ColorStateList itemTextColorDefault; private ColorStateList itemTextColorFromUser; private int labelVisibilityMode; /* access modifiers changed from: private */ public MenuBuilder menu; private final View.OnClickListener onClickListener; /* access modifiers changed from: private */ public BottomNavigationPresenter presenter; private int selectedItemId; private int selectedItemPosition; private final TransitionSet set; private int[] tempChildWidths; public BottomNavigationMenuView(Context context) { this(context, (AttributeSet) null); } public BottomNavigationMenuView(Context context, AttributeSet attrs) { super(context, attrs); this.itemPool = new Pools.SynchronizedPool(5); this.selectedItemId = 0; this.selectedItemPosition = 0; Resources res = getResources(); this.inactiveItemMaxWidth = res.getDimensionPixelSize(C0044R.dimen.design_bottom_navigation_item_max_width); this.inactiveItemMinWidth = res.getDimensionPixelSize(C0044R.dimen.design_bottom_navigation_item_min_width); this.activeItemMaxWidth = res.getDimensionPixelSize(C0044R.dimen.design_bottom_navigation_active_item_max_width); this.activeItemMinWidth = res.getDimensionPixelSize(C0044R.dimen.design_bottom_navigation_active_item_min_width); this.itemHeight = res.getDimensionPixelSize(C0044R.dimen.design_bottom_navigation_height); this.itemTextColorDefault = createDefaultColorStateList(16842808); this.set = new AutoTransition(); this.set.setOrdering(0); this.set.setDuration((long) ACTIVE_ANIMATION_DURATION_MS); this.set.setInterpolator((TimeInterpolator) new FastOutSlowInInterpolator()); this.set.addTransition(new TextScale()); this.onClickListener = new View.OnClickListener() { public void onClick(View v) { MenuItem item = ((BottomNavigationItemView) v).getItemData(); if (!BottomNavigationMenuView.this.menu.performItemAction(item, BottomNavigationMenuView.this.presenter, 0)) { item.setChecked(true); } } }; this.tempChildWidths = new int[5]; } public void initialize(MenuBuilder menu2) { this.menu = menu2; } /* access modifiers changed from: protected */ public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = View.MeasureSpec.getSize(widthMeasureSpec); int visibleCount = this.menu.getVisibleItems().size(); int totalCount = getChildCount(); int heightSpec = View.MeasureSpec.makeMeasureSpec(this.itemHeight, 1073741824); int i = 8; if (isShifting(this.labelVisibilityMode, visibleCount) && this.itemHorizontalTranslationEnabled) { View activeChild = getChildAt(this.selectedItemPosition); int activeItemWidth = this.activeItemMinWidth; if (activeChild.getVisibility() != 8) { activeChild.measure(View.MeasureSpec.makeMeasureSpec(this.activeItemMaxWidth, Integer.MIN_VALUE), heightSpec); activeItemWidth = Math.max(activeItemWidth, activeChild.getMeasuredWidth()); } int inactiveCount = visibleCount - (activeChild.getVisibility() != 8 ? 1 : 0); int activeWidth = Math.min(width - (this.inactiveItemMinWidth * inactiveCount), Math.min(activeItemWidth, this.activeItemMaxWidth)); int inactiveWidth = Math.min((width - activeWidth) / (inactiveCount == 0 ? 1 : inactiveCount), this.inactiveItemMaxWidth); int extra = (width - activeWidth) - (inactiveWidth * inactiveCount); int extra2 = 0; while (true) { int i2 = extra2; if (i2 >= totalCount) { break; } if (getChildAt(i2).getVisibility() != i) { this.tempChildWidths[i2] = i2 == this.selectedItemPosition ? activeWidth : inactiveWidth; if (extra > 0) { int[] iArr = this.tempChildWidths; iArr[i2] = iArr[i2] + 1; extra--; } } else { this.tempChildWidths[i2] = 0; } extra2 = i2 + 1; i = 8; } } else { int childWidth = Math.min(width / (visibleCount == 0 ? 1 : visibleCount), this.activeItemMaxWidth); int extra3 = width - (childWidth * visibleCount); for (int i3 = 0; i3 < totalCount; i3++) { if (getChildAt(i3).getVisibility() != 8) { this.tempChildWidths[i3] = childWidth; if (extra3 > 0) { int[] iArr2 = this.tempChildWidths; iArr2[i3] = iArr2[i3] + 1; extra3--; } } else { this.tempChildWidths[i3] = 0; } } } int totalWidth = 0; for (int i4 = 0; i4 < totalCount; i4++) { View child = getChildAt(i4); if (child.getVisibility() != 8) { child.measure(View.MeasureSpec.makeMeasureSpec(this.tempChildWidths[i4], 1073741824), heightSpec); child.getLayoutParams().width = child.getMeasuredWidth(); totalWidth += child.getMeasuredWidth(); } } setMeasuredDimension(View.resolveSizeAndState(totalWidth, View.MeasureSpec.makeMeasureSpec(totalWidth, 1073741824), 0), View.resolveSizeAndState(this.itemHeight, heightSpec, 0)); } /* access modifiers changed from: protected */ public void onLayout(boolean changed, int left, int top, int right, int bottom) { int count = getChildCount(); int width = right - left; int height = bottom - top; int used = 0; for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != 8) { if (ViewCompat.getLayoutDirection(this) == 1) { child.layout((width - used) - child.getMeasuredWidth(), 0, width - used, height); } else { child.layout(used, 0, child.getMeasuredWidth() + used, height); } used += child.getMeasuredWidth(); } } } public int getWindowAnimations() { return 0; } public void setIconTintList(ColorStateList tint) { this.itemIconTint = tint; if (this.buttons != null) { for (BottomNavigationItemView item : this.buttons) { item.setIconTintList(tint); } } } @Nullable public ColorStateList getIconTintList() { return this.itemIconTint; } public void setItemIconSize(@Dimension int iconSize) { this.itemIconSize = iconSize; if (this.buttons != null) { for (BottomNavigationItemView item : this.buttons) { item.setIconSize(iconSize); } } } @Dimension public int getItemIconSize() { return this.itemIconSize; } public void setItemTextColor(ColorStateList color) { this.itemTextColorFromUser = color; if (this.buttons != null) { for (BottomNavigationItemView item : this.buttons) { item.setTextColor(color); } } } public ColorStateList getItemTextColor() { return this.itemTextColorFromUser; } public void setItemTextAppearanceInactive(@StyleRes int textAppearanceRes) { this.itemTextAppearanceInactive = textAppearanceRes; if (this.buttons != null) { for (BottomNavigationItemView item : this.buttons) { item.setTextAppearanceInactive(textAppearanceRes); if (this.itemTextColorFromUser != null) { item.setTextColor(this.itemTextColorFromUser); } } } } @StyleRes public int getItemTextAppearanceInactive() { return this.itemTextAppearanceInactive; } public void setItemTextAppearanceActive(@StyleRes int textAppearanceRes) { this.itemTextAppearanceActive = textAppearanceRes; if (this.buttons != null) { for (BottomNavigationItemView item : this.buttons) { item.setTextAppearanceActive(textAppearanceRes); if (this.itemTextColorFromUser != null) { item.setTextColor(this.itemTextColorFromUser); } } } } @StyleRes public int getItemTextAppearanceActive() { return this.itemTextAppearanceActive; } public void setItemBackgroundRes(int background) { this.itemBackgroundRes = background; if (this.buttons != null) { for (BottomNavigationItemView item : this.buttons) { item.setItemBackground(background); } } } @Deprecated public int getItemBackgroundRes() { return this.itemBackgroundRes; } public void setItemBackground(@Nullable Drawable background) { this.itemBackground = background; if (this.buttons != null) { for (BottomNavigationItemView item : this.buttons) { item.setItemBackground(background); } } } @Nullable public Drawable getItemBackground() { if (this.buttons == null || this.buttons.length <= 0) { return this.itemBackground; } return this.buttons[0].getBackground(); } public void setLabelVisibilityMode(int labelVisibilityMode2) { this.labelVisibilityMode = labelVisibilityMode2; } public int getLabelVisibilityMode() { return this.labelVisibilityMode; } public void setItemHorizontalTranslationEnabled(boolean itemHorizontalTranslationEnabled2) { this.itemHorizontalTranslationEnabled = itemHorizontalTranslationEnabled2; } public boolean isItemHorizontalTranslationEnabled() { return this.itemHorizontalTranslationEnabled; } public ColorStateList createDefaultColorStateList(int baseColorThemeAttr) { TypedValue value = new TypedValue(); if (!getContext().getTheme().resolveAttribute(baseColorThemeAttr, value, true)) { return null; } ColorStateList baseColor = AppCompatResources.getColorStateList(getContext(), value.resourceId); if (!getContext().getTheme().resolveAttribute(C0395R.attr.colorPrimary, value, true)) { return null; } int colorPrimary = value.data; int defaultColor = baseColor.getDefaultColor(); return new ColorStateList(new int[][]{DISABLED_STATE_SET, CHECKED_STATE_SET, EMPTY_STATE_SET}, new int[]{baseColor.getColorForState(DISABLED_STATE_SET, defaultColor), colorPrimary, defaultColor}); } public void setPresenter(BottomNavigationPresenter presenter2) { this.presenter = presenter2; } public void buildMenuView() { removeAllViews(); if (this.buttons != null) { for (BottomNavigationItemView item : this.buttons) { if (item != null) { this.itemPool.release(item); } } } if (this.menu.size() == 0) { this.selectedItemId = 0; this.selectedItemPosition = 0; this.buttons = null; return; } this.buttons = new BottomNavigationItemView[this.menu.size()]; boolean shifting = isShifting(this.labelVisibilityMode, this.menu.getVisibleItems().size()); for (int i = 0; i < this.menu.size(); i++) { this.presenter.setUpdateSuspended(true); this.menu.getItem(i).setCheckable(true); this.presenter.setUpdateSuspended(false); BottomNavigationItemView child = getNewItem(); this.buttons[i] = child; child.setIconTintList(this.itemIconTint); child.setIconSize(this.itemIconSize); child.setTextColor(this.itemTextColorDefault); child.setTextAppearanceInactive(this.itemTextAppearanceInactive); child.setTextAppearanceActive(this.itemTextAppearanceActive); child.setTextColor(this.itemTextColorFromUser); if (this.itemBackground != null) { child.setItemBackground(this.itemBackground); } else { child.setItemBackground(this.itemBackgroundRes); } child.setShifting(shifting); child.setLabelVisibilityMode(this.labelVisibilityMode); child.initialize((MenuItemImpl) this.menu.getItem(i), 0); child.setItemPosition(i); child.setOnClickListener(this.onClickListener); addView(child); } this.selectedItemPosition = Math.min(this.menu.size() - 1, this.selectedItemPosition); this.menu.getItem(this.selectedItemPosition).setChecked(true); } public void updateMenuView() { if (this.menu != null && this.buttons != null) { int menuSize = this.menu.size(); if (menuSize != this.buttons.length) { buildMenuView(); return; } int previousSelectedId = this.selectedItemId; for (int i = 0; i < menuSize; i++) { MenuItem item = this.menu.getItem(i); if (item.isChecked()) { this.selectedItemId = item.getItemId(); this.selectedItemPosition = i; } } if (previousSelectedId != this.selectedItemId) { TransitionManager.beginDelayedTransition(this, this.set); } boolean shifting = isShifting(this.labelVisibilityMode, this.menu.getVisibleItems().size()); for (int i2 = 0; i2 < menuSize; i2++) { this.presenter.setUpdateSuspended(true); this.buttons[i2].setLabelVisibilityMode(this.labelVisibilityMode); this.buttons[i2].setShifting(shifting); this.buttons[i2].initialize((MenuItemImpl) this.menu.getItem(i2), 0); this.presenter.setUpdateSuspended(false); } } } private BottomNavigationItemView getNewItem() { BottomNavigationItemView item = this.itemPool.acquire(); if (item == null) { return new BottomNavigationItemView(getContext()); } return item; } public int getSelectedItemId() { return this.selectedItemId; } private boolean isShifting(int labelVisibilityMode2, int childCount) { if (labelVisibilityMode2 == -1) { if (childCount <= 3) { return false; } } else if (labelVisibilityMode2 != 0) { return false; } return true; } /* access modifiers changed from: package-private */ public void tryRestoreSelectedItemId(int itemId) { int size = this.menu.size(); for (int i = 0; i < size; i++) { MenuItem item = this.menu.getItem(i); if (itemId == item.getItemId()) { this.selectedItemId = itemId; this.selectedItemPosition = i; item.setChecked(true); return; } } } }
markazmierczak/Polonite
Stp/Base/Compiler/Config.h
<reponame>markazmierczak/Polonite // Copyright 2017 Polonite Authors. All rights reserved. // Distributed under MIT license that can be found in the LICENSE file. #ifndef STP_BASE_COMPILER_CONFIG_H_ #define STP_BASE_COMPILER_CONFIG_H_ #define COMPILER(x) ((_STP_COMPILER & _STP_COMPILER_##x) == _STP_COMPILER_##x) #define _STP_COMPILER_GCC (1 << 0) #define _STP_COMPILER_MSVC (1 << 1) // Clang mimics other compiler frontends. #define _STP_COMPILER_CLANG (1 << 8) #if defined(__clang__) # define _STP_COMPILER_BACKEND _STP_COMPILER_CLANG #else # define _STP_COMPILER_BACKEND 0 #endif #if defined(__GNUC__) # define _STP_COMPILER_FRONTEND _STP_COMPILER_GCC #elif defined(_MSC_VER) # define _STP_COMPILER_FRONTEND _STP_COMPILER_MSVC #else # error "please add support for your compiler" #endif #define _STP_COMPILER (_STP_COMPILER_FRONTEND | _STP_COMPILER_BACKEND) #if COMPILER(GCC) #define COMPILER_GCC_AT_LEAST(major, minor) __GNUC_PREREQ(major, minor) #else #define COMPILER_GCC_AT_LEAST(major, minor) 0 #endif #define SANITIZER(x) (defined HAVE_##x##_SANITIZER) #if SANITIZER(ADDRESS) || \ SANITIZER(LEAK) || \ SANITIZER(THREAD) || \ SANITIZER(MEMORY) || \ SANITIZER(UNDEFINED) || \ SANITIZER(SYZYASAN) # define HAVE_ANY_SANITIZER #endif #if SANITIZER(ADDRESS) extern "C" void __asan_poison_memory_region(void const volatile *addr, size_t size); extern "C" void __asan_unpoison_memory_region(void const volatile *addr, size_t size); extern "C" int __asan_address_is_poisoned(void const volatile *addr); #endif #ifdef COMPONENT_BUILD #if COMPILER(MSVC) #ifdef STP_BASE_IMPLEMENTATION #define BASE_EXPORT __declspec(dllexport) #else #define BASE_EXPORT __declspec(dllimport) #endif #else #ifdef STP_BASE_IMPLEMENTATION #define BASE_EXPORT __attribute__((visibility("default"))) #else #define BASE_EXPORT #endif #endif #else #define BASE_EXPORT #endif // COMPONENT_BUILD #endif // STP_BASE_COMPILER_CONFIG_H_
cice/wsdl-mapper
lib/wsdl_mapper_testing/fake_operation.rb
<gh_stars>1-10 require 'wsdl_mapper_testing/fake_s8r' require 'wsdl_mapper_testing/fake_d10r' module WsdlMapperTesting class FakeOperation attr_accessor :input_s8r, :output_d10r, :input_d10r, :output_d8r def initialize @inputs = {} @outputs = {} @input_s8r = FakeS8r.new @output_s8r = FakeS8r.new @input_d10r = FakeD10r.new @output_d10r = FakeD10r.new end def input_for_body(body, input) @inputs[body] = input end def output_for_body(body, output) @outputs[body] = output end def new_input(_header: nil, body: nil) @inputs.fetch body end def new_output(_header: nil, body: nil) @outputs.fetch body end end end
Jons2k/jfast
src/main/java/org/pp/modules/sys/service/UserLoginService.java
<reponame>Jons2k/jfast package org.pp.modules.sys.service; import java.util.Date; import org.pp.core.BaseService; import org.pp.modules.sys.model.User; import org.pp.modules.sys.model.UserLogin; import com.jfinal.plugin.activerecord.Db; public class UserLoginService implements BaseService<UserLogin>{ public static UserLogin dao = new UserLogin().dao(); private String error = ""; /** * 记录未成功的登录信息 * @param account String 账号 * @param ip String IP */ public void record(String account, String ip) { UserLogin data = new UserLogin(); data.setAccount(account); data.setIp(ip); data.setLoginTime(new Date()); data.save(); } /** * 记录成功的登录 信息 * @param user User 登录成功的用户 * @param ip String IP * @param session String SessionID */ public void record(User user, String ip, String session) { UserLogin data = new UserLogin(); data.setAccount(user.getAccount()); data.setUserId(user.getId()); data.setSessionId(session); data.setIp(ip); data.setLoginTime(new Date()); data.save(); } /** * 记录成功的登录 信息 * @param user User 登录成功的用户 * @param ip String IP * @param session String SessionID */ public void record(User user, String ip) { UserLogin data = new UserLogin(); data.setAccount(user.getAccount()); data.setUserId(user.getId()); data.setIp(ip); data.setLoginTime(new Date()); data.save(); } public void logout(User user, String session) { Db.update("UPDATE sys_user_login set logout_time=? WHERE user_id=? and session_id=?", new Date(), user.getId(), session); } public void logout(String ip, String session) { Db.update("UPDATE sys_user_login set logout_time=? WHERE ip=? and session_id=?", new Date(), ip, session); } @Override public String getError() { return error; } public void setError(String error) { this.error = error; } @Override public UserLogin getModel() { return dao; } }
yonghong915/fib
codes/fib-boot/fib-application/fib-upp/src/main/java/com/fib/upp/service/impl/BepsPackServiceImpl.java
package com.fib.upp.service.impl; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.fib.upp.mapper.BepsMessagePackRuleMapper; import com.fib.upp.pay.beps.pack.BepsMessagePackRule; import com.fib.upp.pay.beps.pack.BepsQueue; import com.fib.upp.pay.beps.pack.BepsQueueHeader; import com.fib.upp.service.IBepsPackService; import com.fib.upp.service.IBepsQueueService; import com.fib.upp.util.BepsUtil; @Service("bepsPackService") public class BepsPackServiceImpl implements IBepsPackService { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private BepsMessagePackRuleMapper bepsMessagePackRuleMapper; @Autowired private IBepsQueueService bepsQueueService; @Override public List<BepsMessagePackRule> queryBepsPackRuleList() { QueryWrapper<BepsMessagePackRule> wrapper = new QueryWrapper<>(); return bepsMessagePackRuleMapper.selectList(wrapper); } @Async("taskExecutor") @Transactional @Override public void packBepsMessage() { String queueType = BepsUtil.QueueType.TMA001.code(); logger.info("queueType={}", queueType); // 获取队列的定义 BepsQueue queue = bepsQueueService.getQueueByQueueType(queueType); // if (Objects.isNull(queue)) { // throw new CommonException("没有定义的队列类型" + queueType); // } // 查询队列头'打开'的队列 BepsQueueHeader queueHeader = bepsQueueService.getOpenedQueueHeader(queueType); // if (Objects.isNull(queueHeader)) { // throw new CommonException("关闭队列失败:队列类型[" + queueType + "]还没有打开"); // } Long queueId = queueHeader.getPkId(); logger.info("queueId={}", queueId); String queueStatus = queue.getQueueStatus(); if (BepsUtil.QueueStatus.VLD.code().equals(queueStatus)) { // 新建状态为'打开'的队列 BepsQueueHeader newQueueHeader = new BepsQueueHeader(); //newQueueHeader.setPkId(IdUtil.createSnowflake(1, 1).nextId()); newQueueHeader.setQueueType(queueType); newQueueHeader.setStatus(BepsUtil.QueueHeaderStatus.OPN.code()); bepsQueueService.createQueueHeader(newQueueHeader); } // 更新原队列为"即将关闭"状态 bepsQueueService.updateQueueHeaderStatus(queueId, BepsUtil.QueueHeaderStatus.FPC.code()); } }
davepkxxx/dai-lang
dai-compiler/src/main/java/dai/compiler/parsing/StructVisitor.java
<filename>dai-compiler/src/main/java/dai/compiler/parsing/StructVisitor.java package dai.compiler.parsing; import dai.compiler.antlr.DaiParser.*; import dai.compiler.ast.AnnotatedNode; import dai.compiler.ast.ClassTypeNode; import dai.compiler.ast.StructDeclaration; import dai.compiler.ast.VariableDeclaration; import java.util.List; public interface StructVisitor extends BaseVisitor { default StructDeclaration visitStructDeclaration(StructDeclarationContext ctx) { StructDeclaration result = new StructDeclaration(); this.accept(ctx.identifier(), this::visitIdentifier, result::setName); this.accept(ctx.annotated(), this::visitAnnotated, result.getAnnotations()::add); this.accept(ctx.declTypeParamsBlock(), this::visitDeclTypeParamsBlock, result::setGenericsParameters); this.accept(ctx.extendsBlock(), this::visitExtendsBlock, result::setSuperType); this.accept(ctx.variableDeclaration(), this::visitVariableDeclaration, result.getFields()::add); return result; } default ClassTypeNode visitExtendsBlock(ExtendsBlockContext ctx) { return this.map(ctx.useType(), this::visitUseType); } AnnotatedNode visitAnnotated(AnnotatedContext ctx); ClassTypeNode visitUseType(UseTypeContext ctx); String visitIdentifier(IdentifierContext ctx); VariableDeclaration visitVariableDeclaration(VariableDeclarationContext ctx); List<ClassTypeNode> visitDeclTypeParamsBlock(DeclTypeParamsBlockContext ctx); }
mohamedelkashif/coffee-app
app/transformers/pod.transformer.js
/** * HATEOAS LINKS * * @param {Object} req * @param {Object} pod * * @return {Array} */ function getHyperLinks(req, pod) { const baseUrl = req.protocol + '://' + req.headers.host; const links = [ { 'rel': `self`, 'href': `${baseUrl}/api/pods/${pod._id}` }, { 'rel': `pod.type`, 'method': "GET", 'href': `${baseUrl}/api/types/${pod.product_type_id}` }, { 'rel': `pod.flavor`, 'method': "GET", 'href': `${baseUrl}/api/flavors/${pod.coffee_flavor_id}` }, { 'rel': `pod.size`, 'method': "GET", 'href': `${baseUrl}/api/sizes/${pod.pack_size_id}` } ]; return links; } /** * Defrag collection, get hyperLinks * * @param {Object} req * @param {Object} collection * * @return {Object} */ module.exports.hyperMediaAll = function hyperMedia(req, collection) { const hyperCollections = []; collection.forEach(function (item, index, array) { const hyperCollection = item.toJSON(); hyperCollection.links = getHyperLinks(req, hyperCollection); hyperCollections.push(hyperCollection); }); return hyperCollections; } /** * Defrag object, get hyperLinks * * @param {Object} req * @param {Object} object * * @return {Object} */ module.exports.hyperMediaOne = function hyperMedia(req, object) { const hyperObject = object.toJSON(); hyperObject.links = getHyperLinks(req, hyperObject); return hyperObject; }
ochafik/rollup
src/ast/nodes/VariableDeclaration.js
import Node from '../Node.js'; import extractNames from '../utils/extractNames.js'; function getSeparator ( code, start ) { let c = start; while ( c > 0 && code[ c - 1 ] !== '\n' ) { c -= 1; if ( code[c] === ';' || code[c] === '{' ) return '; '; } const lineStart = code.slice( c, start ).match( /^\s*/ )[0]; return `;\n${lineStart}`; } const forStatement = /^For(?:Of|In)?Statement/; export default class VariableDeclaration extends Node { initialise ( scope ) { this.scope = scope; super.initialise( scope ); } render ( code, es ) { const treeshake = this.module.bundle.treeshake; let shouldSeparate = false; let separator; if ( this.scope.isModuleScope && !forStatement.test( this.parent.type ) ) { shouldSeparate = true; separator = getSeparator( this.module.code, this.start ); } let c = this.start; let empty = true; for ( let i = 0; i < this.declarations.length; i += 1 ) { const declarator = this.declarations[i]; const prefix = empty ? '' : separator; // TODO indentation if ( declarator.id.type === 'Identifier' ) { const proxy = declarator.proxies.get( declarator.id.name ); const isExportedAndReassigned = !es && proxy.exportName && proxy.isReassigned; if ( isExportedAndReassigned ) { if ( declarator.init ) { if ( shouldSeparate ) code.overwrite( c, declarator.start, prefix ); c = declarator.end; empty = false; } } else if ( !treeshake || proxy.activated ) { if ( shouldSeparate ) code.overwrite( c, declarator.start, `${prefix}${this.kind} ` ); // TODO indentation c = declarator.end; empty = false; } } else { const exportAssignments = []; let activated = false; extractNames( declarator.id ).forEach( name => { const proxy = declarator.proxies.get( name ); const isExportedAndReassigned = !es && proxy.exportName && proxy.isReassigned; if ( isExportedAndReassigned ) { // code.overwrite( c, declarator.start, prefix ); // c = declarator.end; // empty = false; exportAssignments.push( 'TODO' ); } else if ( declarator.activated ) { activated = true; } }); if ( !treeshake || activated ) { if ( shouldSeparate ) code.overwrite( c, declarator.start, `${prefix}${this.kind} ` ); // TODO indentation c = declarator.end; empty = false; } if ( exportAssignments.length ) { throw new Error( 'TODO' ); } } declarator.render( code, es ); } if ( treeshake && empty ) { code.remove( this.leadingCommentStart || this.start, this.next || this.end ); } else { // always include a semi-colon (https://github.com/rollup/rollup/pull/1013), // unless it's a var declaration in a loop head const needsSemicolon = !forStatement.test( this.parent.type ); if ( this.end > c ) { code.overwrite( c, this.end, needsSemicolon ? ';' : '' ); } else if ( needsSemicolon ) { this.insertSemicolon( code ); } } } }
Ron423c/chromium
ui/views/controls/image_view_unittest.cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/image_view.h" #include <memory> #include <string> #include <utility> #include "base/i18n/rtl.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/border.h" #include "ui/views/layout/box_layout.h" #include "ui/views/test/ax_event_counter.h" #include "ui/views/test/views_test_base.h" #include "ui/views/widget/widget.h" namespace { enum class Axis { kHorizontal, kVertical, }; // A test utility function to set the application default text direction. void SetRTL(bool rtl) { // Override the current locale/direction. base::i18n::SetICUDefaultLocale(rtl ? "he" : "en"); EXPECT_EQ(rtl, base::i18n::IsRTL()); } } // namespace namespace views { class ImageViewTest : public ViewsTestBase, public ::testing::WithParamInterface<Axis> { public: ImageViewTest() = default; // ViewsTestBase: void SetUp() override { ViewsTestBase::SetUp(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(200, 200); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; widget_.Init(std::move(params)); auto container = std::make_unique<View>(); // Make sure children can take up exactly as much space as they require. BoxLayout::Orientation orientation = GetParam() == Axis::kHorizontal ? BoxLayout::Orientation::kHorizontal : BoxLayout::Orientation::kVertical; container->SetLayoutManager(std::make_unique<BoxLayout>(orientation)); image_view_ = container->AddChildView(std::make_unique<ImageView>()); widget_.SetContentsView(std::move(container)); widget_.Show(); } void TearDown() override { widget_.Close(); ViewsTestBase::TearDown(); } int CurrentImageOriginForParam() { image_view()->UpdateImageOrigin(); gfx::Point origin = image_view()->GetImageBounds().origin(); return GetParam() == Axis::kHorizontal ? origin.x() : origin.y(); } protected: ImageView* image_view() { return image_view_; } Widget* widget() { return &widget_; } private: ImageView* image_view_ = nullptr; Widget widget_; DISALLOW_COPY_AND_ASSIGN(ImageViewTest); }; // Test the image origin of the internal ImageSkia is correct when it is // center-aligned (both horizontally and vertically). TEST_P(ImageViewTest, CenterAlignment) { image_view()->SetHorizontalAlignment(ImageView::Alignment::kCenter); constexpr int kImageSkiaSize = 4; SkBitmap bitmap; bitmap.allocN32Pixels(kImageSkiaSize, kImageSkiaSize); gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); image_view()->SetImage(image_skia); widget()->GetContentsView()->Layout(); EXPECT_NE(gfx::Size(), image_skia.size()); // With no changes to the size / padding of |image_view|, the origin of // |image_skia| is the same as the origin of |image_view|. EXPECT_EQ(0, CurrentImageOriginForParam()); // Test insets are always respected in LTR and RTL. constexpr int kInset = 5; image_view()->SetBorder(CreateEmptyBorder(gfx::Insets(kInset))); widget()->GetContentsView()->Layout(); EXPECT_EQ(kInset, CurrentImageOriginForParam()); SetRTL(true); widget()->GetContentsView()->Layout(); EXPECT_EQ(kInset, CurrentImageOriginForParam()); // Check this still holds true when the insets are asymmetrical. constexpr int kLeadingInset = 4; constexpr int kTrailingInset = 6; image_view()->SetBorder(CreateEmptyBorder( gfx::Insets(/*top=*/kLeadingInset, /*left=*/kLeadingInset, /*bottom=*/kTrailingInset, /*right=*/kTrailingInset))); widget()->GetContentsView()->Layout(); EXPECT_EQ(kLeadingInset, CurrentImageOriginForParam()); SetRTL(false); widget()->GetContentsView()->Layout(); EXPECT_EQ(kLeadingInset, CurrentImageOriginForParam()); } TEST_P(ImageViewTest, ImageOriginForCustomViewBounds) { gfx::Rect image_view_bounds(10, 10, 80, 80); image_view()->SetHorizontalAlignment(ImageView::Alignment::kCenter); image_view()->SetBoundsRect(image_view_bounds); SkBitmap bitmap; constexpr int kImageSkiaSize = 20; bitmap.allocN32Pixels(kImageSkiaSize, kImageSkiaSize); gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); image_view()->SetImage(image_skia); EXPECT_EQ(gfx::Point(30, 30), image_view()->GetImageBounds().origin()); EXPECT_EQ(image_view_bounds, image_view()->bounds()); } // Verifies setting the accessible name will be call NotifyAccessibilityEvent. TEST_P(ImageViewTest, SetAccessibleNameNotifiesAccessibilityEvent) { base::string16 test_tooltip_text = base::ASCIIToUTF16("Test Tooltip Text"); test::AXEventCounter counter(views::AXEventManager::Get()); EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kTextChanged)); image_view()->SetAccessibleName(test_tooltip_text); EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kTextChanged)); EXPECT_EQ(test_tooltip_text, image_view()->GetAccessibleName()); ui::AXNodeData data; image_view()->GetAccessibleNodeData(&data); const std::string& name = data.GetStringAttribute(ax::mojom::StringAttribute::kName); EXPECT_EQ(test_tooltip_text, base::ASCIIToUTF16(name)); } INSTANTIATE_TEST_SUITE_P(All, ImageViewTest, ::testing::Values(Axis::kHorizontal, Axis::kVertical)); } // namespace views
kuanshi/ductile-fracture
OpenSees/SRC/element/catenaryCable/CatenaryCable.h
<gh_stars>0 /* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** <NAME> (<EMAIL>) ** ** <NAME> (<EMAIL>) ** ** <NAME> (<EMAIL>) ** ** ** ** ****************************************************************** */ // $Revision: 6049 $ // $Date: 2015-07-17 01:56:36 -0300 (Fri, 17 Jul 2015) $ // $URL: svn://peera.berkeley.edu/usr/local/svn/OpenSees/trunk/SRC/element/CatenaryCable/CatenaryCable.h $ #ifndef CatenaryCable_h #define CatenaryCable_h // Written: jaabell (<NAME>) // Created: May 2017 // Revision: A // // Description: This element is a catenary cable, suitable for static and dynamic analysis of // cable structures including thermal effects. Based on: // // <NAME>., <NAME>., <NAME>., & <NAME>. (2013). // Nonlinear analysis of cable structures under general loadings. Finite Elements in Analysis and Design, // 73, 11–19. https://doi.org/10.1016/j.finel.2013.05.002 // // With dynamical extensions (mass matrix). // // Verification suite can be found in www.joseabell.com // // What: "@(#) CatenaryCable.h, revA" #include <Element.h> #include <Matrix.h> class Node; class Channel; class UniaxialMaterial; class CatenaryCable : public Element { public: CatenaryCable(int tag, int node1, int node2, double weight, double E, double A, double L0, double alpha, double temperature_change, double rho, double error_tol, int Nsubsteps, int massType); CatenaryCable(); ~CatenaryCable(); const char *getClassType(void) const {return "CatenaryCable";}; // public methods to obtain inforrmation about dof & connectivity int getNumExternalNodes(void) const; const ID &getExternalNodes(void); Node **getNodePtrs(void); int getNumDOF(void); void setDomain(Domain *theDomain); // public methods to set the state of the element int commitState(void); int revertToLastCommit(void); int revertToStart(void); int update(void); // public methods to obtain stiffness, mass, damping and residual information const Matrix &getKi(void); const Matrix &getTangentStiff(void); const Matrix &getInitialStiff(void); const Matrix &getDamp(void); const Matrix &getMass(void); void zeroLoad(void); int addLoad(ElementalLoad *theLoad, double loadFactor); int addInertiaLoadToUnbalance(const Vector &accel); const Vector &getResistingForce(void); const Vector &getResistingForceIncInertia(void); // public methods for element output int sendSelf(int commitTag, Channel &theChannel); int recvSelf(int commitTag, Channel &theChannel, FEM_ObjectBroker &theBroker); int displaySelf(Renderer &, int mode, float fact, const char **displayModes=0, int numModes=0); void Print(OPS_Stream &s, int flag =0); Response *setResponse(const char **argv, int argc, OPS_Stream &s); int getResponse(int responseID, Information &eleInformation); protected: private: void compute_lambda0(void) ; void compute_projected_lengths(void) ; void compute_flexibility_matrix(void) ; void computeMass(); void computeMassLumped(); void computeMassByIntegration(); // private attributes - a copy for each object of the class ID connectedExternalNodes; // contains the tags of the end nodes Vector *theLoad; // pointer to the load vector P Matrix *theMatrix; // pointer to objects matrix (a class wide Matrix) Vector *theVector; // pointer to objects vector (a class wide Vector) double weight; // weight of the CatenaryCable double E; // Young's modulus of the CatenaryCable material double A; // area of CatenaryCable double L0; // unstreched, unexpanded length of CatenaryCable double alpha; // Coefficient of thermal expansion for CatenaryCable double temperature_change; // Change in temperature of the CatenaryCable double rho; // rho: mass density per unit length of the CatenaryCable double error_tol; int Nsubsteps; double lx0, ly0, lz0; double w1, w2, w3; double f1, f2, f3; double l1, l2, l3; double lambda0; double l[3]; //Projected lengths bool first_step; int massType; Node *theNodes[2]; Vector *load; // static data - single copy for all objects of the class static Matrix Flexibility; // class wide flexibility matrix for iterations static Matrix Stiffness; static Matrix Mass; static Matrix ZeroMatrix; static Vector Forces; }; #endif
JamesCao2048/BlizzardData
Corpus/birt/6929.java
/******************************************************************************* * Copyright (c) 2004, 2005 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.olap.api.query; import java.util.Collection; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.IFilterDefinition; import org.eclipse.birt.data.engine.api.IScriptExpression; public interface ICubeElementFactory { static final String CUBE_ELEMENT_FACTORY_CLASS_NAME = "org.eclipse.birt.data.engine.olap.impl.query.CubeElementFactory"; /** * * @param name * @return */ public ICubeQueryDefinition createCubeQuery( String name ); /** * * @param name * @return */ public ISubCubeQueryDefinition createSubCubeQuery( String name ); /** * * @param filterExpr * @param targetLevel * @param axisQulifierLevel * @param axisQulifierValue * @return */ public ICubeFilterDefinition creatCubeFilterDefinition( IBaseExpression filterExpr, ILevelDefinition targetLevel, ILevelDefinition[] axisQulifierLevel, Object[] axisQulifierValue ); /** * @param filterExpr * @param targetLevel * @param axisQulifierLevel * @param axisQulifierValue * @param updateAggr * @return */ public ICubeFilterDefinition creatCubeFilterDefinition( IBaseExpression filterExpr, ILevelDefinition targetLevel, ILevelDefinition[] axisQulifierLevel, Object[] axisQulifierValue, boolean updateAggr ); /** * * @param targetLevels * @param operator * @param memberValues * @return */ public IFilterDefinition creatLevelMemberFilterDefinition( Collection<IScriptExpression> targetLevels, int operator, Collection<Collection<IScriptExpression>> memberValues ); /** * * @param filterExpr * @param targetLevel * @param axisQulifierLevel * @param axisQulifierValue * @param sortDirection * @return */ public ICubeSortDefinition createCubeSortDefinition( IScriptExpression filterExpr, ILevelDefinition targetLevel, ILevelDefinition[] axisQulifierLevel, Object[] axisQulifierValue, int sortDirection ); /** * * @param filterExpr * @param targetLevel * @param axisQulifierLevel * @param axisQulifierValue * @param sortDirection * @return */ public ICubeSortDefinition createCubeSortDefinition( String filterExpr, ILevelDefinition targetLevel, ILevelDefinition[] axisQulifierLevel, Object[] axisQulifierValue, int sortDirection ); /** * * @param dimensionName * @param hierarchyName * @param levelName * @return */ public ILevelDefinition createLevel( String dimensionName, String hierarchyName, String levelName ); /** * @return cube operation factory to create cube operations */ public ICubeOperationFactory getCubeOperationFactory( ); }
AllSafeCyberSecur1ty/Nuclear-Engineering
pyne/tests/test_origen22.py
<gh_stars>1-10 from __future__ import print_function import warnings try: from StringIO import StringIO except ImportError: from io import StringIO import numpy as np from nose.tools import ( assert_equal, assert_true, assert_raises, assert_in, assert_is_instance, ) from numpy.testing import assert_array_equal from pyne.utils import QAWarning warnings.simplefilter("ignore", QAWarning) from pyne import origen22 from pyne.xs.cache import XSCache from pyne.xs.data_source import NullDataSource from pyne.material import Material def test_sec_to_time_unit(): assert_equal(origen22.sec_to_time_unit(1.0), (1.0, 1)) assert_equal(origen22.sec_to_time_unit(10.0), (10.0, 1)) assert_equal(origen22.sec_to_time_unit(60.0), (1.0, 2)) assert_equal(origen22.sec_to_time_unit(120.0), (2.0, 2)) assert_equal(origen22.sec_to_time_unit(np.inf), (0.0, 6)) assert_equal(origen22.sec_to_time_unit(315569260.0), (10.0, 5)) assert_equal(origen22.sec_to_time_unit(31556926.0 * 1e7), (10.0, 8)) assert_equal(origen22.sec_to_time_unit(31556926.0 * 1e10), (10.0, 9)) def test_write_tape4(): mat = Material({"U235": 0.95, 80160000: 0.05}) tape4 = StringIO() origen22.write_tape4(mat, tape4) tape4.seek(0) observed = tape4.read() expected = ( "1 80160 5.0000000000E-02 0 0 0 0 0 0\n" "2 922350 9.5000000000E-01 0 0 0 0 0 0\n" "0 0 0 0\n" ) assert_equal(observed, expected) def test_out_table_string1(): obs = origen22._out_table_string(None, None) exp = "1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1" assert_equal(obs, exp) def test_out_table_string2(): obs = origen22._out_table_string((False, False, True), None) exp = "1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1" assert_equal(obs, exp) def test_out_table_string3(): obs = origen22._out_table_string((False, False, True), range(1, 25)) exp = "7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7" assert_equal(obs, exp) def test_out_table_string4(): obs = origen22._out_table_string((False, False, True), [10, 5]) exp = "8 8 8 8 7 8 8 8 8 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8" assert_equal(obs, exp) def test_out_table_string5(): obs = origen22._out_table_string((True, False, True), [10, 5]) exp = "8 8 8 8 3 8 8 8 8 3 8 8 8 8 8 8 8 8 8 8 8 8 8 8" assert_equal(obs, exp) def test_write_nan_tape5_irradiation(): tape5 = StringIO() with assert_raises(ValueError) as context: origen22.write_tape5_irradiation( "IRP", 100, np.nan, xsfpy_nlb=[204, 205, 206], outfile=tape5, out_table_nes=(False, False, True), out_table_laf=(True, False, True), out_table_num=[5, 10], ) ex = context.exception assert_equal(ex.args[0], "Irradiation value is NaN.") def test_write_inf_tape5_irradiation(): tape5 = StringIO() with assert_raises(ValueError) as context: origen22.write_tape5_irradiation( "IRP", 100, np.inf, xsfpy_nlb=[204, 205, 206], outfile=tape5, out_table_nes=(False, False, True), out_table_laf=(True, False, True), out_table_num=[5, 10], ) ex = context.exception assert_equal(ex.args[0], "Irradiation value is infinite.") def test_write_tape5_irradiation(): tape5 = StringIO() origen22.write_tape5_irradiation( "IRP", 100, 0.550, xsfpy_nlb=[204, 205, 206], outfile=tape5, out_table_nes=(False, False, True), out_table_laf=(True, False, True), out_table_num=[5, 10], ) tape5.seek(0) observed = tape5.read() expected = ( " -1\n" " -1\n" " -1\n" " CUT 5 1.000E-10 -1\n" " RDA Make sure thet the library identifier numbers match those in the" " TAPE9.INP file\n" " LIB 0 1 2 3 204 205 206 9 3 0 4 0\n" " OPTL 8 8 8 8 7 8 8 8 8 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8\n" " OPTA 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8\n" " OPTF 8 8 8 8 7 8 8 8 8 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8\n" " INP 1 -1 0 -1 4 4\n" " RDA All irradiation (IRF and IRP) cards must be between burnup (BUP) " "cards.\n" " BUP\n" " IRP 1.0000000000E+02 5.5000000000E-01 1 2 4 2\n" " BUP\n" " OUT 2 1 1 0\n" " END\n" ) assert_equal(observed, expected) def test_write_tape5_decay(): tape5 = StringIO() origen22.write_tape5_decay( 100, xsfpy_nlb=[204, 205, 206], outfile=tape5, out_table_nes=(False, False, True), out_table_laf=(True, False, True), out_table_num=[5, 10], ) tape5.seek(0) observed = tape5.read() expected = ( " -1\n" " -1\n" " -1\n" " CUT 5 1.000E-10 -1\n" " RDA Make sure thet the library identifier numbers match those in the " "TAPE9.INP file\n" " LIB 0 1 2 3 204 205 206 9 3 0 4 0\n" " OPTL 8 8 8 8 7 8 8 8 8 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8\n" " OPTA 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8\n" " OPTF 8 8 8 8 7 8 8 8 8 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8\n" " INP 1 -1 0 -1 4 4\n" " RDA All irradiation (IRF and IRP) cards must be between burnup (BUP) " "cards.\n" " BUP\n" " DEC 1.0000000000E+02 1 2 4 2\n" " BUP\n" " OUT 2 1 1 0\n" " END\n" ) assert_equal(observed, expected) def test_parse_tape6(): r = origen22.parse_tape6("tape6.test") assert_true(0 < len(r)) assert_array_equal(r["time_sec"], [0.0, 8.64e06]) assert_array_equal(r["flux"], [0.0, 1.71e17]) assert_array_equal(r["specific_power_MW"], [0.0, 5.50e-01]) assert_array_equal(r["burnup_MWD"], [0.0, 5.50e01]) assert_array_equal(r["k_inf"], [0.0, 0.08498]) assert_array_equal(r["neutron_production_rate"], [0.0, 2.97e-04]) assert_array_equal(r["neutron_destruction_rate"], [0.0, 3.50e-03]) assert_array_equal(r["total_burnup"], [0.0, 5.50e01]) assert_array_equal(r["average_flux"], [0.0, 1.71e17]) assert_array_equal(r["average_specific_power"], [0.0, 5.50e-01]) tab_keys = set( ["table_{0}".format(n) for n in list(range(1, 11)) + list(range(13, 25))] ) assert_true(tab_keys <= set(r)) for tk in tab_keys: for ttype in ["nuclide", "element", "summary"]: if ttype in r[tk]: assert_true( set(r[tk][ttype]) <= set( [ "title", "units", "activation_products", "actinides", "fission_products", ] ) ) assert_array_equal(r["alpha_neutron_source"]["U235"], [7.509e-04, 2.442e-14]) assert_array_equal(r["spont_fiss_neutron_source"]["ES255"], [0.000e00, 1.917e05]) assert_true("materials" in r) assert_equal(len(r["materials"]), len(r["time_sec"])) def test_parse_tape6_PWRM021(): "Originally found at https://typhoon.jaea.go.jp/origen22/sample_pwrmox_orlibj33/PWRM0210.out" r = origen22.parse_tape6("tape6_PWRM0210.test") assert_true(0 < len(r)) assert_array_equal( r["time_sec"], [ 0.00e00, 1.21e07, 2.42e07, 3.63e07, 4.84e07, 6.05e07, 7.26e07, 8.47e07, 9.68e07, 1.09e08, 1.21e08, 1.33e08, ], ) assert_array_equal( r["average_flux"], [ 0.00e00, 3.46e14, 3.46e14, 3.46e14, 3.46e14, 3.46e14, 3.46e14, 3.46e14, 3.46e14, 3.46e14, 3.46e14, 3.46e14, ], ) tab_keys = set(["table_{0}".format(n) for n in [5]]) assert_true(tab_keys <= set(r)) for tk in tab_keys: for ttype in ["nuclide", "element", "summary"]: if ttype in r[tk]: assert_true( set(r[tk][ttype]) <= set( [ "title", "units", "activation_products", "actinides", "fission_products", ] ) ) assert_array_equal( r["alpha_neutron_source"]["CM242"], [ 0.00000e00, 8.50160e08, 1.28411e09, 1.48965e09, 1.57830e09, 1.60855e09, 1.61128e09, 1.60202e09, 1.58856e09, 1.57406e09, 1.55987e09, 1.54529e09, ], ) assert_array_equal( r["spont_fiss_neutron_source"]["PU238"], [ 5.58385e06, 5.52908e06, 5.68992e06, 5.94790e06, 6.24106e06, 6.53804e06, 6.82350e06, 7.09041e06, 7.33580e06, 7.55876e06, 7.75904e06, 7.93683e06, ], ) assert_true("materials" in r) assert_equal(len(r["materials"]), len(r["time_sec"])) def test_parse_tape6_sf97(): """Originally found at https://typhoon.jaea.go.jp/origen22/sample_pwruo2_orlibj33/SF97-4.out""" r = origen22.parse_tape6("tape6_SF97_4.test") assert_true(0 < len(r)) assert_array_equal( r["time_sec"], [1.07e08, 1.11e08, 1.13e08, 1.15e08, 1.16e08, 1.16e08, 1.25e08] ) assert_array_equal( r["k_inf"], [1.17263, 1.16222, 1.15412, 1.14823, 1.14351, 1.14351, 1.14238] ) tab_keys = set(["table_{0}".format(n) for n in [5]]) assert_true(tab_keys <= set(r)) for tk in tab_keys: for ttype in ["nuclide", "element", "summary"]: if ttype in r[tk]: assert_true( set(r[tk][ttype]) <= set( [ "title", "units", "activation_products", "actinides", "fission_products", ] ) ) assert_array_equal( r["alpha_neutron_source"]["PU240"], [ 4.51852e05, 4.62660e05, 4.71046e05, 4.76390e05, 4.81151e05, 4.81151e05, 4.82556e05, ], ) assert_array_equal( r["spont_fiss_neutron_source"]["CM246"], [ 2.78744e06, 3.40763e06, 3.98241e06, 4.41669e06, 4.83645e06, 4.83645e06, 4.83365e06, ], ) assert_true("materials" in r) assert_equal(len(r["materials"]), len(r["time_sec"])) sample_tape9 = """\ 1 SAMPLE DECAY LIB: ACTIVATION PRODUCTS 1 10010 6 0.0 0.0 0.0 0.0 0.0 0.0 1 0.0 0.0 0.0 9.998E+01 1.000E+00 1.000E+00 1 10020 6 0.0 0.0 0.0 0.0 0.0 0.0 1 0.0 0.0 0.0 1.500E-02 1.000E+00 1.000E+00 1 10030 1 3.897E+08 0.0 0.0 0.0 0.0 0.0 1 0.0 0.0 5.680E-03 0.0 2.000E-07 3.000E-03 1 10040 1 1.000E-03 0.0 0.0 0.0 0.0 0.0 1 0.0 0.0 0.0 0.0 3.000E-08 1.000E+00 1 200410 7 8.100E+01 0.0 1.000E+00 0.0 0.0 0.0 1 0.0 0.0 2.700E-03 0.0 1.000E-10 3.000E-06 1 781900 9 6.000E+02 0.0 0.0 0.0 1.000E+00 0.0 1 0.0 0.0 3.250E+00 1.300E-02 2.000E-14 3.000E-08 -1 2 SAMPLE DECAY LIB: ACTINIDES 2 932410 2 1.600E+01 0.0 0.0 0.0 0.0 0.0 2 0.0 0.0 4.710E-01 0.0 3.000E-08 1.000E+00 2 942360 1 8.997E+07 0.0 0.0 0.0 1.000E+00 0.0 2 8.000E-10 0.0 5.871E+00 0.0 6.000E-13 3.000E-05 2 942370 4 4.560E+01 0.0 1.000E+00 0.0 3.300E-05 0.0 2 0.0 0.0 6.220E-02 0.0 2.000E-14 3.000E-08 -1 3 SAMPLE DECAY LIB: FISSION PRODUCTS 3 611460 5 5.500E+00 0.0 6.300E-01 0.0 0.0 0.0 3 0.0 0.0 8.508E-01 0.0 1.000E-10 3.000E-06 3 621460 8 7.000E+01 0.0 0.0 0.0 1.000E+00 0.0 3 0.0 0.0 2.540E+00 0.0 2.000E-14 3.000E-08 3 691720 3 6.360E+01 0.0 0.0 0.0 0.0 0.0 3 0.0 0.0 1.880E+00 0.0 1.000E-10 3.000E-06 -1 381 SAMPLE ACTIVATION PRODUCT XS LIB 381 10010 1.550E-04 0.0 0.0 0.0 0.0 0.0 -1.0 381 10020 3.100E-07 6.757E-04 0.0 0.0 0.0 0.0 -1.0 381 10030 3.510E-09 0.0 0.0 0.0 0.0 0.0 -1.0 381 20030 3.107E+00 0.0 0.0 3.255E+00 0.0 0.0 -1.0 381 30060 1.638E-05 0.0 4.466E-01 7.184E-04 0.0 0.0 -1.0 381 30070 9.100E-06 0.0 4.481E-03 0.0 0.0 0.0 -1.0 381 40090 5.200E-06 3.738E-02 2.168E-02 0.0 0.0 0.0 -1.0 381 40100 5.850E-07 0.0 0.0 0.0 0.0 0.0 -1.0 381 50100 2.925E-04 0.0 2.114E+00 1.566E-03 0.0 0.0 -1.0 381 50110 3.071E-05 6.503E-07 8.573E-06 8.093E-08 0.0 0.0 -1.0 381 60120 3.018E-06 0.0 2.189E-04 4.895E-08 0.0 0.0 -1.0 381 60130 1.690E-06 0.0 4.516E-04 0.0 0.0 0.0 -1.0 381 60140 5.850E-10 0.0 0.0 0.0 0.0 0.0 -1.0 381 70140 4.926E-05 3.198E-07 1.500E-02 1.533E-02 0.0 0.0 -1.0 381 70150 1.315E-05 8.713E-06 2.426E-05 5.091E-06 0.0 0.0 -1.0 381 80160 1.041E-07 0.0 1.364E-03 5.538E-06 0.0 0.0 -1.0 381 80170 7.341E-05 9.378E-06 3.639E-02 3.310E-06 0.0 0.0 -1.0 381 80180 1.053E-06 0.0 2.605E-04 0.0 0.0 0.0 -1.0 -1 382 SAMPLE ACTINIDE XS LIB 382 862200 1.170E-04 0.0 0.0 0.0 0.0 0.0 -1.0 382 862220 4.212E-04 0.0 0.0 0.0 0.0 0.0 -1.0 382 922350 4.202E-01 1.326E-03 1.556E-06 1.637E+00 0.0 0.0 -1.0 382 922360 4.292E-01 1.475E-03 2.529E-05 1.224E-01 0.0 0.0 -1.0 382 922370 3.661E-01 3.986E-03 5.062E-05 6.297E-01 0.0 0.0 -1.0 382 922380 2.125E-01 2.731E-03 2.132E-05 4.976E-02 0.0 0.0 -1.0 -1 383 SAMPLE FISSION PRODUCT YIELD 383 10030 3.510E-09 0.0 0.0 0.0 0.0 0.0 1.0 383 2.00E-02 2.00E-02 2.00E-02 2.30E-02 1.75E-02 1.75E-02 1.75E-02 1.75E-02 383 30060 1.638E-05 0.0 4.466E-01 7.184E-04 0.0 0.0 1.0 383 5.00E-05 5.00E-05 5.00E-05 5.00E-05 5.00E-05 5.00E-05 5.00E-05 5.00E-05 383 30070 9.100E-06 0.0 4.481E-03 0.0 0.0 0.0 1.0 383 1.00E-06 1.00E-06 1.00E-06 1.00E-06 1.00E-06 1.00E-06 1.00E-06 1.00E-06 383 40090 5.200E-06 3.738E-02 2.168E-02 0.0 0.0 0.0 1.0 383 1.50E-06 1.50E-06 1.50E-06 1.50E-06 1.50E-06 1.50E-06 1.50E-06 1.50E-06 383 40100 5.850E-07 0.0 0.0 0.0 0.0 0.0 1.0 383 9.00E-06 9.00E-06 9.00E-06 9.00E-06 9.00E-06 9.00E-06 9.00E-06 9.00E-06 383 60140 5.850E-10 0.0 0.0 0.0 0.0 0.0 1.0 383 1.30E-06 1.30E-06 1.30E-06 1.30E-06 1.30E-06 1.30E-06 1.30E-06 1.30E-06 383 290660 7.897E-02 0.0 0.0 0.0 0.0 0.0 1.0 383 5.97E-12 3.17E-08 9.26E-09 4.12E-10 3.55E-10 1.71E-09 1.68E-09 1.68E-09 383 300660 1.040E-03 0.0 1.193E-08 0.0 0.0 0.0 1.0 383 0.0 0.0 2.55E-11 0.0 0.0 0.0 0.0 0.0 383 300670 2.600E-02 0.0 3.512E-09 0.0 0.0 0.0 1.0 383 0.0 2.50E-09 3.84E-10 4.60E-12 2.14E-11 0.0 0.0 0.0 383 300680 4.001E-03 0.0 1.192E-08 0.0 2.883E-04 0.0 -1.0 383 310690 2.028E-02 0.0 0.0 0.0 0.0 0.0 -1.0 383 300700 4.855E-05 0.0 0.0 0.0 5.091E-06 0.0 -1.0 -1 """ def test_parse_tape9(): tape9_file = StringIO(sample_tape9) tape9 = origen22.parse_tape9(tape9_file) assert_equal(set(tape9), set([1, 2, 3, 381, 382, 383])) # Activation product decay deck1 = tape9[1] assert_equal(deck1["_type"], "decay") assert_equal(deck1["title"], "SAMPLE DECAY LIB: ACTIVATION PRODUCTS") assert_equal(deck1["half_life"][10020], np.inf) assert_equal(deck1["half_life"][10040], 1.000e-03) assert_equal(deck1["half_life"][200410], 8.100e01 * 31556926.0 * 1e3) assert_equal(deck1["half_life"][781900], 6.000e02 * 31556926.0 * 1e9) assert_equal(deck1["frac_beta_minus_x"][10010], 0.0) assert_equal(deck1["frac_beta_plus_or_electron_capture"][200410], 1.0) assert_equal(deck1["frac_beta_plus_or_electron_capture_x"][10010], 0.0) assert_equal(deck1["frac_alpha"][781900], 1.0) assert_equal(deck1["frac_isomeric_transition"][10020], 0.0) assert_equal(deck1["frac_spont_fiss"][10020], 0.0) assert_equal(deck1["frac_beta_n"][10020], 0.0) assert_equal(deck1["recoverable_energy"][10030], 5.680e-03) assert_equal(deck1["frac_natural_abund"][10020], 1.500e-02 * 0.01) assert_equal(deck1["inhilation_concentration"][781900], 2.000e-14) assert_equal(deck1["ingestion_concentration"][781900], 3.000e-08) # Actinide Decay deck2 = tape9[2] assert_equal(deck2["_type"], "decay") assert_equal(deck2["title"], "SAMPLE DECAY LIB: ACTINIDES") assert_equal(deck2["half_life"][932410], 1.600e01 * 60.0) assert_equal(deck2["half_life"][942370], 4.560e01 * 86400.0) # Fission Product Decay deck3 = tape9[3] assert_equal(deck3["_type"], "decay") assert_equal(deck3["title"], "SAMPLE DECAY LIB: FISSION PRODUCTS") assert_equal(deck3["half_life"][611460], 5.500e00 * 31556926.0) assert_equal(deck3["half_life"][621460], 7.000e01 * 31556926.0 * 1e6) assert_equal(deck3["half_life"][691720], 6.360e01 * 3600.0) # Activation product cross sections deck381 = tape9[381] assert_equal(deck381["_type"], "xsfpy") assert_equal(deck381["_subtype"], "activation_products") assert_equal(deck381["title"], "SAMPLE ACTIVATION PRODUCT XS LIB") assert_true(all(["_fiss_yield" not in key for key in deck381])) assert_true("sigma_alpha" in deck381) assert_true("sigma_3n" not in deck381) assert_true("sigma_p" in deck381) assert_true("sigma_f" not in deck381) assert_equal(deck381["sigma_gamma"][80170], 7.341e-05) assert_equal(deck381["sigma_2n"][80170], 9.378e-06) assert_equal(deck381["sigma_alpha"][80170], 3.639e-02) assert_equal(deck381["sigma_p"][80170], 3.310e-06) assert_equal(deck381["sigma_gamma_x"][80170], 0.0) assert_equal(deck381["sigma_2n_x"][80170], 0.0) assert_equal(deck381["fiss_yields_present"][80170], False) # Actinide cross sections deck382 = tape9[382] assert_equal(deck382["_type"], "xsfpy") assert_equal(deck382["_subtype"], "actinides") assert_equal(deck382["title"], "SAMPLE ACTINIDE XS LIB") assert_true(all(["_fiss_yield" not in key for key in deck382])) assert_true("sigma_alpha" not in deck382) assert_true("sigma_3n" in deck382) assert_true("sigma_p" not in deck382) assert_true("sigma_f" in deck382) assert_equal(deck382["sigma_gamma"][922380], 2.125e-01) assert_equal(deck382["sigma_2n"][922380], 2.731e-03) assert_equal(deck382["sigma_3n"][922380], 2.132e-05) assert_equal(deck382["sigma_f"][922380], 4.976e-02) assert_equal(deck382["sigma_gamma_x"][922380], 0.0) assert_equal(deck382["sigma_2n_x"][922380], 0.0) assert_equal(deck382["fiss_yields_present"][922380], False) # Fission product cross sections deck383 = tape9[383] assert_equal(deck383["_type"], "xsfpy") assert_equal(deck383["_subtype"], "fission_products") assert_equal(deck383["title"], "SAMPLE FISSION PRODUCT YIELD") assert_true(any(["_fiss_yield" in key for key in deck383])) assert_true("sigma_alpha" in deck383) assert_true("sigma_3n" not in deck383) assert_true("sigma_p" in deck383) assert_true("sigma_f" not in deck383) assert_equal(deck383["sigma_gamma"][300670], 2.600e-02) assert_equal(deck383["sigma_2n"][300670], 0.0) assert_equal(deck383["sigma_alpha"][300670], 3.512e-09) assert_equal(deck383["sigma_p"][300670], 0.0) assert_equal(deck383["sigma_gamma_x"][300670], 0.0) assert_equal(deck383["sigma_2n_x"][300670], 0.0) assert_equal(deck383["fiss_yields_present"][300670], True) assert_equal(deck383["TH232_fiss_yield"][300670], 0.0) assert_equal(deck383["U233_fiss_yield"][300670], 2.50e-09) assert_equal(deck383["U235_fiss_yield"][300670], 3.84e-10) assert_equal(deck383["U238_fiss_yield"][300670], 4.60e-12) assert_equal(deck383["PU239_fiss_yield"][300670], 2.14e-11) assert_equal(deck383["PU241_fiss_yield"][300670], 0.0) assert_equal(deck383["CM245_fiss_yield"][300670], 0.0) assert_equal(deck383["CF249_fiss_yield"][300670], 0.0) def test_loads_tape9(): tape9 = origen22.loads_tape9(sample_tape9) assert_equal(set(tape9), set([1, 2, 3, 381, 382, 383])) def test_merge_tape9(): tape9_file = StringIO(sample_tape9) tape9_file = origen22.parse_tape9(tape9_file) tape9_dict = { 1: {"_type": "decay", "half_life": {10010: 42.0}}, 2: {"_type": "decay", "_bad_key": None}, 3: {"_type": "decay", "title": "Sweet Decay"}, 382: {"_type": "xsfpy", "_subtype": "actinides", "sigma_f": {922350: 16.0}}, } # merge so that dict takes precedence tape9 = origen22.merge_tape9([tape9_dict, tape9_file]) # run tests assert_equal(tape9[1]["half_life"][10010], 42.0) assert_true("_bad_key" in tape9[2]) assert_equal(tape9[3]["title"], "Sweet Decay") assert_equal(tape9[382]["sigma_f"][922350], 16.0) assert_true("_cards" not in tape9[1]) assert_true("_cards" not in tape9[2]) assert_true("_cards" not in tape9[3]) assert_true("_cards" in tape9[381]) assert_true("_cards" not in tape9[382]) assert_true("_cards" in tape9[383]) def test_write_tape9(): tape9_file = StringIO() tape9_dict = { 1: {"_type": "decay", "half_life": {10010: 42.0}, "title": "decay1"}, 2: { "_type": "decay", "_bad_key": None, "title": "decay2", "half_life": {922350: 42.0}, }, 3: { "_type": "decay", "title": "Sweet Decay", "half_life": {10010: 42.0, 421000: 42.0}, }, 381: { "_type": "xsfpy", "_subtype": "activation_products", "sigma_gamma": {10010: 12.0}, "title": "xs1", }, 382: { "_type": "xsfpy", "_subtype": "actinides", "sigma_f": {922350: 16.0}, "title": "xs2", }, 383: { "_type": "xsfpy", "_subtype": "fission_products", "sigma_gamma": {10010: 20.0}, "title": "xsfpy3", "U235_fiss_yield": {421000: 42.0}, "fiss_yields_present": {421000: True}, }, } # Test that basic functionality works origen22.write_tape9(tape9_dict, tape9_file) tape9_file.seek(0) t9str = tape9_file.readlines() for line in t9str: assert len(line) <= 81 # 81 since newline is counted in len # Try to round-trip full_tape9_file = StringIO(sample_tape9) full_tape9 = origen22.parse_tape9(full_tape9_file) backout_tape9 = StringIO() origen22.write_tape9(full_tape9, backout_tape9) backout_tape9.seek(0) backin_tape9 = origen22.parse_tape9(backout_tape9) def test_xslibs(): exp = { 42: { "_type": "xsfpy", "_subtype": "activation_products", "title": "PyNE Cross Section Data for Activation Products", }, 43: { "_type": "xsfpy", "_subtype": "actinides", "title": "PyNE Cross Section Data for Actinides & Daughters", }, 44: { "_type": "xsfpy", "_subtype": "fission_products", "title": "PyNE Cross Section Data for Fission Products", }, } xsc = XSCache(data_sources=[NullDataSource]) nucs = [922350000, 10010000, 461080000] obs = origen22.xslibs(nucs=nucs, xscache=xsc, nlb=(42, 43, 44)) obs_meta = {} for n in exp: obs_meta[n] = {} for field in ["_type", "_subtype", "title"]: obs_meta[n][field] = obs[n][field] assert_equal(exp, obs_meta) for n in exp: for field in obs[n]: if not field.startswith("sigma_"): continue assert_true(all([v == 0.0 for v in obs[n][field].values()])) assert_true( set(obs[42].keys()) >= set(origen22.ACTIVATION_PRODUCT_FIELDS + origen22.XSFPY_FIELDS) ) assert_true( set(obs[43].keys()) >= set(origen22.ACTINIDE_FIELDS + origen22.XSFPY_FIELDS) ) assert_true( set(obs[44].keys()) >= set(origen22.FISSION_PRODUCT_FIELDS + origen22.XSFPY_FIELDS) ) def test_nlbs(): exp = (1, 2, 3), (42, 43, 44) t9 = { 42: {"_type": "xsfpy", "_subtype": "activation_products"}, 43: {"_type": "xsfpy", "_subtype": "actinides"}, 44: {"_type": "xsfpy", "_subtype": "fission_products"}, 1: {"_type": "decay"}, 2: {"_type": "decay"}, 3: {"_type": "decay"}, } obs = origen22.nlbs(t9) assert_equal(exp, obs) def test_tape9_dict_structure(): nucs = ["U233", "U234", "U235", "U236", "U238"] tape9 = origen22.make_tape9(nucs, nlb=(219, 220, 221)) # check for correct deck ids: 1,2,3 for decay, 219, 220, 221 for xsfpy assert_equal(set(list(tape9.keys())), {1, 2, 3, 219, 220, 221}) # check decay decks for correct structure for field in origen22.DECAY_FIELDS: assert_in(field, tape9[1].keys()) assert_in(field, tape9[2].keys()) assert_in(field, tape9[3].keys()) # check to see if the values are float-valued dicts assert_is_instance(tape9[1][field], dict) for value in tape9[1][field].values(): assert_is_instance(value, float) assert_is_instance(tape9[2][field], dict) for value in tape9[2][field].values(): assert_is_instance(value, float) assert_is_instance(tape9[3][field], dict) for value in tape9[3][field].values(): assert_is_instance(value, float) # check xsfpy decks for correct structure for field in origen22.XSFPY_FIELDS: assert_in(field, tape9[219].keys()) assert_in(field, tape9[220].keys()) assert_in(field, tape9[221].keys()) # check to see if the values are float-valued dicts assert_is_instance(tape9[219][field], dict) for value in tape9[219][field].values(): if value == "fiss_yields_present": # except for these bool-valued dicts assert_is_instance(value, bool) else: assert_is_instance(value, float) assert_is_instance(tape9[220][field], dict) for value in tape9[220][field].values(): if field == "fiss_yields_present": assert_is_instance(value, bool) else: assert_is_instance(value, float) for value in tape9[221][field].values(): if value == "fiss_yields_present": assert_is_instance(value, bool) else: assert_is_instance(value, float) # check activation product deck for correct structure for field in origen22.ACTIVATION_PRODUCT_FIELDS: assert_in(field, tape9[219].keys()) # make sure everything's a float-valued dict assert_is_instance(tape9[219][field], dict) for value in tape9[219][field].values(): assert_is_instance(value, float) # check actinide deck for correct structure for field in origen22.ACTINIDE_FIELDS: assert_in(field, tape9[220].keys()) # make sure everything's a float-valued dict assert_is_instance(tape9[220][field], dict) for value in tape9[220][field].values(): assert_is_instance(value, float) # check fission product deck for correct structure for field in origen22.FISSION_PRODUCT_FIELDS: assert_in(field, tape9[221].keys()) # make sure everything's a float-valued dict assert_is_instance(tape9[221][field], dict) for value in tape9[221][field].values(): assert_is_instance(value, float)
buseorak/school-assignments
BBM104/assignment2/src/StuntPerformer.java
import java.util.ArrayList; public class StuntPerformer extends Performer { // Fields private final double HEIGHT; private final ArrayList<Integer> REAL_ACTOR_IDS; public static ArrayList<StuntPerformer> stuntPerformersArray = new ArrayList<>(); // Constructor public StuntPerformer(int id, String name, String surname, String country, double height, ArrayList<Integer> reals) { super(id, name, surname, country); HEIGHT = height; REAL_ACTOR_IDS = reals; } // Getter protected double getHEIGHT() { return HEIGHT; } }
XSoyOscar/Algorithms
leetcode.com/python/111_Minimum_Depth_of_Binary_Tree.py
<gh_stars>100-1000 import collections # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): # Solution 1: Recursive DFS # def minDepth(self, root): # """ # :type root: TreeNode # :rtype: int # """ # if not root: # return 0 # leftDepth = self.minDepth(root.left) # rightDepth = self.minDepth(root.right) # if not root.left or not root.right: # return max(leftDepth, rightDepth) + 1 # I'm trying to understand the use of max() in the DFS version. I think it's because if one of the node's children is None then in the next recursive call it would return zero but you don't want to count that because you know it is not actually a leaf so the max gets rid of the incorrect zero. # else: # return min(leftDepth, rightDepth) + 1 # Solution 2: Iterative DFS # def minDepth(self, root): # """ # :type root: TreeNode # :rtype: int # """ # if not root: # return 0 # result, stack = float("inf"), [(root, 1)] # while stack: # node, level = stack.pop() # if node and not node.left and not node.right: # result = min(result, level) # if node: # stack.append((node.left, level + 1)) # stack.append((node.right, level + 1)) # return result # Solution 3: Iterative BFS def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 result = 9999 queue = collections.deque([(root, 1)]) while queue: node, level = queue.popleft() if node and not node.left and not node.right: result = min(result, level) if node: queue.append((node.left, level + 1)) queue.append((node.right, level + 1)) return result
vishnudevk/MiBandDecompiled
Original Files/source/src/com/tencent/connect/avatar/a.java
<filename>Original Files/source/src/com/tencent/connect/avatar/a.java // Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.tencent.connect.avatar; // Referenced classes of package com.tencent.connect.avatar: // ImageActivity class a implements Runnable { final String a; final int b; final ImageActivity c; a(ImageActivity imageactivity, String s, int i) { c = imageactivity; a = s; b = i; super(); } public void run() { ImageActivity.a(c, a, b); } }
antonio-te/teleport
lib/srv/app/listener.go
/* Copyright 2020 Gravitational, 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 app import ( "context" "net" "github.com/gravitational/trace" ) // listener wraps a net.Conn in a net.Listener interface. This allows passing // a channel connection from the reverse tunnel subsystem to an HTTP server. type listener struct { connCh chan net.Conn localAddr net.Addr closeContext context.Context closeFunc context.CancelFunc } // newListener creates a new wrapping listener. func newListener(ctx context.Context, conn net.Conn) *listener { closeContext, closeFunc := context.WithCancel(ctx) connCh := make(chan net.Conn, 1) connCh <- conn return &listener{ connCh: connCh, localAddr: conn.LocalAddr(), closeContext: closeContext, closeFunc: closeFunc, } } // Accept returns the connection. func (l *listener) Accept() (net.Conn, error) { select { case conn := <-l.connCh: return conn, nil case <-l.closeContext.Done(): return nil, trace.BadParameter("closing context") } } // Close closes the connection. func (l *listener) Close() error { l.closeFunc() return l.closeContext.Err() } // Addr returns the address of the connection. func (l *listener) Addr() net.Addr { return l.localAddr }
vnys/radix-web-console
src/state/deployments/index.js
<gh_stars>1-10 import get from 'lodash/get'; export const getDeployments = (state) => get(state, 'deployments', []);
networkmodeling/V2X-Hub
src/tmx/Asn_J2735/src/r63/IntersectionState-addGrpC.c
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "AddGrpC" * found in "../J2735_201603DA.ASN" * `asn1c -gen-PER -fcompound-names -fincludes-quoted -S/home/gmb/TMX-OAM/Build/asn1c/skeletons` */ #include "IntersectionState-addGrpC.h" static asn_TYPE_member_t asn_MBR_IntersectionState_addGrpC_1[] = { { ATF_POINTER, 1, offsetof(struct IntersectionState_addGrpC, activePrioritizations), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_PrioritizationResponseList, 0, 0, /* Defer constraints checking to the member type */ 0, /* OER is not compiled, use -gen-OER */ 0, /* No PER visible constraints */ 0, "activePrioritizations" }, }; static const int asn_MAP_IntersectionState_addGrpC_oms_1[] = { 0 }; static const ber_tlv_tag_t asn_DEF_IntersectionState_addGrpC_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_IntersectionState_addGrpC_tag2el_1[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 } /* activePrioritizations */ }; static asn_SEQUENCE_specifics_t asn_SPC_IntersectionState_addGrpC_specs_1 = { sizeof(struct IntersectionState_addGrpC), offsetof(struct IntersectionState_addGrpC, _asn_ctx), asn_MAP_IntersectionState_addGrpC_tag2el_1, 1, /* Count of tags in the map */ asn_MAP_IntersectionState_addGrpC_oms_1, /* Optional members */ 1, 0, /* Root/Additions */ 0, /* Start extensions */ 2 /* Stop extensions */ }; asn_TYPE_descriptor_t asn_DEF_IntersectionState_addGrpC = { "IntersectionState-addGrpC", "IntersectionState-addGrpC", &asn_OP_SEQUENCE, SEQUENCE_constraint, asn_DEF_IntersectionState_addGrpC_tags_1, sizeof(asn_DEF_IntersectionState_addGrpC_tags_1) /sizeof(asn_DEF_IntersectionState_addGrpC_tags_1[0]), /* 1 */ asn_DEF_IntersectionState_addGrpC_tags_1, /* Same as above */ sizeof(asn_DEF_IntersectionState_addGrpC_tags_1) /sizeof(asn_DEF_IntersectionState_addGrpC_tags_1[0]), /* 1 */ 0, /* No OER visible constraints */ 0, /* No PER visible constraints */ asn_MBR_IntersectionState_addGrpC_1, 1, /* Elements count */ &asn_SPC_IntersectionState_addGrpC_specs_1 /* Additional specs */ };
IvarJonsson/Project-Unknown
ScriptControlledPhysics.cpp
<reponame>IvarJonsson/Project-Unknown // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. /************************************************************************* ------------------------------------------------------------------------- $Id$ $DateTime$ ------------------------------------------------------------------------- History: - 26:7:2007 17:01 : Created by <NAME> *************************************************************************/ #include "StdAfx.h" #include "ScriptControlledPhysics.h" namespace SCP { void RegisterEvents( IGameObjectExtension& goExt, IGameObject& gameObject ) { const int eventID = eGFE_OnPostStep; gameObject.UnRegisterExtForEvents( &goExt, NULL, 0 ); gameObject.RegisterExtForEvents( &goExt, &eventID, 1 ); } } //------------------------------------------------------------------------ CScriptControlledPhysics::CScriptControlledPhysics() : m_moving(false) , m_moveTarget(ZERO) , m_lastVelocity(ZERO) , m_speed(0.0f) , m_maxSpeed(0.0f) , m_acceleration(0.0f) , m_stopTime(1.0f) , m_rotating(false) , m_rotationTarget(IDENTITY) , m_rotationSpeed(0.0f) , m_rotationMaxSpeed(0.0f) , m_rotationAcceleration(0.0f) , m_rotationStopTime(0.0f) { } //------------------------------------------------------------------------ CScriptControlledPhysics::~CScriptControlledPhysics() { } //------------------------------------------------------------------------ void CScriptControlledPhysics::RegisterGlobals() { } //------------------------------------------------------------------------ void CScriptControlledPhysics::RegisterMethods() { #undef SCRIPT_REG_CLASSNAME #define SCRIPT_REG_CLASSNAME &CScriptControlledPhysics:: SCRIPT_REG_TEMPLFUNC(Reset, ""); SCRIPT_REG_TEMPLFUNC(GetSpeed, ""); SCRIPT_REG_TEMPLFUNC(GetAcceleration, ""); SCRIPT_REG_TEMPLFUNC(GetAngularSpeed, ""); SCRIPT_REG_TEMPLFUNC(GetAngularAcceleration, ""); SCRIPT_REG_TEMPLFUNC(MoveTo, "point, initialSpeed, speed, acceleration, stopTime"); SCRIPT_REG_TEMPLFUNC(RotateTo, "dir, roll, initialSpeed, speed, acceleration, stopTime"); SCRIPT_REG_TEMPLFUNC(RotateToAngles, "angles, initialSpeed, speed, acceleration, stopTime"); SCRIPT_REG_TEMPLFUNC(HasArrived, ""); } //------------------------------------------------------------------------ bool CScriptControlledPhysics::Init(IGameObject * pGameObject ) { CScriptableBase::Init(gEnv->pScriptSystem, gEnv->pSystem, 1); SetGameObject(pGameObject); pGameObject->EnablePhysicsEvent(true, eEPE_OnPostStepImmediate); RegisterGlobals(); RegisterMethods(); SmartScriptTable thisTable(gEnv->pScriptSystem); thisTable->SetValue("__this", ScriptHandle(GetEntityId())); thisTable->Delegate(GetMethodsTable()); GetEntity()->GetScriptTable()->SetValue("scp", thisTable); return true; } //------------------------------------------------------------------------ void CScriptControlledPhysics::Release() { delete this; } void CScriptControlledPhysics::FullSerialize( TSerialize ser ) { ser.Value("m_moving", m_moving); ser.Value("m_moveTarget", m_moveTarget); ser.Value("m_speed", m_speed); ser.Value("m_maxSpeed", m_maxSpeed); ser.Value("m_acceleration", m_acceleration); ser.Value("m_stopTime", m_stopTime); ser.Value("m_rotating", m_rotating); ser.Value("m_rotationTarget", m_rotationTarget); ser.Value("m_rotationSpeed", m_rotationSpeed); ser.Value("m_rotationMaxSpeed", m_rotationMaxSpeed); ser.Value("m_rotationAcceleration", m_rotationAcceleration); ser.Value("m_rotationStopTime", m_rotationStopTime); } //------------------------------------------------------------------------ void CScriptControlledPhysics::PostInit( IGameObject * pGameObject ) { if (IPhysicalEntity *pPE=GetEntity()->GetPhysics()) { SCP::RegisterEvents(*this,*pGameObject); pe_params_flags fp; fp.flagsOR = pef_monitor_poststep; pPE->SetParams(&fp); } } //------------------------------------------------------------------------ bool CScriptControlledPhysics::ReloadExtension( IGameObject * pGameObject, const SEntitySpawnParams &params ) { ResetGameObject(); if (IPhysicalEntity *pPE=GetEntity()->GetPhysics()) { SCP::RegisterEvents(*this,*pGameObject); } else { pGameObject->UnRegisterExtForEvents( this, NULL, 0 ); } CRY_ASSERT_MESSAGE(false, "CScriptControlledPhysics::ReloadExtension not implemented"); return false; } //------------------------------------------------------------------------ bool CScriptControlledPhysics::GetEntityPoolSignature( TSerialize signature ) { CRY_ASSERT_MESSAGE(false, "CScriptControlledPhysics::GetEntityPoolSignature not implemented"); return true; } //------------------------------------------------------------------------ void CScriptControlledPhysics::HandleEvent(const SGameObjectEvent& event) { switch(event.event) { case eGFE_OnPostStep: OnPostStep((EventPhysPostStep *)event.ptr); break; } } //------------------------------------------------------------------------ void CScriptControlledPhysics::OnPostStep(EventPhysPostStep *pPostStep) { pe_action_set_velocity av; const bool moving = m_moving; const bool rotating = m_rotating; const float deltaTime = pPostStep->dt; if (m_moving) { const Vec3 current = pPostStep->pos; const Vec3 target = m_moveTarget; const Vec3 delta = target - current; const float distanceSq = delta.len2(); if (distanceSq <= sqr(0.025f) || (delta.dot(m_lastVelocity) < 0.0f)) { m_speed = 0.0f; m_moving = false; m_lastVelocity.zero(); pPostStep->pos = target; av.v = ZERO; } else { float velocity = m_speed; float acceleration = m_acceleration; Vec3 direction = delta; const float distanceToEnd = direction.NormalizeSafe(); // Accelerate velocity = std::min(velocity + acceleration * deltaTime, m_maxSpeed); // Calculate acceleration and time needed to stop const float accelerationNeededToStop = (-(velocity*velocity) / distanceToEnd) / 2; if (fabsf(accelerationNeededToStop) > 0.0f) { const float timeNeededToStop = sqrtf((distanceToEnd / 0.5f) / fabsf(accelerationNeededToStop)); if (timeNeededToStop < m_stopTime) { acceleration = accelerationNeededToStop; } } // Prevent overshooting if ((velocity * deltaTime) > distanceToEnd) { const float multiplier = distanceToEnd / fabsf(velocity * deltaTime); velocity *= multiplier; acceleration *= multiplier; } m_acceleration = acceleration; m_speed = velocity; m_lastVelocity = direction * velocity; av.v = direction * velocity; } } if (m_rotating) { Quat current=pPostStep->q; Quat target=m_rotationTarget; Quat rotation=target*!current; float angle=acos_tpl(CLAMP(rotation.w, -1.0f, 1.0f))*2.0f; float original=angle; if (angle>gf_PI) angle=angle-gf_PI2; else if (angle<-gf_PI) angle=angle+gf_PI2; if (fabs_tpl(angle)<0.01f) { m_rotationSpeed=0.0f; m_rotating=false; pPostStep->q=m_rotationTarget; av.w=ZERO; } else { float a=m_rotationSpeed/m_rotationStopTime; float d=m_rotationSpeed*m_stopTime-0.5f*a*m_rotationStopTime*m_rotationStopTime; if (fabs_tpl(angle)<d+0.001f) m_rotationAcceleration=(angle-m_rotationSpeed*m_rotationStopTime)/(m_rotationStopTime*m_rotationStopTime); m_rotationSpeed=m_rotationSpeed+sgn(angle)*m_rotationAcceleration*deltaTime; if (fabs_tpl(m_rotationSpeed*deltaTime)>fabs_tpl(angle)) m_rotationSpeed=angle/deltaTime; else if (fabs_tpl(m_rotationSpeed)<0.001f) m_rotationSpeed=sgn(m_rotationSpeed)*0.001f; else if (fabs_tpl(m_rotationSpeed)>=m_rotationMaxSpeed) { m_rotationSpeed=sgn(m_rotationSpeed)*m_rotationMaxSpeed; m_rotationAcceleration=0.0f; } } if(fabs_tpl(angle)>=0.001f) av.w=(rotation.v/sin_tpl(original*0.5f)).normalized(); av.w*=m_rotationSpeed; } if (moving || rotating) { if (IPhysicalEntity *pPE=GetEntity()->GetPhysics()) pPE->Action(&av, 1); } /* if ((moving && !m_moving) || (rotating && !m_rotating)) GetEntity()->SetWorldTM(Matrix34::Create(GetEntity()->GetScale(), pPostStep->q, pPostStep->pos)); */ } //------------------------------------------------------------------------ int CScriptControlledPhysics::Reset(IFunctionHandler *pH) { m_moving = false; m_moveTarget.zero(); m_lastVelocity.zero(); m_speed = 0.0f; m_maxSpeed = 0.0f; m_acceleration = 0.0f; m_stopTime = 1.0f; m_rotating = false; m_rotationTarget.SetIdentity(); m_rotationSpeed = 0.0f; m_rotationMaxSpeed = 0.0f; m_rotationAcceleration = 0.0f; m_rotationStopTime = 0.0f; return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptControlledPhysics::GetSpeed(IFunctionHandler *pH) { return pH->EndFunction(m_speed); } //------------------------------------------------------------------------ int CScriptControlledPhysics::GetAcceleration(IFunctionHandler *pH) { return pH->EndFunction(m_acceleration); } //------------------------------------------------------------------------ int CScriptControlledPhysics::GetAngularSpeed(IFunctionHandler *pH) { return pH->EndFunction(m_rotationSpeed); } //------------------------------------------------------------------------ int CScriptControlledPhysics::GetAngularAcceleration(IFunctionHandler *pH) { return pH->EndFunction(m_rotationAcceleration); } //------------------------------------------------------------------------ int CScriptControlledPhysics::MoveTo(IFunctionHandler *pH, Vec3 point, float initialSpeed, float speed, float acceleration, float stopTime) { m_moveTarget=point; m_lastVelocity.zero(); m_moving=true; m_speed=initialSpeed; m_maxSpeed=speed; m_acceleration=acceleration; m_stopTime=max(0.05f, stopTime); pe_action_awake aa; aa.bAwake=1; if (IPhysicalEntity *pPE=GetEntity()->GetPhysics()) pPE->Action(&aa); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptControlledPhysics::RotateTo(IFunctionHandler *pH, Vec3 dir, float roll, float initialSpeed, float speed, float acceleration, float stopTime) { m_rotationTarget=Quat::CreateRotationVDir(dir, roll); m_rotating=true; m_rotationSpeed=DEG2RAD(initialSpeed); m_rotationMaxSpeed=DEG2RAD(speed); m_rotationAcceleration=DEG2RAD(acceleration); m_rotationStopTime=stopTime; pe_action_awake aa; aa.bAwake=1; if (IPhysicalEntity *pPE=GetEntity()->GetPhysics()) pPE->Action(&aa); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptControlledPhysics::RotateToAngles(IFunctionHandler *pH, Vec3 angles, float initialSpeed, float speed, float acceleration, float stopTime) { m_rotationTarget=Quat::CreateRotationXYZ(Ang3(angles)); m_rotating=true; m_rotationSpeed=DEG2RAD(initialSpeed); m_rotationMaxSpeed=DEG2RAD(speed); m_rotationAcceleration=DEG2RAD(acceleration); m_rotationStopTime=stopTime; pe_action_awake aa; aa.bAwake=1; if (IPhysicalEntity *pPE=GetEntity()->GetPhysics()) pPE->Action(&aa); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptControlledPhysics::HasArrived(IFunctionHandler *pH) { return pH->EndFunction(!m_moving); } //------------------------------------------------------------------------ void CScriptControlledPhysics::GetMemoryUsage(ICrySizer *pSizer) const { pSizer->AddObject(this,sizeof(*this)); }
inket/smartPins
classdump_SafariShared/WBSFeedEntry.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <objc/NSObject.h> #import <SafariShared/NSSecureCoding-Protocol.h> @class NSDate, NSString; @interface WBSFeedEntry : NSObject <NSSecureCoding> { NSString *_identifier; NSString *_urlString; NSString *_title; NSString *_entryDescription; NSString *_content; NSDate *_datePublished; NSDate *_dateUpdated; } + (BOOL)supportsSecureCoding; + (id)feedEntryWithAtomFeedElement:(id)arg1; + (id)feedEntryWithRSSFeedElement:(id)arg1; + (id)dateFromAtomDateString:(id)arg1; + (id)dateFromRSSDateString:(id)arg1; @property(copy, nonatomic) NSDate *dateUpdated; // @synthesize dateUpdated=_dateUpdated; @property(copy, nonatomic) NSDate *datePublished; // @synthesize datePublished=_datePublished; @property(copy, nonatomic) NSString *content; // @synthesize content=_content; @property(copy, nonatomic) NSString *entryDescription; // @synthesize entryDescription=_entryDescription; @property(copy, nonatomic) NSString *title; // @synthesize title=_title; @property(readonly, copy, nonatomic) NSString *urlString; // @synthesize urlString=_urlString; @property(readonly, copy, nonatomic) NSString *identifier; // @synthesize identifier=_identifier; - (void).cxx_destruct; - (id)description; - (void)encodeWithCoder:(id)arg1; - (id)initWithCoder:(id)arg1; - (id)initWithIdentifier:(id)arg1 urlString:(id)arg2; @end
acabra85/bec-techacademy
007-learn-apache-kafka/producer/src/main/java/dk/bec/gradprogram/kafka/ProducerProperties.java
<reponame>acabra85/bec-techacademy package dk.bec.gradprogram.kafka; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringSerializer; import java.util.Properties; public class ProducerProperties { public static final String BOOTSTRAP_SERVERS = "127.0.0.1:9092"; public static Properties createProperties() { Properties properties = new Properties(); properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS); properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); return properties; } }
zann1x/FrameGraph
tests/offline_compiler/Test_Serializer2.cpp
// Copyright (c) 2018-2019, <NAME>. For more information see 'LICENSE' #include "Utils.h" #include "pipeline_compiler/PipelineCppSerializer.h" extern void Test_Serializer2 (VPipelineCompiler* compiler) { ComputePipelineDesc ppln; ppln.AddShader( EShaderLangFormat::GLSL_450, "main", R"#( #pragma shader_stage(compute) #extension GL_ARB_separate_shader_objects : enable layout (local_size_x=16, local_size_y=8, local_size_z=1) in; layout (push_constant, std140) uniform PushConst { vec4 f0; float f1; vec2 f2; } pc; layout(binding=0, rgba8) writeonly uniform image2D un_OutImage; layout(binding=1, std140) readonly buffer un_SSBO { vec4 ssb_data; }; void main () { vec2 uv = vec2(gl_GlobalInvocationID.xy) / vec2((gl_WorkGroupSize * gl_NumWorkGroups).xy); vec4 fragColor = vec4(sin(uv.x), cos(uv.y), 1.0, ssb_data.r); imageStore( un_OutImage, ivec2(gl_GlobalInvocationID.xy), fragColor ); } )#" ); TEST( compiler->Compile( INOUT ppln, EShaderLangFormat::SPIRV_100 )); ppln._shader.data.clear(); PipelineCppSerializer serializer; String src; TEST( serializer.Serialize( ppln, "default", OUT src )); const String serialized_ref = R"##(CPipelineID Create_default (const FGThreadPtr &fg) { ComputePipelineDesc desc; desc.SetLocalGroupSize( 16, 8, 1 ); desc.AddDescriptorSet( DescriptorSetID{"0"}, 0, {}, {}, {}, {{ UniformID{"un_OutImage"}, EImage::Tex2D, EPixelFormat::RGBA8_UNorm, EShaderAccess::WriteOnly, BindingIndex{UMax, 0u}, EShaderStages::Compute }}, {}, {{ UniformID{"un_SSBO"}, 16_b, 0_b, EShaderAccess::ReadOnly, BindingIndex{UMax, 1u}, EShaderStages::Compute }} ); desc.SetPushConstants({ {PushConstantID("PushConst"), EShaderStages::Compute, 0_b, 32_b}}); return fg->CreatePipeline( std::move(desc) ); } )##"; TEST( serialized_ref == src ); FG_LOGI( "Test_Serializer2 - passed" ); }
maciejg-git/vue-bootstrap-icons
dist-mdi/mdi/video-switch.js
import { h } from 'vue' export default { name: "VideoSwitch", vendor: "Mdi", type: "", tags: ["video","switch"], render() { return h( "svg", {"xmlns":"http://www.w3.org/2000/svg","width":"24","height":"24","viewBox":"0 0 24 24","class":"v-icon","fill":"currentColor","data-name":"mdi-video-switch","innerHTML":"<path d='M13,15.5V13H7V15.5L3.5,12L7,8.5V11H13V8.5L16.5,12M18,9.5V6A1,1 0 0,0 17,5H3A1,1 0 0,0 2,6V18A1,1 0 0,0 3,19H17A1,1 0 0,0 18,18V14.5L22,18.5V5.5L18,9.5Z' />"}, ) } }
MarcoBuster/university
Programmazione_1/2020-11-02/conta-a-continuo.go
package main import ( "bufio" "fmt" "os" ) func main() { var s string b := bufio.NewScanner(os.Stdin) for b.Scan() { // Leggo una riga s = b.Text() // Conto usando il contatore c i caratteri a nella riga c := 0 for _, r := range s { if r == 'a' { c++ } } fmt.Println(c) } }
xqbase/net
proxy/src/main/java/com/xqbase/tuna/proxy/PeerConnection.java
package com.xqbase.tuna.proxy; import com.xqbase.tuna.Connection; import com.xqbase.tuna.ConnectionHandler; import com.xqbase.tuna.ConnectionSession; import com.xqbase.util.Log; abstract class PeerConnection implements Connection { static final int LOG_DEBUG = ProxyConnection.LOG_DEBUG; static final int LOG_VERBOSE = ProxyConnection.LOG_VERBOSE; ProxyServer server; ProxyConnection proxy; ConnectionHandler proxyHandler, handler; boolean connected, disconnected = false; int logLevel; String remote, local = " / 0.0.0.0:0"; PeerConnection(ProxyServer server, ProxyConnection proxy, int logLevel) { this.server = server; this.proxy = proxy; this.logLevel = logLevel; proxyHandler = proxy.getHandler(); } String toString(boolean resp) { return (proxy == null ? "0.0.0.0:0" : proxy.remote) + local + (resp ? " <= " : " => ") + remote; } @Override public void setHandler(ConnectionHandler handler) { this.handler = handler; } @Override public void onQueue(int size) { proxyHandler.setBufferSize(size == 0 ? MAX_BUFFER_SIZE : 0); if (logLevel >= LOG_VERBOSE) { Log.v((size == 0 ? "Request Unblocked, " : "Request Blocked (" + size + "), ") + toString(false)); } } @Override public void onConnect(ConnectionSession session) { connected = true; local = " / " + session.getLocalAddr() + ":" + session.getLocalPort(); if (logLevel >= LOG_VERBOSE) { Log.v("Connection Established, " + toString(false)); } } @Override public void onDisconnect() { decPeers(); } void disconnect() { handler.disconnect(); decPeers(); } private void decPeers() { if (!disconnected) { disconnected = true; server.totalPeers --; } } }
nickolasrm/TimelineBubbles
src/components/organisms/bubbles/atoms/horizontal_line/index.js
<reponame>nickolasrm/TimelineBubbles import { HorizontalLineStyle } from './style.module.css' /** * Adds a horizontal line into the middle of a bubble container * @returns */ export default function HorizontalLine() { return <div className={HorizontalLineStyle}></div> }