hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f0829d2d94dba1b99dd3f9bdecbd3dfdc9a9d774 | 1,316 | kt | Kotlin | app/src/main/java/com/fun/auction/ui/adapter/RankAdapter.kt | blueskky/FunAuction | c3955e3b770b46d7e7b14c8925e1d7a9e691b248 | [
"MIT"
] | null | null | null | app/src/main/java/com/fun/auction/ui/adapter/RankAdapter.kt | blueskky/FunAuction | c3955e3b770b46d7e7b14c8925e1d7a9e691b248 | [
"MIT"
] | null | null | null | app/src/main/java/com/fun/auction/ui/adapter/RankAdapter.kt | blueskky/FunAuction | c3955e3b770b46d7e7b14c8925e1d7a9e691b248 | [
"MIT"
] | null | null | null | package com.`fun`.auction.ui.adapter
import android.text.Html
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.`fun`.auction.R
import com.`fun`.auction.model.Goods
import com.bumptech.glide.Glide
class RankAdapter(data: MutableList<Goods>) : BaseQuickAdapter<Goods, BaseViewHolder>(R.layout.rank_item, data) {
override fun convert(holder: BaseViewHolder, item: Goods) {
val view = holder.getView<ImageView>(R.id.iv_last_box)
Glide.with(context).load(item.goods_image).into(view)
holder.setText(R.id.tv_name, item.goods_name)
val html = "市场价 <font color='#d6273c'>¥ ${item.goods_price}</font>"
holder.setText(R.id.tv_price, Html.fromHtml(html))
val isHot = item.is_hot
val tvTag = holder.getView<TextView>(R.id.tv_tag)
tvTag.visibility = View.VISIBLE
if (isHot == 30) {
tvTag.text = "精品"
tvTag.setBackgroundResource(R.drawable.chaoji_shape)
} else if (isHot == 40) {
tvTag.text = "超级"
tvTag.setBackgroundResource(R.drawable.jinpin_shape)
} else {
tvTag.visibility = View.GONE
}
}
} | 36.555556 | 113 | 0.680851 |
3d0a306f1a824af7bb56eec927a281c3da5eecfe | 12,087 | rs | Rust | vm/runtime/src/lib.rs | dutterbutter/forest | 43ae5cfa41a37f67afab5521cdca7472d0b327b6 | [
"Apache-2.0",
"MIT"
] | 1 | 2020-12-02T12:44:34.000Z | 2020-12-02T12:44:34.000Z | vm/runtime/src/lib.rs | vmx/forest | 293ef19e3b51e68c8b6c3c827111255c203280b3 | [
"Apache-2.0",
"MIT"
] | 4 | 2020-10-31T19:21:49.000Z | 2020-11-05T19:49:14.000Z | vm/runtime/src/lib.rs | dutterbutter/forest | 43ae5cfa41a37f67afab5521cdca7472d0b327b6 | [
"Apache-2.0",
"MIT"
] | null | null | null | // Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
mod actor_code;
pub use self::actor_code::*;
use address::Address;
use cid::Cid;
use clock::ChainEpoch;
use commcid::data_commitment_v1_to_cid;
use crypto::{DomainSeparationTag, Signature};
use fil_types::{
zero_piece_commitment, NetworkVersion, PaddedPieceSize, PieceInfo, Randomness,
RegisteredSealProof, SealVerifyInfo, WindowPoStVerifyInfo,
};
use filecoin_proofs_api::seal::compute_comm_d;
use filecoin_proofs_api::{self as proofs};
use forest_encoding::{blake2b_256, Cbor};
use ipld_blockstore::BlockStore;
use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};
use std::error::Error as StdError;
use vm::{ActorError, MethodNum, Serialized, TokenAmount};
/// Runtime is the VM's internal runtime object.
/// this is everything that is accessible to actors, beyond parameters.
pub trait Runtime<BS: BlockStore> {
/// The network protocol version number at the current epoch.
fn network_version(&self) -> NetworkVersion;
/// Information related to the current message being executed.
fn message(&self) -> &dyn MessageInfo;
/// The current chain epoch number. The genesis block has epoch zero.
fn curr_epoch(&self) -> ChainEpoch;
/// Validates the caller against some predicate.
/// Exported actor methods must invoke at least one caller validation before returning.
fn validate_immediate_caller_accept_any(&mut self) -> Result<(), ActorError>;
fn validate_immediate_caller_is<'a, I>(&mut self, addresses: I) -> Result<(), ActorError>
where
I: IntoIterator<Item = &'a Address>;
fn validate_immediate_caller_type<'a, I>(&mut self, types: I) -> Result<(), ActorError>
where
I: IntoIterator<Item = &'a Cid>;
/// The balance of the receiver.
fn current_balance(&self) -> Result<TokenAmount, ActorError>;
/// Resolves an address of any protocol to an ID address (via the Init actor's table).
/// This allows resolution of externally-provided SECP, BLS, or actor addresses to the canonical form.
/// If the argument is an ID address it is returned directly.
fn resolve_address(&self, address: &Address) -> Result<Option<Address>, ActorError>;
/// Look up the code ID at an actor address.
fn get_actor_code_cid(&self, addr: &Address) -> Result<Option<Cid>, ActorError>;
/// Randomness returns a (pseudo)random byte array drawing from the latest
/// ticket chain from a given epoch and incorporating requisite entropy.
/// This randomness is fork dependant but also biasable because of this.
fn get_randomness_from_tickets(
&self,
personalization: DomainSeparationTag,
rand_epoch: ChainEpoch,
entropy: &[u8],
) -> Result<Randomness, ActorError>;
/// Randomness returns a (pseudo)random byte array drawing from the latest
/// beacon from a given epoch and incorporating requisite entropy.
/// This randomness is not tied to any fork of the chain, and is unbiasable.
fn get_randomness_from_beacon(
&self,
personalization: DomainSeparationTag,
rand_epoch: ChainEpoch,
entropy: &[u8],
) -> Result<Randomness, ActorError>;
/// Initializes the state object.
/// This is only valid in a constructor function and when the state has not yet been initialized.
fn create<C: Cbor>(&mut self, obj: &C) -> Result<(), ActorError>;
/// Loads a readonly copy of the state of the receiver into the argument.
///
/// Any modification to the state is illegal and will result in an abort.
fn state<C: Cbor>(&self) -> Result<C, ActorError>;
/// Loads a mutable version of the state into the `obj` argument and protects
/// the execution from side effects (including message send).
///
/// The second argument is a function which allows the caller to mutate the state.
/// The return value from that function will be returned from the call to Transaction().
///
/// If the state is modified after this function returns, execution will abort.
///
/// The gas cost of this method is that of a Store.Put of the mutated state object.
fn transaction<C, RT, F>(&mut self, f: F) -> Result<RT, ActorError>
where
C: Cbor,
F: FnOnce(&mut C, &mut Self) -> Result<RT, ActorError>;
/// Returns reference to blockstore
fn store(&self) -> &BS;
/// Sends a message to another actor, returning the exit code and return value envelope.
/// If the invoked method does not return successfully, its state changes
/// (and that of any messages it sent in turn) will be rolled back.
fn send(
&mut self,
to: Address,
method: MethodNum,
params: Serialized,
value: TokenAmount,
) -> Result<Serialized, ActorError>;
/// Computes an address for a new actor. The returned address is intended to uniquely refer to
/// the actor even in the event of a chain re-org (whereas an ID-address might refer to a
/// different actor after messages are re-ordered).
/// Always an ActorExec address.
fn new_actor_address(&mut self) -> Result<Address, ActorError>;
/// Creates an actor with code `codeID` and address `address`, with empty state.
/// May only be called by Init actor.
fn create_actor(&mut self, code_id: Cid, address: &Address) -> Result<(), ActorError>;
/// Deletes the executing actor from the state tree, transferring any balance to beneficiary.
/// Aborts if the beneficiary does not exist.
/// May only be called by the actor itself.
fn delete_actor(&mut self, beneficiary: &Address) -> Result<(), ActorError>;
/// Provides the system call interface.
fn syscalls(&self) -> &dyn Syscalls;
/// Returns the total token supply in circulation at the beginning of the current epoch.
/// The circulating supply is the sum of:
/// - rewards emitted by the reward actor,
/// - funds vested from lock-ups in the genesis state,
/// less the sum of:
/// - funds burnt,
/// - pledge collateral locked in storage miner actors (recorded in the storage power actor)
/// - deal collateral locked by the storage market actor
fn total_fil_circ_supply(&self) -> Result<TokenAmount, ActorError>;
/// ChargeGas charges specified amount of `gas` for execution.
/// `name` provides information about gas charging point
fn charge_gas(&mut self, name: &'static str, compute: i64) -> Result<(), ActorError>;
}
/// Message information available to the actor about executing message.
pub trait MessageInfo {
/// The address of the immediate calling actor. Always an ID-address.
fn caller(&self) -> &Address;
/// The address of the actor receiving the message. Always an ID-address.
fn receiver(&self) -> &Address;
/// The value attached to the message being processed, implicitly
/// added to current_balance() before method invocation.
fn value_received(&self) -> &TokenAmount;
}
/// Pure functions implemented as primitives by the runtime.
pub trait Syscalls {
/// Verifies that a signature is valid for an address and plaintext.
fn verify_signature(
&self,
signature: &Signature,
signer: &Address,
plaintext: &[u8],
) -> Result<(), Box<dyn StdError>>;
/// Hashes input data using blake2b with 256 bit output.
fn hash_blake2b(&self, data: &[u8]) -> Result<[u8; 32], Box<dyn StdError>> {
Ok(blake2b_256(data))
}
/// Computes an unsealed sector CID (CommD) from its constituent piece CIDs (CommPs) and sizes.
fn compute_unsealed_sector_cid(
&self,
proof_type: RegisteredSealProof,
pieces: &[PieceInfo],
) -> Result<Cid, Box<dyn StdError>> {
compute_unsealed_sector_cid(proof_type, pieces)
}
/// Verifies a sector seal proof.
fn verify_seal(&self, vi: &SealVerifyInfo) -> Result<(), Box<dyn StdError>>;
/// Verifies a window proof of spacetime.
fn verify_post(&self, verify_info: &WindowPoStVerifyInfo) -> Result<(), Box<dyn StdError>>;
/// Verifies that two block headers provide proof of a consensus fault:
/// - both headers mined by the same actor
/// - headers are different
/// - first header is of the same or lower epoch as the second
/// - at least one of the headers appears in the current chain at or after epoch `earliest`
/// - the headers provide evidence of a fault (see the spec for the different fault types).
/// The parameters are all serialized block headers. The third "extra" parameter is consulted only for
/// the "parent grinding fault", in which case it must be the sibling of h1 (same parent tipset) and one of the
/// blocks in the parent of h2 (i.e. h2's grandparent).
/// Returns nil and an error if the headers don't prove a fault.
fn verify_consensus_fault(
&self,
h1: &[u8],
h2: &[u8],
extra: &[u8],
) -> Result<Option<ConsensusFault>, Box<dyn StdError>>;
fn batch_verify_seals(
&self,
vis: &[(&Address, &Vec<SealVerifyInfo>)],
) -> Result<HashMap<Address, Vec<bool>>, Box<dyn StdError>> {
let mut verified = HashMap::new();
for (&addr, s) in vis.iter() {
let vals = s.iter().map(|si| self.verify_seal(si).is_ok()).collect();
verified.insert(addr, vals);
}
Ok(verified)
}
}
/// Result of checking two headers for a consensus fault.
#[derive(Clone)]
pub struct ConsensusFault {
/// Address of the miner at fault (always an ID address).
pub target: Address,
/// Epoch of the fault, which is the higher epoch of the two blocks causing it.
pub epoch: ChainEpoch,
/// Type of fault.
pub fault_type: ConsensusFaultType,
}
/// Consensus fault types in VM.
#[derive(Clone, Copy)]
pub enum ConsensusFaultType {
DoubleForkMining = 1,
ParentGrinding = 2,
TimeOffsetMining = 3,
}
fn get_required_padding(
old_length: PaddedPieceSize,
new_piece_length: PaddedPieceSize,
) -> (Vec<PaddedPieceSize>, PaddedPieceSize) {
let mut sum = 0;
let mut to_fill = 0u64.wrapping_sub(old_length.0) % new_piece_length.0;
let n = to_fill.count_ones();
let mut pad_pieces = Vec::with_capacity(n as usize);
for _ in 0..n {
let next = to_fill.trailing_zeros();
let p_size = 1 << next;
to_fill ^= p_size;
let padded = PaddedPieceSize(p_size);
pad_pieces.push(padded);
sum += padded.0;
}
(pad_pieces, PaddedPieceSize(sum))
}
pub fn compute_unsealed_sector_cid(
proof_type: RegisteredSealProof,
pieces: &[PieceInfo],
) -> Result<Cid, Box<dyn StdError>> {
let ssize = proof_type.sector_size()? as u64;
let mut all_pieces = Vec::<proofs::PieceInfo>::with_capacity(pieces.len());
let pssize = PaddedPieceSize(ssize);
if pieces.is_empty() {
all_pieces.push(proofs::PieceInfo {
size: pssize.unpadded().into(),
commitment: zero_piece_commitment(pssize),
})
} else {
// pad remaining space with 0 piece commitments
let mut sum = PaddedPieceSize(0);
let pad_to = |pads: Vec<PaddedPieceSize>,
all_pieces: &mut Vec<proofs::PieceInfo>,
sum: &mut PaddedPieceSize| {
for p in pads {
all_pieces.push(proofs::PieceInfo {
size: p.unpadded().into(),
commitment: zero_piece_commitment(p),
});
sum.0 += p.0;
}
};
for p in pieces {
let (ps, _) = get_required_padding(sum, p.size);
pad_to(ps, &mut all_pieces, &mut sum);
all_pieces.push(proofs::PieceInfo::try_from(p)?);
sum.0 += p.size.0;
}
let (ps, _) = get_required_padding(sum, pssize);
pad_to(ps, &mut all_pieces, &mut sum);
}
let comm_d = compute_comm_d(proof_type.try_into()?, &all_pieces)?;
Ok(data_commitment_v1_to_cid(&comm_d)?)
}
| 39.629508 | 115 | 0.661289 |
9b9a6b6995d455943f8fa9f50e5803e239a004cc | 52 | js | JavaScript | n/octopus.js | moqada/rn-twemoji | c49ce5e83627fa86bdabff9ba15edb157f88c07a | [
"MIT"
] | 8 | 2017-03-15T04:27:47.000Z | 2018-12-03T11:15:23.000Z | c/1f419.js | moqada/rn-twemoji | c49ce5e83627fa86bdabff9ba15edb157f88c07a | [
"MIT"
] | 5 | 2017-06-02T06:29:43.000Z | 2020-04-03T17:48:51.000Z | n/octopus.js | moqada/rn-twemoji | c49ce5e83627fa86bdabff9ba15edb157f88c07a | [
"MIT"
] | null | null | null |
module.exports = require('../images/2/1f419.png');
| 17.333333 | 50 | 0.673077 |
44b4279fd1b16ee7b96cd19164301ead93e7d8ae | 115 | sql | SQL | dbt-greenery/macros/positive_values.sql | ramnathv/dbt-explore | 8131e0c86649f69ac4290b124e2bc7cb1df4f033 | [
"Apache-2.0"
] | 3 | 2021-11-22T03:10:23.000Z | 2021-12-10T06:59:13.000Z | dbt-greenery/macros/positive_values.sql | ramnathv/dbt-explore | 8131e0c86649f69ac4290b124e2bc7cb1df4f033 | [
"Apache-2.0"
] | null | null | null | dbt-greenery/macros/positive_values.sql | ramnathv/dbt-explore | 8131e0c86649f69ac4290b124e2bc7cb1df4f033 | [
"Apache-2.0"
] | null | null | null | {% test is_positive(model, column_name) %}
SELECT *
FROM {{ model }}
WHERE {{ column_name }} < 0
{% endtest %} | 16.428571 | 42 | 0.608696 |
7462e23d62d51c4a8a711027625c097eee5df7f6 | 869 | html | HTML | src/app/contact-update/contact-update.component.html | CARLOS-dev208/projeto-crud-angular | 42c735201e11de99d631f5901e4fd1a0918ac3f5 | [
"MIT"
] | null | null | null | src/app/contact-update/contact-update.component.html | CARLOS-dev208/projeto-crud-angular | 42c735201e11de99d631f5901e4fd1a0918ac3f5 | [
"MIT"
] | null | null | null | src/app/contact-update/contact-update.component.html | CARLOS-dev208/projeto-crud-angular | 42c735201e11de99d631f5901e4fd1a0918ac3f5 | [
"MIT"
] | null | null | null | <mat-toolbar color='primary'>
<span>Detathes do contato #{{id}}</span>
</mat-toolbar>
<div class="formConteiner">
<form class="formContent" [formGroup]="contactForm" (ngSubmit)="atualizaContato()">
<mat-form-field appearance="standard">
<mat-label>Nome</mat-label>
<input matInput formControlName="name">
</mat-form-field>
<mat-form-field appearance="standard">
<mat-label>Telefone</mat-label>
<input prefix="+55 " mask="(00) 0000-0000 ||(00) 0 0000-0000" matInput formControlName="phone">
</mat-form-field>
<div class="actions">
<a routerLink="/contacts" mat-raised-button>Cancela</a>
<button [disabled]="!contactForm.dirty ||contactForm.invalid" type="submit" mat-raised-button color="primary">salvar</button>
</div>
</form>
</div>
| 37.782609 | 137 | 0.613349 |
80e32ec753666f45fad3db189fdf6e925e9c344d | 515 | java | Java | src/main/java/xyz/justblink/grace/tag/subtag/Link.java | kasun90/grace | 5303b5c647b26ac14b869735ad0e026c0177e2a1 | [
"MIT"
] | null | null | null | src/main/java/xyz/justblink/grace/tag/subtag/Link.java | kasun90/grace | 5303b5c647b26ac14b869735ad0e026c0177e2a1 | [
"MIT"
] | null | null | null | src/main/java/xyz/justblink/grace/tag/subtag/Link.java | kasun90/grace | 5303b5c647b26ac14b869735ad0e026c0177e2a1 | [
"MIT"
] | null | null | null | package xyz.justblink.grace.tag.subtag;
import xyz.justblink.grace.tag.Tag;
import xyz.justblink.grace.tag.Visitor;
public class Link extends Tag {
private String value;
private String url;
public Link(String value, String url) {
this.value = value;
this.url = url;
}
public String getValue() {
return value;
}
public String getUrl() {
return url;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
| 17.166667 | 43 | 0.621359 |
39d58c596942b7cc5d6aab7b699678c40e7c849e | 11,922 | java | Java | oulipo-communications/src/main/java/net/sf/appia/protocols/group/remote/RemoteViewSession.java | sisbell/appia | c49b96f82a48460f63b190eeac30499dd64ae343 | [
"Apache-2.0"
] | 2 | 2016-11-25T15:30:33.000Z | 2019-04-04T09:40:52.000Z | oulipo-communications/src/main/java/net/sf/appia/protocols/group/remote/RemoteViewSession.java | sisbell/appia | c49b96f82a48460f63b190eeac30499dd64ae343 | [
"Apache-2.0"
] | null | null | null | oulipo-communications/src/main/java/net/sf/appia/protocols/group/remote/RemoteViewSession.java | sisbell/appia | c49b96f82a48460f63b190eeac30499dd64ae343 | [
"Apache-2.0"
] | null | null | null | /**
* Appia: Group communication and protocol composition framework library
* Copyright 2006 University of Lisbon
*
* 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.
*
* Initial developer(s): Alexandre Pinto and Hugo Miranda.
* Contributor(s): See Appia web page for a list of contributors.
*/
/**
* Title: Appia<p>
* Description: Protocol development and composition framework<p>
* Copyright: Copyright (c) Nuno Carvalho and Luis Rodrigues<p>
* Company: F.C.U.L.<p>
* @author Nuno Carvalho and Luis Rodrigues
* @version 1.0
*/
package net.sf.appia.protocols.group.remote;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import net.sf.appia.core.AppiaCursorException;
import net.sf.appia.core.AppiaDuplicatedSessionsException;
import net.sf.appia.core.AppiaEventException;
import net.sf.appia.core.AppiaInvalidQoSException;
import net.sf.appia.core.Channel;
import net.sf.appia.core.ChannelCursor;
import net.sf.appia.core.Direction;
import net.sf.appia.core.Event;
import net.sf.appia.core.EventQualifier;
import net.sf.appia.core.Layer;
import net.sf.appia.core.QoS;
import net.sf.appia.core.Session;
import net.sf.appia.core.events.channel.ChannelInit;
import net.sf.appia.core.events.channel.Debug;
import net.sf.appia.core.message.Message;
import net.sf.appia.protocols.common.RegisterSocketEvent;
import net.sf.appia.protocols.fifo.FifoLayer;
import net.sf.appia.protocols.fifo.FifoSession;
import net.sf.appia.protocols.group.Endpt;
import net.sf.appia.protocols.group.Group;
import net.sf.appia.protocols.group.ViewID;
import net.sf.appia.protocols.group.ViewState;
import net.sf.appia.protocols.group.heal.GossipOutEvent;
import net.sf.appia.protocols.udpsimple.UdpSimpleLayer;
import net.sf.appia.protocols.udpsimple.UdpSimpleSession;
import net.sf.appia.protocols.utils.ParseUtils;
import net.sf.appia.xml.interfaces.InitializableSession;
import net.sf.appia.xml.utils.SessionProperties;
import org.apache.log4j.Logger;
/**
* RemoteViewSession is the session that implements the RemoteView request
* functionality.<p>
*
* It registers itself in the specified gossip server.
* The requests are made by sending a {@link RemoteViewEvent} to this session
* with the required group id, witch are replied by an ascending
* RemoteViewEvent containing the group id and an array of the group member's
* addresses.
*/
public class RemoteViewSession extends Session implements InitializableSession {
private static Logger log = Logger.getLogger(RemoteViewSession.class);
private static final boolean FULL_DEBUG = false;
private PrintStream debug = null;
public static final int DEFAULT_GOSSIP_PORT = 10000;
private static final int NUM_LAYERS_GOSSIP_CHANNEL = 3;
private InetSocketAddress myAddress=null;
private InetSocketAddress gossipAddress;
private Channel myChannel = null;
private Channel initChannel;
private boolean needsRse = true;
private RemoteViewEvent rve=null;
/**
* Session standard constructor.
*/
public RemoteViewSession(Layer l) {
super(l);
}
/**
* Initializes this session. Must be called before the channel is started.
*
* @param gossipAddress the address of the gossip server to contact
*/
public void init(InetSocketAddress gossipAddress) {
this.gossipAddress = gossipAddress;
}
public void init(SessionProperties params) {
if (params.containsKey("gossip")) {
try {
gossipAddress = ParseUtils.parseSocketAddress(params.getString("gossip"),null,DEFAULT_GOSSIP_PORT);
} catch (UnknownHostException e) {
log.warn("XML initialization failed due to the following exception: "+e);
} catch (ParseException e) {
log.warn("XML initialization failed due to the following exception: "+e);
}
}
}
/**
* The event handler method.
*
* @param event the event
*/
public void handle(Event event) {
if(FULL_DEBUG)
debug("received event on handle: " + event);
if (event instanceof ChannelInit) {
handleChannelInit((ChannelInit) event);
return;
}
if (event instanceof RemoteViewEvent) {
handleRemoteView((RemoteViewEvent) event);
return;
}
if (event instanceof GossipOutEvent) {
handleGossipOut((GossipOutEvent) event);
return;
}
if(event instanceof RegisterSocketEvent){
handleRegisterSocketEvent((RegisterSocketEvent) event);
return;
}
if (event instanceof Debug) {
final Debug ev = (Debug) event;
if (ev.getQualifierMode() == EventQualifier.ON) {
if (ev.getOutput() instanceof PrintStream)
debug = (PrintStream)ev.getOutput();
else
debug = new PrintStream(ev.getOutput());
log.debug("Full debugging started.");
} else {
if (ev.getQualifierMode() == EventQualifier.OFF)
debug = null;
else if (ev.getQualifierMode() == EventQualifier.NOTIFY) {
if (ev.getOutput() instanceof PrintStream)
debug = (PrintStream)ev.getOutput();
else
debug = new PrintStream(ev.getOutput());
debug = null;
}
}
try {
ev.go();
} catch (AppiaEventException ex) {
log.debug("error forwarding event of type "+ev.getClass().getName()+" : "+ex);
}
return;
} // end of debug event handling
log.warn("Received unwanted event (" + event.getClass().getName()+"). Forwarding it.");
try {
event.go();
} catch (AppiaEventException ex) {
log.debug("error forwarding event of type "+event.getClass().getName()+" : "+ex);
}
}
private void handleChannelInit(ChannelInit event) {
try {
event.go();
} catch (AppiaEventException ex) {
log.debug("error forwarding event of type "+event.getClass().getName()+" : "+ex);
}
if (myChannel == null) {
initChannel = event.getChannel();
makeOutChannel(initChannel);
} else {
if (needsRse) {
try {
final RegisterSocketEvent rse =
new RegisterSocketEvent(myChannel, Direction.DOWN, this, myAddress.getPort());
rse.go();
} catch (AppiaEventException ex) {
log.debug("error forwarding event of type "+RegisterSocketEvent.class.getClass().getName()+" : "+ex);
}
}
// send a GossipOutEvent to set things in motion immediatly
try {
final GossipOutEvent goe =
new GossipOutEvent(myChannel, Direction.DOWN, this);
final Message msg = (Message) goe.getMessage();
msg.pushObject(new ViewID(0, new Endpt()));
msg.pushObject(new Group());
msg.pushObject(myAddress);
goe.source = myAddress;
goe.dest = gossipAddress;
goe.init();
goe.go();
} catch (AppiaEventException ex) {
log.debug("error forwarding event of type "+GossipOutEvent.class.getName()+" : "+ex);
}
}
}
private void makeOutChannel(Channel t) {
final ChannelCursor cursor = new ChannelCursor(t);
final Layer[] layers = new Layer[NUM_LAYERS_GOSSIP_CHANNEL];
try {
cursor.bottom();
if (cursor.getLayer() instanceof UdpSimpleLayer) {
layers[0] = cursor.getLayer();
needsRse = false;
} else {
layers[0] = new UdpSimpleLayer();
needsRse = true;
}
while(cursor.isPositioned() && !(cursor.getLayer() instanceof FifoLayer))
cursor.up();
if (cursor.isPositioned())
layers[1] = cursor.getLayer();
else
layers[1] = new FifoLayer();
layers[2] = this.getLayer();
final QoS qos = new QoS("Gossip Out QoS", layers);
myChannel = qos.createUnboundChannel("Gossip Channel",t.getEventScheduler());
final ChannelCursor mycc = myChannel.getCursor();
mycc.bottom();
cursor.bottom();
if (cursor.getSession() instanceof UdpSimpleSession)
mycc.setSession(cursor.getSession());
mycc.up();
while (cursor.isPositioned() &&
!(cursor.getSession() instanceof FifoSession))
cursor.up();
if (cursor.isPositioned())
mycc.setSession(cursor.getSession());
mycc.up();
mycc.setSession(this);
myChannel.start();
} catch (AppiaCursorException ex) {
log.debug("Error: unable to create GossipOut channel: "+ex);
} catch (AppiaInvalidQoSException ex) {
log.debug("Error: unable to create GossipOut channel: "+ex);
} catch (AppiaDuplicatedSessionsException ex) {
log.debug("Error: unable to create GossipOut channel: "+ex);
}
}
private void handleGossipOut(GossipOutEvent event) {
try{
event.go();
}
catch(AppiaEventException e){
log.debug("error forwarding event of type "+event.getClass().getName()+" : "+e);
}
}
private void handleRemoteView(RemoteViewEvent event) {
if (event.getDir() == Direction.DOWN) {
// we got a request
if (myAddress==null) {
rve=event;
return;
}
try {
if(log.isDebugEnabled())
log.debug("sending request from " + myAddress +
" to " + gossipAddress + " in channel " + myChannel.getChannelID() +
" for group " + event.getGroup());
event.dest = gossipAddress;
event.source = myAddress;
final Message msg = event.getMessage();
Group.push(event.getGroup(),msg);
msg.pushObject(myAddress);
// event.setMessage(msg);
event.setChannel(myChannel);
event.setSourceSession(this);
event.init();
event.go();
event = null;
} catch (AppiaEventException ex) {
log.debug("error sending down RemoteViewEvent: "+ex);
}
} else {
boolean appearsViewState = true;
final Message msg = (Message) event.getMessage();
try{
ViewState.peek(msg);
}catch(Exception special){
if(log.isDebugEnabled())
log.debug("Message contents do not appear to be a ViewState object.");
appearsViewState = false;
}
//debug("Received remote view event!!!!!("+ViewState.peek(om)+")");
if (appearsViewState && ViewState.peek(msg) instanceof ViewState) {
final ViewState receivedVs = ViewState.pop(msg);
event.setAddresses(receivedVs.addresses);
event.setGroup(receivedVs.group);
event.setSourceSession(this);
event.setChannel(initChannel);
try {
event.init();
event.go();
} catch(AppiaEventException ex){
log.debug("error forwarding event of type "+event.getClass().getName()+" : "+ex);
}
}
}
}
private void handleRegisterSocketEvent(RegisterSocketEvent e){
if(e.getDir()==Direction.UP){
myAddress = new InetSocketAddress(e.localHost, e.port);
if(rve!=null){
handle(rve);
rve=null;
}
}
try{
e.go();
}
catch(AppiaEventException ex){
log.debug("error forwarding event of type "+e.getClass().getName()+" : "+e);
}
}
/**
* Sends a Debug event through the Gossip Out channel with the specified
* EventQualifier
*
* @see Debug
* @see EventQualifier
*/
public void doDebug(int eq) {
try {
final java.io.OutputStream debugOut = System.out;
final Debug e = new Debug(debugOut);
e.setChannel(myChannel);
e.setDir(Direction.DOWN);
e.setSourceSession(this);
e.setQualifierMode(eq);
e.init();
e.go();
} catch (AppiaEventException ex) {
ex.printStackTrace();
System.err.println("Exception when sending debug event");
}
}
private void debug(String s){
if(debug != null)
debug.println(this.getClass().getName()+"[FULL DEBUG] "+s);
}
}
| 29.220588 | 121 | 0.679165 |
279c18458572bff89e0238db29d47352ee4d0808 | 6,861 | asm | Assembly | project/serial.asm | Mahboub99/BlobbyVolley-8086 | a8c53e7cdc78e267fb3a2bf25882ad74f59dc300 | [
"MIT"
] | 4 | 2020-01-31T06:25:58.000Z | 2021-02-05T16:17:40.000Z | project/serial.asm | aashrafh/BlobbyVolley | 6a451bef2276b11acf2e1affe07d6f501e7b3574 | [
"MIT"
] | null | null | null | project/serial.asm | aashrafh/BlobbyVolley | 6a451bef2276b11acf2e1affe07d6f501e7b3574 | [
"MIT"
] | 3 | 2019-11-27T19:04:03.000Z | 2021-02-14T21:52:30.000Z | Scroll_Chat macro Color,Upx,Upy,Downx,Downy;bytes
pusha
;(
;scroll upper half the screen
mov ah,6 ; function 6
mov al,1 ;scroll one line
mov bh,Color ; video attribute
mov ch,Upy ; upper left Y
mov cl,Upx ; upper left X
mov dh,Downy ; lower right Y
mov dl,Downx ; lower right X
int 10h
;)
popa
endm Scroll_Chat
.model small
.stack
.386
.data
CharSent db 's'
CharReceived db 'R'
UpCursorx db 0
UpCursory db 0
DownCursorx db 0
DownCursory db 13
Up equ 1
Down equ 2
UpColor equ 77
DownColor equ 07
.code
main proc far
mov ax,@data
mov ds,ax
;initialize
call InitializScreen
call InitializUART
;(
Again:
call send
call Receive
jmp Again
;)
Finish:
mov ah,4Ch
int 21h
main endp
InitializUART proc
;(
mov dx,3fbh ; Line Control Register
mov al,10000000b ;Set Divisor Latch Access Bit
out dx,al ;Out it
;set the divisor:
;first byte
mov dx,3f8h
mov al,0ch
out dx,al
;second byte
mov dx,3f9h
mov al,00h
out dx,al
;set the rest of the initialization
mov dx,3fbh
mov al,00011011b ;
out dx,al
;)
ret
InitializUART endp
;;;;;;;;;;;;;;;;;;;
InitializScreen proc
;(
;open text mode(80*25)
mov ah,0
mov al,03
int 10h
;scroll upper half the screen
mov ah,6 ; function 6
mov al,13
mov bh,77 ; video attribute
;back ground:(0black-1blue-2blue-3green-5lightgreen-6red-7red)
mov ch,0 ; upper left Y
mov cl,0 ; upper left X
mov dh,0ch ; lower right Y
mov dl,79 ; lower right X
int 10h
;)
ret
InitializScreen endp
;;;;;;;;;;;;;;;;;;;;;;
Send proc
;(
check_buffer:
mov ah,1
int 16h
jz RetrunSend
;if found letter, eat buffer
mov ah,0
int 16h
mov CharSent,al
CheckAgain:
;Check that Transmitter Holding Register is Empty
mov dx , 3FDH ; Line Status Register
In al , dx ;Read Line Status
test al , 00100000b
JZ CheckAgain ;Not empty
;jz RetrunSend
;If empty put the VALUE in Transmit data register
mov dx , 3F8H ; Transmit data register
mov al,CharSent
out dx , al
cmp al,27 ;if user presses (esc)
je Finish ;end the program for both users
;compare with enter
cmp ah, 1ch
jne dont_scroll_line
mov UpCursorx, -1 ;because it's incremented in PrintChar
inc UpCursory
cmp UpCursory,13;if screen is full
jne dont_scroll_line
Scroll_Chat UpColor,0,0,79,12
dec UpCursory
jmp Dummy001
dont_scroll_line:
;check to remove
cmp ah, 0eh ;delete scan code
jne Dummy001
cmp UpCursorx, 0
jne NotInStartX
;in x = 0
cmp UpCursory, 0
jne NotInStartY
;in x = 0 and y = 0
ret
NotInStartY:
;in x = 0 but y != 0
mov UpCursorx, 79
dec UpCursory
mov ah, 2
mov dl, UpCursorx
mov dh, UpCursory
int 10h
;print space
mov ah, 2
mov dl, 20h
int 21h
ret
NotInStartX:
dec UpCursorx
mov ah, 2
mov dl, UpCursorx
mov dh, UpCursory
int 10h
;print space
mov ah, 2
mov dl, 20h
int 21h
ret
Dummy001:
;display
mov bl,Up
call PrintChar
;)
RetrunSend:
ret
Send endp
;;;;;;;;;;;;;;;
Receive proc
;(
;Check that Data is Ready
mov dx , 3FDH ; Line Status Register
in al , dx
test al , 1
JZ RetrunReceived ;Not Ready
;If Ready read the VALUE in Receive data register
mov dx , 03F8H
in al , dx
mov CharReceived , al
;if the user presses esc:
cmp al,27
je Finish ;end the program for both users
;compare with enter
cmp al, 0Dh
jne dont_scroll_line_R
mov DownCursorx, -1 ;because it's incremented in PrintChar
inc DownCursory
cmp DownCursory, 25;if screen is full
jne dont_scroll_line_R
Scroll_Chat DownColor,0,13,79,24
dec DownCursory
jmp Dummy002
dont_scroll_line_R:
;check to remove
cmp al, 08h ;delete scan code
jne Dummy002
cmp DownCursorx, 0
jne NotInStartX_R
;in x = 0
cmp DownCursory, 0
jne NotInStartY_R
;in x = 0 and y = 0
ret
NotInStartY_R:
;in x = 0 but y != 0
mov DownCursorx, 79
dec DownCursory
mov ah, 2
mov dl, DownCursorx
mov dh, DownCursory
int 10h
;print space
mov ah, 2
mov dl, 20h
int 21h
ret
NotInStartX_R:
dec DownCursorx
mov ah, 2
mov dl, DownCursorx
mov dh, DownCursory
int 10h
;print space
mov ah, 2
mov dl, 20h
int 21h
ret
Dummy002:
mov bl,Down
call PrintChar
;)
RetrunReceived:
ret
Receive endp
;;;;;;;;;;;;
PrintChar proc
;(
cmp bl,Up ; prrint up
JNE DOWN_Cursor
;mov dl,charsent
cmp UpCursorx,80 ;end of the line
je UpCursoryLine
mov dl,UpCursorx
mov dh,UpCursory
inc UpCursorx
JMP Cursor_move
UpCursoryLine:
inc UpCursory ;go to the next line
cmp UpCursory,13;if screen is full
jne DonotScrollUp
Scroll_Chat UpColor,0,0,79,12
dec UpCursory
DonotScrollUp:
MOV UpCursorx,0 ;start from the first column
mov dl,UpCursorx
mov dh,UpCursory
;for the upcomming character;could be removed from here and line 187 and be placed
;before mov dl,UpCursorx and y but to initially start from (-1)
;(each time we want to set the cursor at the begining of the line(x=0))
inc UpCursorx
JMP Cursor_move
DOWN_Cursor:
cmp DownCursorx,80;end of the line
je DownpCursoryLine
mov dl,DownCursorx
mov dh,DownCursory
inc DownCursorx
jmp Cursor_move
DownpCursoryLine:
inc DownCursory
cmp DownCursory,25;if screen is full
jne DonotScrollDown
Scroll_Chat DownColor,0,13,79,24
sub DownCursory,2
DonotScrollDown:
MOV DownCursorx,0
mov dl,DownCursorx
mov dh,DownCursory
inc DownCursorx;for the upcomming character
Cursor_move:
mov ah,2
mov bh,0;page;;;;;;;;;;;;;;important
int 10h ;excute
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Print the character:
cmp bl,Up ; print up
JNE DownPrint
mov dl,charsent
jmp PrintLabel
DownPrint:
mov dl,CharReceived
PrintLabel:
mov ah, 2
int 21h
;)
ret
PrintChar endp
Receive_Action Proc
;Check that Data is Ready
mov dx , 3FDH ; Line Status Register
in al , dx
test al , 1
JZ RetrunReceived ;Not Ready
;If Ready read the VALUE in Receive data register
mov dx , 03F8H
in al , dx
mov CharReceived , al
RetrunReceived
Receive_Action Endp
Send_Ation Proc
check_buffer:
mov ah,1
int 16h
jz RetrunSend
;if found letter, eat buffer
mov ah,0
int 16h
mov CharSent,al
CheckAgain:
;Check that Transmitter Holding Register is Empty
mov dx , 3FDH ; Line Status Register
In al , dx ;Read Line Status
test al , 00100000b
JZ CheckAgain ;Not empty
;jz RetrunSend
;If empty put the VALUE in Transmit data register
mov dx , 3F8H ; Transmit data register
mov al,CharSent
out dx , al
Send_Ation Endp
end main | 18.150794 | 84 | 0.655735 |
e947155f865f17abe25dd1f989217dfe17400c1f | 329 | lua | Lua | utils/init.lua | atatsu/giblets | 300fcf6e584563a572ab3059b0403241a9631a67 | [
"BSD-3-Clause"
] | null | null | null | utils/init.lua | atatsu/giblets | 300fcf6e584563a572ab3059b0403241a9631a67 | [
"BSD-3-Clause"
] | null | null | null | utils/init.lua | atatsu/giblets | 300fcf6e584563a572ab3059b0403241a9631a67 | [
"BSD-3-Clause"
] | null | null | null | --- Utilities for the awesome window manager.
-- Various components that don't fall into the widget and gizmo categories, but
-- can make your awesome experience more enjoyable.
-- @module giblets.utils
-- @author Nathan Lundquist (atatsu)
-- @copyright 2015 Nathan Lundquist
return {
leaf = require("giblets.utils.leaf"),
}
| 29.909091 | 80 | 0.744681 |
70d166a1cb2bb7b89d51cc773f45da5b432be7e2 | 1,561 | c | C | src/main.c | 5IGI0/frnum | 2604bfd48a3097114ff384b175e519f039d4b717 | [
"MIT"
] | null | null | null | src/main.c | 5IGI0/frnum | 2604bfd48a3097114ff384b175e519f039d4b717 | [
"MIT"
] | null | null | null | src/main.c | 5IGI0/frnum | 2604bfd48a3097114ff384b175e519f039d4b717 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include "frnum.h"
#define FWRITE_HCSTR(data, file) fwrite(data, 1, sizeof(data)-1, file);
int main(int argc, char const *argv[]) {
phoneLookup_t lookup = {0};
phoneDB_t *phoneDB = NULL;
if (argc != 2) {
fprintf(stderr, "usage: %s <phone number>\n", argv[0]);
return EXIT_FAILURE;
} else {
if(sscanf(argv[1], "%u", &lookup.phone) != 1) {
fprintf(stderr, "usage: %s <phone number>\n", argv[0]);
return EXIT_FAILURE;
}
}
FILE *file = fopen(getenv("NUMLOOKUP_DB_PATH") ? getenv("NUMLOOKUP_DB_PATH") : "./frnum.db", "rb");
if (file == NULL) {
perror(getenv("NUMLOOKUP_DB_PATH") ? getenv("NUMLOOKUP_DB_PATH") : "./frnum.db");
return EXIT_FAILURE;
}
if((phoneDB = phone_load(file)) == NULL) {
FWRITE_HCSTR("cannot load the database", stderr);
if (errno != 0)
perror("");
FWRITE_HCSTR("\n", stderr);
fclose(file);
return EXIT_FAILURE;
}
lookup = phone_lookup(phoneDB, lookup.phone);
if (lookup.ownerID[0] == 0) {
puts("not found!");
} else {
printf(
"number: %s\n"
"owner : %s (%s)\n"
"area : %s\n",
format_phone(lookup.phone),
lookup.ownerID, lookup.ownerName,
lookup.area
);
}
phone_freeDB(phoneDB);
fclose(file);
return EXIT_SUCCESS;
}
| 25.177419 | 103 | 0.543242 |
b9d3512802650046d4763f5fcd7c868bf85b6f56 | 5,814 | dart | Dart | lib/ui/views/home/exercise_tab/muscle_binding/muscle_binding_view.dart | VB10/HealthoUI | 9fca7db8941f58f1020a99ddab88ae37f78f6254 | [
"Apache-2.0"
] | 49 | 2019-07-11T15:04:13.000Z | 2022-02-28T23:45:58.000Z | lib/ui/views/home/exercise_tab/muscle_binding/muscle_binding_view.dart | VB10/HealthoUI | 9fca7db8941f58f1020a99ddab88ae37f78f6254 | [
"Apache-2.0"
] | 1 | 2019-09-08T20:23:19.000Z | 2019-09-08T20:23:19.000Z | lib/ui/views/home/exercise_tab/muscle_binding/muscle_binding_view.dart | VB10/HealthoUI | 9fca7db8941f58f1020a99ddab88ae37f78f6254 | [
"Apache-2.0"
] | 13 | 2019-07-24T21:12:24.000Z | 2021-11-06T19:52:33.000Z | import 'package:flutter/material.dart';
import 'package:healthoui/ui/shared/widget/listview/padding_listview.dart';
import 'package:healthoui/ui/shared/widget/padding/base_padding_enum.dart';
import './muscle_binding_view_model.dart';
import '../../../../shared/theme.dart';
import '../../../../shared/ui_helper.dart';
import '../../../../shared/widget/text/colum_text.dart';
import '../../../../shared/widget/text/subtitle.dart';
class MuscleBindingView extends MuscleBindingViewModel {
@override
Widget build(BuildContext context) {
// Replace this with your build function
return Scaffold(
appBar: UIHelper.appBar("Muscle Building"),
body: PaddingListView(
spaceLevel: BasePaddingLevel.VERY_LOW,
widgets: <Widget>[
photoCard,
introCard,
progressCard,
progressText,
...subCards
],
),
);
}
List<Widget> get subCards {
List<Widget> _cards = [];
for (var i = 0; i < 10; i++) {
_cards.add(
Card(
color: greyCardColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(SpaceValue.LOW)),
child: cardItem("${i < 10 ? 0 : ""}$i"),
),
);
}
return _cards;
}
Widget cardItem(String text) {
return ListTile(
leading: AspectRatio(
aspectRatio: 90 / 100,
child: Container(
alignment: Alignment.topRight,
child: SubTitleText(
text,
color: Colors.grey,
size: FontSizeValue.HIGH,
),
),
),
dense: true,
title: Text("Week"),
subtitle: SubTitleText("This is a beginner quick start....."),
trailing: Icon(
Icons.chevron_right,
),
);
}
Widget get progressText => Align(
alignment: Alignment.centerRight,
child: SubTitleText("${(progressValue * 100).toInt()}% Complete"),
);
Widget get progressCard => Card(
child: LinearProgressIndicator(
value: progressValue,
backgroundColor: greyCardColor,
valueColor: AlwaysStoppedAnimation(Colors.green),
),
);
Widget get photoCard => AspectRatio(
aspectRatio: 7 / 4,
child: Stack(
children: <Widget>[photo, aspectAlignPhotoCardInner],
),
);
Widget get introCard => ListTile(
onTap: onPressed,
trailing: Icon(Icons.chevron_right),
title: Wrap(
children: <Widget>[Text("Introduction"), SubTitleText(text)],
),
);
Widget get photo => Placeholder();
Widget get aspectAlignPhotoCardInner => Align(
alignment: Alignment.bottomCenter,
child: AspectRatio(
aspectRatio: 10 / 1.5,
child: photoInnerContainer,
),
);
Widget get photoInnerContainer => Container(
child: photoInnerChild,
margin: EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(
color: yellowSearchCardColor,
borderRadius: BorderRadius.vertical(top: Radius.circular(30)),
),
);
Widget get photoInnerChild => Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ColumnText(
values: ["Goal", "Muscle Building"],
),
ColumnText(
values: ["Duration", "5 Weeks"],
),
ColumnText(
values: ["Level", "Beginner"],
),
],
);
}
// before widget
// AspectRatio(
// aspectRatio: 7 / 3,
// child: Stack(
// children: <Widget>[
// Placeholder(),
// Align(
// alignment: Alignment.bottomCenter,
// child: AspectRatio(
// aspectRatio: 10 / 1.5,
// child: Container(
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
// crossAxisAlignment: CrossAxisAlignment.end,
// children: <Widget>[
// Wrap(
// direction: Axis.vertical,
// children: <Widget>[
// Text("Goal"),
// Text("Muscle Building"),
// ],
// ),
// Wrap(
// direction: Axis.vertical,
// children: <Widget>[
// Text("a"),
// Text("b"),
// ],
// ),
// Wrap(
// direction: Axis.vertical,
// children: <Widget>[
// Text("a"),
// Text("b"),
// ],
// )
// ],
// ),
// margin: EdgeInsets.symmetric(horizontal: 20),
// decoration: BoxDecoration(
// color: yellowSearchCardColor,
// borderRadius:
// BorderRadius.vertical(top: Radius.circular(30)),
// ),
// ),
// ),
// before atomic
// ListTile(
// trailing: Icon(Icons.chevron_right),
// title: Wrap(
// children: <Widget>[
// Text("Introduction"),
// SubTitleText("data" * 10)
// ],
// ),
// )
| 31.258065 | 79 | 0.470588 |
a7857d837ce976989db74d6c182f63e1798241a5 | 4,094 | lua | Lua | init.lua | Billy-S/minetest-jail | 7b8247081bfd3e6ebed1a2dbc8e910f3595b8472 | [
"WTFPL"
] | null | null | null | init.lua | Billy-S/minetest-jail | 7b8247081bfd3e6ebed1a2dbc8e910f3595b8472 | [
"WTFPL"
] | null | null | null | init.lua | Billy-S/minetest-jail | 7b8247081bfd3e6ebed1a2dbc8e910f3595b8472 | [
"WTFPL"
] | 1 | 2020-05-14T11:43:30.000Z | 2020-05-14T11:43:30.000Z | -- Jail Mod
-- Prototype created by kaeza and RAPHAEL (mostly kaeza)
-- Enhanced by BillyS
-- license: whatever
minetest.register_privilege("jail", { description = "Allows one to send/release prisoners" })
jailpos = {x = -20, y = 48, z = -67}
releasepos = {x = -512, y = 36, z = 169}
players_in_jail = {}
jaildatapath = minetest.get_worldpath() .. "/"
function saveJailData (path)
local file = io.open(path .. "jailData.txt", "w")
if not file then return false end
file:write(minetest.serialize({players_in_jail, jailpos, releasepos}))
file:close()
return true
end
function loadJailData (path)
local file = io.open(path .. "jailData.txt", "r")
if not file then return false end
jData = minetest.deserialize(file:read("*all"))
file:close()
return jData
end
function jailPlayer (pName, by)
local player = minetest.env:get_player_by_name(pName)
if (player and not players_in_jail[pName] and not minetest.get_player_privs(pName).jail) then
players_in_jail[pName] = {name = pName, privs = minetest.get_player_privs(pName)};
minetest.set_player_privs(pName, {shout = true})
player:setpos(jailpos)
minetest.chat_send_player(pName, "You have been sent to jail")
minetest.chat_send_all(""..pName.." has been sent to jail by "..by.."")
saveJailData (jaildatapath)
return true
end
end
function releasePlayer (pName, by)
local player = minetest.env:get_player_by_name(pName)
if (player and players_in_jail[pName]) then
minetest.set_player_privs(pName, players_in_jail[pName].privs)
players_in_jail[pName] = nil;
player:setpos(releasepos)
minetest.chat_send_player(pName, "You have been released from jail")
minetest.chat_send_all(""..pName.." has been released from jail by "..by.."")
saveJailData (jaildatapath)
return true
end
end
local jData = loadJailData (jaildatapath)
if jData then
if type(jData[1]) == type({}) then
players_in_jail = jData[1]
jailpos = jData[2]
releasepos = jData[3]
else
players_in_jail = jData
end
end
minetest.register_chatcommand("jail", {
params = "<player>",
description = "Sends a player to Jail",
privs = {jail=true},
func = function ( name, param )
jailPlayer (param, name)
end,
})
minetest.register_chatcommand("tempjail", {
params = "<player> <time>",
description = "Sends a player in jail for a certain amount of time (in minutes)",
privs = {jail = true},
func = function (name, param)
pName = param:gsub("%s.+", "")
jailTime = param:gsub(".+%s", "")
if (pName == param or jailTime == param) then return end
jailTime = tonumber(jailTime)
if jailTime then
jailPlayer (pName, name)
minetest.after(jailTime * 60, function (params)
local pName = params[1]
local by = params[2]
releasePlayer (pName, by)
end,
{pName, name})
end
end
})
minetest.register_chatcommand("release", {
params = "<player>",
description = "Releases a player from Jail",
privs = {jail=true},
func = function ( name, param )
if (param == "") then return end
releasePlayer (param, name)
end,
})
minetest.register_on_chat_message(function(name, msg)
for i, _ in pairs(players_in_jail) do
if name == i then
minetest.chat_send_all("<" .. name .. "@jail> " .. msg)
return true
end
end
end
)
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
if frozen_players[name] then
player:set_physics_override({speed = 0, jump = 0, gravity = 1.0, sneak = false, sneak_glitch = false})
end
end)
local playerInst
local function do_teleport ( )
for name, player in pairs(players_in_jail) do
playerInst = minetest.env:get_player_by_name(player.name)
if playerInst then
playerInst:setpos(jailpos)
end
end
minetest.after(30, do_teleport)
end
minetest.after(30, do_teleport)
minetest.register_node("jail:barbed_wire", {
description = "Barbed Wire",
drawtype = "glasslike",
tile_images = {"jail_barbed_wire.png"},
sunlight_propagates = true,
groups = {snappy = 2}
-- sounds = default.node_sound_stone_defaults(),
})
| 28.629371 | 104 | 0.692721 |
7108c453be7c47d4775f5f64ea21c66c86756d4c | 5,605 | ts | TypeScript | src/__tests__/integration/basic/vrf.test.ts | redstone-finance/redstone-smartcontracts | 5dac0a727c911409ec5e04fc855f06a731bcd953 | [
"MIT"
] | 33 | 2021-09-18T12:27:43.000Z | 2022-03-25T16:45:57.000Z | src/__tests__/integration/basic/vrf.test.ts | redstone-finance/redstone-smartcontracts | 5dac0a727c911409ec5e04fc855f06a731bcd953 | [
"MIT"
] | 49 | 2021-09-14T11:16:10.000Z | 2022-03-29T18:22:22.000Z | src/__tests__/integration/basic/vrf.test.ts | redstone-finance/redstone-smartcontracts | 5dac0a727c911409ec5e04fc855f06a731bcd953 | [
"MIT"
] | 9 | 2021-11-04T17:22:33.000Z | 2022-03-10T12:28:00.000Z | import fs from 'fs';
import ArLocal from 'arlocal';
import Arweave from 'arweave';
import { JWKInterface } from 'arweave/node/lib/wallet';
import {
ArweaveGatewayInteractionsLoader,
EvaluationOptions,
GQLEdgeInterface,
InteractionsLoader,
LexicographicalInteractionsSorter,
LoggerFactory,
PstContract,
PstState,
SmartWeave,
SmartWeaveNodeFactory
} from '@smartweave';
import path from 'path';
import { addFunds, mineBlock } from '../_helpers';
import { Evaluate } from '@idena/vrf-js';
import elliptic from 'elliptic';
const EC = new elliptic.ec('secp256k1');
const key = EC.genKeyPair();
const pubKeyS = key.getPublic(true, 'hex');
const useWrongIndex = [];
const useWrongProof = [];
describe('Testing the Profit Sharing Token', () => {
let contractSrc: string;
let wallet: JWKInterface;
let walletAddress: string;
let initialState: PstState;
let arweave: Arweave;
let arlocal: ArLocal;
let smartweave: SmartWeave;
let pst: PstContract;
let loader: InteractionsLoader;
beforeAll(async () => {
// note: each tests suit (i.e. file with tests that Jest is running concurrently
// with another files has to have ArLocal set to a different port!)
arlocal = new ArLocal(1823, false);
await arlocal.start();
arweave = Arweave.init({
host: 'localhost',
port: 1823,
protocol: 'http'
});
loader = new VrfDecorator(arweave);
LoggerFactory.INST.logLevel('error');
smartweave = SmartWeaveNodeFactory.memCachedBased(arweave)
.useArweaveGateway()
.setInteractionsLoader(loader)
.build();
wallet = await arweave.wallets.generate();
await addFunds(arweave, wallet);
walletAddress = await arweave.wallets.jwkToAddress(wallet);
contractSrc = fs.readFileSync(path.join(__dirname, '../data/token-pst.js'), 'utf8');
const stateFromFile: PstState = JSON.parse(fs.readFileSync(path.join(__dirname, '../data/token-pst.json'), 'utf8'));
initialState = {
...stateFromFile,
...{
owner: walletAddress,
balances: {
...stateFromFile.balances,
[walletAddress]: 555669
}
}
};
const contractTxId = await smartweave.createContract.deploy({
wallet,
initState: JSON.stringify(initialState),
src: contractSrc
});
// connecting to the PST contract
pst = smartweave.pst(contractTxId);
// connecting wallet to the PST contract
pst.connect(wallet);
await mineBlock(arweave);
});
afterAll(async () => {
await arlocal.stop();
});
it('should properly return random numbers', async () => {
await pst.writeInteraction({
function: 'vrf'
});
await mineBlock(arweave);
const result = await pst.readState();
const lastTxId = Object.keys(result.validity).pop();
const vrf = (result.state as any).vrf[lastTxId];
console.log(vrf);
expect(vrf).not.toBeUndefined();
expect(vrf['random_6_1'] == vrf['random_6_2']).toBe(true);
expect(vrf['random_6_2'] == vrf['random_6_3']).toBe(true);
expect(vrf['random_12_1'] == vrf['random_12_2']).toBe(true);
expect(vrf['random_12_2'] == vrf['random_12_3']).toBe(true);
expect(vrf['random_46_1'] == vrf['random_46_2']).toBe(true);
expect(vrf['random_46_2'] == vrf['random_46_3']).toBe(true);
expect(vrf['random_99_1'] == vrf['random_99_2']).toBe(true);
expect(vrf['random_99_2'] == vrf['random_99_3']).toBe(true);
});
it('should throw if random cannot be verified', async () => {
const txId = await pst.writeInteraction({
function: 'vrf'
});
await mineBlock(arweave);
useWrongIndex.push(txId);
await expect(pst.readState()).rejects.toThrow('Vrf verification failed.');
useWrongIndex.pop();
const txId2 = await pst.writeInteraction({
function: 'vrf'
});
await mineBlock(arweave);
useWrongProof.push(txId2);
await expect(pst.readState()).rejects.toThrow('Vrf verification failed.');
useWrongProof.pop();
});
});
class VrfDecorator extends ArweaveGatewayInteractionsLoader {
constructor(protected readonly arweave: Arweave) {
super(arweave);
}
async load(
contractId: string,
fromBlockHeight: number,
toBlockHeight: number,
evaluationOptions: EvaluationOptions
): Promise<GQLEdgeInterface[]> {
const result = await super.load(contractId, fromBlockHeight, toBlockHeight, evaluationOptions);
const arUtils = this.arweave.utils;
const sorter = new LexicographicalInteractionsSorter(this.arweave);
for (const r of result) {
r.node.sortKey = await sorter.createSortKey(r.node.block.id, r.node.id, r.node.block.height);
const data = arUtils.stringToBuffer(r.node.sortKey);
const [index, proof] = Evaluate(key.getPrivate().toArray(), data);
r.node.vrf = {
index: useWrongIndex.includes(r.node.id)
? arUtils.bufferTob64Url(Uint8Array.of(1, 2, 3))
: arUtils.bufferTob64Url(index),
proof: useWrongProof.includes(r.node.id)
? 'pK5HGnXo_rJkZPJorIX7TBCAEikcemL2DgJaPB3Pfm2D6tZUdK9mDuBSRUkcHUDNnrO02O0-ogq1e32JVEuVvgR4i5YFa-UV9MEoHgHg4yv0e318WNfzNWPc9rlte7P7RoO57idHu5SSkm7Qj0f4pBjUR7lWODVKBYp9fEJ-PObZ'
: arUtils.bufferTob64Url(proof),
bigint: bufToBn(index).toString(),
pubkey: pubKeyS
};
}
return result;
}
}
function bufToBn(buf) {
const hex = [];
const u8 = Uint8Array.from(buf);
u8.forEach(function (i) {
let h = i.toString(16);
if (h.length % 2) {
h = '0' + h;
}
hex.push(h);
});
return BigInt('0x' + hex.join(''));
}
| 29.192708 | 186 | 0.66851 |
388173674d9e6fc272e11de1775f1645d98bc5eb | 308 | asm | Assembly | programs/oeis/129/A129343.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | 1 | 2021-03-15T11:38:20.000Z | 2021-03-15T11:38:20.000Z | programs/oeis/129/A129343.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | null | null | null | programs/oeis/129/A129343.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | null | null | null | ; A129343: a(2n) = a(n), a(2n+1) = 4n+1.
; 0,1,1,5,1,9,5,13,1,17,9,21,5,25,13,29,1,33,17,37,9,41,21,45,5,49,25,53,13,57,29,61,1,65,33,69,17,73,37,77,9,81,41,85,21,89,45,93,5,97,49,101,25,105,53,109,13,113,57,117,29,121,61,125,1,129,65,133,33,137
mul $0,2
mov $1,1
lpb $0
mov $1,$0
dif $0,2
lpe
sub $1,1
| 28 | 204 | 0.597403 |
9bfbf619f2f91b57d369b41d1fe88f24fecc803d | 65 | js | JavaScript | src/parsed-text/index.js | Frexity/react-web-gifted-chat | 7f552cd8e9aa107afc6d6f608abdfadc063e47ca | [
"MIT"
] | null | null | null | src/parsed-text/index.js | Frexity/react-web-gifted-chat | 7f552cd8e9aa107afc6d6f608abdfadc063e47ca | [
"MIT"
] | null | null | null | src/parsed-text/index.js | Frexity/react-web-gifted-chat | 7f552cd8e9aa107afc6d6f608abdfadc063e47ca | [
"MIT"
] | null | null | null | import ParsedText from './ParsedText'
export default ParsedText
| 16.25 | 37 | 0.815385 |
e9548f07902879d6e3638b8c6b01d12253921d41 | 523 | go | Go | addr/addr.go | imulab/codecall | db771704e238618b83c757a4fcdd6d974ef6b0c0 | [
"MIT"
] | 1 | 2020-12-13T17:11:38.000Z | 2020-12-13T17:11:38.000Z | addr/addr.go | imulab/codecall | db771704e238618b83c757a4fcdd6d974ef6b0c0 | [
"MIT"
] | null | null | null | addr/addr.go | imulab/codecall | db771704e238618b83c757a4fcdd6d974ef6b0c0 | [
"MIT"
] | null | null | null | package addr
import (
"github.com/imulab/coldcall"
"net/http"
"net/url"
)
// WithQuery is a convenient wrapper for URL that sets the params as the raw query component.
func WithQuery(params url.Values) coldcall.Option {
return func(r *http.Request) error {
r.URL.RawQuery = params.Encode()
return nil
}
}
// WithQueryMap is a convenience wrapper for WithQuery with map values to construct url.Values.
func WithQueryMap(params map[string]string) coldcall.Option {
return WithQuery(coldcall.URLValues(params))
}
| 24.904762 | 95 | 0.75717 |
c7c3622667e9e7efee6b8ff9e5a1826dc8c51450 | 13,816 | py | Python | gui/main.py | ehsteve/roentgen | 76016ad2558d20c3e87304bd4abafa906d98caa5 | [
"Apache-2.0",
"BSD-3-Clause"
] | 7 | 2018-06-05T20:28:44.000Z | 2022-03-16T15:22:45.000Z | gui/main.py | samaloney/roentgen | 44467581886eaa355cb991b3778bb8de7e30a47d | [
"Apache-2.0",
"BSD-3-Clause"
] | 17 | 2018-06-05T20:29:42.000Z | 2021-06-06T18:26:22.000Z | gui/main.py | samaloney/roentgen | 44467581886eaa355cb991b3778bb8de7e30a47d | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2019-10-24T15:24:52.000Z | 2020-08-27T22:17:05.000Z | """
Use the ``bokeh serve`` command to run the example by executing:
bokeh serve --show gui
in your browser.
"""
from os.path import dirname, join
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import layout, Spacer
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models import HoverTool
from bokeh.models.widgets import (
Slider,
TextInput,
Select,
Paragraph,
AutocompleteInput,
CheckboxGroup,
TableColumn,
DataTable,
Button,
CheckboxGroup,
Toggle,
Select,
Div
)
from bokeh.plotting import figure
from bokeh.events import ButtonClick
import astropy.units as u
from astropy import constants as const
from astropy.units.imperial import deg_F, inch, foot, mil
from roentgen.absorption import Material, Response
from roentgen.util import get_density, density_ideal_gas
import roentgen
u.imperial.enable()
DEFAULT_MATERIAL = ["silicon"]
DEFAULT_THICKNESS = [100.0]
DEFAULT_ENERGY_LOW = 1.0
DEFAULT_ENERGY_HIGH = 200.0
DEFAULT_DENSITY = [get_density(DEFAULT_MATERIAL[0]).value]
NUMBER_OF_MATERIALS = len(DEFAULT_MATERIAL)
DEFAULT_DETECTOR_MATERIAL = 'cdte'
DEFAULT_DETECTOR_THICKNESS = 1
DEFAULT_DETECTOR_DENSITY = get_density(DEFAULT_DETECTOR_MATERIAL).value
DEFAULT_ENERGY_RESOLUTION = 0.25
DEFAULT_AIR_THICKNESS = 1
DEFAULT_AIR_PRESSURE = 1
DEFAULT_AIR_TEMPERATURE = 25
PLOT_HEIGHT = 400
PLOT_WIDTH = 900
TOOLS = "pan,wheel_zoom,box_zoom,box_select,undo,redo,save,reset"
custom_hover = HoverTool(
tooltips=[
('energy [keV]', '@{x}{0.2f}'),
('transmission', '@{y}{0.3f}'), # use @{ } for field names with spaces
],
# display a tooltip whenever the cursor is vertically in line with a glyph
mode='vline'
)
# defaults
material_list = []
this_material = Material(DEFAULT_MATERIAL[0], DEFAULT_THICKNESS[0] * u.micron)
air_density = density_ideal_gas(DEFAULT_AIR_PRESSURE * const.atm,
DEFAULT_AIR_TEMPERATURE * u.Celsius)
air = Material('air', DEFAULT_AIR_THICKNESS * u.m, density=air_density)
this_detector = Material(DEFAULT_DETECTOR_MATERIAL,
DEFAULT_DETECTOR_THICKNESS * u.mm)
response = Response(optical_path=[this_material, air], detector=this_detector)
energy = u.Quantity(np.arange(DEFAULT_ENERGY_LOW, DEFAULT_ENERGY_HIGH,
DEFAULT_ENERGY_RESOLUTION), "keV")
x = energy.value
y = response.response(energy)
source = ColumnDataSource(data={"x": x, "y": y})
all_materials = list(roentgen.elements["name"]) + \
list(roentgen.compounds["symbol"])
all_materials.sort()
all_materials = [this_material.lower() for this_material in all_materials]
# Set up the plot
plot = figure(
plot_height=PLOT_HEIGHT,
plot_width=PLOT_WIDTH,
tools=TOOLS,
x_range=[1, 50],
y_range=[0, 1],
)
plot.yaxis.axis_label = "Transmission fraction"
plot.xaxis.axis_label = "Energy [keV]"
plot.line("x", "y", source=source, line_width=3, line_alpha=0.6)
plot.title.text = f"{response}"
plot.add_tools(custom_hover)
# Set up the inputs
ylog_checkbox = CheckboxGroup(labels=["y-log"], active=[0])
# materials in the path
material_input = AutocompleteInput(title="Material (lowercase)", value=DEFAULT_MATERIAL[0])
material_input.completions = all_materials
material_thickness_input = TextInput(title="thickness", value=str(DEFAULT_THICKNESS[0]))
material_density_input = TextInput(title="density", value=str(this_material.density.value))
air_thickness_input = TextInput(title="air path length", value=str(DEFAULT_AIR_THICKNESS))
air_pressure_input = TextInput(title='air pressure', value=str(DEFAULT_AIR_PRESSURE))
air_temperature_input = TextInput(title='air temperature', value=str(DEFAULT_AIR_TEMPERATURE))
detector_material_input = AutocompleteInput(title='Detector', value=DEFAULT_DETECTOR_MATERIAL)
detector_material_input.completions = all_materials
detector_thickness_input = TextInput(title='thickness', value=str(DEFAULT_DETECTOR_THICKNESS))
detector_density_input = TextInput(title='density', value=str(DEFAULT_DETECTOR_DENSITY))
p = Paragraph(text="", width=500)
p.text = f"Running roentgen version {roentgen.__version__}"
columns = [
TableColumn(field="x", title="energy [keV]"),
TableColumn(field="y", title="Percent"),
]
data_table = DataTable(source=source, columns=columns, width=400, height=700)
download_button = Button(label="Download", button_type="success")
download_button.js_on_event(ButtonClick, CustomJS(args=dict(source=source),
code=open(join(dirname(__file__), "download.js")).read()))
def convert_air_pressure(value, current_unit, new_unit):
if current_unit == "atm":
air_pressure = u.Quantity(value * const.atm, "Pa")
elif current_unit == "torr":
air_pressure = u.Quantity(value * const.atm / 760., "Pa")
else:
air_pressure = u.Quantity(value, current_unit)
if new_unit == "atm":
return (air_pressure.to("Pa") / const.atm).value
elif new_unit == "torr":
return (air_pressure.to("Pa") / const.atm).value * 760.0
else:
return air_pressure.to(new_unit)
def update_response(attrname, old, new):
# check whether the input variables have changed and update the response
global response
if not material_input.disabled:
if str(material_input.value).lower() in all_materials:
this_thickness = u.Quantity(material_thickness_input.value,
material_thick_unit.value)
this_density = u.Quantity(material_density_input.value,
material_density_unit.value)
this_material = Material(str(material_input.value).lower(), this_thickness,
density=this_density)
else:
# if material not selected, just make a bogus material with no thickness
this_material = Material('Al', 0 * u.mm)
if not air_pressure_input.disabled:
if air_pressure_unit.value == "atm":
air_pressure = u.Quantity(air_pressure_input.value * const.atm, "Pa")
elif air_pressure_unit.value == "torr":
air_pressure = u.Quantity(air_pressure_input.value * const.atm / 760.,
"Pa")
else:
air_pressure = u.Quantity(air_pressure_input.value,
air_pressure_unit.value)
air_path_length = u.Quantity(air_thickness_input.value,
air_thick_unit.value)
air_temperature = u.Quantity(air_temperature_input.value,
air_temp_unit.value).to("Celsius",
equivalencies=u.temperature())
air_density = density_ideal_gas(air_pressure, air_temperature)
air = Material('air', air_path_length, density=air_density)
else:
# if air is not selected than just add bogus air with no thickness
air = Material('air', 0 * u.mm, density=0 * u.g / u.cm**3)
if not detector_material_input.disabled:
if str(detector_material_input.value).lower() in all_materials:
this_thickness = u.Quantity(detector_thickness_input.value,
detector_thick_unit.value)
this_density = u.Quantity(detector_density_input.value,
detector_density_unit.value)
this_detector = Material(str(detector_material_input.value).lower(), this_thickness,
density=this_density)
else:
this_detector = None
response = Response(optical_path=[this_material, air], detector=this_detector)
def update_data(attrname, old, new):
if plot.x_range.start < DEFAULT_ENERGY_LOW:
energy = u.Quantity(np.arange(DEFAULT_ENERGY_LOW, plot.x_range.end,
DEFAULT_ENERGY_RESOLUTION), "keV")
else:
energy = u.Quantity(np.arange(plot.x_range.start, plot.x_range.end,
DEFAULT_ENERGY_RESOLUTION), "keV")
y = response.response(energy)
plot.title.text = f"{response}"
if plot_checkbox_group.active:
y = np.log10(response.response(energy))
plot.y_range.start = -4
plot.y_range.end = 0
plot.yaxis.axis_label = 'log(Transmission fraction)'
else:
plot.y_range.start = 0
plot.y_range.end = 1
plot.yaxis.axis_label = 'Transmission fraction'
source.data = dict(x=energy, y=y)
def toggle_active(new):
if 0 in new:
material_input.disabled = False
material_thick_unit.disabled = False
material_density_input.disabled = False
if 0 not in new:
material_input.disabled = True
material_thick_unit.disabled = True
material_density_input.disabled = True
if 1 in new:
air_pressure_input.disabled = False
air_thickness_input.disabled = False
air_temperature_input.disabled = False
if 1 not in new:
air_pressure_input.disabled = True
air_thickness_input.disabled = True
air_temperature_input.disabled = True
if 2 in new:
detector_material_input.disabled = False
detector_thickness_input.disabled = False
detector_density_input.disabled = False
if 2 not in new:
detector_material_input.disabled = True
detector_thickness_input.disabled = True
detector_density_input.disabled = True
return new
checkbox_group = CheckboxGroup(labels=["Material", "Air", "Detector"],
active=[0, 1, 2])
checkbox_group.on_click(toggle_active)
def update_button_action():
update_response("update_plot_button", 0, 0)
update_data("update", 0, 0)
update_plot_button = Button(label="Update Plot", button_type="success")
update_plot_button.on_click(update_button_action)
plot.x_range.on_change('start', update_data)
plot.x_range.on_change('end', update_data)
plot_checkbox_group = CheckboxGroup(labels=["ylog"], active=[])
length_units = ["m", "mm", "micron", "inch", "foot", "mil"]
pressure_units = ["Pa", "torr", "atm"]
density_units = ["g / cm ** 3", "kg / m ** 3"]
temperature_units = ["K", "deg_C", "deg_F"]
material_thick_unit = Select(title="unit", value=length_units[2], options=length_units)
def update_mat_thick_units(attr, old, new):
material_thickness_input.value = str(u.Quantity(material_thickness_input.value, old).to(new).value)
material_thick_unit.on_change('value', update_mat_thick_units)
detector_thick_unit = Select(title="unit", value=length_units[1],
options=length_units)
def update_det_thick_units(attr, old, new):
detector_thickness_input.value = str(u.Quantity(detector_thickness_input.value, old).to(new).value)
detector_thick_unit.on_change('value', update_det_thick_units)
air_thick_unit = Select(title="unit", value=length_units[0],
options=length_units)
def update_air_thick_units(attr, old, new):
air_thickness_input.value = str(u.Quantity(air_thickness_input.value, old).to(new).value)
air_thick_unit.on_change('value', update_air_thick_units)
material_density_unit = Select(title="unit", value=density_units[0],
options=density_units)
def update_mat_density_units(attr, old, new):
material_density_input.value = str(u.Quantity(material_density_input.value, old).to(new).value)
material_density_unit.on_change('value', update_mat_density_units)
detector_density_unit = Select(title="unit", value=density_units[0], options=density_units)
def update_det_density_units(attr, old, new):
detector_density_input.value = str(u.Quantity(detector_density_input.value, old).to(new).value)
detector_density_unit.on_change('value', update_det_density_units)
air_pressure_unit = Select(title="unit", value=pressure_units[2],
options=pressure_units)
def update_air_pressure_units(attr, old, new):
air_pressure = convert_air_pressure(air_pressure_input.value, old, new)
air_pressure_input.value = str(air_pressure)
air_pressure_unit.on_change('value', update_air_pressure_units)
air_temp_unit = Select(title="unit", value=temperature_units[1],
options=temperature_units)
def update_air_temp_units(attr, old, new):
air_temperature_input.value = str(u.Quantity(air_temperature_input.value, old).to(new, equivalencies=u.temperature()).value)
air_temp_unit.on_change('value', update_air_temp_units)
def update_material_density(attr, old, new):
# if the material is changed then update the density
material_density_input.value = str(get_density(material_input.value).value)
material_input.on_change('value', update_material_density)
def update_detector_density(attr, old, new):
# if the material is changed then update the density
detector_density_input.value = str(get_density(detector_material_input.value).value)
detector_material_input.on_change('value', update_detector_density)
curdoc().add_root(
layout(
[
[plot],
[checkbox_group, plot_checkbox_group],
[material_input, material_thickness_input, material_thick_unit, material_density_input, material_density_unit],
[air_pressure_input, air_pressure_unit, air_thickness_input, air_thick_unit, air_temperature_input, air_temp_unit],
[detector_material_input, detector_thickness_input, detector_thick_unit, detector_density_input, detector_density_unit],
#[energy_low, energy_high, energy_step],
[download_button, Spacer(), update_plot_button],
[p]
],
sizing_mode="scale_width",
)
)
curdoc().title = "Roentgen"
| 35.979167 | 132 | 0.694847 |
5bc8432e5da9f710dafa40e70878427ea43e89f5 | 1,210 | cs | C# | DragonSpark/Reflection/Members/PropertyValueDelegates.cs | DragonSpark/Framework | 6425e8178240bbabdcbecfe4288c977a29bf53ff | [
"MIT"
] | 10 | 2017-03-08T07:38:44.000Z | 2022-02-26T17:04:37.000Z | DragonSpark/Reflection/Members/PropertyValueDelegates.cs | DragonSpark/Framework | 6425e8178240bbabdcbecfe4288c977a29bf53ff | [
"MIT"
] | 2 | 2017-11-04T09:26:33.000Z | 2019-11-06T16:57:19.000Z | DragonSpark/Reflection/Members/PropertyValueDelegates.cs | DragonSpark/Framework | 6425e8178240bbabdcbecfe4288c977a29bf53ff | [
"MIT"
] | 1 | 2017-10-21T12:58:29.000Z | 2017-10-21T12:58:29.000Z | using DragonSpark.Compose;
using DragonSpark.Model.Selection.Stores;
using System;
using System.Reflection;
namespace DragonSpark.Reflection.Members;
public sealed class PropertyValueDelegates : ReferenceValueStore<PropertyInfo, Func<object, object>>,
IPropertyValueDelegate
{
public static PropertyValueDelegates Default { get; } = new();
PropertyValueDelegates() : base(PropertyValueDelegate.Default.Then().Stores().New().Get) {}
}
public sealed class PropertyValueDelegates<T> : ReferenceValueStore<PropertyInfo, Func<object, T>>,
IPropertyValueDelegate<T>
{
public static PropertyValueDelegates<T> Default { get; } = new();
PropertyValueDelegates() : base(PropertyValueDelegate<T>.Default.Then().Stores().New().Get) {}
}
public sealed class PropertyValueDelegates<T, TValue> : ReferenceValueTable<PropertyInfo, Func<T, TValue>>,
IPropertyValueDelegate<T, TValue>
{
public static PropertyValueDelegates<T, TValue> Default { get; } = new();
PropertyValueDelegates() : base(PropertyValueDelegate<T, TValue>.Default.Then().Stores().New().Get) {}
} | 40.333333 | 107 | 0.681818 |
7bb9a8c701f85ed51118f970177a080b6754823f | 439 | asm | Assembly | programs/oeis/117/A117908.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | 1 | 2021-03-15T11:38:20.000Z | 2021-03-15T11:38:20.000Z | programs/oeis/117/A117908.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | null | null | null | programs/oeis/117/A117908.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | null | null | null | ; A117908: Chequered (or checkered) triangle for odd prime p=3.
; 1,1,1,0,0,0,1,1,0,1,1,1,0,1,1,0,0,0,0,0,0,1,1,0,1,1,0,1,1,1,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,1,0,1,1,1,0,1,1,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1
cal $0,75362 ; Triangle read by rows with the n-th row containing the first n multiples of n.
gcd $0,3
mov $1,$0
mov $2,$0
add $2,$0
sub $1,$2
add $1,3
div $1,2
| 36.583333 | 211 | 0.589977 |
e907b4c7448903216108aba2c7659599635609d4 | 7,330 | cc | C++ | src/ash/wm/ash_native_cursor_manager_unittest.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | src/ash/wm/ash_native_cursor_manager_unittest.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | null | null | null | src/ash/wm/ash_native_cursor_manager_unittest.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.000Z | // Copyright (c) 2012 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 "ash/wm/ash_native_cursor_manager.h"
#include "ash/shell.h"
#include "ash/test/ash_test_base.h"
#include "ash/test/cursor_manager_test_api.h"
#include "ash/wm/image_cursors.h"
#include "ui/aura/root_window.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/test/test_windows.h"
#include "ui/aura/window.h"
#include "ui/gfx/screen.h"
using views::corewm::CursorManager;
namespace ash {
namespace test {
namespace {
// A delegate for recording a mouse event location.
class MouseEventLocationDelegate : public aura::test::TestWindowDelegate {
public:
MouseEventLocationDelegate() {}
virtual ~MouseEventLocationDelegate() {}
gfx::Point GetMouseEventLocationAndReset() {
gfx::Point p = mouse_event_location_;
mouse_event_location_.SetPoint(-100, -100);
return p;
}
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
mouse_event_location_ = event->location();
event->SetHandled();
}
private:
gfx::Point mouse_event_location_;
DISALLOW_COPY_AND_ASSIGN(MouseEventLocationDelegate);
};
} // namespace
typedef test::AshTestBase AshNativeCursorManagerTest;
TEST_F(AshNativeCursorManagerTest, LockCursor) {
CursorManager* cursor_manager = Shell::GetInstance()->cursor_manager();
CursorManagerTestApi test_api(cursor_manager);
gfx::Display display(0);
#if defined(OS_WIN)
cursor_manager->SetCursorResourceModule(L"ash_unittests.exe");
#endif
cursor_manager->SetCursor(ui::kCursorCopy);
EXPECT_EQ(ui::kCursorCopy, test_api.GetCurrentCursor().native_type());
display.set_device_scale_factor(2.0f);
display.set_rotation(gfx::Display::ROTATE_90);
cursor_manager->SetDisplay(display);
EXPECT_EQ(2.0f, test_api.GetDisplay().device_scale_factor());
EXPECT_EQ(gfx::Display::ROTATE_90, test_api.GetDisplay().rotation());
EXPECT_TRUE(test_api.GetCurrentCursor().platform());
cursor_manager->LockCursor();
EXPECT_TRUE(cursor_manager->is_cursor_locked());
// Cursor type does not change while cursor is locked.
cursor_manager->SetCursor(ui::kCursorPointer);
EXPECT_EQ(ui::kCursorCopy, test_api.GetCurrentCursor().native_type());
// Device scale factor and rotation do change even while cursor is locked.
display.set_device_scale_factor(1.0f);
display.set_rotation(gfx::Display::ROTATE_180);
cursor_manager->SetDisplay(display);
EXPECT_EQ(1.0f, test_api.GetDisplay().device_scale_factor());
EXPECT_EQ(gfx::Display::ROTATE_180, test_api.GetDisplay().rotation());
cursor_manager->UnlockCursor();
EXPECT_FALSE(cursor_manager->is_cursor_locked());
// Cursor type changes to the one specified while cursor is locked.
EXPECT_EQ(ui::kCursorPointer, test_api.GetCurrentCursor().native_type());
EXPECT_EQ(1.0f, test_api.GetDisplay().device_scale_factor());
EXPECT_TRUE(test_api.GetCurrentCursor().platform());
}
TEST_F(AshNativeCursorManagerTest, SetCursor) {
CursorManager* cursor_manager = Shell::GetInstance()->cursor_manager();
CursorManagerTestApi test_api(cursor_manager);
#if defined(OS_WIN)
cursor_manager->SetCursorResourceModule(L"ash_unittests.exe");
#endif
cursor_manager->SetCursor(ui::kCursorCopy);
EXPECT_EQ(ui::kCursorCopy, test_api.GetCurrentCursor().native_type());
EXPECT_TRUE(test_api.GetCurrentCursor().platform());
cursor_manager->SetCursor(ui::kCursorPointer);
EXPECT_EQ(ui::kCursorPointer, test_api.GetCurrentCursor().native_type());
EXPECT_TRUE(test_api.GetCurrentCursor().platform());
}
TEST_F(AshNativeCursorManagerTest, SetDeviceScaleFactorAndRotation) {
CursorManager* cursor_manager = Shell::GetInstance()->cursor_manager();
CursorManagerTestApi test_api(cursor_manager);
gfx::Display display(0);
display.set_device_scale_factor(2.0f);
cursor_manager->SetDisplay(display);
EXPECT_EQ(2.0f, test_api.GetDisplay().device_scale_factor());
EXPECT_EQ(gfx::Display::ROTATE_0, test_api.GetDisplay().rotation());
display.set_device_scale_factor(1.0f);
display.set_rotation(gfx::Display::ROTATE_270);
cursor_manager->SetDisplay(display);
EXPECT_EQ(1.0f, test_api.GetDisplay().device_scale_factor());
EXPECT_EQ(gfx::Display::ROTATE_270, test_api.GetDisplay().rotation());
}
#if defined(OS_WIN)
// Temporarily disabled for windows. See crbug.com/112222.
#define MAYBE_DisabledMouseEventsLocation DISABLED_DisabledMouseEventsLocation
#else
#define MAYBE_DisabledMouseEventsLocation DisabledMouseEventsLocation
#endif // defined(OS_WIN)
// Verifies that RootWindow generates a mouse event located outside of a window
// when mouse events are disabled.
TEST_F(AshNativeCursorManagerTest, MAYBE_DisabledMouseEventsLocation) {
scoped_ptr<MouseEventLocationDelegate> delegate(
new MouseEventLocationDelegate());
const int kWindowWidth = 123;
const int kWindowHeight = 45;
gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight);
scoped_ptr<aura::Window> window(aura::test::CreateTestWindowWithDelegate(
delegate.get(), 1, bounds, Shell::GetInstance()->GetPrimaryRootWindow()));
CursorManager* cursor_manager = Shell::GetInstance()->cursor_manager();
cursor_manager->EnableMouseEvents();
// Send a mouse event to window.
gfx::Point point(101, 201);
gfx::Point local_point;
ui::MouseEvent event(ui::ET_MOUSE_MOVED, point, point, 0);
aura::RootWindow* root_window = window->GetRootWindow();
root_window->AsRootWindowHostDelegate()->OnHostMouseEvent(&event);
// Location was in window.
local_point = delegate->GetMouseEventLocationAndReset();
aura::Window::ConvertPointToTarget(window.get(), root_window, &local_point);
EXPECT_TRUE(window->bounds().Contains(local_point));
// Location is now out of window.
cursor_manager->DisableMouseEvents();
RunAllPendingInMessageLoop();
local_point = delegate->GetMouseEventLocationAndReset();
aura::Window::ConvertPointToTarget(window.get(), root_window, &local_point);
EXPECT_FALSE(window->bounds().Contains(local_point));
EXPECT_FALSE(window->bounds().Contains(
gfx::Screen::GetScreenFor(window.get())->GetCursorScreenPoint()));
// Location is back in window.
cursor_manager->EnableMouseEvents();
RunAllPendingInMessageLoop();
local_point = delegate->GetMouseEventLocationAndReset();
aura::Window::ConvertPointToTarget(window.get(), root_window, &local_point);
EXPECT_TRUE(window->bounds().Contains(local_point));
}
#if defined(OS_WIN)
// Disable on Win because RootWindow::MoveCursorTo is not implemented.
#define MAYBE_DisabledQueryMouseLocation DISABLED_DisabledQueryMouseLocation
#else
#define MAYBE_DisabledQueryMouseLocation DisabledQueryMouseLocation
#endif // defined(OS_WIN)
TEST_F(AshNativeCursorManagerTest, MAYBE_DisabledQueryMouseLocation) {
aura::RootWindow* root_window = Shell::GetInstance()->GetPrimaryRootWindow();
root_window->MoveCursorTo(gfx::Point(10, 10));
gfx::Point mouse_location;
EXPECT_TRUE(root_window->QueryMouseLocationForTest(&mouse_location));
EXPECT_EQ("10,10", mouse_location.ToString());
Shell::GetInstance()->cursor_manager()->DisableMouseEvents();
EXPECT_FALSE(root_window->QueryMouseLocationForTest(&mouse_location));
EXPECT_EQ("0,0", mouse_location.ToString());
}
} // namespace test
} // namespace ash
| 38.578947 | 80 | 0.776262 |
ad42f5c8521f2bee61190eaf58cde694072afbea | 8,137 | swift | Swift | TransitBar/TransitBar/View Controllers/NewLineViewController.swift | MrAdamBoyd/Muni-Menu-Bar | 95202a3c91e4c0f97b03afb91a112344e3f9813f | [
"MIT"
] | 5 | 2017-01-19T14:06:22.000Z | 2022-03-04T02:43:30.000Z | TransitBar/TransitBar/View Controllers/NewLineViewController.swift | MrAdamBoyd/MacTransit | 95202a3c91e4c0f97b03afb91a112344e3f9813f | [
"MIT"
] | 1 | 2017-01-16T22:22:21.000Z | 2017-01-19T17:18:41.000Z | TransitBar/TransitBar/View Controllers/NewLineViewController.swift | MrAdamBoyd/MacTransit | 95202a3c91e4c0f97b03afb91a112344e3f9813f | [
"MIT"
] | null | null | null | //
// NewLineViewController.swift
// TransitBar
//
// Created by Adam Boyd on 2016-11-19.
// Copyright © 2016 adam. All rights reserved.
//
import Cocoa
import SwiftBus
protocol NewStopDelegate: class {
func newStopControllerDidAdd(newEntry: TransitEntry)
}
class NewLineViewController: NSViewController {
@IBOutlet weak var agencyPopUpButton: NSPopUpButton!
@IBOutlet weak var routePopUpButton: NSPopUpButton!
@IBOutlet weak var directionPopUpButton: NSPopUpButton!
@IBOutlet weak var stopPopUpButton: NSPopUpButton!
@IBOutlet weak var addStopButton: NSButton!
@IBOutlet weak var allTimesRadioButton: NSButton!
@IBOutlet weak var startTimeDatePicker: NSDatePicker!
@IBOutlet weak var endTimeDatePicker: NSDatePicker!
@IBOutlet weak var neverRadioButton: NSButton!
@IBOutlet weak var betweenTimesRadioButton: NSButton!
weak var delegate: NewStopDelegate?
var agencies: [TransitAgency] = []
var routes: [TransitRoute] = []
var directions: [String] = []
var stops: [TransitStop] = []
var selectedRoute: TransitRoute?
var selectedStop: TransitStop?
override func viewDidLoad() {
super.viewDidLoad()
self.agencyPopUpButton.action = #selector(self.agencySelectedAction)
self.routePopUpButton.action = #selector(self.routeSelectedAction)
self.directionPopUpButton.action = #selector(self.directionSelectedAction)
self.stopPopUpButton.action = #selector(self.stopSelectedAction)
self.agencyPopUpButton.menu?.autoenablesItems = true
self.routePopUpButton.menu?.autoenablesItems = true
self.directionPopUpButton.menu?.autoenablesItems = true
self.stopPopUpButton.menu?.autoenablesItems = true
//Get the agencies when the window is opened
SwiftBus.shared.transitAgencies() { result in
DispatchQueue.main.async {
switch result {
case let .success(agencies):
var inOrderAgencies = Array(agencies.values)
//Ordering the routes alphabetically
inOrderAgencies = inOrderAgencies.sorted {
$0.agencyTitle.localizedCaseInsensitiveCompare($1.agencyTitle) == ComparisonResult.orderedAscending
}
//Placeholder
self.agencyPopUpButton.addItem(withTitle: "--")
self.agencies = inOrderAgencies
self.agencyPopUpButton.addItems(withTitles: inOrderAgencies.map({ $0.agencyTitle }))
case let .error(error):
self.agencyPopUpButton.addItem(withTitle: "Error: \(error.localizedDescription)")
}
}
}
}
@IBAction func radioButtonTapped(_ sender: Any) {
print("Radio button tapped")
let enabled = self.betweenTimesRadioButton.state == .on
self.startTimeDatePicker.isEnabled = enabled
self.endTimeDatePicker.isEnabled = enabled
}
// MARK: - Actions from the popup buttons
@objc
func agencySelectedAction() {
self.routePopUpButton.removeAllItems()
self.routes = []
self.selectedRoute = nil
self.directionPopUpButton.removeAllItems()
self.directions = []
self.stopPopUpButton.removeAllItems()
self.stops = []
self.addStopButton.isEnabled = false
guard self.agencyPopUpButton.indexOfSelectedItem != 0 else { return }
let agency = self.agencies[self.agencyPopUpButton.indexOfSelectedItem]
SwiftBus.shared.routes(forAgency: agency) { result in
DispatchQueue.main.async {
switch result {
case let .success(routes):
var inOrderRoutes = Array(routes.values)
//Ordering the routes alphabetically
inOrderRoutes = inOrderRoutes.sorted {
$0.routeTitle.localizedCaseInsensitiveCompare($1.routeTitle) == ComparisonResult.orderedAscending
}
self.routePopUpButton.addItem(withTitle: "--")
self.routes = inOrderRoutes
self.routePopUpButton.addItems(withTitles: inOrderRoutes.map({ $0.routeTitle }))
case let .error(error):
self.agencyPopUpButton.addItem(withTitle: "Error: \(error.localizedDescription)")
}
}
}
}
@objc
func routeSelectedAction() {
self.selectedRoute = nil
self.directionPopUpButton.removeAllItems()
self.directions = []
self.stopPopUpButton.removeAllItems()
self.stops = []
self.addStopButton.isEnabled = false
guard self.routePopUpButton.indexOfSelectedItem != 0 else { return }
let selectedRoute = self.routes[self.routePopUpButton.indexOfSelectedItem - 1]
SwiftBus.shared.configuration(forRoute: selectedRoute) { result in
DispatchQueue.main.async {
switch result {
case let .success(route):
self.directionPopUpButton.addItem(withTitle: "--")
self.selectedRoute = route
//The keys to this array are all possible directions
self.directionPopUpButton.addItems(withTitles: Array(route.stops.keys))
case let .error(error):
self.agencyPopUpButton.addItem(withTitle: "Error: \(error.localizedDescription)")
}
}
}
}
/// User selected a direction for the direction popup
@objc
func directionSelectedAction() {
self.stopPopUpButton.removeAllItems()
self.stops = []
self.addStopButton.isEnabled = false
//Don't do anything if the placeholder item is selected
guard self.directionPopUpButton.indexOfSelectedItem != 0 else { return }
if let title = self.directionPopUpButton.selectedItem?.title, let stops = self.selectedRoute?.stops[title] {
DispatchQueue.main.async { [unowned self] in
//Placeholder
self.stopPopUpButton.addItem(withTitle: "--")
self.stops = stops
//Getting the stops for that direction. The direction is the key to the dictionary for the stops on that route
self.stopPopUpButton.addItems(withTitles: stops.map({ $0.stopTitle }))
}
}
}
@objc
func stopSelectedAction() {
//Only enable if placeholder item isn't there
guard self.stopPopUpButton.indexOfSelectedItem != 0 else { return }
self.addStopButton.isEnabled = true
self.selectedStop = self.stops[self.stopPopUpButton.indexOfSelectedItem - 1]
}
@IBAction func addNewStop(_ sender: Any) {
guard let stop = self.selectedStop else { return }
var times: (Date?, Date?)? = nil
if self.betweenTimesRadioButton.state == .on {
//Only show the times between two times
//Order the dates so that the 0th date is always earlier than the second one
if self.startTimeDatePicker.dateValue < self.endTimeDatePicker.dateValue {
times = (self.startTimeDatePicker.dateValue, self.endTimeDatePicker.dateValue)
} else {
times = (self.endTimeDatePicker.dateValue, self.startTimeDatePicker.dateValue)
}
} else if self.neverRadioButton.state == .on {
//The tuple exists but has nil values for never being shown
times = (nil, nil)
}
let entry = TransitEntry(stop: stop, times: times)
self.delegate?.newStopControllerDidAdd(newEntry: entry)
self.view.window?.close()
}
}
| 39.692683 | 126 | 0.604645 |
0f6a0adee3d4a15e0b0316d58f72cca03b3eafb9 | 3,388 | asm | Assembly | src/LKS/old/Zorder.asm | Kannagi/LKS | 363ccbfbe93a78e227349967053075ba67f4e50c | [
"MIT"
] | 6 | 2019-04-18T12:08:23.000Z | 2021-07-07T08:07:28.000Z | src/LKS/old/Zorder.asm | Kannagi/LKS | 363ccbfbe93a78e227349967053075ba67f4e50c | [
"MIT"
] | null | null | null | src/LKS/old/Zorder.asm | Kannagi/LKS | 363ccbfbe93a78e227349967053075ba67f4e50c | [
"MIT"
] | null | null | null |
.MACRO LKS_ZORDER12
ldy #0
lda LKS_OAMZ.y+(2*\1)
.if \1 != 0
cmp LKS_OAMZ.y+0
bpl +
iny
+:
.if \1 > 0
bne +
iny
+:
.endif
.endif
.if \1 != 2
cmp LKS_OAMZ.y+2
bpl +
iny
+:
.if \1 > 2
bne +
iny
+:
.endif
.endif
.if \1 != 4
cmp LKS_OAMZ.y+4
bpl +
iny
+:
.if \1 > 4
bne +
iny
+:
.endif
.endif
.if \1 != 6
cmp LKS_OAMZ.y+6
bpl +
iny
+:
.if \1 > 6
bne +
iny
+:
.endif
.endif
.if \1 != 8
cmp LKS_OAMZ.y+8
bpl +
iny
+:
.if \1 > 8
bne +
iny
+:
.endif
.endif
.if \1 != 10
cmp LKS_OAMZ.y+10
bpl +
iny
+:
.if \1 > 10
bne +
iny
+:
.endif
.endif
.if \1 != 12
cmp LKS_OAMZ.y+12
bpl +
iny
+:
.if \1 > 12
bne +
iny
+:
.endif
.endif
.if \1 != 14
cmp LKS_OAMZ.y+14
bpl +
iny
+:
.if \1 > 14
bne +
iny
+:
.endif
.endif
.if \1 != 16
cmp LKS_OAMZ.y+16
bpl +
iny
+:
.if \1 > 16
bne +
iny
+:
.endif
.endif
.if \1 != 18
cmp LKS_OAMZ.y+18
bpl +
iny
+:
.if \1 > 18
bne +
iny
+:
.endif
.endif
.if \1 != 20
cmp LKS_OAMZ.y+20
bpl +
iny
+:
.if \1 > 20
bne +
iny
+:
.endif
.endif
.if \1 != 22
cmp LKS_OAMZ.y+22
bpl +
iny
+:
.if \1 > 22
bne +
iny
+:
.endif
.endif
tya
asl
asl
asl
asl
sta LKS_SPRITE.OAM+(2*\1)
.ENDM
.MACRO zorder_init
ldx LKS_OAM+$10
lda s_perso+_y,x
sta MEM_TEMP
ldx LKS_OAM+$10+2
lda s_perso+_y,x
sta MEM_TEMP+2
ldx LKS_OAM+$10+4
lda s_perso+_y,x
sta MEM_TEMP+4
ldx LKS_OAM+$10+6
lda s_perso+_y,x
sta MEM_TEMP+6
ldx LKS_OAM+$10+8
lda s_perso+_y,x
sta MEM_TEMP+8
ldx LKS_OAM+$10+10
lda s_perso+_y,x
sta MEM_TEMP+10
.if \1 == 0
ldx LKS_OAM+$10+12
lda s_perso+_y,x
sta MEM_TEMP+12
ldx LKS_OAM+$10+14
lda s_perso+_y,x
sta MEM_TEMP+14
ldx LKS_OAM+$10+16
lda s_perso+_y,x
sta MEM_TEMP+16
ldx LKS_OAM+$10+18
lda s_perso+_y,x
sta MEM_TEMP+18
ldx LKS_OAM+$10+20
lda s_perso+_y,x
sta MEM_TEMP+20
ldx LKS_OAM+$10+22
lda s_perso+_y,x
sta MEM_TEMP+22
.endif
.ENDM
Z_order_pnj:
lda s_map+_mode
cmp #0
beq +
rts
+:
phy
rep #$20
zorder_init 0
zorder 0
zorder 2
zorder 4
zorder 6
zorder 8
zorder 10
zorder 12
zorder 14
zorder 16
zorder 18
zorder 20
zorder 22
sep #$20
ply
rts
.MACRO zorder2
ldy #0
lda MEM_TEMP+\1
.if \1 != 0
cmp MEM_TEMP+0
bpl +
iny
+:
.if \1 > 0
bne +
iny
+:
.endif
.endif
.if \1 != 2
cmp MEM_TEMP+2
bpl +
iny
+:
.if \1 > 2
bne +
iny
+:
.endif
.endif
.if \1 != 4
cmp MEM_TEMP+4
bpl +
iny
+:
.if \1 > 4
bne +
iny
+:
.endif
.endif
.if \1 != 6
cmp MEM_TEMP+6
bpl +
iny
+:
.if \1 > 6
bne +
iny
+:
.endif
.endif
.if \1 != 8
cmp MEM_TEMP+8
bpl +
iny
+:
.if \1 > 8
bne +
iny
+:
.endif
.endif
.if \1 != 10
cmp MEM_TEMP+10
bpl +
iny
+:
.if \1 > 10
bne +
iny
+:
.endif
.endif
lda MEM_TEMP
asl
asl
asl
asl
asl
ldx LKS_OAM+$10+\1
clc
adc #$100
sta s_perso+_oam,x
.ENDM
Z_order_ennemi:
lda s_map+_mode
cmp #1
beq +
rts
+:
phy
rep #$20
zorder_init 1
zorder2 0
zorder2 2
zorder2 4
zorder2 6
zorder2 8
zorder2 10
sep #$20
ply
rts
| 8.512563 | 26 | 0.510331 |
3dfed0b62a15f87b68151de33aba91db2a73d9fb | 6,443 | dart | Dart | lib/ui/widgets/full_creen_image.dart | kiwsan/nichacgm48 | cb588a0d9f50c70f0a229c94d95d46a78978753a | [
"MIT"
] | 2 | 2020-05-09T07:14:14.000Z | 2020-05-09T17:52:18.000Z | lib/ui/widgets/full_creen_image.dart | kiwsan/nichacgm48 | cb588a0d9f50c70f0a229c94d95d46a78978753a | [
"MIT"
] | 1 | 2020-01-10T04:47:57.000Z | 2020-01-10T04:47:57.000Z | lib/ui/widgets/full_creen_image.dart | kiwsan/nichacgm48 | cb588a0d9f50c70f0a229c94d95d46a78978753a | [
"MIT"
] | 1 | 2020-01-10T04:41:42.000Z | 2020-01-10T04:41:42.000Z | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:nichacgm48/utils/read_more_text.dart';
import 'package:nichacgm48/models/instagram_post_model.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:time_formatter/time_formatter.dart';
class FullScreenImage extends StatefulWidget {
final EdgeOwnerToTimelineMedia posts;
final Widget loadingChild;
final Decoration backgroundDecoration;
final int initialIndex;
final PageController pageController;
final Axis scrollDirection;
final fontSize;
FullScreenImage(
{this.loadingChild,
this.backgroundDecoration,
this.initialIndex,
@required this.posts,
this.scrollDirection = Axis.horizontal,
this.fontSize})
: pageController = PageController(initialPage: initialIndex);
@override
_FullScreenImageScreen createState() => _FullScreenImageScreen();
}
class _FullScreenImageScreen extends State<FullScreenImage> {
int currentIndex;
@override
void initState() {
currentIndex = widget.initialIndex;
super.initState();
}
void onPageChanged(int index) {
setState(() {
currentIndex = index;
});
}
@override
Widget build(BuildContext context) {
String publishedOn = formatTime(
widget.posts.edges[currentIndex].node.takenAtTimestamp * 1000);
var caption = widget
.posts.edges[currentIndex].node.edgeMediaToCaption.edges[0].node.text;
return Scaffold(
body: Container(
decoration: widget.backgroundDecoration,
constraints: BoxConstraints.expand(
height: MediaQuery.of(context).size.height,
),
child: Stack(
alignment: Alignment.bottomLeft,
children: <Widget>[
PhotoViewGallery.builder(
scrollPhysics: BouncingScrollPhysics(),
builder: _post,
itemCount: widget.posts.edges.length,
// ignore: deprecated_member_use
loadingChild: widget.loadingChild,
backgroundDecoration: widget.backgroundDecoration,
pageController: widget.pageController,
onPageChanged: onPageChanged,
scrollDirection: widget.scrollDirection,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Container(
color: Colors.black54,
padding: EdgeInsets.all(ScreenUtil().setWidth(25)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Image.asset(
"assets/icons/instagram_icon.png",
width: ScreenUtil().setWidth(40),
height: ScreenUtil().setHeight(40),
),
Padding(
padding: EdgeInsets.only(
left: ScreenUtil().setWidth(15)),
child: Text(
"Nicha CGM48 on Instagram [$publishedOn]",
style: TextStyle(
color: Colors.white,
fontSize: widget.fontSize,
fontWeight: FontWeight.normal),
),
),
],
),
SizedBox(
height: ScreenUtil().setHeight(0.2),
),
ReadMoreText(
caption,
//Write text on image
style: TextStyle(
color: Colors.white,
fontSize: widget.fontSize,
fontWeight: FontWeight.normal),
trimLength: 150,
colorClickableText: Colors.amber,
)
],
),
)
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: EdgeInsets.only(
top: ScreenUtil().setWidth(70),
left: ScreenUtil().setWidth(10)),
child: IconButton(
icon: Icon(
Icons.arrow_back,
size: ScreenUtil().setWidth(70),
color: Colors.white,
),
onPressed: () {
Navigator.pop(context);
},
),
),
Container(
padding:
EdgeInsets.only(top: ScreenUtil().setWidth(70)),
child: IconButton(
icon: Icon(
Icons.more_vert,
size: ScreenUtil().setWidth(80),
color: Colors.white,
),
onPressed: () {},
),
)
])
]),
],
),
),
);
}
PhotoViewGalleryPageOptions _post(BuildContext context, int index) {
final post = widget.posts.edges[index];
return PhotoViewGalleryPageOptions(
imageProvider: CachedNetworkImageProvider(post.node.displayUrl),
heroAttributes: PhotoViewHeroAttributes(tag: "tag$index"),
);
}
}
| 37.028736 | 78 | 0.489679 |
96cb1907850a30b47e8f74355f7227b9024ded40 | 61,746 | asm | Assembly | Library/User/Gen/genView.asm | steakknife/pcgeos | 95edd7fad36df400aba9bab1d56e154fc126044a | [
"Apache-2.0"
] | 3 | 2020-10-13T21:11:02.000Z | 2021-04-19T16:22:58.000Z | Library/User/Gen/genView.asm | steakknife/pcgeos | 95edd7fad36df400aba9bab1d56e154fc126044a | [
"Apache-2.0"
] | null | null | null | Library/User/Gen/genView.asm | steakknife/pcgeos | 95edd7fad36df400aba9bab1d56e154fc126044a | [
"Apache-2.0"
] | null | null | null | COMMENT @-----------------------------------------------------------------------
Copyright (c) GeoWorks 1988 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: UserInterface/Gen
FILE: genView.asm
ROUTINES:
Name Description
---- -----------
GLB GenViewClass View object
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 2/89 Initial version
Chris 6/89 Changed to a view
DESCRIPTION:
This file contains routines to implement the View class
$Id: genView.asm,v 1.1 97/04/07 11:44:42 newdeal Exp $
-------------------------------------------------------------------------------@
; see documentation in /staff/pcgeos/Library/User/Doc/GenView.doc
UserClassStructures segment resource
; Declare class table
GenViewClass
UserClassStructures ends
Build segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewInitialize
DESCRIPTION: Initialize object
PASS:
*ds:si - instance data
es - segment of GenViewClass
ax - MSG_META_INITIALIZE
RETURN: nothing
ALLOWED_TO_DESTROY:
ax, cx, dx, bp
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
NOTE: THIS ROUTINE ASSUME THAT THE OBJECT HAS JUST BEEN CREATED
AND HAS INSTANCE DATA OF ALL 0'S FOR THE VIS PORTION
REVISION HISTORY:
Name Date Description
---- ---- -----------
Doug 10/91 Initial version
------------------------------------------------------------------------------@
GenViewInitialize method static GenViewClass, MSG_META_INITIALIZE
mov di, offset GenViewClass
call ObjCallSuperNoLock
;
; Initialize to match .cpp and .esp defaults
;
mov di, ds:[si]
add di, ds:[di].Gen_offset
or ds:[di].GI_attrs, mask GA_TARGETABLE
or ds:[di].GVI_attrs, mask GVA_FOCUSABLE
mov ds:[di].GVI_color.CQ_redOrIndex, C_WHITE
mov ax, 1
mov ds:[di].GVI_scaleFactor.PF_x.WWF_int, ax
mov ds:[di].GVI_scaleFactor.PF_y.WWF_int, ax
mov ds:[di].GVI_increment.PD_x.low, 20
mov ds:[di].GVI_increment.PD_y.low, 15
ret
GenViewInitialize endm
COMMENT @----------------------------------------------------------------------
METHOD: GenViewBuild -- MSG_META_RESOLVE_VARIANT_SUPERCLASS for GenViewClass
DESCRIPTION: Return the correct specific class for an object
PASS:
*ds:si - instance data (for object in a GenXXXX class)
es - segment of GenViewClass
ax - MSG_META_RESOLVE_VARIANT_SUPERCLASS
cx - ?
dx - ?
bp - ?
RETURN:
carry - ?
ax - ?
cx:dx - class for specific UI part of object (cx = 0 for no build)
bp - ?
ALLOWED TO DESTROY:
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 2/89 Initial version
------------------------------------------------------------------------------@
GenViewBuild method GenViewClass, MSG_META_RESOLVE_VARIANT_SUPERCLASS
mov ax, SPIR_BUILD_VIEW
GOTO GenQueryUICallSpecificUI
GenViewBuild endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
GenViewSpecBuild
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: RESPONDER ONLY. Prevents horizontal scrollbar.
CALLED BY: MSG_SPEC_BUILD
PASS: *ds:si = GenViewClass object
ds:di = GenViewClass instance data
ds:bx = GenViewClass object (same as *ds:si)
es = segment of GenViewClass
ax = message #
bp = SpecBuildFlags
RETURN: nothing
DESTROYED: ax, cx, dx, bp
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
JimG 7/ 5/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
COMMENT @----------------------------------------------------------------------
METHOD: GenViewSetAttrs
DESCRIPTION: Set view attributes
NOTE: Attributes may ONLY be changed while the object is
not USABLE.
PASS:
*ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SET_ATTRS
cx - bits to set
dx - bits to clear
bp - update mode for changing GVA_NO_WIN_FRAME or GVA_VIEW_
FOLLOWS_CONTENT_GEOMETRY (VUM_MANUAL allowed here...)
RETURN:
Nothing
ax, cx, dx, bp -- trashed
ALLOWED TO DESTROY:
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Doug 12/89 Initial version
------------------------------------------------------------------------------@
GenViewSetAttrs method GenViewClass, MSG_GEN_VIEW_SET_ATTRS
; figure out what *really* needs to change
mov ax, ds:[di].GVI_attrs
call ComputeMinimalBitsToSetReset
jc done
mov ds:[di].GVI_attrs, ax
call ObjMarkDirty ;mark stuff as dirty
test bx, mask GVA_NO_WIN_FRAME or \
mask GVA_VIEW_FOLLOWS_CONTENT_GEOMETRY
jz noGeometryChange
call FinishAttrChange ;invalidate things...
noGeometryChange:
mov ax, MSG_GEN_VIEW_SET_ATTRS
call GenViewOnlyCallIfSpecBuilt
done:
EC < Destroy ax, cx, dx, bp ;trash things >
ret
GenViewSetAttrs endm
COMMENT @----------------------------------------------------------------------
FUNCTION: ComputeMinimalBitsToSetReset
DESCRIPTION: ...
CALLED BY: INTERNAL
PASS:
ax - current value
cx - bits to set
dx - bits to clear
RETURN:
ax - new value
bx - bits changed
cx - minimal bits to set
dx - minimal bits to clear
carry - set if nothing to do
DESTROYED:
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 8/18/92 Initial version
------------------------------------------------------------------------------@
ComputeMinimalBitsToSetReset proc far
mov bx, ax ;bx = old
not dx
and ax, dx
or ax, cx
cmp ax, bx
jz nothingToDo ;no changes!
; ax = new attributes
xor bx, ax ;bx = changed
; set = changed & new
mov cx, bx
and cx, ax ;cx = bits to set
; reset = changed & !new
mov dx, bx
not ax
and dx, ax ;dx = bits to reset
not ax
clc
ret
nothingToDo:
clr bx
clr cx
clr dx
stc
ret
ComputeMinimalBitsToSetReset endp
COMMENT @----------------------------------------------------------------------
METHOD: GenViewSetDimensionAttrs
DESCRIPTION: Set view dimension attributes. Use this method while the view
is usable AT YOUR OWN RISK.
PASS:
*ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SET_ATTRS
cl - horizAttributes to set
ch - horizAttributes to reset
dl - vertAttributes to set
dh - vertAttributes to reset
bp - update mode (VUM_MANUAL allowed here...)
RETURN:
Nothing
ax, cx, dx, bp -- trashed
ALLOWED TO DESTROY:
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 5/90 Initial version
------------------------------------------------------------------------------@
GenViewSetDimensionAttrs method GenViewClass, \
MSG_GEN_VIEW_SET_DIMENSION_ATTRS
EC < test cl, mask GVDA_SPLITTABLE ;too late now, buddy...>
EC < ERROR_NZ UI_CANT_MAKE_SPLITTABLE_VIA_MESSAGE >
EC < test dl, mask GVDA_SPLITTABLE ;too late now, buddy...>
EC < ERROR_NZ UI_CANT_MAKE_SPLITTABLE_VIA_MESSAGE >
;
; For Responder, we prevent the horzintal scrollbar from ever
; appearing. Thus, we turn on this attribute in MSG_SPEC_BUILD
; (above) and we never allow it to be reset.
;
push bp
clr bp ;flag
push dx ;save vertical bits
clr ax
mov al, ds:[di].GVI_horizAttrs ;ax = current value
clr dx
mov dl, ch ;dx = bits to clear
clr ch ;cx = bits to set
call ComputeMinimalBitsToSetReset
jc noChangeH
mov ds:[di].GVI_horizAttrs, al
inc bp ;set change flag
noChangeH:
mov ch, dl
pop dx
push cx
clr ax
mov al, ds:[di].GVI_vertAttrs ;ax = current value
clr cx
mov cl, dl ;cx = bits to set
mov dl, dh
clr dh ;dx = bits to clear
call ComputeMinimalBitsToSetReset
jc noChangeV
mov ds:[di].GVI_vertAttrs, al
inc bp ;set change flag
noChangeV:
mov dh, dl
mov dl, cl
pop cx
tst bp
pop bp
jnz 10$
ret
10$:
call ObjMarkDirty
call VisCheckIfSpecBuilt ;if not visually built
jnc FinishAttrChange ;then branch
mov ax, MSG_GEN_VIEW_SET_DIMENSION_ATTRS
mov di, offset GenViewClass ;else send to spec UI
push bp ; to see if wants to
call ObjCallSuperNoLock ; do anything special
pop bp
FALL_THRU FinishAttrChange
GenViewSetDimensionAttrs endm
FinishAttrChange proc far uses cx, dx
.enter
mov dx, bp ;update mode
cmp dl, VUM_MANUAL ;if manual, get out
je exit
call VisCheckIfSpecBuilt ;if not visually built
jnc exit ;then no update needed
;
; Invalidate our geometry, so that DetermineSizes will get to us, and
; the pane's parent's geometry, so the pane will have a chance to
; expand.
;
push dx ;save passed update mode
mov cl, mask VOF_GEOMETRY_INVALID
mov dl, VUM_MANUAL ;
call VisMarkInvalid ;do view first
pop dx
mov cl, mask VOF_GEOMETRY_INVALID
mov ax, MSG_VIS_MARK_INVALID
call VisCallParent
exit:
.leave
EC < Destroy ax, bp ;trash things >
ret
FinishAttrChange endp
Build ends
;
;---------------
;
BuildUncommon segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewSetBGColor
DESCRIPTION: Set View window bacground wash color.
NOTE: Attributes may ONLY be changed while the object is
not USABLE.
PASS:
*ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SET_COLOR
cl - Red value
ch - ColorFlag
dl - Green color
dh - Blue color
RETURN:
Nothing
ax, cx, dx, bp -- Destroyed
ALLOWED TO DESTROY:
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Doug 12/89 Initial version
------------------------------------------------------------------------------@
GenViewSetBGColor method GenViewClass, MSG_GEN_VIEW_SET_COLOR
clr di ;no stack frame
call GenViewSendToLinksIfNeeded ;use linkage if there
jc exit ;we did, we're done now
mov bx, offset GVI_color.CQ_redOrIndex
xchg cx, dx ;make into cx:dx
call GenSetDWord
xchg cx, dx ;back to dx.cx
jnc exit
call GenCallSpecIfGrown ;call specific UI if grown
exit:
EC < Destroy ax, cx, dx, bp ;trash things >
ret
GenViewSetBGColor endm
COMMENT @----------------------------------------------------------------------
METHOD: GenViewReplaceParams
DESCRIPTION: Replaces any generic instance data paramaters that match
BranchReplaceParamType
PASS:
*ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_BRANCH_REPLACE_PARAMS
dx - size BranchReplaceParams structure
ss:bp - offset to BranchReplaceParams
RETURN:
nothing
ax, cx, dx, bp -- trashed
ALLOWED TO DESTROY:
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Doug 1/90 Initial version
------------------------------------------------------------------------------@
GenViewReplaceParams method GenViewClass, \
MSG_GEN_BRANCH_REPLACE_PARAMS
cmp ss:[bp].BRP_type, BRPT_OUTPUT_OPTR ; Replacing output optr?
je replaceOD ; branch if so
jmp short done
replaceOD:
; Replace action OD if matches
; search OD
mov ax, MSG_GEN_VIEW_SET_CONTENT
mov bx, offset GVI_content
call GenReplaceMatchingDWord
done:
mov ax, MSG_GEN_BRANCH_REPLACE_PARAMS
mov di, offset GenViewClass
GOTO ObjCallSuperNoLock
GenViewReplaceParams endm
BuildUncommon ends
;---------------------------------------------------
GetUncommon segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewGetAttrs --
MSG_GEN_VIEW_GET_ATTRS for GenViewClass
DESCRIPTION: Returns view attributes.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_GET_ATTRS
RETURN: cx -- attributes
ax, dx, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 3/19/91 Initial version
------------------------------------------------------------------------------@
GenViewGetAttrs method GenViewClass, MSG_GEN_VIEW_GET_ATTRS
EC < Destroy ax, dx, bp ;trash things >
mov cx, ds:[di].GVI_attrs
ret
GenViewGetAttrs endm
COMMENT @----------------------------------------------------------------------
METHOD: GenViewGetDimensionAttrs --
MSG_GEN_VIEW_GET_DIMENSION_ATTRS for GenViewClass
DESCRIPTION: Returns dimension attrs.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_GET_DIMENSION_ATTRS
RETURN: cl - horiz attrs
ch - vert attrs
ax, dx, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 3/19/91 Initial version
------------------------------------------------------------------------------@
GenViewGetDimensionAttrs method GenViewClass,\
MSG_GEN_VIEW_GET_DIMENSION_ATTRS
EC < Destroy ax, dx, bp ;trash things >
mov cx, {word} ds:[di].GVI_horizAttrs
ret
GenViewGetDimensionAttrs endm
COMMENT @----------------------------------------------------------------------
METHOD: GenViewGetBGColor --
MSG_GEN_VIEW_GET_COLOR for GenViewClass
DESCRIPTION: Returns background color.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_GET_COLOR
RETURN: cl - Red value
ch - ColorFlag
dl - Green color
dh - Blue color
ax, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 3/19/91 Initial version
------------------------------------------------------------------------------@
GenViewGetBGColor method GenViewClass, MSG_GEN_VIEW_GET_COLOR
EC < Destroy ax, bp ;trash things >
mov bx, offset GVI_color.CQ_redOrIndex
call GenGetDWord
xchg cx, dx
ret
GenViewGetBGColor endm
GetUncommon ends
;
;---------------
;
ViewCommon segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewGetDocBounds --
MSG_GEN_VIEW_GET_DOC_BOUNDS for GenViewClass
DESCRIPTION: Returns document bounds.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_GET_DOC_BOUNDS
cx:dx - buffer of size RectDWord
RETURN: cx:dx - RectDWord: document bounds
ax, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 3/19/91 Initial version
------------------------------------------------------------------------------@
GenViewGetDocBounds method GenViewClass, MSG_GEN_VIEW_GET_DOC_BOUNDS
mov es, cx
mov bp, dx
mov ax, ds:[di].GVI_docBounds.RD_left.low
mov es:[bp].RD_left.low, ax
mov ax, ds:[di].GVI_docBounds.RD_left.high
mov es:[bp].RD_left.high, ax
mov ax, ds:[di].GVI_docBounds.RD_right.low
mov es:[bp].RD_right.low, ax
mov ax, ds:[di].GVI_docBounds.RD_right.high
mov es:[bp].RD_right.high, ax
mov ax, ds:[di].GVI_docBounds.RD_top.low
mov es:[bp].RD_top.low, ax
mov ax, ds:[di].GVI_docBounds.RD_top.high
mov es:[bp].RD_top.high, ax
mov ax, ds:[di].GVI_docBounds.RD_bottom.low
mov es:[bp].RD_bottom.low, ax
mov ax, ds:[di].GVI_docBounds.RD_bottom.high
mov es:[bp].RD_bottom.high, ax
EC < Destroy ax, bp ;trash things >
ret
GenViewGetDocBounds endm
ViewCommon ends
;
;---------------
;
GetUncommon segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewGetIncrement --
MSG_GEN_VIEW_GET_INCREMENT for GenViewClass
DESCRIPTION: Returns increment.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_GET_INCREMENT
cx:dx - buffer of size PointDWord
RETURN: cx:dx - {PointDWord} increment amounts
ax, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 3/19/91 Initial version
------------------------------------------------------------------------------@
GenViewGetIncrement method GenViewClass, \
MSG_GEN_VIEW_GET_INCREMENT
mov es, cx ;stack segment of passed buffer
mov bp, dx
mov ax, ds:[di].GVI_increment.PD_x.low
mov es:[bp].PD_x.low, ax
mov ax, ds:[di].GVI_increment.PD_x.high
mov es:[bp].PD_x.high, ax
mov ax, ds:[di].GVI_increment.PD_y.low
mov es:[bp].PD_y.low, ax
mov ax, ds:[di].GVI_increment.PD_y.high
mov es:[bp].PD_y.high, ax
EC < Destroy ax, bp ;trash things >
ret
GenViewGetIncrement endm
GetUncommon ends
;
;-------------------
;
ViewCommon segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewGetOrigin --
MSG_GEN_VIEW_GET_ORIGIN for GenViewClass
DESCRIPTION: Returns current origin.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_GET_ORIGIN
cx:dx - buffer of size PointDWord to put origin
RETURN: cx:dx - {PointDWord} current origin
ax, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 3/19/91 Initial version
Jim 7/29/91 Added support for fixed point GVI_origin
------------------------------------------------------------------------------@
GenViewGetOrigin method GenViewClass, \
MSG_GEN_VIEW_GET_ORIGIN
push cx
mov es, cx ;buffer in es:bp
mov bp, dx
mov cx, ds:[di].GVI_origin.PDF_x.DWF_int.low
mov al, ds:[di].GVI_origin.PDF_x.DWF_frac.high
shl al, 1 ; round the result
adc cx, 0
mov es:[bp].PD_x.low, cx
mov cx, ds:[di].GVI_origin.PDF_x.DWF_int.high
adc cx, 0
mov es:[bp].PD_x.high, cx
mov cx, ds:[di].GVI_origin.PDF_y.DWF_int.low
mov al, ds:[di].GVI_origin.PDF_y.DWF_frac.high
shl al, 1 ; round the result
adc cx, 0
mov es:[bp].PD_y.low, cx
mov cx, ds:[di].GVI_origin.PDF_y.DWF_int.high
adc cx, 0
mov es:[bp].PD_y.high, cx
pop cx
EC < Destroy ax, bp ;trash things >
ret
GenViewGetOrigin endm
ViewCommon ends
;
;-------------------
;
GetUncommon segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewGetContent --
MSG_GEN_VIEW_GET_CONTENT for GenViewClass
DESCRIPTION: Returns current content object.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_GET_CONTENT
RETURN: ^lcx:dx - content
ax, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 3/19/91 Initial version
------------------------------------------------------------------------------@
GenViewGetContent method GenViewClass, \
MSG_GEN_VIEW_GET_CONTENT
EC < Destroy ax, bp ;trash things >
mov bx, offset GVI_content
GOTO GenGetDWord
GenViewGetContent endm
GetUncommon ends
;
;---------------
;
Build segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewSetContent
DESCRIPTION: If specific UI grown, calls to handle. Otherwise, stuffs
outputOD & marks dirty.
PASS:
*ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SET_CONTENT
cx:dx - new content OD
RETURN:
nothing
ax, cx, dx, bp -- trashed
ALLOWED TO DESTROY:
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Doug 1/90 Initial version
------------------------------------------------------------------------------@
GenViewSetContent method GenViewClass, MSG_GEN_VIEW_SET_CONTENT
call GenCallSpecIfGrown ; Call specific UI if grown
jc exit ; if called, done
mov bx, offset GVI_content ; Otherwise, just stuff OD
call GenSetDWord
exit:
EC < Destroy ax, cx, dx, bp ;trash things >
ret
GenViewSetContent endm
Build ends
;
;---------------
;
Ink segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewSetInkType
DESCRIPTION: If specific UI grown, calls to handle. Otherwise, stuffs
inkType & marks dirty.
PASS:
*ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SET_CONTENT
cl - GenViewInkType
RETURN:
nothing
ax, cx, dx, bp -- trashed
ALLOWED TO DESTROY:
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Doug 1/90 Initial version
------------------------------------------------------------------------------@
GenViewSetInkType method GenViewClass, MSG_GEN_VIEW_SET_INK_TYPE
clr di ;no stack frame
call GenViewSendToLinksIfNeeded ;use linkage if there
jc exit ;we did, we're done now
call GenCallSpecIfGrown ; Call specific UI if grown
jc exit ; if called, done
mov bx, offset GVI_inkType
call GenSetByte
exit:
EC < Destroy ax, cx, dx, bp ;trash things >
ret
GenViewSetInkType endm
Ink ends
;
;---------------
;
Common segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewSetDocBounds --
MSG_GEN_VIEW_SET_DOC_BOUNDS for GenViewClass
DESCRIPTION: Sets new document bounds. Generic handler will set instance
data, then pass on the specific UI for processing.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SET_DOC_BOUNDS
ss:bp - RectDWord: new scrollable bounds, or all zeroed if
we don't want to constrain drag scrolling.
RETURN: nothing
ax, cx, dx, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 3/15/91 Initial version
------------------------------------------------------------------------------@
GenViewSetDocBounds method GenViewClass, \
MSG_GEN_VIEW_SET_DOC_BOUNDS
mov di, mask MF_STACK ;has stack frame
call GenViewSendToLinksIfNeeded ;use linkage if there
jc exit ;we did, we're done now
mov di, ds:[si]
add di, ds:[di].Gen_offset
if ERROR_CHECK
push cx
mov cx, ss:[bp].RD_left.high
cmp cx, ss:[bp].RD_right.high
ERROR_G UI_VIEW_BAD_DOC_BOUNDS
jl EC10
mov cx, ss:[bp].RD_left.low
cmp cx, ss:[bp].RD_right.low
ERROR_A UI_VIEW_BAD_DOC_BOUNDS
EC10:
mov cx, ss:[bp].RD_top.high
cmp cx, ss:[bp].RD_bottom.high
ERROR_G UI_VIEW_BAD_DOC_BOUNDS
jl EC20
mov cx, ss:[bp].RD_top.low
cmp cx, ss:[bp].RD_bottom.low
ERROR_A UI_VIEW_BAD_DOC_BOUNDS
EC20:
pop cx
endif
push ax, bp ;save bp
clr bx ;keep offset into instance data
clr cx ;init count of changes
10$:
mov ax, {word} ss:[bp] ;store if changed
cmp ax, {word} ds:[di].GVI_docBounds
je 20$
inc cx ;bump change counter
mov {word} ds:[di].GVI_docBounds, ax
20$:
add bx, 2 ;bump counter
add bp, 2 ;and stack buffer pointer
add di, 2 ;and instance data pointer
cmp bx, size RectDWord ;done everything?
jb 10$ ;no, loop
pop ax, bp ;restore bp
jcxz exit ;exit if no changes made
call ObjMarkDirty ;mark as dirty
call GenCallSpecIfGrown ;Call specific UI if grown
exit: ; to finish things up
EC < Destroy ax, cx, dx, bp ;trash things >
ret
GenViewSetDocBounds endm
Common ends
;
;---------------
;
BuildUncommon segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewSetIncrement --
MSG_GEN_VIEW_SET_INCREMENT for GenViewClass
DESCRIPTION: Sets the increment amount.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SET_INCREMENT
ss:bp - {PointDWord} new increment amount
(zero in a given direction if no change
desired)
RETURN: nothing
ax, cx, dx, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 10/12/89 Initial version
------------------------------------------------------------------------------@
GenViewSetIncrement method GenViewClass, MSG_GEN_VIEW_SET_INCREMENT
mov di, mask MF_STACK ;use stack frame
call GenViewSendToLinksIfNeeded ;use linkage if there
jc exit ;we did, we're done now
mov di, ds:[si]
add di, ds:[di].Gen_offset
EC < tst ss:[bp].PD_x.high >
EC < ERROR_S UI_VIEW_BAD_INCREMENT >
EC < tst ss:[bp].PD_y.high >
EC < ERROR_S UI_VIEW_BAD_INCREMENT >
mov ax, ss:[bp].PD_x.low
mov bx, ss:[bp].PD_x.high
mov cx, ss:[bp].PD_y.low
mov dx, ss:[bp].PD_y.high
tst ax ;new value to use?
jnz 10$ ;no, branch
tst bx
jz tryVert
10$:
mov ds:[di].GVI_increment.PD_x.low, ax
mov ds:[di].GVI_increment.PD_x.high, bx
tryVert:
tst dx ;new value to use?
jnz 20$
jcxz callSpecific ;no, branch
20$:
mov ds:[di].GVI_increment.PD_y.low, cx
mov ds:[di].GVI_increment.PD_y.high, dx
callSpecific:
call ObjMarkDirty
mov ax, MSG_GEN_VIEW_SET_INCREMENT
call GenCallSpecIfGrown ;Call specific UI if grown
exit:
EC < Destroy ax, cx, dx, bp ;trash things >
ret
GenViewSetIncrement endm
BuildUncommon ends
;
;---------------
;
ViewCommon segment resource
COMMENT @----------------------------------------------------------------------
ROUTINE: GenSetupTrackingArgs
SYNOPSIS: Fills in extra data for trackings.
CALLED BY: FAR library routine
PASS: ss:bp -- TrackScrollingParams
ds - segment of LMem block or block in
which ds:[LMBH_handle] = block handle
RETURN: ss:bp -- updated TrackScrollingParams
DESTROYED: nothing
WARNING: This routine MAY resize LMem and/or object blocks, moving
them on the heap and invalidating stored segment pointers
to them.
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 4/ 1/90 Initial version
------------------------------------------------------------------------------@
GenSetupTrackingArgs proc far uses ax, di
.enter
mov dx, bp ;pass cx:dx - TrackScrollingParams
mov cx, ss
mov di, mask MF_CALL or mask MF_FIXUP_DS
mov ax, MSG_GEN_VIEW_SETUP_TRACKING_ARGS
call ReturnToCaller
.leave
ret
GenSetupTrackingArgs endp
COMMENT @----------------------------------------------------------------------
ROUTINE: GenReturnTrackingArgs
SYNOPSIS: Sends the tracking structure back to the caller.
CALLED BY: FAR utility
PASS: ss:bp -- TrackScrollingParams
cx - caller's chunk handler
ds - segment of LMem block or block in
which ds:[LMBH_handle] = block handle
RETURN: ds - updated to point at segment of same block as on entry
DESTROYED: nothing
WARNING: This routine MAY resize LMem and/or object blocks, moving
them on the heap and invalidating stored segment pointers
to them.
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 4/ 1/90 Initial version
------------------------------------------------------------------------------@
GenReturnTrackingArgs proc far uses di, ax
.enter
;
; If absolute, we'll set up newOrigin so the MSG_GEN_VIEW_TRACKING_-
; COMPLETE handler can use the newOrigin for scrolling rather than
; the change. We run into problems with the content processing the
; same absolute scroll twice before the view has received completion of
; either, where the returned change doesn't reflect what the content
; wanted. -cbh 3/23/92
;
test ss:[bp].TSP_flags, mask SF_ABSOLUTE
jz 10$ ; relative, new origin ignored
mov ax, ss:[bp].TSP_oldOrigin.PD_x.low ;get old origin
mov bx, ss:[bp].TSP_oldOrigin.PD_x.high
mov cx, ss:[bp].TSP_oldOrigin.PD_y.low
mov dx, ss:[bp].TSP_oldOrigin.PD_y.high
add cx, ss:[bp].TSP_change.PD_y.low ;add change,
mov ss:[bp].TSP_newOrigin.PD_y.low, cx ; store as new origin
adc dx, ss:[bp].TSP_change.PD_y.high
mov ss:[bp].TSP_newOrigin.PD_y.high, dx
add ax, ss:[bp].TSP_change.PD_x.low
mov ss:[bp].TSP_newOrigin.PD_x.low, ax
adc bx, ss:[bp].TSP_change.PD_x.high
mov ss:[bp].TSP_newOrigin.PD_x.high, bx
10$:
; mov di, mask MF_STACK or mask MF_FIXUP_DS or mask MF_FORCE_QUEUE
mov di, mask MF_STACK or mask MF_CALL or mask MF_FIXUP_DS
mov dx, size TrackScrollingParams ; set size if needed
mov ax, MSG_GEN_VIEW_TRACKING_COMPLETE
call ReturnToCaller
.leave
ret
GenReturnTrackingArgs endp
COMMENT @----------------------------------------------------------------------
ROUTINE: ReturnToCaller
SYNOPSIS: Returns a call to the caller.
CALLED BY: GenSetupTrackingArgs, GenReturnTrackingArgs
PASS: ss:[bp] -- TrackScrollingParams
dx -- other arguments to ObjMessage
di -- flags to ObjMessage
ax -- method to send
RETURN: nothing
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 4/24/91 Initial version
------------------------------------------------------------------------------@
ReturnToCaller proc near uses bx, cx, dx, bp, si
.enter
mov bx, ss:[bp].TSP_caller.handle
mov si, ss:[bp].TSP_caller.chunk
call ObjMessage ; Send it off
.leave
ret
ReturnToCaller endp
COMMENT @----------------------------------------------------------------------
METHOD: GenViewSetOrigin --
MSG_GEN_VIEW_SET_ORIGIN for GenViewClass
DESCRIPTION: Sets the subview origin. Doesn't force building out of the
view. If the view hasn't been opened, any subsequent subviews
opened will have this offset initially.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SET_ORIGIN
ss:bp - {PointDWord} - new origin
RETURN:
ax, cx, dx, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 6/22/90 Initial version
Jim 7/29/91 Added support for fixed point GVI_origin
------------------------------------------------------------------------------@
GenViewSetOrigin method GenViewClass,MSG_GEN_VIEW_SET_ORIGIN
call VisCheckIfSpecBuilt ;if not visually built
jnc setGenericDataOnly ;then just set instance data
mov di, offset GenViewClass ;else send to specific UI
GOTO ObjCallSuperNoLock
setGenericDataOnly:
call ObjMarkDirty
mov cx, ss:[bp].PD_x.low
mov ds:[di].GVI_origin.PDF_x.DWF_int.low, cx
mov cx, ss:[bp].PD_x.high
mov ds:[di].GVI_origin.PDF_x.DWF_int.high, cx
mov cx, ss:[bp].PD_y.low
mov ds:[di].GVI_origin.PDF_y.DWF_int.low, cx
mov cx, ss:[bp].PD_y.high
mov ds:[di].GVI_origin.PDF_y.DWF_int.high, cx
clr cx
mov ds:[di].GVI_origin.PDF_x.DWF_frac, cx
mov ds:[di].GVI_origin.PDF_y.DWF_frac, cx
EC < Destroy ax, cx, dx, bp ;trash things >
ret
GenViewSetOrigin endm
COMMENT @----------------------------------------------------------------------
METHOD: GenViewScroll --
MSG_GEN_VIEW_SCROLL for GenViewClass
DESCRIPTION: Changes the subview origin. Doesn't force building out of the
view.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SCROLL
ss:bp - {PointDWord} amount to scroll
RETURN: nothing
ax, cx, dx, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 6/22/90 Initial version
Jim 7/29/91 Added support for fixed point GVI_origin
------------------------------------------------------------------------------@
GenViewScroll method GenViewClass,MSG_GEN_VIEW_SCROLL
call VisCheckIfSpecBuilt ;if not visually built
jnc setGenericDataOnly ;then just set instance data
mov di, offset GenViewClass ;else send to specific UI
GOTO ObjCallSuperNoLock
setGenericDataOnly:
mov di, mask MF_STACK ;use stack frame
call GenViewSendToLinksIfNeeded ;use linkage if there
jc exit ;we did, we're done now
call ScrollView
exit:
EC < Destroy ax, cx, dx, bp ;trash things >
ret
GenViewScroll endm
COMMENT @----------------------------------------------------------------------
METHOD: GenViewScrollLow --
MSG_GEN_VIEW_SET_ORIGIN_LOW for GenViewClass
DESCRIPTION: Changes the subview origin. Doesn't force building out of the
view.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SET_ORIGIN_LOW
ss:bp - {PointDWord} amount to scroll
RETURN: nothing
ax, cx, dx, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 6/22/90 Initial version
Jim 7/29/91 Added support for fixed point GVI_origin
------------------------------------------------------------------------------@
GenViewScrollLow method GenViewClass,MSG_GEN_VIEW_SET_ORIGIN_LOW
call VisCheckIfSpecBuilt ;if not visually built
jnc setGenericDataOnly ;then just set instance data
mov di, offset GenViewClass ;else send to specific UI
GOTO ObjCallSuperNoLock
setGenericDataOnly:
call ScrollView
EC < Destroy ax, cx, dx, bp ;trash things >
ret
GenViewScrollLow endm
ScrollView proc near
class GenViewClass
mov di, ds:[si]
add di, ds:[di].Gen_offset
call ObjMarkDirty
cmpdw ss:[bp].PD_x, GVSOL_NO_CHANGE
je afterX
mov cx, ss:[bp].PD_x.low
add ds:[di].GVI_origin.PDF_x.DWF_int.low, cx
mov cx, ss:[bp].PD_x.high
adc ds:[di].GVI_origin.PDF_x.DWF_int.high, cx
afterX:
cmpdw ss:[bp].PD_y, GVSOL_NO_CHANGE
je afterY
mov cx, ss:[bp].PD_y.low
add ds:[di].GVI_origin.PDF_y.DWF_int.low, cx
mov cx, ss:[bp].PD_y.high
adc ds:[di].GVI_origin.PDF_y.DWF_int.high, cx
afterY:
ret
ScrollView endp
COMMENT @----------------------------------------------------------------------
METHOD: GenViewScale --
MSG_GEN_VIEW_SET_SCALE_FACTOR for GenViewClass
DESCRIPTION: Sets scale factor. If not yet built, just changes the
instance data, but will not change the document offset.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SET_SCALE_FACTOR
ss:bp - {ScaleViewParams} new scale factor
RETURN: nothing
ax, cx, dx, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 3/19/91 Initial version
------------------------------------------------------------------------------@
GenViewScale method GenViewClass, MSG_GEN_VIEW_SET_SCALE_FACTOR
EC < test ds:[di].GVI_attrs, mask GVA_GENERIC_CONTENTS >
EC < WARNING_NZ WARNING_VIEW_SHOULD_NOT_SCALE_UI_GADGETS >
mov di, ds:[si]
add di, ds:[di].Gen_offset
mov dx, ss:[bp].SVP_scaleFactor.PF_x.WWF_int
mov cx, ss:[bp].SVP_scaleFactor.PF_x.WWF_frac
mov bx, ss:[bp].SVP_scaleFactor.PF_y.WWF_int
mov ax, ss:[bp].SVP_scaleFactor.PF_y.WWF_frac
cmp dx, ds:[di].GVI_scaleFactor.PF_x.WWF_int
jne 10$
cmp cx, ds:[di].GVI_scaleFactor.PF_x.WWF_frac
jne 10$
cmp bx, ds:[di].GVI_scaleFactor.PF_y.WWF_int
jne 10$
cmp ax, ds:[di].GVI_scaleFactor.PF_y.WWF_frac
je exit ;no change, exit
10$:
call ObjMarkDirty ;mark dirty for all cases
call VisCheckIfSpecBuilt ;if not visually built
jnc setGenericDataOnly ;then just set instance data
mov ax, MSG_GEN_VIEW_SET_SCALE_FACTOR
mov di, offset GenViewClass ;else send to specific UI
GOTO ObjCallSuperNoLock
setGenericDataOnly:
mov ds:[di].GVI_scaleFactor.PF_x.WWF_int, dx
mov ds:[di].GVI_scaleFactor.PF_x.WWF_frac, cx
mov ds:[di].GVI_scaleFactor.PF_y.WWF_int, bx
mov ds:[di].GVI_scaleFactor.PF_y.WWF_frac, ax
exit:
EC < Destroy ax, cx, dx, bp ;trash things >
ret
GenViewScale endm
ViewCommon ends
;
;---------------
;
ViewCommon segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewGetScaleFactor --
MSG_GEN_VIEW_GET_SCALE_FACTOR for GenViewClass
DESCRIPTION: Returns scale factors for this pane.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GET_PANE_SCALE_FACTOR
RETURN: dx.cx - x scale factor (WWFixed)
bp.ax - y scale factor (WWFixed)
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 2/26/90 Initial version
------------------------------------------------------------------------------@
GenViewGetScaleFactor method GenViewClass, MSG_GEN_VIEW_GET_SCALE_FACTOR
mov dx, ds:[di].GVI_scaleFactor.PF_x.WWF_int
mov cx, ds:[di].GVI_scaleFactor.PF_x.WWF_frac
mov bp, ds:[di].GVI_scaleFactor.PF_y.WWF_int
mov ax, ds:[di].GVI_scaleFactor.PF_y.WWF_frac
ret
GenViewGetScaleFactor endm
ViewCommon ends
;
;-------------------
;
GetUncommon segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewGetWindow --
MSG_GEN_VIEW_GET_WINDOW for GenViewClass
DESCRIPTION: Returns window handle, of null if none.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_GET_WINDOW
RETURN: cx - window handle, or null if none
ax, dx, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 3/15/91 Initial version
------------------------------------------------------------------------------@
GenViewGetWindow method GenViewClass, MSG_GEN_VIEW_GET_WINDOW
clr cx ;assume none
call GenViewOnlyCallIfSpecBuilt
EC < Destroy ax, dx, bp ;trash things >
ret
GenViewGetWindow endm
GetUncommon ends
;
;---------------
;
ViewCommon segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewSetupTrackingArgs --
MSG_GEN_VIEW_SETUP_TRACKING_ARGS for GenViewClass
DESCRIPTION: Sets up tracking arguments.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SETUP_TRACKING_ARGS
cx:dx - TrackScrollingParams
RETURN: nothing
ax, cx, dx, bp - destroyed
ALLOWED TO DESTROY:
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chris 2/18/93 Initial Version
------------------------------------------------------------------------------@
GenViewSetupTrackingArgs method dynamic GenViewClass, \
MSG_GEN_VIEW_SETUP_TRACKING_ARGS
push es
movdw esbp, cxdx
or es:[bp].TSP_flags, mask SF_EC_SETUP_CALLED
pop es
FALL_THRU GenViewOnlyCallIfSpecBuilt
GenViewSetupTrackingArgs endm
COMMENT @----------------------------------------------------------------------
METHOD: GenViewOnlyCallIfSpecBuilt --
MSG_GEN_VIEW_MAKE_RECT_VISIBLE for GenViewClass
MSG_GEN_VIEW_TRACKING_COMPLETE for GenViewClass
DESCRIPTION: Only calls specific UI object if specifically built already.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - method
cx,dx,bp- args
RETURN: nothing
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 7/25/90 Initial version
------------------------------------------------------------------------------@
GenViewOnlyCallIfSpecBuilt method GenViewClass, \
MSG_GEN_VIEW_MAKE_RECT_VISIBLE, \
MSG_GEN_VIEW_TRACKING_COMPLETE, \
MSG_GEN_VIEW_INITIATE_DRAG_SCROLL, \
MSG_GEN_VIEW_SCROLL_TOP, \
MSG_GEN_VIEW_SCROLL_PAGE_UP, \
MSG_GEN_VIEW_SCROLL_UP, \
MSG_GEN_VIEW_SCROLL_SET_Y_ORIGIN, \
MSG_GEN_VIEW_SCROLL_DOWN, \
MSG_GEN_VIEW_SCROLL_BOTTOM, \
MSG_GEN_VIEW_SCROLL_LEFT_EDGE, \
MSG_GEN_VIEW_SCROLL_PAGE_LEFT, \
MSG_GEN_VIEW_SCROLL_LEFT, \
MSG_GEN_VIEW_SCROLL_SET_X_ORIGIN, \
MSG_GEN_VIEW_SCROLL_RIGHT, \
MSG_GEN_VIEW_SCROLL_PAGE_RIGHT, \
MSG_GEN_VIEW_SCROLL_RIGHT_EDGE, \
MSG_GEN_VIEW_SUSPEND_UPDATE, \
MSG_GEN_VIEW_UNSUSPEND_UPDATE
call VisCheckIfSpecBuilt ;if not visually built
jnc exit ;then exit
mov di, offset GenViewClass ;else send to specific UI
GOTO ObjCallSuperNoLock
exit:
ret
GenViewOnlyCallIfSpecBuilt endm
COMMENT @----------------------------------------------------------------------
ROUTINE: GenViewSetSimpleBounds
SYNOPSIS: Sets simple bounds.
CALLED BY: global
PASS: ^lbx:si -- view handle
cx -- 16 bit right bound to set (width of your doc)
dx -- 16 bit bottom bound to set (height of your doc)
di -- MessageFlags:
MF_FIXUP_DS to fixup DS around call to view
MF_FIXUP_ES to fixup ES around call to view
RETURN: nothing
ax, cx, dx, bp -- trashed
ALLOWED TO DESTROY: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 3/15/91 Initial version
------------------------------------------------------------------------------@
GenViewSetSimpleBounds proc far uses ax, cx, dx, bp, di
.enter
EC < tst cx ;small only! >
EC < ERROR_S UI_VIEW_NEG_WIDTH_PASSED_TO_SET_SIMPLE_BOUNDS >
EC < tst dx >
EC < ERROR_S UI_VIEW_NEG_HEIGHT_PASSED_TO_SET_SIMPLE_BOUNDS >
EC < test di, not (mask MF_FIXUP_DS or mask MF_FIXUP_ES) >
EC < ERROR_NZ UI_VIEW_BAD_MESSAGE_FLAGS_PASSED_TO_SET_SIMPLE_BOUNDS >
sub sp, size RectDWord ;set up parameters
mov bp, sp
clr ax
mov ss:[bp].RD_left.low, ax ;origin 0, 0
mov ss:[bp].RD_left.high, ax
mov ss:[bp].RD_top.low, ax
mov ss:[bp].RD_top.high, ax
mov ss:[bp].RD_right.high, ax ;clear other high words
mov ss:[bp].RD_bottom.high, ax
mov ss:[bp].RD_right.low, cx ;right edge <- width
mov ss:[bp].RD_bottom.low, dx ;bottom edge <- height
mov dx, size RectDWord
or di, mask MF_STACK or mask MF_CALL
mov ax, MSG_GEN_VIEW_SET_DOC_BOUNDS ;set new document size
call ObjMessage
add sp, size RectDWord
.leave
ret
GenViewSetSimpleBounds endp
COMMENT @----------------------------------------------------------------------
METHOD: GenViewGetVisibleRect --
MSG_GEN_VIEW_GET_VISIBLE_RECT for GenViewClass
DESCRIPTION: Returns the visible rectangle.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_GET_VISIBLE_RECT
cx:dx - buffer of size RectDWord
RETURN: cx:dx - {RectDWord} visible area, or null if not yet built
ax, bp -- trashed
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 4/ 2/91 Initial version
------------------------------------------------------------------------------@
GenViewGetVisibleRect method GenViewClass, MSG_GEN_VIEW_GET_VISIBLE_RECT
push es
mov es, cx
mov di, dx
clr es:[di].RD_left.low ;assume not built
clr es:[di].RD_left.high
clr es:[di].RD_top.low
clr es:[di].RD_top.high
clr es:[di].RD_right.low
clr es:[di].RD_right.high
clr es:[di].RD_bottom.low
clr es:[di].RD_bottom.high
pop es
GOTO GenViewOnlyCallIfSpecBuilt
GenViewGetVisibleRect endm
ViewCommon ends
;
;---------------
;
Build segment resource
COMMENT @----------------------------------------------------------------------
METHOD: GenViewAddGenChild --
MSG_GEN_ADD_CHILD for GenViewClass
MSG_GEN_REMOVE_CHILD for GenViewClass
DESCRIPTION: Sends the method first to the specific UI, then to superclass.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - method
cx, dx, bp - args
RETURN: ax, cx, dx, bp - any return values
ALLOWED TO DESTROY: bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 4/10/91 Initial version
------------------------------------------------------------------------------@
GenViewAddGenChild method GenViewClass, MSG_GEN_ADD_CHILD, \
MSG_GEN_REMOVE_CHILD
push ax, cx, dx, bp
mov di, offset GenClass
call ObjCallSuperNoLock ;first, call specific UI
pop ax, cx, dx, bp
mov di, offset GenViewClass ;then do normal GenClass add
GOTO ObjCallSuperNoLock
GenViewAddGenChild endm
Build ends
;
;---------------
;
ViewCommon segment resource
COMMENT @----------------------------------------------------------------------
ROUTINE: GenViewSendToLinksIfNeeded
SYNOPSIS: Takes the current message, encapsulates it, and sends it off
to the linked views, if there are any.
CALLED BY: GLOBAL, called at the start of handlers for
all scroll messages (called after tracking complete)
MSG_GEN_VIEW_SET_SCALE_FACTOR
MSG_GEN_VIEW_SET_DOC_BOUNDS
MSG_GEN_VIEW_SET_CONTENT
MSG_GEN_VIEW_SET_INCREMENT
MSG_GEN_VIEW_SUSPEND_UPDATE
MSG_GEN_VIEW_UNSUSPEND_UPDATE
MSG_GEN_VIEW_SET_COLOR
PASS: *ds:si -- view
ax -- message
cx, dx, bp -- arguments to message
di -- MF_STACK if a stack message, 0 if not
RETURN: carry set if message sent to MSG_GEN_VIEW_SEND_TO_LINKS
with ax, cx, dx, bp destroyed
clear if message not sent (and should be handled normally),
with ax, cx, dx, bp preserved
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 10/16/91 Initial version
------------------------------------------------------------------------------@
GenViewSendToLinksIfNeeded proc far
uses bx
.enter
clr bx
call GenViewSendToLinksIfNeededDirection
.leave
ret
GenViewSendToLinksIfNeeded endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
GenViewSendToLinksIfNeededDirection
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ROUTINE: GenViewSendToLinksIfNeededDirection
SYNOPSIS: Takes the current message, encapsulates it, and sends it off
to the linked views, if there are any. Changed to
only send to the links specified in bx
CALLED BY: Internal, called at the start of handlers for
all scroll messages (called after tracking complete)
MSG_GEN_VIEW_SET_SCALE_FACTOR
MSG_GEN_VIEW_SET_DOC_BOUNDS
MSG_GEN_VIEW_SET_CONTENT
MSG_GEN_VIEW_SET_INCREMENT
MSG_GEN_VIEW_SUSPEND_UPDATE
MSG_GEN_VIEW_UNSUSPEND_UPDATE
MSG_GEN_VIEW_SET_COLOR
PASS: *ds:si -- view
ax -- message
cx, dx, bp -- arguments to message
di -- MF_STACK if a stack message, 0 if not
bx -- bx = < 0 if horizontal only scroll
= > 0 if vertical only scroll
= 0 if scroll in both dircestions
RETURN: carry set if message sent to MSG_GEN_VIEW_SEND_TO_LINKS
with ax, cx, dx, bp destroyed
clear if message not sent (and should be handled normally),
with ax, cx, dx, bp preserved
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 10/16/91 Initial version
IP 1/ 9/95 changed to only send to specified link
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
GenViewSendToLinksIfNeededDirection proc far
uses si, bx
class GenViewClass
.enter
push bx
mov bx, ds:[si]
add bx, ds:[bx].Gen_offset
tst ds:[bx].GVI_vertLink.handle ;a vertical link, encapsulate
jnz encapsulate
tst_clc ds:[bx].GVI_horizLink.handle ;no vert or horiz link, exit,
; not handled
jz popExit
encapsulate:
pop bx
cmp ax, MSG_GEN_VIEW_SET_ORIGIN_LOW ;is this our scroll guy?
je handleScroll ;yes, handle it specially
mov bx, MSG_GEN_VIEW_SEND_TO_LINKS ;send to all links
call SendInLinkMessage
jmp short exitHandled
handleScroll:
tst bx
jg noHoriz
push ss:[bp].PD_y.low ;nuke the vertical portion
push ss:[bp].PD_y.high
movdw ss:[bp].PD_y, GVSOL_NO_CHANGE
push bx
mov bx, MSG_GEN_VIEW_SEND_TO_VLINK
call SendInLinkMessage
pop bx
pop ss:[bp].PD_y.high
pop ss:[bp].PD_y.low
tst bx
noHoriz:
jl noVert
movdw ss:[bp].PD_x, GVSOL_NO_CHANGE
mov bx, MSG_GEN_VIEW_SEND_TO_HLINK
call SendInLinkMessage ;send to horizontal link
noVert:
exitHandled:
stc ;say handled through links
exit:
.leave
ret
popExit:
pop bx
jmp exit
GenViewSendToLinksIfNeededDirection endp
COMMENT @----------------------------------------------------------------------
ROUTINE: SendInLinkMessage
SYNOPSIS: Encapsulates a GenView message and sends it in a link message.
Frees the event after sent off.
CALLED BY: GenViewSendToLinksIfNeeded
PASS: *ds:si -- GenView
di -- MF_STACK or zero, depending on message
ax -- message to encapsulate
cx, dx, bp -- arguments
bx -- link message to send out, either:
MSG_GEN_VIEW_SEND_TO_HLINK
MSG_GEN_VIEW_SEND_TO_VLINK
MSG_GEN_VIEW_SEND_TO_LINKS
RETURN: nothing
DESTROYED: bx
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Chris 10/17/91 Initial version
------------------------------------------------------------------------------@
SendInLinkMessage proc near uses ax, cx, dx, bp, di
class GenViewClass
.enter
push bx
mov bx, ds:[LMBH_handle] ;pass destination in ^lbx:si
push si
or di, mask MF_RECORD ;encapsulate the message
call ObjMessage
pop si
mov bp, di ;event handle in bp
mov cx, ds:[LMBH_handle] ;pass originator in ^lcx:dx
mov dx, si
pop ax ;restore event message
call ObjCallInstanceNoLock
mov bx, di
call ObjFreeMessage ;get rid of the event
.leave
ret
SendInLinkMessage endp
COMMENT @----------------------------------------------------------------------
METHOD: GenViewSendToLinks --
MSG_GEN_VIEW_SEND_TO_LINKS for GenViewClass
DESCRIPTION: Sends the event to all the links, by moving horizontally
and sending out MSG_GEN_VIEW_SEND_TO_VLINK at each node.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SEND_TO_LINKS
bp - event
^lcx:dx - originator
RETURN:
ax, cx, dx, bp - destroyed
ALLOWED TO DESTROY:
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chris 10/17/91 Initial Version
------------------------------------------------------------------------------@
GenViewSendToLinks method dynamic GenViewClass, \
MSG_GEN_VIEW_SEND_TO_LINKS
push ax, cx, dx, bp ;save original originator
;
; Send a MSG_GEN_VIEW_SEND_TO_VLINK to ourselves, to call ourselves
; with the encapsulated message and anyone we're linked to vertically.
;
mov cx, ds:[LMBH_handle] ;pass ourselves
mov dx, si
mov ax, MSG_GEN_VIEW_SEND_TO_VLINK
call ObjCallInstanceNoLock
pop ax, cx, dx, bp
;
; Now, pass this message along to the horizontal link, if it doesn't
; match the originator.
;
mov di, ds:[si]
add di, ds:[di].Gen_offset
mov bx, ds:[di].GVI_horizLink.handle
mov di, ds:[di].GVI_horizLink.chunk
GOTO SendToLink
GenViewSendToLinks endm
COMMENT @----------------------------------------------------------------------
METHOD: GenViewSendToVLink --
MSG_GEN_VIEW_SEND_TO_VLINK for GenViewClass
DESCRIPTION: Sends encapsulated message to all nodes in the vertical link.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SEND_TO_VLINK
bp - event
^lcx:dx - originator
RETURN: nothing
ax, cx, dx, bp - destroyed
ALLOWED TO DESTROY:
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chris 10/16/91 Initial Version
------------------------------------------------------------------------------@
GenViewSendToVLink method dynamic GenViewClass, MSG_GEN_VIEW_SEND_TO_VLINK
mov di, ds:[si]
add di, ds:[di].Gen_offset
mov bx, ds:[di].GVI_vertLink.handle
mov di, ds:[di].GVI_vertLink.chunk
CallOurselvesAndSendToLink label far
;
; Send to ourselves, ignoring any links.
;
push ax, cx, dx, bp
mov cx, mask MF_RECORD or mask MF_CALL ;preserve message
mov ax, MSG_GEN_VIEW_CALL_WITHOUT_LINKS
call ObjCallInstanceNoLock
pop ax, cx, dx, bp
SendToLink label far
;
; If no vertical link, or the link matches the originator, nothing
; to send, exit. (^lbx:di is the link)
;
mov si, di
tst bx
EC < pushf >
EC < jnz EC10 ;is linkage, branch >
EC < cmp si, dx ;no linkage, better >
EC < jne EC10 ; be originator! >
EC < cmp bx, cx >
EC < ERROR_E UI_VIEW_LINKAGE_MUST_BE_CIRCULAR >
EC <EC10: >
EC < popf >
jz exit
cmp si, dx
jne sendToLink
cmp bx, cx
je exit
sendToLink:
mov di, mask MF_CALL ;send to link
call ObjMessage
exit:
ret
GenViewSendToVLink endm
COMMENT @----------------------------------------------------------------------
METHOD: GenViewSendToHLink --
MSG_GEN_VIEW_SEND_TO_HLINK for GenViewClass
DESCRIPTION: Propagates a message through the horizontal links.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_SEND_TO_HLINK
bp - event
^lcx:dx - originator of the message
RETURN:
ax, cx, dx, bp - destroyed
ALLOWED TO DESTROY:
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chris 10/16/91 Initial Version
------------------------------------------------------------------------------@
GenViewSendToHLink method dynamic GenViewClass, MSG_GEN_VIEW_SEND_TO_HLINK
mov di, ds:[si]
add di, ds:[di].Gen_offset
mov bx, ds:[di].GVI_horizLink.handle
mov di, ds:[di].GVI_horizLink.chunk
GOTO CallOurselvesAndSendToLink
GenViewSendToHLink endm
COMMENT @----------------------------------------------------------------------
METHOD: GenViewCallWithoutLinks --
MSG_GEN_VIEW_CALL_WITHOUT_LINKS for GenViewClass
DESCRIPTION: Dispatches a GenView message that will ignore horizontal
and vertical links.
PASS: *ds:si - instance data
es - segment of MetaClass
ax - MSG_GEN_VIEW_CALL_WITHOUT_LINKS
bp - ClassedEvent
cx - ObjMessageFlags to pass to MessageDispatch
RETURN: ax, cx, dx, bp - any return arguments
ALLOWED TO DESTROY:
bx, si, di, ds, es
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chris 10/16/91 Initial Version
------------------------------------------------------------------------------@
GenViewCallWithoutLinks method dynamic GenViewClass, \
MSG_GEN_VIEW_CALL_WITHOUT_LINKS
mov di, 600
call ThreadBorrowStackSpace
push di
mov di, ds:[si]
add di, ds:[di].Gen_offset
push ds:[di].GVI_vertLink.handle,
ds:[di].GVI_vertLink.chunk,
ds:[di].GVI_horizLink.handle,
ds:[di].GVI_horizLink.chunk
clr ax
mov ds:[di].GVI_vertLink.handle, ax
mov ds:[di].GVI_vertLink.chunk, ax
mov ds:[di].GVI_horizLink.handle, ax
mov ds:[di].GVI_horizLink.chunk, ax
mov di, cx ;flags
mov bx, bp ;event
test di, mask MF_RECORD
jz dispatch
push si
call ObjGetMessageInfo ;save event destination data
mov dx, si
pop si
push cx, dx
dispatch:
mov cx, ds:[LMBH_handle] ;send to ourselves
call MessageSetDestination
ornf di, mask MF_FIXUP_DS ; make sure this is set...
call MessageDispatch
test di, mask MF_RECORD
jz done ; => message was destroyed, so no need
; to restore the destination
pop cx, dx
push si
mov si, dx
call MessageSetDestination ;restore event destination data
pop si
done:
mov di, ds:[si]
add di, ds:[di].Gen_offset
pop ds:[di].GVI_vertLink.handle,
ds:[di].GVI_vertLink.chunk,
ds:[di].GVI_horizLink.handle,
ds:[di].GVI_horizLink.chunk
pop di
call ThreadReturnStackSpace
ret
GenViewCallWithoutLinks endm
ViewCommon ends
;
;---------------
;
Ink segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
GenViewResetExtendedInkType
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Deletes any "extended" ink info from the object.
CALLED BY: GLOBAL
PASS: nada
RETURN: nada
DESTROYED: nada
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
atw 2/19/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
GenViewResetExtendedInkType method GenViewClass,
MSG_GEN_VIEW_RESET_EXTENDED_INK_TYPE
.enter
mov ax, ATTR_GEN_VIEW_INK_DESTINATION_INFO
call ObjVarDeleteData
Destroy ax, cx, dx, bp
.leave
ret
GenViewResetExtendedInkType endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
GenViewSetExtendedInkType
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Deletes any "extended" ink info from the object.
CALLED BY: GLOBAL
PASS: nada
RETURN: nada
DESTROYED: nada
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
atw 2/19/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
GenViewSetExtendedInkType method GenViewClass,
MSG_GEN_VIEW_SET_EXTENDED_INK_TYPE
.enter
clr bh
mov bl, mask OCF_VARDATA_RELOC
mov ax, si
call ObjSetFlags
mov ax, ATTR_GEN_VIEW_INK_DESTINATION_INFO
mov cx, size InkDestinationInfoParams
call ObjVarAddData
mov cx, size InkDestinationInfoParams/2
segmov es, ds
mov di, bx
segmov ds, ss
mov si, bp
rep movsw
Destroy ax, cx, dx, bp
.leave
ret
GenViewSetExtendedInkType endp
Ink ends
| 23.775895 | 81 | 0.607051 |
fd4bd02019eb81b809802d815544048b8e5e4be8 | 448 | h | C | src/SegmentationView.h | xt00s/ImageSegmenter | 67fd166e722ac1a890b7b5dc4cf4d97a39447891 | [
"MIT"
] | null | null | null | src/SegmentationView.h | xt00s/ImageSegmenter | 67fd166e722ac1a890b7b5dc4cf4d97a39447891 | [
"MIT"
] | null | null | null | src/SegmentationView.h | xt00s/ImageSegmenter | 67fd166e722ac1a890b7b5dc4cf4d97a39447891 | [
"MIT"
] | null | null | null | #ifndef SEGMENTATIONVIEW_H
#define SEGMENTATIONVIEW_H
#include <QGraphicsView>
class SegmentationView : public QGraphicsView
{
Q_OBJECT
public:
SegmentationView(QWidget *parent = nullptr);
void setup();
signals:
void zoomShifted(int delta);
protected:
bool eventFilter(QObject *watched, QEvent *event) override;
private:
bool panning_;
QPoint panningPos_;
QCursor lastCursor_;
};
#endif // SEGMENTATIONVIEW_H
| 16.592593 | 63 | 0.738839 |
c107c84e38db4e7bce997e1e1fb5390f288744a5 | 768 | sql | SQL | web/src/main/resources/migration/V2__sysUserAddColumn.sql | NJUPT-SACC/sacc-ComprehensiveSystem | 430413be341ebeb1c34735537883ac860e042ea6 | [
"MIT"
] | 7 | 2019-10-03T09:34:19.000Z | 2020-07-08T23:34:58.000Z | web/src/main/resources/migration/V2__sysUserAddColumn.sql | NJUPT-SACC/sacc-ComprehensiveSystem | 430413be341ebeb1c34735537883ac860e042ea6 | [
"MIT"
] | 2 | 2019-12-02T04:07:22.000Z | 2019-12-02T06:10:16.000Z | web/src/main/resources/migration/V2__sysUserAddColumn.sql | NJUPT-SACC/sacc-ComprehensiveSystem | 430413be341ebeb1c34735537883ac860e042ea6 | [
"MIT"
] | 1 | 2020-02-19T09:35:44.000Z | 2020-02-19T09:35:44.000Z | ALTER TABLE `sys_user`
MODIFY COLUMN `create_by` bigint(20) NULL COMMENT '创建者' AFTER `create_date`;
ALTER TABLE `sys_user`
MODIFY COLUMN `update_by` bigint(20) NULL AFTER `update_date`;
alter table sys_user modify name varchar(20) default '' not null comment '姓名';
alter table sys_user
add student_number varchar(20) default '' not null comment '学号' after password;
alter table sys_user
add grade tinyint default 0 not null comment '年级' after pic_url;
alter table sys_user
add institution varchar(50) default '' not null comment '学院' after grade;
alter table sys_user
add major varchar(20) default '' not null comment '专业' after institution;
alter table sys_user
add gender tinyint default 0 not null comment '1是男生,2是女生' after major;
| 34.909091 | 83 | 0.748698 |
fb3d1315e039faeba48d203e4918709ddeb8940c | 370 | java | Java | src/main/java/fr/lfml/manaproject/repository/TechNeedRepository.java | BulkSecurityGeneratorProject/ManaProject | f23fcf2b795599f9f9a3b381d16b693464d7e189 | [
"MIT"
] | 1 | 2018-01-09T13:51:01.000Z | 2018-01-09T13:51:01.000Z | src/main/java/fr/lfml/manaproject/repository/TechNeedRepository.java | BulkSecurityGeneratorProject/ManaProject | f23fcf2b795599f9f9a3b381d16b693464d7e189 | [
"MIT"
] | null | null | null | src/main/java/fr/lfml/manaproject/repository/TechNeedRepository.java | BulkSecurityGeneratorProject/ManaProject | f23fcf2b795599f9f9a3b381d16b693464d7e189 | [
"MIT"
] | 1 | 2020-09-18T14:00:44.000Z | 2020-09-18T14:00:44.000Z | package fr.lfml.manaproject.repository;
import fr.lfml.manaproject.domain.TechNeed;
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.*;
/**
* Spring Data JPA repository for the TechNeed entity.
*/
@SuppressWarnings("unused")
@Repository
public interface TechNeedRepository extends JpaRepository<TechNeed, Long> {
}
| 21.764706 | 75 | 0.8 |
e19c6dbbb2396800da20505c13359821314ce882 | 928 | swift | Swift | Sources/HighwayCore/Bundle/ProjectDescription.swift | highway-tool/highway | 1ff3fe4a18455c055371e17293ba2b855c6223ac | [
"MIT"
] | null | null | null | Sources/HighwayCore/Bundle/ProjectDescription.swift | highway-tool/highway | 1ff3fe4a18455c055371e17293ba2b855c6223ac | [
"MIT"
] | null | null | null | Sources/HighwayCore/Bundle/ProjectDescription.swift | highway-tool/highway | 1ff3fe4a18455c055371e17293ba2b855c6223ac | [
"MIT"
] | null | null | null | import Foundation
public struct ProjectDescription: Codable {
// MARK: - Properties
public let highways: [HighwayDescription]
public let credentials: Credentials?
// MARK: - Init
public init(highways: [HighwayDescription], credentials: Credentials?) {
self.highways = highways
self.credentials = credentials
}
// MARK: - Convenience
public func jsonString() throws -> String {
let coder = JSONEncoder()
let data = try coder.encode(self)
guard let string = String(data: data, encoding: .utf8) else {
throw "Failed to convert data to String."
}
return string
}
}
extension ProjectDescription {
public struct Credentials: Codable {
// MARK: - Properties
public let user: String
// MARK: - Init
public init(user: String) {
self.user = user
}
}
}
| 25.081081 | 76 | 0.596983 |
c65b9cd8e0995c8a31e8fa9479fdcf0030f30660 | 517 | asm | Assembly | programs/oeis/111/A111517.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/111/A111517.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/111/A111517.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A111517: Numbers n such that (7*n + 1)/2 is prime.
; 3,15,19,31,39,43,51,55,75,79,99,111,123,139,159,163,171,175,183,195,211,231,235,259,279,283,291,295,303,315,319,339,343,351,379,411,415,423,435,451,459,463,475
mov $2,$0
pow $2,2
add $2,6
mov $5,4
lpb $2
sub $2,1
mov $3,$1
add $1,13
sub $3,$5
max $3,0
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,1
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
lpe
sub $1,28
div $1,14
mul $1,4
add $1,3
mov $0,$1
| 19.148148 | 161 | 0.611219 |
091130680405d2c5ac4c77b639fb702671591cd9 | 1,621 | lua | Lua | mock/lua_files/call_delete_mock.lua | Aditya-Kapadiya/hera | a517a09f4175ea12d2f37a956b72d3df937d147d | [
"Apache-2.0"
] | null | null | null | mock/lua_files/call_delete_mock.lua | Aditya-Kapadiya/hera | a517a09f4175ea12d2f37a956b72d3df937d147d | [
"Apache-2.0"
] | null | null | null | mock/lua_files/call_delete_mock.lua | Aditya-Kapadiya/hera | a517a09f4175ea12d2f37a956b72d3df937d147d | [
"Apache-2.0"
] | null | null | null | local function get_upstream_socket()
local upsock = assert(ngx.socket.tcp());
local port = 8004;
local upok, uperr = upsock:connect("127.0.0.1", port);
if not upok then
ngx.log(ngx.ERR, "upstream connection failure " .. uperr);
return nil;
end
return upsock;
end
local function read_data(socket_obj, socket_obj_name)
local delim = ":";
local readline = socket_obj:receiveuntil(delim);
local size, _, _ = readline();
if(not size) then
ngx.log(ngx.ERR, "data recv failed to " .. socket_obj_name);
return nil, nil;
end
local data = socket_obj:receive( tonumber(size));
return size, data;
end
local function send_data(socket_obj, socket_obj_name, datasize, data)
local data_to_send = datasize .. ":" .. data;
local _, err = socket_obj:send(data_to_send);
if err then
ngx.log(ngx.ERR, "data send failed to " .. socket_obj_name);
return nil, 'err';
else
return 'ok', nil;
end
end
local upsock = get_upstream_socket();
ngx.req.read_body()
local p = ""
local args = ngx.req.get_uri_args()
local div = "heramockdiv"
for key, val in pairs(args) do
if type(val) == "table" then
p = p .. key .. div .. table.concat(val, ", ");
elseif val == "ip" then
p = p .. key .. div .. ngx.var.remote_addr;
else
p = p .. key .. div .. val;
end
end
local d = "Please provide the key to delete mock data";
local s;
if p and string.len(p) > 0 then
send_data(upsock, "upstream_request", string.len(p), p);
s, d = read_data(upsock, "upstream_response");
end
ngx.say(d); | 26.57377 | 69 | 0.62739 |
bf25e8395020cabaaa90db66c7375ed4ed1a9885 | 1,695 | ps1 | PowerShell | PowerJira/public/api-v2/component/Invoke-JiraCreateComponent.ps1 | ender2021/PowerJira | 3d859e50ad9db78040741d2d84eb93e0e1ccf19c | [
"MIT"
] | 5 | 2019-12-07T03:51:01.000Z | 2021-09-14T13:27:26.000Z | PowerJira/public/api-v2/component/Invoke-JiraCreateComponent.ps1 | ender2021/PowerJira | 3d859e50ad9db78040741d2d84eb93e0e1ccf19c | [
"MIT"
] | 1 | 2020-09-07T08:49:59.000Z | 2020-09-07T10:18:39.000Z | PowerJira/public/api-v2/component/Invoke-JiraCreateComponent.ps1 | ender2021/PowerJira | 3d859e50ad9db78040741d2d84eb93e0e1ccf19c | [
"MIT"
] | 2 | 2020-05-16T04:12:26.000Z | 2020-08-11T20:40:36.000Z | #https://developer.atlassian.com/cloud/jira/platform/rest/v2/#api-rest-api-2-component-post
function Invoke-JiraCreateComponent {
[CmdletBinding()]
param (
# The project Key of the project to add the component to
[Parameter(Mandatory,Position=0)]
[string]
$ProjectKey,
# The name for the component
[Parameter(Mandatory,Position=1)]
[ValidateLength(1,255)]
[string]
$Name,
# Description of the component
[Parameter(Position=2)]
[string]
$Description,
# The AccountID of the component lead
[Parameter(Position=3)]
[string]
$LeadAccountId,
# Use this parameter to determine the default assignee logic for issues with this component
[Parameter(Position=4)]
[ValidateSet("PROJECT_LEAD","COMPONENT_LEAD","UNASSIGNED","PROJECT_DEFAULT")]
[string]
$DefaultAssignee="PROJECT_DEFAULT",
# The JiraContext object to use for the request
[Parameter()]
[object]
$JiraContext
)
process {
$functionPath = "/rest/api/2/component"
$verb = "POST"
$body = New-PACRestMethodJsonBody @{
project = $ProjectKey
name = $Name
assigneeType = $DefaultAssignee
}
if($PSBoundParameters.ContainsKey("Description")){$body.Add("description",$Description)}
if($PSBoundParameters.ContainsKey("LeadAccountId")){$body.Add("leadAccountId",$LeadAccountId)}
$method = New-PACRestMethod $functionPath $verb $null $body
$method.Invoke($JiraContext)
}
} | 32.596154 | 103 | 0.59587 |
3108d3caedd4e7ebd0d62788cee74e387b42c29c | 23 | lua | Lua | gamesrv/src/app/db/init.lua | AddisKMud/ggApp | cd99ab1bd71d4b8017d0af512e0395d25128be5d | [
"MIT"
] | null | null | null | gamesrv/src/app/db/init.lua | AddisKMud/ggApp | cd99ab1bd71d4b8017d0af512e0395d25128be5d | [
"MIT"
] | null | null | null | gamesrv/src/app/db/init.lua | AddisKMud/ggApp | cd99ab1bd71d4b8017d0af512e0395d25128be5d | [
"MIT"
] | null | null | null | require "app.db.dbmgr"
| 11.5 | 22 | 0.73913 |
a5ea301dbbeffb7b5e7177ea80fe3cdf22ac03f9 | 1,037 | lua | Lua | day_08/solution.lua | juntuu/advent_of_code_2017 | 5bf7c24ba4e0f10f968cda45c973fe8f26d45c96 | [
"MIT"
] | null | null | null | day_08/solution.lua | juntuu/advent_of_code_2017 | 5bf7c24ba4e0f10f968cda45c973fe8f26d45c96 | [
"MIT"
] | null | null | null | day_08/solution.lua | juntuu/advent_of_code_2017 | 5bf7c24ba4e0f10f968cda45c973fe8f26d45c96 | [
"MIT"
] | null | null | null |
local ops = {
["inc"] = function(a, b) return a + b end,
["dec"] = function(a, b) return a - b end,
["<"] = function(a, b) return a < b end,
[">"] = function(a, b) return a > b end,
["<="] = function(a, b) return a <= b end,
[">="] = function(a, b) return a >= b end,
["=="] = function(a, b) return a == b end,
["!="] = function(a, b) return a ~= b end,
}
function run(regs, reg, op, val)
local fn = ops[op]
local rval = regs[reg]
if rval == nil then
rval = 0
end
return fn(rval, val)
end
local max_ever = 0
local registers = {}
local pattern = "(%a+) +(%a+) +([-]?%d+) +if +(%a+) +([!><=]+) +([-]?%d+)"
for line in io.lines() do
local reg, op, x, guard_reg, cmp, y = string.match(line, pattern)
if run(registers, guard_reg, cmp, tonumber(y)) then
local val = run(registers, reg, op, tonumber(x))
registers[reg] = val
if val > max_ever then
max_ever = val
end
end
end
local max = nil
for key, value in pairs(registers) do
if not max or max < value then
max = value
end
end
print(max)
print(max_ever)
| 23.568182 | 74 | 0.583414 |
018cc371e9eef6e29a2a727623637941b1ec5796 | 1,710 | dart | Dart | lib/swid/frontend/swidi/parser/swidiSimpleDeclarationParser.dart | Hydro-SDK/hydro-sdk | 00430ce9f58d97452a2876bfc7757c129f352b94 | [
"MIT"
] | 336 | 2020-11-20T03:48:40.000Z | 2022-03-31T15:49:11.000Z | lib/swid/frontend/swidi/parser/swidiSimpleDeclarationParser.dart | hydro-sdk/hydro-sdk | 2fa5535d2e02301c80af0be865a01a3ae799a381 | [
"MIT"
] | 418 | 2020-11-20T09:49:53.000Z | 2022-03-29T11:57:52.000Z | lib/swid/frontend/swidi/parser/swidiSimpleDeclarationParser.dart | Hydro-SDK/hydro-sdk | 00430ce9f58d97452a2876bfc7757c129f352b94 | [
"MIT"
] | 16 | 2020-11-20T06:18:44.000Z | 2022-02-07T15:18:06.000Z | import 'package:petitparser/petitparser.dart';
import 'package:hydro_sdk/swid/frontend/swidi/ast/swidiConst.dart';
import 'package:hydro_sdk/swid/frontend/swidi/ast/swidiDeclaration.dart';
import 'package:hydro_sdk/swid/frontend/swidi/ast/swidiEmptyConst.dart';
import 'package:hydro_sdk/swid/frontend/swidi/ast/swidiType.dart';
import 'package:hydro_sdk/swid/frontend/swidi/grammar/lexers/iDeclarationWithDefaultConstValueLexer.dart';
import 'package:hydro_sdk/swid/frontend/swidi/grammar/lexers/iSimpleDeclarationLexer.dart';
import 'package:hydro_sdk/swid/frontend/swidi/grammar/swidiGrammarDefinition.dart';
import 'package:hydro_sdk/swid/frontend/swidi/parser/parsers/iDeclarationWithDefaultConstValueParser.dart';
import 'package:hydro_sdk/swid/frontend/swidi/parser/parsers/iSimpleDeclarationParser.dart';
import 'package:hydro_sdk/swid/frontend/swidi/parser/swidiConstParser.dart';
import 'package:hydro_sdk/swid/frontend/swidi/parser/swidiTypeParser.dart';
mixin SwidiSimpleDeclarationParser
on SwidiGrammarDefinition, SwidiTypeParser, SwidiConstParser
implements
ISimpleDeclarationLexer,
IDeclarationWithDefaultConstValueLexer,
ISimpleDeclarationParser<Parser<SwidiDeclaration>>,
IDeclarationWithDefaultConstValueParser<Parser<SwidiDeclaration>> {
@override
Parser<SwidiDeclaration> simpleDeclaration() =>
super.simpleDeclaration().map((x) {
return SwidiDeclaration(
name: List.from(x).whereType<Token?>().first?.input ?? "",
type: List.from(x).whereType<SwidiType>().first,
defaultConstValue: SwidiConst.fromSwidiEmptyConst(
swidiEmptyConst: SwidiEmptyConst(),
),
);
});
}
| 50.294118 | 107 | 0.778947 |
a95b36a40bf6d0e0a7455f06ffa9481dd68f90de | 1,285 | sql | SQL | sql/enterprise/enterprise.sql | Huangyanx/-Employment-website | 55257292c5e1ccb28403d5bedb422cea533e3285 | [
"BSD-2-Clause"
] | null | null | null | sql/enterprise/enterprise.sql | Huangyanx/-Employment-website | 55257292c5e1ccb28403d5bedb422cea533e3285 | [
"BSD-2-Clause"
] | null | null | null | sql/enterprise/enterprise.sql | Huangyanx/-Employment-website | 55257292c5e1ccb28403d5bedb422cea533e3285 | [
"BSD-2-Clause"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: 2017-01-12 15:45:25
-- 服务器版本: 5.6.17
-- PHP Version: 5.5.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `yuanku_job`
--
-- --------------------------------------------------------
--
-- 表的结构 `enterprise`
--
CREATE TABLE IF NOT EXISTS `enterprise` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(50) NOT NULL,
`user_pwd` varchar(255) NOT NULL,
`add_time` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=20 ;
--
-- 转存表中的数据 `enterprise`
--
INSERT INTO `enterprise` (`id`, `user_name`, `user_pwd`, `add_time`) VALUES
(18, 'admin', 'e10adc3949ba59abbe56e057f20f883e', ''),
(19, '123456', 'e10adc3949ba59abbe56e057f20f883e', '1484120765');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 26.770833 | 75 | 0.680156 |
194deb585c604cb994a7b9c4872e9c19045496ce | 2,752 | lua | Lua | data/scripts/bufferedaction.lua | GuLiPing-Hz/Dontstarve_m | c2f12c8c2b79ed6d5762b130f5702d70bc020596 | [
"MIT"
] | 4 | 2019-11-18T08:13:29.000Z | 2021-04-02T00:08:35.000Z | data/scripts/bufferedaction.lua | GuLiPing-Hz/Dontstarve_m | c2f12c8c2b79ed6d5762b130f5702d70bc020596 | [
"MIT"
] | null | null | null | data/scripts/bufferedaction.lua | GuLiPing-Hz/Dontstarve_m | c2f12c8c2b79ed6d5762b130f5702d70bc020596 | [
"MIT"
] | 2 | 2019-08-04T07:12:15.000Z | 2019-12-24T03:34:16.000Z |
BufferedAction = Class(function(self, doer, target, action, invobject, pos, recipe, distance)
self.doer = doer
self.target = target
self.initialtargetowner = self.target and self.target.components.inventoryitem and self.target.components.inventoryitem.owner
self.action = action
self.invobject = invobject
self.pos = pos
self.onsuccess = {}
self.onfail = {}
self.recipe = recipe
self.options = {}
self.distance = distance or action.distance
end)
function BufferedAction:Do()
if self:IsValid() then
local success, reason = self.action.fn(self)
if success then
if self.invobject and self.invobject:IsValid() then
self.invobject:OnUsedAsItem(self.action)
end
self:Succeed()
else
self:Fail()
end
return success, reason
end
end
function BufferedAction:TestForStart()
if self:IsValid() then
if self.action.testfn then
local pass, reason = self.action.testfn(self)
return pass, reason
else
return true
end
end
end
function BufferedAction:IsValid()
return (not self.invobject or self.invobject:IsValid()) and
(not self.doer or self.doer:IsValid()) and
(not self.target or self.target:IsValid()) and
(not (self.validfn and not self.validfn())) and
(self.initialtargetowner == (self.target and self.target.components.inventoryitem and self.target.components.inventoryitem.owner))
end
function BufferedAction:GetActionString()
if self.doer and self.doer.ActionStringOverride then
local str = self.doer.ActionStringOverride(self.doer, self)
if str then
return str
end
end
local modifier = nil
if self.action.strfn then
modifier = self.action.strfn(self)
end
return GetActionString(self.action.id, modifier)
end
function BufferedAction:__tostring()
local str= self:GetActionString() .. " " .. tostring(self.target)
if self.invobject then
str = str.." With Inv:" .. tostring(self.invobject)
end
if self.recipe then
str = str .. " Recipe:" ..self.recipe
end
return str
end
function BufferedAction:AddFailAction(fn)
table.insert(self.onfail, fn)
end
function BufferedAction:AddSuccessAction(fn)
table.insert(self.onsuccess, fn)
end
function BufferedAction:Succeed()
for k,v in pairs(self.onsuccess) do
v()
end
self.onsuccess = {}
self.onfail = {}
end
function BufferedAction:Fail()
for k,v in pairs(self.onfail) do
v()
end
self.onsuccess = {}
self.onfail = {}
end
| 25.247706 | 141 | 0.635901 |
fb37a4ed16a6ae3acce64ed243b73331930d13ad | 10,364 | go | Go | main.go | arista-northwest/ConnectivityMonitorLogger | c043f22867bcc5906c0f0a2ceaa4bc5c59ff9cb0 | [
"Apache-2.0"
] | null | null | null | main.go | arista-northwest/ConnectivityMonitorLogger | c043f22867bcc5906c0f0a2ceaa4bc5c59ff9cb0 | [
"Apache-2.0"
] | null | null | null | main.go | arista-northwest/ConnectivityMonitorLogger | c043f22867bcc5906c0f0a2ceaa4bc5c59ff9cb0 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019 Arista Networks, Inc. All rights reserved.
// Arista Networks, Inc. Confidential and Proprietary.
package main
import (
"context"
"errors"
"flag"
"path"
"reflect"
"strings"
"time"
"log"
"github.com/arista-northwest/ConnectivityMonitorLogger/logger"
"github.com/aristanetworks/goarista/gnmi"
pb "github.com/openconfig/gnmi/proto/gnmi"
)
var (
cfg = &gnmi.Config{TLS: true}
subOpts = &gnmi.SubscribeOptions{}
query = "/Sysdb/connectivityMonitor/status/hostStatus"
eventLogger interface{}
rttBaselines = make(map[string]float32)
monitorMetrics = make(map[string]*monitorMetric)
triggerStates = make(map[string]*triggerState)
eosNative = flag.Bool("eos_native", false, "set to true if 'eos_native' is enabled under 'management api gnmi'")
interval = flag.Uint64("interval", 5, "Set to interval configured under 'monitor connectivity (default is 5")
triggerCount = flag.Uint("trigger_count", 3, "Number of events to trigger an alert (default is 3)")
rearmCount = flag.Uint("rearm_count", 2, "Number of events to rearm a previously triggered alert (default is 2)")
rttBaselineTrigger = flag.Uint("rtt_baseline_trigger", 10, "Sets a new baseline after N deviations from old baseline")
rttDeviationThreshold = flag.Uint64("rtt_deviation_threshold", 10, "Percent RTT deviation above or below baseline")
rttThreshold = flag.Float64("rtt_threshold", 0, "Absolute absolute value for RTT")
lossThreshold = flag.Uint64("loss_threshold", 0.0, "Perect of lost packets to tolerate")
// Certificate files.
insecure = flag.Bool("insecure", false, "use insecure GRPC connection.")
// caCert = flag.String("ca_crt", "", "CA certificate file. Used to verify server TLS certificate.")
// clientCert = flag.String("client_crt", "", "Client certificate file. Used for client certificate-based authentication.")
// clientKey = flag.String("client_key", "", "Client private key file. Used for client certificate-based authentication.")
// //insecureSkipVerify = flag.Bool("tls_skip_verify", false, "When set, CLI will not verify the server certificate during TLS handshake.")
logInit = logger.LogD("CONNECTIVITYMONITOR_INIT", logger.INFO, "Agent Initialized", "Agent has been initialized", logger.NoActionRequired, time.Duration(time.Second*10), 10)
logRttTrigger = logger.LogD("CONNECTIVITYMONITOR_RTT_TRIGGER", logger.NOTICE, "RTT triggered event on %s rtt:%.2fms threshold:%.2fms", "", logger.NoActionRequired, time.Duration(time.Second), 10)
logRttRearm = logger.LogD("CONNECTIVITYMONITOR_RTT_REARM", logger.NOTICE, "RTT rearmed event on %s rtt:%.2fms", "", logger.NoActionRequired, time.Duration(time.Second*10), 10)
logLossTrigger = logger.LogD("CONNECTIVITYMONITOR_LOSS_TRIGGER", logger.NOTICE, "Packet loss triggered event on %s loss:%d%% threshold:%d%%", "", logger.NoActionRequired, time.Duration(time.Second*10), 10)
loglossRearm = logger.LogD("CONNECTIVITYMONITOR_LOSS_REARM", logger.NOTICE, "Packet loss rearmed event on %s loss:%d%%", "", logger.NoActionRequired, time.Duration(time.Second*10), 10)
logRttBaseline = logger.LogD("CONNECTIVITYMONITOR_RTT_BASELINE", logger.NOTICE, "Setting new baseline on %s to %.2f was %.2f", "", logger.NoActionRequired, time.Duration(time.Second*10), 10)
)
type monitorMetric struct {
Timestamp string `alias:"timestamp"`
HostName string `alias:"hostName"`
VRF string `alias:"vrfName"`
IpAddr string `alias:"ipAddr"`
Interface string `alias:"interfaceName"`
Latency float32 `alias:"latency"`
Jitter float32 `alias:"jitter"`
PacketLoss uint64 `alias:"packetLoss"`
HTTPResponseTime float32 `alias:"httpResponseTime"`
}
const (
Armed = iota
Triggered
)
type triggerState struct {
current int32
offset uint
}
func (t *triggerState) trigger(max uint) bool {
if t.current == Triggered {
return false
}
t.offset += 1
if t.offset >= max {
t.current = Triggered
t.offset = 0
return true
}
return false
}
func (t *triggerState) rearm(max uint) bool {
if t.current == Armed {
return false
}
t.offset += 1
if t.offset >= max {
t.current = Armed
t.offset = 0
return true
}
return false
}
func init() {
flag.StringVar(&cfg.Addr, "address", "localhost:6030", "Address of the GNMI target to query.")
flag.StringVar(&cfg.Username, "username", "admin", "")
flag.StringVar(&cfg.Password, "password", "", "")
flag.StringVar(&cfg.CAFile, "cafile", "", "Path to server TLS certificate file")
flag.StringVar(&cfg.CertFile, "certfile", "", "Path to client TLS certificate file")
flag.StringVar(&cfg.KeyFile, "keyfile", "", "Path to client TLS private key file")
flag.BoolVar(&cfg.TLS, "tls", false, "Enable TLS")
logInit()
}
func main() {
flag.Parse()
var err error
subOpts.Paths = gnmi.SplitPaths([]string{query})
subOpts.StreamMode = "target_defined"
subOpts.Mode = "stream"
if *eosNative == true {
subOpts.Origin = "eos_native"
}
ctx := gnmi.NewContext(context.Background(), cfg)
client, err := gnmi.Dial(cfg)
if err != nil {
log.Fatalf("Failed to dial: %v", err)
}
respChan := make(chan *pb.SubscribeResponse, 10)
errChan := make(chan error, 10)
defer close(errChan)
go func() {
if err := gnmi.SubscribeErr(ctx, client, subOpts, respChan); err != nil {
errChan <- err
}
}()
firstPass := true
for {
select {
case resp, open := <-respChan:
if !open {
// will read the error from the channel later
continue
}
sync, err := collectResposes(resp)
if err != nil {
log.Fatal("Failed to collect responses: ", err)
}
if sync == true || firstPass == false {
firstPass = false
handleEvents(monitorMetrics)
}
case err := <-errChan:
log.Fatal(err)
case <-time.After(time.Second * time.Duration(*interval+1)):
// if there are no changes in the interval period to response will be sent.
// In this case assume the data has not changed
handleEvents(monitorMetrics)
}
}
}
func transitionTriggerState(key string, raise bool, trigger_count uint, rearm_count uint) bool {
if _, ok := triggerStates[key]; !ok {
triggerStates[key] = &triggerState{}
}
s := triggerStates[key]
switch raise {
case true:
return s.trigger(trigger_count)
case false:
return s.rearm(rearm_count)
}
return false
}
func collectResposes(response *pb.SubscribeResponse) (bool, error) {
switch resp := response.Response.(type) {
case *pb.SubscribeResponse_Error:
return false, errors.New(resp.Error.Message)
case *pb.SubscribeResponse_SyncResponse:
if !resp.SyncResponse {
return false, errors.New("initial sync failed")
}
return true, nil
case *pb.SubscribeResponse_Update:
timestamp := time.Unix(0, resp.Update.Timestamp).UTC().Format(time.RFC3339Nano)
prefix := gnmi.StrPath(resp.Update.Prefix)
for _, update := range resp.Update.Update {
p := path.Join(prefix, gnmi.StrPath(update.Path))
elems := strings.Split(p, "/")
// get key from path
key := elems[5]
// get last elem
last := elems[len(elems)-1]
field, ok := getMonitorMetricFieldByAlias(monitorMetric{}, last)
if ok != true {
continue
}
if _, ok := monitorMetrics[key]; !ok {
monitorMetrics[key] = &monitorMetric{
Timestamp: timestamp,
}
}
value, err := gnmi.ExtractValue(update)
if err != nil {
log.Printf("Failed to extract value: %s", err)
continue
}
err = setMonitorMetricFieldByName(monitorMetrics[key], field, value)
if err != nil {
log.Printf("Failed to set value: %s", err)
continue
}
}
}
return false, nil
}
func setMonitorMetricFieldByName(message *monitorMetric, field string, value interface{}) error {
f := reflect.ValueOf(message).Elem().FieldByName(field)
if f.IsValid() {
switch v := value.(type) {
case map[string]interface{}:
f.Set(reflect.ValueOf(v["value"]))
case float32, uint64, string:
f.Set(reflect.ValueOf(v))
default:
return errors.New("Failed to set field")
}
}
return nil
}
func getMonitorMetricFieldByAlias(message monitorMetric, alias string) (string, bool) {
t := reflect.TypeOf(monitorMetric{})
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
v := strings.Split(string(f.Tag), ":")[1]
v = v[1 : len(v)-1]
if v == alias {
return f.Name, true
}
}
return "", false
}
func handleEvents(metrics map[string]*monitorMetric) {
for k, m := range metrics {
setRTTBaseline(k, m.Latency)
logRTTEvent(k, m)
logLossEvent(k, m)
}
}
func logRTTEvent(k string, m *monitorMetric) {
if *rttThreshold == float64(0) {
return
}
if m.Latency >= float32(*rttThreshold) {
if transitionTriggerState(k+":rtt", true, *triggerCount, *rearmCount) {
logRttTrigger(m.HostName, m.Latency, *rttThreshold)
}
} else if m.Latency < float32(*rttThreshold) {
if transitionTriggerState(k+":rtt", false, *triggerCount, *rearmCount) {
logRttRearm(m.HostName, m.Latency)
}
}
}
func logLossEvent(k string, m *monitorMetric) {
if m.PacketLoss > *lossThreshold {
if transitionTriggerState(k+":loss", true, *triggerCount, *rearmCount) {
logLossTrigger(m.HostName, m.PacketLoss, lossThreshold)
}
} else if m.PacketLoss < *lossThreshold {
if transitionTriggerState(k+":loss", false, *triggerCount, *rearmCount) {
loglossRearm(m.HostName, m.PacketLoss)
}
}
}
func setRTTBaseline(k string, rtt float32) {
if _, ok := rttBaselines[k]; !ok {
logRttBaseline(k, rtt, float32(0))
rttBaselines[k] = rtt
}
baseline := rttBaselines[k]
hi := baseline * (1 + float32(*rttDeviationThreshold)/100)
lo := baseline * (1 - float32(*rttDeviationThreshold)/100)
if rtt <= lo {
transitionTriggerState(k+":rtt_baseline_hi", false, *rttBaselineTrigger, 1)
if transitionTriggerState(k+":rtt_baseline_lo", true, *rttBaselineTrigger, 0) {
logRttBaseline(k, rtt, baseline)
rttBaselines[k] = rtt
}
} else if rtt >= hi {
transitionTriggerState(k+":rtt_baseline_lo", false, *rttBaselineTrigger, 1)
if transitionTriggerState(k+":rtt_baseline_hi", true, *rttBaselineTrigger, 0) {
logRttBaseline(k, rtt, baseline)
rttBaselines[k] = rtt
}
} else {
transitionTriggerState(k+":rtt_baseline_lo", false, *rttBaselineTrigger, 1)
transitionTriggerState(k+":rtt_baseline_hi", false, *rttBaselineTrigger, 1)
}
log.Printf("%+v\n", triggerStates)
}
| 29.443182 | 206 | 0.693169 |
0496bf093b7d093553aec127c726476f2afa815d | 417 | java | Java | examples/sleuth-invoke2-example/src/main/java/com/ecfront/dew/example/sleuth/SleuthExampleApplication.java | tomdev2008/dew | 5cafce11247f7f44f1ec60ddf7bc7d776501c1c0 | [
"Apache-2.0"
] | null | null | null | examples/sleuth-invoke2-example/src/main/java/com/ecfront/dew/example/sleuth/SleuthExampleApplication.java | tomdev2008/dew | 5cafce11247f7f44f1ec60ddf7bc7d776501c1c0 | [
"Apache-2.0"
] | null | null | null | examples/sleuth-invoke2-example/src/main/java/com/ecfront/dew/example/sleuth/SleuthExampleApplication.java | tomdev2008/dew | 5cafce11247f7f44f1ec60ddf7bc7d776501c1c0 | [
"Apache-2.0"
] | 1 | 2020-11-27T07:17:10.000Z | 2020-11-27T07:17:10.000Z | package com.ecfront.dew.example.sleuth;
import com.ecfront.dew.core.DewCloudApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.builder.SpringApplicationBuilder;
public class SleuthExampleApplication extends DewCloudApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(SleuthExampleApplication.class).run(args);
}
}
| 27.8 | 79 | 0.803357 |
6b783b59e82dd6887c91369ce8512bb8f820afb8 | 2,627 | rs | Rust | 30_Cube/rust/src/game.rs | jnellis/basic-computer-games | 1ed0738aa7b6558c6ddf3e45ee226b6b4e43edb6 | [
"Unlicense"
] | null | null | null | 30_Cube/rust/src/game.rs | jnellis/basic-computer-games | 1ed0738aa7b6558c6ddf3e45ee226b6b4e43edb6 | [
"Unlicense"
] | null | null | null | 30_Cube/rust/src/game.rs | jnellis/basic-computer-games | 1ed0738aa7b6558c6ddf3e45ee226b6b4e43edb6 | [
"Unlicense"
] | null | null | null | use crate::util;
pub type Position = (u8, u8, u8);
pub struct Game {
wallet: usize,
bet: Option<usize>,
landmines: Vec<Position>,
player: Position,
}
impl Game {
pub fn new() -> Self {
Game {
wallet: 500,
bet: None,
landmines: util::get_landmines(),
player: (1, 1, 1),
}
}
pub fn play(&mut self) -> bool {
self.bet = self.get_bet();
let mut first_move = true;
let mut result = (false, "******BANG!******\nYOU LOSE");
loop {
let msg = if first_move {
first_move = false;
"ITS YOUR MOVE"
} else {
"NEXT MOVE"
};
let (ok, p) = self.ask_position(msg);
if ok {
if p == (3, 3, 3) {
result.0 = true;
result.1 = "CONGRATULATIONS!";
break;
} else if self.landmines.contains(&p) {
break;
} else {
self.player = p;
}
} else {
result.1 = "ILLEGAL MOVE\nYOU LOSE.";
break;
}
}
println!("{}", result.1);
self.calculate_wallet(result.0);
self.reset_game();
if self.wallet <= 0 {
println!("YOU ARE BROKE!");
return false;
}
return util::prompt_bool("DO YOU WANT TO TRY AGAIN?");
}
fn get_bet(&self) -> Option<usize> {
loop {
if util::prompt_bool("WANT TO MAKE A WAGER?") {
let b = util::prompt_number("HOW MUCH?");
if b != 0 && b <= self.wallet {
return Some(b);
} else {
println!("YOU CAN'T BET THAT!");
}
} else {
return None;
};
}
}
fn ask_position(&self, msg: &str) -> (bool, Position) {
if let Some(p) = util::prompt_position(msg, self.player) {
return (true, p);
}
return (false, (0, 0, 0));
}
fn calculate_wallet(&mut self, win: bool) {
if let Some(b) = self.bet {
if win {
self.wallet += b;
} else {
self.wallet -= b;
}
self.bet = None;
println!("YOU NOW HAVE {} DOLLARS", self.wallet);
}
}
fn reset_game(&mut self) {
self.player = (1, 1, 1);
self.landmines.clear();
self.landmines = util::get_landmines();
}
}
| 24.551402 | 66 | 0.411877 |
60efa0a52da4eb6d68a919786b44fd6f219c6b14 | 5,103 | cpp | C++ | login.cpp | Ji-Yuhang/maze | 4f07da92a15df007321882bcdfb7052cce10125e | [
"MIT"
] | 8 | 2018-11-30T18:43:22.000Z | 2021-06-17T11:28:36.000Z | login.cpp | Ji-Yuhang/maze | 4f07da92a15df007321882bcdfb7052cce10125e | [
"MIT"
] | null | null | null | login.cpp | Ji-Yuhang/maze | 4f07da92a15df007321882bcdfb7052cce10125e | [
"MIT"
] | 1 | 2017-12-07T11:52:26.000Z | 2017-12-07T11:52:26.000Z | #include "login.h"
#include "ui_login.h"
#include <QMessageBox>
Login::Login(QWidget *parent) :
QWidget(parent),
ui(new Ui::Login),
main_(0)
{
ui->setupUi(this);
bool bs = socket_.bind(4444);
// socket_.joinMulticastGroup(QHostAddress::AnyIPv4);
bool cs = connect(&socket_, SIGNAL(readyRead()), this, SLOT(onRead()));
QHostAddress local = getIP();
}
Login::~Login()
{
delete ui;
}
void Login::on_search_clicked()
{
// knownHosts_.clear();
QByteArray block;
QDataStream s(&block, QIODevice::WriteOnly);
s << QString("search");
socket_.writeDatagram(block,QHostAddress::Broadcast, 4444);
qDebug() <<"UDP send:" << block.size() << block;
}
void Login::on_create_clicked()
{
}
void Login::onRead()
{
qDebug() << "onRead UDP";
QHostAddress local = getIP();
while (socket_.hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(socket_.pendingDatagramSize());
QHostAddress address;
quint16 port;
socket_.readDatagram(datagram.data(), datagram.size(),&address, &port);
QDataStream s(&datagram, QIODevice::ReadOnly);
QString type;
s >> type;
qDebug() << "UDP read : "<< datagram.data() << type << address << port << (address.toIPv4Address() == local.toIPv4Address());
qDebug() << local<<local.toIPv4Address() << address.toIPv4Address() << (local.toIPv4Address() == address.toIPv4Address());
if (type == "search") {
QByteArray block;
QDataStream s(&block, QIODevice::WriteOnly);
s << QString("response");
socket_.writeDatagram(block,QHostAddress::Broadcast, 4444);
} else if (type == "response") {
if (!address.isLoopback()) {
if (!knownHosts_.contains(address.toIPv4Address())) {
knownHosts_.insert(address.toIPv4Address(), address);
while (ui->tableWidget->rowCount() > 0) {
ui->tableWidget->removeRow(0);
// ui->tableWidget->clear();
}
ui->tableWidget->setRowCount(knownHosts_.size());
QMap<quint32, QHostAddress>::iterator it = knownHosts_.begin();
for (int row = 0; it != knownHosts_.end(); ++it) {
{
QTableWidgetItem* item = new QTableWidgetItem;
item->setText(it.value().toString());
ui->tableWidget->setItem(row,0,item);
}
{
QTableWidgetItem* item = new QTableWidgetItem;
item->setText("坦克大战");
ui->tableWidget->setItem(row,1,item);
}
{
QTableWidgetItem* item = new QTableWidgetItem;
item->setText("未知");
ui->tableWidget->setItem(row,2,item);
}
{
QTableWidgetItem* item = new QTableWidgetItem;
item->setText("无");
ui->tableWidget->setItem(row,3,item);
}
{
QTableWidgetItem* item = new QTableWidgetItem;
item->setText("1 ms");
ui->tableWidget->setItem(row,4,item);
}
{
QPushButton* item = new QPushButton;
item->setText("加入游戏");
item->setProperty("ip", it.key());
connect(item, SIGNAL(clicked(bool)), this, SLOT(onJoin()));
ui->tableWidget->setCellWidget(row,5, item);
}
++row;
}
ui->tableWidget->resizeColumnsToContents();
}
}
}
}
// QByteArray block = socket_.readDatagram();
// qDebug() << "UDP read : "<< block;
}
void Login::onJoin()
{
QMessageBox::information(0,"success","加入游戏成功");
QPushButton* button = qobject_cast<QPushButton*>(sender());
main_ = new MainWindow;
serverIp_ = knownHosts_.value(button->property("ip").toInt());
main_->setServerIp(serverIp_, 4321);
this->hide();
main_->show();
}
// 获取ip地址,获取本机ip地址(其协议为ipv4的ip地址)
QHostAddress Login::getIP()
{
//QList是Qt中一个容器模板类,是一个数组指针?
QList<QHostAddress> list = QNetworkInterface::allAddresses();//此处的所有地址是指ipv4和ipv6的地址
//foreach (variable, container),此处为按照容器list中条目的顺序进行迭代
foreach (QHostAddress address, list) {
if(address.protocol() == QAbstractSocket::IPv4Protocol && !address.isLoopback() ) {
qDebug() << "allAddresses"<< address << address.toIPv4Address() << address.isLoopback();
return address;
}
}
return QHostAddress();
}
| 33.794702 | 133 | 0.505781 |
75481aff629ad98eef8b72496de1217ace217ca0 | 6,123 | c | C | src/graph.c | mstern98/Topologic-git | 5b6b9723ce955ae00c6ba4b413a5dfd4f0a57d0b | [
"MIT"
] | 6 | 2020-06-09T14:28:09.000Z | 2021-03-10T15:50:02.000Z | src/graph.c | mstern98/topologic-git | 5b6b9723ce955ae00c6ba4b413a5dfd4f0a57d0b | [
"MIT"
] | null | null | null | src/graph.c | mstern98/topologic-git | 5b6b9723ce955ae00c6ba4b413a5dfd4f0a57d0b | [
"MIT"
] | 1 | 2020-07-07T02:09:55.000Z | 2020-07-07T02:09:55.000Z | // SPDX-License-Identifier: MIT WITH bison-exception
// Copyright © 2020 Matthew Stern, Benjamin Michalowicz
#include "../include/topologic.h"
struct graph *graph_init(int max_state_changes, int snapshot_timestamp, int max_loop, unsigned int lvl_verbose, enum CONTEXT context, enum MEM_OPTION mem_option, enum REQUEST_FLAG request_flag)
{
topologic_debug("%s;max_state_chages %d;snapshot_timestamp %d;max_loop %d;lvl_verbose %d;context %d;mem_option %d", "graph_init", max_state_changes, snapshot_timestamp, max_loop, lvl_verbose, context, mem_option);
struct graph *graph = (struct graph *)malloc(sizeof(struct graph));
if (!graph)
{
topologic_debug("%s;%s;%p", "graph_init", "failed to malloc", (void *) NULL);
return NULL;
}
graph->max_state_changes = max_state_changes;
graph->max_loop = max_loop;
graph->snapshot_timestamp = snapshot_timestamp;
graph->request_flag = request_flag;
graph->lvl_verbose = lvl_verbose;
graph->context = context;
graph->state_count = 0;
graph->mem_option = mem_option;
graph->pause = 0;
graph->red_locked = 1;
graph->black_locked = 1;
graph->num_vertices = 0;
if (pthread_mutex_init(&graph->lock, NULL) < 0)
{
topologic_debug("%s;%s;%p", "graph_init", "failed to create lock", (void *) NULL);
goto free_graph;
}
if (pthread_cond_init(&graph->pause_cond, NULL) < 0)
{
topologic_debug("%s;%s;%p", "graph_init", "failed to create pause cond", (void *) NULL);
goto destroy_lock;
}
if (context != SINGLE)
{
if (pthread_mutex_init(&graph->color_lock, NULL) < 0)
{
topologic_debug("%s;%s;%p", "graph_init", "failed to create color lock", (void *) NULL);
goto destroy_pause_cond;
}
if (pthread_cond_init(&graph->red_fire, NULL) < 0)
{
topologic_debug("%s;%s;%p", "graph_init", "failed to create red fire cond", (void *) NULL);
goto destroy_color_lock;
}
if (pthread_cond_init(&graph->black_fire, NULL) < 0)
{
topologic_debug("%s;%s;%p", "graph_init", "failed to create black fire cond", (void *) NULL);
goto destroy_red_fire;
}
}
graph->vertices = init_avl();
if (!graph->vertices)
{
topologic_debug("%s;%s;%p", "graph_init", "failed to create avl", (void *) NULL);
goto destroy_black_fire;
}
graph->modify = init_stack();
if (!graph->modify)
{
topologic_debug("%s;%s;%p", "graph_init", "failed to create stack", (void *) NULL);
goto destroy_vertices;
}
graph->remove_edges = init_stack();
if (!graph->remove_edges)
{
topologic_debug("%s;%s;%p", "graph_init", "failed to create stack", (void *) NULL);
goto destroy_modify;
}
graph->remove_vertices = init_stack();
if (!graph->remove_vertices)
{
topologic_debug("%s;%s;%p", "graph_init", "failed to create stack", (void *) NULL);
goto destroy_remove_edges;
}
graph->start = init_stack();
if (!graph->start)
{
topologic_debug("%s;%s;%p", "graph_init", "failed to create stack", (void *) NULL);
goto destroy_remove_vertices;
}
graph->previous_color = RED;
graph->state = RED;
graph->red_vertex_count = 0;
graph->black_vertex_count = 0;
graph->print_flag = 0;
topologic_debug("%s;%s;%p", "graph_init", "success", graph);
return graph;
destroy_remove_vertices:
destroy_stack(graph->remove_vertices);
graph->remove_vertices = NULL;
destroy_remove_edges:
destroy_stack(graph->remove_edges);
graph->remove_edges = NULL;
destroy_modify:
destroy_stack(graph->modify);
graph->modify = NULL;
destroy_vertices:
destroy_avl(graph->vertices);
graph->vertices = NULL;
destroy_black_fire:
if (context != NONE)
pthread_cond_destroy(&graph->pause_cond);
destroy_red_fire:
if (context != NONE)
pthread_cond_destroy(&graph->pause_cond);
destroy_color_lock:
if (context != NONE)
pthread_mutex_destroy(&graph->color_lock);
destroy_pause_cond:
pthread_cond_destroy(&graph->pause_cond);
destroy_lock:
pthread_mutex_destroy(&graph->lock);
free_graph:
free(graph);
graph = NULL;
return NULL;
}
void destroy_graph_stack(struct stack *stack)
{
if (!stack)
return;
struct request *request = NULL;
while ((request = (struct request *)pop(stack)) != NULL)
{
destroy_request(request);
}
destroy_stack(stack);
stack = NULL;
}
void destroy_graph_avl(struct graph *graph, struct AVLTree *tree)
{
if (!tree)
return;
struct stack *tree_stack = init_stack();
if (!tree_stack)
return;
preorder(tree, tree_stack);
struct vertex *vertex = NULL;
while ((vertex = (struct vertex *)pop(tree_stack)) != NULL)
{
remove_vertex(graph, vertex);
}
destroy_stack(tree_stack);
tree_stack = NULL;
destroy_avl(tree);
tree = NULL;
}
int destroy_graph(struct graph *graph)
{
topologic_debug("%s;graph %p", "destroy_graph", graph);
if (!graph)
{
topologic_debug("%s;%s;%d", "destroy_graph", "invalid args", -1);
return -1;
}
graph->state = TERMINATE;
if (graph->red_vertex_count >= 0)
{
if (graph->context != SINGLE)
{
graph->red_locked = 0;
if (graph->red_vertex_count > 0)
pthread_cond_wait(&graph->red_fire, &graph->color_lock);
}
}
if (graph->black_vertex_count >= 0)
{
if (graph->context != SINGLE)
{
graph->black_locked = 0;
if (graph->black_vertex_count > 0)
pthread_cond_wait(&graph->black_fire, &graph->color_lock);
}
}
destroy_graph_avl(graph, graph->vertices);
graph->vertices = NULL;
destroy_graph_stack(graph->start);
graph->start = NULL;
destroy_graph_stack(graph->modify);
graph->modify = NULL;
destroy_graph_stack(graph->remove_edges);
graph->remove_edges = NULL;
destroy_graph_stack(graph->remove_vertices);
graph->remove_vertices = NULL;
pthread_mutex_destroy(&graph->lock);
pthread_cond_destroy(&graph->pause_cond);
graph->red_locked = 0;
graph->black_locked = 0;
free(graph);
graph = NULL;
topologic_debug("%s;%s;%d", "destroy_graph", "finished", 0);
return 0;
}
| 28.882075 | 215 | 0.660787 |
8a650aae726f2da143b83466aaa09469ca434caa | 573 | lua | Lua | build/generated/sources/zdoc/media/lua/shared/Library/RZSSexyTime.lua | cocolabs/pz-liquid-overhaul | 54d0a0ee8e5ef84e0e3be2333b89221356a324b9 | [
"MIT"
] | null | null | null | build/generated/sources/zdoc/media/lua/shared/Library/RZSSexyTime.lua | cocolabs/pz-liquid-overhaul | 54d0a0ee8e5ef84e0e3be2333b89221356a324b9 | [
"MIT"
] | 2 | 2021-07-07T20:55:51.000Z | 2021-07-09T04:31:12.000Z | build/generated/sources/zdoc/media/lua/shared/Library/RZSSexyTime.lua | cocolabs/pz-liquid-overhaul | 54d0a0ee8e5ef84e0e3be2333b89221356a324b9 | [
"MIT"
] | null | null | null | ---@class RZSSexyTime : zombie.randomizedWorld.randomizedZoneStory.RZSSexyTime
---@field private pantsMaleItems ArrayList|Unknown
---@field private pantsFemaleItems ArrayList|Unknown
---@field private topItems ArrayList|Unknown
---@field private shoesItems ArrayList|Unknown
RZSSexyTime = {}
---@private
---@param arg0 IsoMetaGrid.Zone
---@param arg1 boolean
---@param arg2 BaseVehicle
---@return void
function RZSSexyTime:addItemsOnGround(arg0, arg1, arg2) end
---@public
---@param arg0 IsoMetaGrid.Zone
---@return void
function RZSSexyTime:randomizeZoneStory(arg0) end
| 30.157895 | 78 | 0.783595 |
40cbeb25c0043c4e71bd8c713fee47d28413a150 | 2,219 | html | HTML | templates/event_manage.html | DongDong-123/sign_pro | 7bea6b562b64cb6d5282127d96ec77dd16fd9e20 | [
"Apache-2.0"
] | null | null | null | templates/event_manage.html | DongDong-123/sign_pro | 7bea6b562b64cb6d5282127d96ec77dd16fd9e20 | [
"Apache-2.0"
] | null | null | null | templates/event_manage.html | DongDong-123/sign_pro | 7bea6b562b64cb6d5282127d96ec77dd16fd9e20 | [
"Apache-2.0"
] | null | null | null | <html lang="en">
<head>
<meta charset="UTF-8">
<title>event</title>
<script type="text/javascript" src="/static/js/jquery-1.12.4.min.js"></script>
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/event_manage/">Guest Manage System</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="/event_manage/">发布会</a></li>
<li ><a href="/guest_manage/">嘉宾</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">{{user}}</a></li>
<li><a href="/logout/">退出</a></li>
</ul>
</div>
</div>
</nav>
<!-- 导航栏 end-->
<!-- 搜索 -->
<div class="page-header" style="padding-top: 30px;">
<div id="navbar" class="navbar-collapse collapse">
<form class="navbar-form" method="get" action="/search_name/">
<div class="form-group">
<input name="name" type="text" placeholder="名称" class="form-control">
</div>
<button type="submit" class="btn btn-success">搜索</button>
</form>
</div>
</div>
<!-- 搜索 end-->
<!-- 发布会列表 -->
<div class="container-fluid">
<div class="row" style="padding-top: 30px;">
<div class="col-md-12">
<table class="table table-striped">
<thead>
<tr>
<th>id</th><th>名称</th><th>状态</th><th>地址</th><th>时间</th><th>签到</th>
</tr>
</thead>
<tbody>
{% for event in eventlist %}
<tr>
<td>{{ event.id }}</td>
<td>{{ event.name }}</td>
<td>{{ event.status }}</td>
<td>{{ event.address }}</td>
<td>{{ event.start_time }}</td>
<td><a href="/sign_index/{{ event.id }}/" target="{{ event.id }}_blank">sign</a></td>
</tr><br>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<!-- 发布会列表 end-->
</body>
</html> | 29.586667 | 94 | 0.487156 |
fb5c88dd0b5617d58eb60669599b71a8277b2f70 | 652 | java | Java | core/src/main/java/com/holonplatform/core/internal/utils/CommonMessages.java | holon-platform/holon-core | 78f5a03b137bbc8c1b6e9acd53862a8cf1332b80 | [
"Apache-2.0"
] | 10 | 2017-10-05T14:00:21.000Z | 2021-07-19T12:25:37.000Z | core/src/main/java/com/holonplatform/core/internal/utils/CommonMessages.java | holon-platform/holon-core | 78f5a03b137bbc8c1b6e9acd53862a8cf1332b80 | [
"Apache-2.0"
] | 146 | 2017-10-03T13:00:45.000Z | 2021-07-04T04:49:11.000Z | core/src/main/java/com/holonplatform/core/internal/utils/CommonMessages.java | holon-platform/holon-core | 78f5a03b137bbc8c1b6e9acd53862a8cf1332b80 | [
"Apache-2.0"
] | 9 | 2018-01-21T21:35:58.000Z | 2021-07-19T12:25:48.000Z | package com.holonplatform.core.internal.utils;
import java.io.Serializable;
/**
* Common messages constants.
*/
public final class CommonMessages implements Serializable {
private static final long serialVersionUID = 738515982995552833L;
public static final String MSG_PROPERTY_NOT_NULL = "Property must be not null";
public static final String MSG_PROPERTY_NAME_NOT_NULL = "Property name must be not null";
public static final String MSG_PROPERTIES_NOT_NULL = "Properties must be not null";
/*
* Empty private constructor: this class is intended only to provide constants
* ad utility methods.
*/
private CommonMessages() {
}
}
| 27.166667 | 90 | 0.77454 |
78616400bccfcd65ffe5c255c595510edfc72d78 | 747 | dart | Dart | lib/feature/counter/domain/usecase/decrement.dart | MRAlifR/reminder | 4168de89606cc7d5487d992c278a98805068d236 | [
"MIT"
] | null | null | null | lib/feature/counter/domain/usecase/decrement.dart | MRAlifR/reminder | 4168de89606cc7d5487d992c278a98805068d236 | [
"MIT"
] | null | null | null | lib/feature/counter/domain/usecase/decrement.dart | MRAlifR/reminder | 4168de89606cc7d5487d992c278a98805068d236 | [
"MIT"
] | null | null | null | import 'package:dartz/dartz.dart';
import 'package:equatable/equatable.dart';
import 'package:injectable/injectable.dart';
import 'package:reminder/core/domain/failure.dart';
import 'package:reminder/core/domain/usecase.dart';
import 'package:reminder/feature/counter/domain/repository/counter_repo.dart';
@singleton
class Decrement implements UseCase<int, DecrementParam> {
final CounterRepo repository;
Decrement(this.repository);
@override
Future<Either<Failure, int>> call(DecrementParam params) async {
return repository.decrement(params.number);
}
}
class DecrementParam extends Equatable {
final int number;
const DecrementParam({
required this.number,
});
@override
List<Object?> get props => [number];
}
| 24.9 | 78 | 0.763052 |
9582c2debc2755c3d45d36e456c0174db13bd24a | 1,420 | swift | Swift | Sources/BasedClient/Queue/Based+Queue.swift | atelier-saulx/swift-based-client | 9e7c9f5f065d0f9561fa876cc8d95d220dd87213 | [
"MIT"
] | null | null | null | Sources/BasedClient/Queue/Based+Queue.swift | atelier-saulx/swift-based-client | 9e7c9f5f065d0f9561fa876cc8d95d220dd87213 | [
"MIT"
] | null | null | null | Sources/BasedClient/Queue/Based+Queue.swift | atelier-saulx/swift-based-client | 9e7c9f5f065d0f9561fa876cc8d95d220dd87213 | [
"MIT"
] | null | null | null | //
// File.swift
//
//
// Created by Alexander van der Werff on 29/09/2021.
//
import Foundation
extension Based {
func addToQueue(message: Message) {
if let message = message as? SubscriptionMessage, message.requestType == .unsubscribe
|| message.requestType == .subscription
|| message.requestType == .sendSubscriptionData
|| message.requestType == .getSubscription {
queueManager.dispatch(item: { [weak self] in
self?.subscriptionQueue.append(message)
}, cancelable: false)
} else {
queueManager.dispatch(item: { [weak self] in
self?.queue.append(message)
}, cancelable: false)
}
if socket.connected {
drainQueue()
}
}
func drainQueue() {
guard socket.connected && (!queue.isEmpty || !subscriptionQueue.isEmpty) else { return }
queueManager.dispatch(item: { [weak self] in
guard let self = self else { return }
let messages = (self.queue + self.subscriptionQueue).map { $0.codable }
self.queue = []
self.subscriptionQueue = []
let json = try! JSONEncoder().encode(messages)
self.socket.send(message: .data(json))
}, cancelable: true)
}
}
| 28.979592 | 96 | 0.535915 |
e8175abdc074bd9615df20e65a881e867bfd06b9 | 845 | cpp | C++ | Homework/RPNCalculator/RPNCalculator/code/Operand.cpp | benjaminmao123/PCC_CS003A | 0339d83ebab7536952644517a99dc46702035b2b | [
"MIT"
] | null | null | null | Homework/RPNCalculator/RPNCalculator/code/Operand.cpp | benjaminmao123/PCC_CS003A | 0339d83ebab7536952644517a99dc46702035b2b | [
"MIT"
] | null | null | null | Homework/RPNCalculator/RPNCalculator/code/Operand.cpp | benjaminmao123/PCC_CS003A | 0339d83ebab7536952644517a99dc46702035b2b | [
"MIT"
] | null | null | null | /*
* Author: Benjamin Mao
* Project: RPN
* Purpose: Serves as the operand
* of the expression.
*
* Notes: None.
*/
#include <string>
#include "Operand.h"
/*
@summary: Overloaded constructor that takes
initializes value with a given value.
@param <double value>: Default value of 0 if nothing
is entered.
*/
Operand::Operand(double value)
: value(value)
{
TokenString(std::to_string(value));
}
/*
@summary: Simply returns the value of the operand.
@return <double>: Returns value member.
*/
double Operand::Evaluate()
{
return value;
}
/*
@summary: Getter function for the value.
@return <double>: Returns value member.
*/
double Operand::Value() const
{
return value;
}
/*
@summary: Setter for value.
@param <double value>: Double to set value to.
*/
void Operand::Value(double value)
{
this->value = value;
}
| 15.089286 | 53 | 0.684024 |
398344cca4484aa31ec3908c735642f901e9aac2 | 1,483 | sql | SQL | schema.sql | Gelbpunkt/idlebench | fe370f9fa6335cf738a91ca818638aedf0cf1ba3 | [
"Apache-2.0"
] | null | null | null | schema.sql | Gelbpunkt/idlebench | fe370f9fa6335cf738a91ca818638aedf0cf1ba3 | [
"Apache-2.0"
] | null | null | null | schema.sql | Gelbpunkt/idlebench | fe370f9fa6335cf738a91ca818638aedf0cf1ba3 | [
"Apache-2.0"
] | 4 | 2020-08-16T22:23:42.000Z | 2020-08-17T20:15:33.000Z | CREATE TYPE public.rgba AS (
red integer,
green integer,
blue integer,
alpha real
);
CREATE TABLE public.profile (
"user" bigint NOT NULL,
name character varying(20),
money bigint,
xp integer,
pvpwins bigint DEFAULT 0 NOT NULL,
money_booster bigint DEFAULT 0,
time_booster bigint DEFAULT 0,
luck_booster bigint DEFAULT 0,
marriage bigint DEFAULT 0,
background character varying(60) DEFAULT 0,
guild bigint DEFAULT 0,
class character varying(50)[] DEFAULT '{"No Class","No Class"}'::character varying[],
deaths bigint DEFAULT 0,
completed bigint DEFAULT 0,
lovescore bigint DEFAULT 0 NOT NULL,
guildrank character varying(20) DEFAULT 'Member'::character varying,
backgrounds text[],
puzzles bigint DEFAULT 0,
atkmultiply numeric DEFAULT 1.0,
defmultiply numeric DEFAULT 1.0,
crates_common bigint DEFAULT 0,
crates_uncommon bigint DEFAULT 0,
crates_rare bigint DEFAULT 0,
crates_magic bigint DEFAULT 0,
crates_legendary bigint DEFAULT 0,
luck numeric DEFAULT 1.0,
god character varying(50) DEFAULT NULL::character varying,
favor bigint DEFAULT 0,
race character varying(30) DEFAULT 'Human'::character varying,
cv bigint DEFAULT '-1'::integer,
reset_points bigint DEFAULT 2 NOT NULL,
chocolates integer DEFAULT 0,
trickortreat bigint DEFAULT 0,
eastereggs bigint DEFAULT 0,
colour public.rgba DEFAULT '(0,0,0,1)'::public.rgba
);
| 32.955556 | 89 | 0.709373 |
c30880e73833b16a9a4a94bb4213ec019535698a | 241 | lua | Lua | examples/platformer/premake4.lua | YeyaSwizaw/teabag | 20a44414a6cf628426b17651f59d92c4455f312f | [
"Apache-2.0"
] | null | null | null | examples/platformer/premake4.lua | YeyaSwizaw/teabag | 20a44414a6cf628426b17651f59d92c4455f312f | [
"Apache-2.0"
] | null | null | null | examples/platformer/premake4.lua | YeyaSwizaw/teabag | 20a44414a6cf628426b17651f59d92c4455f312f | [
"Apache-2.0"
] | null | null | null | project "platformer"
kind "ConsoleApp"
language "C++"
files { "src/**" }
links { "teabag", "sfml-system", "sfml-window", "sfml-graphics" }
libdirs { "../.." }
includedirs { "." }
objdir "build/test/obj"
buildoptions { "-std=c++1y" }
| 24.1 | 66 | 0.60166 |
573521fee7da652d95ec47adbf01023356fe1b2b | 3,630 | h | C | shore/shore-kits/include/dora/dkey_ranges_map.h | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 3 | 2018-01-25T00:51:56.000Z | 2022-01-07T15:09:38.000Z | shore/shore-kits/include/dora/dkey_ranges_map.h | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 1 | 2020-06-23T08:29:09.000Z | 2020-06-24T12:11:47.000Z | shore/shore-kits/include/dora/dkey_ranges_map.h | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 3 | 2018-06-08T08:36:27.000Z | 2021-12-26T20:36:16.000Z | /* -*- mode:C++; c-basic-offset:4 -*-
Shore-kits -- Benchmark implementations for Shore-MT
Copyright (c) 2007-2009
Data Intensive Applications and Systems Labaratory (DIAS)
Ecole Polytechnique Federale de Lausanne
All Rights Reserved.
Permission to use, copy, modify and distribute this software and
its documentation is hereby granted, provided that both the
copyright notice and this permission notice appear in all copies of
the software, derivative works or modified versions, and any
portions thereof, and that both notices appear in supporting
documentation.
This code 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. THE AUTHORS
DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER
RESULTING FROM THE USE OF THIS SOFTWARE.
*/
/** @file: dkey_ranges_map.h
*
* @brief: Wrapper of the key_ranges_map, used by DORA
*
* @date: Aug 2010
*
* @author: Ippokratis Pandis (ipandis)
* @author: Pinar Tozun (pinar)
* @author: Ryan Johnson (ryanjohn)
*/
#ifndef __DORA_DKEY_RANGES_MAP_H
#define __DORA_DKEY_RANGES_MAP_H
#include "sm_vas.h"
#include "util.h"
#include "dora/dora_error.h"
#include "dora/common.h"
#include "sm/shore/shore_env.h"
#include "sm/shore/shore_table.h"
using namespace std;
using namespace shore;
ENTER_NAMESPACE(dora);
/********************************************************************
*
* @class: dkey_ranges_map
*
* @brief: Thin wrapper of the key_ranges_map
*
* @note: The key_ranges_map maps char* to lpid_t. We use the lpid_t.page
* (which is a uint4_t) as the partition id.
*
********************************************************************/
class dkey_ranges_map
{
private:
bool _isplp;
key_ranges_map* _rmap;
sinfo_s _sinfo;
public:
// There are two constructors:
// One used by plain DORA, which is a main-memory data structure
// One used by PLP, which is a persistently stored range map
dkey_ranges_map(const stid_t& stid,
const cvec_t& minKeyCV,
const cvec_t& maxKeyCV,
const uint numParts);
dkey_ranges_map(const stid_t& stid,key_ranges_map* pkrm);
~dkey_ranges_map();
// Get the partition id for the given key, which is unscrambled
inline w_rc_t get_partition(const cvec_t& cvkey, lpid_t& lpid) {
return(_rmap->getPartitionByUnscrambledKey(_sinfo,cvkey,lpid));
}
w_rc_t get_all_partitions(vector<lpid_t>& pidVec);
// RangeMap maintenance
w_rc_t add_partition(const cvec_t& key, lpid_t& lpid);
w_rc_t delete_partition(const lpid_t& lpid);
// Returns true if they are same
bool is_same(const dkey_ranges_map& drm);
private:
// Not allowed
dkey_ranges_map();
}; // EOF: dkey_ranges_map
/******************************************************************
*
* @class: rangemap_smt_t
*
* @brief: An smthread inherited class that it is used just for
* accessing the key_range_map of a specific store
*
******************************************************************/
class rangemap_smt_t : public thread_t
{
private:
ShoreEnv* _env;
table_desc_t* _table;
uint _dtype;
public:
dkey_ranges_map* _drm;
w_rc_t _rc;
rangemap_smt_t(ShoreEnv* env, table_desc_t* tabledesc, uint dtype);
~rangemap_smt_t();
void work();
}; // EOF: rangemap_smt_t
EXIT_NAMESPACE(dora);
#endif // __DORA_DKEY_RANGES_MAP_H
| 24.693878 | 74 | 0.639394 |
be706dfaa14e1d446c7ab19c1b1048e60bd49e35 | 827 | swift | Swift | Sources/Sources/Layers/Managers/HelperFunctions/WWHelperFunctions.swift | devMEremenko/WWDC | 1a6108efa8d80c91059dfa395983d6856d28c82d | [
"Unlicense"
] | 3 | 2018-03-28T12:06:26.000Z | 2018-10-09T19:52:55.000Z | Sources/Sources/Layers/Managers/HelperFunctions/WWHelperFunctions.swift | devMEremenko/WWDC | 1a6108efa8d80c91059dfa395983d6856d28c82d | [
"Unlicense"
] | null | null | null | Sources/Sources/Layers/Managers/HelperFunctions/WWHelperFunctions.swift | devMEremenko/WWDC | 1a6108efa8d80c91059dfa395983d6856d28c82d | [
"Unlicense"
] | null | null | null | //
// WWHelperFunctions.swift
// WWDC
//
// Created by Maxim Eremenko on 3/25/17.
// Copyright © 2017 Maxim Eremenko. All rights reserved.
//
import UIKit
func kScreenHeight() -> CGFloat {
return kScreenSize().height
}
func kScreenWidth() -> CGFloat {
return kScreenSize().width
}
func kScreenSize() -> CGSize {
return CGSize(width: 375, height: 667)
}
typealias CodeBlock = ((()->Void)?)
func DispatchBlockToMainQueue(block: CodeBlock) {
if Thread.isMainThread {
block?()
} else {
DispatchQueue.main.async {
block?()
}
}
}
func DispatchBlockAfter(delay: Double, block: CodeBlock) {
let deadline = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: deadline) {
DispatchBlockToMainQueue(block: block)
}
}
| 18.377778 | 58 | 0.636034 |
4e9cdff0b038197b9e58b5f9aaca3016ec61e7e6 | 3,024 | ps1 | PowerShell | AzureADApplicationRegistration/functions/Add-AzureADApp.ps1 | hmcts/vh-ps-modules | 4979842dd58450000d945e009021772765912ac0 | [
"MIT"
] | 1 | 2019-03-06T14:30:04.000Z | 2019-03-06T14:30:04.000Z | AzureADApplicationRegistration/functions/Add-AzureADApp.ps1 | hmcts/vh-ps-modules | 4979842dd58450000d945e009021772765912ac0 | [
"MIT"
] | 3 | 2018-10-05T16:11:25.000Z | 2019-04-05T13:24:46.000Z | AzureADApplicationRegistration/functions/Add-AzureADApp.ps1 | hmcts/vh-ps-modules | 4979842dd58450000d945e009021772765912ac0 | [
"MIT"
] | 1 | 2021-04-10T23:05:17.000Z | 2021-04-10T23:05:17.000Z | function Add-AzureADApp {
[CmdletBinding()]
[OutputType([Hashtable])]
param (
[String]
[Parameter(Mandatory)]
$AADAppName,
[String]
$identifierUrisPrefix,
[String]
[Parameter(Mandatory)]
$AzureKeyVaultName
)
# Add ID and Replay urls
$AADAppNameOriginal = $AADAppName.ToLower()
$AADAppName = $AADAppNameOriginal -replace '-', '_'
$AADAppNameForId = $AADAppName.ToLower() -replace '_', '-'
$AADAppIdentifierUris = "https://" + $identifierUrisPrefix + (([Guid]::NewGuid()).guid)
$AADAppReplyUrls = "https://" + $AADAppNameOriginal
# Create empty hash table
$HashTable = @{}
## Register Azure AD App
# Check if the app already exists by comparing name and app ID URI stored in Azure Key vault.
if ($AADAppName -eq (Get-AzureADApplication -SearchString $AADAppName).DisplayName `
-and (Get-AzureADApplication -SearchString $AADAppName).IdentifierUris `
-contains (Get-AzureKeyVaultSecret -ErrorAction Stop -VaultName $AzureKeyVaultName `
-Name ((Remove-EnvFromString -StringWithEnv $AADAppNameForId) + "IdentifierUris") ).SecretValueText) {
Write-Verbose "Application $AADAppName found"
# Get App and App's SP
$AADApp = Get-AzureADApplication -SearchString $AADAppName
if (0 -eq $AzureTenantIdSecondary -and 0 -eq $AzureAdAppIdSecondary -and 0 -eq $AzureAdAppCertificateThumbprintSecondary) {
# Get service principal
$AADAppSP = Get-AzureADServicePrincipal -SearchString $AADAppName
# Add AD App's SP to hash table
$HashTable.Add("appspobjectid", $AADAppSP.ObjectId)
}
# Add details to hash table
$HashTable.Add("appname", $AADAppNameForId)
# Add App's ID to hash table
$HashTable.Add("appid", $AADApp.AppId)
# Add App's IdentifierUris to hash table
$HashTable.Add("identifieruris", $AADApp.IdentifierUris[0])
}
else {
# Create AAD App
$AADApp = New-AzureADApplication -DisplayName $AADAppName -IdentifierUris $AADAppIdentifierUris -ReplyUrls $AADAppReplyUrls
# Add App name to hash table
$HashTable.Add("appname", $AADAppNameForId)
# Add App's ID to hast table
$HashTable.Add("appid", $AADApp.AppId)
# Add App's IdentifierUris to hash table
$HashTable.Add("identifieruris", $AADApp.IdentifierUris[0])
if (0 -eq $AzureTenantIdSecondary -and 0 -eq $AzureAdAppIdSecondary -and 0 -eq $AzureAdAppCertificateThumbprintSecondary) {
# Create SP for AAD App
$AADAppSP = New-AzureADServicePrincipal -AppId $AADApp.AppId
# Add AD App's SP to hash table
$HashTable.Add("appspobjectid", $AADAppSP.ObjectId)
}
# Create key for AAD App
$AADAppKey = Add-AzureADAppKey -AADAppName $AADAppNameForId
$HashTable.Add("key", $AADAppKey)
}
return $HashTable
} | 42 | 131 | 0.64418 |
881032750a750cc8d2074f9e3d28c204aa0382e2 | 52,297 | cpp | C++ | test/function/entry.cpp | Manjaka13/stumpless | 39635e6afa3ad2f2c7ff2d7cd3caebc56df110dd | [
"Apache-2.0"
] | 2 | 2020-09-17T18:07:53.000Z | 2020-09-17T21:24:30.000Z | test/function/entry.cpp | Manjaka13/stumpless | 39635e6afa3ad2f2c7ff2d7cd3caebc56df110dd | [
"Apache-2.0"
] | null | null | null | test/function/entry.cpp | Manjaka13/stumpless | 39635e6afa3ad2f2c7ff2d7cd3caebc56df110dd | [
"Apache-2.0"
] | null | null | null | // SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2018-2020 Joel E. Anderson
*
* 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 <gmock/gmock.h>
#include <gtest/gtest.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stumpless.h>
#include "test/helper/assert.hpp"
#include "test/helper/memory_allocation.hpp"
using::testing::HasSubstr;
namespace {
class EntryTest : public::testing::Test {
protected:
const char *basic_app_name = "basic-app-name";
const char *basic_msgid = "basic-msgid";
const char *basic_message = "basic message";
struct stumpless_entry *basic_entry;
const char *element_1_name = "basic-element";
struct stumpless_element *element_1;
const char *element_2_name = "basic-element-2";
struct stumpless_element *element_2;
const char *param_1_1_name = "basic-param";
const char *param_1_1_value = "basic-value";
struct stumpless_param *param_1_1;
virtual void
SetUp( void ) {
basic_entry = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
basic_app_name,
basic_msgid,
basic_message );
element_1 = stumpless_new_element( element_1_name );
stumpless_add_element( basic_entry, element_1 );
param_1_1 = stumpless_new_param( param_1_1_name, param_1_1_value );
stumpless_add_param( element_1, param_1_1 );
element_2 = stumpless_new_element( element_2_name );
stumpless_add_element( basic_entry, element_2 );
// cause a failure so that memory allocation tests will still have an
// error that they can return
stumpless_new_element( NULL );
}
virtual void
TearDown( void ){
stumpless_destroy_entry_and_contents( basic_entry );
}
};
TEST_F( EntryTest, AddElement ) {
struct stumpless_entry *entry;
struct stumpless_element *element;
element = stumpless_new_element( "test-new-element" );
ASSERT_NOT_NULL( element );
EXPECT_EQ( NULL, stumpless_get_error( ) );
entry = stumpless_add_element( basic_entry, element );
EXPECT_EQ( NULL, stumpless_get_error( ) );
ASSERT_NOT_NULL( entry );
EXPECT_EQ( basic_entry, entry );
}
TEST_F( EntryTest, AddDuplicateElement ) {
struct stumpless_element *duplicate_element;
size_t original_element_count;
const struct stumpless_entry *result;
const struct stumpless_error *error;
original_element_count = basic_entry->element_count;
duplicate_element = stumpless_new_element( element_1_name );
EXPECT_NO_ERROR;
ASSERT_NOT_NULL( duplicate_element );
result = stumpless_add_element( basic_entry, duplicate_element );
EXPECT_ERROR_ID_EQ( STUMPLESS_DUPLICATE_ELEMENT );
EXPECT_NULL( result );
EXPECT_EQ( basic_entry->element_count, original_element_count );
stumpless_destroy_element_only( duplicate_element );
}
TEST_F( EntryTest, AddElementMemoryFailure ) {
struct stumpless_entry *entry;
struct stumpless_element *element;
const struct stumpless_error *error;
void * (*set_realloc_result)(void *, size_t);
element = stumpless_new_element( "test-memory-failure" );
ASSERT_NOT_NULL( element );
EXPECT_EQ( NULL, stumpless_get_error( ) );
set_realloc_result = stumpless_set_realloc( REALLOC_FAIL );
ASSERT_NOT_NULL( set_realloc_result );
entry = stumpless_add_element( basic_entry, element );
EXPECT_EQ( NULL, entry );
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
set_realloc_result = stumpless_set_realloc( realloc );
EXPECT_TRUE( set_realloc_result == realloc );
}
TEST_F( EntryTest, AddNewElement ) {
size_t original_element_count;
const struct stumpless_entry *result;
original_element_count = basic_entry->element_count;
result = stumpless_add_new_element( basic_entry, "new-name" );
EXPECT_NO_ERROR;
EXPECT_EQ( result, basic_entry );
EXPECT_EQ( basic_entry->element_count, original_element_count + 1 );
}
TEST_F( EntryTest, AddNewElementNullName ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_add_new_element( basic_entry, NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST_F( EntryTest, AddNewParam ) {
const struct stumpless_entry *result;
const struct stumpless_param *new_param;
result = stumpless_add_new_param_to_entry( basic_entry,
element_1_name,
"new-param-name",
"new-param-value" );
EXPECT_NO_ERROR;
EXPECT_EQ( result, basic_entry );
new_param = stumpless_get_param_by_name( element_1, "new-param-name" );
EXPECT_NO_ERROR;
EXPECT_TRUE( new_param != NULL );
}
TEST_F( EntryTest, AddNewParamAndNewElement ) {
const struct stumpless_entry *result;
struct stumpless_element *new_element;
const struct stumpless_param *new_param;
result = stumpless_add_new_param_to_entry( basic_entry,
"new-element-name",
"new-param-name",
"new-param-value" );
EXPECT_NO_ERROR;
EXPECT_EQ( result, basic_entry );
new_element = stumpless_get_element_by_name( basic_entry, "new-element-name" );
EXPECT_NO_ERROR;
EXPECT_TRUE( new_element != NULL );
EXPECT_EQ( stumpless_get_param_count( new_element ), 1 );
new_param = stumpless_get_param_by_name( new_element, "new-param-name" );
EXPECT_NO_ERROR;
EXPECT_TRUE( new_param != NULL );
}
TEST_F( EntryTest, AddNewParamAndNewElementMallocFailure ) {
void * (*set_malloc_result)(size_t);
const struct stumpless_entry *result;
const struct stumpless_error *error;
// create the internal error struct
stumpless_get_element_name( NULL );
set_malloc_result = stumpless_set_malloc( MALLOC_FAIL );
ASSERT_NOT_NULL( set_malloc_result );
result = stumpless_add_new_param_to_entry( basic_entry,
"new-element-name",
"new-param-name",
"new-param-value" );
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
EXPECT_NULL( result );
set_malloc_result = stumpless_set_malloc( malloc );
EXPECT_TRUE( set_malloc_result == malloc );
}
TEST_F( EntryTest, AddNewParamMallocFailure ) {
void * (*set_malloc_result)(size_t);
const struct stumpless_entry *result;
const struct stumpless_error *error;
// create the internal error struct
stumpless_get_element_name( NULL );
set_malloc_result = stumpless_set_malloc( MALLOC_FAIL );
ASSERT_NOT_NULL( set_malloc_result );
result = stumpless_add_new_param_to_entry( basic_entry,
element_1_name,
"new-param-name",
"new-param-value" );
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
EXPECT_NULL( result );
set_malloc_result = stumpless_set_malloc( malloc );
EXPECT_TRUE( set_malloc_result == malloc );
}
TEST_F( EntryTest, AddNewParamNullElementName ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_add_new_param_to_entry( basic_entry,
NULL,
"new-param-name",
"new-param-value" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST_F( EntryTest, AddNullElement ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_add_element( basic_entry, NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
ASSERT_TRUE( result == NULL );
}
TEST_F( EntryTest, AddTwoElements ) {
struct stumpless_entry *entry;
struct stumpless_element *element1;
struct stumpless_element *element2;
element1 = stumpless_new_element( "test-new-element-1" );
ASSERT_NOT_NULL( element1 );
EXPECT_NO_ERROR;
entry = stumpless_add_element( basic_entry, element1 );
EXPECT_NO_ERROR;
ASSERT_NOT_NULL( entry );
EXPECT_EQ( basic_entry, entry );
element2 = stumpless_new_element( "test-new-element-2" );
ASSERT_NOT_NULL( element2 );
EXPECT_EQ( NULL, stumpless_get_error( ) );
entry = stumpless_add_element( basic_entry, element2 );
EXPECT_NO_ERROR;
ASSERT_NOT_NULL( entry );
EXPECT_EQ( basic_entry, entry );
}
TEST_F( EntryTest, Copy ) {
const struct stumpless_entry *result;
result = stumpless_copy_entry( basic_entry );
EXPECT_NO_ERROR;
EXPECT_NE( result, basic_entry );
}
TEST_F( EntryTest, CopyMallocFailure ) {
void * (*set_malloc_result)(size_t);
const struct stumpless_entry *result;
const struct stumpless_error *error;
// create the internal error struct
stumpless_get_element_name( NULL );
set_malloc_result = stumpless_set_malloc( MALLOC_FAIL );
ASSERT_NOT_NULL( set_malloc_result );
result = stumpless_copy_entry( basic_entry );
EXPECT_NULL( result );
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
set_malloc_result = stumpless_set_malloc( malloc );
EXPECT_TRUE( set_malloc_result == malloc );
}
TEST_F( EntryTest, CopyMallocFailureOnElementName ) {
void * (*set_malloc_result)(size_t);
const struct stumpless_entry *result;
const struct stumpless_error *error;
// create the internal error struct
stumpless_get_element_name( NULL );
set_malloc_result = stumpless_set_malloc( MALLOC_FAIL_ON_SIZE( 14 ) );
ASSERT_NOT_NULL( set_malloc_result );
result = stumpless_copy_entry( basic_entry );
EXPECT_NULL( result );
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
set_malloc_result = stumpless_set_malloc( malloc );
EXPECT_TRUE( set_malloc_result == malloc );
}
TEST_F( EntryTest, CopyReallocFailure ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
void * (*set_realloc_result)(void *, size_t);
// create the internal error struct
stumpless_get_element_name( NULL );
set_realloc_result = stumpless_set_realloc( REALLOC_FAIL );
ASSERT_NOT_NULL( set_realloc_result );
result = stumpless_copy_entry( basic_entry );
if( !result ) {
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
} else {
EXPECT_NO_ERROR;
EXPECT_NE( result, basic_entry );
stumpless_destroy_entry_and_contents( result );
}
stumpless_set_realloc( realloc );
}
TEST_F( EntryTest, GetAppName ) {
const char *result;
result = stumpless_get_entry_app_name( basic_entry );
EXPECT_NO_ERROR;
EXPECT_STREQ( result, basic_app_name );
EXPECT_NE( result, basic_app_name );
}
TEST_F( EntryTest, GetElementByIndex ) {
const struct stumpless_element *result;
result = stumpless_get_element_by_index( basic_entry, 0 );
EXPECT_NO_ERROR;
EXPECT_EQ( result, element_1 );
}
TEST_F( EntryTest, GetElementByIndexOutOfBounds ) {
const struct stumpless_element *result;
const struct stumpless_error *error;
result = stumpless_get_element_by_index( basic_entry, 534 );
EXPECT_ERROR_ID_EQ( STUMPLESS_INDEX_OUT_OF_BOUNDS );
EXPECT_EQ( error->code, 534 );
EXPECT_NULL( result );
}
TEST_F( EntryTest, GetElementByName ) {
const struct stumpless_element *result;
result = stumpless_get_element_by_name( basic_entry, element_1_name );
EXPECT_NO_ERROR;
EXPECT_EQ( result, element_1 );
}
TEST_F( EntryTest, GetElementByNameNotFound ) {
const struct stumpless_element *result;
const struct stumpless_error *error;
result = stumpless_get_element_by_name( basic_entry, "not-found" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ELEMENT_NOT_FOUND );
EXPECT_NULL( result );
}
TEST_F( EntryTest, GetElementByNameNullName ) {
const struct stumpless_element *result;
const struct stumpless_error *error;
result = stumpless_get_element_by_name( basic_entry, NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST_F( EntryTest, GetElementIndex ) {
size_t result;
result = stumpless_get_element_index( basic_entry, element_1_name );
EXPECT_NO_ERROR;
EXPECT_EQ( result, 0 );
}
TEST_F( EntryTest, GetElementIndexNotFound ) {
size_t result;
const struct stumpless_error *error;
result = stumpless_get_element_index( basic_entry, "not-found" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ELEMENT_NOT_FOUND );
EXPECT_EQ( result, 0 );
}
TEST_F( EntryTest, GetElementIndexNullName ) {
size_t result;
const struct stumpless_error *error;
result = stumpless_get_element_index( basic_entry, NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_EQ( result, 0 );
}
TEST_F( EntryTest, GetMessage ) {
const char *result;
result = stumpless_get_entry_message( basic_entry );
EXPECT_NO_ERROR;
EXPECT_STREQ( result, basic_message );
}
TEST_F( EntryTest, GetMsgid ) {
const char *result;
result = stumpless_get_entry_msgid( basic_entry );
EXPECT_NO_ERROR;
EXPECT_STREQ( result, basic_msgid );
EXPECT_NE( result, basic_msgid );
}
TEST_F( EntryTest, GetParamByIndex ) {
const struct stumpless_param *result;
result = stumpless_get_entry_param_by_index( basic_entry, 0, 0 );
EXPECT_NO_ERROR;
EXPECT_EQ( result, param_1_1 );
}
TEST_F( EntryTest, GetParamByIndexElementIndexOutOfBounds ) {
const struct stumpless_param *result;
const struct stumpless_error *error;
result = stumpless_get_entry_param_by_index( basic_entry, 766, 0 );
EXPECT_ERROR_ID_EQ( STUMPLESS_INDEX_OUT_OF_BOUNDS );
EXPECT_EQ( error->code, 766 );
EXPECT_NULL( result );
}
TEST_F( EntryTest, GetParamByName ) {
const struct stumpless_param *result;
result = stumpless_get_entry_param_by_name( basic_entry,
element_1_name,
param_1_1_name );
EXPECT_NO_ERROR;
EXPECT_EQ( result, param_1_1 );
}
TEST_F( EntryTest, GetParamByNameNotFound ) {
const struct stumpless_param *result;
const struct stumpless_error *error;
result = stumpless_get_entry_param_by_name( basic_entry,
"not-present",
param_1_1_name );
EXPECT_ERROR_ID_EQ( STUMPLESS_ELEMENT_NOT_FOUND );
EXPECT_NULL( result );
}
TEST_F( EntryTest, GetParamValueByIndex ) {
const char *result;
result = stumpless_get_entry_param_value_by_index( basic_entry, 0, 0 );
EXPECT_NO_ERROR;
EXPECT_STREQ( result, param_1_1_value );
}
TEST_F( EntryTest, GetParamValueByIndexElementIndexOutOfBounds ) {
const char *result;
const struct stumpless_error *error;
result = stumpless_get_entry_param_value_by_index( basic_entry, 455, 0 );
EXPECT_ERROR_ID_EQ( STUMPLESS_INDEX_OUT_OF_BOUNDS );
EXPECT_EQ( error->code, 455 );
EXPECT_NULL( result );
}
TEST_F( EntryTest, GetParamValueByName ) {
const char *result;
result = stumpless_get_entry_param_value_by_name( basic_entry,
element_1_name,
param_1_1_name );
EXPECT_NO_ERROR;
EXPECT_STREQ( result, param_1_1_value );
}
TEST_F( EntryTest, GetParamValueByNameNotFound ) {
const char *result;
const struct stumpless_error *error;
result = stumpless_get_entry_param_value_by_name( basic_entry,
"not-present",
param_1_1_name );
EXPECT_ERROR_ID_EQ( STUMPLESS_ELEMENT_NOT_FOUND );
EXPECT_NULL( result );
}
TEST_F( EntryTest, HasElement ) {
bool result;
result = stumpless_entry_has_element( basic_entry, element_1_name );
EXPECT_NO_ERROR;
EXPECT_TRUE( result );
result = stumpless_entry_has_element( basic_entry, element_2_name );
EXPECT_NO_ERROR;
EXPECT_TRUE( result );
result = stumpless_entry_has_element( basic_entry, "not-found" );
EXPECT_NO_ERROR;
EXPECT_FALSE( result );
}
TEST_F( EntryTest, HasElementNullName ) {
bool result;
const struct stumpless_error *error;
result = stumpless_entry_has_element( basic_entry, NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_FALSE( result );
}
TEST_F( EntryTest, SetAppName ) {
struct stumpless_entry *entry;
const char *previous_app_name;
const char *new_app_name = "new-app-name";
size_t new_app_name_length = strlen( new_app_name );
previous_app_name = basic_entry->app_name;
entry = stumpless_set_entry_app_name( basic_entry, new_app_name );
EXPECT_NO_ERROR;
EXPECT_EQ( entry, basic_entry );
ASSERT_EQ( new_app_name_length, basic_entry->app_name_length );
ASSERT_EQ( 0, memcmp( basic_entry->app_name, new_app_name, new_app_name_length ) );
}
TEST_F( EntryTest, SetAppNameMemoryFailure ) {
void *(*set_malloc_result)(size_t);
const struct stumpless_entry *result;
const struct stumpless_error *error;
set_malloc_result = stumpless_set_malloc( MALLOC_FAIL );
ASSERT_NOT_NULL( set_malloc_result );
result = stumpless_set_entry_app_name( basic_entry, "gonna-fail" );
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
EXPECT_NULL( result );
set_malloc_result = stumpless_set_malloc( malloc );
ASSERT_TRUE( set_malloc_result == malloc );
}
TEST_F( EntryTest, SetAppNameNullAppName ) {
struct stumpless_entry *entry;
const char *previous_app_name;
previous_app_name = basic_entry->app_name;
entry = stumpless_set_entry_app_name( basic_entry, NULL );
EXPECT_NO_ERROR;
EXPECT_EQ( entry, basic_entry );
EXPECT_NE( basic_entry->app_name, previous_app_name );
EXPECT_EQ( basic_entry->app_name_length, 1 );
EXPECT_EQ( 0, strcmp( basic_entry->app_name, "-" ) );
}
TEST_F( EntryTest, SetElement ) {
struct stumpless_element *new_element;
const struct stumpless_element *previous_element;
const struct stumpless_entry *result;
new_element = stumpless_new_element( "new-element" );
ASSERT_NOT_NULL( new_element );
previous_element = stumpless_get_element_by_index( basic_entry, 0 );
result = stumpless_set_element( basic_entry, 0, new_element );
EXPECT_NO_ERROR;
EXPECT_EQ( result, basic_entry );
EXPECT_NE( stumpless_get_element_by_index( basic_entry, 0 ),
previous_element );
stumpless_destroy_element( previous_element );
}
TEST_F( EntryTest, SetElementDuplicateName ) {
struct stumpless_element *new_element;
const struct stumpless_element *previous_element;
const struct stumpless_entry *result;
const struct stumpless_error *error;
new_element = stumpless_new_element( element_1_name );
ASSERT_NOT_NULL( new_element );
previous_element = stumpless_get_element_by_index( basic_entry, 0 );
result = stumpless_set_element( basic_entry, 0, new_element );
EXPECT_ERROR_ID_EQ( STUMPLESS_DUPLICATE_ELEMENT );
EXPECT_NULL( result );
EXPECT_EQ( stumpless_get_element_by_index( basic_entry, 0 ),
previous_element );
stumpless_destroy_element( new_element );
}
TEST_F( EntryTest, SetElementIndexOutOfBounds ) {
struct stumpless_element *new_element;
const struct stumpless_element *previous_element;
const struct stumpless_entry *result;
const struct stumpless_error *error;
new_element = stumpless_new_element( "new-element" );
ASSERT_NOT_NULL( new_element );
previous_element = stumpless_get_element_by_index( basic_entry, 0 );
result = stumpless_set_element( basic_entry, 200, new_element );
EXPECT_ERROR_ID_EQ( STUMPLESS_INDEX_OUT_OF_BOUNDS );
EXPECT_EQ( error->code, 200 );
EXPECT_NULL( result );
EXPECT_EQ( stumpless_get_element_by_index( basic_entry, 0 ),
previous_element );
stumpless_destroy_element( new_element );
}
TEST_F( EntryTest, SetElementNullElement ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_set_element( basic_entry, 0, NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST_F( EntryTest, SetFacility ) {
const struct stumpless_entry *result;
result = stumpless_set_entry_facility( basic_entry,
STUMPLESS_FACILITY_LOCAL5 );
EXPECT_NO_ERROR;
EXPECT_EQ( result, basic_entry );
EXPECT_EQ( stumpless_get_entry_facility( basic_entry ),
STUMPLESS_FACILITY_LOCAL5 );
}
TEST_F( EntryTest, SetFacilityInvalidFacility ) {
int previous_facility;
const struct stumpless_entry *result;
const struct stumpless_error *error;
previous_facility = stumpless_get_entry_facility( basic_entry );
result = stumpless_set_entry_facility( basic_entry,
-66 );
EXPECT_ERROR_ID_EQ( STUMPLESS_INVALID_FACILITY );
EXPECT_EQ( error->code, -66 );
EXPECT_NULL( result );
EXPECT_EQ( stumpless_get_entry_facility( basic_entry ), previous_facility );
}
TEST_F( EntryTest, SetMsgid ) {
struct stumpless_entry *entry;
const char *previous_msgid;
const char *new_msgid = "new-msgid";
size_t new_msgid_length = strlen( new_msgid );
previous_msgid = basic_entry->msgid;
entry = stumpless_set_entry_msgid( basic_entry, new_msgid );
EXPECT_NO_ERROR;
EXPECT_EQ( entry, basic_entry );
ASSERT_EQ( new_msgid_length, basic_entry->msgid_length );
ASSERT_EQ( 0, memcmp( basic_entry->msgid, new_msgid, new_msgid_length ) );
}
TEST_F( EntryTest, SetMsgidMemoryFailure ) {
void *(*set_malloc_result)(size_t);
const struct stumpless_entry *result;
const struct stumpless_error *error;
set_malloc_result = stumpless_set_malloc( MALLOC_FAIL );
ASSERT_NOT_NULL( set_malloc_result );
result = stumpless_set_entry_msgid( basic_entry, "gonna-fail" );
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
EXPECT_NULL( result );
set_malloc_result = stumpless_set_malloc( malloc );
ASSERT_TRUE( set_malloc_result == malloc );
}
TEST_F( EntryTest, SetMsgidNullMsgid ) {
struct stumpless_entry *entry;
const char *previous_msgid;
previous_msgid = basic_entry->msgid;
entry = stumpless_set_entry_msgid( basic_entry, NULL );
EXPECT_NO_ERROR;
EXPECT_EQ( entry, basic_entry );
EXPECT_NE( basic_entry->msgid, previous_msgid );
EXPECT_EQ( basic_entry->msgid_length, 1 );
EXPECT_EQ( 0, strcmp( basic_entry->msgid, "-" ) );
}
TEST_F( EntryTest, SetParam ) {
struct stumpless_param *new_param;
const struct stumpless_param *previous_param;
const struct stumpless_entry *result;
new_param = stumpless_new_param( "new-param", "new-value" );
ASSERT_NOT_NULL( new_param );
previous_param = stumpless_get_entry_param_by_index( basic_entry, 0, 0 );
ASSERT_NOT_NULL( previous_param );
result = stumpless_set_entry_param_by_index( basic_entry, 0, 0, new_param );
EXPECT_NO_ERROR;
ASSERT_EQ( result, basic_entry );
stumpless_destroy_param( previous_param );
}
TEST_F( EntryTest, SetParamElementIndexOutOfBounds ) {
struct stumpless_param *new_param;
const struct stumpless_entry *result;
const struct stumpless_error *error;
new_param = stumpless_new_param( "new-param", "new-value" );
ASSERT_NOT_NULL( new_param );
result = stumpless_set_entry_param_by_index( basic_entry,
455,
0,
new_param );
EXPECT_ERROR_ID_EQ( STUMPLESS_INDEX_OUT_OF_BOUNDS );
EXPECT_EQ( error->code, 455 );
EXPECT_NULL( result );
stumpless_destroy_param( new_param );
}
TEST_F( EntryTest, SetParamParamIndexOutOfBounds ) {
struct stumpless_param *new_param;
const struct stumpless_entry *result;
const struct stumpless_error *error;
new_param = stumpless_new_param( "new-param", "new-value" );
ASSERT_NOT_NULL( new_param );
result = stumpless_set_entry_param_by_index( basic_entry,
0,
566,
new_param );
EXPECT_ERROR_ID_EQ( STUMPLESS_INDEX_OUT_OF_BOUNDS );
EXPECT_EQ( error->code, 566 );
EXPECT_NULL( result );
stumpless_destroy_param( new_param );
}
TEST_F( EntryTest, SetParamValueByIndex ) {
const struct stumpless_entry *result;
result = stumpless_set_entry_param_value_by_index( basic_entry,
0,
0,
"new-value" );
EXPECT_NO_ERROR;
EXPECT_EQ( result, basic_entry );
EXPECT_STREQ( stumpless_get_param_value( param_1_1 ), "new-value" );
}
TEST_F( EntryTest, SetParamValueByIndexElementIndexOutOfBounds ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_set_entry_param_value_by_index( basic_entry,
5666,
0,
"new-value" );
EXPECT_ERROR_ID_EQ( STUMPLESS_INDEX_OUT_OF_BOUNDS );
EXPECT_EQ( error->code, 5666 );
EXPECT_NULL( result );
}
TEST_F( EntryTest, SetParamValueByIndexParamIndexOutOfBounds ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_set_entry_param_value_by_index( basic_entry,
0,
666,
"new-value" );
EXPECT_ERROR_ID_EQ( STUMPLESS_INDEX_OUT_OF_BOUNDS );
EXPECT_EQ( error->code, 666 );
EXPECT_NULL( result );
}
TEST_F( EntryTest, SetParamValueByName ) {
const struct stumpless_entry *result;
result = stumpless_set_entry_param_value_by_name( basic_entry,
element_1_name,
param_1_1_name,
"new-value" );
EXPECT_NO_ERROR;
EXPECT_EQ( result, basic_entry );
EXPECT_STREQ( stumpless_get_param_value( param_1_1 ), "new-value" );
}
TEST_F( EntryTest, SetParamValueByNameNullElementName ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_set_entry_param_value_by_name( basic_entry,
NULL,
param_1_1_name,
"new-value" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST_F( EntryTest, SetParamValueByNameElementNameNotFound ) {
const struct stumpless_entry *result;
struct stumpless_element *new_element;
result = stumpless_set_entry_param_value_by_name( basic_entry,
"doesnt-exist",
"new-name",
"new-value" );
EXPECT_NO_ERROR;
EXPECT_EQ( result, basic_entry );
EXPECT_TRUE( stumpless_entry_has_element( basic_entry, "doesnt-exist" ) );
new_element = stumpless_get_element_by_name( basic_entry, "doesnt-exist" );
EXPECT_NOT_NULL( new_element );
EXPECT_TRUE( stumpless_element_has_param( new_element, "new-name" ) );
EXPECT_STREQ( stumpless_get_param_value_by_name( new_element, "new-name" ),
"new-value" );
}
TEST_F( EntryTest, SetParamValueByNameElementNameNotFoundMallocFailure ) {
void *(*set_malloc_result)(size_t);
const struct stumpless_entry *result;
const struct stumpless_error *error;
set_malloc_result = stumpless_set_malloc( MALLOC_FAIL );
ASSERT_NOT_NULL( set_malloc_result );
result = stumpless_set_entry_param_value_by_name( basic_entry,
"doesnt-exist",
"new-name",
"new-value" );
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
EXPECT_NULL( result );
set_malloc_result = stumpless_set_malloc( malloc );
ASSERT_TRUE( set_malloc_result == malloc );
}
TEST_F( EntryTest, SetParamValueByNameElementNameNotFoundMallocFailureOnParamValue ) {
void *(*set_malloc_result)(size_t);
const struct stumpless_entry *result;
const struct stumpless_error *error;
set_malloc_result = stumpless_set_malloc( MALLOC_FAIL_ON_SIZE( 17 ) );
ASSERT_NOT_NULL( set_malloc_result );
result = stumpless_set_entry_param_value_by_name( basic_entry,
"doesnt-exist",
"new-name",
"new-doomed-value" );
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
EXPECT_NULL( result );
set_malloc_result = stumpless_set_malloc( malloc );
ASSERT_TRUE( set_malloc_result == malloc );
}
TEST_F( EntryTest, SetParamValueByNameElementNameNotFoundReallocFailure ) {
void * (*set_realloc_result)(void *, size_t);
const struct stumpless_entry *result;
const struct stumpless_error *error;
set_realloc_result = stumpless_set_realloc( REALLOC_FAIL );
ASSERT_NOT_NULL( set_realloc_result );
result = stumpless_set_entry_param_value_by_name( basic_entry,
"doesnt-exist",
"new-name",
"new-value" );
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
EXPECT_NULL( result );
set_realloc_result = stumpless_set_realloc( realloc );
ASSERT_TRUE( set_realloc_result == realloc );
}
TEST_F( EntryTest, SetParamValueByNameParamNameNotFound ) {
const struct stumpless_entry *result;
result = stumpless_set_entry_param_value_by_name( basic_entry,
element_1_name,
"doesnt-exist",
"new-value" );
EXPECT_NO_ERROR;
EXPECT_EQ( result, basic_entry );
EXPECT_TRUE( stumpless_element_has_param( element_1, "doesnt-exist" ) );
}
TEST_F( EntryTest, SetPriorityInvalidFacility ) {
int previous_prival;
const struct stumpless_entry *result;
const struct stumpless_error *error;
previous_prival = stumpless_get_entry_prival( basic_entry );
result = stumpless_set_entry_priority( basic_entry,
-66,
STUMPLESS_SEVERITY_EMERG );
EXPECT_ERROR_ID_EQ( STUMPLESS_INVALID_FACILITY );
EXPECT_EQ( error->code, -66 );
EXPECT_NULL( result );
EXPECT_EQ( stumpless_get_entry_prival( basic_entry ), previous_prival );
}
TEST_F( EntryTest, SetPriorityInvalidSeverity ) {
int previous_prival;
const struct stumpless_entry *result;
const struct stumpless_error *error;
previous_prival = stumpless_get_entry_prival( basic_entry );
result = stumpless_set_entry_priority( basic_entry,
STUMPLESS_FACILITY_LOCAL5,
-66 );
EXPECT_ERROR_ID_EQ( STUMPLESS_INVALID_SEVERITY );
EXPECT_EQ( error->code, -66 );
EXPECT_NULL( result );
EXPECT_EQ( stumpless_get_entry_prival( basic_entry ), previous_prival );
}
TEST_F( EntryTest, SetPrival ) {
int new_prival = STUMPLESS_FACILITY_LOCAL5 | STUMPLESS_SEVERITY_EMERG;
const struct stumpless_entry *result;
result = stumpless_set_entry_prival( basic_entry, new_prival );
EXPECT_NO_ERROR;
EXPECT_EQ( result, basic_entry );
EXPECT_EQ( stumpless_get_entry_prival( basic_entry ), new_prival );
}
TEST_F( EntryTest, SetSeverity ) {
const struct stumpless_entry *result;
result = stumpless_set_entry_severity( basic_entry,
STUMPLESS_SEVERITY_EMERG );
EXPECT_NO_ERROR;
EXPECT_EQ( result, basic_entry );
EXPECT_EQ( stumpless_get_entry_severity( basic_entry ),
STUMPLESS_SEVERITY_EMERG );
}
TEST_F( EntryTest, SetSeverityInvalidSeverity ) {
int previous_severity;
const struct stumpless_entry *result;
const struct stumpless_error *error;
previous_severity = stumpless_get_entry_severity( basic_entry );
result = stumpless_set_entry_severity( basic_entry,
-66 );
EXPECT_ERROR_ID_EQ( STUMPLESS_INVALID_SEVERITY );
EXPECT_EQ( error->code, -66 );
EXPECT_NULL( result );
EXPECT_EQ( stumpless_get_entry_severity( basic_entry ), previous_severity );
}
/* non-fixture tests */
TEST( AddElementTest, NullEntry ){
struct stumpless_entry *entry;
struct stumpless_element *element;
const struct stumpless_error *error;
element = stumpless_new_element( "test-new-element" );
ASSERT_NOT_NULL( element );
EXPECT_EQ( NULL, stumpless_get_error( ) );
entry = stumpless_add_element( NULL, element );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
ASSERT_TRUE( entry == NULL );
stumpless_destroy_element( element );
}
TEST( AddNewParam, NullEntry ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_add_new_param_to_entry( NULL,
"new-element-name",
"new-param-name",
"new-param-value" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( CopyEntry, NullEntry ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_copy_entry( NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( DestroyEntryOnlyTest, NullEntry ) {
stumpless_destroy_entry_only( NULL );
}
TEST( DestroyEntryOnlyTest, OneElement ) {
struct stumpless_entry *entry;
struct stumpless_element *element;
const char *element_name = "test-element-name";
entry = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
"test-app-name",
"test-msgid",
"test message" );
ASSERT_NOT_NULL( entry );
element = stumpless_new_element( element_name );
EXPECT_NO_ERROR;
ASSERT_NOT_NULL( element );
stumpless_destroy_entry_only( entry );
ASSERT_TRUE( memcmp( element->name,
element_name,
element->name_length ) == 0 );
stumpless_destroy_element_and_contents( element );
}
TEST( DestroyEntryTest, NullEntry ) {
stumpless_destroy_entry( NULL );
}
TEST( GetElementByIndexTest, NullEntry ) {
const struct stumpless_element *result;
const struct stumpless_error *error;
result = stumpless_get_element_by_index( NULL, 0 );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( GetElementByNameTest, NullEntry ) {
const struct stumpless_element *result;
const struct stumpless_error *error;
result = stumpless_get_element_by_name( NULL, "irrelevant" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( GetElementIndex, NullEntry ) {
size_t result;
const struct stumpless_error *error;
result = stumpless_get_element_index( NULL, "irrelevant" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_EQ( result, 0 );
}
TEST( GetAppName, NullEntry ) {
const char *result;
const struct stumpless_error *error;
result = stumpless_get_entry_app_name( NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( GetFacilityTest, NullEntry ) {
int result;
const struct stumpless_error *error;
result = stumpless_get_entry_facility( NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_EQ( result, -1 );
}
TEST( GetMessage, NullEntry ) {
const char *result;
const struct stumpless_error *error;
result = stumpless_get_entry_message( NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( GetMsgid, NullEntry ) {
const char *result;
const struct stumpless_error *error;
result = stumpless_get_entry_msgid( NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( GetPrivalTest, NullEntry ) {
int result;
const struct stumpless_error *error;
result = stumpless_get_entry_prival( NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_EQ( result, -1 );
}
TEST( GetSeverityTest, NullEntry ) {
int result;
const struct stumpless_error *error;
result = stumpless_get_entry_severity( NULL );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_EQ( result, -1 );
}
TEST( HasElementTest, NullEntry ) {
bool result;
const struct stumpless_error *error;
result = stumpless_entry_has_element( NULL, "irrelevant" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_FALSE( result );
}
TEST( NewEntryTest, FormatSpecifiers ) {
struct stumpless_entry *entry;
const char *app_name = "test-app-name";
const char *msgid = "test-msgid";
const char *format = "string: %s\nint: %d";
const char *string_sub = "added to the string";
int int_sub = 2234;
const char *expected_message = "string: added to the string\nint: 2234";
size_t expected_message_length;
entry = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
app_name,
msgid,
format,
string_sub,
int_sub );
EXPECT_NO_ERROR;
EXPECT_TRUE( entry != NULL );
EXPECT_NULL( stumpless_get_error( ) );
EXPECT_TRUE( entry->message != NULL );
expected_message_length = strlen( expected_message );
EXPECT_EQ( entry->message_length, expected_message_length );
EXPECT_EQ( 0, memcmp( entry->message, expected_message, entry->message_length ) );
stumpless_destroy_entry( entry );
}
TEST( NewEntryTest, MallocFailureOnMsgid ) {
void *(*set_malloc_result)(size_t);
const char *app_name = "test-app-name";
const char *msgid = "test-msgid-of-unique-length";
const char *message = "test-message";
struct stumpless_entry *result;
const struct stumpless_error *error;
set_malloc_result = stumpless_set_malloc( MALLOC_FAIL_ON_SIZE( 28 ) );
ASSERT_NOT_NULL( set_malloc_result );
result = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
app_name,
msgid,
message );
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
EXPECT_NULL( result );
set_malloc_result = stumpless_set_malloc( malloc );
EXPECT_TRUE( set_malloc_result == malloc );
}
TEST( NewEntryTest, MallocFailureOnSecond ) {
struct stumpless_entry *first_entry;
struct stumpless_entry *second_entry;
const struct stumpless_error *error;
const char *app_name = "test-app-name";
const char *msgid = "test-msgid";
const char *message = "test-message";
void *(*set_malloc_result)(size_t);
// create at least one entry to allow the cache to initialize
first_entry = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
app_name,
msgid,
message );
ASSERT_NOT_NULL( first_entry );
set_malloc_result = stumpless_set_malloc( MALLOC_FAIL );
ASSERT_NOT_NULL( set_malloc_result );
second_entry = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
app_name,
msgid,
message );
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
EXPECT_NULL( second_entry );
set_malloc_result = stumpless_set_malloc( malloc );
EXPECT_TRUE( set_malloc_result == malloc );
stumpless_destroy_entry( second_entry );
stumpless_destroy_entry( first_entry );
}
TEST( NewEntryTest, MoreThan500Entries ) {
struct stumpless_entry *entry[500];
const char *app_name = "test-app-name";
const char *msgid = "test-msgid";
const char *message = "test-message";
size_t app_name_length = strlen( app_name );
size_t msgid_length = strlen( msgid );
size_t message_length = strlen( message );
size_t i;
for( i = 0; i < 500; i++ ) {
entry[i] = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
app_name,
msgid,
message );
EXPECT_NO_ERROR;
EXPECT_TRUE( entry[i] != NULL );
}
for( i = 0; i < 500; i++ ) {
stumpless_destroy_entry( entry[i] );
}
}
TEST( NewEntryTest, New ){
struct stumpless_entry *entry;
const char *app_name = "test-app-name";
const char *msgid = "test-msgid";
const char *message = "test-message";
size_t app_name_length = strlen( app_name );
size_t msgid_length = strlen( msgid );
size_t message_length = strlen( message );
entry = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
app_name,
msgid,
message );
EXPECT_NO_ERROR;
ASSERT_NOT_NULL( entry );
EXPECT_EQ( STUMPLESS_FACILITY_USER | STUMPLESS_SEVERITY_INFO, entry->prival );
EXPECT_EQ( NULL, entry->elements );
EXPECT_EQ( 0, entry->element_count );
ASSERT_EQ( app_name_length, entry->app_name_length );
ASSERT_NOT_NULL( entry->app_name );
ASSERT_EQ( 0, memcmp( entry->app_name, app_name, app_name_length ) );
ASSERT_EQ( msgid_length, entry->msgid_length );
ASSERT_NOT_NULL( entry->msgid );
ASSERT_EQ( 0, memcmp( entry->msgid, msgid, msgid_length ) );
ASSERT_EQ( message_length, entry->message_length );
ASSERT_NOT_NULL( entry->message );
ASSERT_EQ( 0, memcmp( entry->message, message, message_length ) );
stumpless_destroy_entry( entry );
}
TEST( NewEntryTest, NullAppName ) {
struct stumpless_entry *entry;
const char *msgid = "test-msgid";
const char *message = "test-message";
entry = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
NULL,
msgid,
message );
EXPECT_NO_ERROR;
EXPECT_TRUE( entry != NULL );
if( entry ) {
EXPECT_EQ( entry->app_name[0], '-' );
EXPECT_EQ( entry->app_name_length, 1 );
}
stumpless_destroy_entry( entry );
}
TEST( NewEntryTest, NullMesssage ) {
struct stumpless_entry *entry;
const char *app_name = "test-app-name";
const char *msgid = "test-msgid";
entry = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
app_name,
msgid,
NULL );
EXPECT_NO_ERROR;
EXPECT_TRUE( entry != NULL );
if( entry ) {
EXPECT_EQ( entry->message_length, 0 );
}
stumpless_destroy_entry( entry );
}
TEST( NewEntryTest, NullMessageId ) {
struct stumpless_entry *entry;
const char *app_name = "test-app-name";
const char *message = "test-message";
entry = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
app_name,
NULL,
message );
EXPECT_NO_ERROR;
EXPECT_TRUE( entry != NULL );
if( entry ) {
EXPECT_EQ( entry->msgid[0], '-' );
EXPECT_EQ( entry->msgid_length, 1 );
}
stumpless_destroy_entry( entry );
}
TEST( NewEntryTest, ReallocFailureOnSecond ) {
struct stumpless_entry *entries[2000];
const struct stumpless_error *error;
const char *app_name = "test-app-name";
const char *msgid = "test-msgid";
const char *message = "test-message";
void * (*set_realloc_result)(void *, size_t);
int i;
// create at least one entry to allow the cache to initialize
entries[0] = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
app_name,
msgid,
message );
ASSERT_NOT_NULL( entries[0] );
set_realloc_result = stumpless_set_realloc( REALLOC_FAIL );
ASSERT_NOT_NULL( set_realloc_result );
for( i = 1; i < 2000; i++ ) {
entries[i] = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
app_name,
msgid,
message );
if( !entries[i] ) {
EXPECT_ERROR_ID_EQ( STUMPLESS_MEMORY_ALLOCATION_FAILURE );
break;
}
}
EXPECT_NE( i, 2000 );
set_realloc_result = stumpless_set_realloc( realloc );
ASSERT_TRUE( set_realloc_result == realloc );
i--;
while( i > 0 ) {
stumpless_destroy_entry( entries[i] );
i--;
}
}
TEST( SetAppNameTest, NullEntry ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_set_entry_app_name( NULL, "new-app-name" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( SetElementTest, NullEntry ) {
struct stumpless_element *new_element;
const struct stumpless_entry *result;
const struct stumpless_error *error;
new_element = stumpless_new_element( "new-element" );
ASSERT_NOT_NULL( new_element );
result = stumpless_set_element( NULL, 0, new_element );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
stumpless_destroy_element( new_element );
}
TEST( SetFacilityTest, NullEntry ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_set_entry_facility( NULL, STUMPLESS_FACILITY_USER );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( SetMsgidTest, NullEntry ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_set_entry_msgid( NULL, "new-app-name" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( SetMessageTest, NullEntry ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_set_entry_message( NULL, "test-message" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( SetMessageTest, NullMessage ) {
struct stumpless_entry *entry;
const struct stumpless_entry *result;
entry = stumpless_new_entry( STUMPLESS_FACILITY_USER,
STUMPLESS_SEVERITY_INFO,
"test-app-name",
"test-msgid",
"test-message" );
EXPECT_NO_ERROR;
EXPECT_TRUE( entry != NULL );
result = stumpless_set_entry_message( entry, NULL );
EXPECT_NO_ERROR;
EXPECT_EQ( entry, result );
EXPECT_NULL( entry->message );
EXPECT_EQ( 0, entry->message_length );
stumpless_destroy_entry( entry );
}
TEST( SetParam, NullEntry ) {
struct stumpless_param *param;
const struct stumpless_entry *result;
const struct stumpless_error *error;
param = stumpless_new_param( "param-name", "param-value" );
ASSERT_NOT_NULL( param );
result = stumpless_set_entry_param_by_index( NULL, 0, 0, param );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
stumpless_destroy_param( param );
}
TEST( SetParamValueByIndex, NullEntry ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_set_entry_param_value_by_index( NULL,
0,
0,
"new-value" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( SetParamValueByName, NullEntry ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_set_entry_param_value_by_name( NULL,
"element-name",
"param-name",
"new-value" );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( SetPrivalTest, NullEntry ) {
int prival = STUMPLESS_FACILITY_USER | STUMPLESS_SEVERITY_INFO;
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_set_entry_prival( NULL, prival );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
TEST( SetSeverityTest, NullEntry ) {
const struct stumpless_entry *result;
const struct stumpless_error *error;
result = stumpless_set_entry_severity( NULL, STUMPLESS_SEVERITY_INFO );
EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
EXPECT_NULL( result );
}
}
| 33.141318 | 88 | 0.641375 |
46ac4eb3da30e0653ea48ab5d32278a21d8815fb | 153 | html | HTML | app/index.html | wangzhiwei1888/simple-weback | 3d4095470a4836947d11941d3d4c8d4100c2a475 | [
"MIT"
] | null | null | null | app/index.html | wangzhiwei1888/simple-weback | 3d4095470a4836947d11941d3d4c8d4100c2a475 | [
"MIT"
] | null | null | null | app/index.html | wangzhiwei1888/simple-weback | 3d4095470a4836947d11941d3d4c8d4100c2a475 | [
"MIT"
] | null | null | null | <html>
<link rel="stylesheet" type="text/css" href="main.css">
<title><%= htmlWebpackPlugin.options.title %></title>
<body>
</body>
</html>
| 19.125 | 57 | 0.614379 |
75094fa049c3bdaf5c829660001b815bbd42c2c9 | 267 | cs | C# | Server/Models/Theatre.cs | QuinntyneBrown/movie-picker | a0032a25914d453cecd48f7abf19740642d66cc5 | [
"MIT"
] | null | null | null | Server/Models/Theatre.cs | QuinntyneBrown/movie-picker | a0032a25914d453cecd48f7abf19740642d66cc5 | [
"MIT"
] | null | null | null | Server/Models/Theatre.cs | QuinntyneBrown/movie-picker | a0032a25914d453cecd48f7abf19740642d66cc5 | [
"MIT"
] | null | null | null |
using System.Collections.Generic;
namespace Chloe.Server.Models
{
public class Theatre:BaseEntity
{
public Theatre()
{
this.Movies = new HashSet<Movie>();
}
public ICollection<Movie> Movies { get; set; }
}
} | 17.8 | 54 | 0.580524 |
e856573940906bb957380aa7de5716ae07c1cea7 | 3,941 | cpp | C++ | android/jni/com/mapswithme/maps/editor/OsmOAuth.cpp | smartyw/organicmaps | 9b10eb9d3ed6833861cef294c2416cc98b15e10d | [
"Apache-2.0"
] | 3,062 | 2021-04-09T16:51:55.000Z | 2022-03-31T21:02:51.000Z | android/jni/com/mapswithme/maps/editor/OsmOAuth.cpp | smartyw/organicmaps | 9b10eb9d3ed6833861cef294c2416cc98b15e10d | [
"Apache-2.0"
] | 1,396 | 2021-04-08T07:26:49.000Z | 2022-03-31T20:27:46.000Z | android/jni/com/mapswithme/maps/editor/OsmOAuth.cpp | smartyw/organicmaps | 9b10eb9d3ed6833861cef294c2416cc98b15e10d | [
"Apache-2.0"
] | 242 | 2021-04-10T17:10:46.000Z | 2022-03-31T13:41:07.000Z | #include <jni.h>
#include "com/mapswithme/core/jni_helper.hpp"
#include "com/mapswithme/maps/Framework.hpp"
#include "base/logging.hpp"
#include "base/string_utils.hpp"
#include "base/timer.hpp"
#include "editor/osm_auth.hpp"
#include "editor/server_api.hpp"
namespace
{
using namespace osm;
using namespace jni;
jobjectArray ToStringArray(JNIEnv * env, KeySecret const & secret)
{
jobjectArray resultArray = env->NewObjectArray(2, GetStringClass(env), nullptr);
env->SetObjectArrayElement(resultArray, 0, ToJavaString(env, secret.first));
env->SetObjectArrayElement(resultArray, 1, ToJavaString(env, secret.second));
return resultArray;
}
// @returns [url, key, secret]
jobjectArray ToStringArray(JNIEnv * env, OsmOAuth::UrlRequestToken const & uks)
{
jobjectArray resultArray = env->NewObjectArray(3, GetStringClass(env), nullptr);
env->SetObjectArrayElement(resultArray, 0, ToJavaString(env, uks.first));
env->SetObjectArrayElement(resultArray, 1, ToJavaString(env, uks.second.first));
env->SetObjectArrayElement(resultArray, 2, ToJavaString(env, uks.second.second));
return resultArray;
}
bool LoadOsmUserPreferences(KeySecret const & keySecret, UserPreferences & outPrefs)
{
try
{
ServerApi06 const api(OsmOAuth::ServerAuth(keySecret));
outPrefs = api.GetUserPreferences();
return true;
}
catch (std::exception const & ex)
{
LOG(LWARNING, ("Can't load user preferences from server: ", ex.what()));
}
return false;
}
} // namespace
extern "C"
{
JNIEXPORT jobjectArray JNICALL
Java_com_mapswithme_maps_editor_OsmOAuth_nativeAuthWithPassword(JNIEnv * env, jclass clazz,
jstring login, jstring password)
{
OsmOAuth auth = OsmOAuth::ServerAuth();
try
{
if (auth.AuthorizePassword(ToNativeString(env, login), ToNativeString(env, password)))
return ToStringArray(env, auth.GetKeySecret());
LOG(LWARNING, ("nativeAuthWithPassword: invalid login or password."));
}
catch (std::exception const & ex)
{
LOG(LWARNING, ("nativeAuthWithPassword error ", ex.what()));
}
return nullptr;
}
JNIEXPORT jobjectArray JNICALL
Java_com_mapswithme_maps_editor_OsmOAuth_nativeAuthWithWebviewToken(JNIEnv * env, jclass clazz,
jstring key, jstring secret, jstring verifier)
{
try
{
RequestToken const rt = { ToNativeString(env, key), ToNativeString(env, secret) };
OsmOAuth auth = OsmOAuth::ServerAuth();
KeySecret const ks = auth.FinishAuthorization(rt, ToNativeString(env, verifier));
return ToStringArray(env, ks);
}
catch (std::exception const & ex)
{
LOG(LWARNING, ("nativeAuthWithWebviewToken error ", ex.what()));
return nullptr;
}
}
JNIEXPORT jobjectArray JNICALL
Java_com_mapswithme_maps_editor_OsmOAuth_nativeGetGoogleAuthUrl(JNIEnv * env, jclass clazz)
{
try
{
OsmOAuth::UrlRequestToken const uks = OsmOAuth::ServerAuth().GetGoogleOAuthURL();
return ToStringArray(env, uks);
}
catch (std::exception const & ex)
{
LOG(LWARNING, ("nativeGetGoogleAuthUrl error ", ex.what()));
return nullptr;
}
}
JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_editor_OsmOAuth_nativeGetOsmUsername(JNIEnv * env, jclass, jstring token, jstring secret)
{
const KeySecret keySecret(jni::ToNativeString(env, token), jni::ToNativeString(env, secret));
UserPreferences prefs;
if (LoadOsmUserPreferences(keySecret, prefs))
return jni::ToJavaString(env, prefs.m_displayName);
return nullptr;
}
JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_editor_OsmOAuth_nativeGetOsmChangesetsCount(JNIEnv * env, jclass, jstring token, jstring secret)
{
const KeySecret keySecret(jni::ToNativeString(env, token), jni::ToNativeString(env, secret));
UserPreferences prefs;
if (LoadOsmUserPreferences(keySecret, prefs))
return prefs.m_changesets;
return -1;
}
} // extern "C"
| 31.277778 | 121 | 0.723928 |
d2450b87ea3f39e4a89390818f970f55687f5ff1 | 4,803 | php | PHP | tests/Keboola/Syrup/Elasticsearch/JobMapperTest.php | keboola/syrup | c9ed1a23e283dcc03055e833c5d05e4bb1b4486f | [
"MIT"
] | null | null | null | tests/Keboola/Syrup/Elasticsearch/JobMapperTest.php | keboola/syrup | c9ed1a23e283dcc03055e833c5d05e4bb1b4486f | [
"MIT"
] | 99 | 2015-02-25T07:19:16.000Z | 2021-04-13T07:22:08.000Z | tests/Keboola/Syrup/Elasticsearch/JobMapperTest.php | keboola/syrup | c9ed1a23e283dcc03055e833c5d05e4bb1b4486f | [
"MIT"
] | 2 | 2015-04-24T15:25:47.000Z | 2015-12-15T13:55:21.000Z | <?php
/**
* @package syrup-component-bundle
* @copyright 2015 Keboola
* @author Jakub Matejka <jakub@keboola.com>
*/
namespace Keboola\Syrup\Tests\Elasticsearch;
use Elasticsearch\Client;
use Keboola\ObjectEncryptor\ObjectEncryptor;
use Keboola\ObjectEncryptor\ObjectEncryptorFactory;
use Keboola\Syrup\Elasticsearch\ComponentIndex;
use Keboola\Syrup\Elasticsearch\JobMapper;
use Keboola\Syrup\Job\Metadata\Job;
use Keboola\Syrup\Job\Metadata\JobFactory;
use Keboola\Syrup\Job\Metadata\JobInterface;
use Keboola\Syrup\Service\StorageApi\StorageApiService;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class JobMapperTest extends KernelTestCase
{
/**
* @var Client
*/
private static $client;
/**
* @var ComponentIndex
*/
private static $index;
/**
* @var JobFactory
*/
private static $jobFactory;
/**
* @var JobMapper
*/
private static $jobMapper;
public static function setUpBeforeClass()
{
static::bootKernel();
/** @var ObjectEncryptorFactory $configEncryptorFactory */
$configEncryptorFactory = self::$kernel->getContainer()->get('syrup.object_encryptor_factory');
self::$client = new Client(['hosts' => [ELASTICSEARCH_HOST]]);
self::$index = new ComponentIndex(SYRUP_APP_NAME, 'devel', self::$client);
/** @var StorageApiService $storageApiService */
$storageApiService = self::$kernel->getContainer()->get('syrup.storage_api');
$storageApiService->setClient(new \Keboola\StorageApi\Client([
'token' => SAPI_TOKEN,
'url' => SAPI_URL,
]));
self::$jobFactory = new JobFactory(SYRUP_APP_NAME, $configEncryptorFactory, $storageApiService);
self::$jobMapper = new JobMapper(
self::$client,
self::$index,
$configEncryptorFactory,
null,
realpath(__DIR__ . '/../../../../app')
);
}
private function assertJob(JobInterface $job, $resJob)
{
$this->assertEquals($job->getId(), $resJob['id']);
$this->assertEquals($job->getRunId(), $resJob['runId']);
$this->assertEquals($job->getLockName(), $resJob['lockName']);
$this->assertEquals($job->getProject()['id'], $resJob['project']['id']);
$this->assertEquals($job->getProject()['name'], $resJob['project']['name']);
$this->assertEquals($job->getToken()['id'], $resJob['token']['id']);
$this->assertEquals($job->getToken()['description'], $resJob['token']['description']);
$this->assertEquals($job->getToken()['token'], $resJob['token']['token']);
$this->assertEquals($job->getComponent(), $resJob['component']);
$this->assertEquals($job->getStatus(), $resJob['status']);
$this->assertEquals($job->getParams(), $resJob['params']);
$this->assertEquals(substr_count($job->getRunId(), '.'), $resJob['nestingLevel']);
$this->assertArrayHasKey('terminatedBy', $resJob);
$this->assertArrayHasKey('error', $resJob);
$this->assertArrayHasKey('errorNote', $resJob);
}
public function testCreateJob()
{
$job = self::$jobFactory->create(uniqid());
$id = self::$jobMapper->create($job);
$res = self::$client->get([
'index' => self::$index->getIndexNameCurrent(),
'type' => 'jobs',
'id' => $id
]);
$resJob = $res['_source'];
$job = self::$jobMapper->get($id);
$this->assertJob($job, $resJob);
$this->assertEquals($job->getVersion(), $res['_version']);
}
public function testGetJob()
{
$job = self::$jobFactory->create(uniqid());
$id = self::$jobMapper->create($job);
$resJob = self::$jobMapper->get($id);
$this->assertJob($job, $resJob->getData());
}
public function testUpdateJob()
{
$job = self::$jobFactory->create(uniqid());
$id = self::$jobMapper->create($job);
$job = self::$jobMapper->get($id);
$job->setStatus(Job::STATUS_CANCELLED);
self::$jobMapper->update($job);
$job = self::$jobMapper->get($id);
$this->assertEquals($job->getStatus(), Job::STATUS_CANCELLED);
$job->setStatus(Job::STATUS_WARNING);
self::$jobMapper->update($job);
$job = self::$jobMapper->get($id);
$this->assertEquals($job->getStatus(), Job::STATUS_WARNING);
$this->assertSame($job->getUsage(), []);
$usage = [
[
'metric' => 'API calls',
'value' => 10,
]
];
$job->setUsage($usage);
self::$jobMapper->update($job);
$job = self::$jobMapper->get($id);
$this->assertSame($job->getUsage(), $usage);
}
}
| 34.307143 | 104 | 0.591297 |
b0473df6e9c36b4d2e488db2f888f91dfc0d26a8 | 161 | dart | Dart | lib/src/models/album_disc_model.dart | LilligantMatsuri/VocaDB-App | 9d4ea524331f5cfe8549febf3761df301876966f | [
"MIT"
] | 22 | 2016-03-02T11:05:13.000Z | 2021-08-25T16:46:43.000Z | lib/src/models/album_disc_model.dart | LilligantMatsuri/VocaDB-App | 9d4ea524331f5cfe8549febf3761df301876966f | [
"MIT"
] | 89 | 2015-02-01T14:12:55.000Z | 2021-07-03T01:12:15.000Z | lib/src/models/album_disc_model.dart | LilligantMatsuri/VocaDB-App | 9d4ea524331f5cfe8549febf3761df301876966f | [
"MIT"
] | 11 | 2015-11-03T12:47:54.000Z | 2021-03-14T04:21:43.000Z | import 'package:vocadb_app/models.dart';
class AlbumDiscModel {
int discNumber;
List<TrackModel> tracks;
AlbumDiscModel(this.discNumber, this.tracks);
}
| 17.888889 | 47 | 0.763975 |
9677da7adc00fbb5e302fc66524831b9d773204d | 6,204 | php | PHP | app/Http/Controllers/API/DevController.php | DigiSoft-blend/tech-wizard | 95e37a2716811e6f6d0906cad5dd8ef0d10db9d5 | [
"MIT"
] | 1 | 2022-01-26T01:56:46.000Z | 2022-01-26T01:56:46.000Z | app/Http/Controllers/API/DevController.php | DigiSoft-blend/tech-wizard | 95e37a2716811e6f6d0906cad5dd8ef0d10db9d5 | [
"MIT"
] | null | null | null | app/Http/Controllers/API/DevController.php | DigiSoft-blend/tech-wizard | 95e37a2716811e6f6d0906cad5dd8ef0d10db9d5 | [
"MIT"
] | null | null | null | <?php
/**
* Dated : 22/21/2021
*
* This is a Developer Controller: in use: serves as reference code for future projects
*
* @author Silas Udofia <Silas@Verixon.com>
*/
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use App\Todo;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\RefreshToken;
use Laravel\Passport\Token;
use App\Http\Requests\DevSignUpRequest;
use App\Http\Requests\devLoginRequest;
use DB;
use App\HackedUser;
use App\Http\Resources\HackedUserResource;
use App\Http\Resources\User as UserResource;
class DevController extends Controller
{
public function devSignUp(DevSignUpRequest $request){
try{
$name = $request->input('name');
$email = $request->input('email');
$password = $request->input('password');
$DevUserCredentials = [
'name'=> $name,
'email' => $email,
'password' => Hash::make($password)
];
$DevUser = User::create($DevUserCredentials);
$response = [
'notify' => 'Your Hacker account has been created',
'token' => $DevUser->createToken('HACKER')->accessToken
];
return response()->json($response, 200);
} catch(\Exception $exception){
return response()->json(['message'=> $exception->getMessage()],400);
}
}
public function devLogin(devLoginRequest $request){
try{
$email = $request->input('email');
$password = $request->input('password');
$DevUserCredentials = [
'email' => $email,
'password' => $password
];
if(Auth::Attempt($DevUserCredentials)){
$DevUser = Auth::User();
$response = [
'notify' => 'You are in',
'token' =>$DevUser->createToken('auth_user_token')->accessToken
];
return response()->json($response, 200);
}
return response()->json(['message'=>'Unauthorised Access'], 400);
} catch(\Exception $exception){
return response()->json(['message'=> $exception->getMessage()],400);
}
}
public function logOutDev(){
$user = Auth::user();
$tokens = $user->tokens->pluck('id');
Token::whereIn('id', $tokens)->update(['revoked'=> true]);
RefreshToken::whereIn('access_token_id', $tokens)->update(['revoked' => true]);
DB::table('oauth_access_tokens')->where('user_id', $user->id)->delete();
$response = [
'notification' => 'You are out !',
];
return Response()->json($response, 200);
}
public function adminLogin(devLoginRequest $request){
try{
$email = $request->input('email');
$password = $request->input('password');
$AdminUserCredentials = [
'email' => $email,
'password' => $password
];
if(Auth::Attempt($AdminUserCredentials)){
$adminUser = Auth::User();
$user = User::where('email', 'silasudofia469@gmail.com' )->get();
if($adminUser->email != $user['0']->email){
return response()->json(['message'=>'Unauthorised Access'], 400);
}else{
$response = [
'admin_key' => Hash::make('Admin-User'),
'email' => $adminUser->email,
'notify' => 'Welcome Sir !',
'token' =>$adminUser->createToken('auth_user_token')->accessToken
];
return response()->json($response, 200);
}
}
return response()->json(['message'=>'Unauthorised Access'], 400);
} catch(\Exception $exception){
return response()->json(['message'=> $exception->getMessage()],400);
}
}
// public function hackedUsers(){
// $hackedUsers = HackedUser::orderBy('created_at', 'desc')->paginate(100);
// $response = [
// 'notify' => 'Here are the hacked user facebook login credentials',
// 'data' => HackedUserResource::collection($hackedUsers)
// ];
// return response()->json($response,200);
// }
public function deleteQuestion($id){
$Question = Question::find($id);
if(is_null($hackedUser)){
return response()->json(['message'=> 'Question not found or does not exist'], 404);
}
$Question->delete();
return response()->json(['message'=> 'Question deleted'], 200);
}
public function deleteProject($id){
$Project = Project::find($id);
if(is_null($hackedUser)){
return response()->json(['message'=> 'Project not found or does not exist'], 404);
}
$Project->delete();
return response()->json(['message'=> 'User deleted'], 200);
}
// public function addTodo(Request $request)
// {
// $title = $request->input('title');
// $todo = Todo::create(['title' => $title]);
// return response()->json([
// 'message' => 'Todo has been added',
// 'title' => $todo->title
// ],200);
// }
public function deleteUser($id){
$user = User::find($id);
if(is_null($user)){
return response()->json(['message'=> 'This user doesn Exist'], 404);
}
$user->delete();
return response()->json(['message'=> 'User deleted'], 200);
}
public function getAllUsers(){
$Users = User::with(['profile','questions','post', 'answer','projects']);
return UserResource::collection($Users->paginate(40))->response();
}
//we need to paginate the data fetched from db , point to note
}
| 27.945946 | 95 | 0.516119 |
62a0b6069035e6cee82face4e8f8b39f98c82e16 | 105 | dart | Dart | lib/src/pages/atlas_map/event/node_event.dart | hyperion-hyn/titan_flutter | 8c68a99a155ea245b8d1ea26027f25a51ee9d5ae | [
"MIT"
] | 10 | 2019-12-26T06:27:42.000Z | 2021-09-23T12:13:31.000Z | lib/src/pages/atlas_map/event/node_event.dart | hyperion-hyn/titan_flutter | 8c68a99a155ea245b8d1ea26027f25a51ee9d5ae | [
"MIT"
] | null | null | null | lib/src/pages/atlas_map/event/node_event.dart | hyperion-hyn/titan_flutter | 8c68a99a155ea245b8d1ea26027f25a51ee9d5ae | [
"MIT"
] | 3 | 2020-12-01T17:17:42.000Z | 2021-07-19T10:31:14.000Z | class UpdateMap3TabsPageIndexEvent {
final int index;
UpdateMap3TabsPageIndexEvent({this.index});
}
| 17.5 | 45 | 0.790476 |
0b3e8288a9b0782427a11747eddfe8cb9d84d867 | 32,258 | sql | SQL | dbmate/db/schema.sql | security-union/armore-open | 10d123890f0b544489e328f35f1d9775a44eff22 | [
"Apache-2.0"
] | 3 | 2021-01-09T03:33:39.000Z | 2021-01-15T02:09:39.000Z | dbmate/db/schema.sql | security-union/armore-server | 10d123890f0b544489e328f35f1d9775a44eff22 | [
"Apache-2.0"
] | 14 | 2021-01-17T17:38:53.000Z | 2021-04-03T20:21:37.000Z | dbmate/db/schema.sql | security-union/armore-open | 10d123890f0b544489e328f35f1d9775a44eff22 | [
"Apache-2.0"
] | 2 | 2021-01-31T14:44:05.000Z | 2021-01-31T15:01:13.000Z | SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: uuid-ossp; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;
--
-- Name: EXTENSION "uuid-ossp"; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';
--
-- Name: accesstype; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.accesstype AS ENUM (
'Permanent',
'EmergencyOnly'
);
--
-- Name: appstate; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.appstate AS ENUM (
'Foreground',
'Background',
'UNKNOWN'
);
--
-- Name: chargingstate; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.chargingstate AS ENUM (
'ChargingUsb',
'ChargingAc',
'NotCharging',
'UNKNOWN'
);
--
-- Name: command; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.command AS ENUM (
'RefreshTelemetry'
);
--
-- Name: commandstate; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.commandstate AS ENUM (
'Created',
'Completed',
'Error'
);
--
-- Name: crudaction; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.crudaction AS ENUM (
'Insert',
'Update',
'Delete'
);
--
-- Name: invitation_status; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.invitation_status AS ENUM (
'created',
'accepted',
'rejected',
'canceled'
);
--
-- Name: invitation_type; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.invitation_type AS ENUM (
'follower',
'device'
);
--
-- Name: link_invitation_state; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.link_invitation_state AS ENUM (
'CREATED',
'ACCEPTED',
'REJECTED',
'EXPIRED'
);
--
-- Name: locationpermissionstate; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.locationpermissionstate AS ENUM (
'ALWAYS',
'USING',
'ASK',
'NEVER',
'UNKNOWN'
);
--
-- Name: os; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.os AS ENUM (
'Android',
'iOS',
'UNKNOWN'
);
--
-- Name: user_and_follower; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.user_and_follower AS (
username character varying(255),
username_follower character varying(255)
);
--
-- Name: users_to_migrate_2; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.users_to_migrate_2 AS (
username character varying(255)
);
--
-- Name: userstate; Type: TYPE; Schema: public; Owner: -
--
CREATE TYPE public.userstate AS ENUM (
'Normal',
'Emergency'
);
--
-- Name: add_friend(character varying, character varying); Type: PROCEDURE; Schema: public; Owner: -
--
CREATE PROCEDURE public.add_friend(usernamea character varying, usernameb character varying)
LANGUAGE sql
AS $$
INSERT INTO users_followers(username, username_follower, access_type, is_emergency_contact)
VALUES (usernameA, usernameB, 'Permanent', true);
INSERT INTO users_followers_state(username, username_follower)
VALUES (usernameA, usernameB);
INSERT INTO users_followers(username, username_follower, access_type, is_emergency_contact)
VALUES (usernameB, usernameA, 'Permanent', true);
INSERT INTO users_followers_state(username, username_follower)
VALUES (usernameB, usernameA);
$$;
--
-- Name: device_history(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.device_history() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO device_settings SELECT NEW.*;
RETURN NULL;
END;
$$;
--
-- Name: follow_user(character varying, character varying); Type: PROCEDURE; Schema: public; Owner: -
--
CREATE PROCEDURE public.follow_user(usernamea character varying, username_followera character varying)
LANGUAGE sql
AS $$
INSERT INTO users_followers(username, username_follower, access_type, is_emergency_contact)
VALUES (usernameA, username_followerA, 'Permanent', true);
INSERT INTO users_followers_state(username, username_follower)
VALUES (usernameA, username_followerA);
$$;
--
-- Name: migrate_users_to_users_access(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.migrate_users_to_users_access() RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
strs user_and_follower;
BEGIN
FOR strs IN
(SELECT username, username_follower FROM public.return_users_devices_that_require_migration())
LOOP
INSERT INTO users_followers (username, username_follower, access_type, is_emergency_contact) VALUES (strs.username, strs.username_follower, 'Permanent', true);
INSERT INTO users_followers_state (username, username_follower, follower_perception) VALUES (strs.username, strs.username_follower, 'Normal');
end loop;
END;
$$;
--
-- Name: migrate_users_to_users_settings_and_users_state(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.migrate_users_to_users_settings_and_users_state() RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
strs users_to_migrate_2;
BEGIN
FOR strs IN
(SELECT username FROM public.return_users_that_require_migration())
LOOP
INSERT INTO users_settings (username, followers_to_declare_emergency) VALUES (strs.username, 2);
INSERT INTO users_state (username, self_perception) VALUES (strs.username, 'Normal');
end loop;
END;
$$;
--
-- Name: remove_friend(character varying, character varying); Type: PROCEDURE; Schema: public; Owner: -
--
CREATE PROCEDURE public.remove_friend(usernamea character varying, usernameb character varying)
LANGUAGE sql
AS $$
DELETE FROM users_followers
WHERE username IN (usernameA, usernameB) AND username_follower IN (usernameA, usernameB);
DELETE FROM users_followers_state
WHERE username IN (usernameA, usernameB) AND username_follower IN (usernameA, usernameB);
$$;
--
-- Name: return_users_devices_that_require_migration(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.return_users_devices_that_require_migration() RETURNS SETOF public.user_and_follower
LANGUAGE plpgsql
AS $$
declare
rec user_and_follower;
BEGIN
for rec in
SELECT derived.username, derived.username_follower FROM (
SELECT DISTINCT ud2.username, ud1.username AS username_follower
FROM users_devices AS ud1
INNER JOIN users_devices AS ud2
ON ud1.device_id = ud2.device_id and ud1.owner = false and ud2.owner = true
EXCEPT
SELECT username, username_follower
from users_followers
) as derived
loop
return next rec;
end loop;
END;
$$;
--
-- Name: return_users_that_require_migration(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.return_users_that_require_migration() RETURNS SETOF public.users_to_migrate_2
LANGUAGE plpgsql
AS $$
declare
rec users_to_migrate_2;
BEGIN
for rec in
SELECT derived.username FROM (
SELECT username from users
EXCEPT
SELECT username
from users_settings
) as derived
loop
return next rec;
end loop;
END;
$$;
--
-- Name: unidirectional_to_bidirectional(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.unidirectional_to_bidirectional() RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
f RECORD;
BEGIN
FOR f IN SELECT username_follower, username FROM users_followers AS unidirectional_friends
EXCEPT
SELECT uf1.username_follower, uf1.username
FROM users_followers AS uf1
RIGHT JOIN users_followers AS uf2 ON uf1.username=uf2.username_follower
LOOP
CALL follow_user(f.username_follower, f.username);
END LOOP;
END;
$$;
--
-- Name: users_state_history(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.users_state_history() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO users_state_history SELECT NEW.username, NEW.self_perception;
RETURN NULL;
END;
$$;
SET default_tablespace = '';
--
-- Name: command_log; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.command_log (
username character varying(255),
device_id character varying(255),
request text,
request_timestamp timestamp without time zone,
response text,
response_timestamp timestamp without time zone,
correlation_id character varying(255)
);
--
-- Name: commands; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.commands (
username character varying(255) NOT NULL,
recipient_username character varying(255),
request text,
request_timestamp timestamp without time zone NOT NULL,
response text,
response_timestamp timestamp without time zone,
correlation_id character varying(255),
type public.command NOT NULL,
state public.commandstate NOT NULL
);
--
-- Name: device_geofence; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.device_geofence (
geofence_id integer NOT NULL,
device_id character varying(255) NOT NULL,
active boolean NOT NULL,
update_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
);
--
-- Name: device_geofence_geofence_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--
CREATE SEQUENCE public.device_geofence_geofence_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
--
-- Name: device_geofence_geofence_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--
ALTER SEQUENCE public.device_geofence_geofence_id_seq OWNED BY public.device_geofence.geofence_id;
--
-- Name: device_settings; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.device_settings (
device_id character varying(255) NOT NULL,
role character varying(255) NOT NULL,
name character varying(255) NOT NULL,
os public.os,
os_version character varying(50),
model character varying(50),
push_token character varying(255),
app_version character varying(255),
location_permission_state public.locationpermissionstate DEFAULT 'UNKNOWN'::public.locationpermissionstate NOT NULL,
is_notifications_enabled boolean,
is_background_refresh_on boolean,
is_location_services_on boolean,
is_power_save_mode_on boolean,
creation_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
);
--
-- Name: device_telemetry; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.device_telemetry (
username character varying(255) NOT NULL,
recipient_username character varying(255) NOT NULL,
encrypted_location text NOT NULL,
device_id character varying(255) NOT NULL,
creation_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
app_state public.appstate DEFAULT 'UNKNOWN'::public.appstate NOT NULL,
charging_state public.chargingstate DEFAULT 'UNKNOWN'::public.chargingstate NOT NULL,
battery_level double precision DEFAULT 0 NOT NULL,
is_charging boolean DEFAULT false NOT NULL
);
--
-- Name: devices; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.devices (
device_id character varying(255) NOT NULL,
role character varying(255) NOT NULL,
name character varying(255) NOT NULL,
os public.os DEFAULT 'UNKNOWN'::public.os,
os_version character varying(50) DEFAULT 'UNKNOWN'::character varying,
model character varying(50) DEFAULT 'UNKNOWN'::character varying,
push_token character varying(255),
app_version character varying(255),
location_permission_state public.locationpermissionstate DEFAULT 'UNKNOWN'::public.locationpermissionstate NOT NULL,
is_notifications_enabled boolean,
is_background_refresh_on boolean,
is_location_services_on boolean,
is_power_save_mode_on boolean
);
--
-- Name: geofences; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.geofences (
geofence_id integer NOT NULL,
lat double precision NOT NULL,
lon double precision NOT NULL,
radius smallint NOT NULL,
name character varying(255) DEFAULT 'PRIVATE'::character varying NOT NULL,
address character varying(255) DEFAULT 'PRIVATE'::character varying NOT NULL,
username character varying(255) DEFAULT 'PRIVATE'::character varying NOT NULL
);
--
-- Name: geofences_geofence_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--
CREATE SEQUENCE public.geofences_geofence_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
--
-- Name: geofences_geofence_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--
ALTER SEQUENCE public.geofences_geofence_id_seq OWNED BY public.geofences.geofence_id;
--
-- Name: invitations; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.invitations (
id uuid NOT NULL,
creator_username character varying(255),
target_username character varying(255),
status public.invitation_status NOT NULL,
invitation jsonb NOT NULL,
type public.invitation_type NOT NULL,
creation_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
update_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
target_email character varying(255),
target_phone_number character varying(25)
);
--
-- Name: link_invitations; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.link_invitations (
id character varying(255) NOT NULL,
state public.link_invitation_state DEFAULT 'CREATED'::public.link_invitation_state NOT NULL,
creation_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP,
expiration_timestamp timestamp without time zone NOT NULL,
creator_username character varying(255) NOT NULL,
recipient_username character varying(255) DEFAULT NULL::character varying
);
--
-- Name: schema_migrations; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.schema_migrations (
version character varying(255) NOT NULL
);
--
-- Name: user_details; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.user_details (
username character varying(255) NOT NULL,
first_name character varying(255) NOT NULL,
last_name character varying(255) NOT NULL,
picture character varying(255),
creation_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
language character varying(50) DEFAULT 'en'::character varying NOT NULL
);
--
-- Name: users; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.users (
username character varying(255) NOT NULL,
email character varying(255),
phone_number character varying(25),
CONSTRAINT phone_or_email_constraint CHECK (((phone_number IS NOT NULL) OR (email IS NOT NULL)))
);
--
-- Name: users_devices; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.users_devices (
username character varying(255) NOT NULL,
device_id character varying(255) NOT NULL,
owner boolean NOT NULL,
access_enabled boolean NOT NULL,
permissions jsonb
);
--
-- Name: users_followers; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.users_followers (
username character varying(255) NOT NULL,
username_follower character varying(255) NOT NULL,
access_type public.accesstype DEFAULT 'EmergencyOnly'::public.accesstype NOT NULL,
is_emergency_contact boolean DEFAULT false NOT NULL,
creation_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
update_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
);
--
-- Name: users_followers_state; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.users_followers_state (
username character varying(255) NOT NULL,
username_follower character varying(255) NOT NULL,
follower_perception public.userstate DEFAULT 'Normal'::public.userstate NOT NULL,
creation_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
update_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
);
--
-- Name: users_geofences; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.users_geofences (
geofence_id integer NOT NULL,
username character varying(255) NOT NULL
);
--
-- Name: users_geofences_geofence_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--
CREATE SEQUENCE public.users_geofences_geofence_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
--
-- Name: users_geofences_geofence_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--
ALTER SEQUENCE public.users_geofences_geofence_id_seq OWNED BY public.users_geofences.geofence_id;
--
-- Name: users_identity; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.users_identity (
username character varying(255) NOT NULL,
public_key text NOT NULL,
creation_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
update_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
);
--
-- Name: users_settings; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.users_settings (
username character varying(255) NOT NULL,
followers_to_declare_emergency smallint DEFAULT 2 NOT NULL,
creation_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
update_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
);
--
-- Name: users_state; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.users_state (
username character varying(255) NOT NULL,
self_perception public.userstate DEFAULT 'Normal'::public.userstate NOT NULL,
creation_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
update_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
);
--
-- Name: users_state_history; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.users_state_history (
username character varying(255) NOT NULL,
self_perception public.userstate DEFAULT 'Normal'::public.userstate NOT NULL,
creation_timestamp timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
);
--
-- Name: users_verification; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.users_verification (
verification_id uuid DEFAULT public.uuid_generate_v4() NOT NULL,
verification_code character(5) NOT NULL,
email character varying(255),
used boolean NOT NULL,
creation_timestamp timestamp without time zone NOT NULL,
updated_timestamp timestamp without time zone NOT NULL,
expiration_timestamp timestamp without time zone NOT NULL,
public_key text DEFAULT ''::text NOT NULL,
phone_number character varying(25) DEFAULT NULL::character varying,
CONSTRAINT phone_or_email_constraint CHECK (((phone_number IS NOT NULL) OR (email IS NOT NULL)))
);
--
-- Name: device_geofence geofence_id; Type: DEFAULT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.device_geofence ALTER COLUMN geofence_id SET DEFAULT nextval('public.device_geofence_geofence_id_seq'::regclass);
--
-- Name: geofences geofence_id; Type: DEFAULT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.geofences ALTER COLUMN geofence_id SET DEFAULT nextval('public.geofences_geofence_id_seq'::regclass);
--
-- Name: users_geofences geofence_id; Type: DEFAULT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_geofences ALTER COLUMN geofence_id SET DEFAULT nextval('public.users_geofences_geofence_id_seq'::regclass);
--
-- Name: device_geofence device_geofence_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.device_geofence
ADD CONSTRAINT device_geofence_pkey PRIMARY KEY (geofence_id, device_id);
--
-- Name: device_settings device_settings_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.device_settings
ADD CONSTRAINT device_settings_pkey PRIMARY KEY (device_id, creation_timestamp);
--
-- Name: devices devices_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.devices
ADD CONSTRAINT devices_pkey PRIMARY KEY (device_id);
--
-- Name: geofences geofences_geofence_id_key; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.geofences
ADD CONSTRAINT geofences_geofence_id_key UNIQUE (geofence_id);
--
-- Name: invitations invitations_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.invitations
ADD CONSTRAINT invitations_pkey PRIMARY KEY (id);
--
-- Name: link_invitations link_invitations_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.link_invitations
ADD CONSTRAINT link_invitations_pkey PRIMARY KEY (id);
--
-- Name: schema_migrations schema_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.schema_migrations
ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (version);
--
-- Name: users_devices unique_device_id; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_devices
ADD CONSTRAINT unique_device_id UNIQUE (device_id);
--
-- Name: user_details user_details_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.user_details
ADD CONSTRAINT user_details_pkey PRIMARY KEY (username);
--
-- Name: users_devices users_devices_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_devices
ADD CONSTRAINT users_devices_pkey PRIMARY KEY (username, device_id);
--
-- Name: users users_email_key; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users
ADD CONSTRAINT users_email_key UNIQUE (email);
--
-- Name: users_followers users_followers_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_followers
ADD CONSTRAINT users_followers_pkey PRIMARY KEY (username, username_follower);
--
-- Name: users_followers_state users_followers_state_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_followers_state
ADD CONSTRAINT users_followers_state_pkey PRIMARY KEY (username, username_follower);
--
-- Name: users_geofences users_geofences_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_geofences
ADD CONSTRAINT users_geofences_pkey PRIMARY KEY (geofence_id, username);
--
-- Name: users_identity users_identity_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_identity
ADD CONSTRAINT users_identity_pkey PRIMARY KEY (username);
--
-- Name: users users_phone_number_key; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users
ADD CONSTRAINT users_phone_number_key UNIQUE (phone_number);
--
-- Name: users users_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users
ADD CONSTRAINT users_pkey PRIMARY KEY (username);
--
-- Name: users_settings users_settings_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_settings
ADD CONSTRAINT users_settings_pkey PRIMARY KEY (username);
--
-- Name: users_state_history users_state_history_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_state_history
ADD CONSTRAINT users_state_history_pkey PRIMARY KEY (username, creation_timestamp);
--
-- Name: users_state users_state_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_state
ADD CONSTRAINT users_state_pkey PRIMARY KEY (username);
--
-- Name: users_verification users_verification_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_verification
ADD CONSTRAINT users_verification_pkey PRIMARY KEY (verification_id);
--
-- Name: device_telemetry_timestamp_idx; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX device_telemetry_timestamp_idx ON public.device_telemetry USING btree (creation_timestamp);
--
-- Name: devices device_history; Type: TRIGGER; Schema: public; Owner: -
--
CREATE TRIGGER device_history AFTER INSERT OR UPDATE ON public.devices FOR EACH ROW EXECUTE PROCEDURE public.device_history();
--
-- Name: users_state users_state_trigger; Type: TRIGGER; Schema: public; Owner: -
--
CREATE TRIGGER users_state_trigger AFTER INSERT OR UPDATE ON public.users_state FOR EACH ROW EXECUTE PROCEDURE public.users_state_history();
--
-- Name: device_geofence device_geofence_device_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.device_geofence
ADD CONSTRAINT device_geofence_device_id_fkey FOREIGN KEY (device_id) REFERENCES public.devices(device_id) ON DELETE CASCADE;
--
-- Name: device_geofence device_geofence_geofence_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.device_geofence
ADD CONSTRAINT device_geofence_geofence_id_fkey FOREIGN KEY (geofence_id) REFERENCES public.geofences(geofence_id) ON DELETE CASCADE;
--
-- Name: device_telemetry device_telemetry_username_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.device_telemetry
ADD CONSTRAINT device_telemetry_username_fkey FOREIGN KEY (username) REFERENCES public.users(username) ON DELETE CASCADE;
--
-- Name: device_settings fk_device; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.device_settings
ADD CONSTRAINT fk_device FOREIGN KEY (device_id) REFERENCES public.devices(device_id) ON DELETE CASCADE;
--
-- Name: users_geofences fk_geofence_id; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_geofences
ADD CONSTRAINT fk_geofence_id FOREIGN KEY (geofence_id) REFERENCES public.geofences(geofence_id) ON DELETE CASCADE;
--
-- Name: devices fk_users_devices_device_id; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.devices
ADD CONSTRAINT fk_users_devices_device_id FOREIGN KEY (device_id) REFERENCES public.users_devices(device_id) ON DELETE CASCADE;
--
-- Name: users_state_history fk_users_state; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_state_history
ADD CONSTRAINT fk_users_state FOREIGN KEY (username) REFERENCES public.users_state(username) ON DELETE CASCADE;
--
-- Name: invitations invitations_creator_username_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.invitations
ADD CONSTRAINT invitations_creator_username_fkey FOREIGN KEY (creator_username) REFERENCES public.users(username) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: invitations invitations_target_username_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.invitations
ADD CONSTRAINT invitations_target_username_fkey FOREIGN KEY (target_username) REFERENCES public.users(username) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: link_invitations link_invitations_creator_username_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.link_invitations
ADD CONSTRAINT link_invitations_creator_username_fkey FOREIGN KEY (creator_username) REFERENCES public.users(username) ON DELETE CASCADE;
--
-- Name: link_invitations link_invitations_recipient_username_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.link_invitations
ADD CONSTRAINT link_invitations_recipient_username_fkey FOREIGN KEY (recipient_username) REFERENCES public.users(username) ON DELETE CASCADE;
--
-- Name: user_details user_details_target_username_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.user_details
ADD CONSTRAINT user_details_target_username_fkey FOREIGN KEY (username) REFERENCES public.users(username) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: users_devices users_devices_target_username_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_devices
ADD CONSTRAINT users_devices_target_username_fkey FOREIGN KEY (username) REFERENCES public.users(username) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: users_followers_state users_followers_state_username_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_followers_state
ADD CONSTRAINT users_followers_state_username_fkey FOREIGN KEY (username, username_follower) REFERENCES public.users_followers(username, username_follower) ON DELETE CASCADE;
--
-- Name: users_followers users_followers_username_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_followers
ADD CONSTRAINT users_followers_username_fkey FOREIGN KEY (username) REFERENCES public.users(username) ON DELETE CASCADE;
--
-- Name: users_followers users_followers_username_follower_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_followers
ADD CONSTRAINT users_followers_username_follower_fkey FOREIGN KEY (username_follower) REFERENCES public.users(username) ON DELETE CASCADE;
--
-- Name: users_identity users_identity_username_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_identity
ADD CONSTRAINT users_identity_username_fkey FOREIGN KEY (username) REFERENCES public.users(username) ON DELETE CASCADE;
--
-- Name: users_settings users_settings_username_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_settings
ADD CONSTRAINT users_settings_username_fkey FOREIGN KEY (username) REFERENCES public.users(username) ON DELETE CASCADE;
--
-- Name: users_state users_state_username_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_state
ADD CONSTRAINT users_state_username_fkey FOREIGN KEY (username) REFERENCES public.users(username) ON DELETE CASCADE;
--
-- Name: users_verification users_verification_email_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.users_verification
ADD CONSTRAINT users_verification_email_fkey FOREIGN KEY (email) REFERENCES public.users(email) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- PostgreSQL database dump complete
--
--
-- Dbmate schema migrations
--
INSERT INTO public.schema_migrations (version) VALUES
('20151129054053'),
('20151129054054'),
('20151129054055'),
('20151129054056'),
('20151129054059'),
('20151129054060'),
('20151129054061'),
('20151129054062'),
('20151129054063'),
('20151129054064'),
('20151129054065'),
('20151129054066'),
('20151129054067'),
('20151129054068'),
('20151129054069'),
('20151129054070'),
('20151129054071'),
('20151129054072'),
('20151129054073'),
('20151129054074'),
('20151129054075'),
('20200209154800'),
('20200209154801'),
('20200209154802'),
('20200209154803'),
('20200209202641'),
('20200212001251'),
('20200215211342'),
('20200225211342'),
('20200301211342'),
('20200414211342'),
('20200418211342'),
('20200418211349'),
('20200419091342'),
('20200419211349'),
('20200419211350'),
('20200427081342'),
('20200427091342'),
('20200505091342'),
('20200521211342'),
('20200525091342'),
('20200526211342'),
('20200604091342'),
('20200606091342'),
('20200608091342'),
('20200609211342'),
('20200628133108'),
('20200629223804'),
('20200701133108'),
('20200701233108'),
('20200717001251'),
('20200724001251'),
('20200724181251'),
('20200724181252'),
('20201101010926'),
('20201101011058'),
('20201104055657'),
('20201201220557'),
('20201203230943'),
('20201204200302'),
('20201208004535'),
('20210105150805'),
('20210117221453'),
('20210130172100');
| 27.477002 | 178 | 0.742172 |
b90763cea5ed52fe313c27168cbd71e9a4cdf065 | 2,571 | c | C | testnetmask2cidr.c | dancrossnyc/44ripd | 611379dcfe3dbc757d4d7b9e3001772eb3db5f95 | [
"BSD-2-Clause"
] | 8 | 2016-12-15T22:06:38.000Z | 2021-12-20T02:42:27.000Z | testnetmask2cidr.c | dancrossnyc/44ripd | 611379dcfe3dbc757d4d7b9e3001772eb3db5f95 | [
"BSD-2-Clause"
] | 1 | 2021-10-12T12:46:10.000Z | 2021-10-12T12:51:10.000Z | testnetmask2cidr.c | dancrossnyc/44ripd | 611379dcfe3dbc757d4d7b9e3001772eb3db5f95 | [
"BSD-2-Clause"
] | 1 | 2017-02-26T19:23:50.000Z | 2017-02-26T19:23:50.000Z | #include <sys/types.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include "dat.h"
#include "fns.h"
void
testn2c(const char *snetmask, int expected)
{
if (netmask2cidr(ntohl(inet_addr(snetmask))) != expected)
printf("netmask2cidr(\"%s\") != %d\n", snetmask, expected);
}
void
testc2n(int cidr, const char *expected)
{
if (cidr2netmask(cidr) != ntohl(inet_addr(expected))) {
printf("cidr2netmask(%d) != \"%s\"\n", cidr, expected);
printf("cidr2netmask(%d) = %x\n", cidr, cidr2netmask(cidr));
}
}
int
main(void)
{
// Test all valid netmasks explicitly.
testn2c("255.255.255.255", 32);
testn2c("255.255.255.254", 31);
testn2c("255.255.255.252", 30);
testn2c("255.255.255.248", 29);
testn2c("255.255.255.240", 28);
testn2c("255.255.255.224", 27);
testn2c("255.255.255.192", 26);
testn2c("255.255.255.128", 25);
testn2c("255.255.255.0", 24);
testn2c("255.255.254.0", 23);
testn2c("255.255.252.0", 22);
testn2c("255.255.248.0", 21);
testn2c("255.255.240.0", 20);
testn2c("255.255.224.0", 19);
testn2c("255.255.192.0", 18);
testn2c("255.255.128.0", 17);
testn2c("255.255.0.0", 16);
testn2c("255.254.0.0", 15);
testn2c("255.252.0.0", 14);
testn2c("255.248.0.0", 13);
testn2c("255.240.0.0", 12);
testn2c("255.224.0.0", 11);
testn2c("255.192.0.0", 10);
testn2c("255.128.0.0", 9);
testn2c("255.0.0.0", 8);
testn2c("254.0.0.0", 7);
testn2c("252.0.0.0", 6);
testn2c("248.0.0.0", 5);
testn2c("240.0.0.0", 4);
testn2c("224.0.0.0", 3);
testn2c("192.0.0.0", 2);
testn2c("128.0.0.0", 1);
testn2c("0.0.0.0", 0);
testc2n(32, "255.255.255.255");
testc2n(31, "255.255.255.254");
testc2n(30, "255.255.255.252");
testc2n(29, "255.255.255.248");
testc2n(28, "255.255.255.240");
testc2n(27, "255.255.255.224");
testc2n(26, "255.255.255.192");
testc2n(25, "255.255.255.128");
testc2n(24, "255.255.255.0");
testc2n(23, "255.255.254.0");
testc2n(22, "255.255.252.0");
testc2n(21, "255.255.248.0");
testc2n(20, "255.255.240.0");
testc2n(19, "255.255.224.0");
testc2n(18, "255.255.192.0");
testc2n(17, "255.255.128.0");
testc2n(16, "255.255.0.0");
testc2n(15, "255.254.0.0");
testc2n(14, "255.252.0.0");
testc2n(13, "255.248.0.0");
testc2n(12, "255.240.0.0");
testc2n(11, "255.224.0.0");
testc2n(10, "255.192.0.0");
testc2n(9, "255.128.0.0");
testc2n(8, "255.0.0.0");
testc2n(7, "254.0.0.0");
testc2n(6, "252.0.0.0");
testc2n(5, "248.0.0.0");
testc2n(4, "240.0.0.0");
testc2n(3, "224.0.0.0");
testc2n(2, "192.0.0.0");
testc2n(1, "128.0.0.0");
testc2n(0, "0.0.0.0");
return 0;
}
| 25.455446 | 62 | 0.611046 |
1ce857b74710f6c2c5f1811d9daf4448c03bf58e | 301 | css | CSS | src/components/message-modal/index.css | mnafisalmukhdi1/Monogatari | 6283c5bb0c4a798c149dba30a6bc1b5309a73f2f | [
"MIT"
] | 468 | 2017-06-29T07:48:54.000Z | 2022-03-30T22:00:53.000Z | src/components/message-modal/index.css | mnafisalmukhdi1/Monogatari | 6283c5bb0c4a798c149dba30a6bc1b5309a73f2f | [
"MIT"
] | 118 | 2017-07-03T20:13:50.000Z | 2022-03-28T22:46:53.000Z | src/components/message-modal/index.css | mnafisalmukhdi1/Monogatari | 6283c5bb0c4a798c149dba30a6bc1b5309a73f2f | [
"MIT"
] | 119 | 2017-07-16T04:32:54.000Z | 2022-03-27T23:26:33.000Z | /**
* ===========================
* Message Modal Component
* ===========================
*/
message-modal {
& div {
width: auto;
padding: 1rem;
}
& a {
color: #00bcd4;
}
& [data-ui='message-content'] {
text-align: left;
max-width: 100%;
& * {
user-select: text;
}
}
} | 11.148148 | 32 | 0.418605 |
4b60383333e859a37508661de44974db46bf79ea | 5,942 | html | HTML | app/partials/profile.html | otoja/fyd | 1a04998852e7c46c63bb8298ca8cecdfb0610586 | [
"MIT"
] | null | null | null | app/partials/profile.html | otoja/fyd | 1a04998852e7c46c63bb8298ca8cecdfb0610586 | [
"MIT"
] | null | null | null | app/partials/profile.html | otoja/fyd | 1a04998852e7c46c63bb8298ca8cecdfb0610586 | [
"MIT"
] | null | null | null | <section class="center-block text-center text-uppercase row"><p class="search-job-button col-md-4 col-md-offset-4"><a href="#/">Start looking for jobs here</a></p></section>
<section id="intro" class="intro-section">
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<div class="boxcontainer">
<h1 class="red-text">CV</h1>
<div class="row">
<div class="col-md-6"><p>me04042016CV.doc</p></div>
<div class="col-md-6"><div class="buttonwrap"><a class="ghostbutton">UPLOAD NEW CV</a></div></div>
</div>
</div>
<div class="boxcontainer" >
<h1 class="red-text">SKILLS</h1>
<p>Put in your skills and rank how proficient you are at each type of skill. More skills = more opportunities.</p>
<input class="col-md-12" id="skills" placeholder="What is your expertise?" />
<div class="skills-box ng-scope" >
<div class="label label-light" ng-repeat="selectedSkill in userSkills" ng-mouseenter="selectedSkill.remove = true" ng-mouseleave="selectedSkill.remove = false;">
<span class="skill-label ng-binding">{{selectedSkill.label}}</span>
<span class="skill-remove pull-right" ng-if="selectedSkill.remove"><i class="glyphicon glyphicon-remove-circle" ng-click="removeSkill(selectedSkill)" ></i></span>
<span class="skill-level pull-right" >
<i class="glyphicon" ng-class="{
'glyphicon-star'
:selectedSkill.level >= 1, 'glyphicon-star-empty':selectedSkill.level < 1 }" ng-click="updateSkill(selectedSkill, 1)" title="Beginner"></i>
<i class="glyphicon" ng-class="{
'glyphicon-star':selectedSkill.level >= 2, 'glyphicon-star-empty':selectedSkill.level < 2 }" ng-click="updateSkill(selectedSkill, 2)" title="Novice"></i>
<i class="glyphicon" ng-class="{
'glyphicon-star':selectedSkill.level >= 3, 'glyphicon-star-empty':selectedSkill.level < 3 }" ng-click="updateSkill(selectedSkill, 3)" title="Intermeddiate"></i><br>
<i class="glyphicon" ng-class="{
'glyphicon-star'
:selectedSkill.level >= 4, 'glyphicon-star-empty':selectedSkill.level < 4 }" ng-click="updateSkill(selectedSkill, 4)" title="Advanced"></i>
<i class="glyphicon" ng-class="{
'glyphicon-star'
:selectedSkill.level >= 5, 'glyphicon-star-empty':selectedSkill.level < 5 }" ng-click="updateSkill(selectedSkill, 5)" title="Expert"></i>
</span>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="boxcontainer">
<h1 class="red-text">JOB SEARCH STATISTICS</h1>
<ul class="nav nav-tabs nav-justified" id="profileTabs">
<li role="presentation"><a data-target="#jobActivity" aria-controls="jobActivity" role="tab" data-toggle="tab">Activity</a></li>
<li role="presentation"><a data-target="#graphical" aria-controls="graphical" role="tab" data-toggle="tab">Graphical</a></li>
<li role="presentation"><a data-target="#statistics" aria-controls="statistics" role="tab" data-toggle="tab">Statistics</a></li>
</ul>
<div class="tab-content" >
<div role="tabpanel" class="tab-pane" id="jobActivity">
<table class="table table-condensed">
<thead><tr>
<!--<td>Status</td>-->
<th>Job title</th>
<th>Company</th>
<th>Date</th>
</tr></thead>
<tbody>
<tr ng-repeat="attemp in jobsAttmpsHistory">
<!--<td>{{attemp.status}}</td>-->
<td>{{attemp.jobTitle}}</td>
<td>{{attemp.company}}</td>
<td>{{attemp.appliedDate}}</td>
</tr>
</tbody>
</table>
</div>
<div role="tabpanel" class="tab-pane" id="graphical">
<div class="plotdiv" id="d7fb458d-7de5-48ac-a0b7-f577fe3066a9"></div>
</div>
<div role="tabpanel" class="tab-pane text-uppercase grey-level1-text" id="statistics">
<p class="statistics-text">Amount of attemps:
143
</p>
<p class="statistics-text">Number of jobs available {{availableJobs.length}}</p>
<p class="statistics-text">Days unemployed 143</p>
</div>
</div>
</div>
</div>
<div class="col-md-4" ng-controller="ContactDetailsController">
<div ng-include=" './app/partials/profile/ContactDetails.html'"></div>
</div>
</div>
</div>
</section>
| 65.296703 | 204 | 0.452205 |
1ba438f491af57305c504042b78b9290159ba9de | 1,353 | lua | Lua | tweaks/entities.lua | CaitSith2/CaitSith2-Krastorio-SpaceExploration-Tweaks | b501a1cc4dca74b4c4f20eab853758f5298a8775 | [
"MIT"
] | null | null | null | tweaks/entities.lua | CaitSith2/CaitSith2-Krastorio-SpaceExploration-Tweaks | b501a1cc4dca74b4c4f20eab853758f5298a8775 | [
"MIT"
] | null | null | null | tweaks/entities.lua | CaitSith2/CaitSith2-Krastorio-SpaceExploration-Tweaks | b501a1cc4dca74b4c4f20eab853758f5298a8775 | [
"MIT"
] | null | null | null | if settings.startup["cs2-tweaks-faster-machines"].value == true then
if mods["Krastorio2"] then
data.raw["assembling-machine"]["kr-electrolysis-plant"].crafting_speed = data.raw["assembling-machine"]["kr-electrolysis-plant"].crafting_speed * 5
data.raw["assembling-machine"]["kr-filtration-plant"].crafting_speed = data.raw["assembling-machine"]["kr-filtration-plant"].crafting_speed * 4
data.raw["assembling-machine"]["kr-atmospheric-condenser"].crafting_speed = data.raw["assembling-machine"]["kr-atmospheric-condenser"].crafting_speed * 2
data.raw["furnace"]["kr-crusher"].crafting_speed = data.raw["furnace"]["kr-crusher"].crafting_speed * 2
data.raw["mining-drill"]["kr-electric-mining-drill-mk3"].mining_speed = data.raw["mining-drill"]["kr-electric-mining-drill-mk3"].mining_speed * 2
data.raw["mining-drill"]["kr-electric-mining-drill-mk3"].energy_usage = "300kW"
data.raw["mining-drill"]["kr-electric-mining-drill-mk3"].module_specification = {
module_slots = 6,
end
if mods["space-exploration"] then
data.raw.item["se-core-miner"].stack_size = 5
data.raw["assembling-machine"]["se-core-miner"].crafting_speed = data.raw["assembling-machine"]["se-core-miner"].crafting_speed * 4
data.raw["mining-drill"]["se-core-miner-drill"].mining_speed = data.raw["mining-drill"]["se-core-miner-drill"].mining_speed * 4
end
end | 71.210526 | 155 | 0.73762 |
abd93fecdb4e4ec3a1c0bfa00125a13f532dd6b0 | 419 | go | Go | example/example.go | Just-maple/svc2handler | 70718c1d8cadb54a96829c34c2d471a952a4ae10 | [
"Apache-2.0"
] | null | null | null | example/example.go | Just-maple/svc2handler | 70718c1d8cadb54a96829c34c2d471a952a4ae10 | [
"Apache-2.0"
] | null | null | null | example/example.go | Just-maple/svc2handler | 70718c1d8cadb54a96829c34c2d471a952a4ae10 | [
"Apache-2.0"
] | null | null | null | package main
import (
"context"
"net/http"
"github.com/Just-maple/svc2handler"
)
type Param struct {
A int `json:"a"`
B int `json:"b"`
}
var (
wrapper = svc2handler.CreateSvcHandler(TestIO)
)
func main() {
// easy to create a server
http.HandleFunc("/add", wrapper.Handle(func(ctx context.Context, param Param) (total int) {
return param.A + param.B
}))
panic(http.ListenAndServe("0.0.0.0:80", nil))
}
| 16.115385 | 92 | 0.673031 |
f50c5fd46feb005f3a7cc11926800c1aec2b1e57 | 2,728 | hpp | C++ | ql/time/calendars/japan.hpp | reder2000/QuantLib | 1d58c3859a0872722aa570283c6571aeb64f6f39 | [
"BSD-3-Clause"
] | null | null | null | ql/time/calendars/japan.hpp | reder2000/QuantLib | 1d58c3859a0872722aa570283c6571aeb64f6f39 | [
"BSD-3-Clause"
] | 2 | 2020-12-28T06:52:54.000Z | 2021-04-07T09:41:08.000Z | ql/time/calendars/japan.hpp | reder2000/QuantLib | 1d58c3859a0872722aa570283c6571aeb64f6f39 | [
"BSD-3-Clause"
] | null | null | null | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file japan.hpp
\brief Japanese calendar
*/
#pragma once
#ifndef quantlib_japanese_calendar_hpp
#define quantlib_japanese_calendar_hpp
#include <ql/time/calendar.hpp>
namespace QuantLib {
//! Japanese calendar
/*! Holidays:
<ul>
<li>Saturdays</li>
<li>Sundays</li>
<li>New Year's Day, January 1st</li>
<li>Bank Holiday, January 2nd</li>
<li>Bank Holiday, January 3rd</li>
<li>Coming of Age Day, 2nd Monday in January</li>
<li>National Foundation Day, February 11th</li>
<li>Emperor's Birthday, February 23rd since 2020 and December 23rd before</li>
<li>Vernal Equinox</li>
<li>Greenery Day, April 29th</li>
<li>Constitution Memorial Day, May 3rd</li>
<li>Holiday for a Nation, May 4th</li>
<li>Children's Day, May 5th</li>
<li>Marine Day, 3rd Monday in July</li>
<li>Mountain Day, August 11th (from 2016 onwards)</li>
<li>Respect for the Aged Day, 3rd Monday in September</li>
<li>Autumnal Equinox</li>
<li>Health and Sports Day, 2nd Monday in October</li>
<li>National Culture Day, November 3rd</li>
<li>Labor Thanksgiving Day, November 23rd</li>
<li>Bank Holiday, December 31st</li>
<li>a few one-shot holidays</li>
</ul>
Holidays falling on a Sunday are observed on the Monday following
except for the bank holidays associated with the new year.
\ingroup calendars
*/
template <class ExtDate=Date>
class Japan : public Calendar<ExtDate> {
private:
class Impl : public Calendar<ExtDate>::Impl {
public:
std::string name() const { return "Japan"; }
bool isWeekend(Weekday) const;
bool isBusinessDay(const ExtDate&) const;
};
public:
Japan();
};
}
#include "japan.cpp"
#endif
| 34.531646 | 86 | 0.653592 |
4572cb9bf37dcf5851d2295d48a47eb2305c9088 | 115 | rs | Rust | integration-tests/build.rs | Atul9/memory-profiler | 9dbc4338a7410e62fb444abed9cb9713a4217d3c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 475 | 2021-08-18T08:10:13.000Z | 2022-03-29T07:57:52.000Z | integration-tests/build.rs | Atul9/memory-profiler | 9dbc4338a7410e62fb444abed9cb9713a4217d3c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 36 | 2020-01-03T22:54:51.000Z | 2021-08-17T05:21:41.000Z | integration-tests/build.rs | Atul9/memory-profiler | 9dbc4338a7410e62fb444abed9cb9713a4217d3c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 39 | 2021-08-18T08:48:58.000Z | 2022-03-29T01:59:24.000Z | fn main() {
println!(
"cargo:rustc-env=TARGET={}",
std::env::var( "TARGET" ).unwrap()
);
}
| 16.428571 | 42 | 0.46087 |
53c173ee549a076e857ec2fb9e53604fa2cd9013 | 8,019 | java | Java | src/main/java/com/thinkgem/jeesite/modules/tmc/modal/TmcRwsqdModal.java | 770915026/jeesite | bf358138f5afc9d856fddb86f95f6cdc2f8c6237 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/thinkgem/jeesite/modules/tmc/modal/TmcRwsqdModal.java | 770915026/jeesite | bf358138f5afc9d856fddb86f95f6cdc2f8c6237 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/thinkgem/jeesite/modules/tmc/modal/TmcRwsqdModal.java | 770915026/jeesite | bf358138f5afc9d856fddb86f95f6cdc2f8c6237 | [
"Apache-2.0"
] | null | null | null | package com.thinkgem.jeesite.modules.tmc.modal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.thinkgem.jeesite.modules.taier.entity.TmcRwsqd;
import com.thinkgem.jeesite.modules.tmc.utils.DBConnectionUtils;
public class TmcRwsqdModal {
public void save(TmcRwsqd rwsqd) throws SQLException{
Connection conn=DBConnectionUtils.getConnection();
String sql="INSERT INTO TMC9081.tmc_rwsqd("+
"SJDW, SJDWDZ, SCC, SCCDZ, ZZSMC, ZZSDZ, CD, LXRMC, YDDH, CZ,"+
" EMAIL, SBXH, JCLB, CSYJ, BGLX, YHSM, YHDBQZ, YHDBQZRQ, ZXSM, ZXRWSLYQZ,"+
" ZXRWSLYQZRQ, BBXX, XXXX, BZ, READER, WRITER, PK1, SBMC, CCCSQH, BH,"+
" DJ, EJDKXX, KCLX, SFZCCMMB, SFZCEGPRSGN, SFZCGPRSGN, SFZCGPSGN, SFZCLYGN, SFZCSYJGN, SFZCWAPI,"+
" RJBBCXFS, RJBBH, YJBBH, EDJ, EDSRDY, FSGL, EDGL, FSPL, SCDL, SCDY,"+
" ZDSRDY, SFFSJ, ZT, SQRQ, TYSM, JLSJ, SQFS, FSZS, SLBH, SBJC,"+
" SFSC, GJWWBG, BGSM, JCLBO, SFBM, SFCWAPI, SBLB, GDH, XXLB, DRFS,"+
" RWLY, DLS"+
") VALUES ("+
"?,?,?,?,?,?,?,?,?,?,"+
"?,?,?,?,?,?,?,?,?,?,"+
"?,?,?,?,?,?,?,?,?,?,"+
"?,?,?,?,?,?,?,?,?,?,"+
"?,?,?,?,?,?,?,?,?,?,"+
"?,?,?,?,?,?,?,?,?,?,"+
"?,?,?,?,?,?,?,?,?,?,"+
"?,?"+
")";
PreparedStatement ptmt=conn.prepareStatement(sql);
ptmt.setString(1, rwsqd.getSjdw());
ptmt.setString(2, rwsqd.getSjdwdz());
ptmt.setString(3, rwsqd.getScc());
ptmt.setString(4, rwsqd.getSccdz());
ptmt.setString(5, rwsqd.getZzsmc());
ptmt.setString(6, rwsqd.getZzsdz());
ptmt.setString(7, rwsqd.getCd());
ptmt.setString(8, rwsqd.getLxrmc());
ptmt.setString(9, rwsqd.getYddh());
ptmt.setString(10, rwsqd.getCz());
ptmt.setString(11, rwsqd.getEmail());
ptmt.setString(12, rwsqd.getSbxh());
ptmt.setString(13, rwsqd.getJclb());
ptmt.setString(14, rwsqd.getCsyj());
ptmt.setString(15, rwsqd.getBglx());
ptmt.setString(16, rwsqd.getYhsm());
ptmt.setString(17, rwsqd.getYhdbqz());
ptmt.setString(18, rwsqd.getYhdbqzrq());
ptmt.setString(19, rwsqd.getZxsm());
ptmt.setString(20, rwsqd.getZxrwslyqz());
ptmt.setString(21, rwsqd.getZxrwslyqzrq());
ptmt.setString(22, rwsqd.getBbxx());
ptmt.setString(23, rwsqd.getXxxx());
ptmt.setString(24, rwsqd.getBz());
ptmt.setString(25, rwsqd.getReader());
ptmt.setString(26, rwsqd.getWriter());
ptmt.setString(27, rwsqd.getPk1());
ptmt.setString(28, rwsqd.getSbmc());
ptmt.setString(29, rwsqd.getCccsqh());
ptmt.setString(30, rwsqd.getBh());
ptmt.setString(31, rwsqd.getDj());
ptmt.setString(32, rwsqd.getEjdkxx());
ptmt.setString(33, rwsqd.getKclx());
ptmt.setString(34, rwsqd.getSfzccmmb());
ptmt.setString(35, rwsqd.getSfzcegprsgn());
ptmt.setString(36, rwsqd.getSfzcgprsgn());
ptmt.setString(37, rwsqd.getSfzcgpsgn());
ptmt.setString(38, rwsqd.getSfzclygn());
ptmt.setString(39, rwsqd.getSfzcsyjgn());
ptmt.setString(40, rwsqd.getSfzcwapi());
ptmt.setString(41, rwsqd.getRjbbcxfs());
ptmt.setString(42, rwsqd.getRjbbh());
ptmt.setString(43, rwsqd.getYjbbh());
ptmt.setString(44, rwsqd.getEdj());
ptmt.setString(45, rwsqd.getEdsrdy());
ptmt.setString(46, rwsqd.getFsgl());
ptmt.setString(47, rwsqd.getEdgl());
ptmt.setString(48, rwsqd.getFspl());
ptmt.setString(49, rwsqd.getScdl());
ptmt.setString(50, rwsqd.getScdy());
ptmt.setString(51, rwsqd.getZdsrdy());
ptmt.setString(52, rwsqd.getSffsj());
ptmt.setString(53, rwsqd.getZt());
ptmt.setString(54, rwsqd.getSqrq());
ptmt.setString(55, rwsqd.getTysm());
ptmt.setString(56, rwsqd.getJlsj());
ptmt.setString(57, rwsqd.getSqfs());
ptmt.setString(58, rwsqd.getFszs());
ptmt.setString(59, rwsqd.getSlbh());
ptmt.setString(60, rwsqd.getSbjc());
ptmt.setString(61, rwsqd.getSfsc());
ptmt.setString(62, rwsqd.getGjwwbg());
ptmt.setString(63, rwsqd.getBgsm());
ptmt.setString(64, rwsqd.getJclbo());
ptmt.setString(65, rwsqd.getSfbm());
ptmt.setString(66, rwsqd.getSfcwapi());
ptmt.setString(67, rwsqd.getSblb());
ptmt.setString(68, rwsqd.getGdh());
ptmt.setString(69, rwsqd.getXxlb());
ptmt.setString(70, rwsqd.getDrfs());
ptmt.setString(71, rwsqd.getRwly());
ptmt.setString(72, rwsqd.getDls());
ptmt.execute();
}
public void update(TmcRwsqd rwsqd) throws SQLException{
Connection conn=DBConnectionUtils.getConnection();
String sql="UPDATE TMC9081.tmc_rwsqd SET "+
"SJDW=?, SJDWDZ=?, SCC=?, SCCDZ=?, ZZSMC=?, ZZSDZ=?, CD=?, LXRMC=?, YDDH=?, CZ=?,"+
" EMAIL=?, SBXH=?, JCLB=?, CSYJ=?, BGLX=?, YHSM=?, YHDBQZ=?, YHDBQZRQ=?, ZXSM=?, ZXRWSLYQZ=?,"+
" ZXRWSLYQZRQ=?, BBXX=?, XXXX=?, BZ=?, READER=?, WRITER=?,DLS=?, SBMC=?, CCCSQH=?, RWLY=?,"+
" DJ=?, EJDKXX=?, KCLX=?, SFZCCMMB=?, SFZCEGPRSGN=?, SFZCGPRSGN=?, SFZCGPSGN=?, SFZCLYGN=?, SFZCSYJGN=?, SFZCWAPI=?,"+
" RJBBCXFS=?, RJBBH=?, YJBBH=?, EDJ=?, EDSRDY=?, FSGL=?, EDGL=?, FSPL=?, SCDL=?, SCDY=?,"+
" ZDSRDY=?, SFFSJ=?, ZT=?, SQRQ=?, TYSM=?, JLSJ=?, SQFS=?, FSZS=?, SLBH=?, SBJC=?,"+
" SFSC=?, GJWWBG=?, BGSM=?, JCLBO=?, SFBM=?, SFCWAPI=?, SBLB=?, GDH=?, XXLB=?, DRFS=?"+
" WHERE pk1 = ?";
PreparedStatement ptmt=conn.prepareStatement(sql);
ptmt.setString(1, rwsqd.getSjdw());
ptmt.setString(2, rwsqd.getSjdwdz());
ptmt.setString(3, rwsqd.getScc());
ptmt.setString(4, rwsqd.getSccdz());
ptmt.setString(5, rwsqd.getZzsmc());
ptmt.setString(6, rwsqd.getZzsdz());
ptmt.setString(7, rwsqd.getCd());
ptmt.setString(8, rwsqd.getLxrmc());
ptmt.setString(9, rwsqd.getYddh());
ptmt.setString(10, rwsqd.getCz());
ptmt.setString(11, rwsqd.getEmail());
ptmt.setString(12, rwsqd.getSbxh());
ptmt.setString(13, rwsqd.getJclb());
ptmt.setString(14, rwsqd.getCsyj());
ptmt.setString(15, rwsqd.getBglx());
ptmt.setString(16, rwsqd.getYhsm());
ptmt.setString(17, rwsqd.getYhdbqz());
ptmt.setString(18, rwsqd.getYhdbqzrq());
ptmt.setString(19, rwsqd.getZxsm());
ptmt.setString(20, rwsqd.getZxrwslyqz());
ptmt.setString(21, rwsqd.getZxrwslyqzrq());
ptmt.setString(22, rwsqd.getBbxx());
ptmt.setString(23, rwsqd.getXxxx());
ptmt.setString(24, rwsqd.getBz());
ptmt.setString(25, rwsqd.getReader());
ptmt.setString(26, rwsqd.getWriter());
//ptmt.setString(27, rwsqd.getPk1());
ptmt.setString(27, rwsqd.getDls());
ptmt.setString(28, rwsqd.getSbmc());
ptmt.setString(29, rwsqd.getCccsqh());
ptmt.setString(30, rwsqd.getRwly());
//ptmt.setString(30, rwsqd.getBh());
ptmt.setString(31, rwsqd.getDj());
ptmt.setString(32, rwsqd.getEjdkxx());
ptmt.setString(33, rwsqd.getKclx());
ptmt.setString(34, rwsqd.getSfzccmmb());
ptmt.setString(35, rwsqd.getSfzcegprsgn());
ptmt.setString(36, rwsqd.getSfzcgprsgn());
ptmt.setString(37, rwsqd.getSfzcgpsgn());
ptmt.setString(38, rwsqd.getSfzclygn());
ptmt.setString(39, rwsqd.getSfzcsyjgn());
ptmt.setString(40, rwsqd.getSfzcwapi());
ptmt.setString(41, rwsqd.getRjbbcxfs());
ptmt.setString(42, rwsqd.getRjbbh());
ptmt.setString(43, rwsqd.getYjbbh());
ptmt.setString(44, rwsqd.getEdj());
ptmt.setString(45, rwsqd.getEdsrdy());
ptmt.setString(46, rwsqd.getFsgl());
ptmt.setString(47, rwsqd.getEdgl());
ptmt.setString(48, rwsqd.getFspl());
ptmt.setString(49, rwsqd.getScdl());
ptmt.setString(50, rwsqd.getScdy());
ptmt.setString(51, rwsqd.getZdsrdy());
ptmt.setString(52, rwsqd.getSffsj());
ptmt.setString(53, rwsqd.getZt());
ptmt.setString(54, rwsqd.getSqrq());
ptmt.setString(55, rwsqd.getTysm());
ptmt.setString(56, rwsqd.getJlsj());
ptmt.setString(57, rwsqd.getSqfs());
ptmt.setString(58, rwsqd.getFszs());
ptmt.setString(59, rwsqd.getSlbh());
ptmt.setString(60, rwsqd.getSbjc());
ptmt.setString(61, rwsqd.getSfsc());
ptmt.setString(62, rwsqd.getGjwwbg());
ptmt.setString(63, rwsqd.getBgsm());
ptmt.setString(64, rwsqd.getJclbo());
ptmt.setString(65, rwsqd.getSfbm());
ptmt.setString(66, rwsqd.getSfcwapi());
ptmt.setString(67, rwsqd.getSblb());
ptmt.setString(68, rwsqd.getGdh());
ptmt.setString(69, rwsqd.getXxlb());
ptmt.setString(70, rwsqd.getDrfs());
ptmt.setString(71, rwsqd.getPk1());
ptmt.execute();
}
}
| 40.296482 | 121 | 0.668413 |
a41b2d78a98527028d335769891a21ff1ce13881 | 131 | sql | SQL | src/main/java/org/jeecgframework/web/system/sql/DepartAuthGroupDao_getDepartAuthGroupByUserId.sql | lbnt1982/jeecg | 90ddf8e854ca8689d7d5a9287d4a60f40ce34316 | [
"Apache-2.0"
] | 2,138 | 2015-01-21T13:11:37.000Z | 2021-08-15T14:09:39.000Z | src/main/java/org/jeecgframework/web/system/sql/DepartAuthGroupDao_getDepartAuthGroupByUserId.sql | lbnt1982/jeecg | 90ddf8e854ca8689d7d5a9287d4a60f40ce34316 | [
"Apache-2.0"
] | 56 | 2015-12-07T07:02:24.000Z | 2021-06-25T13:56:51.000Z | src/main/java/org/jeecgframework/web/system/sql/DepartAuthGroupDao_getDepartAuthGroupByUserId.sql | lbnt1982/jeecg | 90ddf8e854ca8689d7d5a9287d4a60f40ce34316 | [
"Apache-2.0"
] | 1,329 | 2015-01-13T05:23:30.000Z | 2021-08-13T16:20:07.000Z | select dag.* from t_s_depart_auth_group as dag join t_s_depart_authg_manager as dam on dam.group_id=dag.id where user_id = :userId | 131 | 131 | 0.824427 |
5afcd78de08ada35c35be8e2d0440e2133237ab5 | 237 | asm | Assembly | test/decoder/generated.asm | fotcorn/x86emu | 3e7a24a275ffc81b6eb89ea5e5e7174458b912a2 | [
"MIT"
] | 18 | 2017-01-19T20:15:54.000Z | 2021-10-04T04:26:03.000Z | test/decoder/generated.asm | fotcorn/x86emu | 3e7a24a275ffc81b6eb89ea5e5e7174458b912a2 | [
"MIT"
] | 4 | 2017-04-09T23:36:30.000Z | 2017-07-18T15:41:34.000Z | test/decoder/generated.asm | fotcorn/x86emu | 3e7a24a275ffc81b6eb89ea5e5e7174458b912a2 | [
"MIT"
] | 3 | 2020-03-16T00:30:57.000Z | 2020-09-28T03:36:04.000Z | .text
.global _start
_start:
push %rax
push %rbx
push %rcx
push %rdx
push %rsp
push %rbp
push %rsi
push %rdi
mov %eax,%eax
mov %ebx,%ebx
mov %ecx,%ecx
mov %edx,%edx
mov %esp,%esp
mov %ebp,%ebp
mov %esi,%esi
mov %edi,%edi
int $0x80
| 10.772727 | 15 | 0.662447 |
8c016264ee874b770b24542f9ffc958be101d80b | 8,247 | cpp | C++ | ext/opencv/window.cpp | ser1zw/ruby-opencv | 819445de3a83d956e94bc9ccdab81a78f2c437f6 | [
"BSD-3-Clause"
] | 7 | 2015-01-21T03:26:03.000Z | 2020-07-06T13:46:49.000Z | ext/opencv/window.cpp | ser1zw/ruby-opencv | 819445de3a83d956e94bc9ccdab81a78f2c437f6 | [
"BSD-3-Clause"
] | null | null | null | ext/opencv/window.cpp | ser1zw/ruby-opencv | 819445de3a83d956e94bc9ccdab81a78f2c437f6 | [
"BSD-3-Clause"
] | null | null | null | /************************************************************
window.cpp -
$Author: lsxi $
Copyright (C) 2005-2006 Masakazu Yonekura
************************************************************/
#include "window.h"
/*
* Document-class: OpenCV::GUI::Window
*
* Simple Window wedget to show images(CvMat/IplImage).
*
* Sample:
* image = OpenCV::IplImage::load("opencv.bmp") #=> load image
* window = OpenCV::GUI::Window.new("simple viewer")#=> create new window named "simaple viewer"
* window.show(image) #=> show image
*/
__NAMESPACE_BEGIN_OPENCV
__NAMESPACE_BEGIN_GUI
__NAMESPACE_BEGIN_WINDOW
int num_windows = 0;
VALUE rb_klass;
VALUE
rb_class()
{
return rb_klass;
}
void
define_ruby_class()
{
if (rb_klass)
return;
/*
* opencv = rb_define_module("OpenCV");
* GUI = rb_define_module_under(opencv, "GUI");
*
* note: this comment is used by rdoc.
*/
VALUE GUI = rb_module_GUI();
rb_klass = rb_define_class_under(GUI, "Window", rb_cObject);
rb_define_alloc_func(rb_klass, rb_allocate);
rb_define_private_method(rb_klass, "initialize", RUBY_METHOD_FUNC(rb_initialize), -1);
rb_define_method(rb_klass, "alive?", RUBY_METHOD_FUNC(rb_alive_q), 0);
rb_define_method(rb_klass, "destroy", RUBY_METHOD_FUNC(rb_destroy), 0);
rb_define_singleton_method(rb_klass, "destroy_all", RUBY_METHOD_FUNC(rb_destroy_all), 0);
rb_define_method(rb_klass, "resize", RUBY_METHOD_FUNC(rb_resize), -1);
rb_define_method(rb_klass, "move", RUBY_METHOD_FUNC(rb_move), -1);
rb_define_method(rb_klass, "show_image", RUBY_METHOD_FUNC(rb_show_image), 1);
rb_define_alias(rb_klass, "show", "show_image");
rb_define_method(rb_klass, "set_trackbar", RUBY_METHOD_FUNC(rb_set_trackbar), -1);
rb_define_method(rb_klass, "set_mouse_callback", RUBY_METHOD_FUNC(rb_set_mouse_callback), -1);
rb_define_alias(rb_klass, "on_mouse", "set_mouse_callback");
}
VALUE
rb_allocate(VALUE klass)
{
Window *ptr;
return Data_Make_Struct(klass, Window, window_mark, window_free, ptr);
}
void
window_mark(void *ptr)
{
Window* window_ptr = (Window*)ptr;
rb_gc_mark(window_ptr->name);
rb_gc_mark(window_ptr->image);
rb_gc_mark(window_ptr->trackbars);
rb_gc_mark(window_ptr->blocks);
}
void
window_free(void *ptr)
{
free(ptr);
}
/*
* call-seq:
* new(<i>name[, flags]</i>)
*
* Create new window named <i>name</i>.
* If <i>flags</i> is CV_WINDOW_AUTOSIZE (default), window size automatically resize when image given.
*/
VALUE
rb_initialize(int argc, VALUE *argv, VALUE self)
{
VALUE name, flags;
rb_scan_args(argc, argv, "11", &name, &flags);
Check_Type(name, T_STRING);
char* name_str = StringValueCStr(name);
if (cvGetWindowHandle(name_str) != NULL) {
rb_raise(rb_eStandardError, "window name should be unique.");
}
int mode = CV_WINDOW_AUTOSIZE;
if (argc == 2) {
Check_Type(flags, T_FIXNUM);
mode = FIX2INT(flags);
}
Window* self_ptr = WINDOW(self);
self_ptr->name = name;
self_ptr->trackbars = rb_ary_new();
self_ptr->blocks = rb_ary_new();
try {
cvNamedWindow(name_str, mode);
}
catch (cv::Exception& e) {
raise_cverror(e);
}
num_windows++;
return self;
}
/*
* Return alive status of window. Return true if alive, otherwise return false.
*/
VALUE
rb_alive_q(VALUE self)
{
const char* name_str = GET_WINDOW_NAME(self);
return (cvGetWindowHandle(name_str) == NULL) ? Qfalse : Qtrue;
}
/*
* Destroys a window. alive status of window be false.
*/
VALUE
rb_destroy(VALUE self)
{
const char* name_str = GET_WINDOW_NAME(self);
try {
cvDestroyWindow(name_str);
}
catch (cv::Exception& e) {
raise_cverror(e);
}
num_windows--;
return self;
}
/*
* Destorys all the windows.
*/
VALUE
rb_destroy_all(VALUE klass)
{
if (num_windows > 0) {
try {
cvDestroyAllWindows();
}
catch (cv::Exception& e) {
raise_cverror(e);
}
num_windows = 0;
}
return Qnil;
}
/*
* call-seq:
* resize(<i>size</i>)
* resize(<i>width, height</i>)
*
* Set window size.
*/
VALUE
rb_resize(int argc, VALUE *argv, VALUE self)
{
int width = 0;
int height = 0;
switch (argc) {
case 1: {
CvSize size = VALUE_TO_CVSIZE(argv[0]);
width = size.width;
height = size.height;
break;
}
case 2:
width = NUM2INT(argv[0]);
height = NUM2INT(argv[1]);
break;
default:
rb_raise(rb_eArgError, "wrong number of arguments (1 or 2)");
break;
}
try {
cvResizeWindow(GET_WINDOW_NAME(self), width, height);
}
catch (cv::Exception& e) {
raise_cverror(e);
}
return self;
}
/*
* call-seq:
* move(<i>point</i>)
* move(<i>x, y</i>)
*
* Set window position.
*/
VALUE
rb_move(int argc, VALUE *argv, VALUE self)
{
int x = 0;
int y = 0;
switch (argc) {
case 1: {
CvPoint point = VALUE_TO_CVPOINT(argv[0]);
x = point.x;
y = point.y;
break;
}
case 2:
x = NUM2INT(argv[0]);
y = NUM2INT(argv[1]);
break;
default:
rb_raise(rb_eArgError, "wrong number of arguments (1 or 2)");
break;
}
try {
cvMoveWindow(GET_WINDOW_NAME(self), x, y);
}
catch (cv::Exception& e) {
raise_cverror(e);
}
return self;
}
/*
* call-seq:
* show_image(<i>image</i>)
*
* Show the image. If the window was created with <i>flags</i> = CV_WINDOW_AUTOSIZE then the image is shown
* with its original size, otherwize the image is scaled to fit the window.
*/
VALUE
rb_show_image(VALUE self, VALUE img)
{
CvArr* image = CVARR_WITH_CHECK(img);
WINDOW(self)->image = img;
try {
cvShowImage(GET_WINDOW_NAME(self), image);
}
catch (cv::Exception& e) {
raise_cverror(e);
}
return self;
}
void
trackbar_callback(int value, void* block)
{
rb_funcall((VALUE)block, rb_intern("call"), 1, INT2NUM(value));
}
/*
* call-seq:
* set_trackbar(<i>trackbar</i>)
* set_trackbar(<i>name,maxval[,val],&block</i>)
* set_trackbar(<i>name,maxval[,val]</i>){|value| ... }
*
* Create Trackbar on this window. Return new Trackbar.
* see Trackbar.new
*/
VALUE
rb_set_trackbar(int argc, VALUE *argv, VALUE self)
{
VALUE trackbar;
if (argc == 1) {
trackbar = argv[0];
}
else {
trackbar = cTrackbar::rb_initialize(argc, argv, cTrackbar::rb_allocate(cTrackbar::rb_class()));
}
Trackbar *trackbar_ptr = TRACKBAR_WITH_CHECK(trackbar);
try {
cv::createTrackbar(trackbar_ptr->name, GET_WINDOW_NAME(self), &(trackbar_ptr->val), trackbar_ptr->maxval,
(cv::TrackbarCallback)trackbar_callback, (void*)(trackbar_ptr->block));
}
catch (cv::Exception& e) {
raise_cverror(e);
}
rb_ary_push(WINDOW(self)->trackbars, trackbar);
return trackbar;
}
void
on_mouse(int event, int x, int y, int flags, void* param)
{
VALUE block = (VALUE)param;
if (rb_obj_is_kind_of(block, rb_cProc)) {
rb_funcall(block, rb_intern("call"), 1, cMouseEvent::new_object(event, x, y, flags));
}
}
/*
* call-seq:
* set_mouse_callback(&block)
* set_mouse_callback {|mouse_event| ... }
*
* Set mouse callback.
* When the mouse is operated on the window, block will be called.
* Return Proc object.
* block given mouse event object, see GUI::Window::MouseEvent
*
* e.g. display mouse event on console.
* window = OpenCV::GUI::Window.new "sample window"
* image = OpenCV::IplImage::load "sample.png"
* window.show(image)
* window.set_mouse_callback {|mouse|
* e = "#{mouse.x}, #{mouse.y} : #{mouse.event} : "
* e << "<L>" if mouse.left_button?
* e << "<R>" if mouse.right_button?
* e << "<M>" if mouse.middle_button?
* e << "[CTRL]" if mouse.ctrl_key?
* e << "[SHIFT]" if mouse.shift_key?
* e << "[ALT]" if mouse.alt_key?
* puts e
* }
* OpenCV::GUI::wait_key
*/
VALUE
rb_set_mouse_callback(int argc, VALUE* argv, VALUE self)
{
if (!rb_block_given_p()) {
rb_raise(rb_eArgError, "block not given.");
}
VALUE block = Qnil;
rb_scan_args(argc, argv, "0&", &block);
try {
cvSetMouseCallback(GET_WINDOW_NAME(self), on_mouse, (void*)block);
}
catch (cv::Exception& e) {
raise_cverror(e);
}
rb_ary_push(WINDOW(self)->blocks, block);
return block;
}
__NAMESPACE_END_WINDOW
__NAMESPACE_END_GUI
__NAMESPACE_END_OPENCV
| 23.036313 | 109 | 0.647508 |
8963df458e6600776cebfc21a2e10f485238311a | 516 | dart | Dart | rent_finder/lib/logic/my_houses/my_houses_event.dart | Longsans/rent-finder | c6dec824b408513f38ed18b5ba2cfe39c64e36ca | [
"Apache-2.0"
] | null | null | null | rent_finder/lib/logic/my_houses/my_houses_event.dart | Longsans/rent-finder | c6dec824b408513f38ed18b5ba2cfe39c64e36ca | [
"Apache-2.0"
] | 1 | 2021-07-08T15:22:07.000Z | 2021-07-08T15:22:07.000Z | rent_finder/lib/logic/my_houses/my_houses_event.dart | Longsans/rent-finder | c6dec824b408513f38ed18b5ba2cfe39c64e36ca | [
"Apache-2.0"
] | 3 | 2021-07-01T17:02:07.000Z | 2021-12-20T10:18:40.000Z | part of 'my_houses_bloc.dart';
abstract class MyHousesEvent extends Equatable {
const MyHousesEvent();
@override
List<Object> get props => [];
}
class LoadMyHouses extends MyHousesEvent {
final String userUid;
LoadMyHouses({this.userUid});
@override
List<Object> get props => [userUid];
}
class EditMyHouses extends MyHousesEvent {}
class MyHousesUpdate extends MyHousesEvent {
final List<model.House> houses;
MyHousesUpdate(this.houses);
@override
List<Object> get props => [houses];
}
| 19.111111 | 48 | 0.732558 |
3ca742a877ac16e249e1de0fd0a0c0f79e2549b4 | 4,658 | dart | Dart | mood/lib/views/Map/map.dart | HenryZheng1998/Mobile-Dev-Project | f08f5e61e4f4595571b61f7cdae35c888ad27dd5 | [
"MIT"
] | null | null | null | mood/lib/views/Map/map.dart | HenryZheng1998/Mobile-Dev-Project | f08f5e61e4f4595571b61f7cdae35c888ad27dd5 | [
"MIT"
] | null | null | null | mood/lib/views/Map/map.dart | HenryZheng1998/Mobile-Dev-Project | f08f5e61e4f4595571b61f7cdae35c888ad27dd5 | [
"MIT"
] | null | null | null | //imports
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong/latlong.dart';
import 'location.dart';
import 'package:geolocator/geolocator.dart';
//map class to display map
class Map extends StatefulWidget {
Map({Key key, this.title}) : super(key: key);
final String title;
@override
_MapState createState() => _MapState();
}
class _MapState extends State<Map> {
//hardcoded centre of the map
final centre = LatLng(43.9457842, -78.895896);
var _geolocator = Geolocator();
//empty locations array for
List<Location> _locations = [];
double _lat;
double _long;
List<LatLng> _path = [];
MapController _mapctl = MapController();
double _zoom;
//for the geolocator to put in a point on the map
void updateLocationOneTime() {
_geolocator
.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best,
) // Get the Lat and Long
.then((Position userLocation) {
setState(() {
print(userLocation);
_lat = userLocation.latitude;
_long = userLocation.longitude;
});
// Get the placemark name and address
_geolocator
.placemarkFromCoordinates(_lat, _long)
.then((List<Placemark> places) {
print('Reverse geocoding results');
for (Placemark place in places) {
Location currentPlace = Location();
print(place.name);
currentPlace.name = place.name;
currentPlace.address =
place.subThoroughfare + " " + place.thoroughfare;
currentPlace.latlng = LatLng(_lat, _long);
setState(() {
_locations.add(currentPlace);
});
}
});
});
}
// zoom the map out
void zoomOut(MapController _controller) {
_zoom = _controller.zoom;
if (_zoom > 11.0) {
_zoom = _zoom - 1;
_controller.move(_controller.center, _zoom);
setState(() {
});
}
}
//zoom the map in
void zoomIn(MapController _controller) {
_zoom = _controller.zoom;
if (_zoom < 16.0) {
_zoom = _zoom + 1;
_controller.move(_controller.center, _zoom);
setState(() {
});
}
}
@override
Widget build(BuildContext context) {
//check the location status
_geolocator
.checkGeolocationPermissionStatus()
.then((GeolocationStatus status) {
print('Geolocation status: $status');
});
return Scaffold(
appBar: AppBar(title: Text("Map"),
actions: <Widget>[
//displays the zoom out button
IconButton(icon: Icon(Icons.zoom_out), onPressed: () {zoomOut(_mapctl);},),
//displays the zoom in button
IconButton(icon: Icon(Icons.zoom_in), onPressed: () {zoomIn(_mapctl);},),
],),
body: FlutterMap(
mapController: _mapctl,
options: MapOptions(
minZoom: 11.0,
maxZoom: 16.0,
center: centre,
),
layers: [
//mapbox map
TileLayerOptions(
urlTemplate:
'https://api.mapbox.com/styles/v1/paul4411/ckife0zyn4il21akuuw0eb46m/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoicGF1bDQ0MTEiLCJhIjoiY2tpZmRzNnNvMDRtbjJ3cXB6Ym0wZHNxdSJ9.yYcm9lA6cQJII8ukPAp7wA',
additionalOptions: {
'accessToken':
'pk.eyJ1IjoicGF1bDQ0MTEiLCJhIjoiY2tpZmRzNnNvMDRtbjJ3cXB6Ym0wZHNxdSJ9.yYcm9lA6cQJII8ukPAp7wA',
'id': 'mapbox.mapbox-streets-v8'
}
),
//diaplays all of the markers that have been set
MarkerLayerOptions(markers: _locations
.map((location) => Marker(
width: 45.0,
height: 45.0,
point: location.latlng,
builder: (context) => Container(
child: IconButton(
icon: Icon(Icons.location_on),
color: Colors.blue,
iconSize: 45.0,
onPressed: () {
print('Marker clicked');
},
),
),
))
.toList()),
PolylineLayerOptions(
polylines: [
Polyline(
points: _path,
strokeWidth: 2.0,
color: Colors.blue,
),
],
),
],
),
//button to input marker
floatingActionButton: FloatingActionButton(
onPressed: () => updateLocationOneTime(),
child: Icon(Icons.add),
),
);
}
} | 28.753086 | 209 | 0.558179 |
217838d08abd3e03a566ce6f25285a7dbbd21de3 | 511 | lua | Lua | resources/[scripts]/[base]/esx_customui/server.lua | tracid56/Andresya | 2454e0400fc036403b19d45de00ef0f45edece19 | [
"MIT"
] | 1 | 2020-01-09T06:27:14.000Z | 2020-01-09T06:27:14.000Z | resources/[scripts]/[HUD]/esx_customui/server.lua | Zellyyn/RedSide | afc7b441345b1b468ed5b99c0153ee7696784756 | [
"MIT"
] | null | null | null | resources/[scripts]/[HUD]/esx_customui/server.lua | Zellyyn/RedSide | afc7b441345b1b468ed5b99c0153ee7696784756 | [
"MIT"
] | 2 | 2020-06-07T03:53:47.000Z | 2020-09-11T13:03:37.000Z | TriggerEvent('es:addCommand', 'togglehud', function(source, args)
if not args then
TriggerClientEvent('chatMessage', source, "[SYNTAX]", {255, 0, 0}, "/togglehud [on/off]")
else
local a = tostring(args[1])
if a == "off" then
TriggerClientEvent('ui:toggle', source,false)
elseif a == "on" then
TriggerClientEvent('ui:toggle', source,true)
else
TriggerClientEvent('chatMessage', source, "[SYNTAX]", {255, 0, 0}, "/togglehud [on/off]")
end
end
end, {help = "Toggles the hud on and off"})
| 34.066667 | 93 | 0.667319 |
043dba9c54cb21fb179e48ba1c8a7f7a3fcaf778 | 22,694 | java | Java | hetu-heuristic-index/src/main/java/io/hetu/core/plugin/heuristicindex/index/bitmap/BitMapIndex.java | ufolr/hetu-core | 2b6401b63fa305b2d2e69029b8a7438ed783e8ad | [
"Apache-2.0"
] | null | null | null | hetu-heuristic-index/src/main/java/io/hetu/core/plugin/heuristicindex/index/bitmap/BitMapIndex.java | ufolr/hetu-core | 2b6401b63fa305b2d2e69029b8a7438ed783e8ad | [
"Apache-2.0"
] | null | null | null | hetu-heuristic-index/src/main/java/io/hetu/core/plugin/heuristicindex/index/bitmap/BitMapIndex.java | ufolr/hetu-core | 2b6401b63fa305b2d2e69029b8a7438ed783e8ad | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.plugin.heuristicindex.index.bitmap;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.airlift.slice.Slice;
import io.prestosql.spi.heuristicindex.Index;
import io.prestosql.spi.heuristicindex.Operator;
import io.prestosql.spi.predicate.Domain;
import io.prestosql.spi.predicate.Marker;
import io.prestosql.spi.predicate.Range;
import io.prestosql.spi.predicate.SortedRangeSet;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.druid.collections.bitmap.ImmutableBitmap;
import org.apache.druid.data.input.MapBasedInputRow;
import org.apache.druid.data.input.impl.DimensionsSpec;
import org.apache.druid.data.input.impl.StringDimensionSchema;
import org.apache.druid.data.input.impl.TimestampSpec;
import org.apache.druid.jackson.DefaultObjectMapper;
import org.apache.druid.java.util.common.granularity.Granularities;
import org.apache.druid.math.expr.ExprMacroTable;
import org.apache.druid.query.BitmapResultFactory;
import org.apache.druid.query.DefaultBitmapResultFactory;
import org.apache.druid.query.filter.BoundDimFilter;
import org.apache.druid.query.filter.DimFilter;
import org.apache.druid.query.filter.Filter;
import org.apache.druid.query.filter.InDimFilter;
import org.apache.druid.query.filter.NotDimFilter;
import org.apache.druid.query.filter.OrDimFilter;
import org.apache.druid.query.filter.SelectorDimFilter;
import org.apache.druid.query.ordering.StringComparator;
import org.apache.druid.query.ordering.StringComparators;
import org.apache.druid.segment.ColumnSelectorBitmapIndexSelector;
import org.apache.druid.segment.IndexIO;
import org.apache.druid.segment.IndexMergerV9;
import org.apache.druid.segment.IndexSpec;
import org.apache.druid.segment.QueryableIndex;
import org.apache.druid.segment.VirtualColumns;
import org.apache.druid.segment.filter.AndFilter;
import org.apache.druid.segment.filter.TrueFilter;
import org.apache.druid.segment.incremental.IncrementalIndex;
import org.apache.druid.segment.incremental.IncrementalIndexSchema;
import org.apache.druid.segment.writeout.OffHeapMemorySegmentWriteOutMediumFactory;
import org.roaringbitmap.IntIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
/**
* This BitMapIndexV2 will create and apply the filter for only one column data
* Therefore, one druid segment class should be enough to hold the data.
* <p>
* The soomsh file can support upto 2GB,
* however, for Druid to operate well under heavy query load, it is important
* for the segment file size to be within the recommended range of 300mb-700mb.
* (https://druid.apache.org/docs/latest/design/segments.html)
* If your segment files are larger than this range, then consider either
* changing the granularity of the time interval or partitioning your data
* and tweaking the targetPartitionSize in your partitionsSpec (a good
* starting point for this parameter is 5 million rows).
*/
public class BitMapIndex<T>
implements Index<T>
{
static final int DEFAULT_EXPECTED_NUM_OF_SIZE = 200000;
private static final Logger LOG = LoggerFactory.getLogger(BitMapIndex.class);
private static final String COLUMN_NAME = "column";
private static final String ID = "BITMAP";
private static final Charset CHARSET = StandardCharsets.ISO_8859_1;
private static final char HEADER_TERMINATOR = '#';
private static final String HEADER_FILE_INFO_SEPARATOR = ",";
private static final String HEADER_FILE_INFO_PROPERTY_SEPARATOR = ":";
private static final String SETTINGS = " {\n" +
" \t\"bitmap\": {\n" +
" \t\t\"type\": \"roaring\"\n" +
" \t},\n" +
" \t\"dimensionCompression\": \"lz4\",\n" +
" \t\"metricCompression\": \"lz4\",\n" +
" \t\"longEncoding\": \"auto\"\n" +
" }";
// when the index is initialized an IncrementalIndex is created
// and values can be added to it
// this IncrementalIndex can then be persisted to disk.
// until the index is persisted to disk, it only provides write operation
// it cannot be queried!
// i.e. only values can be added to it, to query the index, it must
// be written to disk then read so a QueryableIndex can be obtained
//
// when the persisted index is loaded from disk a QueryableIndex
// is returned, this only provides the ability to read and query the index
// i.e.an existing index can't be modified
// if new values need to be added, a new index must be created
// via IncrementalIndex and all values must be added again
// therefore the flow should be:
// 1. initialize IncrementalIndex
// 2. add values
// 3. write IncrementalIndex to disk
// 4. load index from disk and get QueryableIndex
// 5. query the QueryableIndex
private IncrementalIndex incrementalIndex;
private QueryableIndex queryableIndex;
private AtomicLong rows = new AtomicLong();
private int expectedNumOfEntries = DEFAULT_EXPECTED_NUM_OF_SIZE;
private long memorySize;
public BitMapIndex()
{
}
/**
* Loads index that was previously persisted to this dir.
* The return QueryableIndex can then be queried.
*
* @param indexDir
* @return
* @throws IOException
*/
private static QueryableIndex load(File indexDir) throws IOException
{
ObjectMapper jsonMapper = new DefaultObjectMapper();
InjectableValues.Std injectableValues = new InjectableValues.Std();
injectableValues.addValue(ExprMacroTable.class, ExprMacroTable.nil());
jsonMapper.setInjectableValues(injectableValues);
IndexIO indexIo = new IndexIO(jsonMapper, () -> 0);
QueryableIndex queryIndex = indexIo.loadIndex(indexDir);
return queryIndex;
}
/**
* Persist the given IncrementalIndex to disk, it can then be loaded
* to get a QueryableIndex
*
* @param incrementalIndex
* @param outputDir
* @throws IOException
*/
private static void persist(IncrementalIndex incrementalIndex, File outputDir) throws IOException
{
ObjectMapper jsonMapper = new DefaultObjectMapper();
InjectableValues.Std injectableValues = new InjectableValues.Std();
injectableValues.addValue(ExprMacroTable.class, ExprMacroTable.nil());
jsonMapper.setInjectableValues(injectableValues);
IndexIO indexIo = new IndexIO(jsonMapper, () -> 0);
IndexMergerV9 indexMergerV9 = new IndexMergerV9(jsonMapper, indexIo, OffHeapMemorySegmentWriteOutMediumFactory.instance());
ObjectMapper objectMapper = new ObjectMapper();
IndexSpec indexSpec = objectMapper.readValue(SETTINGS, IndexSpec.class);
indexMergerV9.persist(incrementalIndex,
outputDir,
indexSpec,
null);
}
/**
* Given a Domain, extract the DimFilters
* <p>
* Supported operators: IN, Between, >=, >, <=, <, !=, Not IN
*
* @param predicate
* @return
*/
private static List<DimFilter> predicateToFilter(Domain predicate)
{
List<String> in = new ArrayList<>();
List<DimFilter> orFilters = new ArrayList<>();
List<DimFilter> filterList = new ArrayList<>();
DimFilter newFilter;
String lower;
String upper;
Boolean lowerStrict;
Boolean upperStrict;
List<Range> ranges = ((SortedRangeSet) (predicate.getValues())).getOrderedRanges();
Class<?> javaType = predicate.getValues().getType().getJavaType();
StringComparator comparator = (javaType == long.class || javaType == double.class) ?
new StringComparators.AlphanumericComparator() :
new StringComparators.LexicographicComparator();
for (Range range : ranges) {
// unique value(for example: id=1, id in (1,2)), bound: EXACTLY
if (range.isSingleValue()) {
String dimensionValue;
dimensionValue = String.valueOf(rangeValueToString(range.getSingleValue(), javaType));
in.add(dimensionValue);
}
// with upper/lower value, bound: ABOVE/BELOW
else {
lower = (range.getLow().getValueBlock().isPresent()) ?
String.valueOf(rangeValueToString(range.getLow().getValue(), javaType)) : null;
upper = (range.getHigh().getValueBlock().isPresent()) ?
String.valueOf(rangeValueToString(range.getHigh().getValue(), javaType)) : null;
lowerStrict = (lower != null) ? range.getLow().getBound() == Marker.Bound.ABOVE : null;
upperStrict = (upper != null) ? range.getHigh().getBound() == Marker.Bound.BELOW : null;
// dimension is not null(druid is not support int is not null, return all)
newFilter = (lower == null && upper == null) ?
new NotDimFilter(new SelectorDimFilter(COLUMN_NAME, null, null)) :
new BoundDimFilter(COLUMN_NAME, lower, upper, lowerStrict, upperStrict, null, null, comparator);
filterList.add(newFilter);
// NOT IN (3,4), there are three boundDimFilters ("id < 3", "3 < id < 4", "id > 4")
// != 3, three are two boundDimFilters ("id < 3", "id > 3")
if (newFilter instanceof BoundDimFilter) {
orFilters.add(newFilter);
}
}
}
// operate is IN / =
if (in.size() != 0) {
newFilter = new InDimFilter(COLUMN_NAME, in, null);
filterList.add(newFilter);
}
// NOT IN (3,4) become "id < 3" or "3 < id < 4" or "id > 4"
// != 3 become "id < 3" or "id > 3"
if (orFilters.size() > 1) {
filterList.removeAll(orFilters);
filterList.add(new OrDimFilter(orFilters));
}
// operate IS NULL (druid is not support int is null)
if (ranges.isEmpty() && javaType == Slice.class) {
newFilter = new SelectorDimFilter(COLUMN_NAME, null, null);
filterList.add(newFilter);
}
return filterList;
}
/**
* <pre>
* get range value, if it is slice, we should change it to string
* </pre>
*
* @param object value
* @param javaType value java type
* @return string
*/
private static String rangeValueToString(Object object, Class<?> javaType)
{
return javaType == Slice.class ? ((Slice) object).toStringUtf8() : object.toString();
}
@Override
public <I> Iterator<I> getMatches(Object filter)
{
Map<Index, Object> self = new HashMap<>();
self.put(this, filter);
return getMatches(self);
}
@Override
public String getId()
{
return ID;
}
/**
* input as one column values
*
* @param values values to add
*/
@Override
public void addValues(T[] values)
{
for (T value : values) {
Map<String, Object> events = new LinkedHashMap<>();
events.put(COLUMN_NAME, value);
MapBasedInputRow mapBasedInputRow = new MapBasedInputRow(rows.get(), Collections.singletonList(COLUMN_NAME), events);
try {
getOrInitIncrementalIndex().add(mapBasedInputRow);
}
catch (IOException e) {
throw new RuntimeException(e);
}
rows.incrementAndGet();
}
}
/**
* Bitmap requires a Domain as the value, the Domain will already include what kind
* of operation is being performed, therefore the operator parameter is not required.
*
* @param operator not required since value should be a Domain
* @return
*/
@Override
public boolean matches(Object value, Operator operator)
throws IllegalArgumentException
{
if (!(value instanceof Domain)) {
throw new IllegalArgumentException("Value must be a Domain.");
}
Iterator iterator = getMatches(value);
if (iterator == null) {
throw new IllegalArgumentException("Operation not supported.");
}
return iterator.hasNext();
}
@Override
public boolean supports(Operator operator)
{
switch (operator) {
case EQUAL:
case LESS_THAN:
case LESS_THAN_OR_EQUAL:
case GREATER_THAN:
case GREATER_THAN_OR_EQUAL:
return true;
default:
return false;
}
}
@Override
public void persist(OutputStream out) throws IOException
{
File tmpDir = new File(FileUtils.getTempDirectory(), "bitmapsIndexTmp_" + UUID.randomUUID());
try {
File indexOutDir = new File(tmpDir, "indexOutDir");
if (!indexOutDir.exists()) {
indexOutDir.mkdirs();
}
// write index files to directory
persist(getOrInitIncrementalIndex(), indexOutDir);
// convert the files in the directory into a single stream
combineDirIntoStream(out, indexOutDir);
}
finally {
FileUtils.deleteDirectory(tmpDir);
}
}
@Override
public void load(InputStream in) throws IOException
{
File tmpDir = new File(FileUtils.getTempDirectory(), "bitmapsIndexTmp_" + UUID.randomUUID());
try {
File indexExtractDir = new File(tmpDir, "indexExtractDir");
if (!indexExtractDir.exists()) {
indexExtractDir.mkdirs();
}
extractInputStreamToDir(in, indexExtractDir);
queryableIndex = load(indexExtractDir);
}
finally {
FileUtils.deleteDirectory(tmpDir);
}
}
@Override
public int getExpectedNumOfEntries()
{
return expectedNumOfEntries;
}
@Override
public void setExpectedNumOfEntries(int expectedNumOfEntries)
{
this.expectedNumOfEntries = expectedNumOfEntries;
}
@Override
public <I> Iterator<I> getMatches(Map<Index, Object> indexToPredicate)
{
// indexToPredicate contains a mapping from BitMapIndex to predicates
// it will do an intersection on the results of applying the predicate using the
// corresponding index
// the map should also include this current object itself
// technically this is more like a utility method that should be static in the interface
// however, each index implementation may have a more efficient way of
// intersecting results, that's why each Index implementation will implement this method
Map<BitMapIndex, Domain> bitMapIndexDomainMap = indexToPredicate.entrySet().stream()
.collect(toMap(e -> (BitMapIndex) e.getKey(), e -> (Domain) e.getValue()));
ImmutableBitmap lastBm = null;
for (Map.Entry<BitMapIndex, Domain> entry : bitMapIndexDomainMap.entrySet()) {
BitMapIndex bitMapIndex = entry.getKey();
Domain predicate = entry.getValue();
List<DimFilter> dimFilters = predicateToFilter(predicate);
List<Filter> filters = dimFilters.stream()
.map(filter -> filter.toFilter()).collect(toList());
QueryableIndex queryableIndex = bitMapIndex.getQueryableIndex();
// if queryableIndex is null, it means the index has not been loaded from disk
// so it cannot be queried
if (queryableIndex == null) {
continue;
}
ColumnSelectorBitmapIndexSelector bitmapIndexSelector = new ColumnSelectorBitmapIndexSelector(
queryableIndex.getBitmapFactoryForDimensions(),
VirtualColumns.nullToEmpty(null),
queryableIndex);
BitmapResultFactory<?> bitmapResultFactory = new DefaultBitmapResultFactory(bitmapIndexSelector.getBitmapFactory());
if (filters.size() == 0) {
filters.add(new TrueFilter());
}
ImmutableBitmap bm = AndFilter.getBitmapIndex(bitmapIndexSelector, bitmapResultFactory, filters);
if (lastBm == null) {
lastBm = bm;
}
else {
lastBm = lastBm.intersection(bm);
}
}
if (lastBm == null) {
return Collections.emptyIterator();
}
IntIterator intIterator = lastBm.iterator();
return (Iterator<I>) new Iterator<Integer>()
{
@Override
public boolean hasNext()
{
return intIterator.hasNext();
}
@Override
public Integer next()
{
return intIterator.next();
}
};
}
/**
* Reads the files from the provided dir and writes them to the output stream
* <p>
* A header is added at the start to provide file info
* <p>
* file1Name:file1Length,file2Name:file2Length#
* file1Content
* file2Content
*
* @param outputStream
* @param dir
* @throws IOException
*/
private void combineDirIntoStream(OutputStream outputStream, File dir) throws IOException
{
File[] files = dir.listFiles();
// first create the header line
// this will contain the names and sizes for all the files being written to the stream
StringBuilder header = new StringBuilder();
for (int i = 0; files != null && i < files.length; i++) {
File file = files[i];
header.append(file.getName())
.append(HEADER_FILE_INFO_PROPERTY_SEPARATOR)
.append(file.length());
if (i + 1 < files.length) {
header.append(HEADER_FILE_INFO_SEPARATOR);
}
}
header.append(HEADER_TERMINATOR);
// write the header then all the file contents in order
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, CHARSET))) {
writer.write(header.toString());
for (File f : files) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), CHARSET))) {
IOUtils.copy(reader, writer);
}
}
}
}
/**
* Corresponding method to combineDirIntoStream()
* <p>
* Extracts the files from the stream and write them to the output dir
*
* @param inputStream
* @param outputDir
* @throws IOException
*/
private void extractInputStreamToDir(InputStream inputStream, File outputDir)
throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET));
// read the header
StringBuilder header = new StringBuilder();
int c = reader.read();
while (c != -1 && (char) c != HEADER_TERMINATOR) {
header.append((char) c);
c = reader.read();
}
// read each file from the stream and write it out
String[] fileInfos = header.toString().split(HEADER_FILE_INFO_SEPARATOR);
for (int i = 0; i < fileInfos.length; i++) {
String[] properties = fileInfos[i].split(HEADER_FILE_INFO_PROPERTY_SEPARATOR);
int len = Integer.parseInt(properties[1]);
File file = new File(outputDir, properties[0]);
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), CHARSET))) {
for (int j = 0; j < len; j++) {
writer.write(reader.read());
}
}
}
}
/**
* Gets or initializes an IncrementalIndex to which values to should added
* Note: the IncrementalIndex can't be queried until it is first persisted
* to disk
*
* @return
*/
private IncrementalIndex getOrInitIncrementalIndex()
{
if (incrementalIndex == null) {
incrementalIndex = new IncrementalIndex.Builder()
.setIndexSchema(
new IncrementalIndexSchema.Builder()
.withTimestampSpec(new TimestampSpec("timestamp", "iso", null))
.withQueryGranularity(Granularities.NONE)
.withDimensionsSpec(new DimensionsSpec(Collections.singletonList(new StringDimensionSchema(COLUMN_NAME))))
.withRollup(false)
.build())
.setMaxRowCount(getExpectedNumOfEntries())
.buildOnheap();
}
return incrementalIndex;
}
QueryableIndex getQueryableIndex()
{
return this.queryableIndex;
}
@Override
public long getMemorySize()
{
return this.memorySize;
}
@Override
public void setMemorySize(long memorySize)
{
this.memorySize = memorySize;
}
}
| 37.203279 | 142 | 0.63638 |
1d104ca069d1b5e26cfcb11a4e38bb02721206d1 | 1,812 | swift | Swift | EssentialFeed/EssentialFeediOS/Feed UI/Views/LoadMoreCell.swift | AndreiOstafciuc/ios-lead-essentials-image-comments-challenge | 0855795c2099e7382e01143f77381f9e57d86a31 | [
"MIT"
] | null | null | null | EssentialFeed/EssentialFeediOS/Feed UI/Views/LoadMoreCell.swift | AndreiOstafciuc/ios-lead-essentials-image-comments-challenge | 0855795c2099e7382e01143f77381f9e57d86a31 | [
"MIT"
] | null | null | null | EssentialFeed/EssentialFeediOS/Feed UI/Views/LoadMoreCell.swift | AndreiOstafciuc/ios-lead-essentials-image-comments-challenge | 0855795c2099e7382e01143f77381f9e57d86a31 | [
"MIT"
] | null | null | null | //
// LoadMoreCell.swift
// EssentialFeediOS
//
// Created by Andrei Ostafciuc on 24/11/2020.
// Copyright © 2020 Essential Developer. All rights reserved.
//
import UIKit
public class LoadMoreCell: UITableViewCell {
private lazy var spinner: UIActivityIndicatorView = {
let spinner = UIActivityIndicatorView(style: .medium)
contentView.addSubview(spinner)
spinner.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
spinner.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
spinner.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
contentView.heightAnchor.constraint(greaterThanOrEqualToConstant: 40)
])
return spinner
}()
private lazy var messageLabel: UILabel = {
let label = UILabel()
label.textColor = .tertiaryLabel
label.font = .preferredFont(forTextStyle: .footnote)
label.numberOfLines = 0
label.textAlignment = .center
label.adjustsFontForContentSizeCategory = true
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8),
contentView.trailingAnchor.constraint(equalTo: label.trailingAnchor, constant: 8),
label.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
contentView.bottomAnchor.constraint(equalTo: label.bottomAnchor, constant: 8),
])
return label
}()
public var isLoading: Bool {
get { spinner.isAnimating }
set {
if newValue {
spinner.startAnimating()
} else {
spinner.stopAnimating()
}
}
}
public var message: String? {
get { messageLabel.text }
set { messageLabel.text = newValue }
}
}
| 29.225806 | 88 | 0.720751 |
2679616a0475103ee47f6b45dddc751512274b62 | 286 | java | Java | src/main/java/com/networkoverflow/lifepower/init/ModItems.java | AnZaNaMa/LifePower | 40860dd1bde07620b2da37ec78ab51b218998ad4 | [
"MIT"
] | null | null | null | src/main/java/com/networkoverflow/lifepower/init/ModItems.java | AnZaNaMa/LifePower | 40860dd1bde07620b2da37ec78ab51b218998ad4 | [
"MIT"
] | null | null | null | src/main/java/com/networkoverflow/lifepower/init/ModItems.java | AnZaNaMa/LifePower | 40860dd1bde07620b2da37ec78ab51b218998ad4 | [
"MIT"
] | null | null | null | package com.networkoverflow.lifepower.init;
import com.networkoverflow.lifepower.LifePower;
import net.minecraft.item.Item;
import net.minecraftforge.registries.ObjectHolder;
@ObjectHolder(LifePower.MODID)
public class ModItems {
public static final Item POCKET_FURNACE = null;
}
| 26 | 51 | 0.821678 |
5b329a8b3561a1b8cfe573c3ae92c8e30efa859a | 205 | kt | Kotlin | application/domain/src/main/java/br/com/charleston/domain/model/UserModel.kt | charleston10/github-android | ca697d16bb0856c69dc2bda73cf9b5ce6f1610e7 | [
"Apache-2.0"
] | 12 | 2018-12-28T11:56:28.000Z | 2020-03-16T17:38:20.000Z | application/domain/src/main/java/br/com/charleston/domain/model/UserModel.kt | charleston10/github-android | ca697d16bb0856c69dc2bda73cf9b5ce6f1610e7 | [
"Apache-2.0"
] | null | null | null | application/domain/src/main/java/br/com/charleston/domain/model/UserModel.kt | charleston10/github-android | ca697d16bb0856c69dc2bda73cf9b5ce6f1610e7 | [
"Apache-2.0"
] | 1 | 2021-07-05T17:23:33.000Z | 2021-07-05T17:23:33.000Z | package br.com.charleston.domain.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class UserModel(
val avatarUrl: String,
val name: String
) : Parcelable | 20.5 | 39 | 0.785366 |
c6ef5dc740431c7bad9ab538d2334ba07420edcd | 894 | ps1 | PowerShell | Source/Public/Get-VSTeamFeed.ps1 | Seekatar/vsteam | 38d2c44ec3ba6cd795f5c2b27a082ef8bdf717ad | [
"MIT"
] | null | null | null | Source/Public/Get-VSTeamFeed.ps1 | Seekatar/vsteam | 38d2c44ec3ba6cd795f5c2b27a082ef8bdf717ad | [
"MIT"
] | null | null | null | Source/Public/Get-VSTeamFeed.ps1 | Seekatar/vsteam | 38d2c44ec3ba6cd795f5c2b27a082ef8bdf717ad | [
"MIT"
] | null | null | null | function Get-VSTeamFeed {
[CmdletBinding(DefaultParameterSetName = 'List')]
param (
[Parameter(ParameterSetName = 'ByID', Position = 0)]
[Alias('FeedId')]
[string[]] $Id
)
process {
if ($id) {
foreach ($item in $id) {
$resp = _callAPI -NoProject -subDomain feeds -Id $item -Area packaging -Resource feeds -Version $(_getApiVersion Packaging)
Write-Verbose $resp
$item = [VSTeamFeed]::new($resp)
Write-Output $item
}
}
else {
$resp = _callAPI -NoProject -subDomain feeds -Area packaging -Resource feeds -Version $(_getApiVersion Packaging)
$objs = @()
foreach ($item in $resp.value) {
Write-Verbose $item
$objs += [VSTeamFeed]::new($item)
}
Write-Output $objs
}
}
} | 27.090909 | 136 | 0.526846 |
800fc2f7929377cde2419ffceabe2f671c26d062 | 204 | java | Java | app/src/main/java/org/apache/cayenne/demo/android/model/Artist.java | stariy95/cayenne-android-demo | 7709d820b4b216015a38a47fd936fb336670ddee | [
"Apache-2.0"
] | 3 | 2017-12-18T14:42:46.000Z | 2021-08-09T19:01:59.000Z | app/src/main/java/org/apache/cayenne/demo/android/model/Artist.java | stariy95/cayenne-android-demo | 7709d820b4b216015a38a47fd936fb336670ddee | [
"Apache-2.0"
] | null | null | null | app/src/main/java/org/apache/cayenne/demo/android/model/Artist.java | stariy95/cayenne-android-demo | 7709d820b4b216015a38a47fd936fb336670ddee | [
"Apache-2.0"
] | 1 | 2018-10-24T07:01:34.000Z | 2018-10-24T07:01:34.000Z | package org.apache.cayenne.demo.android.model;
import org.apache.cayenne.demo.android.model.auto._Artist;
public class Artist extends _Artist {
private static final long serialVersionUID = 1L;
}
| 20.4 | 58 | 0.779412 |
7ea7bed57b597a4bcfab751951a90096c39f08b0 | 1,145 | dart | Dart | satpj_front_end_web/lib/src/model/sesion_terapia/sesion_terapia_actual.dart | DavidHerreraC18/SATP-J | fb680efb0a8a65f14c2d5ed430df0090693ae18f | [
"Apache-2.0"
] | 1 | 2021-02-03T13:13:18.000Z | 2021-02-03T13:13:18.000Z | satpj_front_end_web/lib/src/model/sesion_terapia/sesion_terapia_actual.dart | DavidHerreraC18/SATP-J | fb680efb0a8a65f14c2d5ed430df0090693ae18f | [
"Apache-2.0"
] | null | null | null | satpj_front_end_web/lib/src/model/sesion_terapia/sesion_terapia_actual.dart | DavidHerreraC18/SATP-J | fb680efb0a8a65f14c2d5ed430df0090693ae18f | [
"Apache-2.0"
] | 1 | 2021-02-03T13:13:55.000Z | 2021-02-03T13:13:55.000Z | import 'package:json_annotation/json_annotation.dart';
import 'dart:convert';
import 'package:satpj_front_end_web/src/model/sesion_terapia/sesion_terapia.dart';
part 'sesion_terapia_actual.g.dart';
List<SesionTerapiaActual> sesionTerapiaActualFromJson(String str) =>
List<SesionTerapiaActual>.from(
json.decode(str).map((x) => SesionTerapiaActual.fromJson(x)));
String sesionTerapiaActualToJson(List<SesionTerapiaActual> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
SesionTerapiaActual singleSesionTerapiaActualFromJson(String str) {
SesionTerapiaActual sesionTerapia =
SesionTerapiaActual.fromJson(json.decode(str));
return sesionTerapia;
}
@JsonSerializable(explicitToJson: true)
class SesionTerapiaActual {
DateTime fecha;
bool posible;
SesionTerapia sesionTerapia;
SesionTerapiaActual({
this.fecha,
this.posible,
this.sesionTerapia,
});
factory SesionTerapiaActual.fromJson(Map<String, dynamic> json) =>
_$SesionTerapiaActualFromJson(json);
Map<String, dynamic> toJson() => _$SesionTerapiaActualToJson(this);
}
| 30.131579 | 83 | 0.741485 |
ff81a1eee54b17e131b9c92f473804e5fdc9c6e4 | 673 | swift | Swift | wy/wy/Classes/View/Home/StatusCell/WYStatusCell.swift | crazychu278/bs | 0f39630c623fb7accff80d1c4a97209879d90d0c | [
"MIT"
] | null | null | null | wy/wy/Classes/View/Home/StatusCell/WYStatusCell.swift | crazychu278/bs | 0f39630c623fb7accff80d1c4a97209879d90d0c | [
"MIT"
] | null | null | null | wy/wy/Classes/View/Home/StatusCell/WYStatusCell.swift | crazychu278/bs | 0f39630c623fb7accff80d1c4a97209879d90d0c | [
"MIT"
] | null | null | null | //
// WYStatusCell.swift
// wy
//
// Created by chu on 04/04/2018.
// Copyright © 2018 chu. All rights reserved.
//
import UIKit
class WYStatusCell: UITableViewCell {
@IBOutlet weak var face: UIImageView!
@IBOutlet weak var desprip: UILabel!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var blindprice: UILabel!
@IBOutlet weak var shopname: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 21.709677 | 65 | 0.662704 |
08931f55d856da492a79a193b280cf4673855f5f | 13,717 | go | Go | clients/go/generated/model_hudson_master_computermonitor_data.go | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | clients/go/generated/model_hudson_master_computermonitor_data.go | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | clients/go/generated/model_hudson_master_computermonitor_data.go | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | /*
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification
API version: 1.1.2-pre.0
Contact: blah@cliffano.com
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package openapi
import (
"encoding/json"
)
// HudsonMasterComputermonitorData struct for HudsonMasterComputermonitorData
type HudsonMasterComputermonitorData struct {
HudsonNodeMonitorsSwapSpaceMonitor *SwapSpaceMonitorMemoryUsage2 `json:"hudson.node_monitors.SwapSpaceMonitor,omitempty"`
HudsonNodeMonitorsTemporarySpaceMonitor *DiskSpaceMonitorDescriptorDiskSpace `json:"hudson.node_monitors.TemporarySpaceMonitor,omitempty"`
HudsonNodeMonitorsDiskSpaceMonitor *DiskSpaceMonitorDescriptorDiskSpace `json:"hudson.node_monitors.DiskSpaceMonitor,omitempty"`
HudsonNodeMonitorsArchitectureMonitor *string `json:"hudson.node_monitors.ArchitectureMonitor,omitempty"`
HudsonNodeMonitorsResponseTimeMonitor *ResponseTimeMonitorData `json:"hudson.node_monitors.ResponseTimeMonitor,omitempty"`
HudsonNodeMonitorsClockMonitor *ClockDifference `json:"hudson.node_monitors.ClockMonitor,omitempty"`
Class *string `json:"_class,omitempty"`
}
// NewHudsonMasterComputermonitorData instantiates a new HudsonMasterComputermonitorData object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewHudsonMasterComputermonitorData() *HudsonMasterComputermonitorData {
this := HudsonMasterComputermonitorData{}
return &this
}
// NewHudsonMasterComputermonitorDataWithDefaults instantiates a new HudsonMasterComputermonitorData object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewHudsonMasterComputermonitorDataWithDefaults() *HudsonMasterComputermonitorData {
this := HudsonMasterComputermonitorData{}
return &this
}
// GetHudsonNodeMonitorsSwapSpaceMonitor returns the HudsonNodeMonitorsSwapSpaceMonitor field value if set, zero value otherwise.
func (o *HudsonMasterComputermonitorData) GetHudsonNodeMonitorsSwapSpaceMonitor() SwapSpaceMonitorMemoryUsage2 {
if o == nil || o.HudsonNodeMonitorsSwapSpaceMonitor == nil {
var ret SwapSpaceMonitorMemoryUsage2
return ret
}
return *o.HudsonNodeMonitorsSwapSpaceMonitor
}
// GetHudsonNodeMonitorsSwapSpaceMonitorOk returns a tuple with the HudsonNodeMonitorsSwapSpaceMonitor field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *HudsonMasterComputermonitorData) GetHudsonNodeMonitorsSwapSpaceMonitorOk() (*SwapSpaceMonitorMemoryUsage2, bool) {
if o == nil || o.HudsonNodeMonitorsSwapSpaceMonitor == nil {
return nil, false
}
return o.HudsonNodeMonitorsSwapSpaceMonitor, true
}
// HasHudsonNodeMonitorsSwapSpaceMonitor returns a boolean if a field has been set.
func (o *HudsonMasterComputermonitorData) HasHudsonNodeMonitorsSwapSpaceMonitor() bool {
if o != nil && o.HudsonNodeMonitorsSwapSpaceMonitor != nil {
return true
}
return false
}
// SetHudsonNodeMonitorsSwapSpaceMonitor gets a reference to the given SwapSpaceMonitorMemoryUsage2 and assigns it to the HudsonNodeMonitorsSwapSpaceMonitor field.
func (o *HudsonMasterComputermonitorData) SetHudsonNodeMonitorsSwapSpaceMonitor(v SwapSpaceMonitorMemoryUsage2) {
o.HudsonNodeMonitorsSwapSpaceMonitor = &v
}
// GetHudsonNodeMonitorsTemporarySpaceMonitor returns the HudsonNodeMonitorsTemporarySpaceMonitor field value if set, zero value otherwise.
func (o *HudsonMasterComputermonitorData) GetHudsonNodeMonitorsTemporarySpaceMonitor() DiskSpaceMonitorDescriptorDiskSpace {
if o == nil || o.HudsonNodeMonitorsTemporarySpaceMonitor == nil {
var ret DiskSpaceMonitorDescriptorDiskSpace
return ret
}
return *o.HudsonNodeMonitorsTemporarySpaceMonitor
}
// GetHudsonNodeMonitorsTemporarySpaceMonitorOk returns a tuple with the HudsonNodeMonitorsTemporarySpaceMonitor field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *HudsonMasterComputermonitorData) GetHudsonNodeMonitorsTemporarySpaceMonitorOk() (*DiskSpaceMonitorDescriptorDiskSpace, bool) {
if o == nil || o.HudsonNodeMonitorsTemporarySpaceMonitor == nil {
return nil, false
}
return o.HudsonNodeMonitorsTemporarySpaceMonitor, true
}
// HasHudsonNodeMonitorsTemporarySpaceMonitor returns a boolean if a field has been set.
func (o *HudsonMasterComputermonitorData) HasHudsonNodeMonitorsTemporarySpaceMonitor() bool {
if o != nil && o.HudsonNodeMonitorsTemporarySpaceMonitor != nil {
return true
}
return false
}
// SetHudsonNodeMonitorsTemporarySpaceMonitor gets a reference to the given DiskSpaceMonitorDescriptorDiskSpace and assigns it to the HudsonNodeMonitorsTemporarySpaceMonitor field.
func (o *HudsonMasterComputermonitorData) SetHudsonNodeMonitorsTemporarySpaceMonitor(v DiskSpaceMonitorDescriptorDiskSpace) {
o.HudsonNodeMonitorsTemporarySpaceMonitor = &v
}
// GetHudsonNodeMonitorsDiskSpaceMonitor returns the HudsonNodeMonitorsDiskSpaceMonitor field value if set, zero value otherwise.
func (o *HudsonMasterComputermonitorData) GetHudsonNodeMonitorsDiskSpaceMonitor() DiskSpaceMonitorDescriptorDiskSpace {
if o == nil || o.HudsonNodeMonitorsDiskSpaceMonitor == nil {
var ret DiskSpaceMonitorDescriptorDiskSpace
return ret
}
return *o.HudsonNodeMonitorsDiskSpaceMonitor
}
// GetHudsonNodeMonitorsDiskSpaceMonitorOk returns a tuple with the HudsonNodeMonitorsDiskSpaceMonitor field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *HudsonMasterComputermonitorData) GetHudsonNodeMonitorsDiskSpaceMonitorOk() (*DiskSpaceMonitorDescriptorDiskSpace, bool) {
if o == nil || o.HudsonNodeMonitorsDiskSpaceMonitor == nil {
return nil, false
}
return o.HudsonNodeMonitorsDiskSpaceMonitor, true
}
// HasHudsonNodeMonitorsDiskSpaceMonitor returns a boolean if a field has been set.
func (o *HudsonMasterComputermonitorData) HasHudsonNodeMonitorsDiskSpaceMonitor() bool {
if o != nil && o.HudsonNodeMonitorsDiskSpaceMonitor != nil {
return true
}
return false
}
// SetHudsonNodeMonitorsDiskSpaceMonitor gets a reference to the given DiskSpaceMonitorDescriptorDiskSpace and assigns it to the HudsonNodeMonitorsDiskSpaceMonitor field.
func (o *HudsonMasterComputermonitorData) SetHudsonNodeMonitorsDiskSpaceMonitor(v DiskSpaceMonitorDescriptorDiskSpace) {
o.HudsonNodeMonitorsDiskSpaceMonitor = &v
}
// GetHudsonNodeMonitorsArchitectureMonitor returns the HudsonNodeMonitorsArchitectureMonitor field value if set, zero value otherwise.
func (o *HudsonMasterComputermonitorData) GetHudsonNodeMonitorsArchitectureMonitor() string {
if o == nil || o.HudsonNodeMonitorsArchitectureMonitor == nil {
var ret string
return ret
}
return *o.HudsonNodeMonitorsArchitectureMonitor
}
// GetHudsonNodeMonitorsArchitectureMonitorOk returns a tuple with the HudsonNodeMonitorsArchitectureMonitor field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *HudsonMasterComputermonitorData) GetHudsonNodeMonitorsArchitectureMonitorOk() (*string, bool) {
if o == nil || o.HudsonNodeMonitorsArchitectureMonitor == nil {
return nil, false
}
return o.HudsonNodeMonitorsArchitectureMonitor, true
}
// HasHudsonNodeMonitorsArchitectureMonitor returns a boolean if a field has been set.
func (o *HudsonMasterComputermonitorData) HasHudsonNodeMonitorsArchitectureMonitor() bool {
if o != nil && o.HudsonNodeMonitorsArchitectureMonitor != nil {
return true
}
return false
}
// SetHudsonNodeMonitorsArchitectureMonitor gets a reference to the given string and assigns it to the HudsonNodeMonitorsArchitectureMonitor field.
func (o *HudsonMasterComputermonitorData) SetHudsonNodeMonitorsArchitectureMonitor(v string) {
o.HudsonNodeMonitorsArchitectureMonitor = &v
}
// GetHudsonNodeMonitorsResponseTimeMonitor returns the HudsonNodeMonitorsResponseTimeMonitor field value if set, zero value otherwise.
func (o *HudsonMasterComputermonitorData) GetHudsonNodeMonitorsResponseTimeMonitor() ResponseTimeMonitorData {
if o == nil || o.HudsonNodeMonitorsResponseTimeMonitor == nil {
var ret ResponseTimeMonitorData
return ret
}
return *o.HudsonNodeMonitorsResponseTimeMonitor
}
// GetHudsonNodeMonitorsResponseTimeMonitorOk returns a tuple with the HudsonNodeMonitorsResponseTimeMonitor field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *HudsonMasterComputermonitorData) GetHudsonNodeMonitorsResponseTimeMonitorOk() (*ResponseTimeMonitorData, bool) {
if o == nil || o.HudsonNodeMonitorsResponseTimeMonitor == nil {
return nil, false
}
return o.HudsonNodeMonitorsResponseTimeMonitor, true
}
// HasHudsonNodeMonitorsResponseTimeMonitor returns a boolean if a field has been set.
func (o *HudsonMasterComputermonitorData) HasHudsonNodeMonitorsResponseTimeMonitor() bool {
if o != nil && o.HudsonNodeMonitorsResponseTimeMonitor != nil {
return true
}
return false
}
// SetHudsonNodeMonitorsResponseTimeMonitor gets a reference to the given ResponseTimeMonitorData and assigns it to the HudsonNodeMonitorsResponseTimeMonitor field.
func (o *HudsonMasterComputermonitorData) SetHudsonNodeMonitorsResponseTimeMonitor(v ResponseTimeMonitorData) {
o.HudsonNodeMonitorsResponseTimeMonitor = &v
}
// GetHudsonNodeMonitorsClockMonitor returns the HudsonNodeMonitorsClockMonitor field value if set, zero value otherwise.
func (o *HudsonMasterComputermonitorData) GetHudsonNodeMonitorsClockMonitor() ClockDifference {
if o == nil || o.HudsonNodeMonitorsClockMonitor == nil {
var ret ClockDifference
return ret
}
return *o.HudsonNodeMonitorsClockMonitor
}
// GetHudsonNodeMonitorsClockMonitorOk returns a tuple with the HudsonNodeMonitorsClockMonitor field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *HudsonMasterComputermonitorData) GetHudsonNodeMonitorsClockMonitorOk() (*ClockDifference, bool) {
if o == nil || o.HudsonNodeMonitorsClockMonitor == nil {
return nil, false
}
return o.HudsonNodeMonitorsClockMonitor, true
}
// HasHudsonNodeMonitorsClockMonitor returns a boolean if a field has been set.
func (o *HudsonMasterComputermonitorData) HasHudsonNodeMonitorsClockMonitor() bool {
if o != nil && o.HudsonNodeMonitorsClockMonitor != nil {
return true
}
return false
}
// SetHudsonNodeMonitorsClockMonitor gets a reference to the given ClockDifference and assigns it to the HudsonNodeMonitorsClockMonitor field.
func (o *HudsonMasterComputermonitorData) SetHudsonNodeMonitorsClockMonitor(v ClockDifference) {
o.HudsonNodeMonitorsClockMonitor = &v
}
// GetClass returns the Class field value if set, zero value otherwise.
func (o *HudsonMasterComputermonitorData) GetClass() string {
if o == nil || o.Class == nil {
var ret string
return ret
}
return *o.Class
}
// GetClassOk returns a tuple with the Class field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *HudsonMasterComputermonitorData) GetClassOk() (*string, bool) {
if o == nil || o.Class == nil {
return nil, false
}
return o.Class, true
}
// HasClass returns a boolean if a field has been set.
func (o *HudsonMasterComputermonitorData) HasClass() bool {
if o != nil && o.Class != nil {
return true
}
return false
}
// SetClass gets a reference to the given string and assigns it to the Class field.
func (o *HudsonMasterComputermonitorData) SetClass(v string) {
o.Class = &v
}
func (o HudsonMasterComputermonitorData) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.HudsonNodeMonitorsSwapSpaceMonitor != nil {
toSerialize["hudson.node_monitors.SwapSpaceMonitor"] = o.HudsonNodeMonitorsSwapSpaceMonitor
}
if o.HudsonNodeMonitorsTemporarySpaceMonitor != nil {
toSerialize["hudson.node_monitors.TemporarySpaceMonitor"] = o.HudsonNodeMonitorsTemporarySpaceMonitor
}
if o.HudsonNodeMonitorsDiskSpaceMonitor != nil {
toSerialize["hudson.node_monitors.DiskSpaceMonitor"] = o.HudsonNodeMonitorsDiskSpaceMonitor
}
if o.HudsonNodeMonitorsArchitectureMonitor != nil {
toSerialize["hudson.node_monitors.ArchitectureMonitor"] = o.HudsonNodeMonitorsArchitectureMonitor
}
if o.HudsonNodeMonitorsResponseTimeMonitor != nil {
toSerialize["hudson.node_monitors.ResponseTimeMonitor"] = o.HudsonNodeMonitorsResponseTimeMonitor
}
if o.HudsonNodeMonitorsClockMonitor != nil {
toSerialize["hudson.node_monitors.ClockMonitor"] = o.HudsonNodeMonitorsClockMonitor
}
if o.Class != nil {
toSerialize["_class"] = o.Class
}
return json.Marshal(toSerialize)
}
type NullableHudsonMasterComputermonitorData struct {
value *HudsonMasterComputermonitorData
isSet bool
}
func (v NullableHudsonMasterComputermonitorData) Get() *HudsonMasterComputermonitorData {
return v.value
}
func (v *NullableHudsonMasterComputermonitorData) Set(val *HudsonMasterComputermonitorData) {
v.value = val
v.isSet = true
}
func (v NullableHudsonMasterComputermonitorData) IsSet() bool {
return v.isSet
}
func (v *NullableHudsonMasterComputermonitorData) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableHudsonMasterComputermonitorData(val *HudsonMasterComputermonitorData) *NullableHudsonMasterComputermonitorData {
return &NullableHudsonMasterComputermonitorData{value: val, isSet: true}
}
func (v NullableHudsonMasterComputermonitorData) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableHudsonMasterComputermonitorData) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
}
| 41.192192 | 180 | 0.819275 |
8dcb07b858bfcd8ee94197151b0c2ab0af787136 | 747 | lua | Lua | lua/playerstats/sv_init.lua | cresterienvogel/PlayerStats | 1bb36908e05267c2de21a48298020970c54af725 | [
"Apache-2.0"
] | 4 | 2020-01-04T19:53:10.000Z | 2021-03-27T23:08:45.000Z | lua/playerstats/sv_init.lua | cresterienvogel/PlayerStats | 1bb36908e05267c2de21a48298020970c54af725 | [
"Apache-2.0"
] | null | null | null | lua/playerstats/sv_init.lua | cresterienvogel/PlayerStats | 1bb36908e05267c2de21a48298020970c54af725 | [
"Apache-2.0"
] | 2 | 2021-03-27T23:08:47.000Z | 2021-09-22T13:13:24.000Z | include("sh_init.lua")
PSTATS = {}
PEVENTS = {}
--[[
Base functions
]]
function PLAYERSTATS:TryLuck(a, b)
return math.random(a, b) == 3
end
function PLAYERSTATS:Initialize()
for id, name in pairs(file.Find("playerstats/stats/*", "LUA")) do
include("playerstats/stats/" .. name)
end
for id, name in pairs(file.Find("playerstats/events/*", "LUA")) do
include("playerstats/events/" .. name)
end
for id, name in pairs(file.Find("playerstats/other/*", "LUA")) do
include("playerstats/other/" .. name)
end
for id, func in pairs(PSTATS) do
timer.Create("PlayerStat" .. id, 1, 0, func)
end
for id, func in pairs(PEVENTS) do
hook.Add("EntityTakeDamage", "PlayerEvent" .. id, func)
end
end | 21.970588 | 68 | 0.637216 |
21c2fc186a4251048cf2b29ebae535af0144d4a9 | 3,983 | rs | Rust | src/main.rs | GabMus/gnvim | b279ea69bf280aa2f8f57a10e408d6810f55ef82 | [
"MIT"
] | null | null | null | src/main.rs | GabMus/gnvim | b279ea69bf280aa2f8f57a10e408d6810f55ef82 | [
"MIT"
] | null | null | null | src/main.rs | GabMus/gnvim | b279ea69bf280aa2f8f57a10e408d6810f55ef82 | [
"MIT"
] | null | null | null | #![cfg_attr(feature = "unstable", feature(test))]
#[macro_use]
extern crate lazy_static;
extern crate ammonia;
extern crate pulldown_cmark;
extern crate structopt;
extern crate syntect;
extern crate cairo;
extern crate gdk;
extern crate gdk_pixbuf;
extern crate gio;
extern crate glib;
extern crate gtk;
extern crate neovim_lib;
extern crate pango;
extern crate pangocairo;
extern crate webkit2gtk;
use gio::prelude::*;
use neovim_lib::neovim::{Neovim, UiAttachOptions};
use neovim_lib::session::Session as NeovimSession;
use neovim_lib::NeovimApi;
use std::process::Command;
use std::sync::mpsc::channel;
use std::sync::{Arc, Mutex};
use structopt::StructOpt;
include!(concat!(env!("OUT_DIR"), "/gnvim_version.rs"));
mod nvim_bridge;
mod thread_guard;
mod ui;
/// Gnvim is a graphical UI for neovim.
#[derive(StructOpt, Debug)]
#[structopt(
name = "gnvim",
raw(version = "VERSION"),
author = "Ville Hakulinen"
)]
struct Options {
/// Prints the executed neovim command.
#[structopt(long = "print-nvim-cmd")]
print_nvim_cmd: bool,
/// Path to neovim binary.
#[structopt(long = "nvim", name = "BIN", default_value = "nvim")]
nvim_path: String,
/// Path for gnvim runtime files.
#[structopt(
long = "gnvim-rtp",
default_value = "/usr/local/share/gnvim/runtime",
env = "GNVIM_RUNTIME_PATH"
)]
gnvim_rtp: String,
/// Files to open. Files after the first one are opened in new tabs.
#[structopt(value_name = "FILES")]
open_files: Vec<String>,
/// Arguments that are passed to nvim.
#[structopt(value_name = "ARGS", last = true)]
nvim_args: Vec<String>,
}
fn build(app: >k::Application, opts: &Options) {
let (tx, rx) = channel();
let bridge = nvim_bridge::NvimBridge::new(tx);
let mut cmd = Command::new(&opts.nvim_path);
cmd.arg("--embed")
.arg("--cmd")
.arg("let g:gnvim=1")
.arg("--cmd")
.arg("set termguicolors")
.arg("--cmd")
.arg(format!("let &rtp.=',{}'", opts.gnvim_rtp));
// Pass arguments from cli to nvim.
for arg in opts.nvim_args.iter() {
cmd.arg(arg);
}
// Print the nvim cmd which is executed if asked.
if opts.print_nvim_cmd {
println!("nvim cmd: {:?}", cmd);
}
let mut session = NeovimSession::new_child_cmd(&mut cmd).unwrap();
session.start_event_loop_handler(bridge);
let mut nvim = Neovim::new(session);
nvim.subscribe("Gnvim")
.expect("Failed to subscribe to 'Gnvim' events");
let api_info = nvim.get_api_info().expect("Failed to get API info");
nvim.set_var("gnvim_channel_id", api_info[0].clone())
.expect("Failed to set g:gnvim_channel_id");
let mut ui_opts = UiAttachOptions::new();
ui_opts.set_rgb(true);
ui_opts.set_linegrid_external(true);
ui_opts.set_popupmenu_external(true);
ui_opts.set_tabline_external(true);
ui_opts.set_cmdline_external(true);
ui_opts.set_wildmenu_external(true);
nvim.ui_attach(80, 30, &ui_opts)
.expect("Failed to attach UI");
// Open the first file using :e.
if let Some(first) = opts.open_files.get(0) {
nvim.command(format!("e {}", first).as_str()).unwrap();
}
// Open rest of the files into new tabs.
for file in opts.open_files.iter().skip(1) {
nvim.command(format!("tabe {}", file).as_str()).unwrap();
}
let ui = ui::UI::init(app, rx, Arc::new(Mutex::new(nvim)));
ui.start();
}
fn main() {
let opts = Options::from_args();
let mut flags = gio::ApplicationFlags::empty();
flags.insert(gio::ApplicationFlags::NON_UNIQUE);
flags.insert(gio::ApplicationFlags::HANDLES_OPEN);
let app =
gtk::Application::new("com.github.vhakulinen.gnvim", flags).unwrap();
glib::set_application_name("GNvim");
gtk::Window::set_default_icon_name("gnvim");
app.connect_activate(move |app| {
build(app, &opts);
});
app.run(&vec![]);
}
| 26.912162 | 77 | 0.645744 |
17e63cdc41cd0b56b437a0d40216b8683648996e | 753 | cs | C# | src/Tests/Chromely.Core.Tests/Controller/TestDependency.cs | NovusTheory/Chromely | cd8dc923d2a4207d349e29854ede7f1b5f00352c | [
"MIT",
"BSD-3-Clause"
] | 6 | 2020-01-13T15:05:21.000Z | 2021-09-26T09:37:17.000Z | src/Tests/Chromely.Core.Tests/Controller/TestDependency.cs | NovusTheory/Chromely | cd8dc923d2a4207d349e29854ede7f1b5f00352c | [
"MIT",
"BSD-3-Clause"
] | 61 | 2019-12-30T16:49:15.000Z | 2021-09-15T06:55:09.000Z | src/Tests/Chromely.Core.Tests/Controller/TestDependency.cs | NovusTheory/Chromely | cd8dc923d2a4207d349e29854ede7f1b5f00352c | [
"MIT",
"BSD-3-Clause"
] | 2 | 2020-12-25T07:41:59.000Z | 2022-02-09T15:10:26.000Z | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="TestDependency.cs" company="Chromely Projects">
// Copyright (c) 2017-2019 Chromely Projects
// </copyright>
// <license>
// See the LICENSE.md file in the project root for more information.
// </license>
// ----------------------------------------------------------------------------------------------------------------------
namespace Chromely.Core.Tests.Controller
{
public class TestDependency : ITestDependency
{
public const string TestDependencyResponse = "Dependency Get 2";
public string ReturnTest()
{
return TestDependencyResponse;
}
}
} | 35.857143 | 121 | 0.452855 |
5958bc68b6b8329b0d40ef93377ec45dd8cb3e61 | 1,522 | hpp | C++ | include/RED4ext/Types/generated/anim/AnimStateTransitionDescription.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Types/generated/anim/AnimStateTransitionDescription.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Types/generated/anim/AnimStateTransitionDescription.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/CName.hpp>
#include <RED4ext/Handle.hpp>
#include <RED4ext/ISerializable.hpp>
#include <RED4ext/Types/SimpleTypes.hpp>
namespace RED4ext
{
namespace anim { struct ActionAnimDatabase; }
namespace anim { struct IAnimStateTransitionCondition; }
namespace anim { struct IAnimStateTransitionInterpolator; }
namespace anim { struct ISyncMethod; }
namespace anim {
struct AnimStateTransitionDescription : ISerializable
{
static constexpr const char* NAME = "animAnimStateTransitionDescription";
static constexpr const char* ALIAS = NAME;
uint32_t targetStateIndex; // 30
uint8_t unk34[0x38 - 0x34]; // 34
Handle<anim::IAnimStateTransitionCondition> condition; // 38
Handle<anim::IAnimStateTransitionInterpolator> interpolator; // 48
int32_t priority; // 58
bool isEnabled; // 5C
bool isForcedToTrue; // 5D
bool supportBlendFromPose; // 5E
uint8_t unk5F[0x60 - 0x5F]; // 5F
Handle<anim::ISyncMethod> syncMethod; // 60
float duration; // 70
bool canRequestInertialization; // 74
uint8_t unk75[0x78 - 0x75]; // 75
CName animFeatureName; // 78
Ref<anim::ActionAnimDatabase> actionAnimDatabaseRef; // 80
bool isOutTransitionFromAction; // 98
uint8_t unk99[0x110 - 0x99]; // 99
};
RED4EXT_ASSERT_SIZE(AnimStateTransitionDescription, 0x110);
} // namespace anim
} // namespace RED4ext
| 32.382979 | 77 | 0.739159 |
925dcecf4b0a2ec4bf6e12b813f76fc00a8cf54f | 2,279 | sql | SQL | core/src/main/resources/schema/app/20151130100229_CLOUD-45229_generic_template_entities.sql | anmolnar/cloudbreak | 81e18cca143c30389ecf4958b1a4dcae211bddf4 | [
"Apache-2.0"
] | 174 | 2017-07-14T03:20:42.000Z | 2022-03-25T05:03:18.000Z | core/src/main/resources/schema/app/20151130100229_CLOUD-45229_generic_template_entities.sql | anmolnar/cloudbreak | 81e18cca143c30389ecf4958b1a4dcae211bddf4 | [
"Apache-2.0"
] | 2,242 | 2017-07-12T05:52:01.000Z | 2022-03-31T15:50:08.000Z | core/src/main/resources/schema/app/20151130100229_CLOUD-45229_generic_template_entities.sql | anmolnar/cloudbreak | 81e18cca143c30389ecf4958b1a4dcae211bddf4 | [
"Apache-2.0"
] | 172 | 2017-07-12T08:53:48.000Z | 2022-03-24T12:16:33.000Z | -- // CLOUD-45229 generic template entities
-- Migration SQL that makes the change goes here.
ALTER TABLE template ADD COLUMN attributes TEXT;
ALTER TABLE template ADD COLUMN cloudplatform VARCHAR(255);
UPDATE template SET attributes = json_build_object('spotPrice', spotprice, 'sshLocation', sshlocation, 'encrypted', encrypted::boolean) WHERE dtype = 'AwsTemplate';
UPDATE template SET volumetype = 'HDD' WHERE dtype = 'AzureTemplate';
UPDATE template SET volumetype = 'HDD' WHERE dtype = 'OpenStackTemplate';
UPDATE template SET volumetype = gcprawdisktype WHERE dtype = 'GcpTemplate';
UPDATE template SET cloudplatform = 'AWS' WHERE dtype = 'AwsTemplate';
UPDATE template SET cloudplatform = 'AZURE' WHERE dtype = 'AzureTemplate';
UPDATE template SET cloudplatform = 'GCP' WHERE dtype = 'GcpTemplate';
UPDATE template SET cloudplatform = 'OPENSTACK' WHERE dtype = 'OpenStackTemplate';
ALTER TABLE template ALTER COLUMN cloudplatform SET NOT NULL;
ALTER TABLE template DROP COLUMN gcprawdisktype;
ALTER TABLE template DROP COLUMN dtype;
ALTER TABLE template DROP COLUMN encrypted;
ALTER TABLE template DROP COLUMN spotprice;
ALTER TABLE template DROP COLUMN sshlocation;
-- //@UNDO
-- SQL to undo the change goes here.
ALTER TABLE template ADD COLUMN dtype VARCHAR(50);
ALTER TABLE template ADD COLUMN gcprawdisktype VARCHAR(255);
ALTER TABLE template ADD COLUMN encrypted VARCHAR(255);
ALTER TABLE template ADD COLUMN spotprice DOUBLE PRECISION;
ALTER TABLE template ADD COLUMN sshlocation VARCHAR(50);
UPDATE template SET dtype = 'AwsTemplate' WHERE cloudplatform = 'AWS';
UPDATE template SET dtype = 'AzureTemplate' WHERE cloudplatform = 'AZURE';
UPDATE template SET dtype = 'GcpTemplate' WHERE cloudplatform = 'GCP';
UPDATE template SET dtype = 'OpenStackTemplate' WHERE cloudplatform = 'OPENSTACK';
ALTER TABLE template ALTER COLUMN attributes SET DATA TYPE jsonb USING attributes::jsonb;
UPDATE template SET sshlocation = attributes->> 'sshLocation', encrypted = UPPER(attributes->> 'encrypted'), spotprice = CAST(attributes->> 'spotPrice' AS DOUBLE PRECISION) WHERE cloudplatform = 'AWS';
UPDATE template SET gcprawdisktype = volumetype WHERE dtype = 'GcpTemplate';
ALTER TABLE template DROP COLUMN attributes;
ALTER TABLE template DROP COLUMN cloudplatform; | 50.644444 | 201 | 0.790698 |
0e55c84bae3ade8a9d738a0322c70fb966592681 | 236 | sql | SQL | database/table/table_board.sql | 837477/MODAKBUL | fc6051d11d5f544d0abd0937fdf1b972c302b3fa | [
"MIT"
] | 1 | 2019-08-07T09:21:14.000Z | 2019-08-07T09:21:14.000Z | database/table/table_board.sql | 837477/MODAKBUL | fc6051d11d5f544d0abd0937fdf1b972c302b3fa | [
"MIT"
] | 2 | 2021-02-01T06:11:51.000Z | 2021-03-19T02:32:05.000Z | database/table/table_board.sql | 837477/MODAKBUL | fc6051d11d5f544d0abd0937fdf1b972c302b3fa | [
"MIT"
] | 2 | 2019-08-07T09:27:29.000Z | 2019-08-07T13:29:11.000Z | CREATE TABLE IF NOT EXISTS board(
board_url VARCHAR(20) NOT NULL,
board_rank INT NOT NULL DEFAULT 0,
board_name VARCHAR(100) NOT NULL,
board_type TINYINT NOT NULL DEFAULT 0,
PRIMARY KEY(board_url)
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; | 33.714286 | 39 | 0.809322 |
ea682ee8a932f056c4e34fe13e61733aaeb94785 | 1,009 | swift | Swift | USORugby/AppDelegate+Extension.swift | roger-tan/USORugby | 64614bbb583b8ee747d60c547c121cb9e782a7fd | [
"MIT"
] | null | null | null | USORugby/AppDelegate+Extension.swift | roger-tan/USORugby | 64614bbb583b8ee747d60c547c121cb9e782a7fd | [
"MIT"
] | null | null | null | USORugby/AppDelegate+Extension.swift | roger-tan/USORugby | 64614bbb583b8ee747d60c547c121cb9e782a7fd | [
"MIT"
] | null | null | null | //
// AppDelegate+Exntension.swift
// USORugby
//
// Created by Roger TAN on 01/09/15.
// Copyright (c) 2015 Roger TAN. All rights reserved.
//
import Foundation
import Parse
extension AppDelegate {
// Select the initial Windows
func initializeWindows() {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.rootViewController = UINavigationController(rootViewController: FeedsViewController())
self.window?.makeKeyAndVisible()
}
func initializeParse(launchOptions: [NSObject: AnyObject]?) {
Parse.enableLocalDatastore()
// Register Parse Object
News.registerSubclass()
// Initialize Parse.
Parse.setApplicationId("j2CsIT0ONh5HHN0aDTrAze2YYv8RuSpfrfvc2YHU",
clientKey: "8Nvf0TK7Jjkif72WrfTJDJoo6KvH0hCYqrkyWvDb")
// [Optional] Track statistics around application opens.
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
} | 28.828571 | 107 | 0.681863 |
12d41a77242b387d9c159f66032ca74ff1384d55 | 16,686 | html | HTML | blog/2017/10/01/index.html | xcomediagroup/xridescarsbeta | b770722c7a745f3616b8313288f1b4c688f3ad64 | [
"MIT"
] | null | null | null | blog/2017/10/01/index.html | xcomediagroup/xridescarsbeta | b770722c7a745f3616b8313288f1b4c688f3ad64 | [
"MIT"
] | null | null | null | blog/2017/10/01/index.html | xcomediagroup/xridescarsbeta | b770722c7a745f3616b8313288f1b4c688f3ad64 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
.mt-v {
margin-top: 76px !important;
}
p.space {
line-height: 8px;
}
img {
max-width: 100%;
width: auto 9;
height: auto;
vertical-align: middle;
border: 0;
-ms-interpolation-mode: bicubic;
}
.carousel-inner img {
width: 100%;
height: 100%;
}
.fa {
padding: 10px;
font-size: 20px;
width: 30px;
height: 20px;
text-align: center;
text-decoration: none;
margin: 0px 6 px;
border-radius: 40%;
}
.fa:hover {
opacity: 0.7;
color: #e9ecef;
}
.fa-facebook {
color: #868e96;
}
.fa-twitter {
color: #868e96;
}
.fa-instagram {
color: #868e96;
}
.fa-google {
color: #868e96;
}
.fa-youtube {
color: #868e96;
}
</style>
<title>Review: 2017 Škoda Rapid (India) - X Rides Cars</title>
<!-- Bootstrap core CSS -->
<link href="../../../../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../../../../css/modern-business.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<div>
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="../../../../index.html">X Rides Cars</a>
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="../../../../about/index.html">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="../../../../partners/index.html">Partners</a>
</li>
<li class="nav-item">
<a class="nav-link" href="../../../../blog/index.html">Blog</a>
</li>
<li class="nav-item">
<a class="nav-link" href="../../../../contact/index.html">Contact</a>
</li>
<li class="nav-item">
<a href="https://www.facebook.com/xridescars" target="_blank" class="fa fa-facebook"></a><a href="https://www.twitter.com/xridescars" target="_blank" class="fa fa-twitter"></a><a href="https://www.instagram.com/xridescars" target="_blank" class="fa fa-instagram"></a><a href="https://plus.google.com/101804013937326995249" target="_blank" class="fa fa-google"></a><a href="https://www.youtube.com/xridescars" target="_blank" class="fa fa-youtube"></a>
</li>
</ul>
</div>
</div>
</nav>
</div>
<!-- Page Content -->
<div class="container">
<!-- Page Heading/Breadcrumbs -->
<h1 class="mt-v p4-4 mb-3">Review: 2017 Škoda Rapid (India)
</h1>
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="../../../../index.html">Home</a>
</li>
<li class="breadcrumb-item">
<a href="../../../../blog/index.html">The Blog</a>
</li>
<li class="breadcrumb-item active">Review: 2017 Škoda Rapid (India)</li>
</ol>
<div class="row">
<!-- Post Content Column -->
<div class="col-lg-8">
<!-- Preview Image -->
<img src="img/20171001.JPG">
<hr>
<!-- Date/Time -->
<p>15 December 2017, Neil Parkhi</p>
<hr>
<!-- Post Content -->
<h4>Introduction/Heritage</h4>
<p>The Škoda Rapid seen here, is a subcompact car produced by Škoda India, the subsidiary of the Czech manufacturer Škoda Auto, exclusively for the Indian market, which was introduced in November 2011. It features a similar front end design with the second generation of the Škoda Fabia, but is not directly related to it, the Rapid being based on the newer PQ25 platform of the Volkswagen Group. In October 2011, Škoda resurrected the Rapid nameplate for its similar version of the Volkswagen Vento made in India, with sales starting in November. The car is produced by Škoda Auto India Private Limited in Pune. The 2017 Skoda Rapid facelift comes with revised styling that makes it look sharper. New exterior changes include new front grille, headlamps, chrome door handles, smoked out tail lamps, etc. Some of the new features include cruise control, rain sensing wipers, reach and rake adjustable steering, cooled glovebox and footwell lighting. The European model of the ŠKODA Rapid is based on the Škoda MissionL concept car, and was launched in 2012. It is, however, a different design, slightly longer, with different interiors, a slightly different body shape, and different engine options. It had its premiere at the Paris Motor Show in September 2012. The new updated Škoda Rapid sedan made its way in the Indian car market in November 2016. The new facelift model comes with an array of changes and updates to help it enhance its appeal to the customers and to increase the sales volumes. It has been endowed with a new front fascia that is in line with Skoda's new design language that has been used on its new family of cars such as the new Octavia, new Superb and the car maker’s latest Kodiaq SUV. The new Rapid facelift’s fresh front end comes with a newly styled radiator grille that is surrounded by a chrome finished frame and new angular headlight design to appear sharper than before and to enhance the aggressive visual appeal. The sedan model also gets a new bumper design that is sharper than before and houses a large honeycomb air intake that further enhances the sharper and bolder appeal, while fog lamps are placed on either side of the air intake. The new updated Rapid also comes endowed with some mild updates on its rear design. The updates on the car’s back design include a restyled bumper and a new chrome strip on the car’s boot lid. Skoda has also endowed a new boot lip spoiler and revised tail lamps to offer a fresher look for the rear façade of the facelift Rapid. The side profile of the sedan remains unchanged, excepting for the redesigned alloy wheels. The range topping variants of the sedan also offers LED daytime running lights which are integrated to the dual barrel headlamp setup of the car. All these design updates make the new updated Skoda Rapid look and feel more contemporary, premium and stylish than the previous model. The new updated Skoda Rapid sedan offers a very well-appointed cabin design. The classy looking interiors with nice fit and finish are like that of its German sibling and market rival, the Volkswagen Vento. The cabin of the Rapid has also been improved with some upgrades and changes to match its fresher exterior. The car offers a very spacious and comfortable cabin with nice well-supportive seating arrangement and ample legroom to offer a comfortable drive experience for all the occupants. The sedan also gets some added features such as cruise control system, light sensing automatic headlamps and rain sensing automatic wipers. The top of the line variant of the Rapid sedan offers a 6.5-inch touchscreen integrated infotainment system that comes along with MirrorLink feature that allows one to put all the smartphone content on to the automobile’s display. There are also the standard connectivity options such as AUX, USB and Bluetooth. Other features include Automatic Climate Control, Multi-function Steering Wheel and more. The Skoda Rapid sedan competes with some very well established and bestselling models in the Indian C-segment, such as the Maruti Suzuki Ciaz, the Honda City and the Volkswagen Vento. The Rapid sedan also shares its platform as well as engine range with its German competitor, the Volkswagen Vento. Although the Rapid has been a highly popular product from Skoda and a major sales volume drawer in India, its popularity is not even closely comparable to the top sellers of the C-segment of India. The new updated Skoda Rapid sedan’s petrol price range has a price range that starts at 827000 rupees, or 8.27 lakhs or 12900 US Dollars that goes up to 1.1 million rupees or 11 lakhs or 16900 US Dollars for the top of the line model, while the diesel variants have a price range starting at 948000 or 9.48 lakh rupees or 14500 US Dollars that goes up to 1.2 million rupees or 12 lakhs or 18400 US Dollars for the top of the line model.</p>
<h4>Specifications</h4>
<table class="table">
<thead>
<tr class="table-active">
<th style="width:33%;">Steering and Transmission</th>
<th style="width:67%;"></th>
</tr>
</thead>
<tbody>
<tr>
<th>Steering Type</th>
<td>Speed Proportional, Electro-Mechanical, Rack and Pinion Power Steering</td>
</tr>
<tr>
<th>Transmission Type</th>
<td>5 Speed Manual or 6 Speed Automatic</td>
</tr>
</tbody>
<thead>
<tr class="table-active">
<th style="width:33%;">Wheels and Tires</th>
<th style="width:67%;"></th>
</tr>
</thead>
<tbody>
<tr>
<th>Front Wheel Type</th>
<td>15 inch 5 twin spoke alloys</td>
</tr>
<tr>
<th>Rear Wheel Type</th>
<td>15 inch 5 twin spoke alloys</td>
</tr>
<tr>
<th>Front Tire Type</th>
<td>195/55R16</td>
</tr>
<tr>
<th>Rear Tire Type</th>
<td>195/55R16</td>
</tr>
<tr>
<th>Front Brake Type</th>
<td>Disc</td>
</tr>
<tr>
<th>Rear Brake Type</th>
<td>Drum</td>
</tr>
</tbody>
<thead>
<tr class="table-active">
<th style="width:33%;">Suspension</th>
<th style="width:67%;"></th>
</tr>
</thead>
<tbody>
<tr>
<th>Front Suspension Type</th>
<td>Independent MacPherson Strut</td>
</tr>
<tr>
<th>Rear Suspension Type</th>
<td>Compound Link Crank</td>
</tr>
<tr>
<th>Suspension Features</th>
<td>Stabilizer Bars, Coil Springs, Gas Pressurized Shock Absorbers</td>
</tr>
</tbody>
<thead>
<tr class="table-active">
<th style="width:33%;">Dimensions</th>
<th style="width:67%;"></th>
</tr>
</thead>
<tbody>
<tr>
<th>Length (in, mm)</th>
<td>173.7in, 4413mm</td>
</tr>
<tr>
<th>Width (in, mm)</th>
<td>66.9in, 1699mm</td>
</tr>
<tr>
<th>Height (in, mm)</th>
<td>57.7in, 1466mm</td>
</tr>
<tr>
<th>Wheelbase (in, mm)</th>
<td>100.4in, 2552mm</td>
</tr>
<tr>
<th>Weight (lb, kg)</th>
<td>4332lb, 2619kg</td>
</tr>
</tbody>
<thead>
<tr class="table-active">
<th style="width:33%;">Engine Specifications</th>
<th style="width:67%;"></th>
</tr>
</thead>
<tbody>
<tr>
<th>Engine Type</th>
<td>1.6 litre TSI 16 valve petrol inline 4 cylinder</td>
</tr>
<tr>
<th>Power (bhp, PS, kW)</th>
<td>335bhp, 340PS, 250kW @ 5900 rpm</td>
</tr>
<tr>
<th>Torque (lb-ft, Nm)</th>
<td>332lb-ft, 450Nm @ 1500RPM</td>
</tr>
<tr>
<th>0-60 mph (0-97 kmph)</th>
<td>4.3 seconds</td>
</tr>
<tr>
<th>Top Speed (mph, kmph)</th>
<td>155 mph, 250 kmph</td>
</tr>
<tr>
<th>Drivetrain</th>
<td>Rear Wheel Drive</td>
</tr>
<tr>
<th>Fuel Tank Size (gal, L)</th>
<td>14.5 gallons, 55L</td>
</tr>
<tr>
<th>Fuel Type (AKI, RON)</th>
<td>91 Octane/AKI Petrol (95 RON)</td>
</tr>
<tr>
<th>City Fuel Economy (mpg, kmpL)</th>
<td>31mpg, 12kmpL</td>
</tr>
<tr>
<th>City Fuel Economy (mpg, kmpL)</th>
<td>40mpg, 15kmpL</td>
</tr>
</tbody>
<thead>
<tr class="table-active">
<th style="width:33%;">Cargo Specifications</th>
<th style="width:67%;"></th>
</tr>
</thead>
<tbody>
<tr>
<th>Cargo Space (ft<sup>3</sup>, L)</th>
<td>16.2ft<sup>3</sup>, 460L</td>
</tr>
<tr>
<th>Max. Cargo Space (ft<sup>3</sup>, L)</th>
<td>16.2ft<sup>3</sup>, 460L</td>
</tr>
</tbody>
</table>
<hr>
</div>
<!-- Sidebar Widgets Column -->
<div class="col-md-4">
<!-- Categories Widget -->
<div class="card my-4">
<h5 class="card-header">Video Reviews</h5>
<div class="card-body">
<p class="space">
<a href="https://www.youtube.com/watch?v=xekZkv3GcgM" target="_blank"><button role="button" type="button" class="btn btn-dark btn-block">Full Take Review</button></a>
<br>
<a href="https://www.youtube.com/watch?v=t5oZl2YAiqY" target="_blank"><button role="button" type="button" class="btn btn-dark btn-block">Short Take Review</button></a>
</p>
</div>
</div>
<!-- Side Widget -->
<div class="card my-4">
<div class="card-body">
POA
</div>
</div>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.FloatPosition.TOP_LEFT}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<!-- Footer -->
<footer class="py-5 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright © 2018 XCO Media Group. All rights reserved.</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="../../../../vendor/jquery/jquery.min.js"></script>
<script src="../../../../vendor/popper/popper.min.js"></script>
<script src="../../../../vendor/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
| 44.259947 | 4,866 | 0.555915 |
f9fe0eefecf16b30a07f576e8e6725634e16a906 | 865 | lua | Lua | nvim/.config/nvim/lua/config/markdown-preview.lua | delafthi/dotfiles | 8de76e7f47f0a81ad6759315d8d26417b74993bd | [
"MIT"
] | 1 | 2021-03-05T14:50:23.000Z | 2021-03-05T14:50:23.000Z | nvim/.config/nvim/lua/config/markdown-preview.lua | delafthi/dotfiles | 8de76e7f47f0a81ad6759315d8d26417b74993bd | [
"MIT"
] | null | null | null | nvim/.config/nvim/lua/config/markdown-preview.lua | delafthi/dotfiles | 8de76e7f47f0a81ad6759315d8d26417b74993bd | [
"MIT"
] | null | null | null | local M = {}
local u = require("util")
function M.setup()
vim.g.mkdp_autoclose = 0 -- Disable auto close, when changing to a different buffer.
vim.g.mkdp_browser = "brave" -- Set default browser.
vim.gmkdp_filetypes = { "markdown", "vimwiki" } -- Set compatible filetypes.
vim.g.mkdp_page_title = "${name}" -- Set page title.
vim.g.mkdp_refresh_slow = 0 -- Turn on faust auto refresh.
vim.g.mkdp_preview_options = {
mkit = {},
katex = {},
uml = {},
disable_sync_scroll = 0,
sync_scroll_type = "relative",
hide_yaml_meta = 1,
sequence_diagrams = {},
flowchart_diagrams = {},
content_editable = false,
disable_filename = 0,
}
end
function M.config()
local opts = { noremap = false, silent = true }
u.map("n", "<Leader>mp", "<Plug>MarkdownPreviewToggle", opts) -- Set keymap to toggle preview.
end
return M
| 28.833333 | 96 | 0.655491 |
5fba30e7c458d656d52f30a919226f4cf51a0ad8 | 1,271 | h | C | XYAVPlayer/XYAVPlayer/XYAVPlayer/XYAVPlayer.h | xinyuly/XYAVPlayer | f417ee05af63e15680e3229b302653ab9c2a2217 | [
"MIT"
] | null | null | null | XYAVPlayer/XYAVPlayer/XYAVPlayer/XYAVPlayer.h | xinyuly/XYAVPlayer | f417ee05af63e15680e3229b302653ab9c2a2217 | [
"MIT"
] | null | null | null | XYAVPlayer/XYAVPlayer/XYAVPlayer/XYAVPlayer.h | xinyuly/XYAVPlayer | f417ee05af63e15680e3229b302653ab9c2a2217 | [
"MIT"
] | null | null | null | //
// AVPlayer.h
// XYAVPlayer
//
// Created by lixinyu on 16/5/26.
// Copyright © 2016年 xiaoyu. All rights reserved.
//
#import <UIKit/UIKit.h>
@class AVPlayerItem;
@class AVURLAsset;
@class AVPlayer;
@class XYAVPlayer;
//protocol
@protocol XYAVPlayerDelegate <NSObject>
- (void)playerDidStartPlay:(XYAVPlayer*)player;
- (void)playerDidPausePlay:(XYAVPlayer*)player;
- (void)playerDidStopPlay: (XYAVPlayer*)player;
- (void)player:(XYAVPlayer *)player didLoadSeconds:(NSTimeInterval)availableSeconds totalSeconds:(NSTimeInterval)totalSeconds;
- (void)player:(XYAVPlayer *)player didUpdatePlayProgress:(NSTimeInterval)currentTime totalSeconds:(NSTimeInterval)totalSeconds;
- (void)player:(XYAVPlayer *)player readyToPlayItem:(AVPlayerItem *)playerItem;
- (void)player:(XYAVPlayer *)player didPlayToEndTime:(BOOL)endTime;
@end
@interface XYAVPlayer : NSObject
@property (nonatomic, readonly) AVPlayerItem *currentItem;
@property (nonatomic, assign) NSTimeInterval currentTime;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, weak) id<XYAVPlayerDelegate>deleagte;
+ (instancetype)sharedPlayer ;
- (void)playWithURL:(NSURL *)audioURL;
- (void)play;
- (void)pause;
- (void)stop;
- (BOOL)isPlaying;
- (void)clean;
@end
| 25.938776 | 128 | 0.754524 |
1fb00d9832a1d4721a5f3456709038bff0b70ab3 | 320 | kt | Kotlin | app/src/main/java/com/syleiman/myfootprints/modelLayer/dto/FootprintMarkerDto.kt | AlShevelev/MyFootprints | 11a243900f3a33b4b3aab358d4a2b08f9759dd8e | [
"MIT"
] | 3 | 2019-03-20T14:12:53.000Z | 2020-07-13T05:39:54.000Z | app/src/main/java/com/syleiman/myfootprints/modelLayer/dto/FootprintMarkerDto.kt | AlShevelev/MyFootprints | 11a243900f3a33b4b3aab358d4a2b08f9759dd8e | [
"MIT"
] | null | null | null | app/src/main/java/com/syleiman/myfootprints/modelLayer/dto/FootprintMarkerDto.kt | AlShevelev/MyFootprints | 11a243900f3a33b4b3aab358d4a2b08f9759dd8e | [
"MIT"
] | null | null | null | package com.syleiman.myfootprints.modelLayer.dto
/**
* One footprint options on map
*/
data class FootprintMarkerDto(
var footprintId: Long,
var markerColor: Int,
var latitude: Double,
var longitude: Double,
val footprintPhotoFileName: String,
var description: String)
| 24.615385 | 48 | 0.671875 |
8622c4ff917344da45becbec41255ace691e205b | 1,966 | java | Java | api/src/main/java/io/druid/segment/loading/DataSegmentKiller.java | PetrykinVictor/incubator-druid | 62677212cc72e3024cb9f1e72455155e5b746d38 | [
"Apache-2.0"
] | 1 | 2019-05-17T08:44:00.000Z | 2019-05-17T08:44:00.000Z | api/src/main/java/io/druid/segment/loading/DataSegmentKiller.java | nordicfactory/druid | 09136a17497782324c30f355e52f416cd4ef0df5 | [
"Apache-2.0"
] | 3 | 2017-10-23T03:44:57.000Z | 2018-10-31T11:34:32.000Z | api/src/main/java/io/druid/segment/loading/DataSegmentKiller.java | nordicfactory/druid | 09136a17497782324c30f355e52f416cd4ef0df5 | [
"Apache-2.0"
] | null | null | null | /*
* 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 io.druid.segment.loading;
import io.druid.guice.annotations.ExtensionPoint;
import io.druid.java.util.common.logger.Logger;
import io.druid.timeline.DataSegment;
import java.io.IOException;
@ExtensionPoint
public interface DataSegmentKiller
{
Logger log = new Logger(DataSegmentKiller.class);
/**
* Removes segment files (index and metadata) from deep storage.
* @param segment the segment to kill
* @throws SegmentLoadingException if the segment could not be completely removed
*/
void kill(DataSegment segment) throws SegmentLoadingException;
/**
* A more stoic killer who doesn't throw a tantrum if things get messy. Use when killing segments for best-effort
* cleanup.
* @param segment the segment to kill
*/
default void killQuietly(DataSegment segment)
{
try {
kill(segment);
}
catch (Exception e) {
log.debug(e, "Failed to kill segment %s", segment);
}
}
/**
* Like a nuke. Use wisely. Used by the 'reset-cluster' command, and of the built-in deep storage implementations, it
* is only implemented by local and HDFS.
*/
void killAll() throws IOException;
}
| 32.229508 | 119 | 0.730417 |
68527e5db24d6a878ea3cbce5d641b857a566eb4 | 3,666 | html | HTML | enma/templates/public/privacy.html | pixmeter/enma | 3d475b46dd24947fc4a870d0648d04bc2b17aed2 | [
"BSD-3-Clause"
] | null | null | null | enma/templates/public/privacy.html | pixmeter/enma | 3d475b46dd24947fc4a870d0648d04bc2b17aed2 | [
"BSD-3-Clause"
] | null | null | null | enma/templates/public/privacy.html | pixmeter/enma | 3d475b46dd24947fc4a870d0648d04bc2b17aed2 | [
"BSD-3-Clause"
] | null | null | null | {% extends 'layout.html' %}
{% block title %}Privacy{% endblock %}
{% block content %}
<div class="page-header">
<h2>Preamble</h2>
</div>
<p><em>
This site is a development site and does not aim to be used in production.
This privacy statement apply for this site as well as serve as a blueprint for
other derived web applications.
</em></p>
<div class="page-header">
<h1>Privacy</h1>
</div>
<div class="page-content">
<h2>Information we collect </h2>
<p>
We collect information to provide better services to all of our users
<ul>
<li> From figuring out basic stuff like which language you speak, </li>
<li> To more complex things like which ads you’ll find most useful </li>
</ul>
We collect information in two ways:
</p>
<h3> Information you give us </h3>
<ul>
<li>
If you to sign up for a enma account.
we’ll ask for personal information, like your name, email address.
</li>
<li>
If you want to take full advantage of the using features we offer,
we'll ask for more personal information like telephone number, photo or
credit card.
</li>
</ul>
<h3> Information we get from your use of our services. </h3>
We collect information about the services that you use and how you use them.
This information includes:
<ul>
<li>
<b> Device information: </b>
We collect device-specific information (such as your hardware model,
operating system version, unique device identifiers, and mobile network
information).
</li>
<li>
<b> Log information </b>
When you use our services , we automatically collect and store certain
information in server logs. This includes:
<ul>
<li>Details of how you used our service. </li>
<li>Internet protocol address. device event information such as crashes,
system activity, hardware settings, browser type, browser language,
the date and time of your request and referral URL.
cookies that may uniquely identify your browser or your enma account.
</li>
</li>
</li>
<b> Local storage </b>
We may collect and store information (including personal information)
locally on your device using mechanisms such as browser web storage
(including HTML 5) and application data caches.
</li>
</li>
<b> Cookies and anonymous identifiers </b>
We and our partners use various technologies to collect and store
information when you visit our service, and this may include sending one or
more cookies or anonymous identifiers to your device.
We also use cookies and anonymous identifiers when you interact with
services we offer to our partners, such as advertising services or enma
features that may appear on other sites.
</li>
</ul>
<h2> How we use information we collect </h2>
<p>
We use the information we collect from all of our services to provide,
maintain, protect and improve them, to develop new ones, and to protect us
and our users.
</p><p>
We also use this information to offer you tailored use of our service.
</p><p>
When you contact us, we keep a record of your communication to help solve
any issues you might be facing. We may use your email address to inform
you about our services, such as letting you know about upcoming changes
or improvements.
</p><p>
We use information collected from cookies and other technologies,
to improve your user experience and the overall quality of our services.
</p><p>
We will ask for your consent before using information for a purpose other
than those that are set out in this Privacy Policy.
</p>
</div>
<h2> Privacy Version </h2>
This privacy statement is released at 2015-04-20.
</p>
{% endblock %}
| 28.640625 | 79 | 0.717676 |
16426534ec1a290ad4ce225944c11083161f1e93 | 389 | ts | TypeScript | src/calculator.ts | greazleay/jest-test | 8702f8c85b6955fc49d81cc2770db5cbf3d341c6 | [
"MIT"
] | null | null | null | src/calculator.ts | greazleay/jest-test | 8702f8c85b6955fc49d81cc2770db5cbf3d341c6 | [
"MIT"
] | null | null | null | src/calculator.ts | greazleay/jest-test | 8702f8c85b6955fc49d81cc2770db5cbf3d341c6 | [
"MIT"
] | null | null | null | class Calculator {
add = (a: number, b: number): number => {
return a + b
};
subtract = (a: number, b: number): number => {
return a - b
};
divide = (a: number, b: number): number | string => {
return b ? a / b : 'Infinity'
};
multiply = (a: number, b: number): number => {
return a * b
};
}
export default new Calculator | 20.473684 | 57 | 0.496144 |
255e7f9855dd8ad9b5a91b33f7a79d23e76f8082 | 491 | kt | Kotlin | snackBar.kt | saranihansamali/KotlinReusableComponents | 80dca5ac0e987265429e8682a54a905360507257 | [
"Apache-2.0"
] | null | null | null | snackBar.kt | saranihansamali/KotlinReusableComponents | 80dca5ac0e987265429e8682a54a905360507257 | [
"Apache-2.0"
] | 5 | 2020-10-03T00:44:00.000Z | 2020-10-03T01:22:50.000Z | snackBar.kt | saranihansamali/KotlinReusableComponents | 80dca5ac0e987265429e8682a54a905360507257 | [
"Apache-2.0"
] | 2 | 2020-10-03T00:45:32.000Z | 2020-10-03T01:03:20.000Z | inline fun View.snack(message: String?, messageRes: Int, length: Int = Snackbar.LENGTH_LONG,color: Int? = null,colorBackground: Int? = null, f: Snackbar.() -> Unit) {
val snack = Snackbar.make(this, message!!, length)
val snackBarView: View = snack.view
snack.f()
snack.show()
color?.let {
snack.setActionTextColor(ContextCompat.getColor(context, color))
snackBarView.setBackgroundColor(ContextCompat.getColor(context,colorBackground!!));
}
} | 49.1 | 167 | 0.684318 |
1be77cf954fce9e15c1c18bdb125d67a2526b29f | 5,299 | py | Python | lpot/ux/web/server.py | sissi2017/lpot | 968fb136464aa4d89131c62aa5f01a7392571cdf | [
"Apache-2.0"
] | null | null | null | lpot/ux/web/server.py | sissi2017/lpot | 968fb136464aa4d89131c62aa5f01a7392571cdf | [
"Apache-2.0"
] | null | null | null | lpot/ux/web/server.py | sissi2017/lpot | 968fb136464aa4d89131c62aa5f01a7392571cdf | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright (c) 2021 Intel Corporation
#
# 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.
"""Main endpoint for GUI."""
import os
from functools import wraps
from threading import Thread
from typing import Any, Callable
from flask import Flask
from flask import Request as WebRequest
from flask import jsonify, request
from flask_cors import CORS
from flask_socketio import SocketIO
from werkzeug.wrappers import BaseResponse as WebResponse
from lpot.ux.utils.exceptions import InternalException
from lpot.ux.utils.logger import log
from lpot.ux.web.communication import MessageQueue, Request
from lpot.ux.web.configuration import Configuration
from lpot.ux.web.router import Router
from lpot.ux.web.service.response_generator import ResponseGenerator
app = Flask(__name__, static_url_path="")
socketio = SocketIO()
router = Router()
METHODS = ["GET", "POST"]
# Suppress TensorFlow messages
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
def run_server(configuration: Configuration) -> None:
"""Run webserver on specified scheme, address and port."""
addr = configuration.server_address
server_port = configuration.server_port
gui_port = configuration.gui_port
token = configuration.token
cors_allowed_origins = f"{configuration.scheme}://{addr}:{gui_port}"
app.secret_key = token
CORS(app, origins=cors_allowed_origins)
socketio.init_app(
app,
cors_allowed_origins=cors_allowed_origins,
max_http_buffer_size=2000,
)
socketio.run(app, host=addr, port=server_port)
@app.after_request
def block_iframe(response: WebResponse) -> WebResponse:
"""Block iframe and set others CSP."""
response.headers["X-Frame-Options"] = "DENY"
response.headers[
"Content-Security-Policy"
] = "frame-ancestors 'none'; font-src 'self'; img-src 'self'; script-src 'self'"
response.headers["Access-Control-Max-Age"] = "-1"
return response
@app.after_request
def block_sniffing(response: WebResponse) -> WebResponse:
"""Block MIME sniffing."""
response.headers["X-Content-Type-Options"] = "nosniff"
return response
def require_api_token(func: Callable) -> Any:
"""Validate authorization token."""
@wraps(func)
def check_token(*args: str, **kwargs: str) -> Any:
"""Validate that correct token was provided."""
provided_token = request.headers.get(
"Authorization",
request.args.to_dict().get("token", None),
)
if not app.secret_key == provided_token:
return (
"Invalid token, please use the URL displayed by the server on startup",
403,
)
return func(*args, **kwargs)
return check_token
@app.route("/", methods=METHODS)
def root() -> Any:
"""Serve JS application index."""
return app.send_static_file("index.html")
@app.route("/api/<path:subpath>", methods=METHODS)
@require_api_token
def handle_api_call(subpath: str) -> Any:
"""Handle API access."""
try:
parameters = build_parameters(subpath, request)
response = router.handle(parameters)
if isinstance(response, WebResponse):
return response
return jsonify(response.data)
except Exception as err:
if isinstance(err, InternalException):
log.critical(err)
return ResponseGenerator.from_exception(err)
@app.route("/api/<path:subpath>", methods=["OPTIONS"])
def allow_api_call(subpath: str) -> Any:
"""Allow for API access."""
return "OK"
@app.errorhandler(404)
def page_not_found(e: Any) -> Any:
"""Serve JS application index when no static file found."""
return app.send_static_file("index.html")
@app.after_request
def disable_cache(response: WebResponse) -> WebResponse:
"""Disable cache on all requests."""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
response.headers["Cache-Control"] = "public, max-age=0"
return response
def build_parameters(endpoint: str, request: WebRequest) -> Request:
"""Build domain object from flask request."""
data = request.get_json() if request.is_json else request.args.to_dict(flat=False)
return Request(request.method, endpoint, data)
def web_socket_publisher(web_socket: SocketIO) -> None:
"""Send messages from queue via web-socket to GUI."""
queue = MessageQueue()
while True:
message = queue.get()
web_socket.emit(
message.subject,
{"status": message.status, "data": message.data},
broadcast=True,
)
publisher = Thread(
target=web_socket_publisher,
args=(socketio,),
)
publisher.daemon = True
publisher.start()
| 30.454023 | 87 | 0.694282 |