repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
cstom4994/SourceEngineRebuild | src/public/panorama/controls/movieplayer.h | <reponame>cstom4994/SourceEngineRebuild<gh_stars>1-10
//=========== Copyright Valve Corporation, All rights reserved. ===============//
//
// Purpose:
//=============================================================================//
#ifndef PANORAMA_MOVIEPLAYER_H
#define PANORAMA_MOVIEPLAYER_H
#ifdef _WIN32
#pragma once
#endif
#include "panel2d.h"
#include "../data/iimagesource.h"
#include "../data/panoramavideoplayer.h"
#include "panorama/uischeduleddel.h"
namespace panorama
{
class CToggleButton;
class CLabel;
class CSlider;
DECLARE_PANEL_EVENT0( MoviePlayerAudioStart );
DECLARE_PANEL_EVENT0( MoviePlayerAudioStop );
DECLARE_PANEL_EVENT0( MoviePlayerPlaybackStart );
DECLARE_PANEL_EVENT0( MoviePlayerPlaybackStop );
DECLARE_PANEL_EVENT1( MoviePlayerPlaybackEnded, EVideoPlayerPlaybackError );
DECLARE_PANORAMA_EVENT0( MoviePlayerTogglePlayPause );
DECLARE_PANORAMA_EVENT0( MoviePlayerFastForward );
DECLARE_PANEL_EVENT0( MoviePlayerUIVisible );
DECLARE_PANORAMA_EVENT0( MoviePlayerJumpBack );
DECLARE_PANORAMA_EVENT0( MoviePlayerVolumeControl );
DECLARE_PANORAMA_EVENT0( MoviePlayerFullscreenControl );
DECLARE_PANORAMA_EVENT1( MoviePlayerSetRepresentation, int );
DECLARE_PANORAMA_EVENT0( MoviePlayerSelectVideoQuality );
//-----------------------------------------------------------------------------
// Purpose: Base class for controls that pop above movie button bar
//-----------------------------------------------------------------------------
class CMovieControlPopupBase : public CPanel2D
{
public:
CMovieControlPopupBase( CPanel2D *pInvokingPanel, const char *pchPanelID );
virtual ~CMovieControlPopupBase() {}
void Show( float flVolume );
void Close();
virtual void OnLayoutTraverse( float flFinalWidth, float flFinalHeight ) OVERRIDE;
protected:
bool EventCancelled( const CPanelPtr< IUIPanel > &pPanel, EPanelEventSource_t eSource );
CPanel2D *m_pInvisibleBackground;
CPanel2D *m_pInvokingPanel;
CPanel2D *m_pPopupBackground;
};
//-----------------------------------------------------------------------------
// Purpose: Top level menu for volume slider
//-----------------------------------------------------------------------------
class CVolumeSliderPopup : public CMovieControlPopupBase
{
DECLARE_PANEL2D( CVolumeSliderPopup, CMovieControlPopupBase );
public:
CVolumeSliderPopup( CPanel2D *pInvokingPanel, const char *pchPanelID );
virtual ~CVolumeSliderPopup() {}
void Show( float flVolume );
virtual bool OnKeyDown( const KeyData_t &unichar ) OVERRIDE;
private:
bool EventSliderValueChanged( const CPanelPtr< IUIPanel > &pPanel, float flValue );
CSlider *m_pSlider;
};
//-----------------------------------------------------------------------------
// Purpose: Top level menu for showing video resolutions to select
//-----------------------------------------------------------------------------
class CMovieVideoQualityPopup : public CMovieControlPopupBase
{
DECLARE_PANEL2D( CMovieVideoQualityPopup, CMovieControlPopupBase );
public:
CMovieVideoQualityPopup( CPanel2D *pInvokingPanel, const char *pchPanelID );
virtual ~CMovieVideoQualityPopup() {}
void AddRepresentation( int iRep, int nHeight );
void Show( int iFocusRep, int nVideoHeight );
private:
struct Representation_t
{
int m_iRep;
int m_nHeight;
};
bool EventSetRepresentation( int iRep );
static bool SortRepresentations( const Representation_t &lhs, const Representation_t &rhs );
CUtlVector< Representation_t > m_vecRepresentations;
};
//-----------------------------------------------------------------------------
// Purpose: Movie panel. Just displays the movie
//-----------------------------------------------------------------------------
class CMoviePanel : public CPanel2D
{
DECLARE_PANEL2D( CMoviePanel, CPanel2D );
public:
CMoviePanel( CPanel2D *parent, const char *pchPanelID );
virtual ~CMoviePanel();
CVideoPlayerPtr GetMovie() { return m_pVideoPlayer; }
void SetMovie( const char *pchFile );
void SetMovie( CVideoPlayerPtr pVideoPlayer );
bool IsSet() { return (m_pVideoPlayer != NULL); }
void Clear();
void SetPlaybackVolume( float flVolume );
void SuggestMovieHeight();
virtual void Paint();
#ifdef DBGFLAG_VALIDATE
virtual void ValidateClientPanel( CValidator &validator, const tchar *pchName ) OVERRIDE;
#endif
protected:
virtual void OnContentSizeTraverse( float *pflContentWidth, float *pflContentHeight, float flMaxWidth, float flMaxHeight, bool bFinalDimensions ) OVERRIDE;
virtual void OnLayoutTraverse( float flFinalWidth, float flFinalHeight ) OVERRIDE;
bool EventVideoPlayerInitialized( IVideoPlayer *pIMovie );
private:
CVideoPlayerPtr m_pVideoPlayer;
};
//-----------------------------------------------------------------------------
// Purpose: Displays debug info for a movie
//-----------------------------------------------------------------------------
class CMovieDebug : public CPanel2D
{
DECLARE_PANEL2D( CMovieDebug, CPanel2D );
public:
CMovieDebug( CPanel2D *pParent, const char *pchID );
virtual ~CMovieDebug() {}
void Show( CVideoPlayerPtr pVideoPlayer );
private:
void Update();
CVideoPlayerPtr m_pVideoPlayer;
CLabel *m_pDimensions;
CLabel *m_pResolution;
CLabel *m_pFileType;
CLabel *m_pVideoSegment;
CLabel *m_pVideoBandwidth;
panorama::CUIScheduledDel m_scheduledUpdate;
};
//-----------------------------------------------------------------------------
// Purpose: Movie player. Includes UI
//-----------------------------------------------------------------------------
class CMoviePlayer : public CPanel2D
{
DECLARE_PANEL2D( CMoviePlayer, CPanel2D );
public:
CMoviePlayer( CPanel2D *parent, const char *pchPanelID );
virtual ~CMoviePlayer();
virtual void SetupJavascriptObjectTemplate() OVERRIDE;
CVideoPlayerPtr GetMovie() { return m_pMoviePanel->GetMovie(); }
void SetMovie( const char *pchFile );
void SetMovie( CVideoPlayerPtr pVideoPlayer );
bool IsSet() { return m_pMoviePanel->IsSet(); }
void Clear();
enum EAutoplay
{
k_EAutoplayOff,
k_EAutoplayOnLoad,
k_EAutoplayOnFocus
};
enum EControls
{
k_EControlsNone,
k_EControlsMinimal,
k_EControlsFull,
k_EControlsInvalid
};
void SetAutoplay( EAutoplay eAutoPlay, bool bSkipPlay = false );
void SetRepeat( bool bRepeat );
void SetControls( EControls eControls );
void SetControls( const char *pchControls );
virtual bool OnGamePadDown( const GamePadData_t &code ) OVERRIDE;
virtual bool OnKeyTyped( const KeyData_t &unichar ) OVERRIDE;
virtual panorama::IUIPanel *OnGetDefaultInputFocus() OVERRIDE;
void Play();
void Pause();
void Stop();
void TogglePlayPause();
void FastForward();
void Rewind();
void SetPlaybackVolume( float flVolume );
// title control
void SetTitleText( const char *pchText );
void ShowTitle( bool bImmediatelyVisible = false );
void HideTitle();
bool BAdjustingVolume();
virtual bool OnMouseButtonDown( const MouseData_t &code );
protected:
virtual bool BSetProperties( const CUtlVector< ParsedPanelProperty_t > &vecProperties );
static EControls EControlsFromString( const char *pchControls );
bool EventInputFocusSet( const CPanelPtr< IUIPanel > &ptrPanel );
bool EventInputFocusLost( const CPanelPtr< IUIPanel > &ptrPanel );
bool EventMovieInitialized( IVideoPlayer *pIMovie );
bool EventVideoPlayerPlaybackStateChanged( IVideoPlayer *pIMovie );
bool EventVideoPlayerChangedRepresentation( IVideoPlayer *pIMovie );
bool EventVideoPlayerEnded( IVideoPlayer *pIMovie );
bool EventActivated( const CPanelPtr< IUIPanel > &ptrPanel, EPanelEventSource_t eSource );
bool EventCancelled( const CPanelPtr< IUIPanel > &ptrPanel, EPanelEventSource_t eSource );
bool EventMovieTogglePlayPause();
bool EventMoviePlayerFastForward();
bool EventMoviePlayerJumpBack();
bool EventMoviePlayerVolumeControl();
bool EventMoviePlayerSelectQuality();
bool EventSoundVolumeChanged( ESoundType eSoundType, float flVolume );
bool EventSoundMuteChanged( bool bMute );
bool EventSetRepresentation( int iRep );
void UpdateFullUI();
void UpdateTimeline();
void UpdatePlayPauseButton();
void UpdatePlaybackSpeed();
void Seek( uint unOffset );
void RaisePlaybackStartEvents();
void RaisePlaybackStopEvents();
void DisplayControls( bool bVisible );
void DisplayTimeline( bool bVisible );
bool BAnyControlsVisible();
bool BControlBarVisible();
bool BTimelineVisible();
void UpdateMovingPlayingStyle();
void UpdateVolumeControls();
void SetAudioVolumeStyle( CPanoramaSymbol symStyle );
void ShowTitleInternal( bool bImmediatelyVisible = false );
void HideTitleInternal();
private:
CMoviePanel *m_pMoviePanel;
CPanelPtr< CMovieDebug > m_ptrDebug;
// minimal UI
CPanel2D *m_pLoadingThrobber;
CPanel2D *m_pPlayIndicator;
CPanoramaSymbol m_symMoviePlaybackStyle;
// title sections
CPanel2D *m_pPlaybackTitleAndControls;
CLabel *m_pPlaybackTitle;
bool m_bExternalShowTitle;
// full UI
CPanel2D *m_pPlaybackControls;
CPanel2D *m_pPlaybackProgressBar;
CToggleButton *m_pPlayPauseBtn;
CLabel *m_pPlaybackSpeed;
CPanel2D *m_pTimeline;
CPanel2D *m_pControlBarRow;
CPanel2D *m_pVolumeControl;
CLabel *m_pErrorMessage;
CPanelPtr< CVolumeSliderPopup > m_ptrVolumeSlider;
CPanelPtr< CMovieVideoQualityPopup > m_ptrVideoQualityPopup;
CButton *m_pVideoQualityBtn;
bool m_bInConstructor;
bool m_bRaisedAudioStartEvent;
bool m_bRaisedPlaybackStartEvent;
bool m_bHadFocus;
bool m_bCloseControlsOnPlay;
EAutoplay m_eAutoplay;
EControls m_eControls;
bool m_bDisableActivatePause;
bool m_bShowControlsNotFullscreen;
bool m_bRepeat;
bool m_bMuted; // muted flag
float m_flVolume; // playback volume, defaults to movie volume setting
int m_iDesiredVideoRepresentation; // representation selected by user or -1. Video player might not yet have changed to playing this rep
};
} // namespace panorama
#endif // PANORAMA_MOVIEPLAYER_H
|
hwxiasn/archetypes | ygb/ygb-project-impl/src/main/java/com/qingbo/ginkgo/ygb/project/listener/EventPublisherService.java | package com.qingbo.ginkgo.ygb.project.listener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;
/**
* @Resouce private EventPublisherService eventPublisherService;
* @author Administrator
*
*/
@Component
public class EventPublisherService{
@Autowired
private ApplicationContext applicationContext;
public void publishEvent(ApplicationEvent event) {
applicationContext.publishEvent(event);
}
}
|
kami-lang/madex-r8 | src/test/java/com/android/tools/r8/optimize/argumentpropagation/CheckNotZeroMethodWithArgumentRemovalTest.java | // Copyright (c) 2021, the R8 project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package com.android.tools.r8.optimize.argumentpropagation;
import static com.android.tools.r8.utils.codeinspector.Matchers.isPresent;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import com.android.tools.r8.NeverInline;
import com.android.tools.r8.TestBase;
import com.android.tools.r8.TestParameters;
import com.android.tools.r8.TestParametersCollection;
import com.android.tools.r8.utils.codeinspector.ClassSubject;
import com.android.tools.r8.utils.codeinspector.MethodSubject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class CheckNotZeroMethodWithArgumentRemovalTest extends TestBase {
@Parameter(0)
public TestParameters parameters;
@Parameters(name = "{0}")
public static TestParametersCollection parameters() {
return getTestParameters().withAllRuntimesAndApiLevels().build();
}
@Test
public void test() throws Exception {
testForR8(parameters.getBackend())
.addInnerClasses(getClass())
.addKeepMainRule(Main.class)
.addEnumUnboxingInspector(inspector -> inspector.assertUnboxed(MyEnum.class))
.enableInliningAnnotations()
// TODO(b/173398086): uniqueMethodWithName() does not work with argument removal.
.noMinification()
.setMinApi(parameters.getApiLevel())
.compile()
.inspect(
inspector -> {
ClassSubject mainClassSubject = inspector.clazz(Main.class);
assertThat(mainClassSubject, isPresent());
MethodSubject checkNotNullSubject =
mainClassSubject.uniqueMethodWithName("checkNotNull");
assertThat(checkNotNullSubject, isPresent());
assertEquals(1, checkNotNullSubject.getProgramMethod().getReference().getArity());
})
.run(parameters.getRuntime(), Main.class)
.assertSuccessWithEmptyOutput();
}
static class Main {
public static void main(String[] args) {
checkNotNull(System.currentTimeMillis() > 0 ? MyEnum.A : null, "x");
checkNotNull(System.currentTimeMillis() > 0 ? new Object() : null, "x");
}
@NeverInline
static void checkNotNull(Object o, String name) {
if (o == null) {
throw new NullPointerException("Expected not null, but " + name + " was null");
}
}
}
enum MyEnum {
A,
B
}
}
|
dworthen/arquero | src/engine/window/window-state.js | import ascending from '../../util/ascending';
import bisector from '../../util/bisector';
import concat from '../../util/concat';
import unroll from '../../util/unroll';
const bisect = bisector(ascending);
export default function(data, frame, adjust, ops, aggrs) {
let rows, peer, cells, result;
const isPeer = index => peer[index - 1] === peer[index];
const numOps = ops.length;
const numAgg = aggrs.length;
const evaluate = ops.length
? unroll(
ops, ['w', 'r'],
'{' + concat(ops, (_, i) => `r[_${i}.name]=_${i}.value(w,_${i}.get);`) + '}'
)
: () => {};
const w = {
i0: 0,
i1: 0,
index: 0,
size: 0,
peer: isPeer,
init(partition, peers, tuple) {
w.index = w.i0 = w.i1 = 0;
w.size = peers.length;
rows = partition;
peer = peers;
result = tuple;
// initialize aggregates
cells = aggrs ? aggrs.map(aggr => aggr.init()) : null;
// initialize window ops
for (let i = 0; i < numOps; ++i) {
ops[i].init();
}
return w;
},
value(index, get) {
return get(rows[index], data);
},
step(idx) {
const [f0, f1] = frame;
const n = w.size;
const p0 = w.i0;
const p1 = w.i1;
w.i0 = f0 != null ? Math.max(0, idx - Math.abs(f0)) : 0;
w.i1 = f1 != null ? Math.min(n, idx + Math.abs(f1) + 1) : n;
w.index = idx;
if (adjust) {
if (w.i0 > 0 && isPeer(w.i0)) {
w.i0 = bisect.left(peer, peer[w.i0]);
}
if (w.i1 < n && isPeer(w.i1)) {
w.i1 = bisect.right(peer, peer[w.i1 - 1]);
}
}
// evaluate aggregates
for (let i = 0; i < numAgg; ++i) {
const aggr = aggrs[i];
const cell = cells[i];
for (let j = p0; j < w.i0; ++j) {
aggr.rem(cell, rows[j], data);
}
for (let j = p1; j < w.i1; ++j) {
aggr.add(cell, rows[j], data);
}
aggr.writeToObject(cell, result);
}
// evaluate window ops
evaluate(w, result);
return result;
}
};
return w;
} |
LokiProgrammer/IlluminatiBoardGame | src/com/lucky7/ibg/Game.java | package com.lucky7.ibg;
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import com.lucky7.ibg.card.Card;
import com.lucky7.ibg.card.group.*;
import com.lucky7.ibg.card.illuminati.*;
import com.lucky7.ibg.card.special.*;
import com.lucky7.ibg.gui.ActionPanel;
import com.lucky7.ibg.gui.AttackToControlWindow;
import com.lucky7.ibg.gui.TransferWindow;
import com.lucky7.ibg.gui.GamePanel;
import com.lucky7.ibg.gui.GlobalActionPanel;
import com.lucky7.ibg.gui.TransferPower;
import com.lucky7.ibg.input.GameInput;
import com.lucky7.ibg.player.Player;
public class Game implements Runnable{
Thread thread;
public JFrame frame;
public GamePanel gamePanel;
JPanel topPanel;
public ActionPanel actionPanel;
JPanel bottomPanel;
public GlobalActionPanel globalActionPanel;
JSplitPane actionSplitPane;
JSplitPane bottomSplitPane;
JSplitPane rightSplitPane;
JScrollPane scrollPane;
JTextArea gameLogger;
GameInput input;
ArrayList<Player> players;
int playerIndex = 0;
ArrayList<IlluminatiCard> illuminatiCards;
ArrayList<Card> deck;
public ArrayList<GroupCard> uncontrolled;
ArrayList<Card> discardPile;
@Override
public void run() {
// Game prep
init();
configureWindow();
notifyStartup();
loadCards();
shufflePlayers();
assignIlluminatiCards();
setupWindow();
shuffleDeck();
// Main game process
populateMinimumUncontrolled();
}
private void setupWindow() {
actionPanel.updatePlayer(players.get(0));
globalActionPanel.addPlayerList(players);
}
void shuffleDeck() {
Collections.shuffle(deck);
}
public void attackToControl() {
new AttackToControlWindow(this);
}
public void attackToNeutralize() {
new AttackToControlWindow(this);
}
public void attackToDestory() {
new AttackToControlWindow(this);
}
public void transferMoney() {
new TransferWindow(this);
}
public void transferPower() {
new TransferPower(this);
}
public Player getCurrentPlayer() {
return players.get(playerIndex);
}
public Player getViewingPlayer() {
String playerName = (String)globalActionPanel.viewList.getSelectedItem();
for(Player p : players) {
if(p.getName().equals(playerName)) {
return p;
}
}
return null;
}
private void assignIlluminatiCards() {
// Assign random illuminati cards and add initial income
Collections.shuffle(illuminatiCards);
for(Player p : players) {
IlluminatiCard card = illuminatiCards.remove(0);
addLog(p.getName() + " was assigned \"" + card.getName() + "\"");
p.addIlluminatiToPowerStructure(card);
}
addLog("Adding initial income to all players...");
for(Player p : players) {
p.addIncome();
}
}
public static boolean checkValidGame(ArrayList<Player> players) {
for(int i = 0; i < players.size()-1; i++) {
for(int j = i+1; j < players.size(); j++) {
if(players.get(i).getName().equals(players.get(j).getName())) {
return false;
}
}
}
if(players.size() >= 2) {
return true;
}
return false;
}
public void addPlayers(ArrayList<Player> players) {
this.players = players;
}
public Game() {
thread = new Thread(this);
}
public void start() {
thread.start();
}
void init() {
// Initialize
input = new GameInput(this);
deck = new ArrayList<Card>();
discardPile = new ArrayList<Card>();
uncontrolled = new ArrayList<GroupCard>();
illuminatiCards = new ArrayList<IlluminatiCard>();
frame = new JFrame("Illuminati - Lucky7");
frame.setIconImage(new ImageIcon("res/illuminati_icon.png").getImage());
gamePanel = new GamePanel(this);
topPanel = new JPanel();
actionPanel = new ActionPanel(input);
bottomPanel = new JPanel();
globalActionPanel = new GlobalActionPanel(input);
gamePanel.setPreferredSize(new Dimension(900, 650));
gameLogger = new JTextArea();
gameLogger.setEditable(false);
gameLogger.setLineWrap(true);
scrollPane = new JScrollPane(gameLogger);
actionSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topPanel, bottomPanel);
bottomSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, gamePanel, scrollPane);
rightSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, bottomSplitPane, actionSplitPane);
// Configure Logger
gameLogger.setBackground(new Color(60,60,60));
gameLogger.setForeground(Color.WHITE);
// Configure top panel
topPanel.add(actionPanel);
topPanel.setBackground(new Color(60,60,60));
// Configure bottom panel
bottomPanel.add(globalActionPanel);
bottomPanel.setBackground(new Color(60,60,60));
actionSplitPane.setDividerSize(2);
bottomSplitPane.setDividerSize(2);
rightSplitPane.setDividerSize(2);
}
public void endTurn() {
addLog(players.get(playerIndex).getName() + " finished his turn.");
playerIndex = (playerIndex + 1) % players.size();
readyNextPlayer();
}
public void resign() {
addLog(players.get(playerIndex).getName() + " has resigned!");
players.remove(playerIndex);
readyNextPlayer();
}
public int rollDice() {
// Simulates the roll of two dice
Random random = new Random();
int dice1Value = random.nextInt(6) + 1;
int dice2Value = random.nextInt(6) + 1;
return dice1Value + dice2Value;
}
void configureWindow() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(rightSplitPane);
frame.setVisible(true);
frame.pack();
bottomSplitPane.setDividerLocation(0.8);
rightSplitPane.setDividerLocation(0.78);
actionSplitPane.setDividerLocation(0.55);
gamePanel.setFocusable(true);
gamePanel.requestFocusInWindow();
}
public void addLog(String message) {
// Add message
gameLogger.append(message + "\n");
}
public GroupCard getSelectedCard() {
return (GroupCard) actionPanel.cardSelectedList.getSelectedItem();
}
void notifyStartup() {
addLog("Game starting...");
for(int i = 0; i < players.size(); i++) {
Player p = players.get(i);
addLog(p.getName() + " has joined the game.");
}
}
void populateMinimumUncontrolled() {
while(uncontrolled.size() < 4) {
Card card = deck.remove(0);
if(card instanceof GroupCard) {
addLog("Added \"" + card.getName() + "\" to uncontrolled groups.");
uncontrolled.add((GroupCard)card);
}else {
deck.add(card);
}
}
}
void readyNextPlayer() {
actionPanel.updatePlayer(players.get(playerIndex));
globalActionPanel.viewList.setSelectedIndex(playerIndex);
}
void shufflePlayers() {
Collections.shuffle(players);
// Display order of players in logger
addLog("Turn order determined:");
for(int i = 0; i < players.size(); i++) {
addLog(String.valueOf(i + 1) + ". " + players.get(i));
}
}
void loadCards() {
// Illuminati Cards
illuminatiCards.add(new TheDiscordianSociety());
illuminatiCards.add(new TheNetwork());
illuminatiCards.add(new TheSocietyOfAssassins());
illuminatiCards.add(new TheUFOs());
illuminatiCards.add(new TheServantsOfCthulhu());
illuminatiCards.add(new TheGnomesOfZurich());
illuminatiCards.add(new TheBavarianIlluminati());
illuminatiCards.add(new TheBermudaTriangle());
// Group Cards
deck.add(new Airlines());
deck.add(new AlienAbductors());
deck.add(new AmericanAutoduelAssociation());
deck.add(new Antifa());
deck.add(new AntiNuclearActivists());
deck.add(new AntiWarActivists());
deck.add(new ArmsSmugglers());
deck.add(new BigMedia());
deck.add(new Bloggers());
deck.add(new BoySprouts());
deck.add(new CableCompanies());
deck.add(new California());
deck.add(new ChainLetters());
deck.add(new CIA());
deck.add(new CloneArrangers());
deck.add(new CoffeeShops());
deck.add(new CongressionalWives());
deck.add(new ConvenienceStores());
deck.add(new Cosplayers());
deck.add(new CycleGangs());
deck.add(new Democrats());
deck.add(new EcoGuerrillas());
deck.add(new EvilGeniusesForABetterTomorrow());
deck.add(new FastFoodChains());
deck.add(new FBI());
deck.add(new FederalReserve());
deck.add(new FEMA());
deck.add(new FiendishFluidators());
deck.add(new FlatEarthers());
deck.add(new FnordMotorCompany());
deck.add(new FraternalOrders());
deck.add(new GoldfishFanciers());
deck.add(new GunLobby());
deck.add(new Hackers());
deck.add(new HealthFoodStores());
deck.add(new HighFashion());
deck.add(new Hipsters());
deck.add(new Hollywood());
deck.add(new InternationalDrugSmugglers());
deck.add(new InternetPrOn());
deck.add(new IRS());
deck.add(new JunkMail());
deck.add(new L4Society());
deck.add(new Libertarians());
deck.add(new LoanSharks());
deck.add(new LocalPoliceDepartments());
deck.add(new MadisonAvenue());
deck.add(new Militias());
deck.add(new MoralMinority());
deck.add(new Morticians());
deck.add(new MultinationalOilCompanies());
deck.add(new NewYork());
deck.add(new NuclearPowerCompanies());
deck.add(new OnlineVideos());
deck.add(new OrbitalMindControlLasers());
deck.add(new PalePeopleInBlack());
deck.add(new ParentTeacherAgglomeration());
deck.add(new Pentagon());
deck.add(new PostOffice());
deck.add(new Preppers());
deck.add(new ProfessionalSports());
deck.add(new PublicArt());
deck.add(new Psychiatrists());
deck.add(new PunkRockers());
deck.add(new ForwardEmails());
deck.add(new Recyclers());
deck.add(new Republicans());
deck.add(new RobotSeaMonsters());
deck.add(new RussianCampaignDonors());
deck.add(new SciFiFans());
deck.add(new SemiconsciousLiberationArmy());
deck.add(new Spammers());
deck.add(new Tabloids());
deck.add(new Texas());
deck.add(new TheMafia());
deck.add(new TheMenInBlack());
deck.add(new TheUnitedNations());
deck.add(new TobaccoAndLiquorCompanies());
deck.add(new TriliberalCommission());
deck.add(new TVPreachers());
deck.add(new UndergroundMedia());
deck.add(new VideoGames());
deck.add(new Vloggers());
// Ability Cards
deck.add(new Assassination());
deck.add(new Bribery());
deck.add(new ComputerEspionage());
deck.add(new DeepAgent());
deck.add(new Interference());
deck.add(new Interference());
deck.add(new MarketManipulation());
deck.add(new MediaBlitz());
deck.add(new MurphysLaw());
deck.add(new Ninjas());
deck.add(new SecretsManWasNotMeantToKnow());
deck.add(new SenateInvestigatingCommittee());
deck.add(new SlushFund());
deck.add(new SwissBankAccount());
deck.add(new TimeWarp());
deck.add(new WhiteCollarCrime());
}
}
|
scireum/sirius-web | src/test/java/sirius/web/http/TestController.java | /*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - <EMAIL>
*/
package sirius.web.http;
import sirius.kernel.di.std.Part;
import sirius.kernel.di.std.Register;
import sirius.kernel.health.Exceptions;
import sirius.kernel.xml.XMLStructuredOutput;
import sirius.web.controller.BasicController;
import sirius.web.controller.Routed;
import sirius.web.services.Format;
import sirius.web.services.InternalService;
import sirius.web.resources.Resources;
import sirius.web.services.JSONStructuredOutput;
@Register
public class TestController extends BasicController {
@Routed("/api/test/test_large_failure")
@InternalService(format = Format.XML)
public void test_large_failure(WebContext webContext, XMLStructuredOutput out) throws Exception {
for (int i = 0; i < 8192; i++) {
out.property("test" + i, true);
}
throw Exceptions.createHandled().withSystemErrorMessage("Expected!").handle();
}
@Part
private Resources resources;
@Routed("/api/test/test_large")
@InternalService
public void test_large(WebContext webContext, JSONStructuredOutput out) throws Exception {
out.property("test", resources.resolve("assets/test_large.css").get().getContentAsString());
}
@Routed("/api/test")
@InternalService
public void test(WebContext webContext, JSONStructuredOutput out) throws Exception {
out.property("test", true);
}
@Routed("/api/test/small_large_failure")
@InternalService
public void small_large_failure(WebContext webContext, JSONStructuredOutput out) throws Exception {
out.property("test", true);
throw Exceptions.createHandled().withSystemErrorMessage("Expected!").handle();
}
}
|
kue-ipc/ikamail | test/mailers/previews/notification_mailer_preview.rb | <reponame>kue-ipc/ikamail<gh_stars>0
# Preview all emails at http://localhost:3000/rails/mailers/notification_mailer
class NotificationMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/apply
def apply
NotificationMailer.apply
end
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/withdraw
def withdraw
NotificationMailer.withdraw
end
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/approve
def approve
NotificationMailer.approve
end
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/reject
def reject
NotificationMailer.reject
end
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/deliver
def deliver
NotificationMailer.deliver
end
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/cancel
def cancel
NotificationMailer.cancel
end
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/discard
def discard
NotificationMailer.discard
end
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/finish
def finish
NotificationMailer.finish
end
# Preview this email at http://localhost:3000/rails/mailers/notification_mailer/error
def error
NotificationMailer.error
end
end
|
Nabila118/DBProject | demos/React/app/formattedinput/fluidsize/app.js | <reponame>Nabila118/DBProject<filename>demos/React/app/formattedinput/fluidsize/app.js<gh_stars>0
import React from 'react';
import ReactDOM from 'react-dom';
import JqxFormattedInput from '../../../jqwidgets-react/react_jqxformattedinput.js';
class App extends React.Component {
render() {
return (
<JqxFormattedInput
width={'30%'} height={25} radix={'binary'}
value={10111} spinButtons={true}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
RomanYarovoi/oms_cms | oms_cms/config/base/api_settings.py | REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAdminUser',
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.AllowAny',
),
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
],
# 'DEFAULT_FILTER_BACKENDS': [
# 'django_filters.rest_framework.DjangoFilterBackend'
# ],
'DEFAULT_AUTHENTICATION_CLASSES': (
# 'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
#'rest_framework.authentication.SessionAuthentication',
# 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata',
# 'DEFAULT_PAGINATION_CLASS':
# 'rest_framework_json_api.pagination.PageNumberPagination',
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 100,
'UPLOADED_FILES_USE_URL': False
}
# JWT_AUTH = {
# 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=2),
# 'JWT_ALLOW_REFRESH': True,
# 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7) # default
# }
#
# DJOSER = {
# 'SEND_ACTIVATION_EMAIL': True,
# # 'SEND_CONFIRMATION_EMAIL': True,
# 'ACTIVATION_URL': 'auth/activate/{uid}/{token}/',
# 'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': True,
# 'PASSWORD_RESET_CONFIRM_URL': 'auth/reset/confirm/{uid}/{token}/',
# 'TOKEN_MODEL': None
# }
|
ApocalypseMac/CP | atcoder/Educational DP Contest/A.cpp | <gh_stars>0
#include <bits/stdc++.h>
const int maxn = 100005;
int N, h[maxn], dp[maxn];
int main(){
std::cin >> N;
memset(dp, 0, sizeof(dp));
for (int i = 0; i < N; i++) std::cin >> h[i];
dp[1] = abs(h[1] - h[0]);
for (int i = 2; i < N; i++){
dp[i] = std::min(dp[i-1] + abs(h[i] - h[i-1]), dp[i-2] + abs(h[i] - h[i-2]));
}
std::cout << dp[N-1];
return 0;
} |
leeola/muta | _examples/hello/muta.go | package main
import (
"fmt"
"github.com/leeola/muta"
)
func Hello() {
fmt.Println("Hello")
}
func Readme() {
fmt.Println(`
Nice, you ran Muta! Don't forget that you can get a task list
by running the following:
$ muta -h
`)
}
func main() {
// Add the "hello" task, with a func() handler
muta.Task("hello", Hello)
// Add the "world" task, with the "hello" dependency
muta.Task("world", "hello", func() {
fmt.Println("World")
})
// Add the Readme task
muta.Task("readme", Readme)
// Add the optional default task
muta.Task("default", "world", "readme")
// Run Te() or Start() to start Muta
muta.Te()
}
|
AferriDaniel/coaster | coaster/sqlalchemy/registry.py | <gh_stars>10-100
"""
Model helper registry
---------------------
Provides a :class:`Registry` type and a :class:`RegistryMixin` base class
with three registries, used by other mixin classes.
Helper classes such as forms and views can be registered to the model and
later accessed from an instance::
class MyModel(BaseMixin, db.Model):
...
class MyForm(Form):
...
class MyView(ModelView):
...
MyModel.forms.main = MyForm
MyModel.views.main = MyView
When accessed from an instance, the registered form or view will receive the
instance as an ``obj`` parameter::
doc = MyModel()
doc.forms.main() == MyForm(obj=doc)
doc.views.main() == MyView(obj=doc)
The name ``main`` is a recommended default, but an app that has separate forms
for ``new`` and ``edit`` actions could use those names instead.
"""
from functools import partial
from threading import Lock
from typing import Optional, Set
from sqlalchemy.ext.declarative import declared_attr
__all__ = ['Registry', 'InstanceRegistry', 'RegistryMixin']
_marker = object()
class Registry:
"""Container for items registered to a model."""
_param: Optional[str]
_name: Optional[str]
_lock: Lock
_default_property: bool
_default_cached_property: bool
_members: Set[str]
_properties: Set[str]
_cached_properties: Set[str]
def __init__(
self,
param: Optional[str] = None,
property: bool = False, # noqa: A002
cached_property: bool = False,
):
"""Initialize with config."""
if property and cached_property:
raise TypeError("Only one of property and cached_property can be True")
object.__setattr__(self, '_param', str(param) if param else None)
object.__setattr__(self, '_name', None)
object.__setattr__(self, '_lock', Lock())
object.__setattr__(self, '_default_property', property)
object.__setattr__(self, '_default_cached_property', cached_property)
object.__setattr__(self, '_members', set())
object.__setattr__(self, '_properties', set())
object.__setattr__(self, '_cached_properties', set())
def __set_name__(self, owner, name):
"""Set a name for this registry."""
if self._name is None:
object.__setattr__(self, '_name', name)
elif name != self._name:
raise TypeError(
f"A registry cannot be used under multiple names {self._name} and"
f" {name}"
)
def __setattr__(self, name, value):
"""Incorporate a new registry member."""
if name.startswith('_'):
raise ValueError("Registry member names cannot be underscore-prefixed")
if hasattr(self, name):
raise ValueError(f"{name} is already registered")
if not callable(value):
raise ValueError("Registry members must be callable")
self._members.add(name)
object.__setattr__(self, name, value)
def __call__(self, name=None, property=None, cached_property=None): # noqa: A002
"""Return decorator to aid class or function registration."""
use_property = self._default_property if property is None else property
use_cached_property = (
self._default_cached_property
if cached_property is None
else cached_property
)
if use_property and use_cached_property:
raise TypeError(
f"Only one of property and cached_property can be True."
f" Provided: property={property}, cached_property={cached_property}."
f" Registry: property={self._default_property},"
f" cached_property={self._default_cached_property}."
f" Conflicting registry settings must be explicitly set to False."
)
def decorator(f):
use_name = name or f.__name__
setattr(self, use_name, f)
if use_property:
self._properties.add(use_name)
if use_cached_property:
self._cached_properties.add(use_name)
return f
return decorator
# def __iter__ (here or in instance?)
def __get__(self, obj, cls=None):
"""Access at runtime."""
if obj is None:
return self
cache = obj.__dict__ # This assumes a class without __slots__
name = self._name
with self._lock:
ir = cache.get(name, _marker)
if ir is _marker:
ir = InstanceRegistry(self, obj)
cache[name] = ir
# Subsequent accesses will bypass this __get__ method and use the instance
# that was saved to obj.__dict__
return ir
def clear_cache_for(self, obj) -> bool:
"""
Clear cached instance registry from an object.
Returns `True` if cache was cleared, `False` if it wasn't needed.
"""
with self._lock:
return bool(obj.__dict__.pop(self._name, False))
class InstanceRegistry:
"""
Container for accessing registered items from an instance of the model.
Used internally by :class:`Registry`. Returns a partial that will pass
in an ``obj`` parameter when called.
"""
def __init__(self, registry, obj):
"""Prepare to serve a registry member."""
# This would previously be cause for a memory leak due to being a cyclical
# reference, and would have needed a weakref. However, this is no longer a
# concern since PEP 442 and Python 3.4.
self.__registry = registry
self.__obj = obj
def __getattr__(self, attr):
"""Access a registry member."""
registry = self.__registry
obj = self.__obj
param = registry._param
func = getattr(registry, attr)
# If attr is a property, return the result
if attr in registry._properties:
if param is not None:
return func(**{param: obj})
return func(obj)
# If attr is a cached property, cache and return the result
if attr in registry._cached_properties:
if param is not None:
val = func(**{param: obj})
else:
val = func(obj)
setattr(self, attr, val)
return val
# Not a property or cached_property. Construct a partial, cache and return it
if param is not None:
pfunc = partial(func, **{param: obj})
else:
pfunc = partial(func, obj)
setattr(self, attr, pfunc)
return pfunc
def clear_cache(self):
"""Clear cache from this registry."""
with self.__registry.lock:
return bool(self.__obj.__dict__.pop(self.__registry.name, False))
class RegistryMixin:
"""
Adds common registries to a model.
Included:
* ``forms`` registry, for WTForms forms
* ``views`` registry for view classes and helper functions
* ``features`` registry for feature availability test functions.
The forms registry passes the instance to the registered form as an ``obj`` keyword
parameter. The other registries pass it as the first positional parameter.
"""
@declared_attr
def forms(cls):
"""Registry for forms."""
r = Registry('obj')
r.__set_name__(cls, 'forms')
return r
@declared_attr
def views(cls):
"""Registry for views."""
r = Registry()
r.__set_name__(cls, 'views')
return r
@declared_attr
def features(cls):
"""Registry for feature tests."""
r = Registry()
r.__set_name__(cls, 'features')
return r
|
nistefan/cmssw | MagneticField/Interpolation/src/VectorFieldInterpolation.cc | <filename>MagneticField/Interpolation/src/VectorFieldInterpolation.cc<gh_stars>1-10
// include header for VectorFieldInterpolation
#include "VectorFieldInterpolation.h"
void VectorFieldInterpolation::defineCellPoint000(double X1, double X2, double X3, double F1, double F2, double F3){
CellPoint000[0] = X1;
CellPoint000[1] = X2;
CellPoint000[2] = X3;
CellPoint000[3] = F1;
CellPoint000[4] = F2;
CellPoint000[5] = F3;
return;
}
void VectorFieldInterpolation::defineCellPoint100(double X1, double X2, double X3, double F1, double F2, double F3){
CellPoint100[0] = X1;
CellPoint100[1] = X2;
CellPoint100[2] = X3;
CellPoint100[3] = F1;
CellPoint100[4] = F2;
CellPoint100[5] = F3;
return;
}
void VectorFieldInterpolation::defineCellPoint010(double X1, double X2, double X3, double F1, double F2, double F3){
CellPoint010[0] = X1;
CellPoint010[1] = X2;
CellPoint010[2] = X3;
CellPoint010[3] = F1;
CellPoint010[4] = F2;
CellPoint010[5] = F3;
return;
}
void VectorFieldInterpolation::defineCellPoint110(double X1, double X2, double X3, double F1, double F2, double F3){
CellPoint110[0] = X1;
CellPoint110[1] = X2;
CellPoint110[2] = X3;
CellPoint110[3] = F1;
CellPoint110[4] = F2;
CellPoint110[5] = F3;
return;
}
void VectorFieldInterpolation::defineCellPoint001(double X1, double X2, double X3, double F1, double F2, double F3){
CellPoint001[0] = X1;
CellPoint001[1] = X2;
CellPoint001[2] = X3;
CellPoint001[3] = F1;
CellPoint001[4] = F2;
CellPoint001[5] = F3;
return;
}
void VectorFieldInterpolation::defineCellPoint101(double X1, double X2, double X3, double F1, double F2, double F3){
CellPoint101[0] = X1;
CellPoint101[1] = X2;
CellPoint101[2] = X3;
CellPoint101[3] = F1;
CellPoint101[4] = F2;
CellPoint101[5] = F3;
return;
}
void VectorFieldInterpolation::defineCellPoint011(double X1, double X2, double X3, double F1, double F2, double F3){
CellPoint011[0] = X1;
CellPoint011[1] = X2;
CellPoint011[2] = X3;
CellPoint011[3] = F1;
CellPoint011[4] = F2;
CellPoint011[5] = F3;
return;
}
void VectorFieldInterpolation::defineCellPoint111(double X1, double X2, double X3, double F1, double F2, double F3){
CellPoint111[0] = X1;
CellPoint111[1] = X2;
CellPoint111[2] = X3;
CellPoint111[3] = F1;
CellPoint111[4] = F2;
CellPoint111[5] = F3;
return;
}
void VectorFieldInterpolation::putSCoordGetVField(double X1, double X2, double X3, double &F1, double &F2, double &F3){
SC[0] = X1;
SC[1] = X2;
SC[2] = X3;
// values describing 4 help points after interpolation step of variables X1
// 5 dimensions: 2 space dimensions + 3 field dimensions
// X2' , X3' , F1' , F2' , F3'
double HelpPoint00[5]; // {0.0 , 0.0 , 0.0 , 0.0 , 0.0};
double HelpPoint10[5];
double HelpPoint01[5];
double HelpPoint11[5];
// values describing 2 help points after interpolation step of variables X2'
// 4 dimensions: 1 space dimensions + 3 field dimensions
// X3" , F1" , F2" , F3"
double HelpPoint0[4]; // {0.0 , 0.0 , 0.0 , 0.0};
double HelpPoint1[4];
// 1. iteration *****
// prepare interpolation between CellPoint000 and CellPoint100
double DeltaX100X000 = CellPoint100[0] - CellPoint000[0];
double DeltaSC0X000overDeltaX100X000 = 0.;
if (DeltaX100X000 != 0.) DeltaSC0X000overDeltaX100X000 = (SC[0] - CellPoint000[0]) / DeltaX100X000;
// prepare interpolation between CellPoint010 and CellPoint110
double DeltaX110X010 = CellPoint110[0] - CellPoint010[0];
double DeltaSC0X010overDeltaX110X010 = 0.;
if (DeltaX110X010 != 0.) DeltaSC0X010overDeltaX110X010 = (SC[0] - CellPoint010[0]) / DeltaX110X010;
// prepare interpolation between CellPoint001 and CellPoint101
double DeltaX101X001 = CellPoint101[0] - CellPoint001[0];
double DeltaSC0X001overDeltaX101X001 = 0.;
if (DeltaX101X001 != 0.) DeltaSC0X001overDeltaX101X001 = (SC[0] - CellPoint001[0]) / DeltaX101X001;
// prepare interpolation between CellPoint011 and CellPoint111
double DeltaX111X011 = CellPoint111[0] - CellPoint011[0];
double DeltaSC0X011overDeltaX111X011 = 0.;
if (DeltaX111X011 != 0.) DeltaSC0X011overDeltaX111X011 = (SC[0] - CellPoint011[0]) / DeltaX111X011;
for (int i=0; i<5; ++i){
int ip = i+1;
// interpolate between CellPoint000 and CellPoint100
HelpPoint00[i] = CellPoint000[ip] + DeltaSC0X000overDeltaX100X000 * (CellPoint100[ip] - CellPoint000[ip]);
// interpolate between CellPoint010 and CellPoint110
HelpPoint10[i] = CellPoint010[ip] + DeltaSC0X010overDeltaX110X010 * (CellPoint110[ip] - CellPoint010[ip]);
// interpolate between CellPoint001 and CellPoint101
HelpPoint01[i] = CellPoint001[ip] + DeltaSC0X001overDeltaX101X001 * (CellPoint101[ip] - CellPoint001[ip]);
// interpolate between CellPoint011 and CellPoint111
HelpPoint11[i] = CellPoint011[ip] + DeltaSC0X011overDeltaX111X011 * (CellPoint111[ip] - CellPoint011[ip]);
}
// 2. iteration *****
// prepare interpolation between HelpPoint00 and HelpPoint10
double DeltaX10X00 = HelpPoint10[0] - HelpPoint00[0];
double DeltaSC1X00overDeltaX10X00 = 0.;
if (DeltaX10X00 != 0.) DeltaSC1X00overDeltaX10X00 = (SC[1] - HelpPoint00[0]) / DeltaX10X00;
// prepare interpolation between HelpPoint01 and HelpPoint11
double DeltaX11X01 = HelpPoint11[0] - HelpPoint01[0];
double DeltaSC1X01overDeltaX11X01 = 0.;
if (DeltaX11X01 != 0.) DeltaSC1X01overDeltaX11X01 = (SC[1] - HelpPoint01[0]) / DeltaX11X01;
for (int i=0; i<4; ++i){
int ip = i+1;
// interpolate between HelpPoint00 and HelpPoint10
HelpPoint0[i] = HelpPoint00[ip] + DeltaSC1X00overDeltaX10X00 * (HelpPoint10[ip] - HelpPoint00[ip]);
// interpolate between HelpPoint01 and HelpPoint11
HelpPoint1[i] = HelpPoint01[ip] + DeltaSC1X01overDeltaX11X01 * (HelpPoint11[ip] - HelpPoint01[ip]);
}
// 3. iteration *****
// prepare interpolation between HelpPoint0 and HelpPoint1
double DeltaX1X0 = HelpPoint1[0] - HelpPoint0[0];
double DeltaSC2X0overDeltaX1X0 = 0.;
if (DeltaX1X0 != 0.) DeltaSC2X0overDeltaX1X0 = (SC[2] - HelpPoint0[0]) / DeltaX1X0;
for (int i=0; i<3; ++i){
int ip = i+1;
// interpolate between HelpPoint0 and HelpPoint1
VF[i] = HelpPoint0[ip] + DeltaSC2X0overDeltaX1X0 * (HelpPoint1[ip] - HelpPoint0[ip]);
}
F1 = VF[0];
F2 = VF[1];
F3 = VF[2];
return;
}
|
zurawiki/netlify-cms | src/components/EditorWidgets/Markdown/MarkdownControl/Toolbar/ToolbarButton.js | import PropTypes from 'prop-types';
import React from 'react';
import c from 'classnames';
import { Icon } from 'UI';
const ToolbarButton = ({ type, label, icon, onClick, isActive, isHidden, disabled }) => {
const active = isActive && type && isActive(type);
if (isHidden) {
return null;
}
return (
<button
className={c('nc-toolbarButton-button', { ['nc-toolbarButton-active']: active })}
onClick={e => onClick && onClick(e, type)}
title={label}
disabled={disabled}
>
{ icon ? <Icon type={icon}/> : label }
</button>
);
};
ToolbarButton.propTypes = {
type: PropTypes.string,
label: PropTypes.string.isRequired,
icon: PropTypes.string,
onClick: PropTypes.func,
isActive: PropTypes.func,
disabled: PropTypes.bool,
};
export default ToolbarButton;
|
JamesMAWalker/ppr | gatsby-config.js | <reponame>JamesMAWalker/ppr
module.exports = {
siteMetadata: {
title: `PPR 20201 Team Site`,
description: `Information about the Plant Power Racing team for 2021.`,
author: `james-walker`,
},
plugins: [
`gatsby-plugin-layout`,
`gatsby-plugin-react-helmet`,
`gatsby-plugin-transition-link`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
layout: require.resolve(`./src/layouts/index.js`),
},
},
{
resolve: `gatsby-source-sanity`,
options: {
// projectId: process.env.SANITY_PROJECT_ID,
// dataset: process.env.SANITY_DATASET,
// token: process.env.SANITY_TOKEN,
apiVersion: "2021-03-25", // use a UTC date string
watchMode: true,
overlayDrafts: true,
useCdn: true,
withCredentials: true,
graphqlTag: "default",
projectId: `v0rw1hdx`,
dataset: `production`,
token:
"<KEY>",
// token:
// "<KEY>0EFh7X5YrO6I6B52", // or leave blank for unauthenticated usage
},
},
{
resolve: "gatsby-plugin-sanity-image",
options: {
projectId: "v0rw1hdx",
dataset: "production",
defaultImageConfig: {
quality: 100, // use reasonable lossy compression level
fit: "max", // like `object-fit: contain`, but never scaling up
auto: "format", // automatically select next-gen image formats on supporting browsers
},
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-image`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
`gatsby-plugin-sass`,
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
|
brianneisler/moltres-template | src/core/mapProps.js | <filename>src/core/mapProps.js
import createFactory from './createFactory'
const mapProps = (propsMapper) => (factory) =>
createFactory((props, ...rest) =>
factory(propsMapper(props, ...rest), ...rest)
)
export default mapProps
|
alexebaker/java-constant_folding | src/Parser/Nodes/Term.java | <filename>src/Parser/Nodes/Term.java
package Parser.Nodes;
import Errors.SyntaxError;
import Parser.Operators.FactorOp;
import Parser.Operators.Operator;
import Tokenizer.TokenReader;
import Compiler.CompilerState;
import Compiler.SymbolTable;
public class Term extends ASTNode {
public static ASTNode parse(CompilerState cs, SymbolTable st) throws SyntaxError {
TokenReader tr = cs.getTr();
ASTNode node = Factor.parse(cs, st);
while (FactorOp.isOp(tr.peek())) {
Operator temp = new FactorOp(tr.read());
temp.setLhs(node);
temp.setRhs(Factor.parse(cs, st));
node = temp;
}
return node;
}
}
|
AsimKhan2019/Blink-ID | BlinkIDSample/LibUtils/src/main/java/com/microblink/result/extract/blinkid/sweden/SwedenDlFrontRecognitionResultExtractor.java | package com.microblink.result.extract.blinkid.sweden;
import com.microblink.entities.recognizers.blinkid.sweden.dl.SwedenDlFrontRecognizer;
import com.microblink.libresult.R;
import com.microblink.result.extract.blinkid.BlinkIdExtractor;
public class SwedenDlFrontRecognitionResultExtractor extends BlinkIdExtractor<SwedenDlFrontRecognizer.Result, SwedenDlFrontRecognizer> {
@Override
protected void extractData(SwedenDlFrontRecognizer.Result result) {
add(R.string.PPLicenceNumber, result.getLicenceNumber());
add(R.string.PPSurname, result.getSurname());
add(R.string.PPName, result.getName());
add(R.string.PPDateOfBirth, result.getDateOfBirth());
add(R.string.PPIssueDate, result.getDateOfIssue());
add(R.string.PPDateOfExpiry, result.getDateOfExpiry());
add(R.string.PPIssuingAgency, result.getIssuingAgency());
add(R.string.PPReferenceNumber, result.getReferenceNumber());
add(R.string.PPLicenceCategories, result.getLicenceCategories());
}
}
|
DEAKSoftware/panoramic-rendering | source/render/render_ddraw.cpp | /*============================================================================*/
/* <NAME> [Tau] - <NAME> */
/* */
/* DDraw Rendering Functions */
/*============================================================================*/
/*---------------------------------------------------------------------------
Don't include this file if it's already defined.
---------------------------------------------------------------------------*/
#ifndef __RENDER_DDRAW_CPP__
#define __RENDER_DDRAW_CPP__
/*---------------------------------------------------------------------------
Include libraries and other source files needed in this file.
---------------------------------------------------------------------------*/
#include "../_common/std_inc.h"
#include "../render/render.cpp"
#include "../video_io/video.cpp"
/*---------------------------------------------------------------------------
The Renering NULL class.
---------------------------------------------------------------------------*/
class RenderDDrawClass : public RenderClass
{
/*==== Public Declarations ================================================*/
public:
/*---- Constructor --------------------------------------------------------*/
RenderDDrawClass(void) {}
/*---- Destructor ---------------------------------------------------------*/
~RenderDDrawClass(void) {}
/*-------------------------------------------------------------------------
Setup the renderer.
------------------------------------------------------------------------*/
bool Initialize(VideoClass* Video, char* ProfCurve, float ProfEquLim, dword NewTabRes)
{
//No NULL pointers please
if (Video == NULL) {return false;}
//Ensure that the Video uses the correct interface,
// and the Video mode is valid.
if ((Video->CurrentDevice != VIDEO_DDRAW) || !Video->ModeValid) {return false;}
//Indicate that rendering is allowed
//RenderValid = true;
return true;
}
/*-------------------------------------------------------------------------
Shutdown the renderer.
------------------------------------------------------------------------*/
bool ShutDown(void)
{
if (ProfEqu != NULL) {delete[] ProfEqu; ProfEqu = NULL;}
if (ProfCode != NULL) {delete[] ProfCode; ProfCode = NULL;}
//Indicate that rendering is not allowed
RenderValid = false;
return true;
}
/*-------------------------------------------------------------------------
This function will render the entire world.
EntityList : The list of Entities and sub-Entities to render.
LightList : The list of Lights to use for shading.
World : Access to the world data such as view origin and
orientation, etc.
------------------------------------------------------------------------*/
bool DrawScene(ListRec* EntityList, ListRec* LightList, WorldRec* World)
{
//Ensure that the Video uses the correct interface,
// and the Video mode is valid.
if ((Video->CurrentDevice != VIDEO_DDRAW) || !Video->ModeValid) {return false;}
//If the display area is minimized, don't do any rendering
if (Video->Minimized) {return true;}
//Lock the renderer
if (!Video->Lock()) {return false;}
//Unlock the renderer
if (!Video->UnLock()) {return false;}
return true;
}
/*==== End of Class =======================================================*/
};
/*----------------------------------------------------------------------------
Global declaration of the Video class.
----------------------------------------------------------------------------*/
RenderDDrawClass RenderDDraw;
/*==== End of file ===========================================================*/
#endif
|
Brook1711/biubiu_Qt6 | vlc_linux/vlc-3.0.16/modules/gui/qt/dialogs/toolbar.cpp | <gh_stars>0
/*****************************************************************************
* toolbar.cpp : ToolbarEdit dialog
****************************************************************************
* Copyright (C) 2008-2009 the VideoLAN team
* $Id: 58a90f7c5b413718dd8b500d45afca08fa23ad88 $
*
* Authors: <NAME> <jb (at) videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "dialogs/toolbar.hpp"
/* Widgets */
#include "util/input_slider.hpp"
#include "util/customwidgets.hpp"
#include "components/interface_widgets.hpp"
#include "util/buttons/DeckButtonsLayout.hpp"
#include "util/buttons/BrowseButton.hpp"
#include "util/buttons/RoundButton.hpp"
#include "util/imagehelper.hpp"
#include "qt.hpp"
#include "input_manager.hpp"
#include <vlc_vout.h> /* vout_thread_t for aspect ratio combobox */
#include <QGroupBox>
#include <QLabel>
#include <QComboBox>
#include <QListWidget>
#include <QSpinBox>
#include <QRubberBand>
#include <QDrag>
#include <QDragEnterEvent>
#include <QDialogButtonBox>
#include <QInputDialog>
#include <QMimeData>
#include <QFormLayout>
#include <QVBoxLayout>
#include <QTabWidget>
#include <QSignalMapper>
#include <assert.h>
ToolbarEditDialog::ToolbarEditDialog( QWidget *_w, intf_thread_t *_p_intf)
: QVLCDialog( _w, _p_intf )
{
setWindowTitle( qtr( "Toolbars Editor" ) );
setWindowRole( "vlc-toolbars-editor" );
QGridLayout *mainLayout = new QGridLayout( this );
setMinimumWidth( 600 );
setAttribute( Qt::WA_DeleteOnClose );
/* main GroupBox */
QGroupBox *widgetBox = new QGroupBox( qtr( "Toolbar Elements") , this );
widgetBox->setSizePolicy( QSizePolicy::Preferred,
QSizePolicy::MinimumExpanding );
QGridLayout *boxLayout = new QGridLayout( widgetBox );
flatBox = new QCheckBox( qtr( "Flat Button" ) );
flatBox->setToolTip( qtr( "Next widget style" ) );
bigBox = new QCheckBox( qtr( "Big Button" ) );
bigBox->setToolTip( flatBox->toolTip() );
shinyBox = new QCheckBox( qtr( "Native Slider" ) );
shinyBox->setToolTip( flatBox->toolTip() );
boxLayout->addWidget( new WidgetListing( p_intf, this ), 1, 0, 1, -1 );
boxLayout->addWidget( flatBox, 0, 0 );
boxLayout->addWidget( bigBox, 0, 1 );
boxLayout->addWidget( shinyBox, 0, 2 );
mainLayout->addWidget( widgetBox, 5, 0, 3, 6 );
QTabWidget *tabWidget = new QTabWidget();
mainLayout->addWidget( tabWidget, 1, 0, 4, 9 );
/* Main ToolBar */
QWidget *mainToolbarBox = new QWidget();
tabWidget->addTab( mainToolbarBox, qtr( "Main Toolbar" ) );
QFormLayout *mainTboxLayout = new QFormLayout( mainToolbarBox );
positionCheckbox = new QCheckBox( qtr( "Above the Video" ) );
positionCheckbox->setChecked(
getSettings()->value( "MainWindow/ToolbarPos", false ).toBool() );
mainTboxLayout->addRow( new QLabel( qtr( "Toolbar position:" ) ),
positionCheckbox );
QString line1 = getSettings()->value( "MainWindow/MainToolbar1",
MAIN_TB1_DEFAULT ).toString();
controller1 = new DroppingController( p_intf, line1, this );
mainTboxLayout->addRow( new QLabel( qtr("Line 1:") ), controller1 );
QString line2 = getSettings()->value( "MainWindow/MainToolbar2",
MAIN_TB2_DEFAULT ).toString();
controller2 = new DroppingController( p_intf, line2, this );
mainTboxLayout->addRow( new QLabel( qtr("Line 2:") ), controller2 );
/* TimeToolBar */
QString line = getSettings()->value( "MainWindow/InputToolbar",
INPT_TB_DEFAULT ).toString();
controller = new DroppingController( p_intf, line, this );
QWidget *timeToolbarBox = new QWidget();
timeToolbarBox->setLayout( new QVBoxLayout() );
timeToolbarBox->layout()->addWidget( controller );
tabWidget->addTab( timeToolbarBox, qtr( "Time Toolbar" ) );
/* Advanced ToolBar */
QString lineA = getSettings()->value( "MainWindow/AdvToolbar",
ADV_TB_DEFAULT ).toString();
controllerA = new DroppingController( p_intf, lineA, this );
QWidget *advToolbarBox = new QWidget();
advToolbarBox->setLayout( new QVBoxLayout() );
advToolbarBox->layout()->addWidget( controllerA );
tabWidget->addTab( advToolbarBox, qtr( "Advanced Widget" ) );
/* FSCToolBar */
QString lineFSC = getSettings()->value( "MainWindow/FSCtoolbar",
FSC_TB_DEFAULT ).toString();
controllerFSC = new DroppingController( p_intf, lineFSC, this );
QWidget *FSCToolbarBox = new QWidget();
FSCToolbarBox->setLayout( new QVBoxLayout() );
FSCToolbarBox->layout()->addWidget( controllerFSC );
tabWidget->addTab( FSCToolbarBox, qtr( "Fullscreen Controller" ) );
/* Profile */
QGridLayout *profileBoxLayout = new QGridLayout();
profileCombo = new QComboBox;
QToolButton *newButton = new QToolButton;
newButton->setIcon( QIcon( ":/new.svg" ) );
newButton->setToolTip( qtr("New profile") );
QToolButton *deleteButton = new QToolButton;
deleteButton->setIcon( QIcon( ":/toolbar/clear.svg" ) );
deleteButton->setToolTip( qtr( "Delete the current profile" ) );
profileBoxLayout->addWidget( new QLabel( qtr( "Select profile:" ) ), 0, 0 );
profileBoxLayout->addWidget( profileCombo, 0, 1 );
profileBoxLayout->addWidget( newButton, 0, 2 );
profileBoxLayout->addWidget( deleteButton, 0, 3 );
mainLayout->addLayout( profileBoxLayout, 0, 0, 1, 9 );
/* Fill combos */
int i_size = getSettings()->beginReadArray( "ToolbarProfiles" );
for( int i = 0; i < i_size; i++ )
{
getSettings()->setArrayIndex(i);
profileCombo->addItem( getSettings()->value( "ProfileName" ).toString(),
getSettings()->value( "Value" ).toString() );
}
getSettings()->endArray();
/* Load defaults ones if we have no combos */
/* We could decide that we load defaults on first launch of the dialog
or when the combo is back to 0. I choose the second solution, because some clueless
user might hit on delete a bit too much, but discussion is opened. -- jb */
if( i_size == 0 )
{
profileCombo->addItem( PROFILE_NAME_6, QString( VALUE_6 ) );
profileCombo->addItem( PROFILE_NAME_1, QString( VALUE_1 ) );
profileCombo->addItem( PROFILE_NAME_2, QString( VALUE_2 ) );
profileCombo->addItem( PROFILE_NAME_3, QString( VALUE_3 ) );
profileCombo->addItem( PROFILE_NAME_4, QString( VALUE_4 ) );
profileCombo->addItem( PROFILE_NAME_5, QString( VALUE_5 ) );
}
profileCombo->setCurrentIndex( -1 );
/* Build and prepare our preview */
PreviewWidget *previewWidget = new PreviewWidget( controller, controller1, controller2,
positionCheckbox->isChecked() );
QGroupBox *previewBox = new QGroupBox( qtr("Preview"), this );
previewBox->setLayout( new QVBoxLayout() );
previewBox->layout()->addWidget( previewWidget );
mainLayout->addWidget( previewBox, 5, 6, 3, 3 );
CONNECT( positionCheckbox, stateChanged(int),
previewWidget, setBarsTopPosition(int) );
/* Buttons */
QDialogButtonBox *okCancel = new QDialogButtonBox;
QPushButton *okButton = new QPushButton( qtr( "Cl&ose" ), this );
okButton->setDefault( true );
QPushButton *cancelButton = new QPushButton( qtr( "&Cancel" ), this );
okCancel->addButton( okButton, QDialogButtonBox::AcceptRole );
okCancel->addButton( cancelButton, QDialogButtonBox::RejectRole );
BUTTONACT( deleteButton, deleteProfile() );
BUTTONACT( newButton, newProfile() );
CONNECT( profileCombo, currentIndexChanged( int ), this, changeProfile( int ) );
BUTTONACT( okButton, close() );
BUTTONACT( cancelButton, cancel() );
mainLayout->addWidget( okCancel, 8, 0, 1, 9 );
}
ToolbarEditDialog::~ToolbarEditDialog()
{
getSettings()->beginWriteArray( "ToolbarProfiles" );
for( int i = 0; i < profileCombo->count(); i++ )
{
getSettings()->setArrayIndex(i);
getSettings()->setValue( "ProfileName", profileCombo->itemText( i ) );
getSettings()->setValue( "Value", profileCombo->itemData( i ) );
}
getSettings()->endArray();
}
void ToolbarEditDialog::newProfile()
{
bool ok;
QString name = QInputDialog::getText( this, qtr( "Profile Name" ),
qtr( "Please enter the new profile name." ), QLineEdit::Normal, 0, &ok );
if( !ok ) return;
QString temp = QString::number( !!positionCheckbox->isChecked() );
temp += "|" + controller1->getValue();
temp += "|" + controller2->getValue();
temp += "|" + controllerA->getValue();
temp += "|" + controller->getValue();
temp += "|" + controllerFSC->getValue();
profileCombo->addItem( name, temp );
profileCombo->setCurrentIndex( profileCombo->count() - 1 );
}
void ToolbarEditDialog::deleteProfile()
{
profileCombo->removeItem( profileCombo->currentIndex() );
}
void ToolbarEditDialog::changeProfile( int i )
{
QStringList qs_list = profileCombo->itemData( i ).toString().split( "|" );
if( qs_list.count() < 6 )
return;
positionCheckbox->setChecked( qs_list[0].toInt() );
controller1->resetLine( qs_list[1] );
controller2->resetLine( qs_list[2] );
controllerA->resetLine( qs_list[3] );
controller->resetLine( qs_list[4] );
controllerFSC->resetLine( qs_list[5] );
}
void ToolbarEditDialog::close()
{
bool isChecked = getSettings()->value( "MainWindow/ToolbarPos" ).toBool();
QString c1 = getSettings()->value( "MainWindow/MainToolbar1" ).toString();
QString c2 = getSettings()->value( "MainWindow/MainToolbar2" ).toString();
QString cA = getSettings()->value( "MainWindow/AdvToolbar" ).toString();
QString c = getSettings()->value( "MainWindow/InputToolbar" ).toString();
QString cFSC = getSettings()->value( "MainWindow/FSCToolbar" ).toString();
if ( isChecked == positionCheckbox->isChecked()
&& c1 == controller1->getValue()
&& c2 == controller2->getValue()
&& cA == controllerA->getValue()
&& c == controller->getValue()
&& cFSC == controllerFSC->getValue() )
{
reject();
return;
}
getSettings()->setValue( "MainWindow/ToolbarPos", !!positionCheckbox->isChecked() );
getSettings()->setValue( "MainWindow/MainToolbar1", controller1->getValue() );
getSettings()->setValue( "MainWindow/MainToolbar2", controller2->getValue() );
getSettings()->setValue( "MainWindow/AdvToolbar", controllerA->getValue() );
getSettings()->setValue( "MainWindow/InputToolbar", controller->getValue() );
getSettings()->setValue( "MainWindow/FSCtoolbar", controllerFSC->getValue() );
getSettings()->sync();
accept();
}
void ToolbarEditDialog::cancel()
{
reject();
}
PreviewWidget::PreviewWidget( QWidget *a, QWidget *b, QWidget *c, bool barsTopPosition )
: QWidget( a )
{
bars[0] = a;
bars[1] = b;
bars[2] = c;
for ( int i=0; i<3; i++ ) bars[i]->installEventFilter( this );
setAutoFillBackground( true );
setBarsTopPosition( barsTopPosition );
}
void PreviewWidget::setBarsTopPosition( int b )
{
b_top = b;
repaint();
}
void PreviewWidget::paintEvent( QPaintEvent * )
{
int i_total = 0, i_offset = 0, i;
QPainter painter( this );
QPixmap pixmaps[3];
for( int i=0; i<3; i++ )
{
pixmaps[i] = bars[i]->grab( bars[i]->contentsRect() );
/* Because non shown widgets do not have their bitmap updated, we need
to force redraw to grab a pixmap matching layout size */
if( pixmaps[i].size() != bars[i]->contentsRect().size() )
{
bars[i]->layout()->invalidate();
pixmaps[i] = bars[i]->grab( bars[i]->contentsRect() );
}
for( int j=0; j < bars[i]->layout()->count(); j++ )
{
QLayoutItem *item = bars[i]->layout()->itemAt( j );
if ( !strcmp( item->widget()->metaObject()->className(), "QLabel" ) )
{
QPainter eraser( &pixmaps[i] );
eraser.fillRect( item->geometry(), palette().background() );
eraser.end();
}
}
pixmaps[i] = pixmaps[i].scaled( size(), Qt::KeepAspectRatio );
}
for( i=0; i<3; i++ )
i_total += pixmaps[i].size().height();
/* Draw top bars */
i = ( b_top ) ? 1 : 3;
for( ; i<3; i++ )
{
painter.drawPixmap( pixmaps[i].rect().translated( 0, i_offset ), pixmaps[i] );
i_offset += pixmaps[i].rect().height();
}
/* Draw central area */
QRect conearea( 0, i_offset, size().width(), size().height() - i_total );
painter.fillRect( conearea, Qt::black );
QPixmap cone = QPixmap( ":/logo/vlc128.png" );
if ( ( conearea.size() - QSize(10, 10) - cone.size() ).isEmpty() )
cone = cone.scaled( conearea.size() - QSize(10, 10), Qt::KeepAspectRatio );
if ( cone.size().isValid() )
{
painter.drawPixmap( ((conearea.size() - cone.size()) / 2).width(),
i_offset + ((conearea.size() - cone.size()) / 2).height(),
cone );
}
/* Draw bottom bars */
i_offset += conearea.height();
for( i = 0 ; i< ((b_top) ? 1 : 3); i++ )
{
painter.drawPixmap( pixmaps[i].rect().translated( 0, i_offset ), pixmaps[i] );
i_offset += pixmaps[i].rect().height();
}
/* Draw overlay */
painter.fillRect( rect(), QColor( 255, 255, 255, 128 ) );
painter.end();
}
bool PreviewWidget::eventFilter( QObject *obj, QEvent *event )
{
if ( obj == this )
return QWidget::eventFilter( obj, event );
if ( event->type() == QEvent::LayoutRequest )
repaint();
return false;
}
/************************************************
* Widget Listing:
* Creation of the list of drawed lovely buttons
************************************************/
WidgetListing::WidgetListing( intf_thread_t *p_intf, QWidget *_parent )
: QListWidget( _parent )
{
/* We need the parent to know the options checked */
parent = qobject_cast<ToolbarEditDialog *>(_parent);
assert( parent );
/* Normal options */
setViewMode( QListView::ListMode );
setTextElideMode( Qt::ElideNone );
setDragEnabled( true );
int icon_size = fontMetrics().height();
setIconSize( QSize( icon_size * 2, icon_size ) );
/* All the buttons do not need a special rendering */
for( int i = 0; i < BUTTON_MAX; i++ )
{
QListWidgetItem *widgetItem = new QListWidgetItem( this );
widgetItem->setText( qtr( nameL[i] ) );
widgetItem->setSizeHint( QSize( widgetItem->sizeHint().width(), 32 ) );
widgetItem->setIcon( QIcon( iconL[i] ) );
widgetItem->setData( Qt::UserRole, QVariant( i ) );
widgetItem->setToolTip( widgetItem->text() );
addItem( widgetItem );
}
/* Spacers are yet again a different thing */
QListWidgetItem *widgetItem = new QListWidgetItem( QIcon( ":/toolbar/space.svg" ),
qtr( "Spacer" ), this );
widgetItem->setData( Qt::UserRole, WIDGET_SPACER );
widgetItem->setToolTip( widgetItem->text() );
widgetItem->setSizeHint( QSize( widgetItem->sizeHint().width(), 32 ) );
addItem( widgetItem );
widgetItem = new QListWidgetItem( QIcon( ":/toolbar/space.svg" ),
qtr( "Expanding Spacer" ), this );
widgetItem->setData( Qt::UserRole, WIDGET_SPACER_EXTEND );
widgetItem->setToolTip( widgetItem->text() );
widgetItem->setSizeHint( QSize( widgetItem->sizeHint().width(), 32 ) );
addItem( widgetItem );
/**
* For all other widgets, we create then, do a pseudo rendering in
* a pixmaps for the view, and delete the object
*
* A lot of code is retaken from the Abstract, but not exactly...
* So, rewrite.
* They are better ways to deal with this, but I doubt that this is
* necessary. If you feel like you have the time, be my guest.
* --
* jb
**/
for( int i = SPLITTER; i < SPECIAL_MAX; i++ )
{
QWidget *widget = NULL;
QListWidgetItem *widgetItem = new QListWidgetItem;
widgetItem->setSizeHint( QSize( widgetItem->sizeHint().width(), 32 ) );
switch( i )
{
case SPLITTER:
{
QFrame *line = new QFrame( this );
line->setFrameShape( QFrame::VLine );
line->setFrameShadow( QFrame::Raised );
line->setLineWidth( 0 ); line->setMidLineWidth( 1 );
widget = line;
}
widgetItem->setText( qtr("Splitter") );
break;
case INPUT_SLIDER:
{
SeekSlider *slider = new SeekSlider( p_intf, Qt::Horizontal, this );
widget = slider;
}
widgetItem->setText( qtr("Time Slider") );
break;
case VOLUME:
{
SoundWidget *snd = new SoundWidget( this, p_intf,
parent->getOptions() & WIDGET_SHINY );
widget = snd;
}
widgetItem->setText( qtr("Volume") );
break;
case VOLUME_SPECIAL:
{
QListWidgetItem *widgetItem = new QListWidgetItem( this );
widgetItem->setText( qtr("Small Volume") );
widgetItem->setIcon( QIcon( ":/toolbar/volume-medium.svg" ) );
widgetItem->setData( Qt::UserRole, QVariant( i ) );
addItem( widgetItem );
}
continue;
case TIME_LABEL:
{
QLabel *timeLabel = new QLabel( "12:42/2:12:42", this );
widget = timeLabel;
}
widgetItem->setText( qtr("Time") );
break;
case MENU_BUTTONS:
{
QWidget *discFrame = new QWidget( this );
//discFrame->setLineWidth( 1 );
QHBoxLayout *discLayout = new QHBoxLayout( discFrame );
discLayout->setSpacing( 0 ); discLayout->setMargin( 0 );
QToolButton *prevSectionButton = new QToolButton( discFrame );
prevSectionButton->setIcon( QIcon( ":/toolbar/dvd_prev.svg" ) );
prevSectionButton->setToolTip( qtr("Previous chapter") );
discLayout->addWidget( prevSectionButton );
QToolButton *menuButton = new QToolButton( discFrame );
menuButton->setIcon( QIcon( ":/toolbar/dvd_menu.svg" ) );
menuButton->setToolTip( qtr("Go to the DVD menu") );
discLayout->addWidget( menuButton );
QToolButton *nextButton = new QToolButton( discFrame );
nextButton->setIcon( QIcon( ":/toolbar/dvd_next.svg" ) );
nextButton->setToolTip( qtr("Next chapter") );
discLayout->addWidget( nextButton );
widget = discFrame;
}
widgetItem->setText( qtr("DVD menus") );
break;
case TELETEXT_BUTTONS:
{
QWidget *telexFrame = new QWidget( this );
QHBoxLayout *telexLayout = new QHBoxLayout( telexFrame );
telexLayout->setSpacing( 0 ); telexLayout->setMargin( 0 );
QToolButton *telexOn = new QToolButton( telexFrame );
telexOn->setIcon( QIcon( ":/toolbar/tv.svg" ) );
telexLayout->addWidget( telexOn );
QToolButton *telexTransparent = new QToolButton;
telexTransparent->setIcon( QIcon( ":/toolbar/tvtelx.svg" ) );
telexTransparent->setToolTip( qtr("Teletext transparency") );
telexLayout->addWidget( telexTransparent );
QSpinBox *telexPage = new QSpinBox;
telexLayout->addWidget( telexPage );
widget = telexFrame;
}
widgetItem->setText( qtr("Teletext") );
break;
case ADVANCED_CONTROLLER:
{
AdvControlsWidget *advControls = new AdvControlsWidget( p_intf, this );
widget = advControls;
}
widgetItem->setText( qtr("Advanced Buttons") );
break;
case PLAYBACK_BUTTONS:
{
widget = new QWidget;
DeckButtonsLayout *layout = new DeckButtonsLayout( widget );
BrowseButton *prev = new BrowseButton( widget, BrowseButton::Backward );
BrowseButton *next = new BrowseButton( widget );
RoundButton *play = new RoundButton( widget );
layout->setBackwardButton( prev );
layout->setForwardButton( next );
layout->setRoundButton( play );
}
widgetItem->setText( qtr("Playback Buttons") );
break;
case ASPECT_RATIO_COMBOBOX:
widget = new AspectRatioComboBox( p_intf );
widgetItem->setText( qtr("Aspect ratio selector") );
break;
case SPEED_LABEL:
widget = new SpeedLabel( p_intf, this );
widgetItem->setText( qtr("Speed selector") );
break;
case TIME_LABEL_ELAPSED:
widget = new QLabel( "2:42", this );
widgetItem->setText( qtr("Elapsed time") );
break;
case TIME_LABEL_REMAINING:
widget = new QLabel( "-2:42", this );
widgetItem->setText( qtr("Total/Remaining time") );
break;
default:
msg_Warn( p_intf, "This should not happen %i", i );
break;
}
if( widget == NULL ) continue;
widgetItem->setIcon( QIcon( widget->grab() ) );
widgetItem->setToolTip( widgetItem->text() );
widget->hide();
widgetItem->setData( Qt::UserRole, QVariant( i ) );
addItem( widgetItem );
delete widget;
}
}
void WidgetListing::startDrag( Qt::DropActions /*supportedActions*/ )
{
QListWidgetItem *item = currentItem();
QByteArray itemData;
QDataStream dataStream( &itemData, QIODevice::WriteOnly );
int i_type = item->data( Qt::UserRole ).toInt();
int i_option = parent->getOptions();
dataStream << i_type << i_option;
/* Create a new dragging event */
QDrag *drag = new QDrag( this );
/* With correct mimedata */
QMimeData *mimeData = new QMimeData;
mimeData->setData( "vlc/button-bar", itemData );
drag->setMimeData( mimeData );
/* And correct pixmap */
QPixmap aPixmap = item->icon().pixmap( QSize( 22, 22 ) );
drag->setPixmap( aPixmap );
drag->setHotSpot( QPoint( 20, 20 ) );
/* We want to keep a copy */
drag->exec( Qt::CopyAction | Qt::MoveAction );
}
/*
* The special controller with drag'n drop abilities.
* We don't do this in the main controller, since we don't want the OverHead
* to propagate there too
*/
DroppingController::DroppingController( intf_thread_t *_p_intf,
const QString& line,
QWidget *_parent )
: AbstractController( _p_intf, _parent )
{
RTL_UNAFFECTED_WIDGET
rubberband = NULL;
b_draging = false;
setAcceptDrops( true );
controlLayout = new QHBoxLayout( this );
controlLayout->setSpacing( 5 );
controlLayout->setMargin( 0 );
setFrameShape( QFrame::StyledPanel );
setFrameShadow( QFrame::Raised );
setMinimumHeight( 20 );
parseAndCreate( line, controlLayout );
}
void DroppingController::resetLine( const QString& line )
{
hide();
QLayoutItem *child;
while( (child = controlLayout->takeAt( 0 ) ) != 0 )
{
child->widget()->hide();
delete child;
}
parseAndCreate( line, controlLayout );
show();
}
/* Overloading the AbstractController one, because we don't manage the
Spacing items in the same ways */
void DroppingController::createAndAddWidget( QBoxLayout *newControlLayout,
int i_index,
buttonType_e i_type,
int i_option )
{
/* Special case for SPACERS, who aren't QWidgets */
if( i_type == WIDGET_SPACER || i_type == WIDGET_SPACER_EXTEND )
{
QLabel *label = new QLabel( this );
label->setPixmap( ImageHelper::loadSvgToPixmap( ":/toolbar/space.svg", height(), height() ) );
if( i_type == WIDGET_SPACER_EXTEND )
{
label->setSizePolicy( QSizePolicy::MinimumExpanding,
QSizePolicy::Preferred );
/* Create a box around it */
label->setFrameStyle( QFrame::Panel | QFrame::Sunken );
label->setLineWidth ( 1 );
label->setAlignment( Qt::AlignCenter );
}
else
label->setSizePolicy( QSizePolicy::Fixed,
QSizePolicy::Preferred );
/* Install event Filter for drag'n drop */
label->installEventFilter( this );
newControlLayout->insertWidget( i_index, label );
}
/* Normal Widgets */
else
{
QWidget *widg = createWidget( i_type, i_option );
if( !widg ) return;
/* Install the Event Filter in order to catch the drag */
widg->setParent( this );
widg->installEventFilter( this );
/* We are in a complex widget, we need to stop events on children too */
if( i_type >= TIME_LABEL && i_type < SPECIAL_MAX )
{
QList<QObject *>children = widg->children();
QObject *child;
foreach( child, children )
{
QWidget *childWidg;
if( ( childWidg = qobject_cast<QWidget *>( child ) ) )
{
child->installEventFilter( this );
childWidg->setEnabled( true );
}
}
/* Decorating the frames when possible */
QFrame *frame;
if( (i_type >= MENU_BUTTONS || i_type == TIME_LABEL) /* Don't bother to check for volume */
&& ( frame = qobject_cast<QFrame *>( widg ) ) != NULL )
{
frame->setFrameStyle( QFrame::Panel | QFrame::Raised );
frame->setLineWidth ( 1 );
}
}
/* Some Widgets are deactivated at creation */
widg->setEnabled( true );
widg->show();
newControlLayout->insertWidget( i_index, widg );
}
/* QList and QBoxLayout don't act the same with insert() */
if( i_index < 0 ) i_index = newControlLayout->count() - 1;
doubleInt *value = new doubleInt;
value->i_type = i_type;
value->i_option = i_option;
widgetList.insert( i_index, value );
}
DroppingController::~DroppingController()
{
qDeleteAll( widgetList );
widgetList.clear();
}
QString DroppingController::getValue()
{
QString qs = "";
for( int i = 0; i < controlLayout->count(); i++ )
{
doubleInt *dI = widgetList.at( i );
assert( dI );
qs.append( QString::number( dI->i_type ) );
if( dI->i_option ) qs.append( "-" + QString::number( dI->i_option ) );
qs.append( ';' );
}
return qs;
}
void DroppingController::dragEnterEvent( QDragEnterEvent * event )
{
if( event->mimeData()->hasFormat( "vlc/button-bar" ) )
event->accept();
else
event->ignore();
}
void DroppingController::dragMoveEvent( QDragMoveEvent *event )
{
QPoint origin = event->pos();
int i_pos = getParentPosInLayout( origin );
bool b_end = false;
/* Both sides of the frame */
if( i_pos == -1 )
{
if( rubberband ) rubberband->hide();
return;
}
/* Last item is special because of underlying items */
if( i_pos >= controlLayout->count() )
{
i_pos--;
b_end = true;
}
/* Query the underlying item for size && middles */
QLayoutItem *tempItem = controlLayout->itemAt( i_pos ); assert( tempItem );
QWidget *temp = tempItem->widget(); assert( temp );
/* Position assignment */
origin.ry() = 0;
origin.rx() = temp->x() - 2;
if( b_end ) origin.rx() += temp->width();
if( !rubberband )
rubberband = new QRubberBand( QRubberBand::Line, this );
rubberband->setGeometry( origin.x(), origin.y(), 4, height() );
rubberband->show();
}
inline int DroppingController::getParentPosInLayout( QPoint point )
{
point.ry() = height() / 2 ;
QPoint origin = mapToGlobal ( point );
QWidget *tempWidg = QApplication::widgetAt( origin );
if( tempWidg == NULL )
return -1;
int i = controlLayout->indexOf( tempWidg );
if( i == -1 )
{
i = controlLayout->indexOf( tempWidg->parentWidget() );
tempWidg = tempWidg->parentWidget();
}
/* Return the nearest position */
if( ( point.x() - tempWidg->x() > tempWidg->width() / 2 ) && i != -1 )
i++;
// msg_Dbg( p_intf, "%i", i);
return i;
}
void DroppingController::dropEvent( QDropEvent *event )
{
int i = getParentPosInLayout( event->pos() );
QByteArray data = event->mimeData()->data( "vlc/button-bar" );
QDataStream dataStream(&data, QIODevice::ReadOnly);
int i_option = 0, i_type = 0;
dataStream >> i_type >> i_option;
createAndAddWidget( controlLayout, i, (buttonType_e)i_type, i_option );
/* Hide by precaution, you don't exactly know what could have happened in
between */
if( rubberband ) rubberband->hide();
}
void DroppingController::dragLeaveEvent ( QDragLeaveEvent * event )
{
if( rubberband ) rubberband->hide();
event->accept();
}
/**
* Overloading doAction to block any action
**/
void DroppingController::doAction( int i )
{
VLC_UNUSED( i );
}
bool DroppingController::eventFilter( QObject *obj, QEvent *event )
{
switch( event->type() )
{
case QEvent::MouseButtonPress:
b_draging = true;
return true;
case QEvent::MouseButtonRelease:
b_draging = false;
return true;
case QEvent::MouseMove:
{
if( !b_draging ) return true;
QWidget *widg = static_cast<QWidget*>(obj);
QByteArray itemData;
QDataStream dataStream( &itemData, QIODevice::WriteOnly );
int i = -1;
i = controlLayout->indexOf( widg );
if( i == -1 )
{
i = controlLayout->indexOf( widg->parentWidget() );
widg = widg->parentWidget();
/* NOTE: be extra-careful Now with widg access */
}
if( i == -1 ) return true;
i_dragIndex = i;
doubleInt *dI = widgetList.at( i );
int i_type = dI->i_type;
int i_option = dI->i_option;
dataStream << i_type << i_option;
/* With correct mimedata */
QMimeData *mimeData = new QMimeData;
mimeData->setData( "vlc/button-bar", itemData );
QDrag *drag = new QDrag( widg );
drag->setMimeData( mimeData );
/* Remove before the drag to not mess DropEvent,
that will createAndAddWidget */
widgetList.removeAt( i );
controlLayout->removeWidget( widg );
widg->hide();
/* Start the effective drag */
drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::MoveAction);
b_draging = false;
delete dI;
}
return true;
case QEvent::MouseButtonDblClick:
case QEvent::EnabledChange:
case QEvent::Hide:
case QEvent::HideToParent:
case QEvent::Move:
case QEvent::ZOrderChange:
return true;
default:
return false;
}
}
|
joe4568/centreon-broker | neb/inc/com/centreon/broker/neb/downtime_serializable.hh | /*
** Copyright 2009-2013 Centreon
**
** 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.
**
** For more information : <EMAIL>
*/
#ifndef CCB_NEB_DOWNTIME_SERIALIZABLE_HH
# define CCB_NEB_DOWNTIME_SERIALIZABLE_HH
# include <string>
# include <istream>
# include <ostream>
# include <QString>
# include "com/centreon/broker/neb/downtime.hh"
# include "com/centreon/broker/misc/shared_ptr.hh"
# include "com/centreon/broker/ceof/ceof_serializable.hh"
# include "com/centreon/broker/namespace.hh"
CCB_BEGIN()
namespace neb {
/**
* @class downtime_serializable downtime_serializable.hh "com/centreon/broker/neb/downtime_serializable.hh"
* @brief Represent a serializable Centreon Engine Object File downtime.
*/
class downtime_serializable
: public ceof::ceof_serializable {
public:
downtime_serializable();
downtime_serializable(
downtime_serializable const& other);
downtime_serializable&
operator=(downtime_serializable const& other);
virtual ~downtime_serializable();
template <typename U, U (downtime::* member)>
std::string get_downtime_member() const;
template <typename U, U (downtime::* member)>
void set_downtime_member(std::string const& val);
misc::shared_ptr<downtime>
get_downtime() const;
virtual void visit(ceof::ceof_visitor& visitor);
private:
misc::shared_ptr<downtime>
_downtime;
};
// Stream operators for QString.
std::istream& operator>>(std::istream& stream, QString& fake_str);
std::ostream& operator<<(std::ostream& stream, QString const& fake_str);
}
CCB_END()
#endif // !CCB_NEB_TIMEPERIOD_SERIALIZABLE_HH
|
atuldada/checker-framework | checker/jtreg/unboundedWildcards/issue1428/T.java | <filename>checker/jtreg/unboundedWildcards/issue1428/T.java<gh_stars>0
/*
* @test
* @summary Test for Issue 1428.
* https://github.com/typetools/checker-framework/issues/1428
*
* @compile B.java
* @compile -XDrawDiagnostics -processor org.checkerframework.checker.tainting.TaintingChecker -AprintErrorStack T.java
*/
import java.util.Collections;
import java.util.List;
class T {
public List<L<?>> f(B b) {
return true ? Collections.<L<?>>emptyList() : b.getItems();
}
}
|
Smoudii/MigrantHub | MigrantHub/client_new/src/home/Main.js | import React, { Component } from 'react';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import logo from '../logo.svg';
import FriendPanel from '../components/FriendPanel/FriendPanel';
import NavPanel from '../components/NavPanel/NavPanel';
import Header from '../components/Header/Header';
import Sidebar from '../components/Sidebar/Sidebar';
import ServiceCategory from '../services/ServiceCategory';
import ServiceList from '../services/ServiceList';
import SearchBar from '../components/SearchBar';
const styles = theme => ({
app: {
marginLeft: 100,
//marginRight: 36,
},
});
class Main extends Component {
state = {
appName: 'Migrant Hub',
appLogo: logo,
userPic: logo,
navOptions: [
{ description: 'Services', link: '/services' },
{ description: 'Events', link: '/events' },
],
navPanelVisibility: true,
friendPanelVisibility: false,
serviceCategoryVisibility: true,
SearchBarVisibility: true,
};
render() {
const { classes } = this.props;
const {
appLogo, appName, userPic, navPanelVisibility,
navOptions, friendPanelVisibility, friends, serviceCategoryVisibility, SearchBarVisibility,
} = this.state;
return (
<div>
{/* <Header
appLogo={appLogo}
appName={appName}
userPic={userPic}
/> */}
<div className={classes.app}>
<Grid item xs={1}>
<div className="Panel">{navPanelVisibility && <NavPanel />}</div>
</Grid>
<Grid>
<Grid item lg={10}>
<div className="Main-feed">
<div className="">{SearchBarVisibility && <SearchBar />}</div>
</div>
</Grid>
<Grid item lg={10}>
<div className="Main-feed">
<div className="">{serviceCategoryVisibility && <ServiceCategory location = {this.props.location} />}</div>
</div>
</Grid>
<Grid item xs={3}>
<div className="Panel">{friendPanelVisibility && <FriendPanel />}</div>
</Grid>
</Grid>
</div>
</div>
);
}
}
export default withStyles(styles)(Main);
|
netarchivesuite/webarchive-commons | src/main/java/org/archive/util/iterator/FilterStringIterator.java | package org.archive.util.iterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.archive.util.StringFieldExtractor;
public class FilterStringIterator implements Iterator<String> {
private static final Logger LOGGER =
Logger.getLogger(FilterStringIterator.class.getName());
private static final int DEFAULT_FIELD = 0;
private static final char DEFAULT_DELIM = ' ';
private int field = DEFAULT_FIELD;
private char delim = DEFAULT_DELIM;
private StringFilter filter;
private Iterator<String> wrapped;
private StringFieldExtractor extractor;
private String cachedNext;
public FilterStringIterator(Iterator<String> wrapped, StringFilter filter) {
this.wrapped = wrapped;
this.filter = filter;
cachedNext = null;
extractor = new StringFieldExtractor(delim, field);
}
/**
* @return the field
*/
public int getField() {
return field;
}
/**
* @param field the field to set
*/
public void setField(int field) {
this.field = field;
extractor = new StringFieldExtractor(delim, field);
}
/**
* @return the delim
*/
public char getDelim() {
return delim;
}
/**
* @param delim the delim to set
*/
public void setDelim(char delim) {
this.delim = delim;
extractor = new StringFieldExtractor(delim, field);
}
public boolean hasNext() {
if(cachedNext != null) {
return true;
}
while(true) {
if(!wrapped.hasNext()) {
return false;
}
String tmp = wrapped.next();
String f = extractor.extract(tmp);
if(filter.isFiltered(f)) {
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Filtered:" + f);
}
} else {
cachedNext = tmp;
return true;
}
}
}
public String next() {
if(cachedNext == null) {
throw new NoSuchElementException("Call hasNext() first");
}
String tmp = cachedNext;
cachedNext = null;
return tmp;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
|
smolsbs/aoc | 2015/day-15/fuckyou.py | import re
def igscore(ig, ms, k): return max(sum([ing[k] * m for ing, m in zip(ig, ms)]), 0)
def score(ig, m): return igscore(ig, m, "cap") * igscore(ig, m, "dur") * igscore(ig, m, "flav") * igscore(ig, m, "text")
def find_max_score(ingredients, current, mass, remaining_weight):
if current == len(ingredients)-1:
mass[current] = remaining_weight
if igscore(ingredients, mass, "cal") != 500: return 0
return score(ingredients, mass)
best_score = 0
for m in xrange(1, remaining_weight):
mass[current] = m
best_score = max(best_score, find_max_score(ingredients,
current+1,
mass,
remaining_weight-m))
return best_score
ingredients = []
with open('input', 'r') as fh:
p = re.compile(r'^([A-Za-z]+): capacity (-?[0-9]+), durability (-?[0-9]+), flavor (-?[0-9]+), texture (-?[0-9]+), calories (-?[0-9]+)$')
for l in fh:
name, cap, dur, flav, text, cal = p.findall(l.strip())[0]
ingredients.append({"name": name, "cap": int(cap), "dur": int(dur), "flav": int(flav), "text": int(text), "cal": int(cal)})
print find_max_score(ingredients, 0, [0]*len(ingredients), 100) |
Tifosi-M/FlySky | SmartMemoWeb/src/domain/Card/CardDb.java | <reponame>Tifosi-M/FlySky<gh_stars>0
package domain.Card;
/**
* CardDb entity. @author MyEclipse Persistence Tools
*/
public class CardDb extends AbstractCardDb implements java.io.Serializable {
// Constructors
/** default constructor */
public CardDb() {
}
/** minimal constructor */
public CardDb(String tel) {
super(tel);
}
/** full constructor */
public CardDb(String tel, byte[] dbfile) {
super(tel, dbfile);
}
}
|
mfarrera/algorithm-reference-library | workflows/mpi/simple-mpi.py | """Simple demonstration of the use of ARL functions with MPI
Run with:
mpiexec -n 4 python simple-mpi.py
"""
import logging
import numpy
from mpi4py import MPI
import astropy.units as u
from astropy.coordinates import SkyCoord
from data_models.polarisation import PolarisationFrame
from libs.image.operations import create_empty_image_like
from processing_components.simulation.testing_support import create_test_image
from processing_components.image.gather_scatter import image_gather_facets, image_scatter_facets
# Define a simple function to take the square root of an image
def imagerooter(image_list) -> list():
new_image_list = []
for im in image_list:
newim = create_empty_image_like(im)
newim.data = numpy.sqrt(numpy.abs(im.data))
new_image_list.append(newim)
return new_image_list
if __name__ == '__main__':
logging.basicConfig(filename='simple-mpi.log',
filemode='a',
format='%(thread)s %(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
# Set up MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
facets = 8
assert facets * facets % size == 0
# Create test image
frequency = numpy.array([1e8])
phasecentre = SkyCoord(ra=+15.0 * u.deg, dec=-35.0 * u.deg, frame='icrs', equinox='J2000')
model = create_test_image(frequency=frequency, phasecentre=phasecentre, cellsize=0.001,
polarisation_frame=PolarisationFrame('stokesI'))
# Rank 0 scatters the test image
if rank == 0:
subimages = image_scatter_facets(model, facets=facets)
subimages = numpy.array_split(subimages, size)
else:
subimages = list()
sublist = comm.scatter(subimages, root=0)
root_images = imagerooter(sublist)
roots = comm.gather(root_images, root=0)
if rank == 0:
results = sum(roots, [])
root_model = create_empty_image_like(model)
result = image_gather_facets(results, root_model, facets=facets)
numpy.testing.assert_array_almost_equal_nulp(result.data ** 2, numpy.abs(model.data), 7)
|
maurizioabba/rose | tests/CompileTests/ElsaTestCases/gnu/dC0008.c | <reponame>maurizioabba/rose<filename>tests/CompileTests/ElsaTestCases/gnu/dC0008.c
// this form shows up in the kernel
int a[] = { [1] /*no = or : here*/ 0, [2] 10, [3] 13,};
struct A {
int x;
int y;
};
int main() {
struct A a = { .y /*no = or : here*/ 3, .x 8 };
}
|
dbdxnuliba/IHMC- | ihmc-robotics-toolkit/src/main/java/us/ihmc/robotics/geometry/yoFrameObjects/YoFrameEuclideanWaypoint.java | package us.ihmc.robotics.geometry.yoFrameObjects;
import static us.ihmc.robotics.math.frames.YoFrameVariableNameTools.createName;
import us.ihmc.euclid.referenceFrame.ReferenceFrame;
import us.ihmc.euclid.referenceFrame.interfaces.ReferenceFrameHolder;
import us.ihmc.euclid.tuple3D.interfaces.Point3DBasics;
import us.ihmc.euclid.tuple3D.interfaces.Point3DReadOnly;
import us.ihmc.euclid.tuple3D.interfaces.Vector3DBasics;
import us.ihmc.euclid.tuple3D.interfaces.Vector3DReadOnly;
import us.ihmc.robotics.geometry.frameObjects.FrameEuclideanWaypoint;
import us.ihmc.robotics.geometry.interfaces.EuclideanWaypointInterface;
import us.ihmc.robotics.geometry.transformables.EuclideanWaypoint;
import us.ihmc.yoVariables.registry.YoVariableRegistry;
import us.ihmc.yoVariables.variable.YoFramePoint3D;
import us.ihmc.yoVariables.variable.YoFrameVector3D;
public class YoFrameEuclideanWaypoint extends YoFrameWaypoint<YoFrameEuclideanWaypoint, FrameEuclideanWaypoint, EuclideanWaypoint>
implements EuclideanWaypointInterface<YoFrameEuclideanWaypoint>
{
private final YoFramePoint3D position;
private final YoFrameVector3D linearVelocity;
public YoFrameEuclideanWaypoint(String namePrefix, String nameSuffix, YoVariableRegistry registry, ReferenceFrame... referenceFrames)
{
super(new FrameEuclideanWaypoint(), namePrefix, nameSuffix, registry, referenceFrames);
position = createYoPosition(this, namePrefix, nameSuffix, registry);
linearVelocity = createYoLinearVelocity(this, namePrefix, nameSuffix, registry);
}
public static YoFramePoint3D createYoPosition(final ReferenceFrameHolder referenceFrameHolder, String namePrefix, String nameSuffix, YoVariableRegistry registry)
{
return new YoFramePoint3D(createName(namePrefix, "position", ""), nameSuffix, null, registry)
{
@Override
public ReferenceFrame getReferenceFrame()
{
return referenceFrameHolder.getReferenceFrame();
}
};
}
public static YoFrameVector3D createYoLinearVelocity(final ReferenceFrameHolder referenceFrameHolder, String namePrefix, String nameSuffix, YoVariableRegistry registry)
{
return new YoFrameVector3D(createName(namePrefix, "linearVelocity", ""), nameSuffix, null, registry)
{
@Override
public ReferenceFrame getReferenceFrame()
{
return referenceFrameHolder.getReferenceFrame();
}
};
}
@Override
public void setPosition(Point3DReadOnly position)
{
this.position.set(position);
}
@Override
public void setLinearVelocity(Vector3DReadOnly linearVelocity)
{
this.linearVelocity.set(linearVelocity);
}
@Override
public void setPositionToZero()
{
position.setToZero();
}
@Override
public void setLinearVelocityToZero()
{
linearVelocity.setToZero();
}
@Override
public void setPositionToNaN()
{
position.setToNaN();
}
@Override
public void setLinearVelocityToNaN()
{
linearVelocity.setToNaN();
}
@Override
public double positionDistance(YoFrameEuclideanWaypoint other)
{
return frameWaypoint.positionDistance(other.frameWaypoint);
}
@Override
public void getPosition(Point3DBasics positionToPack)
{
positionToPack.set(position);
}
@Override
public void getLinearVelocity(Vector3DBasics linearVelocityToPack)
{
linearVelocityToPack.set(linearVelocity);
}
@Override
protected void putYoValuesIntoFrameWaypoint()
{
EuclideanWaypoint simpleWaypoint = frameWaypoint.getGeometryObject();
simpleWaypoint.set(position, linearVelocity);
}
@Override
protected void getYoValuesFromFrameWaypoint()
{
EuclideanWaypoint simpleWaypoint = frameWaypoint.getGeometryObject();
position.set(simpleWaypoint.getPosition());
linearVelocity.set(simpleWaypoint.getLinearVelocity());
}
}
|
ClinicalOntology/QUICK | quick-api/src/main/java/org/reimagineehr/model/quick/api/event/MedicationStatement.java | package org.reimagineehr.model.quick.api.event;
import java.util.List;
import org.reimagineehr.model.quick.api.backbone.DosageInstruction;
import org.reimagineehr.model.quick.api.other.Medication;
import org.reimagineehr.model.quick.api.party.Party;
import org.reimagineehr.model.quick.api.event.Event;
/**
* Author: <NAME>
* GENERATED CODE - DO NOT EDIT
* Generated or updated on: Thu Jul 11 13:57:04 PDT 2019
* Copyright: University of Utah
* License: Apache 2
*/
public interface MedicationStatement extends Event {
List<DosageInstruction> getDosage();
void setDosage(List<DosageInstruction> arg);
public void addDosage(DosageInstruction arg);
Medication getMedication();
void setMedication(Medication arg);
Party getInformationSource();
void setInformationSource(Party arg);
} |
ThexXTURBOXx/TechReborn | src/main/java/techreborn/client/container/ContainerCompressor.java | <gh_stars>0
package techreborn.client.container;
import net.minecraft.entity.player.EntityPlayer;
import reborncore.client.gui.BaseSlot;
import reborncore.client.gui.SlotOutput;
import techreborn.api.gui.SlotUpgrade;
import techreborn.tiles.teir1.TileCompressor;
public class ContainerCompressor extends ContainerCrafting
{
public int connectionStatus;
EntityPlayer player;
TileCompressor tile;
public ContainerCompressor(TileCompressor tileGrinder, EntityPlayer player)
{
super(tileGrinder.crafter);
tile = tileGrinder;
this.player = player;
// input
this.addSlotToContainer(new BaseSlot(tileGrinder.inventory, 0, 56, 34));
this.addSlotToContainer(new SlotOutput(tileGrinder.inventory, 1, 116, 34));
// upgrades
this.addSlotToContainer(new SlotUpgrade(tileGrinder.inventory, 2, 152, 8));
this.addSlotToContainer(new SlotUpgrade(tileGrinder.inventory, 3, 152, 26));
this.addSlotToContainer(new SlotUpgrade(tileGrinder.inventory, 4, 152, 44));
this.addSlotToContainer(new SlotUpgrade(tileGrinder.inventory, 5, 152, 62));
int i;
for (i = 0; i < 3; ++i)
{
for (int j = 0; j < 9; ++j)
{
this.addSlotToContainer(new BaseSlot(player.inventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
}
}
for (i = 0; i < 9; ++i)
{
this.addSlotToContainer(new BaseSlot(player.inventory, i, 8 + i * 18, 142));
}
}
@Override
public boolean canInteractWith(EntityPlayer p_75145_1_)
{
return true;
}
}
|
erikorbons/axo | axo-core/src/main/java/axo/core/Operator.java | package axo.core;
import java.util.Objects;
import org.reactivestreams.Subscriber;
public abstract class Operator<T, R> implements Subscriber<T> {
private final StreamContext context;
private final Subscriber<? super R> subscriber;
public Operator (final StreamContext context, final Subscriber<? super R> subscriber) {
this.context = Objects.requireNonNull(context, "context cannot be null");
this.subscriber = subscriber;
}
public StreamContext getContext () {
return context;
}
protected Subscriber<? super R> getSubscriber () {
return subscriber;
}
}
|
fangweb/jainbox | client/src/pages/ViewMessage.js | import React, { Component } from 'react';
import { goBack } from 'connected-react-router';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Link } from 'react-router-dom';
import { PathConfig } from '../config';
import { ServiceContainer } from '../services';
import { wait } from '../helpers';
import PanelError from '../components/PanelError';
import Loader from '../components/Loader';
import '../assets/css/view-message.css';
class ViewMessage extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
message: null,
error: false
};
this.auth = ServiceContainer.auth();
}
async componentDidMount() {
const api = ServiceContainer.api();
const { messageId } = this.props.match.params;
await wait(300);
try {
const response = await api.viewMessage({ messageId });
const body = await response.json();
const event = new Date(body.created_at);
const time = event.toLocaleTimeString();
const date = event.toLocaleDateString();
this.setState({ message: { ...body, time, date }, loading: false });
} catch (e) {
console.error(e);
this.setState({ error: true, loading: false });
}
}
onNavigateBack = () => {
this.props.goBack();
};
renderUsernameSegment = (createdBy, receiver) => {
if (this.auth.getAuth().username === receiver) {
return <div className="username message-segment">From: {createdBy}</div>;
}
return <div className="username message-segment">To: {receiver}</div>;
};
render() {
const { loading, message, error } = this.state;
if (error) {
return (
<div className="view-message">
<PanelError message="There was an error" />
</div>
);
}
if (loading) {
return (
<div className="view-message">
<Loader />
</div>
);
}
return (
<div className="view-message">
<div className="top-bar">
{this.renderUsernameSegment(message.created_by, message.receiver)}
<div className="right-control">
<div className="time message-segment">{message.time}</div>
<div className="date message-segment">{message.date}</div>
<div
role="button"
tabIndex="0"
onClick={this.onNavigateBack}
onKeyDown={this.onNavigateBack}
className="back-btn message-segment"
>
<i className="fas fa-backward backwardsIcon" />
</div>
</div>
</div>
<div className="title message-segment">{message.title}</div>
<div className="content message-segment">
<pre>{message.message_text}</pre>
</div>
</div>
);
}
}
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
goBack
},
dispatch
);
export default connect(null, mapDispatchToProps)(ViewMessage);
|
ugurdogrusoz/chilay | src/main/java/org/ivis/layout/sbgn/Compaction.java | package org.ivis.layout.sbgn;
import java.util.ArrayList;
/**
* This class is used to apply compaction on a graph. First a visibility graph
* is constructed from the given set of nodes. Since visibility graphs are
* DAG's, apply topological sort. Then, try to translate each node's location
* vertically/horizontally (compact them)
*
* @author <NAME>
*
*/
public class Compaction
{
/**
* Stores the original provided list of vertices.
*/
private ArrayList<SbgnPDNode> vertices;
/**
* Visibility graph
*/
private VisibilityGraph visGraph;
/**
* Compaction direction: VERTICAL or HORIZONTAL
*/
private CompactionDirection direction;
/**
* Stores the topological sort results of the nodes
*/
ArrayList<SbgnPDNode> orderedNodeList;
/**
* Constructor
*
* @param vertices
* : list of vertices for visibility graph
*/
public Compaction(ArrayList<SbgnPDNode> vertices)
{
this.orderedNodeList = new ArrayList<SbgnPDNode>();
this.vertices = new ArrayList<SbgnPDNode>();
this.vertices = vertices;
}
/**
* Two times do the following: (first for vertical, second horizontal) First
* create a visibility graph for the given elements. The visibility graph is
* always a DAG, so perform a topological sort on the elements (the node
* that has in-degree 0 comes first), perform compaction.
*/
public void perform()
{
algorithmBody(CompactionDirection.VERTICAL);
removeVisibilityEdges();
algorithmBody(CompactionDirection.HORIZONTAL);
removeVisibilityEdges();
}
private void removeVisibilityEdges()
{
for(Object objNode : vertices)
{
SbgnPDNode sbgnNode = (SbgnPDNode) objNode;
for(int i = 0; i < sbgnNode.getEdges().size(); i++)
{
Object objEdge = sbgnNode.getEdges().get(i);
if( objEdge instanceof VisibilityEdge)
{
sbgnNode.getEdges().remove(i);
i--;
}
}
}
}
private void algorithmBody(CompactionDirection direction)
{
this.direction = direction;
visGraph = new VisibilityGraph(null, null, null);
// construct a visibility graph given the direction and vertices
visGraph.construct(this.direction, vertices);
if (visGraph.getEdges().size() > 0)
{
topologicallySort();
compactElements();
}
// positions of the vertices has changed. Update them.
vertices = (ArrayList<SbgnPDNode>) visGraph.getNodes();
}
/**
* Perform a DFS on the given graph nodes and then output the nodes in
* reverse order.
*/
private void topologicallySort()
{
// ensure that the vertices have not been marked as visited.
for (int i = 0; i < visGraph.getNodes().size(); i++)
{
SbgnPDNode s = (SbgnPDNode) visGraph.getNodes().get(i);
s.visited = false;
}
// ensure that the list is empty
orderedNodeList.clear();
DFS();
orderedNodeList = reverseList(orderedNodeList);
}
private void DFS()
{
for (int i = 0; i < visGraph.getNodes().size(); i++)
{
SbgnPDNode s = (SbgnPDNode) visGraph.getNodes().get(i);
if (!s.visited)
{
DFS_Visit(s);
}
}
}
private void DFS_Visit(SbgnPDNode s)
{
ArrayList<SbgnPDNode> neighbors = s.getChildrenNeighbors(null);
if (neighbors.size() == 0)
{
s.visited = true;
orderedNodeList.add(s);
return;
}
for (SbgnPDNode n : neighbors)
{
if (!n.visited)
DFS_Visit(n);
}
s.visited = true;
orderedNodeList.add(s);
}
/**
* Reverse the element order of a given list
*/
private ArrayList<SbgnPDNode> reverseList(ArrayList<SbgnPDNode> originalList)
{
ArrayList<SbgnPDNode> reverseOutput = new ArrayList<SbgnPDNode>();
for (int i = originalList.size() - 1; i >= 0; i--)
reverseOutput.add(originalList.get(i));
return reverseOutput;
}
/**
* This method visits the list that is the result of topological sort. For
* each node in that list, it looks for its incoming edges and finds the
* shortest one. Translates the node wrt the shortest edge.
*/
private void compactElements()
{
double distance;
for (SbgnPDNode s : orderedNodeList)
{
// find shortest incoming edge
VisibilityEdge edge = visGraph.findShortestEdge(s);
if (edge != null)
{
distance = edge.getLength();
if (direction == CompactionDirection.VERTICAL)
{
// bring the node closer to the source node and respect the
// buffer.
if (distance > SbgnPDConstants.COMPLEX_MEM_VERTICAL_BUFFER)
{
s.setLocation(
s.getLeft(),
(s.getTop() - (distance - SbgnPDConstants.COMPLEX_MEM_VERTICAL_BUFFER)));
}
else
{
s.setLocation(s.getLeft(), edge.getOtherEnd(s)
.getBottom()
+ SbgnPDConstants.COMPLEX_MEM_VERTICAL_BUFFER);
}
}
else if (direction == CompactionDirection.HORIZONTAL)
{
if (distance > SbgnPDConstants.COMPLEX_MEM_HORIZONTAL_BUFFER)
{
s.setLocation(
(s.getLeft() - (distance - SbgnPDConstants.COMPLEX_MEM_HORIZONTAL_BUFFER)),
s.getTop());
}
else
{
s.setLocation(
edge.getOtherEnd(s).getRight()
+ SbgnPDConstants.COMPLEX_MEM_HORIZONTAL_BUFFER,
s.getTop());
}
}
}
}
}
/**
* This method prints the edges of the visibility graph.
*/
@SuppressWarnings("unused")
private void printEdges()
{
System.out.println("# of edges: " + visGraph.getEdges().size());
for (int i = 0; i < visGraph.getEdges().size(); i++)
{
VisibilityEdge e = (VisibilityEdge) visGraph.getEdges().get(i);
System.out.println("between: " + e.getSource().label + " "
+ e.getTarget().label);
}
}
/**
* This method prints the nodes of the visibility graph.
*/
@SuppressWarnings("unused")
private void printGraphVertices()
{
for (int i = 0; i < visGraph.getNodes().size(); i++)
{
SbgnPDNode s = (SbgnPDNode) visGraph.getNodes().get(i);
System.out.println(s.label + " (" + s.getLeft() + ", " + s.getTop()
+ ")" + " || " + "(" + (s.getLeft() + s.getWidth()) + ", "
+ (s.getTop() + s.getHeight()) + ")");
}
System.out.println();
}
public enum CompactionDirection
{
VERTICAL, HORIZONTAL
};
} |
olavloite/spanner-jdbc | src/main/java/nl/topicus/jdbc/statement/CloudSpannerParameterMetaData.java | package nl.topicus.jdbc.statement;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.ParameterMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import nl.topicus.jdbc.metadata.AbstractCloudSpannerWrapper;
public class CloudSpannerParameterMetaData extends AbstractCloudSpannerWrapper
implements ParameterMetaData {
private final CloudSpannerPreparedStatement statement;
CloudSpannerParameterMetaData(CloudSpannerPreparedStatement statement) throws SQLException {
this.statement = statement;
statement.getParameterStore().fetchMetaData(statement.getConnection());
}
@Override
public int getParameterCount() throws SQLException {
return statement.getParameterStore().getHighestIndex();
}
@Override
public int isNullable(int param) throws SQLException {
Integer nullable = statement.getParameterStore().getNullable(param);
return nullable == null ? parameterNullableUnknown : nullable.intValue();
}
@Override
public boolean isSigned(int param) throws SQLException {
int type = getParameterType(param);
return type == Types.DOUBLE || type == Types.FLOAT || type == Types.BIGINT
|| type == Types.INTEGER || type == Types.DECIMAL;
}
@Override
public int getPrecision(int param) throws SQLException {
Integer length = statement.getParameterStore().getScaleOrLength(param);
return length == null ? 0 : length.intValue();
}
@Override
public int getScale(int param) throws SQLException {
return 0;
}
@Override
public int getParameterType(int param) throws SQLException {
Integer type = statement.getParameterStore().getType(param);
if (type != null)
return type.intValue();
Object value = statement.getParameterStore().getParameter(param);
if (value == null) {
return Types.OTHER;
} else if (Boolean.class.isAssignableFrom(value.getClass())) {
return Types.BOOLEAN;
} else if (Byte.class.isAssignableFrom(value.getClass())) {
return Types.TINYINT;
} else if (Short.class.isAssignableFrom(value.getClass())) {
return Types.SMALLINT;
} else if (Integer.class.isAssignableFrom(value.getClass())) {
return Types.INTEGER;
} else if (Long.class.isAssignableFrom(value.getClass())) {
return Types.BIGINT;
} else if (Float.class.isAssignableFrom(value.getClass())) {
return Types.FLOAT;
} else if (Double.class.isAssignableFrom(value.getClass())) {
return Types.DOUBLE;
} else if (BigDecimal.class.isAssignableFrom(value.getClass())) {
return Types.DECIMAL;
} else if (Date.class.isAssignableFrom(value.getClass())) {
return Types.DATE;
} else if (Timestamp.class.isAssignableFrom(value.getClass())) {
return Types.TIMESTAMP;
} else if (Time.class.isAssignableFrom(value.getClass())) {
return Types.TIME;
} else if (String.class.isAssignableFrom(value.getClass())) {
return Types.NVARCHAR;
} else if (byte[].class.isAssignableFrom(value.getClass())) {
return Types.BINARY;
} else {
return Types.OTHER;
}
}
@Override
public String getParameterTypeName(int param) throws SQLException {
return getGoogleTypeName(getParameterType(param));
}
@Override
public String getParameterClassName(int param) throws SQLException {
Object value = statement.getParameterStore().getParameter(param);
if (value != null)
return value.getClass().getName();
Integer type = statement.getParameterStore().getType(param);
if (type != null)
return getClassName(type.intValue());
return null;
}
@Override
public int getParameterMode(int param) throws SQLException {
return parameterModeIn;
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
try {
res.append("CloudSpannerPreparedStatementParameterMetaData, parameter count: ")
.append(getParameterCount());
for (int param = 1; param <= getParameterCount(); param++) {
res.append("\nParameter ").append(param).append(":\n\t Class name: ")
.append(getParameterClassName(param));
res.append(",\n\t Parameter type name: ").append(getParameterTypeName(param));
res.append(",\n\t Parameter type: ").append(getParameterType(param));
res.append(",\n\t Parameter precision: ").append(getPrecision(param));
res.append(",\n\t Parameter scale: ").append(getScale(param));
res.append(",\n\t Parameter signed: ").append(isSigned(param));
res.append(",\n\t Parameter nullable: ").append(isNullable(param));
res.append(",\n\t Parameter mode: ").append(getParameterMode(param));
}
} catch (SQLException e) {
res.append("Error while fetching parameter metadata: ").append(e.getMessage());
}
return res.toString();
}
}
|
buchi-busireddy/hypertrace-core-graphql | hypertrace-core-graphql-trace-schema/src/main/java/org/hypertrace/core/graphql/trace/schema/arguments/TraceType.java | package org.hypertrace.core.graphql.trace.schema.arguments;
import graphql.annotations.annotationTypes.GraphQLName;
// TODO temporary for backwards compatibility
@GraphQLName(TraceType.TYPE_NAME)
public enum TraceType {
TRACE,
API_TRACE,
BACKEND_TRACE;
static final String TYPE_NAME = "TraceType";
public String getScopeString() {
return name();
}
}
|
emobileingenieria/youtube | drop-box-clone/src/index.js | require("dotenv").config();
const watch = require("node-watch");
const fetch = require("node-fetch");
const nodePath = require("path");
const fs = require("fs");
const express = require("express");
const multer = require("multer");
const FormData = require("form-data");
const upload = multer({ dest: "uploads/" });
const app = express();
const SYNC_OUT_DIR = process.env.SYNC_OUT_DIR;
const SYNC_IN_DIR = process.env.SYNC_IN_DIR;
watch(SYNC_OUT_DIR, { recursive: false }, async (evt, name) => {
const file = fs.createReadStream(name);
const form = new FormData();
form.append("file", file);
await fetch(`${process.env.REMOTE_URL}/files`, {
method: "POST",
body: form,
});
fs.unlinkSync(name);
});
app.post("/files", upload.single("file"), function (req, res, next) {
const { originalname, path } = req.file;
const file = fs.readFileSync(path);
fs.writeFileSync(nodePath.join(SYNC_IN_DIR, originalname), file);
fs.unlinkSync(path);
res.status(200);
res.send("success");
});
app.listen(process.env.PORT);
|
trekhleb/giphygram | src/Routes.js | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Route, Switch, withRouter } from 'react-router-dom';
import { SearchPage } from './components/searchPage/SearchPage';
import { RouterService } from './services/RouterService';
import { updateSearchQuery } from './actions/searchParamsActions';
import { search } from './actions/searchActions';
export class Routes extends React.Component {
static propTypes = {
routerService: PropTypes.instanceOf(RouterService).isRequired,
updateSearchQuery: PropTypes.func.isRequired,
search: PropTypes.func.isRequired,
};
componentDidMount() {
const {
routerService,
updateSearchQuery: searchQueryFromLocationCallback,
search: searchCallback,
} = this.props;
// Check if search query has been submitted through the URL.
// In case if search query is in URL we need to launch the search.
const searchQueryFromLocation = routerService.getSearchQuery();
if (searchQueryFromLocation) {
// Update search form parameters.
searchQueryFromLocationCallback(searchQueryFromLocation);
// Launch the search and populate the state with search results.
searchCallback({ query: searchQueryFromLocation });
}
}
render() {
// Currently we have only one route. But the next step of the App development might be to create
// a dedicated pages for each GIF with additional details. Or to display most trending GIFs
// on the /home and search results on the /search page.
return (
<Switch>
<Route path="/" component={SearchPage} />
</Switch>
);
}
}
const mapStateToProps = (state, props) => ({
routerService: new RouterService(props.history, props.location),
});
const mapDispatchToProps = {
updateSearchQuery,
search,
};
export default withRouter(
connect(
mapStateToProps,
mapDispatchToProps,
)(Routes),
);
|
kjthegod/chromium | remoting/android/java/src/org/chromium/chromoting/RenderData.java | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chromoting;
import android.graphics.Matrix;
import android.graphics.Point;
/**
* This class stores data that needs to be accessed on both the display thread and the
* event-processing thread.
*/
public class RenderData {
/** Stores pan and zoom configuration and converts image coordinates to screen coordinates. */
public Matrix transform = new Matrix();
public int screenWidth = 0;
public int screenHeight = 0;
public int imageWidth = 0;
public int imageHeight = 0;
/**
* Specifies the position, in image coordinates, at which the cursor image will be drawn.
* This will normally be at the location of the most recently injected motion event.
*/
public Point cursorPosition = new Point();
}
|
phanquanghiep123/fc40-fe | app/components/CustomAgGrid/demoUsage.js | import React, { Component } from 'react';
// import * as PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core';
import { createStructuredSelector } from 'reselect';
import { connect } from 'react-redux';
import { compose } from 'redux';
import withImmutablePropsToJs from 'with-immutable-props-to-js';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-material.css';
import './agGridCustomStyle.css';
import { agAutosizeHeaders } from './agGridUtils';
const style = () => ({
agContainer: {
height: '500px',
width: '100%',
},
});
class TableSection extends Component {
state = {
columnDefs: [
{
headerName: 'STT',
field: 'stt',
},
{
headerName: 'Mã sản phẩm (*)',
field: 'maSP',
},
],
rowData: [
{
stt: 1,
maSP: '',
},
],
};
componentDidMount() {
//
}
render() {
return (
<div
className="ag-theme-material"
style={{
height: '500px',
width: '600px',
}}
>
<AgGridReact
columnDefs={this.state.columnDefs}
rowData={this.state.rowData}
onGridReady={event => {
event.api.sizeColumnsToFit();
agAutosizeHeaders(event);
}}
onGridSizeChanged={event => {
event.api.sizeColumnsToFit();
agAutosizeHeaders(event);
}}
/>
</div>
);
}
}
TableSection.propTypes = {
// classes: PropTypes.object,
};
const mapStateToProps = createStructuredSelector({
//
});
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
const withConnect = connect(
mapStateToProps,
mapDispatchToProps,
);
export default compose(
withConnect,
withImmutablePropsToJs,
withStyles(style()),
)(TableSection);
|
matoruru/purescript-react-material-ui-svgicon | src/MaterialUI/SVGIcon/Icon/CloudDownloadOutlined.js | <reponame>matoruru/purescript-react-material-ui-svgicon
exports.cloudDownloadOutlinedImpl = require('@material-ui/icons/CloudDownloadOutlined').default;
|
RotaNova/asmoboot | rotanava-boot-base/rotanava-boot-base-core/src/main/java/com/rotanava/framework/common/constant/SysPageModule.java | <reponame>RotaNova/asmoboot
package com.rotanava.framework.common.constant;
/**
* @description:
* @author: jintengzhou
* @date: 2021-09-13 10:20
*/
public class SysPageModule {
/**
* 平台设置
*/
public static final Integer PTSZ = 1;
/**
* 设备配置
*/
public static final Integer SBSZ = 2;
/**
* 新航物联网平台
*/
public static final Integer XHWLWPT = 3;
/**
* 工地实名制系统
*/
public static final Integer GDSMZXT = 4;
/**
* 基础资料
*/
public static final Integer ZCJL = 5;
/**
* 智慧安防
*/
public static final Integer ZHAF = 6;
/**
* 智慧停车系统
*/
public static final Integer ZHTCXT = 7;
/**
* 考勤系统
*/
public static final Integer KQGLXT = 8;
} |
mahmadi786/woocommerce-onlineshop | woocommerce-wordpress-service/app/wp-content/plugins/customer-reviews-woocommerce/js/reviews-qa-captcha.js | <reponame>mahmadi786/woocommerce-onlineshop
if (typeof grecaptcha !== 'undefined' && grecaptcha && jQuery('.cr-recaptcha').length) {
grecaptcha.ready(() => {
grecaptcha.render(jQuery('.cr-recaptcha')[0], {
sitekey: crReviewsQaCaptchaConfig.v2Sitekey
});
});
}
|
Newcoin-Foundation/iosdk | dist/overmind/auth/effects.js | // import { Firebase } from './effects/firebase.ts.bak';
// import { Api } from './effects/newlife';
import { fetch } from "./effects/fetch";
export default {
// Firebase,
// Api,
fetch
};
// export default {}
//# sourceMappingURL=effects.js.map |
tea2code/recipe_manager | helper/translator.py | <reponame>tea2code/recipe_manager
#!/usr/bin/python
# -*- coding: utf-8 -*-
import gettext
from bottle import request
class TranslatorNotInitializedError(Exception):
""" Exception raised if Translator is not initialized. """
class Translator:
""" Wrapper for gettext for translations.
Member:
translations -- Dict of gettext translation instances.
"""
translations = {}
@staticmethod
def current_language(default_language):
""" Returns the current language. """
return request.get_cookie('language', default_language)
@staticmethod
def init(language, path):
""" Initialize translator. Must be called before first call to
instance. """
if language in Translator.translations:
return
Translator.language = language
Translator.translations[language] = gettext.translation(
language,
localedir=path,
languages=[language],
fallback=True)
@staticmethod
def instance(language):
""" Returns a translator instance for given language. """
if language not in Translator.translations:
msg = 'Language {} not initialized'.format(language)
raise TranslatorNotInitializedError(msg)
return Translator.translations[language].gettext |
intel/cassian | src/core/system/src/factory.cpp | /*
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include <cassian/system/factory.hpp>
#include <cassian/system/library.hpp>
#include <memory>
#include <string>
#if defined(_WIN32)
#include <library_windows.hpp>
#elif defined(__linux__)
#include <library_linux.hpp>
#endif
namespace cassian {
std::unique_ptr<Library> load_library(const std::string &name) {
#if defined(_WIN32)
return std::make_unique<LibraryWindows>(name);
#elif defined(__linux__)
return std::make_unique<LibraryLinux>(name);
#endif
}
} // namespace cassian
|
telink-semi/telink_b91_ble_single_connection_sdk | vendor/B91_feature/default_att.h | <reponame>telink-semi/telink_b91_ble_single_connection_sdk
/********************************************************************************************************
* @file default_att.h
*
* @brief This is the header file for BLE SDK
*
* @author BLE GROUP
* @date 2020.06
*
* @par Copyright (c) 2020, Telink Semiconductor (Shanghai) Co., Ltd. ("TELINK")
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************************************/
#ifndef DEFAULT_ATT_H_
#define DEFAULT_ATT_H_
#include "app_config.h"
#ifndef APP_DEFAULT_HID_BATTERY_OTA_ATTRIBUTE_TABLE
#define APP_DEFAULT_HID_BATTERY_OTA_ATTRIBUTE_TABLE 0
#endif
#if (APP_DEFAULT_HID_BATTERY_OTA_ATTRIBUTE_TABLE)
///////////////////////////////////// ATT HANDLER define ///////////////////////////////////////
/**
* @brief Att handle define
*/
typedef enum
{
ATT_H_START = 0,
//// Gap ////
/**********************************************************************************************/
GenericAccess_PS_H, //UUID: 2800, VALUE: uuid 1800
GenericAccess_DeviceName_CD_H, //UUID: 2803, VALUE: Prop: Read | Notify
GenericAccess_DeviceName_DP_H, //UUID: 2A00, VALUE: device name
GenericAccess_Appearance_CD_H, //UUID: 2803, VALUE: Prop: Read
GenericAccess_Appearance_DP_H, //UUID: 2A01, VALUE: appearance
CONN_PARAM_CD_H, //UUID: 2803, VALUE: Prop: Read
CONN_PARAM_DP_H, //UUID: 2A04, VALUE: connParameter
//// gatt ////
/**********************************************************************************************/
GenericAttribute_PS_H, //UUID: 2800, VALUE: uuid 1801
GenericAttribute_ServiceChanged_CD_H, //UUID: 2803, VALUE: Prop: Indicate
GenericAttribute_ServiceChanged_DP_H, //UUID: 2A05, VALUE: service change
GenericAttribute_ServiceChanged_CCB_H, //UUID: 2902, VALUE: serviceChangeCCC
//// device information ////
/**********************************************************************************************/
DeviceInformation_PS_H, //UUID: 2800, VALUE: uuid 180A
DeviceInformation_pnpID_CD_H, //UUID: 2803, VALUE: Prop: Read
DeviceInformation_pnpID_DP_H, //UUID: 2A50, VALUE: PnPtrs
//// HID ////
/**********************************************************************************************/
HID_PS_H, //UUID: 2800, VALUE: uuid 1812
//include
HID_INCLUDE_H, //UUID: 2802, VALUE: include
//protocol
HID_PROTOCOL_MODE_CD_H, //UUID: 2803, VALUE: Prop: read | write_without_rsp
HID_PROTOCOL_MODE_DP_H, //UUID: 2A4E, VALUE: protocolMode
//boot keyboard input report
HID_BOOT_KB_REPORT_INPUT_CD_H, //UUID: 2803, VALUE: Prop: Read | Notify
HID_BOOT_KB_REPORT_INPUT_DP_H, //UUID: 2A22, VALUE: bootKeyInReport
HID_BOOT_KB_REPORT_INPUT_CCB_H, //UUID: 2902, VALUE: bootKeyInReportCCC
//boot keyboard output report
HID_BOOT_KB_REPORT_OUTPUT_CD_H, //UUID: 2803, VALUE: Prop: Read | write| write_without_rsp
HID_BOOT_KB_REPORT_OUTPUT_DP_H, //UUID: 2A32, VALUE: bootKeyOutReport
//consume report in
HID_CONSUME_REPORT_INPUT_CD_H, //UUID: 2803, VALUE: Prop: Read | Notify
HID_CONSUME_REPORT_INPUT_DP_H, //UUID: 2A4D, VALUE: reportConsumerIn
HID_CONSUME_REPORT_INPUT_CCB_H, //UUID: 2902, VALUE: reportConsumerInCCC
HID_CONSUME_REPORT_INPUT_REF_H, //UUID: 2908 VALUE: REPORT_ID_CONSUMER, TYPE_INPUT
//keyboard report in
HID_NORMAL_KB_REPORT_INPUT_CD_H, //UUID: 2803, VALUE: Prop: Read | Notify
HID_NORMAL_KB_REPORT_INPUT_DP_H, //UUID: 2A4D, VALUE: reportKeyIn
HID_NORMAL_KB_REPORT_INPUT_CCB_H, //UUID: 2902, VALUE: reportKeyInInCCC
HID_NORMAL_KB_REPORT_INPUT_REF_H, //UUID: 2908 VALUE: REPORT_ID_KEYBOARD, TYPE_INPUT
//keyboard report out
HID_NORMAL_KB_REPORT_OUTPUT_CD_H, //UUID: 2803, VALUE: Prop: Read | write| write_without_rsp
HID_NORMAL_KB_REPORT_OUTPUT_DP_H, //UUID: 2A4D, VALUE: reportKeyOut
HID_NORMAL_KB_REPORT_OUTPUT_REF_H, //UUID: 2908 VALUE: REPORT_ID_KEYBOARD, TYPE_OUTPUT
// report map
HID_REPORT_MAP_CD_H, //UUID: 2803, VALUE: Prop: Read
HID_REPORT_MAP_DP_H, //UUID: 2A4B, VALUE: reportKeyIn
HID_REPORT_MAP_EXT_REF_H, //UUID: 2907 VALUE: extService
//hid information
HID_INFORMATION_CD_H, //UUID: 2803, VALUE: Prop: read
HID_INFORMATION_DP_H, //UUID: 2A4A VALUE: hidInformation
//control point
HID_CONTROL_POINT_CD_H, //UUID: 2803, VALUE: Prop: write_without_rsp
HID_CONTROL_POINT_DP_H, //UUID: 2A4C VALUE: controlPoint
//// battery service ////
/**********************************************************************************************/
BATT_PS_H, //UUID: 2800, VALUE: uuid 180f
BATT_LEVEL_INPUT_CD_H, //UUID: 2803, VALUE: Prop: Read | Notify
BATT_LEVEL_INPUT_DP_H, //UUID: 2A19 VALUE: batVal
BATT_LEVEL_INPUT_CCB_H, //UUID: 2902, VALUE: batValCCC
//// Ota ////
/**********************************************************************************************/
OTA_PS_H, //UUID: 2800, VALUE: telink ota service uuid
OTA_CMD_OUT_CD_H, //UUID: 2803, VALUE: Prop: read | write_without_rsp | Notify
OTA_CMD_OUT_DP_H, //UUID: telink ota uuid, VALUE: otaData
OTA_CMD_INPUT_CCB_H, //UUID: 2902, VALUE: otaDataCCC
OTA_CMD_OUT_DESC_H, //UUID: 2901, VALUE: otaName
ATT_END_H,
}ATT_HANDLE;
#endif //end of APP_USE_DEFAULT_HID_BATTERY_OTA_ATT_TABLE
#endif /* DEFAULT_ATT_H_ */
|
Shiva-D/rtos-course | FreeRTOSv10.4.1/FreeRTOS/Demo/CORTEX_A5_SAMA5D2x_Xplained_IAR/AtmelFiles/drivers/cortex-a/cp15_pmu.c | <reponame>Shiva-D/rtos-course
/* ----------------------------------------------------------------------------
* SAM Software Package License
* ----------------------------------------------------------------------------
* Copyright (c) 2015, Atmel Corporation
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ----------------------------------------------------------------------------
*/
/** \file */
/*----------------------------------------------------------------------------
* Headers
*----------------------------------------------------------------------------*/
#include "chip.h"
#if defined(__ICCARM__)
#include <intrinsics.h>
#endif
#include "cortex-a/cp15_pmu.h"
#include <assert.h>
/*----------------------------------------------------------------------------
* Global functions
*----------------------------------------------------------------------------*/
/**
* \brief Resets the counter and enables/disables all counters including PMCCNTR.
* \param ResetCounterType CounterType: Performance or Cycle counter
*/
static void cp15_pmu_control(uint8_t ResetCounterType, uint8_t EnableCounter)
{
uint32_t PMU_Value = 0;
asm("mrc p15, 0, %0, c9, c12, 0":"=r"(PMU_Value));
PMU_Value |= ((ResetCounterType << 1) | EnableCounter);
asm("mcr p15, 0, %0, c9, c12, 0": :"r"(PMU_Value));
}
/**
* \brief Select Cycle Count divider
* \param Divider 0 for increment of counter at every single cycle or 1 for at every 64th cycle
*/
static void cp15_cycle_count_divider(uint8_t Divider)
{
uint32_t PMU_Value = 0;
assert((Divider > 1 ? 0 : 1));
asm("mrc p15, 0, %0, c9, c12, 0":"=r"(PMU_Value));
PMU_Value |= (Divider << 3);
asm("mcr p15, 0, %0, c9, c12, 0": :"r"(PMU_Value));
}
/**
* \brief Enables PMCCNTR.
*/
static void cp15_enable_PMCNT(void)
{
uint32_t CNT_Value = 0;
asm("mrc p15, 0, %0, c9, c12, 1":"=r"(CNT_Value));
CNT_Value |= (uint32_t) ((1 << CP15_PMCNTENSET));
asm("mcr p15, 0, %0, c9, c12, 1": :"r"(CNT_Value));
}
/**
* \brief Enables PMCCNTR.
*/
static void cp15_enable_counter(uint8_t Counter)
{
uint32_t CNT_Value = 0;
asm("mrc p15, 0, %0, c9, c12, 1":"=r"(CNT_Value));
CNT_Value |= Counter;
asm("mcr p15, 0, %0, c9, c12, 1": :"r"(CNT_Value));
}
/**
* \brief Disables/clear PMCCNTR.
* \param Counter 0 or 1 to selct counter
*/
static void cp15_clear_PMCNT(void)
{
uint32_t CNT_Value = 0;
asm("mrc p15, 0, %0, c9, c12, 2":"=r"(CNT_Value));
CNT_Value |= (uint32_t) (1 << CP15_PMCNTENCLEAR);
asm("mcr p15, 0, %0, c9, c12, 2": :"r"(CNT_Value));
}
/**
* \brief Disables/Enables overflow flag.
* \param Enable Enables or disables the flag option
* \param ClearCounterFlag selects the counter flag to clear
*/
void cp15_overflow_status(uint8_t Enable, uint8_t ClearCounterFlag)
{
uint32_t OFW_Value = 0;
asm("mrc p15, 0, %0, c9, c12, 3":"=r"(OFW_Value));
OFW_Value |= ((Enable << 31) | ClearCounterFlag);
asm("mcr p15, 0, %0, c9, c12, 3": :"r"(OFW_Value));
}
/**
* \brief Disables/Enables overflow flag.
* \param EventCounter Counter of the events
*/
uint32_t cp15_read_overflow_status(uint8_t EventCounter)
{
uint32_t OFW_Value = 0;
asm("mrc p15, 0, %0, c9, c12, 3":"=r"(OFW_Value));
OFW_Value = ((OFW_Value & EventCounter) >> (EventCounter - 1));
return OFW_Value;
}
/**
* \brief Increments the count of a performance monitor count register.
* \param IncrCounter 0 or 1 counters
*/
void cp15_soft_incr(uint8_t IncrCounter)
{
uint32_t INRC_Value = 0;
asm("mrc p15, 0, %0, c9, c12, 4":"=r"(INRC_Value));
INRC_Value |= IncrCounter;
asm("mcr p15, 0, %0, c9, c12, 4": :"r"(INRC_Value));
}
/**
* \brief Increments the count of a performance monitor count register.
* \param EventType Select Event Type
* \param Counter 0 or 1 counters
*/
static void cp15_select_event(PerfEventType EventType, uint8_t Counter)
{
uint32_t CounterSelect = 0;
assert((Counter == 1) || (Counter == 2));
CounterSelect = (Counter & 0x1F);
asm("mcr p15, 0, %0, c9, c12, 5": :"r"(CounterSelect));
CounterSelect = (EventType & 0xFF);
asm("mcr p15, 0, %0, c9, c13, 1": :"r"(CounterSelect));
// PMXEVTYPER
asm("mrc p15, 0, %0, c9, c13, 1":"=r"(CounterSelect));
// PMXEVTYPER
}
/**
* \brief Enables USER mode
*/
void cp15_enable_user_mode(void)
{
uint8_t Value = 1;
asm("mcr p15, 0, %0, c9, c14, 0": :"r"(Value));
}
/**
* \brief Enables Oveflows interrupt
* \param Enable Enables the Interrupt
* \param Counter 0 or 1 counters
*/
void cp15_enable_interrupt(uint8_t Enable, uint8_t Counter)
{
uint32_t ITE_Value = 0;
ITE_Value |= ((Enable << 31) | Counter);
asm("mcr p15, 0, %0, c9, c14, 1": :"r"(ITE_Value));
}
/**
* \brief Disables Oveflows interrupt
* \param Disable Disables the Interrupt
* \param Counter 0 or 1 counters
*/
void cp15_disable_interrupt(uint8_t Disable, uint8_t Counter)
{
uint32_t ITE_Value = 0;
ITE_Value |= ((Disable << 31) | Counter);
asm("mcr p15, 0, %0, c9, c14, 2": :"r"(ITE_Value));
}
/**
* \brief Initialize Cycle counter with Divider 64
*/
uint32_t cp15_init_cycle_counter(void)
{
uint32_t value;
cp15_clear_PMCNT();
cp15_enable_PMCNT();
cp15_overflow_status(true, CP15_BothCounter);
cp15_cycle_count_divider(CP15_CountDivider64);
cp15_pmu_control(CP15_ResetCycCounter, true);
asm("mrc p15, 0, %0, c9, c13, 0":"=r"(value));
return value;
}
/**
* \brief Initialize Performance monitor counter with Divider 64
* \param Event Event type
* \param Counter 0 or 1 counters
*/
void cp15_init_perf_counter(PerfEventType Event, uint8_t Counter)
{
cp15_pmu_control(CP15_ResetPerCounter, true);
cp15_select_event(Event, Counter);
cp15_overflow_status(false, CP15_BothCounter);
cp15_enable_counter(Counter);
}
/**
* \brief gives total number of event count
* \param Counter 0 or 1 counters
*/
uint32_t cp15_count_evt(uint8_t Counter)
{
uint32_t value;
asm("mcr p15, 0, %0, c9, c12, 5": :"r"(Counter));
asm("mrc p15, 0, %0, c9, c13, 2":"=r"(value));
// PMXEVTYPER
return (value);
}
/**
* \brief gives total number of cycle count
*/
uint32_t cp15_get_cycle_counter(void)
{
uint32_t value;
asm("mrc p15, 0, %0, c9, c13, 0":"=r"(value));
return value;
}
|
dingjb/skydragon | test/specs/row.spec.js | <reponame>dingjb/skydragon
import Row from '../../src/package/row';
import Cow from '../../src/package/col';
import { getRenderedVm, getVue } from '../util';
describe('Row', () => {
let vm;
it('check row', () => {
vm = getVue({
template: '<tb-row><tb-col :span="2" :md="4" :xs="24"><div class="group-item"></div></tb-col>'
});
const className = vm.$el.querySelector('div').className;
expect(className).to.equal('tb-col-2 tb-col-xs-24 tb-col-md-4');
});
}); |
Tech-Intellegent/CodeForces-Solution | CodeForces-Contest/1400/D.cpp | #include<bits/stdc++.h>
using namespace std;
const int N = 3030;
int a[N], cnt[N][N];
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t; cin >> t;
while (t--) {
int n; cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
long long ans = 0;
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) ans += cnt[a[i]][a[j]];
for (int j = i - 1; j >= 1; j--) cnt[a[j]][a[i]]++;
}
cout << ans << '\n';
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cnt[i][j] = 0;
}
}
}
return 0;
} |
wedataintelligence/vivaldi-source | chromium/ui/ozone/platform/drm/host/drm_cursor.h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_OZONE_PLATFORM_DRM_HOST_DRM_CURSOR_H_
#define UI_OZONE_PLATFORM_DRM_HOST_DRM_CURSOR_H_
#include <memory>
#include "base/callback.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread_checker.h"
#include "ui/base/cursor/cursor.h"
#include "ui/events/ozone/evdev/cursor_delegate_evdev.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/ozone/platform/drm/host/drm_cursor_core.h"
#include "ui/ozone/public/gpu_platform_support_host.h"
namespace gfx {
class PointF;
class Vector2dF;
class Rect;
}
namespace ui {
class BitmapCursorFactoryOzone;
class DrmWindowHostManager;
class DrmCursor : public CursorDelegateEvdev {
public:
explicit DrmCursor(DrmWindowHostManager* window_manager);
~DrmCursor() override;
// Change the cursor over the specifed window.
void SetCursor(gfx::AcceleratedWidget window, PlatformCursor platform_cursor);
// Handle window lifecycle.
void OnWindowAdded(gfx::AcceleratedWidget window,
const gfx::Rect& bounds_in_screen,
const gfx::Rect& cursor_confined_bounds);
void OnWindowRemoved(gfx::AcceleratedWidget window);
// Handle window bounds changes.
void CommitBoundsChange(gfx::AcceleratedWidget window,
const gfx::Rect& new_display_bounds_in_screen,
const gfx::Rect& new_confined_bounds);
// CursorDelegateEvdev:
void MoveCursorTo(gfx::AcceleratedWidget window,
const gfx::PointF& location) override;
void MoveCursorTo(const gfx::PointF& screen_location) override;
void MoveCursor(const gfx::Vector2dF& delta) override;
bool IsCursorVisible() override;
gfx::PointF GetLocation() override;
gfx::Rect GetCursorConfinedBounds() override;
// IPC.
void OnChannelEstablished(
int host_id,
scoped_refptr<base::SingleThreadTaskRunner> send_runner,
const base::Callback<void(IPC::Message*)>& sender);
void OnChannelDestroyed(int host_id);
bool OnMessageReceived(const IPC::Message& message);
private:
// An IPC-based implementation of the DrmCursorProxy that ships
// messages to the GPU process.
class CursorIPC : public DrmCursorProxy {
public:
explicit CursorIPC(base::Lock* lock);
~CursorIPC();
bool IsConnectedLocked();
void SendLocked(IPC::Message* message);
// DrmCursorProxy implementation.
void CursorSet(gfx::AcceleratedWidget window,
const std::vector<SkBitmap>& bitmaps,
gfx::Point point,
int frame_delay_ms) override;
void Move(gfx::AcceleratedWidget window, gfx::Point point) override;
int host_id;
// Callback for IPC updates.
base::Callback<void(IPC::Message*)> send_callback;
scoped_refptr<base::SingleThreadTaskRunner> send_runner;
base::Lock* lock;
};
// The mutex synchronizing this object.
base::Lock lock_;
// Enforce our threading constraints.
base::ThreadChecker thread_checker_;
CursorIPC ipc_;
std::unique_ptr<DrmCursorCore> core_;
DISALLOW_COPY_AND_ASSIGN(DrmCursor);
};
} // namespace ui
#endif // UI_OZONE_PLATFORM_DRM_HOST_DRM_CURSOR_H_
|
zarehba/mini-apps | src/miniapps/SliderDesign/Slider.js | import React, { useState, useReducer, useEffect } from 'react';
import PropTypes from 'prop-types';
import styled, { createGlobalStyle } from 'styled-components';
function useImageWidth(imageMaxWidth) {
const [screenWidth, setWidth] = useState(window.screen.availWidth);
useEffect(() => {
const updateWidthAndHeight = () => {
setWidth(window.screen.availWidth);
};
window.addEventListener('resize', updateWidthAndHeight);
return () => window.removeEventListener('resize', updateWidthAndHeight);
}, []);
return {
imageWidth: Math.floor(Math.min(screenWidth, imageMaxWidth)),
imageGutterWidth: Math.floor(Math.min(screenWidth, imageMaxWidth) / 16),
};
}
const sliderReducer = (state, action) => {
switch (action.type) {
case 'PREV':
if (state.currentImage === 0) {
return { ...state, currentImage: state.images.length - 1 };
}
return { ...state, currentImage: state.currentImage - 1 };
case 'NEXT':
if (state.currentImage === state.images.length - 1) {
return { ...state, currentImage: 0 };
}
return { ...state, currentImage: state.currentImage + 1 };
default:
return { ...state, currentImage: state.currentImage };
}
};
const Slider = ({ images, imageMaxWidth = 640, slideChangeMs = 5000 }) => {
const { imageWidth, imageGutterWidth } = useImageWidth(imageMaxWidth);
const [state, dispatch] = useReducer(sliderReducer, {
images: images,
currentImage: 0,
});
useEffect(() => {
const changeSlide = () => dispatch({ type: 'NEXT' });
const interval = setInterval(changeSlide, slideChangeMs);
return () => {
clearInterval(interval);
};
}, [slideChangeMs]);
return (
<SliderContainer>
<SliderView>
<ButtonPrev onClick={() => dispatch({ type: 'PREV' })}>
<span>V</span>
</ButtonPrev>
{state.images.map((img, ind) => (
<SliderPicture
key={ind}
src={img}
alt={`Slide no. ${ind}`}
$currentImage={state.currentImage}
/>
))}
<ButtonNext onClick={() => dispatch({ type: 'NEXT' })}>
<span>V</span>
</ButtonNext>
</SliderView>
<SliderStyles
$imageWidth={imageWidth}
$imageGutterWidth={imageGutterWidth}
/>
</SliderContainer>
);
};
const SliderStyles = createGlobalStyle`
html {
--IMAGE_WIDTH: ${(props) => props.$imageWidth}px;
--IMAGES_GUTTER: ${(props) => props.$imageGutterWidth}px;
--BUTTON_HEIGHT: ${(props) => props.$imageGutterWidth}px;
}
`;
const SliderContainer = styled.div`
width: Var(--IMAGE_WIDTH);
overflow: hidden;
`;
const SliderView = styled.div`
display: flex;
gap: Var(--IMAGES_GUTTER);
position: relative;
& > img:first-of-type {
margin-left: calc(Var(--IMAGES_GUTTER) / 2);
}
`;
const buttonArrow = styled.button`
display: grid;
place-content: center;
position: absolute;
top: 50%;
height: Var(--BUTTON_HEIGHT);
padding: calc(Var(--BUTTON_HEIGHT) / 4);
box-sizing: content-box;
border: none;
border-radius: 50%;
background: rgba(255, 255, 255, 0.25);
color: rgba(0, 0, 0, 0.5);
font-size: Var(--BUTTON_HEIGHT);
font-weight: bold;
z-index: 5;
cursor: pointer;
transition: 0.25s all ease;
mix-blend-mode: hard-light;
span {
writing-mode: vertical-rl;
padding-right: calc(Var(--BUTTON_HEIGHT) / 10);
}
:hover {
background: rgba(255, 255, 255, 0.5);
}
:focus {
background: rgba(255, 255, 255, 0.75);
outline: none;
/* outline: 2px solid rgba(255, 255, 255, 0.75); */
}
`;
const ButtonPrev = styled(buttonArrow)`
left: 0;
transform: translateY(-50%);
`;
const ButtonNext = styled(buttonArrow)`
right: 0;
transform: scaleX(-1) translateY(-50%);
`;
const SliderPicture = styled.img`
height: auto;
width: Var(--IMAGE_WIDTH);
border-radius: 5px;
transition: 1s transform cubic-bezier(0.65, 0, 0.35, 1);
transform: translateX(
calc(-1 * Var(--IMAGE_WIDTH) * ${(props) => props.$currentImage})
)
translateX(
calc(-1 * Var(--IMAGES_GUTTER) * ${(props) => props.$currentImage + 0.5})
);
`;
Slider.propTypes = {
images: PropTypes.arrayOf(PropTypes.string).isRequired,
imageMaxWidth: PropTypes.number,
slideChangeMs: PropTypes.number,
};
export default Slider;
|
scbedd/azure-sdk-for-node | lib/services/hdInsightManagement/lib/models/clusterIdentity.js | <reponame>scbedd/azure-sdk-for-node
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Identity for the cluster.
*
*/
class ClusterIdentity {
/**
* Create a ClusterIdentity.
* @property {string} [principalId] The principal id of cluster identity.
* This property will only be provided for a system assigned identity.
* @property {string} [tenantId] The tenant id associated with the cluster.
* This property will only be provided for a system assigned identity.
* @property {string} [type] The type of identity used for the cluster. The
* type 'SystemAssigned, UserAssigned' includes both an implicitly created
* identity and a set of user assigned identities. Possible values include:
* 'SystemAssigned', 'UserAssigned', 'SystemAssigned, UserAssigned', 'None'
* @property {object} [userAssignedIdentities] The list of user identities
* associated with the cluster. The user identity dictionary key references
* will be ARM resource ids in the form:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
*/
constructor() {
}
/**
* Defines the metadata of ClusterIdentity
*
* @returns {object} metadata of ClusterIdentity
*
*/
mapper() {
return {
required: false,
serializedName: 'ClusterIdentity',
type: {
name: 'Composite',
className: 'ClusterIdentity',
modelProperties: {
principalId: {
required: false,
readOnly: true,
serializedName: 'principalId',
type: {
name: 'String'
}
},
tenantId: {
required: false,
readOnly: true,
serializedName: 'tenantId',
type: {
name: 'String'
}
},
type: {
required: false,
serializedName: 'type',
type: {
name: 'Enum',
allowedValues: [ 'SystemAssigned', 'UserAssigned', 'SystemAssigned, UserAssigned', 'None' ]
}
},
userAssignedIdentities: {
required: false,
serializedName: 'userAssignedIdentities',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'ClusterIdentityUserAssignedIdentitiesValueElementType',
type: {
name: 'Composite',
className: 'ClusterIdentityUserAssignedIdentitiesValue'
}
}
}
}
}
}
};
}
}
module.exports = ClusterIdentity;
|
jsupancic/libhand-public | pyhand/kinematics/root_ring_inter_length_2.c | /******************************************************************************
* Code generated with sympy 0.7.6 *
* *
* See http://www.sympy.org/ for more information. *
* *
* This file is part of 'project' *
******************************************************************************/
#include "root_ring_inter_length_2.h"
#include <math.h>
double root_ring_inter_length_2() {
double root_ring_inter_length_2_result;
root_ring_inter_length_2_result = 0;
return root_ring_inter_length_2_result;
}
|
ptahchiev/thymeleaf-spring | thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/context/webflux/SpringWebFluxExpressionContext.java | /*
* =============================================================================
*
* Copyright (c) 2011-2018, The THYMELEAF team (http://www.thymeleaf.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
package org.thymeleaf.spring5.context.webflux;
import java.util.Locale;
import java.util.Map;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.web.server.ServerWebExchange;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.context.IExpressionContext;
import org.thymeleaf.expression.ExpressionObjects;
import org.thymeleaf.expression.IExpressionObjects;
/**
* <p>
* Basic Spring WebFlux-oriented implementation of the {@link IExpressionContext} and
* {@link ISpringWebFluxContext} interfaces.
* </p>
* <p>
* This class is not thread-safe, and should not be shared across executions of templates.
* </p>
*
* @author <NAME>
*
* @since 3.0.3
*
*/
public class SpringWebFluxExpressionContext extends SpringWebFluxContext implements IExpressionContext {
private final IEngineConfiguration configuration;
private IExpressionObjects expressionObjects = null;
public SpringWebFluxExpressionContext(
final IEngineConfiguration configuration, final ServerWebExchange exchange) {
this(configuration, exchange, null, null, null);
}
public SpringWebFluxExpressionContext(
final IEngineConfiguration configuration, final ServerWebExchange exchange, final Locale locale) {
this(configuration, exchange, null, locale, null);
}
public SpringWebFluxExpressionContext(
final IEngineConfiguration configuration,
final ServerWebExchange exchange,
final Locale locale, final Map<String, Object> variables) {
this(configuration, exchange, null, locale, variables);
}
public SpringWebFluxExpressionContext(
final IEngineConfiguration configuration,
final ServerWebExchange exchange,
final ReactiveAdapterRegistry reactiveAdapterRegistry,
final Locale locale, final Map<String, Object> variables) {
super(exchange, reactiveAdapterRegistry, locale, variables);
this.configuration = configuration;
}
@Override
public IEngineConfiguration getConfiguration() {
return this.configuration;
}
@Override
public IExpressionObjects getExpressionObjects() {
// We delay creation of expression objects in case they are not needed at all
if (this.expressionObjects == null) {
this.expressionObjects = new ExpressionObjects(this, this.configuration.getExpressionObjectFactory());
}
return this.expressionObjects;
}
}
|
liuming-dev/compass | sample/src/main/java/com/sogou/bizdev/compass/sample/hibernate/combined/ShardFirstService.java | package com.sogou.bizdev.compass.sample.hibernate.combined;
import com.sogou.bizdev.compass.core.anotation.RouteKey;
import com.sogou.bizdev.compass.sample.common.po.Plan;
/**先执行分库库sevrice的混合模式样例
* @author gly
* @since 1.0.0
*/
public interface ShardFirstService {
/**先执行分库库sevrice的混合模式
* @param accountId
* @param planId
* @return
*/
public Plan getMSAndShardPlan(@RouteKey Long accountId, Long planId);
}
|
ScalablyTyped/SlinkyTyped | e/extjs/src/main/scala/typingsSlinky/extjs/global/Ext/layout.scala | <gh_stars>10-100
package typingsSlinky.extjs.global.Ext
import typingsSlinky.extjs.Ext.IBase
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object layout {
object component {
object field {
@JSGlobal("Ext.layout.component.field.Field")
@js.native
class Field ()
extends typingsSlinky.extjs.Ext.layout.component.field.Field
/* static members */
object Field {
/** [Method] Add methods properties to the prototype of this class
* @param members Object
*/
@JSGlobal("Ext.layout.component.field.Field.addMembers")
@js.native
def addMembers(): Unit = js.native
@JSGlobal("Ext.layout.component.field.Field.addMembers")
@js.native
def addMembers(members: js.Any): Unit = js.native
/** [Method] Add override static properties of this class
* @param members Object
* @returns Ext.Base this
*/
@JSGlobal("Ext.layout.component.field.Field.addStatics")
@js.native
def addStatics(): IBase = js.native
@JSGlobal("Ext.layout.component.field.Field.addStatics")
@js.native
def addStatics(members: js.Any): IBase = js.native
/** [Method] Create aliases for existing prototype methods
* @param alias String/Object The new method name, or an object to set multiple aliases. See flexSetter
* @param origin String/Object The original method name
*/
@JSGlobal("Ext.layout.component.field.Field.createAlias")
@js.native
def createAlias(): Unit = js.native
@JSGlobal("Ext.layout.component.field.Field.createAlias")
@js.native
def createAlias(alias: js.UndefOr[scala.Nothing], origin: js.Any): Unit = js.native
@JSGlobal("Ext.layout.component.field.Field.createAlias")
@js.native
def createAlias(alias: js.Any): Unit = js.native
@JSGlobal("Ext.layout.component.field.Field.createAlias")
@js.native
def createAlias(alias: js.Any, origin: js.Any): Unit = js.native
/** [Method] Destroy the error tip instance */
@JSGlobal("Ext.layout.component.field.Field.destroyTip")
@js.native
def destroyTip(): Unit = js.native
/** [Method] Get the current class name in string format
* @returns String className
*/
@JSGlobal("Ext.layout.component.field.Field.getName")
@js.native
def getName(): java.lang.String = js.native
/** [Method] Adds members to class */
@JSGlobal("Ext.layout.component.field.Field.implement")
@js.native
def implement(): Unit = js.native
/** [Method] Use a custom QuickTip instance separate from the main QuickTips singleton so that we can give it a custom frame style */
@JSGlobal("Ext.layout.component.field.Field.initTip")
@js.native
def initTip(): Unit = js.native
/** [Method] Override members of this class
* @param members Object The properties to add to this class. This should be specified as an object literal containing one or more properties.
* @returns Ext.Base this class
*/
@JSGlobal("Ext.layout.component.field.Field.override")
@js.native
def `override`(): IBase = js.native
@JSGlobal("Ext.layout.component.field.Field.override")
@js.native
def `override`(members: js.Any): IBase = js.native
}
}
}
}
|
jagriti295/Automatic-Code-Complexity-Prediction | ASTExtractor/src/main/java/com/github/mauricioaniche/ck/metric/DIT.java | package com.github.mauricioaniche.ck.metric;
import com.github.mauricioaniche.ck.CKClassResult;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.TypeDeclaration;
public class DIT extends ASTVisitor implements ClassLevelMetric {
int dit = 1; // Object is the father of everyone!
@Override
public boolean visit(TypeDeclaration node) {
ITypeBinding binding = node.resolveBinding();
if(binding!=null) calculate(binding);
return super.visit(node);
}
private void calculate(ITypeBinding binding) {
ITypeBinding father = binding.getSuperclass();
if (father != null) {
String fatherName = father.getQualifiedName();
if (fatherName.endsWith("Object")) return;
dit++;
calculate(father);
}
}
@Override
public void execute(CompilationUnit cu, CKClassResult number) {
cu.accept(new IgnoreSubClasses(this));
}
@Override
public void setResult(CKClassResult result) {
result.setDit(dit);
}
}
|
oxtra/oxtra | src/oxtra/codegen/instructions/arithmetic/mul.h | #ifndef OXTRA_MUL_H
#define OXTRA_MUL_H
#include "oxtra/codegen/instruction.h"
namespace codegen {
class Mul : public codegen::Instruction {
public:
explicit Mul(const fadec::Instruction& inst)
: codegen::Instruction{inst, flags::all, flags::none} {}
void generate(CodeBatch& batch) const override;
};
}
#endif //OXTRA_MUL_H
|
E-Health/gocdm | api/condition_era.go | package api
import (
"net/http"
"github.com/E-Health/gocdm/model"
"github.com/gin-gonic/gin"
"github.com/julienschmidt/httprouter"
"github.com/smallnest/gen/dbmeta"
)
func configConditionErasRouter(router *httprouter.Router) {
router.GET("/conditioneras", GetAllConditionEras)
router.POST("/conditioneras", AddConditionEra)
router.GET("/conditioneras/:id", GetConditionEra)
router.PUT("/conditioneras/:id", UpdateConditionEra)
router.DELETE("/conditioneras/:id", DeleteConditionEra)
}
func configGinConditionErasRouter(router gin.IRoutes) {
router.GET("/conditioneras", ConverHttprouterToGin(GetAllConditionEras))
router.POST("/conditioneras", ConverHttprouterToGin(AddConditionEra))
router.GET("/conditioneras/:id", ConverHttprouterToGin(GetConditionEra))
router.PUT("/conditioneras/:id", ConverHttprouterToGin(UpdateConditionEra))
router.DELETE("/conditioneras/:id", ConverHttprouterToGin(DeleteConditionEra))
}
func GetAllConditionEras(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
page, err := readInt(r, "page", 0)
if err != nil || page < 0 {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
order := r.FormValue("order")
conditioneras := []*model.ConditionEra{}
conditioneras_orm := DB.Model(&model.ConditionEra{})
if page > 0 {
pagesize, err := readInt(r, "pagesize", 20)
if err != nil || pagesize <= 0 {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
offset := (page - 1) * pagesize
conditioneras_orm = conditioneras_orm.Offset(offset).Limit(pagesize)
}
if order != "" {
conditioneras_orm = conditioneras_orm.Order(order)
}
if err = conditioneras_orm.Find(&conditioneras).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, &conditioneras)
}
func GetConditionEra(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
id := ps.ByName("id")
conditionera := &model.ConditionEra{}
if DB.First(conditionera, id).Error != nil {
http.NotFound(w, r)
return
}
writeJSON(w, conditionera)
}
func AddConditionEra(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
conditionera := &model.ConditionEra{}
if err := readJSON(r, conditionera); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := DB.Save(conditionera).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, conditionera)
}
func UpdateConditionEra(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
id := ps.ByName("id")
conditionera := &model.ConditionEra{}
if DB.First(conditionera, id).Error != nil {
http.NotFound(w, r)
return
}
updated := &model.ConditionEra{}
if err := readJSON(r, updated); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := dbmeta.Copy(conditionera, updated); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := DB.Save(conditionera).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, conditionera)
}
func DeleteConditionEra(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
id := ps.ByName("id")
conditionera := &model.ConditionEra{}
if DB.First(conditionera, id).Error != nil {
http.NotFound(w, r)
return
}
if err := DB.Delete(conditionera).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
|
vladkhvo/bem-create-sublime-pligin | node_modules/.bem.MODULES/borschik/lib/techs/css-fast.js | // Backward compatibility: 'css-fast' is 'css' now.
// This hack will be removed in 0.3.x.
exports.Tech = require('./css').Tech;
|
amcp/janusgraph | janusgraph-server/src/test/java/org/janusgraph/graphdb/tinkerpop/AbstractGremlinServerIntegrationTest.java | <gh_stars>1-10
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* This file was pulled from the Apache TinkerPop project:
* https://github.com/apache/tinkerpop/blob/3.2.7/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/AbstractGremlinServerIntegrationTest.java
* and has been stripped down to the basic functionality needed here.
*
* Ideally, TinkerPop would include the src/test in its bundled jar, and
* then we can directly import the class from the gremlin-server dependency.
* We can follow those updates here:
* https://issues.apache.org/jira/projects/TINKERPOP/issues/TINKERPOP-1900?filter=allopenissues
*/
package org.janusgraph.graphdb.tinkerpop;
import org.apache.tinkerpop.gremlin.server.GremlinServer;
import org.apache.tinkerpop.gremlin.server.Settings;
import org.apache.tinkerpop.gremlin.server.op.OpLoader;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.InputStream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assume.assumeThat;
/**
* Starts and stops an instance for each executed test.
*/
public abstract class AbstractGremlinServerIntegrationTest {
protected GremlinServer server;
private final static String epollOption = "gremlin.server.epoll";
private static final boolean GREMLIN_SERVER_EPOLL = "true".equalsIgnoreCase(System.getProperty(epollOption));
private static final Logger logger = LoggerFactory.getLogger(AbstractGremlinServerIntegrationTest.class);
@Rule
public TestName name = new TestName();
public Settings overrideSettings(final Settings settings) {
return settings;
}
public InputStream getSettingsInputStream() {
return AbstractGremlinServerIntegrationTest.class.getResourceAsStream("gremlin-server-integration.yaml");
}
@Before
public void setUp() throws Exception {
logger.info("* Testing: " + name.getMethodName());
logger.info("* Epoll option enabled:" + GREMLIN_SERVER_EPOLL);
startServer();
}
public void setUp(final Settings settings) throws Exception {
logger.info("* Testing: " + name.getMethodName());
logger.info("* Epoll option enabled:" + GREMLIN_SERVER_EPOLL);
startServer(settings);
}
public void startServer(final Settings settings) throws Exception {
if (null == settings) {
startServer();
} else {
final Settings overridenSettings = overrideSettings(settings);
if (GREMLIN_SERVER_EPOLL) {
overridenSettings.useEpollEventLoop = true;
}
this.server = new GremlinServer(overridenSettings);
server.start().join();
}
}
public void startServer() throws Exception {
final InputStream stream = getSettingsInputStream();
final Settings settings = Settings.read(stream);
final Settings overridenSettings = overrideSettings(settings);
if (GREMLIN_SERVER_EPOLL) {
overridenSettings.useEpollEventLoop = true;
}
this.server = new GremlinServer(overridenSettings);
server.start().join();
}
@After
public void tearDown() throws Exception {
stopServer();
}
public void stopServer() throws Exception {
server.stop().join();
// reset the OpLoader processors so that they can get reconfigured on startup - Settings may have changed
// between tests
OpLoader.reset();
}
public static boolean deleteDirectory(final File directory) {
if (directory.exists()) {
final File[] files = directory.listFiles();
if (null != files) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
}
return (directory.delete());
}
}
|
rohankumardubey/safehtml | stylesheet.go | <gh_stars>100-1000
// Copyright (c) 2017 The Go Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package safehtml
import (
"container/list"
"fmt"
"regexp"
"strings"
)
// A StyleSheet is an immutable string-like type which represents a CSS
// style sheet and guarantees that its value, as a string, will not cause
// untrusted script execution (cross-site scripting) when evaluated as CSS
// in a browser.
//
// StyleSheet's string representation can safely be interpolated as the
// content of a style element within HTML. The StyleSheet string should
// not be escaped before interpolation.
type StyleSheet struct {
// We declare a StyleSheet not as a string but as a struct wrapping a string
// to prevent construction of StyleSheet values through string conversion.
str string
}
// StyleSheetFromConstant constructs a StyleSheet with the
// underlying stylesheet set to the given styleSheet, which must be an untyped string
// constant.
//
// No runtime validation or sanitization is performed on script; being under
// application control, it is simply assumed to comply with the StyleSheet
// contract.
func StyleSheetFromConstant(styleSheet stringConstant) StyleSheet {
return StyleSheet{string(styleSheet)}
}
// CSSRule constructs a StyleSheet containng a CSS rule of the form:
// selector{style}
// It returns an error if selector contains disallowed characters or unbalanced
// brackets.
//
// The constructed StyleSheet value is guaranteed to fulfill its type contract,
// but is not guaranteed to be semantically valid CSS.
func CSSRule(selector string, style Style) (StyleSheet, error) {
if strings.ContainsRune(selector, '<') {
return StyleSheet{}, fmt.Errorf("selector %q contains '<'", selector)
}
selectorWithoutStrings := cssStringPattern.ReplaceAllString(selector, "")
if matches := invalidCSSSelectorRune.FindStringSubmatch(selectorWithoutStrings); matches != nil {
return StyleSheet{}, fmt.Errorf("selector %q contains %q, which is disallowed outside of CSS strings", selector, matches[0])
}
if !hasBalancedBrackets(selectorWithoutStrings) {
return StyleSheet{}, fmt.Errorf("selector %q contains unbalanced () or [] brackets", selector)
}
return StyleSheet{fmt.Sprintf("%s{%s}", selector, style.String())}, nil
}
var (
// cssStringPattern matches a single- or double-quoted CSS string.
cssStringPattern = regexp.MustCompile(
`"([^"\r\n\f\\]|\\[\s\S])*"|` + // Double-quoted string literal
`'([^'\r\n\f\\]|\\[\s\S])*'`) // Single-quoted string literal
// invalidCSSSelectorRune matches a rune that is not allowed in a CSS3
// selector that does not contain string literals.
// See https://w3.org/TR/css3-selectors/#selectors.
invalidCSSSelectorRune = regexp.MustCompile(`[^-_a-zA-Z0-9#.:* ,>+~[\]()=^$|]`)
)
// hasBalancedBrackets returns whether s has balanced () and [] brackets.
func hasBalancedBrackets(s string) bool {
stack := list.New()
for i := 0; i < len(s); i++ {
c := s[i]
if expected, ok := matchingBrackets[c]; ok {
e := stack.Back()
if e == nil {
return false
}
// Skip success check for this type assertion since it is trivial to
// see that only bytes are pushed onto this stack.
if v := e.Value.(byte); v != expected {
return false
}
stack.Remove(e)
continue
}
for _, openBracket := range matchingBrackets {
if c == openBracket {
stack.PushBack(c)
break
}
}
}
return stack.Len() == 0
}
// matchingBrackets[x] is the opening bracket that matches closing bracket x.
var matchingBrackets = map[byte]byte{
')': '(',
']': '[',
}
// String returns the string form of the StyleSheet.
func (s StyleSheet) String() string {
return s.str
}
|
cctvzd7/aliyun-openapi-java-sdk | aliyun-java-sdk-sofa/src/main/java/com/aliyuncs/sofa/transform/v20190815/UpdateLinkeLinklogAccountResponseUnmarshaller.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.sofa.transform.v20190815;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.sofa.model.v20190815.UpdateLinkeLinklogAccountResponse;
import com.aliyuncs.sofa.model.v20190815.UpdateLinkeLinklogAccountResponse.Result;
import com.aliyuncs.transform.UnmarshallerContext;
public class UpdateLinkeLinklogAccountResponseUnmarshaller {
public static UpdateLinkeLinklogAccountResponse unmarshall(UpdateLinkeLinklogAccountResponse updateLinkeLinklogAccountResponse, UnmarshallerContext _ctx) {
updateLinkeLinklogAccountResponse.setRequestId(_ctx.stringValue("UpdateLinkeLinklogAccountResponse.RequestId"));
updateLinkeLinklogAccountResponse.setResultCode(_ctx.stringValue("UpdateLinkeLinklogAccountResponse.ResultCode"));
updateLinkeLinklogAccountResponse.setResultMessage(_ctx.stringValue("UpdateLinkeLinklogAccountResponse.ResultMessage"));
updateLinkeLinklogAccountResponse.setErrorMsg(_ctx.stringValue("UpdateLinkeLinklogAccountResponse.ErrorMsg"));
updateLinkeLinklogAccountResponse.setResponseContentRange(_ctx.stringValue("UpdateLinkeLinklogAccountResponse.ResponseContentRange"));
updateLinkeLinklogAccountResponse.setResponseContentType(_ctx.stringValue("UpdateLinkeLinklogAccountResponse.ResponseContentType"));
updateLinkeLinklogAccountResponse.setResponseStatusCode(_ctx.longValue("UpdateLinkeLinklogAccountResponse.ResponseStatusCode"));
updateLinkeLinklogAccountResponse.setSuccess(_ctx.booleanValue("UpdateLinkeLinklogAccountResponse.Success"));
Result result = new Result();
result.setBegin(_ctx.longValue("UpdateLinkeLinklogAccountResponse.Result.Begin"));
result.setBeginMills(_ctx.longValue("UpdateLinkeLinklogAccountResponse.Result.BeginMills"));
result.setCurrentPage(_ctx.longValue("UpdateLinkeLinklogAccountResponse.Result.CurrentPage"));
result.setEmpId(_ctx.stringValue("UpdateLinkeLinklogAccountResponse.Result.EmpId"));
result.setEnd(_ctx.longValue("UpdateLinkeLinklogAccountResponse.Result.End"));
result.setEndMills(_ctx.longValue("UpdateLinkeLinklogAccountResponse.Result.EndMills"));
result.setGmtCreate(_ctx.longValue("UpdateLinkeLinklogAccountResponse.Result.GmtCreate"));
result.setGmtModified(_ctx.longValue("UpdateLinkeLinklogAccountResponse.Result.GmtModified"));
result.setId(_ctx.longValue("UpdateLinkeLinklogAccountResponse.Result.Id"));
result.setNick(_ctx.stringValue("UpdateLinkeLinklogAccountResponse.Result.Nick"));
result.setPageSize(_ctx.longValue("UpdateLinkeLinklogAccountResponse.Result.PageSize"));
result.setRole(_ctx.longValue("UpdateLinkeLinklogAccountResponse.Result.Role"));
result.setRoleName(_ctx.stringValue("UpdateLinkeLinklogAccountResponse.Result.RoleName"));
result.setSorter(_ctx.stringValue("UpdateLinkeLinklogAccountResponse.Result.Sorter"));
List<String> stores = new ArrayList<String>();
for (int i = 0; i < _ctx.lengthValue("UpdateLinkeLinklogAccountResponse.Result.Stores.Length"); i++) {
stores.add(_ctx.stringValue("UpdateLinkeLinklogAccountResponse.Result.Stores["+ i +"]"));
}
result.setStores(stores);
List<Long> storeIds = new ArrayList<Long>();
for (int i = 0; i < _ctx.lengthValue("UpdateLinkeLinklogAccountResponse.Result.StoreIds.Length"); i++) {
storeIds.add(_ctx.longValue("UpdateLinkeLinklogAccountResponse.Result.StoreIds["+ i +"]"));
}
result.setStoreIds(storeIds);
updateLinkeLinklogAccountResponse.setResult(result);
return updateLinkeLinklogAccountResponse;
}
} |
dengzhicheng092/SocialApp | app/src/main/java/innovativedeveloper/com/socialapp/services/MyFirebaseMessagingService.java | package innovativedeveloper.com.socialapp.services;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import innovativedeveloper.com.socialapp.ActivityPost;
import innovativedeveloper.com.socialapp.Comments;
import innovativedeveloper.com.socialapp.MainActivity;
import innovativedeveloper.com.socialapp.R;
import innovativedeveloper.com.socialapp.UserProfile;
import innovativedeveloper.com.socialapp.config.AppHandler;
import innovativedeveloper.com.socialapp.config.Config;
import innovativedeveloper.com.socialapp.dataset.Message;
import innovativedeveloper.com.socialapp.dataset.Notification;
import innovativedeveloper.com.socialapp.dataset.User;
import innovativedeveloper.com.socialapp.messaging.ChatActivity;
import innovativedeveloper.com.socialapp.messaging.Messages;
import static innovativedeveloper.com.socialapp.config.Config.PUSH_TYPE_MESSAGE;
import static innovativedeveloper.com.socialapp.config.Config.PUSH_TYPE_NOTIFICATION;
import static innovativedeveloper.com.socialapp.config.Config.PUSH_TYPE_REPLY;
import static innovativedeveloper.com.socialapp.config.Config.PUSH_TYPE_REQUESTS;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("MessagingService", "Message received.");
Map data = remoteMessage.getData();
String id = data.get("id").toString();
String title = data.get("title").toString();
String type = data.get("type").toString();
String strData = data.get("data").toString();
boolean isBackground = Boolean.valueOf(data.get("isBackground").toString());
boolean isCustom = Boolean.valueOf(data.get("isCustom").toString());
if (type.equals(String.valueOf(PUSH_TYPE_NOTIFICATION)) || type.equals(String.valueOf(PUSH_TYPE_REPLY))) {
updateNotification(strData, title, id, isCustom, isBackground);
} else if (type.equals(String.valueOf(PUSH_TYPE_MESSAGE))) {
updateMessage(strData, title, id, isCustom, isBackground);
} else if (type.equals(String.valueOf(PUSH_TYPE_REQUESTS))) {
updateRequests(strData, title, id, isCustom);
}
}
private void updateMessage(String Data, String title, String id, boolean isCustom, boolean isBackground) {
try {
JSONObject data = new JSONObject(Data);
JSONObject sender = data.getJSONObject("sender");
Notification n = new Notification();
Message m = new Message();
if (!isCustom) {
// Notification set
n.setId(id);
n.setUser_id(sender.getString("id"));
n.setName(sender.getString("name"));
n.setUsername(sender.getString("username"));
n.setAction(data.getString("action"));
n.setIcon(sender.getString("icon"));
n.setData(sender.getString("name") + " sent you a message.");
n.setCreation(data.getString("creation"));
// Message set
m.setUsername(n.getUsername());
m.setMessage(data.getString("message"));
m.setCreation(data.getString("creation"));
m.setType(data.getInt("type"));
m.setChecked(0);
m.setSent(1);
m.setIsOwn(0);
if (!AppHandler.getInstance().getDBHandler().isUserExists(n.getUsername())) {
User u = new User();
u.setUsername(sender.getString("username"));
u.setName(sender.getString("name"));
u.setEmail(sender.getString("email"));
u.setProfilePhoto(sender.getString("icon"));
AppHandler.getInstance().getDBHandler().addUser(u);
}
AppHandler.getInstance().getDBHandler().addMessage(m);
if (!isBackground) {
if (!AppHandler.isAppIsInBackground(getApplicationContext())) {
AppHandler.getInstance().playNotificationSound();
}
broadcastNotification(n, false, title);
}
updateMessage(id);
} else {
n.setAction("3");
n.setData(data.getString("messageData"));
broadcastNotification(n, true, title);
}
} catch (JSONException ex) {
Log.e("ListenerService", ex.getMessage());
}
}
private void updateRequests(String Data, String title, String id, boolean isCustom) {
try {
JSONObject data = new JSONObject(Data);
Notification n = new Notification();
n.setId(id);
n.setUser_id(data.getString("userId"));
n.setUsername(data.getString("username"));
n.setAction(data.getString("action"));
n.setData(data.getString("messageData"));
if (AppHandler.isAppIsInBackground(getApplicationContext())) {
} else {
}
updateNotification(n.getId());
} catch (JSONException ex) {
Log.e("ListenerService", ex.getMessage());
}
}
private void updateNotification(String Data, String title, String id, boolean isCustom, boolean isBackground) {
try {
JSONObject data = new JSONObject(Data);
Notification n = new Notification();
if (!isCustom) {
n.setId(id);
n.setUser_id(data.getString("userId"));
n.setPostId(data.getString("postId"));
n.setCommentId(data.getString("commentId"));
n.setUsername(data.getString("username"));
n.setAction(data.getString("action"));
n.setIcon(data.getString("icon"));
n.setData(data.getString("messageData"));
n.setCreation(data.getString("creation"));
AppHandler.getInstance().getDBHandler().addNotification(n);
if (!isBackground) {
if (!AppHandler.isAppIsInBackground(getApplicationContext())) {
AppHandler.getInstance().playNotificationSound();
}
broadcastNotification(n, false, title);
}
updateNotification(n.getId());
} else {
n.setAction("1");
n.setData(data.getString("messageData"));
broadcastNotification(n, true, title);
}
} catch (JSONException ex) {
Log.e("ListenerService", ex.getMessage());
}
}
private void updateNotification(String id) {
final StringRequest request = new StringRequest(Request.Method.POST, Config.UPDATE_NOTIFICATION.replace(":id", id), new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
Log.d("NotificationService", "Notification marked as read from server-side.");
} else {}
}
catch (JSONException ex) {
Log.e("FirebaseService", "Unexpected error: " + ex.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("FirebaseService", "Unexpected error: " + error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return AppHandler.getInstance().getAuthorization();
}
};
int socketTimeout = 0;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
AppHandler.getInstance().addToRequestQueue(request);
}
private void updateMessage(String id) {
final StringRequest request = new StringRequest(Request.Method.POST, Config.UPDATE_MESSAGE.replace(":id", id), new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
Log.d("MessagingService", "Message marked as read from server-side.");
} else {}
}
catch (JSONException ex) {
Log.e("FirebaseService", "Unexpected error: " + ex.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("FirebaseService", "Unexpected error: " + error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return AppHandler.getInstance().getAuthorization();
}
};
int socketTimeout = 0;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
AppHandler.getInstance().addToRequestQueue(request);
}
private void broadcastNotification(Notification n, boolean isCustom, String title) {
if (AppHandler.isAppIsInBackground(getApplicationContext())) {
Bitmap bitmap = getBitmapFromURL(n.getIcon());
Intent intent = new Intent();
if (n.getAction().equals(String.valueOf(PUSH_TYPE_MESSAGE))) {
if (isCustom) {
intent.setClass(getApplicationContext(), Messages.class);
} else {
intent.putExtra("username", n.getUsername());
intent.putExtra("name", n.getName());
intent.setClass(getApplicationContext(), ChatActivity.class);
}
}
if (n.getAction().equals(String.valueOf(PUSH_TYPE_NOTIFICATION))) {
if (isCustom) {
intent.putExtra("isNotification", true);
intent.setClass(getApplicationContext(), MainActivity.class);
} else {
if (!n.getPostId().equals("0")) {
intent.putExtra("username", n.getUsername());
intent.putExtra("name", n.getUsername());
intent.putExtra("postId", n.getPostId());
intent.setClass(getApplicationContext(), ActivityPost.class);
} else {
intent.putExtra("username", n.getUsername());
intent.putExtra("name", n.getUsername());
intent.setClass(getApplicationContext(), UserProfile.class);
}
}
}
if (n.getAction().equals(String.valueOf(PUSH_TYPE_REPLY))) {
if (isCustom) {
intent.putExtra("isNotification", true);
intent.setClass(getApplicationContext(), MainActivity.class);
} else {
Log.d("Messaging", "comment id: " + n.getPostId());
intent.putExtra("postId", n.getPostId());
intent.putExtra("commentId", n.getCommentId());
intent.putExtra("isDisabled", false);
intent.putExtra("isOwnPost", false);
intent.putExtra("isReply", true);
intent.setClass(getApplicationContext(), Comments.class);
}
}
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
final Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
android.app.Notification notif = new android.app.Notification.Builder(this)
.setContentIntent(resultPendingIntent)
.setContentTitle(title)
.setAutoCancel(true)
.setContentText(n.getData())
.setSound(notificationSound)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(bitmap)
.build();
notificationManager.notify(n.getId() != null ? Integer.valueOf(n.getId()) : 0, notif);
} else {
Intent notificationIntent = new Intent("notification");
notificationIntent.putExtra("isCustom", isCustom);
if (!isCustom) {
notificationIntent.putExtra("id", n.getId());
notificationIntent.putExtra("postId", n.getPostId());
notificationIntent.putExtra("messageData", n.getData());
notificationIntent.putExtra("commentId", n.getCommentId());
notificationIntent.putExtra("userId", n.getUser_id());
notificationIntent.putExtra("action", n.getAction());
notificationIntent.putExtra("username", n.getUsername());
if (n.getName() != null) notificationIntent.putExtra("name", n.getName());
} else {
notificationIntent.putExtra("action", n.getAction());
notificationIntent.putExtra("messageData", n.getData());
}
LocalBroadcastManager.getInstance(this).sendBroadcast(notificationIntent);
}
}
public Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
|
lambdaxymox/DragonFlyBSD | contrib/gcc-8.0/gcc/genmddump.c | <gh_stars>100-1000
/* Generate code from machine description to recognize rtl as insns.
Copyright (C) 1987-2018 Free Software Foundation, Inc.
This file is part of GCC.
GCC 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 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
/* This program is used to produce tmp-mddump.md, which represents
md-file with expanded iterators and after define_subst transformation
is performed.
The only argument of the program is a source md-file (e.g.
config/i386/i386.md). STDERR is used for the program output. */
#include "bconfig.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "rtl.h"
#include "errors.h"
#include "read-md.h"
#include "gensupport.h"
extern int main (int, const char **);
int
main (int argc, const char **argv)
{
progname = "genmddump";
if (!init_rtx_reader_args (argc, argv))
return (FATAL_EXIT_CODE);
/* Read the machine description. */
md_rtx_info info;
while (read_md_rtx (&info))
{
printf (";; %s: %d\n", info.loc.filename, info.loc.lineno);
print_inline_rtx (stdout, info.def, 0);
printf ("\n\n");
}
fflush (stdout);
return (ferror (stdout) != 0 ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE);
}
|
znep/pgjdbc | pgjdbc/src/main/java/org/postgresql/replication/LogSequenceNumber.java | /*
* Copyright (c) 2016, PostgreSQL Global Development Group
* See the LICENSE file in the project root for more information.
*/
package org.postgresql.replication;
import java.nio.ByteBuffer;
/**
* LSN (Log Sequence Number) data which is a pointer to a location in the XLOG
*/
public final class LogSequenceNumber {
/**
* Zero is used indicate an invalid pointer. Bootstrap skips the first possible WAL segment,
* initializing the first WAL page at XLOG_SEG_SIZE, so no XLOG record can begin at zero.
*/
public static final LogSequenceNumber INVALID_LSN = LogSequenceNumber.valueOf(0);
private final long value;
private LogSequenceNumber(long value) {
this.value = value;
}
/**
* @param value numeric represent position in the write-ahead log stream
* @return not null LSN instance
*/
public static LogSequenceNumber valueOf(long value) {
return new LogSequenceNumber(value);
}
/**
* Create LSN instance by string represent LSN
*
* @param strValue not null string as two hexadecimal numbers of up to 8 digits each, separated by
* a slash. For example {@code 16/3002D50}, {@code 0/15D68C50}
* @return not null LSN instance where if specified string represent have not valid form {@link
* LogSequenceNumber#INVALID_LSN}
*/
public static LogSequenceNumber valueOf(String strValue) {
int slashIndex = strValue.lastIndexOf('/');
if (slashIndex <= 0) {
return INVALID_LSN;
}
String logicalXLogStr = strValue.substring(0, slashIndex);
int logicalXlog = (int) Long.parseLong(logicalXLogStr, 16);
String segmentStr = strValue.substring(slashIndex + 1, strValue.length());
int segment = (int) Long.parseLong(segmentStr, 16);
ByteBuffer buf = ByteBuffer.allocate(8);
buf.putInt(logicalXlog);
buf.putInt(segment);
buf.position(0);
long value = buf.getLong();
return LogSequenceNumber.valueOf(value);
}
/**
* @return Long represent position in the write-ahead log stream
*/
public long asLong() {
return value;
}
/**
* @return String represent position in the write-ahead log stream as two hexadecimal numbers of
* up to 8 digits each, separated by a slash. For example {@code 16/3002D50}, {@code 0/15D68C50}
*/
public String asString() {
ByteBuffer buf = ByteBuffer.allocate(8);
buf.putLong(value);
buf.position(0);
int logicalXlog = buf.getInt();
int segment = buf.getInt();
return String.format("%X/%X", logicalXlog, segment);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LogSequenceNumber that = (LogSequenceNumber) o;
return value == that.value;
}
@Override
public int hashCode() {
return (int) (value ^ (value >>> 32));
}
@Override
public String toString() {
return "LSN{" + asString() + '}';
}
}
|
redpesk-common/canbus-binding | low-can-binding/can/signals.cpp | <reponame>redpesk-common/canbus-binding<gh_stars>0
/*
* Copyright (C) 2015, 2016 "IoT.bzh"
* Author "<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.
*/
#include <fnmatch.h>
#include <memory>
#include <low-can/can/signals.hpp>
#include <low-can/binding/application.hpp>
#include <low-can/can/can-decoder.hpp>
#include <low-can/can/can-encoder.hpp>
#include <low-can/can/can-bus.hpp>
#include <low-can/diagnostic/diagnostic-message.hpp>
#include <low-can/utils/signals.hpp>
#include <low-can/utils/openxc-utils.hpp>
#include "canutil/write.h"
signal_t::signal_t(
std::string name,
uint32_t bit_position,
uint32_t bit_size,
float factor,
float offset,
float min_value,
float max_value,
frequency_clock_t frequency,
bool send_same,
bool force_send_changed,
std::map<uint8_t, std::string> states,
bool writable,
signal_decoder decoder,
signal_encoder encoder,
bool received,
std::pair<bool, int> multiplex,
sign_t sign,
int32_t bit_sign_position,
std::string unit,
std::string permission)
: parent_{nullptr},
name_{ name }
, bit_position_{ bit_position }
, bit_size_{ bit_size }
, factor_{ factor }
, offset_{ offset }
, min_value_{min_value}
, max_value_{max_value}
, frequency_{frequency}
, send_same_{send_same}
, force_send_changed_{force_send_changed}
, states_{states}
, writable_{writable}
, decoder_{decoder}
, encoder_{encoder}
, received_{received}
, last_value_{.0f}
, multiplex_{multiplex}
, sign_{sign}
, bit_sign_position_{bit_sign_position}
, unit_{unit}
, permission_{permission}
{}
signal_t::signal_t(
std::string name,
uint32_t bit_position,
uint32_t bit_size,
float factor,
float offset,
float min_value,
float max_value,
frequency_clock_t frequency,
bool send_same,
bool force_send_changed,
std::map<uint8_t, std::string> states,
bool writable,
signal_decoder decoder,
signal_encoder encoder,
bool received,
std::pair<bool, int> multiplex,
sign_t sign,
int32_t bit_sign_position,
std::string unit)
: parent_{nullptr},
name_{ name }
, bit_position_{ bit_position }
, bit_size_{ bit_size }
, factor_{ factor }
, offset_{ offset }
, min_value_{min_value}
, max_value_{max_value}
, frequency_{frequency}
, send_same_{send_same}
, force_send_changed_{force_send_changed}
, states_{states}
, writable_{writable}
, decoder_{decoder}
, encoder_{encoder}
, received_{received}
, last_value_{.0f}
, multiplex_{multiplex}
, sign_{sign}
, bit_sign_position_{bit_sign_position}
, unit_{unit}
{}
signal_t::signal_t(
std::string name,
uint32_t bit_position,
uint32_t bit_size,
float factor,
float offset,
float min_value,
float max_value,
frequency_clock_t frequency,
bool send_same,
bool force_send_changed,
std::map<uint8_t, std::string> states,
bool writable,
signal_decoder decoder,
signal_encoder encoder,
bool received)
: name_{ name }
, bit_position_{ bit_position }
, bit_size_{ bit_size }
, factor_{ factor }
, offset_{ offset }
, min_value_{min_value}
, max_value_{max_value}
, frequency_{frequency}
, send_same_{send_same}
, force_send_changed_{force_send_changed}
, states_{states}
, writable_{writable}
, decoder_{decoder}
, encoder_{encoder}
, received_{received}
{}
std::shared_ptr<signal_t> signal_t::get_shared_ptr()
{
return shared_from_this();
}
std::shared_ptr<message_definition_t> signal_t::get_message() const
{
return parent_;
}
const std::string signal_t::get_name() const
{
return name_;
}
uint32_t signal_t::get_bit_position() const
{
return bit_position_;
}
uint32_t signal_t::get_bit_size() const
{
return bit_size_;
}
float signal_t::get_factor() const
{
return factor_;
}
float signal_t::get_offset() const
{
return offset_;
}
float signal_t::get_min_value() const
{
return min_value_;
}
float signal_t::get_max_value() const
{
return max_value_;
}
frequency_clock_t& signal_t::get_frequency()
{
return frequency_;
}
bool signal_t::get_send_same() const
{
return send_same_;
}
const std::string signal_t::get_states(uint8_t value)
{
if ( states_.count(value) > 0 )
return states_[value];
return std::string();
}
uint64_t signal_t::get_states(const std::string& value) const
{
uint64_t ret = -1;
for( const auto& state: states_)
{
if(caseInsCompare(state.second, value))
{
ret = (uint64_t)state.first;
break;
}
}
return ret;
}
bool signal_t::get_writable() const
{
return writable_;
}
signal_decoder& signal_t::get_decoder()
{
return decoder_;
}
signal_encoder& signal_t::get_encoder()
{
return encoder_;
}
bool signal_t::get_received() const
{
return received_;
}
float signal_t::get_last_value() const
{
return last_value_;
}
json_object* signal_t::afb_verb_get_last_value()
{
json_object *jobj = json_object_new_object();
if(! received_)
return nullptr;
if(states_.empty())
{
json_object_object_add(jobj, get_name().c_str(),
json_object_new_double(last_value_));
}
else
{
std::string val = states_[(uint8_t) last_value_];
json_object_object_add(jobj, get_name().c_str(),
json_object_new_string(val.c_str()));
}
json_object_object_add(jobj, "timestamp",
json_object_new_double(frequency_.get_last_tick()));
return jobj;
}
int signal_t::afb_verb_write_on_bus(json_object *json_value)
{
openxc_DynamicField dynafield_value = build_DynamicField(json_value);
std::shared_ptr<signal_t> sig = get_shared_ptr();
std::string bus_name = sig->get_message()->get_bus_device_name();
bool send = true;
uint64_t value = encoder_ ?
encoder_(*this, dynafield_value, &send) :
encoder_t::encode_DynamicField(*this, dynafield_value, &send);
uint32_t flags = INVALID_FLAG;
if(get_message()->is_j1939())
flags = J1939_PROTOCOL;
else if(get_message()->is_isotp())
flags = ISOTP_PROTOCOL;
else
flags = CAN_PROTOCOL;
message_t *message = encoder_t::build_message(sig, value, false, false);
std::map<std::string, std::shared_ptr<low_can_subscription_t> >& cd = application_t::instance().get_can_devices();
cd[bus_name] = std::make_shared<low_can_subscription_t>(low_can_subscription_t());
cd[bus_name]->set_signal(sig);
if(flags & CAN_PROTOCOL)
return low_can_subscription_t::tx_send(*cd[bus_name], message, bus_name);
#ifdef USE_FEATURE_ISOTP
else if(flags & ISOTP_PROTOCOL)
return low_can_subscription_t::isotp_send(*cd[bus_name], message, bus_name);
#endif
#ifdef USE_FEATURE_J1939
else if(flags & J1939_PROTOCOL)
return low_can_subscription_t::j1939_send(*cd[bus_name], message, bus_name);
#endif
else
return -1;
if(get_message()->is_j1939())
#ifdef USE_FEATURE_J1939
delete (j1939_message_t*) message;
#else
AFB_WARNING("Warning: You do not have J1939 feature activated.");
#endif
else
delete (can_message_t*) message;
return -1;
}
std::pair<float, uint64_t> signal_t::get_last_value_with_timestamp() const
{
return std::make_pair(last_value_, frequency_.get_last_tick());
}
void signal_t::set_parent(std::shared_ptr<message_definition_t> parent)
{
parent_ = parent;
}
void signal_t::set_received(bool r)
{
received_ = r;
}
void signal_t::set_last_value(float val)
{
last_value_ = val;
}
void signal_t::set_timestamp(uint64_t timestamp)
{
frequency_.tick(timestamp);
}
void signal_t::set_bit_position(uint32_t bit_position)
{
bit_position_=bit_position;
}
std::pair<bool,int> signal_t::get_multiplex() const
{
return multiplex_;
}
sign_t signal_t::get_sign() const
{
return sign_;
}
int32_t signal_t::get_bit_sign_position() const
{
return bit_sign_position_;
}
const std::string signal_t::get_unit() const
{
return unit_;
}
const std::string signal_t::get_permission() const
{
return permission_;
}
|
openharmony-gitee-mirror/ace_ace_engine | frameworks/core/components/svg/flutter_render_svg_use.cpp | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "frameworks/core/components/svg/flutter_render_svg_use.h"
#include "frameworks/core/components/transform/flutter_render_transform.h"
#include "frameworks/core/pipeline/base/flutter_render_context.h"
namespace OHOS::Ace {
using namespace Flutter;
RefPtr<RenderNode> RenderSvgUse::Create()
{
return AceType::MakeRefPtr<FlutterRenderSvgUse>();
}
RenderLayer FlutterRenderSvgUse::GetRenderLayer()
{
if (!transformLayer_) {
transformLayer_ = AceType::MakeRefPtr<Flutter::TransformLayer>(Matrix4::CreateIdentity(), 0.0, 0.0);
}
return AceType::RawPtr(transformLayer_);
}
void FlutterRenderSvgUse::Paint(RenderContext& context, const Offset& offset)
{
if (GreatNotEqual(x_.Value(), 0.0) || GreatNotEqual(y_.Value(), 0.0)) {
if (GetRenderLayer()) {
auto transform = Matrix4::CreateTranslate(ConvertDimensionToPx(x_, LengthType::HORIZONTAL),
ConvertDimensionToPx(y_, LengthType::VERTICAL), 0.0f);
if (!transformLayer_) {
transformLayer_ = AceType::MakeRefPtr<Flutter::TransformLayer>(Matrix4::CreateIdentity(), 0.0, 0.0);
}
transformLayer_->Update(transform);
}
}
if (transformLayer_ && NeedTransform()) {
transformLayer_->Update(GetTransformMatrix4());
}
RenderNode::Paint(context, offset);
}
void FlutterRenderSvgUse::OnGlobalPositionChanged()
{
if (transformLayer_ && NeedTransform()) {
transformLayer_->Update(UpdateTransformMatrix4());
}
RenderNode::OnGlobalPositionChanged();
}
} // namespace OHOS::Ace
|
imdeepmind/enviar-web | enviar/src/app/redux/users/action.js | <reponame>imdeepmind/enviar-web
import {
USERS, USERS_SUCCESS, USERS_ERROR,
USERS_INDIVIDUAL, USERS_SUCCESS_INDIVIDUAL, USERS_ERROR_INDIVIDUAL,
USER_ACTION, USER_ACTION_SUCCESS, USER_ACTION_ERROR,
USERS_FOLLOWEE, USERS_FOLLOWEE_ERROR, USERS_FOLLOWEE_SUCCESS,
USERS_FOLLOWERS, USERS_FOLLOWERS_ERROR, USERS_FOLLOWERS_SUCCESS
} from '../../../constants/actions';
export const users = (user, history) => ({
type: USERS,
payload: { user, history }
});
export const usersSuccess = (user) => ({
type: USERS_SUCCESS,
payload: user
});
export const usersError = (error) => ({
type: USERS_ERROR,
payload: error
});
export const usersIndividual = (user, history) => ({
type: USERS_INDIVIDUAL,
payload: { user, history }
});
export const usersSuccessIndividual = (user) => ({
type: USERS_SUCCESS_INDIVIDUAL,
payload: user
});
export const usersErrorIndividual = (error) => ({
type: USERS_ERROR_INDIVIDUAL,
payload: error
});
export const userAction = (user, history) => ({
type: USER_ACTION,
payload: { user, history }
});
export const userActionSuccess = (user) => ({
type: USER_ACTION_SUCCESS,
payload: user
});
export const userActionError = (error) => ({
type: USER_ACTION_ERROR,
payload: error
});
export const usersFollowee = (user) => ({
type: USERS_FOLLOWEE,
payload: { user }
});
export const usersFolloweeSuccess = (user) => ({
type: USERS_FOLLOWEE_SUCCESS,
payload: user
});
export const usersFolloweeError = (error) => ({
type: USERS_FOLLOWEE_ERROR,
payload: error
});
export const usersFollowers = (user) => ({
type: USERS_FOLLOWERS,
payload: { user }
});
export const usersFollowersSuccess = (user) => ({
type: USERS_FOLLOWERS_SUCCESS,
payload: user
});
export const usersFollowersError = (error) => ({
type: USERS_FOLLOWERS_ERROR,
payload: error
}); |
caigy/beats | libbeat/cmd/instance/metrics/metrics_file_descriptors.go | // Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//go:build linux || (freebsd && cgo)
// +build linux freebsd,cgo
package metrics
import (
"github.com/pkg/errors"
"github.com/elastic/beats/v7/libbeat/logp"
"github.com/elastic/beats/v7/libbeat/monitoring"
)
func setupLinuxBSDFDMetrics() {
monitoring.NewFunc(beatMetrics, "handles", reportFDUsage, monitoring.Report)
}
func reportFDUsage(_ monitoring.Mode, V monitoring.Visitor) {
V.OnRegistryStart()
defer V.OnRegistryFinished()
open, hardLimit, softLimit, err := getFDUsage()
if err != nil {
logp.Err("Error while retrieving FD information: %v", err)
return
}
monitoring.ReportInt(V, "open", int64(open))
monitoring.ReportNamespace(V, "limit", func() {
monitoring.ReportInt(V, "hard", int64(hardLimit))
monitoring.ReportInt(V, "soft", int64(softLimit))
})
}
func getFDUsage() (open, hardLimit, softLimit uint64, err error) {
state, err := beatProcessStats.GetSelf()
if err != nil {
return 0, 0, 0, errors.Wrap(err, "error fetching self process")
}
open = state.FD.Open.ValueOr(0)
hardLimit = state.FD.Limit.Hard.ValueOr(0)
softLimit = state.FD.Limit.Soft.ValueOr(0)
return open, hardLimit, softLimit, nil
}
|
c-ehrlich/demo-projects | apps/american-british-translator/components/translator.js | const americanOnly = require('./american-only.js');
const americanToBritishSpelling = require('./american-to-british-spelling.js');
const americanToBritishTitles = require("./american-to-british-titles.js")
const britishOnly = require('./british-only.js')
class Translator {
static replaceCurry(word, replacement, highlight, adjustCase = false) {
if(adjustCase) {
replacement = replacement.replace(/^([a-z])/ig, letter => letter.toUpperCase());
}
return (word) => {
if(highlight) {
return `<span class="highlight">${replacement}</span>`.replace(/\s/g,"\0");
} else {
return '~' + replacement.replace(/\s/g,"\0") + '~';
}
}
}
static translateAmericanToBritish(input, highlight=false) {
let american, british;
// Phrases
for([american, british] of Object.entries(americanOnly) ) {
input = input.replace(new RegExp(`\\b${american}\\b`,'gi'),
Translator.replaceCurry(american,british,highlight));
}
// Spelling
for([american, british] of Object.entries(americanToBritishSpelling) ) {
input = input.replace(new RegExp(`\\b${american}\\b`,'gi'),
Translator.replaceCurry(american,british,highlight));
}
// Title Replacement
for([american, british] of Object.entries(americanToBritishTitles) ) {
american = american.replace('.', '\.');
input = input.replace(new RegExp(`\\b${american}`,'gi'),
Translator.replaceCurry(american,british,highlight, true));
}
// Time Replacement, colon to period replacement
if(highlight) {
input = input.replace(/(\d{1,2}):(\d{1,2})/gi, '<span class="highlight">\$1.\$2</span>');
} else {
input = input.replace(/(?<=\d{1,2}):(?=\d{1,2})/gi, '.');
}
// Uppercase start of sentence
input = input.replace(/^([a-z])/ig, letter => letter.toUpperCase());
return input.replace(/~/g, '').replace(/\0/g, ' ');
}
static translateBritishToAmerican(input, highlight=false) {
let american, british;
// Phrases
for([british, american] of Object.entries(britishOnly) ) {
input = input.replace(new RegExp(`\\b${british}\\b`,'gi'),
Translator.replaceCurry(british,american,highlight));
}
// Spelling
for([american, british] of Object.entries(americanToBritishSpelling) ) {
input = input.replace(new RegExp(`\\b${british}\\b`,'gi'),
Translator.replaceCurry(british,american,highlight));
}
// Title Replacement
for([american, british] of Object.entries(americanToBritishTitles) ) {
input = input.replace(new RegExp(`\\b${british}\\b`,'gi'),
Translator.replaceCurry(british,american,highlight, true));
}
// Time Replacement, period to colon replacement
if(highlight) {
input = input.replace(/(\d{1,2}).(\d{1,2})/gi, '<span class="highlight">\$1:\$2</span>');
} else {
input = input.replace(/(?<=\d{1,2})\.(?=\d{1,2})/gi, ':');
}
// Uppercase start of sentence
input = input.replace(/^([a-z])/ig, letter => letter.toUpperCase());
return input.replace(/~/g, '').replace(/\0/g, ' ');
}
}
module.exports = Translator;
|
michael21910/CPE-1-star-problems | UVa 10235 - Simply Emirp/Simply Emirp.cpp | #include <bits/stdc++.h>
using namespace std;
bool notPrime[1000001];
void makeTable()
{
notPrime[1] = true;
for(int i = 2; i < 1000001; i++){
if(!notPrime[i]){
for(int j = i + i; j < 1000001; j += i){
notPrime[j] = true;
}
}
}
}
int main()
{
makeTable();
string str, temp;
while(cin >> str){
temp = str;
cout << str << " ";
if(!notPrime[stoi(str)]){
reverse(str.begin(), str.end());
if(temp == str){
cout << "is prime." << endl;
continue;
}
if(!notPrime[stoi(str)]){
cout << "is emirp." << endl;
continue;
}
else{
cout << "is prime." << endl;
continue;
}
}
else{
cout << "is not prime." << endl;
continue;
}
}
return 0;
}
|
hmrc/tax-summaries | test/connectors/ODSConnectorTest.scala | /*
* Copyright 2021 HM Revenue & Customs
*
* 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 connectors
import com.github.tomakehurst.wiremock.client.WireMock._
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.{JsObject, JsString}
import uk.gov.hmrc.http.{HeaderCarrier, HeaderNames, RequestId, SessionId, UpstreamErrorResponse}
import utils.TestConstants._
import utils.{BaseSpec, WireMockHelper}
class ODSConnectorTest extends BaseSpec with WireMockHelper {
override def fakeApplication(): Application =
new GuiceApplicationBuilder()
.configure(
"microservice.services.tax-summaries-hod.port" -> server.port(),
"microservice.services.tax-summaries-hod.host" -> "127.0.0.1"
)
.build()
lazy val sut: ODSConnector = inject[ODSConnector]
val json = JsObject(Map("foo" -> JsString("bar")))
val sessionId = "testSessionId"
val requestId = "testRequestId"
implicit val hc: HeaderCarrier = HeaderCarrier(
sessionId = Some(SessionId(sessionId)),
requestId = Some(RequestId(requestId))
)
"connectToSelfAssessment" must {
val url = s"/self-assessment/individuals/$testUtr/annual-tax-summaries/2014"
"return json" when {
"200 is returned" in {
server.stubFor(
get(url).willReturn(ok(json.toString()))
)
val result = sut.connectToSelfAssessment(testUtr, 2014)
whenReady(result) {
_ mustBe Some(json)
}
server.verify(
getRequestedFor(urlEqualTo(url))
.withHeader(HeaderNames.xSessionId, equalTo(sessionId))
.withHeader(HeaderNames.xRequestId, equalTo(requestId))
.withHeader(
"CorrelationId",
matching("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}"))
)
}
}
"return None" when {
"404 is returned" in {
server.stubFor(
get(url).willReturn(notFound())
)
val result = sut.connectToSelfAssessment(testUtr, 2014)
whenReady(result) {
_ mustBe None
}
}
}
"return 500" in {
server.stubFor(
get(url).willReturn(serverError())
)
val result = sut.connectToSelfAssessment(testUtr, 2014)
whenReady(result.failed) { exception =>
exception mustBe a[UpstreamErrorResponse]
}
}
}
"connectToSelfAssessmentList" must {
val url = s"/self-assessment/individuals/$testUtr/annual-tax-summaries"
"return json" when {
"200 is returned" in {
server.stubFor(
get(url).willReturn(ok(json.toString()))
)
val result = sut.connectToSelfAssessmentList(testUtr)
whenReady(result) {
_ mustBe Some(json)
}
}
}
"return None" when {
"404 is returned" in {
server.stubFor(
get(url).willReturn(notFound())
)
val result = sut.connectToSelfAssessmentList(testUtr)
whenReady(result) {
_ mustBe None
}
}
}
"return an exception" when {
"500 is returned" in {
server.stubFor(
get(url).willReturn(serverError())
)
val result = sut.connectToSelfAssessmentList(testUtr)
whenReady(result.failed) { exception =>
exception mustBe a[UpstreamErrorResponse]
}
}
}
}
"connectToSATaxpayerDetails" must {
val url = s"/self-assessment/individual/$testUtr/designatory-details/taxpayer"
"return json" when {
"200 is returned" in {
server.stubFor(
get(url).willReturn(ok(json.toString()))
)
val result = sut.connectToSATaxpayerDetails(testUtr)
whenReady(result) {
_ mustBe Some(json)
}
}
}
"return None" when {
"404 is returned" in {
server.stubFor(
get(url).willReturn(notFound())
)
val result = sut.connectToSATaxpayerDetails(testUtr)
whenReady(result) {
_ mustBe None
}
}
}
"return an exception" when {
"500 is returned" in {
server.stubFor(
get(url).willReturn(serverError())
)
val result = sut.connectToSATaxpayerDetails(testUtr)
whenReady(result.failed) { exception =>
exception mustBe a[UpstreamErrorResponse]
}
}
}
}
}
|
lyubomyr-shaydariv/exolon | src/entities/DoubleLauncherBulletEntity.js | <filename>src/entities/DoubleLauncherBulletEntity.js<gh_stars>10-100
define(
[
"src/me",
"src/util",
"src/entities/BlasterExplosion",
],
function (
me,
util,
BlasterExplosion
) {
var DoubleLauncherBulletEntity = me.ObjectEntity.extend({
init: function (x, y) {
var settings = {};
settings.image = "double_launcher_bullet";
this.parent(x, y + DoubleLauncherBulletEntity.HEIGHT, settings);
this.gravity = 0;
this.vel.x = -3;
this.isLethal = true;
this.isDestroyable = true;
this.collidable = true;
},
update: function () {
this.updateMovement();
this.handleCollisions();
return true;
},
handleCollisions: function () {
var res = me.game.collide(this);
var hitVitorc = res && (res.obj.isSolid || res.obj.name == "vitorc");
if (this.vel.x == 0 || hitVitorc) {
me.game.remove(this);
}
if (hitVitorc) {
this.createExplosion();
}
},
onCollision: function (res, obj) {
if (obj.name == "blaster_bullet") {
me.game.remove(this);
this.createExplosion();
util.updatePoints(50);
}
},
createExplosion: function () {
var explosion = new BlasterExplosion(this.pos.x, this.pos.y);
me.game.add(explosion, this.z);
me.game.sort.defer();
me.audio.play("burst");
},
});
DoubleLauncherBulletEntity.WIDTH = 16;
DoubleLauncherBulletEntity.HEIGHT = 16;
return DoubleLauncherBulletEntity;
});
|
TrashToggled/MinecraftNetwork | Bungee/src/main/java/com/github/jolice/bungee/message/PrivateMessageHandler.java | package io.riguron.bungee.message;
import lombok.RequiredArgsConstructor;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import io.riguron.messaging.handler.MessageHandler;
import io.riguron.messaging.message.PrivateMessageCommand;
import java.lang.reflect.Type;
@RequiredArgsConstructor
public class PrivateMessageHandler implements MessageHandler<PrivateMessageCommand> {
private final ProxyServer proxyServer;
@Override
public void accept(PrivateMessageCommand message) {
proxyServer.getPlayer(message.getFrom()).sendMessage(new TextComponent(message.getText()));
}
@Override
public Type getMessageType() {
return PrivateMessageCommand.class;
}
}
|
Ashindustry007/competitive-programming | uva/00100.py | #!/usr/bin/env python3
# https://uva.onlinejudge.org/external/1/100.pdf
from functools import reduce
def collatz(n):
i = 1
while n > 1:
if n % 2: n = n * 3 + 1
else: n >>= 1
i += 1
return i
while True:
try:
line = input()
except:
break
a, b = map(int, line.split())
print(a, b, reduce(lambda x, y: max(x, collatz(y)), range(min(a, b), max(a, b) + 1), collatz(a)))
|
Frcsty/DocDex | discord/src/main/java/me/piggypiglet/docdex/db/tables/framework/RawServerRuleId.java | package me.piggypiglet.docdex.db.tables.framework;
import org.jetbrains.annotations.NotNull;
// ------------------------------
// Copyright (c) PiggyPiglet 2020
// https://www.piggypiglet.me
// ------------------------------
public interface RawServerRuleId extends RawServerRule {
@NotNull
String getId();
}
|
williambl/interlok | adapter/src/test/java/com/adaptris/core/services/cache/translators/ObjectMetadataCacheValueTranslatorTest.java | <reponame>williambl/interlok
package com.adaptris.core.services.cache.translators;
import javax.jms.JMSException;
import javax.jms.Queue;
import com.adaptris.core.AdaptrisMessage;
import com.adaptris.core.jms.JmsConstants;
public class ObjectMetadataCacheValueTranslatorTest extends CacheValueTranslatorBaseCase {
public ObjectMetadataCacheValueTranslatorTest(String s) {
super(s);
}
public void testGetValueFromMessage() throws Exception {
AdaptrisMessage msg = createMessage();
// We can just reuse the OBJ_JMS_REPLY_TO_KEY metadata
ObjectMetadataCacheValueTranslator translator = new ObjectMetadataCacheValueTranslator();
translator.setMetadataKey(JmsConstants.OBJ_JMS_REPLY_TO_KEY);
assertEquals("myQueue", ((Queue) translator.getValueFromMessage(msg)).getQueueName());
}
public void testAddValueToMessage() throws Exception {
AdaptrisMessage message = createMessage();
ObjectMetadataCacheValueTranslator translator = new ObjectMetadataCacheValueTranslator();
translator.setMetadataKey(JmsConstants.OBJ_JMS_REPLY_TO_KEY);
translator.addValueToMessage(message, new Queue() {
@Override
public String getQueueName() throws JMSException {
return "HelloWorld";
}
});
assertEquals("HelloWorld", ((Queue)message.getObjectMetadata().get(JmsConstants.OBJ_JMS_REPLY_TO_KEY)).getQueueName());
}
}
|
vprilepskiy/java-a-to-z | Servlet_DAO/src/main/java/ru/job4j/model/store/repository/AbstractUser.java | <gh_stars>0
package ru.job4j.model.store.repository;
import ru.job4j.model.entity.*;
import java.util.Set;
/**
* Created by VLADIMIR on 31.01.2018.
*/
public abstract class AbstractUser {
ru.job4j.model.entity.Role role;
Address address;
Set<MusicType> musicTypes;
ru.job4j.model.entity.User user;
Set<ru.job4j.model.entity.User> users;
final ru.job4j.model.store.dao.Role daoRole;
final ru.job4j.model.store.dao.Address daoAddress;
final ru.job4j.model.store.dao.MusicType daoMusicType;
final ru.job4j.model.store.dao.UserHasMusicType daoUserHasMusicType;
final ru.job4j.model.store.dao.User daoUser;
public AbstractUser() {
this.daoRole = new ru.job4j.model.store.dao.Role();
this.daoAddress = new ru.job4j.model.store.dao.Address();
this.daoMusicType = new ru.job4j.model.store.dao.MusicType();
this.daoUserHasMusicType = new ru.job4j.model.store.dao.UserHasMusicType();
this.daoUser = new ru.job4j.model.store.dao.User();
}
public ru.job4j.model.entity.Role getRole() {
return this.role;
}
public void setRole(ru.job4j.model.entity.Role role) {
this.role = role;
}
public Address getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
public Set<MusicType> getMusicTypes() {
return this.musicTypes;
}
public void setMusicTypes(Set<MusicType> musicTypes) {
this.musicTypes = musicTypes;
}
public ru.job4j.model.entity.User getUser() {
return this.user;
}
public void setUser(ru.job4j.model.entity.User user) {
this.user = user;
}
public Set<ru.job4j.model.entity.User> getUsers() {
return users;
}
/**
* операция получения всех связанных с ним сущностей
*/
public abstract void read();
/**
* операция добавления нового User и всех связанных с ним сущностей;
*/
public abstract void create();
/**
* операция поиска User по заданному параметру (Address, Role, MusicType).
*/
public abstract void find();
}
|
annagitel/ocs-ci | tests/manage/storageclass/test_create_storageclass_with_same_name.py | <filename>tests/manage/storageclass/test_create_storageclass_with_same_name.py
import logging
import pytest
from ocs_ci.ocs import constants, defaults
from ocs_ci.framework.testlib import tier1, ManageTest
from ocs_ci.ocs.resources.ocs import OCS
from ocs_ci.ocs.exceptions import CommandFailed
from ocs_ci.utility import templating
log = logging.getLogger(__name__)
SC_OBJ = None
@pytest.fixture(scope="class")
def test_fixture(request):
"""
This fixture defines the teardown function.
"""
request.addfinalizer(teardown)
def teardown():
"""
Tearing down the environment
"""
if SC_OBJ:
log.info(f"Deleting created storage class: {SC_OBJ.name}")
SC_OBJ.delete()
log.info(f"Storage class: {SC_OBJ.name} deleted successfully")
def create_storageclass(sc_name, expect_fail=False):
"""
Function to create a storage class and check for
duplicate storage class name
Args:
sc_name (str): name of the storageclass to be created
expect_fail (bool): To catch the incorrect scenario if
two SCs are indeed created with same name
Returns:
None
"""
# Create a storage class
sc_data = templating.load_yaml(constants.CSI_RBD_STORAGECLASS_YAML)
sc_data["metadata"]["name"] = sc_name
sc_data["parameters"]["clusterID"] = defaults.ROOK_CLUSTER_NAMESPACE
global SC_OBJ
SC_OBJ = OCS(**sc_data)
# Check for expected failure with duplicate SC name
try:
SC_OBJ.create()
assert not expect_fail, "SC creation with same name passed. Expected to fail !"
log.info(f"Storage class: {SC_OBJ.name} created successfully !")
log.debug(sc_data)
except CommandFailed as ecf:
assert "AlreadyExists" in str(ecf)
log.info(
f"Cannot create two StorageClasses with same name !"
f" Error message: \n"
f"{ecf}"
)
@tier1
@pytest.mark.usefixtures(
test_fixture.__name__,
)
@pytest.mark.polarion_id("OCS-322")
class TestCreateSCSameName(ManageTest):
def test_create_storageclass_with_same_name(self):
"""
To test that Storageclass creation with duplicate names is not allowed
"""
sc_name = "ocs-322-sc"
create_storageclass(sc_name)
log.info(
f"Attempting to create another storageclass "
f"with duplicate name {sc_name}"
)
create_storageclass(sc_name, expect_fail=True)
|
MrLoick/flixel-android | examples/flixel-examples-core/src/org/flixel/examples/box2d/TestDistanceJoint.java | package org.flixel.examples.box2d;
import org.flixel.FlxG;
import org.flixel.plugin.flxbox2d.collision.shapes.B2FlxBox;
import org.flixel.plugin.flxbox2d.dynamics.joints.B2FlxDistanceJoint;
/**
*
* @author <NAME>
*/
public class TestDistanceJoint extends Test
{
B2FlxDistanceJoint joint;
private B2FlxBox box1;
private B2FlxBox box2;
@Override
public void create()
{
super.create();
title.setText("DistanceJoint");
info.setText("The distance joint enforces a \ndistance between two bodies.");
box1 = createBox(FlxG.width/2-25, FlxG.height/2-25, 50, 50);
add(box1);
box2 = createBox(box1.x+100, FlxG.height/2-25, 50, 50);
add(box2);
joint = (B2FlxDistanceJoint) new B2FlxDistanceJoint(box1, box2)
.setAnchorA(box1.body.getWorldCenter())
.setAnchorB(box2.body.getWorldCenter())
.setShowLine(true)
.create();
add(joint);
}
@Override
public void destroy()
{
super.destroy();
box1 = box2 = null;
joint = null;
}
}
|
cethap/ScrumTools.io | public/modules/phases/phases.client.module.js | <filename>public/modules/phases/phases.client.module.js
/**
* Created by ScrumTools on 11/17/14.
*/
'use strict';
// Use Application configuration module to register a new module
ApplicationConfiguration.registerModule('phases'); |
joergboe/CppWalkThrough | PointerToMember/src/PointerToMember.cpp | <gh_stars>0
//============================================================================
// Name : PointerToMember.cpp
// Author : joergboe
//============================================================================
#include <cstdlib>
#include <iostream>
using namespace std;
class Base {
public:
char const * mess;
char a, b;
char const cc;
private:
char privc;
public:
Base(char const * mess_ = "Base", char a_ = 'a', char b_ = 'b') : mess(mess_), a(a_), b(b_), cc('C'), privc('p') {};
void print1(int val) const {
cout << "print1";
printVars();
cout << " val=" << val << endl;
}
void setA(char c_) {
a = c_;
}
void setB(char c_) {
b = c_;
}
protected:
void printVars() const {
cout << " mess=" << mess << " a=" << a << " b=" << b << " privc=" << privc;
}
};
class Derived : public Base {
public:
char d;
Derived() : Base("Derived", 'a'), d('d') {};
void print3(int val) {
cout << "print3";
printVars();
cout << " d=" << d << endl;
}
};
typedef char Base::* MemberPointerB1;
//using MemberPointer = char Base::*; //c11 stype
typedef void (Base::*MethodPointer)(int);
//using MethodPointer = void (Base::*)(int);
int main() {
cout << "Demonstration of pointer to member and pointer to method.\n"
"The declaration 'T C::* P' declares P as a pointer to non-static member of C of type T.\n"
"Where member can be a non-static attribute or a non-static class function.\n"
"Use operator '.*' (pointer to member of object) or '->*' (pointer to member of pointer)\n"
"to access these members.\n"
"Address operator '&C::member delivers the address for these pointers.\n"
"Pointers to member must not be assigned to other pointer types an void*.\n"
"The 'nullptr' can be assigned to a pointer to member.\n\n";
Base base1;
base1.print1(1);
cout << "\n****** Pointer to class member (non-static member) ******\n";
cout << "use 'char Base::* const char_ptr1' to declare a pointer to member\n";
cout << "use '&Base::a' to define the pointer\n";
char Base::* char_ptr1 = &Base::a;
cout << "use 'base1.*char_ptr1' to address where it points to.\n";
cout << base1.*char_ptr1 << endl;
cout << "char_ptr1 may point to all non-const char members of Base\n";
char_ptr1 = &Base::b;
cout << base1.*char_ptr1 << endl;
cout << "The member must be visible in that context:\n";
//char_ptr1 = &Base::privc; //error: ‘char Base::privc’ is private within this context
cout << "the pointer can be const qualified with 'char Base::* const char_ptr2 = &Base::a'\n";
char Base::* const char_ptr2 = &Base::a;
cout << "base1.*char_ptr2: " << base1.*char_ptr2 << endl;
cout << "constantness is maintained\n";
//char_ptr2 = &Base::b; //error: assignment of read-only variable ‘char_ptr2’
//char_ptr1 = &Base::cc; //error: invalid conversion from ‘const char Base::*’ to ‘char Base::*’ [-fpermissive]
Base const base2("Base const");
//base2.*char_ptr1 = 'x'; //error: assignment of read-only location ‘*(((const char*)(& base2)) + ((sizetype)char_ptr1))’
const char * Base::* mess_ptr = &Base::mess;
cout << "base2.*mess_ptr: " << base2.*mess_ptr << endl;
cout << "\nPointer to members can be used with objects of public derived classes\n";
Derived derived1;
cout << "derived1.*mess_ptr: " << derived1.*mess_ptr << endl;
cout << "But pointers to members of derived can not point to members of base\n";
char Derived::* char_ptr3 = &Derived::d;
cout << "derived1.*char_ptr3: " << derived1.*char_ptr3 << endl;
//base1.*char_ptr3 = 'x'; //error: pointer to member type ‘char’ incompatible with object type ‘Base’
cout << "\nRecomended use of aliases:\n";
typedef char Base::* BaseToCharMemberPtr;
using BaseToMessMemberPtr = char const * Base::*; //c11 stype
BaseToCharMemberPtr mptr3 = &Base::b;
BaseToMessMemberPtr mptr4 = &Base::mess;
cout << "base2.*mptr4: " << base2.*mptr4 << " base2.*mptr3: " << base2.*mptr3 << endl;
cout << "\nUse operator '->*' with an object pointer\n";
Base const * b_cptr = & base2;
cout << "b_cptr->*mptr4: " << b_cptr->*mptr4 << " b_cptr->*mptr3: " << b_cptr->*mptr3 << endl;
cout << "\n****** Pointer to class member functions (non-static member) ******\n";
cout << "Function pointer declaration rules and '::*' declares a pointer to a visible member function:\n"
"void (Base::*func_ptr1)(char) = &Base::setA\n";
void (Base::*func_ptr1)(char) = &Base::setA;
cout << "the usage of this pointer requires parentheses:\n";
(base1.*func_ptr1)('x');
cout << "a pointer of this type can point to any member function with a matching signature.\n";
func_ptr1 = &Base::setB;
(base1.*func_ptr1)('y');
base1.print1(12);
cout << "The member must be visible in that context:\n";
//void (Base::*func_ptr2)() = &Base::printVars; //error: ‘void Base::printVars()’ is protected within this context
cout << "\nPointer to members can be used with objects of public derived classes\n";
(derived1.*func_ptr1)('z');
derived1.print1(0);
cout << "const qualifier is part of the function pointer type:\n";
void (Base::*func_ptr_const)(int) const = &Base::print1;
cout << "type func_ptr1: " << typeid(func_ptr1).name() <<
"\ntype func_ptr_const: " << typeid(func_ptr_const).name() << endl;
cout << "Use with a pointer to object (b_cptr->*func_ptr_const)(14)\n";
(b_cptr->*func_ptr_const)(14);
Derived * d_ptr = & derived1;
(d_ptr->*func_ptr_const)(15);
cout << "\nRecomended use of aliases:\n";
typedef void (Base::*BaseSetCharMemberFunctionPointer)(char);
using BasePrintMemberFunctionPointer = void (Base::*)(int) const;
BaseSetCharMemberFunctionPointer fmp1 = &Base::setA;
BasePrintMemberFunctionPointer fmp2 = &Base::print1;
(base1.*fmp1)('@');
(base1.*fmp2)(999);
cout << "\n****** compare pointer to members ******\n";
cout << "\nPointer to members of same type can be compared:\n";
if (mess_ptr == mptr4) {
cout << "Equal pointers point to the same member but may not point to different objects.\n"
"(*fp1)(7)=" << base1.*mess_ptr << endl <<
"(*pa1)(7)=" << derived1.*mptr4 << endl;
}
cout << "\nThe same applies to pointers to member functions:\n";
if (fmp1 != func_ptr1) {
cout << "&Base::setB and &Base::setA are not equal\n";
}
cout << "Distinct pointer types without a cast can not be compared.\n";
//if (mess_ptr == mptr3); //comparison between distinct pointer types ‘const char* Base::*’ and ‘BaseToCharMemberPtr’ {aka ‘char Base::*’} lacks a cast [-fpermissive]
cout << "Can assign 'nullptr' to pointer to member but never use such member! The result is undefined.\n"
"You can compare pointer to member to 'nullptr'.\n";
char_ptr1 = nullptr;
if (char_ptr1 == nullptr) {
cout << "Do not use pointers with null or default constructed pointers!\n";
}
char Base::* char_ptr4{};
if (char_ptr4 == nullptr) {
cout << "Do not use default constructed pointers!\n";
}
cout << "\n****** pointer to member and pointer ******\n"
"Pointer to member can not be assigned to a 'void *'\n";
// void * vptr = func_ptr1; //error: cannot convert ‘void (Base::*)(char)’ to ‘void*’ in initialization
cout << "END" << endl;
return EXIT_SUCCESS;
}
|
ChutuveG3/ChotuveAppServer | app/services/videos.js | <reponame>ChutuveG3/ChotuveAppServer<filename>app/services/videos.js<gh_stars>0
const axios = require('axios');
const {
common: {
urls: { mediaServer },
authorization: { apiKey }
}
} = require('../../config');
const { info, error } = require('../logger');
const Video = require('../models/video');
const { databaseError, mediaServerError, videoNotExists } = require('../errors');
const { getUserFromUsername } = require('./users');
exports.uploadVideo = (username, body) => {
const videoData = { ...body };
delete videoData.title;
delete videoData.description;
delete videoData.visibility;
delete videoData.latitude;
delete videoData.longitude;
info(`Sending video data to Media Server at ${mediaServer} for video with url: ${videoData.download_url}`);
return axios
.post(`${mediaServer}/videos`, videoData, { headers: { x_api_key: apiKey } })
.catch(mserror => {
if (!mserror.response || !mserror.response.data) throw mediaServerError(mserror);
error(`Media Server failed to save video. ${mserror.response.data.message}`);
throw mediaServerError(mserror.response.data);
})
.then(response => {
if (!response.data.id) throw mediaServerError('Media server failed to respond with a new video ID');
return response.data.id;
});
};
exports.createVideo = (username, videoData, videoId) => {
info(`Creating video in db with title: ${videoData.title}`);
const video = new Video({
owner: username,
id: videoId,
title: videoData.title,
description: videoData.description,
visibility: videoData.visibility,
latitude: videoData.latitude,
longitude: videoData.longitude
});
return video.save().catch(dbError => {
error(`Video could not be created. Error: ${dbError}`);
throw databaseError(`Video could not be created. Error: ${dbError}`);
});
};
const buildIdsParam = ids => {
let param = '';
if (ids.length) {
param = `id=${ids[0]}`;
}
ids.slice(1).forEach(id => (param = `${param}&id=${id}`));
return param;
};
exports.getMediaVideosFromIds = ids => {
info('Getting media videos by ids');
return axios
.get(`${mediaServer}/videos?${buildIdsParam(ids)}`, { headers: { x_api_key: apiKey } })
.then(res => res.data)
.catch(mserror => {
if (!mserror.response || !mserror.response.data) throw mediaServerError(mserror);
error(`Media Server failed to return video. ${mserror.response.data.message}`);
throw mediaServerError(mserror.response.data);
});
};
exports.makeFilter = ({ tokenUsername }, { pathUsername }) => {
let filter = { owner: pathUsername };
return getUserFromUsername(tokenUsername).then(user => {
if (tokenUsername !== pathUsername && !user.friends.includes(pathUsername)) {
filter = { ...filter, visibility: 'public' };
}
return filter;
});
};
exports.getVideos = (filters, order, options) => {
info('Getting videos');
return Video.find(filters, null, { skip: options.offset, limit: options.limit })
.sort(order)
.catch(dbError => {
error(`Videos could not be found. Error: ${dbError}`);
throw databaseError(`Videos could not be found. Error: ${dbError}`);
});
};
exports.getVideoFromId = id =>
Video.findOne({ id })
.catch(dbError => {
error(`Videos could not be found. Error: ${dbError}`);
throw databaseError(`Videos could not be found. Error: ${dbError}`);
})
.then(video => {
if (!video) throw videoNotExists(`Video with id ${id} does not exist`);
return video;
});
exports.deleteVideo = id => {
info(`Deleting video with id ${id}`);
return exports.getVideoFromId(id).then(video =>
Video.deleteOne({ id })
.catch(dbError => {
error(`Video could not be deleted. Error: ${dbError}`);
throw databaseError(`Video could not be deleted. Error: ${dbError}`);
})
.then(() => video.owner)
);
};
exports.saveVideoInDb = video =>
video.save().catch(dbError => {
error(`Video could not be saved. Error: ${dbError}`);
throw databaseError(`Video could not be saved. Error: ${dbError}`);
});
exports.addLikeToVideo = ({ username, video }) => video.likes.push(username);
exports.removeLikeFromVideo = ({ username, video }) => video.likes.filter(like => like !== username);
exports.addDislikeToVideo = ({ username, video }) => video.dislikes.push(username);
exports.removeDislikeFromVideo = ({ username, video }) =>
video.dislikes.filter(dislike => dislike !== username);
exports.removeReaction = ({ video, reactionList, username, removingFunction }) => {
if (!video[reactionList].includes(username)) return Promise.resolve();
video[reactionList] = removingFunction({ video, username });
return exports.saveVideoInDb(video);
};
exports.addReaction = ({ video, addingList, removingList, username, addingFunction, removingFunction }) => {
if (video[addingList].includes(username)) {
return Promise.resolve();
}
addingFunction({ video, username });
if (video[removingList].includes(username)) {
video[removingList] = removingFunction({ video, username });
}
return exports.saveVideoInDb(video);
};
exports.postComment = (username, commentData, video) => {
info(`Posting comment from ${username} on video with id ${video.id}`);
const comment = {
username,
datetime: commentData.datetime,
comment: commentData.comment
};
video.comments.push(comment);
return exports.saveVideoInDb(video);
};
exports.filterHomeVideos = (videos, username) =>
Promise.all(
// eslint-disable-next-line no-underscore-dangle
videos.map(video => getUserFromUsername(video.owner).then(user => ({ ...video._doc, owner: user })))
).then(videosWithOwner => {
const filteredVideos = videosWithOwner.filter(
video =>
video.visibility === 'public' ||
video.owner.username === username ||
video.owner.friends.includes(username)
);
return filteredVideos;
});
|
Zucke/social_prove | pkg/user/service/user_service_test.go | <filename>pkg/user/service/user_service_test.go
package service
import (
"context"
"testing"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"go.mongodb.org/mongo-driver/bson/primitive"
fmock "github.com/Zucke/social_prove/pkg/auth/mock"
"github.com/Zucke/social_prove/pkg/logger"
"github.com/Zucke/social_prove/pkg/response"
"github.com/Zucke/social_prove/pkg/user"
mock "github.com/Zucke/social_prove/pkg/user/mock"
)
func TestUserService_Create(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mock.NewMockRepository(ctrl)
userWithPassword := user.User{
Email: "<EMAIL>",
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
}
userWithoutPassword := user.User{
Email: "<EMAIL>",
UID: "123456",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
}
userWithIncorrectEmail := user.User{
Email: "userexample.com",
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Client,
}
ctx := context.Background()
l := logger.NewMock()
tests := []struct {
name string
user user.User
err error
active bool
hasPassword bool
times int
}{
{
name: "With password success",
user: userWithPassword,
err: nil,
active: true,
hasPassword: true,
times: 1,
},
{
name: "With password failure",
user: userWithPassword,
hasPassword: true,
active: true,
err: response.ErrCouldNotInsert,
times: 1,
},
{
name: "Without password success",
user: userWithoutPassword,
active: true,
err: nil,
times: 1,
},
{
name: "Without password failure",
user: userWithoutPassword,
active: true,
err: response.ErrCouldNotInsert,
times: 1,
},
{
name: "With invalid email",
user: userWithIncorrectEmail,
err: response.ErrInvalidEmail,
times: 0,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
m.
EXPECT().
Create(gomock.Any(), gomock.Eq(&test.user)).
Return(test.err).
Times(test.times)
s := UserService{
repository: m,
log: l,
}
err := s.Create(ctx, &test.user)
assert.Equal(t, err, test.err)
assert.Equal(t, test.active, test.user.Active)
if test.hasPassword {
assert.NotNil(t, test.user.HashPassword)
} else {
assert.Nil(t, test.user.HashPassword)
}
})
}
}
func TestUserService_GetByEmail(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mock.NewMockRepository(ctrl)
us := user.User{
Email: "<EMAIL>",
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
}
ctx := context.Background()
l := logger.NewMock()
tests := []struct {
name string
user user.User
err error
}{
{
name: "Success",
user: us,
err: nil,
},
{
name: "Failure",
user: user.User{},
err: response.ErrorNotFound,
},
}
email := "<EMAIL>"
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
m.
EXPECT().
GetByEmail(gomock.Any(), email).
Return(test.user, test.err).
Times(1)
s := UserService{
repository: m,
log: l,
}
u, err := s.GetByEmail(ctx, email)
assert.Equal(t, err, test.err)
assert.Equal(t, u, test.user)
})
}
}
func TestUserService_LoginUser(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mock.NewMockRepository(ctrl)
validUser := user.User{
Email: "<EMAIL>",
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
}
validUser.EncryptPassword()
userWithBadEmail := user.User{
Email: "user<EMAIL>",
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
}
userWithBadEmail.EncryptPassword()
userBadPassword := user.User{
Email: "<EMAIL>",
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
}
userBadPassword.EncryptPassword()
ctx := context.Background()
l := logger.NewMock()
tests := []struct {
name string
user user.User
resultUser user.User
err error
times int
}{
{
name: "Success",
user: validUser,
resultUser: validUser,
err: nil,
times: 1,
},
{
name: "Invalid mail",
user: userWithBadEmail,
resultUser: user.User{},
err: response.ErrorBadEmailOrPassword,
times: 0,
},
{
name: "Bad password",
user: userBadPassword,
resultUser: user.User{},
err: response.ErrorBadEmailOrPassword,
times: 1,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
m.
EXPECT().
GetByEmail(gomock.Any(), test.user.Email).
Return(validUser, nil).
Times(test.times)
s := UserService{
repository: m,
log: l,
}
u, tokenString, err := s.LoginUser(ctx, &test.user)
assert.Equal(t, err, test.err)
assert.Equal(t, u, &test.resultUser)
if err == nil {
assert.NotEmpty(t, tokenString)
}
})
}
}
func TestUserService_GetByID(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mock.NewMockRepository(ctrl)
id := primitive.NewObjectID()
us := user.User{
Email: "<EMAIL>",
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
}
ctx := context.Background()
l := logger.NewMock()
tests := []struct {
name string
id string
user user.User
err error
times int
}{
{
name: "Success",
id: id.Hex(),
user: us,
err: nil,
times: 1,
},
{
name: "Failure",
id: id.Hex(),
user: user.User{},
err: response.ErrorNotFound,
times: 1,
},
{
name: "With invalid id",
id: "123",
user: user.User{},
err: response.ErrInvalidID,
times: 0,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
m.
EXPECT().
GetByID(gomock.Any(), id).
Return(test.user, test.err).
Times(test.times)
s := UserService{
repository: m,
log: l,
}
u, err := s.GetByID(ctx, test.id)
assert.Equal(t, err, test.err)
assert.Equal(t, u, test.user)
})
}
}
func TestUserService_GetAll(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mock.NewMockRepository(ctrl)
su := []user.User{
{
Email: "<EMAIL>",
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
},
}
ctx := context.Background()
l := logger.NewMock()
tests := []struct {
name string
users []user.User
err error
}{
{
name: "Success",
users: su,
err: nil,
},
{
name: "Failure",
users: nil,
err: response.ErrorNotFound,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
m.
EXPECT().
GetAll(gomock.Any()).
Return(test.users, test.err).
Times(1)
s := UserService{
repository: m,
log: l,
}
users, err := s.GetAll(ctx)
assert.Equal(t, err, test.err)
assert.Equal(t, len(users), len(test.users))
})
}
}
func TestUserService_GetAllActive(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mock.NewMockRepository(ctrl)
su := []user.User{
{
Email: "<EMAIL>",
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
},
}
ctx := context.Background()
l := logger.NewMock()
tests := []struct {
name string
users []user.User
err error
}{
{
name: "Success",
users: su,
err: nil,
},
{
name: "Failure",
users: nil,
err: response.ErrorNotFound,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
m.
EXPECT().
GetAllActive(gomock.Any()).
Return(test.users, test.err).
Times(1)
s := UserService{
repository: m,
log: l,
}
users, err := s.GetAllActive(ctx)
assert.Equal(t, err, test.err)
assert.Equal(t, len(users), len(test.users))
})
}
}
func TestUserService_GetByUID(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
uid := "123456"
m := mock.NewMockRepository(ctrl)
us := user.User{
Email: "<EMAIL>",
UID: uid,
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
}
ctx := context.Background()
l := logger.NewMock()
tests := []struct {
name string
uid string
user user.User
err error
}{
{
name: "Success",
uid: uid,
user: us,
err: nil,
},
{
name: "Failure",
uid: uid,
user: user.User{},
err: response.ErrorNotFound,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
m.
EXPECT().
GetByUID(gomock.Any(), test.uid).
Return(test.user, test.err).
Times(1)
s := UserService{
repository: m,
log: l,
}
u, err := s.GetByUID(ctx, test.uid)
assert.Equal(t, err, test.err)
assert.Equal(t, u, test.user)
})
}
}
func TestUserService_FollowTo(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
id := primitive.NewObjectID()
id2 := primitive.NewObjectID()
m := mock.NewMockRepository(ctrl)
userFollowing := user.User{
ID: id,
Email: "<EMAIL>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
Following: []primitive.ObjectID{id2},
}
ctx := context.Background()
l := logger.NewMock()
tests := []struct {
name string
user user.User
err error
id string
idtimes int
followTimes int
}{
{
name: "succes following",
user: userFollowing,
err: nil,
id: id.Hex(),
idtimes: 1,
followTimes: 1,
},
{
name: "failure, user is same has following",
user: user.User{},
err: response.ErrCantFollowYou,
id: id.Hex(),
followTimes: 1,
idtimes: 0,
},
{
name: "failure, bad id",
user: user.User{},
err: response.ErrInvalidID,
id: "",
followTimes: 0,
idtimes: 0,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
m.
EXPECT().
FollowTo(gomock.Any(), id2, id).
Return(test.err).
Times(test.followTimes)
m.
EXPECT().
GetByID(gomock.Any(), id).
Return(test.user, nil).
Times(test.idtimes)
s := UserService{
repository: m,
log: l,
}
u, err := s.FollowTo(ctx, id2.Hex(), test.id)
assert.Equal(t, err, test.err)
assert.Equal(t, u, test.user)
})
}
}
func TestUserService_UnfollowTo(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
id := primitive.NewObjectID()
id2 := primitive.NewObjectID()
m := mock.NewMockRepository(ctrl)
userFollowing := user.User{
ID: id,
Email: "<EMAIL>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
Following: []primitive.ObjectID{id2},
}
ctx := context.Background()
l := logger.NewMock()
tests := []struct {
name string
user user.User
err error
id string
idtimes int
followTimes int
}{
{
name: "succes Unfollowing",
user: userFollowing,
err: nil,
id: id.Hex(),
idtimes: 1,
followTimes: 1,
},
{
name: "failure, user is same has following",
user: user.User{},
err: response.ErrCantFollowYou,
id: id.Hex(),
followTimes: 1,
idtimes: 0,
},
{
name: "failure, bad id",
user: user.User{},
err: response.ErrInvalidID,
id: "",
followTimes: 0,
idtimes: 0,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
m.
EXPECT().
FollowTo(gomock.Any(), id2, id).
Return(test.err).
Times(test.followTimes)
m.
EXPECT().
GetByID(gomock.Any(), id).
Return(test.user, nil).
Times(test.idtimes)
s := UserService{
repository: m,
log: l,
}
u, err := s.FollowTo(ctx, id2.Hex(), test.id)
assert.Equal(t, err, test.err)
assert.Equal(t, u, test.user)
})
}
}
func TestUserService_Delete(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mock.NewMockRepository(ctrl)
id := primitive.NewObjectID()
us := user.User{
Email: "<EMAIL>",
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
}
ctx := context.Background()
l := logger.NewMock()
tests := []struct {
name string
id string
user user.User
err error
times int
}{
{
name: "Success",
id: id.Hex(),
user: us,
err: nil,
times: 1,
},
{
name: "Failure",
id: id.Hex(),
user: user.User{},
err: response.ErrorNotFound,
times: 1,
},
{
name: "With invalid id",
id: "123",
user: user.User{},
err: response.ErrInvalidID,
times: 0,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
m.
EXPECT().
Delete(gomock.Any(), test.user.Role, id).
Return(test.err).
Times(test.times)
s := UserService{
repository: m,
log: l,
}
err := s.Delete(ctx, test.user.Role, test.id)
assert.Equal(t, err, test.err)
})
}
}
func TestUserService_Update(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mock.NewMockRepository(ctrl)
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
cliendUser := user.User{
ID: id1,
Email: "<EMAIL>",
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
}
adminUser := user.User{
ID: id1,
Email: "<EMAIL>",
Password: "<PASSWORD>",
FirstName: "user",
LastName: "test",
Role: user.Admin,
Active: true,
}
ctx := context.Background()
l := logger.NewMock()
tests := []struct {
name string
id string
user user.User
rUser user.User
err error
times int
IDtimes int
}{
{
name: "Success cliend",
id: id1.Hex(),
user: cliendUser,
rUser: cliendUser,
err: nil,
times: 1,
IDtimes: 1,
},
{
name: "Success admin",
id: id1.Hex(),
user: adminUser,
rUser: adminUser,
err: nil,
times: 1,
IDtimes: 1,
},
{
name: "Failure cliend id unauthorized",
id: id2.Hex(),
user: cliendUser,
rUser: user.User{},
err: response.ErrorUnauthorized,
times: 0,
IDtimes: 0,
},
{
name: "Cliend with invalid id",
id: "123",
user: cliendUser,
rUser: user.User{},
err: response.ErrorUnauthorized,
times: 0,
IDtimes: 0,
},
{
name: "Admin with invalid id",
id: "123",
user: adminUser,
rUser: user.User{},
err: response.ErrInvalidID,
times: 0,
IDtimes: 0,
},
{
name: "Failed to update",
id: id1.Hex(),
user: adminUser,
rUser: user.User{},
err: response.ErrorInternalServerError,
times: 1,
IDtimes: 0,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
m.
EXPECT().
Update(gomock.Any(), test.user.Role, gomock.Any(), &test.user).
Return(test.err).
Times(test.times)
m.
EXPECT().
GetByID(gomock.Any(), gomock.Any()).
Return(test.user, nil).
Times(test.IDtimes)
s := UserService{
repository: m,
log: l,
}
u, err := s.Update(ctx, test.id, test.user.ID.Hex(), test.user.Role, &test.user)
assert.Equal(t, err, test.err)
assert.Equal(t, u, test.rUser)
})
}
}
func TestUserService_FirebaseAuth(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mock.NewMockRepository(ctrl)
fm := fmock.NewMockRepository(ctrl)
uid := "2134gh"
us := user.User{
Email: "<EMAIL>",
FirstName: "user",
LastName: "test",
Role: user.Client,
Active: true,
}
ctx := context.Background()
l := logger.NewMock()
tests := []struct {
name string
user user.User
err error
fErr error
times int
fTimes int
}{
{
name: "Success",
user: us,
err: nil,
times: 1,
fTimes: 0,
},
{
name: "Succes found in fb",
user: us,
err: response.ErrorNotFound,
fErr: nil,
times: 1,
fTimes: 1,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
m.
EXPECT().
GetByUID(gomock.Any(), uid).
Return(test.user, test.err).
Times(test.times)
m.
EXPECT().
Create(gomock.Any(), gomock.Any()).
Return(nil).
Times(test.fTimes)
fm.
EXPECT().
GetFirebaseUser(gomock.Any(), uid).
Return(test.user, test.fErr).
Times(test.fTimes)
s := UserService{
repository: m,
log: l,
firebaseRepo: fm,
}
u, tokenString, err := s.FirebaseAuth(ctx, uid)
if err != nil {
assert.Equal(t, err, test.err)
} else {
assert.Equal(t, err, test.fErr)
}
assert.NotEmpty(t, tokenString)
test.user.CreatedAt = u.CreatedAt
test.user.ID = u.ID
test.user.UpdatedAt = u.UpdatedAt
test.user.Active = u.Active
assert.Equal(t, u, &test.user)
})
}
}
|
Widen/metadata-extractor | Source/com/drew/metadata/mp4/media/Mp4VideoDescriptor.java | <reponame>Widen/metadata-extractor<filename>Source/com/drew/metadata/mp4/media/Mp4VideoDescriptor.java<gh_stars>0
package com.drew.metadata.mp4.media;
import com.drew.lang.annotations.NotNull;
import com.drew.metadata.TagDescriptor;
import static com.drew.metadata.mp4.media.Mp4VideoDirectory.*;
public class Mp4VideoDescriptor extends TagDescriptor<Mp4VideoDirectory>
{
public Mp4VideoDescriptor(@NotNull Mp4VideoDirectory directory)
{
super(directory);
}
@Override
public String getDescription(int tagType)
{
switch (tagType) {
case TAG_HEIGHT:
case TAG_WIDTH:
return getPixelDescription(tagType);
case TAG_DEPTH:
return getDepthDescription();
case TAG_COLOR_TABLE:
return getColorTableDescription();
case TAG_GRAPHICS_MODE:
return getGraphicsModeDescription();
default:
return super.getDescription(tagType);
}
}
private String getPixelDescription(int tagType)
{
return _directory.getString(tagType) + " pixels";
}
private String getDepthDescription()
{
int depth = _directory.getInteger(TAG_DEPTH);
switch (depth) {
case (40):
case (36):
case (34):
return (depth - 32) + "-bit grayscale";
default:
return Integer.toString(depth);
}
}
private String getColorTableDescription()
{
int colorTableId = _directory.getInteger(TAG_COLOR_TABLE);
switch (colorTableId) {
case (-1):
if (_directory.getInteger(TAG_DEPTH) < 16) {
return "Default";
} else {
return "None";
}
case (0):
return "Color table within file";
default:
return Integer.toString(colorTableId);
}
}
private String getGraphicsModeDescription()
{
Integer graphicsMode = _directory.getInteger(TAG_GRAPHICS_MODE);
if (graphicsMode == null)
return null;
switch (graphicsMode) {
case (0x00):
return "Copy";
case (0x40):
return "Dither copy";
case (0x20):
return "Blend";
case (0x24):
return "Transparent";
case (0x100):
return "Straight alpha";
case (0x101):
return "Premul white alpha";
case (0x102):
return "Premul black alpha";
case (0x104):
return "Straight alpha blend";
case (0x103):
return "Composition (dither copy)";
default:
return "Unknown (" + graphicsMode + ")";
}
}
}
|
imlzw/jweb-boot | src/main/java/cc/jweb/boot/config/JFinalConfig.java | /*
* Copyright (c) 2020-2021 <EMAIL> jweb.cc.
*
* 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 cc.jweb.boot.config;//package com.ndasec.jfinal.config;
//
//import cn.hutool.setting.Setting;
//import com.alibaba.fastjson.JSON;
//import com.jfinal.config.*;
//import com.jfinal.core.JFinal;
//import com.jfinal.ext.interceptor.SessionInViewInterceptor;
//import com.jfinal.handler.Handler;
//import com.jfinal.render.RenderManager;
//import com.jfinal.template.Engine;
//import com.ndasec.jfinal.elasticsearch.ESPlugin;
//import com.ndasec.jfinal.handler.LayuiAdminRouteHandler;
//import com.ndasec.jfinal.interceptor.ExceptionInterceptor;
//import com.ndasec.jfinal.interceptor.LoginInterceptor;
//import com.ndasec.jfinal.plugin.shiro.ShiroInterceptor;
//import com.ndasec.jfinal.plugin.shiro.ShiroKit;
//import com.ndasec.jfinal.plugin.shiro.ShiroPlugin;
//import com.ndasec.jweb.web.support.file.OfficeTemplatePlugin;
//import org.apache.shiro.SecurityUtils;
//import org.apache.shiro.web.filter.mgt.DefaultFilter;
//import org.eclipse.jetty.http.HttpStatus;
//import org.eclipse.jetty.server.Server;
//import org.eclipse.jetty.webapp.WebAppContext;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.util.Properties;
//
//import static com.alibaba.druid.pool.DruidDataSourceFactory.PROP_CONNECTIONPROPERTIES;
//import static com.alibaba.druid.pool.DruidDataSourceFactory.PROP_URL;
//
//public class JFinalConfig extends DefaultConfig {
// /**
// * 供Shiro插件使用。
// */
// Routes routes;
//
// @Override
// public void configRoute(Routes me) {
// super.configRoute(me);
// this.routes = me;
// }
//
// @Override
// public void configEngine(Engine me) {
// super.configEngine(me);
// }
//
// @Override
// public void configHandler(Handlers me) {
// super.configHandler(me);
// me.add(new LayuiAdminRouteHandler());
// }
//
// @Override
// public void configConstant(Constants me) {
// super.configConstant(me);
//// me.setErrorView(401, "/au/login.html");
//// me.setErrorView(403, "/au/login.html");
//// me.setError404View("/404.html");
//// me.setError500View("/500.html");
// }
//
// @Override
// public void configInterceptor(Interceptors me) {
//
// me.add(new ShiroInterceptor());
//// me.add(new LoginInterceptor());
// me.add(new ExceptionInterceptor());
// me.add(new SessionInViewInterceptor());
// }
//
//
// @Override
// public void configPlugin(Plugins me) {
// super.configPlugin(me);
// me.add(new ESPlugin(new Setting("config/elasticsearch.txt")));
// me.add(new OfficeTemplatePlugin(new Setting("config/elasticsearch.txt")));
//
// //加载Shiro插件
// //me.add(new ShiroPlugin(routes));
// ShiroPlugin shiroPlugin = new ShiroPlugin(this.routes);
// shiroPlugin.setLoginUrl("/");
// shiroPlugin.setSuccessUrl("/");
// shiroPlugin.setUnauthorizedUrl("/");
// me.add(shiroPlugin);
//
// /* 新增ESSql插件支持 */
// Setting es_sql = new Setting("config/elasticsearch-sql.txt");
// Properties properties = new Properties();
// properties.put(PROP_URL, es_sql.getStr("jdbc.url"));
// properties.put(PROP_CONNECTIONPROPERTIES, "client.transport.ignore_cluster_name=true");
// }
//
// @Override
// public void afterJFinalStart() {
// super.afterJFinalStart();
// RenderManager.me().getEngine().addSharedObject("servletContext", JFinal.me().getServletContext());
//
// System.out.println(JSON.toJSONString(JFinalConfig.config.getGroups()));
// }
//
//
// public static void main(String[] args) {
// try {
// startWithJetty(8080, "C:\\DATA\\SituationAware\\jweb-test\\target\\jweb-test-1.0", null);
// } catch (Exception exception) {
// exception.printStackTrace();
// }
// }
//
//
// public static void startWithJetty(int port, String webroot, String extClassPath) throws Exception {
// Server server = new Server(port);
// WebAppContext context = new WebAppContext();
// context.setContextPath("/");
// context.setResourceBase(webroot);// 指定webapp目录
// context.setExtraClasspath(extClassPath);
// server.setHandler(context);
// server.start();
// server.join();
// }
//
// public static class ExampleServlet extends HttpServlet {
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp)
// throws ServletException, IOException {
//
// resp.setStatus(HttpStatus.OK_200);
// resp.getWriter().println("EmbeddedJetty");
// }
// }
//}
|
WeCare-Online-Clinic/back-end-mysql | src/main/java/wecare/backend/model/Clinic.java | package wecare.backend.model;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "clinic")
public class Clinic {
@Id
@SequenceGenerator(
name = "clinic_id_seq",
sequenceName = "clinic_id_seq",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "clinic_id_seq"
)
@Column(name="id")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@OneToMany(targetEntity = ClinicSchedule.class, cascade = CascadeType.ALL, mappedBy = "clinic")
private List<ClinicSchedule> clinicSchedules;
public Clinic() {
}
public List<ClinicSchedule> getClinicSchedules(){
if(clinicSchedules == null){
clinicSchedules = new ArrayList<>();
}
return clinicSchedules;
}
public Integer getId(){
return id;
}
public String getName(){
return name;
}
public String getDescription(){
return description;
}
}
|
christopherhein/manager | apis/certificatemanager/v1alpha1/certificate_types.go | /*
Copyright © 2019 AWS Controller authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
metav1alpha1 "go.awsctrl.io/manager/apis/meta/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// CertificateSpec defines the desired state of Certificate
type CertificateSpec struct {
metav1alpha1.CloudFormationMeta `json:",inline"`
// DomainName http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-certificatemanager-certificate.html#cfn-certificatemanager-certificate-domainname
DomainName string `json:"domainName,omitempty" cloudformation:"DomainName,Parameter"`
// DomainValidationOptions http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-certificatemanager-certificate.html#cfn-certificatemanager-certificate-domainvalidationoptions
DomainValidationOptions []Certificate_DomainValidationOption `json:"domainValidationOptions,omitempty" cloudformation:"DomainValidationOptions"`
// SubjectAlternativeNames http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-certificatemanager-certificate.html#cfn-certificatemanager-certificate-subjectalternativenames
SubjectAlternativeNames []string `json:"subjectAlternativeNames,omitempty" cloudformation:"SubjectAlternativeNames"`
// ValidationMethod http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-certificatemanager-certificate.html#cfn-certificatemanager-certificate-validationmethod
ValidationMethod string `json:"validationMethod,omitempty" cloudformation:"ValidationMethod,Parameter"`
}
// Certificate_DomainValidationOption defines the desired state of CertificateDomainValidationOption
type Certificate_DomainValidationOption struct {
// DomainName http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-certificatemanager-certificate-domainvalidationoption.html#cfn-certificatemanager-certificate-domainvalidationoptions-domainname
DomainName string `json:"domainName,omitempty" cloudformation:"DomainName,Parameter"`
// ValidationDomain http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-certificatemanager-certificate-domainvalidationoption.html#cfn-certificatemanager-certificate-domainvalidationoption-validationdomain
ValidationDomain string `json:"validationDomain,omitempty" cloudformation:"ValidationDomain,Parameter"`
}
// CertificateStatus defines the observed state of Certificate
type CertificateStatus struct {
metav1alpha1.StatusMeta `json:",inline"`
}
// CertificateOutput defines the stack outputs
type CertificateOutput struct {
// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-certificatemanager-certificate.html
Ref string `json:"ref,omitempty"`
}
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:categories=aws;certificatemanager
// +kubebuilder:printcolumn:JSONPath=.status.status,description="status of the stack",name=Status,priority=0,type=string
// +kubebuilder:printcolumn:JSONPath=.status.message,description="reason for the stack status",name=Message,priority=1,type=string
// +kubebuilder:printcolumn:JSONPath=.status.stackID,description="CloudFormation Stack ID",name=StackID,priority=2,type=string
// Certificate is the Schema for the certificatemanager Certificate API
type Certificate struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec CertificateSpec `json:"spec,omitempty"`
Status CertificateStatus `json:"status,omitempty"`
}
// +kubebuilder:object:root=true
// CertificateList contains a list of Account
type CertificateList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Certificate `json:"items"`
}
func init() {
SchemeBuilder.Register(&Certificate{}, &CertificateList{})
}
|
npocmaka/Windows-Server-2003 | drivers/storage/tape/drivers/qic157/qic157.h |
/*++
Copyright (C) Microsoft Corporation, 1992 - 1998
Module Name:
qic157.h
Abstract:
This file contains structures and defines that are used
specifically for the tape drivers.
Revision History:
--*/
#ifndef _QIC157_H
#define _QIC157_H
//
// Internal (module wide) defines that symbolize
// non-QFA mode and the two QFA mode partitions.
//
#define DATA_PARTITION 0 // non-QFA mode, or QFA mode, data partition #
#define DIRECTORY_PARTITION 1 // QFA mode, directory partition #
#define QIC157_SUPPORTED_TYPES 3
//
// Drive id values
//
#define ECRIX_VXA_1 0x01
//
// Error counter upper limits
//
#define TAPE_READ_ERROR_LIMIT 0x8000
#define TAPE_WRITE_ERROR_LIMIT 0x8000
#define TAPE_READ_WARNING_LIMIT 0x4000
#define TAPE_WRITE_WARNING_LIMIT 0x4000
//
// Logpage Paramcodes
//
#define QIC_TAPE_REMAINING_CAPACITY 0x01
#define QIC_TAPE_MAXIMUM_CAPACITY 0x03
//
// Defines for Log Sense Pages
//
#define LOGSENSEPAGE0 0x00
#define LOGSENSEPAGE3 0x03
#define QIC_LOGSENSE_TAPE_CAPACITY 0x31
//
// Defines for parameter codes
//
#define ECCCorrectionsCode 0x0000
#define ReadRetriesCode 0x0001
#define EventTrackECCCorrectionsCode 0x8020
#define OddTrackECCCorrectionsCode 0x8021
#define EventTrackRetriesCode 0x8022
#define OddTrackRetriesCode 0x8023
//
// Minitape extension definition.
//
typedef struct _MINITAPE_EXTENSION {
ULONG CurrentPartition;
ULONG DriveID;
MODE_CAPABILITIES_PAGE CapabilitiesPage;
} MINITAPE_EXTENSION, *PMINITAPE_EXTENSION;
//
// Defined Log Sense Page Header
//
typedef struct _LOG_SENSE_PAGE_HEADER {
UCHAR PageCode : 6;
UCHAR Reserved1 : 2;
UCHAR Reserved2;
UCHAR Length[2]; // [0]=MSB ... [1]=LSB
} LOG_SENSE_PAGE_HEADER, *PLOG_SENSE_PAGE_HEADER;
//
// Defined Log Sense Parameter Header
//
typedef struct _LOG_SENSE_PARAMETER_HEADER {
UCHAR ParameterCode[2]; // [0]=MSB ... [1]=LSB
UCHAR LPBit : 1;
UCHAR Reserved1 : 1;
UCHAR TMCBit : 2;
UCHAR ETCBit : 1;
UCHAR TSDBit : 1;
UCHAR DSBit : 1;
UCHAR DUBit : 1;
UCHAR ParameterLength;
} LOG_SENSE_PARAMETER_HEADER, *PLOG_SENSE_PARAMETER_HEADER;
//
// Defined Log Page Information - statistical values, accounts
// for maximum parameter values that is returned for each page
//
typedef struct _LOG_SENSE_PAGE_INFORMATION {
union {
struct {
UCHAR Page0;
UCHAR Page3;
} PageData ;
struct {
LOG_SENSE_PARAMETER_HEADER Parm1;
UCHAR ECCCorrections[4];
LOG_SENSE_PARAMETER_HEADER Parm2;
UCHAR ReadRetries[4];
LOG_SENSE_PARAMETER_HEADER Parm3;
UCHAR EvenTrackECCCorrections[4];
LOG_SENSE_PARAMETER_HEADER Parm4;
UCHAR OddTrackECCCorrections[4];
LOG_SENSE_PARAMETER_HEADER Parm5;
UCHAR EvenTrackReadRetries[4];
LOG_SENSE_PARAMETER_HEADER Parm6;
UCHAR OddTrackReadRetries[4];
} Page3 ;
struct {
LOG_SENSE_PARAMETER_HEADER Param1;
UCHAR RemainingCapacity[4];
LOG_SENSE_PARAMETER_HEADER Param2;
UCHAR Param2Reserved[4];
LOG_SENSE_PARAMETER_HEADER Param3;
UCHAR MaximumCapacity[4];
LOG_SENSE_PARAMETER_HEADER Param4;
UCHAR Param4Reserved[4];
} LogSenseTapeCapacity;
} LogSensePage;
} LOG_SENSE_PAGE_INFORMATION, *PLOG_SENSE_PAGE_INFORMATION;
//
// Log Sense Page format
//
typedef struct _LOG_SENSE_PAGE_FORMAT {
LOG_SENSE_PAGE_HEADER LogSenseHeader;
LOG_SENSE_PAGE_INFORMATION LogSensePageInfo;
} LOG_SENSE_PAGE_FORMAT, *PLOG_SENSE_PAGE_FORMAT;
//
// Defined Log Sense Parameter Format - statistical values, accounts
// for maximum parameter values that is returned
//
typedef struct _LOG_SENSE_PARAMETER_FORMAT {
LOG_SENSE_PAGE_HEADER LogSenseHeader;
LOG_SENSE_PAGE_INFORMATION LogSensePageInfo;
} LOG_SENSE_PARAMETER_FORMAT, *PLOG_SENSE_PARAMETER_FORMAT;
BOOLEAN
VerifyInquiry(
IN PINQUIRYDATA InquiryData,
IN PMODE_CAPABILITIES_PAGE ModeCapabilitiesPage
);
VOID
ExtensionInit(
OUT PVOID MinitapeExtension,
IN PINQUIRYDATA InquiryData,
IN PMODE_CAPABILITIES_PAGE ModeCapabilitiesPage
);
TAPE_STATUS
CreatePartition(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
TAPE_STATUS
Erase(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
TAPE_STATUS
GetDriveParameters(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
TAPE_STATUS
GetMediaParameters(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
TAPE_STATUS
GetPosition(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
TAPE_STATUS
GetStatus(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
TAPE_STATUS
Prepare(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
TAPE_STATUS
SetDriveParameters(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
TAPE_STATUS
SetMediaParameters(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
TAPE_STATUS
SetPosition(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
TAPE_STATUS
WriteMarks(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
TAPE_STATUS
GetMediaTypes(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
TAPE_STATUS
TapeWMIControl(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
ULONG
WhichIsIt(
IN PINQUIRYDATA InquiryData
);
TAPE_STATUS
PrepareSrbForTapeCapacityInfo(
IN OUT PSCSI_REQUEST_BLOCK Srb
);
BOOLEAN
ProcessTapeCapacityInfo(
IN PSCSI_REQUEST_BLOCK Srb,
OUT PULONG RemainingCapacity,
OUT PULONG MaximumCapacity
);
//
// Internal routines for wmi
//
TAPE_STATUS
QueryIoErrorData(
IN OUT PVOID MinitapeExtension,
IN OUT PVOID CommandExtension,
IN OUT PVOID CommandParameters,
IN OUT PSCSI_REQUEST_BLOCK Srb,
IN ULONG CallNumber,
IN TAPE_STATUS LastError,
IN OUT PULONG RetryFlags
);
VOID
ProcessReadWriteErrors(
IN PSCSI_REQUEST_BLOCK Srb,
IN BOOLEAN Read,
IN OUT PWMI_TAPE_PROBLEM_IO_ERROR IoErrorData
);
TAPE_DRIVE_PROBLEM_TYPE
VerifyReadWriteErrors(
IN PWMI_TAPE_PROBLEM_IO_ERROR IoErrorData
);
#endif // _QIC157_H
|
roycrippen/sicxe | src/assembler/code.cc | <reponame>roycrippen/sicxe
#include "assembler/code.h"
#include "assembler/block_table.h"
#include "assembler/literal_table.h"
#include "assembler/symbol_table.h"
using std::string;
namespace sicxe {
namespace assembler {
Code::Code() : text_file_(nullptr), start_address_(0), end_address_(0), entry_point_(0) {}
Code::~Code() {}
const TextFile* Code::text_file() const {
return text_file_;
}
void Code::set_text_file(const TextFile* file) {
text_file_ = file;
}
const Code::NodeList& Code::nodes() const {
return nodes_;
}
Code::NodeList* Code::mutable_nodes() {
return &nodes_;
}
const SymbolTable* Code::symbol_table() const {
return symbol_table_.get();
}
void Code::set_symbol_table(SymbolTable* table) {
symbol_table_.reset(table);
}
const BlockTable* Code::block_table() const {
return block_table_.get();
}
void Code::set_block_table(BlockTable* table) {
block_table_.reset(table);
}
const LiteralTable* Code::literal_table() const {
return literal_table_.get();
}
void Code::set_literal_table(LiteralTable* table) {
literal_table_.reset(table);
}
const string& Code::program_name() const {
return program_name_;
}
void Code::set_program_name(const std::string& name) {
program_name_ = name;
}
uint32 Code::start_address() const {
return start_address_;
}
void Code::set_start_address(uint32 the_start_address) {
start_address_ = the_start_address;
}
uint32 Code::end_address() const {
return end_address_;
}
void Code::set_end_address(uint32 the_end_address) {
end_address_ = the_end_address;
}
uint32 Code::entry_point() const {
return entry_point_;
}
void Code::set_entry_point(uint32 the_entry_point) {
entry_point_ = the_entry_point;
}
} // namespace assembler
} // namespace sicxe
|
dmgerman/camel | components/camel-milo/src/test/java/org/apache/camel/component/milo/testing/ExampleServer.java | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.camel.component.milo.testing
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|milo
operator|.
name|testing
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|CamelContext
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|RouteBuilder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|milo
operator|.
name|server
operator|.
name|MiloServerComponent
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|impl
operator|.
name|DefaultCamelContext
import|;
end_import
begin_comment
comment|/** * This is a simple example application which tests a few ways of mapping data * to an OPC UA server instance. */
end_comment
begin_class
DECL|class|ExampleServer
specifier|public
specifier|final
class|class
name|ExampleServer
block|{
DECL|method|ExampleServer ()
specifier|private
name|ExampleServer
parameter_list|()
block|{ }
DECL|method|main (final String[] args)
specifier|public
specifier|static
name|void
name|main
parameter_list|(
specifier|final
name|String
index|[]
name|args
parameter_list|)
throws|throws
name|Exception
block|{
comment|// camel conext
specifier|final
name|CamelContext
name|context
init|=
operator|new
name|DefaultCamelContext
argument_list|()
decl_stmt|;
comment|// configure milo
operator|(
operator|(
name|MiloServerComponent
operator|)
name|context
operator|.
name|getComponent
argument_list|(
literal|"milo-server"
argument_list|)
operator|)
operator|.
name|setUserAuthenticationCredentials
argument_list|(
literal|"foo:bar"
argument_list|)
expr_stmt|;
comment|// add routes
name|context
operator|.
name|addRoutes
argument_list|(
operator|new
name|RouteBuilder
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|void
name|configure
parameter_list|()
throws|throws
name|Exception
block|{
comment|/* * Take an MQTT topic and forward its content to an OPC UA * server item. You can e.g. take some MQTT application and an * OPC UA client, connect with both applications to their * topics/items. When you write on the MQTT item it will pop up * on the OPC UA item. */
name|from
argument_list|(
literal|"paho:my/foo/bar?brokerUrl=tcp://iot.eclipse.org:1883"
argument_list|)
operator|.
name|log
argument_list|(
literal|"Temp update: ${body}"
argument_list|)
operator|.
name|convertBodyTo
argument_list|(
name|String
operator|.
name|class
argument_list|)
operator|.
name|to
argument_list|(
literal|"milo-server:MyItem"
argument_list|)
expr_stmt|;
comment|/* * Creating a simple item which has not data but logs anything * which gets written to by an OPC UA write call */
name|from
argument_list|(
literal|"milo-server:MyItem"
argument_list|)
operator|.
name|log
argument_list|(
literal|"MyItem: ${body}"
argument_list|)
expr_stmt|;
comment|/* * Creating an item which takes write command and forwards them * to an MQTT topic */
name|from
argument_list|(
literal|"milo-server:MyItem2"
argument_list|)
operator|.
name|log
argument_list|(
literal|"MyItem2: ${body}"
argument_list|)
operator|.
name|convertBodyTo
argument_list|(
name|String
operator|.
name|class
argument_list|)
operator|.
name|to
argument_list|(
literal|"paho:de/dentrassi/camel/milo/temperature?brokerUrl=tcp://iot.eclipse.org:1883"
argument_list|)
expr_stmt|;
comment|/* * Re-read the output from the previous route from MQTT to the * local logging */
name|from
argument_list|(
literal|"paho:de/dentrassi/camel/milo/temperature?brokerUrl=tcp://iot.eclipse.org:1883"
argument_list|)
operator|.
name|log
argument_list|(
literal|"Back from MQTT: ${body}"
argument_list|)
expr_stmt|;
block|}
block|}
argument_list|)
expr_stmt|;
comment|// start
name|context
operator|.
name|start
argument_list|()
expr_stmt|;
comment|// sleep
while|while
condition|(
literal|true
condition|)
block|{
name|Thread
operator|.
name|sleep
argument_list|(
name|Long
operator|.
name|MAX_VALUE
argument_list|)
expr_stmt|;
block|}
block|}
block|}
end_class
end_unit
|
kristianmandrup/ai-component | lib/creator/templator.js | const { utils, Registry, Preferences} = require('ai-core');
const { _, log, ask, io, template } = utils;
const { filesIn, path } = io;
const ContextMaker = require('./context-maker');
const _eval = require('eval');
_.path = path;
function loadEval(filePath, dirname) {
let content = io.readFile(filePath + '.js', 'utf8');
try {
return _eval(content, { _: _ });
} catch (e) {
console.error(e);
throw e;
}
}
function loadEvalRecurse(filePath) {
let content = io.readFile(filePath + '.js', 'utf8');
filePath = filePath.replace('\/index', '');
content = content.replace(/require\('./g, "loadEval('" + filePath);
return _eval(content, {loadEval: loadEval});
}
module.exports = class Templator {
constructor(paths, ctx) {
this.paths = paths;
this.name = paths.name;
this.destinationFolder = this.paths.destinationFolder;
this.registry = new Registry();
this.preferences = new Preferences();
this.ctx = new ContextMaker(this.name, ctx).ctx;
this.layoutPath = this.paths.layoutPath;
let layouterPath = this.paths.relativeLayoutPath;
let load = require;
if (this.paths.custom) {
load = loadEvalRecurse;
layouterPath = this.paths.relativeLayoutPath + '/index';
}
this.layouter = load(layouterPath);
let componentTemplatesPath = path.join(this.paths.relativeLayoutPath, 'component');
let files = filesIn(componentTemplatesPath);
this.templatePaths = this.layouter.template.paths(this.ctx, files);
}
get registryConfig() {
return this.registry.config;
}
// TODO: use component layout/skeleton mapping?
create() {
// console.log('create');
this.createComponentFiles();
this.createIndex();
}
createComponentFiles() {
// console.log('create Component Files');
for (let templatePath of this.templatePaths) {
let targetFile = this.layouter.template.rename(templatePath, this.ctx);
this.componentFile(templatePath, targetFile);
}
}
// TODO: check file not there!
// skip if not a feature component
createIndex() {
if (!this.ctx.feature) return;
io.unlessFilePresent('index.js', () => {
console.log('creating missing feature index');
this.componentFile('index.js', '../index.js');
})
}
componentFile(templatePath, destinationPath) {
let opts = {
basePath: path.join(this.layoutPath, 'component'),
templatePath: templatePath,
destinationPath: destinationPath,
ctx: this.ctx
};
// console.log('componentFile', opts);
let templater = template(this.destinationFolder, opts)
templater.create();
}
} |
andreybukhtoyarov/abukhtoyarov | chapter_001/src/main/java/ru/job4j/condition/DummyBot.java | package ru.job4j.condition;
/**
*This is simple (dummy) chat bot.
*@author <NAME> (<EMAIL>).
*@version 1.0.
*@since 27.12.2017.
*/
public class DummyBot {
/**
* This method answers questions.
* @param question - question for bot.
* @return result - answer of bot.
*/
public String answer(String question) {
String result = "Это ставит меня в тупик. Спросите другой вопрос.";
if (question.equals("Привет, Бот!")) {
result = "Привет, умник.";
} else if (question.equals("Пока.")) {
result = "До скорой встречи.";
}
return result;
}
}
|
ZackMurry/forar | frontend/src/components/UserPage/Bio.js | <gh_stars>1-10
import React from 'react'
import { Typography } from '@material-ui/core'
export default function Bio ({ user }) {
return (
//bio limit 250 chars
<div style={{marginTop: '1%', width: '60%'}}>
<Typography variant='h5' style={{marginLeft: '28vh', lineHeight: 1.25}}>
{user.bio}
</Typography>
</div>
)
} |
pchaigno/chess-service | CentralServer/src/core/Resource.java | <reponame>pchaigno/chess-service<gh_stars>1-10
package core;
import java.net.URISyntaxException;
import java.util.List;
import javax.swing.event.EventListenerList;
import javax.ws.rs.core.MediaType;
import org.eclipse.core.runtime.URIUtil;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
/**
* The model for all resources (databases and chess engines).
* Fire the events to the resource listeners.
* @author <NAME>
* @author <NAME>
* @author <NAME>
*/
public abstract class Resource {
public final static int OPENINGS_DATABASE = 0;
public final static int BOT = 1;
public final static int ENDINGS_DATABASE = 2;
protected final static int CONNECT_TIMEOUT = Integer.parseInt(PropertiesManager.getProperty(PropertiesManager.PROPERTY_CONNECT_TIMEOUT));
protected final static int READ_TIMEOUT = Integer.parseInt(PropertiesManager.getProperty(PropertiesManager.PROPERTY_READ_TIMEOUT));
protected final static int DEFAULT_TRUST = 1;
protected Integer id;
protected String uri;
protected String name;
protected int trust;
protected boolean changed;
protected boolean san;
protected String version;
protected boolean connected;
protected boolean active;
protected static final String JSON_MOVE = "move";
/**
* The list of event listener for the central server.
* EventListenerList is used for a better multithread safety.
*/
private static final EventListenerList listeners = new EventListenerList();
/**
* Add a resource listener to the listeners.
* @param listener The new listener.
*/
public static void addResourceListener(ResourceListener listener) {
listeners.add(ResourceListener.class, listener);
}
/**
* Remove a resource listener from the listeners.
* @param listener The new listener.
*/
public static void removeResourceListener(ResourceListener listener) {
listeners.remove(ResourceListener.class, listener);
}
/**
* @return The resource listeners.
*/
public static ResourceListener[] getResourceListeners() {
return listeners.getListeners(ResourceListener.class);
}
/**
* Constructor
* Add a slash at the end of the URI if there isn't already one.
* @param uri The URI of the resource.
* @param name The name of the resource.
* @param trust The trust in the resource.
* @param active True if the resource is active.
* @param id The resource id.
*/
public Resource(String uri, String name, int trust, boolean active, int id) {
this.uri = uri;
if(!this.uri.endsWith("/")) {
this.uri += "/";
}
if(!this.uri.contains("://")) {
this.uri = "http://"+this.uri;
}
this.name = name;
this.changed = false;
this.trust = trust;
this.id = id;
this.active = active;
}
/**
* @return The trust.
*/
public int getTrust() {
return trust;
}
/**
* Update the trust.
* @param trust The new trust value.
*/
public void setTrust(int trust) {
this.trust = trust;
this.changed = true;
}
/**
* @return True if the resource was changed.
*/
public boolean isChanged() {
return this.changed;
}
/**
* Clear the suggestions of moves.
*/
protected abstract void clearSuggestions();
/**
* Query the resource on the network and update the suggestions of move.
* The resource need to send moves in a JSON document.
* To be send to the resource, the slashes in the FEN are replaced by dollars.
* Indead, slashes are a special character for URL.
* @param fen The FEN representing the current position of the chessboard.
*/
public void query(String fen) {
// Notify the resource listeners about the request.
this.fireQueryRequest(fen);
this.clearSuggestions();
// Replace the slashes in the FEN by dollars.
String fenEncoded = fen.replaceAll("/", "\\$");
// Convert the FEN into a url encoded string:
try {
fenEncoded = URIUtil.fromString(fenEncoded).toASCIIString();
} catch (URISyntaxException e) {
System.err.println("FEN incorrect: "+fen);
}
// Prepare the request (timeouts and URL):
Client c = Client.create();
System.out.println(this.uri+fenEncoded); // TODO Call listener instead.
WebResource r = c.resource(this.uri+fenEncoded);
c.setConnectTimeout(CONNECT_TIMEOUT);
c.setReadTimeout(READ_TIMEOUT);
// Launch the request and parse the result:
try {
String response = r.accept(MediaType.APPLICATION_JSON_TYPE).get(String.class);
// Notify the resource listeners about the response received.
this.fireSuggestionsReceived(response);
this.parseJSONMove(response, fen);
// Notify the resource listeners about the suggestions update.
this.fireSuggestionsUpdated();
} catch(ClientHandlerException e) {
// It just do nothing if the resource isn't connected.
}
}
/**
* Parse the JSON moves to openings move.
* Convert the LAN to SAN if it's necessary.
* @param response The JSON moves.
* @param fen The FEN.
*/
protected abstract void parseJSONMove(String response, String fen);
/**
* @return The URI.
*/
public String getURI() {
return this.uri;
}
/**
* @return The name.
*/
public String getName() {
return this.name;
}
/**
* @return True if the resource send SAN moves.
*/
public boolean isSAN() {
return this.san;
}
/**
* @return The version.
*/
public String getVersion() {
return this.version;
}
/**
* @param v The version of the resource.
*/
public void setVersion(String v) {
this.version = v;
}
/**
* @return True if the resource is active.
*/
public boolean isActive() {
return this.active;
}
/**
* Enable the resource.
*/
public void enable() {
this.active = true;
}
/**
* Disable the resource.
*/
public void disable() {
this.active = false;
}
/**
* @return True if the resource if connected.
*/
public boolean isConnected() {
return connected;
}
/**
* @return The resource id.
*/
public int getId() {
return id;
}
/**
* @param id The new id.
*/
public void setId(int id) {
this.id = id;
}
/**
* Complete the version and the san parameters by calling the resource.
*/
public void checkVersion() {
// Notify the resource listeners about the request.
this.fireVersionRequest();
// Prepare the request:
Client client = Client.create();
WebResource webresource = client.resource(this.uri + "/version");
client.setConnectTimeout(CONNECT_TIMEOUT);
client.setReadTimeout(READ_TIMEOUT);
// Launch the request and complete the params:
try {
ClientResponse clientresponse = webresource.get(ClientResponse.class);
String response = clientresponse.getEntity(String.class);
int status = clientresponse.getStatus();
// Notify the resource listeners about the response received.
this.fireVersionReceived(status, response);
if(status != 200) {
this.connected = false;
} else {
if(response.length()<4) {
// The version number returned is incorrect, we remove the resource.
this.connected = false;
System.err.println("Version number incorrect for "+this.name+" at "+this.uri);
} else {
this.connected = true;
this.san = ('s' == response.charAt(response.length()-1));
this.version = response.substring(0, response.length()-1);
}
}
} catch(ClientHandlerException e) {
this.connected = false;
}
// Notify the resource listeners that the version is updated.
this.fireVersionUpdated();
}
/**
* @return The suggestions of move.
*/
public abstract List<? extends MoveSuggestion> getMoveSuggestions();
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((uri == null)? 0 : uri.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if(this==obj) {
return true;
}
if(obj==null) {
return false;
}
if(!(obj instanceof Resource)) {
return false;
}
Resource other = (Resource)obj;
if(id==null) {
if(other.id!=null) {
return false;
}
} else if(!id.equals(other.id)) {
return false;
}
return true;
}
/**
* Fire a query request event for all resource listeners.
* @param fen The FEN sent.
*/
private void fireQueryRequest(String fen) {
for(ResourceListener listener: getResourceListeners()) {
listener.onQueryRequest(this, fen);
}
}
/**
* Fire a suggestions received event for all resource listeners.
* @param suggestions The suggestions received as a JSON document.
*/
private void fireSuggestionsReceived(String suggestions) {
for(ResourceListener listener: getResourceListeners()) {
listener.onSuggestionsReceived(this, suggestions);
}
}
/**
* Fire a suggestions updated event for all resource listeners.
*/
private void fireSuggestionsUpdated() {
for(ResourceListener listener: getResourceListeners()) {
listener.onSuggestionsUpdated(this);
}
}
/**
* Fire a version request event for all resource listeners.
*/
private void fireVersionRequest() {
for(ResourceListener listener: getResourceListeners()) {
listener.onVersionRequest(this);
}
}
/**
* Fire a version received event for all resource listeners.
* @param status The response status, a HTTP code.
* @param response The response body.
*/
private void fireVersionReceived(int status, String response) {
for(ResourceListener listener: getResourceListeners()) {
listener.onVersionReceived(this, status, response);
}
}
/**
* Fire a version updated event for all resource listeners.
*/
private void fireVersionUpdated() {
for(ResourceListener listener: getResourceListeners()) {
listener.onVersionUpdated(this);
}
}
} |
FinalCraftMC/EnderIO | enderio-base/src/main/java/crazypants/enderio/util/NNPair.java | package crazypants.enderio.util;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.tuple.MutablePair;
import com.enderio.core.common.util.NullHelper;
public class NNPair<L, R> extends MutablePair<L, R> {
private static final @Nonnull String INTERNAL_LOGIC_ERROR = "internal logic Error";
private static final long serialVersionUID = 5714349103405358085L;
public @Nonnull static <L, R> NNPair<L, R> of(final @Nonnull L left, final @Nonnull R right) {
return new NNPair<L, R>(left, right);
}
public NNPair(@Nonnull L left, @Nonnull R right) {
super(left, right);
}
@Override
public @Nonnull L getLeft() {
return NullHelper.notnull(super.getLeft(), INTERNAL_LOGIC_ERROR);
}
@Override
public @Nonnull R getRight() {
return NullHelper.notnull(super.getRight(), INTERNAL_LOGIC_ERROR);
}
@Override
public @Nonnull R getValue() {
return NullHelper.notnull(super.getValue(), INTERNAL_LOGIC_ERROR);
}
@Override
public void setLeft(L left) {
super.setLeft(NullHelper.notnull(left, INTERNAL_LOGIC_ERROR));
}
@Override
public void setRight(R right) {
super.setRight(NullHelper.notnull(right, INTERNAL_LOGIC_ERROR));
}
@Override
public @Nonnull R setValue(R value) {
return NullHelper.notnull(super.setValue(NullHelper.notnull(value, INTERNAL_LOGIC_ERROR)), INTERNAL_LOGIC_ERROR);
}
}
|
crackersamdjam/DMOJ-Solutions | CCC/ccc05j5.cpp | #include <bits/stdc++.h>
using namespace std;
string in;
inline bool go(string str){
if(str.length() < 1)
return 0;
if(str == "A")
return 1;
if(str[0] == 'B' && str[str.length()-1] == 'S'){
if(go(str.substr(1,str.length()-2)))
return 1;
}
for(int i = 1; i <= str.length()-2; i++){
if(str[i] == 'N')
if(go(str.substr(0,i)) && go(str.substr(i+1)))
return 1;
}
return 0;
}
int main(){
while(1){
cin >> in;
if(in == "X")
break;
printf(go(in)? "YES\n": "NO\n");
}
} |
gilalan/rhpontocode | src/app/pages/entities/sectors/edit/EditSectorCtrl.js | <gh_stars>0
/**
* @author <NAME>
* created on 22.04.2017
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.entities.sectors')
.controller('EditSectorCtrl', EditSectorCtrl);
/** @ngInject */
function EditSectorCtrl($scope, $filter, $state, setor, sectorAPI, campi, estados) {
console.log('dentro do EDITSectorCtrl! ', setor);
$scope.title = 'Editar';
$scope.setor = setor.data;
$scope.campi = campi.data;
$scope.estados = estados.data;
$scope.municipios = [];
console.log('Campi array: ', campi.data);
$scope.selectedUF = function(sItem){
$scope.selectedMunicipio = {};
console.log("item Estado: ", sItem);
if (sItem){
if (sItem.item){
$scope.municipios = sItem.item.cidades;
} else {
$scope.municipios = sItem.cidades;
}
if($scope.municipios.length > 0)
$scope.selectedMunicipio = $scope.municipios[0];
}
}
$scope.save = function (setor) {
//acopla o campus ao setor
setor.campus = $scope.selected.item;
setor.local = {};
setor.local.estado = $scope.selectedEstado.item;
setor.local.municipio = $scope.selectedMunicipio.item;
console.log('Setor enviado: ', setor);
sectorAPI.update(setor).then(function sucessCallback(response){
console.log('dados recebidos da atualização: ', response.data);
$scope.successMsg = response.data.message;
//back to list
$state.go('entities.sectors.list');
}, function errorCallback(response){
$scope.errorMsg = response.data.message;
console.log('Erro de registro: ' + response.data.message);
});
}
function checkCampus(campus) {
return $scope.setor.campus == campus._id;
};
function checkEstado(estado) {
if($scope.setor.local)
return $scope.setor.local.estado == estado._id;
};
function checkMunicipio(municipio) {
if($scope.setor.local)
return $scope.setor.local.municipio == municipio._id;
};
function initSelects(){
if ($scope.campi.length > 0){
$scope.selected = { item: $scope.campi[$scope.campi.findIndex(checkCampus)] };
}
if ($scope.estados.length > 0){
$scope.selectedEstado = { item: $scope.estados[$scope.estados.findIndex(checkEstado)] };
if ($scope.selectedEstado.item) {
$scope.municipios = $scope.selectedEstado.item.cidades;
if ($scope.municipios.length > 0)
$scope.selectedMunicipio = {item: $scope.municipios[$scope.municipios.findIndex(checkMunicipio)]};
}
}
};
initSelects();
}
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.