repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
fernandogar92/javaee8-samples | ejb/remote/roles-allowed/src/main/java/org/javaee8/ejb/remote/remote/Bean.java | /** Copyright Payara Services Limited **/
package org.javaee8.ejb.remote.remote;
import java.io.Serializable;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
@Stateless
public class Bean implements BeanRemote, Serializable {
private static final long serialVersionUID = 1L;
@Override
@RolesAllowed("g1")
public String method() {
return "method";
}
}
|
LaudateCorpus1/llvm-project | libcxx/test/std/utilities/time/time.traits/time.traits.specializations/duration.pass.cpp | <reponame>LaudateCorpus1/llvm-project
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <chrono>
// template <class Rep1, class Period1, class Rep2, class Period2>
// struct common_type<chrono::duration<Rep1, Period1>, chrono::duration<Rep2, Period2>>
// {
// typedef chrono::duration<typename common_type<Rep1, Rep2>::type, see below }> type;
// };
#include <chrono>
#include <ratio>
#include <type_traits>
#include "test_macros.h"
template <class D1, class D2, class De>
void
test()
{
typedef typename std::common_type<D1, D2>::type Dc;
static_assert((std::is_same<Dc, De>::value), "");
}
int main(int, char**)
{
test<std::chrono::duration<int, std::ratio<1, 100> >,
std::chrono::duration<long, std::ratio<1, 1000> >,
std::chrono::duration<long, std::ratio<1, 1000> > >();
test<std::chrono::duration<long, std::ratio<1, 100> >,
std::chrono::duration<int, std::ratio<1, 1000> >,
std::chrono::duration<long, std::ratio<1, 1000> > >();
test<std::chrono::duration<char, std::ratio<1, 30> >,
std::chrono::duration<short, std::ratio<1, 1000> >,
std::chrono::duration<int, std::ratio<1, 3000> > >();
test<std::chrono::duration<double, std::ratio<21, 1> >,
std::chrono::duration<short, std::ratio<15, 1> >,
std::chrono::duration<double, std::ratio<3, 1> > >();
return 0;
}
|
jonnypjohnston/JohnCoker-thrustcurve3 | config/server.js | <gh_stars>1-10
module.exports = {
mongoUrl: process.env.MONGODB_URI || 'mongodb://localhost/thrustcurve',
sendGridApiKey: process.env.SENDGRID_API_KEY,
};
|
cbFabian/Ceiba-Drogueria | microservicio/aplicacion/src/main/java/com/ceiba/festivos/comando/ComandoFestivos.java | package com.ceiba.festivos.comando;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ComandoFestivos{
private Long id;
private String fechaCreacion;
}
|
cloudify-cosmo/cloudify-manager | rest-service/manager_rest/security/audit.py | <reponame>cloudify-cosmo/cloudify-manager<gh_stars>100-1000
import typing
import flask
from manager_rest.storage.models_base import db
def set_audit_method(method: str):
flask.g.audit_auth_method = method
def set_username(username: str):
flask.g.audit_username = username
db.session.execute("SET SESSION audit.username = :name",
params={'name': username})
def set_tenant(tenant: str):
flask.g.audit_tenant = tenant
def extend_headers(response: flask.Response) -> flask.Response:
audit_headers = _prepare_headers()
response.headers.extend(audit_headers)
return response
def _prepare_headers() -> typing.List[typing.Tuple[str, str]]:
headers = []
if 'audit_auth_method' in flask.g:
headers.append(('X-Cloudify-Audit-Auth-Method',
flask.g.audit_auth_method))
if 'audit_tenant' in flask.g:
headers.append(('X-Cloudify-Audit-Tenant',
flask.g.audit_tenant))
if 'audit_username' in flask.g:
headers.append(('X-Cloudify-Audit-Username',
flask.g.audit_username))
return headers
|
eckserah/nifskope | src/lib/nvtristripwrapper.h | #ifndef NVTRISTRIP_WRAPPER_H
#define NVTRISTRIP_WRAPPER_H
#include <QList>
#include <QVector>
class Triangle;
QVector<QVector<quint16> > stripify( QVector<Triangle> triangles, bool stitch = true );
QVector<Triangle> triangulate( QVector<quint16> strips );
QVector<Triangle> triangulate( QVector<QVector<quint16> > strips );
#endif
|
baozhoutao/steedos-platform | packages/design-system-react/utilities/warning/component-is-deprecated.js | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _lowPriorityWarning = _interopRequireDefault(require("./low-priority-warning"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */
/* eslint-disable import/no-mutable-exports */
// This function will deliver a warning message to the browser console about the component being a deprecated component.
var isPrototype = function isPrototypeFunction() {};
if (process.env.NODE_ENV !== 'production') {
var hasWarned = {};
isPrototype = function isPrototypeFunction(control, props, comment) {
var additionalComment = comment ? " ".concat(comment) : '';
if (!props.silenceDeprecationWarning && !hasWarned[control]) {
/* eslint-disable max-len */
(0, _lowPriorityWarning.default)(false, "[Design System React] ".concat(control, " is a deprecated component. Bugfixes can be contributed, but new features and additional alignment with SLDS may be declined.").concat(additionalComment));
/* eslint-enable max-len */
hasWarned[control] = true;
}
};
}
var _default = isPrototype;
exports.default = _default; |
Arodev76/L2Advanced | dist/gameserver/data/scripts/quests/_300_HuntingLetoLizardman.java | package quests;
import l2f.commons.util.Rnd;
import l2f.gameserver.model.instances.NpcInstance;
import l2f.gameserver.model.quest.Quest;
import l2f.gameserver.model.quest.QuestState;
import l2f.gameserver.scripts.ScriptFile;
public class _300_HuntingLetoLizardman extends Quest implements ScriptFile
{
//NPCs
private static int RATH = 30126;
//Items
private static int BRACELET_OF_LIZARDMAN = 7139;
private static int ANIMAL_BONE = 1872;
private static int ANIMAL_SKIN = 1867;
//Chances
private static int BRACELET_OF_LIZARDMAN_CHANCE = 70;
public _300_HuntingLetoLizardman()
{
super(false);
addStartNpc(RATH);
for (int lizardman_id = 20577; lizardman_id <= 20582; lizardman_id++)
addKillId(lizardman_id);
addQuestItem(BRACELET_OF_LIZARDMAN);
}
@Override
public String onTalk(NpcInstance npc, QuestState st)
{
String htmltext = "noquest";
if (npc.getNpcId() != RATH)
return htmltext;
if (st.getState() == CREATED)
{
if (st.getPlayer().getLevel() < 34)
{
htmltext = "rarshints_q0300_0103.htm";
st.exitCurrentQuest(true);
}
else
{
htmltext = "rarshints_q0300_0101.htm";
st.setCond(0);
}
}
else if (st.getQuestItemsCount(BRACELET_OF_LIZARDMAN) < 60)
{
htmltext = "rarshints_q0300_0106.htm";
st.setCond(1);
}
else
htmltext = "rarshints_q0300_0105.htm";
return htmltext;
}
@Override
public String onEvent(String event, QuestState st, NpcInstance npc)
{
String htmltext = event;
int _state = st.getState();
if (event.equalsIgnoreCase("rarshints_q0300_0104.htm") && _state == CREATED)
{
st.setState(STARTED);
st.setCond(1);
st.playSound(SOUND_ACCEPT);
}
else if (event.equalsIgnoreCase("rarshints_q0300_0201.htm") && _state == STARTED)
if (st.getQuestItemsCount(BRACELET_OF_LIZARDMAN) < 60)
{
htmltext = "rarshints_q0300_0202.htm";
st.setCond(1);
}
else
{
st.takeItems(BRACELET_OF_LIZARDMAN, -1);
switch (Rnd.get(3))
{
case 0:
st.giveItems(ADENA_ID, 30000, true);
break;
case 1:
st.giveItems(ANIMAL_BONE, 50, true);
break;
case 2:
st.giveItems(ANIMAL_SKIN, 50, true);
break;
}
st.playSound(SOUND_FINISH);
st.exitCurrentQuest(true);
}
return htmltext;
}
@Override
public String onKill(NpcInstance npc, QuestState qs)
{
if (qs.getState() != STARTED)
return null;
long _count = qs.getQuestItemsCount(BRACELET_OF_LIZARDMAN);
if (_count < 60 && Rnd.chance(BRACELET_OF_LIZARDMAN_CHANCE))
{
qs.giveItems(BRACELET_OF_LIZARDMAN, 1);
if (_count == 59)
{
qs.setCond(2);
qs.playSound(SOUND_MIDDLE);
}
else
qs.playSound(SOUND_ITEMGET);
}
return null;
}
@Override
public void onLoad()
{
}
@Override
public void onReload()
{
}
@Override
public void onShutdown()
{
}
} |
hellowzk/light-spark | example/src/main/scala/com/hellowzk/light/spark/AppTest.scala | <filename>example/src/main/scala/com/hellowzk/light/spark/AppTest.scala
package com.hellowzk.light.spark
import com.hellowzk.light.spark.uitils.ReflectUtils
/**
* <p>
* 日期: 2020/7/3
* <p>
* 时间: 11:16
* <p>
* 星期: 星期五
* <p>
* 描述:
* <p>
* 作者: zhaokui
**/
object AppTest {
def main(args: Array[String]): Unit = {
setUp()
testBatch1()
}
def setUp(): Unit = {
val path1 = "example/src/main/resources/localcluster"
ReflectUtils.apply.addClasspath(path1)
val path2 = "example/src/main/resources/data"
ReflectUtils.apply.addClasspath(path2)
}
def testBatch1(): Unit = {
val configFile1 = "full-batch.yaml"
val configFile2 = "variables.yaml"
val date = "20191211"
App.main(Array("-d", date, "-c", configFile1, "--debug"))
}
}
|
Aryido/Demo-SpringBoot | Demo-Spring-Security-OAuth/Authorization-Code-Resource/src/main/java/com/example/security/oauth/AuthorizationCodeResourceApp.java | <reponame>Aryido/Demo-SpringBoot
package com.example.security.oauth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
/**
* The main program.
*
* @author <NAME>
*
*/
@EnableOAuth2Sso
@SpringBootApplication
public class AuthorizationCodeResourceApp {
public static void main( String[] args ) {
SpringApplication.run( AuthorizationCodeResourceApp.class, args );
}
}
|
ChristianStiehl/LiveGameDesignTool | Doxygen/html/search/all_1.js | var searchData=
[
['changebehavior',['ChangeBehavior',['../class_node_inspector.html#a622010fcd39b4bee19087e238b9574d6',1,'NodeInspector.ChangeBehavior()'],['../class_select_node_button.html#a23cb12320f235b9caf63e15c27c100ed',1,'SelectNodeButton.ChangeBehavior()']]],
['changetype',['ChangeType',['../class_model_view_controller.html#a733e3f93205ae7dea9e3c643a04174ea',1,'ModelViewController']]],
['clearreferencepoints',['ClearReferencePoints',['../class_definition_script.html#a8cb4f36965c85361ae6cb466596e2afd',1,'DefinitionScript']]],
['closetab',['CloseTab',['../class_close_tab.html',1,'']]],
['consolescript',['ConsoleScript',['../class_console_script.html',1,'']]]
];
|
iDingDong/libDDCPP-old | src/standard/bits/DD_Producer.hpp | // DDCPP/standard/bits/DD_Producer.hpp
#ifndef DD_PRODUCER_HPP_INCLUDED_
# define DD_PRODUCER_HPP_INCLUDED_ 1
# include "DD_construct.hpp"
# include "DD_Allocateable.hpp"
DD_DETAIL_BEGIN_
# if __cplusplus >= 201103L
template <typename ValueT_, typename AllocatorT_ = Allocator<ValueT_>>
# else
template <typename ValueT_, typename AllocatorT_ = Allocator<ValueT_> >
# endif
struct Producer : protected Allocateable<AllocatorT_> {
public:
DD_ALIAS(AllocateAgent, Allocateable<AllocatorT_>);
DD_ALIAS(ThisType, Producer);
DD_VALUE_TYPE_NESTED(ValueT_);
DD_ALIAS(AllocatorType, AllocatorT_);
public:
AllocatorType& get_allocator() const DD_NOEXCEPT {
return AllocateAgent::get_allocator();
}
# if __cplusplus >= 201103L
public:
template <typename... ArgumentsT__>
PointerType call(ArgumentsT__&&... arguments___) {
PointerType pointer_ = AllocateAgent::basic_allocate(sizeof(*pointer_));
try {
::DD::construct(pointer_, ::DD::forward<ArgumentsT__>(arguments___)...);
} catch (...) {
AllocateAgent::basic_deallocate(pointer_, sizeof(*pointer_));
}
return pointer_;
}
# else
public:
PointerType call() {
PointerType pointer_ = AllocateAgent::basic_allocate(sizeof(*pointer_));
try {
::DD::construct(pointer_);
} catch (...) {
AllocateAgent::basic_deallocate(pointer_, sizeof(*pointer_));
}
return pointer_;
}
public:
template <typename ArgumentT__>
PointerType call(ArgumentT__ const& argument___) {
PointerType pointer_ = AllocateAgent::basic_allocate(sizeof(*pointer_));
try {
::DD::construct(pointer_, argument___);
} catch (...) {
AllocateAgent::basic_deallocate(pointer_, sizeof(*pointer_));
}
return pointer_;
}
# endif
# if __cplusplus >= 201103L
public:
template <typename... ArgumentsT__>
PointerType operator ()(ArgumentsT__&&... arguments___) {
return call(pointer_, ::DD::forward<ArgumentsT__>(arguments___)...);
}
# else
public:
PointerType operator ()() {
return call();
}
public:
template <typename ArgumentT__>
PointerType operator ()(ArgumentT__ const& argument___) {
return call(argument___);
}
# endif
};
DD_DETAIL_END_
DD_BEGIN_
DD_END_
#endif
|
camelcc/leetcode | src/S0592FractionAdditionSubtraction.java | <filename>src/S0592FractionAdditionSubtraction.java
import java.util.ArrayList;
import java.util.List;
public class S0592FractionAdditionSubtraction {
public String fractionAddition(String expression) {
if (expression.isEmpty()) {
return "";
}
List<int[]> values = new ArrayList<>();
List<Character> ops = new ArrayList<>();
StringBuilder sb = new StringBuilder();
sb.append(expression.charAt(0));
for (int i = 1; i < expression.length(); i++) {
char c = expression.charAt(i);
if (c == '+' || c == '-') {
values.add(parse(sb.toString()));
ops.add(c);
sb = new StringBuilder();
} else {
sb.append(c);
}
}
values.add(parse(sb.toString()));
int[] res = values.remove(0);
while (!ops.isEmpty()) {
int[] sec = values.remove(0);
int[] fir = res;
char op = ops.remove(0);
int n = fir[1]*sec[1];
int d;
if (op == '+') {
d = fir[0]*sec[1]+fir[1]*sec[0];
} else if (op == '-') {
d = fir[0]*sec[1]-fir[1]*sec[0];
} else {
throw new IllegalArgumentException("invalid ops");
}
res = new int[]{d, n};
}
boolean nag = false;
if (res[0] < 0 && res[1] > 0) {
nag = true;
res[0] = - res[0];
} else if (res[0] > 0 && res[1] < 0) {
nag = true;
res[1] = - res[1];
} else {
if (res[0] < 0) {
res[0] = -res[0];
}
if (res[1] < 0) {
res[1] = - res[1];
}
}
int gcd = gcd(res[0], res[1]);
return (nag ? "-" : "") + String.valueOf(res[0]/gcd) + "/" + String.valueOf(res[1]/gcd);
}
private int[] parse(String ex) {
String[] vs = ex.split("/");
int[] n = new int[2];
n[0] = Integer.valueOf(vs[0]);
n[1] = Integer.valueOf(vs[1]);
return n;
}
private int gcd(int a, int b) {
if (b == 0) {
return a;
}
int x = a%b;
return gcd(b, x);
}
}
|
ericleb010/chrome-automated-device-mode | front_end/source_frame/TextEditorAutocompleteController.js | // Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @constructor
* @implements {WebInspector.SuggestBoxDelegate}
* @param {!WebInspector.CodeMirrorTextEditor} textEditor
* @param {!CodeMirror} codeMirror
*/
WebInspector.TextEditorAutocompleteController = function(textEditor, codeMirror)
{
this._textEditor = textEditor;
this._codeMirror = codeMirror;
this._onScroll = this._onScroll.bind(this);
this._onCursorActivity = this._onCursorActivity.bind(this);
this._changes = this._changes.bind(this);
this._blur = this._blur.bind(this);
this._codeMirror.on("changes", this._changes);
this._enabled = true;
this._initialized = false;
}
WebInspector.TextEditorAutocompleteController.prototype = {
_initializeIfNeeded: function()
{
if (this._initialized)
return;
this._initialized = true;
this._codeMirror.on("scroll", this._onScroll);
this._codeMirror.on("cursorActivity", this._onCursorActivity);
this._codeMirror.on("blur", this._blur);
this._delegate.initialize(this._textEditor);
},
/**
* @param {!WebInspector.TextEditorAutocompleteDelegate} delegate
*/
setDelegate: function(delegate)
{
if (this._delegate)
this._delegate.dispose();
this._delegate = delegate;
},
/**
* @param {boolean} enabled
*/
setEnabled: function(enabled)
{
if (enabled === this._enabled)
return;
this._enabled = enabled;
if (!this._delegate)
return;
if (!enabled)
this._delegate.dispose();
else
this._delegate.initialize();
},
/**
* @param {!CodeMirror} codeMirror
* @param {!Array.<!CodeMirror.ChangeObject>} changes
*/
_changes: function(codeMirror, changes)
{
if (!changes.length || !this._enabled || !this._delegate)
return;
var singleCharInput = false;
for (var changeIndex = 0; changeIndex < changes.length; ++changeIndex) {
var changeObject = changes[changeIndex];
singleCharInput = (changeObject.origin === "+input" && changeObject.text.length === 1 && changeObject.text[0].length === 1) ||
(this._suggestBox && changeObject.origin === "+delete" && changeObject.removed.length === 1 && changeObject.removed[0].length === 1);
}
if (singleCharInput)
setImmediate(this.autocomplete.bind(this));
},
_blur: function()
{
this.finishAutocomplete();
},
/**
* @param {!WebInspector.TextRange} mainSelection
* @return {boolean}
*/
_validateSelectionsContexts: function(mainSelection)
{
var selections = this._codeMirror.listSelections();
if (selections.length <= 1)
return true;
var mainSelectionContext = this._textEditor.copyRange(mainSelection);
for (var i = 0; i < selections.length; ++i) {
var wordRange = this._delegate.substituteRange(this._textEditor, selections[i].head.line, selections[i].head.ch);
if (!wordRange)
return false;
var context = this._textEditor.copyRange(wordRange);
if (context !== mainSelectionContext)
return false;
}
return true;
},
autocomplete: function()
{
if (!this._enabled || !this._delegate)
return;
this._initializeIfNeeded();
if (this._codeMirror.somethingSelected()) {
this.finishAutocomplete();
return;
}
var cursor = this._codeMirror.getCursor("head");
var substituteRange = this._delegate.substituteRange(this._textEditor, cursor.line, cursor.ch);
if (!substituteRange || !this._validateSelectionsContexts(substituteRange)) {
this.finishAutocomplete();
return;
}
var prefixRange = substituteRange.clone();
prefixRange.endColumn = cursor.ch;
var wordsWithPrefix = this._delegate.wordsWithPrefix(this._textEditor, prefixRange, substituteRange);
if (!wordsWithPrefix.length) {
this.finishAutocomplete();
return;
}
if (!this._suggestBox)
this._suggestBox = new WebInspector.SuggestBox(this, 6);
var oldPrefixRange = this._prefixRange;
this._prefixRange = prefixRange;
if (!oldPrefixRange || prefixRange.startLine !== oldPrefixRange.startLine || prefixRange.startColumn !== oldPrefixRange.startColumn)
this._updateAnchorBox();
this._suggestBox.updateSuggestions(this._anchorBox, wordsWithPrefix.map(item => ({title: item})), 0, true, this._textEditor.copyRange(prefixRange));
if (!this._suggestBox.visible())
this.finishAutocomplete();
this._onSuggestionsShownForTest(wordsWithPrefix);
},
/**
* @param {!Array.<string>} suggestions
*/
_onSuggestionsShownForTest: function(suggestions) { },
finishAutocomplete: function()
{
if (!this._suggestBox)
return;
this._suggestBox.hide();
this._suggestBox = null;
this._prefixRange = null;
this._anchorBox = null;
},
/**
* @param {!Event} e
* @return {boolean}
*/
keyDown: function(e)
{
if (!this._suggestBox)
return false;
if (e.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) {
this.finishAutocomplete();
return true;
}
if (e.keyCode === WebInspector.KeyboardShortcut.Keys.Tab.code) {
this._suggestBox.acceptSuggestion();
this.finishAutocomplete();
return true;
}
return this._suggestBox.keyPressed(e);
},
/**
* @override
* @param {string} suggestion
* @param {boolean=} isIntermediateSuggestion
*/
applySuggestion: function(suggestion, isIntermediateSuggestion)
{
this._currentSuggestion = suggestion;
},
/**
* @override
*/
acceptSuggestion: function()
{
if (this._prefixRange.endColumn - this._prefixRange.startColumn === this._currentSuggestion.length)
return;
var selections = this._codeMirror.listSelections().slice();
var prefixLength = this._prefixRange.endColumn - this._prefixRange.startColumn;
for (var i = selections.length - 1; i >= 0; --i) {
var start = selections[i].head;
var end = new CodeMirror.Pos(start.line, start.ch - prefixLength);
this._codeMirror.replaceRange(this._currentSuggestion, start, end, "+autocomplete");
}
},
_onScroll: function()
{
if (!this._suggestBox)
return;
var cursor = this._codeMirror.getCursor();
var scrollInfo = this._codeMirror.getScrollInfo();
var topmostLineNumber = this._codeMirror.lineAtHeight(scrollInfo.top, "local");
var bottomLine = this._codeMirror.lineAtHeight(scrollInfo.top + scrollInfo.clientHeight, "local");
if (cursor.line < topmostLineNumber || cursor.line > bottomLine)
this.finishAutocomplete();
else {
this._updateAnchorBox();
this._suggestBox.setPosition(this._anchorBox);
}
},
_onCursorActivity: function()
{
if (!this._suggestBox)
return;
var cursor = this._codeMirror.getCursor();
if (cursor.line !== this._prefixRange.startLine || cursor.ch > this._prefixRange.endColumn || cursor.ch <= this._prefixRange.startColumn)
this.finishAutocomplete();
},
_updateAnchorBox: function()
{
var line = this._prefixRange.startLine;
var column = this._prefixRange.startColumn;
var metrics = this._textEditor.cursorPositionToCoordinates(line, column);
this._anchorBox = metrics ? new AnchorBox(metrics.x, metrics.y, 0, metrics.height) : null;
},
}
/**
* @interface
*/
WebInspector.TextEditorAutocompleteDelegate = function() {}
WebInspector.TextEditorAutocompleteDelegate.prototype = {
/**
* @param {!WebInspector.CodeMirrorTextEditor} editor
* @param {number} lineNumber
* @param {number} columnNumber
* @return {?WebInspector.TextRange}
*/
substituteRange: function(editor, lineNumber, columnNumber) {},
/**
* @param {!WebInspector.CodeMirrorTextEditor} editor
* @param {!WebInspector.TextRange} prefixRange
* @param {!WebInspector.TextRange} substituteRange
* @return {!Array.<string>}
*/
wordsWithPrefix: function(editor, prefixRange, substituteRange) {},
/**
* @param {!WebInspector.CodeMirrorTextEditor} editor
*/
initialize: function(editor) {},
dispose: function() {}
}
/**
* @constructor
* @implements {WebInspector.TextEditorAutocompleteDelegate}
* @param {string=} additionalWordChars
*/
WebInspector.SimpleAutocompleteDelegate = function(additionalWordChars)
{
this._additionalWordChars = additionalWordChars;
}
WebInspector.SimpleAutocompleteDelegate.prototype = {
/**
* @override
* @param {!WebInspector.CodeMirrorTextEditor} editor
*/
initialize: function(editor)
{
if (this._dictionary)
this._dictionary.dispose();
this._dictionary = editor.createTextDictionary(this._additionalWordChars);
},
/**
* @override
*/
dispose: function()
{
if (this._dictionary) {
this._dictionary.dispose();
delete this._dictionary;
}
},
/**
* @override
* @param {!WebInspector.CodeMirrorTextEditor} editor
* @param {number} lineNumber
* @param {number} columnNumber
* @return {?WebInspector.TextRange}
*/
substituteRange: function(editor, lineNumber, columnNumber)
{
return editor.wordRangeForCursorPosition(lineNumber, columnNumber, this._dictionary.isWordChar.bind(this._dictionary));
},
/**
* @override
* @param {!WebInspector.CodeMirrorTextEditor} editor
* @param {!WebInspector.TextRange} prefixRange
* @param {!WebInspector.TextRange} substituteRange
* @return {!Array.<string>}
*/
wordsWithPrefix: function(editor, prefixRange, substituteRange)
{
if (prefixRange.startColumn === prefixRange.endColumn)
return [];
var dictionary = this._dictionary;
var completions = dictionary.wordsWithPrefix(editor.copyRange(prefixRange));
var substituteWord = editor.copyRange(substituteRange);
if (dictionary.wordCount(substituteWord) === 1)
completions = completions.filter(excludeFilter.bind(null, substituteWord));
completions.sort(sortSuggestions);
return completions;
function sortSuggestions(a, b)
{
return dictionary.wordCount(b) - dictionary.wordCount(a) || a.length - b.length;
}
function excludeFilter(excludeWord, word)
{
return word !== excludeWord;
}
}
}
|
gaps-closure/top-level | apps/eop1/timing/MA_v1.0_src/MPX/TOI.cpp | <filename>apps/eop1/timing/MA_v1.0_src/MPX/TOI.cpp<gh_stars>0
#include "TOI.h"
TOI::TOI(string id, double x, double y, double z, double speed,
double bearing, double confidence, string classification) {
this->id = id;
this->x = x;
this->y = y;
this->z = z;
this->speed = speed;
this->bearing = bearing;
this->confidence = confidence;
this->classification = classification;
}
void TOI::setSpeedAndBearing(double speed, double bearing) {
this->speed = speed;
this->bearing = bearing;
}
string TOI::getId() {
return id;
}
double TOI::getX() {
return x;
}
double TOI::getY() {
return y;
}
double TOI::getZ() {
return z;
}
double TOI::getSpeed() {
return speed;
}
double TOI::getBearing() {
return bearing;
}
double TOI::getConfidence() {
return confidence;
}
string TOI::getClassification() {
return classification;
} |
jina-ai/benchmark | src/utils/benchmark.py | <gh_stars>10-100
from collections import namedtuple
from contextlib import ExitStack
from statistics import mean, stdev
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
from .profiler import Profiler, merge_profiles
from .timecontext import TimeContext
BenchmarkResult = namedtuple(
'BenchmarkResult', ['mean', 'std', 'iterations', 'profiles']
)
def benchmark_time(
func: Callable[[Any], Any],
n: int = 5,
setup: Optional[Callable[[Any], Optional[Tuple[Iterable, Dict[str, Any]]]]] = None,
teardown: Optional[Callable[[None], None]] = None,
profile_cls: Optional[List[type]] = [],
args: Optional[Tuple] = None,
kwargs: Optional[Dict] = None,
):
"""Get average time and std by benchmarking a function multiple times
:param func: The function to benchmark
:param setup: A setup function that can perform setup before running
the ``func``. It should take as inputs the ``args`` and ``kwargs``
that you provided, and return a tuple of an iterable, which will
be used to provide ``args`` to ``func``, and a dictionary, which
will be used to provide ``kwargs`` to ``func``.
:param teardown: A teardown function that can perform teardown/cleanup after running
the ``func``.
:param profile_cls: A list of the classes that want to be profiled
:param n: Number of repetitions
:param args: Positional arguments to pass to ``func`` (or ``setup``)
:param kwargs: Keyword arguments to pass to ``func`` (or ``setup``)
"""
results = []
args = args if args is not None else ()
kwargs = kwargs if kwargs is not None else {}
profiles_by_cls = {_cls: [] for _cls in profile_cls}
with TimeContext() as test_timer:
while test_timer.time_since_start() < 1e9 or len(results) < n:
if setup is not None:
new_args, new_kwargs = setup(*args, **kwargs)
else:
new_args, new_kwargs = args, kwargs
ctx_manager = ExitStack()
profiles = [ctx_manager.enter_context(Profiler(cls)) for cls in profile_cls]
with ctx_manager:
with TimeContext() as t:
func(*new_args, **new_kwargs)
for p in profiles:
profiles_by_cls[p._cls].append(p.profile)
if teardown is not None:
teardown()
results.append(t.duration)
mean_profiles = []
for profile_cls, profile_list in profiles_by_cls.items():
mean_profiles.append(merge_profiles(profile_list))
m = int(mean(results))
s = int(stdev(results)) if len(results) > 1 else None
print(
f'----> mean_time={round(m,3)}, std_time={round(s,3)}, iterations={len(results)}'
)
return BenchmarkResult(m, s, len(results), mean_profiles)
|
danilucaci/danilucaci.com | packages/web/src/components/FilteredPropsInputField/FilteredPropsInputField.js | <filename>packages/web/src/components/FilteredPropsInputField/FilteredPropsInputField.js
import React from "react";
import { oneOfType, string, bool } from "prop-types";
/**
* It removes any non-standard html props from the field
* valid=true or error=true will not be rendered on the final dom node
*
* This also works:
*
* const StyledLink= styled(({ primary, ...props }) => <Link {...props} />)`
* color: ${props => props.primary ? themeColors.primary : 'red'};
* `
*
*/
function FilteredPropsInputField({ className, valid, error, ...props }) {
return <input {...props} className={className} />;
}
FilteredPropsInputField.propTypes = {
className: string.isRequired,
valid: oneOfType([bool, string]),
error: oneOfType([bool, string]),
};
FilteredPropsInputField.defaultProps = {
valid: undefined,
error: undefined,
};
export default FilteredPropsInputField;
|
mxstbr/emotion | site/plugins/gatsby-plugin-emotion-next-compat/gatsby-ssr.js | <gh_stars>0
// @flow
import * as React from 'react'
import { renderToString } from 'react-dom/server'
import { renderStylesToString } from 'emotion-server'
import { cache } from 'emotion'
import { CacheProvider } from '@emotion/core'
export const replaceRenderer = ({
replaceBodyHTMLString,
bodyComponent
}: *) => {
return replaceBodyHTMLString(
renderStylesToString(
renderToString(
<CacheProvider value={cache}>{bodyComponent}</CacheProvider>
)
)
)
}
|
nodesource/ah-net.processor | lib/http-connection.processor.js | <filename>lib/http-connection.processor.js
const ServerConnectionProcessorBase = require('./base/server-connection.processor')
const HttpParser = 'HTTPPARSER'
/**
* Sample init stack of http parser we are interested in:
*
* ```
* "at Server.connectionListener (_http_server.js:302:10)",
* "at emitOne (events.js:121:13)",
* "at Server.emit (events.js:216:7)",
* "at TCP.onconnection (net.js:1535:8)"
* ```
*
* Code at _http_server.js:302:
*
* `parser.reinitialize(HTTPParser.REQUEST);`
*
* The parser we aren't interested in is allocated right before
* at _http_server.js:301:
*
* `var parser = parsers.alloc();`
*/
const httpParserInitFrame0Rx = /at Server.connectionListener/i
/**
* Instantiates an http server connection data processor to process data collected via
* [nodesource/ah-net](https://github.com/nodesource/ah-net)
*
* Parameters and return value are congruent to the ones explained in
* [ReadFileProcessor](https://nodesource.github.io/ah-fs.processor/#readfileprocessor)
*
* @name HttpConnectionProcessor
* @constructor
*/
class HttpConnectionProcessor extends ServerConnectionProcessorBase {
/**
* Processing algorithm is the same as the [one for the readFile processor](https://nodesource.github.io/ah-fs.processor/#readfileprocessorprocess).
*
* ## Sample Return Value
*
* For a sample return value please consult the [related tests](https://github.com/nodesource/ah-net.processor/blob/master/test/http.one-connection.server.js).
*
* @name httpConnectionProcessor.process
* @function
*/
process() {
this._clear()
this._findTcpSocketIds()
this._findTcpSocketShutdownIds()
this._findHttpParserIds()
this._separateIntoGroups()
this._addOperations()
return { groups: this._groups, operations: this._operations }
}
// @override
_clear() {
super._clear()
this._httpParserIds = new Set()
}
_findHttpParserIds() {
// Each connection includes two http parsers, both triggerd by the
// server connect operation.
// The TcpSocket connection is triggered by the same resource.
// However only one of them includes information we need
for (const a of this._activities.values()) {
if (a.type !== HttpParser) continue
if (a.initStack == null || a.initStack < 1) continue
if (!httpParserInitFrame0Rx.test(a.initStack[0])) continue
// not interested if we can't at least link the http parser to the
// related socket connection (@see _httpParserIdRelatedToSocket)
if (a.resource == null || a.resource.socket == null) continue
this._httpParserIds.add(a.id)
}
}
_httpParserIdRelatedToSocket(socketId) {
for (const parserId of this._httpParserIds) {
const a = this._activities.get(parserId)
// socket will never be `null` since in that case we woulnd't have
// included the parser during @see _findHttpParserIds
if (a.resource.socket._asyncId === socketId) return parserId
}
return null
}
// @override
_separateIntoGroups() {
super._separateIntoGroups()
for (const [ socketId, group ] of this._groups) {
// The http parser is not triggered by the socket, but its resource
// includes the socket information and thus its async id which allows
// us to group it.
const httpParserId = this._httpParserIdRelatedToSocket(socketId)
if (httpParserId != null) group.add(httpParserId)
}
}
_resolveGroup(group) {
const groupInfo = []
for (const id of group) {
const activity = this._activities.get(id)
const issocket = this._tcpSocketIds.has(id)
const isshutdown = this._tcpSocketShutdownIds.has(id)
const ishttpparser = this._httpParserIds.has(id)
const info = { activity, issocket, isshutdown, ishttpparser }
groupInfo.push(info)
}
return groupInfo
}
}
exports = module.exports = HttpConnectionProcessor
exports.operationSteps = 3
exports.operation = 'http:server connection'
|
pulipulichen/PACOR | webpack-app/admin/Domain/DomainAdd/DomainAdd.js | <reponame>pulipulichen/PACOR
let DomainAdd = {
props: ['lib', 'status', 'config', 'progress', 'error', 'view'],
data() {
this.$i18n.locale = this.config.locale
return {
addInput: {
domain: 'http://blog.pulipuli.info',
title: '',
admins: '',
config: ''
}
}
},
components: {
},
computed: {
enableAdd: function () {
return (this.lib.ValidateHelper.isURL(this.addInput.domain)
&& (this.addInput.config === '' || this.lib.ValidateHelper.isJSON(this.addInput.config)) )
},
domainIsURL: function () {
return (this.addInput.domain === ''
|| this.lib.ValidateHelper.isURL(this.addInput.domain))
},
configIsJSON: function () {
return (this.addInput.config === ''
|| this.lib.ValidateHelper.isJSON(this.addInput.config))
}
},
watch: {
},
mounted() {
this.status.title = this.$t('Domaian Management')
},
methods: {
addSubmit: async function () {
let input = JSON.parse(JSON.stringify(this.addInput))
let data = {
domain: input.domain
}
if (input.title !== '') {
data.title = input.title
}
if (input.admins !== '') {
data.admins = input.admins.replace(/\n/g, ' ').trim().split(' ')
}
if (input.config !== '') {
try {
data.config = JSON.parse(data.config)
}
catch (e) {}
}
let result = await this.lib.AxiosHelper.post('/admin/Domain/add', data)
//console.log(result)
// 完成admin之後呢?
if (result === 1) {
this.$router.push('/domain/list/')
}
}
} // methods
}
export default DomainAdd |
luciVuc/openui5 | src/sap.ui.webc.common/src/sap/ui/webc/common/thirdparty/icons/v5/minimize.js | sap.ui.define(['sap/ui/webc/common/thirdparty/base/asset-registries/Icons'], function (Icons) { 'use strict';
const name = "minimize";
const pathData = "M426.5 0c48 0 85 37 85 85v341c0 48-37 85-85 85h-341c-48 0-85-37-85-85V85c0-48 37-85 85-85h341zm28 426V85c0-17-11-28-28-28h-341c-17 0-28 11-28 28v341c0 17 11 28 28 28h341c17 0 28-11 28-28zm-113-114c17 0 28 12 28 29s-11 28-28 28h-170c-17 0-29-11-29-28s12-29 29-29h170z";
const ltr = false;
const collection = "SAP-icons-v5";
const packageName = "@ui5/webcomponents-icons";
Icons.registerIcon(name, { pathData, ltr, collection, packageName });
var pathDataV4 = { pathData };
return pathDataV4;
});
|
bpmbox/gitpod-laravel-starter | sample/demo/frontend/src/documentation/pages/ScrollSpyComponent.js | import React from "react";
import { HashLink as Link } from 'react-router-hash-link';
import Scrollspy from "react-scrollspy";
import s from '../styles.module.scss';
export default (props) => (
<div
className="border-left pl-4 d-md-down-none"
style={{
position: 'fixed',
overflowY: 'auto',
maxHeight: 'calc(100vh - 130px)',
paddingLeft: '15px'
}}
>
<h6 className="fw-semi-bold">{props.title}</h6>
<Scrollspy
items={props.ids}
currentClassName={s.activeScrollSpy}
offset={-170}
>
{props.ids.map((id) => (
<li key="id" className="mb-xs"><Link to={`/documentation/${props.prefix}#${id}`} className={s.scrollSpy}>{id.split('-').join(' ')}</Link></li>
))}
</Scrollspy>
</div>
)
|
ursinnDev/projectlombok_lombok | test/transform/resource/after-ecj/LoggerFloggerRecord.java | import lombok.extern.flogger.Flogger;
class LoggerFloggerRecord {
static @Flogger record Inner(String x) {
private static final com.google.common.flogger.FluentLogger log = com.google.common.flogger.FluentLogger.forEnclosingClass();
/* Implicit */ private final String x;
<clinit>() {
}
public Inner(String x) {
super();
.x = x;
}
}
LoggerFloggerRecord() {
super();
}
} |
monovertex/ygorganizer | ygo_import/urls.py | <reponame>monovertex/ygorganizer
from django.conf.urls import patterns, url
from .views import ImportView
urlpatterns = patterns(
'',
url(r'^(?P<step>[a-z]+)/$', ImportView.as_view(), name='import'),
url(r'^$', ImportView.as_view(), name='import'),
)
|
pan3793/cdh-hive | ql/src/java/org/apache/hadoop/hive/ql/index/compact/CompactIndexHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.index.compact;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.common.JavaUtils;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Index;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.exec.FilterOperator;
import org.apache.hadoop.hive.ql.exec.Operator;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.hooks.ReadEntity;
import org.apache.hadoop.hive.ql.hooks.WriteEntity;
import org.apache.hadoop.hive.ql.index.HiveIndexQueryContext;
import org.apache.hadoop.hive.ql.index.IndexPredicateAnalyzer;
import org.apache.hadoop.hive.ql.index.IndexSearchCondition;
import org.apache.hadoop.hive.ql.index.TableBasedIndexHandler;
import org.apache.hadoop.hive.ql.io.HiveInputFormat;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.HiveStoragePredicateHandler.DecomposedPredicate;
import org.apache.hadoop.hive.ql.metadata.HiveUtils;
import org.apache.hadoop.hive.ql.metadata.Partition;
import org.apache.hadoop.hive.ql.metadata.VirtualColumn;
import org.apache.hadoop.hive.ql.optimizer.IndexUtils;
import org.apache.hadoop.hive.ql.parse.ParseContext;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.plan.MapWork;
import org.apache.hadoop.hive.ql.plan.MapredWork;
import org.apache.hadoop.hive.ql.plan.OperatorDesc;
import org.apache.hadoop.hive.ql.plan.PartitionDesc;
import org.apache.hadoop.hive.ql.session.LineageState;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqual;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqualOrGreaterThan;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqualOrLessThan;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPGreaterThan;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPLessThan;
public class CompactIndexHandler extends TableBasedIndexHandler {
private Configuration configuration;
// The names of the partition columns
private Set<String> partitionCols;
// Whether or not the conditions have been met to use the fact the index is sorted
private boolean useSorted;
private static final Logger LOG = LoggerFactory.getLogger(CompactIndexHandler.class.getName());
@Override
public void analyzeIndexDefinition(Table baseTable, Index index,
Table indexTable) throws HiveException {
StorageDescriptor storageDesc = index.getSd();
if (this.usesIndexTable() && indexTable != null) {
StorageDescriptor indexTableSd = storageDesc.deepCopy();
List<FieldSchema> indexTblCols = indexTableSd.getCols();
FieldSchema bucketFileName = new FieldSchema("_bucketname", "string", "");
indexTblCols.add(bucketFileName);
FieldSchema offSets = new FieldSchema("_offsets", "array<bigint>", "");
indexTblCols.add(offSets);
indexTable.setSd(indexTableSd);
}
}
@Override
protected Task<?> getIndexBuilderMapRedTask(Set<ReadEntity> inputs, Set<WriteEntity> outputs,
List<FieldSchema> indexField, boolean partitioned,
PartitionDesc indexTblPartDesc, String indexTableName,
PartitionDesc baseTablePartDesc, String baseTableName, String dbName,
LineageState lineageState) throws HiveException {
String indexCols = HiveUtils.getUnparsedColumnNamesFromFieldSchema(indexField);
//form a new insert overwrite query.
StringBuilder command= new StringBuilder();
LinkedHashMap<String, String> partSpec = indexTblPartDesc.getPartSpec();
command.append("INSERT OVERWRITE TABLE " +
HiveUtils.unparseIdentifier(dbName) + "." + HiveUtils.unparseIdentifier(indexTableName ));
if (partitioned && indexTblPartDesc != null) {
command.append(" PARTITION ( ");
List<String> ret = getPartKVPairStringArray(partSpec);
for (int i = 0; i < ret.size(); i++) {
String partKV = ret.get(i);
command.append(partKV);
if (i < ret.size() - 1) {
command.append(",");
}
}
command.append(" ) ");
}
command.append(" SELECT ");
command.append(indexCols);
command.append(",");
command.append(VirtualColumn.FILENAME.getName());
command.append(",");
command.append(" collect_set (");
command.append(VirtualColumn.BLOCKOFFSET.getName());
command.append(") ");
command.append(" FROM " +
HiveUtils.unparseIdentifier(dbName) + "." + HiveUtils.unparseIdentifier(baseTableName));
LinkedHashMap<String, String> basePartSpec = baseTablePartDesc.getPartSpec();
if(basePartSpec != null) {
command.append(" WHERE ");
List<String> pkv = getPartKVPairStringArray(basePartSpec);
for (int i = 0; i < pkv.size(); i++) {
String partKV = pkv.get(i);
command.append(partKV);
if (i < pkv.size() - 1) {
command.append(" AND ");
}
}
}
command.append(" GROUP BY ");
command.append(indexCols + ", " + VirtualColumn.FILENAME.getName());
HiveConf builderConf = new HiveConf(getConf(), CompactIndexHandler.class);
builderConf.setBoolVar(HiveConf.ConfVars.HIVEMERGEMAPFILES, false);
builderConf.setBoolVar(HiveConf.ConfVars.HIVEMERGEMAPREDFILES, false);
builderConf.setBoolVar(HiveConf.ConfVars.HIVEMERGETEZFILES, false);
Task<?> rootTask = IndexUtils.createRootTask(builderConf, inputs, outputs,
command, partSpec, indexTableName, dbName, lineageState);
return rootTask;
}
@Override
public void generateIndexQuery(List<Index> indexes, ExprNodeDesc predicate,
ParseContext pctx, HiveIndexQueryContext queryContext) {
Index index = indexes.get(0);
DecomposedPredicate decomposedPredicate = decomposePredicate(predicate, index,
queryContext.getQueryPartitions());
if (decomposedPredicate == null) {
queryContext.setQueryTasks(null);
return; // abort if we couldn't pull out anything from the predicate
}
// pass residual predicate back out for further processing
queryContext.setResidualPredicate(decomposedPredicate.residualPredicate);
// setup TableScanOperator to change input format for original query
queryContext.setIndexInputFormat(HiveCompactIndexInputFormat.class.getName());
// Build reentrant QL for index query
StringBuilder qlCommand = new StringBuilder("INSERT OVERWRITE DIRECTORY ");
String tmpFile = pctx.getContext().getMRTmpPath().toUri().toString();
queryContext.setIndexIntermediateFile(tmpFile);
qlCommand.append( "\"" + tmpFile + "\" "); // QL includes " around file name
qlCommand.append("SELECT `_bucketname` , `_offsets` FROM ");
qlCommand.append(HiveUtils.unparseIdentifier(index.getIndexTableName()));
qlCommand.append(" WHERE ");
String predicateString = decomposedPredicate.pushedPredicate.getExprString();
qlCommand.append(predicateString);
// generate tasks from index query string
LOG.info("Generating tasks for re-entrant QL query: " + qlCommand.toString());
HiveConf queryConf = new HiveConf(pctx.getConf(), CompactIndexHandler.class);
HiveConf.setBoolVar(queryConf, HiveConf.ConfVars.COMPRESSRESULT, false);
Driver driver = new Driver(queryConf, pctx.getQueryState().getLineageState());
driver.compile(qlCommand.toString(), false);
if (pctx.getConf().getBoolVar(ConfVars.HIVE_INDEX_COMPACT_BINARY_SEARCH) && useSorted) {
// For now, only works if the predicate is a single condition
MapWork work = null;
String originalInputFormat = null;
for (Task task : driver.getPlan().getRootTasks()) {
// The index query should have one and only one map reduce task in the root tasks
// Otherwise something is wrong, log the problem and continue using the default format
if (task.getWork() instanceof MapredWork) {
if (work != null) {
LOG.error("Tried to use a binary search on a compact index but there were an " +
"unexpected number (>1) of root level map reduce tasks in the " +
"reentrant query plan.");
work.setInputformat(null);
work.setInputFormatSorted(false);
break;
}
if (task.getWork() != null) {
work = ((MapredWork)task.getWork()).getMapWork();
}
String inputFormat = work.getInputformat();
originalInputFormat = inputFormat;
if (inputFormat == null) {
inputFormat = HiveConf.getVar(pctx.getConf(), HiveConf.ConfVars.HIVEINPUTFORMAT);
}
// We can only perform a binary search with HiveInputFormat and CombineHiveInputFormat
// and BucketizedHiveInputFormat
try {
if (!HiveInputFormat.class.isAssignableFrom(JavaUtils.loadClass(inputFormat))) {
work = null;
break;
}
} catch (ClassNotFoundException e) {
LOG.error("Map reduce work's input format class: " + inputFormat + " was not found. " +
"Cannot use the fact the compact index is sorted.");
work = null;
break;
}
work.setInputFormatSorted(true);
}
}
if (work != null) {
// Find the filter operator and expr node which act on the index column and mark them
if (!findIndexColumnFilter(work.getAliasToWork().values())) {
LOG.error("Could not locate the index column's filter operator and expr node. Cannot " +
"use the fact the compact index is sorted.");
work.setInputformat(originalInputFormat);
work.setInputFormatSorted(false);
}
}
}
queryContext.addAdditionalSemanticInputs(driver.getPlan().getInputs());
queryContext.setQueryTasks(driver.getPlan().getRootTasks());
return;
}
/**
* Does a depth first search on the operator tree looking for a filter operator whose predicate
* has one child which is a column which is not in the partition
* @param operators
* @return whether or not it has found its target
*/
private boolean findIndexColumnFilter(
Collection<Operator<? extends OperatorDesc>> operators) {
for (Operator<? extends OperatorDesc> op : operators) {
if (op instanceof FilterOperator &&
((FilterOperator)op).getConf().getPredicate().getChildren() != null) {
// Is this the target
if (findIndexColumnExprNodeDesc(((FilterOperator)op).getConf().getPredicate())) {
((FilterOperator)op).getConf().setSortedFilter(true);
return true;
}
}
// If the target has been found, no need to continue
if (findIndexColumnFilter(op.getChildOperators())) {
return true;
}
}
return false;
}
private boolean findIndexColumnExprNodeDesc(ExprNodeDesc expression) {
if (expression.getChildren() == null) {
return false;
}
if (expression.getChildren().size() == 2) {
ExprNodeColumnDesc columnDesc = null;
if (expression.getChildren().get(0) instanceof ExprNodeColumnDesc) {
columnDesc = (ExprNodeColumnDesc)expression.getChildren().get(0);
} else if (expression.getChildren().get(1) instanceof ExprNodeColumnDesc) {
columnDesc = (ExprNodeColumnDesc)expression.getChildren().get(1);
}
// Is this the target
if (columnDesc != null && !partitionCols.contains(columnDesc.getColumn())) {
assert expression instanceof ExprNodeGenericFuncDesc :
"Expression containing index column is does not support sorting, should not try" +
"and sort";
((ExprNodeGenericFuncDesc)expression).setSortedExpr(true);
return true;
}
}
for (ExprNodeDesc child : expression.getChildren()) {
// If the target has been found, no need to continue
if (findIndexColumnExprNodeDesc(child)) {
return true;
}
}
return false;
}
/**
* Split the predicate into the piece we can deal with (pushed), and the one we can't (residual)
* @param predicate
* @param index
* @return
*/
private DecomposedPredicate decomposePredicate(ExprNodeDesc predicate, Index index,
Set<Partition> queryPartitions) {
IndexPredicateAnalyzer analyzer = getIndexPredicateAnalyzer(index, queryPartitions);
List<IndexSearchCondition> searchConditions = new ArrayList<IndexSearchCondition>();
// split predicate into pushed (what we can handle), and residual (what we can't handle)
ExprNodeGenericFuncDesc residualPredicate = (ExprNodeGenericFuncDesc)analyzer.
analyzePredicate(predicate, searchConditions);
if (searchConditions.size() == 0) {
return null;
}
int numIndexCols = 0;
for (IndexSearchCondition searchCondition : searchConditions) {
if (!partitionCols.contains(searchCondition.getColumnDesc().getColumn())) {
numIndexCols++;
}
}
// For now, only works if the predicate has a single condition on an index column
if (numIndexCols == 1) {
useSorted = true;
} else {
useSorted = false;
}
DecomposedPredicate decomposedPredicate = new DecomposedPredicate();
decomposedPredicate.pushedPredicate = analyzer.translateSearchConditions(searchConditions);
decomposedPredicate.residualPredicate = residualPredicate;
return decomposedPredicate;
}
/**
* Instantiate a new predicate analyzer suitable for determining
* whether we can use an index, based on rules for indexes in
* WHERE clauses that we support
*
* @return preconfigured predicate analyzer for WHERE queries
*/
private IndexPredicateAnalyzer getIndexPredicateAnalyzer(Index index, Set<Partition> queryPartitions) {
IndexPredicateAnalyzer analyzer = new IndexPredicateAnalyzer();
analyzer.addComparisonOp(GenericUDFOPEqual.class.getName());
analyzer.addComparisonOp(GenericUDFOPLessThan.class.getName());
analyzer.addComparisonOp(GenericUDFOPEqualOrLessThan.class.getName());
analyzer.addComparisonOp(GenericUDFOPGreaterThan.class.getName());
analyzer.addComparisonOp(GenericUDFOPEqualOrGreaterThan.class.getName());
// only return results for columns in this index
List<FieldSchema> columnSchemas = index.getSd().getCols();
for (FieldSchema column : columnSchemas) {
analyzer.allowColumnName(column.getName());
}
// partitioned columns are treated as if they have indexes so that the partitions
// are used during the index query generation
partitionCols = new HashSet<String>();
for (Partition part : queryPartitions) {
if (part.getSpec().isEmpty()) {
continue; // empty partitions are from whole tables, so we don't want to add them in
}
for (String column : part.getSpec().keySet()) {
analyzer.allowColumnName(column);
partitionCols.add(column);
}
}
return analyzer;
}
@Override
public boolean checkQuerySize(long querySize, HiveConf hiveConf) {
long minSize = hiveConf.getLongVar(HiveConf.ConfVars.HIVEOPTINDEXFILTER_COMPACT_MINSIZE);
long maxSize = hiveConf.getLongVar(HiveConf.ConfVars.HIVEOPTINDEXFILTER_COMPACT_MAXSIZE);
if (maxSize < 0) {
maxSize = Long.MAX_VALUE;
}
return (querySize > minSize & querySize < maxSize);
}
@Override
public boolean usesIndexTable() {
return true;
}
}
|
MolecularAI/reinvent-scoring | unittest_reinvent/scoring_tests/scoring_components/test_classification_selectivity_component.py | import numpy.testing as npt
from unittest_reinvent.fixtures.test_data import CELECOXIB
from unittest_reinvent.scoring_tests.fixtures import create_activity_component_classification, \
create_offtarget_activity_component_classification
from unittest_reinvent.scoring_tests.scoring_components.fixtures import score_single
from unittest_reinvent.scoring_tests.scoring_components.base_selectivity_component import BaseTestSelectivityComponent
class TestClassificationSelectivityComponent(BaseTestSelectivityComponent):
def setUp(self):
self.activity = create_activity_component_classification()
self.off_activity = create_offtarget_activity_component_classification()
super().setUp()
def test_selectivity_component_1(self):
npt.assert_almost_equal(score_single(self.component, CELECOXIB), 0.01)
|
palace2001/bitbucket_prereceive_plugin_offline | target/bitbucket/app/static/bitbucket/internal/util/user-created-version.js | define('bitbucket/internal/util/user-created-version', ['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var RAW_VERSION = exports.RAW_VERSION = WRM.data.claim('com.atlassian.bitbucket.server.bitbucket-web:user-created-version.data') || '';
/**
* Parse a version string in to an array of numbers.
* @param {string} version - a dot-separated string of numbers
* @returns {Array<number>}
*/
var parseVersion = function parseVersion(version) {
return version.split('.').map(function (v) {
return Math.abs(parseInt(v));
});
};
/**
* Map a version array or string to a map with a major, minor, patch prop
* @param {Array<number>|string} version
* @returns {{major: number, minor: number, patch: number}}
*/
var mapVersion = exports.mapVersion = function mapVersion(version) {
if (typeof version === 'string') {
version = parseVersion(version);
}
return {
major: version[0] || 0,
minor: version[1] || 0,
patch: version[2] || 0
};
};
/**
* The mapped version at which the current user was created
* @type {{major: number, minor: number, patch: number}}
*/
var userCreatedVersion = exports.userCreatedVersion = mapVersion(RAW_VERSION);
/**
* Check if the current user has been created before the given target version
*
* @param {string} targetVersion - a version string in the format "1.2.3", i.e. "Major.Minor.Patch"
* @returns {boolean}
*/
var userCreatedBefore = exports.userCreatedBefore = function userCreatedBefore(targetVersion) {
var mappedTargetVersion = mapVersion(targetVersion);
// if major is less
if (userCreatedVersion.major < mappedTargetVersion.major) {
return true;
}
// if majors are the same but minor is less
if (userCreatedVersion.major === mappedTargetVersion.major && userCreatedVersion.minor < mappedTargetVersion.minor) {
return true;
}
// if majors and minors are the same but patch is less
if (userCreatedVersion.major === mappedTargetVersion.major && userCreatedVersion.minor === mappedTargetVersion.minor && userCreatedVersion.patch < mappedTargetVersion.patch) {
return true;
}
return false;
};
}); |
greensnark/go-sequell | pg/bind.go | <reponame>greensnark/go-sequell<filename>pg/bind.go
package pg
import "strconv"
// Binder tracks a postgres query bind variable.
type Binder int
// NotFirst returns true if this is not the first bind variable.
func (p *Binder) NotFirst() bool {
return *p > 1
}
// Next gets the bind variable string "$1", "$2" etc. for the current bind
// variable, and increments the binder.
func (p *Binder) Next() string {
nv := "$" + strconv.Itoa(int(*p))
(*p)++
return nv
}
// NewBinder creates a bind variable generator initialized to 1.
func NewBinder() *Binder {
var binder Binder = 1
return &binder
}
|
multiscripter/job4j | junior/pack2_junior/p4_web/ch6_filter/src/main/java/ru/job4j/filter/package-info.java | /**
* Package for junior.pack2.p9.ch6. Filter Security.
*
* @author <NAME> (mailto:<EMAIL>)
* @version 1
* @since 2017-12-08
*/
package ru.job4j.filter;
|
mendelmaleh/td | tg/tl_photos_get_user_photos_gen.go | <gh_stars>0
// Code generated by gotdgen, DO NOT EDIT.
package tg
import (
"context"
"fmt"
"strings"
"github.com/gotd/td/bin"
)
// No-op definition for keeping imports.
var _ = bin.Buffer{}
var _ = context.Background()
var _ = fmt.Stringer(nil)
var _ = strings.Builder{}
// PhotosGetUserPhotosRequest represents TL type `photos.getUserPhotos#91cd32a8`.
// Returns the list of user photos.
//
// See https://core.telegram.org/method/photos.getUserPhotos for reference.
type PhotosGetUserPhotosRequest struct {
// User ID
UserID InputUserClass
// Number of list elements to be skipped
Offset int
// If a positive value was transferred, the method will return only photos with IDs less than the set one
MaxID int64
// Number of list elements to be returned
Limit int
}
// PhotosGetUserPhotosRequestTypeID is TL type id of PhotosGetUserPhotosRequest.
const PhotosGetUserPhotosRequestTypeID = 0x91cd32a8
// String implements fmt.Stringer.
func (g *PhotosGetUserPhotosRequest) String() string {
if g == nil {
return "PhotosGetUserPhotosRequest(nil)"
}
var sb strings.Builder
sb.WriteString("PhotosGetUserPhotosRequest")
sb.WriteString("{\n")
sb.WriteString("\tUserID: ")
sb.WriteString(fmt.Sprint(g.UserID))
sb.WriteString(",\n")
sb.WriteString("\tOffset: ")
sb.WriteString(fmt.Sprint(g.Offset))
sb.WriteString(",\n")
sb.WriteString("\tMaxID: ")
sb.WriteString(fmt.Sprint(g.MaxID))
sb.WriteString(",\n")
sb.WriteString("\tLimit: ")
sb.WriteString(fmt.Sprint(g.Limit))
sb.WriteString(",\n")
sb.WriteString("}")
return sb.String()
}
// Encode implements bin.Encoder.
func (g *PhotosGetUserPhotosRequest) Encode(b *bin.Buffer) error {
if g == nil {
return fmt.Errorf("can't encode photos.getUserPhotos#91cd32a8 as nil")
}
b.PutID(PhotosGetUserPhotosRequestTypeID)
if g.UserID == nil {
return fmt.Errorf("unable to encode photos.getUserPhotos#91cd32a8: field user_id is nil")
}
if err := g.UserID.Encode(b); err != nil {
return fmt.Errorf("unable to encode photos.getUserPhotos#91cd32a8: field user_id: %w", err)
}
b.PutInt(g.Offset)
b.PutLong(g.MaxID)
b.PutInt(g.Limit)
return nil
}
// Decode implements bin.Decoder.
func (g *PhotosGetUserPhotosRequest) Decode(b *bin.Buffer) error {
if g == nil {
return fmt.Errorf("can't decode photos.getUserPhotos#91cd32a8 to nil")
}
if err := b.ConsumeID(PhotosGetUserPhotosRequestTypeID); err != nil {
return fmt.Errorf("unable to decode photos.getUserPhotos#91cd32a8: %w", err)
}
{
value, err := DecodeInputUser(b)
if err != nil {
return fmt.Errorf("unable to decode photos.getUserPhotos#91cd32a8: field user_id: %w", err)
}
g.UserID = value
}
{
value, err := b.Int()
if err != nil {
return fmt.Errorf("unable to decode photos.getUserPhotos#91cd32a8: field offset: %w", err)
}
g.Offset = value
}
{
value, err := b.Long()
if err != nil {
return fmt.Errorf("unable to decode photos.getUserPhotos#91cd32a8: field max_id: %w", err)
}
g.MaxID = value
}
{
value, err := b.Int()
if err != nil {
return fmt.Errorf("unable to decode photos.getUserPhotos#91cd32a8: field limit: %w", err)
}
g.Limit = value
}
return nil
}
// Ensuring interfaces in compile-time for PhotosGetUserPhotosRequest.
var (
_ bin.Encoder = &PhotosGetUserPhotosRequest{}
_ bin.Decoder = &PhotosGetUserPhotosRequest{}
)
// PhotosGetUserPhotos invokes method photos.getUserPhotos#91cd32a8 returning error if any.
// Returns the list of user photos.
//
// Possible errors:
// 400 MAX_ID_INVALID: The provided max ID is invalid
// 400 USER_ID_INVALID: The provided user ID is invalid
//
// See https://core.telegram.org/method/photos.getUserPhotos for reference.
// Can be used by bots.
func (c *Client) PhotosGetUserPhotos(ctx context.Context, request *PhotosGetUserPhotosRequest) (PhotosPhotosClass, error) {
var result PhotosPhotosBox
if err := c.rpc.InvokeRaw(ctx, request, &result); err != nil {
return nil, err
}
return result.Photos, nil
}
|
alphalapz/siie | src/erp/mod/trn/db/SRowFunctionalAreaBudgets.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package erp.mod.trn.db;
import erp.mod.cfg.db.SDbFunctionalArea;
import sa.lib.grid.SGridRow;
/**
*
* @author <NAME>
*/
public class SRowFunctionalAreaBudgets implements SGridRow {
public final static int COL_JAN = 1;
private SDbFunctionalArea moFunctionalArea;
private Double[] madBudgets; //
/**
* Create row of monthly budgets for functinoal area.
* @param functionalArea Functional area.
* @param budgets 12 monthly budgets.
* <code>null</code> means no budget set!, 0 means 0 budget, that is, no budget!
*/
public SRowFunctionalAreaBudgets(final SDbFunctionalArea functionalArea, final Double[] budgets) {
moFunctionalArea = functionalArea;
madBudgets = budgets;
}
public SDbFunctionalArea getFunctionalArea() { return moFunctionalArea; }
public Double[] getBudgets() { return madBudgets; }
@Override
public int[] getRowPrimaryKey() {
return moFunctionalArea.getPrimaryKey();
}
@Override
public String getRowCode() {
return moFunctionalArea.getCode();
}
@Override
public String getRowName() {
return moFunctionalArea.getName();
}
@Override
public boolean isRowSystem() {
return false;
}
@Override
public boolean isRowDeletable() {
return false;
}
@Override
public boolean isRowEdited() {
return true;
}
@Override
public void setRowEdited(boolean edited) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object getRowValueAt(int col) {
Object value = null;
switch (col) {
case 0: // functional area name
value = moFunctionalArea.getName();
break;
case COL_JAN: // Jan
case 2: // Feb
case 3: // Mar
case 4: // Apr
case 5: // May
case 6: // Jun
case 7: // Jul
case 8: // Aug
case 9: // Sep
case 10: // Oct
case 11: // Nov
case 12: // Dec
value = madBudgets[col - COL_JAN];
break;
default:
}
return value;
}
@Override
public void setRowValueAt(Object value, int col) {
switch (col) {
case 0: // functional area name
break;
case COL_JAN: // Jan
case 2: // Feb
case 3: // Mar
case 4: // Apr
case 5: // May
case 6: // Jun
case 7: // Jul
case 8: // Aug
case 9: // Sep
case 10: // Oct
case 11: // Nov
case 12: // Dec
madBudgets[col - COL_JAN] = (Double) value;
break;
default:
}
}
}
|
newmanne/logparser | src/chord/analyses/basicblock/DomW.java | <filename>src/chord/analyses/basicblock/DomW.java
/*
* Copyright (c) 2008-2010, Intel Corporation.
* Copyright (c) 2006-2007, The Trustees of Stanford University.
* All rights reserved.
* Licensed under the terms of the New BSD License.
*/
package chord.analyses.basicblock;
import joeq.Compiler.Quad.BasicBlock;
import joeq.Class.jq_Method;
import chord.project.Chord;
/**
* Domain of loop head/exit basic blocks.
*
* @author <NAME> (<EMAIL>)
*/
@Chord(
name = "W"
)
public class DomW extends DomB {
public int getOrAdd(BasicBlock b, jq_Method m) {
basicBlockToMethodMap.put(b, m);
return super.getOrAdd(b);
}
}
|
mitchellolsthoorn/ASE-Technical-2021-api-linkage-replication | EvoMaster/client-java/instrumentation/src/test/java/org/evomaster/client/java/instrumentation/coverage/methodreplacement/classes/CollectionClassReplacementTest.java | <filename>EvoMaster/client-java/instrumentation/src/test/java/org/evomaster/client/java/instrumentation/coverage/methodreplacement/classes/CollectionClassReplacementTest.java
package org.evomaster.client.java.instrumentation.coverage.methodreplacement.classes;
import org.evomaster.client.java.instrumentation.coverage.methodreplacement.DistanceHelper;
import org.evomaster.client.java.instrumentation.shared.ObjectiveNaming;
import org.evomaster.client.java.instrumentation.staticstate.ExecutionTracer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
/**
* Created by jgaleotti on 29-Ago-19.
*/
public class CollectionClassReplacementTest {
@BeforeEach
public void setUp() {
ExecutionTracer.reset();
}
@Test
public void testIsEmpty() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
List<Object> emptyList = Collections.emptyList();
boolean isEmptyValue = CollectionClassReplacement.isEmpty(emptyList, prefix);
assertTrue(isEmptyValue);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
String objectiveId = nonCoveredObjectives.iterator().next();
double value = ExecutionTracer.getValue(objectiveId);
assertEquals(0, value);
}
@Test
public void testIsNotEmpty() {
List<Object> emptyList = Collections.singletonList("Hello World");
boolean isEmptyValue = CollectionClassReplacement.isEmpty(emptyList, ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate");
assertFalse(isEmptyValue);
}
@Test
public void testNull() {
assertThrows(NullPointerException.class,
() -> {
CollectionClassReplacement.isEmpty(null, ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate");
});
}
@Test
public void testContainsOnEmptyCollection() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
List<Object> emptyList = Collections.emptyList();
boolean containsValue = CollectionClassReplacement.contains(emptyList, "Hello World", prefix);
assertFalse(containsValue);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
String objectiveId = nonCoveredObjectives.iterator().next();
double value = ExecutionTracer.getValue(objectiveId);
assertNotEquals(0, value);
assertEquals(DistanceHelper.H_REACHED_BUT_EMPTY, value);
}
@Test
public void testContainsOnNonEmptyStringCollection() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
List<Object> singletonList = Collections.singletonList("");
boolean containsValue = CollectionClassReplacement.contains(singletonList, "Hello World", prefix);
assertFalse(containsValue);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
String objectiveId = nonCoveredObjectives.iterator().next();
double value = ExecutionTracer.getValue(objectiveId);
assertNotEquals(0, value);
assertTrue(value > DistanceHelper.H_NOT_EMPTY);
assertTrue(value > DistanceHelper.H_REACHED_BUT_EMPTY);
}
@Test
public void testContainsOnNonEmptyMoreThanOne() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
boolean containsValue0 = CollectionClassReplacement.contains(Collections.singletonList("Hello W____"), "Hello World", prefix);
assertFalse(containsValue0);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
final String objectiveId = nonCoveredObjectives.iterator().next();
final double heuristicValue0 = ExecutionTracer.getValue(objectiveId);
assertNotEquals(0, heuristicValue0);
assertTrue(heuristicValue0 > DistanceHelper.H_NOT_EMPTY);
assertTrue(heuristicValue0 > DistanceHelper.H_REACHED_BUT_EMPTY);
boolean containsValue1 = CollectionClassReplacement.contains(Arrays.asList("Hello W____", "Hello Worl_"), "Hello World", prefix);
assertFalse(containsValue1);
final double heuristicValue1 = ExecutionTracer.getValue(objectiveId);
assertTrue(heuristicValue1 > heuristicValue0);
}
@Test
public void testContainsOnNonEmptyIntegerCollection() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
boolean containsValue0 = CollectionClassReplacement.contains(Collections.singletonList(1010), 1000, prefix);
assertFalse(containsValue0);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
String objectiveId = nonCoveredObjectives.iterator().next();
double heuristicValue0 = ExecutionTracer.getValue(objectiveId);
assertNotEquals(0, heuristicValue0);
assertTrue(heuristicValue0 > DistanceHelper.H_NOT_EMPTY);
assertTrue(heuristicValue0 > DistanceHelper.H_REACHED_BUT_EMPTY);
boolean containsValue1 = CollectionClassReplacement.contains(Arrays.asList(1010, 1001), 1000, prefix);
double heuristicValue1 = ExecutionTracer.getValue(objectiveId);
assertTrue(heuristicValue1 > heuristicValue0);
}
@Test
public void testContainsNoMatch() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
boolean containsValue0 = CollectionClassReplacement.contains(Collections.singletonList("Hello W____"), 1000, prefix);
assertFalse(containsValue0);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
final String objectiveId = nonCoveredObjectives.iterator().next();
final double heuristicValue0 = ExecutionTracer.getValue(objectiveId);
assertNotEquals(0, heuristicValue0);
assertEquals(DistanceHelper.H_NOT_EMPTY, heuristicValue0);
}
@Test
public void testContainsByte() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
boolean containsValue0 = CollectionClassReplacement.contains(Collections.singletonList((byte) 0), (byte) 1, prefix);
assertFalse(containsValue0);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
final String objectiveId = nonCoveredObjectives.iterator().next();
final double heuristicValue0 = ExecutionTracer.getValue(objectiveId);
assertNotEquals(0, heuristicValue0);
assertTrue(heuristicValue0 > DistanceHelper.H_REACHED_BUT_EMPTY);
}
@Test
public void testContainsShort() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
boolean containsValue0 = CollectionClassReplacement.contains(Collections.singletonList((short) 0), (short) 1, prefix);
assertFalse(containsValue0);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
final String objectiveId = nonCoveredObjectives.iterator().next();
final double heuristicValue0 = ExecutionTracer.getValue(objectiveId);
assertNotEquals(0, heuristicValue0);
assertTrue(heuristicValue0 > DistanceHelper.H_REACHED_BUT_EMPTY);
}
@Test
public void testContainsCharacter() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
boolean containsValue0 = CollectionClassReplacement.contains(Collections.singletonList((char) 0), (char) 1, prefix);
assertFalse(containsValue0);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
final String objectiveId = nonCoveredObjectives.iterator().next();
final double heuristicValue0 = ExecutionTracer.getValue(objectiveId);
assertNotEquals(0, heuristicValue0);
assertTrue(heuristicValue0 > DistanceHelper.H_REACHED_BUT_EMPTY);
}
@Test
public void testContainsLong() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
boolean containsValue0 = CollectionClassReplacement.contains(Collections.singletonList((long) 0), (long) 1, prefix);
assertFalse(containsValue0);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
final String objectiveId = nonCoveredObjectives.iterator().next();
final double heuristicValue0 = ExecutionTracer.getValue(objectiveId);
assertNotEquals(0, heuristicValue0);
assertTrue(heuristicValue0 > DistanceHelper.H_REACHED_BUT_EMPTY);
}
@Test
public void testContainsFloat() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
boolean containsValue0 = CollectionClassReplacement.contains(Collections.singletonList((float) 0.0), (float) 0.1, prefix);
assertFalse(containsValue0);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
final String objectiveId = nonCoveredObjectives.iterator().next();
final double heuristicValue0 = ExecutionTracer.getValue(objectiveId);
assertNotEquals(0, heuristicValue0);
assertTrue(heuristicValue0 > DistanceHelper.H_REACHED_BUT_EMPTY);
}
@Test
public void testContainsDouble() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
boolean containsValue0 = CollectionClassReplacement.contains(Collections.singletonList((double) 0.0), (double) 0.1, prefix);
assertFalse(containsValue0);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
final String objectiveId = nonCoveredObjectives.iterator().next();
final double heuristicValue0 = ExecutionTracer.getValue(objectiveId);
assertNotEquals(0, heuristicValue0);
assertTrue(heuristicValue0 > DistanceHelper.H_REACHED_BUT_EMPTY);
}
@Test
public void testContainsDate() throws ParseException {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
String date1 = "07/15/2016";
String time1 = "11:00 AM";
String time2 = "11:15 AM";
String format = "MM/dd/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateTime1 = sdf.parse(date1 + " " + time1);
Date dateTime2 = sdf.parse(date1 + " " + time2);
boolean containsValue0 = CollectionClassReplacement.contains(Collections.singletonList(dateTime1), dateTime2, prefix);
assertFalse(containsValue0);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
final String objectiveId = nonCoveredObjectives.iterator().next();
final double heuristicValue0 = ExecutionTracer.getValue(objectiveId);
assertNotEquals(0, heuristicValue0);
assertTrue(heuristicValue0 > DistanceHelper.H_REACHED_BUT_EMPTY);
}
@Test
public void testContainsString() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
boolean containsValue0 = CollectionClassReplacement.contains(Collections.singletonList("Hello World"), "Hello World", prefix);
assertTrue(containsValue0);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
final String objectiveId = nonCoveredObjectives.iterator().next();
final double heuristicValue0 = ExecutionTracer.getValue(objectiveId);
assertEquals(0, heuristicValue0);
}
@Test
public void testContainsNotSupported() {
final String prefix = ObjectiveNaming.METHOD_REPLACEMENT + "idTemplate";
boolean containsValue0 = CollectionClassReplacement.contains(Collections.singletonList(true), false, prefix);
assertFalse(containsValue0);
Set<String> nonCoveredObjectives = ExecutionTracer.getNonCoveredObjectives(prefix);
assertEquals(1, nonCoveredObjectives.size());
final String objectiveId = nonCoveredObjectives.iterator().next();
final double heuristicValue0 = ExecutionTracer.getValue(objectiveId);
assertEquals(DistanceHelper.H_NOT_EMPTY, heuristicValue0);
}
}
|
kalisjoshua/adventofcode | 2021/day17.js | <filename>2021/day17.js
// 20, 30, -10, -5
// 143, 177, -106, -71
const example = "target area: x=20..30, y=-10..-5"
const sumOfIntegers = (start) => start * (1 + start) / 2
function findMaxHeight (input) {
// const mapAscending =
const reduceInRange = (acc, [num, sumInts]) =>
sumInts >= input[0] && sumInts <= input[1]
? [...acc, num]
: acc
return Array
.from(Array(Math.floor(input[0])), (_, i) => [i, sumOfIntegers(i)])
.reduce(reduceInRange, [])
// I do NOT know why (initial Y velocity) this - Math.abs(input[2]) - 1) - works
.map((x) => simulate(input, x, Math.abs(input[2]) - 1))
.sort((a, b) => a.maxHeight - b.maxHeight)
.pop()
// return Array
// .from(Array(Math.floor(input[0])), (_, i) => [i, sumOfIntegers(i)])
// .reduce(reduceInRange, [])
// .map((velocityX) => {
// let velocityY = 1
// const results = []
//
// do {
// results.unshift(simulate(input, velocityX, velocityY++))
// } while (results[0].maxHeight)
//
// // results.shift()
//
// return results
// })
// .flat()
// .sort((a, b) => a.maxHeight - b.maxHeight)
// .pop()
}
function simulate ([rangeXmin, rangeXmax, rangeYmin, rangeYmax], velocityX, velocityY) {
const initialVelocity = [velocityX, velocityY]
let failed = false
let height = 0
let success = false
let x = 0
let y = 0
while (!failed && !success) {
// 1. The probe's x position increases by its x velocity.
x += velocityX
// 2. The probe's y position increases by its y velocity.
y += velocityY
// 3. Due to drag, the probe's x velocity changes by 1 toward the value 0; that is,
// it decreases by 1 if it is greater than 0,
// increases by 1 if it is less than 0,
// or does not change if it is already 0.
velocityX += velocityX > 0 ? -1 : velocityX < 0 ? 1 : 0
// 4. Due to gravity, the probe's y velocity decreases by 1.
velocityY -= 1
height = height < y ? y : height
success = rangeXmin <= x && rangeXmax >= x && rangeYmin <= y && rangeYmax >= y
failed = x > rangeXmax || y < rangeYmin
// console.log({x, y, velocityX, velocityY})
}
return {
initialVelocity,
maxHeight: success ? height : 0,
position: [x, y],
success,
underOrOver: x < rangeXmin ? -1 : x > rangeXmax ? 1 : 0,
}
}
module.exports = (input, {report}) => {
input = input
.trim()
.match(/-?\d+/g)
const partOne = findMaxHeight(input)
// console.log(JSON.stringify(partOne, null, 4))
// my guess and check - totally luck based - solution
// console.log(JSON.stringify(simulate(input, 17, 105), null, 4))
// console.log(JSON.stringify(simulate(input, 18, 105), null, 4))
const partTwo = input
// 1326 is too low
report('Part one', partOne.maxHeight, 5565)
// report('Part two', partTwo)
}
|
abhishekkarnani/hound | spec/lib/tasks/membership_spec.rb | require "spec_helper"
require "rake"
describe "namespace membership" do
before :all do
Rake.application.rake_require "tasks/membership"
Rake::Task.define_task(:environment)
end
describe "task cleanup_duplicates" do
before do
@user1 = create :user
create :membership, user: @user1
create :membership, user: @user1
@user2 = create :user
repo = create :repo
create :membership, user: @user2, repo: repo
create :membership, user: @user2, repo: repo
create :membership, user: @user2, repo: repo
create :membership, user: @user2
task = Rake::Task["membership:cleanup_duplicates"]
task.reenable
task.invoke
end
it "cleans up duplicates" do
expect(@user2.repos.count).to eq(2)
end
it "does not alter user without duplicates" do
expect(@user1.repos.count).to eq(2)
end
end
end
|
debmalya/mapDB | src/main/java/scrapper/FormProcessor.java | /**
* Copyright 2015-2016 <NAME>
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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 scrapper;
import java.io.IOException;
import java.net.URL;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import model.SecDocument;
/**
* Mainly 10K like form processor.
*
* @author debmalyajash
*
*/
public class FormProcessor {
private String parsedString;
/**
*
*/
private static final String TABLE_OF_CONTENTS = "Table of Contents";
private static final Logger LOGGER = Logger.getLogger(FormProcessor.class);
public void process(final URL url) throws IOException {
Document doc = Jsoup.connect(url.toString()).get();
SecDocument secDocument = new SecDocument();
setHeader(doc, secDocument);
setPart(doc, secDocument);
}
/**
*
* @param url
* @return
* @throws IOException
*/
public String processHTML(final URL url) throws IOException {
return Jsoup.connect(url.toString()).get().text();
}
/**
* @param doc
* @param secDocument
*/
private void setPart(Document doc, SecDocument secDocument) {
// TODO Auto-generated method stub
}
/**
* @param doc
* @return
*/
private void setHeader(Document doc, SecDocument secDocument) {
secDocument.setDescription(doc.select("title").text());
Elements descriptionElements = doc.select("div");
StringBuilder sb = new StringBuilder();
int count = 1;
for (Element eachDescriptionElement : descriptionElements) {
LOGGER.debug(count + " " + eachDescriptionElement.text());
sb.append(eachDescriptionElement.text());
count++;
}
setParsedString(sb.toString());
}
/**
* Process all the links of the document.
*
* @param doc
* @throws IOException
*/
private void processLinks(final Document doc) throws IOException {
Elements links = doc.select("a");
for (Element eachLink : links) {
String linkText = eachLink.text().trim();
if (linkText.length() > 0 && !linkText.equalsIgnoreCase(TABLE_OF_CONTENTS))
LOGGER.debug(eachLink.text());
}
}
/**
* Processes all the font from the document.
*
* @param doc
* document to be processed.
*/
public void processFonts(Document doc) {
Elements fontList = doc.select("font");
for (Element eachELement : fontList) {
String txt = eachELement.text();
if (txt.contains("ITEM")) {
LOGGER.debug(eachELement.text());
}
}
}
/**
* @return the parsedString
*/
public String getParsedString() {
return parsedString;
}
/**
* @param parsedString the parsedString to set
*/
private void setParsedString(String parsedString) {
this.parsedString = parsedString;
}
}
|
CooperRedhat/insights-rbac-ui | src/test/redux/actions/role-actions.test.js | import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import promiseMiddleware from 'redux-promise-middleware';
import { fetchRoles } from '../../../redux/actions/role-actions';
import { FETCH_ROLES } from '../../../redux/action-types';
import { notificationsMiddleware } from '@redhat-cloud-services/frontend-components-notifications/';
import * as RoleHelper from '../../../helpers/role/role-helper';
describe('role actions', () => {
const middlewares = [thunk, promiseMiddleware, notificationsMiddleware()];
let mockStore;
const fetchRolesSpy = jest.spyOn(RoleHelper, 'fetchRoles');
beforeEach(() => {
mockStore = configureStore(middlewares);
});
afterEach(() => {
fetchRolesSpy.mockReset();
});
it('should dispatch correct actions after fetching roles', async () => {
const store = mockStore({});
fetchRolesSpy.mockResolvedValueOnce({
data: [{ name: 'roleName', uuid: '1234' }],
});
const expectedActions = [
{
type: `${FETCH_ROLES}_PENDING`,
},
{
payload: { data: [{ name: 'roleName', uuid: '1234' }] },
type: `${FETCH_ROLES}_FULFILLED`,
},
];
await store.dispatch(fetchRoles());
expect(store.getActions()).toEqual(expectedActions);
});
});
|
nangelos/abcd | server/api/parents.js | const router = require('express').Router()
const {ParentInfo} = require('../db/models')
module.exports = router
router.get('/', async (req, res, next) => {
try {
const info = await ParentInfo.findAll({})
res.json(info)
} catch (err) {
next(err)
}
})
router.post('/', async (req, res, next) => {
try {
console.log('post req.body: ', req.body)
let {body} = req
const info = await ParentInfo.create({...body})
res.status(201).json(info)
} catch (err) {
next(err)
}
})
router.put('/:id', async (req, res, next) => {
try {
const {id} = req.params
const {body} = req
console.log('here is the req.body: ', body)
const data = await ParentInfo.update({...body}, {where: {userId: id}})
res.json(data)
} catch (err) {
next(err)
}
})
router.get('/:id', async (req, res, next) => {
try {
console.log('get :id params: ', req.params)
let {id} = req.params
const user = await ParentInfo.findAll({
where: {userId: id},
})
res.json(user)
} catch (err) {
next(err)
}
})
|
dmarcotte/intellij-community | plugins/hg4idea/src/org/zmlx/hg4idea/action/HgMqRebaseAction.java | <filename>plugins/hg4idea/src/org/zmlx/hg4idea/action/HgMqRebaseAction.java
// Copyright 2008-2010 <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 org.zmlx.hg4idea.action;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.zmlx.hg4idea.command.HgMQCommand;
import org.zmlx.hg4idea.command.HgPullCommand;
import org.zmlx.hg4idea.ui.HgPullDialog;
import java.util.Collection;
// TODO unsued code. Keeping until MQ extension will be supported
public class HgMqRebaseAction extends HgAbstractGlobalAction {
protected HgGlobalCommandBuilder getHgGlobalCommandBuilder(final Project project) {
return new HgGlobalCommandBuilder() {
public HgGlobalCommand build(Collection<VirtualFile> repos) {
HgPullDialog dialog = new HgPullDialog(project);
dialog.setRoots(repos);
dialog.show();
if (dialog.isOK()) {
return buildCommand(dialog, project);
}
return null;
}
};
}
private HgGlobalCommand buildCommand(final HgPullDialog dialog, final Project project) {
final VirtualFile repository = dialog.getRepository();
return new HgGlobalCommand() {
public VirtualFile getRepo() {
return repository;
}
public void execute() {
HgMQCommand mqCommand = new HgMQCommand(project);
boolean notFoundAppliedPatches = mqCommand.qapplied(repository).isEmpty();
if (notFoundAppliedPatches) {
return;
}
HgPullCommand pullCommand = new HgPullCommand(project, repository);
pullCommand.setSource(dialog.getSource());
pullCommand.setRebase(true);
pullCommand.setUpdate(false);
//pullCommand.execute(new HgCommandResultHandler() {
// @Override
// public void process(@Nullable HgCommandResult result) {
// new HgCommandResultNotifier(project).process(result, null, null);
//
// String currentBranch = new HgTagBranchCommand(project, repository).getCurrentBranch();
// if (StringUtil.isEmptyOrSpaces(currentBranch)) {
// return;
// }
//
// new HgConflictResolver(project).resolve(repository);
//
// HgResolveCommand resolveCommand = new HgResolveCommand(project);
// Map<HgFile, HgResolveStatusEnum> status = resolveCommand.getListSynchronously(repository);
//
// if (status.containsValue(HgResolveStatusEnum.UNRESOLVED)) {
// return;
// }
//
// new HgRebaseCommand(project, repository).continueRebase();
// }
//});
}
};
}
}
|
kwonjoseph/CharismaticChard | client/src/components/historyItem.js | import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchSplitterHistoryItem } from '../actions/historyAction.js';
import Loading from './loading';
const mapStateToProps = state => {
return {
item: state.history.splitterHistoryItem
};
};
const mapDispatchToProps = dispatch => {
return {
fetchSplitterHistoryItem: () => dispatch(
fetchSplitterHistoryItem()
),
};
};
class SplitterHistoryItem extends React.Component {
componentWillMount() {
this.props.fetchSplitterHistoryItem();
}
render() {
return this.props.item ? (
<div className="head">
<h3 className="split-history-title">Item History</h3>
<div className="history-button">
<Link className="btn btn-primary" to="/history" >Split History</Link>
<Link className="btn btn-primary" to="/item">Item History</Link>
</div>
<div className="container-fluid">
{ this.props.item.map((data, index) => (
<div className= "split-history" key={index}>
<div className="row">
<label className="col-xs-6">Split Name: </label>
<p className="col-xs-6">{data.split.split_name}</p>
</div>
<div className="row">
<label className="col-xs-6">Splitter: </label>
<p className="col-xs-6">{data.splitter.display}</p>
</div>
<div className="row">
<label className="col-xs-6">Item: </label>
<p className="col-xs-6">{data.item_name}</p>
</div>
<div className="row">
<label className="col-xs-6">Price: </label>
<p className="col-xs-6">${data.price}</p>
</div>
</div>
))
}
</div>
</div>
) : (
<Loading/>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SplitterHistoryItem); |
wilseypa/ROSS | rnf/modules/application/ftp/ftp-extern.h | #ifndef INC_model_extern_h
#define INC_model_extern_h
/*
* ftp-xml.c
*/
extern void ftp_xml();
/*
* ftp.c
*/
extern void ftp_statistics_print();
/*
* ftp.c
*/
extern void ftp_init(ftp_lp_state * state, tw_lp * lp);
extern void ftp_event_handler(ftp_lp_state * state, tw_bf * bf,
rn_message * msg, tw_lp * lp);
extern void ftp_rc_event_handler(ftp_lp_state * state, tw_bf * bf,
rn_message * msg, tw_lp * lp);
extern void ftp_final(ftp_lp_state * state, tw_lp * lp);
/*
* ftp-global.c
*/
extern char *g_ftp_buffer;
extern unsigned int g_ftp_buffer_size;
extern unsigned long int g_ftp_chunk_size;
extern tw_fd g_ftp_fd;
extern ftp_statistics g_ftp_stats;
#if MODULE
extern rn_lptype ftp_lp;
#endif
#endif
|
McJty/AquaMunda | src/main/java/mcjty/aquamunda/compat/jei/JeiGrindstoneRecipeWrapper.java | package mcjty.aquamunda.compat.jei;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.ingredients.VanillaTypes;
import mezz.jei.api.recipe.wrapper.ICraftingRecipeWrapper;
import net.minecraft.client.Minecraft;
import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.List;
class JeiGrindstoneRecipeWrapper implements ICraftingRecipeWrapper {
private final JeiGrindstoneRecipe recipe;
public JeiGrindstoneRecipeWrapper(JeiGrindstoneRecipe recipe) {
this.recipe = recipe;
}
@Override
public void getIngredients(@Nonnull IIngredients ingredients) {
ingredients.setOutput(VanillaTypes.ITEM, recipe.getRecipe().getOutputItem());
ingredients.setInput(VanillaTypes.ITEM, recipe.getRecipe().getInputItem());
}
@Override
public void drawInfo(@Nonnull Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY) {
}
@Override
public List<String> getTooltipStrings(int mouseX, int mouseY) {
return Collections.emptyList();
}
}
|
trickyMan/paraview_view | Qt/ApplicationComponents/pqListPropertyWidget.cxx | <reponame>trickyMan/paraview_view<gh_stars>0
/*=========================================================================
Program: ParaView
Module: $RCSfile$
Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
========================================================================*/
#include "pqListPropertyWidget.h"
#include "vtkSMProperty.h"
#include <QDoubleValidator>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QIntValidator>
#include <QItemDelegate>
#include <QLineEdit>
#include <QPointer>
#include <QTableWidget>
namespace
{
class pqListPropertyWidgetDelegate : public QItemDelegate
{
public:
QPointer<QValidator> Validator;
pqListPropertyWidgetDelegate(QObject* parentObject = 0)
: QItemDelegate(parentObject)
{
}
// create a line-edit with validator.
virtual QWidget* createEditor(
QWidget* parentObject, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
(void)option;
(void)index;
QLineEdit* editor = new QLineEdit(parentObject);
editor->setValidator(this->Validator);
return editor;
}
};
}
//-----------------------------------------------------------------------------
pqListPropertyWidget::pqListPropertyWidget(
vtkSMProxy* smproxy, vtkSMProperty* smproperty, QWidget* parentObject)
: Superclass(smproxy, parentObject)
, TableWidget(new QTableWidget(this))
{
pqListPropertyWidgetDelegate* delegate = new pqListPropertyWidgetDelegate(this);
if (smproperty->IsA("vtkSMDoubleVectorProperty"))
{
delegate->Validator = new QDoubleValidator(delegate);
}
else if (smproperty->IsA("vtkSMIntVectorProperty"))
{
delegate->Validator = new QIntValidator(delegate);
}
this->TableWidget->setObjectName("ListWidget");
this->TableWidget->setColumnCount(1);
this->TableWidget->horizontalHeader()->setStretchLastSection(true);
this->TableWidget->setItemDelegate(delegate);
this->TableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
QStringList headerLabels;
headerLabels << smproperty->GetXMLLabel();
this->TableWidget->setHorizontalHeaderLabels(headerLabels);
QHBoxLayout* hbox = new QHBoxLayout(this);
hbox->setMargin(0);
hbox->setSpacing(0);
hbox->addWidget(this->TableWidget);
this->setShowLabel(false);
this->addPropertyLink(this, "value", SIGNAL(valueChanged()), smproperty);
QObject::connect(
this->TableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), this, SIGNAL(valueChanged()));
}
//-----------------------------------------------------------------------------
pqListPropertyWidget::~pqListPropertyWidget()
{
}
//-----------------------------------------------------------------------------
QList<QVariant> pqListPropertyWidget::value() const
{
QList<QVariant> values;
for (int cc = 0; cc < this->TableWidget->rowCount(); cc++)
{
QTableWidgetItem* item = this->TableWidget->item(cc, 0);
values << item->text();
}
return values;
}
//-----------------------------------------------------------------------------
void pqListPropertyWidget::setValue(const QList<QVariant>& values)
{
this->TableWidget->setRowCount(values.size());
for (int cc = 0; cc < values.size(); cc++)
{
QTableWidgetItem* item = this->TableWidget->item(cc, 0);
if (item)
{
item->setText(values[cc].toString());
}
else
{
item = new QTableWidgetItem(values[cc].toString());
item->setFlags(item->flags() | Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled);
this->TableWidget->setItem(cc, 0, item);
}
}
}
|
ghsecuritylab/alios_aligenie | platform/mcu/sv6266/user_atcmd.h | <filename>platform/mcu/sv6266/user_atcmd.h<gh_stars>0
#ifndef __USER_ATCMD_H__
#define __USER_ATCMD_H__
/***********************************************************************************/
//#define ANION "anionOnOff" //负离子
#define ULTRAVIOLET "ultravioletOnOff" //消毒
#define AIR_DRYING "airDryOnOff" //风干
#define DRYING "drying" //烘干
#define ILLUMINATION "illumination" //照明
#define UP_DOWN "motorControl" //上升或下降
#define CMD_SET_END_CODE 0x69
#define CMD_SET_RESERVE_CODE 0xB4
#define CMD_SET_USER_CODE 0x10
#define CMD_SET_APP_VERSION 0x01
#define APP_UART_BUF_MAX 512
#define APP_UART_RX_TIMEOUT 50
/***********************************************************************************/
typedef struct {
uint8_t lightStatus;
uint8_t posationStatus;
uint8_t functionStatus;
uint8_t voiceStatus;
}deviceProperty_t;
typedef struct {
uint8_t anionOnOff;
uint8_t ultravioletOnOff;
uint8_t airDryOnOff;
uint8_t drying;
uint8_t illumination;
uint8_t motorControl;
}deviceStatus_t;
typedef struct
{
uint8_t useFlag;
uint8_t buf[APP_UART_BUF_MAX+1];
uint32_t recvLen;
}appUartRx_t;
/***********************************************************************************/
void server_cmd_process(char* str);
void app_components_init(void);
uint8_t user_pub_msg(char*, uint16_t);
#endif
|
cjsteel/python3-venv-ansible-2.10.5 | lib/python3.8/site-packages/ansible/module_utils/facts/system/pkg_mgr.py | <gh_stars>1-10
# Collect facts related to the system package manager
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import subprocess
from ansible.module_utils.facts.collector import BaseFactCollector
# A list of dicts. If there is a platform with more than one
# package manager, put the preferred one last. If there is an
# ansible module, use that as the value for the 'name' key.
PKG_MGRS = [{'path': '/usr/bin/yum', 'name': 'yum'},
{'path': '/usr/bin/dnf', 'name': 'dnf'},
{'path': '/usr/bin/apt-get', 'name': 'apt'},
{'path': '/usr/bin/zypper', 'name': 'zypper'},
{'path': '/usr/sbin/urpmi', 'name': 'urpmi'},
{'path': '/usr/bin/pacman', 'name': 'pacman'},
{'path': '/bin/opkg', 'name': 'opkg'},
{'path': '/usr/pkg/bin/pkgin', 'name': 'pkgin'},
{'path': '/opt/local/bin/pkgin', 'name': 'pkgin'},
{'path': '/opt/tools/bin/pkgin', 'name': 'pkgin'},
{'path': '/opt/local/bin/port', 'name': 'macports'},
{'path': '/usr/local/bin/brew', 'name': 'homebrew'},
{'path': '/sbin/apk', 'name': 'apk'},
{'path': '/usr/sbin/pkg', 'name': 'pkgng'},
{'path': '/usr/sbin/swlist', 'name': 'swdepot'},
{'path': '/usr/bin/emerge', 'name': 'portage'},
{'path': '/usr/sbin/pkgadd', 'name': 'svr4pkg'},
{'path': '/usr/bin/pkg', 'name': 'pkg5'},
{'path': '/usr/bin/xbps-install', 'name': 'xbps'},
{'path': '/usr/local/sbin/pkg', 'name': 'pkgng'},
{'path': '/usr/bin/swupd', 'name': 'swupd'},
{'path': '/usr/sbin/sorcery', 'name': 'sorcery'},
{'path': '/usr/bin/rpm-ostree', 'name': 'atomic_container'},
{'path': '/usr/bin/installp', 'name': 'installp'},
{'path': '/QOpenSys/pkgs/bin/yum', 'name': 'yum'},
]
class OpenBSDPkgMgrFactCollector(BaseFactCollector):
name = 'pkg_mgr'
_fact_ids = set()
_platform = 'OpenBSD'
def collect(self, module=None, collected_facts=None):
facts_dict = {}
facts_dict['pkg_mgr'] = 'openbsd_pkg'
return facts_dict
# the fact ends up being 'pkg_mgr' so stick with that naming/spelling
class PkgMgrFactCollector(BaseFactCollector):
name = 'pkg_mgr'
_fact_ids = set()
_platform = 'Generic'
required_facts = set(['distribution'])
def _check_rh_versions(self, pkg_mgr_name, collected_facts):
if collected_facts['ansible_distribution'] == 'Fedora':
if os.path.exists('/run/ostree-booted'):
return "atomic_container"
try:
if int(collected_facts['ansible_distribution_major_version']) < 23:
for yum in [pkg_mgr for pkg_mgr in PKG_MGRS if pkg_mgr['name'] == 'yum']:
if os.path.exists(yum['path']):
pkg_mgr_name = 'yum'
break
else:
for dnf in [pkg_mgr for pkg_mgr in PKG_MGRS if pkg_mgr['name'] == 'dnf']:
if os.path.exists(dnf['path']):
pkg_mgr_name = 'dnf'
break
except ValueError:
# If there's some new magical Fedora version in the future,
# just default to dnf
pkg_mgr_name = 'dnf'
elif collected_facts['ansible_distribution'] == 'Amazon':
pkg_mgr_name = 'yum'
else:
# If it's not one of the above and it's Red Hat family of distros, assume
# RHEL or a clone. For versions of RHEL < 8 that Ansible supports, the
# vendor supported official package manager is 'yum' and in RHEL 8+
# (as far as we know at the time of this writing) it is 'dnf'.
# If anyone wants to force a non-official package manager then they
# can define a provider to either the package or yum action plugins.
if int(collected_facts['ansible_distribution_major_version']) < 8:
pkg_mgr_name = 'yum'
else:
pkg_mgr_name = 'dnf'
return pkg_mgr_name
def _check_apt_flavor(self, pkg_mgr_name):
# Check if '/usr/bin/apt' is APT-RPM or an ordinary (dpkg-based) APT.
# There's rpm package on Debian, so checking if /usr/bin/rpm exists
# is not enough. Instead ask RPM if /usr/bin/apt-get belongs to some
# RPM package.
rpm_query = '/usr/bin/rpm -q --whatprovides /usr/bin/apt-get'.split()
if os.path.exists('/usr/bin/rpm'):
with open(os.devnull, 'w') as null:
try:
subprocess.check_call(rpm_query, stdout=null, stderr=null)
pkg_mgr_name = 'apt_rpm'
except subprocess.CalledProcessError:
# No apt-get in RPM database. Looks like Debian/Ubuntu
# with rpm package installed
pkg_mgr_name = 'apt'
return pkg_mgr_name
def collect(self, module=None, collected_facts=None):
facts_dict = {}
collected_facts = collected_facts or {}
pkg_mgr_name = 'unknown'
for pkg in PKG_MGRS:
if os.path.exists(pkg['path']):
pkg_mgr_name = pkg['name']
# Handle distro family defaults when more than one package manager is
# installed or available to the distro, the ansible_fact entry should be
# the default package manager officially supported by the distro.
if collected_facts['ansible_os_family'] == "RedHat":
pkg_mgr_name = self._check_rh_versions(pkg_mgr_name, collected_facts)
elif collected_facts['ansible_os_family'] == 'Debian' and pkg_mgr_name != 'apt':
# It's possible to install yum, dnf, zypper, rpm, etc inside of
# Debian. Doing so does not mean the system wants to use them.
pkg_mgr_name = 'apt'
elif collected_facts['ansible_os_family'] == 'Altlinux':
if pkg_mgr_name == 'apt':
pkg_mgr_name = 'apt_rpm'
# Check if /usr/bin/apt-get is ordinary (dpkg-based) APT or APT-RPM
if pkg_mgr_name == 'apt':
pkg_mgr_name = self._check_apt_flavor(pkg_mgr_name)
facts_dict['pkg_mgr'] = pkg_mgr_name
return facts_dict
|
amgmetallica/polymer-chrome-dev-summit-learning | node_modules/hydrolysis/lib/loader/file-loader.js | /**
* @license
* Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
// jshint node:true
'use strict';
// jshint -W079
// Promise polyfill
var Promise = global.Promise || require('es6-promise').Promise;
// jshint +W079
function Deferred() {
var self = this;
this.promise = new Promise(function(resolve, reject) {
self.resolve = resolve;
self.reject = reject;
});
}
/**
* An object that knows how to resolve resources.
* @typedef {Object} Resolver
* @memberof hydrolysis
* @property {function(string, Deferred): boolean} accept Attempt to resolve
* `deferred` with the contents the specified URL. Returns false if the
* Resolver is unable to resolve the URL.
*/
/**
* A FileLoader lets you resolve URLs with a set of potential resolvers.
* @constructor
* @memberof hydrolysis
*/
function FileLoader() {
this.resolvers = [];
// map url -> Deferred
this.requests = {};
}
FileLoader.prototype = {
/**
* Add an instance of a Resolver class to the list of url resolvers
*
* Ordering of resolvers is most to least recently added
* The first resolver to "accept" the url wins.
* @param {Resolver} resolver The resolver to add.
*/
addResolver: function(resolver) {
this.resolvers.push(resolver);
},
/**
* Return a promise for an absolute url
*
* Url requests are deduplicated by the loader, returning the same Promise for
* identical urls
*
* @param {string} url The absolute url to request.
* @return {Promise.<string>} A promise that resolves to the contents of the URL.
*/
request: function(uri) {
var promise;
if (!(uri in this.requests)) {
var handled = false;
var deferred = new Deferred();
this.requests[uri] = deferred;
// loop backwards through resolvers until one "accepts" the request
for (var i = this.resolvers.length - 1, r; i >= 0; i--) {
r = this.resolvers[i];
if (r.accept(uri, deferred)) {
handled = true;
break;
}
}
if (!handled) {
deferred.reject(new Error('no resolver found for ' + uri));
}
promise = deferred.promise;
} else {
promise = this.requests[uri].promise;
}
return promise;
}
};
module.exports = FileLoader;
|
Right-Angle-Engineering/mui-treasury | packages/mui-styles/esm/button/twitter/twitterBtn.styles.js | export default (function (_ref) {
var shadows = _ref.shadows,
palette = _ref.palette;
return {
root: {
borderRadius: 100,
minHeight: 30,
padding: '0 1em'
},
label: {
textTransform: 'none',
fontSize: 15,
fontWeight: 700
},
outlined: {
padding: '0 1em'
},
outlinedPrimary: {
borderColor: 'rgb(29, 161, 242)',
color: 'rgb(29, 161, 242)',
'&:hover': {
borderColor: 'rgb(29, 161, 242)',
color: 'rgb(29, 161, 242)',
backgroundColor: 'rgb(29, 161, 242, 0.1)'
}
},
contained: {
minHeight: 30,
boxShadow: shadows[0],
'&:hover': {
boxShadow: shadows[0]
},
'&:active': {
boxShadow: shadows[0]
}
},
containedPrimary: {
backgroundColor: 'rgb(29, 161, 242)',
color: palette.common.white,
'&:hover': {
backgroundColor: 'rgb(29, 145, 218)',
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'rgb(29, 145, 218)'
}
}
},
sizeLarge: {
padding: '0 1em',
minHeight: 39
}
};
}); |
MartinGeisse/public | name.martingeisse.json/src/main/java/name/martingeisse/common/javascript/ownjson/parserbase/JsonLexerInput.java | /**
* Copyright (c) 2010 <NAME>
*
* This file is distributed under the terms of the MIT license.
*/
package name.martingeisse.common.javascript.ownjson.parserbase;
/**
* Helper class for the {@link JsonLexer}.
*
* This class treats both CR and NL as newline characters
* independently.
*
* TODO disallow literal ASCII control characters inside string literals
*/
final class JsonLexerInput {
/**
* the input
*/
private final CharSequence input;
/**
* the inputLength
*/
private final int inputLength;
/**
* the inputPosition
*/
private int inputPosition;
/**
* the line
*/
private int line;
/**
* the column
*/
private int column;
/**
* the segment
*/
private StringBuilder segment;
/**
* the floatingPoint
*/
private boolean floatingPoint;
/**
* Constructor.
* @param input the input to split into tokens
*/
public JsonLexerInput(CharSequence input) {
this.input = input;
this.inputLength = input.length();
this.inputPosition = 0;
this.line = 0;
this.column = 0;
this.segment = new StringBuilder();
}
/**
* Getter method for the line.
* @return the line
*/
public int getLine() {
return line;
}
/**
* Getter method for the column.
* @return the column
*/
public int getColumn() {
return column;
}
/**
* Reads the current character from the input
* @return the current character, or -1 for EOF
*/
public int getCurrentCharacter() {
return (inputPosition < inputLength ? input.charAt(inputPosition) : -1);
}
/**
* Getter method for the segment.
* @return the segment
*/
public StringBuilder getSegment() {
return segment;
}
/**
* Getter method for the floatingPoint.
* @return the floatingPoint
*/
public boolean isFloatingPoint() {
return floatingPoint;
}
/**
* Steps to the next input character. Has no effect if at EOF.
*/
public void step() {
if (inputPosition < inputLength) {
stepInternal(input.charAt(inputPosition));
}
}
/**
* Skips all current whitespace characters in the input.
*/
public void skipSpaces() {
while (inputPosition < inputLength) {
char c = input.charAt(inputPosition);
if (c > 32) {
break;
} else {
stepInternal(c);
}
}
}
/**
*
*/
private void stepInternal(char c) {
if (c == '\n' || c == '\r') {
line++;
column = 0;
} else {
column++;
}
inputPosition++;
}
/**
*
*/
private void stepInternalNoNewline() {
column++;
inputPosition++;
}
/**
*
*/
private void stepInternalNoNewline(int steps) {
column += steps;
inputPosition += steps;
}
/**
* Reads a segment that represents a number and stores it as the current
* segment. This method also sets the 'floatingPoint' flag to indicate
* whether a decimal point or exponent sign was found.
*/
public void readNumber() {
segment.setLength(0);
floatingPoint = false;
while (inputPosition < inputLength) {
char c = input.charAt(inputPosition);
if (c == '.' || c == 'e') {
floatingPoint = true;
} else if (c < '0' || c > '9') {
break;
}
stepInternalNoNewline();
segment.append(c);
}
}
/**
* Reads a segment that represents a keyword and stores it as the current
* segment.
*/
public void readKeyword() {
segment.setLength(0);
while (inputPosition < inputLength) {
char c = input.charAt(inputPosition);
if (c < 'a' || c > 'z') {
break;
}
stepInternalNoNewline();
segment.append(c);
}
}
/**
* Reads a segment that represents a string literal and stores it as the current
* segment.
*/
public void readString() {
int stringStartLine = line, stringStartColumn = column;
stepInternalNoNewline();
segment.setLength(0);
while (inputPosition < inputLength) {
char c = input.charAt(inputPosition);
if (c == '"') {
stepInternalNoNewline();
return;
} else if (c == '\\') {
stepInternalNoNewline();
if (inputPosition == inputLength) {
throw new JsonSyntaxException(line, column - 1, line, column, "backslash right before EOF");
}
c = input.charAt(inputPosition);
if (!isEscapableCharacter(c)) {
throw new JsonSyntaxException(line, column - 1, line, column + 1, "invalid escape sequence: \\" + c);
}
switch (c) {
// literal escapes
case '"':
case '\\':
case '/':
segment.append(c);
stepInternalNoNewline();
break;
// ASCII backspace
case 'b':
segment.append('\b');
stepInternalNoNewline();
break;
// ASCII form feed
case 'f':
segment.append('\f');
stepInternalNoNewline();
break;
// ASCII form feed
case 'n':
segment.append('\n');
stepInternalNoNewline();
break;
// ASCII form feed
case 'r':
segment.append('\r');
stepInternalNoNewline();
break;
// ASCII form feed
case 't':
segment.append('\t');
stepInternalNoNewline();
break;
// Unicode escapes
case 'u':
stepInternalNoNewline();
if (inputLength - inputPosition < 4) {
throw new JsonSyntaxException(line, column - 2, line, column, "partial unicode escape before EOF");
}
int unicodeValue;
try {
unicodeValue = Integer.parseInt(input.subSequence(inputPosition, inputPosition + 4).toString(), 16);
} catch (NumberFormatException e) {
throw new JsonSyntaxException(line, column - 2, line, column + 4, "malformed unicode escape");
}
segment.append((char)unicodeValue);
stepInternalNoNewline(4);
break;
}
} else if (c < 32) {
if (c == '\n' || c == '\r') {
break;
} else {
throw new JsonSyntaxException(line, column, line, column + 1, "control characters not allowed in strings");
}
} else {
segment.append(c);
stepInternal(c);
}
}
throw new JsonSyntaxException(stringStartLine, stringStartColumn, line, column, "unterminated string");
}
/**
* Checks whether the specified character may appear after a
* backslash inside a string literal.
*
* @param c the character
* @return true if escapable, false if not
*/
static boolean isEscapableCharacter(char c) {
if (c < 'a') {
return (c == '"' || c == '\\' || c == '/');
} else if (c < 'o') {
return (c == 'b' || c == 'f' || c == 'n');
} else {
return (c == 'r' || c == 't' || c == 'u');
}
}
}
|
ScalablyTyped/SlinkyTyped | e/evernote/src/main/scala/typingsSlinky/evernote/mod/NoteStore/NoteList.scala | package typingsSlinky.evernote.mod.NoteStore
import typingsSlinky.evernote.anon.Notes
import typingsSlinky.evernote.mod.Types.Note
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@JSImport("evernote", "NoteStore.NoteList")
@js.native
class NoteList () extends StObject {
def this(args: Notes) = this()
var notes: js.UndefOr[js.Array[Note]] = js.native
var searchedWords: js.UndefOr[js.Array[String]] = js.native
var startIndex: js.UndefOr[Double] = js.native
var stoppedWords: js.UndefOr[js.Array[String]] = js.native
var totalNotes: js.UndefOr[Double] = js.native
var updateCount: js.UndefOr[Double] = js.native
}
|
LoliGothick/mitama-dimensional | tests/format-io-tests/molality-tests/molality-tests.cpp | <filename>tests/format-io-tests/molality-tests/molality-tests.cpp
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <mitama/dimensional/systems/si/derived_units/molality.hpp>
#include <mitama/dimensional/systems/si/quantity.hpp>
#include "../format_io_common.hpp"
TEST_CASE("molality format test", "[quantity][abbreviation]") {
REQUIRE(fmt(1 | systems::si::molality_t{}) == "1 [mol/kg]");
}
TEST_CASE("molality quantifier format test", "[quantity][abbreviation]") {
REQUIRE(fmt(1 | systems::si::molality) == "1 [mol/kg]");
}
TEST_CASE("molality type test", "[quantity][abbreviation]") {
REQUIRE(mitama::is_same_dimensional_v<std::decay_t<decltype(1|systems::si::molality)>, mitama::systems::si::quantity_t<std::decay_t<decltype(kilogram<-1>*mol<>)>>>);
}
|
ashwink6361/admin-hirundo | src/app/pages/settings/settingsService.js | /**
* @author <EMAIL>
* created on 25.01.2018
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.settings').service('SettingsService', SettingsService);
function SettingsService($q, $http) {
var _variantDetails = {};
return {
getSettings: function() {
var def = $q.defer();
var url = '/api/settings';
doGet($q, $http, url).then(function(data) {
def.resolve(data);
}).catch(function(error) {
def.reject(error);
});
return def.promise;
},
saveSettings: function(opts) {
var def = $q.defer();
var url = '/api/settings';
doPut($q, $http, url, opts).then(function(data) {
def.resolve(data);
}).catch(function(error) {
def.reject(error);
});
return def.promise;
},
getDevices: function() {
var def = $q.defer();
var url = '/api/bluetooth/scan';
doGet($q, $http, url).then(function(data) {
def.resolve(data);
}).catch(function(error) {
def.reject(error);
});
return def.promise;
},
connectDevice: function(opts) {
var def = $q.defer();
var url = '/api/bluetooth/connection';
doPost($q, $http, url, opts).then(function(data) {
def.resolve(data);
}).catch(function(error) {
def.reject(error);
});
return def.promise;
}
};
}
})();
|
augustinebest/app | dashboard/src/actions/schedule.js | import { postApi, getApi, deleteApi, putApi } from '../api';
import * as types from '../constants/schedule';
import errors from '../errors';
// Get a payload of Schedules
export function resetSchedule() {
return {
type: types.SCHEDULE_FETCH_RESET,
};
}
export function scheduleRequest(promise) {
return {
type: types.SCHEDULE_FETCH_REQUEST,
payload: promise,
};
}
export function scheduleError(error) {
return {
type: types.SCHEDULE_FETCH_FAILED,
payload: error,
};
}
export function scheduleSuccess(schedule) {
return {
type: types.SCHEDULE_FETCH_SUCCESS,
payload: schedule,
};
}
// Calls the API to fetch Schedules.
export function fetchSchedules(projectId, skip, limit) {
return function(dispatch) {
let promise = null;
promise = getApi(
`schedule/${projectId}?skip=${skip || 0}&limit=${limit || 10}`
);
promise.then(
function(schedule) {
dispatch(scheduleSuccess(schedule.data));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
if (error && error.message) {
error = error.message;
} else {
error = 'Network Error';
}
dispatch(scheduleError(errors(error)));
}
);
return promise;
};
}
// Get a payload of SubProject Schedules
export function resetSubProjectSchedule() {
return {
type: types.SUBPROJECT_SCHEDULE_FETCH_RESET,
};
}
export function subProjectScheduleRequest(promise) {
return {
type: types.SUBPROJECT_SCHEDULE_FETCH_REQUEST,
payload: promise,
};
}
export function subProjectScheduleError(error) {
return {
type: types.SUBPROJECT_SCHEDULE_FETCH_FAILED,
payload: error,
};
}
export function subProjectScheduleSuccess(schedule) {
return {
type: types.SUBPROJECT_SCHEDULE_FETCH_SUCCESS,
payload: schedule,
};
}
// Calls the API to fetch Schedules.
export function fetchSubProjectSchedules(projectId) {
return function(dispatch) {
let promise = null;
promise = getApi(`schedule/${projectId}/schedules`);
dispatch(subProjectScheduleRequest());
promise.then(
function(schedule) {
dispatch(subProjectScheduleSuccess(schedule.data));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
if (error && error.message) {
error = error.message;
} else {
error = 'Network Error';
}
dispatch(subProjectScheduleError(errors(error)));
}
);
return promise;
};
}
export function resetProjectSchedule() {
return {
type: types.PROJECT_SCHEDULE_FETCH_RESET,
};
}
export function projectScheduleRequest(promise) {
return {
type: types.PROJECT_SCHEDULE_FETCH_REQUEST,
payload: promise,
};
}
export function projectScheduleError(error) {
return {
type: types.PROJECT_SCHEDULE_FETCH_FAILED,
payload: error,
};
}
export function projectScheduleSuccess(schedule) {
return {
type: types.PROJECT_SCHEDULE_FETCH_SUCCESS,
payload: schedule,
};
}
// Gets list of schedules in a project.
export function fetchProjectSchedule(projectId, skip, limit) {
return function(dispatch) {
let promise = null;
promise = getApi(
`schedule/${projectId}/schedule?skip=${skip}&limit=${limit}`
);
promise.then(
function(schedule) {
const data = schedule.data;
data.projectId = projectId;
dispatch(projectScheduleSuccess(data));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
if (error && error.message) {
error = error.message;
} else {
error = 'Network Error';
}
dispatch(projectScheduleError(errors(error)));
}
);
return promise;
};
}
// Create a new schedule
export function createScheduleRequest() {
return {
type: types.CREATE_SCHEDULE_REQUEST,
};
}
export function createScheduleError(error) {
return {
type: types.CREATE_SCHEDULE_FAILED,
payload: error,
};
}
export function createScheduleSuccess(schedule) {
return {
type: types.CREATE_SCHEDULE_SUCCESS,
payload: schedule,
};
}
// Calls the API to create the schedule.
export function createSchedule(projectId, values) {
return function(dispatch) {
const promise = postApi(`schedule/${projectId}`, values);
dispatch(createScheduleRequest());
promise.then(
function(schedule) {
dispatch(createScheduleSuccess(schedule.data));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
if (error && error.message) {
error = error.message;
} else {
error = 'Network Error';
}
dispatch(createScheduleError(errors(error)));
}
);
return promise;
};
}
// Rename a Schedule
export function renameScheduleReset() {
return {
type: types.RENAME_SCHEDULE_RESET,
};
}
export function renameScheduleRequest() {
return {
type: types.RENAME_SCHEDULE_REQUEST,
payload: true,
};
}
export function renameScheduleSuccess(schedule) {
return {
type: types.RENAME_SCHEDULE_SUCCESS,
payload: schedule.data,
};
}
export function renameScheduleError(error) {
return {
type: types.RENAME_SCHEDULE_FAILED,
payload: error,
};
}
export function renameSchedule(projectId, scheduleId, scheduleName) {
return function(dispatch) {
const promise = putApi(`schedule/${projectId}/${scheduleId}`, {
name: scheduleName,
});
dispatch(renameScheduleRequest());
promise
.then(
function(schedule) {
dispatch(renameScheduleSuccess(schedule));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
if (error && error.message) {
error = error.message;
} else {
error = 'Network Error';
}
dispatch(renameScheduleError(errors(error)));
}
)
.then(function() {
dispatch(renameScheduleReset());
});
return promise;
};
}
// Delete a Schedule
export function deleteScheduleReset() {
return {
type: types.DELETE_SCHEDULE_RESET,
};
}
export function deleteScheduleRequest() {
return {
type: types.DELETE_SCHEDULE_REQUEST,
payload: true,
};
}
export function deleteScheduleSuccess(schedule) {
return {
type: types.DELETE_SCHEDULE_SUCCESS,
payload: schedule.data,
};
}
export function deleteProjectSchedules(projectId) {
return {
type: types.DELETE_PROJECT_SCHEDULES,
payload: projectId,
};
}
export function deleteScheduleError(error) {
return {
type: types.DELETE_SCHEDULE_FAILED,
payload: error,
};
}
export function deleteSchedule(projectId, scheduleId) {
return function(dispatch) {
const promise = deleteApi(`schedule/${projectId}/${scheduleId}`);
dispatch(deleteScheduleRequest());
promise
.then(
function(schedule) {
const data = Object.assign(
{},
{ scheduleId },
schedule.data
);
dispatch(fetchSchedules(projectId));
return dispatch(deleteScheduleSuccess({ data }));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
if (error && error.message) {
error = error.message;
} else {
error = 'Network Error';
}
dispatch(deleteScheduleError(errors(error)));
}
)
.then(function() {
dispatch(deleteScheduleReset());
});
return promise;
};
}
// Add Monitors to Schedule
export function addMonitorReset() {
return {
type: types.ADD_MONITOR_RESET,
};
}
export function addMonitorRequest() {
return {
type: types.ADD_MONITOR_REQUEST,
payload: true,
};
}
export function addMonitorSuccess(schedule) {
return {
type: types.ADD_MONITOR_SUCCESS,
payload: schedule.data,
};
}
export function addMonitorError(error) {
return {
type: types.ADD_MONITOR_FAILED,
payload: error,
};
}
export function addMonitors(projectId, scheduleId, data) {
return function(dispatch) {
const promise = putApi(`schedule/${projectId}/${scheduleId}`, data);
dispatch(addMonitorRequest());
promise
.then(
function(schedule) {
dispatch(addMonitorSuccess(schedule));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
if (error && error.message) {
error = error.message;
} else {
error = 'Network Error';
}
dispatch(addMonitorError(errors(error)));
}
)
.then(function() {
dispatch(addMonitorReset());
});
return promise;
};
}
// Add Users to Schedule
export function addUserReset() {
return {
type: types.ADD_USER_RESET,
};
}
export function addUserRequest() {
return {
type: types.ADD_USER_REQUEST,
payload: true,
};
}
export function addUserSuccess(schedule) {
return {
type: types.ADD_USER_SUCCESS,
payload: schedule.data,
};
}
export function addUserError(error) {
return {
type: types.ADD_USER_FAILED,
payload: error,
};
}
export function addUsers(projectId, scheduleId, data) {
return function(dispatch) {
const promise = postApi(
`schedule/${projectId}/${scheduleId}/addUsers`,
data
);
dispatch(addUserRequest());
promise
.then(
function(schedule) {
dispatch(addUserSuccess(schedule));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
if (error && error.message) {
error = error.message;
} else {
error = 'Network Error';
}
dispatch(addUserError(errors(error)));
}
)
.then(function() {
dispatch(addUserReset());
});
return promise;
};
}
// onCallAlertBox
export function escalationReset() {
return {
type: types.ESCALATION_RESET,
};
}
export function escalationRequest() {
return {
type: types.ESCALATION_REQUEST,
payload: true,
};
}
export function escalationSuccess(escalation) {
return {
type: types.ESCALATION_SUCCESS,
payload: escalation,
};
}
export function escalationError(error) {
return {
type: types.ESCALATION_FAILED,
payload: error,
};
}
export function addEscalation(projectId, scheduleId, data) {
data = data.OnCallAlertBox;
return function(dispatch) {
const promise = postApi(
`schedule/${projectId}/${scheduleId}/addescalation`,
data
);
dispatch(escalationRequest());
promise.then(
function(escalation) {
dispatch(escalationSuccess(escalation));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
if (error && error.message) {
error = error.message;
} else {
error = 'Network Error';
}
dispatch(escalationError(errors(error)));
}
);
return promise;
};
}
export function getEscalation(projectId, scheduleId) {
return function(dispatch) {
const promise = getApi(
`schedule/${projectId}/${scheduleId}/getescalation`
);
dispatch(escalationRequest());
promise.then(
function(escalation) {
dispatch(escalationSuccess(escalation.data));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
if (error && error.message) {
error = error.message;
} else {
error = 'Network Error';
}
dispatch(escalationError(errors(error)));
}
);
return promise;
};
}
// Implements pagination for Team Members table
export function paginateNext() {
return {
type: types.PAGINATE_NEXT,
};
}
export function paginatePrev() {
return {
type: types.PAGINATE_PREV,
};
}
export function paginateReset() {
return {
type: types.PAGINATE_RESET,
};
}
export function paginate(type) {
return function(dispatch) {
type === 'next' && dispatch(paginateNext());
type === 'prev' && dispatch(paginatePrev());
type === 'reset' && dispatch(paginateReset());
};
}
export function userScheduleReset() {
return {
type: types.USER_SCHEDULE_RESET,
};
}
export function userScheduleRequest() {
return {
type: types.USER_SCHEDULE_REQUEST,
};
}
export function userScheduleSuccess(userSchedule) {
return {
type: types.USER_SCHEDULE_SUCCESS,
payload: userSchedule,
};
}
export function userScheduleError(error) {
return {
type: types.USER_SCHEDULE_FAILED,
payload: error,
};
}
export function fetchUserSchedule(projectId, userId) {
return function(dispatch) {
const promise = getApi(
`schedule/${projectId}/${userId}/getescalations`
);
dispatch(userScheduleRequest());
promise.then(
function(schedule) {
dispatch(userScheduleSuccess(schedule.data));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
if (error && error.message) {
error = error.message;
} else {
error = 'Network Error';
}
dispatch(userScheduleError(errors(error)));
}
);
return promise;
};
}
|
nickchen-mitac/fork | src/ava/ext/service.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pkg_resources
logger = logging.getLogger(__name__)
class Extension(object):
def __init__(self, name, entry_point):
self.name = name
self.entry_point = entry_point
self.cls = None
self.obj = None
def __repr__(self):
return 'Extension(%s)' % self.name
class ExtensionManager(object):
def __init__(self, namespace="ava.extension"):
self.namespace = namespace
self.extensions = []
def load_extensions(self, invoke_on_load=True):
for it in pkg_resources.working_set.iter_entry_points(self.namespace, name=None):
logger.debug("Loading extension: %s at module: %s", it.name, it.module_name)
logger.debug("")
ext = Extension(it.name, it)
ext.cls = it.load()
if invoke_on_load:
ext.obj = ext.cls()
self.extensions.append(ext)
# sort extensions by names
self.extensions.sort(key=lambda e: e.name)
logger.debug("Loaded extensions: %r", self.extensions)
def start_extensions(self, context=None):
for ext in self.extensions:
startfun = getattr(ext.obj, "start", None)
if startfun is not None and callable(startfun):
startfun(context)
def stop_extensions(self, context=None):
for ext in reversed(self.extensions):
stopfun = getattr(ext.obj, "stop", None)
if stopfun is not None and callable(stopfun):
try:
stopfun(context)
except Exception:
pass
#IGNORED.
__all__ = ['Extension', 'ExtensionManager']
|
marcaoas/hoppy-android | data/src/main/java/com/marcaoas/hoppy/data/models/ApiUser.java | package com.marcaoas.hoppy.data.models;
import com.google.firebase.database.Exclude;
import com.google.firebase.database.IgnoreExtraProperties;
import java.util.HashMap;
import java.util.Map;
/**
* Created by marco on 18/04/17.
*/
@IgnoreExtraProperties
public class ApiUser extends ModelBase {
public String name;
public String email;
public String profilePictureUrl;
@Exclude
@Override
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("id", id);
result.put("name", name);
result.put("email", email);
result.put("profilePictureUrl", profilePictureUrl);
return result;
}
}
|
bluebosh/rep | auctioncellrep/helpers.go | <filename>auctioncellrep/helpers.go
package auctioncellrep
import uuid "github.com/nu7hatch/gouuid"
func GenerateGuid() (string, error) {
guid, err := uuid.NewV4()
if err != nil {
return "", err
}
guidString := guid.String()
if len(guidString) > 28 {
guidString = guidString[:28]
}
return guidString, nil
}
|
masud-technope/ACER-Replication-Package-ASE2017 | corpus/class/eclipse.jdt.ui/5993.java | /*******************************************************************************
* Copyright (c) 2008, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit;
import java.io.File;
import org.eclipse.osgi.util.TextProcessor;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.resources.IResource;
/**
* A label provider for basic elements like paths. The label provider will make sure that the labels are correctly
* shown in RTL environments.
*
* @since 3.4
*/
public class BasicElementLabels {
private BasicElementLabels() {
}
/**
* Adds special marks so that that the given string is readable in a BIDI environment.
*
* @param string the string
* @param delimiters the additional delimiters
* @return the processed styled string
*/
private static String markLTR(String string, String delimiters) {
return TextProcessor.process(string, delimiters);
}
/**
* Returns the label of a path.
*
* @param path the path
* @param isOSPath if <code>true</code>, the path represents an OS path, if <code>false</code> it is a workspace path.
* @return the label of the path to be used in the UI.
*/
public static String getPathLabel(IPath path, boolean isOSPath) {
String label;
if (isOSPath) {
label = path.toOSString();
} else {
label = path.makeRelative().toString();
}
//$NON-NLS-1$
return markLTR(label, "/\\:.");
}
/**
* Returns the label of the path of a file.
*
* @param file the file
* @return the label of the file path to be used in the UI.
*/
public static String getPathLabel(File file) {
//$NON-NLS-1$
return markLTR(file.getAbsolutePath(), "/\\:.");
}
/**
* Returns the label for a file pattern like '*.java'
*
* @param name the pattern
* @return the label of the pattern.
*/
public static String getFilePattern(String name) {
//$NON-NLS-1$
return markLTR(name, "*.?/\\:.");
}
/**
* Returns the label for a URL, URI or URL part. Example is 'http://www.x.xom/s.html#1'
*
* @param name the URL string
* @return the label of the URL.
*/
public static String getURLPart(String name) {
//$NON-NLS-1$
return markLTR(name, ":@?-#/\\:.");
}
/**
* Returns a label for a resource name.
*
* @param resource the resource
* @return the label of the resource name.
*/
public static String getResourceName(IResource resource) {
//$NON-NLS-1$
return markLTR(resource.getName(), ":.");
}
/**
* Returns a label for a resource name.
*
* @param resourceName the resource name
* @return the label of the resource name.
*/
public static String getResourceName(String resourceName) {
//$NON-NLS-1$
return markLTR(resourceName, ":.");
}
/**
* Returns a label for a version name. Example is '1.4.1'
*
* @param name the version string
* @return the version label
*/
public static String getVersionName(String name) {
//$NON-NLS-1$
return markLTR(name, ":.");
}
/**
* Returns a label for Java element name. Example is 'new Test<? extends List>() { ...}'.
* This method should only be used for simple element names. Use
* JavaElementLabels to create a label from a Java element.
*
* @param name the Java element name.
* @return the label for the Java element
*/
public static String getJavaElementName(String name) {
//$NON-NLS-1$
return markLTR(name, "<>()?,{}.:");
}
}
|
eido5/cubrid | src/heaplayers/heaps/buildingblock/freelistheap.h | /* -*- C++ -*- */
/*
Heap Layers: An Extensible Memory Allocation Infrastructure
Copyright (C) 2000-2020 by <NAME>
http://www.emeryberger.com
<EMAIL>
Heap Layers is distributed under the terms of the Apache 2.0 license.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
*/
#ifndef HL_FREELISTHEAP_H
#define HL_FREELISTHEAP_H
/**
* @class FreelistHeap
* @brief Manage freed memory on a linked list.
* @warning This is for one "size class" only.
*
* Note that the linked list is threaded through the freed objects,
* meaning that such objects must be at least the size of a pointer.
*/
#include <assert.h>
#include "utility/freesllist.h"
#ifndef NULL
#define NULL 0
#endif
namespace HL {
template <class SuperHeap>
class FreelistHeap : public SuperHeap {
public:
inline void * malloc (size_t sz) {
// Check the free list first.
void * ptr = _freelist.get();
// If it's empty, get more memory;
// otherwise, advance the free list pointer.
if (ptr == 0) {
ptr = SuperHeap::malloc (sz);
}
return ptr;
}
inline void free (void * ptr) {
if (ptr == 0) {
return;
}
_freelist.insert (ptr);
}
inline void clear (void) {
void * ptr;
while ((ptr = _freelist.get())) {
SuperHeap::free (ptr);
}
}
private:
FreeSLList _freelist;
};
}
#endif
|
BjornB2/gb-printer-web | src/javascript/app/store/reducers/lightboxImageReducer.js | const lightboxImageReducer = (value = null, action) => {
switch (action.type) {
case 'SET_LIGHTBOX_IMAGE_INDEX':
return action.payload;
// on some filters reset this to null?
default:
return value;
}
};
export default lightboxImageReducer;
|
fancylou/o2oa | x_okr_assemble_control/src/main/java/com/x/okr/assemble/control/service/OkrWorkProcessIdentityService.java | package com.x.okr.assemble.control.service;
import java.util.List;
public class OkrWorkProcessIdentityService {
private OkrWorkPersonService okrWorkPersonService = new OkrWorkPersonService();
/**
* 判断一个工作是否是用户阅知的工作, 用户是否在工作的干系人身份中拥有阅知者身份
* @param workId
* @return
* @throws Exception
*/
public Boolean isMyReadWork( String userIdentity, String workId ) throws Exception {
if( userIdentity == null || userIdentity.isEmpty() ){
throw new Exception("user identity is null, can not query work person.");
}
if( workId == null || workId.isEmpty() ){
throw new Exception("workId is null, can not query work person.");
}
List<String> ids = okrWorkPersonService.listByWorkAndIdentity( null, workId, userIdentity, "阅知者", null );
if( ids != null && !ids.isEmpty() ){
return true;
}
return false;
}
public boolean isMyCooperateWork( String userIdentity, String workId ) throws Exception {
if( userIdentity == null || userIdentity.isEmpty() ){
throw new Exception("user identity is null, can not query work person.");
}
if( workId == null || workId.isEmpty() ){
throw new Exception("workId is null, can not query work person.");
}
List<String> ids = okrWorkPersonService.listByWorkAndIdentity( null, workId, userIdentity, "协助者", null );
if( ids != null && !ids.isEmpty() ){
return true;
}
return false;
}
public boolean isMyResponsibilityWork( String userIdentity, String workId ) throws Exception {
if( userIdentity == null || userIdentity.isEmpty() ){
throw new Exception("user identity is null, can not query work person.");
}
if( workId == null || workId.isEmpty() ){
throw new Exception("workId is null, can not query work person.");
}
List<String> ids = okrWorkPersonService.listByWorkAndIdentity( null, workId, userIdentity, "责任者", null );
if( ids != null && !ids.isEmpty() ){
return true;
}
return false;
}
public boolean isMyAuthorizeWork(String userIdentity, String workId ) throws Exception {
if( userIdentity == null || userIdentity.isEmpty() ){
throw new Exception("user identity is null, can not query work person.");
}
if( workId == null || workId.isEmpty() ){
throw new Exception("workId is null, can not query work person.");
}
List<String> ids = okrWorkPersonService.listByWorkAndIdentity( null, workId, userIdentity, "授权者", null );
if( ids != null && !ids.isEmpty() ){
return true;
}
return false;
}
public boolean isMyDeployWork(String userIdentity, String workId ) throws Exception {
if( userIdentity == null || userIdentity.isEmpty() ){
throw new Exception("user identity is null, can not query work person.");
}
if( workId == null || workId.isEmpty() ){
throw new Exception("workId is null, can not query work person.");
}
List<String> ids = okrWorkPersonService.listByWorkAndIdentity( null, workId, userIdentity, "部署者", null );
if( ids != null && !ids.isEmpty() ){
return true;
}
return false;
}
/**
* 判断一个工作是否是用户阅知的工作, 用户是否在工作的干系人身份中拥有阅知者身份
* @param workId
* @return
* @throws Exception
*/
public Boolean isMyReadCenter( String userIdentity, String centerId ) throws Exception {
if( userIdentity == null || userIdentity.isEmpty() ){
throw new Exception("user identity is null, can not query work person.");
}
if( centerId == null || centerId.isEmpty() ){
throw new Exception("centerId is null, can not query work person.");
}
List<String> ids = okrWorkPersonService.listByWorkAndIdentity( centerId, null, userIdentity, "阅知者", null );
if( ids != null && !ids.isEmpty() ){
return true;
}
return false;
}
public boolean isMyDeployCenter(String userIdentity, String centerId ) throws Exception {
if( userIdentity == null || userIdentity.isEmpty() ){
throw new Exception("user identity is null, can not query work person.");
}
if( centerId == null || centerId.isEmpty() ){
throw new Exception("centerId is null, can not query work person.");
}
List<String> ids = okrWorkPersonService.listByWorkAndIdentity( centerId, null, userIdentity, "部署者", null );
if( ids != null && !ids.isEmpty() ){
return true;
}
return false;
}
} |
dbastin/donkey | src/java/test/org/burroloco/butcher/util/poll/DefaultPoller.java | package org.burroloco.butcher.util.poll;
import org.burroloco.util.snooze.Snoozer;
import static org.burroloco.butcher.glue.constants.ButcherTestConstants.ONE_SECOND;
public class DefaultPoller implements Poller {
public static final long TIMEOUT_SECS = 180;
Snoozer snoozer;
public boolean call(PollingBlock block) {
return call(block, TIMEOUT_SECS);
}
public boolean call(PollingBlock block, long timeoutSecs) {
long endTime = currentTime() + timeoutSecs * ONE_SECOND;
while (currentTime() < endTime) {
if (block.call()) return true;
snoozer.snooze(100);
}
return false;
}
private long currentTime() {
return System.currentTimeMillis();
}
} |
crimergio/linux_test | env/lib/python3.8/site-packages/opentracing/scope_managers/contextvars.py | # Copyright (c) The OpenTracing Authors.
#
# 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 __future__ import absolute_import
from contextlib import contextmanager
from contextvars import ContextVar
from opentracing import Scope, ScopeManager
_SCOPE = ContextVar('scope')
class ContextVarsScopeManager(ScopeManager):
"""
:class:`~opentracing.ScopeManager` implementation for **asyncio**
that stores the :class:`~opentracing.Scope` using ContextVar.
The scope manager provides automatic :class:`~opentracing.Span` propagation
from parent coroutines, tasks and scheduled in event loop callbacks to
their children.
.. code-block:: python
async def child_coroutine():
# No need manual activation of parent span in child coroutine.
with tracer.start_active_span('child') as scope:
...
async def parent_coroutine():
with tracer.start_active_span('parent') as scope:
...
await child_coroutine()
...
"""
def activate(self, span, finish_on_close):
"""
Make a :class:`~opentracing.Span` instance active.
:param span: the :class:`~opentracing.Span` that should become active.
:param finish_on_close: whether *span* should automatically be
finished when :meth:`Scope.close()` is called.
:return: a :class:`~opentracing.Scope` instance to control the end
of the active period for the :class:`~opentracing.Span`.
It is a programming error to neglect to call :meth:`Scope.close()`
on the returned instance.
"""
return self._set_scope(span, finish_on_close)
@property
def active(self):
"""
Return the currently active :class:`~opentracing.Scope` which
can be used to access the currently active :attr:`Scope.span`.
:return: the :class:`~opentracing.Scope` that is active,
or ``None`` if not available.
"""
return self._get_scope()
def _set_scope(self, span, finish_on_close):
return _ContextVarsScope(self, span, finish_on_close)
def _get_scope(self):
return _SCOPE.get(None)
class _ContextVarsScope(Scope):
def __init__(self, manager, span, finish_on_close):
super(_ContextVarsScope, self).__init__(manager, span)
self._finish_on_close = finish_on_close
self._token = _SCOPE.set(self)
def close(self):
if self.manager.active is not self:
return
_SCOPE.reset(self._token)
if self._finish_on_close:
self.span.finish()
@contextmanager
def no_parent_scope():
"""
Context manager that resets current Scope. Intended to break span
propagation to children coroutines, tasks or scheduled callbacks.
.. code-block:: python
from opentracing.scope_managers.contextvars import no_parent_scope
def periodic()
# `periodic` span will be children of root only at the first time.
with self.tracer.start_active_span('periodic'):
# Now we break span propagation.
with no_parent_scope():
self.loop.call_soon(periodic)
with self.tracer.start_active_span('root'):
self.loop.call_soon(periodic)
"""
token = _SCOPE.set(None)
try:
yield
finally:
_SCOPE.reset(token)
|
Marsevil/LovecraftLetter_IA | src/view/View.py | <filename>src/view/View.py<gh_stars>0
import os
from model.card.Sanity import Sanity
from model.Player import Player
from model.ai.Agent import Agent
class View():
"""
Ask for a number and return the player at this number from the list of players
@params nbPlayer, number of players to choose
@params players, list of players
@return selected player object
"""
def chooseTargetPlayer(self,nbPlayer, players):
self._displayNewAction()
playersAvailable = []
for i in range(len(players)):
playersAvailable.append(i+1)
choosenPlayersList =[]
while len(choosenPlayersList) < nbPlayer:
print("Please choose a target (number) in this list : " + str(playersAvailable))
nbInput = None
while True:
try:
nbInput = int(input())
if nbInput in playersAvailable:
break
else:
print("Wrong number please retry")
except Exception as e:
print(e)
choosenPlayersList.append(players.pop(nbInput-1-len(choosenPlayersList)))
playersAvailable.remove(nbInput)
return choosenPlayersList
"""
Ask for which card to play
@params playerHand, playable cards
@çeturn card object
"""
def cardToPlay(self,playerHand):
self._displayNewAction()
cardStr = "You can play " + playerHand[0].name + "(1) or " + playerHand[1].name + "(2) (You can also view cards info with 3)"
print(cardStr)
cardNb = self.chooseNumber(1,3)
#Display cards info
if cardNb == 3:
self.showCards(playerHand)
cardNb = self.chooseNumber(1,2)
# if cardNb:
return cardNb-1
# return None
"""
Wrong action display function
"""
def cardCantBePlayed(self):
print("This action cannot be done, please choose another")
"""
Choose between Sane and Insane
@return SANE or INSANE enum value (None in case of error)
"""
def askInsanity(self):
self._displayNewAction()
infoStr = "Your card can be played as Sane (1) or Insane (2) "
print(infoStr)
choosenState = self.chooseNumber(1,2)
if (choosenState == 1):
return Sanity.SANE
else:
if (choosenState==2):
return Sanity.INSANE
else:
return None
"""
Re order a list of card
@params inGameCards, list of card who need to be reordered
@return list of card reordered
"""
def redistribute(self,inGameCards):
self._displayNewAction()
cardsStr = "Cards : "
for card in inGameCards:
cardsStr += card.name + ", "
cardsStr = cardsStr[:-2]
cardsStr += " need to be redistribute to each player "
print(cardsStr)
nbPlayers = len(inGameCards)
newCardsOrder = inGameCards.copy()
playerNbAvailable = []
for i in range(1,nbPlayers+1):
playerNbAvailable.append(i)
while len(inGameCards) > 0:
#retrieve last card from list
currentCard = inGameCards.pop()
print("Distribute '" + currentCard.name + "' to a player (number) in this list : " + str(playerNbAvailable))
nbInput = None
while True:
try:
nbInput = int(input())
if nbInput in playerNbAvailable:
break
else:
print("Wrong number please retry")
except Exception as e:
print(e)
newCardsOrder[nbInput-1] = currentCard
playerNbAvailable.remove(nbInput)
return newCardsOrder
"""
@params minNb, min value
@params maxNb, max value
@return number between min and max
"""
def chooseNumber(self,minNb,maxNb):
infoStr = "Choose a number between " + str(minNb) + " and " + str(maxNb) + " : "
nbInput = None
#do while
while True:
try:
nbInput = int(input(infoStr))
if (nbInput >= minNb and nbInput <= maxNb):
break
except Exception as e:
print(e)
return nbInput
"""
Display a list of cards
@params cards, list of cards
"""
def showCards(self,cards):
self._displayNewAction()
print("Cards : ")
for card in cards:
print("\t Name : " + card.name)
print("\t Value : " + str(card.value))
print("\t Effect : \n\t\t" + card.description)
print("")
input("continue (c) : ")
"""
Discard hand function
"""
def playerDiscard(self,player,nbCard):
returnList = []
returnList.append(self.cardToPlay(player.hand))
return returnList
# hand = player.hand
# handStr = ""
# for card in hand:
# handStr += str(card.name) + ", "
# handStr = handStr[:-2]
# discardStr = "You need to discard " + str(nbCard) + " cards from "+ handStr
"""
Display winner of round
"""
def displayRoundWinner(self,playerIndex,sanity):
self.cls()
sanityStr = "NEUTRAL"
if sanity == Sanity.INSANE:
sanityStr = "INSANE"
if sanity == Sanity.SANE:
sanityStr = "SANE"
print("Player " + str(playerIndex+1) + " win the round with a " + sanityStr + " sanity")
input("continue (c) : ")
"""
Display Turn and Round info
"""
def displayNewTurn(self,gameManager):
self.cls()
currentPlayer = gameManager.currentPlayer
roundNumber = gameManager.roundNumber
infoStr = "========================"
infoStr1 = "Round number "+ str(roundNumber + 1)
infoStr2 = ""
if isinstance(gameManager.getCurrentPlayer(),Agent):
infoStr2 = "AI "
else:
infoStr2 = "Player "
infoStr2 += str(currentPlayer + 1) + " is playing"
infoStr3 = str(gameManager.getCurrentPlayer().saneToken) + " sane token \t"+ str(gameManager.getCurrentPlayer().insaneToken) + " insane token"
print(infoStr)
print(infoStr1)
print(infoStr2)
print(infoStr3)
print(infoStr)
"""
Display new action
"""
def _displayNewAction(self):
print("----------------------------------------------------------")
def displayBeginSanityCheck(self, playerID, nbCard) :
print("Sanity check begin for player", str(playerID + 1), "with", nbCard, "cards.")
input("continue (c) : ")
def displayStepSanityCheck(self, card) :
print("Name : ", card.getName())
print("Sanity : ", Sanity.INSANE if card.hasInsane() else Sanity.SANE)
input("continue (c) : ")
def displayCardWillBePlayed(self, playerID, card) :
self.cls()
print("Player ", str(playerID + 1), " will play ", card.getName())
input("continue (c) : ")
"""
Clear screen function
"""
def cls(self):
os.system('cls' if os.name=='nt' else 'clear')
|
WA2301/uboot-2011.06 | arch/arm/include/asm/arch-pantheon/pantheon.h | /*
* (C) Copyright 2011
* Marvell Semiconductor <www.marvell.com>
* Written-by: <NAME> <<EMAIL>>
*
* See file CREDITS for list of people who contributed to this
* project.
*
* 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
*/
#ifndef _PANTHEON_H
#define _PANTHEON_H
#ifndef __ASSEMBLY__
#include <asm/types.h>
#include <asm/io.h>
#endif /* __ASSEMBLY__ */
#include <asm/arch/cpu.h>
/* Common APB clock register bit definitions */
#define APBC_APBCLK (1<<0) /* APB Bus Clock Enable */
#define APBC_FNCLK (1<<1) /* Functional Clock Enable */
#define APBC_RST (1<<2) /* Reset Generation */
/* Functional Clock Selection Mask */
#define APBC_FNCLKSEL(x) (((x) & 0xf) << 4)
/* Register Base Addresses */
#define PANTHEON_DRAM_BASE 0xB0000000
#define PANTHEON_TIMER_BASE 0xD4014000
#define PANTHEON_WD_TIMER_BASE 0xD4080000
#define PANTHEON_APBC_BASE 0xD4015000
#define PANTHEON_UART1_BASE 0xD4017000
#define PANTHEON_UART2_BASE 0xD4018000
#define PANTHEON_GPIO_BASE 0xD4019000
#define PANTHEON_MFPR_BASE 0xD401E000
#define PANTHEON_MPMU_BASE 0xD4050000
#define PANTHEON_CPU_BASE 0xD4282C00
#endif /* _PANTHEON_H */
|
grondo/mvapich2-cce | src/pm/util/env.c | <filename>src/pm/util/env.c
/* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
* (C) 2003 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*/
#include "pmutilconf.h"
#include <stdio.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#if defined( HAVE_PUTENV ) && defined( NEEDS_PUTENV_DECL )
extern int putenv(char *string);
#endif
#include "pmutil.h"
#include "process.h"
#include "env.h"
#include "cmnargs.h" /* for mpiexec_usage */
/*
*
*/
/*
* This routine may be called by MPIE_Args to handle any environment arguments
* Returns the number of arguments to skip (0 if argument is not recognized
* as an environment control)
*/
int MPIE_ArgsCheckForEnv( int argc, char *argv[], ProcessWorld *pWorld,
EnvInfo **appEnv )
{
int i, incr=0;
EnvInfo *env;
char *cmd;
if ( strncmp( argv[0], "-env", 4) == 0) {
if (!*appEnv) {
env = (EnvInfo *)MPIU_Malloc( sizeof(EnvInfo) );
env->includeAll = 1;
env->envPairs = 0;
env->envNames = 0;
*appEnv = env;
}
else
env = *appEnv;
cmd = argv[0] + 4;
}
else if (strncmp( argv[0], "-genv", 5 ) == 0) {
if (!pWorld->genv) {
env = (EnvInfo *)MPIU_Malloc( sizeof(EnvInfo) );
env->includeAll = 1;
env->envPairs = 0;
env->envNames = 0;
pWorld->genv = env;
}
env = pWorld->genv;
cmd = argv[0] + 5;
}
else
return 0;
/* genv and env commands have the same form, just affect different
env structures. We handle this by identifying which structure,
then checkout the remaining command */
if (!cmd[0]) {
/* A basic name value command */
EnvData *p;
if (!argv[1] || !argv[2]) {
mpiexec_usage( "Missing arguments to -env or -genv" );
}
p = (EnvData *)MPIU_Malloc( sizeof(EnvData) );
p->name = (const char *)MPIU_Strdup( argv[1] );
p->value = (const char *)MPIU_Strdup( argv[2] );
p->envvalue = 0;
p->nextData = env->envPairs;
env->envPairs = p;
incr = 3;
}
else if (strcmp( cmd, "none" ) == 0) {
env->includeAll = 0;
incr = 1;
}
else if (strcmp( cmd, "list" ) == 0) {
/* argv[1] has a list of names, separated by commas */
EnvData *p;
char *lPtr = argv[1], *name;
int namelen;
if (!argv[1]) {
mpiexec_usage( "Missing argument to -envlist or -genvlist" );
}
while (*lPtr) {
name = lPtr++;
while (*lPtr && *lPtr != ',') lPtr++;
namelen = lPtr - name;
p = (EnvData *)MPIU_Malloc( sizeof(EnvData) );
p->value = 0;
p->name = (const char *)MPIU_Malloc( namelen + 1 );
p->envvalue = 0;
for (i=0; i<namelen; i++) ((char *)p->name)[i] = name[i];
((char *)p->name)[namelen] = 0;
p->nextData = env->envNames;
env->envNames = p;
if (*lPtr == ',') lPtr++;
}
incr = 2;
}
else {
/* Unrecognized env argument. */
incr = 0;
}
return incr;
}
/*
Setup the environment of a process for a given process state.
This handles the options for the process world and app
Input Arguments:
pState - process state structure
envp - Base (pre-existing) environment. Note that this should
be the envp from main() (see below)
maxclient - size of client_envp array
Output Arguments:
client_envp -
Side Effects:
If envnone or genvnone was selected, the environment variables in envp
will be removed with unsetenv() or by direct manipulation of the envp
array (for systems that do not support unsetenv, envp must be the
array pass into main()).
Returns the number of items set in client_envp, or -1 on error.
*/
int MPIE_EnvSetup( ProcessState *pState, char *envp[],
char *client_envp[], int maxclient )
{
ProcessWorld *pWorld;
ProcessApp *app;
EnvInfo *env;
EnvData *wPairs = 0,*wNames = 0, *aPairs = 0, *aNames = 0;
int includeAll = 1;
int irc = 0;
int debug = 1;
app = pState->app;
pWorld = app->pWorld;
/* Get the world defaults */
env = pWorld->genv;
if (env) {
includeAll = env->includeAll;
wPairs = env->envPairs;
wNames = env->envNames;
}
/* Get the app values (overrides includeAll) */
env = app->env;
if (env) {
if (includeAll) {
/* Let the local env set envnone (there is no way to undo
-genvnone) */
includeAll = env->includeAll;
}
aPairs = env->envPairs;
aNames = env->envNames;
}
if (includeAll) {
if (envp) {
int j;
for (j=0; envp[j] && j < maxclient; j++) {
putenv( envp[j] );
client_envp[j] = envp[j];
}
irc = j;
}
else
irc = 0;
}
else {
MPIE_UnsetAllEnv( envp );
irc = 0;
}
while (wPairs) {
if (putenv( (char *)(wPairs->envvalue) )) {
irc = -1;
if (debug) perror( "putenv(wPairs) failed: " );
}
wPairs = wPairs->nextData;
}
while (wNames) {
if (putenv( (char *)(wNames->envvalue) )) {
irc = -1;
if (debug) perror( "putenv(wNames) failed: " );
}
wNames = wNames->nextData;
}
while (aPairs) {
if (putenv( (char *)(aPairs->envvalue) )) {
irc = -1;
if (debug) perror( "putenv(aPairs) failed: " );
}
aPairs = aPairs->nextData;
}
while (aNames) {
if (putenv( (char *)(aNames->envvalue) )) {
irc = -1;
if (debug) {
perror( "putenv(aNames) failed: " );
}
}
aNames = aNames->nextData;
}
return irc;
}
/*
Initialize the environment data
Builds the envvalue version of the data, using the given data.
if getValue is true, get the value for the name with getenv .
*/
int MPIE_EnvInitData( EnvData *elist, int getValue )
{
const char *value;
char *str;
int slen, rc;
while (elist) {
/* Skip variables that already have value strings */
if (!elist->envvalue) {
if (getValue) {
value = (const char *)getenv( elist->name );
}
else {
value = elist->value;
}
if (!value) {
/* Special case for an empty value */
value = "";
}
slen = strlen( elist->name ) + strlen(value) + 2;
str = (char *)MPIU_Malloc( slen );
if (!str) {
return 1;
}
MPIU_Strncpy( str, elist->name, slen );
if (value && *value) {
rc = MPIU_Strnapp( str, "=", slen );
rc += MPIU_Strnapp( str, value, slen );
if (rc) {
return 1;
}
}
elist->envvalue = (const char *)str;
}
elist = elist->nextData;
}
return 0;
}
/*
* Add an enviroinment variable to the global list of variables
*/
int MPIE_Putenv( ProcessWorld *pWorld, const char *env_string )
{
EnvInfo *genv;
EnvData *p;
/* FIXME: This should be getGenv (so allocation/init in one place) */
if (!pWorld->genv) {
genv = (EnvInfo *)MPIU_Malloc( sizeof(EnvInfo) );
genv->includeAll = 1;
genv->envPairs = 0;
genv->envNames = 0;
pWorld->genv = genv;
}
genv = pWorld->genv;
p = (EnvData *)MPIU_Malloc( sizeof(EnvData) );
if (!p) return 1;
p->name = 0;
p->value = 0;
p->envvalue = (const char *)MPIU_Strdup( env_string );
if (!p->envvalue) return 1;
p->nextData = genv->envPairs;
genv->envPairs = p;
return 0;
}
/* Unset all environment variables.
Not all systems support unsetenv (e.g., System V derived systems such
as Solaris), so we have to provide our own implementation.
In addition, there are various ways to determine the "current" environment
variables. One is to pass a third arg to main; the other is a global
variable.
Also, we prefer the environ variable over envp, because exec often
prefers what is in environ rather than the envp (envp appears to be a
copy, and unsetting the env doesn't always change the environment
that exec creates. This seems wrong, but it was what was observed
on Linux).
*/
#ifdef HAVE_EXTERN_ENVIRON
#ifdef NEEDS_ENVIRON_DECL
extern char **environ;
#endif
int MPIE_UnsetAllEnv( char *envp[] )
{
/* Ignore envp because environ is the real array that controls
the environment used by getenv/putenv/etc */
char **ep = environ;
while (*ep) *ep++ = 0;
return 0;
}
#elif defined(HAVE_UNSETENV)
int MPIE_UnsetAllEnv( char *envp[] )
{
int j;
for (j=0; envp[j]; j++) {
unsetenv( envp[j] );
}
return 0;
}
#else
/* No known way to unset the environment. Return failure */
int MPIE_UnsetAllEnv( char *envp[] )
{
return 1;
}
#endif
|
jodavis42/ZeroPhysicsTestbed | PhysicsTestbeds/Physics2d/Components/CollisionDebug.cpp | <gh_stars>0
#include "Precompiled.hpp"
#include "Components/CollisionDebug.hpp"
#include "Colliders/Collider2d.hpp"
#include "Components/PhysicsSpace2d.hpp"
#include "CollisionDetection/CollisionLibrary.hpp"
#include "Engine/Cog.hpp"
#include "Engine/Time.hpp"
#include "Engine/DebugDraw.hpp"
#include "Geometry/DebugDraw.hpp"
#include "Common/Math/ByteColor.hpp"
namespace Physics2d
{
//-------------------------------------------------------------------CollisionDebug
ZilchDefineType(CollisionDebug, builder, type)
{
ZeroBindSetup(Zero::SetupMode::DefaultSerialization);
ZeroBindComponent();
ZeroBindDocumented();
ZeroBindDependency(Zero::Cog);
ZilchBindFieldProperty(mActive)->ZeroSerialize(false);
ZilchBindFieldProperty(mPath0);
ZilchBindFieldProperty(mPath1);
ZilchBindFieldProperty(mOnTop)->ZeroSerialize(true);
ZilchBindFieldProperty(mPoint0Color)->ZeroSerialize(ToFloatColor(Color::Red));
ZilchBindFieldProperty(mPoint1Color)->ZeroSerialize(ToFloatColor(Color::Blue));
ZilchBindFieldProperty(mNormalColor)->ZeroSerialize(ToFloatColor(Color::White));
ZilchBindFieldProperty(mPenetrationDistanceColor)->ZeroSerialize(ToFloatColor(Color::Green));
ZilchBindFieldProperty(mPointSize)->ZeroSerialize(0.1f);
ZilchBindFieldProperty(mNormalHeadSize)->ZeroSerialize(0.1f);
}
void CollisionDebug::Serialize(Zero::Serializer& stream)
{
SerializeNameDefault(mActive, false);
stream.SerializeFieldDefault("Path0", mPath0, Zero::CogPath());
stream.SerializeFieldDefault("Path1", mPath1, Zero::CogPath());
SerializeNameDefault(mOnTop, true);
SerializeNameDefault(mPoint0Color, ToFloatColor(Color::Red));
SerializeNameDefault(mPoint1Color, ToFloatColor(Color::Blue));
SerializeNameDefault(mNormalColor, ToFloatColor(Color::White));
SerializeNameDefault(mPenetrationDistanceColor, ToFloatColor(Color::Green));
SerializeNameDefault(mPointSize, 0.1f);
SerializeNameDefault(mNormalHeadSize, 0.1f);
}
void CollisionDebug::Initialize(Zero::CogInitializer& initializer)
{
ConnectThisTo(GetSpace(), Zero::Events::FrameUpdate, OnFrameUpdate);
}
void CollisionDebug::OnAllObjectsCreated(Zero::CogInitializer& initializer)
{
mPath0.RestoreLink(initializer, this, "Path0");
mPath1.RestoreLink(initializer, this, "Path1");
}
void CollisionDebug::OnFrameUpdate(Zero::UpdateEvent* e)
{
if(!mActive)
return;
Collider2d* collider0 = mPath0.Has<Collider2d>();
Collider2d* collider1 = mPath1.Has<Collider2d>();
if(collider0 == nullptr || collider1 == nullptr)
return;
PhysicsSpace2d* physicsSpace = GetSpace()->has(PhysicsSpace2d);
CollisionLibrary* collisionLibrary = physicsSpace->GetCollisionLibrary();
Array<ContactManifold2d> manifolds;
if(!collisionLibrary->TestPair(collider0, collider1, manifolds))
return;
DrawManifolds(manifolds);
}
void CollisionDebug::DrawManifolds(const Array<ContactManifold2d>& manifolds) const
{
for(size_t i = 0; i < manifolds.Size(); ++i)
{
const ContactManifold2d& manifold = manifolds[i];
for(size_t pointIndex = 0; pointIndex < manifold.mPointCount; ++pointIndex)
{
const ManifoldPoint2d& point = manifold.mPoints[pointIndex];
Math::Vector3 p0 = Math::ToVector3(point.mPoint0, 0);
Math::Vector3 p1 = Math::ToVector3(point.mPoint1, 0);
Math::Vector3 penDistPoint = Math::ToVector3(point.mPoint0 - point.mNormal * point.mPenetrationDistance, 0);
Zero::gDebugDraw->Add(Zero::Debug::Sphere(p0, mPointSize).Color(mPoint0Color).OnTop(mOnTop));
Zero::gDebugDraw->Add(Zero::Debug::Sphere(p1, mPointSize).Color(mPoint1Color).OnTop(mOnTop));
Zero::gDebugDraw->Add(Zero::Debug::Line(p0, p1).Color(mNormalColor).HeadSize(mNormalHeadSize).OnTop(mOnTop));
Zero::gDebugDraw->Add(Zero::Debug::Line(p0, penDistPoint).Color(mPenetrationDistanceColor).HeadSize(mNormalHeadSize).OnTop(mOnTop));
}
}
}
}//namespace Physics2d
|
braydonf/yours-bitcoin | lib/base-58.js | <gh_stars>10-100
/**
* Base58 Encoding
* ===============
*
* Base58 (no check)
*/
'use strict'
let dependencies = {
bs58: require('bs58'),
Struct: require('./struct')
}
let inject = function (deps) {
let bs58 = deps.bs58
let Struct = deps.Struct
class Base58 extends Struct {
constructor (buf) {
super({buf})
}
fromHex (hex) {
return this.fromBuffer(new Buffer(hex, 'hex'))
}
toHex () {
return this.toBuffer().toString('hex')
}
static encode (buf) {
if (!Buffer.isBuffer(buf)) {
throw new Error('Input should be a buffer')
}
return bs58.encode(buf)
}
static decode (str) {
if (typeof str !== 'string') {
throw new Error('Input should be a string')
}
return new Buffer(bs58.decode(str))
}
fromBuffer (buf) {
this.buf = buf
return this
}
fromString (str) {
let buf = Base58.decode(str)
this.buf = buf
return this
}
toBuffer () {
return this.buf
}
toString () {
return Base58.encode(this.buf)
}
}
return Base58
}
inject = require('injecter')(inject, dependencies)
let Base58 = inject()
module.exports = Base58
|
Narottam04/StoreBay | frontend/src/pages/AdminOrdersList.js | <filename>frontend/src/pages/AdminOrdersList.js
import React, { useEffect, useState } from "react";
import { MenuIcon, XIcon } from '@heroicons/react/outline'
import Sidebar from '../components/Sidebar'
import { useDispatch, useSelector } from 'react-redux'
import Loader from '../components/Loader'
import { deleteUser, listUsers } from '../actions/userActions'
import { Link,useNavigate } from 'react-router-dom'
import { listOrders } from "../actions/orderActions";
const AdminOrdersList = () => {
const [openSidebar,setOpenSidebar] = useState(false)
const navigate = useNavigate()
const dispatch = useDispatch()
const orderList = useSelector(state => state.orderList)
const {loading, error,orders} = orderList
const userLogin = useSelector(state => state.userLogin)
const {userInfo} = userLogin
useEffect(()=> {
if(userInfo && userInfo.isAdmin){
dispatch(listOrders())
}
else {
navigate('/')
}
},[dispatch,userInfo])
return (
<div className="flex flex-row min-h-screen bg-gray-100 text-gray-800 md:overflow-x-hidden">
<Sidebar openSidebar = {openSidebar} />
<main className="main flex flex-col flex-grow -ml-64 md:ml-0 transition-all duration-150 ease-in pl-64">
<header className="header bg-white shadow py-4 px-4">
<div className="header-content flex items-center flex-row">
<div >
<a href className="flex flex-row items-center">
<img
src={`https://avatars.dicebear.com/api/initials/${userInfo.name}.svg`}
alt
className="h-10 w-10 bg-gray-200 border rounded-full"
/>
<span className="flex flex-col ml-2">
<span className=" w-60 font-semibold tracking-wide leading-none">{userInfo.name}</span>
<span className=" w-30 text-gray-500 text-xs leading-none mt-1">{userInfo.email}</span>
</span>
</a>
</div>
<div className="flex ml-auto">
{!openSidebar?
<svg xmlns="http://www.w3.org/2000/svg" class="text-black w-8 h-8 md:hidden" fill="none" viewBox="0 0 24 24" stroke="currentColor" onClick={()=>setOpenSidebar(!openSidebar)}>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
</svg>
:
<svg xmlns="http://www.w3.org/2000/svg" class="text-black w-8 h-8 md:hidden" fill="none" viewBox="0 0 24 24" stroke="currentColor" onClick={()=>setOpenSidebar(!openSidebar)}>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
}
</div>
</div>
</header>
<div className="main-content flex flex-col flex-grow p-4">
<h1 className="font-bold text-2xl text-gray-700 mb-6">Customer Orders</h1>
{/* table */}
{
loading ? <Loader/> : error ? <p>{error}</p>
:
<div className="flex flex-col w-[90vw] md:w-full overflow-x-scroll overflow-y-hidden md:overflow-y-auto">
<div className="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div className="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
<div className="shadow border-b border-gray-200 sm:rounded-lg">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
Product Id
</th>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
User Info
</th>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
Date
</th>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
Total Price
</th>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
Paid
</th>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
Delivered
</th>
<th scope="col" className="relative px-6 py-3">
<span className="sr-only">Edit</span>
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{orders.map((order) => (
<tr key={order._id}>
<td className="px-6 py-4 whitespace-nowrap">
<span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-gray-800">
{order._id}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center">
<div className="flex-shrink-0 h-10 w-10">
<img className="h-10 w-10 rounded-full" src={`https://avatars.dicebear.com/api/initials/${order.user ? order.user.name: "Anonymous"}.svg`} alt="avatar" />
</div>
<div className="ml-4">
<div className="text-sm font-medium text-gray-900">{order.user && order.user.name}</div>
<div className="text-sm text-gray-500">{order.user && order.user.email}</div>
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center">
<div className="flex-shrink-0 h-10 w-10">
<div className="text-sm text-gray-500">{order.createdAt.substring(0,10)}</div>
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center">
<div className="flex-shrink-0 h-10 w-10">
<div className="text-sm text-gray-500">${order.totalPrice}</div>
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
{
order.isPaid ?
<p className="text-sm w-20 text-green-700 bg-green-100 rounded-lg px-2 py-1">Paid at {order.paidAt.substring(0,10)}</p>
:
<p className="text-sm text-red-700 w-28 bg-red-100 rounded-lg px-2 py-1">Not Paid</p>
}
</td>
<td className="px-6 py-4 whitespace-nowrap">
{
order.isDelivered ?
<p className="text-sm w-20 text-green-700 bg-green-100 rounded-lg px-2 py-1">Delivered at {order.deliveredAt.substring(0,10)}</p>
:
<p className="text-sm text-red-700 w-28 bg-red-100 rounded-lg px-2 py-1">Not Delivered</p>
}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium flex space-x-2">
<Link to={`/order/${order._id}/`} className="text-indigo-600 hover:text-indigo-900">
Order Details
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
</div>
}
</div>
<footer className="footer px-4 py-6">
<div className="footer-content">
<p className="text-sm text-gray-600 text-center">© Brandname 2020. All rights reserved. <a href="https://twitter.com/iaminos">by iAmine</a></p>
</div>
</footer>
</main>
</div>
)
}
export default AdminOrdersList
|
eliothedeman/heath | vendor/github.com/eliothedeman/randutil/string.go | package randutil
import "math/rand"
const (
// Set of characters to use for generating random strings
Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Lower = "abcdefghijklmnopqrstuvwxyz"
Upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Numerals = "1234567890"
Alphanumeric = Alphabet + Numerals
Ascii = Alphanumeric + "~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:`"
)
// Bytes returns a random []byte of a certain length
func Bytes(length int) []byte {
buff := make([]byte, length)
for i := range buff {
buff[i] = Uint8()
}
return buff
}
// String returns a random string n characters long, composed of entities
// from charset.
func String(length int, charset string) string {
randstr := make([]byte, length) // Random string to return
size := len(charset)
for i := 0; i < length; i++ {
randstr[i] = charset[rand.Int()%size]
}
return string(randstr)
}
// AlphaString returns a random alphanumeric string n characters long.
func AlphaString(length int) string {
return String(length, Alphanumeric)
}
|
AmyliaScarlet/amyliascarletlib | src/test/java/com/amyliascarlet/jsontest/test/dubbo/Tiger.java | <reponame>AmyliaScarlet/amyliascarletlib
package com.amyliascarlet.jsontest.test.dubbo;
import java.io.Serializable;
public class Tiger implements Serializable {
/**
*
*/
private static final long serialVersionUID = -768303386469936078L;
public Tiger(){
}
private String tigerName;
private Boolean tigerSex;
public String getTigerName() {
return tigerName;
}
public void setTigerName(String tigerName) {
this.tigerName = tigerName;
}
public Boolean getTigerSex() {
return tigerSex;
}
public void setTigerSex(Boolean tigerSex) {
this.tigerSex = tigerSex;
}
} |
AdityaVSM/algorithms | 1 Mathematics/factorial.cpp | #include<bits/stdc++.h>
using namespace std;
long iterFactorial(long n){ //O(n) best soln
long res = 1;
for(int i=2; i<=n; i++){
res*=i;
}
return res;
}
long recurFactorial(long n){ //O(n)-time and O(n)- Auxiliary space
if(n == 0)
return 1;
return n*recurFactorial(n-1);
}
int main(){
cout<<iterFactorial(5)<<endl;
cout<<recurFactorial(5)<<endl;
return 0;
} |
vinpac/base-express-kit | src/components/base/Form/Form.js | import React, { PropTypes } from 'react';
import validators from '../../../common/validators';
import { forEach } from '../../../utils/object-utils';
import Validator from '../../../lib/Validator';
import has from 'has';
class Form extends React.Component {
static defaultProps = {
component: 'form'
};
static childContextTypes = {
subscribe: PropTypes.func.isRequired,
unsubscribe: PropTypes.func.isRequired,
validate: PropTypes.func.isRequired,
errors: PropTypes.objectOf(PropTypes.any)
};
constructor(props) {
super(props);
this.state = {
errors: {}
}
this.components = {}
this.handleSubmit = this.handleSubmit.bind(this)
this.subscribe = this.subscribe.bind(this)
this.unsubscribe = this.unsubscribe.bind(this)
this.validateOne = this.validateOne.bind(this)
this.validate = this.validate.bind(this)
//this.isValid = this.isValid.bind(this)
this.each = this.each.bind(this)
}
getChildContext() {
return {
subscribe: this.subscribe,
unsubscribe: this.unsubscribe,
validate: this.validateOne,
errors: this.state.errors
}
}
subscribe(field, component) {
if (this.components.hasOwnProperty(field)) {
console.warn(`Form Control with name ${field} already exists. Replacing it.`)
}
this.components[field] = component
}
unsubscribe(field) {
const { errors } = this.state
delete this.components[field]
delete errors[field]
this.setState({ errors })
}
validate() {
const errors = {}
this.each((component, inputName) => this.validateOne(inputName, errors))
this.setState({ errors })
return errors
}
isValid() {
let d = this.validate()
return !Object.keys(d).length
}
invalidateOne(field, rule, hint) {
if (this.components[field]) {
const { errors } = this.state
errors[field] = rule
this.components[field].invalidate(
hint
? hint(this.components[field].value, this.components)
: validators[rule].hint(this.components.value, this.components)
)
this.setState({
errors
})
}
}
getInputErrors(inputName, validators=this.props.validators, returnFirstError) {
const component = this.components[inputName]
return Validator.validate(
component.value,
component.props.validate,
validators,
{
returnFirstError,
data: {
inputName: inputName,
components: this.components
}
}
)
}
validateOne(inputName, initialErrors, shouldUpdate=!initialErrors) {
const errors = initialErrors || this.state.errors
const component = this.components[inputName]
const inputError = this.getInputErrors(inputName, this.props.validators, true)
if (!inputError) {
delete errors[inputName]
} else {
errors[inputName] = [ inputError ]
}
if (shouldUpdate) {
this.setState({
errors
})
component.setState(
inputError
? { isValid: false, hint: inputError.hint }
: { isValid: true, hint: null }
)
}
return inputError
}
getData() {
const data = {}
let keys;
let obj;
this.each((component, field) => {
obj = data
keys = field.split('.')
forEach(keys, (key, i) => {
if (i === keys.length -1) {
console.log(obj)
obj[key] = component.value
} else {
if(!has(obj, key)) {
obj[key] = {}
}
if (typeof obj[key] !== 'object') {
obj[key] = { '0': obj[key] }
}
obj = obj[key]
}
})
})
return data
}
handleSubmit(e) {
if (e) {
e.preventDefault()
}
if (!this.isValid()) {
return e ? e.preventDefault() : false
}
if (this.props.onSubmit) {
this.props.onSubmit(e)
}
}
each(fn) {
forEach(this.components, fn)
}
clean() {
this.each(component => component.clean ? component.clean() : component.value = "")
}
render() {
const { children, component:Component, ...props } = this.props
return (
<Component {...props} onSubmit={this.handleSubmit}>
{ children }
</Component>
);
}
}
export default Form;
|
gseteamproject/sandbox | examples/src/main/java/task/TellerAgent.java | <gh_stars>1-10
package task;
import java.util.Random;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.TickerBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
public class TellerAgent extends Agent {
String conversationAgentName;
long tickerPeriod;
Random randomNumber = new Random(5);
String gottedMessage = "5";
String messageToSend = "5";
MessageTemplate messageTemplate = MessageTemplate.MatchConversationId("1234");
private static final long serialVersionUID = 1832882011224052171L;
@Override
protected void setup() {
Object[] args = getArguments();
if (args != null && args.length > 0) {
conversationAgentName = args[0].toString();
tickerPeriod = Long.parseLong(args[1].toString());
} else {
conversationAgentName = null;
}
addBehaviour(new TellingBehavior(this, tickerPeriod));
addBehaviour(new ListeningBehavior());
}
class TellingBehavior extends TickerBehaviour {
private static final long serialVersionUID = 2440456042860733818L;
public TellingBehavior(Agent a, long period) {
super(a, period);
}
@Override
protected void onTick() {
messageToSend = String.valueOf(randomNumber.nextInt(5));
if (Long.parseLong(messageToSend) == Long.parseLong(gottedMessage)) {
ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
msg.addReceiver(new AID(("Boss"), AID.ISLOCALNAME));
msg.setConversationId("1234");
msg.setContent(messageToSend);
send(msg);
}
ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
msg.addReceiver(new AID((conversationAgentName), AID.ISLOCALNAME));
msg.setConversationId("1234");
msg.setContent(messageToSend);
send(msg);
tickerPeriod = 1000;
}
}
class ListeningBehavior extends CyclicBehaviour {
private static final long serialVersionUID = 5624499704245954673L;
@Override
public void action() {
ACLMessage msg = myAgent.receive(messageTemplate);
if (msg != null) {
gottedMessage = msg.getContent();
} else {
block();
}
}
}
}
|
chandanmb/activiti-karaf | bpmn-webui-components/bpmn-webui-bpmn20-model/src/main/java/de/hpi/bpmn2_0/model/extension/DummyPropertyListItem.java | package de.hpi.bpmn2_0.model.extension;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="dummypropertylistitem")
public class DummyPropertyListItem extends PropertyListItem {
}
|
hilaryosborne/fields | src/Types/BluePrintEvent.js | <reponame>hilaryosborne/fields<gh_stars>0
// @flow
export type BluePrintEvent = {
uuid: string,
action: string,
[string]: mixed,
};
|
rokroskar/GPy | GPy/models_modules/bayesian_gplvm.py | <gh_stars>1-10
# Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
import itertools
from matplotlib import pyplot
from ..core.sparse_gp import SparseGP
from ..likelihoods import Gaussian
from .. import kern
from ..inference.optimization import SCG
from ..util import plot_latent, linalg
from .gplvm import GPLVM, initialise_latent
from ..util.plot_latent import most_significant_input_dimensions
from ..core.model import Model
from ..util.subarray_and_sorting import common_subarrays
class BayesianGPLVM(SparseGP, GPLVM):
"""
Bayesian Gaussian Process Latent Variable Model
:param Y: observed data (np.ndarray) or GPy.likelihood
:type Y: np.ndarray| GPy.likelihood instance
:param input_dim: latent dimensionality
:type input_dim: int
:param init: initialisation method for the latent space
:type init: 'PCA'|'random'
"""
def __init__(self, likelihood_or_Y, input_dim, X=None, X_variance=None, init='PCA', num_inducing=10,
Z=None, kernel=None, **kwargs):
if type(likelihood_or_Y) is np.ndarray:
likelihood = Gaussian(likelihood_or_Y)
else:
likelihood = likelihood_or_Y
if X == None:
X = initialise_latent(init, input_dim, likelihood.Y)
self.init = init
if X_variance is None:
X_variance = np.clip((np.ones_like(X) * 0.5) + .01 * np.random.randn(*X.shape), 0.001, 1)
if Z is None:
Z = np.random.permutation(X.copy())[:num_inducing]
assert Z.shape[1] == X.shape[1]
if kernel is None:
kernel = kern.rbf(input_dim) # + kern.white(input_dim)
SparseGP.__init__(self, X, likelihood, kernel, Z=Z, X_variance=X_variance, **kwargs)
self.ensure_default_constraints()
def _get_param_names(self):
X_names = sum([['X_%i_%i' % (n, q) for q in range(self.input_dim)] for n in range(self.num_data)], [])
S_names = sum([['X_variance_%i_%i' % (n, q) for q in range(self.input_dim)] for n in range(self.num_data)], [])
return (X_names + S_names + SparseGP._get_param_names(self))
#def _get_print_names(self):
# return SparseGP._get_print_names(self)
def _get_params(self):
"""
Horizontally stacks the parameters in order to present them to the optimizer.
The resulting 1-input_dim array has this structure:
===============================================================
| mu | S | Z | theta | beta |
===============================================================
"""
x = np.hstack((self.X.flatten(), self.X_variance.flatten(), SparseGP._get_params(self)))
return x
def _set_params(self, x, save_old=True, save_count=0):
N, input_dim = self.num_data, self.input_dim
self.X = x[:self.X.size].reshape(N, input_dim).copy()
self.X_variance = x[(N * input_dim):(2 * N * input_dim)].reshape(N, input_dim).copy()
SparseGP._set_params(self, x[(2 * N * input_dim):])
def dKL_dmuS(self):
dKL_dS = (1. - (1. / (self.X_variance))) * 0.5
dKL_dmu = self.X
return dKL_dmu, dKL_dS
def dL_dmuS(self):
dL_dmu_psi0, dL_dS_psi0 = self.kern.dpsi0_dmuS(self.dL_dpsi0, self.Z, self.X, self.X_variance)
dL_dmu_psi1, dL_dS_psi1 = self.kern.dpsi1_dmuS(self.dL_dpsi1, self.Z, self.X, self.X_variance)
dL_dmu_psi2, dL_dS_psi2 = self.kern.dpsi2_dmuS(self.dL_dpsi2, self.Z, self.X, self.X_variance)
dL_dmu = dL_dmu_psi0 + dL_dmu_psi1 + dL_dmu_psi2
dL_dS = dL_dS_psi0 + dL_dS_psi1 + dL_dS_psi2
return dL_dmu, dL_dS
def KL_divergence(self):
var_mean = np.square(self.X).sum()
var_S = np.sum(self.X_variance - np.log(self.X_variance))
return 0.5 * (var_mean + var_S) - 0.5 * self.input_dim * self.num_data
def log_likelihood(self):
ll = SparseGP.log_likelihood(self)
kl = self.KL_divergence()
return ll - kl
def _log_likelihood_gradients(self):
dKL_dmu, dKL_dS = self.dKL_dmuS()
dL_dmu, dL_dS = self.dL_dmuS()
d_dmu = (dL_dmu - dKL_dmu).flatten()
d_dS = (dL_dS - dKL_dS).flatten()
self.dbound_dmuS = np.hstack((d_dmu, d_dS))
self.dbound_dZtheta = SparseGP._log_likelihood_gradients(self)
return np.hstack((self.dbound_dmuS.flatten(), self.dbound_dZtheta))
def plot_latent(self, plot_inducing=True, *args, **kwargs):
return plot_latent.plot_latent(self, plot_inducing=plot_inducing, *args, **kwargs)
def do_test_latents(self, Y):
"""
Compute the latent representation for a set of new points Y
Notes:
This will only work with a univariate Gaussian likelihood (for now)
"""
assert not self.likelihood.is_heteroscedastic
N_test = Y.shape[0]
input_dim = self.Z.shape[1]
means = np.zeros((N_test, input_dim))
covars = np.zeros((N_test, input_dim))
dpsi0 = -0.5 * self.input_dim * self.likelihood.precision
dpsi2 = self.dL_dpsi2[0][None, :, :] # TODO: this may change if we ignore het. likelihoods
V = self.likelihood.precision * Y
#compute CPsi1V
if self.Cpsi1V is None:
psi1V = np.dot(self.psi1.T, self.likelihood.V)
tmp, _ = linalg.dtrtrs(self._Lm, np.asfortranarray(psi1V), lower=1, trans=0)
tmp, _ = linalg.dpotrs(self.LB, tmp, lower=1)
self.Cpsi1V, _ = linalg.dtrtrs(self._Lm, tmp, lower=1, trans=1)
dpsi1 = np.dot(self.Cpsi1V, V.T)
start = np.zeros(self.input_dim * 2)
for n, dpsi1_n in enumerate(dpsi1.T[:, :, None]):
args = (self.kern, self.Z, dpsi0, dpsi1_n.T, dpsi2)
xopt, fopt, neval, status = SCG(f=latent_cost, gradf=latent_grad, x=start, optargs=args, display=False)
mu, log_S = xopt.reshape(2, 1, -1)
means[n] = mu[0].copy()
covars[n] = np.exp(log_S[0]).copy()
return means, covars
def dmu_dX(self, Xnew):
"""
Calculate the gradient of the prediction at Xnew w.r.t Xnew.
"""
dmu_dX = np.zeros_like(Xnew)
for i in range(self.Z.shape[0]):
dmu_dX += self.kern.dK_dX(self.Cpsi1Vf[i:i + 1, :], Xnew, self.Z[i:i + 1, :])
return dmu_dX
def dmu_dXnew(self, Xnew):
"""
Individual gradient of prediction at Xnew w.r.t. each sample in Xnew
"""
dK_dX = np.zeros((Xnew.shape[0], self.num_inducing))
ones = np.ones((1, 1))
for i in range(self.Z.shape[0]):
dK_dX[:, i] = self.kern.dK_dX(ones, Xnew, self.Z[i:i + 1, :]).sum(-1)
return np.dot(dK_dX, self.Cpsi1Vf)
def plot_steepest_gradient_map(self, fignum=None, ax=None, which_indices=None, labels=None, data_labels=None, data_marker='o', data_s=40, resolution=20, aspect='auto', updates=False, ** kwargs):
input_1, input_2 = significant_dims = most_significant_input_dimensions(self, which_indices)
X = np.zeros((resolution ** 2, self.input_dim))
indices = np.r_[:X.shape[0]]
if labels is None:
labels = range(self.output_dim)
def plot_function(x):
X[:, significant_dims] = x
dmu_dX = self.dmu_dXnew(X)
argmax = np.argmax(dmu_dX, 1)
return dmu_dX[indices, argmax], np.array(labels)[argmax]
if ax is None:
fig = pyplot.figure(num=fignum)
ax = fig.add_subplot(111)
if data_labels is None:
data_labels = np.ones(self.num_data)
ulabels = []
for lab in data_labels:
if not lab in ulabels:
ulabels.append(lab)
marker = itertools.cycle(list(data_marker))
from GPy.util import Tango
for i, ul in enumerate(ulabels):
if type(ul) is np.string_:
this_label = ul
elif type(ul) is np.int64:
this_label = 'class %i' % ul
else:
this_label = 'class %i' % i
m = marker.next()
index = np.nonzero(data_labels == ul)[0]
x = self.X[index, input_1]
y = self.X[index, input_2]
ax.scatter(x, y, marker=m, s=data_s, color=Tango.nextMedium(), label=this_label)
ax.set_xlabel('latent dimension %i' % input_1)
ax.set_ylabel('latent dimension %i' % input_2)
from matplotlib.cm import get_cmap
from GPy.util.latent_space_visualizations.controllers.imshow_controller import ImAnnotateController
if not 'cmap' in kwargs.keys():
kwargs.update(cmap=get_cmap('jet'))
controller = ImAnnotateController(ax,
plot_function,
tuple(self.X.min(0)[:, significant_dims]) + tuple(self.X.max(0)[:, significant_dims]),
resolution=resolution,
aspect=aspect,
**kwargs)
ax.legend()
ax.figure.tight_layout()
if updates:
pyplot.show()
clear = raw_input('Enter to continue')
if clear.lower() in 'yes' or clear == '':
controller.deactivate()
return controller.view
def plot_X_1d(self, fignum=None, ax=None, colors=None):
"""
Plot latent space X in 1D:
- if fig is given, create input_dim subplots in fig and plot in these
- if ax is given plot input_dim 1D latent space plots of X into each `axis`
- if neither fig nor ax is given create a figure with fignum and plot in there
colors:
colors of different latent space dimensions input_dim
"""
import pylab
if ax is None:
fig = pylab.figure(num=fignum, figsize=(8, min(12, (2 * self.X.shape[1]))))
if colors is None:
colors = pylab.gca()._get_lines.color_cycle
pylab.clf()
else:
colors = iter(colors)
plots = []
x = np.arange(self.X.shape[0])
for i in range(self.X.shape[1]):
if ax is None:
a = fig.add_subplot(self.X.shape[1], 1, i + 1)
elif isinstance(ax, (tuple, list)):
a = ax[i]
else:
raise ValueError("Need one ax per latent dimnesion input_dim")
a.plot(self.X, c='k', alpha=.3)
plots.extend(a.plot(x, self.X.T[i], c=colors.next(), label=r"$\mathbf{{X_{{{}}}}}$".format(i)))
a.fill_between(x,
self.X.T[i] - 2 * np.sqrt(self.X_variance.T[i]),
self.X.T[i] + 2 * np.sqrt(self.X_variance.T[i]),
facecolor=plots[-1].get_color(),
alpha=.3)
a.legend(borderaxespad=0.)
a.set_xlim(x.min(), x.max())
if i < self.X.shape[1] - 1:
a.set_xticklabels('')
pylab.draw()
if ax is None:
fig.tight_layout(h_pad=.01) # , rect=(0, 0, 1, .95))
return fig
def getstate(self):
"""
Get the current state of the class,
here just all the indices, rest can get recomputed
"""
return SparseGP.getstate(self) + [self.init]
def setstate(self, state):
self._const_jitter = None
self.init = state.pop()
SparseGP.setstate(self, state)
class BayesianGPLVMWithMissingData(Model):
"""
Bayesian Gaussian Process Latent Variable Model with missing data support.
NOTE: Missing data is assumed to be missing at random!
This extension comes with a large memory and computing time deficiency.
Use only if fraction of missing data at random is higher than 60%.
Otherwise, try filtering data before using this extension.
Y can hold missing data as given by `missing`, standard is :class:`~numpy.nan`.
If likelihood is given for Y, this likelihood will be discarded, but the parameters
of the likelihood will be taken. Also every effort of creating the same likelihood
will be done.
:param likelihood_or_Y: observed data (np.ndarray) or GPy.likelihood
:type likelihood_or_Y: :class:`~numpy.ndarray` | :class:`~GPy.likelihoods.likelihood.likelihood` instance
:param int input_dim: latent dimensionality
:param init: initialisation method for the latent space
:type init: 'PCA' | 'random'
"""
def __init__(self, likelihood_or_Y, input_dim, X=None, X_variance=None, init='PCA', num_inducing=10,
Z=None, kernel=None, **kwargs):
#=======================================================================
# Filter Y, such that same missing data is at same positions.
# If full rows are missing, delete them entirely!
if type(likelihood_or_Y) is np.ndarray:
Y = likelihood_or_Y
likelihood = Gaussian
params = 1.
normalize=None
else:
Y = likelihood_or_Y.Y
likelihood = likelihood_or_Y.__class__
params = likelihood_or_Y._get_params()
if isinstance(likelihood_or_Y, Gaussian):
normalize = True
scale = likelihood_or_Y._scale
offset = likelihood_or_Y._offset
# Get common subrows
filter_ = np.isnan(Y)
self.subarray_indices = common_subarrays(filter_,axis=1)
likelihoods = [likelihood(Y[~np.array(v,dtype=bool),:][:,ind]) for v,ind in self.subarray_indices.iteritems()]
for l in likelihoods:
l._set_params(params)
if normalize: # get normalization in common
l._scale = scale
l._offset = offset
#=======================================================================
if X == None:
X = initialise_latent(init, input_dim, Y[:,np.any(np.isnan(Y),1)])
self.init = init
if X_variance is None:
X_variance = np.clip((np.ones_like(X) * 0.5) + .01 * np.random.randn(*X.shape), 0.001, 1)
if Z is None:
Z = np.random.permutation(X.copy())[:num_inducing]
assert Z.shape[1] == X.shape[1]
if kernel is None:
kernel = kern.rbf(input_dim) # + kern.white(input_dim)
self.submodels = [BayesianGPLVM(l, input_dim, X, X_variance, init, num_inducing, Z, kernel) for l in likelihoods]
self.gref = self.submodels[0]
#:type self.gref: BayesianGPLVM
self.ensure_default_constraints()
def log_likelihood(self):
ll = -self.gref.KL_divergence()
for g in self.submodels:
ll += SparseGP.log_likelihood(g)
return ll
def _log_likelihood_gradients(self):
dLdmu, dLdS = reduce(lambda a, b: [a[0] + b[0], a[1] + b[1]], (g.dL_dmuS() for g in self.bgplvms))
dKLmu, dKLdS = self.gref.dKL_dmuS()
dLdmu -= dKLmu
dLdS -= dKLdS
dLdmuS = np.hstack((dLdmu.flatten(), dLdS.flatten())).flatten()
dldzt1 = reduce(lambda a, b: a + b, (SparseGP._log_likelihood_gradients(g)[:self.gref.num_inducing*self.gref.input_dim] for g in self.submodels))
return np.hstack((dLdmuS,
dldzt1,
np.hstack([np.hstack([g.dL_dtheta(),
g.likelihood._gradients(\
partial=g.partial_for_likelihood)]) \
for g in self.submodels])))
def getstate(self):
return Model.getstate(self)+[self.submodels,self.subarray_indices]
def setstate(self, state):
self.subarray_indices = state.pop()
self.submodels = state.pop()
self.gref = self.submodels[0]
Model.setstate(self, state)
self._set_params(self._get_params())
def _get_param_names(self):
X_names = sum([['X_%i_%i' % (n, q) for q in range(self.input_dim)] for n in range(self.num_data)], [])
S_names = sum([['X_variance_%i_%i' % (n, q) for q in range(self.input_dim)] for n in range(self.num_data)], [])
return (X_names + S_names + SparseGP._get_param_names(self.gref))
def _get_params(self):
return self.gref._get_params()
def _set_params(self, x):
[g._set_params(x) for g in self.submodels]
pass
def latent_cost_and_grad(mu_S, kern, Z, dL_dpsi0, dL_dpsi1, dL_dpsi2):
"""
objective function for fitting the latent variables for test points
(negative log-likelihood: should be minimised!)
"""
mu, log_S = mu_S.reshape(2, 1, -1)
S = np.exp(log_S)
psi0 = kern.psi0(Z, mu, S)
psi1 = kern.psi1(Z, mu, S)
psi2 = kern.psi2(Z, mu, S)
lik = dL_dpsi0 * psi0 + np.dot(dL_dpsi1.flatten(), psi1.flatten()) + np.dot(dL_dpsi2.flatten(), psi2.flatten()) - 0.5 * np.sum(np.square(mu) + S) + 0.5 * np.sum(log_S)
mu0, S0 = kern.dpsi0_dmuS(dL_dpsi0, Z, mu, S)
mu1, S1 = kern.dpsi1_dmuS(dL_dpsi1, Z, mu, S)
mu2, S2 = kern.dpsi2_dmuS(dL_dpsi2, Z, mu, S)
dmu = mu0 + mu1 + mu2 - mu
# dS = S0 + S1 + S2 -0.5 + .5/S
dlnS = S * (S0 + S1 + S2 - 0.5) + .5
return -lik, -np.hstack((dmu.flatten(), dlnS.flatten()))
def latent_cost(mu_S, kern, Z, dL_dpsi0, dL_dpsi1, dL_dpsi2):
"""
objective function for fitting the latent variables (negative log-likelihood: should be minimised!)
This is the same as latent_cost_and_grad but only for the objective
"""
mu, log_S = mu_S.reshape(2, 1, -1)
S = np.exp(log_S)
psi0 = kern.psi0(Z, mu, S)
psi1 = kern.psi1(Z, mu, S)
psi2 = kern.psi2(Z, mu, S)
lik = dL_dpsi0 * psi0 + np.dot(dL_dpsi1.flatten(), psi1.flatten()) + np.dot(dL_dpsi2.flatten(), psi2.flatten()) - 0.5 * np.sum(np.square(mu) + S) + 0.5 * np.sum(log_S)
return -float(lik)
def latent_grad(mu_S, kern, Z, dL_dpsi0, dL_dpsi1, dL_dpsi2):
"""
This is the same as latent_cost_and_grad but only for the grad
"""
mu, log_S = mu_S.reshape(2, 1, -1)
S = np.exp(log_S)
mu0, S0 = kern.dpsi0_dmuS(dL_dpsi0, Z, mu, S)
mu1, S1 = kern.dpsi1_dmuS(dL_dpsi1, Z, mu, S)
mu2, S2 = kern.dpsi2_dmuS(dL_dpsi2, Z, mu, S)
dmu = mu0 + mu1 + mu2 - mu
# dS = S0 + S1 + S2 -0.5 + .5/S
dlnS = S * (S0 + S1 + S2 - 0.5) + .5
return -np.hstack((dmu.flatten(), dlnS.flatten()))
|
ShalithaCell/CSSE_WEB | src/components/Dialogs/ViewOrderDialog.js | /* eslint-disable consistent-return,no-plusplus,react/destructuring-assignment,max-len,array-callback-return */
import React, { useState, useEffect } from 'react';
import { connect } from "react-redux";
import Dialog from "@material-ui/core/Dialog";
import DialogTitle from "@material-ui/core/DialogTitle";
import DialogContent from "@material-ui/core/DialogContent";
import DialogActions from "@material-ui/core/DialogActions";
import TextField from "@material-ui/core/TextField";
import InputLabel from "@material-ui/core/InputLabel";
import { Button } from 'rsuite';
import { MuiPickersUtilsProvider, KeyboardDatePicker } from '@material-ui/pickers';
import MaterialTable from "material-table";
import DateFnsUtils from '@date-io/date-fns';
import { ToastContainer, toast } from 'react-toastify';
import {
fetchOrders,
handleViewOrderDialogStatus,
handleViewPaymentDialogStatus,
updateOrderStatus,
} from "../../redux/action/OrderAction";
import 'date-fns';
/**
* order view dialog
* @param props
* @returns {JSX.Element}
* @constructor
*/
function ViewOrderDialog(props)
{
const { isEnable } = props;
// order reference id
const [ orderID, setOrderID ] = useState(null);
// order net amount
const [ netAmount, setNetAmount ] = useState(0);
// cart details
const [ orderItems, setOrderItems ] = useState([]);
// address
const [ address, setAddress ] = useState('');
// due date
const [ dueDate, setDueDate ] = useState(Date.now);
// back to previous
function handleBack()
{
setOrderID(null);
setNetAmount(0);
setOrderItems([]);
props.handleViewOrderDialogStatus(false, null);
}
useEffect(() =>
{
if (props.editDetails !== null)
{
setOrderID(props.editDetails.referenceID);
setDueDate(new Date(props.editDetails.dueDate.toDate()));
setAddress(props.editDetails.address);
const itemList = props.orderItems.filter((i) => i.OrderID === props.editDetails.id);
itemList.map((i) =>
{
const item = props.itemList.filter((s) => s.id === i.itemID);
const cartObj = {
id : i.OrderID,
item : item[0].name,
supplier : props.editDetails.supplierName,
unitPrice : i.unitPrice,
qty : i.qty,
amount : (Number(i.unitPrice) * Number(i.qty)),
};
setNetAmount(netAmount + Number(cartObj.amount));
setOrderItems([
...orderItems,
cartObj,
]);
return i;
});
}
}, [ isEnable ]);
function handleOnApprove()
{
const paymentObj = {
orderItems,
netAmount,
orderID,
address,
dueDate,
};
props.handleViewPaymentDialogStatus(true, paymentObj);
handleBack();
}
function handleOnDiscard()
{
props.updateOrderStatus(orderItems[0].id, 0);
handleBack();
props.fetchOrders();
}
return (
<div>
<Dialog
open={isEnable}
aria-labelledby='form-dialog-title'
fullWidth
maxWidth='xl'
>
<DialogTitle id='form-dialog-title'>
<div className='row'>
<div className='col-md-6'>
Order (Ref -
{orderID }
)
</div>
<div className='col-md-6 text-right'>
Net amount =
{' '}
{netAmount}
</div>
</div>
</DialogTitle>
<DialogContent>
<div className='row'>
<div className='col-md-12 border-1'>
<div className='mt-2'>
<InputLabel id='lblSurveyName'>
Address
<span className='text-danger'> *</span>
</InputLabel>
<TextField
autoFocus
margin='dense'
id='address'
placeholder='enter deliver address'
type='text'
variant='outlined'
value={address}
onChange={(e) => setAddress(e.target.value)}
error={address.length === 0}
fullWidth
disabled
/>
</div>
<div className='mt-2 mb-3'>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
disableToolbar
fullWidth
variant='inline'
format='MM/dd/yyyy'
margin='normal'
id='date-picker-inline'
label='Select Deliver Date'
value={dueDate}
onChange={(e) => setDueDate(e)}
KeyboardButtonProps={{
'aria-label' : 'change date',
}}
/>
</MuiPickersUtilsProvider>
</div>
<MaterialTable
title='Order Items'
columns={[
{ title: 'Item', field: 'item' },
{ title: 'Supplier', field: 'supplier' },
{ title: 'Unit Price', field: 'unitPrice' },
{ title: 'Qty', field: 'qty' },
{ title: 'Amount', field: 'amount' },
]}
data={orderItems}
options={{
actionsColumnIndex : -1,
search : true,
pageSize : 5,
headerStyle : {
backgroundColor : '#055FB3',
color : '#FFF',
},
}}
/>
</div>
</div>
</DialogContent>
<DialogActions>
<Button
appearance='ghost'
onClick={() => handleBack()}
className='mr-3'
>
Cancel
</Button>
<Button
color='red'
className='mr-3'
// onClick={() => handleOnPlaceOrder()}
>
Discard
</Button>
<Button
color='green'
onClick={() => handleOnApprove()}
>
Approve
</Button>
</DialogActions>
<ToastContainer />
</Dialog>
</div>
);
}
const mapStateToProps = (state) => ({
isEnable : state.system.viewOrderDialog,
editDetails : state.system.viewOrderDetails,
orderItems : state.orders.orderItems,
supplier : state.supplier.suppliers,
itemList : state.items.items,
});
export default connect(
mapStateToProps,
{
fetchOrders,
handleViewOrderDialogStatus,
handleViewPaymentDialogStatus,
updateOrderStatus,
},
)(ViewOrderDialog);
|
shubs/api-store | store/Facebook ID Finder/Facebook ID Finder.js | <filename>store/Facebook ID Finder/Facebook ID Finder.js<gh_stars>1-10
// Phantombuster configuration {
"phantombuster command: nodejs"
"phantombuster package: 5"
"phantombuster dependencies: lib-StoreUtilities.js"
// Buster and Nick instantiation
const Buster = require("phantombuster")
const buster = new Buster()
const Nick = require("nickjs")
const nick = new Nick({
loadImages: true,
printPageErrors: false,
printResourceErrors: false,
printNavigation: false,
printAborts: false,
debug: false,
})
const StoreUtilities = require("./lib-StoreUtilities")
const utils = new StoreUtilities(nick, buster)
const DB_NAME = "result"
// }
const scrapeId = (arg, callback) => callback(null, document.querySelector("code").textContent.trim())
const getId = async (tab, url) => {
const selector = "form.i-amphtml-form"
try {
await tab.open("https://findmyfbid.com/")
await tab.waitUntilVisible(selector)
await tab.fill(selector, {url: url}, {submit: false})
await tab.click("input[type=\"submit\"]")
const resultSelector = await tab.waitUntilVisible(["#success-wrap", ".text-danger"], 20000, "or")
if (resultSelector === "#success-wrap") {
return (await tab.evaluate(scrapeId))
}
return false
} catch (e) {
utils.log(`Error: ${e}`, "error")
return false
}
}
// Checks if a url is already in the csv
const checkDb = (str, db) => {
for (const line of db) {
if (str === line.originalUrl) {
return false
}
}
return true
}
;(async () => {
const tab = await nick.newTab()
let { spreadsheetUrl, csvName } = utils.validateArguments()
if (!csvName) {
csvName = DB_NAME
}
let facebookLinks = await utils.getDataFromCsv2(spreadsheetUrl)
let result = await utils.getDb(csvName + ".csv")
facebookLinks = facebookLinks.filter(el => checkDb(el, result))
if (facebookLinks.length < 1) {
utils.log("Spreadsheet is empty or every URLs from this sheet has already been treated.", "warning")
nick.exit()
}
for (const link of facebookLinks) {
const timeLeft = await utils.checkTimeLeft()
if (!timeLeft.timeLeft) {
utils.log(`Stopped getting IDs: ${timeLeft.message}`, "warning")
break
}
if (link) {
utils.log(`Getting the ID for url:${link}...`, "loading")
const id = await getId(tab, link)
if (id === false) {
utils.log(`Could not get the id for ${link}, profile might be protected.`, "warning")
result.push({error: "Could not find the ID: profile protected.", originalUrl: link})
} else {
utils.log(`Got ID: ${id} for ${link}`, "done")
result.push({url: "https://www.facebook.com/" + id, id, originalUrl: link})
}
} else {
utils.log("Empty line... skipping entry", "warning")
}
}
await utils.saveResult(result, csvName)
})()
.catch(err => {
utils.log(err, "error")
nick.exit(1)
})
|
Havret/AlgorithmsJava | src/GraphProperties.java | <reponame>Havret/AlgorithmsJava<gh_stars>0
public class GraphProperties {
private int[] eccentricities;
public GraphProperties(Graph graph) {
this.eccentricities = new int[graph.V()];
for (int v = 0; v < graph.V(); v++) {
int eccentricity = 0;
var paths = new BreadthFirstPaths(graph, v);
for (int w = 0; w < graph.V(); w++) {
if (paths.hasPathTo(w)) {
var distance = paths.distanceTo(w);
if (distance > eccentricity) {
eccentricity = distance;
}
}
}
this.eccentricities[v] = eccentricity;
}
}
// length of the shortest path from
// v to the furthest vertex from v
public int eccentricity(int v) {
return eccentricities[v];
}
// maximum eccentricity of any vertex
public int diameter() {
int diameter = 0;
for (int eccentricity : eccentricities) {
if (eccentricity > diameter) {
diameter = eccentricity;
}
}
return diameter;
}
// smallest eccentricity of any vertex
public int radius() {
int radius = Integer.MAX_VALUE;
for (int eccentricity : eccentricities) {
if (eccentricity < radius) {
radius = eccentricity;
}
}
return radius;
}
public int center() {
int radius = radius();
for (int i = 0; i < eccentricities.length; i++) {
if (eccentricity(i) == radius)
return i;
}
throw new IllegalArgumentException();
}
}
|
krbalag/Tamil | ezhuththu/src/main/java/tamil/lang/known/derived/ThozhirrPeyar.java | package tamil.lang.known.derived;
import tamil.lang.TamilWord;
import tamil.lang.known.non.derived.Vinaiyadi;
/**
* <p>
*
* தொழிற்பெயர்
* எ.கா ஆட்டம், எழுத்து
* </p>
*
* @author velsubra
*/
public final class ThozhirrPeyar extends VinaiyadiDerivative {
public ThozhirrPeyar(TamilWord word, Vinaiyadi vinaiyadi) {
super(word, vinaiyadi);
}
}
|
kuo77122/serverless-survey-forms | web/portal/src/components/L10n/ControlBtn/index.js |
// CSS
import styles from './style.css';
import React from 'react';
import PureComponent from 'react-pure-render/component';
import IconButton from '../../IconButton';
class ControlBtn extends PureComponent {
constructor() {
super();
this._onDeleteL10nClick = this._onDeleteL10nClick.bind(this);
this._onExportL10nClick = this._onExportL10nClick.bind(this);
this._onImportL10nClick = this._onImportL10nClick.bind(this);
}
render() {
const { lang, selectedL10n } = this.props;
const btnsData = [
{ id: 'exportBtn', string: 'Export', img: 'report', func: this._onExportL10nClick },
{ id: 'importBtn', string: 'Import', img: '', func: this._onImportL10nClick },
{ id: 'delBtn', string: 'Delete', img: 'delete', func: this._onDeleteL10nClick }
];
let btns = [];
btnsData.forEach((btn, idx) => {
if (idx === 0 || idx === 1 ||
(idx === 2 && selectedL10n !== '' && lang !== selectedL10n)) {
// btn showed conditions:
// if it is Export or Import
// if it is Delete, and selectedL10n is not equal to basic lang
btns.push(
<IconButton
key={idx}
id={btn.id}
string={btn.string}
i18nKey={false}
img={btn.img}
onClick={btn.func}
/>);
}
});
return (
<div ref="root" className={styles.control}>
<div className={styles.wrap}>{btns}</div>
</div>
);
}
_onImportL10nClick() {
const { popupActions } = this.props;
popupActions.setPopup('ImportL10n');
}
_onExportL10nClick() {
const { popupActions } = this.props;
popupActions.setPopup('ExportL10n');
}
_onDeleteL10nClick() {
const { lang, selectedL10n, questionsActions } = this.props;
if (lang === selectedL10n) {
return;
}
questionsActions.deleteSelectedL10n();
}
}
export default ControlBtn;
|
blankRiot96/PygameHelper | setup.py | <filename>setup.py
from setuptools import setup, find_packages
import PygameHelper as pgh
import codecs
import os
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, "README.md"), encoding="utf-8") as fh:
long_description = "\n" + fh.read()
PACKAGE_NAME = "PygameHelper"
VERSION = pgh.__version__
DESCRIPTION = "helpful tools/widgets for pygame"
def setup_package():
metadata = {
"name": PACKAGE_NAME,
"version": VERSION,
"author": "emc235",
"description": DESCRIPTION,
"long_description": long_description,
"long_description_content_type": "text/markdown",
"url": "https://github.com/Emc2356/PygameHelper",
"packages": find_packages(),
"python_requires": ">=3.7",
"license": "MIT",
"install_requires": ["pygame", "numpy"]
}
setup(**metadata)
if __name__ == '__main__':
setup_package()
|
prezi/spaghetti | spaghetti-core/src/main/java/com/prezi/spaghetti/packaging/ApplicationPackageParameters.java | package com.prezi.spaghetti.packaging;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedMap;
import com.prezi.spaghetti.bundle.ModuleBundleSet;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
public class ApplicationPackageParameters {
public static final String DEFAULT_APPLICATION_NAME = "application.js";
public final ModuleBundleSet bundles;
public final String applicationName;
public final String mainModule;
public final boolean execute;
public final List<String> prefixes;
public final List<String> suffixes;
public final SortedMap<String, String> externals;
public ApplicationPackageParameters(ModuleBundleSet bundles, String applicationName, String mainModule, boolean execute, Iterable<String> prefixes, Iterable<String> suffixes, Map<String, String> externals) {
this.bundles = bundles;
this.applicationName = applicationName;
this.mainModule = mainModule;
this.execute = execute;
this.prefixes = ImmutableList.copyOf(prefixes);
this.suffixes = ImmutableList.copyOf(suffixes);
this.externals = ImmutableSortedMap.copyOf(externals);
}
}
|
utr001/dhis2-android-capture-app | app/src/main/java/org/dhis2/usescases/eventsWithoutRegistration/eventSummary/EventSummaryActivity.java | <filename>app/src/main/java/org/dhis2/usescases/eventsWithoutRegistration/eventSummary/EventSummaryActivity.java
package org.dhis2.usescases.eventsWithoutRegistration.eventSummary;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import org.dhis2.App;
import org.dhis2.R;
import org.dhis2.data.forms.FormSectionViewModel;
import org.dhis2.data.forms.dataentry.fields.FieldViewModel;
import org.dhis2.databinding.ActivityEventSummaryBinding;
import org.dhis2.usescases.general.ActivityGlobalAbstract;
import org.dhis2.utils.DateUtils;
import org.dhis2.utils.DialogClickListener;
import org.dhis2.utils.HelpManager;
import org.dhis2.utils.custom_views.CustomDialog;
import org.dhis2.utils.custom_views.ProgressBarAnimation;
import org.hisp.dhis.android.core.event.EventModel;
import org.hisp.dhis.android.core.program.ProgramModel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import io.reactivex.functions.Consumer;
import static android.text.TextUtils.isEmpty;
/**
* QUADRAM. Created by Cristian on 01/03/2018.
*/
public class EventSummaryActivity extends ActivityGlobalAbstract implements EventSummaryContract.View, ProgressBarAnimation.OnUpdate {
private static final int PROGRESS_TIME = 2000;
public static final String EVENT_ID = "event_id";
public static final String PROGRAM_ID = "program_id";
private Map<String, View> sections = new HashMap<>();
@Inject
EventSummaryContract.Presenter presenter;
private ActivityEventSummaryBinding binding;
private int completionPercent;
private int totalFields;
private int totalCompletedFields;
private int fieldsToCompleteBeforeClosing;
String eventId;
String programId;
private String messageOnComplete = "";
private boolean canComplete = true;
private CustomDialog dialog;
private boolean fieldsWithErrors;
private EventModel eventModel;
private ProgramModel programModel;
private ArrayList<String> sectionsToHide;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(EVENT_ID) && getIntent().getExtras().containsKey(PROGRAM_ID)
&& getIntent().getExtras().getString(EVENT_ID) != null && getIntent().getExtras().getString(PROGRAM_ID) != null) {
eventId = getIntent().getExtras().getString(EVENT_ID);
programId = getIntent().getExtras().getString(PROGRAM_ID);
((App) getApplicationContext()).userComponent().plus(new EventSummaryModule(this, eventId)).inject(this);
} else {
finish();
}
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_event_summary);
binding.setPresenter(presenter);
binding.actionButton.setOnClickListener(v -> finish());
}
@Override
protected void onResume() {
super.onResume();
presenter.init(this, programId, eventId);
}
@Override
protected void onPause() {
presenter.onDettach();
super.onPause();
}
@Override
public void setProgram(@NonNull ProgramModel program) {
binding.setName(program.displayName());
programModel = program;
}
@Override
public void onUpdate(boolean lost, float value) {
String text = String.valueOf((int) value) + "%";
binding.progress.setText(text);
}
@Override
public void onEventSections(List<FormSectionViewModel> formSectionViewModels) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
for (FormSectionViewModel formSectionViewModel : formSectionViewModels) {
View inflatedLayout = inflater.inflate(R.layout.event_section_row, null, false);
((TextView) inflatedLayout.findViewById(R.id.section_title)).setText(formSectionViewModel.label());
binding.eventSectionRows.addView(inflatedLayout);
sections.put(formSectionViewModel.sectionUid(), inflatedLayout);
presenter.getSectionCompletion(formSectionViewModel.sectionUid());
}
}
@Override
public void setHideSection(String sectionUid) {
if (sectionsToHide == null || sectionUid == null)
sectionsToHide = new ArrayList<>();
if (sectionUid != null && !sectionsToHide.contains(sectionUid))
sectionsToHide.add(sectionUid);
}
@NonNull
@Override
public Consumer<List<FieldViewModel>> showFields(String sectionUid) {
return fields -> swap(fields, sectionUid);
}
@Override
public void onStatusChanged(EventModel event) {
Toast.makeText(this, getString(R.string.event_updated), Toast.LENGTH_SHORT).show();
new Handler().postDelayed(this::finish, 1000);
}
@Override
public void setActionButton(EventModel eventModel) {
this.eventModel = eventModel;
}
@Override
public void messageOnComplete(String content, boolean canComplete) {
this.messageOnComplete = content;
this.canComplete = canComplete;
}
@Override
public void checkAction() {
dialog = new CustomDialog(
getContext(),
getString(R.string.warning_error_on_complete_title),
messageOnComplete,
getString(R.string.button_ok),
getString(R.string.cancel),
1001,
new DialogClickListener() {
@Override
public void onPositive() {
if (canComplete)
presenter.doOnComple();
dialog.dismiss();
}
@Override
public void onNegative() {
dialog.dismiss();
}
});
if (!isEmpty(messageOnComplete))
dialog.show();
else
presenter.doOnComple();
}
@Override
public void accessDataWrite(Boolean canWrite) {
if (DateUtils.getInstance().isEventExpired(null, eventModel.completedDate(), programModel.completeEventsExpiryDays())) {
binding.actionButton.setVisibility(View.GONE);
} else {
switch (eventModel.status()) {
case ACTIVE:
binding.actionButton.setText(getString(R.string.complete_and_close));
binding.actionButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
break;
case SKIPPED:
binding.actionButton.setVisibility(View.GONE);
break;
case VISITED:
binding.actionButton.setVisibility(View.GONE); //TODO: Can this happen?
break;
case SCHEDULE:
binding.actionButton.setVisibility(View.GONE); //TODO: Can this happen?
break;
case COMPLETED:
binding.actionButton.setText(getString(R.string.re_open));
binding.actionButton.setVisibility(canWrite ? View.VISIBLE : View.GONE);
break;
}
}
}
@Override
public void fieldWithError(boolean hasError) {
fieldsWithErrors = hasError;
}
void swap(@NonNull List<FieldViewModel> updates, String sectionUid) {
View sectionView = sections.get(sectionUid);
if (sectionsToHide != null && sectionsToHide.contains(sectionUid)) {
sectionView.setVisibility(View.GONE);
sectionView.setVisibility(View.GONE);
} else
sectionView.setVisibility(View.VISIBLE);
if (sectionView.getVisibility() == View.VISIBLE) {
int completedSectionFields = calculateCompletedFields(updates);
int totalSectionFields = updates.size();
totalFields = totalFields + totalSectionFields;
totalCompletedFields = totalCompletedFields + completedSectionFields;
fieldsToCompleteBeforeClosing = fieldsToCompleteBeforeClosing + calculateMandatoryUnansweredFields(updates);
String completionText = completedSectionFields + "/" + totalSectionFields;
((TextView) sectionView.findViewById(R.id.section_percent)).setText(completionText);
sectionView.findViewById(R.id.completed_progress)
.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT, (float) totalSectionFields - (float) completedSectionFields));
sectionView.findViewById(R.id.empty_progress)
.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT, completedSectionFields));
List<String> missingMandatoryFields = new ArrayList<>();
List<String> errorFields = new ArrayList<>();
for (FieldViewModel fields : updates) {
if (fields.error() != null)
errorFields.add(fields.label());
if (fields.mandatory() && fields.value() == null)
missingMandatoryFields.add(fields.label());
}
if (!missingMandatoryFields.isEmpty() || !errorFields.isEmpty()) {
sectionView.findViewById(R.id.section_info).setVisibility(View.VISIBLE);
StringBuilder missingString = new StringBuilder(missingMandatoryFields.isEmpty() ? "" : "These fields are mandatory. Please check their values to be able to complete the event.");
for (String missinField : missingMandatoryFields) {
missingString.append(String.format("\n- %s", missinField));
}
StringBuilder errorString = new StringBuilder(errorFields.isEmpty() ? "" : "These fields contain errors. Please check their values to be able to complete the event.");
for (String errorField : errorFields) {
errorString.append(String.format("\n- %s", errorField));
}
String finalMessage = missingString.append("\n").append(errorString.toString()).toString();
sectionView.findViewById(R.id.section_info).setOnClickListener(view ->
showInfoDialog("Error", finalMessage)
);
}
}
binding.summaryHeader.setText(String.format(getString(R.string.event_summary_header), String.valueOf(totalCompletedFields), String.valueOf(totalFields)));
float completionPerone = (float) totalCompletedFields / (float) totalFields;
completionPercent = (int) (completionPerone * 100);
ProgressBarAnimation gainAnim = new ProgressBarAnimation(binding.progressGains, 0, completionPercent, false, this);
gainAnim.setDuration(PROGRESS_TIME);
binding.progressGains.startAnimation(gainAnim);
checkButton();
}
private void checkButton() {
binding.actionButton.setEnabled(fieldsToCompleteBeforeClosing <= 0 && !fieldsWithErrors);
}
private int calculateCompletedFields(@NonNull List<FieldViewModel> updates) {
int total = 0;
for (FieldViewModel fieldViewModel : updates) {
if (fieldViewModel.value() != null && !fieldViewModel.value().isEmpty())
total++;
}
return total;
}
private int calculateMandatoryUnansweredFields(@NonNull List<FieldViewModel> updates) {
int total = 0;
for (FieldViewModel fieldViewModel : updates) {
if ((fieldViewModel.value() == null || fieldViewModel.value().isEmpty()) && fieldViewModel.mandatory())
total++;
}
return total;
}
@Override
public void setTutorial() {
new Handler().postDelayed(() -> {
if (binding.actionButton.getVisibility() == View.VISIBLE) {
HelpManager.getInstance().show(getActivity(), HelpManager.TutorialName.EVENT_SUMMARY, null);
}
}, 500);
}
@Override
public void showTutorial(boolean shaked) {
setTutorial();
}
} |
arielerv/hero-journey | src/pages/login/index.js | <reponame>arielerv/hero-journey
import React from 'react';
import { useDispatch } from 'react-redux';
import authCreator from 'store/auth/actions';
import { Formik } from 'formik';
import { routes, EMAIL } from 'constant';
import { LinkButton } from 'styled/buttons';
import { push } from 'connected-react-router';
import validationSchema from './validation-schema';
import { Container, Content, WrapperImage, Logo } from './styled';
import LoginForm from './login-form';
const typeConfirm = process.env.REACT_APP_TYPE_CONFIRM;
const Login = () => {
const dispatch = useDispatch();
const goToPath = e => dispatch(push(e.target.id));
const handleSubmit = values => {
return dispatch(authCreator.authLoginRequest(values.email, values.password));
};
return (
<Container>
<Content>
<WrapperImage>
<Logo />
</WrapperImage>
<Formik
component={LoginForm}
validationSchema={validationSchema}
onSubmit={handleSubmit}
initialValues={{ email: '', password: '' }}
/>
{typeConfirm === EMAIL && (
<LinkButton
id={routes.RECOVERY_PASSWORD}
onClick={goToPath}
$bsStyle={{ fontSize: '12px' }}
>
Forgot password?
</LinkButton>
)}
<br />
<LinkButton id={routes.REGISTER} onClick={goToPath}>
Sign up
</LinkButton>
</Content>
</Container>
);
};
export default Login;
|
abu-al3ees/-data-structures-and-algorithms401 | arrayBinarySearch/array-binary-search.js | module.exports=function binarySearch(array, val) {
let upper=array.length -1;
let lower=0
while(lower<=upper){
let middel=lower+Math.floor((upper-lower)/2);
if(array[middel]==val){
return middel;
}
if(val<array[middel]){
upper=middel -1;
}else{
lower=middel+1
}
}
return -1;
} |
fvannee/cards-image-recognition | app/src/main/java/com/fnee/pbn/PbnGameTags.java | package com.fnee.pbn;/*
* File : PbnGameTags.java
* Author : <NAME>
* Date : 2007-06-24
* PBN : 2.1
*
* History
* -------
* 1999-03-28 Added GetScoreTable().
* 1999-03-28 Added GetTotalScoreTable().
* 1999-04-19 Changed PbnTagID.NUMBER_20.
* 1999-07-05 Added other tables.
* 1999-08-22 Added GetTagUse() and SetTagUse().
* 1999-09-29 Added GetTagString().
* 2002-02-17 Added tables.
* 2007-06-24 Added VERSION_21
*/
import java.lang.reflect.*;
public class PbnGameTags
{
String [] maTagValues;
int [] maUsedTags;
private PbnMoveNote [] maCallNote;
private PbnMoveNote [] maCardNote;
private PbnComment mGameComment;
private PbnComment [] maTagComments;
private PbnComment [] maCallNoteComments;
private PbnComment [] maCardNoteComments;
private PbnMoveAnno [] maCallAnno;
private PbnMoveAnno [][] maaCardAnno;
private PbnTable mActionTable;
private PbnTable mAuctionTimeTable;
private PbnTable mInstantScoreTable;
private PbnTable mPlayTimeTable;
private PbnTable mScoreTable;
private PbnTable mTotalScoreTable;
private PbnTable mOptimumPlayTable;
private PbnTable mOptimumResultTable;
public boolean [] mabHiddenSide;
public PbnGameTags()
{
maTagValues = new String[ PbnTagId.NUMBER_TOTAL ];
maUsedTags = new int[ PbnTagId.NUMBER_TOTAL ];
maCallNote = new PbnMoveNote[ PbnNote.NUMBER ];
maCardNote = new PbnMoveNote[ PbnNote.NUMBER ];
mabHiddenSide = new boolean[ PbnSide.NUMBER ];
mGameComment = new PbnComment();
maTagComments = new PbnComment[ PbnTagId.NUMBER_TOTAL ];
maCallNoteComments = new PbnComment[ PbnNote.NUMBER ];
maCardNoteComments = new PbnComment[ PbnNote.NUMBER ];
maCallAnno = new PbnMoveAnno[ 0 ];
maaCardAnno = new PbnMoveAnno[ PbnTrick.NUMBER ][ PbnSide.NUMBER ];
mActionTable = new PbnTable();
mAuctionTimeTable = new PbnTable();
mInstantScoreTable = new PbnTable();
mPlayTimeTable = new PbnTable();
mScoreTable = new PbnTable();
mTotalScoreTable = new PbnTable();
mOptimumPlayTable = new PbnTable();
mOptimumResultTable = new PbnTable();
for ( int iNote = 0; iNote < PbnNote.NUMBER; iNote++ )
{
maCallNote[ iNote ] = new PbnMoveNote();
maCardNote[ iNote ] = new PbnMoveNote();
maCallNoteComments[ iNote ] = new PbnComment();
maCardNoteComments[ iNote ] = new PbnComment();
}
for ( int iTag = 0; iTag < PbnTagId.NUMBER_TOTAL; iTag++ )
{
maUsedTags[ iTag ] = PbnTagUse.NONE;
maTagComments[ iTag ] = new PbnComment();
}
for ( int iSide = 0; iSide < PbnSide.NUMBER; iSide++ )
{
mabHiddenSide[ iSide ] = false;
for ( int iTrick = 0; iTrick < PbnTrick.NUMBER; iTrick++ )
{
maaCardAnno[ iTrick][ iSide ] = new PbnMoveAnno();
}
}
}
public boolean TagIdExist(
PbnTagId oTagId )
{
switch ( maUsedTags[ oTagId.Get() ] )
{
case PbnTagUse.NONE:
case PbnTagUse.COPY:
return false;
default:
break;
}
return true;
}
public String GetTagValue(
PbnTagId oTagId )
{
return maTagValues[ oTagId.Get() ];
}
public String GetTagString(
PbnTagId oTagId )
{
return PbnChar.FilterBackslash( GetTagValue( oTagId ) );
}
public void SetTagValue(
PbnTagId oTagId,
String oString )
{
SetTagValue( oTagId, PbnTagUse.USED, oString );
}
public void SetTagValue(
PbnTagId oTagId,
int iTagType,
String oString )
{
int index = oTagId.Get();
maTagValues[ index ] = oString; //.clone();
maUsedTags[ index ] = iTagType;
}
public int GetTagUse(
PbnTagId oTagId )
{
return maUsedTags[ oTagId.Get() ];
}
public void SetTagUse(
PbnTagId oTagId,
int iTagType )
{
maUsedTags[ oTagId.Get() ] = iTagType;
}
public boolean UsedTagValue(
PbnTagId oTagId )
{
return UsedTagValue( oTagId.Get() );
}
public boolean UsedTagValue(
int iTag )
{
return (maUsedTags[ iTag ] != PbnTagUse.NONE);
}
public void CopyTags(
PbnGameTags oGameTags )
{
for ( int iTag = 0; iTag < PbnTagId.NUMBER_TOTAL; iTag++ )
{
maUsedTags[ iTag ] = oGameTags.maUsedTags[ iTag ];
if ( UsedTagValue( iTag ) )
{
maTagValues[ iTag ] = new String( oGameTags.maTagValues[ iTag ] );
}
}
}
public void IncCallAnno()
{
maCallAnno = (PbnMoveAnno []) PbnU.ArrayInc( maCallAnno );
maCallAnno[ Array.getLength(maCallAnno)-1 ] = new PbnMoveAnno();
}
public PbnMoveAnno GetCallAnno(
int ixCall )
{
return maCallAnno[ ixCall ];
}
public PbnMoveAnno GetCardAnno(
int ixTrick,
PbnSide oSide )
{
return maaCardAnno[ ixTrick ][ oSide.Get() ];
}
public PbnMoveNote GetCallNote(
int iNote )
{
return maCallNote[ iNote-1 ];
}
public PbnMoveNote GetCardNote(
int iNote )
{
return maCardNote[ iNote-1 ];
}
public PbnComment GetGameComment()
{
return mGameComment;
}
public PbnComment GetTagComment(
PbnTagId oTagId )
{
return maTagComments[ oTagId.Get() ];
}
public PbnComment GetCallNoteComment(
int iNote )
{
return maCallNoteComments[ iNote-1 ];
}
public PbnComment GetCardNoteComment(
int iNote )
{
return maCardNoteComments[ iNote-1 ];
}
public void SetHiddenSide(
PbnSide oSide,
boolean bHidden )
{
mabHiddenSide[ oSide.Get() ] = bHidden;
}
public void PutComment(
String oString,
int iSection,
int iType,
int iTagIndex,
int iNrCalls,
int iNrTricks,
PbnSide oPlaySide )
{
switch ( iSection )
{
case PbnGen.SECTION_IDENT:
switch ( iType )
{
case PbnCommentAdmin.TYPE_IDENT:
mGameComment.Put( oString );
break;
case PbnCommentAdmin.TYPE_TAG:
maTagComments[ iTagIndex ].Put( oString );
break;
}
break;
case PbnGen.SECTION_AUCTION:
switch ( iType )
{
case PbnCommentAdmin.TYPE_TAG:
maTagComments[ iTagIndex ].Put( oString );
break;
case PbnCommentAdmin.TYPE_NOTE_TAG:
maCallNoteComments[ iTagIndex ].Put( oString );
break;
default:
maCallAnno[ iNrCalls ].PutComment( oString, iType );
break;
}
break;
case PbnGen.SECTION_PLAY:
switch ( iType )
{
case PbnCommentAdmin.TYPE_TAG:
maTagComments[ iTagIndex ].Put( oString );
break;
case PbnCommentAdmin.TYPE_NOTE_TAG:
maCardNoteComments[ iTagIndex ].Put( oString );
break;
default:
maaCardAnno[iNrTricks][oPlaySide.Get()].PutComment( oString, iType );
break;
}
break;
}
}
public PbnTable GetInstantScoreTable()
{
return mInstantScoreTable;
}
public PbnTable GetActionTable()
{
return mActionTable;
}
public PbnTable GetScoreTable()
{
return mScoreTable;
}
public PbnTable GetTotalScoreTable()
{
return mTotalScoreTable;
}
public PbnTable GetOptimumPlayTable()
{
return mOptimumPlayTable;
}
public PbnTable GetOptimumResultTable()
{
return mOptimumResultTable;
}
public PbnTable GetTable(
PbnTagId oTagId )
{
switch ( oTagId.Get() )
{
case PbnTagId.ACTIONTABLE:
return mActionTable;
case PbnTagId.AUCTIONTIMETABLE:
return mAuctionTimeTable;
case PbnTagId.INSTANTSCORETABLE:
return mInstantScoreTable;
case PbnTagId.PLAYTIMETABLE:
return mPlayTimeTable;
case PbnTagId.SCORETABLE:
return mScoreTable;
case PbnTagId.TOTALSCORETABLE:
return mTotalScoreTable;
case PbnTagId.OPTIMUMPLAYTABLE:
return mOptimumPlayTable;
case PbnTagId.OPTIMUMRESULTTABLE:
return mOptimumResultTable;
default:
return null;
}
}
public void InheritCopy(
PbnGameTags oGameTags,
PbnTagId oTagId )
{
int iTag = oTagId.Get();
maUsedTags[ iTag ] = PbnTagUse.COPY;
if ( oGameTags.UsedTagValue( iTag ) )
{
maTagValues[ iTag ] = new String( oGameTags.maTagValues[ iTag ] );
}
else
{
maTagValues[ iTag ] = "";
}
}
}
|
SHIVJITH/Odoo_Machine_Test | addons/sale_timesheet_purchase/models/project_overview.py | <reponame>SHIVJITH/Odoo_Machine_Test<gh_stars>0
# -*- coding: utf-8 -*-
from odoo import _, models
from odoo.addons.sale_timesheet.models.project_overview import _to_action_data
class Project(models.Model):
_inherit = 'project.project'
def _plan_get_stat_button(self):
stat_buttons = super(Project, self)._plan_get_stat_button()
if self.env.user.has_group('purchase.group_purchase_user'):
accounts = self.mapped('analytic_account_id.id')
purchase_order_lines = self.env['purchase.order.line'].search([('account_analytic_id', 'in', accounts)])
purchase_orders = purchase_order_lines.mapped('order_id')
if purchase_orders:
stat_buttons.append({
'name': _('Purchase Orders'),
'count': len(purchase_orders),
'icon': 'fa fa-shopping-cart',
'action': _to_action_data('purchase.order',
domain=[('id', 'in', purchase_orders.ids)],
context={'create': False, 'edit': False, 'delete': False}
)
})
account_invoice_lines = self.env['account.move.line'].search(
[('analytic_account_id', 'in', accounts),
('move_id.move_type', 'in', ['in_invoice', 'in_refund'])])
account_invoices = account_invoice_lines.mapped('move_id')
if account_invoices:
stat_buttons.append({
'name': _('Vendor Bills'),
'count': len(account_invoices),
'icon': 'fa fa-pencil-square-o',
'action': _to_action_data(
action=self.env.ref('account.action_move_in_invoice_type'),
domain=[('id', 'in', account_invoices.ids)],
context={'create': False, 'edit': False, 'delete': False}
)})
return stat_buttons
|
CarbonDDR/al-go-rithms | cryptography/rot13_cipher/go/rot13_test.go | package main
import "testing"
var tests = []struct {
input string
expected string
}{
{"AAA", "NNN"},
{"NNN", "AAA"},
{"BBB", "OOO"},
{"OOO", "BBB"},
{"bbb", "ooo"},
{"ooo", "bbb"},
{"helloworld", "uryybjbeyq"},
{"uryybjbeyq", "helloworld"},
{"Guvf vf harapelcgrq fnzcyr grkg", "This is unencrypted sample text"},
{"This is unencrypted sample text", "Guvf vf harapelcgrq fnzcyr grkg"},
}
func TestRot13(t *testing.T) {
for _, test := range tests {
if actual := Rot13(test.input); actual != test.expected {
t.Errorf("Rot13(%q) = %q, expected %q.",
test.input, actual, test.expected)
}
}
}
|
syx01/Learn | src/main/java/com/learn/designpatten/strategy/sale/Context.java | package com.learn.designpatten.strategy.sale;
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public double sale(double price) {
return this.strategy.sale(price);
}
}
|
crank17/UniProjects | engg2800/embeddedsystem/LCD_funcs.c | <gh_stars>0
/*
* LCD_funcs.c
*
* Created: 25/10/2020 4:20:00 PM
* Author: <NAME>
*/
#include <avr/io.h>
#include <avr/io.h>
#include <u8g2.h>
#include "u8x8_avr.h"
#include <util/delay.h>
#define DISPLAY_CLK_DIR DDRB
#define DISPLAY_CLK_PORT PORTB
#define DISPLAY_CLK_PIN 5
#define DISPLAY_DATA_DIR DDRB
#define DISPLAY_DATA_PORT PORTB
#define DISPLAY_DATA_PIN 3
#define DISPLAY_CS_DIR DDRB
#define DISPLAY_CS_PORT PORTB
#define DISPLAY_CS_PIN 2
#define DISPLAY_DC_DIR DDRB
#define DISPLAY_DC_PORT PORTB
#define DISPLAY_DC_PIN 6
#define DISPLAY_RESET_DIR DDRB
#define DISPLAY_RESET_PORT PORTB
#define DISPLAY_RESET_PIN 0
#define P_CPU_NS (1000000000UL / F_CPU)
u8g2_t u8g2;
/*
* A U8G2 library delay that will be used to render the appropriate images to the LCD.
*/
uint8_t u8x8_avr_delay(u8x8_t *u8x8, uint8_t msg, uint8_t arg_int, void *arg_ptr)
{
uint8_t cycles;
switch(msg)
{
case U8X8_MSG_DELAY_NANO: // delay arg_int * 1 nano second
// At 20Mhz, each cycle is 50ns, the call itself is slower.
break;
case U8X8_MSG_DELAY_100NANO: // delay arg_int * 100 nano seconds
// Approximate best case values...
#define CALL_CYCLES 26UL
#define CALC_CYCLES 4UL
#define RETURN_CYCLES 4UL
#define CYCLES_PER_LOOP 4UL
cycles = (100UL * arg_int) / (P_CPU_NS * CYCLES_PER_LOOP);
if(cycles > CALL_CYCLES + RETURN_CYCLES + CALC_CYCLES)
break;
__asm__ __volatile__ (
"1: sbiw %0,1" "\n\t" // 2 cycles
"brne 1b" : "=w" (cycles) : "0" (cycles) // 2 cycles
);
break;
case U8X8_MSG_DELAY_10MICRO: // delay arg_int * 10 micro seconds
for(int i=0 ; i < arg_int ; i++)
_delay_us(10);
break;
case U8X8_MSG_DELAY_MILLI: // delay arg_int * 1 milli second
for(int i=0 ; i < arg_int ; i++)
_delay_ms(1);
break;
default:
return 0;
}
return 1;
}
/*
* This function is used to set and reset GPIOs (in the case of software implemented interfaces),
e.g. a software I2C, SPI, 8080 or 6800 interface.
*/
uint8_t u8x8_avr_gpio_and_delay(u8x8_t *u8x8, uint8_t msg, uint8_t arg_int, void *arg_ptr)
{
// Re-use library for delays
switch(msg)
{
case U8X8_MSG_GPIO_AND_DELAY_INIT: // called once during init phase of u8g2/u8x8
DISPLAY_CLK_DIR |= 1<<DISPLAY_CLK_PIN;
DISPLAY_DATA_DIR |= 1<<DISPLAY_DATA_PIN;
DISPLAY_CS_DIR |= 1<<DISPLAY_CS_PIN;
DISPLAY_DC_DIR |= 1<<DISPLAY_DC_PIN;
DISPLAY_RESET_DIR |= 1<<DISPLAY_RESET_PIN;
break; // can be used to setup pins
case U8X8_MSG_GPIO_SPI_CLOCK: // Clock pin: Output level in arg_int
if(arg_int)
DISPLAY_CLK_PORT |= (1<<DISPLAY_CLK_PIN);
else
DISPLAY_CLK_PORT &= ~(1<<DISPLAY_CLK_PIN);
break;
case U8X8_MSG_GPIO_SPI_DATA: // MOSI pin: Output level in arg_int
if(arg_int)
DISPLAY_DATA_PORT |= (1<<DISPLAY_DATA_PIN);
else
DISPLAY_DATA_PORT &= ~(1<<DISPLAY_DATA_PIN);
break;
case U8X8_MSG_GPIO_CS: // CS (chip select) pin: Output level in arg_int
if(arg_int)
DISPLAY_CS_PORT |= (1<<DISPLAY_CS_PIN);
else
DISPLAY_CS_PORT &= ~(1<<DISPLAY_CS_PIN);
break;
case U8X8_MSG_GPIO_DC: // DC (data/cmd, A0, register select) pin: Output level in arg_int
if(arg_int)
DISPLAY_DC_PORT |= (1<<DISPLAY_DC_PIN);
else
DISPLAY_DC_PORT &= ~(1<<DISPLAY_DC_PIN);
break;
case U8X8_MSG_GPIO_RESET: // Reset pin: Output level in arg_int
if(arg_int)
DISPLAY_RESET_PORT |= (1<<DISPLAY_RESET_PIN);
else
DISPLAY_RESET_PORT &= ~(1<<DISPLAY_RESET_PIN);
break;
default:
if (u8x8_avr_delay(u8x8, msg, arg_int, arg_ptr)) // check for any delay msgs
return 1;
u8x8_SetGPIOResult(u8x8, 1); // default return value
break;
}
return 1;
} |
zemora/Hyperbolic | hyperbolic/__init__.py | <reponame>zemora/Hyperbolic<gh_stars>10-100
from . import util
from . import euclid
from . import poincare
|
uniqss/jasslua | projects/jasslua/src/mapdensity.cpp | <gh_stars>1-10
#include "mapdensity.h"
|
deveshbajpai19/CodeForces | problems/A/PensAndPencils.py | __author__ = '<NAME>'
'''
https://codeforces.com/problemset/problem/1244/A
Solution: If we have to take m notes and one stationary item can write n notes, the no. of those stationary items needed
is ceil(m/n) = (m + n - 1) / n. This way we calculate the minimum pens and pencils needed. If their sum is <= k, we return
that as the answer, else it is -1. Note that the question doesn't require minimization but it seems straightforward for
calculation purposes.
'''
def solve(a, b, c, d, k):
pens = (a + c - 1) / c
pencils = (b + d - 1) / d
return -1 if pens + pencils > k else str(pens) + " " + str(pencils)
if __name__ == "__main__":
t = int(raw_input())
for _ in xrange(0, t):
a, b, c, d, k = map(int, raw_input().split(" "))
print solve(a, b, c, d, k)
|
shuwill/spreadme-framework | spreadme-commons/src/main/java/org/spreadme/io/reactor/IOSessionBufferStatus.java | <reponame>shuwill/spreadme-framework<filename>spreadme-commons/src/main/java/org/spreadme/io/reactor/IOSessionBufferStatus.java<gh_stars>0
package org.spreadme.io.reactor;
/**
* @description:
* @author shuwei.wang
*/
public interface IOSessionBufferStatus {
boolean hasBufferedInput();
boolean hasBufferedOutput();
}
|
tfn10/beecrowd | iniciante/python/2140-duas-notas.py | def duas_notas():
notas_disponiveis = [2, 5, 10, 20, 50, 100]
while True:
entrada = list(map(int, input().split()))
compra_pelo_cliente = entrada[0]
valor_pago = entrada[1]
devolver_troco_exato = False
if compra_pelo_cliente == valor_pago == 0:
break
troco = valor_pago - compra_pelo_cliente
for i in range(len(notas_disponiveis)):
for j in range(1, len(notas_disponiveis)):
if troco / (notas_disponiveis[i]+notas_disponiveis[j]) == 1:
devolver_troco_exato = True
break
if devolver_troco_exato:
break
if devolver_troco_exato:
print('possible')
else:
print('impossible')
duas_notas()
|
sandro78/2x2is4_android | android/pirates_version/src/com/oktogames/app_2x2is4/light/engine/MultiplicationTableEngineImpl.java | <reponame>sandro78/2x2is4_android
/**
MIT License
Copyright (c) 2018 OkToGames
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 com.oktogames.app_2x2is4.light.engine;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
/**
* Old purpose JNI stub for MultiplicationTableEngineImpl class C++.
* Load libraries code:
* <code>static {
* System.loadLibrary("stlport");
* System.loadLibrary("multitableengine");
* System.loadLibrary("multitableengine-jni");
* }</code>
* <p/>
* New appointment java realisation game engine.
*/
public class MultiplicationTableEngineImpl {
public final static int MAX_TIMES_TABLE_NUMBER = 12;
public final static int MAX_HISTORY_SIZE = 10;
public final static int MAX_NUMBER_IN_TIMES_TABLE = 12;
public final static int MAX_OPENED_TIMES_TABLE_NUMBER = 12;
private OperationType operationType;
private int number;
private GameLevel gameLevel;
private static Random random = new Random();
private ArrayList<CombinationImpl> combinationImplsList = new ArrayList<CombinationImpl>();
private int lastTimesTableNumber;
public MultiplicationTableEngineImpl(int number, OperationType type, GameLevel lavel, int lastTimesTableNumber) {
this.operationType = type;
this.gameLevel = lavel;
this.number = number;
this.lastTimesTableNumber = lastTimesTableNumber;
assert (number >= 2 && number <= MAX_OPENED_TIMES_TABLE_NUMBER);
fillCombinationsList();
}
public MultiplicationTableEngineImpl(int number, OperationType type, GameLevel lavel) {
this(number, type, lavel, MAX_NUMBER_IN_TIMES_TABLE);
}
public MultiplicationTableEngineImpl(){
number = 2;
operationType = OperationType.UNKNOWN;
gameLevel = GameLevel.EASY;
lastTimesTableNumber = 3;
}
private void fillCombinationsList() {
switch (operationType)
{
case MULTIPLICATION:
for (int i = 2; i <= number; ++i) {
for (int j = 2; j <= lastTimesTableNumber; ++j) {
combinationImplsList.add(new CombinationImpl(operationType, i, j, i * j));
}
}
break;
case DIVISION:
for (int i = 2; i <= number; ++i) {
for (int j = 2; j <= lastTimesTableNumber; ++j) {
combinationImplsList.add(new CombinationImpl(operationType, i * j, i, j));
}
}
break;
default:
assert(false);
}
Collections.shuffle(combinationImplsList);
}
public static int generateNumber() {
return Math.abs(random.nextInt());
}
public CombinationImpl getCombination() {
if (0 == combinationImplsList.size())
return CombinationImpl.nullCombination();
CombinationImpl combinationImpl = combinationImplsList.get(combinationImplsList.size()-1);
combinationImplsList.remove(combinationImplsList.size()-1);
return combinationImpl;
}
public int combinationsCount() {
return combinationImplsList.size();
}
public void reinit() {
combinationImplsList.clear();
fillCombinationsList();
}
public int getShotsForWin() {
return number - 1;
}
public int getHealthStatus(int shotsWereDone) {
if (0 == shotsWereDone)
return 0;
int shotsForWin = getShotsForWin();
if (shotsForWin == shotsWereDone)
return -1;
return shotsWereDone * ((MAX_TIMES_TABLE_NUMBER - 1) / shotsForWin);
}
public CanonReadiness getMyCanonReadiness(boolean needMakeShot) {
if (needMakeShot) needMakeShot = false;
int delta = combinationImplsList.size() % (lastTimesTableNumber - 1);
int correctDelta = MAX_NUMBER_IN_TIMES_TABLE/lastTimesTableNumber;
if (0 == delta) {
if ((number - 1) * (lastTimesTableNumber - 1) == combinationImplsList.size())
return new CanonReadiness(needMakeShot, 0);
else {
return new CanonReadiness(true, ((lastTimesTableNumber - 1)*correctDelta));
}
} else {
return new CanonReadiness(needMakeShot, (lastTimesTableNumber - 1 - delta)*correctDelta);
}
}
public class CanonReadiness {
private boolean needMakeShot = false;
private int readiness;
public CanonReadiness(boolean needMakeShot, int readiness) {
this.needMakeShot = needMakeShot;
this.readiness = readiness;
}
public boolean isNeedMakeShot() {
return needMakeShot;
}
public int getReadiness() {
return readiness;
}
}
private int getPirateCanonRatio() {
switch (gameLevel) {
case EASY:
return 4;
case MEDIUM:
return 3;
default:
return 2;
}
}
public CanonReadiness getPirateCanonReadiness(int timeCounter, boolean makeShotSign){
if (makeShotSign) makeShotSign = false;
if (0 == timeCounter/getPirateCanonRatio())
return new CanonReadiness(makeShotSign, 0);
int delta = timeCounter/getPirateCanonRatio()%(lastTimesTableNumber-1);
int correctDelta = MAX_NUMBER_IN_TIMES_TABLE/lastTimesTableNumber;
if (0 == delta) {
if (0 == timeCounter%getPirateCanonRatio())
makeShotSign = true;
return new CanonReadiness(makeShotSign, 0 == timeCounter%getPirateCanonRatio() ?
(lastTimesTableNumber-1)*correctDelta : 0);
}
else
return new CanonReadiness(makeShotSign, delta*correctDelta);
}
public GameLevel getGameLevel() {
return gameLevel;
}
}
|
RuntimeConverter/RuntimeConverterLaravelJava | laravel-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/Illuminate/namespaces/Support/namespaces/Testing/namespaces/Fakes/classes/BusFake.java | <reponame>RuntimeConverter/RuntimeConverterLaravelJava<filename>laravel-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/Illuminate/namespaces/Support/namespaces/Testing/namespaces/Fakes/classes/BusFake.java
package com.project.convertedCode.globalNamespace.namespaces.Illuminate.namespaces.Support.namespaces.Testing.namespaces.Fakes.classes;
import com.runtimeconverter.runtime.references.ReferenceContainer;
import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs;
import com.runtimeconverter.runtime.references.BasicReferenceContainer;
import com.runtimeconverter.runtime.classes.StaticBaseClass;
import com.runtimeconverter.runtime.nativeClasses.Closure;
import com.runtimeconverter.runtime.classes.RuntimeClassBase;
import com.runtimeconverter.runtime.RuntimeEnv;
import com.runtimeconverter.runtime.passByReference.RuntimeArgsWithReferences;
import com.project.convertedCode.globalNamespace.namespaces.Illuminate.namespaces.Contracts.namespaces.Bus.classes.Dispatcher;
import com.runtimeconverter.runtime.references.ReferenceClassProperty;
import com.runtimeconverter.runtime.ZVal;
import com.runtimeconverter.runtime.reflection.ReflectionClassData;
import com.runtimeconverter.runtime.annotations.ConvertedParameter;
import com.runtimeconverter.runtime.arrays.ZPair;
import com.runtimeconverter.runtime.nativeFunctions.runtime.function_get_class;
import java.lang.invoke.MethodHandles;
import com.runtimeconverter.runtime.nativeFunctions.typeIsA.function_is_numeric;
import com.project.convertedCode.globalNamespace.namespaces.PHPUnit.namespaces.Framework.classes.Assert;
import com.runtimeconverter.runtime.interfaces.ContextConstants;
import com.runtimeconverter.runtime.classes.NoConstructor;
import com.runtimeconverter.runtime.arrays.ArrayAction;
import com.runtimeconverter.runtime.annotations.ConvertedMethod;
import com.project.convertedCode.globalNamespace.functions.collect;
import static com.runtimeconverter.runtime.ZVal.arrayActionR;
import static com.runtimeconverter.runtime.ZVal.toStringR;
import static com.runtimeconverter.runtime.ZVal.assignParameter;
/*
Converted with The Runtime Converter (runtimeconverter.com)
vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/BusFake.php
*/
public class BusFake extends RuntimeClassBase implements Dispatcher {
public Object commands = ZVal.newArray();
public BusFake(RuntimeEnv env, Object... args) {
super(env);
}
public BusFake(NoConstructor n) {
super(n);
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "command")
@ConvertedParameter(
index = 1,
name = "callback",
defaultValue = "NULL",
defaultValueType = "constant"
)
public Object assertDispatched(RuntimeEnv env, Object... args) {
Object command = assignParameter(args, 0, false);
Object callback = assignParameter(args, 1, true);
if (null == callback) {
callback = ZVal.getNull();
}
if (function_is_numeric.f.env(env).call(callback).getBool()) {
return ZVal.assign(this.assertDispatchedTimes(env, command, callback));
}
Assert.runtimeStaticObject.assertTrue(
env,
ZVal.isGreaterThan(
env.callMethod(
this.dispatched(env, command, callback), "count", BusFake.class),
'>',
0),
"The expected [" + toStringR(command, env) + "] job was not dispatched.");
return null;
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "command")
@ConvertedParameter(index = 1, name = "times", defaultValue = "1", defaultValueType = "number")
protected Object assertDispatchedTimes(RuntimeEnv env, Object... args) {
Object command = assignParameter(args, 0, false);
Object times = assignParameter(args, 1, true);
if (null == times) {
times = 1;
}
Object count = null;
Assert.runtimeStaticObject.assertTrue(
env,
ZVal.strictEqualityCheck(
count =
env.callMethod(
this.dispatched(env, command), "count", BusFake.class),
"===",
times),
"The expected ["
+ toStringR(command, env)
+ "] job was pushed "
+ toStringR(count, env)
+ " times instead of "
+ toStringR(times, env)
+ " times.");
return null;
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "command")
@ConvertedParameter(
index = 1,
name = "callback",
defaultValue = "NULL",
defaultValueType = "constant"
)
public Object assertNotDispatched(RuntimeEnv env, Object... args) {
Object command = assignParameter(args, 0, false);
Object callback = assignParameter(args, 1, true);
if (null == callback) {
callback = ZVal.getNull();
}
Assert.runtimeStaticObject.assertTrue(
env,
ZVal.strictEqualityCheck(
env.callMethod(
this.dispatched(env, command, callback), "count", BusFake.class),
"===",
0),
"The unexpected [" + toStringR(command, env) + "] job was dispatched.");
return null;
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "command")
@ConvertedParameter(
index = 1,
name = "callback",
defaultValue = "NULL",
defaultValueType = "constant"
)
public Object dispatched(RuntimeEnv env, Object... args) {
ContextConstants runtimeConverterFunctionClassConstants =
new ContextConstants()
.setDir("/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes")
.setFile(
"/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/BusFake.php");
Object command = assignParameter(args, 0, false);
Object callback = assignParameter(args, 1, true);
if (null == callback) {
callback = ZVal.getNull();
}
Object ternaryExpressionTemp = null;
if (!ZVal.isTrue(this.hasDispatched(env, command))) {
return ZVal.assign(collect.f.env(env).call().value());
}
callback =
ZVal.assign(
ZVal.isTrue(ternaryExpressionTemp = callback)
? ternaryExpressionTemp
: new Closure(
env,
runtimeConverterFunctionClassConstants,
"Illuminate\\Support\\Testing\\Fakes",
this) {
@Override
@ConvertedMethod
public Object run(
RuntimeEnv env,
Object thisvar,
PassByReferenceArgs runtimePassByReferenceArgs,
Object... args) {
return ZVal.assign(true);
}
});
return ZVal.assign(
env.callMethod(
collect.f
.env(env)
.call(
new ReferenceClassProperty(this, "commands", env)
.arrayGet(env, command))
.value(),
"filter",
BusFake.class,
new Closure(
env,
runtimeConverterFunctionClassConstants,
"Illuminate\\Support\\Testing\\Fakes",
this) {
@Override
@ConvertedMethod
@ConvertedParameter(index = 0, name = "command")
public Object run(
RuntimeEnv env,
Object thisvar,
PassByReferenceArgs runtimePassByReferenceArgs,
Object... args) {
ReferenceContainer command =
new BasicReferenceContainer(
assignParameter(args, 0, false));
Object callback = null;
callback = this.contextReferences.getCapturedValue("callback");
return ZVal.assign(
env.callFunctionDynamic(
callback,
new RuntimeArgsWithReferences()
.add(0, command),
command.getObject())
.value());
}
}.use("callback", callback)));
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "command")
public Object hasDispatched(RuntimeEnv env, Object... args) {
Object command = assignParameter(args, 0, false);
return ZVal.assign(
ZVal.toBool(
arrayActionR(
ArrayAction.ISSET,
new ReferenceClassProperty(this, "commands", env),
env,
command))
&& ZVal.toBool(
!arrayActionR(
ArrayAction.EMPTY,
new ReferenceClassProperty(this, "commands", env),
env,
command)));
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "command")
public Object dispatch(RuntimeEnv env, Object... args) {
Object command = assignParameter(args, 0, false);
return ZVal.assign(this.dispatchNow(env, command));
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "command")
@ConvertedParameter(
index = 1,
name = "handler",
defaultValue = "NULL",
defaultValueType = "constant"
)
public Object dispatchNow(RuntimeEnv env, Object... args) {
Object command = assignParameter(args, 0, false);
Object handler = assignParameter(args, 1, true);
if (null == handler) {
handler = ZVal.getNull();
}
new ReferenceClassProperty(this, "commands", env)
.arrayAppend(env, function_get_class.f.env(env).call(command).value())
.set(command);
return null;
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "pipes", typeHint = "array")
public Object pipeThrough(RuntimeEnv env, Object... args) {
Object pipes = assignParameter(args, 0, false);
return null;
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "command")
public Object hasCommandHandler(RuntimeEnv env, Object... args) {
Object command = assignParameter(args, 0, false);
return ZVal.assign(false);
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "command")
public Object getCommandHandler(RuntimeEnv env, Object... args) {
Object command = assignParameter(args, 0, false);
return ZVal.assign(false);
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "map", typeHint = "array")
public Object map(RuntimeEnv env, Object... args) {
Object map = assignParameter(args, 0, false);
return ZVal.assign(this);
}
public static final Object CONST_class = "Illuminate\\Support\\Testing\\Fakes\\BusFake";
// Runtime Converter Internals
// RuntimeStaticCompanion contains static methods
// RequestStaticProperties contains static (per-request) properties
// ReflectionClassData contains php reflection data used by the runtime library
public static class RuntimeStaticCompanion extends StaticBaseClass {
private static final MethodHandles.Lookup staticCompanionLookup = MethodHandles.lookup();
}
public static final RuntimeStaticCompanion runtimeStaticObject = new RuntimeStaticCompanion();
private static final ReflectionClassData runtimeConverterReflectionData =
ReflectionClassData.builder()
.setName("Illuminate\\Support\\Testing\\Fakes\\BusFake")
.setLookup(
BusFake.class,
MethodHandles.lookup(),
RuntimeStaticCompanion.staticCompanionLookup)
.setLocalProperties("commands")
.setFilename(
"vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/BusFake.php")
.addInterface("Illuminate\\Contracts\\Bus\\Dispatcher")
.get();
@Override
public ReflectionClassData getRuntimeConverterReflectionData() {
return runtimeConverterReflectionData;
}
@Override
public Object converterRuntimeCallExtended(
RuntimeEnv env,
String method,
Class<?> caller,
PassByReferenceArgs passByReferenceArgs,
Object... args) {
return RuntimeClassBase.converterRuntimeCallExtendedWithDataStatic(
this,
runtimeConverterReflectionData,
env,
method,
caller,
passByReferenceArgs,
args);
}
}
|
joostoudeman/external-resources | api/src/test/java/org/onehippo/forge/externalresource/api/scheduler/ExternalResourceScheduler.java | <gh_stars>0
package org.onehippo.forge.externalresource.api.scheduler;
import org.quartz.Scheduler;
import org.quartz.core.QuartzScheduler;
import org.quartz.impl.StdScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.Session;
/**
* @version $Id: ExternalResourceScheduler.java 310 2015-02-24 13:46:19Z gilgamesh $
*/
public class ExternalResourceScheduler extends StdScheduler implements Scheduler {
@SuppressWarnings({"UnusedDeclaration"})
private static Logger log = LoggerFactory.getLogger(ExternalResourceScheduler.class);
private QuartzScheduler qs;
/**
* <p>
* Construct a <code>StdScheduler</code> instance to proxy the given
* <code>QuartzScheduler</code> instance, and with the given <code>SchedulingContext</code>.
* </p>
*/
public ExternalResourceScheduler(QuartzScheduler sched) {
super(sched);
this.qs = sched;
}
public ExternalResourceScheduler(ExternalResourceScheduler sched) {
this(sched.qs);
}
}
|
lifning/gorilla-audio | contrib/mp3/mp3dec.c | #include "gorilla/ga.h"
#define DR_MP3_IMPLEMENTATION
#define DR_MP3_NO_STDIO
#define DRMP3_API static
#include "dr_mp3.h"
struct GaSampleSourceContext {
drmp3 mp3;
GaMutex mutex;
GaDataSource *data_src;
};
static void *mp3_alloc(ga_usize sz, void *data) { return ga_alloc(sz); }
static void *mp3_realloc(void *p, ga_usize sz, void *data) { return ga_realloc(p, sz); }
static void mp3_free(void *p, void *data) { return ga_free(p); }
static drmp3_allocation_callbacks mp3_allocator = {.onMalloc = mp3_alloc, .onRealloc = mp3_realloc, .onFree = mp3_free};
static ga_usize mp3_read(void *ctx, void *buf, ga_usize l) {
return ga_data_source_read(ctx, buf, 1, l);
}
static drmp3_bool32 mp3_seek(void *ctx, int offset, drmp3_seek_origin origin) {
switch (origin) {
case drmp3_seek_origin_start: return ga_isok(ga_data_source_seek(ctx, offset, GaSeekOrigin_Set));
case drmp3_seek_origin_current: return ga_isok(ga_data_source_seek(ctx, offset, GaSeekOrigin_Cur));
default: return 0;
}
}
static ga_usize ss_read(GaSampleSourceContext *ctx, void *dst, ga_usize num_frames, GaCbOnSeek onseek, void *seek_ctx) {
ga_mutex_lock(ctx->mutex);
drmp3_uint64 res = drmp3_read_pcm_frames_s16(&ctx->mp3, num_frames, dst);
ga_mutex_unlock(ctx->mutex);
return res;
}
static ga_bool ss_end(GaSampleSourceContext *ctx) {
return ctx->mp3.atEnd;
}
static ga_result ss_seek(GaSampleSourceContext *ctx, ga_usize frame_offset) {
ga_mutex_lock(ctx->mutex);
drmp3_bool32 res = drmp3_seek_to_pcm_frame(&ctx->mp3, frame_offset);
ga_mutex_unlock(ctx->mutex);
return res ? GA_OK : GA_ERR_GENERIC;
}
static ga_result ss_tell(GaSampleSourceContext *ctx, ga_usize *cur, ga_usize *total) {
if (total && !ctx->mp3.onSeek) return GA_ERR_MIS_UNSUP;
ga_result res = GA_OK;
ga_mutex_lock(ctx->mutex);
if (cur) *cur = ctx->mp3.currentPCMFrame;
if (total) {
drmp3_uint64 tot_frames_pcm;
if (!drmp3_get_mp3_and_pcm_frame_count(&ctx->mp3, NULL, &tot_frames_pcm)) res = GA_ERR_GENERIC;
*total = tot_frames_pcm;
}
ga_mutex_unlock(ctx->mutex);
return res;
}
static void ss_close(GaSampleSourceContext *ctx) {
ga_data_source_release(ctx->data_src);
ga_mutex_destroy(ctx->mutex);
drmp3_uninit(&ctx->mp3);
ga_free(ctx);
}
GaSampleSource *ga_contrib_sample_source_create_mp3(GaDataSource *data_src) {
GaSampleSourceContext *ctx = ga_alloc(sizeof(GaSampleSourceContext));
if (!ctx) return NULL;
if (!ga_isok(ga_mutex_create(&ctx->mutex))) goto fail;
ctx->data_src = data_src;
if (!drmp3_init(&ctx->mp3, mp3_read, (ga_data_source_flags(data_src) & GaDataAccessFlag_Seekable) ? mp3_seek : NULL, data_src, &mp3_allocator)) goto fail;
GaSampleSourceCreationMinutiae m = {
.read = ss_read,
.end = ss_end,
.tell = ss_tell,
.close = ss_close,
.context = ctx,
.format = {.num_channels = ctx->mp3.channels, .sample_fmt = GaSampleFormat_S16, .frame_rate = ctx->mp3.sampleRate},
.threadsafe = ga_true,
};
if (ga_data_source_flags(data_src) & GaDataAccessFlag_Seekable) m.seek = ss_seek;
GaSampleSource *ret = ga_sample_source_create(&m);
if (!ret) goto fail;
ga_data_source_acquire(data_src);
return ret;
fail:
ga_mutex_destroy(ctx->mutex);
ga_free(ctx);
return NULL;
}
|
Ibuki-Suika/THEngine_Empty | Game/src/THEngine/Tween/THConcreteTween.h | #ifndef THCONCRETETWEEN_H
#define THCONCRETETWEEN_H
#include "THTween.h"
#include "THTweener.h"
#include <Math\THVector.h>
namespace THEngine
{
class Delay : public TweenUnit
{
public:
Delay(int duration);
virtual ~Delay();
virtual void OnStart() override;
};
/////////////////////////////////////////////////////
class MoveTo : public TweenUnit
{
protected:
Vector3f position;
Tweener::Type type;
public:
MoveTo(Vector3f position, int duration, Tweener::Type type);
virtual ~MoveTo();
virtual void OnStart() override;
};
////////////////////////////////////////////////////
class MoveBy : public TweenUnit
{
protected:
Vector3f position;
Tweener::Type type;
public:
MoveBy(Vector3f position, int duration, Tweener::Type type);
virtual ~MoveBy();
virtual void OnStart() override;
};
////////////////////////////////////////////////////
class FadeTo : public TweenUnit
{
protected:
float alpha;
Tweener::Type type;
public:
FadeTo(float alpha, int duration, Tweener::Type type);
virtual ~FadeTo();
virtual void OnStart() override;
};
////////////////////////////////////////////////////
class FadeOut : public TweenUnit
{
protected:
Tweener::Type type;
public:
FadeOut(int duration, Tweener::Type type);
virtual ~FadeOut();
virtual void OnStart() override;
virtual void OnFinish() override;
};
/////////////////////////////////////////////////////
class ColorTo : public TweenUnit
{
protected:
Vector3f color;
Tweener::Type type;
public:
ColorTo(Vector3f color, int duration, Tweener::Type type);
virtual ~ColorTo();
virtual void OnStart() override;
};
/////////////////////////////////////////////////////
class ScaleTo : public TweenUnit
{
protected:
Vector3f scale;
Tweener::Type type;
public:
ScaleTo(Vector3f scale, int duration, Tweener::Type type);
virtual ~ScaleTo();
virtual void OnStart() override;
};
/////////////////////////////////////////////////////
class Rotate2D : public TweenUnit
{
protected:
float rotation;
Tweener::Type type;
public:
Rotate2D(float rotation, int duration, Tweener::Type type);
virtual ~Rotate2D();
virtual void OnStart() override;
};
/////////////////////////////////////////////////////
class SpeedTo : public TweenUnit
{
protected:
float speed;
Tweener::Type type;
public:
SpeedTo(float rotation, int duration, Tweener::Type type);
virtual ~SpeedTo();
virtual void OnStart() override;
};
}
#endif |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.