repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
plankes-projects/BaseWar | client/Classes/View/Layers/StartMenuLayer/StartMenuLayer.cpp | <reponame>plankes-projects/BaseWar
#include "StartMenuLayer.h"
using namespace cocos2d;
#include "../../../Model/Model.h"
#include "../../../SceneControl.h"
#include "../../../Constants.h"
#include "../../../Tools/SupportHandler.h"
#include "../../CCConfirmView.h"
#include "../../CCAlertView.h"
#include "../../../Tools/Tools.h"
#include "../../../Debug/BalanceSingleton.h"
#include "../../../AchievementSystem/AchievementSystem.h"
#include "../../../AchievementSystem/AchievementFeedback.h"
#include "../../../Tools/ViewTools.h"
#include "../../../Sound/SoundHandler.h"
// on "init" you need to initialize your instance
bool StartMenuLayer::init() {
float scaleMult = Model::getInstance()->getGUIElementScaleMultiplicator();
if (!CCLayerColor::initWithColor(ccc4(100, 0, 0, 0)))
return false;
SoundHandler::getInstance()->playBackground("sound_menu1");
float button_length = 66 * scaleMult;
float button_heigth = 66 * scaleMult;
float padding = 10 * scaleMult;
_soundOnString = "on";
_soundOffString = "off";
//setting background
ViewTools::setStandardBackgroundImage(this);
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCMenuItemSprite *startOneVsComp = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("pVsAI0.png"),
CCSprite::createWithSpriteFrameName("pVsAI1.png"), (CCObject*) this, menu_selector(StartMenuLayer::oneVsCompTouched));
startOneVsComp->setScaleX(button_length / startOneVsComp->getContentSize().width);
startOneVsComp->setScaleY(button_heigth / startOneVsComp->getContentSize().height);
CCMenuItemSprite *startOneVsOne = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("pPvP0.png"),
CCSprite::createWithSpriteFrameName("pPvP1.png"), (CCObject*) this, menu_selector(StartMenuLayer::oneVsOneTouched));
startOneVsOne->setScaleX(button_length / startOneVsOne->getContentSize().width);
startOneVsOne->setScaleY(button_heigth / startOneVsOne->getContentSize().height);
CCMenuItemSprite *startOneVsOneX3 = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("pInternet0.png"),
CCSprite::createWithSpriteFrameName("pInternet1.png"), (CCObject*) this, menu_selector(StartMenuLayer::networkGameTouched));
startOneVsOneX3->setScaleX(button_length / startOneVsOneX3->getContentSize().width);
startOneVsOneX3->setScaleY(button_heigth / startOneVsOneX3->getContentSize().height);
CCMenuItemSprite *achievement = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("achievementButton1.png"),
CCSprite::createWithSpriteFrameName("achievementButton2.png"), (CCObject*) this, menu_selector(StartMenuLayer::achievementTouched));
achievement->setScaleX(button_length / achievement->getContentSize().width);
achievement->setScaleY(button_heigth / achievement->getContentSize().height);
CCMenuItemSprite *stats = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("pStats0.png"), CCSprite::createWithSpriteFrameName("pStats1.png"),
(CCObject*) this, menu_selector(StartMenuLayer::statsTouched));
stats->setScaleX(button_length / stats->getContentSize().width);
stats->setScaleY(button_heigth / stats->getContentSize().height);
CCMenuItemSprite *feedback = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("pFeedback0.png"),
CCSprite::createWithSpriteFrameName("pFeedback1.png"), (CCObject*) this, menu_selector(StartMenuLayer::feedbackTouched));
feedback->setScaleX(button_length / feedback->getContentSize().width);
feedback->setScaleY(button_heigth / feedback->getContentSize().height);
#ifdef DEBUG
CCMenuItemSprite *balancegame = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("pStats0.png"),
CCSprite::createWithSpriteFrameName("pStats1.png"), (CCObject*) this, menu_selector(StartMenuLayer::startBalanceGameTouched));
balancegame->setScaleX(button_length / balancegame->getContentSize().width);
balancegame->setScaleY(button_heigth / balancegame->getContentSize().height);
this->schedule(schedule_selector(StartMenuLayer::startNextRoundIfNeeded), 1);
#endif
CCMenu* menu = CCMenu::create();
menu->addChild(startOneVsComp, 1);
menu->addChild(startOneVsOne, 1);
menu->addChild(startOneVsOneX3, 1);
menu->addChild(stats, 1);
menu->addChild(achievement, 1);
menu->addChild(feedback, 1);
#ifdef DEBUG
menu->addChild(balancegame, 1);
#endif
menu->alignItemsHorizontallyWithPadding(padding);
addChild(menu);
CCMenu* shutdownmenu = CCMenu::create();
CCMenuItemSprite *shutdown = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("shutdown0.png"),
CCSprite::createWithSpriteFrameName("shutdown1.png"), (CCObject*) this, menu_selector(StartMenuLayer::shutdownTouched));
shutdown->setScaleX(button_length / shutdown->getContentSize().width);
shutdown->setScaleY(button_heigth / shutdown->getContentSize().height);
shutdownmenu->addChild(shutdown);
CCMenuItemSprite *enableSound = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("soundEnable0.png"),
CCSprite::createWithSpriteFrameName("soundEnable1.png"), (CCObject*) this, menu_selector(StartMenuLayer::enableSoundTouched));
enableSound->setScaleX(button_length / enableSound->getContentSize().width);
enableSound->setScaleY(button_heigth / enableSound->getContentSize().height);
float scale = button_heigth / enableSound->getContentSize().height;
_enableSoundLabel = CCLabelTTF::create(SoundHandler::getInstance()->isSoundEnabled() ? _soundOnString.c_str() : _soundOffString.c_str(), FONT_NAME,
PRICE_LABEL_FONT_SIZE / scale * scaleMult, CCSize(enableSound->getContentSize().width, PRICE_LABEL_HEIGTH / scale * scaleMult),
kCCTextAlignmentCenter);
enableSound->addChild(_enableSoundLabel);
_enableSoundLabel->setColor(SoundHandler::getInstance()->isSoundEnabled() ? ccc3(0, 255, 0) : ccc3(255, 0, 0));
_enableSoundLabel->setPosition(CCPoint(enableSound->getContentSize().width / 2, PRICE_LABEL_BOTTOM_SPACE / scale * scaleMult));
_enableSoundLabel->enableStroke(PRICE_LABEL_COLOR_STROKE, PRICE_LABEL_STROKE_SIZE / scale * scaleMult, true);
shutdownmenu->addChild(enableSound);
shutdownmenu->alignItemsVerticallyWithPadding(padding);
addChild(shutdownmenu);
shutdownmenu->setPosition(CCPoint(winSize.width - button_length / 2, winSize.height - (button_heigth * 2.0f + padding) / 2));
CCMenuItemFont* tutorial = CCMenuItemFont::create("Tutorial", this, menu_selector(StartMenuLayer::tutorialTouched));
tutorial->setFontSizeObj(28 * scaleMult);
tutorial->setFontName(FONT_NAME);
tutorial->setColor(ccc3(0, 0, 255)); //red
menu = CCMenu::create(tutorial, NULL);
addChild(menu);
menu->setPosition(CCPoint(winSize.width / 2, winSize.height / 2 - (button_heigth / 1.5 + padding)));
if (SupportHandler::isEditBoxSupported()) {
CCScale9Sprite* tmp = CCScale9Sprite::createWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("inputText.png"));
_playerNameTextBox = CCEditBox::create(CCSize(300, 60), tmp);
_playerNameTextBox->setPosition(ccp(winSize.width / 2, winSize.height / 2 - (tutorial->getContentSize().height + button_heigth / 1.5 + 3 * padding)));
_playerNameTextBox->setFontColor(ccWHITE);
_playerNameTextBox->setPlaceHolder("Name");
std::string name = CCUserDefault::sharedUserDefault()->getStringForKey("playername", "");
_playerNameTextBox->setText(name.c_str());
_playerNameTextBox->setMaxLength(10);
_playerNameTextBox->setReturnType(kKeyboardReturnTypeDone);
_playerNameTextBox->setInputMode(kEditBoxInputModeSingleLine);
_playerNameTextBox->setScale(scaleMult);
//m_pEditName->setDelegate(this);
addChild(_playerNameTextBox);
}
//init message
float label_font_size = 25 * scaleMult;
const char* label_font = FONT_NAME;
ccColor3B color = ccc3(0, 0, 0);
float offsetDown = ViewTools::addVersionAndCreditInfo(this, scaleMult);
ViewTools::addIdleUnitTo(this, offsetDown);
//build it once to update the achievements.
// we make it here because this is the central place where we will land after doing anything
AchievementSystem a = AchievementSystem();
float achHeight = 0;
std::vector<Achievement*> newAch = a.getAchievements();
if (newAch.size() != 0 && newAch.front()->isAchieved()) {
CCLayerColor* layer = ViewTools::createLayerFromAchievement(newAch.front());
achHeight = layer->getContentSize().height;
addChild(layer);
layer->setPosition(CCPoint(winSize.width / 2 - layer->getContentSize().width / 2, winSize.height / 2 + button_heigth / 2 + padding));
}
std::string s = "Newest achievement:";
#ifdef DEBUG
s = "!!! DEBUG BUILD - DO NOT RELEASE THIS !!!\n" + s;
#endif
cocos2d::CCLabelTTF* information = CCLabelTTF::create(s.c_str(), label_font, label_font_size);
information->setColor(color);
information->setPosition(
CCPoint(winSize.width / 2, information->getContentSize().height / 2 + achHeight + winSize.height / 2 + button_heigth / 2 + 2 * padding));
this->addChild(information);
int numTutorialUsed = CCUserDefault::sharedUserDefault()->getIntegerForKey("tutorialShowed", 0);
if (numTutorialUsed == 0) {
CCUserDefault::sharedUserDefault()->setIntegerForKey("tutorialShowed", 1);
CCUserDefault::sharedUserDefault()->flush();
CCConfirmView *alert = CCConfirmView::create("Tutorial", "Check out the tutorial", "Start", "Skip", this,
callfuncO_selector(StartMenuLayer::tutorialTouched), callfuncO_selector(StartMenuLayer::voidTouched));
addChild(alert, 100);
} else {
//show give feedback
std::string lastFeedBackForVersion = CCUserDefault::sharedUserDefault()->getStringForKey(LAST_FEEDBACK_FOR_VERSION, "");
if (lastFeedBackForVersion != VERSION) {
//check time diff
std::string key = std::string("feedbackShowTresh") + Tools::toString(SHOW_GIVE_FEEDBACK_EVERY_SECONDS);
int secondsPlayed = GameStatistics().getSecondsPlayed();
int tresh = secondsPlayed / SHOW_GIVE_FEEDBACK_EVERY_SECONDS;
int showTresh = CCUserDefault::sharedUserDefault()->getIntegerForKey(key.c_str(), 0);
if (showTresh < tresh) {
CCUserDefault::sharedUserDefault()->setIntegerForKey(key.c_str(), tresh);
CCUserDefault::sharedUserDefault()->flush();
int points = (new AchievementFeedback())->getPoints();
std::string q = std::string("Want to get ") + Tools::toString(points) + " points?\nGive some feedback.";
CCConfirmView *alert = CCConfirmView::create("Feedback", q.c_str(), "Now", "Later", this,
callfuncO_selector(StartMenuLayer::feedbackTouched), callfuncO_selector(StartMenuLayer::voidTouched));
addChild(alert, 100);
}
}
}
return true;
}
void StartMenuLayer::tutorialTouched(cocos2d::CCObject* pSender) {
if (SupportHandler::isEditBoxSupported()) {
CCUserDefault::sharedUserDefault()->setStringForKey("playername", _playerNameTextBox->getText());
CCUserDefault::sharedUserDefault()->flush();
}
SceneControl::replaceScene(SceneControl::raceScene(TUTORIAL, "Tut", LEFT), true);
}
void StartMenuLayer::shutdownTouched(cocos2d::CCObject* pSender) {
if (SupportHandler::isEditBoxSupported()) {
CCUserDefault::sharedUserDefault()->setStringForKey("playername", _playerNameTextBox->getText());
CCUserDefault::sharedUserDefault()->flush();
}
CCUserDefault::sharedUserDefault()->flush();
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
void StartMenuLayer::voidTouched(cocos2d::CCObject* pSender) {
}
void StartMenuLayer::networkGameTouched(cocos2d::CCObject* pSender) {
if (AchievementSystem().getPoints() < NEEDED_POINTS_FOR_NETWORK_GAME) {
addChild(ViewTools::createNotUnlockedMessage(NEEDED_POINTS_FOR_NETWORK_GAME), 100);
return;
}
std::string name = "";
if (SupportHandler::isEditBoxSupported()) {
name = _playerNameTextBox->getText();
CCUserDefault::sharedUserDefault()->setStringForKey("playername", name);
CCUserDefault::sharedUserDefault()->flush();
} else {
//wrote the playername in another way... proj.linux/main.cpp
name = CCUserDefault::sharedUserDefault()->getStringForKey("playername", "");
}
if (name == "")
name = "Player";
//we are not allowed to use ; in a networkgame name because the server splits the string by ;
for (unsigned int i = 0; i < name.size(); i++) {
if (name[i] == ';')
name[i] = '_';
}
SceneControl::replaceScene(SceneControl::raceScene(NETWORK, name, LEFT), true);
}
void StartMenuLayer::oneVsOneTouched(cocos2d::CCObject* pSender) {
std::string name = "";
if (SupportHandler::isEditBoxSupported()) {
name = _playerNameTextBox->getText();
CCUserDefault::sharedUserDefault()->setStringForKey("playername", name);
CCUserDefault::sharedUserDefault()->flush();
}
if (name == "")
name = "Player";
SceneControl::replaceScene(SceneControl::raceScene(PVP, name, LEFT), true);
}
void StartMenuLayer::oneVsCompTouched(cocos2d::CCObject* pSender) {
CCAlertView::removeAlertViewIfPresent();
std::string name = "";
if (SupportHandler::isEditBoxSupported()) {
name = _playerNameTextBox->getText();
CCUserDefault::sharedUserDefault()->setStringForKey("playername", name);
CCUserDefault::sharedUserDefault()->flush();
}
if (name == "")
name = "Player";
SceneControl::replaceScene(SceneControl::raceScene(PVA, name, LEFT), true);
}
void StartMenuLayer::achievementTouched(cocos2d::CCObject* pSender) {
if (SupportHandler::isEditBoxSupported()) {
CCUserDefault::sharedUserDefault()->setStringForKey("playername", _playerNameTextBox->getText());
CCUserDefault::sharedUserDefault()->flush();
}
SceneControl::replaceScene(SceneControl::achievementScene(), true);
}
void StartMenuLayer::statsTouched(cocos2d::CCObject* pSender) {
if (SupportHandler::isEditBoxSupported()) {
CCUserDefault::sharedUserDefault()->setStringForKey("playername", _playerNameTextBox->getText());
CCUserDefault::sharedUserDefault()->flush();
}
SceneControl::replaceScene(SceneControl::statsScene(), true);
}
void StartMenuLayer::feedbackTouched(cocos2d::CCObject* pSender) {
if (SupportHandler::isEditBoxSupported()) {
CCUserDefault::sharedUserDefault()->setStringForKey("playername", _playerNameTextBox->getText());
CCUserDefault::sharedUserDefault()->flush();
}
SceneControl::replaceScene(SceneControl::feedbackScene(), true);
}
void StartMenuLayer::enableSoundTouched(cocos2d::CCObject* pSender) {
bool sound = !SoundHandler::getInstance()->isSoundEnabled();
SoundHandler::getInstance()->enableSound(sound);
_enableSoundLabel->setColor(sound ? ccc3(0, 255, 0) : ccc3(255, 0, 0));
_enableSoundLabel->setString(sound ? _soundOnString.c_str() : _soundOffString.c_str());
}
#ifdef DEBUG
void StartMenuLayer::startBalanceGameTouched(cocos2d::CCObject* pSender) {
SceneControl::replaceScene(SceneControl::raceScene(BALANCE_TEST, "name", LEFT), true);
}
void StartMenuLayer::startNextRoundIfNeeded(float dt) {
if(BalanceSingleton::getInstance() && BalanceSingleton::getInstance()->isAnotherRound()) {
Model::getInstance()->reset();
Model::getInstance()->setPlayer1RaceId(BalanceSingleton::getInstance()->getRaceId1());
Model::getInstance()->setPlayer2RaceId(BalanceSingleton::getInstance()->getRaceId2());
SceneControl::replaceScene(SceneControl::gameScene(BALANCE_TEST_GAME_SPEED, BALANCE_TEST), true);
}
}
#endif
|
romera-github/graph500 | cpu_2d/compression/simdplus/conf.h | /**
Copyright (C) powturbo 2013-2015
GPL v2 License
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.
- homepage : https://sites.google.com/site/powturbo/
- github : https://github.com/powturbo
- twitter : https://twitter.com/powturbo
- email : powturbo [_AT_] gmail [_DOT_] com
**/
// conf.h - "Integer Compression" config & common
#ifndef CONF_H
#define CONF_H
#if defined(__GNUC__)
#define ALIGNED(t,v,n) t v __attribute__ ((aligned (n)))
#define ALWAYS_INLINE inline __attribute__((always_inline))
#define _PACKED __attribute__ ((packed))
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
#define popcnt32(__x) __builtin_popcount(__x)
#define popcnt64(__x) __builtin_popcountll(__x)
#define TEMPLATE2_(__x, __y) __x##__y
#define TEMPLATE2(__x, __y) TEMPLATE2_(__x,__y)
#define TEMPLATE3_(__x,__y,__z) __x##__y##__z
#define TEMPLATE3(__x,__y,__z) TEMPLATE3_(__x, __y, __z)
#if defined(__x86_64__) || defined(__x86_32__)
static inline int bsr32(int x) {
int b = -1;
asm("bsrl %1,%0" : "+r" (b): "rm" (x) );
return b + 1;
}
static inline int __bsr32(int x) {
asm("bsr %1,%0" : "=r" (x) : "rm" (x) );
return x;
}
static inline int bsr64(unsigned long long x) {
return x?64 - __builtin_clzll(x):0;
}
#define bsr16(__x) bsr32(__x)
#else
static inline int bsr32(int x) {
return x?32 - __builtin_clz(x):0;
}
static inline int bsr64(unsigned long long x) {
return x?64 - __builtin_clzll(x):0;
}
#endif
#define ctzll(__x) __builtin_ctzll(__x)
#else
#error "only gcc support in this version"
#endif
#define SIZE_ROUNDUP(__n, __a) (((size_t)(__n) + (size_t)((__a) - 1)) & ~(size_t)((__a) - 1))
//---------------------------------------------------------------------------------------------------
#define ctou8(__cp) (*(unsigned char *)(__cp))
#define ctou16(__cp) (*(unsigned short *)(__cp))
#define ctou24(__cp) ((*(unsigned *)(__cp)) & 0xffffff)
#define ctou32(__cp) (*(unsigned *)(__cp))
#define ctou64(__cp) (*(unsigned long long *)(__cp))
#define ctou48(__cp) ((*(unsigned long long *)(__cp)) & 0xffffffffffffull)
#define ctou(__cp_t, __cp) (*(__cp_t *)(__cp))
#ifndef min
#define min(x,y) (((x)<(y)) ? (x) : (y))
#define max(x,y) (((x)>(y)) ? (x) : (y))
#endif
#ifdef NDEBUG
#define AS(expr, fmt,args...)
#else
#include <stdio.h>
#define AS(expr, fmt,args...) if(!(expr)) { fflush(stdout);fprintf(stderr, "%s:%s:%d:", __FILE__, __FUNCTION__, __LINE__); fprintf(stderr, fmt, ## args ); fflush(stderr); abort(); }
#endif
#define AC(expr, fmt,args...) if(!(expr)) { fflush(stdout);fprintf(stderr, "%s:%s:%d:", __FILE__, __FUNCTION__, __LINE__); fprintf(stderr, fmt, ## args ); fflush(stderr); abort(); }
#define die(fmt,args...) do { fprintf(stderr, "%s:%s:%d:", __FILE__, __FUNCTION__, __LINE__); fprintf(stderr, fmt, ## args ); fflush(stderr); exit(-1); } while(0)
#endif
|
weiss/original-bsd | local/ditroff/ditroff.old.okeeffe/gremlin.aed/gremlin/grem2.h | <reponame>weiss/original-bsd
/* @(#)grem2.h 1.2 04/18/83
* This is an include file for database macros.
*/
#define DBNextElt(elt) elt->nextelt
#define DBNextofSet(elt) elt->setnext
#define DBNullelt(elt) ( elt == NULL )
#define Nullpoint(pt) ( pt->x == nullpt )
#define PTNextPoint(pt) pt->nextpt
|
kvery/k-mall | mall-admin/mall-product/src/main/java/com/kvery/mall/admin/product/entity/CommentReplay.java | <filename>mall-admin/mall-product/src/main/java/com/kvery/mall/admin/product/entity/CommentReplay.java
package com.kvery.mall.admin.product.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 产品评价回复表
*
* @author kvery
* @date 2022-04-20 14:54
*/
@Getter
@Setter
@TableName("pms_comment_replay")
@ApiModel(value = "CommentReplay对象" , description = "产品评价回复表")
public class CommentReplay implements Serializable {
public static final String ID = "id" ;
public static final String COMMENT_ID = "comment_id" ;
public static final String MEMBER_NICK_NAME = "member_nick_name" ;
public static final String MEMBER_ICON = "member_icon" ;
public static final String CONTENT = "content" ;
public static final String CREATE_TIME = "create_time" ;
public static final String TYPE = "type" ;
private static final long serialVersionUID = 1L;
@TableId(value = "id" , type = IdType.AUTO)
private Long id;
private Long commentId;
private String memberNickName;
private String memberIcon;
private String content;
private LocalDateTime createTime;
@ApiModelProperty("评论人员类型;0->会员;1->管理员")
private Integer type;
} |
vboitsov/mobapp | app/src/main/java/ua/org/rshu/fmi/mobapp/view/fragment/entitieslist/groupslist/core/impl/GroupsListPresenterImpl.java | <filename>app/src/main/java/ua/org/rshu/fmi/mobapp/view/fragment/entitieslist/groupslist/core/impl/GroupsListPresenterImpl.java
package ua.org.rshu.fmi.mobapp.view.fragment.entitieslist.groupslist.core.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import ua.org.rshu.fmi.mobapp.persistent.fmipersistent.entity.Group;
import ua.org.rshu.fmi.mobapp.service.fmiservices.FmiService;
import ua.org.rshu.fmi.mobapp.util.PaginationArgs;
import ua.org.rshu.fmi.mobapp.view.fragment.entitieslist.core.EntitiesListFragment;
import ua.org.rshu.fmi.mobapp.view.fragment.entitieslist.core.impl.EntitiesListWithProgressbarPresenterImpl;
import ua.org.rshu.fmi.mobapp.view.fragment.entitieslist.groupslist.core.GroupsListPresenter;
/**
* Created by vb on 19/11/2017.
*/
public class GroupsListPresenterImpl extends EntitiesListWithProgressbarPresenterImpl<Group> implements GroupsListPresenter {
private FmiService mFmiService;
public GroupsListPresenterImpl(FmiService mFmiService) {
this.mFmiService = mFmiService;
}
@Override
public void bindView(EntitiesListFragment groupsListFragment) {
mEntitiesListFragment = groupsListFragment;
}
@Override
public void unbindView() {
mEntitiesListFragment = null;
}
@Override
protected List<Group> loadMoreForPagination(PaginationArgs paginationArgs) {
boolean isConnected = false;
List<Group> groupsList = new ArrayList<>();
showProgressBarFromMainThread();
while (!isConnected) {
try {
groupsList = mFmiService.getListOfGroups(paginationArgs).execute().body();
isConnected = true;
} catch (IOException | NullPointerException e) {
e.printStackTrace();
if (mEntitiesListFragment == null) {
return new ArrayList<>();
}
}
}
hideProgressBarFromMainThread();
return groupsList;
}
// protected void showProgressBarFromMainThread() {
// Handler mainHandler = new Handler(Looper.getMainLooper());
// Runnable myRunnable = () -> ((GroupsListFragment) mEntitiesListFragment).showProgressBar();
// mainHandler.post(myRunnable);
// }
//
// protected void hideProgressBarFromMainThread() {
// Handler mainHandler = new Handler(Looper.getMainLooper());
// Runnable myRunnable = () -> ((GroupsListFragment) mEntitiesListFragment).hideProgressBar();
// mainHandler.post(myRunnable);
// }
}
|
rbock/hana | include/boost/hana/monoid.hpp | /*!
@file
Defines `boost::hana::Monoid`.
@copyright <NAME> 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_MONOID_HPP
#define BOOST_HANA_MONOID_HPP
#include <boost/hana/monoid/laws.hpp>
#include <boost/hana/monoid/mcd.hpp>
#include <boost/hana/monoid/monoid.hpp>
#endif // !BOOST_HANA_MONOID_HPP
|
pussbb/pymaillib | pymaillib/imap/imap4.py | # -*- coding: utf-8 -*-
"""
Imap4
~~~~~~~~~~~~~~~~
Imap4 helper client library
:copyright: (c) 2017 WTFPL.
:license: WTFPL, see LICENSE for more details.
"""
import imaplib
import socket
import collections
from datetime import datetime
from typing import Any
from .exceptions.base import ImapClientError, ImapClientAbort, \
ImapClientReadOnlyError, ImapByeByeException, ImapRuntimeError
imaplib.IMAP4.error = ImapClientError
imaplib.IMAP4.abort = ImapClientAbort
imaplib.IMAP4.readonly = ImapClientReadOnlyError
def _profile(func):
if func.__func__.__name__.startswith('_'):
return func
def wrapper(*args, **kwargs):
start = datetime.now()
try:
return func(*args, **kwargs)
finally:
print('Function "{}" done in {}.'.format(func.__func__,
datetime.now() - start),
flush=True)
return wrapper
class IMAP4(imaplib.IMAP4):
def __init__(self, host: Any, port: int, timeout: int=60):
self._timeout = timeout
super().__init__(host, port)
def _create_socket(self):
return socket.create_connection((self.host, self.port), self._timeout)
def _check_bye(self):
try:
super()._check_bye()
except ImapClientError as exp:
raise ImapByeByeException(exp)
def open(self, *args, **kwargs):
try:
super().open(*args, **kwargs)
except BaseException as excp:
raise ImapRuntimeError(excp)
if __debug__:
def __getattribute__(self, item):
item = super().__getattribute__(item)
if imaplib.Debug > 5 and isinstance(item, collections.Callable):
return _profile(item)
return item
class IMAP4SSL(imaplib.IMAP4_SSL):
def __init__(self, host: Any, port: int, keyfile=None, certfile=None,
ssl_context=None, timeout: int=60):
self._timeout = timeout
super().__init__(host, port, keyfile, certfile, ssl_context)
def _create_socket(self):
sock = IMAP4._create_socket(self)
try:
return self.ssl_context.wrap_socket(sock,
server_hostname=self.host)
except Exception as excp:
raise ImapRuntimeError(excp)
class IMAP4Stream(imaplib.IMAP4_stream):
def __init__(self, command: str):
super().__init__(command=command.replace('stream:/', '', 1))
|
Yulyalu/yes-cart | core-modules/core-module-reports/src/main/java/org/yes/cart/report/impl/ReportObjectStreamFactoryImpl.java | <reponame>Yulyalu/yes-cart
/*
* Copyright 2009 Inspire-Software.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yes.cart.report.impl;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.security.AnyTypePermission;
import org.yes.cart.report.ReportObjectStreamFactory;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Writer;
import java.util.Map;
/**
*
* Use this factory to get configured xStream object or configured object output stream
* to perform transformation of domain objects to xml.
*
* User: <NAME> <EMAIL>
* Date: 7/1/12
* Time: 11:55 AM
*/
public class ReportObjectStreamFactoryImpl implements ReportObjectStreamFactory {
private static final String ROOT_NODE = "yes-report";
private final XStream xStream;
public ReportObjectStreamFactoryImpl() {
this.xStream = getXStream();
}
/**
* Get configured xstream object.
* @return {@link XStream}
*/
private XStream getXStream() {
final XStream xStream = new XStream(new DomDriver());
xStream.addPermission(AnyTypePermission.ANY);
xStream.setMode(XStream.NO_REFERENCES);
return xStream;
}
/**
* Spring IoC.
*
* @param aliases alias
*/
public void setAliasesMap(final Map<String, Class> aliases) {
for (final Map.Entry<String, Class> entry : aliases.entrySet()) {
this.xStream.alias(entry.getKey(), entry.getValue());
}
}
/**
* Spring IoC.
*
* @param omit omit
*/
public void setOmitFieldsMap(final Map<Class, String[]> omit) {
for (final Map.Entry<Class, String[]> entry : omit.entrySet()) {
for (final String field : entry.getValue()) {
this.xStream.omitField(entry.getKey(), field);
}
}
}
/**
* Spring IoC.
*
* @param converters converter
*/
public void setConverterMap(final Map<String, Converter> converters) {
for (final Map.Entry<String, Converter> entry : converters.entrySet()) {
this.xStream.registerConverter(entry.getValue());
}
}
/**
* Get configured object output stream.
*
* @param writer given writer
*
* @return {@link ObjectOutputStream}
*/
public ObjectOutputStream getObjectOutputStream(final Writer writer) throws IOException {
return xStream.createObjectOutputStream(writer, ROOT_NODE);
}
}
|
xiaohaijin/RHIC-STAR | StRoot/StJetMaker/towers/StjFMSTree.cxx | // $Id: StjFMSTree.cxx,v 1.1 2017/05/22 19:36:06 zchang Exp $
#include "StjFMSTree.h"
#include "StjTowerEnergyListReader.h"
ClassImp(StjFMSTree)
StjTowerEnergyList StjFMSTree::getEnergyList()
{
return _reader->getEnergyList();
}
|
lamerexter/universel | src/test/java/org/orthodox/universel/exec/types/script/declarations/field/nonstatic/fin/FinalDoubleFieldInitialisationTest.java | <reponame>lamerexter/universel
/*
* MIT Licence:
*
* Copyright (c) 2020 Orthodox Engineering Ltd
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
package org.orthodox.universel.exec.types.script.declarations.field.nonstatic.fin;
import org.junit.jupiter.api.Test;
import org.orthodox.universel.exec.types.script.declarations.field.nonstatic.AbstractFieldInitialisationTest;
/**
* Unit tests for simple final double field assignment scoped at the enclosing script level.
*/
public class FinalDoubleFieldInitialisationTest extends AbstractFieldInitialisationTest {
@Test
void primitiveDoubleField_withPrimitiveValue() throws Exception {
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "0d", 0d);
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "123d", 123d);
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "-1d", -1d);
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "Double('" + Double.MAX_VALUE + "').doubleValue()", Double.MAX_VALUE);
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "Double('" + Double.MIN_VALUE + "').doubleValue()", Double.MIN_VALUE);
}
@Test
void primitiveDoubleField_withPrimitiveWrapperValue_isAssignedUnboxedValue() throws Exception {
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "Double(123d)", 123d);
}
@Test
void primitiveDoubleField_withWiderTypeValue_isAssignedNarrowedValue() throws Exception {
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "123I", 123d);
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "123D", 123d);
}
@Test
void primitiveDoubleField_withWiderPrimitiveWrapperTypeValue_isAssignedNarrowedUnboxedValue() throws Exception {
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "Double('123')", 123d);
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "123D", 123d);
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "123I", 123d);
}
@Test
void primitiveDoubleField_withExpressionValue() throws Exception {
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "100d - 10d", 100d - 10d);
assertSingleAllAccessFinalFieldIsAssigned("double", double.class, "doubleField", "5d * -1d", -5d);
assertSingleAllAccessFinalFieldIsAssigned("import java.lang.Double.*", "Double", Double.class, "doubleField", "MAX_VALUE", Double.MAX_VALUE);
assertSingleAllAccessFinalFieldIsAssigned("import java.lang.Double.*", "Double", Double.class, "doubleField", "-9d + MAX_VALUE - 1d", -9d + Double.MAX_VALUE - 1d);
}
@Test
void primitiveDoubleWrapperField_withPrimitiveWrapperValue() throws Exception {
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "Double(0d)", 0d);
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "Double(123d)", 123d);
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "Double(-1d)", -1d);
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "Double(" + Double.MAX_VALUE + ")", Double.MAX_VALUE);
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "Double(" + Double.MIN_VALUE + ")", Double.MIN_VALUE);
}
@Test
void primitiveDoubleWrapperField_withPrimitiveValue_isAssignedBoxedValue() throws Exception {
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "Double('123').doubleValue()", 123d);
}
@Test
void primitiveDoubleWrapperField_withWiderTypeValue_isAssignedNarrowedValue() throws Exception {
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "Double(123d)", 123d);
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "123I", 123d);
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "123D", 123d);
}
@Test
void primitiveDoubleWrapperField_withWiderPrimitiveTypeValue_isAssignedNarrowedBoxedValue() throws Exception {
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "123", 123d);
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "123d", 123d);
}
@Test
void primitiveDoubleWrapperField_withExpressionValue() throws Exception {
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "Double(100d) - Double(10d)", 100d - 10d);
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "Double(5d) * Double(-1d)", -5d);
assertSingleAllAccessFinalFieldIsAssigned("import java.lang.Double.*", "Double", Double.class, "doubleWrapperField", "Double(MAX_VALUE)", Double.MAX_VALUE);
assertSingleAllAccessFinalFieldIsAssigned("import java.lang.Double.*", "Double", Double.class, "doubleWrapperField", "Double(-9d) + MAX_VALUE - Double(1d)", -9d + Double.MAX_VALUE - 1d);
}
@Test
void primitiveDoubleWrapperField_withNullValue() throws Exception {
assertSingleAllAccessFinalFieldIsAssigned("Double", Double.class, "doubleWrapperField", "null", null);
}
}
|
foreignfilm/advent-of-code-ruby | 2018/day-08/day-08-part-1.rb | #!/usr/bin/env ruby
file_path = File.expand_path("../day-08-input.txt", __FILE__)
input = File.read(file_path)
numbers = input.split.map(&:to_i)
def sum(numbers)
child_nodes = numbers.shift
meta_entries = numbers.shift
sum = 0
child_nodes.times do
sum += sum(numbers)
end
meta_entries.times do
sum += numbers.shift
end
sum
end
puts sum(numbers)
|
tedhyu/thermo | tests/test_joback.py | <filename>tests/test_joback.py
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2017, <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.'''
from numpy.testing import assert_allclose
import pytest
from thermo.joback import *
@pytest.mark.rdkit
def test_Joback_acetone():
from rdkit import Chem
from rdkit.Chem import Descriptors
from rdkit.Chem import AllChem
from rdkit.Chem import rdMolDescriptors
for i in [Chem.MolFromSmiles('CC(=O)C'), 'CC(=O)C']:
ex = Joback(i) # Acetone example
assert_allclose(ex.Tb(ex.counts), 322.11)
assert_allclose(ex.Tm(ex.counts), 173.5)
assert_allclose(ex.Tc(ex.counts), 500.5590049525365)
assert_allclose(ex.Tc(ex.counts, 322.11), 500.5590049525365)
assert_allclose(ex.Pc(ex.counts, ex.atom_count), 4802499.604994407)
assert_allclose(ex.Vc(ex.counts), 0.0002095)
assert_allclose(ex.Hf(ex.counts), -217830)
assert_allclose(ex.Gf(ex.counts), -154540)
assert_allclose(ex.Hfus(ex.counts), 5125)
assert_allclose(ex.Hvap(ex.counts), 29018)
assert_allclose(ex.Cpig_coeffs(ex.counts),[7.52, 0.26084, -0.0001207, 1.546e-08] )
assert_allclose(ex.Cpig(300), 75.32642000000001)
assert_allclose(ex.mul_coeffs(ex.counts), [839.11, -14.99])
assert_allclose(ex.mul(300), 0.0002940378347162687) |
winterroberts/AOS | src/net/aionstudios/api/error/ErrorManager.java | <gh_stars>0
package net.aionstudios.api.error;
import java.util.ArrayList;
import java.util.List;
import net.aionstudios.api.context.Context;
import net.aionstudios.api.context.ContextHandler;
import net.aionstudios.api.context.ContextManager;
import net.aionstudios.api.cron.CronDateTime;
import net.aionstudios.api.cron.CronJob;
import net.aionstudios.api.server.APIServer;
/**
* A class that accumulates {@link AOSError}s for the {@link APIServer} so that they can be thrown when they're encountered.
*
* @author <NAME>
*
*/
public class ErrorManager {
private static List<AOSError> errors = new ArrayList<AOSError>();
/**
* Registers an {@link AOSError} to the {@link ErrorManager}.
*
* @param con the {@link AOSError} to be registered to the {@link ErrorManager}.
* @return True if the {@link AOSError} was registered and none other by the same name was already registered to the {@link ErrorManager}, false otherwise.
*/
public static boolean registerError(AOSError error) {
for(AOSError e : errors) {
if(e.getName().equals(error.getName())) {
System.out.println("An error identified as '"+e.getName()+"' was already registered! This new instance couldn't be");
return false;
}
}
errors.add(error);
return true;
}
/**
* Locates an {@link AOSError} within the {@link ErrorManager}.
*
* @param error The string name of the {@link AOSError} to be found.
* @return A {@link AOSError} registered to the {@link ErrorManager} matching the provided name, or null if no such entry exists.
*/
public static AOSError getErrorByName(String error) {
for(AOSError e : errors) {
if(e.getName().equals(error)) {
return e;
}
}
return null;
}
/**
* Gets the number of the named {@link AOSError}
*
* @param error The string name of the {@link AOSError} to be found.
* @return The error number of the {@link AOSError} matching the provided name, or -1 if no such entry exists.
*/
public static int getErrorNumber(String error) {
for(int i = 0; i < errors.size(); i++) {
if(errors.get(i).getName().equals(error)) {
return i+1;
}
}
System.err.println("No such error '"+error+"'");
return -1;
}
}
|
maksim-khiuttiulia/contrib | activity/gpio-output/activity.go | package gpio_output
import (
"github.com/project-flogo/core/activity"
"github.com/project-flogo/core/data/coerce"
"github.com/project-flogo/core/support/log"
"github.com/stianeikeland/go-rpio/v4"
)
const (
actionTurnOn = "TurnOn"
actionTurnOff = "TurnOff"
actionToggle = "Toggle"
)
const (
jsonGpioPin = "gpioPin"
jsonAction = "action"
)
type Input struct {
GpioPin int `md:"GPIOPin, required"`
Action string `md:"Action, required, allowed(TurnOn, TurnOff, Toggle)"`
}
type Activity struct {
}
func init() {
_ = activity.Register(&Activity{})
}
func (i *Input) ToMap() map[string]interface{} {
return map[string]interface{}{
jsonGpioPin: i.GpioPin,
jsonAction: i.Action,
}
}
func (i *Input) FromMap(values map[string]interface{}) error {
var err error
i.GpioPin, err = coerce.ToInt(values[jsonGpioPin])
if err != nil {
return err
}
i.Action, err = coerce.ToString(values[jsonAction])
return err
}
func (a *Activity) Metadata() *activity.Metadata {
return activity.ToMetadata(&Input{})
}
func (a *Activity) Eval(ctx activity.Context) (done bool, err error) {
settings := &Input{}
ctx.GetInputObject(settings)
pinNumber := settings.GpioPin
pin := rpio.Pin(pinNumber)
action := settings.Action
log.RootLogger().Debug("Action %s, pin %d", action, pinNumber)
openError := rpio.Open()
if openError != nil {
log.RootLogger().Error("Failed to open pin")
return false, openError
}
pin.Output()
if action == actionTurnOn {
pin.Write(rpio.High)
} else if action == actionTurnOff {
pin.Write(rpio.Low)
} else if action == actionToggle {
pin.Toggle()
} else {
log.RootLogger().Error("Unknown action %s", action)
return false, nil
}
return true, nil
}
|
smagill/opensphere-desktop | open-sphere-base/core/src/main/java/io/opensphere/core/util/collections/AbstractProxyMap.java | package io.opensphere.core.util.collections;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* A map implementation that proxies map calls through the map provided by the
* subclass.
*
* @param <K> The type of the keys in the map.
* @param <V> The type of the values in the map.
*/
public abstract class AbstractProxyMap<K, V> implements Map<K, V>
{
@Override
public void clear()
{
getMap().clear();
}
@Override
public boolean containsKey(Object key)
{
return getMap().containsKey(key);
}
@Override
public boolean containsValue(Object value)
{
return getMap().containsValue(value);
}
@Override
public Set<java.util.Map.Entry<K, V>> entrySet()
{
return getMap().entrySet();
}
@Override
public boolean equals(Object obj)
{
return getMap().equals(obj);
}
@Override
public V get(Object key) throws IllegalStateException
{
return getMap().get(key);
}
@Override
public int hashCode()
{
return getMap().hashCode();
}
@Override
public boolean isEmpty()
{
return getMap().isEmpty();
}
@Override
public Set<K> keySet()
{
return getMap().keySet();
}
@Override
public V put(K key, V value)
{
return getMap().put(key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> m)
{
getMap().putAll(m);
}
@Override
public V remove(Object key)
{
return getMap().remove(key);
}
@Override
public int size()
{
return getMap().size();
}
@Override
public String toString()
{
return new StringBuilder().append(getClass().getSimpleName()).append(" [").append(getMap().toString()).append(']')
.toString();
}
@Override
public Collection<V> values()
{
return getMap().values();
}
/**
* Accessor for the map.
*
* @return The map.
*/
protected abstract Map<K, V> getMap();
}
|
uktrade/jupyterhub-data-auth-admin | dataworkspace/dataworkspace/apps/datasets/migrations/0022_joint_datasets_linked_field_name_change.py | <reponame>uktrade/jupyterhub-data-auth-admin<filename>dataworkspace/dataworkspace/apps/datasets/migrations/0022_joint_datasets_linked_field_name_change.py
# Generated by Django 2.2.4 on 2019-11-15 12:29
from django.db import migrations
def update_joint_dataset_version_number(apps, schema_editor):
ReferenceDataset = apps.get_model("datasets", "ReferenceDataset")
joint_datasets = ReferenceDataset.objects.filter(is_joint_dataset=True, deleted=False)
for dataset in joint_datasets:
dataset.major_version += 1
dataset.minor_version = 0
dataset.save()
class Migration(migrations.Migration):
dependencies = [("datasets", "0021_dataset_access_criteria")]
operations = [
migrations.RunPython(update_joint_dataset_version_number, migrations.RunPython.noop)
]
|
npocmaka/Windows-Server-2003 | termsrv/license/tlserver/server/wkstore.cpp | //+--------------------------------------------------------------------------
//
// Copyright (c) 1997-1999 Microsoft Corporation
//
// File: wkstore.cpp
//
// Contents: Persistent job store routine.
//
// History:
//
//---------------------------------------------------------------------------
#include "pch.cpp"
#include "server.h"
#include "jobmgr.h"
#include "tlsjob.h"
#include "wkstore.h"
#include "debug.h"
WORKOBJECTINITFUNC g_WorkObjectInitFunList[] = {
{WORKTYPE_RETURN_LICENSE, InitializeCReturnWorkObject }
};
DWORD g_NumWorkObjectInitFunList = sizeof(g_WorkObjectInitFunList) / sizeof(g_WorkObjectInitFunList[0]);
//---------------------------------------------------
//
CLASS_PRIVATE
CWorkObject*
CPersistentWorkStorage::InitializeWorkObject(
IN DWORD dwWorkType,
IN PBYTE pbData,
IN DWORD cbData
)
/*++
--*/
{
DBGPrintf(
DBG_INFORMATION,
DBG_FACILITY_WORKMGR,
DBGLEVEL_FUNCTION_TRACE,
_TEXT("CPersistentWorkStorage::InitializeWorkObject() initializing work %d\n"),
dwWorkType
);
CWorkObject* ptr = NULL;
DWORD dwStatus = ERROR_SUCCESS;
for(DWORD index =0; index < g_NumWorkObjectInitFunList; index ++)
{
if(dwWorkType == g_WorkObjectInitFunList[index].m_WorkType)
{
ptr = (g_WorkObjectInitFunList[index].m_WorkInitFunc)(
GetWorkManager(),
pbData,
cbData
);
break;
}
}
if(index >= g_NumWorkObjectInitFunList)
{
SetLastError(dwStatus = TLS_E_WORKSTORAGE_UNKNOWNWORKTYPE);
}
else
{
TLSWorkManagerSetJobDefaults(ptr);
}
if(dwStatus != ERROR_SUCCESS)
{
DBGPrintf(
DBG_ERROR,
DBG_FACILITY_WORKMGR,
DBGLEVEL_FUNCTION_DETAILSIMPLE,
_TEXT("CPersistentWorkStorage::InitializeWorkObject() return 0x%08x\n"),
dwStatus
);
}
return ptr;
}
//---------------------------------------------------
//
CLASS_PRIVATE BOOL
CPersistentWorkStorage::DeleteWorkObject(
IN OUT CWorkObject* ptr
)
/*++
--*/
{
DWORD dwStatus = ERROR_SUCCESS;
DWORD dwWorkType = 0;
DBGPrintf(
DBG_INFORMATION,
DBG_FACILITY_WORKMGR,
DBGLEVEL_FUNCTION_TRACE,
_TEXT("CPersistentWorkStorage::DeleteWorkObject() deleting work %s\n"),
ptr->GetJobDescription()
);
dwWorkType = ptr->GetWorkType();
ptr->SelfDestruct();
if(dwStatus != ERROR_SUCCESS)
{
DBGPrintf(
DBG_ERROR,
DBG_FACILITY_WORKMGR,
DBGLEVEL_FUNCTION_DETAILSIMPLE,
_TEXT("CPersistentWorkStorage::DeleteWorkObject() return 0x%08x\n"),
dwStatus
);
}
return dwStatus == ERROR_SUCCESS;
}
//---------------------------------------------------
//
CPersistentWorkStorage::CPersistentWorkStorage(
IN WorkItemTable* pWkItemTable
) :
m_pWkItemTable(pWkItemTable),
m_dwNumJobs(0),
m_dwJobsInProcesssing(0),
m_dwNextJobTime(INFINITE),
m_pNextWorkObject(NULL)
/*++
--*/
{
}
//---------------------------------------------------
//
CPersistentWorkStorage::~CPersistentWorkStorage()
{
// just make sure we have shutdown
// TLSASSERT(m_pWkItemTable == NULL);
}
//---------------------------------------------------
//
BOOL
CPersistentWorkStorage::DeleteErrorJob(
IN CWorkObject* ptr
)
/*++
--*/
{
BOOL bSuccess = TRUE;
DWORD dwStatus = ERROR_SUCCESS;
PBYTE pbBookmark;
DWORD cbBookmark;
DWORD dwTime;
DWORD dwJobType;
if(IsValidWorkObject(ptr) == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_PARAMETER);
goto cleanup;
}
bSuccess = ptr->GetJobId(&pbBookmark, &cbBookmark);
if(bSuccess == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_DATA);
goto cleanup;
}
dwJobType = ptr->GetWorkType();
m_hTableLock.Lock();
bSuccess = UpdateWorkItemEntry(
m_pWkItemTable,
WORKITEM_DELETE,
pbBookmark,
cbBookmark,
INFINITE,
INFINITE,
dwJobType,
NULL,
0
);
if(bSuccess == FALSE)
{
dwStatus = GetLastError();
}
m_hTableLock.UnLock();
DeleteWorkObject(ptr);
cleanup:
return bSuccess;
}
//---------------------------------------------------
//
CLASS_PRIVATE DWORD
CPersistentWorkStorage::GetCurrentBookmark(
IN WorkItemTable* pTable,
IN PBYTE pbData,
IN OUT PDWORD pcbData
)
/*++
--*/
{
BOOL bSuccess = TRUE;
DWORD dwStatus = ERROR_SUCCESS;
if(pTable != NULL)
{
JET_ERR jbError;
bSuccess = pTable->GetBookmark(pbData, pcbData);
if(bSuccess == FALSE)
{
jbError = pTable->GetLastJetError();
if(jbError == JET_errNoCurrentRecord)
{
*pcbData = 0;
SetLastError(dwStatus = ERROR_NO_DATA);
}
else if(jbError == JET_errBufferTooSmall)
{
SetLastError(dwStatus = ERROR_INSUFFICIENT_BUFFER);
}
else
{
SetLastError(dwStatus = SET_JB_ERROR(jbError));
}
}
}
else
{
SetLastError(dwStatus = ERROR_INVALID_PARAMETER);
TLSASSERT(FALSE);
}
return dwStatus;
}
//-------------------------------------------------------------
//
CLASS_PRIVATE DWORD
CPersistentWorkStorage::GetCurrentBookmarkEx(
IN WorkItemTable* pTable,
IN OUT PBYTE* ppbData,
IN OUT PDWORD pcbData
)
/*++
--*/
{
DWORD dwStatus = ERROR_SUCCESS;
BOOL bSucess = TRUE;
if(ppbData == NULL || pcbData == NULL || pTable == 0)
{
SetLastError(dwStatus = ERROR_INVALID_PARAMETER);
return dwStatus;
}
*ppbData = NULL;
*pcbData = 0;
dwStatus = GetCurrentBookmark(
pTable,
*ppbData,
pcbData
);
if(dwStatus == ERROR_INSUFFICIENT_BUFFER)
{
*ppbData = (PBYTE)AllocateMemory(*pcbData);
if(*ppbData != NULL)
{
dwStatus = GetCurrentBookmark(
pTable,
*ppbData,
pcbData
);
}
}
if(dwStatus != ERROR_SUCCESS)
{
if(*ppbData != NULL)
{
FreeMemory(*ppbData);
}
*ppbData = NULL;
*pcbData = 0;
}
return dwStatus;
}
//------------------------------------------------------
CLASS_PRIVATE DWORD
CPersistentWorkStorage::SetCurrentBookmark(
IN WorkItemTable* pTable,
IN PBYTE pbData,
IN DWORD cbData
)
/*++
--*/
{
BOOL bSuccess;
DWORD dwStatus = ERROR_SUCCESS;
if(pTable != NULL && pbData != NULL && cbData != 0)
{
bSuccess = pTable->GotoBookmark(pbData, cbData);
if(bSuccess == FALSE)
{
if(pTable->GetLastJetError() == JET_errRecordDeleted)
{
SetLastError(dwStatus = ERROR_NO_DATA);
}
else
{
SetLastError(dwStatus = SET_JB_ERROR(pTable->GetLastJetError()));
}
}
}
else
{
SetLastError(dwStatus = ERROR_INVALID_PARAMETER);
TLSASSERT(FALSE);
}
return dwStatus;
}
//---------------------------------------------------
//
BOOL
CPersistentWorkStorage::Shutdown()
{
BOOL bSuccess = TRUE;
//
// CWorkManager will make sure
// no job is in processing state before calling this
// routine and no job can be scheduled.
//
m_hTableLock.Lock();
//
// Timing.
//
TLSASSERT(m_dwJobsInProcesssing == 0);
if(m_pWkItemTable != NULL)
{
bSuccess = m_pWkItemTable->CloseTable();
m_pWkItemTable = NULL;
}
TLSASSERT(bSuccess == TRUE);
m_pWkItemTable = NULL;
m_dwNumJobs = 0;
m_dwNextJobTime = INFINITE;
if(m_pNextWorkObject != NULL)
{
DeleteWorkObject( m_pNextWorkObject );
m_pNextWorkObject = NULL;
}
m_hTableLock.UnLock();
return bSuccess;
}
//---------------------------------------------------
//
DWORD
CPersistentWorkStorage::StartupUpdateExistingJobTime()
{
BOOL bSuccess;
DWORD dwStatus = ERROR_SUCCESS;
DWORD dwTime;
DWORD dwMinTime = INFINITE;
// CWorkObject* ptr = NULL;
BOOL bValidJob = TRUE;
DWORD dwCurrentTime;
m_hTableLock.Lock();
//
//
bSuccess = m_pWkItemTable->MoveToRecord(JET_MoveFirst);
if(bSuccess == FALSE)
{
SetLastError(dwStatus = SET_JB_ERROR(m_pWkItemTable->GetLastJetError()));
}
while(dwStatus == ERROR_SUCCESS)
{
WORKITEMRECORD wkItem;
//if(ptr != NULL)
//{
// DeleteWorkObject(ptr);
// ptr = NULL;
//}
bValidJob = FALSE;
//
// fetch the record
//
bSuccess = m_pWkItemTable->FetchRecord(wkItem);
if(bSuccess == FALSE)
{
SetLastError(dwStatus = SET_JB_ERROR(m_pWkItemTable->GetLastJetError()));
continue;
}
if(wkItem.dwRestartTime != INFINITE && wkItem.dwScheduledTime >= m_dwStartupTime)
{
if(wkItem.dwScheduledTime < dwMinTime)
{
dwMinTime = wkItem.dwScheduledTime;
}
break;
}
//
// invalid data
//
if(wkItem.cbData != 0 && wkItem.pbData != NULL)
{
if(wkItem.dwRestartTime != INFINITE)
{
wkItem.dwScheduledTime = wkItem.dwRestartTime + time(NULL);
wkItem.dwJobType &= ~WORKTYPE_PROCESSING;
bSuccess = m_pWkItemTable->UpdateRecord(
wkItem,
WORKITEM_PROCESS_JOBTIME | WORKITEM_PROCESS_JOBTYPE
);
if(bSuccess == FALSE)
{
SetLastError(dwStatus = SET_JB_ERROR(m_pWkItemTable->GetLastJetError()));
break;
}
if(wkItem.dwScheduledTime < dwMinTime)
{
dwMinTime = wkItem.dwScheduledTime;
}
bValidJob = TRUE;
}
}
if(bValidJob == FALSE)
{
m_pWkItemTable->DeleteRecord();
}
// move the record pointer
bSuccess = m_pWkItemTable->MoveToRecord();
if(bSuccess == FALSE)
{
JET_ERR jetErrCode;
jetErrCode = m_pWkItemTable->GetLastJetError();
if(jetErrCode != JET_errNoCurrentRecord)
{
SetLastError(dwStatus = SET_JB_ERROR(jetErrCode));
}
break;
}
}
if(dwStatus == ERROR_SUCCESS)
{
bSuccess = m_pWkItemTable->MoveToRecord(JET_MoveFirst);
if(bSuccess == FALSE)
{
SetLastError(dwStatus = SET_JB_ERROR(m_pWkItemTable->GetLastJetError()));
}
UpdateNextJobTime(dwMinTime);
}
m_hTableLock.UnLock();
//if(ptr != NULL)
//{
// DeleteWorkObject(ptr);
// ptr = NULL;
//}
return dwStatus;
}
//---------------------------------------------------
//
BOOL
CPersistentWorkStorage::Startup(
IN CWorkManager* pWkMgr
)
/*++
--*/
{
BOOL bSuccess;
DWORD dwStatus = ERROR_SUCCESS;
CWorkStorage::Startup(pWkMgr);
if(IsGood() == TRUE)
{
//
// loop thru all workitem and count number of job
//
m_hTableLock.Lock();
m_dwStartupTime = time(NULL);
//
// Get number of job in queue
//
//
// GetCount() will set index to time column
m_dwNumJobs = m_pWkItemTable->GetCount(
FALSE,
0,
NULL
);
if(m_dwNumJobs == 0)
{
UpdateNextJobTime(INFINITE);
}
else
{
bSuccess = m_pWkItemTable->BeginTransaction();
if(bSuccess == TRUE)
{
dwStatus = StartupUpdateExistingJobTime();
if(dwStatus == ERROR_SUCCESS)
{
m_pWkItemTable->CommitTransaction();
}
else
{
m_pWkItemTable->RollbackTransaction();
}
}
else
{
dwStatus = GetLastError();
}
//
// constructor set next job time to 0 so
// work manager will immediately try to find next job
//
// Move to first record in table
//bSuccess = m_pWkItemTable->MoveToRecord(JET_MoveFirst);
}
m_hTableLock.UnLock();
}
else
{
SetLastError(dwStatus = ERROR_INVALID_PARAMETER);
}
return (dwStatus == ERROR_SUCCESS);
}
//----------------------------------------------------
//
CLASS_PRIVATE BOOL
CPersistentWorkStorage::IsValidWorkObject(
CWorkObject* ptr
)
/*++
--*/
{
BOOL bSuccess = FALSE;
DWORD dwJobType;
PBYTE pbData;
DWORD cbData;
//
// Validate input parameter
//
if(ptr == NULL)
{
TLSASSERT(FALSE);
goto cleanup;
}
dwJobType = ptr->GetWorkType();
if(dwJobType == WORK_TYPE_UNKNOWN)
{
TLSASSERT(FALSE);
goto cleanup;
}
ptr->GetWorkObjectData(&pbData, &cbData);
if(pbData == NULL || cbData == 0)
{
TLSASSERT(pbData != NULL && cbData != NULL);
goto cleanup;
}
bSuccess = TRUE;
cleanup:
return bSuccess;
}
//----------------------------------------------------
//
BOOL
CPersistentWorkStorage::IsGood()
{
if( m_pWkItemTable == NULL ||
m_hTableLock.IsGood() == FALSE ||
GetWorkManager() == NULL )
{
return FALSE;
}
return m_pWkItemTable->IsValid();
}
//----------------------------------------------------
//
CLASS_PRIVATE BOOL
CPersistentWorkStorage::UpdateJobEntry(
IN WorkItemTable* pTable,
IN PBYTE pbBookmark,
IN DWORD cbBookmark,
IN WORKITEMRECORD& wkItem
)
/*++
--*/
{
BOOL bSuccess = TRUE;
DWORD dwStatus = ERROR_SUCCESS;
dwStatus = SetCurrentBookmark(
pTable,
pbBookmark,
cbBookmark
);
if(dwStatus == ERROR_SUCCESS)
{
bSuccess = pTable->UpdateRecord(wkItem);
}
else
{
bSuccess = FALSE;
TLSASSERT(dwStatus == ERROR_SUCCESS);
}
return bSuccess;
}
//----------------------------------------------------
//
CLASS_PRIVATE BOOL
CPersistentWorkStorage::AddJobEntry(
IN WorkItemTable* pTable,
IN WORKITEMRECORD& wkItem
)
/*++
--*/
{
BOOL bSuccess;
bSuccess = pTable->InsertRecord(wkItem);
if(bSuccess == TRUE)
{
m_dwNumJobs++;
}
return bSuccess;
}
//----------------------------------------------------
//
CLASS_PRIVATE BOOL
CPersistentWorkStorage::DeleteJobEntry(
IN WorkItemTable* pTable,
IN PBYTE pbBookmark,
IN DWORD cbBookmark,
IN WORKITEMRECORD& wkItem
)
/*++
--*/
{
BOOL bSuccess = TRUE;
DWORD dwStatus = ERROR_SUCCESS;
dwStatus = SetCurrentBookmark(
pTable,
pbBookmark,
cbBookmark
);
if(dwStatus == ERROR_SUCCESS)
{
bSuccess = pTable->DeleteRecord();
if(bSuccess == TRUE)
{
m_dwNumJobs--;
}
}
else
{
bSuccess = FALSE;
TLSASSERT(dwStatus == ERROR_SUCCESS);
}
return bSuccess;
}
//----------------------------------------------------
//
CLASS_PRIVATE BOOL
CPersistentWorkStorage::UpdateWorkItemEntry(
IN WorkItemTable* pTable,
IN WORKITEM_OPERATION opCode,
IN PBYTE pbBookmark,
IN DWORD cbBookmark,
IN DWORD dwRestartTime,
IN DWORD dwTime,
IN DWORD dwJobType,
IN PBYTE pbJobData,
IN DWORD cbJobData
)
/*++
--*/
{
BOOL bSuccess = TRUE;
DWORD dwStatus = ERROR_SUCCESS;
WORKITEMRECORD item;
PBYTE pbCurrentBookmark=NULL;
DWORD cbCurrentBookmark=0;
m_hTableLock.Lock();
dwStatus = GetCurrentBookmarkEx(
pTable,
&pbCurrentBookmark,
&cbCurrentBookmark
);
if(dwStatus != ERROR_SUCCESS && dwStatus != ERROR_NO_DATA)
{
goto cleanup;
}
bSuccess = pTable->BeginTransaction();
if(bSuccess == FALSE)
{
dwStatus = GetLastError();
goto cleanup;
}
item.dwScheduledTime = dwTime;
item.dwRestartTime = dwRestartTime;
item.dwJobType = dwJobType;
item.cbData = cbJobData;
item.pbData = pbJobData;
switch(opCode)
{
case WORKITEM_ADD:
TLSASSERT(cbJobData != 0 && pbJobData != NULL);
m_pWkItemTable->SetInsertRepositionBookmark(
(dwTime < (DWORD)m_dwNextJobTime)
);
bSuccess = AddJobEntry(
pTable,
item
);
break;
case WORKITEM_BEGINPROCESSING:
item.dwJobType |= WORKTYPE_PROCESSING;
//
// FALL THRU
//
case WORKITEM_RESCHEDULE:
TLSASSERT(cbJobData != 0 && pbJobData != NULL);
bSuccess = UpdateJobEntry(
pTable,
pbBookmark,
cbBookmark,
item
);
break;
case WORKITEM_DELETE:
bSuccess = DeleteJobEntry(
pTable,
pbBookmark,
cbBookmark,
item
);
break;
default:
TLSASSERT(FALSE);
bSuccess = FALSE;
}
if(bSuccess == TRUE)
{
pTable->CommitTransaction();
dwStatus = ERROR_SUCCESS;
//
// constructor set time to first job 0 so that work manager can immediate kick off
//
if( (opCode != WORKITEM_ADD && opCode != WORKITEM_RESCHEDULE) || dwTime > (DWORD)m_dwNextJobTime )
{
if(pbCurrentBookmark != NULL && cbCurrentBookmark != 0)
{
dwStatus = SetCurrentBookmark(
pTable,
pbCurrentBookmark,
cbCurrentBookmark
);
if(dwStatus == ERROR_NO_DATA)
{
// record already deleted
dwStatus = ERROR_SUCCESS;
}
else
{
TLSASSERT(dwStatus == ERROR_SUCCESS);
}
}
}
else
{
UpdateNextJobTime(dwTime);
}
}
else
{
SetLastError(dwStatus = SET_JB_ERROR(pTable->GetLastJetError()));
pTable->RollbackTransaction();
TLSASSERT(FALSE);
}
cleanup:
m_hTableLock.UnLock();
if(pbCurrentBookmark != NULL)
{
FreeMemory(pbCurrentBookmark);
}
//
// WORKITEMRECORD will try to cleanup memory
//
item.pbData = NULL;
item.cbData = 0;
return dwStatus == ERROR_SUCCESS;
}
//----------------------------------------------------
//
BOOL
CPersistentWorkStorage::AddJob(
IN DWORD dwTime,
IN CWorkObject* ptr
)
/*++
--*/
{
DWORD dwStatus = ERROR_SUCCESS;
BOOL bSuccess = TRUE;
PBYTE pbData;
DWORD cbData;
DBGPrintf(
DBG_INFORMATION,
DBG_FACILITY_WORKMGR,
DBGLEVEL_FUNCTION_TRACE,
_TEXT("CPersistentWorkStorage::AddJob() scheduling job %s at time %d\n"),
ptr->GetJobDescription(),
dwTime
);
if(IsValidWorkObject(ptr) == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_PARAMETER);
goto cleanup;
}
bSuccess = ptr->GetWorkObjectData(&pbData, &cbData);
if(bSuccess == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_PARAMETER);
goto cleanup;
}
m_hTableLock.Lock();
if(m_pWkItemTable != NULL)
{
bSuccess = UpdateWorkItemEntry(
m_pWkItemTable,
WORKITEM_ADD,
NULL,
0,
ptr->GetJobRestartTime(),
dwTime + time(NULL),
ptr->GetWorkType(),
pbData,
cbData
);
if(bSuccess == FALSE)
{
dwStatus = GetLastError();
}
}
m_hTableLock.UnLock();
cleanup:
// Let Calling function delete it.
// DeleteWorkObject(ptr);
return dwStatus == ERROR_SUCCESS;
}
//----------------------------------------------------
//
BOOL
CPersistentWorkStorage::RescheduleJob(
CWorkObject* ptr
)
/*++
--*/
{
BOOL bSuccess = TRUE;
DWORD dwStatus = ERROR_SUCCESS;
PBYTE pbData;
DWORD cbData;
PBYTE pbBookmark;
DWORD cbBookmark;
DWORD dwTime;
DWORD dwJobType;
DBGPrintf(
DBG_INFORMATION,
DBG_FACILITY_WORKMGR,
DBGLEVEL_FUNCTION_TRACE,
_TEXT("CPersistentWorkStorage::RescheduleJob() scheduling job %s\n"),
ptr->GetJobDescription()
);
if(IsValidWorkObject(ptr) == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_PARAMETER);
goto cleanup;
}
bSuccess = ptr->GetWorkObjectData(&pbData, &cbData);
if(bSuccess == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_DATA);
goto cleanup;
}
bSuccess = ptr->GetJobId(&pbBookmark, &cbBookmark);
if(bSuccess == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_DATA);
goto cleanup;
}
dwTime = ptr->GetSuggestedScheduledTime();
dwJobType = ptr->GetWorkType();
m_hTableLock.Lock();
if(m_pWkItemTable != NULL)
{
bSuccess = UpdateWorkItemEntry(
m_pWkItemTable,
(dwTime == INFINITE) ? WORKITEM_DELETE : WORKITEM_RESCHEDULE,
pbBookmark,
cbBookmark,
ptr->GetJobRestartTime(),
(dwTime == INFINITE) ? dwTime : dwTime + time(NULL),
dwJobType,
pbData,
cbData
);
if(bSuccess == FALSE)
{
dwStatus = GetLastError();
}
}
m_hTableLock.UnLock();
cleanup:
DeleteWorkObject(ptr);
return dwStatus == ERROR_SUCCESS;
}
//----------------------------------------------------
//
CLASS_PRIVATE DWORD
CPersistentWorkStorage::FindNextJob()
{
DWORD dwStatus = ERROR_SUCCESS;
BOOL bSuccess = TRUE;
CWorkObject* ptr = NULL;
JET_ERR jetErrCode;
PBYTE pbBookmark = NULL;
DWORD cbBookmark = 0;
m_hTableLock.Lock();
while(dwStatus == ERROR_SUCCESS)
{
WORKITEMRECORD wkItem;
// move the record pointer
bSuccess = m_pWkItemTable->MoveToRecord();
if(bSuccess == FALSE)
{
jetErrCode = m_pWkItemTable->GetLastJetError();
if(jetErrCode == JET_errNoCurrentRecord)
{
// end of table
UpdateNextJobTime(INFINITE);
SetLastError(dwStatus = ERROR_NO_DATA);
continue;
}
}
//
// fetch the record
//
bSuccess = m_pWkItemTable->FetchRecord(wkItem);
if(bSuccess == FALSE)
{
SetLastError(dwStatus = SET_JB_ERROR(m_pWkItemTable->GetLastJetError()));
continue;
}
if(wkItem.dwJobType & WORKTYPE_PROCESSING)
{
// job is been processed, move to next one.
continue;
}
dwStatus = GetCurrentBookmarkEx(
m_pWkItemTable,
&pbBookmark,
&cbBookmark
);
if(dwStatus != ERROR_SUCCESS)
{
// Error...
TLSASSERT(dwStatus == ERROR_SUCCESS);
UpdateNextJobTime(INFINITE);
break;
}
if(wkItem.dwScheduledTime > m_dwStartupTime)
{
if(pbBookmark != NULL && cbBookmark != 0)
{
FreeMemory( pbBookmark );
pbBookmark = NULL;
cbBookmark = 0;
}
UpdateNextJobTime(wkItem.dwScheduledTime);
break;
}
//
// job is in queue before system startup, re-schedule
//
ptr = InitializeWorkObject(
wkItem.dwJobType,
wkItem.pbData,
wkItem.cbData
);
if(ptr == NULL)
{
if(pbBookmark != NULL && cbBookmark != 0)
{
FreeMemory( pbBookmark );
pbBookmark = NULL;
cbBookmark = 0;
}
//
// something is wrong, delete this job
// and move on to next job
//
m_pWkItemTable->DeleteRecord();
continue;
}
//
// Set Job's storage ID and re-schedule this job
//
ptr->SetJobId(pbBookmark, cbBookmark);
bSuccess = RescheduleJob(ptr);
if(bSuccess == FALSE)
{
dwStatus = GetLastError();
}
if(pbBookmark != NULL && cbBookmark != 0)
{
FreeMemory( pbBookmark );
pbBookmark = NULL;
cbBookmark = 0;
}
}
m_hTableLock.UnLock();
return dwStatus;
}
//----------------------------------------------------
//
CLASS_PRIVATE CWorkObject*
CPersistentWorkStorage::GetCurrentJob(
PDWORD pdwTime
)
/*++
--*/
{
DWORD dwStatus = ERROR_SUCCESS;
BOOL bSuccess = TRUE;
WORKITEMRECORD wkItem;
CWorkObject* ptr = NULL;
PBYTE pbBookmark=NULL;
DWORD cbBookmark=0;
TLSASSERT(IsGood() == TRUE);
m_hTableLock.Lock();
while(dwStatus == ERROR_SUCCESS)
{
//
// fetch the record
//
bSuccess = m_pWkItemTable->FetchRecord(wkItem);
TLSASSERT(bSuccess == TRUE);
//TLSASSERT(!(wkItem.dwJobType & WORKTYPE_PROCESSING));
if(bSuccess == FALSE)
{
SetLastError(dwStatus = SET_JB_ERROR(m_pWkItemTable->GetLastJetError()));
break;
}
if( wkItem.dwScheduledTime < m_dwStartupTime ||
wkItem.cbData == 0 ||
wkItem.pbData == NULL )
{
// FindNextJob() move record pointer one position down
m_pWkItemTable->MoveToRecord(JET_MovePrevious);
dwStatus = FindNextJob();
continue;
}
if( wkItem.dwJobType & WORKTYPE_PROCESSING )
{
dwStatus = FindNextJob();
continue;
}
ptr = InitializeWorkObject(
wkItem.dwJobType,
wkItem.pbData,
wkItem.cbData
);
dwStatus = GetCurrentBookmarkEx(
m_pWkItemTable,
&pbBookmark,
&cbBookmark
);
if(dwStatus != ERROR_SUCCESS)
{
// something is wrong, free up memory
// and exit.
SetLastError(dwStatus);
// TLSASSERT(FALSE);
DeleteWorkObject(ptr);
ptr = NULL;
// grab next job
dwStatus = FindNextJob();
continue;
}
//
// Set Job's storage ID
//
ptr->SetJobId(pbBookmark, cbBookmark);
//ptr->SetScheduledTime(wkItem.dwScheduledTime);
*pdwTime = wkItem.dwScheduledTime;
if(pbBookmark != NULL && cbBookmark != 0)
{
FreeMemory( pbBookmark );
pbBookmark = NULL;
cbBookmark = 0;
}
break;
}
m_hTableLock.UnLock();
return ptr;
}
//-----------------------------------------------------
//
DWORD
CPersistentWorkStorage::GetNextJobTime()
{
DWORD dwTime;
dwTime = (DWORD)m_dwNextJobTime;
return dwTime;
}
//-----------------------------------------------------
//
CWorkObject*
CPersistentWorkStorage::GetNextJob(
PDWORD pdwTime
)
/*++
--*/
{
CWorkObject* ptr = NULL;
if((DWORD)m_dwNextJobTime != INFINITE)
{
m_hTableLock.Lock();
//
// Fetch record where current bookmark points to,
// it is possible that new job arrived after
// WorkManager already calls GetNextJobTime(),
// this is OK since in this case this new job
// needs immediate processing.
//
ptr = GetCurrentJob(pdwTime);
//
// reposition current record pointer
//
FindNextJob();
m_hTableLock.UnLock();
}
return ptr;
}
//-----------------------------------------------------
//
BOOL
CPersistentWorkStorage::ReturnJobToQueue(
IN DWORD dwTime,
IN CWorkObject* ptr
)
/*++
--*/
{
DWORD dwStatus = ERROR_SUCCESS;
PBYTE pbBookmark;
DWORD cbBookmark;
DWORD dwJobType;
PBYTE pbData;
DWORD cbData;
if(IsValidWorkObject(ptr) == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_PARAMETER);
goto cleanup;
}
if(ptr->IsWorkPersistent() == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_DATA);
TLSASSERT(FALSE);
goto cleanup;
}
if(ptr->GetWorkObjectData(&pbData, &cbData) == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_DATA);
goto cleanup;
}
if(ptr->GetJobId(&pbBookmark, &cbBookmark) == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_DATA);
goto cleanup;
}
m_hTableLock.Lock();
if(dwTime < (DWORD)m_dwNextJobTime)
{
// Position current record
dwStatus = SetCurrentBookmark(
m_pWkItemTable,
pbBookmark,
cbBookmark
);
TLSASSERT(dwStatus == ERROR_SUCCESS);
if(dwStatus == ERROR_SUCCESS)
{
UpdateNextJobTime(dwTime);
}
}
m_hTableLock.UnLock();
cleanup:
DeleteWorkObject(ptr);
return dwStatus == ERROR_SUCCESS;
}
//-----------------------------------------------------
//
BOOL
CPersistentWorkStorage::EndProcessingJob(
IN ENDPROCESSINGJOB_CODE opCode,
IN DWORD dwOriginalTime,
IN CWorkObject* ptr
)
/*++
Abstract:
Parameter:
opCode : End Processing code.
ptr : Job has completed processing or been
returned by workmanager due to time or
resource constraint.
Return:
TRUE/FALSE
--*/
{
BOOL bSuccess = TRUE;
BYTE pbData = NULL;
DWORD cbData = 0;
DBGPrintf(
DBG_INFORMATION,
DBG_FACILITY_WORKMGR,
DBGLEVEL_FUNCTION_TRACE,
_TEXT("CPersistentWorkStorage::EndProcessingJob() - end processing %s opCode %d\n"),
ptr->GetJobDescription(),
opCode
);
if(ptr == NULL)
{
bSuccess = FALSE;
SetLastError(ERROR_INVALID_PARAMETER);
goto cleanup;
}
if(ptr->IsWorkPersistent() == FALSE)
{
SetLastError(ERROR_INVALID_DATA);
TLSASSERT(FALSE);
goto cleanup;
}
switch(opCode)
{
case ENDPROCESSINGJOB_SUCCESS:
bSuccess = RescheduleJob(ptr);
m_dwJobsInProcesssing--;
break;
case ENDPROCESSINGJOB_ERROR:
bSuccess = DeleteErrorJob(ptr);
m_dwJobsInProcesssing--;
break;
case ENDPROCESSINGJOB_RETURN:
bSuccess = ReturnJobToQueue(dwOriginalTime, ptr);
break;
default:
TLSASSERT(FALSE);
}
cleanup:
return bSuccess;
}
//-------------------------------------------------------
//
BOOL
CPersistentWorkStorage::BeginProcessingJob(
IN CWorkObject* ptr
)
/*++
Abstract:
Work Manager call this to inform. storage that
this job is about to be processed.
Parameter:
ptr - Job to be process.
Return:
TRUE/FALSE
--*/
{
BOOL bSuccess = TRUE;
DWORD dwStatus = ERROR_SUCCESS;
PBYTE pbBookmark;
DWORD cbBookmark;
DWORD dwTime;
PBYTE pbData;
DWORD cbData;
DBGPrintf(
DBG_INFORMATION,
DBG_FACILITY_WORKMGR,
DBGLEVEL_FUNCTION_TRACE,
_TEXT("CPersistentWorkStorage::BeginProcessingJob() - beginning processing %s\n"),
ptr->GetJobDescription()
);
if(IsValidWorkObject(ptr) == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_PARAMETER);
goto cleanup;
}
if(ptr->IsWorkPersistent() == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_DATA);
TLSASSERT(FALSE);
goto cleanup;
}
bSuccess = ptr->GetWorkObjectData(&pbData, &cbData);
if(bSuccess == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_DATA);
goto cleanup;
}
bSuccess = ptr->GetJobId(&pbBookmark, &cbBookmark);
if(bSuccess == FALSE)
{
SetLastError(dwStatus = ERROR_INVALID_DATA);
goto cleanup;
}
m_hTableLock.Lock();
bSuccess = UpdateWorkItemEntry(
m_pWkItemTable,
WORKITEM_BEGINPROCESSING,
pbBookmark,
cbBookmark,
ptr->GetJobRestartTime(),
ptr->GetScheduledTime(),
ptr->GetWorkType(),
pbData,
cbData
);
if(bSuccess == TRUE)
{
m_dwJobsInProcesssing ++;
}
else
{
dwStatus = GetLastError();
}
m_hTableLock.UnLock();
cleanup:
return dwStatus == ERROR_SUCCESS;
}
|
alcidesrh/tour-agency | vue-app/store/modules/destination/index.js | import list from './list';
import create from './create';
import del from './delete';
import update from './update';
export default {
namespaced: true,
modules: {
list,
create,
del,
update
}
}
|
PuercoPop/maiko | src/byteswap.c | /* $Id: byteswap.c,v 1.5 2002/01/02 08:15:16 sybalsky Exp $ (C) Copyright Venue, All Rights Reserved
*/
static char *id = "$Id: byteswap.c,v 1.5 2002/01/02 08:15:16 sybalsky Exp $ Copyright (C) Venue";
/************************************************************************/
/* */
/* (C) Copyright 1989-95 Venue. All Rights Reserved. */
/* Manufactured in the United States of America. */
/* */
/************************************************************************/
#include "version.h"
/***************************************************************************/
/* */
/* byteswap.c */
/* */
/* Support functions for byte-swapped architecture machines */
/* (e.g., 80386's) */
/* */
/***************************************************************************/
#include "hdw_conf.h"
#include "lispemul.h"
#include "lispmap.h"
#include "lsptypes.h"
#include "stack.h"
#include "byteswapdefs.h"
#if defined(ISC)
#include "inlnPS2.h"
#else
/****************************************************************/
/* */
/* swap halves of a single 4-byte word */
/* */
/****************************************************************/
unsigned int swapx(unsigned int word) {
return (((word >> 16) & 0xffff) | ((word & 0xffff) << 16));
}
/****************************************************************/
/* */
/* Byte-swap a single 2-byte word */
/* */
/****************************************************************/
unsigned short byte_swap_word(unsigned short word) {
return (((word >> 8) & 0xff) | ((word & 0xff) << 8));
}
/****************************************************************/
/* */
/* Word-swap a 2-word integer */
/* Does NOT byte-swap the words themselves. */
/* */
/****************************************************************/
/***
unsigned int word_swap_longword(word)
unsigned int word;
{
return( ((word>>16)&0xffff)+((word&0xffff)<<16) );
} ***/
#ifndef I386
#define word_swap_longword(word) (((word >> 16) & 0xffff) | ((word & 0xffff) << 16))
#endif
#endif /* !ISC */
/****************************************************************/
/* */
/* Byte-swap a region wordcount words long */
/* This does NOT swap words in a long-word! */
/* */
/****************************************************************/
void byte_swap_page(unsigned short *page, int wordcount) {
int i;
for (i = 0; i < wordcount; i++) { *(page + i) = byte_swap_word(*(page + i)); }
}
#ifndef GCC386
/****************************************************************/
/* */
/* Byte- & word-swap a region wordcount long-words long */
/* */
/****************************************************************/
void word_swap_page(unsigned short *page, int longwordcount) {
register int i;
register unsigned int *longpage;
longpage = (unsigned int *)page;
for (i = 0; i < (longwordcount + longwordcount); i++) {
*(page + i) = byte_swap_word(*(page + i));
}
for (i = 0; i < longwordcount; i++) { *(longpage + i) = word_swap_longword(*(longpage + i)); }
}
#endif /* GCC386 */
/****************************************************************/
/* */
/* Bit-reverse all the words in a region */
/* */
/****************************************************************/
unsigned char reversedbits[256] = {
/* table of bytes with their bits reversed */
0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff,
};
/*unsigned short reverse_bits(word)
unsigned short word;
{
return ((reversedbits[(word>>8) & 0xFF] <<8) | reversedbits[word & 0xff]);
}
******/
#define reverse_bits(word) ((reversedbits[((word) >> 8) & 0xFF] << 8) | reversedbits[(word)&0xff])
void bit_reverse_region(unsigned short *top, int width, int height, int rasterwidth) {
register int i, j, wordwid = ((width + 31) >> 5) << 1;
register unsigned short *word;
for (i = 0; i < height; i++) {
word = top;
for (j = 0; j < wordwid; j++) { GETWORD(word + j) = reverse_bits(GETWORD(word + j)); }
word_swap_page((unsigned short *)((UNSIGNED)word & 0xFFFFFFFE), (wordwid + 1) >> 1);
top += rasterwidth;
}
}
/************************************************************************/
/* */
/* b y t e _ s w a p _ c o d e _ b l o c k */
/* */
/* Byte-swap the opcodes in a piece of compiled code. This */
/* can be used to make the compiled bytes be in machine-natural */
/* order, so we can avoid pointer arithmetic on the PC in the */
/* inner loop. The performance effect isn't yet known (2/92) */
/* */
/************************************************************************/
#ifdef RESWAPPEDDCODESTREAM
unsigned int byte_swap_code_block(unsigned int *base) {
UNSIGNED startpc, len;
startpc = ((UNSIGNED)base) + ((struct fnhead *)base)->startpc;
len = code_block_size(base);
word_swap_page((unsigned short *)startpc, (len + 3) >> 2);
return (UNSIGNED)base;
} /* end of byte_swap_code_block */
#endif /* RESWAPPEDCODESTREAM */
|
ahsai001/zlcore | zlcore/src/main/java/com/zaitunlabs/zlcore/views/ASShiftableImageView.java | <reponame>ahsai001/zlcore
package com.zaitunlabs.zlcore.views;
import android.graphics.Rect;
import android.view.ViewGroup;
import android.widget.ImageView.ScaleType;
public class ASShiftableImageView {
CanvasSection section = null;
ASImageView iv = null;
private boolean isSticky = false;
private boolean isLocked = false;
public ASShiftableImageView() {
}
public ASImageView getImageView(){
return iv;
}
public static ASShiftableImageView create(ViewGroup parent, int left, int top, int width, int height){
return create(parent,left,top, width, height,false, false);
}
public void setPositionLocked(boolean isLocked){
this.isLocked = isLocked;
}
public void setPositionToOrigin(boolean animate){
section.getShiftPositionHandler().changeStateToDimension(0,animate);
}
public void setPositionToNearest(boolean animate){
section.getShiftPositionHandler().changeStateToNearestDimension(animate);
}
public void setPositionToRect(Rect dimension, boolean animate){
section.getShiftPositionHandler().changeStateToCustomDimension(dimension,10,animate);
}
public static ASShiftableImageView create(ViewGroup parent, int left, int top, int width, int height, boolean isSticky, boolean isLocked){
final ASShiftableImageView shiftableImageView = new ASShiftableImageView();
if(parent instanceof CanvasLayout)
shiftableImageView.section = ((CanvasLayout)parent).createNewSectionWithFrame(left, top, width, height, true);
else if(parent instanceof CanvasSection)
shiftableImageView.section = ((CanvasSection)parent).addSubSectionWithFrame(left, top, width, height, true);
shiftableImageView.iv = new ASImageView(parent.getContext());
shiftableImageView.iv.setScaleType(ScaleType.FIT_XY);
shiftableImageView.iv.setAdjustViewBounds(true);
shiftableImageView.section.addViewWithFrame(shiftableImageView.iv, 0, 0, 100, 100);
shiftableImageView.isSticky = isSticky;
shiftableImageView.isLocked = isLocked;
shiftableImageView.section.getShiftPositionHandler().addRectToDimensionState(left, top, width, height);
shiftableImageView.section.getShiftPositionHandler().addRectToDimensionState(0, 0, width, height);
shiftableImageView.section.getShiftPositionHandler().addRectToDimensionState(0, 100-height, width, height);
shiftableImageView.section.getShiftPositionHandler().addRectToDimensionState(100-width, 100-height, width, height);
shiftableImageView.section.getShiftPositionHandler().addRectToDimensionState(100-width, 0, width, height);
shiftableImageView.iv.setASGestureListener(new ASGestureListener() {
@Override
public boolean upEventOccurred(float x, float y) {
if (shiftableImageView.isSticky) {
shiftableImageView.section.getShiftPositionHandler().changeStateToNearestDimension(true);
}
return true;
}
@Override
public boolean downEventOccured(float x, float y) {
return true;
}
@Override
public boolean deltaMoveOutsideParameter(int swipeType, float x,
float y, float dx, float dy, float fromDownDX, float fromDownDY) {
if (!shiftableImageView.isLocked) {
shiftableImageView.section.getShiftPositionHandler().shiftViewWithDelta(dx, dy, fromDownDX, fromDownDY);
}
return true;
}
@Override
public boolean deltaMoveInsideParameter(int swipeType, float x,
float y, float dx, float dy, float fromDownDX, float fromDownDY) {
if (!shiftableImageView.isLocked) {
shiftableImageView.section.getShiftPositionHandler().shiftViewWithDelta(dx, dy, fromDownDX, fromDownDY);
}
return true;
}
@Override
public boolean movingSpeed(float xSpeed, float ySpeed) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean cancelEventOccured(float x, float y) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean clickEventOccured() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean longClickEventOccured() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isClickEnabled() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isLongClickEnabled() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean doubleTapEventOccured() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isDoubleTapEnabled() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean swipeEventOccured(int swipeType, float x, float y,
float dx, float dy) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean swipeTypeFinal(int swipeType) {
return false;
}
@Override
public boolean isSwipeEnabled() {
// TODO Auto-generated method stub
return false;
}
});
return shiftableImageView;
}
}
|
EdwardPrentice/wrongo | jstests/repl/repl4.js | <reponame>EdwardPrentice/wrongo
// Test replication 'only' mode
soonCount = function(db, coll, count) {
assert.soon(function() {
return s.getDB(db)[coll].find().count() == count;
});
};
doTest = function() {
rt = new ReplTest("repl4tests");
m = rt.start(true);
s = rt.start(false, {only: "c"});
cm = m.getDB("c").c;
bm = m.getDB("b").b;
cm.save({x: 1});
bm.save({x: 2});
soonCount("c", "c", 1);
assert.eq(1, s.getDB("c").c.findOne().x);
sleep(10000);
printjson(s.getDBNames());
assert.eq(-1, s.getDBNames().indexOf("b"));
assert.eq(0, s.getDB("b").b.find().count());
rt.stop(false);
cm.save({x: 3});
bm.save({x: 4});
s = rt.start(false, {only: "c"}, true);
soonCount("c", "c", 2);
};
// Disabled because of SERVER-10344
if (false) {
doTest();
}
|
CaptEmulation/modeldb | protos/gen/go/protos/public/uac/Workspace.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: uac/Workspace.proto
package uac
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
_ "google.golang.org/genproto/googleapis/api/annotations"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
type GetWorkspaceById struct {
Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *GetWorkspaceById) Reset() { *m = GetWorkspaceById{} }
func (m *GetWorkspaceById) String() string { return proto.CompactTextString(m) }
func (*GetWorkspaceById) ProtoMessage() {}
func (*GetWorkspaceById) Descriptor() ([]byte, []int) {
return fileDescriptor_fa02a41bd20f6ea6, []int{0}
}
func (m *GetWorkspaceById) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GetWorkspaceById.Unmarshal(m, b)
}
func (m *GetWorkspaceById) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GetWorkspaceById.Marshal(b, m, deterministic)
}
func (m *GetWorkspaceById) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetWorkspaceById.Merge(m, src)
}
func (m *GetWorkspaceById) XXX_Size() int {
return xxx_messageInfo_GetWorkspaceById.Size(m)
}
func (m *GetWorkspaceById) XXX_DiscardUnknown() {
xxx_messageInfo_GetWorkspaceById.DiscardUnknown(m)
}
var xxx_messageInfo_GetWorkspaceById proto.InternalMessageInfo
func (m *GetWorkspaceById) GetId() uint64 {
if m != nil {
return m.Id
}
return 0
}
type GetWorkspaceByName struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *GetWorkspaceByName) Reset() { *m = GetWorkspaceByName{} }
func (m *GetWorkspaceByName) String() string { return proto.CompactTextString(m) }
func (*GetWorkspaceByName) ProtoMessage() {}
func (*GetWorkspaceByName) Descriptor() ([]byte, []int) {
return fileDescriptor_fa02a41bd20f6ea6, []int{1}
}
func (m *GetWorkspaceByName) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GetWorkspaceByName.Unmarshal(m, b)
}
func (m *GetWorkspaceByName) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GetWorkspaceByName.Marshal(b, m, deterministic)
}
func (m *GetWorkspaceByName) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetWorkspaceByName.Merge(m, src)
}
func (m *GetWorkspaceByName) XXX_Size() int {
return xxx_messageInfo_GetWorkspaceByName.Size(m)
}
func (m *GetWorkspaceByName) XXX_DiscardUnknown() {
xxx_messageInfo_GetWorkspaceByName.DiscardUnknown(m)
}
var xxx_messageInfo_GetWorkspaceByName proto.InternalMessageInfo
func (m *GetWorkspaceByName) GetName() string {
if m != nil {
return m.Name
}
return ""
}
type Workspace struct {
Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
// Types that are valid to be assigned to InternalId:
// *Workspace_UserId
// *Workspace_OrgId
InternalId isWorkspace_InternalId `protobuf_oneof:"internal_id"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Workspace) Reset() { *m = Workspace{} }
func (m *Workspace) String() string { return proto.CompactTextString(m) }
func (*Workspace) ProtoMessage() {}
func (*Workspace) Descriptor() ([]byte, []int) {
return fileDescriptor_fa02a41bd20f6ea6, []int{2}
}
func (m *Workspace) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Workspace.Unmarshal(m, b)
}
func (m *Workspace) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Workspace.Marshal(b, m, deterministic)
}
func (m *Workspace) XXX_Merge(src proto.Message) {
xxx_messageInfo_Workspace.Merge(m, src)
}
func (m *Workspace) XXX_Size() int {
return xxx_messageInfo_Workspace.Size(m)
}
func (m *Workspace) XXX_DiscardUnknown() {
xxx_messageInfo_Workspace.DiscardUnknown(m)
}
var xxx_messageInfo_Workspace proto.InternalMessageInfo
func (m *Workspace) GetId() uint64 {
if m != nil {
return m.Id
}
return 0
}
type isWorkspace_InternalId interface {
isWorkspace_InternalId()
}
type Workspace_UserId struct {
UserId string `protobuf:"bytes,2,opt,name=user_id,json=userId,proto3,oneof"`
}
type Workspace_OrgId struct {
OrgId string `protobuf:"bytes,3,opt,name=org_id,json=orgId,proto3,oneof"`
}
func (*Workspace_UserId) isWorkspace_InternalId() {}
func (*Workspace_OrgId) isWorkspace_InternalId() {}
func (m *Workspace) GetInternalId() isWorkspace_InternalId {
if m != nil {
return m.InternalId
}
return nil
}
func (m *Workspace) GetUserId() string {
if x, ok := m.GetInternalId().(*Workspace_UserId); ok {
return x.UserId
}
return ""
}
func (m *Workspace) GetOrgId() string {
if x, ok := m.GetInternalId().(*Workspace_OrgId); ok {
return x.OrgId
}
return ""
}
// XXX_OneofWrappers is for the internal use of the proto package.
func (*Workspace) XXX_OneofWrappers() []interface{} {
return []interface{}{
(*Workspace_UserId)(nil),
(*Workspace_OrgId)(nil),
}
}
func init() {
proto.RegisterType((*GetWorkspaceById)(nil), "ai.verta.uac.GetWorkspaceById")
proto.RegisterType((*GetWorkspaceByName)(nil), "ai.verta.uac.GetWorkspaceByName")
proto.RegisterType((*Workspace)(nil), "ai.verta.uac.Workspace")
}
func init() {
proto.RegisterFile("uac/Workspace.proto", fileDescriptor_fa02a41bd20f6ea6)
}
var fileDescriptor_fa02a41bd20f6ea6 = []byte{
// 328 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0x4f, 0x4b, 0xc3, 0x30,
0x18, 0xc6, 0x5d, 0x9d, 0x93, 0xc5, 0x3f, 0x8c, 0x78, 0xd8, 0x1c, 0x32, 0x4a, 0x0f, 0xb2, 0x53,
0x83, 0x7a, 0xf3, 0x20, 0xb8, 0x8b, 0xf6, 0x22, 0x32, 0x41, 0xc1, 0x83, 0x23, 0x4d, 0x5e, 0x62,
0xb0, 0xcd, 0x5b, 0xd2, 0x74, 0xb2, 0xeb, 0xbe, 0x82, 0x1f, 0xcd, 0xaf, 0xe0, 0x07, 0x91, 0x56,
0x57, 0xdc, 0x86, 0xbb, 0x25, 0xcf, 0xf3, 0xe4, 0xf9, 0xf1, 0xbe, 0x21, 0x47, 0x05, 0x17, 0xec,
0x09, 0xed, 0x5b, 0x9e, 0x71, 0x01, 0x61, 0x66, 0xd1, 0x21, 0xdd, 0xe7, 0x3a, 0x9c, 0x82, 0x75,
0x3c, 0x2c, 0xb8, 0xe8, 0x9f, 0x28, 0x44, 0x95, 0x00, 0xe3, 0x99, 0x66, 0xdc, 0x18, 0x74, 0xdc,
0x69, 0x34, 0xf9, 0x4f, 0x36, 0x08, 0x48, 0xe7, 0x06, 0x5c, 0xdd, 0x30, 0x9a, 0x45, 0x92, 0x1e,
0x12, 0x4f, 0xcb, 0x5e, 0xc3, 0x6f, 0x0c, 0x9b, 0x63, 0x4f, 0xcb, 0x60, 0x48, 0xe8, 0x72, 0xe6,
0x8e, 0xa7, 0x40, 0x29, 0x69, 0x1a, 0x9e, 0x42, 0x95, 0x6b, 0x8f, 0xab, 0x73, 0xf0, 0x42, 0xda,
0x75, 0x6c, 0xb5, 0x86, 0x1e, 0x93, 0xdd, 0x22, 0x07, 0x3b, 0xd1, 0xb2, 0xe7, 0x95, 0x6f, 0x6e,
0xb7, 0xc6, 0xad, 0x52, 0x88, 0x24, 0xed, 0x92, 0x16, 0x5a, 0x55, 0x3a, 0xdb, 0xbf, 0xce, 0x0e,
0x5a, 0x15, 0xc9, 0xd1, 0x01, 0xd9, 0xd3, 0xc6, 0x81, 0x35, 0x3c, 0x99, 0x68, 0x79, 0x3e, 0xf7,
0x48, 0xa7, 0x06, 0x3c, 0x80, 0x9d, 0x6a, 0x01, 0x34, 0x27, 0x1d, 0xb5, 0x3a, 0xc2, 0x20, 0xfc,
0xbb, 0x83, 0x70, 0x75, 0xc4, 0x7e, 0x77, 0xd9, 0xaf, 0xcd, 0xe0, 0x74, 0xfe, 0xf9, 0xf5, 0xe1,
0xf9, 0x74, 0xc0, 0xa6, 0x67, 0xec, 0x7d, 0x21, 0xb3, 0x35, 0xc0, 0x8c, 0x50, 0xb5, 0xbe, 0x13,
0x7f, 0x13, 0xb6, 0x4c, 0xfc, 0x0f, 0x1e, 0x56, 0xe0, 0x80, 0xfa, 0x9b, 0xc0, 0x65, 0xc5, 0xe8,
0xea, 0xbe, 0xf1, 0x7c, 0xa9, 0xb4, 0x7b, 0x2d, 0xe2, 0x50, 0x60, 0xca, 0x1e, 0xcb, 0xb6, 0xeb,
0x88, 0xa5, 0x28, 0x21, 0x91, 0x31, 0xab, 0x3e, 0x36, 0x67, 0x0a, 0x0c, 0x53, 0xb8, 0xb8, 0x65,
0x45, 0x9c, 0x68, 0xc1, 0x0a, 0x2e, 0xe2, 0x56, 0x25, 0x5d, 0x7c, 0x07, 0x00, 0x00, 0xff, 0xff,
0x3f, 0x51, 0xa0, 0xa3, 0x3c, 0x02, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6
// WorkspaceServiceClient is the client API for WorkspaceService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type WorkspaceServiceClient interface {
GetWorkspaceById(ctx context.Context, in *GetWorkspaceById, opts ...grpc.CallOption) (*Workspace, error)
GetWorkspaceByName(ctx context.Context, in *GetWorkspaceByName, opts ...grpc.CallOption) (*Workspace, error)
}
type workspaceServiceClient struct {
cc grpc.ClientConnInterface
}
func NewWorkspaceServiceClient(cc grpc.ClientConnInterface) WorkspaceServiceClient {
return &workspaceServiceClient{cc}
}
func (c *workspaceServiceClient) GetWorkspaceById(ctx context.Context, in *GetWorkspaceById, opts ...grpc.CallOption) (*Workspace, error) {
out := new(Workspace)
err := c.cc.Invoke(ctx, "/ai.verta.uac.WorkspaceService/getWorkspaceById", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *workspaceServiceClient) GetWorkspaceByName(ctx context.Context, in *GetWorkspaceByName, opts ...grpc.CallOption) (*Workspace, error) {
out := new(Workspace)
err := c.cc.Invoke(ctx, "/ai.verta.uac.WorkspaceService/getWorkspaceByName", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// WorkspaceServiceServer is the server API for WorkspaceService service.
type WorkspaceServiceServer interface {
GetWorkspaceById(context.Context, *GetWorkspaceById) (*Workspace, error)
GetWorkspaceByName(context.Context, *GetWorkspaceByName) (*Workspace, error)
}
// UnimplementedWorkspaceServiceServer can be embedded to have forward compatible implementations.
type UnimplementedWorkspaceServiceServer struct {
}
func (*UnimplementedWorkspaceServiceServer) GetWorkspaceById(ctx context.Context, req *GetWorkspaceById) (*Workspace, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetWorkspaceById not implemented")
}
func (*UnimplementedWorkspaceServiceServer) GetWorkspaceByName(ctx context.Context, req *GetWorkspaceByName) (*Workspace, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetWorkspaceByName not implemented")
}
func RegisterWorkspaceServiceServer(s *grpc.Server, srv WorkspaceServiceServer) {
s.RegisterService(&_WorkspaceService_serviceDesc, srv)
}
func _WorkspaceService_GetWorkspaceById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetWorkspaceById)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(WorkspaceServiceServer).GetWorkspaceById(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ai.verta.uac.WorkspaceService/GetWorkspaceById",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(WorkspaceServiceServer).GetWorkspaceById(ctx, req.(*GetWorkspaceById))
}
return interceptor(ctx, in, info, handler)
}
func _WorkspaceService_GetWorkspaceByName_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetWorkspaceByName)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(WorkspaceServiceServer).GetWorkspaceByName(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/ai.verta.uac.WorkspaceService/GetWorkspaceByName",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(WorkspaceServiceServer).GetWorkspaceByName(ctx, req.(*GetWorkspaceByName))
}
return interceptor(ctx, in, info, handler)
}
var _WorkspaceService_serviceDesc = grpc.ServiceDesc{
ServiceName: "ai.verta.uac.WorkspaceService",
HandlerType: (*WorkspaceServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "getWorkspaceById",
Handler: _WorkspaceService_GetWorkspaceById_Handler,
},
{
MethodName: "getWorkspaceByName",
Handler: _WorkspaceService_GetWorkspaceByName_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "uac/Workspace.proto",
}
|
G-Lem/spring-cloud-stream | spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/SchemaReference.java | /*
* Copyright 2016-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.stream.schema;
import org.springframework.util.Assert;
/**
* References a schema through its subject and version.
*
* @author <NAME>
*/
public class SchemaReference {
private String subject;
private int version;
private String format;
public SchemaReference(String subject, int version, String format) {
Assert.hasText(subject, "cannot be empty");
Assert.isTrue(version > 0, "must be a positive integer");
Assert.hasText(format, "cannot be empty");
this.subject = subject;
this.version = version;
this.format = format;
}
public String getSubject() {
return this.subject;
}
public void setSubject(String subject) {
Assert.hasText(subject, "cannot be empty");
this.subject = subject;
}
public int getVersion() {
return this.version;
}
public void setVersion(int version) {
Assert.isTrue(version > 0, "must be a positive integer");
this.version = version;
}
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
Assert.hasText(format, "cannot be empty");
this.format = format;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SchemaReference that = (SchemaReference) o;
if (this.version != that.version) {
return false;
}
if (!this.subject.equals(that.subject)) {
return false;
}
return this.format.equals(that.format);
}
@Override
public int hashCode() {
int result = this.subject.hashCode();
result = 31 * result + this.version;
result = 31 * result + this.format.hashCode();
return result;
}
@Override
public String toString() {
return "SchemaReference{" + "subject='" + this.subject + '\'' + ", version="
+ this.version + ", format='" + this.format + '\'' + '}';
}
}
|
Devil0305/JSBankApp | JS-api/src/main/java/com/pukanghealth/config/WebLogAspect.java | <reponame>Devil0305/JSBankApp
package com.pukanghealth.config;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* @author liukang
* 切面类
*/
@Aspect
@Component
public class WebLogAspect {
private final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
//切入点描述
@Pointcut("execution(public * com.pukanghealth.controller..*.*(..))")
/**
* 签名 切入点的一个名称
*/
public void controllerLog() {
}
@Before("controllerLog()")
public void logBeforeController(JoinPoint joinPoint) {
//RequestContextHolder SpingMvc提供给获取请求的东西
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
//请求内容
logger.info("################URL : " + request.getRequestURI());
logger.info("################HTTP_METHOD : " + request.getMethod());
logger.info("################IP : " + request.getRemoteAddr());
logger.info("################THE ARGS OF THE CONTROLLER : " + Arrays.toString(joinPoint.getArgs()));
//getSignature().getDeclaringTypeName()是获取包+类名的 然后后面的joinPoint.getSignature.getName()获取了方法名
logger.info("################CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
}
}
|
pradyumnasagar/jvarkit | src/test/java/com/github/lindenb/jvarkit/tools/biostar/Biostar77288Test.java | <gh_stars>1-10
package com.github.lindenb.jvarkit.tools.biostar;
import java.io.File;
import java.io.IOException;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.github.lindenb.jvarkit.tools.tests.TestUtils;
public class Biostar77288Test extends TestUtils {
@DataProvider(name = "src1")
public Object[][] createData1() {
return new Object[][]{
{"http://www.tcoffee.org/Courses/Exercises/saragosa_pb_2010/practicals/practical_2/ex.1.19/file/clustalw.msa"}
};
}
@Test(dataProvider="src1")
public void test01(final String url) throws IOException {
final File out = createTmpFile(".svg");
Assert.assertEquals(
new Biostar77288().instanceMain(newCmd().
add("-o").add(out).add(url).make()
),0);
assertIsXml(out);
}
}
|
juntoscomvc/juntos.com.vc | app/services/recurring_contribution/subscriptions/create.rb | <gh_stars>0
class RecurringContribution::Subscriptions::Create
def initialize(juntos_subscription)
@juntos_subscription = juntos_subscription
end
def self.process(juntos_subscription)
new(juntos_subscription).process
end
def process
pagarme_response = create_subscription_on_pagarme
update_juntos_subscription(pagarme_response)
end
private
attr_reader :juntos_subscription
def create_subscription_on_pagarme
RecurringContribution::Subscriptions::CreatePagarme.new(juntos_subscription).process
end
def update_juntos_subscription(pagarme_response)
juntos_subscription_service(juntos_subscription, pagarme_response).process
end
def juntos_subscription_service(juntos_subscription, pagarme_response)
RecurringContribution::Subscriptions::UpdateJuntos.new(juntos_subscription, pagarme_response)
end
end
|
SariskaIO/sariska-media-transport | dist/esm/service/RTC/MediaType.js | <filename>dist/esm/service/RTC/MediaType.js
export var MediaType;
(function (MediaType) {
/**
* The audio type.
*/
MediaType["AUDIO"] = "audio";
/**
* The presenter type.
*/
MediaType["PRESENTER"] = "presenter";
/**
* The video type.
*/
MediaType["VIDEO"] = "video";
})(MediaType || (MediaType = {}));
|
alchemy315/NoPFS | torch-test/mpich-3.4.3/modules/yaksa/src/backend/cuda/hooks/yaksuri_cuda_init_hooks.c | /*
* Copyright (C) by Argonne National Laboratory
* See COPYRIGHT in top-level directory
*/
#include "yaksi.h"
#include "yaksuri_cudai.h"
#include <assert.h>
#include <string.h>
#include <cuda.h>
#include <cuda_runtime_api.h>
static void *cuda_host_malloc(uintptr_t size)
{
void *ptr = NULL;
cudaError_t cerr = cudaMallocHost(&ptr, size);
YAKSURI_CUDAI_CUDA_ERR_CHECK(cerr);
return ptr;
}
static void *cuda_gpu_malloc(uintptr_t size, int device)
{
void *ptr = NULL;
cudaError_t cerr;
int cur_device;
cerr = cudaGetDevice(&cur_device);
YAKSURI_CUDAI_CUDA_ERR_CHECK(cerr);
if (cur_device != device) {
cerr = cudaSetDevice(device);
YAKSURI_CUDAI_CUDA_ERR_CHECK(cerr);
}
cerr = cudaMalloc(&ptr, size);
YAKSURI_CUDAI_CUDA_ERR_CHECK(cerr);
if (cur_device != device) {
cerr = cudaSetDevice(cur_device);
YAKSURI_CUDAI_CUDA_ERR_CHECK(cerr);
}
return ptr;
}
static void cuda_host_free(void *ptr)
{
cudaError_t cerr = cudaFreeHost(ptr);
YAKSURI_CUDAI_CUDA_ERR_CHECK(cerr);
}
static void cuda_gpu_free(void *ptr)
{
cudaError_t cerr = cudaFree(ptr);
YAKSURI_CUDAI_CUDA_ERR_CHECK(cerr);
}
yaksuri_cudai_global_s yaksuri_cudai_global;
static int finalize_hook(void)
{
int rc = YAKSA_SUCCESS;
cudaError_t cerr;
for (int i = 0; i < yaksuri_cudai_global.ndevices; i++) {
cerr = cudaSetDevice(i);
YAKSURI_CUDAI_CUDA_ERR_CHKANDJUMP(cerr, rc, fn_fail);
cerr = cudaStreamDestroy(yaksuri_cudai_global.stream[i]);
YAKSURI_CUDAI_CUDA_ERR_CHKANDJUMP(cerr, rc, fn_fail);
free(yaksuri_cudai_global.p2p[i]);
}
free(yaksuri_cudai_global.stream);
free(yaksuri_cudai_global.p2p);
fn_exit:
return rc;
fn_fail:
goto fn_exit;
}
static int get_num_devices(int *ndevices)
{
*ndevices = yaksuri_cudai_global.ndevices;
return YAKSA_SUCCESS;
}
static int check_p2p_comm(int sdev, int ddev, bool * is_enabled)
{
#if CUDA_P2P == CUDA_P2P_ENABLED
*is_enabled = yaksuri_cudai_global.p2p[sdev][ddev];
#elif CUDA_P2P == CUDA_P2P_CLIQUES
if ((sdev + ddev) % 2)
*is_enabled = 0;
else
*is_enabled = yaksuri_cudai_global.p2p[sdev][ddev];
#else
*is_enabled = 0;
#endif
return YAKSA_SUCCESS;
}
int yaksuri_cuda_init_hook(yaksur_gpudriver_hooks_s ** hooks)
{
int rc = YAKSA_SUCCESS;
cudaError_t cerr;
cerr = cudaGetDeviceCount(&yaksuri_cudai_global.ndevices);
YAKSURI_CUDAI_CUDA_ERR_CHKANDJUMP(cerr, rc, fn_fail);
if (getenv("CUDA_VISIBLE_DEVICES") == NULL) {
/* user did not do any filtering for us; if any of the devices
* is in exclusive mode, disable GPU support to avoid
* incorrect device sharing */
bool excl = false;
for (int i = 0; i < yaksuri_cudai_global.ndevices; i++) {
struct cudaDeviceProp prop;
cerr = cudaGetDeviceProperties(&prop, i);
YAKSURI_CUDAI_CUDA_ERR_CHKANDJUMP(cerr, rc, fn_fail);
if (prop.computeMode != cudaComputeModeDefault) {
excl = true;
break;
}
}
if (excl == true) {
fprintf(stderr, "[yaksa] ====> Disabling CUDA support <====\n");
fprintf(stderr,
"[yaksa] CUDA is setup in exclusive compute mode, but CUDA_VISIBLE_DEVICES is not set\n");
fprintf(stderr,
"[yaksa] You can silence this warning by setting CUDA_VISIBLE_DEVICES\n");
fflush(stderr);
*hooks = NULL;
goto fn_exit;
}
}
yaksuri_cudai_global.stream = (cudaStream_t *)
malloc(yaksuri_cudai_global.ndevices * sizeof(cudaStream_t));
yaksuri_cudai_global.p2p = (bool **) malloc(yaksuri_cudai_global.ndevices * sizeof(bool *));
for (int i = 0; i < yaksuri_cudai_global.ndevices; i++) {
yaksuri_cudai_global.p2p[i] = (bool *) malloc(yaksuri_cudai_global.ndevices * sizeof(bool));
}
int cur_device;
cerr = cudaGetDevice(&cur_device);
YAKSURI_CUDAI_CUDA_ERR_CHKANDJUMP(cerr, rc, fn_fail);
for (int i = 0; i < yaksuri_cudai_global.ndevices; i++) {
cerr = cudaSetDevice(i);
YAKSURI_CUDAI_CUDA_ERR_CHKANDJUMP(cerr, rc, fn_fail);
cerr = cudaStreamCreateWithFlags(&yaksuri_cudai_global.stream[i], cudaStreamNonBlocking);
YAKSURI_CUDAI_CUDA_ERR_CHKANDJUMP(cerr, rc, fn_fail);
for (int j = 0; j < yaksuri_cudai_global.ndevices; j++) {
if (i == j) {
yaksuri_cudai_global.p2p[i][j] = 1;
} else {
int val;
cerr = cudaDeviceCanAccessPeer(&val, i, j);
YAKSURI_CUDAI_CUDA_ERR_CHKANDJUMP(cerr, rc, fn_fail);
if (val) {
cerr = cudaDeviceEnablePeerAccess(j, 0);
if (cerr != cudaErrorPeerAccessAlreadyEnabled) {
YAKSURI_CUDAI_CUDA_ERR_CHKANDJUMP(cerr, rc, fn_fail);
}
yaksuri_cudai_global.p2p[i][j] = 1;
} else {
yaksuri_cudai_global.p2p[i][j] = 0;
}
}
}
}
cerr = cudaSetDevice(cur_device);
YAKSURI_CUDAI_CUDA_ERR_CHKANDJUMP(cerr, rc, fn_fail);
*hooks = (yaksur_gpudriver_hooks_s *) malloc(sizeof(yaksur_gpudriver_hooks_s));
(*hooks)->get_num_devices = get_num_devices;
(*hooks)->check_p2p_comm = check_p2p_comm;
(*hooks)->finalize = finalize_hook;
(*hooks)->get_iov_pack_threshold = yaksuri_cudai_get_iov_pack_threshold;
(*hooks)->get_iov_unpack_threshold = yaksuri_cudai_get_iov_unpack_threshold;
(*hooks)->ipack = yaksuri_cudai_ipack;
(*hooks)->iunpack = yaksuri_cudai_iunpack;
(*hooks)->pup_is_supported = yaksuri_cudai_pup_is_supported;
(*hooks)->host_malloc = cuda_host_malloc;
(*hooks)->host_free = cuda_host_free;
(*hooks)->gpu_malloc = cuda_gpu_malloc;
(*hooks)->gpu_free = cuda_gpu_free;
(*hooks)->get_ptr_attr = yaksuri_cudai_get_ptr_attr;
(*hooks)->event_record = yaksuri_cudai_event_record;
(*hooks)->event_query = yaksuri_cudai_event_query;
(*hooks)->add_dependency = yaksuri_cudai_add_dependency;
(*hooks)->type_create = yaksuri_cudai_type_create_hook;
(*hooks)->type_free = yaksuri_cudai_type_free_hook;
(*hooks)->info_create = yaksuri_cudai_info_create_hook;
(*hooks)->info_free = yaksuri_cudai_info_free_hook;
(*hooks)->info_keyval_append = yaksuri_cudai_info_keyval_append;
fn_exit:
return rc;
fn_fail:
goto fn_exit;
}
|
wbprice/trails-email-notifications-signup | assets/components/environments/Home.js | <gh_stars>0
import React, { PropTypes, Component } from 'react'
import SubscribeEmailUpdates from '../ecosystems/SubscribeEmailUpdates'
class Home extends Component {
render() {
return (
<div>
<SubscribeEmailUpdates />
</div>
)
}
}
export default Home
|
connorwyatt/AxonFramework | eventsourcing/src/main/java/org/axonframework/eventsourcing/conflictresolution/ContextAwareConflictExceptionSupplier.java | <filename>eventsourcing/src/main/java/org/axonframework/eventsourcing/conflictresolution/ContextAwareConflictExceptionSupplier.java
/*
* Copyright (c) 2010-2018. Axon Framework
*
* 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.axonframework.eventsourcing.conflictresolution;
/**
* ConflictExceptionSupplier that is provided with more details of a version conflict.
*
* @param <T> The type of exception supplied
* @author <NAME>
* @since 3.2
*/
@FunctionalInterface
public interface ContextAwareConflictExceptionSupplier<T> {
/**
* Creates an instance of an exception indicating a conflict described by the given {@code conflictDescription}.
*
* @param conflictDescription Describing details of the conflict detected
* @return the exception describing the conflict
*/
T supplyException(ConflictDescription conflictDescription);
}
|
notonthehighstreet/toga | tests/e2e/components/test-redux/components/ProductListItem/ProductListItem.spec.js | <reponame>notonthehighstreet/toga
import helper from '../../../../../../tests/helper';
import React from 'react';
import {shallow} from 'enzyme';
import Product from './ProductListItem';
import createFakeProduct from '../../spec-helpers/createFakeProduct';
import createSanitisedProduct from '../../spec-helpers/createSanitisedProduct';
const {chance, sandbox, expect} = helper;
describe('Product component', () => {
beforeEach(() => {
sandbox.reset();
});
it('product should not have \'removed\' class', () => {
const product = createSanitisedProduct(createFakeProduct().product);
const wrapper = shallow(
<Product
product={product}
listId={chance.word()}
actions={{toggleProduct: () => {}}} />
);
expect(wrapper.hasClass('toga-product-list-item--removed')).to.be.false;
});
it('product should have \'removed\' class if it has been removed', () => {
const product = createSanitisedProduct(createFakeProduct().product);
product.removed = true;
const removedWrapper = shallow(
<Product
product={product}
listId={chance.word()}
actions={{toggleProduct: () => {}}} />
);
expect(removedWrapper.hasClass('toga-product-list-item--removed')).to.be.true;
});
it('clicking the \'remove button\' toggles the product', () => {
const toggleProductSpy = sandbox.spy();
const listId = chance.word();
const product = createSanitisedProduct(createFakeProduct().product);
const wrapper = shallow(
<Product
product={product}
listId={listId}
actions={{toggleProduct: toggleProductSpy}} />
);
wrapper.find('.toga-product-list-item__remove-button').simulate('click');
expect(toggleProductSpy.withArgs(
{
listId,
productCode: product.code,
productRemoved: product.removed
}, {
event: 'toggleProduct',
productCode: product.code,
triggerSource: 'remove button'
}
)).to.have.been.calledOnce;
});
});
|
DotMail/DotMail | Mail/MTTokenField/_MTTokenTextView.h | //
// MTTokenTextView.h
// TokenField
//
// Created by smorr on 11-11-29.
// Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//
#import <AppKit/AppKit.h>
@interface _MTTokenTextView : NSTextView
-(void)insertTextWithoutCompletion:(id)aString;
-(NSString*)completionStem;
-(NSArray *)getCompletionsForStem:(NSString*)stem;
-(void)setTokenArray:(NSArray*)tokenArray;
-(NSArray*)tokenArray;
-(void) insertTokenForText:(NSString*)tokenText replacementRange:(NSRange)replacementRange;
-(void)insertText:(id)aString replacementRange:(NSRange)replacementRange andBeginCompletion:(BOOL)beginCompletionFlag;
@end
|
Tech-XCorp/visit-deps | windowsbuild/MSVC2017/Qwt/6.1.2/doc/html/search/PaxHeaders.13080/functions_78.js | 30 mtime=1418307194.959186449
30 atime=1418307194.959186449
30 ctime=1418307255.949184647
|
styu/MIT-Mobile-for-Android | src/edu/mit/mitmobile2/DividerView.java | <reponame>styu/MIT-Mobile-for-Android<filename>src/edu/mit/mitmobile2/DividerView.java
package edu.mit.mitmobile2;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
public class DividerView extends View {
public DividerView(Context context, AttributeSet attrs) {
super(context, attrs);
int height = context.getResources().getDimensionPixelSize(R.dimen.dividerHeight);
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, height));
setBackgroundColor(context.getResources().getColor(R.color.dividerColor));
}
}
|
i37oC/java-note | design-mode/src/main/java/xyy/java/note/dm/strategy/RedHetDuck.java | package xyy.java.note.dm.strategy;
import xyy.java.note.dm.strategy.impl.FlyWithWin;
/**
* @author xyy
* @version 1.0 2017/3/9.
* @since 1.0
*/
public class RedHetDuck extends Duck {
public RedHetDuck() {
super();
super.setStrategy(new FlyWithWin());
}
@Override
public void display() {
System.out.println("我的脖子是红色的");
}
}
|
ScalablyTyped/SlinkyTyped | i/ipfs-core/src/main/scala/typingsSlinky/ipfsCore/mod/multihash.scala | <reponame>ScalablyTyped/SlinkyTyped
package typingsSlinky.ipfsCore.mod
import org.scalablytyped.runtime.TopLevel
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@JSImport("ipfs-core/dist/src", "multihash")
@js.native
object multihash
extends TopLevel[js.Any]
|
oweson/ruoyi | ruoyi-system/src/main/java/com/ruoyi/system/mapper/FireProjectMapper.java | package com.ruoyi.system.mapper;
import java.util.List;
import com.ruoyi.system.domain.FireProject;
/**
* 拥有的项目能力Mapper接口
*
* @author ruoyi
* @date 2020-06-03
*/
public interface FireProjectMapper
{
/**
* 查询拥有的项目能力
*
* @param id 拥有的项目能力ID
* @return 拥有的项目能力
*/
public FireProject selectFireProjectById(Long id);
/**
* 查询拥有的项目能力列表
*
* @param fireProject 拥有的项目能力
* @return 拥有的项目能力集合
*/
public List<FireProject> selectFireProjectList(FireProject fireProject);
/**
* 新增拥有的项目能力
*
* @param fireProject 拥有的项目能力
* @return 结果
*/
public int insertFireProject(FireProject fireProject);
/**
* 修改拥有的项目能力
*
* @param fireProject 拥有的项目能力
* @return 结果
*/
public int updateFireProject(FireProject fireProject);
/**
* 删除拥有的项目能力
*
* @param id 拥有的项目能力ID
* @return 结果
*/
public int deleteFireProjectById(Long id);
/**
* 批量删除拥有的项目能力
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteFireProjectByIds(String[] ids);
}
|
KimJeongYeon/jack2_android | jack/common/JackInternalClient.h | <filename>jack/common/JackInternalClient.h<gh_stars>10-100
/*
Copyright (C) 2001 <NAME>
Copyright (C) 2004-2008 Grame
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __JackInternalClient__
#define __JackInternalClient__
#include "JackClient.h"
#include "JackClientControl.h"
#include "driver_interface.h"
namespace Jack
{
struct JackEngineControl;
/*!
\brief Internal clients in the server.
*/
class JackInternalClient : public JackClient
{
private:
JackClientControl fClientControl; /*! Client control */
public:
JackInternalClient(JackServer* server, JackSynchro* table);
virtual ~JackInternalClient();
int Open(const char* server_name, const char* name, int uuid, jack_options_t options, jack_status_t* status);
void ShutDown();
JackGraphManager* GetGraphManager() const;
JackEngineControl* GetEngineControl() const;
JackClientControl* GetClientControl() const;
static JackGraphManager* fGraphManager; /*! Shared memory Port manager */
static JackEngineControl* fEngineControl; /*! Shared engine cotrol */
};
/*!
\brief Loadable internal clients in the server.
*/
typedef int (*InitializeCallback)(jack_client_t*, const char*);
typedef int (*InternalInitializeCallback)(jack_client_t*, const JSList* params);
typedef void (*FinishCallback)(void *);
class JackLoadableInternalClient : public JackInternalClient
{
protected:
JACK_HANDLE fHandle;
FinishCallback fFinish;
JackDriverDescFunction fDescriptor;
public:
JackLoadableInternalClient(JackServer* server, JackSynchro* table)
:JackInternalClient(server, table), fHandle(NULL), fFinish(NULL), fDescriptor(NULL)
{}
virtual ~JackLoadableInternalClient();
virtual int Init(const char* so_name);
};
class JackLoadableInternalClient1 : public JackLoadableInternalClient
{
private:
InitializeCallback fInitialize;
char fObjectData[JACK_LOAD_INIT_LIMIT];
public:
JackLoadableInternalClient1(JackServer* server, JackSynchro* table, const char* object_data);
virtual ~JackLoadableInternalClient1()
{}
int Init(const char* so_name);
int Open(const char* server_name, const char* name, int uuid, jack_options_t options, jack_status_t* status);
};
class JackLoadableInternalClient2 : public JackLoadableInternalClient
{
private:
InternalInitializeCallback fInitialize;
const JSList* fParameters;
public:
JackLoadableInternalClient2(JackServer* server, JackSynchro* table, const JSList* parameters);
virtual ~JackLoadableInternalClient2()
{}
int Init(const char* so_name);
int Open(const char* server_name, const char* name, int uuid, jack_options_t options, jack_status_t* status);
};
} // end of namespace
#endif
|
AntoniosKalattas/Ping_rep | gui/node_modules/core-js/es/function/index.js | <filename>gui/node_modules/core-js/es/function/index.js
version https://git-lfs.github.com/spec/v1
oid sha256:80f97e3afff46e837108f62c2c98d413d0364b8d594e22d400c783af1274119f
size 214
|
bytectl/gopkg | crypto/gconfig/gconfig.go | package gconfig
import (
"encoding/base64"
"fmt"
"strings"
"github.com/gogf/gf/crypto/gaes"
)
const (
EncPrefix = "enc("
EncSuffix = ")"
)
func DecryptConfigMap(config map[string]interface{}, key []byte) {
for k, value := range config {
switch v1 := value.(type) {
case string:
source, err := DecryptString(v1, key)
if err != nil {
fmt.Println(k, ":", v1, ",decrypt error:", err)
continue
}
config[k] = source
case map[string]interface{}:
DecryptConfigMap(v1, key)
case []interface{}:
for i, item := range v1 {
switch v2 := item.(type) {
case string:
source, err := DecryptString(v2, key)
if err != nil {
fmt.Println(k, ":", v2, ",decrypt error:", err)
continue
}
v1[i] = source
case map[string]interface{}:
DecryptConfigMap(v2, key)
}
}
}
}
}
func EncryptString(source string, key []byte) string {
key = gaes.PKCS5Padding(key, 16)
encrypted, err := gaes.Encrypt([]byte(source), key)
if err != nil {
fmt.Println(source, ",encrypt error:", err)
return source
}
return EncPrefix + base64.StdEncoding.EncodeToString(encrypted) + EncSuffix
}
func DecryptString(encrypted string, key []byte) (string, error) {
if !strings.HasPrefix(encrypted, EncPrefix) {
return encrypted, nil
}
key = gaes.PKCS5Padding(key, 16)
encrypted = strings.TrimPrefix(encrypted, EncPrefix)
encrypted = strings.TrimSuffix(encrypted, EncSuffix)
decoded, err := base64.StdEncoding.DecodeString(encrypted)
if err != nil {
return encrypted, err
}
decrypted, err := gaes.Decrypt(decoded, key)
if err != nil {
return encrypted, err
}
return string(decrypted), nil
}
|
hottredpen/base-think | script/module/tasktoPage.js | <filename>script/module/tasktoPage.js
require.config({
baseUrl: "/script/module",//用绝对位置
shim: {
'uploadify' : ['jquery'],
'chat' : ['jquery'],
'kindeditor': ['jquery']
},
paths: {
'jquery' : "../../static/cpk/public/js/jquery",
'uploadify' : "../../static/cpk/plugins/uploadify/jquery.uploadify",
'chat' : "../../static/cpk/public/js/chat_all",
'kindeditor' : "../../static/js/kindeditor/kindeditor-all"
},
map: {
'*': {
'css': '../../static/cpk/public/js/css'
}
}
});
define(['jquery','./cpk_tools/cpk_user_needchkphone','./cpk_tools/cpk_user_taskto','common','commonTool','uploadify'],function($,CPK_user_needchkphone,CPK_user_taskto){
var o_document = $(document);
o_document.ready(function(){
var _user_taskto = CPK_user_taskto.createObj();
_user_taskto.init();
var _user_needchkphone = CPK_user_needchkphone.createObj();
_user_needchkphone.init(_user_taskto.modifyPhone);
require(["chat"]);
});
o_document.on("click","#J_monthtasktobtn",function(){
var isopen =$(this).attr("data-isopen");
if(isopen==1){
window.location.href = $(this).attr('data-url');
}else if(isopen==2){
$.cpk_alert("对方当前包月数量已达上限");
}else{
$.cpk_alert("对方未开启包月服务");
}
});
});
|
rueyaa332266/testcafe | test/server/data/test-suites/selector-prev-sibling-incorrect-arg-type/testfile.js | <filename>test/server/data/test-suites/selector-prev-sibling-incorrect-arg-type/testfile.js
import { Selector } from 'testcafe';
fixture `Test`;
Selector('span').prevSibling();
Selector('span').prevSibling({});
test('yo', () => {
});
|
nastusha-merry/ossmoss-hasher-database | test-data/095 Кратчайшая суперстрока/(golovan)(2013-11-07_22:27:50)(FAILED_TESTS)(NOT_PLAG).c | <reponame>nastusha-merry/ossmoss-hasher-database
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int maxcount, maxlen;
void Permut(char **s , unsigned short n)
{
unsigned short k[n],i;
for (i=0; i<n; i++) k[i]=-1;
PRec(s ,1023, n, n, k, 0, 0);
}
void PRec(char **s, unsigned short Q, unsigned short count, unsigned short m, unsigned short *p, unsigned short pc, unsigned short elem)
{
unsigned short i, k[pc+1];
int j;
for (i=0; i<pc; i++) k[i]=p[i];
if (pc>0) k[pc-1]=elem;
if (m==0) {
j=getsuper(s, k, pc, maxlen);
if (j<maxcount) maxcount=j;
} else {
for (i=0; i<count; i++)
if (Q & (1<<i))
PRec(s, Q-(1<<i), count, m-1, k, pc+1, i);
}
}
void intersect(char *s1, char *s2)
{
unsigned short m=strlen(s1), n=strlen(s2), c, count, i;
if (m>n) c=m-n+1;
else c=1;
char p[n+1];
p[0]='\0';
for (i=c; i<m; i++) {
strncpy(p, s2, m-i);
p[m-i]='\0';
if (strcmp(p, &s1[i])==0) {
// printf("Concat: %s + %s ", s1, s2);
strcat(s1, &s2[m-i]);
// printf("(%d)\n", strlen(s1));
// printf(" %s\n", s1);
return;
}
}
strcat(s1, s2);
}
int getsuper(char **s, unsigned short *q, unsigned short n, int mlen)
{
short i;
char st[mlen];
st[0]='\0';
strcat(st, s[q[0]]);
for (i=1; i<n; i++) {
intersect(st, s[q[i]]);
if (strlen(st)>=maxcount)
return maxcount;
}
return strlen(st);
}
int main() {
unsigned short i, n,c;
scanf("%d ", &n);
char *s[n];
for (i=0; i<n; i++) {
s[i]=(char*)malloc(256);
scanf("%s", s[i]);
maxlen+=strlen(s[i]);
}
maxcount=maxlen;
Permut(s, n);
printf("%d\n", maxcount);
for (i=0; i<n; i++) free(s[i]);
return 0;
} |
dengjumingdream/study_base | src/main/java/com/zhenyue/techcenter/mockserver/gm/controller/RechargeController.java | <reponame>dengjumingdream/study_base<filename>src/main/java/com/zhenyue/techcenter/mockserver/gm/controller/RechargeController.java
package com.zhenyue.techcenter.mockserver.gm.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhenyue.techcenter.mockserver.gm.model.ResponseModel;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("local/recharge")
public class RechargeController {
/**
* 新增测试接口
* @param params
* @return
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
public JSON add(@RequestBody String params) {
JSONArray dataArray = new JSONArray();
JSONObject info1 = new JSONObject();
info1.put("", "");
info1.put("", "");
info1.put("", "");
ResponseModel responseModel = new ResponseModel();
responseModel.setRet(0);
responseModel.setData(dataArray);
return (JSON) JSON.toJSON(responseModel);
}
/**
* 编辑测试接口
* @param params
* @return
*/
@RequestMapping(value = "/edit", method = RequestMethod.POST)
public JSON edit(@RequestBody String params) {
JSONArray dataArray = new JSONArray();
JSONObject info1 = new JSONObject();
info1.put("", "");
info1.put("", "");
info1.put("", "");
ResponseModel responseModel = new ResponseModel();
responseModel.setRet(0);
responseModel.setData(dataArray);
return (JSON) JSON.toJSON(responseModel);
}
/**
* 查询测试接口
* @param params
* @return
*/
@RequestMapping(value = "/list", method = RequestMethod.POST)
public JSON list(@RequestBody String params) {
JSONObject info1 = new JSONObject();
info1.put("uid", "1001");
info1.put("gold", 1);
info1.put("vip1", 5);
info1.put("vip2", 3);
JSONArray dataArray = new JSONArray();
dataArray.add(info1);
ResponseModel responseModel = new ResponseModel();
responseModel.setRet(0);
responseModel.setData(dataArray);
return (JSON) JSON.toJSON(responseModel);
}
/**
* 自定义测试接口 - show
* @param params
* @return
*/
@RequestMapping(value = "/show", method = RequestMethod.POST)
public JSON show(@RequestBody String params) {
JSONArray dataArray = new JSONArray();
JSONObject info1 = new JSONObject();
info1.put("", "");
info1.put("", "");
info1.put("", "");
ResponseModel responseModel = new ResponseModel();
responseModel.setRet(0);
responseModel.setData(dataArray);
return (JSON) JSON.toJSON(responseModel);
}
}
|
nuggetwheat/study | src/cc/Books/ElementsOfProgrammingInterviews/reference/ch19.cpp |
#include "ch19.hpp"
#include <algorithm>
#include <cassert>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <stack>
#include <stdexcept>
#include <utility>
#include <vector>
extern "C" {
#include <math.h>
}
#include <Common/Graph.hpp>
using study::Graph;
using study::EdgeType;
namespace reference {
size_t CelebrityFinding(const std::vector<std::deque<bool>> &F) {
size_t i = 0, j = 1;
while (j < F.size()) {
if (F[i][j])
i = j++;
else
++j;
}
return i;
}
bool SearchDown(Graph<Coordinate> &g, Coordinate vertex,
Coordinate finish,
std::map<Coordinate, int> &color,
std::stack<Coordinate> &pstack) {
//std::cout << vertex << std::endl;
if (vertex == finish) {
pstack.push(vertex);
return false;
}
color[vertex] = GRAY;
for (const auto &neighbor : g.adj(vertex)) {
if (color[neighbor] == WHITE) {
if (!SearchDown(g, neighbor, finish, color, pstack)) {
pstack.push(vertex);
return false;
}
}
}
color[vertex] = BLACK;
return true;
}
std::vector<Coordinate>
SearchMaze(std::vector<std::vector<Color>> maze,
const Coordinate start, const Coordinate finish) {
std::stack<Coordinate> pstack;
std::vector<Coordinate> vertices;
std::map<Coordinate, int> color;
for (size_t i=0; i<maze.size(); ++i)
for (size_t j=0; j<maze[i].size(); ++j) {
vertices.push_back( {i, j} );
color[{i, j}] = WHITE;
}
Graph<Coordinate> g(EdgeType::UNDIRECTED, vertices);
// Build graph
for (size_t i=0; i<maze.size(); ++i) {
for (size_t j=0; j<maze[i].size(); ++j) {
if (j < maze[i].size()-1 && maze[i][j] == WHITE && maze[i][j+1] == WHITE)
g.add_edge({{i, j}, {i, j+1}});
if (i < maze.size()-1 && maze[i][j] == WHITE && maze[i+1][j] == WHITE)
g.add_edge({{i, j}, {i+1, j}});
}
}
#if 0
std::cout << "adjacent(start) = ";
for (const auto &neighbor : g.adj(start))
std::cout << neighbor;
std::cout << std::endl;
std::cout << "adjacent(finish) = ";
for (const auto &neighbor : g.adj(finish))
std::cout << neighbor;
std::cout << std::endl;
#endif
if (start == finish)
pstack.push(start);
else {
for (const auto &neighbor : g.adj(start)) {
if (color[neighbor] == WHITE) {
if (!SearchDown(g, neighbor, finish, color, pstack)) {
pstack.push(start);
break;
}
}
}
}
std::vector<Coordinate> path;
path.reserve(pstack.size());
while (!pstack.empty()) {
path.push_back(pstack.top());
pstack.pop();
}
return path;
}
void FlipColor(size_t x, size_t y, std::vector<std::vector<Color>> *A_ptr) {
std::vector<std::vector<Color>> &A = *A_ptr;
std::queue<Coordinate> tbd;
Color old_color = A[x][y];
Color new_color = (old_color == WHITE) ? BLACK : WHITE;
tbd.push({x, y});
while (!tbd.empty()) {
Coordinate &coord = tbd.front();
assert(coord.x < A.size() && coord.y < A[0].size());
// Flip color
A[coord.x][coord.y] = new_color;
if (coord.x > 0 && A[coord.x-1][coord.y] == old_color)
tbd.push({coord.x-1, coord.y});
if (coord.y < A[0].size()-1 && A[coord.x][coord.y+1] == old_color)
tbd.push({coord.x, coord.y+1});
if (coord.x < A.size()-1 && A[coord.x+1][coord.y] == old_color)
tbd.push({coord.x+1, coord.y});
if (coord.y > 0 && A[coord.x][coord.y-1] == old_color)
tbd.push({coord.x, coord.y-1});
tbd.pop();
}
}
}
|
ZhangHanDong/ansuz | vendor/plugins/ansuz_scrollable_content/init.rb | Ansuz::PluginManagerInstance.register_plugin(Ansuz::JAdams::ScrollableContent)
|
ToeEngine/toe-engine | toe-renderer/src/main/java/br/toe/engine/platform/input/GLFWInputMapper.java | package br.toe.engine.platform.input;
import br.toe.framework.cdi.annotation.*;
import static org.lwjgl.glfw.GLFW.*;
@Singleton
public final class GLFWInputMapper implements InputMapper {
public InputMouse inputMouse(int keycode) {
return switch (keycode) {
case GLFW_MOUSE_BUTTON_LEFT -> InputMouse.BUTTON_LEFT;
case GLFW_MOUSE_BUTTON_RIGHT -> InputMouse.BUTTON_RIGHT;
case GLFW_MOUSE_BUTTON_MIDDLE -> InputMouse.BUTTON_MIDDLE;
default -> throw new InputException("Unknown Mouse Button [%s]".formatted(keycode));
};
}
public InputKey inputKey(int keycode) {
return switch (keycode) {
case GLFW_KEY_A -> InputKey.KEY_A;
case GLFW_KEY_B -> InputKey.KEY_B;
case GLFW_KEY_C -> InputKey.KEY_C;
case GLFW_KEY_D -> InputKey.KEY_D;
case GLFW_KEY_E -> InputKey.KEY_E;
case GLFW_KEY_F -> InputKey.KEY_F;
case GLFW_KEY_G -> InputKey.KEY_G;
case GLFW_KEY_H -> InputKey.KEY_H;
case GLFW_KEY_I -> InputKey.KEY_I;
case GLFW_KEY_J -> InputKey.KEY_J;
case GLFW_KEY_K -> InputKey.KEY_K;
case GLFW_KEY_L -> InputKey.KEY_L;
case GLFW_KEY_M -> InputKey.KEY_M;
case GLFW_KEY_N -> InputKey.KEY_N;
case GLFW_KEY_O -> InputKey.KEY_O;
case GLFW_KEY_P -> InputKey.KEY_P;
case GLFW_KEY_Q -> InputKey.KEY_Q;
case GLFW_KEY_R -> InputKey.KEY_R;
case GLFW_KEY_S -> InputKey.KEY_S;
case GLFW_KEY_T -> InputKey.KEY_T;
case GLFW_KEY_U -> InputKey.KEY_U;
case GLFW_KEY_V -> InputKey.KEY_V;
case GLFW_KEY_W -> InputKey.KEY_W;
case GLFW_KEY_X -> InputKey.KEY_X;
case GLFW_KEY_Y -> InputKey.KEY_Y;
case GLFW_KEY_Z -> InputKey.KEY_Z;
case GLFW_KEY_APOSTROPHE -> InputKey.KEY_APOSTROPHE;
case GLFW_KEY_COMMA -> InputKey.KEY_COMMA;
case GLFW_KEY_MINUS -> InputKey.KEY_MINUS;
case GLFW_KEY_PERIOD -> InputKey.KEY_PERIOD;
case GLFW_KEY_SLASH -> InputKey.KEY_SLASH;
case GLFW_KEY_0 -> InputKey.KEY_0;
case GLFW_KEY_1 -> InputKey.KEY_1;
case GLFW_KEY_2 -> InputKey.KEY_2;
case GLFW_KEY_3 -> InputKey.KEY_3;
case GLFW_KEY_4 -> InputKey.KEY_4;
case GLFW_KEY_5 -> InputKey.KEY_5;
case GLFW_KEY_6 -> InputKey.KEY_6;
case GLFW_KEY_7 -> InputKey.KEY_7;
case GLFW_KEY_8 -> InputKey.KEY_8;
case GLFW_KEY_9 -> InputKey.KEY_9;
case GLFW_KEY_SEMICOLON -> InputKey.KEY_SEMICOLON;
case GLFW_KEY_EQUAL -> InputKey.KEY_EQUAL;
case GLFW_KEY_LEFT_BRACKET -> InputKey.KEY_LEFT_BRACKET;
case GLFW_KEY_BACKSLASH -> InputKey.KEY_BACKSLASH;
case GLFW_KEY_RIGHT_BRACKET -> InputKey.KEY_RIGHT_BRACKET;
case GLFW_KEY_GRAVE_ACCENT -> InputKey.KEY_GRAVE_ACCENT;
case GLFW_KEY_ESCAPE -> InputKey.KEY_ESCAPE;
case GLFW_KEY_ENTER -> InputKey.KEY_ENTER;
case GLFW_KEY_SPACE -> InputKey.KEY_SPACE;
case GLFW_KEY_TAB -> InputKey.KEY_TAB;
case GLFW_KEY_BACKSPACE -> InputKey.KEY_BACKSPACE;
case GLFW_KEY_INSERT -> InputKey.KEY_INSERT;
case GLFW_KEY_DELETE -> InputKey.KEY_DELETE;
case GLFW_KEY_UP -> InputKey.KEY_UP;
case GLFW_KEY_DOWN -> InputKey.KEY_DOWN;
case GLFW_KEY_LEFT -> InputKey.KEY_LEFT;
case GLFW_KEY_RIGHT -> InputKey.KEY_RIGHT;
case GLFW_KEY_PAGE_UP -> InputKey.KEY_PAGE_UP;
case GLFW_KEY_PAGE_DOWN -> InputKey.KEY_PAGE_DOWN;
case GLFW_KEY_HOME -> InputKey.KEY_HOME;
case GLFW_KEY_END -> InputKey.KEY_END;
case GLFW_KEY_CAPS_LOCK -> InputKey.KEY_CAPS_LOCK;
case GLFW_KEY_SCROLL_LOCK -> InputKey.KEY_SCROLL_LOCK;
case GLFW_KEY_NUM_LOCK -> InputKey.KEY_NUM_LOCK;
case GLFW_KEY_PRINT_SCREEN -> InputKey.KEY_PRINT_SCREEN;
case GLFW_KEY_PAUSE -> InputKey.KEY_PAUSE;
case GLFW_KEY_F1 -> InputKey.KEY_F1;
case GLFW_KEY_F2 -> InputKey.KEY_F2;
case GLFW_KEY_F3 -> InputKey.KEY_F3;
case GLFW_KEY_F4 -> InputKey.KEY_F4;
case GLFW_KEY_F5 -> InputKey.KEY_F5;
case GLFW_KEY_F6 -> InputKey.KEY_F6;
case GLFW_KEY_F7 -> InputKey.KEY_F7;
case GLFW_KEY_F8 -> InputKey.KEY_F8;
case GLFW_KEY_F9 -> InputKey.KEY_F9;
case GLFW_KEY_F10 -> InputKey.KEY_F10;
case GLFW_KEY_F11 -> InputKey.KEY_F11;
case GLFW_KEY_F12 -> InputKey.KEY_F12;
case GLFW_KEY_LEFT_ALT -> InputKey.KEY_LEFT_ALT;
case GLFW_KEY_LEFT_SHIFT -> InputKey.KEY_LEFT_SHIFT;
case GLFW_KEY_LEFT_CONTROL -> InputKey.KEY_LEFT_CTRL;
case GLFW_KEY_RIGHT_ALT -> InputKey.KEY_RIGHT_ALT;
case GLFW_KEY_RIGHT_CONTROL -> InputKey.KEY_RIGHT_CTRL;
case GLFW_KEY_RIGHT_SHIFT -> InputKey.KEY_RIGHT_SHIFT;
case GLFW_KEY_KP_0 -> InputKey.KEY_KP_0;
case GLFW_KEY_KP_1 -> InputKey.KEY_KP_1;
case GLFW_KEY_KP_2 -> InputKey.KEY_KP_2;
case GLFW_KEY_KP_3 -> InputKey.KEY_KP_3;
case GLFW_KEY_KP_4 -> InputKey.KEY_KP_4;
case GLFW_KEY_KP_5 -> InputKey.KEY_KP_5;
case GLFW_KEY_KP_6 -> InputKey.KEY_KP_6;
case GLFW_KEY_KP_7 -> InputKey.KEY_KP_7;
case GLFW_KEY_KP_8 -> InputKey.KEY_KP_8;
case GLFW_KEY_KP_9 -> InputKey.KEY_KP_9;
case GLFW_KEY_KP_DECIMAL -> InputKey.KEY_KP_DECIMAL;
case GLFW_KEY_KP_DIVIDE -> InputKey.KEY_KP_DIVIDE;
case GLFW_KEY_KP_MULTIPLY -> InputKey.KEY_KP_MULTIPLY;
case GLFW_KEY_KP_SUBTRACT -> InputKey.KEY_KP_SUBTRACT;
case GLFW_KEY_KP_ADD -> InputKey.KEY_KP_ADD;
case GLFW_KEY_KP_ENTER -> InputKey.KEY_KP_ENTER;
case GLFW_KEY_KP_EQUAL -> InputKey.KEY_KP_EQUAL;
case GLFW_KEY_MENU -> InputKey.KEY_MENU;
case GLFW_KEY_LEFT_SUPER -> InputKey.KEY_LEFT_SUPER;
case GLFW_KEY_RIGHT_SUPER -> InputKey.KEY_RIGHT_SUPER;
default -> throw new InputException("Unknown keycode [%s]".formatted(keycode));
};
}
}
|
pltxtra/kngtz | core/src/main/java/com/holidaystudios/kngt/tools/RandomUtils.java | <gh_stars>1-10
package com.holidaystudios.kngt.tools;
import java.util.Random;
/**
* Created by tedbjorling on 2014-02-20.
*/
public class RandomUtils {
private static Random generator = new Random();
private static String seed = null;
public static void setSeed(final String seed) {
RandomUtils.generator.setSeed(seed.hashCode());
}
public static double getRandom() {
return RandomUtils.generator.nextDouble();
}
}
|
JonZhang3/flume-helper | view/src/flume-configs/sinks/null.js | export default {
batchSize: {
type: Number,
default: 100,
description: ''
}
}
|
wanxiang-blockchain/2021Wanxiang-Blockchain-Hackathon-Filscan | coinmobile/packages/rankingPool/index.js | <reponame>wanxiang-blockchain/2021Wanxiang-Blockchain-Hackathon-Filscan
import RankingPool from "./src/index"
RankingPool.install = function(Vue) {
Vue.component(RankingPool.name, RankingPool)
}
export default RankingPool |
pankaj4red/greek_house | resources/assets/v3/js/custom/number_format.js | window.number_format = function (number, decimals, dec_point, thousands_sep) {
var units = number.toString().split(".");
var decimal = '00';
if (units.length > 1) {
decimal = units[1];
units = units[0];
} else {
decimal = '00';
units = units[0];
}
if (decimal.length < 1) {
decimal = decimal + '0';
}
if (decimal.length < 2) {
decimal = decimal + '0';
}
var unitsParts = units.split(/(?=(?:...)*$)/);
var final = '';
for (var i = 0; i < unitsParts.length; i++) {
if (i > 0) final += ',';
final += unitsParts[i];
}
final = final + '.' + decimal;
return final;
};
|
tommo/gii | lib/gii/qt/controls/PropertyEditor/__init__.py | ##----------------------------------------------------------------##
from PropertyEditor import \
PropertyEditor, FieldEditor, FieldEditorFactory, registerSimpleFieldEditorFactory, registerFieldEditorFactory
##----------------------------------------------------------------##
from CommonFieldEditors import \
StringFieldEditor, NumberFieldEditor, BoolFieldEditor
from EnumFieldEditor import EnumFieldEditor
from ColorFieldEditor import ColorFieldEditor
from ReferenceFieldEditor import ReferenceFieldEditor
from AssetRefFieldEditor import AssetRefFieldEditor
import LongTextFieldEditor
import CodeBoxFieldEditor
import ActionFieldEditor
import VecFieldEditor
import CollectionFieldEditor
import SelectionFieldEditor
##----------------------------------------------------------------##
|
QuocAnh90/Uintah_Aalto | CCA/Components/Models/MultiMatlExchange/ExchangeModel.h | <reponame>QuocAnh90/Uintah_Aalto
/*
* The MIT License
*
* Copyright (c) 1997-2019 The University of Utah
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef Models_MultiMatlExchange_Exchange_h
#define Models_MultiMatlExchange_Exchange_h
#include <CCA/Components/ICE/CustomBCs/C_BC_driver.h>
#include <CCA/Components/MPM/Core/MPMLabel.h>
#include <CCA/Ports/DataWarehouse.h>
#include <CCA/Ports/SchedulerP.h>
#include <Core/Grid/DbgOutput.h>
#include <Core/Grid/Patch.h>
#include <Core/Grid/MaterialManagerP.h>
#include <Core/Grid/Variables/ComputeSet.h>
namespace Uintah {
class DataWarehouse;
class Material;
class Patch;
class ExchangeModel {
public:
ExchangeModel(const ProblemSpecP & prob_spec,
const MaterialManagerP & materialManager,
const bool with_mpm );
virtual ~ExchangeModel();
virtual void problemSetup(const ProblemSpecP & prob_spec ) = 0;
virtual void outputProblemSpec(ProblemSpecP & prob_spec ) = 0;
virtual void sched_PreExchangeTasks(SchedulerP & sched,
const PatchSet * patches,
const MaterialSubset * iceMatls,
const MaterialSubset * mpmMatls,
const MaterialSet * allMatls) = 0;
virtual void addExchangeModelRequires ( Task* t,
const MaterialSubset * zeroMatls,
const MaterialSubset * iceMatls,
const MaterialSubset * mpmMatls) = 0;
virtual void sched_AddExch_VelFC(SchedulerP & sched,
const PatchSet * patches,
const MaterialSubset * iceMatls,
const MaterialSubset * mpmMatls,
const MaterialSet * allMatls,
customBC_globalVars * BC_globalVars,
const bool recursion) = 0;
virtual void addExch_VelFC(const ProcessorGroup * pg,
const PatchSubset * patch,
const MaterialSubset * matls,
DataWarehouse * old_dw,
DataWarehouse * new_dw,
customBC_globalVars * BC_globalVars,
const bool recursion) = 0;
virtual void sched_AddExch_Vel_Temp_CC(SchedulerP & sched,
const PatchSet * patches,
const MaterialSubset * ice_matls,
const MaterialSubset * mpm_matls,
const MaterialSet * all_matls,
customBC_globalVars * BC_globalVars) = 0;
virtual void addExch_Vel_Temp_CC( const ProcessorGroup * pg,
const PatchSubset * patches,
const MaterialSubset * matls,
DataWarehouse * old_dw,
DataWarehouse * new_dw,
customBC_globalVars * BC_globalVars) = 0;
void schedComputeSurfaceNormal( SchedulerP & sched,
const PatchSet * patches,
const MaterialSubset * mpmMatls );
void ComputeSurfaceNormal( const ProcessorGroup *,
const PatchSubset * patches,
const MaterialSubset *,
DataWarehouse * old_dw,
DataWarehouse * new_dw );
protected:
//__________________________________
// variables & objects needed by
// the different exchange models.
const VarLabel* d_surfaceNormLabel;
const VarLabel* d_isSurfaceCellLabel;
double d_SMALL_NUM = 1.0e-100;
int d_numMatls = -9;
MaterialManagerP d_matlManager;
MaterialSubset * d_zero_matl;
MPMLabel* Mlb;
ICELabel* Ilb;
bool d_with_mpm;
};
}
#endif
|
sourac/Algorithms-and-Data-Structures | 10 Sorting/9 2Sum.java | public class Solution
{
public boolean isSum(int[] a, int k)
{
Arrays.sort(a);
int n = a.length;
int low = 0, high = n-1;
while(low<high){
int sum = a[low] + a[high];
if(sum==k) return true;
else if(sum<k) low++;
else high--;
}
return false;
}
}
|
zhuyongyong/crosswalk-test-suite | webapi/tct-xmlhttprequest-w3c-tests/xmlhttprequest/w3c/xmlhttprequest-timeout-overrides.js | <reponame>zhuyongyong/crosswalk-test-suite
if (this.document === undefined)
importScripts("xmlhttprequest-timeout.js");
/*
Sets up three requests to a resource that will take 0.6 seconds to load:
1) timeout first set to 1000ms, after 400ms timeout is set to 0, asserts load fires
2) timeout first set to 1000ms, after 200ms timeout is set to 400, asserts load fires (race condition..?!?)
3) timeout first set to 0, after 400ms it is set to 1000, asserts load fires
*/
runTestRequests([ new RequestTracker(true, "timeout disabled after initially set", TIME_NORMAL_LOAD, TIME_REGULAR_TIMEOUT, 0),
new RequestTracker(true, "timeout overrides load after a delay", TIME_NORMAL_LOAD, TIME_DELAY, TIME_REGULAR_TIMEOUT),
new RequestTracker(true, "timeout enabled after initially disabled", 0, TIME_REGULAR_TIMEOUT, TIME_NORMAL_LOAD) ]);
|
fgirse/commodore3 | node_modules/micromark-extension-math/dev/lib/math-flow.js | /**
* @typedef {import('micromark-util-types').Construct} Construct
* @typedef {import('micromark-util-types').Tokenizer} Tokenizer
* @typedef {import('micromark-util-types').State} State
*/
import {ok as assert} from 'uvu/assert'
import {factorySpace} from 'micromark-factory-space'
import {markdownLineEnding} from 'micromark-util-character'
import {codes} from 'micromark-util-symbol/codes.js'
import {constants} from 'micromark-util-symbol/constants.js'
import {types} from 'micromark-util-symbol/types.js'
/** @type {Construct} */
export const mathFlow = {
tokenize: tokenizeMathFenced,
concrete: true
}
/** @type {Construct} */
const nonLazyLine = {tokenize: tokenizeNonLazyLine, partial: true}
/** @type {Tokenizer} */
function tokenizeMathFenced(effects, ok, nok) {
const self = this
const tail = self.events[self.events.length - 1]
const initialSize =
tail && tail[1].type === types.linePrefix
? tail[2].sliceSerialize(tail[1], true).length
: 0
let sizeOpen = 0
return start
/** @type {State} */
function start(code) {
assert(code === codes.dollarSign, 'expected `$`')
effects.enter('mathFlow')
effects.enter('mathFlowFence')
effects.enter('mathFlowFenceSequence')
return sequenceOpen(code)
}
/** @type {State} */
function sequenceOpen(code) {
if (code === codes.dollarSign) {
effects.consume(code)
sizeOpen++
return sequenceOpen
}
effects.exit('mathFlowFenceSequence')
return sizeOpen < 2
? nok(code)
: factorySpace(effects, metaOpen, types.whitespace)(code)
}
/** @type {State} */
function metaOpen(code) {
if (code === codes.eof || markdownLineEnding(code)) {
return openAfter(code)
}
effects.enter('mathFlowFenceMeta')
effects.enter(types.chunkString, {contentType: constants.contentTypeString})
return meta(code)
}
/** @type {State} */
function meta(code) {
if (code === codes.eof || markdownLineEnding(code)) {
effects.exit(types.chunkString)
effects.exit('mathFlowFenceMeta')
return openAfter(code)
}
if (code === codes.dollarSign) return nok(code)
effects.consume(code)
return meta
}
/** @type {State} */
function openAfter(code) {
effects.exit('mathFlowFence')
return self.interrupt ? ok(code) : contentStart(code)
}
/** @type {State} */
function contentStart(code) {
if (code === codes.eof) {
return after(code)
}
if (markdownLineEnding(code)) {
return effects.attempt(
nonLazyLine,
effects.attempt(
{tokenize: tokenizeClosingFence, partial: true},
after,
initialSize
? factorySpace(
effects,
contentStart,
types.linePrefix,
initialSize + 1
)
: contentStart
),
after
)(code)
}
effects.enter('mathFlowValue')
return contentContinue(code)
}
/** @type {State} */
function contentContinue(code) {
if (code === codes.eof || markdownLineEnding(code)) {
effects.exit('mathFlowValue')
return contentStart(code)
}
effects.consume(code)
return contentContinue
}
/** @type {State} */
function after(code) {
effects.exit('mathFlow')
return ok(code)
}
/** @type {Tokenizer} */
function tokenizeClosingFence(effects, ok, nok) {
let size = 0
return factorySpace(
effects,
closingPrefixAfter,
types.linePrefix,
constants.tabSize
)
/** @type {State} */
function closingPrefixAfter(code) {
effects.enter('mathFlowFence')
effects.enter('mathFlowFenceSequence')
return closingSequence(code)
}
/** @type {State} */
function closingSequence(code) {
if (code === codes.dollarSign) {
effects.consume(code)
size++
return closingSequence
}
if (size < sizeOpen) return nok(code)
effects.exit('mathFlowFenceSequence')
return factorySpace(effects, closingSequenceEnd, types.whitespace)(code)
}
/** @type {State} */
function closingSequenceEnd(code) {
if (code === codes.eof || markdownLineEnding(code)) {
effects.exit('mathFlowFence')
return ok(code)
}
return nok(code)
}
}
}
/** @type {Tokenizer} */
function tokenizeNonLazyLine(effects, ok, nok) {
const self = this
return start
/** @type {State} */
function start(code) {
assert(markdownLineEnding(code), 'expected eol')
effects.enter(types.lineEnding)
effects.consume(code)
effects.exit(types.lineEnding)
return lineStart
}
/** @type {State} */
function lineStart(code) {
return self.parser.lazy[self.now().line] ? nok(code) : ok(code)
}
}
|
YgorCastor/opentelemetry-java-instrumentation | instrumentation/play/play-2.6/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/play/v2_6/PlayTracer.java | <filename>instrumentation/play/play-2.6/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/play/v2_6/PlayTracer.java
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.instrumentation.play.v2_6;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.instrumentation.api.tracer.BaseTracer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.annotation.Nullable;
import play.api.mvc.Request;
import play.api.routing.HandlerDef;
import play.libs.typedmap.TypedKey;
import play.routing.Router;
import scala.Option;
public class PlayTracer extends BaseTracer {
private static final PlayTracer TRACER = new PlayTracer();
public static PlayTracer tracer() {
return TRACER;
}
@Nullable private static final Method typedKeyGetUnderlying;
static {
Method typedKeyGetUnderlyingCheck = null;
try {
// This method was added in Play 2.6.8
typedKeyGetUnderlyingCheck = TypedKey.class.getMethod("asScala");
} catch (NoSuchMethodException ignored) {
// Ignore
}
// Fallback
if (typedKeyGetUnderlyingCheck == null) {
try {
typedKeyGetUnderlyingCheck = TypedKey.class.getMethod("underlying");
} catch (NoSuchMethodException ignored) {
// Ignore
}
}
typedKeyGetUnderlying = typedKeyGetUnderlyingCheck;
}
public void updateSpanName(Span span, Request request) {
if (request != null) {
// more about routes here:
// https://github.com/playframework/playframework/blob/master/documentation/manual/releases/release26/migration26/Migration26.md
Option<HandlerDef> defOption = null;
if (typedKeyGetUnderlying != null) { // Should always be non-null but just to make sure
try {
defOption =
request
.attrs()
.get(
(play.api.libs.typedmap.TypedKey<HandlerDef>)
typedKeyGetUnderlying.invoke(Router.Attrs.HANDLER_DEF));
} catch (IllegalAccessException | InvocationTargetException ignored) {
// Ignore
}
}
if (defOption != null && !defOption.isEmpty()) {
String path = defOption.get().path();
span.updateName(path);
}
}
}
@Override
protected String getInstrumentationName() {
return "io.opentelemetry.play-2.6";
}
}
|
JayDi85/intellij-community | java/java-tests/testSrc/com/intellij/java/psi/impl/cache/impl/IdCacheTest.java | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.psi.impl.cache.impl;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.ide.todo.TodoConfiguration;
import com.intellij.ide.todo.TodoIndexPatternProvider;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.cache.CacheManager;
import com.intellij.psi.impl.cache.TodoCacheManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.TodoAttributesUtil;
import com.intellij.psi.search.TodoPattern;
import com.intellij.psi.search.UsageSearchContext;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.testFramework.PsiTestUtil;
import com.intellij.util.ArrayUtilRt;
import java.io.File;
import java.util.Arrays;
public class IdCacheTest extends CodeInsightTestCase{
private VirtualFile myRootDir;
private File myCacheFile;
@Override
protected void setUp() throws Exception {
super.setUp();
String root = JavaTestUtil.getJavaTestDataPath()+ "/psi/impl/cache/";
PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17());
myRootDir = createTestProjectStructure(root);
myCacheFile = FileUtil.createTempFile("cache", "");
myCacheFile.delete();
myFilesToDelete.add(myCacheFile);
}
public void testBuildCache() {
checkCache(CacheManager.SERVICE.getInstance(myProject), TodoCacheManager.SERVICE.getInstance(myProject));
}
public void testLoadCacheNoTodo() {
final CacheManager cache = CacheManager.SERVICE.getInstance(myProject);
checkResult(new String[]{"1.java", "2.java"}, convert(cache.getFilesWithWord("b", UsageSearchContext.ANY, GlobalSearchScope.projectScope(myProject), false)));
}
public void testUpdateCache1() throws Exception {
createChildData(myRootDir, "4.java");
Thread.sleep(1000);
checkCache(CacheManager.SERVICE.getInstance(myProject), TodoCacheManager.SERVICE.getInstance(myProject));
}
public void testUpdateCache2() {
VirtualFile child = myRootDir.findChild("1.java");
setFileText(child, "xxx");
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
FileDocumentManager.getInstance().saveAllDocuments();
final CacheManager cache = CacheManager.SERVICE.getInstance(myProject);
final TodoCacheManager todocache = TodoCacheManager.SERVICE.getInstance(myProject);
final GlobalSearchScope scope = GlobalSearchScope.projectScope(myProject);
checkResult(new String[] {"1.java"}, convert(cache.getFilesWithWord("xxx", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{}, convert(cache.getFilesWithWord("a", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"2.java"}, convert(cache.getFilesWithWord("b", UsageSearchContext.ANY,scope, false)));
checkResult(new String[]{"2.java", "3.java"}, convert(cache.getFilesWithWord("c", UsageSearchContext.ANY,scope, false)));
checkResult(new String[]{"2.java", "3.java"}, convert(cache.getFilesWithWord("d", UsageSearchContext.ANY,scope, false)));
checkResult(new String[]{"3.java"}, convert(cache.getFilesWithWord("e", UsageSearchContext.ANY,scope, false)));
checkResult(new String[]{"3.java"}, convert(todocache.getFilesWithTodoItems()));
assertEquals(0, todocache.getTodoCount(myRootDir.findChild("1.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(0, todocache.getTodoCount(myRootDir.findChild("2.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(2, todocache.getTodoCount(myRootDir.findChild("3.java"), TodoIndexPatternProvider.getInstance()));
}
public void testUpdateCache3() {
VirtualFile child = myRootDir.findChild("1.java");
delete(child);
final CacheManager cache2 = CacheManager.SERVICE.getInstance(myProject);
final TodoCacheManager todocache2 = TodoCacheManager.SERVICE.getInstance(myProject);
final GlobalSearchScope scope = GlobalSearchScope.projectScope(myProject);
checkResult(ArrayUtilRt.EMPTY_STRING_ARRAY, convert(cache2.getFilesWithWord("xxx", UsageSearchContext.ANY, scope, false)));
checkResult(ArrayUtilRt.EMPTY_STRING_ARRAY, convert(cache2.getFilesWithWord("a", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"2.java"}, convert(cache2.getFilesWithWord("b", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"2.java", "3.java"}, convert(cache2.getFilesWithWord("c", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"2.java", "3.java"}, convert(cache2.getFilesWithWord("d", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"3.java"}, convert(cache2.getFilesWithWord("e", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"3.java"}, convert(todocache2.getFilesWithTodoItems()));
assertEquals(0, todocache2.getTodoCount(myRootDir.findChild("2.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(2, todocache2.getTodoCount(myRootDir.findChild("3.java"), TodoIndexPatternProvider.getInstance()));
}
public void testUpdateCacheNoTodo() {
createChildData(myRootDir, "4.java");
final GlobalSearchScope scope = GlobalSearchScope.projectScope(myProject);
final CacheManager cache = CacheManager.SERVICE.getInstance(myProject);
checkResult(new String[]{"1.java", "2.java"}, convert(cache.getFilesWithWord("b", UsageSearchContext.ANY, scope, false)));
}
public void testUpdateOnTodoChange() {
TodoPattern pattern = new TodoPattern("newtodo", TodoAttributesUtil.createDefault(), true);
TodoPattern[] oldPatterns = TodoConfiguration.getInstance().getTodoPatterns();
TodoConfiguration.getInstance().setTodoPatterns(new TodoPattern[]{pattern});
try{
final TodoCacheManager todocache = TodoCacheManager.SERVICE.getInstance(myProject);
checkResult(new String[]{"2.java"}, convert(todocache.getFilesWithTodoItems()));
assertEquals(0, todocache.getTodoCount(myRootDir.findChild("1.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(1, todocache.getTodoCount(myRootDir.findChild("2.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(0, todocache.getTodoCount(myRootDir.findChild("3.java"), TodoIndexPatternProvider.getInstance()));
}
finally{
TodoConfiguration.getInstance().setTodoPatterns(oldPatterns);
}
}
public void testFileModification() {
final CacheManager cache = CacheManager.SERVICE.getInstance(myProject);
final TodoCacheManager todocache = TodoCacheManager.SERVICE.getInstance(myProject);
checkCache(cache, todocache);
VirtualFile child = myRootDir.findChild("1.java");
checkCache(cache, todocache);
setFileText(child, "xxx");
setFileText(child, "xxx");
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
final GlobalSearchScope scope = GlobalSearchScope.projectScope(myProject);
checkResult(new String[] {"1.java"}, convert(cache.getFilesWithWord("xxx", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{}, convert(cache.getFilesWithWord("a", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"2.java"}, convert(cache.getFilesWithWord("b", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"2.java", "3.java"}, convert(cache.getFilesWithWord("c", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"2.java", "3.java"}, convert(cache.getFilesWithWord("d", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"3.java"}, convert(cache.getFilesWithWord("e", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"3.java"}, convert(todocache.getFilesWithTodoItems()));
assertEquals(0, todocache.getTodoCount(myRootDir.findChild("1.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(0, todocache.getTodoCount(myRootDir.findChild("2.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(2, todocache.getTodoCount(myRootDir.findChild("3.java"), TodoIndexPatternProvider.getInstance()));
}
public void testFileDeletion() {
final CacheManager cache = CacheManager.SERVICE.getInstance(myProject);
final TodoCacheManager todocache = TodoCacheManager.SERVICE.getInstance(myProject);
checkCache(cache, todocache);
VirtualFile child = myRootDir.findChild("1.java");
delete(child);
final GlobalSearchScope scope = GlobalSearchScope.projectScope(myProject);
checkResult(new String[]{}, convert(cache.getFilesWithWord("xxx", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{}, convert(cache.getFilesWithWord("a", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"2.java"}, convert(cache.getFilesWithWord("b", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"2.java", "3.java"}, convert(cache.getFilesWithWord("c", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"2.java", "3.java"}, convert(cache.getFilesWithWord("d", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"3.java"}, convert(cache.getFilesWithWord("e", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"3.java"}, convert(todocache.getFilesWithTodoItems()));
assertEquals(0, todocache.getTodoCount(myRootDir.findChild("2.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(2, todocache.getTodoCount(myRootDir.findChild("3.java"), TodoIndexPatternProvider.getInstance()));
}
public void testFileCreation() {
final CacheManager cache = CacheManager.SERVICE.getInstance(myProject);
final TodoCacheManager todocache = TodoCacheManager.SERVICE.getInstance(myProject);
checkCache(cache, todocache);
VirtualFile child = createChildData(myRootDir, "4.java");
setFileText(child, "xxx //todo");
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
final GlobalSearchScope scope = GlobalSearchScope.projectScope(myProject);
checkResult(new String[]{"4.java"}, convert(cache.getFilesWithWord("xxx", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"1.java"}, convert(cache.getFilesWithWord("a", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"1.java", "2.java"}, convert(cache.getFilesWithWord("b", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"1.java", "2.java", "3.java"}, convert(cache.getFilesWithWord("c", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"2.java", "3.java"}, convert(cache.getFilesWithWord("d", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"3.java"}, convert(cache.getFilesWithWord("e", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"1.java", "3.java", "4.java"}, convert(todocache.getFilesWithTodoItems()));
assertEquals(1, todocache.getTodoCount(myRootDir.findChild("1.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(0, todocache.getTodoCount(myRootDir.findChild("2.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(2, todocache.getTodoCount(myRootDir.findChild("3.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(1, todocache.getTodoCount(myRootDir.findChild("4.java"), TodoIndexPatternProvider.getInstance()));
}
public void testCrash() {
final CacheManager cache = CacheManager.SERVICE.getInstance(myProject);
cache.getFilesWithWord("xxx", UsageSearchContext.ANY, GlobalSearchScope.projectScope(myProject), false);
System.gc();
}
private void checkCache(CacheManager cache, TodoCacheManager todocache) {
final GlobalSearchScope scope = GlobalSearchScope.projectScope(myProject);
checkResult(ArrayUtilRt.EMPTY_STRING_ARRAY, convert(cache.getFilesWithWord("xxx", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"1.java"}, convert(cache.getFilesWithWord("a", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"1.java", "2.java"}, convert(cache.getFilesWithWord("b", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"1.java", "2.java", "3.java"}, convert(cache.getFilesWithWord("c", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"2.java", "3.java"}, convert(cache.getFilesWithWord("d", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"3.java"}, convert(cache.getFilesWithWord("e", UsageSearchContext.ANY, scope, false)));
checkResult(new String[]{"1.java", "3.java"}, convert(todocache.getFilesWithTodoItems()));
assertEquals(1, todocache.getTodoCount(myRootDir.findChild("1.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(0, todocache.getTodoCount(myRootDir.findChild("2.java"), TodoIndexPatternProvider.getInstance()));
assertEquals(2, todocache.getTodoCount(myRootDir.findChild("3.java"), TodoIndexPatternProvider.getInstance()));
}
private static VirtualFile[] convert(PsiFile[] psiFiles) {
final VirtualFile[] files = new VirtualFile[psiFiles.length];
for (int idx = 0; idx < psiFiles.length; idx++) {
files[idx] = psiFiles[idx].getVirtualFile();
}
return files;
}
private static void checkResult(String[] expected, VirtualFile[] result){
assertEquals(expected.length, result.length);
Arrays.sort(expected);
Arrays.sort(result, (o1, o2) -> {
VirtualFile file1 = o1;
VirtualFile file2 = o2;
return file1.getName().compareTo(file2.getName());
});
for(int i = 0; i < expected.length; i++){
String name = expected[i];
assertEquals(name, result[i].getName());
}
}
}
|
smeyffret/SCARS | Util/src/test/scala/fr/cnrs/liris/scars/math/ProbabilityUniformTest.scala | package fr.cnrs.liris.scars.math
import org.scalatest.FunSuite
import org.scalatest.matchers.ShouldMatchers
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
/**
* @author <NAME>
* @version 0.0.1
* @since scala 2.8
* Date: 9 déc. 2010
* Time: 12:32:04
*/
@RunWith(classOf[JUnitRunner])
class ProbabilityUniformTest extends FunSuite with ShouldMatchers {
val r = Probability
val PICK = 5
test("A bigger collection should return the goog number of random elements") {
val NB_TRIES = 100
val elements = (1 to 10).toList
val tirages = (1 to NB_TRIES).map{ _ =>
val result = r.selectUniformaly(elements, PICK)
result should have size(PICK)
result.reduceLeft(_+_)
}
val randomSum = tirages.reduceLeft(_+_) / NB_TRIES
val totalSum = elements.reduceLeft(_+_)
randomSum should be( totalSum / 2 plusOrMinus 3)
}
testDistribution(5)
testDistribution(9)
//test("Random elements should be uniformaly distributed") {
def testDistribution(pick: Int){
val MAX = 1500
val EXPECTED = MAX * pick / 10
val MORE_OR_LESS = EXPECTED / 10
val elements = (1 to 10).toList
var distribution = collection.mutable.Map[Int, Int]()
(1 to MAX) foreach { _ =>
r.selectUniformaly(elements, pick) foreach { i =>
distribution(i) = distribution.getOrElse(i, 0) + 1
}
}
//println(distribution)
distribution.foreach{ case (i,d) =>
test("%d should have more or less %d apparition in a %d population".format(i, EXPECTED, MAX)) {
d should be (EXPECTED plusOrMinus MORE_OR_LESS)
}
}
}
}
// vim: set ts=2 sw=2 et:
|
croconaut/wifon | app/src/main/java/com/croconaut/ratemebuddy/ui/preferences/MyPreferenceCategory.java | <filename>app/src/main/java/com/croconaut/ratemebuddy/ui/preferences/MyPreferenceCategory.java<gh_stars>0
package com.croconaut.ratemebuddy.ui.preferences;
import android.content.Context;
import android.content.res.Resources;
import android.preference.PreferenceCategory;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;
import com.croconaut.ratemebuddy.R;
public class MyPreferenceCategory extends PreferenceCategory {
private Context context;
public MyPreferenceCategory(Context context) {
super(context);
this.context = context;
}
public MyPreferenceCategory(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public MyPreferenceCategory(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
this.context = context;
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
theme.resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
TextView titleView = (TextView) view.findViewById(android.R.id.title);
titleView.setTextColor(typedValue.data);
}
} |
rpau/java-symbol-solver | java-symbol-solver-testing/src/test/resources/javaparser_new_src/javaparser-core/com/github/javaparser/ast/body/VariableDeclarator.java | /*
* Copyright (C) 2007-2010 <NAME>.
* Copyright (C) 2011, 2013-2016 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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 Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import com.github.javaparser.Range;
import com.github.javaparser.ast.ArrayBracketPair;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.nodeTypes.NodeWithElementType;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.type.ArrayType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.utils.Pair;
import java.util.List;
import static com.github.javaparser.ast.type.ArrayType.wrapInArrayTypes;
/**
* @author <NAME>
*/
public final class VariableDeclarator extends Node implements
NodeWithType<VariableDeclarator> {
private VariableDeclaratorId id;
private Expression init;
public VariableDeclarator() {
}
public VariableDeclarator(VariableDeclaratorId id) {
setId(id);
}
public VariableDeclarator(String variableName) {
setId(new VariableDeclaratorId(variableName));
}
/**
* Defines the declaration of a variable.
*
* @param id The identifier for this variable. IE. The variables name.
* @param init What this variable should be initialized to.
* An {@link com.github.javaparser.ast.expr.AssignExpr} is unnecessary as the <code>=</code> operator is
* already added.
*/
public VariableDeclarator(VariableDeclaratorId id, Expression init) {
setId(id);
setInit(init);
}
public VariableDeclarator(String variableName, Expression init) {
setId(new VariableDeclaratorId(variableName));
setInit(init);
}
public VariableDeclarator(Range range, VariableDeclaratorId id, Expression init) {
super(range);
setId(id);
setInit(init);
}
@Override
public <R, A> R accept(GenericVisitor<R, A> v, A arg) {
return v.visit(this, arg);
}
@Override
public <A> void accept(VoidVisitor<A> v, A arg) {
v.visit(this, arg);
}
public VariableDeclaratorId getId() {
return id;
}
public Expression getInit() {
return init;
}
public VariableDeclarator setId(VariableDeclaratorId id) {
this.id = id;
setAsParentNodeOf(this.id);
return this;
}
public VariableDeclarator setInit(Expression init) {
this.init = init;
setAsParentNodeOf(this.init);
return this;
}
/**
* Will create a {@link NameExpr} with the init param
*/
public VariableDeclarator setInit(String init) {
this.init = new NameExpr(init);
setAsParentNodeOf(this.init);
return this;
}
@Override
public Type getType() {
NodeWithElementType<?> elementType = getParentNodeOfType(NodeWithElementType.class);
return wrapInArrayTypes(elementType.getElementType(),
elementType.getArrayBracketPairsAfterElementType(),
getId().getArrayBracketPairsAfterId());
}
@Override
public VariableDeclarator setType(Type type) {
Pair<Type, List<ArrayBracketPair>> unwrapped = ArrayType.unwrapArrayTypes(type);
NodeWithElementType<?> nodeWithElementType = getParentNodeOfType(NodeWithElementType.class);
if (nodeWithElementType == null) {
throw new IllegalStateException("Cannot set type without a parent");
}
nodeWithElementType.setElementType(unwrapped.a);
nodeWithElementType.setArrayBracketPairsAfterElementType(null);
getId().setArrayBracketPairsAfterId(unwrapped.b);
return this;
}
}
|
coolwangfei/marss-riscv | src/riscvsim/riscv_sim_macros.h | <reponame>coolwangfei/marss-riscv<gh_stars>1-10
/**
* Global typedefs and macros used by MARSS-RISCV
*
* Copyright (c) 2016-2017 <NAME>
*
* MARSS-RISCV : Micro-Architectural System Simulator for RISC-V
*
* Copyright (c) 2017-2019 <NAME> {<EMAIL>}
* State University of New York at Binghamton
*
* Copyright (c) 2018-2019 <NAME> {<EMAIL>}
* State University of New York at Binghamton
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef _RISCV_SIM_MACROS_H_
#define _RISCV_SIM_MACROS_H_
/* Type of Functional Units */
#define FU_ALU 0x0
#define FU_MUL 0x1
#define FU_DIV 0x2
#define FU_FPU_ALU 0x3
#define FU_FPU_FMA 0x4
#define NUM_MAX_FU 5
/* Type of Branch instructions */
#define BRANCH_UNCOND 0x0
#define BRANCH_COND 0x1
#define BRANCH_FUNC_CALL 0x2
#define BRANCH_FUNC_RET 0x3
/* Extension C Quadrants */
#define C_QUADRANT0 0
#define C_QUADRANT1 1
#define C_QUADRANT2 2
/* Major Opcodes */
#define OP_IMM_MASK 0x13
#define OP_IMM_32_MASK 0x1b
#define OP_MASK 0x33
#define OP_MASK_32 0x3b
#define LUI_MASK 0x37
#define AUIPC_MASK 0x17
#define JAL_MASK 0x6f
#define JALR_MASK 0x67
#define BRANCH_MASK 0x63
#define LOAD_MASK 0x3
#define STORE_MASK 0x23
#define FENCE_MASK 0xf
#define CSR_MASK 0x73
#define ATOMIC_MASK 0x2F
/* Floating Point Instructions */
#define FLOAD_MASK 0x07
#define FSTORE_MASK 0x27
#define FMADD_MASK 0x43
#define FMSUB_MASK 0x47
#define FNMSUB_MASK 0x4B
#define FNMADD_MASK 0x4F
#define F_ARITHMETIC_MASK 0x53
/* Used as stage IDs for in-order pipeline */
#define PCGEN 0x0
#define FETCH 0x1
#define DECODE 0x2
#define MEMORY 0x3
#define COMMIT 0x4
#define NUM_CPU_STAGES 5 /* Excluding the functional units which are allocated separately */
#define NUM_INT_REG 32
#define NUM_FP_REG 32
#define NUM_FU 5 /* ALU, MUL, DIV, FP ALU, FP FMA */
#define NUM_FWD_BUS 6 /* Total 6 forwarding buses, 5 for functional units and 1 for memory stage */
#define INCORE_NUM_INS_DISPATCH_QUEUE_ENTRY 16
#define SPEC_REG_STATE_ENTRY 128
#define RISCV_INS_STR_MAX_LENGTH 64
/* NOTE: IMAP size must always be greater than ROB size */
#define NUM_IMAP_ENTRY 128
#define IMAP_ENTRY_STATUS_FREE 0
#define IMAP_ENTRY_STATUS_ALLOCATED 1
/* Used to check pipeline drain status in case of exception inside simulator */
#define PIPELINE_NOT_DRAINED 0
#define PIPELINE_DRAINED 1
#define NUM_MAX_PRV_LEVELS 4
/* Used for updating performance counters */
#define NUM_MAX_INS_TYPES 17
#define INS_TYPE_LOAD 0x0
#define INS_TYPE_STORE 0x1
#define INS_TYPE_ATOMIC 0x2
#define INS_TYPE_SYSTEM 0x3
#define INS_TYPE_ARITMETIC 0x4
#define INS_TYPE_COND_BRANCH 0x5
#define INS_TYPE_JAL 0x6
#define INS_TYPE_JALR 0x7
#define INS_TYPE_INT_MUL 0x8
#define INS_TYPE_INT_DIV 0x9
#define INS_TYPE_FP_LOAD 0xa
#define INS_TYPE_FP_STORE 0xb
#define INS_TYPE_FP_ADD 0xc
#define INS_TYPE_FP_MUL 0xd
#define INS_TYPE_FP_FMA 0xe
#define INS_TYPE_FP_DIV_SQRT 0xf
#define INS_TYPE_FP_MISC 0x10
#define INS_CLASS_INT 0x11
#define INS_CLASS_FP 0x12
/* For Branch prediction unit */
#define BPU_MISS 0x0
#define BPU_HIT 0x1
#define GET_NUM_BITS(x) ceil(log2((x)))
#define GET_INDEX(x, bits) ((x) & ((1 << (bits)) - 1))
#define PRINT_INIT_MSG(str) fprintf(stderr, " \x1B[32m*\x1B[0m " str "...\n")
#define PRINT_PROG_TITLE_MSG(str) fprintf(stderr, "\x1B[32m\x1B[0m " str "\n\n")
/* For exception handling during simulation */
#define SIM_ILLEGAL_OPCODE 0x1
#define SIM_COMPLEX_OPCODE 0x2
#define SIM_TIMEOUT_EXCEPTION 0x3
#define SIM_MMU_EXCEPTION 0x4
#define REALTIME_STATS_CLOCK_CYCLES_INTERVAL 500000
/* Instruction types processed by FPU ALU. This is used to set the latencies. */
#define FU_FPU_ALU_FADD 0x0
#define FU_FPU_ALU_FSUB 0x1
#define FU_FPU_ALU_FMUL 0x2
#define FU_FPU_ALU_FDIV 0x3
#define FU_FPU_ALU_FSQRT 0x4
#define FU_FPU_ALU_FSGNJ 0x5
#define FU_FPU_ALU_FMIN 0x6
#define FU_FPU_ALU_FMAX 0x7
#define FU_FPU_ALU_FEQ 0x8
#define FU_FPU_ALU_FLT 0x9
#define FU_FPU_ALU_FLE 0xa
#define FU_FPU_ALU_FCVT 0xb
#define FU_FPU_ALU_CVT 0xc
#define FU_FPU_ALU_FMV 0xd
#define FU_FPU_ALU_FCLASS 0xe
#define MAX_FU_FPU_ALU_TYPES 15
#endif
|
DrWolf-OSS/force | force-ejb/ejbModule/it/drwolf/slot/alfresco/custom/model/SlotModel.java | <filename>force-ejb/ejbModule/it/drwolf/slot/alfresco/custom/model/SlotModel.java
package it.drwolf.slot.alfresco.custom.model;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
@Root(name = "model")
@Namespace(reference = "http://www.alfresco.org/model/dictionary/1.0")
public class SlotModel {
@Attribute
private String name;
@Element
private String description;
@Element
private String author;
@Element
private String version;
@ElementList
private List<Import> imports;
@ElementList
private List<it.drwolf.slot.alfresco.custom.model.Namespace> namespaces;
@ElementList
private List<Aspect> aspects;
@ElementList
private List<Constraint> constraints;
public SlotModel() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public List<Import> getImports() {
return imports;
}
public void setImports(List<Import> imports) {
this.imports = imports;
}
public List<it.drwolf.slot.alfresco.custom.model.Namespace> getNamespaces() {
return namespaces;
}
public void setNamespaces(
List<it.drwolf.slot.alfresco.custom.model.Namespace> namespaces) {
this.namespaces = namespaces;
}
public List<Aspect> getAspects() {
return aspects;
}
public void setAspects(List<Aspect> aspects) {
this.aspects = aspects;
}
public List<Constraint> getConstraints() {
return constraints;
}
public void setConstraints(List<Constraint> constraints) {
this.constraints = constraints;
}
}
|
sycle/sycle-gateway | server/config/middleware.js | module.exports = {
"initial:before": {
"expressx#logger": {
"enabled": true,
"params": "combined"
},
"connect-powered-by": {
"params": "sycle-gateway"
},
"cors": {
},
"strong-express-metrics": {
}
},
"initial": {
"compression": {
"params": {
"threshold": "4kb"
}
},
"body-parser#urlencoded": {
"params": { "extended": false }
},
"body-parser#json": {},
"method-override": {}
},
"session": {
"express-session": {
"params": {
"saveUninitialized": true,
"resave": true,
"secret": "keyboard cat"
}
}
},
"auth": {
"copress-component-oauth2#authenticate": {
"paths": [
"/_internal",
"/protected",
"/api",
"/me"
],
"params": {
"session": false,
"scopes": {
"demo": [
"/me", "/protected", "/_internal", "/api/note"
],
"note": [
{
"methods": "all",
"path": "/api/note"
}
]
}
}
}
},
"routes:before": {
"./middleware/https-redirect": {}
},
"routes:after": {
"./middleware/rate-limiting-policy": {
"paths": ["/api", "/protected"],
"params": {
"limit": 100,
"interval": 60000,
"keys": {
"app": {
"template": "app-${app.id}",
"limit": 1000
},
"ip": 500,
"url": {
"template": "url-${urlPaths[0]}/${urlPaths[1]}",
"limit": 1000
},
"user": {
"template": "user-${user.id}",
"limit": 1000
},
"app,user": {
"template": "app-${app.id}-user-${user.id}",
"limit": 1000
}
}
}
},
"./middleware/proxy": {
"params": {
"rules": [
"^/api/(.*)$ http://localhost:3002/api/$1 [P]",
"^/protected/(.*)$ http://localhost:3000/protected/$1 [P]"
]
}
}
},
"files": {
"serve-static": [
{
"params": "$!../../client/public",
"paths": ["/"]
},
{
"params": "$!../../client/admin",
"paths": ["/admin"]
}
]
},
"final": {
"expressx#urlNotFound": {}
},
"final:after": {
"errorhandler": {"params": {"log": true}}
}
}; |
idvoretskyi/trickster | pkg/proxy/headers/forwarding.go | /*
* Copyright 2018 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package headers
import (
"fmt"
"net"
"net/http"
"strings"
"github.com/tricksterproxy/trickster/pkg/runtime"
)
const (
// NameVia represents the HTTP Header Name of "Via"
NameVia = "Via"
// NameForwarded reqresents the HTTP Header Name of "Forwarded"
NameForwarded = "Forwarded"
// NameXForwardedFor represents the HTTP Header Name of "X-Forwarded-For"
NameXForwardedFor = "X-Forwarded-For"
// NameXForwardedServer represents the HTTP Header Name of "X-Forwarded-Server"
NameXForwardedServer = "X-Forwarded-Server"
// NameXForwardedHost represents the HTTP Header Name of "X-Forwarded-Host"
NameXForwardedHost = "X-Forwarded-Host"
// NameXForwardedProto represents the HTTP Header Name of "X-Forwarded-Proto"
NameXForwardedProto = "X-Forwarded-Proto"
)
// Hop describes a collection of data about the forwarded request
// to be used in Via, Forwarded and X-Forwarded-* headers
type Hop struct {
// RemoteAddr is the client address for which the request is being forwarded.
RemoteAddr string
// Host header as received by the proxy
Host string
// Scheme is the protocol scheme requested of the proxy
Scheme string
// Server is an identier for the server running the Trickster process
Server string
// protocol indicates the HTTP protocol Version in proper format (.eg., "HTTP/1.1")
// requested by the client
Protocol string
// Hops is a list of previous X-Forwarded-For or Forwarded headers to which we can append our hop
Hops Hops
// Via is the previous Via header, we will append ours to it.
Via string
}
// Hops defines a list of Hop References
type Hops []*Hop
// HopHeaders defines a list of headers that Proxies should not pass through
var HopHeaders = []string{
NameAcceptEncoding,
NameConnection,
NameProxyConnection,
NameKeepAlive,
NameProxyAuthenticate,
NameProxyAuthorization,
NameTe,
NameTrailer,
NameTransferEncoding,
NameUpgrade,
NameAcceptEncoding,
}
// ForwardingHeaders defines a list of headers that Proxies use to identify themselves in a request
var ForwardingHeaders = []string{
NameXForwardedFor,
NameXForwardedHost,
NameXForwardedProto,
NameXForwardedServer,
NameForwarded,
NameVia,
}
// MergeRemoveHeaders defines a list of headers that should be removed when Merging time series results
var MergeRemoveHeaders = []string{
NameLastModified,
NameDate,
NameContentLength,
NameContentType,
NameTransferEncoding,
}
var forwardingFuncs = map[string]func(*http.Request, *Hop){
"standard": AddForwarded,
"x": AddXForwarded,
"none": nil,
"both": AddForwardedAndX,
}
// IsValidForwardingType returns true if the input is a valid Forwarding Type name
// Valid names comprise the keys of the forwardingFuncs map
func IsValidForwardingType(input string) bool {
_, ok := forwardingFuncs[input]
return ok
}
// AddForwardingHeaders sets or appends to the forwarding headers to the provided request
func AddForwardingHeaders(r *http.Request, headerType string) {
if r == nil {
return
}
hop := HopsFromRequest(r)
// Now we can safely remove any pre-existing Forwarding headers before we set them fresh
StripClientHeaders(r.Header)
StripForwardingHeaders(r.Header)
SetVia(r, hop)
if f, ok := forwardingFuncs[headerType]; ok && f != nil {
f(r, hop)
}
}
// String returns a "Forwarded" Header value
func (hop *Hop) String(expand ...bool) string {
parts := make([]string, 0, 4)
if hop.Server != "" {
parts = append(parts, fmt.Sprintf("by=%s", formatForwardedAddress(hop.Server)))
}
if hop.RemoteAddr != "" {
parts = append(parts, fmt.Sprintf("for=%s", formatForwardedAddress(hop.RemoteAddr)))
}
if hop.Host != "" {
parts = append(parts, fmt.Sprintf("host=%s", formatForwardedAddress(hop.Host)))
}
if hop.Scheme != "" {
parts = append(parts, fmt.Sprintf("proto=%s", formatForwardedAddress(hop.Scheme)))
}
currentHop := strings.Join(parts, ";")
if (len(expand) == 1 && !expand[0]) || len(hop.Hops) == 0 {
return currentHop
}
l := len(hop.Hops)
parts = make([]string, l+1)
for i := 0; i < l; i++ {
parts[i] = hop.Hops[i].String(false)
}
parts[l] = currentHop
return strings.Join(parts, ", ")
}
// XHeader returns an http.Header containing the "X-Forwarded-*" headers
func (hop *Hop) XHeader() http.Header {
h := make(http.Header)
if hop.Server != "" {
h.Set(NameXForwardedServer, hop.Server)
}
if hop.RemoteAddr != "" {
l := len(hop.Hops)
if l > 0 {
Hops := make([]string, l+1)
for i, hop := range hop.Hops {
Hops[i] = hop.RemoteAddr
}
Hops[l] = hop.RemoteAddr
h.Set(NameXForwardedFor, strings.Join(Hops, ", "))
} else {
h.Set(NameXForwardedFor, hop.RemoteAddr)
}
}
if hop.Host != "" {
h.Set(NameXForwardedHost, hop.Host)
}
if hop.Scheme != "" {
h.Set(NameXForwardedProto, hop.Scheme)
}
return h
}
// AddForwarded sets or appends to the standard Forwarded header to the provided request
func AddForwarded(r *http.Request, hop *Hop) {
r.Header.Set(NameForwarded, hop.String())
}
// AddXForwarded sets or appends to the "X-Forwarded-*" headers to the provided request
func AddXForwarded(r *http.Request, hop *Hop) {
h := hop.XHeader()
Merge(r.Header, h)
}
// AddForwardedAndX sets or appends to the to the "X-Forwarded-*" headers
// headers, and to the standard Forwarded header to the provided request
func AddForwardedAndX(r *http.Request, hop *Hop) {
h := hop.XHeader()
h.Set(NameForwarded, hop.String())
Merge(r.Header, h)
}
// SetVia sets the "Via" header to the provided request
func SetVia(r *http.Request, hop *Hop) {
if r == nil || r.Header == nil || hop == nil {
return
}
if hop.Via != "" {
r.Header.Set(NameVia, hop.Via+", "+hop.Protocol+" "+runtime.Server)
} else {
r.Header.Set(NameVia, hop.Protocol+" "+runtime.Server)
}
}
// HopsFromRequest extracts a Hop reference that includes a list of any previous hops
func HopsFromRequest(r *http.Request) *Hop {
clientIP, _, _ := net.SplitHostPort(r.RemoteAddr)
hop := &Hop{
RemoteAddr: clientIP,
Scheme: r.URL.Scheme,
Protocol: r.Proto,
}
if r.Header == nil {
return hop
}
hop.Via = r.Header.Get(NameVia)
hop.Hops = HopsFromHeader(r.Header)
return hop
}
// HopsFromHeader extracts a hop from the header
func HopsFromHeader(h http.Header) Hops {
if _, ok := h[NameForwarded]; ok {
return parseForwardHeaders(h)
} else if _, ok := h[NameXForwardedFor]; ok {
return parseXForwardHeaders(h)
}
return nil
}
func parseForwardHeaders(h http.Header) Hops {
var hops Hops
fh := h.Get(NameForwarded)
if fh != "" {
fwds := strings.Split(strings.Replace(fh, " ", "", -1), ",")
hops = make(Hops, 0, len(fwds))
for _, f := range fwds {
hop := &Hop{}
var ok bool
parts := strings.Split(f, ";")
for _, p := range parts {
subparts := strings.Split(p, "=")
if len(subparts) == 2 {
switch subparts[0] {
case "for":
hop.RemoteAddr = subparts[1]
ok = true
case "by":
hop.Server = subparts[1]
case "proto":
hop.Protocol = subparts[1]
case "host":
hop.Host = subparts[1]
}
}
}
if ok {
hop.normalizeAddresses()
hops = append(hops, hop)
}
}
}
return hops
}
func (hop *Hop) normalizeAddresses() {
hop.Host = normalizeAddress(hop.Host)
hop.RemoteAddr = normalizeAddress(hop.RemoteAddr)
hop.Server = normalizeAddress(hop.Server)
}
const v6LB = `["`
const v6RB = `"]`
func normalizeAddress(input string) string {
input = strings.TrimPrefix(input, v6LB)
input = strings.TrimSuffix(input, v6RB)
return input
}
func formatForwardedAddress(input string) string {
if isV6Address(input) {
input = v6LB + input + v6RB
}
return input
}
func parseXForwardHeaders(h http.Header) Hops {
xff := h.Get(NameXForwardedFor)
if xff != "" {
fwds := strings.Split(strings.Replace(xff, " ", "", -1), ",")
hops := make(Hops, len(fwds))
for i, f := range fwds {
hop := &Hop{RemoteAddr: f}
hop.Host = h.Get(NameXForwardedHost)
hop.Protocol = h.Get(NameXForwardedProto)
hop.Server = h.Get(NameXForwardedServer)
hop.normalizeAddresses()
hops[i] = hop
}
return hops
}
return nil
}
// AddResponseHeaders injects standard Trickster headers into downstream HTTP responses
func AddResponseHeaders(h http.Header) {
// We're read only and a harmless API, so allow all CORS
h.Set(NameAllowOrigin, "*")
}
// StripClientHeaders strips certain headers from the HTTP request to facililate acceleration
func StripClientHeaders(h http.Header) {
for _, k := range HopHeaders {
h.Del(k)
}
}
// StripForwardingHeaders strips certain headers from the HTTP request to facililate acceleration
func StripForwardingHeaders(h http.Header) {
for _, k := range ForwardingHeaders {
h.Del(k)
}
}
func isV6Address(input string) bool {
ip := net.ParseIP(input)
return ip != nil && strings.Contains(input, ":")
}
// StripMergeHeaders strips certain headers from the HTTP request to facililate acceleration when
// merging HTTP responses from multiple origins
func StripMergeHeaders(h http.Header) {
for _, k := range MergeRemoveHeaders {
h.Del(k)
}
}
|
Neroho/Test | src/digitalDigest/RSA.java | package digitalDigest;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
public class RSA {
private static String src="This's RSA";
/**
*
*/
public static void jdkRSA(){
KeyPairGenerator keyPairGenerator;
try {
//init private key
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(512);
KeyPair keyPair=keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey=(RSAPublicKey)keyPair.getPublic();
RSAPrivateKey rsaPrivateKey=(RSAPrivateKey)keyPair.getPrivate();
PKCS8EncodedKeySpec pkcs8=new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
KeyFactory keyFactory=KeyFactory.getInstance("RSA");
PrivateKey privateKey=keyFactory.generatePrivate(pkcs8);
//sign数字签名
Signature signature=Signature.getInstance("MD5withRSA");
signature.initSign(privateKey);
signature.update(src.getBytes());
byte[] result = signature.sign();
System.out.println("jdk RSA:"+Hex.encodeHexString(result));
X509EncodedKeySpec x509=new X509EncodedKeySpec(rsaPublicKey.getEncoded());
keyFactory=KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509);
//verify the sign
signature=Signature.getInstance("MD5withRSA");
signature.initVerify(publicKey);
signature.update(src.getBytes());
boolean flag=signature.verify(result);
System.out.println(flag);
//私钥加密,公钥解密--加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
result = cipher.doFinal(src.getBytes());
System.out.println("私钥加密,公钥解密--加密:"+Base64.encodeBase64String(result));
//私钥加密,公钥解密--解密
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
result = cipher.doFinal(result);
System.out.println("私钥加密,公钥解密--解密:"+new String(result));
//公钥加密,私钥解密--加密
x509=new X509EncodedKeySpec(rsaPublicKey.getEncoded());
keyFactory=KeyFactory.getInstance("RSA");
publicKey = keyFactory.generatePublic(x509);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
result = cipher.doFinal(src.getBytes());
System.out.println("公钥加密,私钥解密--加密:"+Base64.encodeBase64String(result));
//公钥加密,私钥解密--解密
pkcs8=new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
keyFactory=KeyFactory.getInstance("RSA");
privateKey=keyFactory.generatePrivate(pkcs8);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
result = cipher.doFinal(result);
System.out.println("公钥加密,私钥解密--解密:"+new String(result));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
jdkRSA();
}
}
|
Teoan/TClass | tclassserver/tclass-user/tclass-user-server-core/src/main/java/com/teoan/tclass/user/mapper/PositionMapper.java | <filename>tclassserver/tclass-user/tclass-user-server-core/src/main/java/com/teoan/tclass/user/mapper/PositionMapper.java
package com.teoan.tclass.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.teoan.tclass.user.entity.Position;
/**
* (Position)表数据库访问层
*
* @author Teoan
* @since 2021-05-19 16:47:44
*/
public interface PositionMapper extends BaseMapper<Position> {
}
|
anmolnar/cloudbreak | core-api/src/main/java/com/sequenceiq/cloudbreak/api/endpoint/v4/connector/responses/PlatformIpPoolsV4Response.java | package com.sequenceiq.cloudbreak.api.endpoint.v4.connector.responses;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.sequenceiq.cloudbreak.api.endpoint.v4.JsonEntity;
@JsonIgnoreProperties(ignoreUnknown = true)
public class PlatformIpPoolsV4Response implements JsonEntity {
private Map<String, Set<IpPoolV4Response>> ippools = new HashMap<>();
public PlatformIpPoolsV4Response() {
}
public PlatformIpPoolsV4Response(Map<String, Set<IpPoolV4Response>> ippools) {
this.ippools = ippools;
}
public Map<String, Set<IpPoolV4Response>> getIppools() {
return ippools;
}
public void setIppools(Map<String, Set<IpPoolV4Response>> ippools) {
this.ippools = ippools;
}
}
|
Shusshu/paperparcel | paperparcel-compiler/src/main/java/paperparcel/PaperParcelAutoValueExtension.java | /*
* Copyright (C) 2016 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package paperparcel;
import com.google.auto.common.MoreElements;
import com.google.auto.common.MoreTypes;
import com.google.auto.service.AutoService;
import com.google.auto.value.extension.AutoValueExtension;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import static javax.lang.model.element.Modifier.*;
@AutoService(AutoValueExtension.class)
public class PaperParcelAutoValueExtension extends AutoValueExtension {
private static final String PARCELABLE_CLASS_NAME = "android.os.Parcelable";
private static final TypeName PARCEL = ClassName.get("android.os", "Parcel");
private static final String NULLABLE_ANNOTATION_NAME = "Nullable";
@Override public boolean applicable(Context context) {
ProcessingEnvironment env = context.processingEnvironment();
Elements elements = env.getElementUtils();
Types types = env.getTypeUtils();
Messager messager = env.getMessager();
TypeMirror parcelable = elements.getTypeElement(PARCELABLE_CLASS_NAME).asType();
TypeElement autoValueTypeElement = context.autoValueClass();
if (types.isAssignable(autoValueTypeElement.asType(), parcelable)) {
PaperParcelAutoValueExtensionValidator extensionValidator =
new PaperParcelAutoValueExtensionValidator(elements, types);
ValidationReport<TypeElement> report = extensionValidator.validate(autoValueTypeElement);
report.printMessagesTo(messager);
return report.isClean();
}
return false;
}
@Override public Set<String> consumeProperties(Context context) {
ImmutableSet.Builder<String> properties = new ImmutableSet.Builder<>();
for (String property : context.properties().keySet()) {
switch (property) {
case "describeContents":
properties.add(property);
break;
}
}
return properties.build();
}
@Override public Set<ExecutableElement> consumeMethods(Context context) {
ImmutableSet.Builder<ExecutableElement> methods = new ImmutableSet.Builder<>();
for (ExecutableElement element : context.abstractMethods()) {
switch (element.getSimpleName().toString()) {
case "writeToParcel":
methods.add(element);
break;
}
}
return methods.build();
}
@Override public boolean mustBeFinal(Context context) {
return true;
}
@Override public String generateClass(
Context context, String simpleName, String classToExtend, boolean isFinal) {
ClassName className = ClassName.get(context.packageName(), simpleName);
TypeSpec.Builder subclass = TypeSpec.classBuilder(className)
.addModifiers(FINAL)
.addMethod(constructor(context))
.addAnnotation(PaperParcel.class)
.addField(creator(className))
.addMethod(writeToParcel(className));
ClassName superClass = ClassName.get(context.packageName(), classToExtend);
List<? extends TypeParameterElement> typeParams = context.autoValueClass().getTypeParameters();
if (typeParams.isEmpty()) {
subclass.superclass(superClass);
} else {
TypeName[] superTypeVariables = new TypeName[typeParams.size()];
for (int i = 0, size = typeParams.size(); i < size; i++) {
TypeParameterElement typeParam = typeParams.get(i);
subclass.addTypeVariable(TypeVariableName.get(typeParam));
superTypeVariables[i] = TypeVariableName.get(typeParam.getSimpleName().toString());
}
subclass.superclass(ParameterizedTypeName.get(superClass, superTypeVariables));
}
if (needsContentDescriptor(context)) {
subclass.addMethod(describeContents());
}
return JavaFile.builder(context.packageName(), subclass.build())
.build()
.toString();
}
private MethodSpec writeToParcel(ClassName className) {
ClassName parcelableImplClassName =
ClassName.get(className.packageName(), "PaperParcel" + className.simpleName());
return MethodSpec.methodBuilder("writeToParcel")
.addAnnotation(Override.class)
.addModifiers(PUBLIC)
.addParameter(PARCEL, "dest")
.addParameter(int.class, "flags")
.addStatement("$T.writeToParcel(this, dest, flags)", parcelableImplClassName)
.build();
}
private FieldSpec creator(ClassName className) {
ClassName creator = ClassName.get("android.os", "Parcelable", "Creator");
TypeName creatorOfClass = ParameterizedTypeName.get(creator, className);
ClassName parcelableImplClassName =
ClassName.get(className.packageName(), "PaperParcel" + className.simpleName());
return FieldSpec.builder(creatorOfClass, "CREATOR", PUBLIC, FINAL, STATIC)
.initializer("$T.CREATOR", parcelableImplClassName)
.build();
}
private MethodSpec constructor(Context context) {
Types types = context.processingEnvironment().getTypeUtils();
DeclaredType declaredValueType = MoreTypes.asDeclared(context.autoValueClass().asType());
ImmutableList.Builder<ParameterSpec> parameterBuilder = ImmutableList.builder();
for (Map.Entry<String, ExecutableElement> entry : context.properties().entrySet()) {
ExecutableType resolvedExecutableType =
MoreTypes.asExecutable(types.asMemberOf(declaredValueType, entry.getValue()));
TypeName typeName = TypeName.get(resolvedExecutableType.getReturnType());
ParameterSpec.Builder spec = ParameterSpec.builder(typeName, entry.getKey());
AnnotationMirror nullableAnnotation =
Utils.getAnnotationWithSimpleName(entry.getValue(), NULLABLE_ANNOTATION_NAME);
if (nullableAnnotation != null) {
spec.addAnnotation(AnnotationSpec.get(nullableAnnotation));
}
parameterBuilder.add(spec.build());
}
ImmutableList<ParameterSpec> parameters = parameterBuilder.build();
CodeBlock parameterList = CodeBlocks.join(FluentIterable.from(parameters)
.transform(new Function<ParameterSpec, CodeBlock>() {
@Override public CodeBlock apply(ParameterSpec parameterSpec) {
return CodeBlock.of("$N", parameterSpec.name);
}
}), ", ");
return MethodSpec.constructorBuilder()
.addParameters(parameters)
.addStatement("super($L)", parameterList)
.build();
}
private static boolean needsContentDescriptor(Context context) {
ProcessingEnvironment env = context.processingEnvironment();
TypeElement autoValueTypeElement = context.autoValueClass();
Elements elements = env.getElementUtils();
@SuppressWarnings("deprecation") // Support for kapt2
ImmutableSet<ExecutableElement> methods =
MoreElements.getLocalAndInheritedMethods(autoValueTypeElement, elements);
for (ExecutableElement element : methods) {
if (element.getSimpleName().contentEquals("describeContents")
&& MoreTypes.isTypeOf(int.class, element.getReturnType())
&& element.getParameters().isEmpty()
&& !element.getModifiers().contains(ABSTRACT)) {
return false;
}
}
return true;
}
private MethodSpec describeContents() {
return MethodSpec.methodBuilder("describeContents")
.addAnnotation(Override.class)
.addModifiers(PUBLIC)
.returns(int.class)
.addStatement("return 0")
.build();
}
}
|
fuxingguoee/Xiaofeiyu | app/src/main/java/com/il360/xiaofeiyu/adapter/UserCreditAdapter.java | package com.il360.xiaofeiyu.adapter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import com.il360.xiaofeiyu.R;
import com.il360.xiaofeiyu.model.hua.UserCredit;
import com.il360.xiaofeiyu.util.DataUtil;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
public class UserCreditAdapter extends BaseAdapter {
private Context context;
private LayoutInflater mInflater;
private List<UserCredit> list;
DecimalFormat df = new DecimalFormat("0.00");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public UserCreditAdapter(List<UserCredit> list, Context context) {
this.context = context;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.listitem_user_credit, null);
holder.llApplyDate = (LinearLayout) convertView.findViewById(R.id.llApplyDate);
holder.tvApplyDate = (TextView) convertView.findViewById(R.id.tvApplyDate);
holder.tvApplyTime = (TextView) convertView.findViewById(R.id.tvApplyTime);
holder.tvLoan = (TextView) convertView.findViewById(R.id.tvLoan);
holder.tvStatus = (TextView) convertView.findViewById(R.id.tvStatus);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String timeStr = sdf.format(list.get(position).getCreateTime());
if(position > 0){
String timeStr1 = sdf.format(list.get(position-1).getCreateTime());
if(DataUtil.getDate(timeStr).equals(DataUtil.getDate(timeStr1))){
holder.llApplyDate.setVisibility(View.GONE);
} else {
holder.llApplyDate.setVisibility(View.VISIBLE);
}
} else {
holder.llApplyDate.setVisibility(View.VISIBLE);
}
holder.tvApplyDate.setText("申请日期:" + DataUtil.getDate(timeStr));
holder.tvApplyTime.setText(DataUtil.getTime(timeStr));
holder.tvLoan.setText(list.get(position).getAmount() + "元");
holder.tvStatus.setText(list.get(position).getChstatus());
if (list.get(position).getStatus() != null && list.get(position).getStatus() == 0) {
holder.tvStatus.setTextColor(context.getResources().getColor(R.color.green));
} else {
holder.tvStatus.setTextColor(context.getResources().getColor(R.color.red));
}
return convertView;
}
class ViewHolder {
LinearLayout llApplyDate;
TextView tvApplyDate;
TextView tvApplyTime;
TextView tvLoan;
TextView tvStatus;
}
}
|
Atelier-Developers/atelier-workshop-website-api | src/main/java/com/atelier/atelier/repository/Form/FileAnswerRepository.java | package com.atelier.atelier.repository.Form;
import com.atelier.atelier.entity.FormService.FileAnswer;
import org.springframework.data.jpa.repository.JpaRepository;
public interface FileAnswerRepository extends JpaRepository<FileAnswer, Long> {
}
|
rjw57/tiw-computer | emulator/src/devices/bus/nubus/nubus_48gc.h | // license:BSD-3-Clause
// copyright-holders:<NAME>
#ifndef MAME_BUS_NUBUS_NUBUS_48GC_H
#define MAME_BUS_NUBUS_NUBUS_48GC_H
#pragma once
#include "nubus.h"
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
// ======================> jmfb_device
class jmfb_device :
public device_t,
public device_video_interface,
public device_nubus_card_interface
{
protected:
// construction/destruction
jmfb_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock, bool is824);
// device-level overrides
virtual void device_start() override;
virtual void device_reset() override;
virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) override;
// optional information overrides
virtual void device_add_mconfig(machine_config &config) override;
virtual const tiny_rom_entry *device_rom_region() const override;
private:
DECLARE_READ32_MEMBER(mac_48gc_r);
DECLARE_WRITE32_MEMBER(mac_48gc_w);
uint32_t screen_update(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect);
screen_device *m_screen;
emu_timer *m_timer;
std::vector<uint8_t> m_vram;
uint32_t m_mode, m_vbl_disable, m_toggle, m_stride, m_base;
uint32_t m_palette[256], m_colors[3], m_count, m_clutoffs;
uint32_t m_registers[0x100];
int m_xres, m_yres;
const bool m_is824;
const std::string m_assembled_tag;
};
class nubus_48gc_device : public jmfb_device
{
public:
nubus_48gc_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock);
};
class nubus_824gc_device : public jmfb_device
{
public:
nubus_824gc_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock);
virtual const tiny_rom_entry *device_rom_region() const override;
};
// device type definition
DECLARE_DEVICE_TYPE(NUBUS_48GC, nubus_48gc_device)
DECLARE_DEVICE_TYPE(NUBUS_824GC, nubus_824gc_device)
#endif /// MAME_BUS_NUBUS_NUBUS_48GC_H
|
Yzx835/AISafety | Datasets/base.py | # !/usr/bin/env python
# coding=UTF-8
"""
@Author: <NAME>
@LastEditors: <NAME>
@Description:
@Date: 2021-08-16
@LastEditTime: 2022-04-15
Dataset类,用于载入数据进行模型评测,
主要基于TextAttack的实现
"""
import os
import re
import random
import math
import multiprocessing as mp
from string import punctuation
from collections import OrderedDict, Counter
from typing import List, Tuple, Optional, Dict, NoReturn, Sequence, Union, Iterable
from numbers import Real
import pandas as pd
from torch.utils.data import Dataset as TD
from datasets import (
Dataset as HFD,
NamedSplit as HFNS,
load_dataset as HFD_load_dataset,
)
from zhon.hanzi import punctuation as zh_punctuation
from utils.strings import LANGUAGE, ReprMixin
from utils.attacked_text import AttackedText
__all__ = [
"NLPDataset",
]
class NLPDataset(ReprMixin, TD):
""" """
__name__ = "NLPDataset"
def __init__(
self,
dataset: List[tuple],
input_columns: List[str] = ["text"],
label_map: Optional[Dict[int, int]] = None,
label_names: Optional[List[str]] = None,
output_scale_factor: Optional[float] = None,
shuffle: bool = False,
max_len: Optional[int] = 512,
) -> NoReturn:
"""
@param {
dataset:
A list of :obj:`(input, output)` pairs.
If :obj:`input` consists of multiple fields (e.g. "premise" and "hypothesis" for SNLI),
:obj:`input` must be of the form :obj:`(input_1, input_2, ...)` and :obj:`input_columns` parameter must be set.
:obj:`output` can either be an integer representing labels for classification or a string for seq2seq tasks.
input_columns:
List of column names of inputs in order.
label_map:
Mapping if output labels of the dataset should be re-mapped. Useful if model was trained with a different label arrangement.
For example, if dataset's arrangement is 0 for `Negative` and 1 for `Positive`, but model's label
arrangement is 1 for `Negative` and 0 for `Positive`, passing :obj:`{0: 1, 1: 0}` will remap the dataset's label to match with model's arrangements.
Could also be used to remap literal labels to numerical labels (e.g. :obj:`{"positive": 1, "negative": 0}`).
label_names:
List of label names in corresponding order (e.g. :obj:`["World", "Sports", "Business", "Sci/Tech"]` for AG-News dataset).
If not set, labels will printed as is (e.g. "0", "1", ...). This should be set to :obj:`None` for non-classification datasets.
output_scale_factor:
Factor to divide ground-truth outputs by. Generally, TextAttack goal functions require model outputs between 0 and 1.
Some datasets are regression tasks, in which case this is necessary.
shuffle: Whether to shuffle the underlying dataset.
max_len: Maximum length of input text.
}
@return: None
"""
self._language = LANGUAGE.ENGLISH # default language
self._dataset = dataset
self.input_columns = input_columns
self.label_map = label_map
self.label_names = label_names
if self.label_map and self.label_names:
# If labels are remapped, the label names have to be remapped as well.
self.label_names = [
self.label_names[self.label_map[i]] for i in self.label_map
]
self.shuffled = shuffle
self.output_scale_factor = output_scale_factor
if shuffle:
random.shuffle(self._dataset)
self.max_len = max_len
self._word_freq = None
self._word_log_freq = None
def _format_as_dict(self, example: tuple) -> tuple:
output = example[1]
if self.label_map:
output = self.label_map[output]
if self.output_scale_factor:
output = output / self.output_scale_factor
if isinstance(example[0], str):
if len(self.input_columns) != 1:
raise ValueError(
"Mismatch between the number of columns in `input_columns` and number of columns of actual input."
)
input_dict = OrderedDict(
[(self.input_columns[0], self.clip_text(example[0]))]
)
else:
if len(self.input_columns) != len(example[0]):
raise ValueError(
"Mismatch between the number of columns in `input_columns` and number of columns of actual input."
)
input_dict = OrderedDict(
[
(c, self.clip_text(example[0][i]))
for i, c in enumerate(self.input_columns)
]
)
return input_dict, output
def shuffle(self) -> NoReturn:
random.shuffle(self._dataset)
self.shuffled = True
def filter_by_labels_(self, labels_to_keep: Iterable) -> NoReturn:
"""Filter items by their labels for classification datasets. Performs
in-place filtering.
Args:
labels_to_keep:
Set, tuple, list, or iterable of integers representing labels.
"""
if not isinstance(labels_to_keep, set):
labels_to_keep = set(labels_to_keep)
self._dataset = filter(lambda x: x[1] in labels_to_keep, self._dataset)
def __getitem__(self, i: Union[slice, int]) -> Union[tuple, List[tuple]]:
"""Return i-th sample."""
if isinstance(i, int):
return self._format_as_dict(self._dataset[i])
else:
# `idx` could be a slice or an integer. if it's a slice,
# return the formatted version of the proper slice of the list
return [self._format_as_dict(ex) for ex in self._dataset[i]]
def __len__(self):
"""Returns the size of dataset."""
return len(self._dataset)
@staticmethod
def from_huggingface_dataset(
ds: Union[str, HFD], split: Optional[HFNS] = None
) -> "NLPDataset":
""" """
if isinstance(ds, str):
_ds = HFD_load_dataset(ds, split=split)
else:
_ds = ds
if isinstance(_ds.column_names, dict):
sets = list(_ds.column_names.keys())
column_names = _ds.column_names[sets[0]]
else:
sets = []
column_names = _ds.column_names
input_columns, output_column = _split_dataset_columns(column_names)
if sets:
ret_ds = NLPDataset(
[
(_gen_input(row, input_columns), row[output_column])
for s in sets
for row in _ds[s]
],
input_columns=input_columns,
)
else:
ret_ds = NLPDataset(
[(_gen_input(row, input_columns), row[output_column]) for row in _ds],
input_columns=input_columns,
)
return ret_ds
def get_word_freq(
self,
cache_fp: Optional[str] = None,
use_log: bool = False,
parallel: bool = False,
) -> Dict[str, float]:
""" """
if use_log and self._word_log_freq is not None:
return self._word_log_freq
elif not use_log and self._word_freq is not None:
return self._word_freq
if cache_fp is not None and os.path.exists(cache_fp):
self._word_freq = pd.read_csv(cache_fp)
self._word_freq = {
w: f for w, f in zip(self._word_freq.word, self._word_freq.freq)
}
self._word_log_freq = {w: math.log(f) for w, f in self._word_freq.items()}
if use_log:
return self._word_log_freq
return self._word_freq
if parallel:
with mp.Pool(processes=max(1, mp.cpu_count() - 2)) as pool:
processed = pool.starmap(
_get_word_freq_from_text,
iterable=[
(item[idx], self._language)
for item in self._dataset
for idx in range(len(item) - 1)
],
)
else:
processed = [
_get_word_freq_from_text(item[idx], self._language)
for item in self._dataset
for idx in range(len(item) - 1)
]
self._word_freq = Counter()
for p in processed:
self._word_freq += Counter(p)
self._word_freq = dict(self._word_freq)
self._word_log_freq = {w: math.log(f) for w, f in self._word_freq.items()}
if cache_fp is not None:
to_save = pd.DataFrame(
list(self._word_freq.items()), columns=["word", "freq"]
)
to_save.to_csv(cache_fp, index=False, encoding="utf-8", compression="gzip")
del to_save
if use_log:
return self._word_log_freq
return self._word_freq
@property
def word_freq(self) -> Dict[str, Real]:
""" """
return self._word_freq
@property
def word_log_freq(self) -> Dict[str, Real]:
""" """
return self._word_log_freq
def clip_text(self, text: str) -> str:
""" """
if self.max_len is None:
return text
inds = [
m.start()
for m in re.finditer(f"[{punctuation+zh_punctuation}]", text)
if m.start() < self.max_len
]
if len(inds) == 0:
return text[: self.max_len]
return text[: inds[-1]]
def _get_word_freq_from_text(text: str, language: LANGUAGE) -> Dict[str, float]:
""" """
t = AttackedText(language, text)
return t.word_count
def _gen_input(row: dict, input_columns: Tuple[str]) -> Union[Tuple[str, ...], str]:
""" """
if len(input_columns) == 1:
return row[input_columns[0]]
return tuple(row[c] for c in input_columns)
def _split_dataset_columns(column_names: Sequence[str]) -> Tuple[Tuple[str, ...], str]:
"""Common schemas for datasets found in huggingface datasets hub."""
_column_names = set(column_names)
if {"premise", "hypothesis", "label"} <= _column_names:
input_columns = ("premise", "hypothesis")
output_column = "label"
elif {"question", "sentence", "label"} <= _column_names:
input_columns = ("question", "sentence")
output_column = "label"
elif {"sentence1", "sentence2", "label"} <= _column_names:
input_columns = ("sentence1", "sentence2")
output_column = "label"
elif {"question1", "question2", "label"} <= _column_names:
input_columns = ("question1", "question2")
output_column = "label"
elif {"question", "sentence", "label"} <= _column_names:
input_columns = ("question", "sentence")
output_column = "label"
elif {"text", "label"} <= _column_names:
input_columns = ("text",)
output_column = "label"
elif {"sentence", "label"} <= _column_names:
input_columns = ("sentence",)
output_column = "label"
elif {"document", "summary"} <= _column_names:
input_columns = ("document",)
output_column = "summary"
elif {"content", "summary"} <= _column_names:
input_columns = ("content",)
output_column = "summary"
elif {"label", "review"} <= _column_names:
input_columns = ("review",)
output_column = "label"
else:
raise ValueError(
f"Unsupported dataset column_names {_column_names}. Try passing your own `dataset_columns` argument."
)
return input_columns, output_column
|
Milxnor/Nacro | Nacro/SDK/FN_BulletWhipTrackerComponent_parameters.hpp | <filename>Nacro/SDK/FN_BulletWhipTrackerComponent_parameters.hpp
#pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function BulletWhipTrackerComponent.BulletWhipTrackerComponent_C.PlayWhipSound
struct UBulletWhipTrackerComponent_C_PlayWhipSound_Params
{
};
// Function BulletWhipTrackerComponent.BulletWhipTrackerComponent_C.GetLocalPawnForTracking
struct UBulletWhipTrackerComponent_C_GetLocalPawnForTracking_Params
{
class AFortPlayerPawn* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function BulletWhipTrackerComponent.BulletWhipTrackerComponent_C.TrackWhipStatus
struct UBulletWhipTrackerComponent_C_TrackWhipStatus_Params
{
bool Changed; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
float Whip_Distance; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BulletWhipTrackerComponent.BulletWhipTrackerComponent_C.ReceiveTick
struct UBulletWhipTrackerComponent_C_ReceiveTick_Params
{
float* DeltaSeconds; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function BulletWhipTrackerComponent.BulletWhipTrackerComponent_C.Reset
struct UBulletWhipTrackerComponent_C_Reset_Params
{
struct FVector StartLocation; // (Parm, IsPlainOldData)
};
// Function BulletWhipTrackerComponent.BulletWhipTrackerComponent_C.Update Velocity
struct UBulletWhipTrackerComponent_C_Update_Velocity_Params
{
struct FVector Current_Velocity; // (Parm, IsPlainOldData)
};
// Function BulletWhipTrackerComponent.BulletWhipTrackerComponent_C.ExecuteUbergraph_BulletWhipTrackerComponent
struct UBulletWhipTrackerComponent_C_ExecuteUbergraph_BulletWhipTrackerComponent_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
madebyankur/auth0-delegated-administration-extension | server/lib/middlewares/verifyUserAccess.js | import Promise from 'bluebird';
import { NotFoundError } from 'auth0-extension-tools';
export default (action, scriptManager) => (req, res, next) =>
req.auth0.users.get({ id: req.params.id })
.then(user => {
if (!user) {
return Promise.reject(new NotFoundError(`User not found: ${req.params.id}`));
}
const accessContext = {
request: {
user: req.user
},
payload: {
user,
action
}
};
return scriptManager.execute('access', accessContext)
.then(() => {
// cache the target user so we don't have to get it again if it is needed
req.targetUser = user;
});
})
.then(() => next())
.catch(next);
|
maartenbreddels/mab | mab/gd/tri/plots.py | # -*- coding: utf-8 -*-
from kaplot import *
import mab
class PlotOrblib(object): # abstract
def __init__(self, orblib):
self.orblib = orblib
def draw(self, axis=None, aperture=None):
nx = self.orblib.orblib.noI1
if axis is None:
ny = self.orblib.orblib.noI2*self.orblib.orblib.noI3
else:
ny = self.orblib.orblib.noI2#*self.orblib.orblib.noI3
grid = self.orblib.grid.reshape((self.orblib.orblib.noI1, self.orblib.orblib.noI2, self.orblib.orblib.noI3, self.orblib.orblib.noConstraints, self.orblib.orblib.noMaxVelocityHistograms))
mozaic(nx, ny, container)
colormap = "blackwhite"
if aperture is not None:
area = [sum(aperture.aperture == k+1) for k in range(grid.shape[3])]
print "area", area
area = array(area)
else:
area = None
for i in range(nx):
for j in range(ny):
select(i, j)
if axis is None:
indexedimage(grid[i,j/self.orblib.orblib.noI2, j%self.orblib.orblib.noI2].T, colormap=colormap)
else:
border()
spacer()
for k in range(self.orblib.orblib.noI3):
mass = grid[i,j, k].sum(axis=axis)
if area is not None:
mass = mass/area
graph(mass, color=nicecolors[k])
#draw()
class PlotDensity(PlotOrblib):
def __init__(self, orblib, aperture):
PlotOrblib.__init__(self, orblib)
self.aperture = aperture
def run(self, args, opts, scope):
self.orblib.load()
self.aperture.load()
self.draw(axis=1, aperture=self.aperture)
draw()
class PlotVelocity(PlotOrblib):
def __init__(self, orblib):
PlotOrblib.__init__(self, orblib)
def run(self, args, opts, scope):
self.orblib.load()
self.draw(axis=0)
draw()
class PlotOrbits(PlotOrblib):
def __init__(self, orblib):
PlotOrblib.__init__(self, orblib)
def run(self, args, opts, scope):
self.orblib.load()
self.draw(axis=None)
draw()
class PlotDensity2D(PlotOrblib):
def __init__(self, orblib, aperture):
PlotOrblib.__init__(self, orblib)
self.aperture = aperture
def run(self, args, opts, scope):
self.orblib.load()
self.aperture.load()
nx = self.orblib.orblib.noI1
ny = self.orblib.orblib.noI2*self.orblib.orblib.noI3 #/2
grid = self.orblib.grid.reshape((self.orblib.orblib.noI1, self.orblib.orblib.noI2, self.orblib.orblib.noI3, self.orblib.orblib.noConstraints, self.orblib.orblib.noMaxVelocityHistograms))
document(size="15cm,25cm")
mozaic(nx, ny, container)
colormap = "blackwhite"
if 0:
if aperture is not None:
area = [sum(aperture.aperture == k+1) for k in range(grid.shape[3])]
print "area", area
area = array(area)
else:
area = None
print "%" * 70
for i in range(nx):
for j in range(ny):
select(i, j)
if isinstance(self.aperture, mab.gd.tri.aperture.ApertureNative):
density = grid[i,j/self.orblib.orblib.noI2, j%self.orblib.orblib.noI2].sum(axis=1)
density2d = density.reshape((self.aperture.Nx, self.aperture.Ny))
else:
density = grid[i,j/self.orblib.orblib.noI2, j%self.orblib.orblib.noI2].sum(axis=1)
density2d = zeros_like(self.aperture.aperture)
N = self.aperture.aperture.max()
print "max", N
for k in range(N):
#import pdb
#pdb.set_trace()
density2d[self.aperture.aperture==k+1] = density[k]
if (i==3) and (j==3):
print self.aperture.aperture==k+1
print density[k]
indexedimage(density2d**0.25, colormap=colormap)
draw()
|
theLongLab/mkTWAS | src/simulations/AdhocFunctions4Analysis.java | package simulations;
import mixedmodel.LocalKinshipAnalyzer;
import mixedmodel.MultiPhenotype;
public class AdhocFunctions4Analysis {
public static void analyze_local(String input_geno, String input_pheno, String output_folder,
String local_kinship_files_folder, String global_kinship_file, int win_size){
int the_phe_index=0;
double step=0.01;
LocalKinshipAnalyzer local_k=new LocalKinshipAnalyzer(input_geno, win_size, null);
MultiPhenotype phenotypeS=new MultiPhenotype(input_pheno);
String out_phe_file=output_folder+"Local_VO."+the_phe_index+"."+phenotypeS.phenotypes[the_phe_index].phe_id+".w"+win_size+".csv";
local_k.local_VO_all_grids(phenotypeS.phenotypes[the_phe_index], input_geno, global_kinship_file, local_kinship_files_folder,
out_phe_file, step, false);
}
}
|
jin-benben/Viktor | src/components/EditableFormTable/index.js | <reponame>jin-benben/Viktor<filename>src/components/EditableFormTable/index.js
import React, { PureComponent } from 'react';
import { Table, Input, Select, DatePicker, Form } from 'antd';
import moment from 'moment';
const { Option } = Select;
const { TextArea } = Input;
class EditableCell extends PureComponent {
getInput = (dataIndex, record) => {
const { inputType } = this.props;
const defaultValue = record[dataIndex];
switch (inputType) {
case 'date':
return (
<DatePicker
value={defaultValue ? moment(defaultValue, 'YYYY-MM-DD') : null}
onChange={(date, dateString) => this.dateChange(dateString, dataIndex, record)}
/>
);
case 'textArea':
return (
<TextArea
value={defaultValue}
rows={1}
onChange={e => this.InputChange(e, dataIndex, record)}
/>
);
case 'select':
return (
<Select
value={defaultValue}
style={{ width: 120 }}
onChange={value => this.selectChange(value, dataIndex, record)}
>
{record.selectList.map(item => (
<Option value={item.value}>{item.lable}</Option>
))}
</Select>
);
default:
return (
<Input onChange={e => this.InputChange(e, dataIndex, record)} value={defaultValue} />
);
}
};
dateChange = (dateString, dataIndex, record) => {
Object.assign(record, { [dataIndex]: dateString });
this.updateRow(record);
};
selectChange = (value, dataIndex, record) => {
Object.assign(record, { [dataIndex]: value });
this.updateRow(record);
};
InputChange = (e, dataIndex, record) => {
Object.assign(record, { [dataIndex]: e.target.value });
this.updateRow(record);
};
updateRow = record => {
const { rowChange } = this.props;
rowChange(record);
};
render() {
const {
editing,
dataIndex,
title,
inputType,
rowChange,
record,
lastIndex,
index,
...restProps
} = this.props;
return (
<td {...restProps}>
{editing && !lastIndex ? this.getInput(dataIndex, record, index) : restProps.children}
</td>
);
}
}
// eslint-disable-next-line react/no-multi-comp
class EditableTable extends React.Component {
// eslint-disable-next-line react/destructuring-assignment
render() {
const components = {
body: {
cell: EditableCell,
},
};
const { data, rowChange, rowKey, ...rest } = this.props;
let { columns } = this.props;
columns = columns.map(col => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: record => ({
record,
data,
rowChange,
inputType: col.inputType,
dataIndex: col.dataIndex,
title: col.title,
editing: col.editable,
lastIndex: record.lastIndex || false,
render: col.render, // this.isEditing(record)
}),
};
});
return (
<Table
components={components}
pagination={false}
rowKey={rowKey || 'key'}
bordered
size="middle"
dataSource={data}
{...rest}
columns={columns}
/>
);
}
}
const EditableFormTable = Form.create()(EditableTable);
export default EditableFormTable;
|
ehddn5252/AlgorithmStorage | src/com/ssafy/algorithm/bj/Bj14888.java | <reponame>ehddn5252/AlgorithmStorage
package com.ssafy.algorithm.bj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// 연산자 끼워넣기
/*
1. 숫자 N 개가 주어지고 연산자 N-1 개가 주어진다.
2. 연산자 우선순위 상관없이 숫자 사이에 연산자를 끼워넣어서 나올 수 있는 값의 최대와 최소를 구하라.
(permutation 사용)
*/
public class Bj14888 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static int N;
static int[] numbers;
static boolean[] visit;
static int[] operatorList;
static int plusNum, minusNum, multiplyNum, divisionNum;
static int resultMin = Integer.MAX_VALUE, resultMax = Integer.MIN_VALUE;
public static void main(String[] args) throws IOException {
N = Integer.parseInt(br.readLine());
numbers = new int[N];
operatorList = new int[N];
visit = new boolean[N];
String[] s = br.readLine().split(" ");
for (int i = 0; i < N; ++i) {
numbers[i] = Integer.parseInt(s[i]);
}
// 0은 더하기, 1은 빼기, 2는 곱하기, 3은 나누기
s = br.readLine().split(" ");
plusNum = Integer.parseInt(s[0]);
minusNum = Integer.parseInt(s[1]);
multiplyNum = Integer.parseInt(s[2]);
divisionNum = Integer.parseInt(s[3]);
operatorList[0] = 0;
int indexNum = 1;
for (int i = 0; i < plusNum; ++i) {
operatorList[indexNum] = 0;
indexNum += 1;
}
for (int i = 0; i < minusNum; ++i) {
operatorList[indexNum] = 1;
indexNum += 1;
}
for (int i = 0; i < multiplyNum; ++i) {
operatorList[indexNum] = 2;
indexNum += 1;
}
for (int i = 0; i < divisionNum; ++i) {
operatorList[indexNum] = 3;
indexNum += 1;
}
permu(1, numbers[0]);
System.out.println(resultMax);
System.out.println(resultMin);
}
static void permu(int cnt, int calcResult) {
if (cnt == N) {
if (calcResult > resultMax) resultMax = calcResult;
if (calcResult < resultMin) resultMin = calcResult;
return;
}
for (int i = 1; i < N; ++i) {
if (visit[i]) continue;
visit[i] = true;
if (operatorList[i] == 0) {
permu(cnt + 1, calcResult + numbers[cnt]);
} else if (operatorList[i] == 1) {
permu(cnt + 1, calcResult - numbers[cnt]);
} else if (operatorList[i] == 2) {
permu(cnt + 1, calcResult * numbers[cnt]);
} else if( operatorList[i] == 3 ){
if(calcResult <0){
permu(cnt+1,-(Math.abs(calcResult) / numbers[cnt]));
}
else{
permu(cnt + 1, calcResult / numbers[cnt]);
}
}
visit[i]=false;
}
}
}
|
axxepta/argon-api | RestServicesModule/src/main/java/de/axxepta/services/implementations/DocumentGitServiceImpl.java | package de.axxepta.services.implementations;
import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Singleton;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PushCommand;
import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.NoHeadException;
import org.eclipse.jgit.api.errors.UnmergedPathsException;
import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
import org.eclipse.jgit.errors.RevisionSyntaxException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevSort;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.glassfish.jersey.server.ResourceConfig;
import org.jvnet.hk2.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.axxepta.models.UserAuthModel;
import de.axxepta.services.interfaces.IDocumentGitService;
import gitdb.integration.DataItem;
import gitdb.integration.GitDB;
@Service(name = "DocumentGitServiceImplementation")
@Singleton
public class DocumentGitServiceImpl implements IDocumentGitService {
private static final Logger LOG = LoggerFactory.getLogger(DocumentGitServiceImpl.class);
private Map<String, Repository> repositoryCloneMap;
private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
@Context
private Application application;
private int timeDifference;
private Runnable clearRunnable = new Runnable() {
public void run() {
long now = Instant.now().toEpochMilli();
int numberDeletedDir = 0;
for (Entry<String, Repository> entry : repositoryCloneMap.entrySet()) {
File dirGit = entry.getValue().getDirectory();
if (now - timeDifference > dirGit.lastModified()) {
try {
FileUtils.forceDelete(dirGit.getParentFile());
repositoryCloneMap.remove(entry.getKey());
numberDeletedDir++;
} catch (IOException e) {
LOG.error("Directory " + dirGit.getParentFile().getAbsolutePath()
+ " cannot be deleted, with exception " + e.getMessage());
}
}
}
LOG.info("Number of directory deleted is " + numberDeletedDir);
}
};
@PostConstruct
private void initService() {
ResourceConfig resourceConfiguration = ResourceConfig.forApplication(application);
String startTimeDelete = (String) resourceConfiguration.getProperty("start-time-delete-Git-clone");
String cicleTimeDelete = (String) resourceConfiguration.getProperty("cicle-time-delete-Git-clone");
String timeDifferenceDelete = (String) resourceConfiguration.getProperty("difference-time-delete-Git-clone");
int startTime = 3;
if (startTimeDelete != null && !startTimeDelete.isEmpty()) {
try {
startTime = Integer.parseInt(startTimeDelete);
} catch (NumberFormatException e) {
LOG.error(startTimeDelete + " is not a number");
}
}
int cicleTime = 10;
if (cicleTimeDelete != null && !cicleTimeDelete.isEmpty()) {
try {
Integer.parseInt(cicleTimeDelete);
} catch (NumberFormatException e) {
LOG.error(cicleTimeDelete + " is not a number");
}
}
timeDifference = 100000;
if (timeDifferenceDelete != null && !timeDifferenceDelete.isEmpty()) {
try {
timeDifference = Integer.parseInt(startTimeDelete);
} catch (NumberFormatException e) {
LOG.error(startTimeDelete + " is not a number");
}
}
repositoryCloneMap = new HashMap<>();
scheduledExecutorService.scheduleAtFixedRate(clearRunnable, startTime, cicleTime, TimeUnit.MINUTES);
}
@Override
public List<String> getRemoteBranchesNames(String gitURL, UserAuthModel userAuth) {
Collection<Ref> refs = getRefsFromURL(gitURL, userAuth);
if (refs == null) {
LOG.error("Refs collections for " + gitURL + " is null");
return null;
}
List<String> branchesNameList = new ArrayList<>();
for (Ref ref : refs) {
branchesNameList.add(ref.getName().substring(ref.getName().lastIndexOf("/") + 1));
}
LOG.info("Head names list for repository have size " + branchesNameList.size());
return branchesNameList;
}
@Override
public Pair<List<String>, List<String>> getFileNamesFromCommit(String gitURL, UserAuthModel userAuth) {
Repository repository = getRepository(gitURL, null, userAuth, true);
if (repository == null) {
LOG.info("Null repository for " + gitURL);
return null;
}
List<String> listDirs = new ArrayList<>();
List<String> listFiles = new ArrayList<>();
try (RevWalk walk = new RevWalk(repository); TreeWalk treeWalk = new TreeWalk(repository);) {
ObjectId objectId = repository.resolve(Constants.HEAD);
RevCommit commit = walk.parseCommit(objectId);
RevTree tree = commit.getTree();
treeWalk.addTree(tree);
treeWalk.setRecursive(false);
while (treeWalk.next()) {
if (treeWalk.isSubtree()) {
listDirs.add(treeWalk.getPathString());
treeWalk.enterSubtree();
} else {
listFiles.add(treeWalk.getPathString());
}
}
repository.close();
} catch (IOException e) {
LOG.error(e.getMessage());
return null;
}
LOG.info("Pair of list with size for dirs list " + listDirs.size() + " and size for files list " + listFiles.size());
return Pair.of(listDirs, listFiles);
}
@Override
public byte[] getDocumentFromRepository(String gitURL, String branchName, String pathFileName,
UserAuthModel userAuth) {
Repository repository;
if (branchName == null) {
repository = getRepository(gitURL, null, userAuth, true);
} else {
repository = getRepository(gitURL, branchName, userAuth, true);
}
if (repository == null)
return null;
try (RevWalk walk = new RevWalk(repository);) {
ObjectId objectId = repository.resolve(Constants.HEAD);
RevCommit commit = walk.parseCommit(objectId);
RevTree tree = commit.getTree();
TreeWalk treewalk = TreeWalk.forPath(repository, pathFileName, tree);
byte[] content = repository.open(treewalk.getObjectId(0)).getBytes();
LOG.info("Get content of document " + pathFileName);
return content;
} catch (IOException e) {
LOG.error(e.getMessage());
return null;
}
}
@Override
public Boolean commitDocumentLocalToGit(String gitURL, String branchName, File localFile, String copyOnDir,
String commitMessage, UserAuthModel userAuth) {
Repository repository = getRepository(gitURL, branchName, userAuth, false);
if(repository == null) {
LOG.info("Repository for " + gitURL + " is null");
return false;
}
boolean isLocale = false;
if (!gitURL.toLowerCase().startsWith("https"))
isLocale = true;
Boolean response = null;
try {
response = commitDocumentLocalToGit(repository, branchName, localFile, copyOnDir, commitMessage, userAuth,
isLocale);
} catch (Exception e) {
LOG.error(e.getMessage());
}
if (!isLocale) {
deleteTmpDir(repository.getDirectory().getParentFile());
}
LOG.info("Commit and eventually push is executed");
return response;
}
private Boolean commitDocumentLocalToGit(Repository repository, String branchName, File localFile, String copyOnDir,
String commitMessage, UserAuthModel userAuth, boolean isLocale) {
if (repository == null) {
LOG.error("Repository is null");
return false;
}
String fileName = localFile.getName();
LOG.info("File name " + fileName);
String directoryRepositoryPath = repository.getDirectory().getAbsolutePath();
String pathRepository = directoryRepositoryPath.substring(0,
directoryRepositoryPath.lastIndexOf(File.separator));
File directoryRepository = new File(pathRepository + File.separator + copyOnDir);
if (!directoryRepository.exists()) {
try {
java.nio.file.Files.createDirectories(directoryRepository.toPath());
} catch (IOException e) {
LOG.error(e.getMessage());
return false;
}
}
LOG.info("Path is " + directoryRepository.getAbsolutePath());
try {
FileUtils.copyFileToDirectory(localFile, directoryRepository);
} catch (IOException e1) {
LOG.error("Copy to temp directory has not been achieved");
return false;
}
try (RevWalk walk = new RevWalk(repository);
Git git = new Git(repository);
GitDB gitDB = new GitDB(repository);) {
LOG.info("Try to commit file with name " + fileName + " from path " + pathRepository);
DataItem dataItem;
if (copyOnDir == null) {
dataItem = new DataItem(fileName,
FileUtils.readFileToString(new File(directoryRepository + File.separator + fileName)));
} else {
dataItem = new DataItem(copyOnDir + "/" + fileName,
FileUtils.readFileToString(new File(directoryRepository + File.separator + fileName)));
}
LOG.info("Commit message " + commitMessage);
Config config = repository.getConfig();
String name = config.getString("user", null, "name");
String email = config.getString("user", null, "email");
LOG.info("Repository name " + name + " with email " + email);
RevCommit commit = gitDB.commit(dataItem, commitMessage, name, email);
LOG.info("SHA commit " + commit.getName());
if (!isLocale) {
PushCommand pushCommand = git.push();
try {
UsernamePasswordCredentialsProvider credentialsProvider = getCredetialsProvider(userAuth);
pushCommand.setCredentialsProvider(credentialsProvider).call();
LOG.info("Commit is push it");
} catch (GitAPIException e) {
LOG.error("Push on repository exception " + e.getMessage());
return false;
}
}
} catch (RevisionSyntaxException | IOException | InterruptedException | UnmergedPathsException
| WrongRepositoryStateException | NoHeadException | ConcurrentRefUpdateException e) {
LOG.error("Commit Exception " + e.getMessage());
return false;
}
return true;
}
@Override
public Date lastModify(String url, UserAuthModel userAuth) {
LOG.info("last modification time for " + url);
Repository repository = getRepository(url, null, userAuth, false);
if (repository == null) {
LOG.info("Repository for " + url + " is null");
return null;
}
try (RevWalk revWalk = new RevWalk(repository);) {
revWalk.sort(RevSort.COMMIT_TIME_DESC);
List<Ref> refs = repository.getRefDatabase().getRefs();
for (Ref ref : refs) {
RevCommit commit = revWalk.parseCommit(ref.getLeaf().getObjectId());
revWalk.markStart(commit);
}
RevCommit newest = revWalk.next();
return newest.getAuthorIdent().getWhen();
} catch (IOException e) {
LOG.error(e.getMessage());
return null;
}
}
private UsernamePasswordCredentialsProvider getCredetialsProvider(UserAuthModel userAuth) {
UsernamePasswordCredentialsProvider credentials = null;
String username = userAuth.getUsername();
String password = <PASSWORD>();
if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
LOG.info("For username " + username);
credentials = new UsernamePasswordCredentialsProvider(username, password);
}
return credentials;
}
private Collection<Ref> getRefsFromURL(String url, UserAuthModel userAuth) {
LOG.info("Get refs for " + url);
UsernamePasswordCredentialsProvider credentials = getCredetialsProvider(userAuth);
long start = System.nanoTime();
Collection<Ref> refsRepository = null;
try {
refsRepository = Git.lsRemoteRepository().setHeads(true).setTags(true).setRemote(url)
.setCredentialsProvider(credentials).call();
} catch (GitAPIException e) {
LOG.error(e.getMessage());
return null;
}
long end = System.nanoTime();
LOG.info("Duration to obtain Ref from URL " + url + " is " + (end - start) + " nano seconds");
return refsRepository;
}
private Repository getRepository(String urlGitRepository, String branchName, UserAuthModel authUser,
boolean withCache) {
// is a local repository
if (!urlGitRepository.startsWith("https")) {
Repository repository = getLocalRepository(urlGitRepository);
return repository;
}
UsernamePasswordCredentialsProvider credentials = getCredetialsProvider(authUser);
Repository repository = null;
if (!repositoryCloneMap.containsKey(urlGitRepository)) {
File tempDirClone = null;
tempDirClone = com.google.common.io.Files.createTempDir();
long start = System.nanoTime();
try {
Git git = null;
if (branchName == null)
// clone all available branches
git = Git.cloneRepository().setURI(urlGitRepository).setCredentialsProvider(credentials)
.setDirectory(tempDirClone).setCloneAllBranches(true).call();
else {
git = Git.cloneRepository().setURI(urlGitRepository).setBranch(branchName)
.setCredentialsProvider(credentials).setDirectory(tempDirClone).call();
urlGitRepository += "/tree/" + branchName;
}
if (git != null)
repository = git.getRepository();
else
return null;
if (withCache) {
LOG.info("URL " + urlGitRepository + " was registered to cache");
repositoryCloneMap.put(urlGitRepository, repository);
}
} catch (GitAPIException e) {
LOG.error(e.getMessage());
return null;
}
long end = System.nanoTime();
LOG.info("Duration to obtain Ref from URL " + urlGitRepository + " is " + (end - start) + " nano seconds");
} else {
LOG.info(urlGitRepository + " is contained in hash map");
if (branchName == null)
repository = repositoryCloneMap.get(urlGitRepository);
else
repository = repositoryCloneMap.get(urlGitRepository + "/tree/" + branchName);
}
return repository;
}
private Repository getLocalRepository(String pathToGit) {
File dotGitFile = new File(pathToGit + File.separator + ".git");
if (!dotGitFile.exists() || !dotGitFile.isDirectory()) {
LOG.info("Directory " + pathToGit + " not exists");
return null;
}
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
try {
Repository repository = repositoryBuilder.setGitDir(dotGitFile).readEnvironment().findGitDir()
.setMustExist(true).build();
return repository;
} catch (IOException e) {
LOG.error("IOException " + e.getMessage());
return null;
}
}
@PreDestroy
private void shutdownService() {
for (Entry<String, Repository> entry : repositoryCloneMap.entrySet()) {
File dirGit = entry.getValue().getDirectory();
deleteTmpDir(dirGit.getParentFile());
}
}
private void deleteTmpDir(File file) {
try {
FileUtils.forceDelete(file);
LOG.info(file.getAbsolutePath() + " was succesfuly deleted");
} catch (IOException e) {
LOG.error("Directory " + file.getAbsolutePath() + " cannot be deleted, with exception " + e.getMessage()
+ " in shutdown method");
}
}
}
|
lukaselmer/adventofcode | 2018/aoc/d20/tokenizer.py | def tokenize(regex: str):
return list(_tokenize(regex))
def _tokenize(regex: str):
current = ""
for index, char in enumerate(regex):
if char in "ENWS":
current += char
else:
if current:
yield current
current = ""
if char in "^$":
pass
elif char == "|":
if regex[index - 1] == "(":
yield ""
yield char
if regex[index + 1] == ")":
yield ""
else:
yield char
|
sniperkit/snk.fork.palantir-distgo | distgo/printproducts/printproducts_test.go | <filename>distgo/printproducts/printproducts_test.go
/*
Sniperkit-Bot
- Status: analyzed
*/
// Copyright 2016 Palantir Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package printproducts_test
import (
"bytes"
"fmt"
"io/ioutil"
"path"
"testing"
"github.com/nmiyake/pkg/dirs"
"github.com/nmiyake/pkg/gofiles"
"github.com/palantir/pkg/gittest"
"github.com/palantir/pkg/matcher"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/sniperkit/snk.fork.palantir-distgo/distgo"
distgoconfig "github.com/sniperkit/snk.fork.palantir-distgo/distgo/config"
"github.com/sniperkit/snk.fork.palantir-distgo/distgo/printproducts"
"github.com/sniperkit/snk.fork.palantir-distgo/distgo/testfuncs"
)
func TestProducts(t *testing.T) {
rootDir, cleanup, err := dirs.TempDir("", "")
require.NoError(t, err)
defer cleanup()
for i, tc := range []struct {
name string
projectCfg distgoconfig.ProjectConfig
setupProjectDir func(projectDir string)
want func(projectDir string) string
}{
{
"prints products defined in param",
distgoconfig.ProjectConfig{
Products: distgoconfig.ToProductsMap(map[distgo.ProductID]distgoconfig.ProductConfig{
"foo": {},
"bar": {},
}),
},
func(projectDir string) {},
func(projectDir string) string {
return `bar
foo
`
},
},
{
"if param is empty, prints main packages",
distgoconfig.ProjectConfig{},
func(projectDir string) {
_, err := gofiles.Write(projectDir, []gofiles.GoFileSpec{
{
RelPath: "main.go",
Src: `package main`,
},
{
RelPath: "bar/bar.go",
Src: `package bar`,
},
{
RelPath: "foo/foo.go",
Src: `package main`,
},
})
require.NoError(t, err)
},
func(projectDir string) string {
return fmt.Sprintf(`%s
foo
`, path.Base(projectDir))
},
},
{
"if param is empty, prints main packages and uses exclude param",
distgoconfig.ProjectConfig{
Exclude: matcher.NamesPathsCfg{
Paths: []string{
"foo",
},
},
},
func(projectDir string) {
_, err := gofiles.Write(projectDir, []gofiles.GoFileSpec{
{
RelPath: "main.go",
Src: `package main`,
},
{
RelPath: "bar/bar.go",
Src: `package bar`,
},
{
RelPath: "foo/foo.go",
Src: `package main`,
},
})
require.NoError(t, err)
},
func(projectDir string) string {
return fmt.Sprintf(`%s
`, path.Base(projectDir))
},
},
} {
projectDir, err := ioutil.TempDir(rootDir, "")
require.NoError(t, err, "Case %d: %s", i, tc.name)
gittest.InitGitDir(t, projectDir)
tc.setupProjectDir(projectDir)
projectParam := testfuncs.NewProjectParam(t, tc.projectCfg, projectDir, fmt.Sprintf("Case %d: %s", i, tc.name))
buf := &bytes.Buffer{}
err = printproducts.Run(projectParam, buf)
require.NoError(t, err, "Case %d: %s", i, tc.name)
assert.Equal(t, tc.want(projectDir), buf.String(), "Case %d: %s", i, tc.name)
}
}
|
jobial-io/sclap | sclap-app/src/main/scala/io/jobial/sclap/CommandLineParser.scala | /*
* Copyright (c) 2020 Jobial OÜ. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package io.jobial.sclap
import cats.instances.AllInstances
import cats.syntax.AllSyntax
import io.jobial.sclap.core.implicits.{ArgumentValueParserInstances, ArgumentValuePrinterInstances, CommandLineParserImplicits}
import io.jobial.sclap.impl.picocli.implicits.PicocliCommandLineParserImplicits
trait CommandLineParser
extends CommandLineParserNoImplicits
with CommandLineParserImplicits
with ArgumentValueParserInstances
with ArgumentValuePrinterInstances
with PicocliCommandLineParserImplicits
with AllSyntax
with AllInstances
|
caojie09/sofa-registry | server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/MetaNodeServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alipay.sofa.registry.server.session.node.service;
import com.alipay.sofa.registry.common.model.metaserver.FetchProvideDataRequest;
import com.alipay.sofa.registry.common.model.metaserver.ProvideData;
import com.alipay.sofa.registry.common.model.store.URL;
import com.alipay.sofa.registry.log.Logger;
import com.alipay.sofa.registry.log.LoggerFactory;
import com.alipay.sofa.registry.remoting.exchange.NodeExchanger;
import com.alipay.sofa.registry.remoting.exchange.RequestException;
import com.alipay.sofa.registry.remoting.exchange.message.Request;
import com.alipay.sofa.registry.remoting.exchange.message.Response;
import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfig;
import com.alipay.sofa.registry.server.session.node.RaftClientManager;
import com.alipay.sofa.registry.server.session.node.SessionNodeManager;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* @author shangyu.wh
* @version $Id: MetaNodeServiceImpl.java, v 0.1 2018-04-17 21:23 shangyu.wh Exp $
*/
public class MetaNodeServiceImpl implements MetaNodeService {
private static final Logger LOGGER = LoggerFactory.getLogger(SessionNodeManager.class,
"[MetaNodeService]");
@Autowired
protected SessionServerConfig sessionServerConfig;
@Autowired
protected NodeExchanger metaNodeExchanger;
@Autowired
RaftClientManager raftClientManager;
@Override
public ProvideData fetchData(String dataInfoId) {
try {
Request<FetchProvideDataRequest> request = new Request<FetchProvideDataRequest>() {
@Override
public FetchProvideDataRequest getRequestBody() {
return new FetchProvideDataRequest(dataInfoId);
}
@Override
public URL getRequestUrl() {
return new URL(raftClientManager.getLeader().getIp(),
sessionServerConfig.getMetaServerPort());
}
};
Response response = metaNodeExchanger.request(request);
Object result = response.getResult();
if (result instanceof ProvideData) {
return (ProvideData) result;
} else {
LOGGER.error("fetch null provider data!");
throw new RuntimeException("MetaNodeService fetch null provider data!");
}
} catch (RequestException e) {
LOGGER.error("fetch provider data error! " + e.getRequestMessage(), e);
throw new RuntimeException("fetch provider data error! " + e.getRequestMessage(), e);
}
}
} |
fury999io/JavaPrograms | Example.java | <reponame>fury999io/JavaPrograms
cd Desktop/REOLADON/Programming/Java
import java.io.*;
public class
{
public static void main(String[] args) throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
}
}
|
WebucatorTraining/classfiles-actionable-python | flow-control/Solutions/guess_word_challenge.py | import random
def get_word():
"""Returns random word."""
with open('../data/words.txt') as f:
words = f.read().splitlines()
return random.choice(words).upper()
def check(word, guesses):
"""Creates and returns string representation of word
displaying asterisks for letters not yet guessed."""
status = '' # Current status of guess
last_guess = guesses[-1]
matches = 0 # Number of occurrences of last_guess in word
for letter in word:
status += letter if letter in guesses else '*'
if letter == last_guess:
matches += 1
if matches > 1:
print('The word has {} "{}"s.'.format(matches, last_guess))
elif matches == 1:
print('The word has one "{}".'.format(last_guess))
else:
print('Sorry. The word has no "{}"s.'.format(last_guess))
return status
def main():
word = get_word() # The random word
n = len(word) # The number of letters in the random word
guesses = [] # The list of guesses made so far
guessed = False
print('The word contains {} letters.'.format(n))
while not guessed:
guess = input('Guess a letter or a {}-letter word: '.format(n))
guess = guess.upper()
if guess in guesses:
print('You already guessed "{}".'.format(guess))
elif len(guess) == n: # Guessing whole word
guesses.append(guess)
if guess == word:
guessed = True
else:
print('Sorry, that is incorrect.')
elif len(guess) == 1: # Guessing letter
guesses.append(guess)
result = check(word, guesses)
if result == word:
guessed = True
else:
print(result)
else: # guess had wrong number of characters
print('Invalid entry.')
print('{} is it! It took {} tries.'.format(word, len(guesses)))
main() |
javgat/devtest | BackEnd/restapi/operations/test/get_all_edit_tests_responses.go | <gh_stars>1-10
// Code generated by go-swagger; DO NOT EDIT.
package test
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"uva-devtest/models"
)
// GetAllEditTestsOKCode is the HTTP code returned for type GetAllEditTestsOK
const GetAllEditTestsOKCode int = 200
/*GetAllEditTestsOK tests found
swagger:response getAllEditTestsOK
*/
type GetAllEditTestsOK struct {
/*
In: Body
*/
Payload []*models.Test `json:"body,omitempty"`
}
// NewGetAllEditTestsOK creates GetAllEditTestsOK with default headers values
func NewGetAllEditTestsOK() *GetAllEditTestsOK {
return &GetAllEditTestsOK{}
}
// WithPayload adds the payload to the get all edit tests o k response
func (o *GetAllEditTestsOK) WithPayload(payload []*models.Test) *GetAllEditTestsOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the get all edit tests o k response
func (o *GetAllEditTestsOK) SetPayload(payload []*models.Test) {
o.Payload = payload
}
// WriteResponse to the client
func (o *GetAllEditTestsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
payload := o.Payload
if payload == nil {
// return empty array
payload = make([]*models.Test, 0, 50)
}
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
// GetAllEditTestsBadRequestCode is the HTTP code returned for type GetAllEditTestsBadRequest
const GetAllEditTestsBadRequestCode int = 400
/*GetAllEditTestsBadRequest Incorrect Request, or invalida data
swagger:response getAllEditTestsBadRequest
*/
type GetAllEditTestsBadRequest struct {
/*
In: Body
*/
Payload *models.Error `json:"body,omitempty"`
}
// NewGetAllEditTestsBadRequest creates GetAllEditTestsBadRequest with default headers values
func NewGetAllEditTestsBadRequest() *GetAllEditTestsBadRequest {
return &GetAllEditTestsBadRequest{}
}
// WithPayload adds the payload to the get all edit tests bad request response
func (o *GetAllEditTestsBadRequest) WithPayload(payload *models.Error) *GetAllEditTestsBadRequest {
o.Payload = payload
return o
}
// SetPayload sets the payload to the get all edit tests bad request response
func (o *GetAllEditTestsBadRequest) SetPayload(payload *models.Error) {
o.Payload = payload
}
// WriteResponse to the client
func (o *GetAllEditTestsBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(400)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
// GetAllEditTestsForbiddenCode is the HTTP code returned for type GetAllEditTestsForbidden
const GetAllEditTestsForbiddenCode int = 403
/*GetAllEditTestsForbidden Not authorized to this content
swagger:response getAllEditTestsForbidden
*/
type GetAllEditTestsForbidden struct {
/*
In: Body
*/
Payload *models.Error `json:"body,omitempty"`
}
// NewGetAllEditTestsForbidden creates GetAllEditTestsForbidden with default headers values
func NewGetAllEditTestsForbidden() *GetAllEditTestsForbidden {
return &GetAllEditTestsForbidden{}
}
// WithPayload adds the payload to the get all edit tests forbidden response
func (o *GetAllEditTestsForbidden) WithPayload(payload *models.Error) *GetAllEditTestsForbidden {
o.Payload = payload
return o
}
// SetPayload sets the payload to the get all edit tests forbidden response
func (o *GetAllEditTestsForbidden) SetPayload(payload *models.Error) {
o.Payload = payload
}
// WriteResponse to the client
func (o *GetAllEditTestsForbidden) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(403)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
// GetAllEditTestsInternalServerErrorCode is the HTTP code returned for type GetAllEditTestsInternalServerError
const GetAllEditTestsInternalServerErrorCode int = 500
/*GetAllEditTestsInternalServerError Internal error
swagger:response getAllEditTestsInternalServerError
*/
type GetAllEditTestsInternalServerError struct {
}
// NewGetAllEditTestsInternalServerError creates GetAllEditTestsInternalServerError with default headers values
func NewGetAllEditTestsInternalServerError() *GetAllEditTestsInternalServerError {
return &GetAllEditTestsInternalServerError{}
}
// WriteResponse to the client
func (o *GetAllEditTestsInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(500)
}
|
mansam/manageiq | spec/requests/api/regions_spec.rb | #
# REST API Request Tests - Regions
#
# Regions primary collections:
# /api/regions
#
# Tests for:
# GET /api/regions/:id
#
describe "Regions API" do
it "forbids access to regions without an appropriate role" do
api_basic_authorize
run_get(regions_url)
expect(response).to have_http_status(:forbidden)
end
it "forbids access to a region resource without an appropriate role" do
api_basic_authorize
region = FactoryGirl.create(:miq_region, :region => "2")
run_get(regions_url(region.id))
expect(response).to have_http_status(:forbidden)
end
it "allows GETs of a region" do
api_basic_authorize action_identifier(:regions, :read, :resource_actions, :get)
region = FactoryGirl.create(:miq_region, :region => "2")
run_get(regions_url(region.id))
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to include(
"href" => a_string_matching(regions_url(region.id)),
"id" => region.id
)
end
end
|
KarolGitHub/gatsby-blog | src/hooks/useMetaDataQuery.js | import { useStaticQuery, graphql } from 'gatsby';
export const useMetaDataQuery = () => {
const data = useStaticQuery(graphql`
query MetaDataQuery {
site {
siteMetadata {
author
description
title
social {
name
url
}
projects {
name
code
demo
desc
}
}
}
}
`);
return data.site.siteMetadata;
};
|
luohaiyun/sqlbuilder | src/main/java/com/github/haivan/sqlbuilder/clauses/condition/BasicDateCondition.java | <filename>src/main/java/com/github/haivan/sqlbuilder/clauses/condition/BasicDateCondition.java
package com.github.haivan.sqlbuilder.clauses.condition;
import com.github.haivan.sqlbuilder.clauses.AbstractClause;
public class BasicDateCondition extends BasicCondition
{
protected String part;
public BasicDateCondition()
{
}
public BasicDateCondition(String column, String operator, Object value, boolean isNot, boolean isOr, String part)
{
super(column, operator, value, isNot, isOr);
this.part = part;
}
public String getPart()
{
return part;
}
public void setPart(String part)
{
this.part = part;
}
@Override
public AbstractClause clone()
{
BasicDateCondition newBasicDateCondition = new BasicDateCondition();
newBasicDateCondition.dialect = dialect;
newBasicDateCondition.column = column;
newBasicDateCondition.isNot = isNot;
newBasicDateCondition.isOr = isOr;
newBasicDateCondition.component = component;
newBasicDateCondition.operator = operator;
newBasicDateCondition.value = value;
newBasicDateCondition.part = part;
return newBasicDateCondition;
}
}
|
ccol002/larva-rv-tool | Other projects/CaseStudies/Clocks/src/larva/ClockEvent.java | <reponame>ccol002/larva-rv-tool
package larva;
public class ClockEvent implements Runnable
{
long millis;
Clock c;
public ClockEvent(Clock c, long millis)
{
this.millis = millis;
this.c = c;
Thread t = new Thread(this);
t.setDaemon(true);
t.start();
}
public void run()
{
synchronized(c){
if (c != null/* && c._inst != null*/) c.event(millis);
}
}
} |
Updownquark/DISEnumerations | src/main/java/edu/nps/moves/disenum/Fuse.java | <reponame>Updownquark/DISEnumerations<filename>src/main/java/edu/nps/moves/disenum/Fuse.java<gh_stars>1-10
package edu.nps.moves.disenum;
import java.util.HashMap;
import edu.nps.moves.siso.EnumNotFoundException;
/** Enumeration values for Fuse
* The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
* obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31<p>
*
* Note that this has two ways to look up an enumerated instance from a value: a fast
* but brittle array lookup, and a slower and more garbage-intensive, but safer, method.
* if you want to minimize memory use, get rid of one or the other.<p>
*
* Copyright 2008-2009. This work is licensed under the BSD license, available at
* http://www.movesinstitute.org/licenses<p>
*
* @author DMcG, <NAME>
*/
public enum Fuse
{
OTHER(0, "Other"),
INTELLIGENT_INFLUENCE(10, "Intelligent Influence"),
SENSOR(20, "Sensor"),
SELF_DESTRUCT(30, "Self-destruct"),
ULTRA_QUICK(40, "Ultra Quick"),
BODY(50, "Body"),
DEEP_INTRUSION(60, "Deep Intrusion"),
MULTIFUNCTION(100, "Multifunction"),
POINT_DETONATION_PD(200, "Point Detonation (PD)"),
BASE_DETONATION_BD(300, "Base Detonation (BD)"),
CONTACT(1000, "Contact"),
CONTACT_INSTANT_IMPACT(1100, "Contact, Instant (Impact)"),
CONTACT_DELAYED(1200, "Contact, Delayed"),
X_10_MS_DELAY(1201, "10 ms delay"),
X_20_MS_DELAY(1202, "20 ms delay"),
X_50_MS_DELAY(1205, "50 ms delay"),
X_60_MS_DELAY(1206, "60 ms delay"),
X_100_MS_DELAY(1210, "100 ms delay"),
X_125_MS_DELAY(1212, "125 ms delay"),
X_250_MS_DELAY(1225, "250 ms delay"),
CONTACT_ELECTRONIC_OBLIQUE_CONTACT(1300, "Contact, Electronic (Oblique Contact)"),
CONTACT_GRAZE(1400, "Contact, Graze"),
CONTACT_CRUSH(1500, "Contact, Crush"),
CONTACT_HYDROSTATIC(1600, "Contact, Hydrostatic"),
CONTACT_MECHANICAL(1700, "Contact, Mechanical"),
CONTACT_CHEMICAL(1800, "Contact, Chemical"),
CONTACT_PIEZOELECTRIC(1900, "Contact, Piezoelectric"),
CONTACT_POINT_INITIATING(1910, "Contact, Point Initiating"),
CONTACT_POINT_INITIATING_BASE_DETONATING(1920, "Contact, Point Initiating, Base Detonating"),
CONTACT_BASE_DETONATING(1930, "Contact, Base Detonating"),
CONTACT_BALLISTIC_CAP_AND_BASE(1940, "Contact, Ballistic Cap and Base"),
CONTACT_BASE(1950, "Contact, Base"),
CONTACT_NOSE(1960, "Contact, Nose"),
CONTACT_FITTED_IN_STANDOFF_PROBE(1970, "Contact, Fitted in Standoff Probe"),
CONTACT_NON_ALIGNED(1980, "Contact, Non-aligned"),
TIMED(2000, "Timed"),
TIMED_PROGRAMMABLE(2100, "Timed, Programmable"),
TIMED_BURNOUT(2200, "Timed, Burnout"),
TIMED_PYROTECHNIC(2300, "Timed, Pyrotechnic"),
TIMED_ELECTRONIC(2400, "Timed, Electronic"),
TIMED_BASE_DELAY(2500, "Timed, Base Delay"),
TIMED_REINFORCED_NOSE_IMPACT_DELAY(2600, "Timed, Reinforced Nose Impact Delay"),
TIMED_SHORT_DELAY_IMPACT(2700, "Timed, Short Delay Impact"),
X_10_MS_DELAY_1(2701, "10 ms delay"),
X_20_MS_DELAY_2(2702, "20 ms delay"),
X_50_MS_DELAY_3(2705, "50 ms delay"),
X_60_MS_DELAY_4(2706, "60 ms delay"),
X_100_MS_DELAY_5(2710, "100 ms delay"),
X_125_MS_DELAY_6(2712, "125 ms delay"),
X_250_MS_DELAY_7(2725, "250 ms delay"),
TIMED_NOSE_MOUNTED_VARIABLE_DELAY(2800, "Timed, Nose Mounted Variable Delay"),
TIMED_LONG_DELAY_SIDE(2900, "Timed, Long Delay Side"),
TIMED_SELECTABLE_DELAY(2910, "Timed, Selectable Delay"),
TIMED_IMPACT(2920, "Timed, Impact"),
TIMED_SEQUENCE(2930, "Timed, Sequence"),
PROXIMITY(3000, "Proximity"),
PROXIMITY_ACTIVE_LASER(3100, "Proximity, Active Laser"),
PROXIMITY_MAGNETIC_MAGPOLARITY(3200, "Proximity, Magnetic (Magpolarity)"),
PROXIMITY_ACTIVE_RADAR_DOPPLER_RADAR(3300, "Proximity, Active Radar (Doppler Radar)"),
PROXIMITY_RADIO_FREQUENCY_RF(3400, "Proximity, Radio Frequency (RF)"),
PROXIMITY_PROGRAMMABLE(3500, "Proximity, Programmable"),
PROXIMITY_PROGRAMMABLE_PREFRAGMENTED(3600, "Proximity, Programmable, Prefragmented"),
PROXIMITY_INFRARED(3700, "Proximity, Infrared"),
COMMAND(4000, "Command"),
COMMAND_ELECTRONIC_REMOTELY_SET(4100, "Command, Electronic, Remotely Set"),
ALTITUDE(5000, "Altitude"),
ALTITUDE_RADIO_ALTIMETER(5100, "Altitude, Radio Altimeter"),
ALTITUDE_AIR_BURST(5200, "Altitude, Air Burst"),
DEPTH(6000, "Depth"),
ACOUSTIC(7000, "Acoustic"),
PRESSURE(8000, "Pressure"),
PRESSURE_DELAY(8010, "Pressure, Delay"),
INERT(8100, "Inert"),
DUMMY(8110, "Dummy"),
PRACTICE(8120, "Practice"),
PLUG_REPRESENTING(8130, "Plug Representing"),
TRAINING(8150, "Training"),
PYROTECHNIC(9000, "Pyrotechnic"),
PYROTECHNIC_DELAY(9010, "Pyrotechnic, Delay"),
ELECTRO_OPTICAL(9100, "Electro-optical"),
ELECTROMECHANICAL(9110, "Electromechanical"),
ELECTROMECHANICAL_NOSE(9120, "Electromechanical, Nose"),
STRIKERLESS(9200, "Strikerless"),
STRIKERLESS_NOSE_IMPACT(9210, "Strikerless, Nose Impact"),
STRIKERLESS_COMPRESSION_IGNITION(9220, "Strikerless, Compression-Ignition"),
COMPRESSION_IGNITION(9300, "Compression-Ignition"),
COMPRESSION_IGNITION_STRIKERLESS_NOSE_IMPACT(9310, "Compression-Ignition, Strikerless, Nose Impact"),
PERCUSSION(9400, "Percussion"),
PERCUSSION_INSTANTANEOUS(9410, "Percussion, Instantaneous"),
ELECTRONIC(9500, "Electronic"),
ELECTRONIC_INTERNALLY_MOUNTED(9510, "Electronic, Internally Mounted"),
ELECTRONIC_RANGE_SETTING(9520, "Electronic, Range Setting"),
ELECTRONIC_PROGRAMMED(9530, "Electronic, Programmed"),
MECHANICAL(9600, "Mechanical"),
MECHANICAL_NOSE(9610, "Mechanical, Nose"),
MECHANICAL_TAIL(9620, "Mechanical, Tail");
/** The enumerated value */
public final int value;
/** Text/english description of the enumerated value */
public final String description;
/** This is an array, with each slot corresponding to an enumerated value. This is a fast but brittle way to look up
* enumerated values. If there is no enumeration corresponding to the value it will fail, and it will also fail if the
* index it out of range of the array. But it is fast, and generates less garbage than the alternative of using
* getEnumerationForValue(). It should be used only in real-time environments, and be careful even then.<p>
* Use as Fuse.lookup[aVal] to get the enumeration that corresponds to a value.<p>
* In non-realtime environments, the prefered method is getEnumerationForValue().
*/
static public Fuse lookup[] = new Fuse[9621];
static private HashMap<Integer, Fuse>enumerations = new HashMap<Integer, Fuse>();
/* initialize the array and hash table at class load time */
static
{
for(Fuse anEnum:Fuse.values())
{
lookup[anEnum.value] = anEnum;
enumerations.put(new Integer(anEnum.getValue()), anEnum);
}
}
/** Constructor */
Fuse(int value, String description)
{
this.value = value;
this.description = description;
}
/** Returns the string description associated with the enumerated instance with this value.
* If there is no enumerated instance for this value, the string Invalid enumeration: <val> is returned.
*/
static public String getDescriptionForValue(int aVal)
{
String desc;
Fuse val = enumerations.get(new Integer(aVal));
if(val == null)
desc = "Invalid enumeration: " + (new Integer(aVal)).toString();
else
desc = val.getDescription();
return desc;
}
/** Returns the enumerated instance with this value.
* If there is no enumerated instance for this value, the exception is thrown.
*/
static public Fuse getEnumerationForValue(int aVal) throws EnumNotFoundException
{
Fuse val;
val = enumerations.get(new Integer(aVal));
if(val == null)
throw new EnumNotFoundException("no enumeration found for value " + aVal + " of enumeration Fuse");
return val;
}
/** Returns true if there is an enumerated instance for this value, false otherwise.
*/
static public boolean enumerationForValueExists(int aVal)
{
Fuse val;
val = enumerations.get(new Integer(aVal));
if(val == null)
return false;
return true;
}
/** Returns the enumerated value for this enumeration */
public int getValue()
{
return value;
}
/** Returns a text descriptioni for this enumerated value. This is usually used as the basis for the enumeration name. */
public String getDescription()
{
return description;
}
}
|
JuleCvet/Account-for-time-report | src/main/java/com/hellokoding/account/service/UserServiceImpl.java | package com.hellokoding.account.service;
import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.hellokoding.account.model.User;
import com.hellokoding.account.repository.roleRepository;
import com.hellokoding.account.repository.UserRepository;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private roleRepository roleRepository;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public void save(User user) {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setRoles(new HashSet<>(roleRepository.findAll()));
userRepository.save(user);
}
@Override
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
@Override
public void deleteUser(User user) {
System.out.printf("Trying to delete user ", user);
userRepository.delete(user.getId());
}
@Override
public List<User> showAllUsers() {
List<User> allUsers = userRepository.findAll();
return allUsers;
}
@Override
public boolean updateUser(User user) {
User oldUser = userRepository.findOne(user.getId());
oldUser.setUsername(user.getUsername());
userRepository.saveAndFlush(oldUser);
return true;
}
@Override
public boolean updateUserDel(User user) {
User oldUser = userRepository.findOne(user.getId());
oldUser.setDeleted(1);
userRepository.saveAndFlush(oldUser);
return true;
}
@Override
public User findByid(Long id) {
User oldUser = userRepository.findByid(id);
return oldUser;
}
}
|
Nik6198/Data-Structures | other/s.cpp | #include<stdio.h>
int full(int );
void push(int );
int empty();
int pop();
char item[100];
int top=-1;
int main()
{
push(4);
printf("%d\n",top);
push(5);
printf("%d\n",top);
push(5);
printf("%d\n",top);
push(4);
printf("%d\n",top);
return 0;
}
//full
int full(int max)
{
if(top==max-1)
{ return 1; }
else
{return 0; }
}
//push
void push(int max)
{
int x;
//printf("K");
top++;
if(full(max))
{ printf("stack is full");
}
else
{
//printf("l");
scanf("%d",&x);
item[top]=x;
printf("%d",item[top]);
}
}
//empty
int empty()
{
if(top==-1)
{ return 1; }
else {return 0; }
};
//pop
int pop()
{int x;
if(empty()==1)
{ printf("stack is empty");
}
else
{ x=item[top];
top--;
return x;}
}
|
ljaljushkin/PatternPractise | own/editor/src/main/java/weak_bridge/shape/decorator/DottedLineDecorator.java | <filename>own/editor/src/main/java/weak_bridge/shape/decorator/DottedLineDecorator.java
package weak_bridge.shape.decorator;
import weak_bridge.drawer.IDrawer;
import weak_bridge.shape.Shape;
public class DottedLineDecorator extends Decorator {
private static final double[] DEFAULT_DASHES = new double[]{25d, 10d};
private static final int SOLID_LINE = 0;
public DottedLineDecorator(Shape shape) {
super(shape);
}
@Override
public void draw(IDrawer drawer) {
drawer.setLineDashes(DEFAULT_DASHES);
shape.draw(drawer);
drawer.setLineDashes(SOLID_LINE);
}
@Override
public Decorator clone() {
return new DottedLineDecorator(shape);
}
}
|
kinshuk4/algorithm-cpp | src/compete/hackerrank/mathematics/fundamentals/die-hard-3.cpp | <filename>src/compete/hackerrank/mathematics/fundamentals/die-hard-3.cpp
//die-hard-3.cpp
//Die Hard 3
//Weekly Challenges - Week 7
//Author: derekhh
#include<iostream>
#include<algorithm>
using namespace std;
int gcd(int a, int b)
{
return b ? gcd(b, a%b) : a;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int a, b, c;
cin >> a >> b >> c;
if (c % gcd(a, b) == 0 && c <= max(a, b))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
} |
watsonjj/CHECLabPySB | sstcam_sandbox/d191122_dc_tf/__init__.py | <gh_stars>0
from TargetCalibSB.tf import TFDC, TFACCrossCorrelation
from TargetCalibSB.vped import VpedCalibrator
def get_dc_tf(dc_tf_path, vped_calibration_path):
tf = TFDC.from_file(dc_tf_path)
vped_calibrator = VpedCalibrator()
vped_calibrator.load(vped_calibration_path)
tf.finish_generation(vped_calibrator)
return tf
def get_ac_tf(ac_tf_path):
tf = TFACCrossCorrelation.from_tcal(ac_tf_path)
tf.finish_generation()
return tf
def get_ac_cc_tf(ac_cc_tf_path):
tf = TFACCrossCorrelation.from_file(ac_cc_tf_path)
tf.finish_generation()
return tf
|
kylemacd/workato-connector-sdk | lib/workato/connector/sdk/workato_schemas.rb | <gh_stars>1-10
# frozen_string_literal: true
require 'json'
module Workato
module Connector
module Sdk
class WorkatoSchemas
include Singleton
class << self
def from_json(path = DEFAULT_SCHEMAS_PATH)
load_data(JSON.parse(File.read(path)))
end
delegate :find,
:load_data,
to: :instance
end
def load_data(data)
@schemas_by_id ||= {}.with_indifferent_access
@schemas_by_id.merge!(data.stringify_keys)
end
def find(id)
unless @schemas_by_id
raise 'Workato Schemas are not initialized. ' \
'Init data by calling WorkatoSchemas.from_json or WorkatoSchemas.load_data'
end
@schemas_by_id.fetch(id.to_s)
end
end
end
end
end
|
devbis/tl_zigbee_sdk | zigbee/zcl/zll_commissioning/zcl_zllTouchLinkDiscovery.c | <filename>zigbee/zcl/zll_commissioning/zcl_zllTouchLinkDiscovery.c
/********************************************************************************************************
* @file zcl_zllTouchLinkDiscovery.c
*
* @brief This is the source file for zcl_zllTouchLinkDiscovery
*
* @author <NAME>
* @date 2021
*
* @par Copyright (c) 2021, 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.
*******************************************************************************************************/
/**********************************************************************
* INCLUDES
*/
#include "../zcl_include.h"
#include "zcl_zll_commissioning_internal.h"
#define ZB_PRIMARY_CHANNEL_1 11
#define ZB_PRIMARY_CHANNEL_2 15
#define ZB_PRIMARY_CHANNEL_3 20
#define ZB_PRIMARY_CHANNEL_4 25
_CODE_ZCL_ void zcl_zllTouchLinkDiscoveyStop(void);
_CODE_ZCL_ void zcl_zllTouchLinkDiscoveyStart(void);
extern zcl_zllCommission_t g_zllCommission;
extern bool scanReqProfileInterop;
u8 reset2FactoryFlag = 0;
s32 zcl_touchLinkIdentifyRequestDone(void *arg){
u32 sta = (u32)arg;
zcl_zllTouchLinkFinish(sta);
return -1;
}
/*
* @fn zcl_zllTouchLinkIdentifyRequest
*
* @brief send command of "identify request"
*
* @param arg
*
*/
_CODE_ZCL_ static void zcl_zllTouchLinkIdentifyRequest(void *arg){
zll_touchLinkScanInfo *peerInfo = &g_zllTouchLink.disc->scanList[g_zllTouchLink.opIdx];
epInfo_t dstEp;
TL_SETSTRUCTCONTENT(dstEp, 0);
memcpy((u8 *)&dstEp,(u8 *)&peerInfo->dstEp, sizeof(dstEp));
zcl_zllTouchLinkIdentifyReq_t req;
req.transId = g_zllTouchLink.transId;
req.identifyDuration = 3;
g_zllTouchLink.state = ZCL_ZLL_COMMISSION_STATE_TOUCHLINK_IDENTIFY;
zcl_sendInterPANCmd(g_zllTouchLink.devInfo.epId, &dstEp, ZCL_CLUSTER_TOUCHLINK_COMMISSIONING, ZCL_CMD_ZLL_COMMISSIONING_IDENTIFY, TRUE,
ZCL_FRAME_CLIENT_SERVER_DIR, TRUE, 0, g_zllTouchLink.seqNo++, sizeof(zcl_zllTouchLinkIdentifyReq_t), (u8 *)&req);
if(BDB_ATTR().nodeIsOnANetwork){
if(ZB_EXTPANID_CMP(peerInfo->epanId, NWK_NIB().extPANId)){
/* follow the bdb Spec8.7: Step 9*/
if(peerInfo->nwkUpdateId < NWK_NIB().updateId){
/* send network update command */
zcl_zllTouchLinkNetworkUpdateReq_t networkUpdateCmd;
networkUpdateCmd.transId = g_zllTouchLink.transId;
ZB_EXTPANID_COPY(networkUpdateCmd.epanId, NWK_NIB().extPANId);
networkUpdateCmd.nwkUpdateId = NWK_NIB().updateId;
networkUpdateCmd.logicalChannel = MAC_IB().phyChannelCur;
networkUpdateCmd.panId = NWK_NIB().panId;
networkUpdateCmd.nwkAddr = NWK_NIB().nwkAddr;
zcl_sendInterPANCmd(g_zllTouchLink.devInfo.epId, &dstEp, ZCL_CLUSTER_TOUCHLINK_COMMISSIONING, ZCL_CMD_ZLL_COMMISSIONING_NETWORK_UPDATE, TRUE,
ZCL_FRAME_CLIENT_SERVER_DIR, TRUE, 0, g_zllTouchLink.seqNo++, sizeof(zcl_zllTouchLinkNetworkUpdateReq_t), (u8 *)&networkUpdateCmd);
}
if(peerInfo->nwkUpdateId > NWK_NIB().updateId){
NWK_NIB().updateId = peerInfo->nwkUpdateId;
zdo_nlmeChannelShift(peerInfo->logicalChannel);
}
/* channel restore */
TL_ZB_TIMER_SCHEDULE(zcl_touchLinkIdentifyRequestDone, (void *)ZCL_ZLL_TOUCH_LINK_STA_EXIST, 5);
return;
}
if(!ss_securityModeIsDistributed()){
zcl_zllTouchLinkFinish(ZCL_ZLL_TOUCH_LINK_STA_NOT_PERMITTED);
return;
}
}
/* Is initiator address assignment capable? Set bdbCommissioningStatus
to NOT_AA_CAPABLE*/
if(g_zllTouchLink.zllInfo.bf.addrAssign == 0){
zcl_zllTouchLinkFinish(ZCL_ZLL_TOUCH_LINK_STA_NO_CAPACITY);
return;
}
TL_SCHEDULE_TASK(zcl_zllTouchLinkNetworkStartOrJoin, NULL);
}
/*
* @fn zcl_zllDeviceInformationRequest
*
* @brief send command of "Device Information request"
*
* @param arg
*
*/
_CODE_ZCL_ void zcl_zllTouchLinkDeviceInformationRequest(void *arg){
zll_touchLinkScanInfo *peerInfo = &g_zllTouchLink.disc->scanList[g_zllTouchLink.opIdx];
epInfo_t dstEp;
TL_SETSTRUCTCONTENT(dstEp, 0);
memcpy((u8 *)&dstEp,(u8 *)&peerInfo->dstEp, sizeof(dstEp));
/* send Device Information request */
zcl_zllTouchLinkDeviceInfoReq_t req;
req.transId = g_zllTouchLink.transId;
req.startIdx = (u8)((u32)arg);
zcl_sendInterPANCmd(g_zllTouchLink.devInfo.epId, &dstEp, ZCL_CLUSTER_TOUCHLINK_COMMISSIONING, ZCL_CMD_ZLL_COMMISSIONING_DEVICE_INFORMATION, TRUE,
ZCL_FRAME_CLIENT_SERVER_DIR, TRUE, 0, g_zllTouchLink.seqNo++, sizeof(zcl_zllTouchLinkDeviceInfoReq_t), (u8 *)&req);
g_zllTouchLink.state = ZCL_ZLL_COMMISSION_STATE_TOUCHLINK_DEVICE_INFO_EXCHANGE;
}
/*
* @fn zcl_zllDeviceInformationRequestHandler
*
* @brief the handler for receiving the command of "Device Information request"
*
* @param arg
*
*/
_CODE_ZCL_ void zcl_zllTouchLinkDeviceInformationRequestHandler(epInfo_t *dstEp,u8 startEpIdx){
/*
* send Device Information Response here
* */
af_endpoint_descriptor_t *aed = af_epDescriptorGet();
u8 MatchEpnumOnce = 0;
u8 totalMatchEpnum = 0;
u8 matchEpIdx[MAX_ACTIVE_EP_NUMBER] = {0};
for(u8 i = 0; i < af_availableEpNumGet(); i++){
if(af_clsuterIdMatched(ZCL_CLUSTER_TOUCHLINK_COMMISSIONING, aed[i].correspond_simple_desc)){
matchEpIdx[totalMatchEpnum++] = i;
}
}
if(totalMatchEpnum > startEpIdx){
MatchEpnumOnce = totalMatchEpnum - startEpIdx;
MatchEpnumOnce = (MatchEpnumOnce >= 5) ? 5 : MatchEpnumOnce;
}
u8 len = MatchEpnumOnce * sizeof(zcl_zllDeviceInfoRec_t) + sizeof(zcl_zllTouchLinkDeviceInfoResp_t);
zcl_zllTouchLinkDeviceInfoResp_t *resp = (zcl_zllTouchLinkDeviceInfoResp_t *)ev_buf_allocate(len);
if(resp){
memset(resp, 0, len);
resp->numOfSubdevices = totalMatchEpnum;
resp->transId = g_zllTouchLink.transId;
resp->deviceInfoRecordCnt = MatchEpnumOnce;
resp->startIdx = startEpIdx;
if(MatchEpnumOnce > 0)
{
zcl_zllDeviceInfoRec_t *rec = resp->rec;
for(u8 i = 0; i < MatchEpnumOnce; i++){
u8 epIdx = matchEpIdx[startEpIdx + i];
rec->deviceId = aed[epIdx].correspond_simple_desc->app_dev_id;
rec->epId = aed[epIdx].ep;
rec->groupIdCnt = 0;
if(scanReqProfileInterop){
rec->profileId = aed[epIdx].correspond_simple_desc->app_profile_id;
}else{
rec->profileId = LL_PROFILE_ID;
}
rec->sort = 0;
rec->version = aed[epIdx].correspond_simple_desc->app_dev_ver;
memcpy(rec->ieeeAddr, MAC_IB().extAddress, 8);
rec++;
}
}
zcl_sendInterPANCmd(g_zllTouchLink.devInfo.epId, dstEp, ZCL_CLUSTER_TOUCHLINK_COMMISSIONING, ZCL_CMD_ZLL_COMMISSIONING_DEVICE_INFORMATION_RSP, TRUE,
ZCL_FRAME_SERVER_CLIENT_DIR, TRUE, 0, g_zllTouchLink.seqNo++, len, (u8 *)resp);
ev_buf_free((u8 *)resp);
}
}
/*
* @fn zcl_zllDeviceInformationResponseHandler
*
* @brief the handler for receiving the command of "Device Information Response"
*
* @param arg
*
*/
_CODE_ZCL_ void zcl_zllTouchLinkDeviceInformationResponseHandler(zcl_zllTouchLinkDeviceInfoResp_t *devInfoResp){
if(devInfoResp->startIdx + devInfoResp->deviceInfoRecordCnt >= devInfoResp->numOfSubdevices)
{
/* send identify request */
TL_SCHEDULE_TASK(zcl_zllTouchLinkIdentifyRequest, NULL);
}
else
{
u32 nextIndex = devInfoResp->startIdx + devInfoResp->deviceInfoRecordCnt;
TL_SCHEDULE_TASK(zcl_zllTouchLinkDeviceInformationRequest, (void*)nextIndex);
}
return;
}
/*
* @fn zcl_zllTouchLinkScanRequestProc
*
* @brief send touch link scan response command once receive scan request
*
* @param NULL
*
*/
_CODE_ZCL_ void zcl_zllTouchLinkScanRequestHandler(epInfo_t *srcEp, u8 seqNo){
#if (ZB_ED_ROLE)
/* if it's under rejoin mode, exit */
if(zb_isUnderRejoinMode()){
return;
}
zb_setPollRate(0);
#endif
/*
* maybe the initiator receive the scan request, if it's a factory new device, firstly stop the scan operation
*
* */
zcl_zllTouchLinkDiscoveyStop();
zcl_zllTouchLinkScanResp_t resp;
TL_SETSTRUCTCONTENT(resp,0);
u8 scanRespLen = sizeof(zcl_zllTouchLinkScanResp_t) - sizeof(zcl_zllSubdeviceInfo_t);
resp.transId = g_zllTouchLink.transId;
resp.rssiCorrection = 0; //This value should be pre-configured
resp.zbInfo.bf.logicDevType = af_nodeDevTypeGet();
resp.zbInfo.bf.rxOnWihleIdle = (af_nodeMacCapabilityGet() & MAC_CAP_RX_ON_WHEN_IDLE) ? 1 : 0;
if(is_device_factory_new())
{
g_zllTouchLink.zllInfo.bf.factoryNew = 1; //the bf is initiated in function of touchlinkinit(),maybe changed later,should be updated here.
}
else{
g_zllTouchLink.zllInfo.bf.factoryNew = 0;
}
g_zllTouchLink.zllInfo.bf.profileInterop = 1;
memcpy(&resp.zllInfo, &g_zllTouchLink.zllInfo, 1);
if(!is_device_factory_new()){
memcpy(resp.epanId, NWK_NIB().extPANId, sizeof(addrExt_t));// NIB/AIB
resp.nwkUpdateId = NWK_NIB().updateId; //if factory new , it is 0x00, else nwkUpdateId attribute of originator , only have my update_id, not originators ???
resp.panId = MAC_IB().panId;
resp.nwkAddr = NIB_NETWORK_ADDRESS();
}else{ //is_device_factory_new()
resp.nwkUpdateId = 0;
memset(resp.epanId, 0, 8);
if(MAC_IB().panId == MAC_INVALID_PANID){
MAC_IB().panId = ZB_RANDOM();
}
resp.panId = MAC_IB().panId;
}
resp.keyBitmask = 0;
#ifdef ZB_SECURITY
resp.keyBitmask |= (1 << g_zllTouchLink.keyType);
#endif
resp.respId = g_zllTouchLink.respId;
resp.logicalChannel = MAC_IB().phyChannelCur;
resp.totalGroupIds = 0;
af_endpoint_descriptor_t *aed = af_epDescriptorGet();
for(u8 i = 0; i < af_availableEpNumGet(); i++){
if(af_clsuterIdMatched(ZCL_CLUSTER_TOUCHLINK_COMMISSIONING, aed[i].correspond_simple_desc)){
resp.numOfSubdevices++;
}
}
/**TODO
* only present if no of sub devices is 1.
* Now only one end point is supported on a device, don't add this if multiple End Points are present in this device */
if(1 == resp.numOfSubdevices){
for(u8 i = 0; i < af_availableEpNumGet(); i++){
if(af_clsuterIdMatched(ZCL_CLUSTER_TOUCHLINK_COMMISSIONING, aed[i].correspond_simple_desc)){
resp.subDevInfo.epId = aed[i].ep;
if(scanReqProfileInterop){
resp.subDevInfo.profileId = aed[i].correspond_simple_desc->app_profile_id;
}else{
resp.subDevInfo.profileId = LL_PROFILE_ID;
}
resp.subDevInfo.deviceId = aed[i].correspond_simple_desc->app_dev_id;
resp.subDevInfo.version = aed[i].correspond_simple_desc->app_dev_ver;
resp.subDevInfo.groupIdCnt = 0; //TODO - find group identifier count needed for this end device.
scanRespLen += sizeof(zcl_zllSubdeviceInfo_t);
break;
}
}
}
MAC_IB().rxOnWhenIdle = 1;
g_zllTouchLink.touchLinkChan = MAC_IB().phyChannelCur;
/* Send Response to Originator ,should be Unicast */
zcl_sendInterPANCmd(g_zllTouchLink.devInfo.epId, srcEp, ZCL_CLUSTER_TOUCHLINK_COMMISSIONING, ZCL_CMD_ZLL_COMMISSIONING_SCAN_RSP, TRUE,
ZCL_FRAME_SERVER_CLIENT_DIR, TRUE, 0, seqNo, scanRespLen, (u8 *)&resp);
/* start a timer which is used during the whole touch link */
if(g_zllTouchLink.transIdLifeTimer){
TL_ZB_TIMER_CANCEL(&g_zllTouchLink.transIdLifeTimer);
}
g_zllTouchLink.transIdLifeTimer = TL_ZB_TIMER_SCHEDULE(zcl_zllTouchLinkTimeout, NULL, ZB_INTER_PAN_TRANS_ID_LIFETIME);
/* bdb set as BDB_STATE_COMMISSIONING_TOUCHLINK status */
if(g_zllCommission.appCb->touchLinkCallback){
g_zllCommission.appCb->touchLinkCallback(ZCL_ZLL_TOUCH_LINK_STA_TARGET_START, NULL);
}
}
/*
* @fn zcl_zllTouchLinkScanResponseProc
*
* @brief add scan result to scan list
*
* @param resp the target information from scan response command
*
*/
_CODE_ZCL_ void zcl_zllTouchLinkScanResponseHandler(zcl_zllTouchLinkScanResp_t *resp, epInfo_t *dstEp){
zcl_zllTouchLinkScanResp_t *p = resp;
u8 idx = g_zllTouchLink.disc->targetNum;
if(idx >= g_zllTouchLink.scanListNum){
return;// ZCL_STA_INVALID_VALUE;
}
#ifdef ZB_SECURITY
u16 matched_algorithms = 0;
if((matched_algorithms = p->keyBitmask & (1 << g_zllTouchLink.keyType)) == 0){
return;// ZCL_STA_INVALID_VALUE;
}
#endif
zll_touchLinkScanInfo *scanInfo = &g_zllTouchLink.disc->scanList[idx];
/* check if the response by the same node with different respId */
zll_touchLinkScanInfo *list = &g_zllTouchLink.disc->scanList[0];
u8 i = 0;
for(i = 0; i < idx; i++){
if(ZB_64BIT_ADDR_CMP(list->dstEp.dstAddr.extAddr, dstEp->dstAddr.extAddr)){
if(p->respId != list->respId){
scanInfo = list;
break;
}
}
list++;
}
if(i >= idx){
g_zllTouchLink.disc->targetNum++;
}
ZB_EXTPANID_COPY(scanInfo->epanId, p->epanId);
scanInfo->panId = p->panId;
scanInfo->nwkAddr = p->nwkAddr;
scanInfo->zbInfo.byte = p->zbInfo.byte;
scanInfo->zllInfo.byte = p->zllInfo.byte;
scanInfo->logicalChannel = p->logicalChannel;
scanInfo->numOfSubdevices = p->numOfSubdevices;
scanInfo->totalGroupIds = p->totalGroupIds;
scanInfo->respId = p->respId;
scanInfo->nwkUpdateId = p->nwkUpdateId;
memcpy((u8 *)&scanInfo->dstEp, (u8 *)dstEp, sizeof(epInfo_t));
if(scanInfo->numOfSubdevices == 1){
memcpy(&scanInfo->devInfo, &p->subDevInfo, sizeof(zcl_zllSubdeviceInfo_t));
}
#ifdef ZB_SECURITY
// u8 i = 0;
for(i = 0; i <= CERTIFICATION_KEY; i++){
if((matched_algorithms & (1 << i)) && ((i == DEVELOPMENT_KEY) || (i == MASTER_KEY) || (i == CERTIFICATION_KEY))){
scanInfo->keyIdx = i;
}
}
#endif
}
/*
* @fn zcl_zllTouchLinkDiscoverydone
*
* @brief touch link scan finish
*
* @param arg
*
*/
_CODE_ZCL_ static void zcl_zllTouchLinkDiscoverydone(void *arg){
zcl_zllTouckLinkDisc_t *pDisc = g_zllTouchLink.disc;
if(pDisc->targetNum){
g_zllTouchLink.opIdx = 0;
zll_touchLinkScanInfo *pScanInfo = &pDisc->scanList[g_zllTouchLink.opIdx];
for(u32 i = 0; i < pDisc->targetNum; i++){
if(pScanInfo->zllInfo.bf.priorityReq){
g_zllTouchLink.opIdx = i;
break;
}
pScanInfo++;
}
pScanInfo = &pDisc->scanList[g_zllTouchLink.opIdx];
/* switch the channel to the target node 's */
ZB_TRANSCEIVER_SET_CHANNEL(pScanInfo->logicalChannel);
g_zllTouchLink.touchLinkChan = pScanInfo->logicalChannel;
/**
* If number of sub devices is 1 , info of that sub device will be in this scan response itself
* so we don't need to send Device Info Request to target device. :)
* Check the scan response and prioritize the device if asked for priority.
*/
g_zllTouchLink.respId = pScanInfo->respId;
if(reset2FactoryFlag){
zcl_zllTouchLinkResetFactoryReq(NULL);
zcl_zllTouchLinkFinish(ZCL_ZLL_TOUCH_LINK_STA_SUCC);
return;
}
if(pScanInfo->numOfSubdevices > 1)
{
u32 start_idx = 0;
TL_SCHEDULE_TASK(zcl_zllTouchLinkDeviceInformationRequest, (void*)start_idx);
}
else
{
TL_SCHEDULE_TASK(zcl_zllTouchLinkIdentifyRequest, NULL);
}
}else{
zcl_zllTouchLinkFinish(ZCL_ZLL_TOUCH_LINK_STA_NO_SERVER);
}
}
/*
* @fn zcl_touchLinkScanStart
*
* @brief touch link scan start
*
* @param arg
*
*/
_CODE_ZCL_ static s32 zcl_touchLinkScanStart(void *arg){
zcl_zllTouckLinkDisc_t *pDisc = g_zllTouchLink.disc;
epInfo_t dstEpInfo;
u32 i = 0;
TL_SETSTRUCTCONTENT(dstEpInfo, 0);
dstEpInfo.dstAddrMode = APS_SHORT_DSTADDR_WITHEP;
dstEpInfo.dstEp = 0;
dstEpInfo.dstAddr.shortAddr = MAC_SHORT_ADDR_BROADCAST;
dstEpInfo.profileId = LL_PROFILE_ID;
dstEpInfo.txOptions = 0;
dstEpInfo.radius = 0;
if(g_zllTouchLink.IsFirstChannel){
pDisc->scanCnt = 5;
}
if(g_zllTouchLink.IsFirstChannel || pDisc->scanCnt == 0){
for(i = TL_ZB_MAC_CHANNEL_START; i < TL_ZB_MAC_CHANNEL_STOP+1; i++){
if(pDisc->unscannedChannelMask & (1 << i)){
pDisc->currentScannChannel = i;
g_zllTouchLink.IsFirstChannel = 0;
pDisc->unscannedChannelMask &= ~(1 << i);
break;
}
}
}
if(pDisc->scanCnt > 0){
pDisc->scanCnt--;
}
if(i == TL_ZB_MAC_CHANNEL_STOP+1){
pDisc->primaryChannelScanComplete = 1;
}
if(!pDisc->primaryChannelScanComplete){
/* switch channel to another one */
ZB_TRANSCEIVER_SET_CHANNEL(pDisc->currentScannChannel);
/* send scan request */
zcl_zllTouchLinkScanReq_t scanReq;
scanReq.transId = g_zllTouchLink.transId;
scanReq.zbInfo.byte = g_zllTouchLink.zbInfo.byte;
scanReq.zllInfo.byte = g_zllTouchLink.zllInfo.byte;
zcl_sendInterPANCmd(g_zllTouchLink.devInfo.epId , &dstEpInfo, ZCL_CLUSTER_TOUCHLINK_COMMISSIONING, ZCL_CMD_ZLL_COMMISSIONING_SCAN, TRUE, ZCL_FRAME_CLIENT_SERVER_DIR, TRUE, 0,
g_zllTouchLink.seqNo++, sizeof(zcl_zllTouchLinkScanReq_t), (u8 *)&scanReq);
}else{
if(g_zllTouchLink.vDoPrimaryScan){
g_zllTouchLink.vDoPrimaryScan = 0;
pDisc->unscannedChannelMask = BDB_ATTR().secondaryChannelSet;
pDisc->primaryChannelScanComplete = 0;
if(pDisc->unscannedChannelMask){
return ZB_SCAN_TIME_BASE_DURATION;
}
}
TL_SCHEDULE_TASK(zcl_zllTouchLinkDiscoverydone, NULL);
g_zllTouchLink.runTimer = NULL;
return -1;
}
return ZB_SCAN_TIME_BASE_DURATION;
}
/*
* @fn zcl_zllTouchLinkDiscoveyStart
*
* @brief start a timer to process touch link discovery
*
* @param arg
*
*/
_CODE_ZCL_ void zcl_zllTouchLinkDiscoveyStart(void){
/* start a timer which is used during touch link discovery */
if(g_zllTouchLink.runTimer){
TL_ZB_TIMER_CANCEL(&g_zllTouchLink.runTimer);
}
g_zllTouchLink.runTimer = TL_ZB_TIMER_SCHEDULE(zcl_touchLinkScanStart, NULL, 5);
/* start a timer which is used during the whole touch link */
if(g_zllTouchLink.transIdLifeTimer){
TL_ZB_TIMER_CANCEL(&g_zllTouchLink.transIdLifeTimer);
}
g_zllTouchLink.transIdLifeTimer = TL_ZB_TIMER_SCHEDULE(zcl_zllTouchLinkTimeout, NULL, ZB_INTER_PAN_TRANS_ID_LIFETIME);
}
/*
* @fn zcl_zllTouchLinkDiscoveyStop
*
* @brief stop the timer that is to process touch link discovery
*
* @param arg
*
*/
_CODE_ZCL_ void zcl_zllTouchLinkDiscoveyStop(void){
if(g_zllTouchLink.runTimer){
TL_ZB_TIMER_CANCEL(&g_zllTouchLink.runTimer);
}
if(g_zllTouchLink.transIdLifeTimer){
TL_ZB_TIMER_CANCEL(&g_zllTouchLink.transIdLifeTimer);
}
if(g_zllTouchLink.disc){
ev_buf_free((u8 *)g_zllTouchLink.disc);
g_zllTouchLink.disc = NULL;
}
}
|
2dreet/java_exemplos | src/orientacaoObjeto/DesafioCalculadora.java | <gh_stars>0
package orientacaoObjeto;
import java.util.Scanner;
public class DesafioCalculadora {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Digite o N1");
Double a = scanner.nextDouble();
System.out.println("Digite o N2");
Double b = scanner.nextDouble();
System.out.println("Digite a operação (+ , - , / , * )");
String op = scanner.next();
if(op.equals("+")) {
System.out.println("Resultado: " + ( a + b ));
} else if(op.equals("-")) {
System.out.println("Resultado: " + ( a - b));
} else if(op.equals("*")) {
System.out.println("Resultado: " + ( a * b ));
} else if(op.equals("/")) {
System.out.println("Resultado: " + ( a / b));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.