repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
hnatt/tdlib-schema
|
lib/tdlib/types/update/connection_state.rb
|
module TD::Types
# The connection state has changed.
# This update must be used only to show a human-readable description of the connection state.
#
# @attr state [TD::Types::ConnectionState] The new connection state.
class Update::ConnectionState < Update
attribute :state, TD::Types::ConnectionState
end
end
|
hydrognomik/cssnano
|
site/src/layouts/App/Index.js
|
import * as React from 'react';
import Sticky from 'react-sticky-el';
import Analytics from '../../components/Analytics';
import Container from '../../components/Container';
import DefaultHeadMeta from '../../components/DefaultHeadMeta';
import Content from '../../components/Content';
import Header from '../../components/Header';
import Footer from '../../components/Footer';
import './index.css';
import './syntax.css';
class App extends React.Component {
constructor (props) {
super(props);
this.state = {
sticky: false,
};
}
render () {
const {children} = this.props;
return (
<Analytics>
<Container>
<DefaultHeadMeta />
<Sticky disabled={!this.state.sticky}>
<Header />
</Sticky>
<Content>
{children}
</Content>
<Footer />
</Container>
</Analytics>
);
}
updateSticky () {
this.setState({sticky: document.body.clientWidth > 599});
}
componentDidMount () {
window.addEventListener('resize', this.updateSticky.bind(this));
this.updateSticky();
}
componentWillUnmount () {
window.removeEventListener('resize', this.updateSticky.bind(this));
}
}
export default App;
|
yangdinglou/DryadSynth
|
StarExec/src/z3/src/smt/smt_b_justification.h
|
/*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
smt_b_justification.h
Abstract:
<abstract>
Author:
<NAME> (leonardo) 2008-02-19.
Revision History:
--*/
#ifndef SMT_B_JUSTIFICATION_H_
#define SMT_B_JUSTIFICATION_H_
#include "smt/smt_literal.h"
#include "smt/smt_clause.h"
namespace smt {
/**
\brief Proof like object used to track dependencies of boolean propagation.
The idea is to reduce the cost of dependency tracking for the most common
justifications used during boolean propagation: unit propagation
*/
class b_justification {
void * m_data;
public:
enum kind {
CLAUSE, //!< clause of arbitrary size
BIN_CLAUSE, //!< binary clause
AXIOM, //!< no justification, it is only use if proof generation is disabled
JUSTIFICATION //!< fallback
};
b_justification():
m_data(reinterpret_cast<void*>(static_cast<size_t>(AXIOM))) {}
b_justification(b_justification const & source):
m_data(source.m_data) {
}
explicit b_justification(clause * c):
m_data(TAG(void*, c, CLAUSE)) {
}
explicit b_justification(literal l):
m_data(BOXTAGINT(void*, l.index(), BIN_CLAUSE)) {
}
explicit b_justification(justification * js):
m_data(TAG(void*, js, JUSTIFICATION)) {
SASSERT(js);
}
kind get_kind() const {
return static_cast<kind>(GET_TAG(m_data));
}
clause * get_clause() const {
SASSERT(get_kind() == CLAUSE);
return UNTAG(clause*, m_data);
}
justification * get_justification() const {
SASSERT(get_kind() == JUSTIFICATION);
return UNTAG(justification*, m_data);
}
literal get_literal() const {
SASSERT(get_kind() == BIN_CLAUSE);
return to_literal(UNBOXINT(m_data));
}
bool operator==(b_justification const & other) const {
return m_data == other.m_data;
}
bool operator!=(b_justification const & other) const {
return !operator==(other);
}
static b_justification mk_axiom() {
return b_justification();
}
};
const b_justification null_b_justification(static_cast<clause*>(nullptr));
inline std::ostream& operator<<(std::ostream& out, b_justification::kind k) {
switch (k) {
case b_justification::CLAUSE: return out << "clause";
case b_justification::BIN_CLAUSE: return out << "bin_clause";
case b_justification::AXIOM: return out << "axiom";
case b_justification::JUSTIFICATION: return out << "theory";
}
return out;
}
typedef std::pair<literal, b_justification> justified_literal;
};
#endif /* SMT_B_JUSTIFICATION_H_ */
|
jwytd/cscipm
|
src/main/java/com/csci/cscipm/core/constant/CsciExceptionConstant.java
|
package com.csci.cscipm.core.constant;
public interface CsciExceptionConstant {
//账号冻结
String EXCEPTION_ACCOUNT_LOCKED_CODE = "100001";
String EXCEPTION_ACCOUNT_LOCKED_MSG = "账号冻结!";
//账号密码错误异常
String EXCEPTION_ACCOUNT_PASSWORD_ERROR_CODE = "100002";
String EXCEPTION_ACCOUNT_PASSWORD_ERROR_MSG = "账号或密码错误!";
//无权限访问资源
String EXCEPTION_UNDECLARED_CODE = "100003";
String EXCEPTION_UNDECLARED_MSG = "无权限访问!";
}
|
gorkamolero/hb-react
|
src/context/SlideContext.js
|
import React, { useState, createContext, useEffect, useRef } from 'react'
import {cfg} from '../containers/App'
import Utils from '../utils/Utils'
export const SlideContext = createContext(null);
const SlideContextProvider = ({children}) => {
const EngineRef = useRef(null);
const [slideModel, setSlideModel] = useState(null);
const [nav, setNav] = useState({canBack:false, canNext:false});
const [progress, setProgress] = useState(0);
const [progressBar, setProgressBar] = useState({})
const [touched, setTouched] = React.useState(0)
useEffect(() => {
// Mounted
Utils.waitForEngine((Engine)=>{
if (Engine) {
EngineRef.current = Engine;
Engine.load(cfg.code, cfg.server, {}, cfg.preview, cfg.preload).then( ({css, jsLibs}) => {
let progressBar = Engine.getProgressBar()
setProgressBar(progressBar)
displayCurrentSlide();
Utils.embedCSS(css);
Utils.embedJSLibs(jsLibs);
}).catch((error) => {
console.error(error);
});
} else {
console.error("Error loading the Pickzen SDK");
}
});
}, []);
/* useEffect(() => {
console.log(slideModel)
}) */
const displayCurrentSlide = () => {
const Engine = EngineRef.current;
const slideModel = Engine.getSlide();
setSlideModel(slideModel);
const canRestart = slideModel.getType()==='End';
const canBack = slideModel.canBack();
const canNext = slideModel.canNext();
const backLabel = slideModel.getBackLabel() || 'Back';
const nextLabel = slideModel.getNextLabel() || 'Next';
setNav( {canBack, canNext, backLabel, nextLabel, canRestart});
setProgress(Engine.getProgress(false, true));
};
const next = () => {
slideModel.next();
displayCurrentSlide();
setTouched(touched + 1)
};
const back = () => {
slideModel.back();
displayCurrentSlide();
setTouched(touched + 1)
};
const restart = () => {
slideModel.restart();
displayCurrentSlide();
setTouched(touched + 1)
};
return (
<SlideContext.Provider value={{
Engine:EngineRef.current,
interpolate: (txt) => txt.includes('%') ? EngineRef.current.interpolate(txt) : txt,
getDatasheet: (ids) => EngineRef.current.getDatasheets(ids),
slideModel, displayCurrentSlide,
progress, progressBar,
nav:{canBack:nav.canBack, canNext:nav.canNext, canRestart:nav.canRestart, backLabel:nav.backLabel, nextLabel:nav.nextLabel, back, next, restart},
touched, setTouched
}}>
{slideModel ? children : null}
</SlideContext.Provider>
)
};
export default SlideContextProvider
|
lizij/Leetcode
|
src/Friend_Circles/Solution.java
|
package Friend_Circles;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
public class Solution {
public int findCircleNum(int[][] M) {
int N = M.length;
Integer[] marked = new Integer[N];
for (int i = 0; i < N; i++) {
marked[i] = i;
}
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
if (M[i][j] == 1){
int oldMark = marked[j];
for (int k = 0; k < N; k++) {
if (marked[k] == oldMark) marked[k] = marked[i];
}
}
}
}
HashSet<Integer> set = new HashSet<>();
set.addAll(Arrays.asList(marked));
return set.size();
}
public static void main(String[] args) {
Solution s = new Solution();
// int[][] input1 = {
// {1, 1, 0},
// {1, 1, 0},
// {0, 0, 1}
// };
// System.out.println(s.findCircleNum(input1));
// int[][] input2 = {
// {1, 1, 0},
// {1, 1, 1},
// {0, 1, 1}
// };
// System.out.println(s.findCircleNum(input2));
int[][] input3 = {
{1,0,0,1},
{0,1,1,0},
{0,1,1,1},
{1,0,1,1}
};
System.out.println(s.findCircleNum(input3));
}
}
|
lani009/Ajou-OOP-Practice_22
|
Lecture Codes/week3/MovieAudience/src/hw03/Movie.java
|
package hw03;
public class Movie {
private String title;
private String genre;
private double rating;
private int ageLimit;
public Movie(String title, String genre, double rating, int ageLimit) {
this.title = title;
this.genre = genre;
this.rating = rating;
this.ageLimit = ageLimit;
}
public String getTitle() {
return title;
}
public String getGenre() {
return genre;
}
public int getAgeLimit() {
return ageLimit;
}
public int compareRating(Movie anotherMovie) {
if (rating > anotherMovie.rating) {
return 1;
} else if (rating == anotherMovie.rating) {
return 0;
} else {
return -1;
}
}
}
|
liyu711/SUAS
|
UpdatedImageProcessing/integrated_image_processing_runner.py
|
<reponame>liyu711/SUAS<gh_stars>0
import timeit
from UpdatedImageProcessing import *
start_time = timeit.default_timer()
#IntegratedImageProcessingTester.complete_integrated_image_processing()
IntegratedImageProcessingTester.run_integrated_image_processing_tester()
Logger.format_time_report(timeit.default_timer() - start_time)
|
lgykuuga/jeefast2.0
|
jeefast-oms/src/main/java/com/lgy/oms/interfaces/kjy/util/ApacheHttpUtils.java
|
<filename>jeefast-oms/src/main/java/com/lgy/oms/interfaces/kjy/util/ApacheHttpUtils.java
package com.lgy.oms.interfaces.kjy.util;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* HttpUtils 请求客户端
*
* @author ck
* @date 2019/9/9
*/
public class ApacheHttpUtils {
private static Logger logger = LoggerFactory.getLogger(ApacheHttpUtils.class);
public static String doPost(String url, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
String rest = null;
//设置请求超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(60 * 1000)
.setConnectTimeout(60 * 1000)
.setConnectionRequestTimeout(60 * 1000)
.build();
try {
httpPost.setHeader("token", "<KEY>");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setConfig(requestConfig);
//组装请求参数
List<NameValuePair> nvps = new ArrayList<>();
for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext(); ) {
String key = (String) iter.next();
String value = String.valueOf(params.get(key));
nvps.add(new BasicNameValuePair(key, value));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
//执行
response = httpClient.execute(httpPost);
//返回结果集
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
rest = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}
} catch (IOException e) {
logger.error("请求失败:", e);
} finally {
//关闭流
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
logger.error("关闭流失败:", e);
}
}
return rest;
}
public static String doGet(String url) {
String rest = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
rest = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}
} catch (IOException e) {
System.out.printf("e" + e);
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
System.out.printf("e" + e);
}
}
return null;
}
}
|
zzachimed/ClickHouse
|
src/Interpreters/TransactionLog.h
|
<reponame>zzachimed/ClickHouse<filename>src/Interpreters/TransactionLog.h<gh_stars>1000+
#pragma once
#include <Interpreters/MergeTreeTransaction.h>
#include <Interpreters/MergeTreeTransactionHolder.h>
#include <Common/ZooKeeper/ZooKeeper.h>
#include <Common/ThreadPool.h>
#include <boost/noncopyable.hpp>
#include <mutex>
#include <unordered_map>
namespace DB
{
/// We want to create a TransactionLog object lazily and avoid creation if it's not needed.
/// But we also want to call shutdown() in a specific place to avoid race conditions.
/// We cannot simply use return-static-variable pattern,
/// because a call to shutdown() may construct unnecessary object in this case.
template <typename Derived>
class SingletonHelper : private boost::noncopyable
{
public:
static Derived & instance()
{
Derived * ptr = instance_raw_ptr.load();
if (likely(ptr))
return *ptr;
return createInstanceOrThrow();
}
static void shutdownIfAny()
{
std::lock_guard lock{instance_mutex};
if (instance_holder)
instance_holder->shutdown();
}
private:
static Derived & createInstanceOrThrow();
static inline std::atomic<Derived *> instance_raw_ptr;
/// It was supposed to be std::optional, but gcc fails to compile it for some reason
static inline std::shared_ptr<Derived> instance_holder;
static inline std::mutex instance_mutex;
};
class TransactionsInfoLog;
using TransactionsInfoLogPtr = std::shared_ptr<TransactionsInfoLog>;
using ZooKeeperPtr = std::shared_ptr<zkutil::ZooKeeper>;
/// This class maintains transaction log in ZooKeeper and a list of currently running transactions in memory.
///
/// Each transaction has unique ID (TID, see details below).
/// TransactionID is allocated when transaction begins.
///
/// We use TransactionID to associate changes (created/removed data parts) with transaction that has made/is going to make these changes.
/// To commit a transaction we create sequential node "/path_to_log/log/csn-" in ZK and write TID into this node.
/// Allocated sequential number is a commit timestamp or Commit Sequence Number (CSN). It indicates a (logical) point in time
/// when transaction is committed and all its changes became visible. So we have total order of all changes.
///
/// Also CSNs are used as snapshots: all changes that were made by a transaction that was committed with a CSN less or equal than some_csn
/// are visible in some_csn snapshot.
///
/// TransactionID consists of three parts: (start_csn, local_tid, host_id)
/// - start_csn is the newest CSN that existed when the transaction was started and also it's snapshot that is visible for this transaction
/// - local_tid is local sequential number of the transaction, each server allocates local_tids independently without requests to ZK
/// - host_id is persistent UUID of host that has started the transaction, it's kind of tie-breaker that makes ID unique across all servers
///
/// To check if some transaction is committed or not we fetch "csn-xxxxxx" nodes from ZK and construct TID -> CSN mapping,
/// so for committed transactions we know commit timestamps.
/// However, if we did not find a mapping for some TID, it means one of the following cases:
/// 1. Transaction is not committed (yet)
/// 2. Transaction is rolled back (quite similar to the first case, but it will never be committed)
/// 3. Transactions was committed a long time ago and we removed its entry from the log
/// To distinguish the third case we store a "tail pointer" in "/path_to_log/tail_ptr". It's a CSN such that it's safe to remove from log
/// entries with tid.start_csn < tail_ptr, because CSNs for those TIDs are already written into data parts
/// and we will not do a CSN lookup for those TIDs anymore.
///
/// (however, transactions involving multiple hosts and/or ReplicatedMergeTree tables are currently not supported)
class TransactionLog final : public SingletonHelper<TransactionLog>
{
public:
TransactionLog();
~TransactionLog();
void shutdown();
/// Returns the newest snapshot available for reading
CSN getLatestSnapshot() const;
/// Returns the oldest snapshot that is visible for some running transaction
CSN getOldestSnapshot() const;
/// Allocates TID, returns new transaction object
MergeTreeTransactionPtr beginTransaction();
/// Tries to commit transaction. Returns Commit Sequence Number.
/// Throw if transaction was concurrently killed or if some precommit check failed.
/// May throw if ZK connection is lost. Transaction status is unknown in this case.
/// Returns CommittingCSN if throw_on_unknown_status is false and connection was lost.
CSN commitTransaction(const MergeTreeTransactionPtr & txn, bool throw_on_unknown_status);
/// Releases locks that that were acquired by transaction, releases snapshot, removes transaction from the list of active transactions.
/// Normally it should not throw, but if it does for some reason (global memory limit exceeded, disk failure, etc)
/// then we should terminate server and reinitialize it to avoid corruption of data structures. That's why it's noexcept.
void rollbackTransaction(const MergeTreeTransactionPtr & txn) noexcept;
/// Returns CSN if transaction with specified ID was committed and UnknownCSN if it was not.
/// Returns PrehistoricCSN for PrehistoricTID without creating a TransactionLog instance as a special case.
static CSN getCSN(const TransactionID & tid);
static CSN getCSN(const TIDHash & tid);
/// Ensures that getCSN returned UnknownCSN because transaction is not committed and not because entry was removed from the log.
static void assertTIDIsNotOutdated(const TransactionID & tid);
/// Returns a pointer to transaction object if it's running or nullptr.
MergeTreeTransactionPtr tryGetRunningTransaction(const TIDHash & tid);
using TransactionsList = std::unordered_map<TIDHash, MergeTreeTransactionPtr>;
/// Returns copy of list of running transactions.
TransactionsList getTransactionsList() const;
/// Waits for provided CSN (and all previous ones) to be loaded from the log.
/// Returns false if waiting was interrupted (e.g. by shutdown)
bool waitForCSNLoaded(CSN csn) const;
bool isShuttingDown() const { return stop_flag.load(); }
void sync() const;
private:
void loadLogFromZooKeeper();
void runUpdatingThread();
void loadEntries(Strings::const_iterator beg, Strings::const_iterator end);
void loadNewEntries();
void removeOldEntries();
CSN finalizeCommittedTransaction(MergeTreeTransaction * txn, CSN allocated_csn, scope_guard & state_guard) noexcept;
void tryFinalizeUnknownStateTransactions();
static UInt64 deserializeCSN(const String & csn_node_name);
static String serializeCSN(CSN csn);
static TransactionID deserializeTID(const String & csn_node_content);
static String serializeTID(const TransactionID & tid);
ZooKeeperPtr getZooKeeper() const;
CSN getCSNImpl(const TIDHash & tid_hash) const;
ContextPtr global_context;
Poco::Logger * log;
/// The newest snapshot available for reading
std::atomic<CSN> latest_snapshot;
/// Local part of TransactionID number. We reset this counter for each new snapshot.
std::atomic<LocalTID> local_tid_counter;
mutable std::mutex mutex;
/// Mapping from TransactionID to CSN for recently committed transactions.
/// Allows to check if some transactions is committed.
struct CSNEntry
{
CSN csn;
TransactionID tid;
};
using TIDMap = std::unordered_map<TIDHash, CSNEntry>;
TIDMap tid_to_csn;
mutable std::mutex running_list_mutex;
/// Transactions that are currently processed
TransactionsList running_list;
/// If we lost connection on attempt to create csn- node then we don't know transaction's state.
using UnknownStateList = std::vector<std::pair<MergeTreeTransaction *, scope_guard>>;
UnknownStateList unknown_state_list;
UnknownStateList unknown_state_list_loaded;
/// Ordered list of snapshots that are currently used by some transactions. Needed for background cleanup.
std::list<CSN> snapshots_in_use;
ZooKeeperPtr zookeeper;
String zookeeper_path;
String zookeeper_path_log;
/// Name of the newest entry that was loaded from log in ZK
String last_loaded_entry;
/// The oldest CSN such that we store in log entries with TransactionIDs containing this CSN.
std::atomic<CSN> tail_ptr = Tx::UnknownCSN;
zkutil::EventPtr log_updated_event = std::make_shared<Poco::Event>();
std::atomic_bool stop_flag = false;
ThreadFromGlobalPool updating_thread;
Float64 fault_probability_before_commit = 0;
Float64 fault_probability_after_commit = 0;
};
template <typename Derived>
Derived & SingletonHelper<Derived>::createInstanceOrThrow()
{
std::lock_guard lock{instance_mutex};
if (!instance_holder)
{
instance_holder = std::make_shared<Derived>();
instance_raw_ptr = instance_holder.get();
}
return *instance_holder;
}
}
|
bence-toth/nano-router
|
packages/history/src/memory.spec.js
|
<filename>packages/history/src/memory.spec.js<gh_stars>1-10
import unexpected from "unexpected";
import unexpectedSinon from "unexpected-sinon";
import sinon from "sinon";
import { createMemoryHistory } from "./memory.js";
const expect = unexpected.clone().use(unexpectedSinon);
describe("memory", () => {
let history, clearListener, transitionSpy;
beforeEach(() => {
history = createMemoryHistory({
initialEntries: ["/posts"],
});
transitionSpy = sinon.spy();
clearListener = history.listen(transitionSpy);
});
afterEach(() => {
clearListener();
});
describe("push", () => {
it("pushes the given location on the history", () => {
history.push("/posts/edit/123?hello=you#anchor", "hello");
history.push("/posts/new");
expect(transitionSpy, "to have calls satisfying", () => {
transitionSpy({
action: "PUSH",
location: {
pathname: "/posts/edit/123",
search: "?hello=you",
hash: "#anchor",
state: "hello",
},
});
transitionSpy({
action: "PUSH",
location: {
pathname: "/posts/new",
state: null,
},
});
});
expect(history.location, "to satisfy", {
pathname: "/posts/new",
search: "",
hash: "",
state: null,
href: "/posts/new",
});
});
describe("when navitation is blocked", () => {
it("doesn't navigate", () => {
history.block(() => {});
history.push("/posts/edit/123?hello=you#anchor", "hello");
expect(transitionSpy, "was not called");
expect(history.location, "to satisfy", {
pathname: "/posts",
search: "",
hash: "",
state: null,
href: "/posts",
});
});
});
});
describe("replace", () => {
it("replace the current history location", () => {
history.replace("/posts/edit/123?hello=you#anchor", "hello");
history.replace("/posts/new");
expect(transitionSpy, "to have calls satisfying", () => {
transitionSpy({
action: "REPLACE",
location: {
pathname: "/posts/edit/123",
search: "?hello=you",
hash: "#anchor",
state: "hello",
},
});
transitionSpy({
action: "REPLACE",
location: {
pathname: "/posts/new",
state: null,
},
});
});
expect(history.location, "to satisfy", {
pathname: "/posts/new",
search: "",
hash: "",
state: null,
href: "/posts/new",
});
});
describe("when navitation is blocked", () => {
it("doesn't navigate", () => {
history.block(() => {});
history.replace("/posts/edit/123?hello=you#anchor", "hello");
expect(transitionSpy, "was not called");
expect(history.location, "to satisfy", {
pathname: "/posts",
search: "",
hash: "",
state: null,
href: "/posts",
});
});
});
});
describe("back", () => {
it("navigates to the previous history entry", () => {
history.push("/posts/edit/123?hello=you#anchor", "hello");
history.push("/posts/new");
history.replace("/posts/new/da");
history.back();
expect(history.location, "to satisfy", {
pathname: "/posts/edit/123",
search: "?hello=you",
hash: "#anchor",
state: "hello",
href: "/posts/edit/123?hello=you#anchor",
});
});
describe("when navitation is blocked", () => {
it("doesn't navigate", () => {
history.push("/posts/edit/123?hello=you#anchor", "hello");
history.push("/posts/new");
history.replace("/posts/new/da");
history.block(() => {});
history.back();
expect(history.location, "to satisfy", {
href: "/posts/new/da",
search: "",
hash: "",
pathname: "/posts/new/da",
state: null,
});
});
});
});
describe("forward", () => {
it("navigates to the next history entry", () => {
history.push("/posts/edit/123?hello=you#anchor", "hello");
history.push("/posts/new");
history.replace("/posts/new/da");
history.back();
history.forward();
expect(history.location, "to satisfy", {
pathname: "/posts/new/da",
search: "",
hash: "",
state: null,
href: "/posts/new/da",
});
});
describe("when navitation is blocked", () => {
it("doesn't navigate", () => {
history.push("/posts/edit/123?hello=you#anchor", "hello");
history.push("/posts/new");
history.replace("/posts/new/da");
history.back();
history.block(() => {});
history.forward();
expect(history.location, "to satisfy", {
href: "/posts/edit/123?hello=you#anchor",
search: "?hello=you",
hash: "#anchor",
pathname: "/posts/edit/123",
state: "hello",
});
});
});
});
describe("pushLocation", () => {
it("pushes an external location", () => {
history.pushLocation(
"https://example.com/posts/edit/123?hello=you#anchor"
);
expect(transitionSpy, "was not called");
expect(history.action, "to equal", "PUSH");
expect(history.location, "to satisfy", {
href: "https://example.com/posts/edit/123?hello=you#anchor",
hash: "#anchor",
search: "?hello=you",
pathname: "/posts/edit/123",
state: null,
});
});
describe("when given a target", () => {
beforeEach(() => {
history.pushLocation(
"https://example.com/posts/edit/123?hello=you#anchor",
"_blank"
);
});
it("simulates opening up a window", () => {
expect(history.openedWindow, "to equal", {
url: "https://example.com/posts/edit/123?hello=you#anchor",
target: "_blank",
});
});
it("doesn't affect the current history", () => {
expect(transitionSpy, "was not called");
expect(history.action, "to equal", "POP");
expect(history.location, "to satisfy", {
pathname: "/posts",
search: "",
hash: "",
state: null,
href: "/posts",
});
});
});
describe("when navitation is blocked", () => {
it("doesn't navigate", () => {
history.block(() => {});
history.pushLocation(
"https://example.com/posts/edit/123?hello=you#anchor"
);
expect(transitionSpy, "was not called");
expect(history.location, "to satisfy", {
pathname: "/posts",
search: "",
hash: "",
state: null,
href: "/posts",
});
});
describe("when given a target", () => {
it("doesn't block opening the window", () => {
history.block(() => {});
history.pushLocation(
"https://example.com/posts/edit/123?hello=you#anchor",
"_blank"
);
expect(history.openedWindow, "to equal", {
url: "https://example.com/posts/edit/123?hello=you#anchor",
target: "_blank",
});
});
});
});
});
describe("replaceLocation", () => {
it("replaces the current location", () => {
history.replaceLocation(
"https://example.com/posts/edit/123?hello=you#anchor"
);
expect(transitionSpy, "was not called");
expect(history.action, "to equal", "REPLACE");
expect(history.location, "to satisfy", {
href: "https://example.com/posts/edit/123?hello=you#anchor",
hash: "#anchor",
search: "?hello=you",
pathname: "/posts/edit/123",
state: null,
});
});
describe("when navitation is blocked", () => {
it("doesn't navigate", () => {
history.block(() => {});
history.pushLocation(
"https://example.com/posts/edit/123?hello=you#anchor"
);
expect(transitionSpy, "was not called");
expect(history.location, "to satisfy", {
pathname: "/posts",
search: "",
hash: "",
state: null,
href: "/posts",
});
});
});
});
});
|
michael51/node-easywechat
|
dist/OfficialAccount/Card/CoinClient.js
|
<filename>dist/OfficialAccount/Card/CoinClient.js
'use strict';
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const BaseClient_1 = __importDefault(require("../../Core/BaseClient"));
class CoinClient extends BaseClient_1.default {
activate() {
return this.httpGet('card/pay/activate');
}
summary() {
return this.httpGet('card/pay/getcoinsinfo');
}
getPrice(cardId = '', quantity) {
return this.httpPostJson('card/pay/getpayprice', {
card_id: cardId,
quantity,
});
}
recharge(count) {
return this.httpPostJson('card/pay/recharge', {
coin_count: count,
});
}
order(orderId) {
return this.httpPostJson('card/pay/getorder', {
order_id: orderId,
});
}
orders(filters) {
return this.httpPostJson('card/pay/getorderlist', filters);
}
confirm(cardId = '', orderId, quantity) {
return this.httpPostJson('card/pay/confirm', {
card_id: cardId,
order_id: orderId,
quantity,
});
}
}
exports.default = CoinClient;
|
MobileSeoul/2017seoul-15
|
seoulMarketDayAndroid/seoulMarketDayAndroid/app/src/main/java/com/stm/market/fragment/story/adapter/MarketStoryFileAdapter.java
|
package com.stm.market.fragment.story.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.vr.sdk.widgets.pano.VrPanoramaView;
import com.stm.R;
import com.stm.common.dao.File;
import com.stm.common.flag.DefaultFileFlag;
import com.stm.market.fragment.story.presenter.MarketStoryPresenter;
import java.util.List;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTouch;
/**
* Created by ㅇㅇ on 2017-08-24.
*/
public class MarketStoryFileAdapter extends PagerAdapter {
private MarketStoryPresenter marketStoryPresenter;
private MarketStoryFileViewHolder marketStoryFileViewHolder;
private List<File> files;
private Context context;
private int layout;
public MarketStoryFileAdapter(MarketStoryPresenter marketStoryPresenter, List<File> files, Context context, int layout) {
this.marketStoryPresenter = marketStoryPresenter;
this.files = files;
this.context = context;
this.layout = layout;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = LayoutInflater.from(context).inflate(layout, container, false);
File file = files.get(position);
int type = file.getType();
marketStoryFileViewHolder = new MarketStoryFileViewHolder(marketStoryPresenter, file, view);
if (type == DefaultFileFlag.PHOTO_TYPE) {
String uri = marketStoryFileViewHolder.storyImageUrl + file.getName() + "." + file.getExt();
marketStoryFileViewHolder.ll_marketstory_photo.setVisibility(View.VISIBLE);
marketStoryFileViewHolder.ll_marketstory_video.setVisibility(View.GONE);
marketStoryFileViewHolder.ll_marketstory_vr.setVisibility(View.GONE);
marketStoryFileViewHolder.ll_marketstory_photo.bringToFront();
Glide.with(context).load(uri).thumbnail(0.5f).diskCacheStrategy(DiskCacheStrategy.ALL).into(marketStoryFileViewHolder.iv_marketstory_photo);
}
if (type == DefaultFileFlag.VIDEO_THUMBNAIL_TYPE) {
String uri = marketStoryFileViewHolder.storyVideoUrl + file.getName() + "." + file.getExt();
marketStoryFileViewHolder.ll_marketstory_photo.setVisibility(View.GONE);
marketStoryFileViewHolder.ll_marketstory_video.setVisibility(View.VISIBLE);
marketStoryFileViewHolder.ll_marketstory_vr.setVisibility(View.GONE);
marketStoryFileViewHolder.ll_marketstory_video.bringToFront();
marketStoryFileViewHolder.iv_marketstory_videoplayer.bringToFront();
Glide.with(context).load(uri).thumbnail(0.5f).diskCacheStrategy(DiskCacheStrategy.ALL).into(marketStoryFileViewHolder.iv_marketstory_video);
}
if (type == DefaultFileFlag.VR360_TYPE) {
String uri = marketStoryFileViewHolder.storyVr360Url + file.getName() + "." + file.getExt();
marketStoryFileViewHolder.ll_marketstory_photo.setVisibility(View.GONE);
marketStoryFileViewHolder.ll_marketstory_video.setVisibility(View.GONE);
marketStoryFileViewHolder.ll_marketstory_vr.setVisibility(View.VISIBLE);
marketStoryFileViewHolder.ll_marketstory_vr.bringToFront();
Glide.with(context).load(uri).asBitmap().diskCacheStrategy(DiskCacheStrategy.ALL).into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
VrPanoramaView.Options options = new VrPanoramaView.Options();
options.inputType = VrPanoramaView.Options.TYPE_MONO;
marketStoryFileViewHolder.vrpv_marketstory_vr.setInfoButtonEnabled(false);
marketStoryFileViewHolder.vrpv_marketstory_vr.loadImageFromBitmap(resource, options);
}
});
}
container.addView(view);
return view;
}
@Override
public int getCount() {
return files.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
public static class MarketStoryFileViewHolder {
private MarketStoryPresenter marketStoryPresenter;
private File file;
@BindView(R.id.ll_marketstory_photo)
LinearLayout ll_marketstory_photo;
@BindView(R.id.ll_marketstory_video)
LinearLayout ll_marketstory_video;
@BindView(R.id.ll_marketstory_vr)
LinearLayout ll_marketstory_vr;
@BindView(R.id.iv_marketstory_photo)
ImageView iv_marketstory_photo;
@BindView(R.id.iv_marketstory_video)
ImageView iv_marketstory_video;
@BindView(R.id.iv_marketstory_videoplayer)
ImageView iv_marketstory_videoplayer;
@BindView(R.id.vrpv_marketstory_vr)
VrPanoramaView vrpv_marketstory_vr;
@BindString(R.string.cloud_front_story_image)
String storyImageUrl;
@BindString(R.string.cloud_front_story_video)
String storyVideoUrl;
@BindString(R.string.cloud_front_story_vr360)
String storyVr360Url;
public MarketStoryFileViewHolder(MarketStoryPresenter marketStoryPresenter, File file, View view) {
ButterKnife.bind(this, view);
this.marketStoryPresenter = marketStoryPresenter;
this.file = file;
}
@OnClick(R.id.iv_marketstory_videoplayer)
public void onClickPlayer() {
marketStoryPresenter.onClickPlayer(file);
}
@OnClick(R.id.iv_marketstory_photo)
public void onClickPhoto() {
marketStoryPresenter.onClickPhoto(file);
}
@OnTouch(R.id.vrpv_marketstory_vr)
public boolean onTouchVrView() {
return true;
}
}
}
|
mattwamboldt/synthesizer
|
source/app/audio/file/midi.h
|
<filename>source/app/audio/file/midi.h
#ifndef AUDIO_FILE_MIDI
#define AUDIO_FILE_MIDI
#include "../audio.h"
#include <vector>
#include <string>
namespace Audio
{
class MidiController;
// A Midi track is a collection of timed midi events or commands that modify
// the midi system to generate music. It also defines the playback speed
// TODO: The whole midi system is a WIP and would be better arranged using
// the command pattern for it's events. I'm trying to directly process the
// events using a loop.
class MidiTrack
{
public:
void Advance(MidiController* controller);
MidiEvent Current(){ return events[currentEvent]; }
bool Load(SDL_RWops* file);
private:
Uint32 ReadLength(SDL_RWops* file);
Uint8 NextByte(SDL_RWops* file);
std::string MidiTrack::ReadString(SDL_RWops* file, Uint32 length);
bool IsCommandByte(){ return currentByte & 128;} //The first bit is 1 on a command byte
Uint32 numBytes;
Uint32 numBytesRemaining;
Uint8 currentByte;
Uint16 sequenceNumber;
Uint32 pulseCounter;
int currentEvent;
std::vector<MidiEvent> events;
std::string name;
std::string copyright;
std::string text;
std::string instrument;
};
// A Midi file is a collection of tracks which comtain commands for
// the underlying midi controller
class MidiFile
{
public:
bool Load(const char* path);
void Advance(MidiController* controller);
Uint16 pulsesPerBeat;
private:
std::vector<MidiTrack> tracks;
Uint16 format; //Format 0 is a one track file, 1 is multitrack simul and 2 is multisong
Uint16 numTracks;
};
}
#endif
|
stytooldex/NewProject0
|
app/src/main/java/android/app/IApplicationThread.java
|
package android.app;
/**
* Created by rikka on 2017/11/6.
*/
public class IApplicationThread {
}
|
H-Tatsuhiro/Com_Pro-Cpp
|
AtCoder/abc165/d/main.cpp
|
<filename>AtCoder/abc165/d/main.cpp
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
long long int a, b, n; cin >> a >> b >> n;
long long int ans = (a * n) / b - a * (n / b);
if (b - 1 <= n) ans = max(ans, (a * (b - 1)) / b - a * ((b - 1) / b));
cout << ans << endl;
}
|
lastaflute/lastaflute
|
src/main/java/org/lastaflute/core/smartdeploy/RomanticServiceCreator.java
|
<reponame>lastaflute/lastaflute
/*
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.lastaflute.core.smartdeploy;
import java.util.List;
import org.lastaflute.core.smartdeploy.coins.CreatorPackageProvider;
import org.lastaflute.core.smartdeploy.coins.CreatorStateChecker;
import org.lastaflute.core.smartdeploy.exception.ServiceExtendsActionException;
import org.lastaflute.core.smartdeploy.exception.ServiceWebReferenceException;
import org.lastaflute.di.core.ComponentDef;
import org.lastaflute.di.core.creator.ServiceCreator;
import org.lastaflute.di.naming.NamingConvention;
/**
* @author jflute
* @since 0.7.3 (2015/12/27 Sunday)
*/
public class RomanticServiceCreator extends ServiceCreator {
// ===================================================================================
// Attribute
// =========
protected final List<String> webPackagePrefixList; // not null, for check, e.g. 'org.docksidestage.app.web.'
protected final CreatorPackageProvider packageProvider = new CreatorPackageProvider();
protected final CreatorStateChecker stateChecker = createCreatorStateChecker();
protected CreatorStateChecker createCreatorStateChecker() {
return new CreatorStateChecker();
}
// ===================================================================================
// Constructor
// ===========
public RomanticServiceCreator(NamingConvention namingConvention) {
super(namingConvention);
webPackagePrefixList = deriveWebPackageList(namingConvention);
}
protected List<String> deriveWebPackageList(NamingConvention namingConvention) {
return packageProvider.deriveWebPackageList(namingConvention);
}
// ===================================================================================
// Component Def
// =============
@Override
public ComponentDef createComponentDef(Class<?> componentClass) {
// env dispatch is unsupported at service because of too large concept, so use e.g. logic for environment process
final ComponentDef componentDef = super.createComponentDef(componentClass); // null allowed
if (componentDef == null) {
return null;
}
checkExtendsAction(componentDef);
if (isWebReferenceChecked()) {
checkWebReference(componentDef);
}
return componentDef;
}
protected boolean isWebReferenceChecked() {
return false; // service has delicate role for various people so no check about web reference
}
// ===================================================================================
// State Check
// ===========
protected void checkExtendsAction(ComponentDef componentDef) {
stateChecker.checkExtendsAction(componentDef, getNameSuffix(), msg -> {
return new ServiceExtendsActionException(msg);
});
}
protected void checkWebReference(ComponentDef componentDef) {
stateChecker.checkWebReference(componentDef, webPackagePrefixList, getNameSuffix(), msg -> {
return new ServiceWebReferenceException(msg);
});
}
}
|
lezzles11/End-to-End-Testing
|
cypress_examples/examples/fundamentals__custom-browsers/cypress/integration/spec.js
|
/// <reference types="cypress" />
describe('browser', () => {
it('works', () => {
cy.log(
`Running in browser **${Cypress.browser.displayName} v${
Cypress.browser.majorVersion
}**`
)
cy.task('echo', {
browser: Cypress.browser
})
})
})
|
st-js/st-js
|
generator/src/test/java/org/stjs/generator/writer/specialMethods/SpecialMethod23.java
|
<gh_stars>10-100
package org.stjs.generator.writer.specialMethods;
import org.stjs.javascript.JSGlobal;
public class SpecialMethod23 {
@SuppressWarnings("unused")
public void method() {
String n = JSGlobal.typeof("abc");
}
}
|
pyrated/cable
|
libcable/src/core/stream.c
|
#include <errno.h>
#include <string.h>
#include <cable/core/stream.h>
#include <cable/core/allocator.h>
#include <cable/core/string.h>
#include <cable/core/error.h>
#include <cable/core/data.h>
typedef enum Species Species;
enum Species {
ISTREAM,
OSTREAM,
IDATA,
ODATA,
};
struct CblStream {
CblConcreteObject isa;
Species species;
union {
FILE *cstream;
struct {
union {
CblObject *proxy;
CblData *idata;
CblMutableData *odata;
};
size_t index;
};
};
};
static void finalizeCallback(CblStream *stream) {
switch (stream->species) {
case IDATA:
case ODATA:
cblDisown(stream->proxy);
break;
default:
break;
}
}
static CblClass STREAM_CLASS = {
.name = "CblStream",
.finalizeCallback = (CblObjectFinalizeCallback)finalizeCallback,
.hashCallback = NULL,
.compareCallback = NULL,
.stringCallback = NULL,
};
CblClass * const CBL_STREAM_CLASS = &STREAM_CLASS;
static inline FILE *openStream(CblAllocator *alloc, const char *location, const char *mode, CblError **error) {
cblReturnUnless(location, NULL);
FILE *cstream = fopen(location, "rb");
int err = errno;
if (!cstream) {
if (error) {
*error = cblErrorNewWithErrno(alloc, err);
}
return NULL;
}
return cstream;
}
void cblStreamClose(CblAllocator *alloc, CblStream *stream, CblError **error) {
cblBailUnless(stream);
int code = 0;
switch (stream->species) {
case ISTREAM:
case OSTREAM:
code = fclose(stream->cstream);
default:
break;
}
if (code != 0 && error) {
*error = cblErrorNewWithErrno(alloc, errno);
}
}
void cblStreamFlush(CblAllocator *alloc, CblStream *stream, CblError **error) {
cblBailUnless(stream);
int code = 0;
switch (stream->species) {
case ISTREAM:
case OSTREAM:
code = fflush(stream->cstream);
default:
break;
}
if (code != 0 && error) {
*error = cblErrorNewWithErrno(alloc, errno);
}
}
CblInputStream *cblInputStreamNew(CblAllocator *alloc, const char *location, CblError **error) {
FILE *cstream = openStream(alloc, location, "rb", error);
cblReturnUnless(cstream, NULL);
CblInputStream *stream = cblInputStreamNewWithCStream(alloc, cstream);
if (!stream) {
fclose(cstream);
}
return stream;
}
CblInputStream *cblInputStreamNewWithCStream(CblAllocator *alloc, FILE *cstream) {
cblReturnUnless(cstream, NULL);
CblInputStream *stream = cblAllocatorAllocate(alloc, sizeof(CblStream));
cblReturnUnless(stream, NULL);
cblInitialize(stream, alloc, CBL_STREAM_CLASS);
stream->species = ISTREAM;
stream->cstream = cstream;
return stream;
}
CblInputStream *cblInputStreamNewWithData(CblAllocator *alloc, CblData *data) {
cblReturnUnless(data, NULL);
CblInputStream *stream = cblAllocatorAllocate(alloc, sizeof(CblStream));
cblReturnUnless(stream, NULL);
cblInitialize(stream, alloc, CBL_STREAM_CLASS);
cblOwn(data);
stream->species = IDATA;
stream->proxy = data;
stream->index = 0;
return stream;
}
size_t cblStreamReadBytes(CblAllocator *alloc, CblInputStream *stream, uint8_t *buffer, size_t length, CblError **error) {
cblReturnUnless(stream && buffer && length, 0);
switch (stream->species) {
case ISTREAM: {
FILE *cstream = stream->cstream;
clearerr(cstream);
size_t count = fread(buffer, 1, length, cstream);
int err = errno;
if (ferror(cstream)) {
if (error) {
*error = cblErrorNewWithErrno(alloc, err);
}
return 0;
}
return count;
}
case IDATA: {
CblData *data = stream->idata;
size_t dataLength = cblDataGetLength(data);
if (stream->index >= dataLength) {
if (error) {
*error = cblErrorNewWithErrno(alloc, EOVERFLOW);
}
return 0;
}
size_t count = cblUSizeMin(dataLength - length, dataLength - stream->index);
cblDataGetBytes(data, buffer, cblRangeNew(stream->index, count));
stream->index += count;
return count;
}
default:
break;
}
return 0;
}
CblOutputStream *cblOutputStreamNew(CblAllocator *alloc, const char *location, bool append, CblError **error) {
FILE *cstream = openStream(alloc, location, append ? "wba" : "wb", error);
cblReturnUnless(cstream, NULL);
CblOutputStream *stream = cblOutputStreamNewWithCStream(alloc, cstream);
if (!stream) {
fclose(cstream);
}
return stream;
}
CblOutputStream *cblOutputStreamNewWithCStream(CblAllocator *alloc, FILE *cstream) {
cblReturnUnless(cstream, NULL);
CblOutputStream *stream = cblAllocatorAllocate(alloc, sizeof(CblStream));
cblReturnUnless(stream, NULL);
cblInitialize(stream, alloc, CBL_STREAM_CLASS);
stream->species = OSTREAM;
stream->cstream = cstream;
return stream;
}
CblOutputStream *cblOutputStreamNewWithData(CblAllocator *alloc, CblMutableData *data, bool append) {
cblReturnUnless(data, NULL);
CblOutputStream *stream = cblAllocatorAllocate(alloc, sizeof(CblStream));
cblReturnUnless(stream, NULL);
cblInitialize(stream, alloc, CBL_STREAM_CLASS);
cblOwn(data);
stream->species = ODATA;
stream->odata = data;
if (!append) {
cblDataSetLength(data, 0);
}
return stream;
}
size_t cblStreamWriteCString(CblAllocator *alloc, CblOutputStream *stream, const char *cstring, CblError **error) {
return cblStreamWriteBytes(alloc, stream, (const uint8_t *)cstring, strlen(cstring), error);
}
size_t cblStreamWriteCFormat(CblAllocator *alloc, CblOutputStream *stream, const char *format, CblError **error, ...) {
va_list args;
va_start(args, error);
size_t written = cblStreamWriteCFormatList(alloc, stream, format, error, args);
va_end(args);
return written;
}
size_t cblStreamWriteCFormatList(CblAllocator *alloc, CblOutputStream *stream, const char *format, CblError **error, va_list args) {
cblReturnUnless(stream && format, 0);
CblString *string = cblStringNewWithCFormatList(alloc, format, args);
cblReturnUnless(string, 0);
size_t written = cblStringOutput(alloc, string, stream, CBL_STRING_ENCODING_UTF8, error);
cblDisown(string);
return written;
}
size_t cblStreamWriteBytes(CblAllocator *alloc,
CblOutputStream *stream,
const uint8_t *bytes,
size_t length,
CblError **error)
{
cblReturnUnless(stream && bytes && length, 0);
switch (stream->species) {
case OSTREAM: {
FILE *cstream = stream->cstream;
clearerr(cstream);
size_t count = fwrite(bytes, 1, length, cstream);
int err = errno;
if (ferror(cstream)) {
if (error) {
*error = cblErrorNewWithErrno(alloc, err);
}
return 0;
}
return count;
}
case ODATA: {
CblMutableData *data = stream->odata;
size_t oldLength = cblDataGetLength(data);
cblDataAppendBytes(data, bytes, length);
return cblDataGetLength(data) - oldLength;
}
default:
break;
}
return 0;
}
|
awesome-archive/Dragon
|
Dragon/include/operators/arithmetic/eltwise_op.h
|
/*!
* Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
*
* Licensed under the BSD 2-Clause License.
* You should have received a copy of the BSD 2-Clause License
* along with the software. If not, See,
*
* <https://opensource.org/licenses/BSD-2-Clause>
*
* ------------------------------------------------------------
*/
#ifndef DRAGON_OPERATORS_ARITHMETIC_ELTWISE_OP_H_
#define DRAGON_OPERATORS_ARITHMETIC_ELTWISE_OP_H_
#include "core/operator.h"
namespace dragon {
template <class Context>
class EltwiseOp final : public Operator<Context> {
public:
EltwiseOp(const OperatorDef& def, Workspace* ws)
: Operator<Context>(def, ws),
operation(OperatorBase::Arg<string>("operation", "SUM")),
coeffs(OperatorBase::Args<float>("coefficients")) {
// Check the number of coeffients
if (coeffs.size() > 0) {
CHECK_EQ(coeffs.size(), InputSize())
<< "\nOp has " << InputSize() << " inputs, "
<< "but provided " << coeffs.size() << " coeffs.";
} else coeffs.resize(InputSize(), 1.f);
// Compute the alpha for product operation
for (auto e : coeffs) { if (e != 1.f) alpha *= e; }
}
USE_OPERATOR_FUNCTIONS;
void RunOnDevice() override;
template <typename T> void RunWithType();
template <typename T> void SumRunWithType();
template <typename T> void ProdRunWithType();
protected:
string operation;
float alpha = 1.f;
vector<float> coeffs;
};
template <class Context>
class EltwiseGradientOp final : public Operator<Context> {
public:
EltwiseGradientOp(const OperatorDef& def, Workspace* ws)
: Operator<Context>(def, ws),
operation(OperatorBase::Arg<string>("operation", "SUM")),
coeffs(OperatorBase::Args<float>("coefficients")) {
if (coeffs.size() > 0) {
CHECK_EQ(coeffs.size(), OutputSize())
<< "\nOp has " << OutputSize() << " inputs, "
<< "but provided " << coeffs.size() << " coeffs.";
} else coeffs.resize(InputSize(), 1.f);
// Compute the alpha for product operation
for (auto e : coeffs) { if (e != 1.f) alpha *= e; }
}
USE_OPERATOR_FUNCTIONS;
void RunOnDevice() override;
template <typename T> void RunWithType();
template <typename T> void SumRunWithType();
template <typename T> void ProdRunWithType();
protected:
string operation;
float alpha = 1.f;
vector<float> coeffs;
};
} // namespace dragon
#endif // DRAGON_OPERATORS_ARITHMETIC_ELTWISE_OP_H_
|
jnthn/intellij-community
|
java/java-tests/testData/compileServer/incremental/markDirty/cleanTimestampsWithOutputOnModuleRebuild/moduleA/src/a/FA.java
|
<reponame>jnthn/intellij-community
package a;
public class FA {
}
|
RilaShu/spatio-temporal-visualization-of-massive-web-map-logs
|
tile-generation/src/test/scala/com/oculusinfo/tilegen/tiling/analytics/InSituAnalyticTestSuite.scala
|
/*
* Copyright (c) 2014 Oculus Info Inc.
* http://www.oculusinfo.com/
*
* Released under the MIT License.
*
* 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.oculusinfo.tilegen.tiling.analytics
import java.lang.{Integer => JavaInt}
import java.util.{List => JavaList}
import scala.collection.JavaConverters._
import org.scalatest.FunSuite
import org.apache.spark.SharedSparkContext
import com.oculusinfo.binning.impl.WebMercatorTilePyramid
import com.oculusinfo.binning.metadata.PyramidMetaData
import com.oculusinfo.binning.TileIndex
import org.json.JSONObject
import scala.util.Try
class InSituAnalyticTestSuite extends FunSuite with SharedSparkContext {
test("Array tile analytic output") {
val analytic = new ArrayTileAnalytic[Int](new NumericSumTileAnalytic[Int](Some("inner")), Some("outer"))
val analyticDesc = new MonolithicAnalysisDescription(((i: Int) => Seq(i)), analytic)
analyticDesc.addGlobalAccumulator(sc)
analyticDesc.addLevelAccumulator(sc, 0)
analyticDesc.addLevelAccumulator(sc, 1)
analyticDesc.accumulate(new TileIndex(0, 0, 0, 4, 4), Seq(1, 0, 0, 0))
analyticDesc.accumulate(new TileIndex(0, 0, 0, 4, 4), Seq(1, 1, 0, 0))
analyticDesc.accumulate(new TileIndex(1, 0, 0, 4, 4), Seq(0, 1, 0, 0))
analyticDesc.accumulate(new TileIndex(1, 1, 0, 4, 4), Seq(0, 0, 1, 0))
analyticDesc.accumulate(new TileIndex(1, 0, 1, 4, 4), Seq(0, 0, 1, 1))
analyticDesc.accumulate(new TileIndex(1, 1, 1, 4, 4), Seq(0, 0, 0, 1))
val pyramid = new WebMercatorTilePyramid
val metaData = new PyramidMetaData("name", "description", 4, 4,
pyramid.getTileScheme(),
pyramid.getProjection(),
Seq(Int.box(0), Int.box(1)).asJava,
pyramid.getTileBounds(new TileIndex(0, 0, 0)),
null, null)
AnalysisDescription.record(analyticDesc, metaData)
def getInnerValues (from: String): List[Int] = {
val json = new JSONObject(from).getJSONArray("outer")
Range(0, json.length()).map(n =>
json.getInt(n)
).toList
}
val global = getInnerValues(metaData.getCustomMetaData("global"))
val level0= getInnerValues(metaData.getCustomMetaData("0"))
val level1 = getInnerValues(metaData.getCustomMetaData("1"))
assert(List(2, 2, 2, 2) === global)
assert(List(2, 1, 0, 0) === level0)
assert(List(0, 1, 2, 2) === level1)
}
}
|
jsienniak/sttp-oauth2
|
oauth2/src/main/scala/com/ocadotechnology/sttp/oauth2/ClientCredentialsToken.scala
|
package com.ocadotechnology.sttp.oauth2
import com.ocadotechnology.sttp.oauth2.common._
import io.circe.Decoder
import io.circe.refined._
import sttp.client3.ResponseAs
import com.ocadotechnology.sttp.oauth2.common.Error.OAuth2Error
import scala.concurrent.duration.FiniteDuration
object ClientCredentialsToken {
type Response = Either[Error, ClientCredentialsToken.AccessTokenResponse]
private[oauth2] implicit val bearerTokenResponseDecoder: Decoder[Either[OAuth2Error, AccessTokenResponse]] =
circe.eitherOrFirstError[AccessTokenResponse, OAuth2Error](
Decoder[AccessTokenResponse],
Decoder[OAuth2Error]
)
val response: ResponseAs[Response, Any] =
common.responseWithCommonError[ClientCredentialsToken.AccessTokenResponse]
final case class AccessTokenResponse(
accessToken: Secret[String],
domain: String,
expiresIn: FiniteDuration,
scope: Scope
)
object AccessTokenResponse {
import com.ocadotechnology.sttp.oauth2.circe._
implicit val tokenDecoder: Decoder[AccessTokenResponse] =
Decoder
.forProduct4(
"access_token",
"domain",
"expires_in",
"scope"
)(AccessTokenResponse.apply)
.validate {
_.downField("token_type").as[String] match {
case Right(value) if value.equalsIgnoreCase("Bearer") => List.empty
case Right(string) => List(s"Error while decoding '.token_type': value '$string' is not equal to 'Bearer'")
case Left(s) => List(s"Error while decoding '.token_type': ${s.getMessage}")
}
}
}
}
|
EmileRouxTriton/android-sdk
|
streamingproxy/src/main/java/com/tritondigital/net/streaming/proxy/server/http/HttpRequest.java
|
<reponame>EmileRouxTriton/android-sdk<filename>streamingproxy/src/main/java/com/tritondigital/net/streaming/proxy/server/http/HttpRequest.java
package com.tritondigital.net.streaming.proxy.server.http;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Represents an Http Request.
* Filled when each line is read from the server.
*
* Call toString() to have the string representing the original request.
* Note that only fields that are actually used are in the map (and therefore are present in the string version
* obtained by toString). Supported fields are all the values in the HttpHeaderField enum.
*/
class HttpRequest
{
protected static final String CRLF = "\r\n";
private HttpMethod.Method mMethod;
private String mUri;
private HttpVersion.Version mVersion;
private final LinkedHashMap<HttpHeaderField.Field, String> mHeader;
public HttpRequest()
{
mHeader = new LinkedHashMap<>();
}
public void setMethod(HttpMethod.Method method) { mMethod = method; }
public HttpMethod.Method getMethod() { return mMethod; }
public void setUri(String uri) { mUri = uri; }
public void setVersion(HttpVersion.Version version) { mVersion = version; }
public void setHeader(HttpHeaderField.Field field, String value) { mHeader.put(field, value); }
@Override
public String toString()
{
// Method
StringBuilder stringBuffer = new StringBuilder(mMethod + " " + mUri + " " + mVersion + CRLF);
// Headers
for (Map.Entry<HttpHeaderField.Field, String> curEntry : mHeader.entrySet())
stringBuffer.append(curEntry.getKey()).append(": ").append(curEntry.getValue()).append(CRLF);
// End of request
stringBuffer.append(CRLF);
return stringBuffer.toString();
}
}
|
tsh2/platform-sdk2
|
src/client/assets/js/nodes/inputs/inject/actions.js
|
<filename>src/client/assets/js/nodes/inputs/inject/actions.js<gh_stars>1-10
import * as Action from './constants';
import {actionCreators as nodeActions} from 'features/nodes/actions';
import moment from 'moment';
const multiplier = { 's': 1, 'm': 60, 'h': 60*60};
function crontab(state){
if (state.repeatOption === "interval-time"){
return `*/${state.intervalFrequency} ${state.intervalStart}-${state.intervalEnd-1} * * ${state.intervalOn.join(",")}`
}
else if (state.repeatOption === "time"){
const [h,m] = state.specificTime.split(":");
return `${m} ${h} * * ${state.specificTimeOn.join(",")}`;
}
return "";
}
//this will change the multiplier for the 'repeat' value
export function updateRepeatUnits(id, event){
return function (dispatch, getState) {
dispatch({
type: Action.REPEAT_UNITS_CHANGED,
units: event.target.value,
id,
})
dispatch(nodeActions.updateNode('repeat', getState()[id].repeat * multiplier[getState()[id]['units']]));
}
}
export function setRepeat(id, event){
return function (dispatch, getState) {
dispatch({
type: Action.SET_REPEAT,
value: event.target.value,
id,
})
console.log("setting repeat to", getState()[id].repeat * multiplier[getState()[id]['units']]);
dispatch(nodeActions.updateNode('repeat', getState()[id].repeat * multiplier[getState()[id]['units']]));
}
}
//increment/decrement the 'repeat' value
/* return function (dispatch, getState) {
dispatch({
type: Action.REPEAT_INCREMENT,
min: options.min,
max: options.max,
amount: options.amount,
id,
})
dispatch(nodeActions.nodeActions.updateNode('repeat', getState()[id].repeat * multiplier[getState()[id]['units']]));
}
}*/
//crontab
export function updateTimeIntervalFrequency(id, event){
return function (dispatch, getState) {
dispatch({
type: Action.INTERVAL_FREQUENCY,
id,
frequency: event.target.value,
});
dispatch(nodeActions.updateNode('crontab', crontab(getState()[id])))
}
}
export function updateTimeIntervalStart(id, event){
return function (dispatch, getState) {
dispatch({
type: Action.INTERVAL_START,
id,
start: event.target.value,
});
dispatch(nodeActions.updateNode('crontab', crontab(getState()[id])));
}
}
export function updateTimeIntervalEnd(id, event){
return function (dispatch, getState) {
dispatch({
type: Action.INTERVAL_END,
id,
end: event.target.value,
});
dispatch(nodeActions.updateNode('crontab', crontab(getState()[id])));
}
}
export function updateTimeIntervalOn(id,event){
return function (dispatch, getState) {
dispatch({
type: Action.INTERVAL_ON,
id,
on: event.target.value,
});
dispatch(nodeActions.updateNode('crontab', crontab(getState()[id])));
}
}
export function updateOnce(id, event){
return function (dispatch, getState) {
dispatch({
type: Action.ONCE,
id,
once: event.target.checked,
});
dispatch(nodeActions.updateNode('once', getState()[id].once));
}
}
/* this is a thunk, because we need to dispatch two actions and one is dependent upon the result of the other
the first updates an internal representation of a time intervale (i.e an integer), the second dispatches an update to the
editing buffer with the string representation */
export function setSpecificTime(id, value){
return function (dispatch, getState) {
let [hour, minute] = (getState()[id].specificTime || "12:00").split(":");
dispatch({
type: Action.SPECIFIC_TIME,
value: moment(value).format("HH:mm"),
id,
})
//this is where we update the crontab property for the editing buffer
dispatch(nodeActions.updateNode('crontab', crontab(getState()[id])));
}
}
export function updateSpecificTimeOn(id, event){
return function (dispatch, getState) {
dispatch({
type: Action.SPECIFIC_TIME_ON,
id,
on: event.target.value,
});
dispatch(nodeActions.updateNode('crontab', crontab(getState()[id])));
}
}
//and heer
export function repeatOptionChanged(id,value){
console.log("ok repeat option changed!!");
return function (dispatch, getState) {
dispatch({
type: Action.REPEAT_OPTION_CHANGED,
value,
id,
});
//set the defaults here and remove the current defaults! - in the editing buffer!!
dispatch(nodeActions.initNodeKeys(Action.REPEAT_DEFAULT_OBJECTS[getState()[id].repeatOption]));
}
}
export function selectPayloadType(id, payloadType){
return function (dispatch, getState) {
dispatch ({
type: Action.PAYLOAD_TYPE_SELECTED,
payloadType,
id
});
dispatch(nodeActions.updateNode('payloadType', getState()[id].payloadType));
}
}
export function updatePayload(id, event){
return function (dispatch, getState) {
dispatch ({
type: Action.PAYLOAD,
payload: event.target.value,
id
});
dispatch(nodeActions.updateNode('payload', getState()[id].payload));
}
};
export function togglePayloadMenu(id){
return {
type: Action.TOGGLE_PAYLOAD_MENU,
id
}
}
export function toggleBoolMenu(id){
return {
type: Action.TOGGLE_BOOL_MENU,
id
}
}
export function selectBool(id, value){
return {
type: Action.BOOL_SELECTED,
value,
id
}
}
|
wookie41/blitz
|
renderer/core/src/core/ogl/buffer/OpenGLBufferFiller.cpp
|
<reponame>wookie41/blitz
#include "core/RendererErrorCode.h"
#include "core/ogl/OpenGLContext.h"
#include "core/ogl/buffer/OpenGLBufferFiller.h"
#include "core/ogl/buffer/SimpleOpenGLBuffer.h"
namespace blitz::ogl
{
OpenGLBufferFiller::OpenGLBufferFiller(OpenGLContext* glContext) : glContext(glContext) {}
void OpenGLBufferFiller::fill(Buffer* buffer, const FillArgs& fillArgs)
{
auto simpleBuffer = dynamic_cast<SimpleOpenGLBuffer*>(buffer);
if (simpleBuffer != nullptr)
{
simpleFill(simpleBuffer, fillArgs);
return;
}
exit(RendererErrorCode::OPENGL_UNSUPPORTED_BUFFER);
}
void OpenGLBufferFiller::simpleFill(SimpleOpenGLBuffer* buffer, const FillArgs& fillArgs)
{
// TODO currently for the sake of simplicity, partial updates are not supported
if (fillArgs.offset > 0)
{
exit(OPENGL_UNSUPPORTED_BUFFER_OPERATION);
}
if (!buffer->isIsWriteable())
{
DLOG_F(ERROR, "[OpenGL] Can't fill buffer with id %d - it's not writeable", buffer->getId());
return;
}
DLOG_F(INFO, "[OpenGL] Filling buffer with id %d with %d bytes, starting from address %p", buffer->getId(),
fillArgs.dataSizeInBytes, fillArgs.data);
GLenum usageHint;
switch (buffer->getUsageHint())
{
case UsageHint::STREAM:
case UsageHint::IMMUTABLE:
case UsageHint::STATIC:
usageHint = GL_STATIC_DRAW;
break;
}
buffer->bind({ 0, 0, 0, BufferBindTarget::WRITE });
if (fillArgs.shouldInvalidate)
{
GLint bufferSize;
glGetBufferParameteriv(GL_COPY_WRITE_BUFFER, GL_BUFFER_SIZE, &bufferSize);
DLOG_F(INFO, "[OpenGL] Orhpaning buffer with id %d, size = %d", buffer->getId(), bufferSize);
glBufferData(GL_COPY_WRITE_BUFFER, buffer->getId(), NULL, usageHint);
}
glBufferData(GL_COPY_WRITE_BUFFER, fillArgs.dataSizeInBytes, fillArgs.data, usageHint);
#ifndef NDEBUG
GLint bufferSize;
glGetBufferParameteriv(GL_COPY_WRITE_BUFFER, GL_BUFFER_SIZE, &bufferSize);
DLOG_F(INFO, "[OpenGL] Buffer %d filled with %d bytes", buffer->getId(), bufferSize);
#endif
glBindBuffer(GL_COPY_WRITE_BUFFER, 0);
buffer->setSize(fillArgs.dataSizeInBytes);
}
} // namespace blitz::ogl
|
piiigletTheThird/FlightOneOpenSource
|
src/flight_controller/inc/imu.h
|
<reponame>piiigletTheThird/FlightOneOpenSource
#pragma once
// +X to the right
// +Y straight up
// +Z axis toward viewer
// Heading = rotation about y axis
// Attitude = rotation about z axis
// Bank = rotation about x axis
//30 degrees per second
#define MAX_SPIN_RATE_RAD 0.523599f
typedef struct {
volatile float x;
volatile float y;
volatile float z;
volatile float w;
} quaternion_record;
typedef struct {
volatile float x;
volatile float y;
volatile float z;
} vector_record;
extern volatile int quadInverted;
extern volatile float currentSpinRate;
extern volatile quaternion_record attitudeFrameQuat;
extern volatile float requestedDegrees[3];
extern void InitImu(void);
extern void ImuResetCommandQuat(void);
extern void ImuUpdateCommandQuat(float rollDps, float pitchDps, float yawDps, float halfdT);
extern void UpdateImu(float gx, float gy, float gz, float ax, float ay, float az);
|
metux/chromium-deb
|
mojo/public/tools/bindings/generate_export_header.py
|
#!/usr/bin/env python
# Copyright 2017 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.
"""Generates a C++ header to define a component export macro."""
import argparse
import os
import sys
_TEMPLATE = """// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef {{guard}}
#define {{guard}}
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined({{impl_macro}})
#define {{export_macro}} __declspec(dllexport)
#else
#define {{export_macro}} __declspec(dllimport)
#endif // defined({{impl_macro}})
#else // defined(WIN32)
#if defined({{impl_macro}})
#define {{export_macro}} __attribute__((visibility("default")))
#else
#define {{export_macro}}
#endif
#endif
#else // defined(COMPONENT_BUILD)
#define {{export_macro}}
#endif
#endif // {{guard}}
"""
def WriteHeader(output_file, relative_path, impl_macro, export_macro):
# Allow inputs for impl_macro to be of the form FOO_IMPL=1. Drop the "=1".
impl_macro = impl_macro.split("=")[0]
substitutions = {
"guard": relative_path.replace("/", "_").replace(".", "_").upper() + "_",
"impl_macro": impl_macro,
"export_macro": export_macro,
}
contents = _TEMPLATE
for k, v in substitutions.iteritems():
contents = contents.replace("{{%s}}" % k, v)
with open(output_file, "w") as f:
f.write(contents)
def main():
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument(
"--impl_macro", type=str, required=True,
help=("The name of the macro to emit for component IMPL blocks."))
parser.add_argument(
"--export_macro", type=str, required=True,
help=("The name of the macro to emit for component EXPORT attributes."))
parser.add_argument(
"--output_file", type=str, required=True,
help=("The file path to which the generated header should be written."))
parser.add_argument(
"--relative_path", type=str, required=True,
help=("The generated header's path relative to the generated output"
" root. Used to generate header guards."))
params, _ = parser.parse_known_args()
WriteHeader(params.output_file, params.relative_path, params.impl_macro,
params.export_macro)
if __name__ == "__main__":
sys.exit(main())
|
nhojpatrick/nhojpatrick-cucumber
|
testing-internal/steps/src/main/java/com/github/nhojpatrick/cucumber/testing/internal/steps/json/transform/WhitespaceTransformation_TestingInternalSteps.java
|
<reponame>nhojpatrick/nhojpatrick-cucumber
package com.github.nhojpatrick.cucumber.testing.internal.steps.json.transform;
import com.github.nhojpatrick.cucumber.core.exceptions.IllegalKeyException;
import com.github.nhojpatrick.cucumber.core.exceptions.IllegalOperationException;
import com.github.nhojpatrick.cucumber.core.exceptions.IllegalTypeClassException;
import com.github.nhojpatrick.cucumber.core.exceptions.TypeMismatchException;
import com.github.nhojpatrick.cucumber.json.core.castto.exceptions.UnsupportedDataTypeException;
import com.github.nhojpatrick.cucumber.json.core.transform.Transformation;
import com.github.nhojpatrick.cucumber.json.transformations.whitespace.WhitespaceTransformation;
import com.github.nhojpatrick.cucumber.json.transformations.whitespace.exceptions.WhitespaceTransformationArgumentException;
import com.github.nhojpatrick.cucumber.state.RunState;
import com.google.inject.Inject;
import io.cucumber.java.en.Given;
import static com.github.nhojpatrick.cucumber.json.transform.TransformConstants.DEFAULT_MAP_KEY;
public class WhitespaceTransformation_TestingInternalSteps
extends BaseTransformation_TestingInternalSteps {
@Inject
public WhitespaceTransformation_TestingInternalSteps(final RunState runState) {
super(runState);
}
@Given("TestingInternalSteps I transform json map using default RunStateKey and whitespace the following path {string} produces the IllegalPathOperationException {string}")
public void whitespaceIllegalPathOperationException(final String path,
final String expectedExceptionMessageRaw)
throws IllegalKeyException,
IllegalTypeClassException,
TypeMismatchException,
WhitespaceTransformationArgumentException {
whitespaceIllegalPathOperationException(path, 4, 4, expectedExceptionMessageRaw);
}
@Given("TestingInternalSteps I transform json map using default RunStateKey and whitespace the following path {string} with prefix {int} and suffix {int} produces the IllegalPathOperationException {string}")
public void whitespaceIllegalPathOperationException(final String path,
final int prefix,
final int suffix,
final String expectedExceptionMessageRaw)
throws IllegalKeyException,
IllegalTypeClassException,
TypeMismatchException,
WhitespaceTransformationArgumentException {
whitespaceIllegalPathOperationException(DEFAULT_MAP_KEY, path, prefix, suffix, expectedExceptionMessageRaw);
}
@Given("TestingInternalSteps I transform json map using RunStateKey {string} and whitespace the following path {string} produces the IllegalPathOperationException {string}")
public void whitespaceIllegalPathOperationException(final String runStateJsonMapKey,
final String path,
final String expectedExceptionMessageRaw)
throws IllegalKeyException,
IllegalTypeClassException,
TypeMismatchException,
WhitespaceTransformationArgumentException {
whitespaceIllegalPathOperationException(runStateJsonMapKey, path, 4, 4, expectedExceptionMessageRaw);
}
@Given("TestingInternalSteps I transform json map using RunStateKey {string} and whitespace the following path {string} with prefix {int} and suffix {int} produces the IllegalPathOperationException {string}")
public void whitespaceIllegalPathOperationException(final String runStateJsonMapKey,
final String path,
final int prefix,
final int suffix,
final String expectedExceptionMessageRaw)
throws IllegalKeyException,
IllegalTypeClassException,
TypeMismatchException,
WhitespaceTransformationArgumentException {
whitespace(runStateJsonMapKey,
path,
prefix,
suffix,
IllegalOperationException.class,
expectedExceptionMessageRaw);
}
@Given("TestingInternalSteps I transform json map using default RunStateKey and whitespace the following path {string} produces the UnsupportedDataTypeException {string}")
public void whitespaceUnsupportedDataTypeException(final String path,
final String expectedExceptionMessageRaw)
throws IllegalKeyException,
IllegalTypeClassException,
TypeMismatchException,
WhitespaceTransformationArgumentException {
whitespaceUnsupportedDataTypeException(path, 4, 4, expectedExceptionMessageRaw);
}
@Given("TestingInternalSteps I transform json map using default RunStateKey and whitespace the following path {string} with prefix {int} and suffix {int} produces the UnsupportedDataTypeException {string}")
public void whitespaceUnsupportedDataTypeException(final String path,
final int prefix,
final int suffix,
final String expectedExceptionMessageRaw)
throws IllegalKeyException,
IllegalTypeClassException,
TypeMismatchException,
WhitespaceTransformationArgumentException {
whitespaceUnsupportedDataTypeException(DEFAULT_MAP_KEY, path, prefix, suffix, expectedExceptionMessageRaw);
}
@Given("TestingInternalSteps I transform json map using RunStateKey {string} and whitespace the following path {string} produces the UnsupportedDataTypeException {string}")
public void whitespaceUnsupportedDataTypeException(final String runStateJsonMapKey,
final String path,
final String expectedExceptionMessageRaw)
throws IllegalKeyException,
IllegalTypeClassException,
TypeMismatchException,
WhitespaceTransformationArgumentException {
whitespaceUnsupportedDataTypeException(runStateJsonMapKey, path, 4, 4, expectedExceptionMessageRaw);
}
@Given("TestingInternalSteps I transform json map using RunStateKey {string} and whitespace the following path {string} with prefix {int} and suffix {int} produces the UnsupportedDataTypeException {string}")
public void whitespaceUnsupportedDataTypeException(final String runStateJsonMapKey,
final String path,
final int prefix,
final int suffix,
final String expectedExceptionMessageRaw)
throws IllegalKeyException,
IllegalTypeClassException,
TypeMismatchException,
WhitespaceTransformationArgumentException {
whitespace(runStateJsonMapKey,
path,
prefix,
suffix,
UnsupportedDataTypeException.class,
expectedExceptionMessageRaw);
}
public <T extends Exception> void whitespace(final String runStateJsonMapKey,
final String path,
final Integer prefix,
final Integer suffix,
final Class<T> t,
final String expectedExceptionMessageRaw)
throws IllegalKeyException,
IllegalTypeClassException,
TypeMismatchException,
WhitespaceTransformationArgumentException {
final Transformation transformation = new WhitespaceTransformation(prefix, suffix);
transformationCheck(runStateJsonMapKey, path, t, expectedExceptionMessageRaw, transformation);
}
}
|
ht1131589588/web-library
|
Webpack/mini-webpack/plugins/TestPlugin.js
|
<filename>Webpack/mini-webpack/plugins/TestPlugin.js
class TestPlugin {
apply(compiler) {
compiler.hooks.beforeRun.tapAsync("just4fun", function() {
console.log('[Success] 开始编译')
})
}
}
module.exports = TestPlugin
|
nielsmeima/tinyMediaManagerSME
|
src/main/java/org/tinymediamanager/scraper/moviemeter/MovieMeter.java
|
/*
* Copyright 2012 - 2020 <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.tinymediamanager.scraper.moviemeter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
import org.tinymediamanager.scraper.http.TmmHttpClient;
import org.tinymediamanager.scraper.moviemeter.services.FilmService;
import org.tinymediamanager.scraper.moviemeter.services.SearchService;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.SerializedName;
import com.google.gson.internal.bind.DateTypeAdapter;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
class MovieMeter {
// the base API url
public static final String API_URL = "http://www.moviemeter.nl/api/";
// the api key query parameter; hast to be supplied at all calls
public static final String PARAM_API_KEY = "api_key";
private Retrofit restAdapter;
private boolean isDebug;
private String apiKey;
public MovieMeter() {
this.apiKey = "";
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
static class ErrorResponse {
@SerializedName("message")
String msg;
@Override
public String toString() {
return msg;
}
}
/**
* Set the {@link retrofit.RestAdapter} log level.
*
* @param isDebug
* If true, the log level is set to {@link retrofit.RestAdapter.LogLevel#FULL}. Otherwise {@link retrofit.RestAdapter.LogLevel#NONE}.
*/
public MovieMeter setIsDebug(boolean isDebug) {
this.isDebug = isDebug;
// if (restAdapter != null) {
// restAdapter.setLogLevel(isDebug ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE);
// }
return this;
}
/**
* Create a new {@link retrofit.RestAdapter.Builder}. Override this to e.g. set your own client or executor.
*
* @return A {@link retrofit.RestAdapter.Builder} with no modifications.
*/
protected Retrofit.Builder newRestAdapterBuilder() {
return new Retrofit.Builder();
}
/**
* Return the current {@link retrofit.RestAdapter} instance. If none exists (first call), builds a new one.
*/
protected Retrofit getRestAdapter() {
if (restAdapter == null) {
Retrofit.Builder builder = newRestAdapterBuilder();
builder.baseUrl(API_URL);
builder.addConverterFactory(GsonConverterFactory.create(getGsonBuilder().create()));
builder.client(TmmHttpClient.newBuilder().addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl url = request.url().newBuilder().addQueryParameter(PARAM_API_KEY, apiKey).build();
request = request.newBuilder().url(url).build();
return chain.proceed(request);
}
}).build());
// if (isDebug) {
// builder.setLogLevel(RestAdapter.LogLevel.FULL);
// }
restAdapter = builder.build();
}
return restAdapter;
}
protected GsonBuilder getGsonBuilder() {
GsonBuilder builder = new GsonBuilder();
// class types
builder.registerTypeAdapter(Integer.class, new JsonDeserializer<Integer>() {
@Override
public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
return Integer.valueOf(json.getAsInt());
}
catch (NumberFormatException e) {
return 0;
}
}
});
builder.registerTypeAdapter(Date.class, new DateTypeAdapter());
builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return builder;
}
public FilmService getFilmService() {
return getRestAdapter().create(FilmService.class);
}
public SearchService getSearchService() {
return getRestAdapter().create(SearchService.class);
}
}
|
yzr0512/tingwoshuo
|
app/src/main/java/com/cqu/shixun/tingwoshuo/MyApplication.java
|
package com.cqu.shixun.tingwoshuo;
import android.app.Application;
import com.cqu.shixun.tingwoshuo.model.User;
public class MyApplication extends Application {
// 在这里可以定义一些全局的变量
User currUser; // 当前登录的用户
public User getCurrUser() {
return currUser;
}
public void setCurrUser(User currUser) {
this.currUser = currUser;
}
}
|
BrianApple/iRpc
|
src/main/java/iRpc/base/processor/IProcessor.java
|
<filename>src/main/java/iRpc/base/processor/IProcessor.java
package iRpc.base.processor;
import java.util.HashMap;
import java.util.Map;
import iRpc.dataBridge.ResponseData;
/**
* 执行器
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2019</p>
* <p>Company: www.uiotp.com</p>
* @author yangcheng
* @date 2021年2月27日
* @version 1.0
*/
public interface IProcessor {
public void run(ResponseData ret);
}
|
hodgman/eight
|
src/core/timer/timer.cpp
|
//------------------------------------------------------------------------------
#include <eight/core/test.h>
#include <eight/core/debug.h>
#include <eight/core/alloc/scope.h>
#include <eight/core/timer/timer.h>
#include <eight/core/thread/atomic.h>
#include <timer_lib/timer.h>
using namespace eight;
//------------------------------------------------------------------------------
class TimerImpl
{
public:
TimerImpl();
~TimerImpl();
void Reset();
double Elapsed() const;
double Elapsed(bool reset);
timer data;
};
eiImplementInterface( Timer, TimerImpl );
eiInterfaceConstructor( Timer, () );
eiInterfaceFunction( void, Timer, Reset, () );
eiInterfaceFunctionConst( double, Timer, Elapsed, () );
eiInterfaceFunction( double, Timer, Elapsed, (a), bool a );
static eight::Atomic g_TimerSystemInit;
static void InitSystem()
{
if( 0 == g_TimerSystemInit++ )
timer_lib_initialize();
//todo - init/shutdown here supposed to be able to be stupid-proof, allowing user to init multiple times.
// not actually safe to use this feature yet:
//thread A: g_TimerSystemInit++ -> true
//thread B: g_TimerSystemInit++ -> false
//thread B: return
//thread B: ...goes on to use timer functions...
//thread A: timer_lib_initialize(); -- too late
}
static void ShutdownSystem()
{
eiASSERT( g_TimerSystemInit );
if( --g_TimerSystemInit == 0 )
timer_lib_shutdown();
}
TimerImpl::TimerImpl()
{
InitSystem();
eiASSERT( g_TimerSystemInit );
timer_initialize( &data );
}
TimerImpl::~TimerImpl()
{
ShutdownSystem();
}
void TimerImpl::Reset()
{
timer_reset( &data );
}
double TimerImpl::Elapsed() const
{
return timer_elapsed( (timer*)&data, 0 );
}
double TimerImpl::Elapsed(bool reset)
{
return timer_elapsed( &data, (int)reset );
}
//------------------------------------------------------------------------------
|
jasonadamyoung/busterleague
|
app/models/game_batting_stat.rb
|
# === COPYRIGHT:
# Copyright (c) <NAME>
# === LICENSE:
# see LICENSE file
class GameBattingStat < ApplicationRecord
include CleanupTools
belongs_to :roster, optional: true
has_one :player, through: :roster
belongs_to :team
belongs_to :opposing_team, :class_name => 'Team'
belongs_to :boxscore
before_save :set_singles
scope :for_season, lambda {|season| where(season: season)}
scope :four_homer_games, -> {where("hr >= 4")}
scope :six_hit_games, -> {where("h >= 6")}
scope :cycles, ->{where('h1b >= 1').where('h2b >= 1').where('h3b >=1').where('hr >= 1')}
# location
LOCATION_HOME = 1
LOCATION_AWAY = 2
def home?
self.location == LOCATION_HOME
end
def set_singles
self.h1b = (h - (h3b+h2b+hr))
end
def self.rebuild_all
self.dump_data
Boxscore.find_each do |boxscore|
boxscore.create_game_batting_stats
end
end
def fix_roster_id
if(roster = Roster.find_roster_for_name_position_team_season(self.name,
self.position,
self.team_id,
self.season))
self.update_attribute(:roster_id,roster.id)
end
end
def self.fix_roster_ids
self.where(roster_id: 0).find_each do |gbs|
gbs.fix_roster_id
end
end
end
|
fuqi1001/EasyTrading
|
data/index.js
|
<reponame>fuqi1001/EasyTrading
module.exports = {
users: require("./users"),
items: require("./items"),
classify: require("./classify"),
apartments: require("./apartments"),
locations: require("./locations"),
comments: require("./comments")
};
|
cobot/coworkers
|
features/support/id_generators.rb
|
module IdGenerators
def next_id
@id ||= 0
@id += 1
@id.to_s
end
end
World(IdGenerators) if respond_to?(:World)
|
srgnuclear/shogun
|
src/shogun/classifier/svm/SVMSGD.cpp
|
<gh_stars>1-10
/*
SVM with stochastic gradient
Copyright (C) 2007- <NAME>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 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 Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
$Id: svmsgd.cpp,v 1.13 2007/10/02 20:40:06 cvs Exp $
Shogun adjustments (w) 2008-2009 <NAME>
*/
#include <shogun/classifier/svm/SVMSGD.h>
#include <shogun/base/Parameter.h>
#include <shogun/lib/Signal.h>
#include <shogun/labels/BinaryLabels.h>
#include <shogun/loss/HingeLoss.h>
using namespace shogun;
CSVMSGD::CSVMSGD()
: CLinearMachine()
{
init();
}
CSVMSGD::CSVMSGD(float64_t C)
: CLinearMachine()
{
init();
C1=C;
C2=C;
}
CSVMSGD::CSVMSGD(float64_t C, CDotFeatures* traindat, CLabels* trainlab)
: CLinearMachine()
{
init();
C1=C;
C2=C;
set_features(traindat);
set_labels(trainlab);
}
CSVMSGD::~CSVMSGD()
{
SG_UNREF(loss);
}
void CSVMSGD::set_loss_function(CLossFunction* loss_func)
{
SG_REF(loss_func);
SG_UNREF(loss);
loss=loss_func;
}
bool CSVMSGD::train_machine(CFeatures* data)
{
// allocate memory for w and initialize everyting w and bias with 0
ASSERT(m_labels)
ASSERT(m_labels->get_label_type() == LT_BINARY)
if (data)
{
if (!data->has_property(FP_DOT))
SG_ERROR("Specified features are not of type CDotFeatures\n")
set_features((CDotFeatures*) data);
}
ASSERT(features)
int32_t num_train_labels=m_labels->get_num_labels();
int32_t num_vec=features->get_num_vectors();
ASSERT(num_vec==num_train_labels)
ASSERT(num_vec>0)
w=SGVector<float64_t>(features->get_dim_feature_space());
w.zero();
bias=0;
float64_t lambda= 1.0/(C1*num_vec);
// Shift t in order to have a
// reasonable initial learning rate.
// This assumes |x| \approx 1.
float64_t maxw = 1.0 / sqrt(lambda);
float64_t typw = sqrt(maxw);
float64_t eta0 = typw / CMath::max(1.0,-loss->first_derivative(-typw,1));
t = 1 / (eta0 * lambda);
SG_INFO("lambda=%f, epochs=%d, eta0=%f\n", lambda, epochs, eta0)
//do the sgd
calibrate();
SG_INFO("Training on %d vectors\n", num_vec)
CSignal::clear_cancel();
ELossType loss_type = loss->get_loss_type();
bool is_log_loss = false;
if ((loss_type == L_LOGLOSS) || (loss_type == L_LOGLOSSMARGIN))
is_log_loss = true;
for(int32_t e=0; e<epochs && (!CSignal::cancel_computations()); e++)
{
count = skip;
for (int32_t i=0; i<num_vec; i++)
{
float64_t eta = 1.0 / (lambda * t);
float64_t y = ((CBinaryLabels*) m_labels)->get_label(i);
float64_t z = y * (features->dense_dot(i, w.vector, w.vlen) + bias);
if (z < 1 || is_log_loss)
{
float64_t etd = -eta * loss->first_derivative(z,1);
features->add_to_dense_vec(etd * y / wscale, i, w.vector, w.vlen);
if (use_bias)
{
if (use_regularized_bias)
bias *= 1 - eta * lambda * bscale;
bias += etd * y * bscale;
}
}
if (--count <= 0)
{
float64_t r = 1 - eta * lambda * skip;
if (r < 0.8)
r = pow(1 - eta * lambda, skip);
SGVector<float64_t>::scale_vector(r, w.vector, w.vlen);
count = skip;
}
t++;
}
}
float64_t wnorm = SGVector<float64_t>::dot(w.vector,w.vector, w.vlen);
SG_INFO("Norm: %.6f, Bias: %.6f\n", wnorm, bias)
return true;
}
void CSVMSGD::calibrate()
{
ASSERT(features)
int32_t num_vec=features->get_num_vectors();
int32_t c_dim=features->get_dim_feature_space();
ASSERT(num_vec>0)
ASSERT(c_dim>0)
float64_t* c=SG_MALLOC(float64_t, c_dim);
memset(c, 0, c_dim*sizeof(float64_t));
SG_INFO("Estimating sparsity and bscale num_vec=%d num_feat=%d.\n", num_vec, c_dim)
// compute average gradient size
int32_t n = 0;
float64_t m = 0;
float64_t r = 0;
for (int32_t j=0; j<num_vec && m<=1000; j++, n++)
{
r += features->get_nnz_features_for_vector(j);
features->add_to_dense_vec(1, j, c, c_dim, true);
//waste cpu cycles for readability
//(only changed dims need checking)
m=SGVector<float64_t>::max(c, c_dim);
}
// bias update scaling
bscale = 0.5*m/n;
// compute weight decay skip
skip = (int32_t) ((16 * n * c_dim) / r);
SG_INFO("using %d examples. skip=%d bscale=%.6f\n", n, skip, bscale)
SG_FREE(c);
}
void CSVMSGD::init()
{
t=1;
C1=1;
C2=1;
wscale=1;
bscale=1;
epochs=5;
skip=1000;
count=1000;
use_bias=true;
use_regularized_bias=false;
loss=new CHingeLoss();
SG_REF(loss);
m_parameters->add(&C1, "C1", "Cost constant 1.");
m_parameters->add(&C2, "C2", "Cost constant 2.");
m_parameters->add(&wscale, "wscale", "W scale");
m_parameters->add(&bscale, "bscale", "b scale");
m_parameters->add(&epochs, "epochs", "epochs");
m_parameters->add(&skip, "skip", "skip");
m_parameters->add(&count, "count", "count");
m_parameters->add(&use_bias, "use_bias", "Indicates if bias is used.");
m_parameters->add(&use_regularized_bias, "use_regularized_bias", "Indicates if bias is regularized.");
}
|
ncgomez17/OlympicGames
|
juegos_olimpicos/src/main/java/com/juegosolimpicos/services/impl/HeadquarterServiceImpl.java
|
<gh_stars>0
package com.juegosolimpicos.services.impl;
import com.juegosolimpicos.dto.IOlympicGamesDto;
import com.juegosolimpicos.exceptions.BaseException;
import com.juegosolimpicos.exceptions.ConflictException;
import com.juegosolimpicos.exceptions.EntityNotFoundException;
import com.juegosolimpicos.exceptions.ErrorCodeEnum;
import com.juegosolimpicos.mapper.CityMapper;
import com.juegosolimpicos.mapper.HeadquarterMapper;
import com.juegosolimpicos.mapper.OlympicGamesMapper;
import com.juegosolimpicos.mapper.TypeJjooMapper;
import com.juegosolimpicos.model.entities.sql.HeadquarterEntity;
import com.juegosolimpicos.model.entities.sql.HeadquarterPk;
import com.juegosolimpicos.model.repositories.IHeadquarterRepository;
import com.juegosolimpicos.openapi.model.*;
import com.juegosolimpicos.services.IHeadquarterService;
import com.juegosolimpicos.services.predicates.HeadquarterPredicates;
import com.juegosolimpicos.services.utils.PageableUtils;
import com.juegosolimpicos.ws.aop.ILogeable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Class to perform the different logical operations with the repository of the headquarter entity
*
* @author <EMAIL>
*/
@Service
@Transactional
@ILogeable
public class HeadquarterServiceImpl implements IHeadquarterService {
@Autowired private IHeadquarterRepository headquarterRepository;
@Autowired private HeadquarterMapper headquarterMapper;
@Autowired private TypeJjooMapper typeJjooMapper;
@Autowired private CityMapper cityMapper;
@Autowired private OlympicGamesMapper olympicGamesMapper;
@Autowired private CityServiceImpl cityService;
@Autowired private TypeJjooServiceImpl typeJjooService;
/**
* Function to return all headquarters
*
* @return list of HeadquarterDto
*/
@Override
public List<HeadquarterDto> getHeadquarters() {
return this.headquarterRepository.findAll().stream()
.map(headquarterMapper::toHeadquarterDto)
.collect(Collectors.toList());
}
public List<OlympicGamesDto> getOlympicGames() {
return this.headquarterRepository.findOlympicGames().stream()
.map(this.olympicGamesMapper::toOlympicGamesDto)
.collect(Collectors.toList());
}
/**
* save or update an entity
*
* @param headquarterDto
* @return entity HeadquarterDto
*/
@Override
public HeadquarterDto save(HeadquarterDto headquarterDto) throws BaseException {
Objects.requireNonNull(headquarterDto);
Objects.requireNonNull(headquarterDto.getId().getYear());
Objects.requireNonNull(headquarterDto.getId().getType());
Objects.requireNonNull(headquarterDto.getCity());
System.out.println(headquarterDto);
Boolean exists =
this.headquarterRepository.existsByYearAndType(
headquarterDto.getId().getYear(), headquarterDto.getId().getType().getId());
if (exists) {
throw new ConflictException(
ErrorCodeEnum.EXISTS_HEADQUARTER,
String.format(
"There is already a headquarter %s that was held in that year and with that type",
headquarterDto));
}
HeadquarterEntity headquarterEntity = new HeadquarterEntity();
HeadquarterPk headquarterId =
HeadquarterPk.builder()
.typeJjoo(headquarterDto.getCity().getId())
.year(headquarterDto.getId().getYear())
.build();
headquarterEntity.setId(headquarterId);
headquarterEntity.setTypeJjoo(
this.typeJjooMapper.toTypeJjooEntity(
this.typeJjooService.getById(headquarterDto.getId().getType().getId())));
headquarterEntity.setCity(
this.cityMapper.toCityEntity(this.cityService.getById(headquarterDto.getCity().getId())));
headquarterEntity = this.headquarterRepository.save(headquarterEntity);
return this.headquarterMapper.toHeadquarterDto(headquarterEntity);
}
/**
* @param year
* @param typeId
* @throws EntityNotFoundException if entity not exists
*/
@Override
public void deleteById(Integer year, Integer typeId) throws BaseException {
Objects.requireNonNull(year);
Objects.requireNonNull(typeId);
HeadquarterPk headquarterPk = HeadquarterPk.builder().year(year).typeJjoo(typeId).build();
this.headquarterRepository.delete(
this.headquarterRepository
.findById(headquarterPk)
.orElseThrow(
() ->
new EntityNotFoundException(
ErrorCodeEnum.NOT_FOUND_HEADQUARTER,
String.format(
"There is no headquarter with the id %s", headquarterPk))));
;
}
/**
* @param year
* @param typeId
* @return entity CityDto
* @throws EntityNotFoundException if entity not exists
*/
@Override
public HeadquarterDto getById(Integer year, Integer typeId) throws BaseException {
Objects.requireNonNull(year);
Objects.requireNonNull(typeId);
HeadquarterPk headquarterPk = HeadquarterPk.builder().year(year).typeJjoo(typeId).build();
HeadquarterEntity headquarterEntity = this.headquarterRepository.findById(headquarterPk)
.orElseThrow( () ->
new EntityNotFoundException(
ErrorCodeEnum.NOT_FOUND_HEADQUARTER,
String.format(
"There is no headquarter with the id %s", headquarterPk)));
return this.headquarterMapper.toHeadquarterDto(headquarterEntity);
}
public FindHeadquarterResponseDto findHeadquarterList(FindHeadquarterRequestDto headquarterRequestDto, Integer offSet, Integer limitParam,
String sortDirection, String sortProperty) {
FindHeadquarterResponseDto headquarterResponse = new FindHeadquarterResponseDto();
String property = Optional.ofNullable(sortProperty).orElse("id.year");
Pageable page = PageableUtils.createPageable(offSet,limitParam, sortDirection, property);
Page<HeadquarterEntity> headquarterPage = this.headquarterRepository.findAll(HeadquarterPredicates.findHeadquarterList(headquarterRequestDto), page);
if (!headquarterPage.getContent().isEmpty()) {
headquarterResponse = this.headquarterMapper.toFindHeadquarterResponseDto(headquarterPage);
}
return headquarterResponse;
}
public FindOlympicGamesResponseDto findOlympicGamesList(Integer offSet, Integer limitParam,
String sortDirection, String sortProperty) {
FindOlympicGamesResponseDto olympicGamesResponse = new FindOlympicGamesResponseDto();
String property = Optional.ofNullable(sortProperty).orElse("countryId");
Pageable page = PageableUtils.createPageable(offSet,limitParam, sortDirection, property);
Page<IOlympicGamesDto> olympicGamesPage = this.headquarterRepository.findOlympicGamesList(page);
if (!olympicGamesPage.getContent().isEmpty()) {
olympicGamesResponse = this.olympicGamesMapper.toFindOlympicGamesResponseDto(olympicGamesPage);
}
return olympicGamesResponse;
}
}
|
julian119988/crud-ecommerce-server
|
models/tables.model.js
|
module.exports = (sequelize, DataTypes) => {
const Products = sequelize.define(
"products",
{
name: {
type: DataTypes.STRING,
allowNull: false,
required: true,
},
description: {
type: DataTypes.STRING(512),
allowNull: false,
required: true,
},
image_url: {
type: DataTypes.STRING(2083),
allowNull: false,
required: true,
},
price: {
type: DataTypes.INTEGER,
allowNull: false,
required: true,
},
brand_id: {
type: DataTypes.INTEGER,
allowNull: false,
required: true,
},
},
{ underscored: true }
);
const Brands = sequelize.define(
"brands",
{
name: {
type: DataTypes.STRING,
allowNull: false,
required: true,
},
logo_url: {
type: DataTypes.STRING(2083),
allowNull: false,
required: true,
},
},
{ underscored: true }
);
const Users = sequelize.define("users", {
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
required: true,
},
password: {
type: DataTypes.STRING,
allowNull: false,
required: true,
},
admin: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: 0,
},
});
Products.belongsTo(Brands, { onDelete: "cascade", hooks: true });
return { Products, Brands, Users };
};
|
fsxfreak/esys-pbi
|
src/pupil/pupil_src/shared_modules/video_capture/uvc_backend.py
|
'''
(*)~---------------------------------------------------------------------------
Pupil - eye tracking platform
Copyright (C) 2012-2017 <NAME>
Distributed under the terms of the GNU
Lesser General Public License (LGPL v3.0).
See COPYING and COPYING.LESSER for license details.
---------------------------------------------------------------------------~(*)
'''
import time
import logging
import uvc
from .base_backend import InitialisationError, Base_Source, Base_Manager
# check versions for our own depedencies as they are fast-changing
assert uvc.__version__ >= '0.91'
# logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class UVC_Source(Base_Source):
"""
Camera Capture is a class that encapsualtes uvc.Capture:
"""
def __init__(self, g_pool, frame_size, frame_rate, name=None, preferred_names=(), uid=None, uvc_controls={}):
super().__init__(g_pool)
self.uvc_capture = None
self._restart_in = 3
assert name or preferred_names or uid
self.devices = uvc.Device_List()
devices_by_name = {dev['name']: dev for dev in self.devices}
# if uid is supplied we init with that
if uid:
try:
self.uvc_capture = uvc.Capture(uid)
except uvc.OpenError:
logger.warning("No avalilable camera found that matched {}".format(preferred_names))
except uvc.InitError:
logger.error("Camera failed to initialize.")
except uvc.DeviceNotFoundError:
logger.warning("No camera found that matched {}".format(preferred_names))
# otherwise we use name or preffered_names
else:
if name:
preferred_names = (name,)
else:
pass
assert preferred_names
# try to init by name
for name in preferred_names:
for d_name in devices_by_name.keys():
if name in d_name:
uid_for_name = devices_by_name[d_name]['uid']
try:
self.uvc_capture = uvc.Capture(uid_for_name)
except uvc.OpenError:
logger.info("{} matches {} but is already in use or blocked.".format(uid_for_name, name))
except uvc.InitError:
logger.error("Camera failed to initialize.")
else:
break
# check if we were sucessfull
if not self.uvc_capture:
logger.error("Init failed. Capture is started in ghost mode. No images will be supplied.")
self.name_backup = preferred_names
self.frame_size_backup = frame_size
self.frame_rate_backup = frame_rate
else:
self.configure_capture(frame_size, frame_rate, uvc_controls)
self.name_backup = (self.name,)
self.frame_size_backup = frame_size
self.frame_rate_backup = frame_rate
def configure_capture(self, frame_size, frame_rate, uvc_controls):
# Set camera defaults. Override with previous settings afterwards
if 'C930e' in self.uvc_capture.name:
logger.debug('Timestamp offset for c930 applied: -0.1sec')
self.ts_offset = -0.1
else:
self.ts_offset = 0.0
# UVC setting quirks:
controls_dict = dict([(c.display_name, c) for c in self.uvc_capture.controls])
self.frame_size = frame_size
self.frame_rate = frame_rate
for c in self.uvc_capture.controls:
try:
if c.display_name == 'White Balance temperature':
c.display_name = 'White Balance Temperature'
elif c.display_name == 'White Balance temperature,Auto':
c.display_name = 'White Balance Temperature, Auto'
c.value = uvc_controls[c.display_name]
except KeyError:
logger.debug('No UVC setting "{}" found from settings.'.format(c.display_name))
try:
controls_dict['Auto Focus'].value = 0
except KeyError:
pass
if ("Pupil Cam1" in self.uvc_capture.name or
"USB2.0 Camera" in self.uvc_capture.name):
if ("ID0" in self.uvc_capture.name or "ID1" in self.uvc_capture.name):
self.uvc_capture.bandwidth_factor = 1.3
try: controls_dict['Auto Exposure Priority'].value = 0
except KeyError: pass
try: controls_dict['Auto Exposure Mode'].value = 1
except KeyError: pass
try:controls_dict['Saturation'].value = 0
except KeyError: pass
try: controls_dict['Absolute Exposure Time'].value = 63
except KeyError: pass
try: controls_dict['Backlight Compensation'].value = 2
except KeyError: pass
try: controls_dict['Gamma'].value = 100
except KeyError: pass
else:
self.uvc_capture.bandwidth_factor = 2.0
try: controls_dict['Auto Exposure Priority'].value = 1
except KeyError: pass
else:
self.uvc_capture.bandwidth_factor = 3.0
try: controls_dict['Auto Focus'].value = 0
except KeyError: pass
def _re_init_capture(self, uid):
current_size = self.uvc_capture.frame_size
current_fps = self.uvc_capture.frame_rate
current_uvc_controls = self._get_uvc_controls()
self.deinit_gui()
self.uvc_capture.close()
self.uvc_capture = uvc.Capture(uid)
self.configure_capture(current_size, current_fps, current_uvc_controls)
self.init_gui()
def _init_capture(self, uid):
self.deinit_gui()
self.uvc_capture = uvc.Capture(uid)
self.configure_capture(self.frame_size_backup, self.frame_rate_backup, self._get_uvc_controls())
self.init_gui()
def _re_init_capture_by_names(self, names):
# burn-in test specific. Do not change text!
self.devices.update()
for d in self.devices:
for name in names:
if d['name'] == name:
logger.info("Found device. {}.".format(name))
if self.uvc_capture:
self._re_init_capture(d['uid'])
else:
self._init_capture(d['uid'])
return
raise InitialisationError('Could not find Camera {} during re initilization.'.format(names))
def _restart_logic(self):
if self._restart_in <= 0:
if self.uvc_capture:
logger.warning("Capture failed to provide frames. Attempting to reinit.")
self.name_backup = (self.uvc_capture.name,)
self.uvc_capture = None
try:
self._re_init_capture_by_names(self.name_backup)
except (InitialisationError, uvc.InitError):
time.sleep(0.02)
self.deinit_gui()
self.init_gui()
self._restart_in = int(5/0.02)
else:
self._restart_in -= 1
def recent_events(self, events):
try:
frame = self.uvc_capture.get_frame(0.05)
frame.timestamp = self.g_pool.get_timestamp()+self.ts_offset
except uvc.StreamError:
self._recent_frame = None
self._restart_logic()
except (AttributeError, uvc.InitError):
self._recent_frame = None
time.sleep(0.02)
self._restart_logic()
else:
self._recent_frame = frame
events['frame'] = frame
self._restart_in = 3
def _get_uvc_controls(self):
d = {}
if self.uvc_capture:
for c in self.uvc_capture.controls:
d[c.display_name] = c.value
return d
def get_init_dict(self):
d = super().get_init_dict()
d['frame_size'] = self.frame_size
d['frame_rate'] = self.frame_rate
if self.uvc_capture:
d['name'] = self.name
d['uvc_controls'] = self._get_uvc_controls()
else:
d['preferred_names'] = self.name_backup
return d
@property
def name(self):
if self.uvc_capture:
return self.uvc_capture.name
else:
return "Ghost capture"
@property
def frame_size(self):
if self.uvc_capture:
return self.uvc_capture.frame_size
else:
return self.frame_size_backup
@frame_size.setter
def frame_size(self, new_size):
# closest match for size
sizes = [abs(r[0]-new_size[0]) for r in self.uvc_capture.frame_sizes]
best_size_idx = sizes.index(min(sizes))
size = self.uvc_capture.frame_sizes[best_size_idx]
if tuple(size) != tuple(new_size):
logger.warning("%s resolution capture mode not available. Selected {}.".format(new_size, size))
self.uvc_capture.frame_size = size
self.frame_size_backup = size
@property
def frame_rate(self):
if self.uvc_capture:
return self.uvc_capture.frame_rate
else:
return self.frame_rate_backup
@frame_rate.setter
def frame_rate(self, new_rate):
# closest match for rate
rates = [abs(r-new_rate) for r in self.uvc_capture.frame_rates]
best_rate_idx = rates.index(min(rates))
rate = self.uvc_capture.frame_rates[best_rate_idx]
if rate != new_rate:
logger.warning("{}fps capture mode not available at ({}) on '{}'. Selected {}fps. ".format(
new_rate, self.uvc_capture.frame_size, self.uvc_capture.name, rate))
self.uvc_capture.frame_rate = rate
self.frame_rate_backup = rate
@property
def jpeg_support(self):
return True
@property
def online(self):
return bool(self.uvc_capture)
def init_gui(self):
from pyglui import ui
ui_elements = []
# lets define some helper functions:
def gui_load_defaults():
for c in self.uvc_capture.controls:
try:
c.value = c.def_val
except:
pass
def gui_update_from_device():
for c in self.uvc_capture.controls:
c.refresh()
def set_frame_size(new_size):
self.frame_size = new_size
if self.uvc_capture is None:
ui_elements.append(ui.Info_Text('Capture initialization faild.'))
self.g_pool.capture_source_menu.extend(ui_elements)
return
ui_elements.append(ui.Info_Text('{} Controls'.format(self.name)))
sensor_control = ui.Growing_Menu(label='Sensor Settings')
sensor_control.append(ui.Info_Text("Do not change these during calibration or recording!"))
sensor_control.collapsed = False
image_processing = ui.Growing_Menu(label='Image Post Processing')
image_processing.collapsed = True
sensor_control.append(ui.Selector(
'frame_size', self,
setter=set_frame_size,
selection=self.uvc_capture.frame_sizes,
label='Resolution'
))
def frame_rate_getter():
return (self.uvc_capture.frame_rates, [str(fr) for fr in self.uvc_capture.frame_rates])
sensor_control.append(ui.Selector('frame_rate', self, selection_getter=frame_rate_getter, label='Frame rate'))
for control in self.uvc_capture.controls:
c = None
ctl_name = control.display_name
# now we add controls
if control.d_type == bool:
c = ui.Switch('value', control, label=ctl_name, on_val=control.max_val, off_val=control.min_val)
elif control.d_type == int:
c = ui.Slider('value', control, label=ctl_name, min=control.min_val, max=control.max_val, step=control.step)
elif type(control.d_type) == dict:
selection = [value for name, value in control.d_type.items()]
labels = [name for name, value in control.d_type.items()]
c = ui.Selector('value', control, label=ctl_name, selection=selection, labels=labels)
else:
pass
# if control['disabled']:
# c.read_only = True
# if ctl_name == 'Exposure, Auto Priority':
# # the controll should always be off. we set it to 0 on init (see above)
# c.read_only = True
if c is not None:
if control.unit == 'processing_unit':
image_processing.append(c)
else:
sensor_control.append(c)
ui_elements.append(sensor_control)
if image_processing.elements:
ui_elements.append(image_processing)
ui_elements.append(ui.Button("refresh",gui_update_from_device))
ui_elements.append(ui.Button("load defaults",gui_load_defaults))
self.g_pool.capture_source_menu.extend(ui_elements)
def cleanup(self):
self.devices.cleanup()
self.devices = None
if self.uvc_capture:
self.uvc_capture.close()
self.uvc_capture = None
super().cleanup()
class UVC_Manager(Base_Manager):
"""Manages local USB sources
Attributes:
check_intervall (float): Intervall in which to look for new UVC devices
"""
gui_name = 'Local USB'
def __init__(self, g_pool):
super().__init__(g_pool)
self.devices = uvc.Device_List()
def get_init_dict(self):
return {}
def init_gui(self):
from pyglui import ui
ui_elements = []
ui_elements.append(ui.Info_Text('Local UVC sources'))
def dev_selection_list():
default = (None, 'Select to activate')
self.devices.update()
dev_pairs = [default] + [(d['uid'], d['name']) for d in self.devices]
return zip(*dev_pairs)
def activate(source_uid):
if not source_uid:
return
if not uvc.is_accessible(source_uid):
logger.error("The selected camera is already in use or blocked.")
return
settings = {
'frame_size': self.g_pool.capture.frame_size,
'frame_rate': self.g_pool.capture.frame_rate,
'uid': source_uid
}
if self.g_pool.process == 'world':
self.notify_all({'subject': 'start_plugin', "name": "UVC_Source", 'args': settings})
else:
self.notify_all({'subject': 'start_eye_capture', 'target': self.g_pool.process, "name": "UVC_Source", 'args': settings})
ui_elements.append(ui.Selector(
'selected_source',
selection_getter=dev_selection_list,
getter=lambda: None,
setter=activate,
label='Activate source'
))
self.g_pool.capture_selector_menu.extend(ui_elements)
def cleanup(self):
self.deinit_gui()
self.devices.cleanup()
self.devices = None
def recent_events(self, events):
pass
|
Priyansh863/e-backend
|
Lib/site-packages/opt_einsum/backends/cupy.py
|
<reponame>Priyansh863/e-backend
"""
Required functions for optimized contractions of numpy arrays using cupy.
"""
import numpy as np
from ..sharing import to_backend_cache_wrap
__all__ = ["to_cupy", "build_expression", "evaluate_constants"]
@to_backend_cache_wrap
def to_cupy(array): # pragma: no cover
import cupy
if isinstance(array, np.ndarray):
return cupy.asarray(array)
return array
def build_expression(_, expr): # pragma: no cover
"""Build a cupy function based on ``arrays`` and ``expr``.
"""
def cupy_contract(*arrays):
return expr._contract([to_cupy(x) for x in arrays], backend='cupy').get()
return cupy_contract
def evaluate_constants(const_arrays, expr): # pragma: no cover
"""Convert constant arguments to cupy arrays, and perform any possible
constant contractions.
"""
return expr(*[to_cupy(x) for x in const_arrays], backend='cupy', evaluate_constants=True)
|
vis4rd/db_project_2021
|
doc/html/search/functions_8.js
|
var searchData=
[
['placeformsection_169',['placeFormSection',['../class_application.html#a81f066df3ca1cdae16028a15a952a94b',1,'Application']]],
['placemenusection_170',['placeMenuSection',['../class_application.html#abb3ba6361b4dc0042031ea66ae6fe544',1,'Application']]]
];
|
jan-zajic/kotlin-eclipse
|
kotlin-eclipse-core/src/org/jetbrains/kotlin/core/debug/KotlinSourceLookupNavigator.java
|
<gh_stars>100-1000
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* 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.jetbrains.kotlin.core.debug;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.model.ISourceLocator;
import org.eclipse.debug.core.sourcelookup.ISourceContainer;
import org.eclipse.debug.core.sourcelookup.ISourceLookupDirector;
import org.eclipse.jdt.debug.core.IJavaStackFrame;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.core.builder.KotlinPsiManager;
import org.jetbrains.kotlin.core.log.KotlinLogger;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.psi.KtFile;
public class KotlinSourceLookupNavigator {
public static final KotlinSourceLookupNavigator INSTANCE = new KotlinSourceLookupNavigator();
private KotlinSourceLookupNavigator() {
}
// From JDI model we obtain path to file as "some/pckg/File.kt" and Java seeks file in folder some/pckg what might be wrong
@Nullable
public IFile findKotlinSourceFile(@NotNull IJavaStackFrame frame) {
ISourceLocator sourceLocator = frame.getLaunch().getSourceLocator();
if (!(sourceLocator instanceof ISourceLookupDirector)) {
return null;
}
try {
return findKotlinSourceFile(frame, (ISourceLookupDirector) sourceLocator);
} catch (CoreException e) {
KotlinLogger.logAndThrow(e);
}
return null;
}
private IFile findKotlinSourceFile(IJavaStackFrame frame, ISourceLookupDirector lookupDirector) throws CoreException {
boolean isFindDuplicates = lookupDirector.isFindDuplicates();
try {
lookupDirector.setFindDuplicates(true);
return findKotlinSourceFile(lookupDirector, frame);
} finally {
lookupDirector.setFindDuplicates(isFindDuplicates);
}
}
@Nullable
private IFile findKotlinSourceFile(@NotNull ISourceLookupDirector lookupDirector, @NotNull IJavaStackFrame frame) throws CoreException {
String sourceName = frame.getSourceName();
if (sourceName == null) return null;
FqName declaringPackage = new FqName(frame.getDeclaringTypeName()).parent();
for (ISourceContainer sourceContainer : lookupDirector.getSourceContainers()) {
Object[] elements = sourceContainer.findSourceElements(sourceName);
for (Object element : elements) {
if (!(element instanceof IFile)) {
continue;
}
IFile kotlinFile = (IFile) element;
if (fileMatches(kotlinFile, declaringPackage, sourceName)) {
return kotlinFile;
}
}
}
return null;
}
private boolean fileMatches(@NotNull IFile kotlinFile, @NotNull FqName packageName, @NotNull String sourceName) {
boolean isKotlinSourceFile = kotlinFile.getName().equals(sourceName) && KotlinPsiManager.INSTANCE.existsSourceFile(kotlinFile);
if (isKotlinSourceFile) {
KtFile jetFile = KotlinPsiManager.INSTANCE.getParsedFile(kotlinFile);
if (jetFile.getPackageFqName().equals(packageName)) {
return true;
}
}
return false;
}
}
|
dmaciaszek/pac4j
|
pac4j-openid/src/main/java/org/pac4j/openid/credentials/extractor/YahooCredentialsExtractor.java
|
<filename>pac4j-openid/src/main/java/org/pac4j/openid/credentials/extractor/YahooCredentialsExtractor.java
package org.pac4j.openid.credentials.extractor;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.message.ParameterList;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.credentials.extractor.CredentialsExtractor;
import org.pac4j.core.util.CommonHelper;
import org.pac4j.openid.client.YahooOpenIdClient;
import org.pac4j.openid.credentials.OpenIdCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
/**
* Credentials extractor for Yahoo.
*
* @author <NAME>
* @since 2.0.0
*/
public class YahooCredentialsExtractor implements CredentialsExtractor<OpenIdCredentials> {
private static final Logger logger = LoggerFactory.getLogger(YahooCredentialsExtractor.class);
private static final String OPENID_MODE = "openid.mode";
private static final String CANCEL_MODE = "cancel";
private YahooOpenIdClient client;
public YahooCredentialsExtractor(final YahooOpenIdClient client) {
CommonHelper.assertNotNull("client", client);
this.client = client;
}
@Override
public Optional<OpenIdCredentials> extract(final WebContext context) {
final String mode = context.getRequestParameter(OPENID_MODE).orElse(null);
// cancelled authentication
if (CommonHelper.areEquals(mode, CANCEL_MODE)) {
logger.debug("authentication cancelled");
return Optional.empty();
}
// parameters list returned by the provider
final ParameterList parameterList = new ParameterList(context.getRequestParameters());
// retrieve the previously stored discovery information
final DiscoveryInformation discoveryInformation = (DiscoveryInformation) context
.getSessionStore().get(context, this.client.getDiscoveryInformationSessionAttributeName()).orElse(null);
// create credentials
final OpenIdCredentials credentials = new OpenIdCredentials(discoveryInformation, parameterList);
logger.debug("credentials: {}", credentials);
return Optional.of(credentials);
}
}
|
adamnok/linden
|
componens/linden-package-flowers/src/main/scala/linden/flowers/dynamic.scala
|
/*
* MIT LICENCE
*
* Copyright (c) 2021 <NAME> [<EMAIL>]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package linden.flowers
import org.scalajs.dom.{Element, document, window}
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.Random
@Experimental
object dynamic {
def awaitElementById(id: String): Future[Element] = {
val promise = Promise[Element]
awaitElementByIdWithNative(id) { element =>
promise.trySuccess(element)
}
promise.future
}
def awaitElementByIds(ids: Seq[String])(implicit ec: ExecutionContext): Future[Seq[Element]] =
Future.sequence(ids.map(awaitElementById))
def awaitElementByIds(id_1: String, id_2: String)(implicit ec: ExecutionContext): Future[(Element, Element)] =
awaitElementByIds(Seq(id_1, id_2)).map {
case Seq(a, b) => a -> b
}
def awaitElementByIds(id_1: String, id_2: String, id_3: String)(implicit ec: ExecutionContext): Future[(Element, Element, Element)] =
awaitElementByIds(Seq(id_1, id_2, id_3)).map {
case Seq(it_1, it_2, it_3) => (it_1, it_2, it_3)
}
def awaitElementByIds(id_1: String, id_2: String, id_3: String, id_4: String)(implicit ec: ExecutionContext): Future[(Element, Element, Element, Element)] =
awaitElementByIds(Seq(id_1, id_2, id_3, id_4)).map {
case Seq(it_1, it_2, it_3, it_4) => (it_1, it_2, it_3, it_4)
}
def awaitElementByIds(id_1: String, id_2: String, id_3: String, id_4: String, id_5: String)(implicit ec: ExecutionContext): Future[(Element, Element, Element, Element, Element)] =
awaitElementByIds(Seq(id_1, id_2, id_3, id_4, id_5)).map {
case Seq(it_1, it_2, it_3, it_4, it_5) => (it_1, it_2, it_3, it_4, it_5)
}
def awaitElementByIdWithNative(id: String)(callback: Element => Unit): Unit = {
repeater(5) { () =>
val element = document.getElementById(id)
if (element != null) {
callback(element)
false
} else true
}
}
def repeater[L, R](timeout: Int)(callback: () => Boolean): Unit = {
val repeatable = callback()
if (repeatable)
window.setTimeout({ () => repeater[L, R](timeout)(callback) }, timeout)
}
def randomIdForDOM(prefix: String): String = prefix + Random.alphanumeric.take(30).mkString("")
}
|
uscliufei/TouMai-Net
|
app/src/main/java/com/runer/toumai/dao/AddImageDao.java
|
package com.runer.toumai.dao;
import android.content.Context;
import com.fasterxml.jackson.databind.JsonNode;
import com.loopj.android.http.RequestParams;
import com.orhanobut.logger.Logger;
import com.runer.net.IDao;
import com.runer.net.RequestCode;
import com.runer.net.interf.INetResult;
import com.runer.toumai.base.Constant;
import com.runer.toumai.net.NetConfig;
import com.runer.toumai.net.NetInter;
import com.runer.toumai.net.RunnerParam;
import com.runer.toumai.util.AppUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
/**
* Created by szhua on 2017/9/7/007.
* github:https://github.com/szhua
* TouMaiNetApp
* AddImageDao
*/
public class AddImageDao extends IDao {
public AddImageDao(Context context, INetResult iNetResult) {
super(context, iNetResult);
}
@Override
public void onRequestSuccess(JsonNode result, int requestCode) throws IOException {
}
public void addImagList(String goods_id, File img , String cover ){
RequestParams requestParams =new RequestParams() ;
RunnerParam param = new RunnerParam();
param.put("goods_id",goods_id );
param.put("cover",cover );
JSONObject jsonObject = new JSONObject();
try {
if(param!=null)
for (Object key : param.keySet()) {
jsonObject.put((String)key,param.get(key));
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
requestParams.put("img",img);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String timesnamp = String.valueOf(System.currentTimeMillis());
String sign = getSign(NetInter.ADD_IMG,timesnamp);
requestParams.put("openid", Constant.OPEN_ID);
requestParams.put("sign",sign);
requestParams.put("a",NetInter.ADD_IMG.getA());
requestParams.put("c",NetInter.ADD_IMG.getC());
requestParams.put("param",jsonObject.toString());
requestParams.put("timesnamp",timesnamp);
//打印请求参数;
Logger.d(requestParams);
requestParams.setForceMultipartEntityContentType(true);
requestParams.setAutoCloseInputStreams(true);
originalPostRequest(NetConfig.BASE_REQUEST_URL,requestParams, RequestCode.CODE_1);
}
public String getSign(NetInter netInter ,String timesnamp){
String forSign = netInter.getA() + netInter.getC() + timesnamp
+ Constant.TOKEN;
String sign = AppUtil.md5(AppUtil.md5(forSign));
return sign ;
}
}
|
DFE-Digital/login.dfe.applications
|
src/app/services/upsertServiceBanner.js
|
<reponame>DFE-Digital/login.dfe.applications
const { upsertServiceBanner } = require('./data');
const logger = require('./../../infrastructure/logger');
const validate = (req) => {
const model = {
banner: {
bannerId: req.body.id,
serviceId: req.params.id,
name: req.body.name,
title: req.body.title,
message: req.body.message,
validFrom: req.body.validFrom,
validTo: req.body.validTo,
isActive: req.body.isActive,
},
errors: [],
};
if (!model.banner.serviceId) {
model.errors.push('serviceId must be specified');
}
if (!model.banner.name) {
model.errors.push('name must be specified');
}
if (!model.banner.title) {
model.errors.push('title must be specified');
}
if (!model.banner.message) {
model.errors.push('message must be specified');
}
return model;
};
const upsertBanner = async (req, res) => {
const model = validate(req);
if (model.errors.length > 0) {
return res.status(400).json({
errors: model.errors,
});
}
try {
logger.info(`Processing upsert service banner request. CorrelationId: ${req.correlationId}`);
const banner = await upsertServiceBanner(
model.banner.bannerId,
model.banner.serviceId,
model.banner.name,
model.banner.title,
model.banner.message,
model.banner.validFrom,
model.banner.validTo,
model.banner.isActive,
);
return res.status(202).json(banner);
} catch (e) {
logger.error(`Error processing upsert service banner request - ${e.message}. CorrelationId: ${req.correlationId}`);
throw e;
}
};
module.exports = upsertBanner;
|
zipated/src
|
third_party/blink/renderer/core/editing/commands/selection_for_undo_step.cc
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/editing/commands/selection_for_undo_step.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/selection_template.h"
#include "third_party/blink/renderer/core/editing/text_affinity.h"
#include "third_party/blink/renderer/core/editing/visible_selection.h"
namespace blink {
SelectionForUndoStep SelectionForUndoStep::From(
const SelectionInDOMTree& selection) {
SelectionForUndoStep result;
result.base_ = selection.Base();
result.extent_ = selection.Extent();
result.affinity_ = selection.Affinity();
result.is_base_first_ = selection.IsBaseFirst();
return result;
}
SelectionForUndoStep::SelectionForUndoStep(const SelectionForUndoStep& other) =
default;
SelectionForUndoStep::SelectionForUndoStep() = default;
SelectionForUndoStep& SelectionForUndoStep::operator=(
const SelectionForUndoStep& other) = default;
bool SelectionForUndoStep::operator==(const SelectionForUndoStep& other) const {
if (IsNone())
return other.IsNone();
if (other.IsNone())
return false;
return base_ == other.base_ && extent_ == other.extent_ &&
affinity_ == other.affinity_ && is_base_first_ == other.is_base_first_;
}
bool SelectionForUndoStep::operator!=(const SelectionForUndoStep& other) const {
return !operator==(other);
}
SelectionInDOMTree SelectionForUndoStep::AsSelection() const {
if (IsNone()) {
return SelectionInDOMTree();
}
return SelectionInDOMTree::Builder()
.SetBaseAndExtent(base_, extent_)
.SetAffinity(affinity_)
.Build();
}
Position SelectionForUndoStep::Start() const {
return is_base_first_ ? base_ : extent_;
}
Position SelectionForUndoStep::End() const {
return is_base_first_ ? extent_ : base_;
}
bool SelectionForUndoStep::IsCaret() const {
return base_.IsNotNull() && base_ == extent_;
}
bool SelectionForUndoStep::IsNone() const {
return base_.IsNull();
}
bool SelectionForUndoStep::IsRange() const {
return base_ != extent_;
}
bool SelectionForUndoStep::IsValidFor(const Document& document) const {
if (base_.IsNull())
return true;
return base_.IsValidFor(document) && extent_.IsValidFor(document);
}
void SelectionForUndoStep::Trace(blink::Visitor* visitor) {
visitor->Trace(base_);
visitor->Trace(extent_);
}
// ---
SelectionForUndoStep::Builder::Builder() = default;
SelectionForUndoStep::Builder&
SelectionForUndoStep::Builder::SetBaseAndExtentAsBackwardSelection(
const Position& base,
const Position& extent) {
DCHECK(base.IsNotNull());
DCHECK(extent.IsNotNull());
DCHECK_NE(base, extent);
selection_.base_ = base;
selection_.extent_ = extent;
selection_.is_base_first_ = false;
return *this;
}
SelectionForUndoStep::Builder&
SelectionForUndoStep::Builder::SetBaseAndExtentAsForwardSelection(
const Position& base,
const Position& extent) {
DCHECK(base.IsNotNull());
DCHECK(extent.IsNotNull());
DCHECK_NE(base, extent);
selection_.base_ = base;
selection_.extent_ = extent;
selection_.is_base_first_ = true;
return *this;
}
void SelectionForUndoStep::Builder::Trace(blink::Visitor* visitor) {
visitor->Trace(selection_);
}
// ---
VisibleSelection CreateVisibleSelection(
const SelectionForUndoStep& selection_in_undo_step) {
return CreateVisibleSelection(selection_in_undo_step.AsSelection());
}
} // namespace blink
|
Mortimyrrh/Mycelia-Forge
|
build/tmp/expandedArchives/forge-1.16.5-36.1.0_mapped_official_1.16.5-sources.jar_01fb3b8234f72f7172716347a075bc60/net/minecraft/command/impl/ParticleCommand.java
|
<filename>build/tmp/expandedArchives/forge-1.16.5-36.1.0_mapped_official_1.16.5-sources.jar_01fb3b8234f72f7172716347a075bc60/net/minecraft/command/impl/ParticleCommand.java
package net.minecraft.command.impl;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.FloatArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.command.arguments.EntityArgument;
import net.minecraft.command.arguments.ParticleArgument;
import net.minecraft.command.arguments.Vec3Argument;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.particles.IParticleData;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.text.TranslationTextComponent;
public class ParticleCommand {
private static final SimpleCommandExceptionType ERROR_FAILED = new SimpleCommandExceptionType(new TranslationTextComponent("commands.particle.failed"));
public static void register(CommandDispatcher<CommandSource> p_198563_0_) {
p_198563_0_.register(Commands.literal("particle").requires((p_198568_0_) -> {
return p_198568_0_.hasPermission(2);
}).then(Commands.argument("name", ParticleArgument.particle()).executes((p_198562_0_) -> {
return sendParticles(p_198562_0_.getSource(), ParticleArgument.getParticle(p_198562_0_, "name"), p_198562_0_.getSource().getPosition(), Vector3d.ZERO, 0.0F, 0, false, p_198562_0_.getSource().getServer().getPlayerList().getPlayers());
}).then(Commands.argument("pos", Vec3Argument.vec3()).executes((p_201226_0_) -> {
return sendParticles(p_201226_0_.getSource(), ParticleArgument.getParticle(p_201226_0_, "name"), Vec3Argument.getVec3(p_201226_0_, "pos"), Vector3d.ZERO, 0.0F, 0, false, p_201226_0_.getSource().getServer().getPlayerList().getPlayers());
}).then(Commands.argument("delta", Vec3Argument.vec3(false)).then(Commands.argument("speed", FloatArgumentType.floatArg(0.0F)).then(Commands.argument("count", IntegerArgumentType.integer(0)).executes((p_198565_0_) -> {
return sendParticles(p_198565_0_.getSource(), ParticleArgument.getParticle(p_198565_0_, "name"), Vec3Argument.getVec3(p_198565_0_, "pos"), Vec3Argument.getVec3(p_198565_0_, "delta"), FloatArgumentType.getFloat(p_198565_0_, "speed"), IntegerArgumentType.getInteger(p_198565_0_, "count"), false, p_198565_0_.getSource().getServer().getPlayerList().getPlayers());
}).then(Commands.literal("force").executes((p_198561_0_) -> {
return sendParticles(p_198561_0_.getSource(), ParticleArgument.getParticle(p_198561_0_, "name"), Vec3Argument.getVec3(p_198561_0_, "pos"), Vec3Argument.getVec3(p_198561_0_, "delta"), FloatArgumentType.getFloat(p_198561_0_, "speed"), IntegerArgumentType.getInteger(p_198561_0_, "count"), true, p_198561_0_.getSource().getServer().getPlayerList().getPlayers());
}).then(Commands.argument("viewers", EntityArgument.players()).executes((p_198566_0_) -> {
return sendParticles(p_198566_0_.getSource(), ParticleArgument.getParticle(p_198566_0_, "name"), Vec3Argument.getVec3(p_198566_0_, "pos"), Vec3Argument.getVec3(p_198566_0_, "delta"), FloatArgumentType.getFloat(p_198566_0_, "speed"), IntegerArgumentType.getInteger(p_198566_0_, "count"), true, EntityArgument.getPlayers(p_198566_0_, "viewers"));
}))).then(Commands.literal("normal").executes((p_198560_0_) -> {
return sendParticles(p_198560_0_.getSource(), ParticleArgument.getParticle(p_198560_0_, "name"), Vec3Argument.getVec3(p_198560_0_, "pos"), Vec3Argument.getVec3(p_198560_0_, "delta"), FloatArgumentType.getFloat(p_198560_0_, "speed"), IntegerArgumentType.getInteger(p_198560_0_, "count"), false, p_198560_0_.getSource().getServer().getPlayerList().getPlayers());
}).then(Commands.argument("viewers", EntityArgument.players()).executes((p_198567_0_) -> {
return sendParticles(p_198567_0_.getSource(), ParticleArgument.getParticle(p_198567_0_, "name"), Vec3Argument.getVec3(p_198567_0_, "pos"), Vec3Argument.getVec3(p_198567_0_, "delta"), FloatArgumentType.getFloat(p_198567_0_, "speed"), IntegerArgumentType.getInteger(p_198567_0_, "count"), false, EntityArgument.getPlayers(p_198567_0_, "viewers"));
})))))))));
}
private static int sendParticles(CommandSource p_198564_0_, IParticleData p_198564_1_, Vector3d p_198564_2_, Vector3d p_198564_3_, float p_198564_4_, int p_198564_5_, boolean p_198564_6_, Collection<ServerPlayerEntity> p_198564_7_) throws CommandSyntaxException {
int i = 0;
for(ServerPlayerEntity serverplayerentity : p_198564_7_) {
if (p_198564_0_.getLevel().sendParticles(serverplayerentity, p_198564_1_, p_198564_6_, p_198564_2_.x, p_198564_2_.y, p_198564_2_.z, p_198564_5_, p_198564_3_.x, p_198564_3_.y, p_198564_3_.z, (double)p_198564_4_)) {
++i;
}
}
if (i == 0) {
throw ERROR_FAILED.create();
} else {
p_198564_0_.sendSuccess(new TranslationTextComponent("commands.particle.success", Registry.PARTICLE_TYPE.getKey(p_198564_1_.getType()).toString()), true);
return i;
}
}
}
|
FStoeltie/themaopdracht04
|
examples/courses/v1th04/practicum1/main.c
|
// blink a LED on pin PIO1_4
//
// This is a very simple blink-a-LED application.
// It aims to show direct use of the hardware rather than
// good programming practices (like abstracting from the GPIO pin
// used and using a timer for the delay).
//
// It uses the CMSIS header file to access the direction
// and value registers for pin GPIO1_4.
// It uses a busy-wait for the delay, which can be affected
// by the compiler and optimization settings used.
//
// Note that after a reset the GPIO1_4 pin is automatically
// configured as GPIO, hence there is no need to configure
// the pin. Some other pins are NOT configured to GPIO by a reset,
// hence blinking on such a pin requires the additional step of
// configuring the pin as GPIO.
//
// includes the cmsis definitions for the LPC1114
#include "bmptk.h"
#include "pins.h"
#include "servo.h"
#include "timer.h"
void disable_others() {
int prep_port, prep_pin;
for(prep_pin = 4; prep_pin < 8; prep_pin++) {
//if(prep_pin > 4)
// prep_port = 1;
pin_set(prep_port, prep_pin, 0);
}
pin_set(1, 4, 0);
pin_set(1, 5, 0);
pin_set(1, 8, 0);
pin_set(1, 9, 0);
}
void week1() {
// must be volatile to prevent optimization of the wait loops
volatile int i;
// make PIO1_4 an output
//LPC_GPIO1->DIR = LPC_GPIO1->DIR | 0x10;
int prep_port = 0, prep_pin;
for(prep_pin = 4; prep_pin < 8; prep_pin++) {
//if(prep_pin > 4)
// prep_port = 1;
pin_configure_as_output(prep_port, prep_pin);
}
pin_configure_as_output(1, 4);
pin_configure_as_output(1, 5);
pin_configure_as_output(1, 8);
pin_configure_as_output(1, 9);
int current_led = 0;
// loop forever
while( 1 ){
#define count_down 40000
for(current_led = 4; current_led < 8; current_led++) {
for( i = 0; i < count_down; i++ ){
}
disable_others();
pin_set(0, current_led, 1);
for( i = 0; i < count_down; i++ ){
}
}
for(current_led = 4; current_led < 6; current_led++) {
for( i = 0; i < count_down; i++ ){
}
disable_others();
pin_set(1, current_led, 1);
for( i = 0; i < count_down; i++ ){
}
}
for(current_led = 8; current_led < 10; current_led++) {
for( i = 0; i < count_down; i++ ){
}
disable_others();
pin_set(1, current_led, 1);
for( i = 0; i < count_down; i++ ){
}
}
}
}
void week2_servo() {
}
int main( void ){
unsigned int n;
servo_init(1, 5);
timer_init();
for(;;){
for(n = 600; n < 2200; n = n + 10) {
servo_pulse(1, 5, n);
//servo_pulse( 1, 5, 2500 );
await(now() + 50 * 700);
}
/* await( now() + 50 * 1000 );
servo_pulse( 1, 4, 1000 );
await( now() + 50 * 1000 );
servo_pulse( 1, 4, 1500 );
await( now() + 50 * 1000 );*/
/* for( n = 500; n < 2500; n = n + 10 ){
servo_pulse( 1, 4, 500 );
await( now() + 50 * 1000 );
} */
}
}
|
austin-starks/Zetta
|
test/fixture/portscanner.js
|
<reponame>austin-starks/Zetta<gh_stars>100-1000
var portscanner = require('portscanner');
var async = require('async');
module.exports = find;
function find(obj, cb) {
var startPort = obj.startingPort || 3000;
var ports = [];
async.until(function(){
return ports.length > obj.count;
}, function(next) {
portscanner.findAPortNotInUse(startPort, 650000, '127.0.0.1', function(error, port) {
if (!error) {
startPort = ++port;
ports.push(port);
}
next();
});
}, function(err) {
cb(err, ports);
});
}
|
fexter-svk/C90-Compiler-EIE2
|
test/c_compiler/int_18/int_18.c
|
int main(){
int j = 10, z = 120;
int i = 2;
i &= 20 + j;
i |= 20 + i + z;
return i;
}
|
derpferd/aws-sdk-cpp
|
aws-cpp-sdk-application-insights/include/aws/application-insights/model/ApplicationInfo.h
|
<filename>aws-cpp-sdk-application-insights/include/aws/application-insights/model/ApplicationInfo.h
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/application-insights/ApplicationInsights_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace ApplicationInsights
{
namespace Model
{
/**
* <p>Describes the status of the application.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/application-insights-2018-11-25/ApplicationInfo">AWS
* API Reference</a></p>
*/
class AWS_APPLICATIONINSIGHTS_API ApplicationInfo
{
public:
ApplicationInfo();
ApplicationInfo(Aws::Utils::Json::JsonView jsonValue);
ApplicationInfo& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The name of the resource group used for the application.</p>
*/
inline const Aws::String& GetResourceGroupName() const{ return m_resourceGroupName; }
/**
* <p>The name of the resource group used for the application.</p>
*/
inline bool ResourceGroupNameHasBeenSet() const { return m_resourceGroupNameHasBeenSet; }
/**
* <p>The name of the resource group used for the application.</p>
*/
inline void SetResourceGroupName(const Aws::String& value) { m_resourceGroupNameHasBeenSet = true; m_resourceGroupName = value; }
/**
* <p>The name of the resource group used for the application.</p>
*/
inline void SetResourceGroupName(Aws::String&& value) { m_resourceGroupNameHasBeenSet = true; m_resourceGroupName = std::move(value); }
/**
* <p>The name of the resource group used for the application.</p>
*/
inline void SetResourceGroupName(const char* value) { m_resourceGroupNameHasBeenSet = true; m_resourceGroupName.assign(value); }
/**
* <p>The name of the resource group used for the application.</p>
*/
inline ApplicationInfo& WithResourceGroupName(const Aws::String& value) { SetResourceGroupName(value); return *this;}
/**
* <p>The name of the resource group used for the application.</p>
*/
inline ApplicationInfo& WithResourceGroupName(Aws::String&& value) { SetResourceGroupName(std::move(value)); return *this;}
/**
* <p>The name of the resource group used for the application.</p>
*/
inline ApplicationInfo& WithResourceGroupName(const char* value) { SetResourceGroupName(value); return *this;}
/**
* <p>The lifecycle of the application. </p>
*/
inline const Aws::String& GetLifeCycle() const{ return m_lifeCycle; }
/**
* <p>The lifecycle of the application. </p>
*/
inline bool LifeCycleHasBeenSet() const { return m_lifeCycleHasBeenSet; }
/**
* <p>The lifecycle of the application. </p>
*/
inline void SetLifeCycle(const Aws::String& value) { m_lifeCycleHasBeenSet = true; m_lifeCycle = value; }
/**
* <p>The lifecycle of the application. </p>
*/
inline void SetLifeCycle(Aws::String&& value) { m_lifeCycleHasBeenSet = true; m_lifeCycle = std::move(value); }
/**
* <p>The lifecycle of the application. </p>
*/
inline void SetLifeCycle(const char* value) { m_lifeCycleHasBeenSet = true; m_lifeCycle.assign(value); }
/**
* <p>The lifecycle of the application. </p>
*/
inline ApplicationInfo& WithLifeCycle(const Aws::String& value) { SetLifeCycle(value); return *this;}
/**
* <p>The lifecycle of the application. </p>
*/
inline ApplicationInfo& WithLifeCycle(Aws::String&& value) { SetLifeCycle(std::move(value)); return *this;}
/**
* <p>The lifecycle of the application. </p>
*/
inline ApplicationInfo& WithLifeCycle(const char* value) { SetLifeCycle(value); return *this;}
/**
* <p>The issues on the user side that are blocking Application Insights from fully
* monitoring the application.</p>
*/
inline const Aws::String& GetRemarks() const{ return m_remarks; }
/**
* <p>The issues on the user side that are blocking Application Insights from fully
* monitoring the application.</p>
*/
inline bool RemarksHasBeenSet() const { return m_remarksHasBeenSet; }
/**
* <p>The issues on the user side that are blocking Application Insights from fully
* monitoring the application.</p>
*/
inline void SetRemarks(const Aws::String& value) { m_remarksHasBeenSet = true; m_remarks = value; }
/**
* <p>The issues on the user side that are blocking Application Insights from fully
* monitoring the application.</p>
*/
inline void SetRemarks(Aws::String&& value) { m_remarksHasBeenSet = true; m_remarks = std::move(value); }
/**
* <p>The issues on the user side that are blocking Application Insights from fully
* monitoring the application.</p>
*/
inline void SetRemarks(const char* value) { m_remarksHasBeenSet = true; m_remarks.assign(value); }
/**
* <p>The issues on the user side that are blocking Application Insights from fully
* monitoring the application.</p>
*/
inline ApplicationInfo& WithRemarks(const Aws::String& value) { SetRemarks(value); return *this;}
/**
* <p>The issues on the user side that are blocking Application Insights from fully
* monitoring the application.</p>
*/
inline ApplicationInfo& WithRemarks(Aws::String&& value) { SetRemarks(std::move(value)); return *this;}
/**
* <p>The issues on the user side that are blocking Application Insights from fully
* monitoring the application.</p>
*/
inline ApplicationInfo& WithRemarks(const char* value) { SetRemarks(value); return *this;}
private:
Aws::String m_resourceGroupName;
bool m_resourceGroupNameHasBeenSet;
Aws::String m_lifeCycle;
bool m_lifeCycleHasBeenSet;
Aws::String m_remarks;
bool m_remarksHasBeenSet;
};
} // namespace Model
} // namespace ApplicationInsights
} // namespace Aws
|
xge/megamol
|
plugins/mesh/src/Utility.cpp
|
<filename>plugins/mesh/src/Utility.cpp<gh_stars>10-100
#include "mesh/Utility.h"
namespace megamol {
namespace mesh {
namespace utility {
std::tuple<VertexPositions, VertexNormals, QuadIndices> tessellateFace(
glm::vec3 v00, glm::vec3 v10, glm::vec3 v11, glm::vec3 v01, unsigned int u_subdivs, unsigned int v_subdivs) {
VertexPositions vertex_positions;
VertexNormals vertex_normals;
QuadIndices quad_indices;
auto normal = -1.0f * glm::cross(glm::normalize(v10 - v00), glm::normalize(v01 - v00));
// compute vertex positions using bilinear interpolation
for (int v = 0; v <= v_subdivs + 1; ++v) {
auto lambda_v = static_cast<float>(v) / static_cast<float>(v_subdivs + 1);
auto p_v_0 = lambda_v * v00 + (1.0f - lambda_v) * v01;
auto p_v_1 = lambda_v * v10 + (1.0f - lambda_v) * v11;
for (int u = 0; u <= u_subdivs + 1; ++u) {
auto lambda_u = static_cast<float>(u) / static_cast<float>(u_subdivs + 1);
auto p = lambda_u * p_v_0 + (1.0f - lambda_u) * p_v_1;
vertex_positions.push_back({p.x, p.y, p.z});
vertex_normals.push_back({normal.x, normal.y, normal.z});
}
}
// iterate subdivs again and create faces
for (int v = 0; v < v_subdivs + 1; ++v) {
for (int u = 0; u < u_subdivs + 1; ++u) {
// # faces per row = # u_subdivs + vertices on edges
uint32_t base_idx = v * (u_subdivs + 2) + u;
quad_indices.push_back(
{base_idx, base_idx + 1, base_idx + (u_subdivs + 2) + 1, base_idx + (u_subdivs + 2)});
}
}
return std::make_tuple<VertexPositions, VertexNormals, QuadIndices>(
std::move(vertex_positions), std::move(vertex_normals), std::move(quad_indices));
}
} // namespace utility
} // namespace mesh
} // namespace megamol
|
ViktorHirin/NFT-Tax-Tool
|
src/views/pages/Default/index.js
|
<reponame>ViktorHirin/NFT-Tax-Tool<gh_stars>1-10
import { useEffect, useState } from 'react';
// material-ui
import { Grid, Typography, useMediaQuery, Button } from '@mui/material';
import { useTheme } from '@mui/material/styles';
// Import EventBus
import EventBus from 'hooks/eventBus';
import ReactExport from 'react-export-excel-fixed-xlsx';
// project imports
import { gridSpacing } from 'store/constant';
import TableStickyHead from 'components/TableStickyHead';
import PopularCard from './PopularCard';
import MainCard from 'ui-component/cards/MainCard';
import { IconShare, IconAccessPoint, IconCircles, IconCreditCard } from '@tabler/icons';
import RevenueCard from 'ui-component/cards/Skeleton/RevenueCard';
import DialogSlide from 'ui-elements/advance/UIDialog/AlertDialogSlide';
const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;
const ExcelColumn = ReactExport.ExcelFile.ExcelColumn;
// ==============================|| DEFAULT DASHBOARD ||============================== //
const Dashboard = () => {
const [isLoading, setLoading] = useState(true);
const [loading, setRLoading] = useState(false);
const theme = useTheme();
const matchDownXs = useMediaQuery(theme.breakpoints.down('sm'));
const blockSX = {
p: 2.5,
borderLeft: '1px solid ',
borderBottom: '1px solid ',
borderLeftColor: theme.palette.mode === 'dark' ? theme.palette.dark.main : theme.palette.grey[200],
borderBottomColor: theme.palette.mode === 'dark' ? theme.palette.dark.main : theme.palette.grey[200]
};
const [sent, setSent] = useState(0);
const [received, setReceived] = useState(0);
const [fee, setFee] = useState(0);
const [revenue, setRevenue] = useState(0);
const [dataForExcel, setDataForExcel] = useState([
{
address: '',
sent: 0,
received: 0,
trading_fee: 0,
revenue: 0
}
]);
const [dataForExcel2, setDataForExcel2] = useState([
{
method: '',
amount: ''
}
]);
const fixedPriceDecimals = (_price) => {
const fixed = Number(_price).toFixed(4);
return fixed;
};
const initialStates = () => {
setSent(0);
setReceived(0);
setFee(0);
setRevenue(0);
};
useEffect(() => {
setLoading(false);
EventBus.on('initialize', (e) => {
initialStates();
});
EventBus.on('show-revenue', (e) => {
console.log('taxdata', e.taxdata);
initialStates();
setRLoading(true);
setSent(Math.abs(fixedPriceDecimals(e.sent)));
setRevenue(fixedPriceDecimals(e.revenue));
setFee(fixedPriceDecimals(e.gas));
setReceived(fixedPriceDecimals(e.received));
setDataForExcel2(e.taxdata);
setDataForExcel([
{
address: e.addr,
sent: Math.abs(fixedPriceDecimals(e.sent)),
received: fixedPriceDecimals(e.received),
trading_fee: fixedPriceDecimals(e.gas),
revenue: fixedPriceDecimals(e.revenue)
}
]);
setRLoading(false);
});
}, []);
return (
<>
<DialogSlide />
<Grid container spacing={gridSpacing}>
<Grid item xs={12} sm={8}>
<TableStickyHead isLoading={isLoading} />
</Grid>
<Grid item xs={12} sm={4}>
<Grid container spacing={gridSpacing}>
<Grid item xs={12}>
<Grid container spacing={gridSpacing}>
<Grid item xs={12}>
<MainCard
content={false}
sx={{
'& svg': {
width: 50,
height: 50,
color: theme.palette.secondary.main,
borderRadius: '14px',
p: 1.25,
bgcolor: theme.palette.mode === 'dark' ? theme.palette.background.default : 'primary.light'
}
}}
>
{loading ? (
<RevenueCard />
) : (
<>
<Grid container alignItems="center" spacing={0}>
<Grid item xs={12} sm={6} sx={blockSX}>
<Grid
container
alignItems="center"
spacing={1}
justifyContent={matchDownXs ? 'space-between' : 'center'}
>
<Grid item>
<IconShare stroke={1.5} />
</Grid>
<Grid item sm zeroMinWidth>
<Typography variant="h5" align="center">
$ {sent}
</Typography>
<Typography variant="subtitle2" align="center">
Sent
</Typography>
</Grid>
</Grid>
</Grid>
<Grid item xs={12} sm={6} sx={blockSX}>
<Grid
container
alignItems="center"
spacing={1}
justifyContent={matchDownXs ? 'space-between' : 'center'}
>
<Grid item>
<IconAccessPoint stroke={1.5} />
</Grid>
<Grid item sm zeroMinWidth>
<Typography variant="h5" align="center">
$ {received}
</Typography>
<Typography variant="subtitle2" align="center">
Received
</Typography>
</Grid>
</Grid>
</Grid>
</Grid>
<Grid container alignItems="center" spacing={0}>
<Grid item xs={12} sm={6} sx={blockSX}>
<Grid
container
alignItems="center"
spacing={1}
justifyContent={matchDownXs ? 'space-between' : 'center'}
>
<Grid item>
<IconCircles stroke={1.5} />
</Grid>
<Grid item sm zeroMinWidth>
<Typography variant="h5" align="center">
$ {fee}
</Typography>
<Typography variant="subtitle2" align="center">
Trading Fee
</Typography>
</Grid>
</Grid>
</Grid>
<Grid item xs={12} sm={6} sx={blockSX}>
<Grid
container
alignItems="center"
spacing={1}
justifyContent={matchDownXs ? 'space-between' : 'center'}
>
<Grid item>
<IconCreditCard stroke={1.5} />
</Grid>
<Grid item sm zeroMinWidth>
<Typography variant="h5" align="center">
$ {revenue}
</Typography>
<Typography variant="subtitle2" align="center">
Revenue
</Typography>
</Grid>
</Grid>
</Grid>
</Grid>
<Grid container alignItems="center" spacing={0}>
<Grid item xs={12} sm={12} sx={blockSX}>
{Number(revenue) !== 0 && (
<ExcelFile
element={
<Button variant="outlined" disabled={Number(revenue) === 0}>
Download Data
</Button>
}
filename="RevenueData"
>
<ExcelSheet data={dataForExcel} name="Revenue">
<ExcelColumn label="Address" value="address" />
<ExcelColumn label="Sent ($)" value="sent" />
<ExcelColumn label="Received ($)" value="received" />
<ExcelColumn label="Trading Fee ($)" value="trading_fee" />
<ExcelColumn label="Revenue ($)" value="revenue" />
</ExcelSheet>
<ExcelSheet data={dataForExcel2} name="Tax Data">
<ExcelColumn label="Method" value="method" />
<ExcelColumn label="Amount ($)" value="amount" />
</ExcelSheet>
</ExcelFile>
)}
</Grid>
</Grid>
</>
)}
</MainCard>
</Grid>
</Grid>
</Grid>
<Grid item xs={12} sm={12}>
<PopularCard isLoading={isLoading} />
</Grid>
</Grid>
</Grid>
</Grid>
</>
);
};
export default Dashboard;
|
NumberAI/python-bandwidth-iris
|
examples/rate_center.py
|
<reponame>NumberAI/python-bandwidth-iris
import sys
from iris_sdk import Client, RateCenters, RestError
if len(sys.argv) < 2:
sys.exit("usage: python rate_center.py [state], e.g.:\n" +
"python rate_center.py NJ")
rate_centers = RateCenters(client=Client(filename="config.cfg"))
print("\n")
try:
centers = rate_centers.list({"state": sys.argv[1]})
except RestError as error:
sys.exit(error)
print("\ntotal for search: " + (rate_centers.total_count or ""))
for rc in centers.items:
print((rc.abbreviation or "") + " (" + (rc.name or "") + ")")
|
gitwyy/prometheus
|
aphrodite-model/src/main/java/com/pay/aphrodite/model/entity/HqlTaskLog.java
|
package com.pay.aphrodite.model.entity;
public class HqlTaskLog extends BaseEntity<HqlTaskLog>{
private String lfsPath;
private String taskStep;
private String taskNo;
public String getLfsPath() {
return lfsPath;
}
public HqlTaskLog setLfsPath(String lfsPath) {
this.lfsPath = lfsPath;
return this;
}
public String getTaskStep() {
return taskStep;
}
public HqlTaskLog setTaskStep(String taskStep) {
this.taskStep = taskStep;
return this;
}
public String getTaskNo() {
return taskNo;
}
public HqlTaskLog setTaskNo(String taskNo) {
this.taskNo = taskNo;
return this;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("HqlTaskLog{");
sb.append("lfsPath='").append(lfsPath).append('\'');
sb.append(", taskStep='").append(taskStep).append('\'');
sb.append(", taskNo='").append(taskNo).append('\'');
sb.append(", id=").append(id);
sb.append(", createTime=").append(createTime);
sb.append(", optimistic='").append(optimistic).append('\'');
sb.append(", remark='").append(remark).append('\'');
sb.append(", operator='").append(operator).append('\'');
sb.append('}');
return sb.toString();
}
}
|
ndennu/appPattern
|
AppPattern/app/src/main/java/com/example/ndennu/apppattern/TaskActivity.java
|
package com.example.ndennu.apppattern;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import com.example.ndennu.apppattern.adapter.TaskAdapter;
import com.example.ndennu.apppattern.adapter.TodoViewHolder;
import com.example.ndennu.todolib.Observer.ConcreteObservable;
import com.example.ndennu.todolib.Observer.Observer;
import com.example.ndennu.todolib.PrototypeFactory;
import com.example.ndennu.todolib.SQLite.DatabaseAccess;
import com.example.ndennu.todolib.SQLite.DatabaseFacade;
import com.example.ndennu.todolib.SQLite.Request;
import com.example.ndennu.todolib.memento.TodoObjectStateMemory;
import com.example.ndennu.todolib.model.Project;
import com.example.ndennu.todolib.model.Task;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class TaskActivity extends AppCompatActivity implements Observer<Task>,
TodoItemTouchHelper.TodoItemTouchHelperListener {
public static String ID_PROJECT = "ID_PROJECT";
public static int ITEM_REQUEST_CODE = 1449;
@BindView(R.id.recycler_task)
RecyclerView recyclerTask;
private TaskAdapter taskAdapter;
private Project projectParent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
ButterKnife.bind(this);
recyclerTask.setLayoutManager(new LinearLayoutManager(this));
initList(getIntent().getIntExtra(ID_PROJECT, 1));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ITEM_REQUEST_CODE) {
initList(projectParent.getId());
}
}
@Override
public void update(Task task, Request request) {
if (Request.UPDATE == request) {
for (int i = 0; i < projectParent.getTasks().size(); i++) {
if (projectParent.getTasks().get(i).getId() == task.getId())
projectParent.getTasks().get(i).setText(task.getText());
}
}
if (Request.INSERT == request) {
projectParent.add(task);
taskAdapter.notifyDataSetChanged();
openPopup(task);
}
if (Request.DELETE == request)
projectParent.remove(task);
ConcreteObservable.getINSTANCE().removeObserver(TaskActivity.this);
taskAdapter.notifyDataSetChanged();
}
@OnClick(R.id.add_task)
public void addTask() {
Task t = (Task) new PrototypeFactory().getPrototypes(Task.class);
if (t == null) {
Log.e("INSERT_TASK", "ERROR INSERT TASK");
}
ConcreteObservable.getINSTANCE().addObserver(TaskActivity.this);
DatabaseAccess.getInstance(TaskActivity.this).insertTask(projectParent.getId(), t);
}
private void initList(int idProject) {
fetchAllTaskFromProject(idProject);
setTitle(projectParent.getText());
taskAdapter = new TaskAdapter(projectParent.getTasks());
setOnClickItem();
setOnClickImg();
recyclerTask.setAdapter(taskAdapter);
}
private void fetchAllTaskFromProject(int idProject) {
projectParent = DatabaseAccess.getInstance(TaskActivity.this).getProjectById(idProject);
}
private void setOnClickItem() {
ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new TodoItemTouchHelper(0, ItemTouchHelper.LEFT, this);
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerTask);
taskAdapter.setListener(new TaskAdapter.Listener() {
@Override
public void onClick(Task task) {
Intent intent = new Intent(TaskActivity.this, SubtaskActivity.class);
intent.putExtra(SubtaskActivity.ID_TASK, task.getId());
startActivityForResult(intent, ITEM_REQUEST_CODE);
}
});
}
private void setOnClickImg() {
taskAdapter.setEditListener(new TaskAdapter.EditListener() {
@Override
public void onEdit(final Task task) {
openPopup(task);
}
});
}
private void openPopup(final Task task) {
final TodoObjectStateMemory memory = new TodoObjectStateMemory();
memory.setMemento(task.getMemento());
LayoutInflater inflater = TaskActivity.this.getLayoutInflater();
final View v = inflater.inflate(R.layout.popup_edit, null);
((EditText) v.findViewById(R.id.edit_text)).setText(task.getText());
AlertDialog.Builder alert = new AlertDialog.Builder(TaskActivity.this)
.setTitle("Edit")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
task.setText(((EditText) v.findViewById(R.id.edit_text)).getText().toString());
ConcreteObservable.getINSTANCE().addObserver(TaskActivity.this);
DatabaseAccess.getInstance(TaskActivity.this).updateTask(task);
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
task.retoreMemento(memory.getMemento());
}
});
alert.setView(v);
alert.show();
}
@Override
public void onSwiped(TodoViewHolder viewHolder, int direction, final int position) {
new AlertDialog.Builder(TaskActivity.this)
.setTitle("Delete")
.setMessage("Are you sur want to delete ?")
.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ConcreteObservable.getINSTANCE().addObserver(TaskActivity.this);
if (DatabaseFacade.deleteTask(TaskActivity.this, taskAdapter.getTaskList().get(position), projectParent.getId())) {
ConcreteObservable.getINSTANCE().notifyObservers(taskAdapter.getTaskList().get(position), Request.DELETE);
}
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {}
})
.show();
}
}
|
jingcao80/Elastos
|
Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/pm/CrossProfileIntentFilter.cpp
|
//=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/server/pm/CrossProfileIntentFilter.h"
#include "elastos/droid/server/pm/CPackageManagerService.h"
#include "elastos/droid/server/pm/Settings.h"
#include "elastos/droid/internal/utility/XmlUtils.h"
#include <elastos/core/StringUtils.h>
#include <elastos/core/StringBuilder.h>
using Elastos::Core::StringUtils;
using Elastos::Core::StringBuilder;
using Elastos::Droid::Os::IUserHandle;
using Elastos::Droid::Internal::Utility::XmlUtils;
using Elastos::Droid::Utility::ILogHelper;
namespace Elastos {
namespace Droid {
namespace Server {
namespace Pm {
const String CrossProfileIntentFilter::ATTR_TARGET_USER_ID("targetUserId");
const String CrossProfileIntentFilter::ATTR_FLAGS("flags");
const String CrossProfileIntentFilter::ATTR_OWNER_USER_ID("ownerUserId");
const String CrossProfileIntentFilter::ATTR_OWNER_PACKAGE("wnerPackage");
const String CrossProfileIntentFilter::ATTR_FILTER("filter");
const String CrossProfileIntentFilter::TAG("CrossProfileIntentFilter");
ECode CrossProfileIntentFilter::constructor(
/* [in] */ IIntentFilter* filter)
{
return IntentFilter::constructor(filter);
}
CrossProfileIntentFilter::CrossProfileIntentFilter(
/* [in] */ const String& ownerPackage,
/* [in] */ Int32 ownerUserId,
/* [in] */ Int32 targetUserId,
/* [in] */ Int32 flags)
: mTargetUserId(targetUserId)
, mOwnerUserId(ownerUserId)
, mOwnerPackage(ownerPackage)
, mFlags(flags)
{}
CrossProfileIntentFilter::CrossProfileIntentFilter(
/* [in] */ IXmlPullParser* parser)
: mTargetUserId(0)
, mOwnerUserId(0)
, mFlags(0)
{
mTargetUserId = GetInt32FromXml(parser, ATTR_TARGET_USER_ID, IUserHandle::USER_NULL);
mOwnerUserId = GetInt32FromXml(parser, ATTR_OWNER_USER_ID, IUserHandle::USER_NULL);
mOwnerPackage = GetStringFromXml(parser, ATTR_OWNER_PACKAGE, String(""));
mFlags = GetInt32FromXml(parser, ATTR_FLAGS, 0);
Int32 outerDepth;
parser->GetDepth(&outerDepth);
String tagName;
parser->GetName(&tagName);
Int32 type, depth;
while ((parser->Next(&type), type != IXmlPullParser::END_DOCUMENT)
&& (type != IXmlPullParser::END_TAG || (parser->GetDepth(&depth), depth > outerDepth))) {
parser->GetName(&tagName);
if (type == IXmlPullParser::END_TAG || type == IXmlPullParser::TEXT) {
continue;
}
else if (type == IXmlPullParser::START_TAG) {
if (tagName.Equals(ATTR_FILTER)) {
break;
}
else {
String des;
parser->GetPositionDescription(&des);
String msg = String("Unknown element under ")
+ Settings::TAG_CROSS_PROFILE_INTENT_FILTERS + ": " + tagName + " at "
+ des;
CPackageManagerService::ReportSettingsProblem(ILogHelper::WARN, msg);
XmlUtils::SkipCurrentTag(parser);
}
}
}
if (tagName.Equals(ATTR_FILTER)) {
ReadFromXml(parser);
}
else {
String des;
parser->GetPositionDescription(&des);
String msg = String("Missing element under ") + TAG + ": " + ATTR_FILTER +
" at " + des;
CPackageManagerService::ReportSettingsProblem(ILogHelper::WARN, msg);
XmlUtils::SkipCurrentTag(parser);
}
}
Int32 CrossProfileIntentFilter::GetTargetUserId()
{
return mTargetUserId;
}
Int32 CrossProfileIntentFilter::GetFlags()
{
return mFlags;
}
Int32 CrossProfileIntentFilter::GetOwnerUserId()
{
return mOwnerUserId;
}
String CrossProfileIntentFilter::GetOwnerPackage()
{
return mOwnerPackage;
}
String CrossProfileIntentFilter::GetStringFromXml(
/* [in] */ IXmlPullParser* parser,
/* [in] */ const String& attribute,
/* [in] */ const String& defaultValue)
{
String value;
parser->GetAttributeValue(String(NULL), attribute, &value);
if (value.IsNull()) {
String des;
parser->GetPositionDescription(&des);
String msg = String("Missing element under ") + TAG +": " + attribute + " at " + des;
CPackageManagerService::ReportSettingsProblem(ILogHelper::WARN, msg);
return defaultValue;
}
else {
return value;
}
}
Int32 CrossProfileIntentFilter::GetInt32FromXml(
/* [in] */ IXmlPullParser* parser,
/* [in] */ const String& attribute,
/* [in] */ Int32 defaultValue)
{
String stringValue = GetStringFromXml(parser, attribute, String(NULL));
if (!stringValue.IsNull()) {
return StringUtils::ParseInt32(stringValue);
}
return defaultValue;
}
ECode CrossProfileIntentFilter::WriteToXml(
/* [in] */ IXmlSerializer* serializer)
{
serializer->WriteAttribute(String(NULL), ATTR_TARGET_USER_ID, StringUtils::ToString(mTargetUserId));
serializer->WriteAttribute(String(NULL), ATTR_FLAGS, StringUtils::ToString(mFlags));
serializer->WriteAttribute(String(NULL), ATTR_OWNER_USER_ID, StringUtils::ToString(mOwnerUserId));
serializer->WriteAttribute(String(NULL), ATTR_OWNER_PACKAGE, mOwnerPackage);
serializer->WriteStartTag(String(NULL), ATTR_FILTER);
IntentFilter::WriteToXml(serializer);
serializer->WriteEndTag(String(NULL), ATTR_FILTER);
return NOERROR;
}
ECode CrossProfileIntentFilter::ToString(
/* [out] */ String* str)
{
VALIDATE_NOT_NULL(str)
StringBuilder sb("CrossProfileIntentFilter{0x");
sb += StringUtils::ToHexString((Int32)this);
sb += " ";
sb += mTargetUserId;
sb += "}";
*str = sb.ToString();
return NOERROR;
}
} // namespace Pm
} // namespace Server
} // namespace Droid
} // namespace Elastos
|
Arodev76/L2Advanced
|
src/main/java/l2f/gameserver/model/reward/RewardList.java
|
<reponame>Arodev76/L2Advanced
package l2f.gameserver.model.reward;
import java.util.ArrayList;
import java.util.List;
import l2f.gameserver.model.Player;
/**
* @reworked VISTALL
*/
@SuppressWarnings("serial")
public class RewardList extends ArrayList<RewardGroup>
{
public static final int MAX_CHANCE = 1000000;
private final RewardType _type;
private final boolean _autoLoot;
public RewardList(RewardType rewardType, boolean a)
{
super(5);
_type = rewardType;
_autoLoot = a;
}
public List<RewardItem> roll(Player player)
{
return roll(player, 1.0, false, false);
}
public List<RewardItem> roll(Player player, double mod)
{
return roll(player, mod, false, false);
}
public List<RewardItem> roll(Player player, double mod, boolean isRaid)
{
return roll(player, mod, isRaid, false);
}
public List<RewardItem> roll(Player player, double mod, boolean isRaid, boolean isSiegeGuard)
{
List<RewardItem> temp = new ArrayList<RewardItem>(size());
for (RewardGroup g : this)
{
List<RewardItem> tdl = g.roll(_type, player, mod, isRaid, isSiegeGuard);
if (!tdl.isEmpty())
for (RewardItem itd : tdl)
temp.add(itd);
}
return temp;
}
public boolean validate()
{
for (RewardGroup g : this)
{
int chanceSum = 0; // сумма шансов группы
for (RewardData d : g.getItems())
chanceSum += d.getChance();
if (chanceSum <= MAX_CHANCE) // всё в порядке?
return true;
double mod = MAX_CHANCE / chanceSum;
for (RewardData d : g.getItems())
{
double chance = d.getChance() * mod; // коррекция шанса группы
d.setChance(chance);
g.setChance(MAX_CHANCE);
}
}
return false;
}
public boolean isAutoLoot()
{
return _autoLoot;
}
public RewardType getType()
{
return _type;
}
}
|
JJhuk/study_emu
|
chip8/src/main.cpp
|
<reponame>JJhuk/study_emu
#include <iostream>
#include <atomic>
#include <thread>
#include <gl/gl3w.h>
#include <GLFW/glfw3.h>
#include "hardware/Chip8.h"
#include <chrono>
/*
void ReadCh(std::atomic<bool>& run)
{
std::string buffer;
int input;
while (run.load())
{
input = _getch();
if (input == '0')
{
run.store(false);
}
}
}
*/
GLuint program;
GLuint vao;
GLint mv_location;
GLint proj_ortho;
GLint position_location;
Chip8 chip8;
void startup()
{
static const char * vs_source[] =
{
"#version 420 core \n"
" \n"
"in vec2 position;\n"
"uniform mat4 proj_ortho; \n"
"void main(void) \n"
"{ \n"
" gl_Position = proj_ortho * vec4(position.xy, 0.0, 1.0); \n"
"} \n"
};
static const char * fs_source[] =
{
"#version 420 core \n"
" \n"
"out vec4 color; \n"
" \n"
"void main(void) \n"
"{ \n"
" color = vec4(0.0, 0.8, 1.0, 1.0); \n"
"} \n"
};
program = glCreateProgram();
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fs, 1, fs_source, NULL);
glCompileShader(fs);
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vs, 1, vs_source, NULL);
glCompileShader(vs);
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
proj_ortho = glGetUniformLocation(program, "proj_ortho");
position_location = glGetAttribLocation(program, "position");
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glEnableVertexAttribArray(position_location);
glVertexAttribPointer(position_location, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, (GLvoid*)0); // offset set.
}
constexpr float HEIGHT = 320.f;
constexpr float WIDTH = 640.f;
void draw( float x, float y)
{
const float ortho_projection[4][4] =
{
{ 2.0f/ WIDTH, 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f / -HEIGHT, 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{-1.0f, 1.0f, 0.0f, 1.0f },
};
glUseProgram(program);
glPointSize(10.0f);
glUniformMatrix4fv(proj_ortho, 1, GL_FALSE, &ortho_projection[0][0]);
glVertexAttrib2f(position_location, x, y);
glDrawArrays(GL_POINTS, 0, 1);
}
void render( Chip8 & chip8 )
{
for( int y = 0; y < 32; y++ )
{
for (int x = 0; x < 64; x++)
{
if( chip8.getScreenData( x, y ) != 0 )
{
draw( x * 10, y * 10 );
}
}
}
}
struct KeyBind
{
int key; int bind;
};
static KeyBind keyMap[] = {
{ GLFW_KEY_1, 0x0 },
{ GLFW_KEY_2, 0x1 },
{ GLFW_KEY_3, 0x2 },
{ GLFW_KEY_4, 0x3 },
{ GLFW_KEY_Q, 0x4 },
{ GLFW_KEY_W, 0x5 },
{ GLFW_KEY_E, 0x6 },
{ GLFW_KEY_R, 0x7 },
{ GLFW_KEY_A, 0x8 },
{ GLFW_KEY_S, 0x9 },
{ GLFW_KEY_D, 0xA },
{ GLFW_KEY_F, 0xB },
{ GLFW_KEY_Z, 0xC },
{ GLFW_KEY_X, 0xD },
{ GLFW_KEY_C, 0xE },
{ GLFW_KEY_V, 0xF },
};
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
BYTE bind = 0xff;
for ( auto & key_bind : keyMap )
{
if( key == key_bind.key )
{
bind = key_bind.bind;
break;
}
}
if(bind == 0xff)
{
return;
}
if( action == GLFW_PRESS )
{
chip8.addInput( bind );
return;
}
if ( action == GLFW_RELEASE )
{
chip8.upInput( bind );
return;
}
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS)
{
}
}
#ifdef _CHIP8_DISASM_BUILD
int main() // 디스어셈블러 빌드
{
chip8.reset();
chip8.loadRom();
while( !chip8.isEOF() )
{
chip8.nextStep();
}
chip8.createDisASMFile();
}
#endif
#ifndef _CHIP8_DISASM_BUILD
int main()
{
float color[4] = {0.51f, 0.44f, 0.51f, 1.0f};
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, false);
glfwWindowHint(GLFW_SAMPLES, 4);
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "CHIP - 8", nullptr, nullptr);
glfwMakeContextCurrent(window);
if (gl3wInit()) {
fprintf(stderr, "failed to initialize OpenGL\n");
return -1;
}
std::atomic<bool> run(true);
chip8.reset();
chip8.loadRom();
startup();
double lastTime = 0.0;
const double maxFPS = 240.0;
const double maxPeriod = 1.0 / maxFPS;
glfwSetKeyCallback(window, key_callback);
static const GLfloat black[] = { 0.0f, 0.0f, 0.0f, 1.0f };
while (!glfwWindowShouldClose(window))
{
double time = glfwGetTime();
//glViewport(0, 0, 640, 320);
//glClearColor(color[0], color[1], color[2], color[3]);
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glfwPollEvents();
glClearBufferfv(GL_COLOR, 0, black);
render( chip8 );
glfwSwapBuffers(window);
#ifdef __CHIP8_DEBUG
if ( glfwGetKey ( window, GLFW_KEY_SPACE ) )
{
#endif
chip8.nextStep();
#ifdef __CHIP8_DEBUG
}
#endif
while ( time - lastTime < maxPeriod )
{
time = glfwGetTime();
glfwPollEvents();
}
lastTime = glfwGetTime();
}
return 0;
}
#endif // _CHIP8_DISASM_BUILD
|
andy-v-h/hollow
|
pkg/api/v1/server.go
|
package hollow
import (
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/volatiletech/null/v8"
"go.metalkube.net/hollow/internal/models"
)
// Server represents a server in a facility
type Server struct {
UUID uuid.UUID `json:"uuid"`
Name string `json:"name"`
FacilityCode string `json:"facility"`
Attributes []Attributes `json:"attributes"`
Components []ServerComponent `json:"components"`
VersionedAttributes []VersionedAttributes `json:"versioned_attributes"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (r *Router) getServers(c *gin.Context, params ServerListParams) (models.ServerSlice, int64, error) {
mods := params.queryMods()
count, err := models.Servers(mods...).Count(c.Request.Context(), r.DB)
if err != nil {
return nil, 0, err
}
// add pagination
mods = append(mods, params.PaginationParams.queryMods()...)
s, err := models.Servers(mods...).All(c.Request.Context(), r.DB)
if err != nil {
return s, 0, err
}
return s, count, nil
}
func (s *Server) fromDBModel(dbS *models.Server) error {
var err error
s.UUID, err = uuid.Parse(dbS.ID)
if err != nil {
return err
}
s.Name = dbS.Name.String
s.FacilityCode = dbS.FacilityCode.String
s.CreatedAt = dbS.CreatedAt.Time
s.UpdatedAt = dbS.UpdatedAt.Time
if dbS.R != nil {
if dbS.R.Attributes != nil {
s.Attributes, err = convertFromDBAttributes(dbS.R.Attributes)
if err != nil {
return err
}
}
if dbS.R.ServerComponents != nil {
s.Components, err = convertDBServerComponents(dbS.R.ServerComponents)
if err != nil {
return err
}
}
if dbS.R.VersionedAttributes != nil {
s.VersionedAttributes, err = convertFromDBVersionedAttributes(dbS.R.VersionedAttributes)
if err != nil {
return err
}
}
}
return nil
}
func (s *Server) toDBModel() (*models.Server, error) {
dbS := &models.Server{
Name: null.StringFrom(s.Name),
FacilityCode: null.StringFrom(s.FacilityCode),
}
if s.UUID.String() != uuid.Nil.String() {
dbS.ID = s.UUID.String()
}
return dbS, nil
}
|
bharath063/NSPHP-DOC
|
class_net_suite_1_1_classes_1_1_topic_solution.js
|
<filename>class_net_suite_1_1_classes_1_1_topic_solution.js
var class_net_suite_1_1_classes_1_1_topic_solution =
[
[ "$message", "class_net_suite_1_1_classes_1_1_topic_solution.html#abf17cb2dba2ed17cb28aa5f37deb5293", null ],
[ "$solution", "class_net_suite_1_1_classes_1_1_topic_solution.html#aa9d7f2370bf077bc320892aa7023acab", null ]
];
|
mongobaba/refactoring-java
|
src/main/java/org/mongobaba/refactory/chapter10/Chapter10_7.java
|
package org.mongobaba.refactory.chapter10;
/**
* Preserve Whole Object
* 保持对象完整
*/
public class Chapter10_7 {
static class TempRange {
private int low;
private int high;
public TempRange(int low, int high) {
this.low = low;
this.high = high;
}
public int getLow() {
return low;
}
public int getHigh() {
return high;
}
}
static class Room {
private TempRange tempRange;
public void setTempRange(TempRange tempRange) {
this.tempRange = tempRange;
}
public TempRange daysTempRange() {
return tempRange;
}
boolean withinPlan(HeatingPlan plan) {
int low = daysTempRange().getLow();
int high = daysTempRange().getHigh();
return plan.withinRange(low, high);
}
}
static class HeatingPlan {
private TempRange _range;
public void setRange(TempRange _range) {
this._range = _range;
}
// TODO 更改参数类型为TempRange,去除现有参数
// 将此方法的本体移入TempRange类型中
boolean withinRange(int low, int high) {
return low >= _range.getLow() && high <= _range.getHigh();
}
}
}
|
billchenxi/ClaraGenomicsAnalysis
|
docs/cpp/search/functions_5.js
|
var searchData=
[
['filter_5foverlaps_194',['filter_overlaps',['../group__cudamapper.html#ga3e5732f34489315ec8d1ef8b82ccea5c',1,'claragenomics::cudamapper::Overlapper']]],
['first_5foccurrence_5fof_5frepresentations_195',['first_occurrence_of_representations',['../classclaragenomics_1_1cudamapper_1_1Index.html#af4f69a9003fedb9ca11665d5faa43bff',1,'claragenomics::cudamapper::Index']]],
['format_5falignment_196',['format_alignment',['../classclaragenomics_1_1cudaaligner_1_1Alignment.html#a4be4bb544d593f3fd7624628f2bda29c',1,'claragenomics::cudaaligner::Alignment']]]
];
|
trygas/CGHomework
|
Ubpa/UGM-0.1/include/UGM/Interfaces/IArray/IArray.h
|
<filename>Ubpa/UGM-0.1/include/UGM/Interfaces/IArray/IArray.h<gh_stars>0
#pragma once
#include "../../basic.h"
#include "../Arg.h"
#include <UTemplate/SI.h>
#include <array>
#include <vector>
#include <iostream>
#include <cmath>
#include <assert.h>
namespace Ubpa {
template<typename Base, typename Impl, typename ArgList>
struct IArray : Base, std::array<At_t<At_t<ArgList,0>, 0>, At_t<At_t<ArgList, 0>, 1>::value> {
private:
using Base::operator[];
public:
using std::array<At_t<At_t<ArgList, 0>, 0>, At_t<At_t<ArgList, 0>, 1>::value>::operator[];
public:
using T = Arg_T<ArgList>;
static constexpr size_t N = Arg_N<ArgList>;
using F = Arg_F<ArgList>;
static_assert(N > 0);
//static_assert(std::is_arithmetic_v<F>);
using Base::Base;
using std::array<At_t<At_t<ArgList, 0>, 0>, At_t<At_t<ArgList, 0>, 1>::value>::array;
IArray() {}
IArray(T t) {
for (size_t i = 0; i < N; i++)
(*this)[i] = T{ t };
}
template<typename... U, typename = std::enable_if_t<(std::is_convertible_v<U, T>&&...)>>
inline IArray(U... data) : std::array<T, N>{static_cast<T>(data)...} {
static_assert(sizeof...(U) == N);
}
inline const Impl rmv_epsilon() const noexcept {
Impl rst{};
for (size_t i = 0; i < N; i++)
rst[i] = Ubpa::rmv_epsilon((*this)[i]);
return rst;
}
inline bool is_all_zero() const noexcept {
for (size_t i = 0; i < N; i++) {
if (is_zero((*this)[i]))
return false;
}
return true;
}
inline bool has_nan() const noexcept {
for (size_t i = 0; i < N; i++) {
if (is_nan((*this)[i]))
return true;
}
return false;
}
static const Impl lerp(const Impl& x, const Impl& y, F t) noexcept {
Impl rst{};
F one_minus_t = static_cast<F>(1) - t;
for (size_t i = 0; i < N; i++)
rst[i] = Ubpa::lerp(x[i], y[i], t);
return rst;
}
inline const Impl lerp(const Impl& y, F t) const noexcept {
auto& x = static_cast<const Impl&>(*this);
return lerp(x, y, t);
}
static const Impl mid(const Impl& x, const Impl& y) noexcept {
return lerp(x, y, static_cast<F>(0.5));
}
static const Impl mix(const std::vector<Impl>& vals, const std::vector<float>& weights) noexcept {
assert(vals.size() > 0 && vals.size() == weights.size());
Impl rst{};
for (size_t j = 0; j < N; j++)
rst[j] = vals[0][j] * weights[0];
for (size_t i = 1; i < vals.size(); i++) {
for (size_t j = 0; j < N; j++)
rst[j] += vals[i][j] * weights[i];
}
return rst;
}
};
}
|
PatrickDropbox/abc
|
src/jvm_bytecode/operations/math_operations.scala
|
import java.io.DataInputStream
import java.io.DataOutput
// stack: ..., value1, value2 -> ..., result
abstract class BinaryIOp(owner: AttributeOwner, opCode: Int, mnemonic: String)
extends NoOperandOp(owner, opCode, mnemonic) {
}
// stack: ..., value1 -> ..., result
abstract class UnaryIOp(owner: AttributeOwner, opCode: Int, mnemonic: String)
extends NoOperandOp(owner, opCode, mnemonic) {
}
// stack: ..., value1, value2 -> ..., result
abstract class BinaryLOp(owner: AttributeOwner, opCode: Int, mnemonic: String)
extends NoOperandOp(owner, opCode, mnemonic) {
}
// stack: ..., value1 -> ..., result
abstract class UnaryLOp(owner: AttributeOwner, opCode: Int, mnemonic: String)
extends NoOperandOp(owner, opCode, mnemonic) {
}
// stack: ..., (long) value1, (int) value2 -> (long) result
abstract class ShiftLOp(owner: AttributeOwner, opCode: Int, mnemonic: String)
extends NoOperandOp(owner, opCode, mnemonic) {
}
// stack: ..., value1, value2 -> ..., result
abstract class BinaryFOp(owner: AttributeOwner, opCode: Int, mnemonic: String)
extends NoOperandOp(owner, opCode, mnemonic) {
}
// stack: ..., value1 -> ..., result
abstract class UnaryFOp(owner: AttributeOwner, opCode: Int, mnemonic: String)
extends NoOperandOp(owner, opCode, mnemonic) {
}
// stack: ..., value1, value2 -> ..., result
abstract class BinaryDOp(owner: AttributeOwner, opCode: Int, mnemonic: String)
extends NoOperandOp(owner, opCode, mnemonic) {
}
// stack: ..., value1 -> ..., result
abstract class UnaryDOp(owner: AttributeOwner, opCode: Int, mnemonic: String)
extends NoOperandOp(owner, opCode, mnemonic) {
}
//
// int operations
//
class Iadd(owner: AttributeOwner)
extends BinaryIOp(owner, OpCode.IADD, "iadd") {
}
class Isub(owner: AttributeOwner)
extends BinaryIOp(owner, OpCode.ISUB, "isub") {
}
class Imul(owner: AttributeOwner)
extends BinaryIOp(owner, OpCode.IMUL, "imul") {
}
class Idiv(owner: AttributeOwner)
extends BinaryIOp(owner, OpCode.IDIV, "idiv") {
}
class Irem(owner: AttributeOwner)
extends BinaryIOp(owner, OpCode.IREM, "irem") {
}
class Ineg(owner: AttributeOwner)
extends UnaryIOp(owner, OpCode.INEG, "ineg") {
}
class Ishl(owner: AttributeOwner)
extends BinaryIOp(owner, OpCode.ISHL, "ishl") {
}
class Ishr(owner: AttributeOwner)
extends BinaryIOp(owner, OpCode.ISHR, "ishr") {
}
class Iushr(owner: AttributeOwner)
extends BinaryIOp(owner, OpCode.IUSHR, "iushr") {
}
class Iand(owner: AttributeOwner)
extends BinaryIOp(owner, OpCode.IAND, "iand") {
}
class Ior(owner: AttributeOwner) extends BinaryIOp(owner, OpCode.IOR, "ior") {
}
class Ixor(owner: AttributeOwner)
extends BinaryIOp(owner, OpCode.IXOR, "ixor") {
}
// iinc <local var index> <const int>
// increment local variable by const without modifying stack
class Iinc(owner: AttributeOwner, index: Int, v: Int)
extends TwoByteOperandsOp(
owner,
OpCode.IINC,
"iinc",
false, // signed
index,
true, // signed
v) {
def this(owner: AttributeOwner) = this(owner, -1, 0)
override def serialize(output: DataOutput) {
if (operand1 <= Const.UINT8_MAX &&
(Const.INT8_MIN <= operand2 && operand2 <= Const.INT8_MAX)) {
super.serialize(output)
} else {
output.writeByte(OpCode.WIDE)
output.writeByte(OpCode.IINC)
output.writeShort(operand1)
output.writeShort(operand2)
}
}
}
//
// long operations
//
class Ladd(owner: AttributeOwner)
extends BinaryLOp(owner, OpCode.LADD, "ladd") {
}
class Lsub(owner: AttributeOwner)
extends BinaryLOp(owner, OpCode.LSUB, "lsub") {
}
class Lmul(owner: AttributeOwner)
extends BinaryLOp(owner, OpCode.LMUL, "lmul") {
}
class Ldiv(owner: AttributeOwner)
extends BinaryLOp(owner, OpCode.LDIV, "ldiv") {
}
class Lrem(owner: AttributeOwner)
extends BinaryLOp(owner, OpCode.LREM, "lrem") {
}
class Lneg(owner: AttributeOwner)
extends UnaryLOp(owner, OpCode.LNEG, "lneg") {
}
class Lshl(owner: AttributeOwner) extends ShiftLOp(owner, OpCode.LSHL, "lshl") {
}
class Lshr(owner: AttributeOwner) extends ShiftLOp(owner, OpCode.LSHR, "lshr") {
}
class Lushr(owner: AttributeOwner)
extends ShiftLOp(owner, OpCode.LUSHR, "lushr") {
}
class Land(owner: AttributeOwner)
extends BinaryLOp(owner, OpCode.LAND, "land") {
}
class Lor(owner: AttributeOwner) extends BinaryLOp(owner, OpCode.LOR, "lor") {
}
class Lxor(owner: AttributeOwner)
extends BinaryLOp(owner, OpCode.LXOR, "lxor") {
}
//
// float operations
//
class Fadd(owner: AttributeOwner)
extends BinaryFOp(owner, OpCode.FADD, "fadd") {
}
class Fsub(owner: AttributeOwner)
extends BinaryFOp(owner, OpCode.FSUB, "fsub") {
}
class Fmul(owner: AttributeOwner)
extends BinaryFOp(owner, OpCode.FMUL, "fmul") {
}
class Fdiv(owner: AttributeOwner)
extends BinaryFOp(owner, OpCode.FDIV, "fdiv") {
}
class Frem(owner: AttributeOwner)
extends BinaryFOp(owner, OpCode.FREM, "frem") {
}
class Fneg(owner: AttributeOwner) extends UnaryFOp(owner, OpCode.FNEG, "fneg") {
}
//
// double operations
//
class Dadd(owner: AttributeOwner)
extends BinaryDOp(owner, OpCode.DADD, "dadd") {
}
class Dsub(owner: AttributeOwner)
extends BinaryDOp(owner, OpCode.DSUB, "dsub") {
}
class Dmul(owner: AttributeOwner)
extends BinaryDOp(owner, OpCode.DMUL, "dmul") {
}
class Ddiv(owner: AttributeOwner)
extends BinaryDOp(owner, OpCode.DDIV, "ddiv") {
}
class Drem(owner: AttributeOwner)
extends BinaryDOp(owner, OpCode.DREM, "drem") {
}
class Dneg(owner: AttributeOwner) extends UnaryDOp(owner, OpCode.DNEG, "dneg") {
}
|
arez/arez
|
processor/src/test/fixtures/input/com/example/pre_dispose/other/AbstractMultiModel.java
|
package com.example.pre_dispose.other;
import arez.annotations.PreDispose;
public abstract class AbstractMultiModel
{
@PreDispose
protected void abstractPreDispose1()
{
}
@PreDispose
protected void abstractPreDispose2()
{
}
}
|
Oracle-Exam-Preparation/OCP
|
src/main/java/com/trl/_tests/nestedClass/innerClass/t3/Test.java
|
<reponame>Oracle-Exam-Preparation/OCP
package com.trl._tests.nestedClass.innerClass.t3;
/**
* This test is taken from the book: OCP: Oracle ®
* Certified Professional
* Java® SE 8 Programmer II
* by <NAME>, <NAME>
* Released December 2015
* Publisher(s): Wiley
* ISBN: 9781119067900
*
* @link https://www.oreilly.com/library/view/ocp-oracle-certified/9781119067900/
*/
public class Test {
}
/*
Which of the following can be inserted in main?
public class Outer {
class Inner { }
public static void main(String[] args) {
// INSERT CODE HERE
} }
A. Inner in = new Inner();
B. Inner in = Outer.new Inner();
C. Outer.Inner in = new Outer.Inner();
D. Outer.Inner in = new Outer().Inner();
E. Outer.Inner in = new Outer().new Inner();
F. Outer.Inner in = Outer.new Inner();
In this case this answer is wrong.
E. This is a member inner class. It needs to be created using an instance of the outer class. The syntax looks
weird, but it creates an object of the outer class and then an object of the inner class from it.
Correct answer is: A and E. This example have problems with "static" but not initialization.
Example: src/main/java/com/trl/theoreticalKnowledge/nestedClass/innerClass/initialization/c/c1/Example.java
*/
/*
Which of the following can be inserted in main?
public class Outer {
class Inner { }
}
class Main {
public static void main(String[] args) {
// INSERT CODE HERE
}}
A. Inner in = new Inner();
B. Inner in = Outer.new Inner();
C. Outer.Inner in = new Outer.Inner();
D. Outer.Inner in = new Outer().Inner();
E. Outer.Inner in = new Outer().new Inner();
F. Outer.Inner in = Outer.new Inner();
In this case this answer is correct.
E. This is a member inner class. It needs to be created using an instance of the outer class. The syntax looks weird,
but it creates an object of the outer class and then an object of the inner class from it.
*/
|
simplificator/helena_administration
|
spec/features/surveys/manage_survey_spec.rb
|
require 'spec_helper'
feature 'Surveys' do
scenario 'Index site lists all surveys' do
create :survey, name: 'Innerbetriebliche Zufriedenheit', position: 2
create :survey, name: 'Life satisfaction scale', position: 1
visit surveys_path
within 'nav .breadcrumbs' do
expect(page).to have_content 'Surveys'
end
within 'table tbody tr:nth-child(1)' do
expect(page).to have_content 'Life satisfaction scale'
end
within 'table tbody tr:nth-child(2)' do
expect(page).to have_content 'Innerbetriebliche Zufriedenheit'
end
end
scenario 'User deletes a survey' do
survey = create :survey
visit surveys_path
within "##{dom_id(survey)}" do
expect { click_link 'Delete' }.to change { Helena::Survey.count }.from(1).to(0)
end
end
scenario 'User creates a new survey' do
visit surveys_path
click_link 'New'
within 'nav .breadcrumbs' do
expect(page).to have_text 'New'
end
expect { click_button 'Save' }.to change { Helena::Survey.count }.by 0
fill_in 'Name', with: 'More crazy stuff...'
select 'en', from: 'Language'
fill_in 'Tag list', with: 'english, foo, 42'
within 'nav .breadcrumbs' do
expect(page).to have_text 'New'
end
expect { click_button 'Save' }.to change { Helena::Survey.count }.by 1
end
scenario 'User updates a survey' do
survey = create :survey, name: 'Swiss fertility survey'
visit surveys_path
within "##{dom_id(survey)}" do
click_link 'Edit'
end
within 'nav .breadcrumbs' do
expect(page).to have_text 'Swiss fertility survey'
end
fill_in 'Name', with: ''
expect { click_button 'Save' }.not_to(change { survey.reload })
within 'nav .breadcrumbs' do
expect(page).to have_text 'Swiss fertility survey'
end
fill_in 'Name', with: 'More crazy stuff...'
select 'en', from: 'Language'
fill_in 'Tag list', with: 'english, foo, 42'
expect { click_button 'Save' }.to change { survey.reload.name }.from('Swiss fertility survey').to('More crazy stuff...')
end
scenario 'User can view survey details' do
survey = create :survey, name: 'Swiss fertility survey'
visit survey_path(survey)
within 'nav .breadcrumbs' do
expect(page).to have_content 'Swiss fertility survey'
end
within "##{dom_id(survey)}" do
expect(page).to have_content 'Swiss fertility survey'
end
end
end
|
Amity-Network/amity
|
contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/DiscRecording.framework/Versions/A/Headers/DRContentFile.h
|
<gh_stars>0
/*
File: DiscRecording/DRContentFile.h
Contains: Interface to file objects used in filesystem creation.
Version: Technology: Mac OS X
Release: Mac OS X
Copyright: (c) 2002-2007 Apple Inc. All Rights Reserved.
Bugs?: For bug reports, consult the following page on
the World Wide Web:
http://developer.apple.com/bugreporter/
*/
/*! @header
@abstract File objects used in filesystem creation.
@discussion
*/
#ifndef _H_DRContentFile
#define _H_DRContentFile
#if PRAGMA_ONCE
#pragma once
#endif
#ifndef _H_DRContentObject
#include <DiscRecording/DRContentObject.h>
#endif
#ifndef __COREFOUNDATION_CFURL__
#include <CoreFoundation/CFURL.h>
#endif
#ifndef __AVAILABILITYMACROS__
#include <AvailabilityMacros.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function DRFileGetTypeID
@abstract Returns the type identifier of all DRFile objects.
*/
extern
CFTypeID DRFileGetTypeID(void)
AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
/*!
@typedef DRLinkType
@abstract Link types available for the @link DRFileCreateVirtualLink DRFileCreateVirtualLink @/link function.
*/
typedef UInt32 DRLinkType;
/*!
@enum DRLinkType contants
@discussion Link type constants used by the @link DRFileCreateVirtualLink DRFileCreateVirtualLink @/link function.
@constant kDRLinkTypeHardLink Link type for hard links.
@constant kDRLinkTypeSymbolicLink Link type for symbolic links.
@constant kDRLinkTypeFinderAlias Link type for Finder aliases.
*/
enum {
kDRLinkTypeHardLink = 1,
kDRLinkTypeSymbolicLink = 2,
kDRLinkTypeFinderAlias = 3
};
/*!
@typedef DRFileMessage
@abstract Messages sent to the @link DRFileProc DRFileProc @/link callback during a burn.
*/
typedef UInt32 DRFileMessage;
/*!
@enum DRFileMessage constants
@discussion Messages sent to the @link DRFileProc DRFileProc @/link callback during a burn.
@constant kDRFileMessageForkSize
Indicates a request for your @link DRFileProc DRFileProc @/link callback to supply a file track size.
Your @link DRFileProc DRFileProc @/link callback should respond to this
message by placing the requested file fork size into the
@link DRFileForkSizeInfo DRFileForkSizeInfo @/link structure, which is pointed to
by the callback's <tt>ioParam</tt> parameter. Your callback
may receive this message at any time after the file object
has been created.
On input, the structure's <tt>fork</tt> field indicates which fork
you are being asked about, as defined in the @link DRFileForkIndex DRFileForkIndex @/link
enumeration.
Also on input, the structure's <tt>query</tt> field indicates
whether you are being asked for an estimated or actual fork size, as
defined in the @link DRFileForkSizeQuery DRFileForkSizeQuery @/link enumeration.
When the <tt>query</tt> field is @link DRFileForkSizeQuery DRFileForkSizeQuery @/link, you are
being asked for an estimate of the final fork size, perhaps for the
burn engine to estimate the track size. You do not have to be exact,
but your estimate should err on the high side. This call may be made
at any time.
When the <tt>query</tt> field is @link kDRFileForkSizeActual kDRFileForkSizeActual @/link, you
are being asked for the actual fork size to be used in the burn. This
call is made only in the burn phase.
@constant kDRFileMessagePreBurn
Indicates that your application should perform all necessary preparation for the burn.
Your @link DRFileProc DRFileProc @/link callback should respond to this message
by telling your application to open files, or to do any other pre-burn
preparation work needed. The burn engine sends this message before the
burn but after the disc's entire hierarchy is completely in place. You
can query the hierarchy
After this call, the burn's content is locked down, and you should be
able to respond to the @link kDRFileMessageForkSize kDRFileMessageForkSize @/link message with exact values.
Sent before the burn.
The callback's <tt>ioParam</tt> parameter is ignored.
@constant kDRFileMessageProduceData
Sent during the burn (after the pre-burn call). The callback's <tt>ioParam</tt> parameter points to a @link DRFileProductionInfo DRFileProductionInfo @/link structure. Speed is critical during this call. You should produce the data as fast as possible, and try not to perform any time-consuming tasks.
You may be asked to produce twice, once during the actual burn
and once during verification.
@constant kDRFileMessageVerificationStarting
Sent during the burn (after the pre-burn call, after production, before the post-burn call) to indicate that verification is about to begin. The callback's <tt>ioParam</tt> parameter is ignored.
This would be an appropriate place to seek back to the beginning of
files, reset state machines, or do whatever else is needed to prepare to
produce again.
@constant kDRFileMessagePostBurn
Sent at the end of the burn. The callback's <tt>ioParam</tt> parameter is ignored.
This would be an appropriate place to close files, or do any other
teardown work needed. This call will always be made regardless of
whether the burn succeeded or failed.
@constant kDRFileMessageRelease
Sent when the @link //apple_ref/c/tdef/DRFileRef DRFileRef @/link is released. The callback's <tt>ioParam</tt> parameter is ignored.
No further messages will be sent for this object. This would be an
appropriate time to release any memory allocated by the object (whether
in the refCon or anywhere else).
*/
enum {
kDRFileMessageForkSize = 'fsiz',
kDRFileMessagePreBurn = 'pre ',
kDRFileMessageProduceData = 'prod',
kDRFileMessageVerificationStarting = 'vrfy',
kDRFileMessagePostBurn = 'post',
kDRFileMessageRelease = 'bye '
};
/*!
@typedef DRFileForkIndex
@abstract Index used for accessing the forks of a file.
@discussion The data fork and resource fork always have fixed indices. Other forks
may be allowed in the future.
*/
typedef UInt32 DRFileForkIndex;
/*!
@enum DRFileFork indicies
@discussion Index used for accessing the forks of a file.
@constant kDRFileForkData Typically, the data fork contains the primary information for the file and is the fork used for files such as JPEGs, text files, etc.
@constant kDRFileForkResource Typically, the resource fork contains secondary meta-data, which is not
important to the primary content of the file and may safely be ignored
when the file is sent to a filesystem or OS which does not support
multiple forks. See Inside Macintosh: Resources for more information on
the format of a resource fork.
*/
enum
{
kDRFileForkData = 0,
kDRFileForkResource = 1
};
/*!
@typedef DRFileForkSizeQuery
@abstract Type used to define queries on the fork size.
*/
typedef UInt32 DRFileForkSizeQuery;
/*!
@enum DRFileForkSizeQuery contants
@discussion Type used to define queries on the fork size.
@constant kDRFileForkSizeActual Indicates a request for actual size.
@constant kDRFileForkSizeEstimate Indicates a request for estimated size.
*/
enum
{
kDRFileForkSizeActual = 0,
kDRFileForkSizeEstimate = 1
};
/*!
@struct DRFileForkSizeInfo
@abstract Structure used when requesting fork sizes.
@field fork (in) which fork is being requested
@field query (in) type of query, estimate or actual
@field size (out) returned size
*/
struct DRFileForkSizeInfo
{
DRFileForkIndex fork;
DRFileForkSizeQuery query;
UInt64 size;
};
typedef struct DRFileForkSizeInfo DRFileForkSizeInfo;
/*!
@struct DRFileProductionInfo
@abstract Structure used by the @link DRFileProc DRFileProc @/link callback during production of a track.
@field requestedAddress (out) byte address that the burn engine is requesting
@field buffer (out) buffer to produce into
@field reqCount (out) number of bytes requested
@field actCount (in) number of bytes you actually produced
@field blockSize (out) current block size, you must always return multiples of this
@field fork (out) which fork is being requested
*/
struct DRFileProductionInfo
{
UInt64 requestedAddress;
void * buffer;
UInt32 reqCount;
UInt32 actCount;
UInt32 blockSize;
DRFileForkIndex fork;
};
typedef struct DRFileProductionInfo DRFileProductionInfo;
/*!
@typedef DRFileProc
@abstract Callback function to produce and manage a file for recording a track.
@discussion Your application needs to implement a callback to create files representing
tracks to burn, and to interact with those tracks by responding to the
messages in the @link DRFileMessage DRFileMessage @/link enumeration.
If you name your function <tt>MyDRFileCallback</tt>, you would
declare it like this:
<pre>
OSStatus MyDRFileCallback (
void *refCon,
DRFileRef file,
DRFileMessage message,
void *ioParam
);
</pre>
Your callback places the requested data
If your callback does not support a given function, it should return
@link //apple_ref/c/econst/kDRFunctionNotSupportedErr kDRFunctionNotSupportedErr @/link.
@param refCon Reference context for your use, established when
the callback is registered.
@param file The file object being produced.
@param message Sent by the Disc Recording engine to indicate the
type of data it needs your application to supply. The
various messages are defined in the @link DRFileMessage DRFileMessage @/link
enumeration.
@param ioParam Parameters are message-specific. See the @link DRFileMessage DRFileMessage @/link
enumeration.
@result Your application should return @link //apple_ref/c/econst/kDRFunctionNotSupportedErr kDRFunctionNotSupportedErr @/link
when a message was passed that it doesn't respond to.
*/
typedef OSStatus (*DRFileProc)(
void * refCon,
DRFileRef file,
DRFileMessage message,
void * ioParam);
/*!
@function DRFileCreateReal
@abstract Creates a new real file object corresponding to a given FSRef.
@discussion A real file object is a file object which corresponds to a real
file on disk. The content of the file object corresponds to the
actual on-disk content of the file.
@param fsRef An <tt>FSRef</tt> reference to a file on-disk.
@result The newly-created file, or <tt>NULL</tt>.
*/
extern DRFileRef
DRFileCreateReal(
const FSRef * fsRef)
AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
/*!
@function DRFileCreateRealWithURL
@abstract Creates a new real file object corresponding to a given file URL.
@discussion A real file object is a file object which corresponds to a real
file on disk. The content of the file object corresponds to the
actual on-disk content of the file.
@param urlRef CFURLRef reference to a file on-disk.
@result Returns a reference to the newly-created real file object, or <tt>NULL</tt>.
*/
extern DRFileRef
DRFileCreateRealWithURL(
const CFURLRef urlRef)
AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
/*!
@function DRFileCreateVirtualWithData
@abstract Creates a virtual file object with the specified data.
@discussion A virtual file is a file object which does not correspond to any real
file on disk, but represents a file you want to appear in the file
structure of the disc you are burning. It is created and modified
using Disc Recording's 'content' functions -- see the
documentation for DRContentObject.h.
The file data passed in to this function is copied internally. Although
it's possible to create files of arbitrary size with this function, you
should limit files created in this way to a reasonable size, such as
100K or less, because each file consumes a corresponding amount of memory.
On multi-fork file systems the file data is used for the data fork.
@param baseName The base name to assign to the new virtual file.
@param fileData A pointer to the data for the file. May be <tt>NULL</tt> if
<tt>inFileLength</tt> is zero.
@param fileDataLength The length of data in bytes.
@result Returns a reference to the newly-created virtual file object, or <tt>NULL</tt>.
*/
extern DRFileRef
DRFileCreateVirtualWithData(
CFStringRef baseName,
void * fileData,
UInt32 fileDataLength)
AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
/*!
@function DRFileCreateVirtualWithCallback
@abstract Creates a virtual file object that will be filled in during data production
by a callback function.
@discussion A virtual file is a file object which does not correspond to any real file
on disk, but represents a file you want to appear in the file
structure of the disc you are burning. It is created and modified
using Disc Recording's 'content' functions -- see the
documentation for DRContentObject.h.
The Disc Recording framework may invoke the callback at any time, and the
calls may be made in any order, until the file object has been disposed.
@param baseName The base name to assign to the new virtual file. For information on base
names and how Disc Recording works with them, see @link //apple_ref/c/func/DRFSObjectSetBaseName DRFSObjectSetBaseName @/link
and @link //apple_ref/c/func/DRFSObjectSetSpecificName DRFSObjectSetSpecificName @/link.
@param fileProc Your application-implemented callback function to generate file data.
@param fileProcRefCon An optional reference context for the callback to use.
@result Returns a reference to the newly-created virtual file object, or <tt>NULL</tt>.
*/
extern DRFileRef
DRFileCreateVirtualWithCallback(
CFStringRef baseName,
DRFileProc fileProc,
void * fileProcRefCon)
AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
/*!
@function DRFileCreateVirtualLink
@abstract Creates a virtual file or folder object in the form of a link to another
file or folder in the hierarchy.
@discussion Disc Recording currently supports four link types: symbolic links, hard links,
Finder aliases, and combination symbolic link/Finder aliases.
Links often include relative path information. Since the relative path
between two objects can be different depending on the target file system, you
must specify a target file system when requesting a link. The file system
mask on the newly-created link will automatically be set to ensure the file
appears only in that file system.
@param original The file or folder to link to.
@param linkType The type of link to create. See the @link DRLinkType DRLinkType @/link enumeration.
@param fsKey The target file system for the link. The various keys are defined in
DRContentProperties.h.
@result A reference to the newly-created virtual file or folder object.
*/
extern DRFileRef
DRFileCreateVirtualLink(
DRFSObjectRef original,
DRLinkType linkType,
CFStringRef fsKey)
AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
#ifdef __cplusplus
}
#endif
#endif /* _H_DRContentFile */
|
XuHaijwill/spring-demo
|
spring-base/src/test/java/org/example/spring/base/cap8/Cap8MainTest.java
|
package org.example.spring.base.cap8;
import org.example.spring.base.cap8.bean.Bird;
import org.example.spring.base.cap8.config.Cap8MainConfig;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import static org.junit.Assert.*;
public class Cap8MainTest {
@Test
public void test01(){
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Cap8MainConfig.class);
//从容器中获取所有bean
String[] names = app.getBeanDefinitionNames();
for(String name:names){
System.out.println(name);
}
Bird bird = (Bird) app.getBean("bird");
System.out.println(bird);
System.out.println("IOC容器创建完成........");
ConfigurableEnvironment environment = app.getEnvironment();
System.out.println("environment===="+environment.getProperty("bird.color"));
app.close();
}
}
|
sylphlike/Gopal.pan-hairSalon
|
src/main/java/com/horse/v7mc/common/base/BaseAction.java
|
<reponame>sylphlike/Gopal.pan-hairSalon<gh_stars>0
package com.horse.v7mc.common.base;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.horse.v7mc.po.V7Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ModelAttribute;
/**
*
* @author carrey(潘冰)
* @Email <EMAIL>
* @Date 2016年5月18日下午10:33:53
* @version v 1.0.1
* @description Action基类
*/
@Component
public class BaseAction {
protected HttpServletRequest request;
protected HttpServletResponse response;
@ModelAttribute
public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
this.request = request;
this.response = response;
}
/**
* 获取 request
* @return
*/
protected HttpServletRequest getRequest(){
return request;
}
/**
* 获取response
* @return
*/
protected HttpServletResponse getResponse(){
return response;
}
/**
* 获取session
* @return
*/
protected HttpSession getSession(){
return request.getSession();
}
/**
* 获取登录人信息
* @return
*/
protected V7Employee getLoginUser(){
V7Employee employee = (V7Employee) getSession().getAttribute("user");
return employee;
}
}
|
flightstats/hub
|
src/main/java/com/flightstats/hub/dao/ContentKeyUtil.java
|
package com.flightstats.hub.dao;
import com.flightstats.hub.model.*;
import com.flightstats.hub.util.TimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ContentKeyUtil {
public static SortedSet<ContentKey> filter(Collection<ContentKey> keys, DirectionQuery query) {
Stream<ContentKey> stream = keys.stream();
if (query.isNext()) {
stream = stream.filter(key -> key.compareTo(query.getStartKey()) > 0);
} else {
Collection<ContentKey> contentKeys = new TreeSet<>(Collections.reverseOrder());
contentKeys.addAll(keys);
stream = contentKeys.stream()
.filter(key -> key.compareTo(query.getStartKey()) < 0);
}
stream = enforceLimits(query, stream);
return stream
.limit(query.getCount())
.collect(Collectors.toCollection(TreeSet::new));
}
public static Stream<ContentKey> enforceLimits(Query query, Stream<ContentKey> stream) {
ChannelConfig channelConfig = query.getChannelConfig();
if (!channelConfig.isHistorical()) {
stream = stream.filter(key -> !key.getTime().isBefore(channelConfig.getTtlTime()));
} else if (query.getEpoch().equals(Epoch.IMMUTABLE)) {
stream = stream.filter(key -> key.getTime().isAfter(channelConfig.getMutableTime()));
} else if (query.getEpoch().equals(Epoch.MUTABLE)) {
stream = stream.filter(key -> !key.getTime().isAfter(channelConfig.getMutableTime()));
}
if (query.isStable()) {
stream = stream.filter(key -> !key.getTime().isAfter(query.getChannelStable()));
}
return stream;
}
public static SortedSet<MinutePath> convert(SortedSet<ContentKey> keys) {
Map<DateTime, MinutePath> minutes = new TreeMap<>();
for (ContentKey key : keys) {
DateTime time = TimeUtil.Unit.MINUTES.round(key.getTime());
MinutePath minutePath = minutes.get(time);
if (minutePath == null) {
minutePath = new MinutePath(time, new TreeSet<>());
minutes.put(time, minutePath);
}
minutePath.getKeys().add(key);
}
return new TreeSet<>(minutes.values());
}
public static void convertKeyStrings(String keysString, Collection<ContentKey> contentKeys) {
if (StringUtils.isNotEmpty(keysString)) {
String[] keys = keysString.split(",");
for (String key : keys) {
contentKeys.add(convertKey(key).get());
}
}
}
public static Optional<ContentKey> convertKey(String key) {
if (StringUtils.isNotEmpty(key)) {
return ContentKey.fromUrl(StringUtils.substringAfter(key, "/"));
}
return Optional.empty();
}
}
|
loveweb58/React-Pro-Dashboard
|
architectui-react-pro/src/DemoPages/Dashboards/Design/index.js
|
import React, { Component, Fragment } from 'react';
import Tabs from 'react-responsive-tabs';
import DesignLanding from './Landing';
// Examples
const tabsContent = [
{
title: 'Landing',
content: <DesignLanding />
},
{
title: 'Collection',
content: <DesignLanding />
},
{
title: 'Product',
content: <DesignLanding />
},
{
title: 'Cart',
content: <DesignLanding />
},
{
title: 'User',
content: <DesignLanding />
},
{
title: 'Search',
content: <DesignLanding />
}
];
function getTabs() {
return tabsContent.map((tab, index) => ({
title: tab.title,
getContent: () => tab.content,
key: index
}));
}
export default class DesignApp extends Component {
render() {
return (
<Fragment>
<div className="app-inner-layout">
{/* <div className="app-inner-layout__header-boxed p-0">
<div className="app-inner-layout__header page-title-icon-rounded text-white bg-premium-dark mb-4">
<PageTitle
heading="Sales Dashboard"
subheading="Example of a Dashboard page built with ArchitectUI."
icon="pe-7s-umbrella icon-gradient bg-sunny-morning"
/>
</div>
</div> */}
<Tabs
tabsWrapperClass="body-tabs body-tabs-layout body-tabs-big"
transform={false}
showInkBar
items={getTabs()}
/>
</div>
</Fragment>
);
}
}
|
IgnoredAmbience/test262
|
implementation-contributed/javascriptcore/stress/weakmap-set-cse.js
|
function shouldBe(actual, expected)
{
if (actual !== expected)
throw new Error('bad value: ' + actual);
}
function test()
{
var key1 = {};
var map = new WeakMap();
var r1 = map.get(key1);
map.set(key1, 42);
var r2 = map.get(key1);
return [r1, r2];
}
noInline(test);
for (var i = 0; i < 1e5; ++i) {
let [r1, r2] = test();
shouldBe(r1, undefined);
shouldBe(r2, 42);
}
|
silviu-negoita/smallrye-reactive-messaging
|
smallrye-reactive-messaging-provider/src/main/java/io/smallrye/reactive/messaging/providers/extension/HealthCenter.java
|
package io.smallrye.reactive.messaging.providers.extension;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import io.smallrye.reactive.messaging.health.HealthReport;
import io.smallrye.reactive.messaging.health.HealthReporter;
/**
* Component responsible to compute the current state of the reactive messaging application.
*/
@ApplicationScoped
public class HealthCenter {
@Inject
@Any
Instance<HealthReporter> reporters;
List<ReportedFailure> failures = new CopyOnWriteArrayList<>();
private volatile boolean initialized = false;
public HealthReport getReadiness() {
HealthReport.HealthReportBuilder builder = HealthReport.builder();
for (HealthReporter r : reporters) {
for (HealthReport.ChannelInfo channelInfo : r.getReadiness().getChannels()) {
builder.add(channelInfo);
}
}
for (ReportedFailure rf : failures) {
builder.add(rf.source, false, rf.failure.getMessage());
}
return builder.build();
}
public HealthReport getLiveness() {
HealthReport.HealthReportBuilder builder = HealthReport.builder();
for (HealthReporter r : reporters) {
for (HealthReport.ChannelInfo channelInfo : r.getLiveness().getChannels()) {
builder.add(channelInfo);
}
}
for (ReportedFailure rf : failures) {
builder.add(rf.source, false, rf.failure.getMessage());
}
return builder.build();
}
public HealthReport getStartup() {
HealthReport.HealthReportBuilder builder = HealthReport.builder();
for (HealthReporter r : reporters) {
for (HealthReport.ChannelInfo channelInfo : r.getStartup().getChannels()) {
builder.add(channelInfo);
}
}
// failures do not contribute to the startup probe when app is running
return builder.build();
}
public void report(String source, Throwable cause) {
failures.add(new ReportedFailure(source, cause));
}
public void reportApplicationFailure(String method, Throwable cause) {
failures.add(new ReportedFailure("application-" + method, cause));
}
public boolean isInitialized() {
return initialized;
}
public void markInitialized() {
this.initialized = true;
}
public static class ReportedFailure {
final String source;
final Throwable failure;
public ReportedFailure(String source, Throwable failure) {
this.source = source;
this.failure = failure;
}
}
}
|
JamesCao2048/BlizzardData
|
Corpus/aspectj/6533.java
|
<gh_stars>1-10
/* *******************************************************************
* Copyright (c) 2004 IBM
* 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:
* <NAME> - initial implementation {date}
* ******************************************************************/
package org.aspectj.apache.bcel.classfile.annotation;
import java.io.DataOutputStream;
import java.io.IOException;
import org.aspectj.apache.bcel.classfile.ConstantPool;
public class ArrayElementValue extends ElementValue {
private static final ElementValue[] NO_VALUES = new ElementValue[0];
// J5TODO: Should we make this an array or a list? A list would be easier to modify ...
private ElementValue[] evalues = NO_VALUES;
public ElementValue[] getElementValuesArray() {
return evalues;
}
public int getElementValuesArraySize() {
return evalues.length;
}
public ArrayElementValue(ConstantPool cp) {
super(ARRAY, cp);
}
public ArrayElementValue(int type, ElementValue[] datums, ConstantPool cpool) {
super(type, cpool);
if (type != ARRAY)
throw new RuntimeException("Only element values of type array can be built with this ctor");
this.evalues = datums;
}
public ArrayElementValue(ArrayElementValue value, ConstantPool cpool, boolean copyPoolEntries) {
super(ARRAY, cpool);
evalues = new ElementValue[value.getElementValuesArraySize()];
ElementValue[] in = value.getElementValuesArray();
for (int i = 0; i < in.length; i++) {
evalues[i] = ElementValue.copy(in[i], cpool, copyPoolEntries);
}
}
@Override
public void dump(DataOutputStream dos) throws IOException {
dos.writeByte(type); // u1 type of value (ARRAY == '[')
dos.writeShort(evalues.length);
for (int i = 0; i < evalues.length; i++) {
evalues[i].dump(dos);
}
}
@Override
public String stringifyValue() {
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int i = 0; i < evalues.length; i++) {
ElementValue element = evalues[i];
sb.append(element.stringifyValue());
if ((i + 1) < evalues.length)
sb.append(",");
}
sb.append("]");
return sb.toString();
}
public void addElement(ElementValue gen) {
ElementValue[] old = evalues;
evalues = new ElementValue[evalues.length + 1];
System.arraycopy(old, 0, evalues, 0, old.length);
evalues[old.length] = gen;
}
}
|
Yoomee/ym-content
|
test/dummy/db/migrate/20140212152412_create_content_attributes.rb
|
<filename>test/dummy/db/migrate/20140212152412_create_content_attributes.rb
class CreateContentAttributes < ActiveRecord::Migration
def change
create_table :content_attributes do |t|
t.belongs_to :content_type
t.string :slug
t.string :name
t.text :description
t.string :field_type
t.integer :limit_quantity
t.string :limit_unit
t.integer :position, :default => 0
t.boolean :required, :default => false
t.boolean :meta, :default => false
t.text :sir_trevor_settings
t.integer :resource_content_type_id
end
add_index :content_attributes, :content_type_id
end
end
|
billwert/azure-sdk-for-java
|
sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/provider/authentication/NamedKeyProvider.java
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.spring.cloud.core.provider.authentication;
import com.azure.spring.cloud.core.properties.authentication.NamedKeyProperties;
/**
* Interface to be implemented by classes that wish to provide the named key.
*/
public interface NamedKeyProvider {
/**
* Get the named key properties
* @return the named key properties
*/
NamedKeyProperties getNamedKey();
}
|
RedRecondite/hotel
|
story/pigsack.c
|
//sack of grain. again more or less copied from the original game.
void main( void )
{
sp_touch_damage(¤t_sprite, -1);
}
void hit(void)
{
say("I hate you, sack of feed!", 1);
}
void talk(void)
{
//removing the freezing because it can lock up the game if you pick it up and talk to it at the same time
//freeze(1);
say_stop("*inhales*", 1);
say_stop("Mmm, the smell of pig feed. Makes me hungry.", 1);
wait(500);
say_stop("...I hope no one heard that.", 1);
//unfreeze(1);
}
void touch(void)
{
//dink touched this sprite
Playsound(10,22050,0,0,0);
sp_brain_parm(¤t_sprite, 10);
sp_brain(¤t_sprite, 12);
sp_touch_damage(¤t_sprite, 0);
sp_timing(¤t_sprite, 0);
add_item("item-pig",438, 2);
say("I now have a sack of pig feed. Aaah, memories.", 1);
//kill this item so it doesn't show up again for this player
int &hold = sp_editor_num(¤t_sprite);
if (&hold != 0)
editor_type(&hold, 1);
}
|
jovialgent/ivx-js
|
src/angular/directives/input.options.js
|
<gh_stars>0
import createFactoryFunction from '../utilities/create-factory-function.js';
import OptionsInputController from '../controllers/input.options.js';
import { ErrorMessages } from '../utilities/messages.error.js';
class OptionsInput {
constructor($compile, $filter, iVXjs, iVXjsUIModule, iVXjsBus, pullInTemplate, ivxExperienceScope) {
this.template = this.templateHTML;
this.transclude = true;
this.restrict = 'E';
this.require = "^ivxjsFormInput";
this.scope = {
inputData: '=inputData'
}
this.controller = OptionsInputController;
this.controllerAs = 'vm';
this.replace = true;
this.link = ($scope, iElm, iAttrs, controller) => {
let { inputData: input } = $scope;
let { id, errors = {}, name, labelHTML, attributes = {}, options, defaultDisplay, settings = {} } = input;
let { directives = '' } = settings;
let errorMessages = new ErrorMessages(input, errors, attributes);
let defaultOptionTag = `<option value="">Select an option...</option>`;
let tagHTML = `${directives}
ng-change='vm.onChange(vm.selected.value, event)'
ng-click="event = $event"
ng-options="option.display for option in inputData.options track by option.value"
ng-model='vm.selected'`;
$scope = ivxExperienceScope.setScopeExperience($scope);
input.label = input.label ? input.label : $filter('stringParsers')('startCase', id);
input = pullInTemplate.convertLabel($filter('stringParsers')('startCase', id), input, $scope);
input.beforeHtml = pullInTemplate.convertTemplateUrlToHtml(input.beforeHtml, $scope);
input.afterHtml = pullInTemplate.convertTemplateUrlToHtml(input.afterHtml, $scope);
if (attributes.required || defaultDisplay) {
defaultOptionTag = defaultDisplay ?
`<option value="">${defaultDisplay}</option>` :
defaultOptionTag;
}
let uiOptionsObj = {
input: input,
defaultDisplay: defaultDisplay,
settings: settings,
tags: tagHTML,
errors: errorMessages
};
let optionsClass = new iVXjsUIModule.options(uiOptionsObj);
iElm.html(optionsClass.html);
$compile(iElm.contents())($scope);
}
}
get templateHTML() {
return `<div></div>`;
};
}
OptionsInput.$inject = ['$compile', '$filter', 'iVXjs', 'ivxjs.modules.ui', 'ivxjs.bus', 'pullInTemplate', 'ivxExperienceScope'];
export default angular
.module('ivx-js.directives.input.options', [])
.directive('ivxjsOptionsInput', createFactoryFunction(OptionsInput))
.name;
|
karinakozarova/C-Programming-Exercises
|
Code/Entrance level/11grade/17_twin_primes.c
|
#include <stdio.h>
int are_prime(int num1,int num2){
if(num1 - num2 == 2 || num2 - num1 == 2)
return 1;
return 0;
}
float sum_primes(float x){
double sum = 0,result = 0;
for (int i = 1; ; ++i){
result = 1/i + 1/(i+2);
printf("%f %d\n",result,i );
if (result < x) break;
sum += result;
}
return sum;
}
float primes(int x){
float result = 0.0, primes;
int first = 3,second = 5;
do{
primes = 1.0/(first + second);
first += 2;
second += 2;
result += primes;
if(primes <= x) break;
}while(primes > x);
return result;
}
int main(){
float x = -1;
while(x <= 0 || x >= 1) scanf("%f",&x);
printf("%f",primes(x));
return 0;
}
|
vnyrjkmr/myapp
|
strongloop/node_modules/strong-build/test/test-onto.js
|
var assert = require('assert');
var debug = require('debug')('strong-build:test');
var fs = require('fs');
var path = require('path');
var tar = require('tar');
var util = require('util');
var vasync = require('vasync');
var zlib = require('zlib');
var shell = require('shelljs/global');
// Check for node silently exiting with code 0 when tests have not passed.
var ok = false;
process.on('exit', function(code) {
if (code === 0) {
assert(ok);
}
});
console.log('pwd: %s', pwd());
// Create two branches that are different, and commit the src
// over the dst, and then diff them to prove identical.
rm('-rf', '_onto');
mkdir('_onto');
cd('_onto');
run('git init');
touchAndCommit('.gitignore');
run('git checkout -b dst master');
touchAndCommit('only-on-dst');
run('git checkout -b src master');
touchAndCommit('only-on-src');
assert(!branchEqual('src', 'dst'));
var build = require('../');
function onto(_, callback) {
build.build(['node', 'main.js', '--onto=dst'], function(er) {
if (er) return callback(er);
assert(branchEqual('src', 'dst'));
return callback();
});
}
// simulate build, by generating output
touch('build.out');
function commit(_, callback) {
build.build(['node', 'main.js', '-c'], function(er) {
if (er) return callback(er);
run('git log build.out'); // check build.out was committed
return callback();
});
}
// Note we run onto twice, one to prove we can do it onto a branch with a
// different head than ours, and the next time to prove we can do it onto a
// branch with the same head as ours.
vasync.pipeline({funcs: [onto, onto, commit]}, function(er) {
assert.ifError(er);
ok = true;
});
// Shell wrappers
function run() {
var cmd = util.format.apply(util, arguments);
debug('exec `%s`: ...', cmd);
var out = exec(cmd, {silent: true});
out.output = out.output.trim();
console.log('exec `%s`: (code %s)\n%s', cmd, out.code, out.output);
if (out.code !== 0) {
throw Error(error);
}
return out.output;
}
function touch(name) {
console.log('touch %s', name);
fs.closeSync(fs.openSync(name, 'a'));
}
function touchAndCommit(name) {
touch(name);
run('git add %s', name);
run('git commit -m add-%s', name);
}
function branchEqual(src, dst) {
try {
run('git diff --quiet %s %s', src, dst);
return true;
} catch(er) {
return false;
}
}
|
codingchili/chili-game-ext
|
services/realm/main/java/com/codingchili/instance/transport/UpdateMessage.java
|
<filename>services/realm/main/java/com/codingchili/instance/transport/UpdateMessage.java
package com.codingchili.instance.transport;
import com.codingchili.common.ReceivableMessage;
import com.codingchili.instance.model.events.Event;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
/**
* @author <NAME>
*
* An update message from the realm or instance to a single client.
*/
public class UpdateMessage implements ReceivableMessage {
@JsonUnwrapped
private Event event;
@JsonProperty
private String target;
public UpdateMessage(Event event, String target) {
this.event = event;
this.target = target;
}
public Event event() {
return event;
}
@Override
public String target() {
return target;
}
@Override
public String route() {
return event.getRoute().name();
}
}
|
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
|
XFree86-3.3/xc/lib/x11/CrGlCur.c
|
/* $XConsortium: CrGlCur.c,v 11.9 94/04/17 20:19:00 rws Exp $ */
/*
Copyright (c) 1986 X Consortium
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
X CONSORTIUM 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.
Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the X Consortium.
*/
#include "Xlibint.h"
Cursor XCreateGlyphCursor(dpy, source_font, mask_font,
source_char, mask_char,
foreground, background)
register Display *dpy;
Font source_font, mask_font;
unsigned int source_char, mask_char;
XColor *foreground, *background;
{
Cursor cid;
register xCreateGlyphCursorReq *req;
LockDisplay(dpy);
GetReq(CreateGlyphCursor, req);
cid = req->cid = XAllocID(dpy);
req->source = source_font;
req->mask = mask_font;
req->sourceChar = source_char;
req->maskChar = mask_char;
req->foreRed = foreground->red;
req->foreGreen = foreground->green;
req->foreBlue = foreground->blue;
req->backRed = background->red;
req->backGreen = background->green;
req->backBlue = background->blue;
UnlockDisplay(dpy);
SyncHandle();
return (cid);
}
|
qnoid/windmill-api
|
src/test/java/io/windmill/windmill/services/NotificationMessagesTest.java
|
//
// Created by <NAME> (<EMAIL>)
// Copyright © 2014-2020 qnoid.com. All rights reserved.
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation is required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
package io.windmill.windmill.services;
import org.junit.Test;
import io.windmill.windmill.services.Notification.Messages;
import io.windmill.windmill.services.Notification.Platform;
import io.windmill.windmill.services.common.ContentType;
import junit.framework.Assert;
public class NotificationMessagesTest {
@Test
public void testGivenNewBuildAssertMessage() {
String actual = "{\"aps\":{"
+ "\"alert\":{"
+ "\"title\":\"New build\","
+ "\"body\":\"foo 1.0 (455f6a1) is now available to install.\""
+ "}}"
+ "}";
String sampleAppleMessage = Notification.Messages.of("New build", String.format("%s %s (455f6a1) is now available to install.", "foo", 1.0));
Assert.assertEquals(actual, sampleAppleMessage);
}
@Test
public void testGivenPlatformAssertMessage() {
String expected = Messages.of("New build", String.format("%s %s (455f6a1) is now available to install.", "foo", 1.0));
String actual = Platform.APNS_SANDBOX.message(expected);
Assert.assertEquals("{\"APNS_SANDBOX\":\"{\\\"aps\\\":{\\\"alert\\\":{\\\"title\\\":\\\"New build\\\",\\\"body\\\":\\\"foo 1.0 (455f6a1) is now available to install.\\\"}}}\"}", actual);
}
@Test
public void testPlatformInstance() {
Platform actual = Platform.getInstance();
Assert.assertEquals(Platform.APNS_SANDBOX, actual);
}
@Test
public void testGivenContentAvailableExportAssertMessage() {
String actual = Messages.contentAvailable(ContentType.EXPORT);
String expected = "{\"aps\":{"
+ "\"content-available\":1"
+ "},"
+ "\"type\":\"export\""
+ "}";
Assert.assertEquals(expected, actual);
}
}
|
quantummaiddeveloper/mapmaid
|
tests/src/test/java/de/quantummaid/mapmaid/specs/examples/system/generator/concepts/CustomPrimitive.java
|
/*
* Copyright (c) 2020 <NAME> - https://quantummaid.de/.
*
* 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 de.quantummaid.mapmaid.specs.examples.system.generator.concepts;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import java.util.ArrayList;
import java.util.List;
import static de.quantummaid.mapmaid.specs.examples.system.generator.lowlevel.ClassModel.classModel;
import static de.quantummaid.mapmaid.specs.examples.system.generator.lowlevel.FieldModel.field;
import static de.quantummaid.mapmaid.specs.examples.system.generator.lowlevel.MethodModel.method;
import static de.quantummaid.mapmaid.specs.examples.system.generator.lowlevel.ParameterModel.finalParameter;
import static java.lang.String.format;
@ToString
@EqualsAndHashCode
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public final class CustomPrimitive {
private final String name;
private final String backingType;
private final List<String> factories;
public static CustomPrimitive customPrimitive(final String name, final String backingType) {
return new CustomPrimitive(name, backingType, new ArrayList<>(3));
}
public String render() {
return classModel(this.name)
.withField(field("value", this.backingType)
.withModifiers("private", "final"))
.withMethod(method("fromStringValue")
.withModifiers("public", "static")
.withReturnType(this.name)
.withParameter(finalParameter("value", this.backingType))
.withLine(format("return new %s(value);", this.backingType)))
.withMethod(method("stringValue")
.withModifiers("public")
.withReturnType("String")
.withLine(format("return value;")))
.render();
}
}
|
paulmetzger/Device-Hopping-Paper
|
source_to_source_translator/malloc_for_indirectly_accessed_buffers_template.h
|
{
auto start_index_lambda = %START_INDEX_LAMBDA%;
auto final_index_lambda = %FINAL_INDEX_LAMBDA%;
const size_t start_thread_id = current_offsets[0] * BLOCK_SIZE_X;
const size_t final_thread_id = start_thread_id + current_slice_sizes[0] * BLOCK_SIZE_X;
const size_t start_index = start_index_lambda(start_thread_id);
const size_t stop_index = final_index_lambda(final_thread_id);
const size_t indirect_start_index = %INTERMEDIATE_BUFFER%[start_index];
const size_t indirect_stop_index = %INTERMEDIATE_BUFFER%[stop_index];
const size_t elements = indirect_stop_index - indirect_start_index;
const size_t required_buffer_size = elements * %ELEMENT_SIZE%;
if (%BUFFER_NAME%_current_size_in_bytes < required_buffer_size) {
cudaError err = cudaFree(h.cuda.%BUFFER_NAME%_d);
if (err != cudaSuccess) utils::exit_with_err("Could not reallocate buffer '%BUFFER_NAME%'");
err = cudaMalloc(&h.cuda.%BUFFER_NAME%_d, required_buffer_size);
if (err != cudaSuccess) utils::exit_with_err("Could not reallocate buffer '%BUFFER_NAME%'");
%BUFFER_NAME%_current_size_in_bytes = required_buffer_size;
}
%DATA_TRANSFER%
}
|
cpreh/spacegameengine
|
libs/opencl/src/opencl/command_queue/map_flags_to_native.cpp
|
// Copyright <NAME> 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/opencl/clinclude.hpp>
#include <sge/opencl/command_queue/map_flags.hpp>
#include <sge/opencl/command_queue/map_flags_to_native.hpp>
#include <fcppt/assert/unreachable.hpp>
cl_map_flags
sge::opencl::command_queue::map_flags_to_native(sge::opencl::command_queue::map_flags const _flags)
{
switch (_flags)
{
case sge::opencl::command_queue::map_flags::read:
return CL_MAP_READ; // NOLINT(hicpp-signed-bitwise)
case sge::opencl::command_queue::map_flags::write:
return CL_MAP_WRITE; // NOLINT(hicpp-signed-bitwise)
case sge::opencl::command_queue::map_flags::read_write:
return CL_MAP_READ | CL_MAP_WRITE; // NOLINT(hicpp-signed-bitwise)
}
FCPPT_ASSERT_UNREACHABLE;
}
|
Iceweazel/testbed
|
separate/testbedproject/src/main/java/com/johan/producers/RabbitProducer.java
|
package com.johan.producers;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.johan.generic.Producer;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
public class RabbitProducer implements Producer {
private static final String EXCHANGE = "ledger-exchange";
private static final String TYPE = "direct";
private static final String QUEUE = "ledger-1";
private static final String ROUTING_KEY = "ledger-route";
private static final boolean DURABLE = true;
private static final boolean EXCLUSIVE = false;
private static final boolean AUTO_DELETE = true;
private static final BasicProperties PROPERTIES = MessageProperties.MINIMAL_PERSISTENT_BASIC;
private Connection connection;
private Channel channel;
public RabbitProducer() {
//only using default java options for connection
ConnectionFactory connectionFactory = new ConnectionFactory();
try {
connection = connectionFactory.newConnection();
channel = connection.createChannel();
} catch (Exception e) {
e.printStackTrace();
}
try {
channel.exchangeDeclare(EXCHANGE, TYPE, DURABLE);
channel.queueDeclare(QUEUE, DURABLE, EXCLUSIVE, AUTO_DELETE, null);
channel.queueBind(QUEUE, EXCHANGE, ROUTING_KEY);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void publish(byte[] payload) {
try {
channel.basicPublish(EXCHANGE, ROUTING_KEY, PROPERTIES, payload);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void close() {
try {
channel.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
}
|
uw-x/tymp
|
mcu/imageSensor/HM01B0_GPIO.h
|
<filename>mcu/imageSensor/HM01B0_GPIO.h
/*
* HM01B0_GPIO.h
*
* Created on: Nov 20, 2018
* Author: Ali
*/
#ifndef HM01B0_GPIO_H_
#define HM01B0_GPIO_H_
/* Standard C Included Files */
#include <stdbool.h>
//#include <stdio.h>
//#include <string.h>
#include "nrf.h"
#include "nrf_drv_gpiote.h"
#include "app_error.h"
#include "boards.h"
/*******************************************************************************
* GPIO Variables
******************************************************************************/
//uint32_t sw_cam_d0;
//XXXXX
#if defined(BOARD_PCA10056)
uint32_t CAM_SPI_CS = 44;
#define FRAME_VLD 43
#endif
//#if defined(BOARD_PCA10040)
//uint32_t CAM_SPI_CS = 22;
//#define FRAME_VLD 20
//#endif
#if defined(BOARD_PCA10040)
uint32_t CAM_SPI_CS = 16;
#define FRAME_VLD 18
#endif
//uint32_t CAM_SPI_CS = 44;
//#define FRAME_VLD 43
//
//#define PIN_OUT BSP_LED_0
////#define PIN_IN BSP_BUTTON_0
//#define PIN_IN 43//Port1, pin11
#define pint_intr_callback in_pin_handler
/*******************************************************************************
* Interrupt Variables
******************************************************************************/
/*******************************************************************************
* GPIO Functions
******************************************************************************/
/*!
* @brief GPIO settings initialization.
*/
void gpio_setting_init(void);
uint8_t gpio_read_cam(void);
/*******************************************************************************
* I2C Functions
******************************************************************************/
/*!
* @brief I2C settings initialization.
*/
/*******************************************************************************
* Code PINT Intr
******************************************************************************/
/*!
* @brief Call back for PINT Pin interrupt 0-7.
*/
void in_pin_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action);
#endif /* HM01B0_GPIO_H_ */
///*******************************************************************************
// * GPIO Variables
// ******************************************************************************/
////#define gpio1_byte1_address 0x50000811//0x50000300 + 0x510 + 1(higher byte)
////uint8_t *gpio_address = gpio1_byte1_address;
////uint8_t gpio_read;
//
////uint32_t sw_cam_d0;
//
//uint32_t CAM_SPI_CS = 44;
//#define FRAME_VLD 43
//
////#define CAM_D0 44 //Port1, pin12
////#define CAM_D1 45
////#define CAM_D2 46
////#define CAM_D3 47
////
////#define PIN_OUT BSP_LED_0
//////#define PIN_IN BSP_BUTTON_0
////#define PIN_IN 43//Port1, pin11
//
//#define pint_intr_callback in_pin_handler
//
///*******************************************************************************
// * Interrupt Variables
// ******************************************************************************/
//// #define hm_mem_size 766
////static uint32_t hm_image_size = 766;
////#define hm_mem_size 100
////static uint32_t hm_image_size = 100;
////extern uint8_t image_mem[hm_mem_size];
////extern uint8_t image_rd_done;
////
////
////extern uint32_t hm_pixel_counter;
////static bool msb_flag; //0 means lsb data, 1 msb data
////uint8_t test_gpio = 0xC5;
////uint8_t mask_lsb = 0x0F;
////uint8_t mask_msb = 0xF0;
////uint8_t gpio_8b;
//
///*******************************************************************************
// * GPIO Functions
// ******************************************************************************/
///*!
//* @brief GPIO settings initialization.
//*/
//void gpio_setting_init(void);
//
//uint8_t gpio_read_cam(void);
//
//
//
///*******************************************************************************
// * I2C Functions
// ******************************************************************************/
///*!
//* @brief I2C settings initialization.
//*/
//
//
///*******************************************************************************
// * Code PINT Intr
// ******************************************************************************/
//
///*!
//* @brief Call back for PINT Pin interrupt 0-7.
//*/
//void in_pin_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action);
//
//
//
//
//#endif /* HM01B0_GPIO_H_ */
|
iamzken/aliyun-openapi-cpp-sdk
|
rds/include/alibabacloud/rds/model/DescribeOssDownloadsForSQLServerResult.h
|
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_RDS_MODEL_DESCRIBEOSSDOWNLOADSFORSQLSERVERRESULT_H_
#define ALIBABACLOUD_RDS_MODEL_DESCRIBEOSSDOWNLOADSFORSQLSERVERRESULT_H_
#include <string>
#include <vector>
#include <utility>
#include <alibabacloud/core/ServiceResult.h>
#include <alibabacloud/rds/RdsExport.h>
namespace AlibabaCloud
{
namespace Rds
{
namespace Model
{
class ALIBABACLOUD_RDS_EXPORT DescribeOssDownloadsForSQLServerResult : public ServiceResult
{
public:
struct OssDownload
{
std::string status;
std::string desc;
std::string createTime1;
std::string fileName;
std::string createTime;
std::string isAvail;
std::string bakType;
std::string fileSize;
};
DescribeOssDownloadsForSQLServerResult();
explicit DescribeOssDownloadsForSQLServerResult(const std::string &payload);
~DescribeOssDownloadsForSQLServerResult();
std::vector<OssDownload> getItems()const;
std::string getMigrateIaskId()const;
std::string getDBInstanceName()const;
protected:
void parse(const std::string &payload);
private:
std::vector<OssDownload> items_;
std::string migrateIaskId_;
std::string dBInstanceName_;
};
}
}
}
#endif // !ALIBABACLOUD_RDS_MODEL_DESCRIBEOSSDOWNLOADSFORSQLSERVERRESULT_H_
|
yanyushr/fuchsia
|
garnet/bin/a11y/a11y_manager/util.cc
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "garnet/bin/a11y/a11y_manager/util.h"
namespace a11y_manager {
zx_koid_t GetKoid(const fuchsia::ui::views::ViewRef& view_ref) {
return fsl::GetKoid(view_ref.reference.get());
}
} // namespace a11y_manager
|
blackjyn/flex-sdk
|
modules/thirdparty/velocity/src/java/org/apache/flex/forks/velocity/exception/MethodInvocationException.java
|
package org.apache.flex.forks.velocity.exception;
/*
* Copyright 2001,2004 The Apache Software Foundation.
*
* 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.
*/
/**
* Application-level exception thrown when a reference method is
* invoked and an exception is thrown.
* <br>
* When this exception is thrown, a best effort will be made to have
* useful information in the exception's message. For complete
* information, consult the runtime log.
*
* @author <a href="mailto:<EMAIL>"><NAME>.</a>
* @version $Id: MethodInvocationException.java,v 1.2.14.1 2004/03/03 23:22:54 geirm Exp $
*/
public class MethodInvocationException extends VelocityException
{
private String methodName = "";
private String referenceName = "";
private Throwable wrapped = null;
/**
* CTOR - wraps the passed in exception for
* examination later
*
* @param message
* @param e Throwable that we are wrapping
* @param methodName name of method that threw the exception
*/
public MethodInvocationException( String message, Throwable e, String methodName )
{
super(message);
this.wrapped = e;
this.methodName = methodName;
}
/**
* Returns the name of the method that threw the
* exception
*
* @return String name of method
*/
public String getMethodName()
{
return methodName;
}
/**
* returns the wrapped Throwable that caused this
* MethodInvocationException to be thrown
*
* @return Throwable thrown by method invocation
*/
public Throwable getWrappedThrowable()
{
return wrapped;
}
/**
* Sets the reference name that threw this exception
*
* @param reference name of reference
*/
public void setReferenceName( String ref )
{
referenceName = ref;
}
/**
* Retrieves the name of the reference that caused the
* exception
*
* @return name of reference
*/
public String getReferenceName()
{
return referenceName;
}
}
|
McDoyen/yavasource
|
javasource/saml20/proxies/EntityDescriptor.java
|
<filename>javasource/saml20/proxies/EntityDescriptor.java
// This file was generated by Mendix Modeler.
//
// WARNING: Code you write here will be lost the next time you deploy the project.
package saml20.proxies;
public class EntityDescriptor
{
private final com.mendix.systemwideinterfaces.core.IMendixObject entityDescriptorMendixObject;
private final com.mendix.systemwideinterfaces.core.IContext context;
/**
* Internal name of this entity
*/
public static final java.lang.String entityName = "SAML20.EntityDescriptor";
/**
* Enum describing members of this entity
*/
public enum MemberNames
{
entityID("entityID"),
validUntil("validUntil"),
cacheDuration("cacheDuration"),
_ID("_ID"),
Updated("Updated"),
EntityDescriptor_EntitiesDescriptor("SAML20.EntityDescriptor_EntitiesDescriptor");
private java.lang.String metaName;
MemberNames(java.lang.String s)
{
metaName = s;
}
@Override
public java.lang.String toString()
{
return metaName;
}
}
public EntityDescriptor(com.mendix.systemwideinterfaces.core.IContext context)
{
this(context, com.mendix.core.Core.instantiate(context, "SAML20.EntityDescriptor"));
}
protected EntityDescriptor(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject entityDescriptorMendixObject)
{
if (entityDescriptorMendixObject == null)
throw new java.lang.IllegalArgumentException("The given object cannot be null.");
if (!com.mendix.core.Core.isSubClassOf("SAML20.EntityDescriptor", entityDescriptorMendixObject.getType()))
throw new java.lang.IllegalArgumentException("The given object is not a SAML20.EntityDescriptor");
this.entityDescriptorMendixObject = entityDescriptorMendixObject;
this.context = context;
}
/**
* @deprecated Use 'EntityDescriptor.load(IContext, IMendixIdentifier)' instead.
*/
@Deprecated
public static saml20.proxies.EntityDescriptor initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
return saml20.proxies.EntityDescriptor.load(context, mendixIdentifier);
}
/**
* Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
* The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.createSudoClone() can be used to obtain sudo access).
*/
public static saml20.proxies.EntityDescriptor initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject mendixObject)
{
return new saml20.proxies.EntityDescriptor(context, mendixObject);
}
public static saml20.proxies.EntityDescriptor load(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
com.mendix.systemwideinterfaces.core.IMendixObject mendixObject = com.mendix.core.Core.retrieveId(context, mendixIdentifier);
return saml20.proxies.EntityDescriptor.initialize(context, mendixObject);
}
public static java.util.List<saml20.proxies.EntityDescriptor> load(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String xpathConstraint) throws com.mendix.core.CoreException
{
java.util.List<saml20.proxies.EntityDescriptor> result = new java.util.ArrayList<saml20.proxies.EntityDescriptor>();
for (com.mendix.systemwideinterfaces.core.IMendixObject obj : com.mendix.core.Core.retrieveXPathQuery(context, "//SAML20.EntityDescriptor" + xpathConstraint))
result.add(saml20.proxies.EntityDescriptor.initialize(context, obj));
return result;
}
/**
* Commit the changes made on this proxy object.
*/
public final void commit() throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Commit the changes made on this proxy object using the specified context.
*/
public final void commit(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Delete the object.
*/
public final void delete()
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* Delete the object using the specified context.
*/
public final void delete(com.mendix.systemwideinterfaces.core.IContext context)
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* @return value of entityID
*/
public final java.lang.String getentityID()
{
return getentityID(getContext());
}
/**
* @param context
* @return value of entityID
*/
public final java.lang.String getentityID(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.String) getMendixObject().getValue(context, MemberNames.entityID.toString());
}
/**
* Set value of entityID
* @param entityid
*/
public final void setentityID(java.lang.String entityid)
{
setentityID(getContext(), entityid);
}
/**
* Set value of entityID
* @param context
* @param entityid
*/
public final void setentityID(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String entityid)
{
getMendixObject().setValue(context, MemberNames.entityID.toString(), entityid);
}
/**
* @return value of validUntil
*/
public final java.util.Date getvalidUntil()
{
return getvalidUntil(getContext());
}
/**
* @param context
* @return value of validUntil
*/
public final java.util.Date getvalidUntil(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.util.Date) getMendixObject().getValue(context, MemberNames.validUntil.toString());
}
/**
* Set value of validUntil
* @param validuntil
*/
public final void setvalidUntil(java.util.Date validuntil)
{
setvalidUntil(getContext(), validuntil);
}
/**
* Set value of validUntil
* @param context
* @param validuntil
*/
public final void setvalidUntil(com.mendix.systemwideinterfaces.core.IContext context, java.util.Date validuntil)
{
getMendixObject().setValue(context, MemberNames.validUntil.toString(), validuntil);
}
/**
* @return value of cacheDuration
*/
public final java.lang.String getcacheDuration()
{
return getcacheDuration(getContext());
}
/**
* @param context
* @return value of cacheDuration
*/
public final java.lang.String getcacheDuration(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.String) getMendixObject().getValue(context, MemberNames.cacheDuration.toString());
}
/**
* Set value of cacheDuration
* @param cacheduration
*/
public final void setcacheDuration(java.lang.String cacheduration)
{
setcacheDuration(getContext(), cacheduration);
}
/**
* Set value of cacheDuration
* @param context
* @param cacheduration
*/
public final void setcacheDuration(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String cacheduration)
{
getMendixObject().setValue(context, MemberNames.cacheDuration.toString(), cacheduration);
}
/**
* @return value of _ID
*/
public final java.lang.String get_ID()
{
return get_ID(getContext());
}
/**
* @param context
* @return value of _ID
*/
public final java.lang.String get_ID(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.String) getMendixObject().getValue(context, MemberNames._ID.toString());
}
/**
* Set value of _ID
* @param _id
*/
public final void set_ID(java.lang.String _id)
{
set_ID(getContext(), _id);
}
/**
* Set value of _ID
* @param context
* @param _id
*/
public final void set_ID(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String _id)
{
getMendixObject().setValue(context, MemberNames._ID.toString(), _id);
}
/**
* @return value of Updated
*/
public final java.lang.Boolean getUpdated()
{
return getUpdated(getContext());
}
/**
* @param context
* @return value of Updated
*/
public final java.lang.Boolean getUpdated(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.Boolean) getMendixObject().getValue(context, MemberNames.Updated.toString());
}
/**
* Set value of Updated
* @param updated
*/
public final void setUpdated(java.lang.Boolean updated)
{
setUpdated(getContext(), updated);
}
/**
* Set value of Updated
* @param context
* @param updated
*/
public final void setUpdated(com.mendix.systemwideinterfaces.core.IContext context, java.lang.Boolean updated)
{
getMendixObject().setValue(context, MemberNames.Updated.toString(), updated);
}
/**
* @return value of EntityDescriptor_EntitiesDescriptor
*/
public final saml20.proxies.EntitiesDescriptor getEntityDescriptor_EntitiesDescriptor() throws com.mendix.core.CoreException
{
return getEntityDescriptor_EntitiesDescriptor(getContext());
}
/**
* @param context
* @return value of EntityDescriptor_EntitiesDescriptor
*/
public final saml20.proxies.EntitiesDescriptor getEntityDescriptor_EntitiesDescriptor(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
{
saml20.proxies.EntitiesDescriptor result = null;
com.mendix.systemwideinterfaces.core.IMendixIdentifier identifier = getMendixObject().getValue(context, MemberNames.EntityDescriptor_EntitiesDescriptor.toString());
if (identifier != null)
result = saml20.proxies.EntitiesDescriptor.load(context, identifier);
return result;
}
/**
* Set value of EntityDescriptor_EntitiesDescriptor
* @param entitydescriptor_entitiesdescriptor
*/
public final void setEntityDescriptor_EntitiesDescriptor(saml20.proxies.EntitiesDescriptor entitydescriptor_entitiesdescriptor)
{
setEntityDescriptor_EntitiesDescriptor(getContext(), entitydescriptor_entitiesdescriptor);
}
/**
* Set value of EntityDescriptor_EntitiesDescriptor
* @param context
* @param entitydescriptor_entitiesdescriptor
*/
public final void setEntityDescriptor_EntitiesDescriptor(com.mendix.systemwideinterfaces.core.IContext context, saml20.proxies.EntitiesDescriptor entitydescriptor_entitiesdescriptor)
{
if (entitydescriptor_entitiesdescriptor == null)
getMendixObject().setValue(context, MemberNames.EntityDescriptor_EntitiesDescriptor.toString(), null);
else
getMendixObject().setValue(context, MemberNames.EntityDescriptor_EntitiesDescriptor.toString(), entitydescriptor_entitiesdescriptor.getMendixObject().getId());
}
/**
* @return the IMendixObject instance of this proxy for use in the Core interface.
*/
public final com.mendix.systemwideinterfaces.core.IMendixObject getMendixObject()
{
return entityDescriptorMendixObject;
}
/**
* @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization.
*/
public final com.mendix.systemwideinterfaces.core.IContext getContext()
{
return context;
}
@Override
public boolean equals(Object obj)
{
if (obj == this)
return true;
if (obj != null && getClass().equals(obj.getClass()))
{
final saml20.proxies.EntityDescriptor that = (saml20.proxies.EntityDescriptor) obj;
return getMendixObject().equals(that.getMendixObject());
}
return false;
}
@Override
public int hashCode()
{
return getMendixObject().hashCode();
}
/**
* @return String name of this class
*/
public static java.lang.String getType()
{
return "SAML20.EntityDescriptor";
}
/**
* @return String GUID from this object, format: ID_0000000000
* @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
*/
@Deprecated
public java.lang.String getGUID()
{
return "ID_" + getMendixObject().getId().toLong();
}
}
|
PowerOlive/garnet
|
bin/auth/cache/token_cache.h
|
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GARNET_BIN_AUTH_CACHE_TOKEN_CACHE_H
#define GARNET_BIN_AUTH_CACHE_TOKEN_CACHE_H
#include <list>
#include <map>
#include <string>
#include <utility>
#include "lib/fxl/logging.h"
#include "lib/fxl/time/time_delta.h"
#include "lib/fxl/time/time_point.h"
// Token cache interface for an in-memory cache for storing most frequently used
// short lived tokens such as OAuth Access Tokens, ID Tokens and Firebase Auth
// Tokens. Token cache uses |CacheKey| as the key that uniquely combines User
// Identifier with the Identity Provider and the credential received from the
// Identity Provider. Each CacheKey stores a set of |OAuthTokens| that contains
// token creation timestamp, expiration time, and the actual value of the token.
//
// Token cache implements LRU Cache functionality where both insert and remove
// operations are done in O(lgN) using a map and a list implementation.
namespace auth {
namespace cache {
// Adjusts the token expiration window by a small amount to proactively refresh
// tokens before the expiry time limit has reached.
constexpr fxl::TimeDelta kPaddingForTokenExpiry =
fxl::TimeDelta::FromSeconds(600);
// The status of an operation.
enum Status {
// The operation succeeded.
kOK = 0,
// The operation was not attempted because the arguments are invalid.
kInvalidArguments,
// The operation was not attempted because the given key is not found in
// cache.
kKeyNotFound,
// The operation was attempted but failed because the entry in cache has
// expired.
kCacheExpired,
// The operation was attempted but failed for an unspecified reason. More
// information may be found in the log file.
kOperationFailed,
};
// Unique key for accessing token cache.
struct CacheKey {
const std::string idp_provider;
const std::string idp_credential_id;
CacheKey(std::string idp_provider, std::string idp_credential_id)
: idp_provider(std::move(idp_provider)),
idp_credential_id(std::move(idp_credential_id)) {}
bool operator<(const CacheKey& other) const {
return std::tie(idp_provider, idp_credential_id) <
std::tie(other.idp_provider, other.idp_credential_id);
}
bool operator==(const CacheKey& other) const {
return (this->idp_provider == other.idp_provider &&
this->idp_credential_id == other.idp_credential_id);
}
bool IsValid() const {
return !(idp_provider.empty() || idp_credential_id.empty());
}
};
// In-memory cache for short lived firebase auth id-tokens. These tokens get
// reset on system reboots. Tokens are cached based on the expiration time
// set by the Firebase servers. Cache is indexed by firebase api keys.
struct FirebaseAuthToken {
fxl::TimePoint expiration_time;
std::string fb_id_token;
std::string local_id;
std::string email;
bool operator==(const FirebaseAuthToken& other) const {
return (this->expiration_time == other.expiration_time &&
this->fb_id_token == other.fb_id_token &&
this->local_id == other.local_id && this->email == other.email);
}
bool IsValid() const {
return expiration_time > fxl::TimePoint::Min() && !fb_id_token.empty() &&
!local_id.empty();
}
// Returns true if the stored token has expired.
bool HasExpired() const {
FXL_DCHECK(IsValid());
return (expiration_time - fxl::TimePoint::Now()) < kPaddingForTokenExpiry;
}
};
struct OAuthToken {
fxl::TimePoint expiration_time;
std::string token;
bool operator==(const OAuthToken& other) const {
return (this->expiration_time == other.expiration_time &&
this->token == other.token);
}
bool IsValid() const {
return expiration_time > fxl::TimePoint::Min() && !token.empty();
}
bool HasExpired() const {
FXL_DCHECK(IsValid());
return (expiration_time - fxl::TimePoint::Now()) < kPaddingForTokenExpiry;
}
};
// In-memory cache for short lived oauth tokens that resets on system reboots.
// Tokens are cached based on the expiration time set by the Identity provider.
// Token cache is indexed by unique |CacheKey|.
struct OAuthTokens {
OAuthToken id_token;
OAuthToken access_token;
std::map<std::string, FirebaseAuthToken> firebase_tokens_map;
};
class LinkedHashMap {
public:
LinkedHashMap(int cache_size) { cache_size_ = cache_size; }
Status Insert(const CacheKey& key, const OAuthTokens& tokens) {
if (!key.IsValid() ||
!(tokens.id_token.IsValid() || tokens.access_token.IsValid())) {
return Status::kInvalidArguments;
}
auto it = tokens_map_.find(key);
if (it != tokens_map_.end()) {
tokens_list_.erase(it->second);
tokens_map_.erase(it);
}
tokens_list_.push_front(std::make_pair(key, tokens));
tokens_map_.insert(std::make_pair(key, tokens_list_.begin()));
// readjust tokens_map_ for max cache_size
while (tokens_map_.size() > cache_size_) {
auto last_it = tokens_list_.end();
last_it--;
tokens_map_.erase(last_it->first);
tokens_list_.pop_back();
}
return Status::kOK;
}
Status Fetch(const CacheKey& key, OAuthTokens* tokens_out) {
FXL_CHECK(tokens_out);
if (!key.IsValid()) {
return Status::kInvalidArguments;
}
auto it = tokens_map_.find(key);
if (it == tokens_map_.end()) {
return Status::kKeyNotFound;
}
auto& tokens = it->second->second;
// check if the cache has expired before returning. If oauth tokens are
// expired, remove them from cache before returning error status.
// TODO: invalidate id and access tokens individually
if ((tokens.id_token.IsValid() && tokens.id_token.HasExpired()) ||
(tokens.access_token.IsValid() && tokens.access_token.HasExpired())) {
Delete(key);
return Status::kCacheExpired;
}
tokens_list_.splice(tokens_list_.begin(), tokens_list_, it->second);
// OAuth token is valid, check to see if firebase tokens are all also valid.
// Purge all expired firebase tokens before returning.
for (auto fbtoken_itr = tokens.firebase_tokens_map.begin();
fbtoken_itr != tokens.firebase_tokens_map.end(); ++fbtoken_itr) {
if (fbtoken_itr->second.HasExpired()) {
tokens.firebase_tokens_map.erase(fbtoken_itr);
}
}
*tokens_out = tokens;
return Status::kOK;
}
Status Delete(const CacheKey& key) {
if (!key.IsValid()) {
return Status::kInvalidArguments;
}
auto it = tokens_map_.find(key);
if (it == tokens_map_.end()) {
return Status::kKeyNotFound;
}
tokens_list_.erase(it->second);
tokens_map_.erase(it);
return Status::kOK;
}
bool HasKey(const CacheKey& key) { return tokens_map_.count(key) > 0; }
private:
// List of entries in the cache stored as pairs of |CacheKey| and
// |OAuthTokens|. The most recently used one is always found at the beginning
// of the list and the least recently used at the tail end.
std::list<std::pair<CacheKey, OAuthTokens>> tokens_list_;
// Map with keys as |CacheKey| and an iterator value pointing to the
// beginning of the above list that implements an LRU based cache.
std::map<CacheKey, decltype(tokens_list_.begin())> tokens_map_;
// Max size of cache
size_t cache_size_;
FXL_DISALLOW_COPY_AND_ASSIGN(LinkedHashMap);
};
class TokenCache {
public:
// Initializes token cache with a capacity of |cache_size|.
TokenCache(int cache_size);
// Returns all unexpired tokens stored in cache in |tokens_out| for the given
// |key|. Expired tokens are also purged from the underlying cache. These
// include both OAuthTokens and FirebaseAuthTokens.
//
// Returns kOK on success or an error status on failure.
Status Get(const CacheKey& key, OAuthTokens* tokens_out);
// Adds a new cache entry for the cache key |key| and sets it with the given
// list of tokens |tokens|.
//
// Returns kOK on success or an error status on failure.
Status Put(const CacheKey& key, const OAuthTokens& tokens);
// Removes all tokens indexed by cache key |key| from the token cache.
Status Delete(const CacheKey& key);
// Adds a new firebase auth token |firebase_token| for api key
// |firebase_api_key| to an existing cache entry identified by |key|.
//
// Returns kOK on success or an error status on failure.
Status AddFirebaseToken(const CacheKey& key,
const std::string& firebase_api_key,
const FirebaseAuthToken firebase_token);
// Returns true if |key| was found in the token cache.
bool HasKey(const CacheKey& key);
private:
LinkedHashMap cache_map_;
FXL_DISALLOW_COPY_AND_ASSIGN(TokenCache);
};
} // namespace cache
} // namespace auth
#endif // GARNET_BIN_AUTH_CACHE_TOKEN_CACHE_H
|
flapjs/webapp
|
src/main.js
|
/* global __NODE_ENV__ */
/* global __VERSION__ */
import { startUp } from './WebApplication.js';
// NOTE: __NODE_ENV__ is defined in `template.html` as a global.
// NOTE: __VERSION__ is defined by Webpack with the DefinePlugin.
startUp(__NODE_ENV__, __VERSION__);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.