content
stringlengths
10
4.9M
def is_apply_to_error_spans(self, is_apply_to_error_spans): self._is_apply_to_error_spans = is_apply_to_error_spans
Security service level agreement measurement in cloud: A proof of concept implementation Security concerns of cloud computing mainly originate from outsourced data and computation on which data owners do not have full control. Recent works in both industry and academia documented these concerns well and described both technical and non-technical measures to address these concerns. Many of the suggestions to address security concerns are in the form of physical audits by experts and certifications from standard groups for compliance. Unlike the performance measurement in cloud, security measurement is not matured and except solutions which address these concerns in part, there is no comprehensive mechanism which looks everything user wants to know about cloud. This paper introduces a notion of service level agreement from security perspective and proposes to monitor the cloud environment for run time compliance. Monitoring is done by a third party on end user's behalf by collecting credible evidence in the form of events, logs and measurement snapshots. Through this collected evidence the third party can answer to user security concerns stated in the form of SLA for compliance. We do a proof-of-concept implementation of security measurement with few sample service level agreements.
import os, argparse, shutil import numpy as np import open3d as o3d import trimesh def scale(args): """For now this function is simply used to rescale the ConvOnet output from unit cube to 75mm cube as used in Berger et al. benchmark""" args.scene_conf = args.scene + "_" + str(args.conf) gt_file = os.path.join(args.user_dir,args.data_dir,"ground_truth_surface",args.scene+".off") print("ground truth file ", gt_file) gt_mesh = trimesh.load(gt_file,'off',process=False) recon_file = os.path.join(args.user_dir,args.data_dir,"reconstructions","occ",args.scene_conf+".off") print("reconstruction file ", recon_file) recon_mesh = trimesh.load(recon_file,'off',process=False) # get the centroid pc_file = os.path.join(args.user_dir,args.data_dir,"scans","with_normals",args.scene_conf+".ply") pc = o3d.io.read_point_cloud(pc_file) centroid=pc.get_center() recon_mesh.vertices*=75 recon_mesh.vertices+=centroid recon_mesh.export(os.path.join(args.user_dir,args.data_dir,"reconstructions","occ","75",args.scene_conf+".off")) def npz(args): """This function is simply used to convert from ply files to ConvOnet or IGR input""" args.scene_conf = args.scene + "_" + str(args.conf) in_file = os.path.join(args.user_dir,args.data_dir,"scans","with_normals",args.scene_conf+".ply") print("convert file ", in_file) pc = o3d.io.read_point_cloud(in_file) pc.translate(-pc.get_center()) pc.scale(scale=1 / 75, center=False) out_path = os.path.join(args.user_dir,args.data_dir,"scans","occ",args.scene_conf) if not os.path.exists(out_path): os.makedirs(out_path) out_file = os.path.join(out_path,"pointcloud.npz") np.savez_compressed(out_file, \ points=np.array(pc.points), \ normals=np.array(pc.normals)) o3d.io.write_point_cloud(os.path.join(args.user_dir,args.data_dir,"scans","with_normals_scaled",args.scene_conf+".ply"), pc) ## input for IGR # np.savez_compressed(file.split('.')[0]+".npz", \ # np.concatenate((np.array(points.points),np.array(points.normals)),1)) ## test if it worked and load the file again to inspect that the correct fields are there # data = np.load(in_file.split('.')[0]+".npz") def copy(args): """This is for copying the scene.npz files to /scene/pointcloud.npz""" input_dir = args.user_dir + args.data_dir + "reconbench/occ/pointclouds/" output_dir = args.user_dir + args.data_dir + "occ/reconbench/" # onlyfiles = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(working_dir, f))] for i in os.listdir(input_dir): pointcloud_file=os.path.join(input_dir, i) # print(pointcloud_file) # if path doesn't exist if not os.path.exists(os.path.join(output_dir, i[:-4])): os.makedirs(os.path.join(output_dir, i[:-4])) # if file isn't already copied copy_to = os.path.join(output_dir,i[:-4],'pointcloud.npz') if not os.path.isfile(copy_to) or args.overwrite: print("copy from {} to {}".format(pointcloud_file,copy_to)) shutil.copyfile(pointcloud_file,copy_to) if __name__ == "__main__": parser = argparse.ArgumentParser(description='make onet input data') parser.add_argument('--user_dir', type=str, default="/home/raphael/", help='the user folder, or PhD folder.') parser.add_argument('-d', '--data_dir', type=str, default="data/", help='working directory which should include the different scene folders.') parser.add_argument('-s', '--scenes', nargs='+', type=str, default=["Ship"], help='on which scene to execute pipeline.') parser.add_argument('-c', '--confs', nargs='+', type=int, default=[0], help='which config file to load') parser.add_argument('-i', '--input_file_extension', type=str, default="", help='the mesh file to be evaluated') parser.add_argument('--reconbench_dir', type=str, default="cpp/reconbench-CMake/build", help='Indicate the openMVS binary directory, pointing to .../bin folder starting from user_dir') parser.add_argument('--sure_dir', type=str, default="cpp/surfaceReconstruction/build/release", help='Indicate the sure build directory, pointing to .../build/release folder starting from user_dir') parser.add_argument('--gco', type=str, default="area-1.0", help='graph cut optimization type,weight. default: area,1.0') # additional Mesh reconstruction options: parser.add_argument('-p', '--steps', type=str, default='e', help='pipeline steps. default: idmr. extra options: sampling = s, evaluation = e') parser.add_argument('--overwrite', action='store_true', default=True, help='Whether to overwrite output.') args = parser.parse_args() scale(args) npz(args) copy(args)
/** * Indicates that the given object was deleted in the model. If this object * is currently edited in a form, this form is closed. * * @param obj */ public void objectDeleted(IScenarioObject obj) { if (currentForm != null) { if (currentForm.getCurrentlyEditedObject() == obj) { currentForm = null; layout2.topControl = form; container.layout(); } } }
// -*- coding: utf-8 -*- /** Kanevsky all minimum node k cutsets algorithm. */ from operator import itemgetter from itertools import combinations #include <xnetwork.hpp> // as xn from .utils import build_auxiliary_node_connectivity from xnetwork.algorithms.flow import ( build_residual_network, edmonds_karp, shortest_augmenting_path, ); default_flow_func = edmonds_karp __author__ = "\n".join(["<NAME> <<EMAIL>>"]); static const auto __all__ = ["all_node_cuts"]; auto all_node_cuts(G, k=None, flow_func=None) { r/** Return all minimum k cutsets of an undirected graph G. This implementation is based on Kanevsky"s algorithm [1]_ for finding all minimum-size node cut-sets of an undirected graph G; ie the set (or sets) of nodes of cardinality equal to the node connectivity of G. Thus if ( removed, would break G into two || more connected components. Parameters ---------- G : XNetwork graph Undirected graph k : Integer Node connectivity of the input graph. If k.empty(), then it is computed. Default value: None. flow_func : function Function to perform the underlying flow computations. Default value edmonds_karp. This function performs better : sparse graphs with right tailed degree distributions. shortest_augmenting_path will perform better : denser graphs. Returns ------- cuts : a generator of node cutsets Each node cutset has cardinality equal to the node connectivity of the input graph. Examples -------- >>> // A two-dimensional grid graph has 4 cutsets of cardinality 2 >>> G = xn::grid_2d_graph(5, 5); >>> cutsets = list(xn::all_node_cuts(G)); >>> len(cutsets); 4 >>> all(2 == len(cutset) for cutset : cutsets); true >>> xn::node_connectivity(G); 2 Notes ----- This implementation is based on the sequential algorithm for finding all minimum-size separating vertex sets : a graph [1]_. The main idea is to compute minimum cuts using local maximum flow computations among a set of nodes of highest degree && all other non-adjacent nodes : the Graph. Once we find a minimum cut, we add an edge between the high degree node && the target node of the local maximum flow computation to make sure that we will not find that minimum cut again. See also -------- node_connectivity edmonds_karp shortest_augmenting_path References ---------- .. [1] <NAME>. (1993). Finding all minimum-size separating vertex sets : a graph. Networks 23(6), 533--541. http://onlinelibrary.wiley.com/doi/10.1002/net.3230230604/abstract */ if (!xn::is_connected(G) { throw xn::XNetworkError("Input graph is disconnected."); // Address some corner cases first. // For cycle graphs if (G.order() == G.size() { if (all(2 == d for n, d : G.degree()) { seen = set(); for (auto u : G) { for (auto v : xn::non_neighbors(G, u) { if ((u, v) not : seen && (v, u) not : seen) { yield {v, u} seen.add((v, u)); return; // For complete Graphs if (xn::density(G) == 1) { for (auto cut_set : combinations(G, len(G) - 1) { yield set(cut_set); return; // Initialize data structures. // Keep track of the cuts already computed so we do not repeat them. seen = []; // Even-Tarjan reduction is what we call auxiliary digraph // for node connectivity. H = build_auxiliary_node_connectivity(G); mapping = H.graph["mapping"]; R = build_residual_network(H, "capacity"); kwargs = dict(capacity="capacity", residual=R); // Define default flow function if (flow_func.empty()) { flow_func = default_flow_func if (flow_func is shortest_augmenting_path) { kwargs["two_phase"] = true; // Begin the actual algorithm // step 1: Find node connectivity k of G if (k.empty()) { k = xn::node_connectivity(G, flow_func=flow_func); // step 2) { // Find k nodes with top degree, call it X) { X = {n for n, d : sorted(G.degree(), key=itemgetter(1), reverse=true)[:k]} // Check if (X is a k-node-cutset if (_is_separating_set(G, X) { seen.append(X); yield X for (auto x : X) { // step 3: Compute local connectivity flow of x with all other // non adjacent nodes : G non_adjacent = set(G) - X - set(G[x]); for (auto v : non_adjacent) { // step 4: compute maximum flow : an Even-Tarjan reduction H of G // && step:5 build the associated residual network R R = flow_func(H, "%sB" % mapping[x], "%sA" % mapping[v], **kwargs); flow_value = R.graph["flow_value"]; if (flow_value == k) { // Remove saturated edges form the residual network saturated_edges = [(u, w, d) for (auto u, w, d) in R.edges(data=true); if (d["capacity"] == d["flow"]]; R.remove_edges_from(saturated_edges); // step 6: shrink the strongly connected components of // residual flow network R && call it L L = xn::condensation(R); cmap = L.graph["mapping"]; // step 7: Compute antichains of L; they map to closed sets : H // Any edge : H that links a closed set is part of a cutset for (auto antichain : xn::antichains(L) { // Nodes : an antichain of the condensation graph of // the residual network map to a closed set of nodes that // define a node partition of the auxiliary digraph H. S = {n for n, scc : cmap.items() if (scc : antichain} // Find the cutset that links the node partition (S,~S] : H cutset = set(); for (auto u : S) { cutset.update((u, w) for w : H[u] if (w not : S); // The edges : H that form the cutset are internal edges // (ie edges that represent a node of the original graph G); node_cut = {H.nodes[n]["id"] for edge : cutset for n : edge} if (len(node_cut) == k) { if (node_cut not : seen) { yield node_cut seen.append(node_cut); // Add an edge (x, v) to make sure that we do not // find this cutset again. This is equivalent // of adding the edge : the input graph // G.add_edge(x, v) && then regenerate H && R) { // Add edges to the auxiliary digraph. H.add_edge("%sB" % mapping[x], "%sA" % mapping[v], capacity=1); H.add_edge("%sB" % mapping[v], "%sA" % mapping[x], capacity=1); // Add edges to the residual network. R.add_edge("%sB" % mapping[x], "%sA" % mapping[v], capacity=1); R.add_edge("%sA" % mapping[v], "%sB" % mapping[x], capacity=1); break; // Add again the saturated edges to reuse the residual network R.add_edges_from(saturated_edges); auto _is_separating_set(G, cut) { /** Assumes that the input graph is connected */ if (len(cut) == len(G) - 1) { return true; H = xn::restricted_view(G, cut, []); if (xn::is_connected(H) { return false; return true;
Density functional theory study of the interaction of H2 with pure and Ti-doped WO3 (002) surfaces Density functional theory (DFT) calculations are conducted to explore the interaction of H2 with pure and Ti-doped WO3 (002) surfaces. Four top adsorption models of H2 on pure and Ti-doped WO3 (002) surfaces are investigated respectively, they are adsorption on bridging oxygen O1c, absorption on plane oxygen O2c, absorption on 5-fold W5c (Ti), and absorption on 6-fold W6c. The most stable and H2 possible adsorption structure in the pure surface is H-end oriented to the surface plane oxygen O2c site, while the favourable adsorption sites for H2 in a Ti-doped surface is not only an O2c site but also a W6c site. The adsorption energy, the Fermi energy level EF, and the electronic population are investigated and the H2-sensing mechanism of a pure-doped WO3 (002) surface is revealed theoretically: the theoretical results are in good accordance with our existing experimental results. By comparing the above three terms, it is found that Ti doping can obviously enhance the adsorption of H2. It can be predicted that the method of Ti-doped into a WO3 thin film is an effective way to improve WO3 sensor sensitivity to H2 gas.
struct point { int x; int y; int z; }; int main() { return 0; }
/* * Colan Biemer * This class is in charge of holding the path string and the * date held by the file. */ public class Scene { private String path; private SimpleDateFormat format; private long date; public File file; public Scene(File fileFile) { this.file = fileFile; this.path = file.toString(); this.date = file.lastModified(); this.format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); } public String getFormattedDate() { return this.format.format(this.date); } public String getPath() { return this.path; } public long getDate() { return date; } public File getFile() { return file; } }
A man believed to be the suspect in an attack that injured five people in Edmonton over the weekend was detained days after arriving in the United States from Mexico, U.S. officials said. Abdullahi Hassan Sharif, who sources say is the same person as Abdulahi Hasan Sharif, the man charged with attempted murder after a knife and vehicle attack in Edmonton on Sept. 30, entered the United States at a pedestrian crossing near San Diego, Calif., in 2011, according to U.S. Customs and Border Protection (CBP). Sharif is originally from Somalia, RCMP officials said. He made an asylum claim at a Canada-U.S. border crossing in 2012 and was granted refugee status later that year, according to the office of federal Public Safety Minister Ralph Goodale. On July 12, 2011, Sharif arrived at the San Ysidro port of entry near San Diego on foot with no documents and no legal status to enter the U.S., said CBP spokeswoman Jacqueline Wasiluk. CBP officers took him into custody, and he was turned over to U.S. Immigration and Customs Enforcement (ICE). He was detained at the Otay Mesa Detention Center in San Diego on July 15, 2011. Wasiluk had no information on how long Sharif had been in Mexico. He had no known criminal history at the time of his encounter with ICE. On Sept. 22, 2011, an immigration judge ordered Sharif removed to Somalia, and Sharif waived his right to appeal the decision. About a month later, on Nov. 23, Sharif was released from custody on a supervision order due to a “lack of likelihood of his removal in the reasonably foreseeable future,” U.S. immigration officials said in a statement. Sharif did not report to U.S. immigration officials on Jan. 24, 2012, the day he was to be removed, and law enforcement officials could not track him down. Sharif was arrested after a city police officer was rammed by a car, then stabbed, outside Commonwealth Stadium on Saturday, and a U-Haul truck led police on a chase in downtown Edmonton early Sunday. The truck deliberately swerved to strike four pedestrians, police said. Sharif is charged with five counts of attempted murder, as well as dangerous driving and possession of a weapon. The RCMP “K” Division Integrated National Security Enforcement Teams has put out a call for any photos and videos of the attack on the officer and pedestrians. Contact them at 780-449-0209. [email protected]
use rsip::{headers::*, message::HeadersExt}; #[test] fn headers() { //TODO: start using randomized stuff/traits let via = Via::new("SIP/2.0/TLS client.biloxi.example.com:5061;branch=z9hG4bKnashd92"); let max_forwards = MaxForwards::new("70"); let to = To::new("Bob <sips:<EMAIL>>"); let from = From::new("Bob <sips:<EMAIL>>;tag=ja743ks76zlflH"); let call_id = CallId::new("<EMAIL>"); let cseq = CSeq::new("2 REGISTER"); let contact = Contact::new("<sips:<EMAIL>>"); let authorization = Authorization::new("Digest username=\"bob\", realm=\"atlanta.example.com\" nonce=\"ea9c8e88df84f1cec4341ae6cbe5a359\", opaque=\"\" uri=\"sips:ss2.biloxi.example.com\", response=\"dfe56131d1958046689d83306477ecc\""); let content_length = ContentLength::new("0"); let headers: rsip::headers::Headers = vec![ via.clone().into(), max_forwards.clone().into(), from.clone().into(), to.clone().into(), call_id.clone().into(), cseq.clone().into(), contact.clone().into(), authorization.clone().into(), content_length.clone().into(), ] .into(); let implementer = crate::support::HasHeadersImpl(headers); assert_eq!(implementer.via_header(), Ok(&via)); assert_eq!(implementer.max_forwards_header(), Ok(&max_forwards)); assert_eq!(implementer.to_header(), Ok(&to)); assert_eq!(implementer.from_header(), Ok(&from)); assert_eq!(implementer.call_id_header(), Ok(&call_id)); assert_eq!(implementer.cseq_header(), Ok(&cseq)); assert_eq!(implementer.contact_header(), Ok(&contact)); assert_eq!(implementer.authorization_header(), Some(&authorization)); }
<filename>autoload/autoload.go package autoload import "github.com/PrashantRaj18198/goenvargs" func init() { goenvargs.LoadEnvVars(nil, nil) }
/** * Sums two values. * @param <R> the result type * @param <T1> the first parameter type * @param <T2> the second parameter type */ public class Sum<R, T1, T2> implements BiFunction<T1, T2, R> { private final SumPolicy<R, T1, T2> policy; public Sum(SumPolicy<R, T1, T2> policy) { dbc.precondition(policy != null, "cannot create Sum with a null sum policy"); this.policy = policy; } @Override public R apply(T1 accumulator, T2 value) { return policy.sum(accumulator, value); } }
def config_logging(): yaml = YAML(typ="safe") with current_app.open_resource(current_app.config['LOGGING_CONFIG']) as f: config = yaml.load(f) log_lvl = "INFO" if os.environ.get('VERLOOP_DEBUG', False): log_lvl = "DEBUG" update_config = { "handlers": { "console": { "level": log_lvl }, "file": { "filename": current_app.config['LOGS'] } } } pydash.merge(config, update_config) logging.config.dictConfig(config) LOG.debug("Logger Configured!")
/** * Trim list of flashcards to review * @param flashcardsToReviewList Shuffled list of flashcards to review * @return Trimmed list of flashcards to review */ private ObservableList<Flashcard> trimReviewFlashcards(ObservableList<Flashcard> flashcardsToReviewList) { long reviewCardLimit = userPrefs.getReviewCardLimit(); boolean isReviewLimitValid = reviewCardLimit >= 1; boolean isReviewLimitUsed = reviewCardLimit < flashcardsToReviewList.size(); if (isReviewLimitUsed && isReviewLimitValid) { flashcardsToReviewList = FXCollections.observableArrayList( flashcardsToReviewList.subList(0, (int) reviewCardLimit)); } return flashcardsToReviewList; }
n=int(input()) l=list(map(lambda x: int(x), input().split())) res,a,b,c,d=0,0,0,0,0 for i in range(0,n): p=l[i] if (p==4) : a=a+1 elif p==3: b+=1 elif p==2: c+=1 else: d+=1 res+=a+b if b>=d: res+=c//2+c%2 else: if (d-b +2*(c%2))%4>0: res+=c//2+ (((d-b)+ 2*(c%2))//4) +1 else: res+=c//2+((d-b)+ 2*(c%2))//4 print (res )
<filename>src/lexer.rs<gh_stars>0 use lasso::{Rodeo, Spur}; use logos::{Lexer, Logos}; use std::fmt::Display; pub fn lex(src: &str) -> Lexer<Token> { let mut lexer = Token::lexer(src); for s in ["void", "int"] { lexer.extras.get_or_intern_static(s); } lexer } #[derive(Debug, PartialEq, Clone, Copy, Logos)] #[logos(extras = Rodeo)] pub enum Token { /// ( #[token("(")] LeftParen, /// ) #[token(")")] RightParen, /// { #[token("{")] LeftBrace, /// } #[token("}")] RightBrace, /// [ #[token("[")] LeftBracket, /// #[ #[token("#[")] HashBracket, /// ] #[token("]")] RightBracket, /// , #[token(",")] Comma, /// . #[token(".")] Dot, #[token("-")] Minus, #[token("+")] Plus, #[token("/")] Slash, #[token("%")] Percent, /// : #[token(":")] Colon, #[token("*")] Star, #[token("**")] DoubleStar, #[token("!")] Bang, #[token("!=")] BangEqual, #[token("=")] Equal, #[token("==")] DoubleEqual, #[token(">")] Greater, #[token(">=")] GreaterEqual, #[token("<")] Less, #[token("<=")] LessEqual, /// -> #[token("->")] Arrow, #[regex(r"[_a-zA-Z][_a-zA-Z0-9]*", |lex| lex.extras.get_or_intern(lex.slice()))] Identifier(Spur), #[regex(r"[0-9]+", |lex| lex.slice().parse())] Int(i32), #[regex(r"[0-9]+[.][0-9]+", |lex| lex.slice().parse())] Float(f32), #[token("else")] Else, #[token("false")] False, #[token("fun")] Fun, #[token("as")] As, #[token("if")] If, #[token("return")] Return, #[token("true")] True, #[token("struct")] Struct, #[token("loop")] Loop, #[token("let")] Let, #[token("mut")] Mut, #[token("spirv")] Spirv, #[token("unif")] Uniform, #[regex(r"//.*")] Comment, EOF, #[error] #[regex(r"[ \r\n\t\f]+", logos::skip)] Poisoned, } impl Display for Token { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Token::LeftParen => write!(f, "'('"), Token::RightParen => write!(f, "')'"), Token::LeftBrace => write!(f, "'{{'"), Token::RightBrace => write!(f, "'}}'"), Token::LeftBracket => write!(f, "'['"), Token::HashBracket => write!(f, "'#['"), Token::RightBracket => write!(f, "']'"), Token::Comma => write!(f, "','"), Token::Dot => write!(f, "'.'"), Token::Minus => write!(f, "'-'"), Token::Plus => write!(f, "'+'"), Token::Slash => write!(f, "'/'"), Token::Percent => write!(f, "'%'"), Token::Colon => write!(f, "':'"), Token::Star => write!(f, "'*'"), Token::DoubleStar => write!(f, "'**'"), Token::Bang => write!(f, "'!'"), Token::BangEqual => write!(f, "'!='"), Token::Equal => write!(f, "'='"), Token::DoubleEqual => write!(f, "'=='"), Token::Greater => write!(f, "'>'"), Token::GreaterEqual => write!(f, "'>='"), Token::Less => write!(f, "'<'"), Token::LessEqual => write!(f, "'<='"), Token::Arrow => write!(f, "'->'"), Token::Identifier(_) => write!(f, "Identifier"), Token::Int(_) => write!(f, "Int"), Token::Float(_) => write!(f, "Float"), Token::Else => write!(f, "'else'"), Token::False => write!(f, "'false'"), Token::Fun => write!(f, "'fun'"), Token::As => write!(f, "'as'"), Token::If => write!(f, "'if'"), Token::Return => write!(f, "'return'"), Token::True => write!(f, "'true'"), Token::Struct => write!(f, "'struct'"), Token::Loop => write!(f, "'loop'"), Token::Let => write!(f, "'let'"), Token::Mut => write!(f, "'mut'"), Token::Spirv => write!(f, "'spirv'"), Token::Uniform => write!(f, "'unif'"), Token::Comment => write!(f, "'//'"), Token::EOF => write!(f, "EOF"), Token::Poisoned => write!(f, "POISONED"), } } } #[cfg(test)] mod tests { use super::*; use insta::assert_debug_snapshot; #[test] fn identifiers() { assert_debug_snapshot!(Token::lexer("asd . _asd . _ . asd90 . 90asd").collect::<Vec<_>>(), @r###" [ Identifier( Spur { key: 1, }, ), Dot, Identifier( Spur { key: 2, }, ), Dot, Identifier( Spur { key: 3, }, ), Dot, Identifier( Spur { key: 4, }, ), Dot, Int( 90, ), Identifier( Spur { key: 1, }, ), ] "###); } #[test] fn floats() { assert_debug_snapshot!(Token::lexer("123 3. .4 23.45 11").collect::<Vec<_>>(), @r###" [ Int( 123, ), Int( 3, ), Dot, Dot, Int( 4, ), Float( 23.45, ), Int( 11, ), ] "###); } }
def send_to_health_monitor(event): env = get_environment(event) target_region = os.environ.get("TARGET_REGION") aws_sqs = boto3.client("sqs", region_name=target_region) payload_json = event.to_json() queue_url = get_health_target_queue_url(env) LOG.debug("Send to SQS: %s", queue_url) response = aws_sqs.send_message(QueueUrl=queue_url, MessageBody=payload_json) return Dict(response)
// +build ignore package main import ( "context" "errors" "flag" "fmt" "os" "sync" "github.com/hashicorp/go-hclog" goplugin "github.com/hashicorp/go-plugin" "github.com/spiffe/spire-plugin-sdk/pluginmain" "github.com/spiffe/spire-plugin-sdk/private/proto/test" "github.com/spiffe/spire/pkg/common/catalog/testplugin" "github.com/spiffe/spire/proto/private/test/legacyplugin" "github.com/spiffe/spire/proto/spire/common/plugin" spi "github.com/spiffe/spire/proto/spire/common/plugin" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) var ( modeFlag = flag.String("mode", "good", "plugin mode to use (one of [good, bad, legacy])") registerConfigFlag = flag.Bool("registerConfig", false, "register the configuration service") ) func main() { flag.Parse() switch *modeFlag { case "good": flag.Parse() builtIn := testplugin.BuiltIn(*registerConfigFlag) pluginmain.Serve( builtIn.Plugin, builtIn.Services..., ) case "bad": goplugin.Serve(&goplugin.ServeConfig{ HandshakeConfig: goplugin.HandshakeConfig{ ProtocolVersion: 99, MagicCookieKey: "BAD", MagicCookieValue: "BAD", }, Plugins: map[string]goplugin.Plugin{ "BAD": &badHCServerPlugin{}, }, GRPCServer: goplugin.DefaultGRPCServer, }) case "legacy": plugin := new(Plugin) logger := hclog.New(&hclog.LoggerOptions{ Level: hclog.Trace, Output: os.Stderr, JSONFormat: true, }) goplugin.Serve(&goplugin.ServeConfig{ HandshakeConfig: goplugin.HandshakeConfig{ ProtocolVersion: 1, MagicCookieKey: "SomePlugin", MagicCookieValue: "SomePlugin", }, Plugins: map[string]goplugin.Plugin{ "LEGACY": &hcServerPlugin{ logger: logger, plugin: plugin, }, }, Logger: logger, GRPCServer: goplugin.DefaultGRPCServer, }) default: fmt.Fprintln(os.Stderr, "bad value for mode: must be one of [good,bad,legacy]") os.Exit(1) } } type badHCServerPlugin struct { goplugin.NetRPCUnsupportedPlugin } func (p *badHCServerPlugin) GRPCServer(b *goplugin.GRPCBroker, s *grpc.Server) (err error) { return nil } func (p *badHCServerPlugin) GRPCClient(ctx context.Context, b *goplugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) { return nil, errors.New("unimplemented") } // HostServiceBroker is used by plugins that implement the NeedsHostBroker // service to obtain host service clients. type HostServiceBroker interface { GetHostService(HostServiceClient) (has bool, err error) } // HostServiceClient is used to initialize a host service client. type HostServiceClient interface { HostServiceType() string // InitHostServiceClient initializes the host service client. InitHostServiceClient(conn grpc.ClientConnInterface) } // NeedsLogger is implemented by plugin/service implementations that need a // logger that is connected to the SPIRE core logger. type NeedsLogger interface { SetLogger(hclog.Logger) } // NeedsHostServices is implemented by plugin/service implementations that need // to obtain clients to host services. type NeedsHostServices interface { BrokerHostServices(HostServiceBroker) error } type Plugin struct { legacyplugin.UnimplementedSomePluginServer log hclog.Logger hostService someHostServiceClient } var _ NeedsLogger = (*Plugin)(nil) var _ NeedsHostServices = (*Plugin)(nil) func (p *Plugin) SetLogger(log hclog.Logger) { p.log = log } func (p *Plugin) BrokerHostServices(broker HostServiceBroker) error { if has, err := broker.GetHostService(&p.hostService); err != nil { return err } else if !has { return errors.New("required host service was not available") } return nil } func (p *Plugin) PluginEcho(ctx context.Context, req *legacyplugin.EchoRequest) (*legacyplugin.EchoResponse, error) { out := wrap(req.In, "plugin") resp, err := p.hostService.HostServiceEcho(ctx, &test.EchoRequest{In: out}) if err != nil { return nil, err } return &legacyplugin.EchoResponse{Out: resp.Out}, nil } func (p *Plugin) Configure(ctx context.Context, req *plugin.ConfigureRequest) (*plugin.ConfigureResponse, error) { p.log.Info("CONFIGURED") if req.GlobalConfig.TrustDomain != "example.org" { return nil, status.Errorf(codes.InvalidArgument, "expected trust domain %q; got %q", "example.org", req.GlobalConfig.TrustDomain) } if req.Configuration != "GOOD" { return nil, status.Error(codes.InvalidArgument, "bad config") } return &plugin.ConfigureResponse{}, nil } type hcServerPlugin struct { goplugin.NetRPCUnsupportedPlugin logger hclog.Logger plugin *Plugin } var _ goplugin.GRPCPlugin = (*hcServerPlugin)(nil) func (p *hcServerPlugin) GRPCServer(b *goplugin.GRPCBroker, s *grpc.Server) (err error) { legacyplugin.RegisterSomePluginServer(s, p.plugin) spi.RegisterPluginInitServer(s, &initServer{ logger: p.logger, dialer: &grpcBrokerDialer{b: b}, impls: []interface{}{p.plugin}, }) return nil } func (p *hcServerPlugin) GRPCClient(ctx context.Context, b *goplugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) { return nil, errors.New("unimplemented") } type grpcBrokerDialer struct { b *goplugin.GRPCBroker } func (d grpcBrokerDialer) DialHost() (*grpc.ClientConn, error) { const legacyHostServicesID = 1 return d.b.Dial(legacyHostServicesID) } type initServer struct { spi.UnsafePluginInitServer logger hclog.Logger dialer *grpcBrokerDialer impls []interface{} } func (p *initServer) Init(ctx context.Context, req *spi.InitRequest) (resp *spi.InitResponse, err error) { // create a new broker and make sure it is torn down if there is an error. // otherwise, it needs to stay up open as it maintains the client // connection for the brokered services. broker := newHostServiceBroker(p.dialer, req.HostServices) defer func() { if err != nil { broker.Close() } }() initted := make(map[interface{}]bool) for _, impl := range p.impls { // skip initializing the same implementation twice. the plugin and // service interface might be implemented by the same underlying struct. if initted[impl] { continue } initted[impl] = true // wire up logging if x, ok := impl.(NeedsLogger); ok { x.SetLogger(p.logger) } // initialize host service dependencies if x, ok := impl.(NeedsHostServices); ok { if err := x.BrokerHostServices(broker); err != nil { return nil, err } } } return &spi.InitResponse{}, nil } type hostServiceBroker struct { dialer *grpcBrokerDialer hostServices map[string]bool c *grpc.ClientConn closeOnce sync.Once } func newHostServiceBroker(dialer *grpcBrokerDialer, hostServices []string) *hostServiceBroker { b := &hostServiceBroker{ dialer: dialer, hostServices: map[string]bool{}, } for _, service := range hostServices { b.hostServices[service] = true } return b } func (b *hostServiceBroker) GetHostService(hostService HostServiceClient) (bool, error) { if b.c == nil { var err error b.c, err = b.dialer.DialHost() if err != nil { return false, fmt.Errorf("unable to dial service broker on host: %v", err) } } if !b.hostServices[hostService.HostServiceType()] { return false, nil } hostService.InitHostServiceClient(b.c) return true, nil } func (b *hostServiceBroker) Close() { b.closeOnce.Do(func() { if b.c != nil { b.c.Close() } }) } type someHostServiceClient struct { test.SomeHostServiceClient } func (pc *someHostServiceClient) HostServiceType() string { return "SomeHostService" } func (pc *someHostServiceClient) InitHostServiceClient(conn grpc.ClientConnInterface) { pc.SomeHostServiceClient = test.NewSomeHostServiceClient(conn) } func wrap(s string, with string) string { return fmt.Sprintf("%s(%s)", with, s) }
<gh_stars>0 package lu.acel.lidderbuch.model; import android.graphics.Bitmap; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; /** * Created by mirkomack on 16.11.16. */ public class LBBacker implements Serializable { private URL logoDisplayUrl; private String logoId; public String getLogoId() { return logoId; } public void setLogoId(String logoId) { this.logoId = logoId; } public URL getLogoDisplayUrl() { return logoDisplayUrl; } public void setLogoDisplayUrl(URL logoDisplayUrl) { this.logoDisplayUrl = logoDisplayUrl; } public LBBacker(JSONObject jsonObject) { // retrieve required attributes try { logoDisplayUrl = new URL(jsonObject.getString("logo_display_url")); logoId = jsonObject.getString("logo_id"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }
It sounds like a direct-to-Netflix horror movie plot — a cheap, addictive drug available in a foreign land, that turns the user's skin a scaly green color. Soon it rots the flesh, causing the user's skin to emulate that of a crocodile, leaving bone and muscle tissue exposed to the world. But the Russian drug known as krokodil is real. Warning: Disburbing images of the effects of Krokodil below. This article may be shocking or upsetting for some people. Please proceed with caution. Advertisement Top image via fritscdejong on Flickr. YouTube videos emanating from Russia displaying the aftereffects of Krokodil use have been available for months. The clips often spotlight the gore factor, displaying the gangrene, exposed bones, and scale-like skin that lent the drug its name. What makes people use a drug that will destroy their body, to the point where their bones are exposed and require amputation? Why is usage (so far) contained to Russia? What is in Krokodil? Just as crack is the broke addict's cocaine, krokodil is a substitute for a much more expensive drug, heroin. The chemical behind krokodil, desomorphine, was available as a morphine substitute shortly after laboratory synthesis in 1932. Desomorphine is 8-10 times more potent than morphine. The medicinal use of desomorphine was concentrated to Europe, particularly Switzerland. The synthetic opiate has a structure nearly identical to heroin. Advertisement Codeine, a readily available narcotic, can be turned into desomorphine in a relatively easy series of chemical reactions, and then injected intravenously by the user. Whereas heroin may cost $150 US and up per use, krokodil can be obtained for $6-$8 US per injection. How is Krokodil made? The problem is not necessarily desomorphine addiction, it's the fact that krokodil users are unable to make a pure enough final product prior to use. When performed in a lab, the transformation of codeine into desomorphine is a rather easy, three step synthesis. When cooked in a kitchen lab, however, krokodil users often lack for materials, and thus use gasoline as a solvent along with red phosphorous, iodine, and hydrochloric acid as reactants to synthesize desomorphine from codeine tablets. Advertisement The final product is often an impure, orange-colored liquid, with this impurity causing skin irritation, a scale-like look, and eventual destruction of the skin. This is likely due to the presence of hydrochloric acid still in the final liquid solution prior to injection, with red phosphorous, obtained by solvating and removing the "striker" portion of matchboxes, playing a role in furthering sickening the user. Once the skin around the injection site is damaged, the area becomes a target for gangrene. This leads to skin decay around the injection site, and, in time, the skin sloughs off, often exposing the bone below. Addiction is a full time job The high associated with krokodil is akin to that of heroin, but last a much shorter period. While the affects of heroin use can last four to eight hours, krokodil users are lucky to get an hour and a half of bliss, with the symptoms of withdrawal setting in soon after. Krokodil takes roughly 30 minutes to an hour to prepare with over-the-counter ingredients in a kitchen. Advertisement The short time table causes addicts to be trapped in a full time, twenty-four hour a day cycle of cooking and injecting in order to avoid withdrawal. Once someone becomes addicted, it is common for the individual to die within two-three years of heavy use from exposure and associated health issues, with many dying within a year. Why is use prevalent in Russia? The major reason krokodil use is confined to Russia is due to the availability of codeine for purchase without a prescription — anyone can walk into any pharmacy and buy tablets containing the starting point of krokodil synthesis. Access could quickly be cut off by making codeine containing analgesics a prescription-only pharmaceutical in Russia. This has been met with backlash from citizens, as most believe that krokodil users will find another avenue for codeine, while preventing "proper" users from obtaining the analgesic tablets. Advertisement A lack of government infrastructure also plagues krokodil users. Russia lacks a significant state-sponsored rehabilitation system, nor have they made any significant moves to ban the over the counter sale of codeine tablets. Speaking on this subject, Viktor Ivanov, head of Russia's Drug Control Agency, said: A year ago we said that we need to introduce prescriptions [...] These tablets don't cost much but the profit margins are high. Some pharmacies make up to 25 per cent of their profits from the sale of these tablets. It's not in the interests of pharmaceutical companies or pharmacies themselves to stop this, so the government needs to use its power to regulate their sale. Advertisement Withdrawal symptoms can last up to month, making it a rather difficult habit to kick. It takes a phenomenal amount of will power to put up with the physical pain of withdrawal for a month than go to the kitchen and make another dose. Rehabilitation systems are present, with the vast majority religious-based due to the lack of government involvement. Apart from wanting to name this article In Soviet Russia, Drugs Eat You, there is not a lot to laugh about in regards to krokodil. It is a debilitating, body-destroying drug that's consumed predominantly by the poor. Reports of usage in Germany have also surfaced as of October 2011, where codeine drugs require a prescription. Codeine products have been considered "prescription only" narcotic for decades in U.S., the UK and Sweden. But pills containing codeine can still be purchased without a prescription in a Canada, Australia, Israel, France, and Japan. We may soon see the devastating effects of krokodil in these regions too. Images of Krokodil use courtesy of stopnarkotik.com.ua and youtube user kay8x. Sources linked within article.
Any good fantasy world deserves a map, but how does a world map go from your notebook to an espansive illustration that provides depth and information? Read on as Isaac Stewart shares his process for making the map for The Emperor’s Blades, the first book in Brian Staveley’s new fantasy series Chronicles of the Unhewn Throne. The book is out on January 14th but you can read the first seven chapters for FREE right here. (Did we mention it has ninjas that ride enormous hawks? It has ninjas that ride enormous hawks!) I was ten years old, holding a golden Nintendo cartridge in my hands. The first time I’d lost myself in fantasy maps was when I discovered Dad’s old Lord of the Rings paperbacks. But everything was about to change for me. I didn’t play The Legend of Zelda to win. I played it to explore. With colored pencils and an old piece of graph paper, I mapped the 8-bit world of Hyrule. When I ran out of paper, I taped on new segments. I kept it in my back pocket and took it to school with me, unfolding it at every chance to plan my next adventure. I dreamed of filling out those blank spaces and wondered what I would find there. Oh boy, I had no idea where that little folded up map would lead me. I guess I could’ve found myself mapping Antarctica or outer space or the bottom of the ocean. But I dislike the snow, am extremely claustrophobic, and am terrified of being out to sea. So I explore fantasy novels. Exploration For Brian Staveley’s excellent fantasy debut, The Emperor’s Blades, Heather Saunders at Tor wanted a two-page map that would match the feel of the book. When drawing a map, often all I have is the text of the book itself. This time I had both the book and the author’s sketch of his world. Brian’s attention to detail was amazing! I immediately wanted to dive into reading the book. I wasn’t disappointed. The same care with which he built the map is also found in the novel. Before I jumped in headfirst, I needed to make sure of my destination. I wanted the final map to: Match the design of the book. Match the feel of the book. Feel like an artifact from the world of The Emperor’s Blades. I asked Heather for samples of the book’s interior design. I studied the book’s cover. I tried to distill the feeling I had while reading the novel and decided that a somewhat far Eastern looking map would work well. As much as possible, I try to design my maps as if they were artifacts of the world they depict. This is probably influenced by my time creating ephemera for Brandon Sanderson’s worlds. There are plenty of well-designed fantasy maps that don’t follow this paradigm, but it’s my preference. Because of that, I always try to find real-world examples on which to base my maps. After some serious web surfing (and an unfortunate delay in the Straits of Social Media), I discovered a map on a website I hadn’t come across before (David Rumsey Map Collection), but which has quickly become my go-to place for map reference. I later found the same map reference on Wikimedia. This was exactly what I was looking for and made it my style target. The Problem of Real World Maps I almost always run into the same problem each time I try to adapt a real-world cartographic style to a map meant for a novel. Real world maps are huge and detailed. A map meant to fit in a hardcover book (and subsequently a paperback) can’t be as detailed as a real-world map and still be legible. Even though I treat the map as a product of its fantasy world, it has to be understandable to modern audiences. Usually this means I can’t copy the exact style of my reference, but I can use it for inspiration. I decided to borrow the style of the mountains, rivers, and ocean. Borders I start with the project specs to create a Photoshop file with all the guides I need to keep the image and text from getting too close to the book’s trim line. With a two-page spread like this map, I also add in safety guidelines around the gutter between the two pages. Using the interior chapter designs as inspiration, I created a border, then went about fitting Brian’s sketched map into the space available, resizing and moving it until it fit right. I also cut the reference map in half and pulled it to either side of the gutter line. This makes the final map slightly wider than the sketch, but it also gives me space in the middle with no labels or important features. This keeps readers from having to pull the book apart to find words that are hidden in the binding. Map Creation Painters have their preferred way of working, whether dark to light, light to dark, background to foreground, etc. With maps, it’s a bit more like Genesis (the book, not the band). I decided, for the sake of contrast and legibility, what parts of the map will be light and what will be dark. Then I separate the land from the water. I add the coastline and different biomes: mountains, deserts, forests, etc. Final border and texture for that antique feel. (Okay, so this step has nothing to do with Genesis.) Then I draw national borders and label everything. I would’ve loved to have found a font with an Eastern flair to match the reference image, but I’ve found that most faux Eastern fonts often aren’t very legible, especially at small sizes. My first rule of fantasy cartography is clarity. For that reason, I opted to go with a nice Roman font that matched the book’s interior design. Finally, I make a few layer adjustments to make sure the map would print out clearly in the final book. There you have it. A map that would’ve made my ten-year old self proud, except I doubt I could’ve used it to find another piece of the Triforce. Find more from Isaac Stewart at his website and on Twitter.
Chris Hemsworth, Tom Hiddleston, Mark Ruffalo, Cate Blanchett, Jeff Goldblum and Tessa Thompson treated an unexpected audience to a 4D experience on the 'Late Late Show With James Corden.' James Corden and the cast of Marvel's Thor: Ragnarok crashed a screening of the new film at the Grove in Los Angeles this week to perform a 4D live performance of the superhero movie. Shortly into the film's opening scene, Corden cut in onscreen to inform the confused (and slightly irritated by the looks of them) audience that they had purchased a ticket "to the future." He then introduced himself as he walked out in person before the crowded theater. Beside him, stagehands dressed the front of the theater with cosmic backdrops as Corden read stage directions. In came star Chris Hemsworth, sporting a dollar store Thor costume and long, blonde wig and hammer. Next, Tom Hiddleston, similarly decked out in knock-off apparel and a bad wig, walked on stage to raucous applause. That wasn't all, however, as Cate Blanchett, who stars as Hela, Goddess of Death in the film, showed up with an array of pipe cleaners on her back, fashioned to imitate the horns of her character. "I think those poor people just want to watch the movie," Blanchett said in a taped interview backstage. The opening scene done, Jeff Goldblum, who plays the Grandmaster in the film, made an entrance on a scooter to introduce his "grand champion," Mark Ruffalo, who, of course, was dressed in a cheap Hulk costume with green, rubber fists. Hemsworth and Ruffalo battled their way through the crowded theater that preluded a "brief, 45-minute intermission," as announced by Corden. When the show returned, Hemsworth, Ruffalo, Hiddleston and Tessa Thompson squared off against Blanchett and her "ferocious guard dog" — a stuffed huskie dog. "And they all lived happily ever after...until the next Thor movie," Corden narrated. Backstage, the actors celebrated. "Thor: Ragnarok 4D gets 10 Goldblums out of a possible 10 Goldblums. That's my highest rating," Goldblum said. Watch the video below.
/// Step when the control contains a value. fn step_value(&mut self, value: Rc<Value<'a>>, kont: Kont<'a>) -> Ctrl<'a> { use Kont::*; match kont { Dump(env) => { self.env = env; Ctrl::Value(value) } Pop(count) => { self.env.pop_many(count); Ctrl::Value(value) } Arg(arg) => { self.kont.push(App(value)); Ctrl::Expr(arg) } ArgValue(arg) => { self.kont.push(App(value)); Ctrl::Value(arg) } App(fun) => match Rc::try_unwrap(fun) { Ok(fun) => match fun { Value::PAP(pap) => self.pap_apply_arg(pap, value), Value::Fix(fun) => self.fix_apply_arg(fun, value), _ => Ctrl::Error(format!("expected PAP, found {:?}", fun)), }, Err(fun) => match &*fun { Value::PAP(pap) => self.pap_apply_arg(pap.clone(), value), Value::Fix(fun) => self.fix_apply_arg(Rc::clone(fun), value), _ => Ctrl::Error(format!("expected PAP, found {:?}", fun)), }, }, Let(_name, body) => { self.kont.push(Kont::Pop(1)); self.env.push(value); Ctrl::Expr(body) } If(then, elze) => match value.as_bool() { Ok(true) => Ctrl::Expr(then), Ok(false) => Ctrl::Expr(elze), Err(e) => Ctrl::Error(e), }, } }
import { PartialQuery } from './../query/partial'; import { StringToken } from './../tokens'; export class Now extends PartialQuery { constructor() { super(new StringToken(`NOW()`)); } } export const now = () => new Now();
Self-Determination along the Austrian Frontier, 1918-1920: Case Studies of German Bohemia, Vorarlberg, and Carinthia The First World War led to the collapse of a number of prominent European empires, allowing for the spread of new ideas into Europe. US President Woodrow Wilson’s rhetoric of national self-determination attracted particular symbolic importance because it legitimised popular sovereignty through the use of plebiscites. German-Austrians, like other national groups within the Austro-Hungarian Empire, used self-determination to justify establishing independent successor states after the war. The German-Austrian Republic, founded in 1918, claimed all German-speaking regions of the former Austro-Hungarian Empire on the basis of self-determination. This thesis examines claims to self-determination in three different cases: German Bohemia, Vorarlberg, and Carinthia. Representatives from each region took their case to the Paris Peace Conference, appealing to the Allied delegations to grant international recognition. These representatives faced much opposition, both from local non-German populations and occasionally even from the German-Austrian government itself.  German-Austrian politicians in the Czech lands opposed the incorporation of German-majority lands into Czechoslovakia, and instead sought to establish an autonomous German Bohemian province as part of German-Austria. In Paris, Allied delegations supported the historic frontier of the Czech lands, and therefore opposed local German self-determination outright, refusing demands for a plebiscite in German Bohemia. Vorarlberg representatives sought Vorarlberg’s secession from German-Austria, hoping instead for union with Switzerland. Vorarlbergers held a plebiscite to join Switzerland on their own initiative, initially with some degree of international support, but ultimately the international community, fearful of the disintegration of Austria, refused to allow Vorarlbergers to realise their wishes. Carinthian German representatives opposed Yugoslav claims to sovereignty over the region, seeking to remain part of German-Austria. Disagreements between and within the Allied delegations over Carinthia resulted in a decision to hold a plebiscite, which showed a majority in favour of remaining part of Austria. The thesis suggests that the implementation of self-determination in the Carinthian case resulted in a more successful resolution of border disputes. Unlike in the other two cases, the new Carinthian border mostly reflected the desires of the local population. Despite idealistic rhetoric, the final Austrian frontier suggested that Allied delegations at the Paris Peace Conference routinely favoured strategic justifications over self-determination.
/** * Get method for field imageGranularity [vkstruct]<br> * Prototype: VkExtent3D imageGranularity */ public VkExtent3D imageGranularity(){ long pointer = getImageGranularity0(super.ptr); if(pointer == 0){ this.imageGranularity = null; return null; } if(this.imageGranularity == null){ this.imageGranularity = new VkExtent3D(pointer); }else{ this.imageGranularity.setPointer(pointer); } return this.imageGranularity; }
/** * This class represents a node in parse tree. */ static class ClosureToken extends Token implements java.io.Serializable { private static final long serialVersionUID = 1L; int min; int max; Token child; ClosureToken(int type, Token tok) { super(type); this.child = tok; this.setMin(-1); this.setMax(-1); } @Override int size() { return 1; } @Override Token getChild(int index) { return this.child; } @Override final void setMin(int min) { this.min = min; } @Override final void setMax(int max) { this.max = max; } @Override final int getMin() { return this.min; } @Override final int getMax() { return this.max; } @Override public String toString(int options) { String ret; if (this.type == CLOSURE) { if (this.getMin() < 0 && this.getMax() < 0) { ret = this.child.toString(options)+"*"; } else if (this.getMin() == this.getMax()) { ret = this.child.toString(options)+"{"+this.getMin()+"}"; } else if (this.getMin() >= 0 && this.getMax() >= 0) { ret = this.child.toString(options)+"{"+this.getMin()+","+this.getMax()+"}"; } else if (this.getMin() >= 0 && this.getMax() < 0) { ret = this.child.toString(options)+"{"+this.getMin()+",}"; } else throw new RuntimeException("Token#toString(): CLOSURE " +this.getMin()+", "+this.getMax()); } else { if (this.getMin() < 0 && this.getMax() < 0) { ret = this.child.toString(options)+"*?"; } else if (this.getMin() == this.getMax()) { ret = this.child.toString(options)+"{"+this.getMin()+"}?"; } else if (this.getMin() >= 0 && this.getMax() >= 0) { ret = this.child.toString(options)+"{"+this.getMin()+","+this.getMax()+"}?"; } else if (this.getMin() >= 0 && this.getMax() < 0) { ret = this.child.toString(options)+"{"+this.getMin()+",}?"; } else throw new RuntimeException("Token#toString(): NONGREEDYCLOSURE " + this.getMin() + ", " + this.getMax()); } return ret; } }
async def ensure_cached_claimant(channel: discord.TextChannel) -> None: if await _caches.claimants.get(channel.id): return async for message in channel.history(limit=1000): if message.author.id != bot.instance.user.id: continue if message.embeds: if _message._match_bot_embed(message, _message.DORMANT_MSG): log.info("Hit the dormant message embed before finding a claimant in %s (%d).", channel, channel.id) break if match := CLAIMED_BY_RE.match(message.embeds[0].description): await _caches.claimants.set(channel.id, int(match.group("user_id"))) return await bot.instance.get_channel(constants.Channels.helpers).send( f"I couldn't find a claimant for {channel.mention} in that last 1000 messages. " "Please use your helper powers to close the channel if/when appropriate." ) await _caches.claimants.set(channel.id, bot.instance.user.id)
<filename>types/carbon__icons-react/es/pills--subtract/32.d.ts<gh_stars>1000+ export { PillsSubtract32 as default } from "../../";
#include "CommandExamine.h" #include <boost/algorithm/string.hpp> using internationalization::Internationalization; void CommandExamine::executeInHeartbeat(const std::string& username, const std::vector<std::string>& fullCommand) { auto location = characterManager.getCharacterLocation(username); if(location.area == "") { //should not reach here, report error return; } if(fullCommand[1] == stringManager.getString(Internationalization::STRING_CODE::EXITS)){ onlineUserManager.addMessageToUser(username, (worldManager.listExits(location) + "\n")); }else if(fullCommand[1] == stringManager.getString(Internationalization::STRING_CODE::NPCS)){ auto currentRoom = worldManager.findRoomByLocation(location); auto NPCs = currentRoom.getNPCs(); std::string returnMessage = stringManager.getString(Internationalization::STRING_CODE::NPC_IN_ROOM); for(auto npc : NPCs) { returnMessage += "- " + npc; returnMessage += "\n"; } onlineUserManager.addMessageToUser(username, returnMessage); }else{ onlineUserManager.addMessageToUser(username, (worldManager.look(location, fullCommand[1]) + "\n")); } } std::vector<std::string> CommandExamine::reassembleCommand(std::string& fullCommand, bool& commandIsValid) { std::vector<std::string> processedCommand; //Format: examine <object/username> boost::trim_if(fullCommand, boost::is_any_of(" \t")); //split by " " and compress all long spaces boost::split(processedCommand, fullCommand, boost::is_any_of(" \t"), boost::token_compress_on); commandIsValid = (processedCommand.size() == 2); return processedCommand; }
package pipelines import "fmt" type HttpBinPipeline struct{ In chan string } func (h *HttpBinPipeline) Process(){ for item:= range h.In{ fmt.Println("Process item") fmt.Println(item) } }
/** * Read messages from the panel * The first message found in the LinkedList of messages is * returned which matches the given command code. * * @param m1Command * @return message * @throws IOException */ public Message readMessages(String m1Command) throws IOException { Message msg = null; Iterator<Message> itr = messages.iterator(); while (itr.hasNext()) { msg = itr.next(); if (msg.getType().equals(m1Command) || m1Command == null) { itr.remove(); return msg; } } String s; MessageFactory mf = MessageFactory.getInstance(); while ((s = in.readLine()) != null) { if (MessageFactory.MSG_CLASSES.containsKey(s.substring(2, 4))) { msg = mf.getMessageClass(s); } else { msg = new Message(null, s); } if (msg.getType().equals(m1Command) || m1Command == null) { return msg; } else { this.messages.add(msg); } } return null; }
#!/usr/bin/env python3 import warnings import glob from pathlib import Path ## for os-agnostic paths import pandas as pd from mendeleev import get_table from ase import data as ase_data from pymatgen import Element HERE = Path(__file__).parent def gather_ptable_dataframe(): df_list = [] ## get properties in csv (retrieved from magpie project, imat project, and wikipedia) all_files = glob.glob(str(HERE/"*"/"*.csv")) for filename in all_files: prop = str(Path(filename).stem) source = str(Path(filename).parent.stem) name = source + "_" + prop tmp_df = pd.read_csv(filename, names=[name]) valid_0_list = [ "valence", "valence_s", "valence_p", "valence_d", "valence_f", "unfilled", "unfilled_f", "unfilled_d", "electron_affinity", "electronegativity", "magnetic_moment", ] if not prop in valid_0_list: tmp_df = tmp_df[name].apply(lambda x: None if x==0 else x) df_list.append(tmp_df) ## get ase magnetic moments magmom_list = ase_data.ground_state_magnetic_moments tmp_df = pd.DataFrame(magmom_list, columns=["ase_magnetic_moment"]) df_list.append(tmp_df) # concat in a single dataframe and drop the 0th entry (up to here, # properties were savec with element 0 as dummy so the index corresponed # to the atomic number) external_props = pd.concat(df_list, axis=1).drop(0) # concat with mendeleev's ptable (need reindexing with atomic number) ptable = get_table("elements") ptable = ptable.set_index('atomic_number', drop=False) ptable = pd.concat([ptable, external_props], axis=1) # add pymatgen properties ptable["pymg_atomic_radius"] = [Element(x).atomic_radius for x in ptable['symbol']] with warnings.catch_warnings(): warnings.simplefilter("ignore") ptable["pymg_electronegativity"] = [Element(x).X for x in ptable['symbol']] # add the first ionization energy from mendeleev tmp_df = get_table("ionizationenergies") ptable["ionization_energy"] = tmp_df.loc[tmp_df["degree"] == 1].set_index('atomic_number')['energy'] # drop useless columns ptable = ptable.drop([ 'annotation', 'description', 'discoverers', 'discovery_location', 'geochemical_class', 'goldschmidt_class', 'uses', 'sources', 'name_origin', ],1) # reindex by symbol ptable = ptable.set_index('symbol') return ptable def save_ptable(): ptable = gather_ptable_dataframe() ptable.to_csv("ptable.csv") ptable.to_pickle("ptable.pkl") if __name__ == "__main__": save_ptable()
async def image(self, ctx): async with ctx.bot.session.get(url) as resp: if not resp.status == 200: raise exceptions.WebAPIInvalidResponse( api=service, status=resp.status ) data = await resp.json(content_type=None) img = TEXT.get(service, "") + data[key] embed = discord.Embed() embed.set_image(url=img) embed.set_footer( text=ctx._("provided_by {service}").format( service=urlparse(url).netloc ) ) await ctx.send(embed=embed)
/** * This class formats a DCP message for ingest into Kisters' WISKI database * by dropping files into a know directory in the Kisters ZRXP format. * * @author Michael Maloney, Cove Software, LLC */ public class KistersFormatter extends OutputFormatter { private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); /** Can be set by "includeTZ" property */ private boolean includeTZ = true; /** Can be set by tzName property. Defaults to abbreviation from Routing Spec TZ */ private String tzName = null; /** Can be set by "includeCNAME" property */ private boolean includeCNAME = false; /** Can be set by "includeCUNIT" property. */ private boolean includeCUNIT = false; /** Can be set by "includeRINVAL" property. */ private boolean includeRINVAL = true; /** Can be set by "RINVAL" property. */ private String RINVAL = "-777"; /** Can be set by "SiteNameType" property */ private String siteNameType = Constants.snt_NWSHB5; /** Can be set by "SiteNameTypeAlt" property */ private String siteNameTypeAlt = Constants.snt_local; /** Can be set by "DataTypeStandard" property */ private String dataTypeStandard = Constants.datatype_SHEF; /** Can be set by "DataTypeStandardAlt" property */ private String dataTypeStandardAlt = null; /** Can be set by "SitePrefix" property */ private String sitePrefix = ""; /** Can be set by "includeLayout" property */ private boolean includeLayout = false; private int bufferTimeSec = 0; private DataConsumer theConsumer = null; public static final String headerDelim = "|*|"; class SampleValue { long t; String v; SampleValue(long t, String v) { this.t = t; this.v = v; } }; class SensorData { String header; DecodedMessage msg; ArrayList<SampleValue> samples = new ArrayList<SampleValue>(); SensorData(String header, DecodedMessage msg) { this.header = header; this.msg = msg; } void addSample(long t, String v) { for(SampleValue sv : samples) if (sv.t == t) { // Don't overwrite good data with RINVAL data. if (!v.contains(RINVAL)) sv.v = v; return; } samples.add(new SampleValue(t,v)); } void sort() { Collections.sort(samples, new Comparator<SampleValue>() { @Override public int compare(SampleValue o1, SampleValue o2) { return o1.t - o2.t < 0 ? -1 : o1.t - o2.t > 0 ? 1 : 0; } }); } } long bufferingStarted = -1L; ArrayList<SensorData> sensorDataArray = new ArrayList<SensorData>(); /** * Constructor for Kisters ZRXP Formatter */ public KistersFormatter() { super(); } @Override public boolean requiresDecodedMessage() { return true; } @Override public boolean acceptRealDcpMessagesOnly() { return true; } @Override public boolean attemptDecode() { return true; } @Override protected void initFormatter(String type, TimeZone tz, PresentationGroup presGrp, Properties rsProps) throws OutputFormatterException { sdf.setTimeZone(tz); tzName = tz.getID(); String s = PropertiesUtil.getIgnoreCase(rsProps, "includeTZ"); if (s != null) includeTZ = TextUtil.str2boolean(s); s = PropertiesUtil.getIgnoreCase(rsProps, "includeCNAME"); if (s != null) includeCNAME = TextUtil.str2boolean(s); s = PropertiesUtil.getIgnoreCase(rsProps, "includeCUNIT"); if (s != null) includeCUNIT = TextUtil.str2boolean(s); s = PropertiesUtil.getIgnoreCase(rsProps, "includeRINVAL"); if (s != null) includeRINVAL = TextUtil.str2boolean(s); s = PropertiesUtil.getIgnoreCase(rsProps, "RINVAL"); if (s != null) RINVAL = s; s = PropertiesUtil.getIgnoreCase(rsProps, "SiteNameType"); if (s != null) siteNameType = s; s = PropertiesUtil.getIgnoreCase(rsProps, "SiteNameTypeAlt"); if (s != null) siteNameTypeAlt = s; s = PropertiesUtil.getIgnoreCase(rsProps, "DataTypeStandard"); if (s != null) dataTypeStandard = s; s = PropertiesUtil.getIgnoreCase(rsProps, "DataTypeStandardAlt"); if (s != null) dataTypeStandardAlt = s; s = PropertiesUtil.getIgnoreCase(rsProps, "SitePrefix"); if (s != null) sitePrefix = s; s = PropertiesUtil.getIgnoreCase(rsProps, "tzName"); if (s != null) tzName = s; s = PropertiesUtil.getIgnoreCase(rsProps, "includeLayout"); if (s != null) includeLayout = TextUtil.str2boolean(s); s = PropertiesUtil.getIgnoreCase(rsProps, "bufferTimeSec"); if (s != null) { try { bufferTimeSec = Integer.parseInt(s.trim()); } catch(Exception ex) { logger.warning("Invalid bufferTimeSec property '" + s + "' ignored. Buffering disabled."); bufferTimeSec = 0; } } } @Override public void shutdown() { if (bufferTimeSec <= 0) return; // If any data is accumulated in the buffer, flush it now. try { this.flushBuffer(); } catch (DataConsumerException ex) { logger.warning("Error shutting down formatter: " + ex); } } @Override public void formatMessage(DecodedMessage msg, DataConsumer consumer) throws DataConsumerException, OutputFormatterException { theConsumer = consumer; //MJM 20150227 If a message is nothing but missing, don't output anything. boolean hasData = false; // logger.debug3("KistersFormatter msg from " + msg.getPlatform().makeFileName() + " with time " + // sdf.format(msg.getMessageTime())); ts_loop: for(Iterator<TimeSeries> tsit = msg.getAllTimeSeries(); tsit.hasNext(); ) { TimeSeries ts = tsit.next(); if (ts == null || ts.size() == 0) continue; for(int idx=0; idx<ts.size(); idx++) { TimedVariable tv = ts.sampleAt(idx); if ((tv.getFlags() & (IFlags.IS_ERROR | IFlags.IS_MISSING)) == 0) { // logger.debug1("Found first data: " + ts.getSensorName() + " " // + sdf.format(tv.getTime()) + " " + tv.getStringValue()); hasData = true; break ts_loop; } } } if (!hasData) { logger.debug1("Skipping message with no non-missing data"); return; } // Get the site associated with the Platform that generated the message. Site platformSite = null; try { platformSite = msg.getRawMessage().getPlatform().getSite(); if (platformSite == null) logger.warning("No site associated with platform."); } catch(Exception ex) { throw new OutputFormatterException( "Cannot determine platform site: " + ex.toString()); } if (bufferTimeSec <= 0) consumer.startMessage(msg); // For each time series in the message ... for(Iterator<TimeSeries> tsit = msg.getAllTimeSeries(); tsit.hasNext(); ) { TimeSeries ts = tsit.next(); if (ts == null || ts.size() == 0) continue; // Determine the site name Site site = platformSite; Sensor sensor = ts.getSensor(); Site sensorSite = sensor.getSensorSite(); if (sensorSite != null) site = sensorSite; if (site == null) { logger.warning("No platform site and no site associated with " + "sensor " + sensor.getName() + " -- skipped."); continue; } SiteName siteName = site.getName(siteNameType); if (siteName == null) if ((siteName = site.getName(siteNameTypeAlt)) == null) siteName = site.getPreferredName(); DataType dt = sensor.getDataType(dataTypeStandard); if (dt == null) if (dataTypeStandardAlt == null || (dt = sensor.getDataType(dataTypeStandardAlt)) == null) dt = sensor.getDataType(); StringBuilder headerLineBuilder = new StringBuilder(); headerLineBuilder.append("#REXCHANGE"); headerLineBuilder.append(sitePrefix); headerLineBuilder.append(siteName.getNameValue()); headerLineBuilder.append("." + dt.getCode()); headerLineBuilder.append(headerDelim); if (includeTZ) { headerLineBuilder.append("TZ" + tzName); headerLineBuilder.append(headerDelim); } if (includeRINVAL) { headerLineBuilder.append("RINVAL" + RINVAL); headerLineBuilder.append(headerDelim); } if (includeCNAME) { headerLineBuilder.append("CNAME" + sensor.getName()); headerLineBuilder.append(headerDelim); } if (includeCUNIT) { String eustr = "RAW"; EngineeringUnit eu = ts.getEU(); if (eu != null) eustr = eu.getAbbr(); headerLineBuilder.append("CUNIT" + eustr); headerLineBuilder.append(headerDelim); } String headerLine = headerLineBuilder.toString(); if (bufferTimeSec <= 0) { // output data directly -- no buffering. consumer.println(headerLine); if (includeLayout) consumer.println("#LAYOUT(timestamp,value)"); } ts.sort(); for(int idx=0; idx<ts.size(); idx++) { TimedVariable tv = ts.sampleAt(idx); String samp = ts.formattedSampleAt(idx); boolean inval = samp.equals("error") || samp.equals("missing") || ((tv.getFlags() & (IFlags.IS_ERROR | IFlags.IS_MISSING)) != 0); if (inval) { if (!includeRINVAL) continue; else samp = RINVAL; } Date sampTime = ts.timeAt(idx); String dataLine = sdf.format(sampTime) + " " + samp; if (bufferTimeSec <= 0) consumer.println(dataLine); // No buffering else { addToBuffer(headerLine, dataLine, sampTime.getTime(), msg); } } } if (bufferTimeSec <= 0) consumer.endMessage(); else if (bufferingStarted > 0L && (System.currentTimeMillis() - bufferingStarted)/1000L > bufferTimeSec) flushBuffer(); } protected PropertySpec kfPropSpecs[] = { new PropertySpec("includeTZ", PropertySpec.BOOLEAN, "Default=true. Set to false to exclude TZ specifier from the header."), new PropertySpec("tzName", PropertySpec.STRING, "Default=null. Set to override the TZ name in the routing spec." + " Caution: this will not change the time values, just the name in the header."), new PropertySpec("includeCNAME", PropertySpec.BOOLEAN, "Default=false. Set to true to include CNAME in the header with the DECODES sensor name."), new PropertySpec("includeCUNIT", PropertySpec.BOOLEAN, "Default=false. Set to true to include CUNIT in the header with the " + "engineering units."), new PropertySpec("includeRINVAL", PropertySpec.BOOLEAN, "Default=true. Set to false to exclude RINVAL from the header. " + "RINVAL specifies the special value to be used for missing or erroneous values."), new PropertySpec("RINVAL", PropertySpec.STRING, "Default=-777. Specifies a special value to be used for missing or erroneous " + "values in the output data."), new PropertySpec("SiteNameType", PropertySpec.DECODES_ENUM + Constants.enum_SiteName, "Specifies which DECODES site name to use in the header."), new PropertySpec("SiteNameTypeAlt", PropertySpec.DECODES_ENUM + Constants.enum_SiteName, "Specifies the alternate DECODES site name to use in the header " + "(if the primary is undefined)."), new PropertySpec("DataTypeStandard", PropertySpec.DECODES_ENUM + Constants.enum_DataTypeStd, "Specifies which DECODES data type to use in the header."), new PropertySpec("DataTypeStandardAlt", PropertySpec.DECODES_ENUM + Constants.enum_DataTypeStd, "Specifies the alternate DECODES data type to use in the header if the primary" + " is undefined."), new PropertySpec("SitePrefix", PropertySpec.STRING, "A constant string to be placed before the site name in REXCHANGE values."), new PropertySpec("includeLayout", PropertySpec.BOOLEAN, "Default=true. Set to true to include a separate header line with layout."), new PropertySpec("bufferTimeSec", PropertySpec.INT, "(# seconds, default=0) Set this to positive number to have data lines buffered and combined." + " This may result in fewer ZRXP headers with more data lines.") }; @Override public PropertySpec[] getSupportedProps() { return kfPropSpecs; } @Override public boolean additionalPropsAllowed() { return false; } private void flushBuffer() throws DataConsumerException { if (bufferingStarted <= 0) return; // Sort the SensrData array by header. This will put all data for same platform together. Collections.sort(sensorDataArray, new Comparator<SensorData>() { @Override public int compare(SensorData o1, SensorData o2) { return o1.header.compareTo(o2.header); } }); String platformName = ""; for(SensorData sd : sensorDataArray) { // Within each SensorData struct, sort the samples ascending by time Collections.sort(sd.samples, new Comparator<SampleValue>() { @Override public int compare(SampleValue o1, SampleValue o2) { long deltat = o1.t - o2.t; return deltat < 0 ? -1 : deltat > 0 ? 1 : 0; } }); String pn = sd.msg.getPlatform().makeFileName(); if (!platformName.equals(pn)) { // Platform Name is different. Start a new message. if (platformName.length() > 0) theConsumer.endMessage(); // End the previous message if one was started. theConsumer.startMessage(sd.msg); platformName = pn; } // output the header line theConsumer.println(sd.header); if (includeLayout) theConsumer.println("#LAYOUT(timestamp,value)"); // output each data line for(SampleValue sv : sd.samples) theConsumer.println(sv.v); } // End the last message we were working on. if (platformName.length() > 0) theConsumer.endMessage(); sensorDataArray.clear(); bufferingStarted = -1; } private void addToBuffer(String header, String dataLine, long t, DecodedMessage dm) { if (bufferingStarted < 0) bufferingStarted = System.currentTimeMillis(); SensorData sensorData = null; for(SensorData sd : sensorDataArray) if (header.equals(sd.header)) { sensorData = sd; break; } if (sensorData == null) sensorDataArray.add(sensorData = new SensorData(header, dm)); sensorData.addSample(t, dataLine); } }
def inverse_udwt_n_combine_splits(cls, coeffs, wavelet, pad_lengths, split_dim, raw_data_shape): num_splits = len(coeffs) pad_len_row = pad_lengths[0] pad_len_col = pad_lengths[1] pad_len_row2 = pad_lengths[2] pad_len_col2 = pad_lengths[3] intensities = np.empty(raw_data_shape) for inx in range(num_splits): filtered_coeff = pywt.iswt2(coeffs[inx], wavelet) if raw_data_shape[0] > raw_data_shape[1]: if inx == num_splits-1: unpadded_filtered_coeff_split = filtered_coeff[pad_len_row2:, pad_len_col2:] intensities[(num_splits-1)*split_dim:, :] = unpadded_filtered_coeff_split else: unpadded_filtered_coeff_split = filtered_coeff[pad_len_row:, pad_len_col:] intensities[inx*split_dim:(inx+1)*split_dim, :] = unpadded_filtered_coeff_split else: if inx == num_splits-1: unpadded_filtered_coeff_split = filtered_coeff[pad_len_row2:, pad_len_col2:] intensities[:, (num_splits-1)*split_dim:] = unpadded_filtered_coeff_split else: unpadded_filtered_coeff_split = filtered_coeff[pad_len_row:, pad_len_col:] intensities[:, inx*split_dim:(inx+1)*split_dim] = unpadded_filtered_coeff_split return intensities
Despite doubts and denials, Russia is about to embark on an ambitious expansion of its Syrian presence, likely to change the game in the war-torn country. Russia’s small and dated naval repair facility in Tartous will be enlarged, while Jableh near Latakia (Laodicea of old) will become the Russian Air Force base and a full-blown Russian Navy base in the Eastern Mediterranean, beyond the narrow Bosphorus straits. The jihadi multitudes besetting Damascus are likely to be beaten into obedience and compliance, and the government of President Assad relieved from danger and siege. The war with Da’esh (ISIS) is to provide the cover for this operation. This is the first report of this fateful development, based on confidential and usually reliable Russian sources in Moscow. The knowledgeable and Damascus-based French investigative journalist and dissident Thierry Meyssan noted the arrival of many Russian advisers. Russians began to share satellite imagery in real time with their Syrian allies, he added. An Israeli news site said “Russia has begun its military intervention in Syria” and predicted that “in the coming weeks thousands of Russian military personnel are set to touch down in Syria”. Russians promptly denied that. President Bashar al Assad hinted at that a few days ago expressing his full confidence of Russian support for Damascus. First six MiG-31 fighter jets landed in Damascus a couple of weeks ago, as reported in the official RG newspaper. Michael Weiss in the far-right Daily Beast presented a flesh-creeping picture of a Russian penetration of Syria. Al-Quds Al-Arabi newspaper referred to Jableh as the second-base location. Now we can confirm that to the best of our knowledge, despite denials (remember Crimea?) Russia has cast its lot and made a very important decision to enter the Syrian war. This decision may yet save Syria from total collapse and incidentally save Europe, too, from being swept by refugee waves. The Russian air force will ostensibly fight Da’esh, but probably (as Michael Weiss guessed) they will also bomb not just Da’esh but the US-allied opposition of al-Nusra (formerly al-Qaeda) and other non-Da’esh Islamic extremists for the simple reason that they can’t be distinguished from Da’esh. The Russian Foreign Minister Mr Sergey Lavrov proposed to organise a new coalition against Da’esh including Assad’s army, Saudis and some opposition forces. The US envoy visiting Russia said that there is no chance that the Saudis or other Gulf states would agree to join forces with Bashar Assad. Russia still plans to build this coalition, but in the view of the American rejection, apparently President Putin decided to act. Russia is worried by successes of Da’esh, as this force fights and displaces Christians in Syria, while Russia considers itself a traditional protector of these people. Russia is also worried that Da’esh may begin operations in Muslim areas of Russia, in the Caucasus and on the Volga River. And the US-led anti-Da’esh coalition didn’t do the trick. The US and Turkey ostensibly fight Da’esh, but they have their own interests, quite different from those of Syrians, Europeans and Russians. Turkey fights the Kurds who are staunch opponents of Da’esh. The US uses the war with Da’esh as a smokescreen to fight the legitimate government of Bashar Assad who was recently re-elected by vast majority of the Syrians. Da’esh does not suffer much from the US raids, as opposed to the Syrian Army. Moreover, the US sent hundreds of trained terrorists to Syria after providing them with a military upgrade in Jordan and elsewhere. Recently David Petraeus called for the arming of Jabhat an Nusra so they would fight Da’esh. This silly idea was laughed out of court but it is far from dead. The US and its allies have wreaked havoc in Syria. The US is far away and can enjoy the show. Europe is a loser once removed as it gets the flood of refugees. Turkey is a direct loser, as it gets refugees, terrorism, the rapid decline of President Erdogan’s popularity, and a drop of living standards, all this being due to its erroneous policies in Syria. Now Russia has taken over the difficult task of saving the situation. If Erdogan, Obama, Kerry, and the Saudis had thought that Putin would drop Assad, now they are having a rude awakening from such delusions. The Russian position is rather nuanced. Russia will not fight for Assad, as it did not fight for [the Ukrainian President] Yanukovych. Russia thinks it is up to Syrians to decide who will be their president. Assad or somebody else – that’s an internal Syrian affair. On the other hand, Obama and his allies do fight against Assad. He had “lost his legitimacy”, they say. They have a problem with Assad, as they admit. Russia has no problems with Assad. As long as he is popular with his people, let him rule, Russians say. If some members of the opposition will join him, fine. Russia does not intend to fight the armed opposition per se, as long as this opposition is ready for peaceful negotiations and does not demand impossible (say, Assad’s head). In real life, nobody can distinguish between legitimate and illegitimate groups and Da’esh. All of them are likely to suffer when the Russians will begin to do the job seriously. They’d better negotiate with the government and come for some arrangement. The alternative (destruction of Syria, millions of refugees, uprooting of Middle Eastern Christendom, jihadi attack on Russia proper) is too horrible to contemplate. ORDER IT NOW The War in Syria is fraught with dangers for Russia; that’s why Putin steered clear of direct involvement since 2011. The adversary is well armed, has some support on the ground, it has the wealth of the Gulf states and fanatic warriors likely to unleash a wave of terror attacks in Russia. The US position is ambiguous: Obama and his staff does not react on the growing Russian involvement. Thierry Meyssan thinks that Obama and Putin came to agreement regarding the need to defeat Da’esh. In his view, some American officials and generals (Petraeus, Allen) would like to undermine this agreement; so do the Republicans and the Neo-Cons. Some Russian officials are worried. Perhaps Obama keeps mum in order to lure Putin into the Syrian War. Remember, the US enticed Saddam Hussein to invade Kuwait. Russian and American planes in the air over Syria could come to hostile encounters. Others say: shouldn’t Russia get involved in the Ukraine, rather than in Syria? But the apparent decision of Putin to enter war in Syria makes sense. A war far away from home presents logistic challenges, as the US experienced in Vietnam and Afghanistan, but there is much less danger of war spilling into Russia proper. In the distant theatre of war, Russian army, navy and air force will be able to show their pluck. If they will succeed, Syria will regain peace, refugees will return to their homes, while Russia will remain forever in the Eastern Mediterranean. Russian success will cool the warmongers in Washington, Kiev, Brussels. However, if they will fail, NATO will think that Russia is ripe for reaping and may try to move war close to home. We can compare it with military campaigns on 1930s. The Russians under brilliant Marshal Zhukov soundly trashed the Japanese at Khalkhyn Gol in 1939, and the Japanese signed Neutrality pact with Russians and refrained from attacking Russia during the Soviet-German war. But the Red Army managed poorly against Marshal Mannerheim in Finland in 1940, and this encouraged Hitler to begin the war. This time Russia will act within the international law framework, as opposed to Saddam Hussein’s adventure in Kuwait. While the US and Turkey bomb and strafe Syria without as much as ‘by your leave’ from the legitimate government of the state, Russia is coming by permission and by invitation of the Syrian authorities as their ally. There is a Mutual Defence Treaty between Russia and Syria. Syrian government offered Russians its facilities, airports and harbours for the defence purposes. The Christian Churches of the Middle East welcome Russia and ask for its assistance in the face of the jihadi onslaught. The ancient Orthodox Church of Antioch and the Orthodox Church of Jerusalem welcomed Russian involvement. The most high-ranking and politically active Palestinian clergyman, Archbishop Theodosius Atallah Hanna expressed his hope the Russians will bring peace to Syria and the refugees will return home. For the Europeans, this is the chance to wean themselves from blind support of the US policies, to return millions of refugees home from European railway stations and hostels. If it will work, this Putin’s initiative in Syria will count with his greatest achievements. He is playing his hand keeping cards very close to his chest, and this report is the first emanating from his vicinity. Israel Shamir reports from Moscow and can be reached at [email protected] This report was first published in the Unz Review
<filename>benchmark/stats.py import os, re N = 40 values_pt = [0] * N values_cudnn = [0] * N values_best = [0] * N def cmd(method, index): binary = " ./benchmark-persistent-kernels.out" mini_batch_size = "--mini-batch-size" backend = "--backend" command = binary + " " + mini_batch_size + " " + str(index) + " " + backend + " " + str(method) print(command + "\n") ret = os.popen(command).read() all_ret = ret.split("\n") match = re.match(r"RNN Forward Propagation:(.*)TFLOPS/s", all_ret[0]) flops = float(match.group(1).strip()) if method == "persistent": values_pt[index-3] += flops elif method == "cudnn": values_cudnn[index-3] += flops elif method == "best": values_best[index-3] += flops for iter in range(1, 4): for i in range(3, N): cmd("persistent", i) print("<<<<<<< Persistent Finish \n >>>>>>>>") for iter in range(1,4): for j in range(3, N): cmd("cudnn", j) print("<<<<<<< cuDNN Fininsh \n >>>>>>>>>") for iter in range(1,4): for j in range(3, N): cmd("best", j) print("<<<<<<< best Finish \n >>>>>>>>>>>") for i in range(3, N): values_pt[i-3] = round(values_pt[i-3]/3.0, 2); values_cudnn[i-3] = round(values_cudnn[i-3]/3.0, 2); values_best[i-3] = round(values_best[i-3]/3.0, 2) pt_file = open("pt_result.txt", "w+") cudnn_file = open("cudnn_result.txt", "w+") best_file = open("best_result.txt", "w+") print("============== Save Data =============") for i in range(3, N): pt_file.write(str(values_pt[i-3]) + "\n") cudnn_file.write(str(values_cudnn[i-3]) + "\n") best_file.write(str(values_best[i-3]) + "\n")
<filename>gibson2/envs/parallel_env.py from gibson2.core.physics.robot_locomotors import Turtlebot, Husky, Ant, Humanoid, JR2, JR2_Kinova from gibson2.core.simulator import Simulator from gibson2.core.physics.scene import BuildingScene, StadiumScene import gibson2 from gibson2.utils.utils import parse_config, rotate_vector_3d, l2_distance, quatToXYZW from gibson2.envs.base_env import BaseEnv from transforms3d.euler import euler2quat from collections import OrderedDict from gibson2.envs.locomotor_env import NavigateEnv, NavigateRandomEnv import atexit import multiprocessing import sys import traceback from tqdm import tqdm import numpy as np import os class ParallelNavEnvironment(NavigateEnv): """Batch together environments and simulate them in external processes. The environments are created in external processes by calling the provided callables. This can be an environment class, or a function creating the environment and potentially wrapping it. The returned environment should not access global variables. """ def __init__(self, env_constructors, blocking=False, flatten=False): """Batch together environments and simulate them in external processes. The environments can be different but must use the same action and observation specs. Args: env_constructors: List of callables that create environments. blocking: Whether to step environments one after another. flatten: Boolean, whether to use flatten action and time_steps during communication to reduce overhead. Raises: ValueError: If the action or observation specs don't match. """ self._envs = [ProcessPyEnvironment(ctor, flatten=flatten) for ctor in env_constructors] self._num_envs = len(env_constructors) self.start() self.action_space = self._envs[0].action_space self.observation_space = self._envs[0].observation_space self._blocking = blocking self._flatten = flatten def start(self): #tf.logging.info('Starting all processes.') for env in self._envs: env.start() #tf.logging.info('All processes started.') @property def batched(self): return True @property def batch_size(self): return self._num_envs def reset(self): """Reset all environments and combine the resulting observation. Returns: Time step with batch dimension. """ time_steps = [env.reset(self._blocking) for env in self._envs] if not self._blocking: time_steps = [promise() for promise in time_steps] return time_steps def step(self, actions): """Forward a batch of actions to the wrapped environments. Args: actions: Batched action, possibly nested, to apply to the environment. Raises: ValueError: Invalid actions. Returns: Batch of observations, rewards, and done flags. """ time_steps = [env.step(action, self._blocking) for env, action in zip(self._envs, actions)] # When blocking is False we get promises that need to be called. if not self._blocking: time_steps = [promise() for promise in time_steps] return time_steps def close(self): """Close all external process.""" for env in self._envs: env.close() def set_subgoal(self, subgoals): time_steps = [env.set_subgoal(subgoal, self._blocking) for env, subgoal in zip(self._envs, subgoals)] if not self._blocking: time_steps = [promise() for promise in time_steps] return time_steps def set_subgoal_type(self,sg_types): time_steps = [env.set_subgoal_type(np.array(sg_type), self._blocking) for env, sg_type in zip(self._envs, sg_types)] if not self._blocking: time_steps = [promise() for promise in time_steps] return time_steps #def _stack_time_steps(self, time_steps): # """Given a list of TimeStep, combine to one with a batch dimension.""" # if self._flatten: # return fast_map_structure_flatten(lambda *arrays: np.stack(arrays), # self._time_step_spec, # *time_steps) # else: # return fast_map_structure(lambda *arrays: np.stack(arrays), *time_steps) #def _unstack_actions(self, batched_actions): # """Returns a list of actions from potentially nested batch of actions.""" # flattened_actions = nest.flatten(batched_actions) # if self._flatten: # unstacked_actions = zip(*flattened_actions) # else: # unstacked_actions = [nest.pack_sequence_as(batched_actions, actions) # for actions in zip(*flattened_actions)] # return unstacked_actions ## TODO(sguada) Move to utils. #def fast_map_structure_flatten(func, structure, *flat_structure): # entries = zip(*flat_structure) # return nest.pack_sequence_as(structure, [func(*x) for x in entries]) #def fast_map_structure(func, *structure): # flat_structure = [nest.flatten(s) for s in structure] # entries = zip(*flat_structure) # return nest.pack_sequence_as( # structure[0], [func(*x) for x in entries]) class ProcessPyEnvironment(object): """Step a single env in a separate process for lock free paralellism.""" # Message types for communication via the pipe. _READY = 1 _ACCESS = 2 _CALL = 3 _RESULT = 4 _EXCEPTION = 5 _CLOSE = 6 def __init__(self, env_constructor, flatten=False): """Step environment in a separate process for lock free paralellism. The environment is created in an external process by calling the provided callable. This can be an environment class, or a function creating the environment and potentially wrapping it. The returned environment should not access global variables. Args: env_constructor: Callable that creates and returns a Python environment. flatten: Boolean, whether to assume flattened actions and time_steps during communication to avoid overhead. Attributes: observation_spec: The cached observation spec of the environment. action_spec: The cached action spec of the environment. time_step_spec: The cached time step spec of the environment. """ self._env_constructor = env_constructor self._flatten = flatten #self._observation_spec = None #self._action_spec = None #self._time_step_spec = None def start(self): """Start the process.""" self._conn, conn = multiprocessing.Pipe() self._process = multiprocessing.Process(target=self._worker, args=(conn, self._env_constructor, self._flatten)) atexit.register(self.close) self._process.start() result = self._conn.recv() if isinstance(result, Exception): self._conn.close() self._process.join(5) raise result assert result is self._READY, result #def observation_spec(self): # if not self._observation_spec: # self._observation_spec = self.call('observation_spec')() # return self._observation_spec #def action_spec(self): # if not self._action_spec: # self._action_spec = self.call('action_spec')() # return self._action_spec #def time_step_spec(self): # if not self._time_step_spec: # self._time_step_spec = self.call('time_step_spec')() # return self._time_step_spec def __getattr__(self, name): """Request an attribute from the environment. Note that this involves communication with the external process, so it can be slow. Args: name: Attribute to access. Returns: Value of the attribute. """ self._conn.send((self._ACCESS, name)) return self._receive() def call(self, name, *args, **kwargs): """Asynchronously call a method of the external environment. Args: name: Name of the method to call. *args: Positional arguments to forward to the method. **kwargs: Keyword arguments to forward to the method. Returns: Promise object that blocks and provides the return value when called. """ payload = name, args, kwargs self._conn.send((self._CALL, payload)) return self._receive def close(self): """Send a close message to the external process and join it.""" try: self._conn.send((self._CLOSE, None)) self._conn.close() except IOError: # The connection was already closed. pass self._process.join(5) def step(self, action, blocking=True): """Step the environment. Args: action: The action to apply to the environment. blocking: Whether to wait for the result. Returns: time step when blocking, otherwise callable that returns the time step. """ promise = self.call('step', action) if blocking: return promise() else: return promise def reset(self, blocking=True): """Reset the environment. Args: blocking: Whether to wait for the result. Returns: New observation when blocking, otherwise callable that returns the new observation. """ promise = self.call('reset') if blocking: return promise() else: return promise def set_subgoal(self, subgoal, blocking=True): promise = self.call('set_subgoal', subgoal) if blocking: return promise() else: return promise def set_subgoal_type(self, subgoal_type, blocking=True): promise = self.call('set_subgoal_type', subgoal_type) if blocking: return promise() else: return promise def _receive(self): """Wait for a message from the worker process and return its payload. Raises: Exception: An exception was raised inside the worker process. KeyError: The reveived message is of an unknown type. Returns: Payload object of the message. """ message, payload = self._conn.recv() #print(message, payload) # Re-raise exceptions in the main process. if message == self._EXCEPTION: stacktrace = payload raise Exception(stacktrace) if message == self._RESULT: return payload self.close() raise KeyError('Received message of unexpected type {}'.format(message)) def _worker(self, conn, env_constructor, flatten=False): """The process waits for actions and sends back environment results. Args: conn: Connection for communication to the main process. env_constructor: env_constructor for the OpenAI Gym environment. flatten: Boolean, whether to assume flattened actions and time_steps during communication to avoid overhead. Raises: KeyError: When receiving a message of unknown type. """ try: np.random.seed() env = env_constructor() #action_spec = env.action_spec() conn.send(self._READY) # Ready. while True: #print(len(self._conn._cache)) try: # Only block for short times to have keyboard exceptions be raised. if not conn.poll(0.1): continue message, payload = conn.recv() except (EOFError, KeyboardInterrupt): break if message == self._ACCESS: name = payload result = getattr(env, name) conn.send((self._RESULT, result)) continue if message == self._CALL: name, args, kwargs = payload if name == 'step' or name == 'reset' or name == 'set_subgoal' or name == 'set_subgoal_type': result = getattr(env, name)(*args, **kwargs) #result = [] #if flatten and name == 'step' or name == 'reset': # args = [nest.pack_sequence_as(action_spec, args[0])] # result = getattr(env, name)(*args, **kwargs) #if flatten and name in ['step', 'reset']: # result = nest.flatten(result) conn.send((self._RESULT, result)) continue if message == self._CLOSE: assert payload is None break raise KeyError('Received message of unknown type {}'.format(message)) except Exception: # pylint: disable=broad-except etype, evalue, tb = sys.exc_info() stacktrace = ''.join(traceback.format_exception(etype, evalue, tb)) message = 'Error in environment process: {}'.format(stacktrace) #tf.logging.error(message) conn.send((self._EXCEPTION, stacktrace)) finally: conn.close() if __name__ == "__main__": config_filename = os.path.join(os.path.dirname(gibson2.__file__), '../test/test.yaml') def load_env(): return NavigateEnv(config_file=config_filename, mode='headless') parallel_env = ParallelNavEnvironment([load_env] * 2, blocking=False) #from IPython import embed; embed() #parallel_env.close() from time import time for episode in range(10): start = time() print("episode {}".format(episode)) parallel_env.reset() for i in range(300): res = parallel_env.step([[0.5, 0.5] for _ in range(2)]) state, reward, done, _ = res[0] if done: print("Episode finished after {} timesteps".format(i + 1)) break print("{} elapsed".format(time() - start))
<filename>Java/Tobin.c #include<stdio.h> int n,k,a[100]; void pat(int x, int y){ int i; if(x>=n){ if(y==k){ for(i=0; i<n; i++)printf("%d",a[i]); printf("\n"); } return; } if(y<k){ a[x]=1; pat(x+1,y+1); } a[x]=0; pat(x+1,y); } int main(void){ scanf("%d %d",&n,&k); pat(0,0); return 0; }
Design and control of the first foldable single-actuator rotary wing micro aerial vehicle The monocopter is a type of micro aerial vehicle largely inspired from the flight of botanical samaras (Acer palmatum). A large section of its fuselage forms the single wing where all its useful aerodynamic forces are generated, making it achieve a highly efficient mode of flight. However, compared to a multi-rotor of similar weight, monocopters can be large and cumbersome for transport, mainly due to their large and rigid wing structure. In this work, a monocopter with a foldable, semi-rigid wing is proposed and its resulting flight performance is studied. The wing is non-rigid when not in flight and relies on centrifugal forces to become straightened during flight. The wing construction uses a special technique for its lightweight and semi-rigid design, and together with a purpose-designed autopilot board, the entire craft can be folded into a compact pocketable form factor, decreasing its footprint by 69%. Furthermore, the proposed craft accomplishes a controllable flight in 5 degrees of freedom by using only one thrust unit. It achieves altitude control by regulating the force generated from the thrust unit throughout multiple rotations. Lateral control is achieved by pulsing the thrust unit at specific instances during each cycle of rotation. A closed-loop feedback control is achieved using a motion-captured camera system, where a hybrid proportional stabilizer controller and proportional-integral position controller are applied. Waypoint tracking, trajectory tracking and flight time tests were performed and analyzed. Overall, the vehicle weighs 69 g, achieves a maximum lateral speed of about 2.37 m s−1, an average power draw of 9.78 W and a flight time of 16 min with its semi-rigid wing. Introduction With quick advancement of technology in numerous fields and miniaturization of components, micro aerial vehicles (MAVs) have become increasingly useful and ubiquitous. MAVs weigh typically less than 100 g and due to their lightweight and small form factor, they can be considered as safer to operate indoors and nearby humans or animals. Typically, MAVs can be of three different types: fixed-wing, rotary wing and flapping wing. Fixed-wing MAVs, such as the Black Widow , are particularly good for longer ranged missions but not suitable for operation within confined spaces due to its forward speed. Rotary wings, which may be of helicopter type such as Black Hornet or multi-rotor type such as Crazyflie , are better suited for indoor operations due to their low-speed flights and maneuverability. Their design and control are well researched, however they require multiple actuators and by its physical nature, they may be less efficient and have shorter range than the fixed-wing counterparts. Lastly, flapping wings are a new emerging field in MAV research due to their relatively high aerodynamic efficiency at low Reynolds number regime. Among rotary wings, monocopters have recently enjoyed renewed interest in research. The design of the monocopter is inspired from naturally occurring samara seeds, more fondly known as 'helicopter seeds' due to their ability to use autorotation as a way to slow down their descent and disperse. Similar to the samara seed, the design of the monocopter is relatively simple, consisting of a large single wing and a seed-like portion that houses most electronics and battery. The concept of monocopters is actually not new. The first design of the monocopter can be traced back to 1913 when a failed manned-flight attempt was made. As the entire craft is supposed to rotate, additional complex mechanisms must be added if the flight is manned, ultimately making the concept more suitable as an unmanned system. As an MAV, the monocopter is a relatively simple platform, with minimum moving parts and actuators, making it possible for low cost manufacturing. With approximately 80% of its body forming the wing for useful aerodynamic forces generation (as seen in Figure 1(A)), it forms the basis of an efficient platform as compared to multi-rotor type rotary wing crafts. With today's technology, the monocopter has become particularly relevant. High speed micro-sized sensors can measure the monocopter's rapidly changing states and use it for control, which had been a challenging task in the past. One of the advantages of the monocopter platform is its inherent ability for autorotation, the mode of flight of the samara seeds. The monocopter is thus equipped with a natural fail-safe, thanks to this ability to descend gracefully in autorotation in the event of a power failure. Autorotation of single-winged seeds is relatively well studied, both in its natural form , or their mechanical counterparts . Attempts have been made to use samara-inspired flight for payload delivery in the past . Research interest on monocopter platforms revived back in 2008 when a research attempt by students from MIT made one of the first documented controllable monocopters. It used an electric motor and propeller to provide propulsion for its rotation, and a servo to control the flap (aileron) deflection angle for pitch and roll movements. It featured a simple construction-a foam wing, with orthogonal carbon fiber struts as a structure to house the motor, battery and other electronic components. The researchers employed cyclic actuation of the flap, similar to the swashplate control of the blades in helicopters, for controlling the lateral movements. This means that in every revolution of the monocopter, the flap is deflected up and down smoothly in a sinusoidal wave. However, as opposed to swashplate of helicopters, there is no stationary frame of reference from which control inputs can be applied as the entire body of the craft is rotating. Knowledge of the vehicle orientation relative to the desired flight path is obtained by an on-board electronic magnetometer. The work demonstrated that a powered controllable flight with a monocopter was possible and outlined a basic theory of monocopter dynamics. Although they did not publish the flight time achieved with their setup, one can perform a simple calculation based on the battery used (7.2 V 300 mAh) and the power consumption reported (32 W) and arrive to a flight time of approximately 4 min. In 2010 , researchers from University of Maryland made samara-I, samara-II and samara-III prototypes, which are of different sizes and weights. Their smallest variant, samara-III, is tiny enough to fit on a palm. Monocopters with smaller wingspan typically have to rotate faster for flight than their larger counterparts. As sensor packages capable of measuring onboard flight data for this nano-class crafts were not commercially available at that time, the researchers had to find a different approach for control that did not rely on once-per-revolution sensing and actuation. Their research focused on first investigating autorotation properties of different wing geometries of mechanical replicas of the samara design. Upon observing the helical trajectories of an autorotating samara are coupled to variations in its wing pitch, the researchers proposed a method to control the resulting robotic samara. By changing the pitch angle of the entire wing, the radius of the precession circle could be controlled, thus making the craft move towards an intended direction in circles of changing radii. As opposed to once per revolution control used in , this method requires the wing pitch to change over several revolutions. Hence, high speed sensing and actuation, which are costly at micro-scale, are not required. The robotic samara prototypes thus carried only an electric motor, an electronic speed controller (ESC), a servo, a receiver and a battery. With no microcontroller and sensing on-board, it allowed for an efficient, simple and lightweight construction. The robotic samara prototypes were all manually piloted by a human operator, with its largest prototype achieving a maximum of 20 min of flight time. Traditionally, monocopters have always used two actuators to achieve flight and control in five degreesof-freedom (DOF). This is already under-actuated, as compared to multi-rotors or traditional rotary wings which require a minimum of four actuators. In 2020, a research work proposed a Single Actuator Monocopter (SAM), using one single electric motor to both provide propulsion for flight and produce control effort for pitch and roll motions. SAM featured a custom printed circuit board (PCB) to connect all its electronic components and also provide structural rigidity to the seed portion. As opposed to which used special airfoils for added efficiency, this work used optimization methods to find the best wing planform geometry and motor location, while using flat-plate airfoil for simplicity. For controlling its direction, the motor is pulsed in a cyclic manner. SAM carries a microcontroller and an IMU-when given position states feedback, it can perform completely autonomous flights. It demonstrated waypoint-tracking flight using a closed-loop PID controller and motion-captured camera system to provide position feedback, and achieved 20 min of flight time. Research efforts to achieve controllable flight using a single actuator have been made before SAM. The monospinner has a single actuator and achieves a 5 DOF flight. Essentially, it is a mechanically simple version building upon the idea of a quadcopter losing three of its propellers. It is passively unstable and requires closed-loop feedback control for its flight. Another example is Piccolissimo which is claimed to be the smallest MAV. It demonstrated limited directional control by leveraging on asymmetry between the rotation axis of the body of the craft and that of the motor. Using a flexible or semi-rigid wing for a rotary wing type aircraft is almost non-existent, perhaps due to not having any obvious benefits of such feature. However, for fixed wing and flapping wing counterparts, there are some examples available. A flexiblewing-based fixed wing MAV was explored in a work in 2002 , mentioning numerous advantages such as improved aerodynamic efficiency, delayed stall and ability to be reconfigured for storage. Most flapping wing MAVs employ flexible wings , as flexible wings give superior aerodynamic efficiency at low Reynolds number regime, or for collision resilience using soft actuators . However, their construction usually does not allow for folding or reconfiguration for storage. Most MAV research rely on commercial off-theshelf (COTS) flight controllers . This has obvious benefits such as lower cost for prototyping, quick and easy replacement in the event of damages, and being able to rely on existing sensor integration. However, some research projects especially on micro-class crafts opt for building their own custom flight controller boards. This allows them to carefully select and use only the most suitable components relevant to the project, obtain weight savings, and perhaps most importantly, be able to obtain the desired form factor. If mass-produced, the cost of custom flight boards can be equivalent or lower than COTS counterparts. In summary, various forms of MAVs have been explored in numerous research efforts around the world and the current trend is towards pushing boundaries in efficient flight, the use of minimal actuators and superior capabilities such as flexibility and easy deployment. The monocopter, as seen in figure 2 and table 1, is a strong contender in this field, as its form factor allows for increased flight efficiency while enabling a dynamically stable under-actuated flight. However, one drawback of the monocopter is its large footprint which hinders it from quick and easy packaging and transportation. This work aims to explore minimizing the footprint of the monocopter (when not in flight), thus making the platform more compelling and versatile in the field of MAVs. The following research contributions are presented. • The design and development of a Foldable Single Actuator (F-SAM) is presented. The details for the compliant 3D-printed body design and explorations on different types of flexible wing construction are shown. Next, details are given for an optimization process to find the best wing planform considering the effects of wing flexibility and constraints due to the folding process. The resulting F-SAM prototype is able to decrease its footprint area by 69% when folded and fly for a duration of 16 min with a take-offweight of 69 g. • A dynamic model of F-SAM is devised for a simulation in 6 DOF which is used in the optimization process and simulation of new control strategies. A proportional stabilizer controller and proportional-integral position controller are devised and tested in the simulation. This new control strategy proposed is suitable for nonlinear rotating platforms similar to F-SAM and improves their dynamic stability. Design and control of F-SAM The F-SAM consists of two major structures similar to other monocopters: the body and the wing. The single motor is mounted on the leading edge of the wing, unlike some monocopter designs where the motor is mounted on a separate structure extended from the base of the body . By mounting the motor on the wing, a more compact folded structure can be achieved. The components are placed such that the center of gravity (CG) lies close to the body in the unfolded state, enabling most areas of the wing to receive airflow to generate useful aerodynamic forces. Most of the components are carefully selected in an effort to reduce as much weight as possible. F-SAM is designed to rotate counter-clockwise (looking from above) although there is no observed difference in physical dynamics in either direction of rotation. Body The body houses all the flight avionics and the flight battery. The flight avionics are all mounted on a purpose-designed autopilot board. Two single cell lithium polymer batteries are connected in series to supply power for avionics and flight. The autopilot board provides most of the structural rigidity of the body and small 3D-printed structures are used to facilitate folding of the body structure itself. Normally, 3D-printed components are designed to be rigid and provide structural support. In the case with F-SAM, however, due to the design of the fold, the 3D-printed components are designed to be semirigid. A compliant design, shown in figure 3, allows the 3D-printed component to achieve flexibility in one axis. Two of such structures hold the battery and flight board together. When folded, the battery rests next to the folded wing structure at about α = 60 • . When in flight, the battery can be either fully folded in (α = 0 • ) or out (α = 180 • ). In the former case, the moment of inertia of F-SAM is decreased, causing it to fly at higher spin rate during hover while in the latter configuration, the moment of inertia is increased, resulting in a lower spin rate. The center of rotation also changes due to the shift in CG. A total of four 3D-printed parts and two carbon rods are used in the construction of F-SAM. Two of them use compliant design to hold the battery and flight board together. One holds the base of the wing using a tight-fit slot and a 3M surgical tape and connects to the carbon rod which acts as the main hinge between the wing and the body. The last 3D-printed component attaches the motor to the wing. A second carbon rod is used as support during take off to prevent the propeller from touching the ground. Wing The wing forms the largest area of the structure of the craft while being the lowest mass proportion. It needs to generate useful aerodynamic forces to keep the craft in flight and by having a low mass, the CG can be placed nearer to the body, enabling a larger section of the wing to have inflow during rotation. Monocopter wings generally have been built using lightweight materials such as foam , carbon fiber , balsa wood or a combination between balsa and foam . The autorotating versions of this samara-inspired craft have been built using a combination of balsa and foam as well . Various airfoil types have been used on monocopter wings. Airfoil types such as AG455 , AG38 , samara-inspired custom airfoil and flateplate airfoils are used on different monocopter prototypes. As for the planform geometry of the wing, monocopters have mostly utilized a rectangular planform for simplicity. A samara-inspired shape has been explored . With F-SAM, the wing needs to be flexible for folding compactly, allowing it to be folded and stored or transported inside a small container. Different materials and folding techniques are explored in this work. The airfoil is set to flat-plate airfoil as it allows for easy folding and prototyping. The wing planform, with the chosen wing material, is optimized using genetic algorithm on a dynamic model in a 6-DOF space, applying blade element theory for aerodynamics modeling. The different materials and folding techniques explored are presented below. Flexible plastic A flexible wing structure can be made from laminated plastic (Suremark Laminating Pouch 100 micron) as shown in figure 4(a). In order to increase chordwise stiffness, narrow strips of balsa wood (1 mm thickness) are added in between two layers of plastic before lamination. In this variant, three wires for the motor are also placed within the plastic sheets before lamination. The structure of the wing is flexible along the wing span, allowing it to fold into a roll. In flight, the apparent centrifugal force generated from the rotation of the craft pulls the wing straight. A torque is generated when the spinning motor and propeller is rotated about the rotation axis of the craft. This torque pitches the outer section of the wing up, twisting the wing along spanwise direction of the wing. The same flexibility allowing the spanwise twist also leads to a less effective cyclic control. Flexible PCB An alternative idea is to use PCB structure as the wing, effectively making it a multi-functional element. Not only would the wing be used to generate aerodynamic forces, it could also be used to embed connections for the motor and other electronics such as a wireless communication antenna. A flexible PCB material (0.1 mm polymide flex) was considered as the material of the wing. Carbon spars (1 mm diameter) are taped onto the wing to increase its chordwise stiffness. A narrow strip of plastic is laminated along the leading edge of the wing to increase its spanwise stiffness. Similar to the flexible plastic wing, the flexible PCB wing can be rolled into a compact form factor. Likewise, centrifugal forces pull the wing straight during flight. The cyclic control is even less effective on this wing as the wing material is more flexible than the flexible plastic, allowing too much twisting in spanwise direction. Semi-rigid balsa with plastic To increase the effectiveness of cyclic control, spanwise stiffness must be increased. The next strategy is similar to the first flexible plastic concept, but with increased width of the balsa elements. In this case, the balsa elements fill up the entire area of the wing, joined together by one sheet of laminated plastic. To produce this wing, balsa is first lasercut into precise shapes and placed within laminating pouch (125 microns) leaving a tiny gap (approximately 1 mm) between each element. Once lamination is done, the excess plastic is manually cut off, after which one side of the plastic is removed, leaving only the balsa pieces and one side of laminated plastic sheet as the structure of the wing. This wing can be folded into its plastic side. Although it cannot be rolled like previous wing structures, the semi-rigid wing can be folded into a neat pre-determined configuration, such as triangular or rectangular. The benefit of the semi-rigid structure as compared to its other flexible counterparts is that it has increased responsiveness to control inputs and increased flight efficiency. However, it has less control responsiveness and flight efficiency as compared to a fully rigid wing, which we found during preliminary testing. For F-SAM, this semi-rigid wing structure is chosen. Custom autopilot board implementation The F-SAM platform is passively stable. An autopilot implementation allows the craft to be controlled via a human operator or closed-loop feedback control in a motion-captured environment. Creating a purpose-designed autopilot board allows us to take several advantages over simply using an off-the-shelf autopilot system. It enables us to choose exactly the components needed, packaged in a form factor that is favorable to the folding design. All the components including sensors, microcontroller, power regulators, and the ESC are arranged in a narrow rectangular form factor as shown in figure 5. For the attitude heading reference system, a combination of magnetometer and inertial sensor is used. The former is LIS3MDLTR, an ultra-low-power highperformance three-axis magnetometer, capable of an update rate of 500 Hz. The latter is ICM20649 that consists of a gyroscope and an accelerometer. The gyroscope has a full-scale range of 4000 degrees per second, making it suitable for high rotation speed measurements such as the monocopter. For the microcontroller, Espressif ESP32 is chosen for use, in Sparkfun MicroMod configuration. This allows us to easily swap and replace the microcontroller should it be damaged during a crash. ESP32 comes with a WiFi connectivity, allowing flight telemetry and a wireless reconfiguration of parameters. An ESC is directly soldered onto the control board, receiving control signals directly from the microcontroller and providing power to the brushless motor mounted on the wing. The control board is also designed to include data-logging capability using a MicroSD card. Additionally, two time-of-flight laser ranging sensors are added for potential sensing applications and a current sensor to measure the power consumption during the flight. A power distribution board (PDB) connects two 1S lithium polymer batteries in series and provides input power to the control board. Flying prototype The prototype, shown in figures 1 and 6, is assembled using the 3D printed components, laminated wing, custom autopilot board and the propulsion system. With all the parts available, the prototype can be easily assembled within about 10 min. The wing used on the F-SAM prototype has holes cutout on the balsa for more weight savings. It is assumed to not affect the aerodynamics significantly as the plastic film still covers the entire area to form aerodynamic surface. The COTS parts used are given in table 2. The weight breakdown of the F-SAM prototype is shown in figure 7 and it should be noted that the battery and propulsion system form about 49% of the weight of the craft, whereas the wing only forms 12%. In its unfolded state, F-SAM is about 35 cm in length. However, once folded, its footprint area is reduced by 69%. The prototype is flown and its current and power consumption is measured using the INA219 current sensor included in our custom autopilot board. The final specifications of the flying prototype are given in table 3. F-SAM achieves a flight efficiency of about 7.1 g W −1 whereas a Crazyflie quadcopter averages about 4.3 g W −1 during hover. Dynamic model In order to simulate and optimize the wing planform of F-SAM, a dynamic model is first created. Figure 8 shows all the forces and torques acting on F-SAM typically during its flight. The world frame is denoted as Ψ W and the body-fixed frame is denoted as Ψ b with its center fixed to the CG of the craft, x-axis aligned with the longitudinal direction of the wing and y-axis along chordwise direction of the wing. In the simulation, the battery module is fixed at its folded orientation (α = 0 • ) giving a smaller rotational moment of inertia, with the CG located near the root of the wing. Aerodynamic forces The forces and torques acting on F-SAM include the weight W, thrust and torque from motor F m and τ m respectively, and aerodynamic forces from the wing. In general, it is modeled as a rigid body in a 6 degrees of freedom environment, where it is able to freely translate and rotate in any direction. MATLAB Simscape Multibody is used for the simulation, where an application of six-DOF joint automatically applies the standard formulations of six-DOF motion which are commonly used for simulation of aircraft and spacecraft . Simscape Multibody provides multibody simulation environment using a graphical programming interface representing relationships between bodies using joints, constraints, force elements and sensors. Forces and moments can be specified at component level, such as individual blade elements, and resolved forces and moments are automatically computed and applied to the entire body through component relationships. Using Simscape Multibody ensures that human errors are minimized in the process of manually writing, assembling and running the code for integrating the equations of motion and resolving the numerous forces and moments. The geometries of autopilot board, 3D-printed components, battery, motor and propeller are drawn in SolidWorks and imported into Simscape Multibody, with their exact weights applied. Hence the mechanical properties of these elements are precisely accounted for in the simulation. The wing is generated using flat rectangular blocks to form a generic shape, which must be optimized using the simulation. In order to model the aerodynamic forces, we apply blade element theory . The wing is split into n be blade elements. The lift and drag forces generated from each blade element is calculated using: where dL and dD are the lift and drag forces respectively acting on the blade element, ρ is the density of air, U is the relative air velocity interacting with the blade element, c is the chord length of the blade element, C l and C D are coefficients of lift and drag respectively, and dr is the width of the blade element. As the wing is constantly flying into its own wake during hover and in most aspects of the flight, it is assumed to to be less efficient than in its ideal state. To account for this, the drag coefficients are multiplied with a constant μ such that C D = μC d . This value of μ is experimentally found by flying an arbitrary configuration of F-SAM and then fine-tuning the simulated parameters to match the results. The values of C l and C d are flat-plate airfoil coefficients obtained and linearly interpolated from NACA Technical Report 3221 . dL and dD forces are resolved into normal and axial forces (dN and dA respectively) before being applied back into the model. In Simscape Multibody, the relative inflow angle can be found by attaching a transform sensor to measure velocities with respect to a non-rotating follower on the blade element, as shown in figure 9. The two cases consider all inflow velocity situations, allowing the model to be simulated in almost any scenario. dN and dA forces are then calculated using: where ζ is the relative inflow angle of air. In F-SAM, due to its configuration, the CG is located in between the first and second blade element. As F-SAM typically rotates about its CG, this leads to a negative flow on the first blade element and a very small positive flow on the second blade element due to their close proximity to the center of rotation. The aerodynamic force contribution from these two elements are hence assumed to be negligible. For the rest of the blade elements, the normal and axial forces are assumed to be acting at the quarter-chord location. The thrust unit simply consists of a brushless motor directly attached to a propeller. In order to consider the gyroscopic effects of a spinning mass (the motor bell and propeller), these components are modeled to spin in the simulation with an estimated rotation speed of 240 rotations per second at 100 g of thrust, modeled with a direct linear relationship to the motor force. The accuracy of the simulated model is cross-checked with an actual prototype during mid-design phase, on parameters such as the rotation speed Ω Z and thrust T required for hover. Wing flexibility considerations In order to simplify the simulation, each blade element is assumed to be each foldable piece on the semirigid wing. Due to the folding methodology shown in figure 8, the width of each blade element Δ i (measured in mm) follows the following relationship where δ is the parameter which defines the width of the first blade element, and hence indirectly defines the length of the wing, and i is the blade element designation and i ∈ Z + . The flexibility of the wing during flight is also considered for simulation. Each blade element is linked to the other using a revolute joint that allows rotational degree of freedom along y-axis of Ψ b , as shown figure 10. A spring stiffness value of k y and damping coefficient of σ y is applied to all the joints between the blade element. As the wing also has limited flexibility along x-axis, a single revolute joint along x-axis is applied between the 5-th and 6-th blade elements with a spring stiffness and damping coefficients of k x and σ x respectively. The values of the coefficients have not been found experimentally, but are selected such that the wing deformation during the flight is similar between real life and simulation. These values are presented in table 5. Cyclic control F-SAM is equipped with just one actuator and this single actuator is responsible for both altitude and attitude controls. As F-SAM is a constantly rotating system, it is intuitive to apply a cyclic control. In helicopters, a swashplate is used to obtain cyclic control of the blade pitch angle. The swashplate mechanically limits and controls the pitch angle of each blade, producing a smooth sine wave through each rotation. The result gradually increases and decreases lift over different regions within each rotation. The imbalance of lift tilts the tip path plane of the blade into a pitch or roll motion, also resulting in the pitch or roll motion of the craft. On F-SAM, direct motor control allows a more rapid approach of cyclic control. One simple way to maximize the benefits of rapidly changing thrust is to use square waves. As shown in figure 11(A), an arbitrary constant thrust with an arbitrary configuration of F-SAM results in hover flight. Increasing this thrust results in increasing the rotation speed of F-SAM which in turn creates more lift to start a climb. Decreasing the thrust, on the other hand, results in a descent. During cyclic application of thrust, thrust is higher in a portion of the rotation period and lower in the remainder as shown in figure 11(B). At an arbitrary cyclic thrust, the craft remains at constant altitude while moving. Increasing or decreasing cyclic thrust results in climbing or descending while moving laterally in general. The parameter T o is the offset thrust. The effect of this parameter is similar to that of collective pitch control on helicopters. When flown manually, this parameter is mapped directly to the throttle stick value. The parameter T amp is the amplitude of the square wave. When flown manually, this parameter is mapped to the amplitude of roll and pitch input, φ c and θ c respectively. T amp and control direction γ c of pitch and roll input can be defined as where k is a constant to scale the effectiveness of pitch and roll commands. Square cyclic control for thrust T can be defined as where γ z is the current azimuth heading of the craft, γ off is the angle correction offset due to gyroscopic precession and other effects, and is the variable to control the duty cycle. Closed-loop control To control F-SAM in simulation and in experiments with MOCAP (motion captured) environment, a closed-loop control is devised. The controller consists of a proportional stabilizer control and traditional proportional integral position Control. Proportional stabilizer Being a system influenced by both aerodynamic forces and gyroscopic precession, F-SAM, like any other monocopter, has a natural precession circle. Depending on the physical dynamics of the craft, the precession circle may be one that is growing (unstable), constant (marginally stable) or reducing (stable). For a monocopter, before any control is applied, it is desirable to have physical dynamics configured such that the precession circle is reducing. This means that when a disturbance is introduced, the monocopter flies in spirals of decreasing radius. However, the natural decay of the precession circle in a stable configuration of the monocopter may become problematic when applying linear controllers such as PID control. The latter, when used to control position for example, may cause the system to enter a growing precession circle. Various methods have been attempted to reduce precession circle while having PID control in tandem. The main problem with such attempts results from precession circle having a different phase from the controller itself. This will be explored in detail in a future work. It is found that having a proportional stabilizer based on angular velocity states in the world frame helps to reduce the precession circle. The proportional stabilizer is defined as follows where φ s and θ s are stabilizer controller outputs for pitch and roll respectively, k s is the stabilizer gain, and Ω X and Ω Y are angular velocities in X and Y axis respectively. This controller will be analyzed and Position control A traditional PI controller is applied each for altitude, and a P controller for pitch and roll controls. Altitude control works in the following manner. Increasing the thrust from the single actuator causes F-SAM to have increased spin rate. This in turn generates increased aerodynamic lift forces from the wing and results in the vehicle climbing altitude. Decreasing the thrust, on the other hand, causes it to spin slower and descend. This effect is easy to observe. The less observable effect is the following. In order to increase thrust, the motor and the propeller needs to spin faster, gaining angular velocity on the motor and propeller bodies. As these bodies are rotating about a different axis as the rotational axis of the body of the craft, there is a resultant torque acting on the motor and propeller. This torque causes the wing to pitch upwards, increasing the angle of attack. The thrust direction of the motor also pitches upwards, contributing a portion of its thrust directly to the climb. The controller for altitude control is where K pz and K iz are proportional and integral gains respectively, and e z (t) is position error in Z-axis at time t. A derivative gain is not introduced as it is found to cause instability in the simulated model. Pitch and roll controller is formulated as where K py and K px are proportional gains for pitch and roll respectively, and e y (t) and e x (t) are position errors in Y and X-axis respectively in the world frame. The controller outputs for pitch and roll are combined with proportional stabilizer output to get the final control outputs for pitch and roll which are fed to the cyclic controller Optimization of design parameters A simple optimization was executed to find the best wing planform for F-SAM. Formulation The planform of the wing is defined by a polynomial of order 3 to ensure smoothness of the shape. This can be defined as where j = i − 2 and ( j n be − 2| j ∈ Z + ), c(i) is the chord length of the respective blade element, and C 1 , C 2 , and C 3 are the coefficients to be determined such that the value of c(i) is bounded between c min and c max . C 4 is fixed to a constant and C 4 defines the length of the first two blade elements which are constrained to a minimum length as they contribute negligible aerodynamic forces. The folding process requires the motor and propeller to not get in the way-to prevent this, the leading edge of the wing is constrained to form a straight line. The motor is fixed to the 7th blade element and its position is not considered for optimization. Parameter Lower bound Upper bound For the optimization, F-SAM is simulated for a duration of 20 s with initial conditions v Z0 and Ω Z0 with controllers described in section 2.7 turned off. During this simulation, multiple parameters are evaluated in a combined single objective function. The parameters selected are indicative of a decent flight dynamics of F-SAM during hover, and they include • maintaining a decent spin rate during hover, as too high spin rate would not allow the actuator and sensors to keep up and too low spin rate could lead to the wing stalling, • hovering near a target altitude and not ascending or descending, • a minimum level of thrust from the motor is used, • minimum oscillating values in Ω X and Ω Y , as when these values oscillate and grow, they indicate the presence of a growing precession circle, • minimum values of v X and v Y as these values indicate the platform is drifting away and lacks dynamic stability. The variables in this formulation, shown in table 4, can be expressed in a single concatenated vector Γ = T . The first three variables (C 1 , C 2 , C 3 ) are polynomial coefficients for chordwise wing shape in equation (15) and are real numbers. Only δ is integer valued. The lower and upper bounds are selected such that there is adequate region to search for solutions without bias towards any particular value. The main objective function for the first formulation consists of five sub-objective functions, namely F 1 , F 2 , F 3 , F 4 and F 5 . F 1 is the sub-objective for average spin rate during hover, which is defined as where Ω Z (t i ) is a negative value, Ω des is the target rotation speed, and n 1 and n 2 are selected time steps of the simulation. F 2 is the sub-objective for height difference between the start and end of simulation and is defined as where z(t i ) is the Z-axis coordinate of the model at the end of the simulation. F 3 is the sub-objective penalty function for undesired oscillations in Ω X and Ω Y , and is defined as where Ω X and Ω Y are angular velocities in the X and Y-axes respectively. F 4 is the sub-objective function to penalize velocity drifts in X and Y-axis and is defined as where v X and v Y are velocity values in X and Y-axis respectively. Finally F 5 is the sub-objective function for thrust and is defined as where T o is the thrust value part of Γ. The subobjective functions are combined together to yield the final objective function for the first optimization which is summarized as where κ 1 , κ 2 , κ 3 , κ 4 and κ 5 are the weightage coefficients of each sub-objective function. Although the problem can be formulated as a multi-objective optimization, it is simplified to produce a single result using a weighted sum from user subjective preferences. The coefficients, given in table 5, serve to nondimensionalize each function outputs and bring them to a similar order of magnitude. Highest priority is given to F 5 . Optimization results The optimization is run using MATLAB's ga function scripted to run on the MATLAB Simscape Multibody simulation model developed based on section 2.5. GA uses principles of biological evolution and natural selection in order to find an optimum result. This works by first initiating with a fixed population P S of random solutions which are run through the Simulink model. The results of all solutions from the population is evaluated using the objective function in equation (21). The resulting best individual is bred into a new generation of population size P S using mutation functions and once again fed into Simulink model. This process is repeated until a better solution cannot be found for G S generations or max generation count G M is reached, as explained in a flowchart in figure 12. P S , G S and G M are set manually and are given in table 5. Figure 13 shows the convergence of penalty values and average distance between individuals over G M generations. The convergence indicates the optimization The design variables corresponding to the best fitness value are Γ = T . This results in a wing planform shown in figures 1 and 8. When making the actual wing, the smooth shape of the wing is achieved by joining the blade elements together using a spline. Simulation parameters are given in table 5. The use of GA does not guarantee a globally optimum solution to the problem, but because it searches randomly within the search space, it is less likely to be stuck in a local optimum. The use of other optimization algorithms may result in a slightly better solution or may take up less computational power, but the goal here is to generally only search for a decently optimized solution and therefore, GA is considered a suitable option. Simulation In this section, we discuss the simulation setup used and show results of simulated hover and waypoint tracking. Figure 14 shows the setup within MATLAB Simscape Multibody. It consists of a rigid body dynamics portion which has the configuration settings for gravity, solver and world frame, linked to a six-DOF joint which computes rigid body dynamics in six degrees of freedom. This is connected to the rigid body portion, which includes physical properties of solid objects that combine to represent a physical F-SAM. BET calculation subsystem consists of blade element velocity sensing and aerodynamic force calculations. The electronic swashplate subsystem computes the cyclic actuation of the single actuator. Simulation setup Simulation is run with an automatic solver selection and fixed time step of 0.001 s. Simulation results Two simulations are presented in this section-(1) F-SAM with optimum wing and thrust without any controller versus with only stabilizer controller, and (2) waypoint tracking performance with stabilizer and position control. Optimum configuration with and without stabilizer controller Using the optimized wing geometry and thrust value obtained in section 3.2, F-SAM model is simulated with initial conditions v Z0 and Ω Z0 to observe its behavior without the influence of any controller for a duration of 40 s. This is compared with another simulation of the same duration with identical initial conditions but with stabilizer controller applied. Figure 15 shows the response in position and angular velocity. Small decaying oscillations in Ω X and Ω Y can be observed without controllers applied, indicating that the platform possesses dynamic stability with a decaying precession circle. In the XY plot, it can be seen that the model started with a velocity in positive X direction from its initial position of (0, 0). This is due to the fact that initial angular velocity of Ω Z0 is not applied at its center of mass. The tiny circles are formed on its trajectory as the reference frame is not placed directly at the center of rotation of the model. After moving towards positive X for a short distance, the model is observed to enter a decaying precession circle. With stabilizer controller applied, the model is observed to converge to stability much faster. In figure 10, the wing's pose during an equilibrium hover state can be observed. Applied with spring stiffness and damping coefficients in the joints between the blade elements, the wing in simulation imitates Rising and falling edges γ A and γ B occur when sin(γ z + γ c + γ off ) crosses (both scaled for visibility). The resulting translational motion from cyclic effects is γ app when γ off is not applied, and γ cor when γ off is applied. that of the actual semi-rigid wing during flight. The values of spring stiffness and damping coefficients used are given in table 5. Waypoint tracking with stabilizer control and position control In this simulation, stabilizer and position controller described in section 2.7 are both active. 40 s after starting with initial conditions v Z0 , Ω Z0 and position (0, 0, 0), the model is tasked to reach waypoints (2, 0, 0), (2, 2, 1), (0, 2, 1), and (0, 0, 0) in this order with 30 s intervals. Figure 16 shows the positions, angular velocities and a 3D plot of the trajectory. In the first 40 s, the model converges to (0, 0, 0) position and the corresponding angular velocities Ω X and Ω Y shows that it is able to stabilize in about 15 s. The model is able to approach each waypoint within the time interval. At 70 s when a desired altitude is at 1 m, the spin rate Ω Z is observed to increase momentarily, and at 130 s with desired altitude at 0 m, the spin rate is observed to decrease. The altitude control has remarkably quicker response than lateral position control. This may be the case as the single actuator has direct influence over altitude while it only has indirect influence over lateral position through cyclic control. It should be noted that the model is highly non-linear in X and Y-axis. In the 3D plot, the trajectory of the first 40 s is removed to improve the clarity of the plot. The thrust plot is also shown in figure 16, with another plot zoomed in around 40 s to shown the cyclic behavior. It can be observed that large variations of thrust lead to altitude changes while the much smaller, high frequency changes in thrust is required for cyclic control. Thrust only varies by about 0.01 N with cyclic control and the square cyclic behavior can be observed. This simulation proves that the model is controllable using the simple controllers devised in this work. Experiments In this section, we discuss the experiment setup used and the results of closed-loop waypoint tracking, trajectory tracking, and flight time test. Experiment setup The experiments are conducted in a motion-captured flying arena. It is within a rectangular flying space of 7 m × 5 m × 2.3 m in size. The entire volume is covered by 8 OptiTrack Prime 41 cameras. The cameras project infra-red light into the flying space which are reflected by infra-red reflective markers mounted onto F-SAM prototype. Real-time position and orientation data from the camera system is fed into MATLAB where controller outputs are computed. The output is then sent through an RC module to F-SAM. A human operator, using an RC transmitter unit, is also able to send control signals to F-SAM at the same time. The prototype carries two RC receivers and combines the input from both closedloop control and human operator control. This setup, as shown in figure 17, allows the human operator to take over the flight in the event of emergency. Closed-loop waypoint tracking F-SAM is tasked to follow a waypoint trajectory, similar to the simulation in figure 16. It consists of a square shape, with a side of 2 m, one side at 1 m in height and the other side at 1.8 m in height. The four corners of the square are at (1, −1, 1), (1, 1, 1.8), (−1, 1, 1.8), and (−1, −1, 1). Each waypoint is set for 30 s before moving onto the next. In the experiment, F-SAM approaches the waypoint and stabilizes much faster than in the simulation. However, similar to simulation, it tends to overshoot the waypoint during the approach. Ω X , Ω Y and Ω Z values are also plotted. Ω Z is noticeably less than the simulated value, most likely due to components such as the body not modeled for aerodynamics in simulation creating high drag. As observed in the simulation, at the instances where the waypoint is shifted to the next, spikes in Ω X and Ω Y can be observed, indicating the tip path plane of F-SAM is highly tilted at these points. The results are shown in figure 18. The PWM values sent to the motor are also shown. At the instance of waypoint shifting, high frequency fluctuations in motor command values can be observed and this is due to square cyclic controller. Closed-loop trajectory tracking F-SAM is tasked to follow a continuous trajectory that shifts the desired position incrementally with every time step. The trajectory is a simple square shape with 2 m length on each side. The corners of the square are at points (−1, −1, 1.6), (1, −1, 1.6), (1, 1, 1.6), and (−1, 1, 1.6). A duration of 10 s is given to move along each side of the square, resulting in a movement speed of 0.2m s −1 . The desired position linearly moves along the square throughout the experiment. The flight performance of F-SAM in its XYZ position and world frame rotational speeds are shown in figure 19. Unlike the previous waypoint tracking experiment, the current experiment does not involve abruptly changing desired setpoint, hence the movements are gentle and no large changes in tip path plane are observed. A physical object in the shape of a wide but short window is placed along one of the sides of the square. This is to demonstrate that F-SAM is maneuverable enough to fly through a window. F-SAM can be seen flying through this window multiple times in the recorded video, from which frames are extracted and shown in figure 20. Straight-line speed test In this experiment, F-SAM is pushed to its limit of lateral speed. It is tasked to fly between two points (1, 1, 1.5) and (−1, −1, 1.5), back and forth at increasing speed at each round using trajectory control similar to previous experiment. A duration of 10 s is given for each time it moves, allowing enough time for it to stabilize at the end point before moving off again. In figure 21, it can be observed that F-SAM is able to follow desired location in X and Y coordinates, where Z is observed to start fluctuating when faster speed is required. Ω X and Ω Y are seen to fluctuate more at faster speeds, indicating greater changes to tip path plane. Ω Z is less effected as F-SAM's rotation speed is not affected as much by fast flights. Large fluctuations in motor command can also be observed at the points where desire trajectory begins moving. In the last plot where F-SAM's lateral velocity and desired velocity are plotted, F-SAM has an mean maximum lateral speed of 2.37 m s −1 . Other kinematics of F-SAM, such as maximum speed for ascend, average rotation speed, linear acceleration, and autorotation performance are given in table 6. Flight time test and autorotation performance In order to find out F-SAM's flight time, it is flown at coordinate (0, 0, 1) with stabilizer and position controller enabled. Figure 22 shows that the vehicle's altitude dropped as the battery's voltage dropped. This may be improved with a better tuning or controller. It can also be observed that even with our simple proportional stabilizer control and PI controller for position, the vehicle did not deviate much laterally, whereby the maximum deviation is 0.4 m. The battery's voltage and current levels are also plotted, and the voltage appears to drop sharply right before the end of the flight, indicating that the lithium battery is used to its maximum capacity. The total energy used for the flight is found to be at 2.6 Wh, while the battery's rated capacity is 3.2 Wh. This may be due to the fact that the battery may have degraded in capac-ity over several charge cycles. The mean power draw for hover flight of F-SAM is found to be about 9.78 W. In a separate test, F-SAM's autorotation performance was observed. It was flown to about 2.1 m height and the motor was completely turned off. Although the height was limited, it reached a steady state drop velocity of −3.56 m s −1 and rotation speed of 27.93 rad s −1 momentarily before landing on the floor. Figure 22. Flight time test of F-SAM. Battery voltage and current levels are logged at 10 s intervals. Discussions and conclusion There is recent interest in using compliant or foldable wings in various flying crafts due to better aerodynamic performance and ability to be reconfigured for storage. This is only most commonly seen in fixedwing type crafts. For rotary wing crafts, flexible wings that can be folded inwards generally have not been explored, as there are no real benefits in folding the wings of a rotary wing aircraft, except for helicopters which may rotate their rigid wings backwards for storage. F-SAM is the first documented semi-rigid and foldable winged rotary wing craft, according to our best knowledge. The folded wing allows the craft to be reconfigured for quick and easy transportation. Although the semi-rigid wing does not provide any superior aerodynamic performance as compared to its rigid counterpart, this work shows that monocopters can be compact and controllable, similar to multi-rotor of comparable weight, while enjoying superior flight efficiency. In this work, the motor position is fixed to the 7th blade element and its effect on the flight performance is not considered for optimization. Generally, depending on the pitch of the propeller, rotation speed of the motor and rotation speed of the monocopter, it is favorable to put the motor near the tip of the wing, as the larger distance from the CG provides a longer moment arm for the craft's rotation. There are two reasons behind fixing its location on the particular element on the folding blade. Firstly, as the wing is semi-rigid, it can help to absorb energy during crashes, saving the motor and propeller from breaking, which may not be the case when the motor and propeller are placed at the wing tip. Secondly, due to the folding method, the motor can only be mounted on each folding element. The optimization considers a range of widths for each blade element, with the tip element being as small as 17 mm in width. It is too small to support the motor mount. It is observed that in the simulation, the craft spins faster during hover by about 11 rad s −1 . This is partially contributed by the body portion creating drag in real-life prototype which is not considered in the simulation. The wing components may also be generating more drag than predicted by blade element theory. In section 2.1, it was mentioned that F-SAM can fly in two configurations: the first is with battery fully folded (α = 0 • ), and the second is with the battery unfolded (α = 180 • ). In the experiments and results presented in this paper, F-SAM is flown with the first configuration. In separate tests with the second configuration, F-SAM flew with a mean rotation speed of 28.73 rad s −1 and mean power draw of 10.0 W, which is 15.1% slower rotation and 2.2% higher power draw. A slower rotation is generally undesirable as the wing performs less efficiently. Additionally, the integrity of the body portion during flight in this configuration relies on the compliant hinge and the centrifugal force from the battery component may stress and break the compliant hinge over time. The proportional stabilizer controller is introduced in this paper, in order to help F-SAM dynamic stability faster, producing faster response times during waypoint and trajectory control tests. The controller will be further analyzed in depth in a future work. In the accompanying supplementary video (https: //stacks.iop.org/BB/16/066019/mmedia), F-SAM is shown to be easily stored inside a small container, and it can be unfolded and flown within seconds. Dynamic stability of F-SAM also allows it to be handlaunched, without the need for closed-loop control. In future work, we may look into possible launching of F-SAM directly from the container, without the need for human intervention. Data availability statement The data that support the findings of this study are available upon reasonable request from the authors.
/** * Microservice for managing TestPlans. * * @since 1.0.0-SNAPSHOT */ @Path("/testplan") public class TestPlanAPI { TestPlanRunnerManager runnerManager = ApplicationDataHolder.getInstance().getRunnerManager(); @POST @Path("/add") @Consumes("application/json") @Produces("application/json") public TestPlanAddConfirmationDTO addTestPlan(AddTestPlanDTO plan) { String testId = this.runnerManager.addPlan(plan.getTestPlan()); Report report = null; if (plan.isRunNow()) { report = this.runnerManager.start(testId); } return new TestPlanAddConfirmationDTO(testId, report); } @OPTIONS @Path("/add") public Response getOptionsRunTestPlan() { return Response.status(Response.Status.OK).header("Access-Control-Allow-Methods", "POST,OPTIONS").build(); } @GET @Path("/run/{uuid}") @Produces("application/json") public Report startTestPlan(@PathParam("uuid") String uuid) { return this.runnerManager.start(uuid); } @GET @Path("/list/all") @Produces("application/json") public Map<String, TestPlanDTO> getAllTestPlans() { Map<String, TestPlanDTO> results = new HashMap<>(); this.runnerManager.getAllTests().forEach( (uuid, testPlan) -> results.put( uuid, new TestPlanDTO(uuid, testPlan, this.runnerManager.getAllReports(uuid)) ) ); return results; } @GET @Path("/callback") public Response processCallback(@QueryParam("code") String code) { this.runnerManager.setContextAttribute("auth_code", code); return Response.ok().type(MediaType.TEXT_HTML).entity("Done").build(); } }
def kbhit(): try: import msvcrt return msvcrt.kbhit() except ImportError: import select i, _, _ = select.select([sys.stdin], [], [], 0.0001) return sys.stdin in i
// Copyright 2020, Shulhan <<EMAIL>>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package asciidoctor import "fmt" type DocumentTitle struct { Main string Sub string el *element raw string sep byte } // // String return the combination of main and subtitle separated by colon or // meta "title-separator" value. // func (docTitle *DocumentTitle) String() string { if len(docTitle.Sub) > 0 { return fmt.Sprintf("%s%c %s", docTitle.Main, docTitle.sep, docTitle.Sub) } return docTitle.Main }
def remove_lrc(lrc_array=None,remove_lrc_array=None): joined_array= np.vstack([remove_lrc_array,lrc_array]) all_cells,uinds,uinv = unique_rows(joined_array,sort=False,return_inverse=True) uord = [(uinds==utemp).nonzero()[0][0] for utemp in np.sort(uinds)] repeated_inds = uord[remove_lrc_array.shape[0]:] keep_inds = uinds[repeated_inds]-remove_lrc_array.shape[0] return keep_inds
use super::{ any::Any, boolean::Boolean, byte_string::ByteString, function::Function, list::List, none::None, number::Number, record::Record, reference::Reference, union::Union, }; use position::Position; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] pub enum Type { Any(Any), Boolean(Boolean), Function(Function), List(List), None(None), Number(Number), Record(Record), Reference(Reference), String(ByteString), Union(Union), } impl Type { pub fn position(&self) -> &Position { match self { Self::Any(any) => any.position(), Self::Boolean(boolean) => boolean.position(), Self::Function(function) => function.position(), Self::List(list) => list.position(), Self::None(none) => none.position(), Self::Number(number) => number.position(), Self::Record(record) => record.position(), Self::Reference(reference) => reference.position(), Self::String(string) => string.position(), Self::Union(union) => union.position(), } } pub fn into_function(self) -> Option<Function> { match self { Type::Function(function) => Some(function), _ => None, } } pub fn into_list(self) -> Option<List> { match self { Type::List(list) => Some(list), _ => None, } } pub fn into_record(self) -> Option<Record> { match self { Type::Record(record) => Some(record), _ => None, } } pub fn is_any(&self) -> bool { matches!(self, Type::Any(_)) } pub fn is_function(&self) -> bool { matches!(self, Type::Function(_)) } pub fn is_list(&self) -> bool { matches!(self, Type::List(_)) } pub fn is_record(&self) -> bool { matches!(self, Type::Record(_)) } pub fn is_union(&self) -> bool { matches!(self, Type::Union(_)) } } impl From<Any> for Type { fn from(any: Any) -> Self { Self::Any(any) } } impl From<Boolean> for Type { fn from(boolean: Boolean) -> Self { Self::Boolean(boolean) } } impl From<ByteString> for Type { fn from(string: ByteString) -> Self { Self::String(string) } } impl From<Function> for Type { fn from(function: Function) -> Self { Self::Function(function) } } impl From<List> for Type { fn from(list: List) -> Self { Self::List(list) } } impl From<None> for Type { fn from(none: None) -> Self { Self::None(none) } } impl From<Number> for Type { fn from(number: Number) -> Self { Self::Number(number) } } impl From<Record> for Type { fn from(record: Record) -> Self { Self::Record(record) } } impl From<Reference> for Type { fn from(reference: Reference) -> Self { Self::Reference(reference) } } impl From<Union> for Type { fn from(union: Union) -> Self { Self::Union(union) } }
<reponame>addventa/rosaenlg /** * @license * Copyright 2019 <NAME> * SPDX-License-Identifier: Apache-2.0 */ import { Context, Callback } from 'aws-lambda'; import { S3RosaeContextsManager } from 'rosaenlg-server-toolkit'; import { createS3rosaeContextsManager, getUserID, corsHeaders } from './helper'; let s3rosaeContextsManager: S3RosaeContextsManager = null; exports.handler = function (event: any, _context: Context, callback: Callback): void { const user = getUserID(event); if (s3rosaeContextsManager == null) { s3rosaeContextsManager = createS3rosaeContextsManager(null, false); } const templateId: string = event.pathParameters.templateId; console.log({ user: user, templateId: templateId, action: 'delete', message: `start delete...` }); // we cannot delete in cache, as the cache is in another lambda s3rosaeContextsManager.deleteFromBackend(user, templateId, (err: Error) => { if (err) { const response = { statusCode: '204', headers: corsHeaders, body: err.message, }; callback(null, response); return; } else { const response = { statusCode: '204', headers: corsHeaders, }; callback(null, response); return; } }); };
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef mozilla_dom_InspectorUtils_h #define mozilla_dom_InspectorUtils_h #include "mozilla/dom/InspectorUtilsBinding.h" #include "mozilla/UniquePtr.h" #include "nsLayoutUtils.h" class nsAtom; class nsINode; class nsINodeList; class nsRange; namespace mozilla { class StyleSheet; namespace css { class Rule; } // namespace css namespace dom { class CharacterData; class Document; class Element; class InspectorFontFace; } // namespace dom } // namespace mozilla namespace mozilla::dom { class CSSStyleRule; /** * A collection of utility methods for use by devtools. */ class InspectorUtils { public: static void GetAllStyleSheets(GlobalObject& aGlobal, Document& aDocument, bool aDocumentOnly, nsTArray<RefPtr<StyleSheet>>& aResult); static void GetCSSStyleRules(GlobalObject& aGlobal, Element& aElement, const nsAString& aPseudo, bool aIncludeVisitedStyle, nsTArray<RefPtr<CSSStyleRule>>& aResult); /** * Get the line number of a rule. * * @param aRule The rule. * @return The rule's line number. Line numbers are 1-based. */ static uint32_t GetRuleLine(GlobalObject& aGlobal, css::Rule& aRule); /** * Get the column number of a rule. * * @param aRule The rule. * @return The rule's column number. Column numbers are 1-based. */ static uint32_t GetRuleColumn(GlobalObject& aGlobal, css::Rule& aRule); /** * Like getRuleLine, but if the rule is in a <style> element, * returns a line number relative to the start of the element. * * @param aRule the rule to examine * @return the line number of the rule, possibly relative to the * <style> element */ static uint32_t GetRelativeRuleLine(GlobalObject& aGlobal, css::Rule& aRule); static bool HasRulesModifiedByCSSOM(GlobalObject& aGlobal, StyleSheet& aSheet); static void GetAllStyleSheetCSSStyleRules( GlobalObject& aGlobal, StyleSheet& aSheet, nsTArray<RefPtr<css::Rule>>& aResult); // Utilities for working with CSS properties // // Returns true if the string names a property that is inherited by default. static bool IsInheritedProperty(GlobalObject& aGlobal, const nsACString& aPropertyName); // Get a list of all our supported property names. Optionally // property aliases included. static void GetCSSPropertyNames(GlobalObject& aGlobal, const PropertyNamesOptions& aOptions, nsTArray<nsString>& aResult); // Get a list of all properties controlled by preference, as well as // their corresponding preference names. static void GetCSSPropertyPrefs(GlobalObject& aGlobal, nsTArray<PropertyPref>& aResult); // Get a list of all valid keywords and colors for aProperty. static void GetCSSValuesForProperty(GlobalObject& aGlobal, const nsACString& aPropertyName, nsTArray<nsString>& aResult, ErrorResult& aRv); // Utilities for working with CSS colors static void RgbToColorName(GlobalObject& aGlobal, uint8_t aR, uint8_t aG, uint8_t aB, nsAString& aResult); // Convert a given CSS color string to rgba. Returns null on failure or an // InspectorRGBATuple on success. // // NOTE: Converting a color to RGBA may be lossy when converting from some // formats e.g. CMYK. static void ColorToRGBA(GlobalObject&, const nsACString& aColorString, const Document*, Nullable<InspectorRGBATuple>& aResult); // Check whether a given color is a valid CSS color. static bool IsValidCSSColor(GlobalObject& aGlobal, const nsACString& aColorString); // Utilities for obtaining information about a CSS property. // Get a list of the longhands corresponding to the given CSS property. If // the property is a longhand already, just returns the property itself. // Throws on unsupported property names. static void GetSubpropertiesForCSSProperty(GlobalObject& aGlobal, const nsACString& aProperty, nsTArray<nsString>& aResult, ErrorResult& aRv); // Check whether a given CSS property is a shorthand. Throws on unsupported // property names. static bool CssPropertyIsShorthand(GlobalObject& aGlobal, const nsACString& aProperty, ErrorResult& aRv); // Check whether values of the given type are valid values for the property. // For shorthands, checks whether there's a corresponding longhand property // that accepts values of this type. Throws on unsupported properties or // unknown types. static bool CssPropertySupportsType(GlobalObject& aGlobal, const nsACString& aProperty, InspectorPropertyType, ErrorResult& aRv); static bool Supports(GlobalObject&, const nsACString& aDeclaration, const SupportsOptions&); static bool IsIgnorableWhitespace(GlobalObject& aGlobalObject, CharacterData& aDataNode) { return IsIgnorableWhitespace(aDataNode); } static bool IsIgnorableWhitespace(CharacterData& aDataNode); // Returns the "parent" of a node. The parent of a document node is the // frame/iframe containing that document. aShowingAnonymousContent says // whether we are showing anonymous content. static nsINode* GetParentForNode(nsINode& aNode, bool aShowingAnonymousContent); static nsINode* GetParentForNode(GlobalObject& aGlobalObject, nsINode& aNode, bool aShowingAnonymousContent) { return GetParentForNode(aNode, aShowingAnonymousContent); } static void GetChildrenForNode(GlobalObject&, nsINode& aNode, bool aShowingAnonymousContent, bool aIncludeAssignedNodes, nsTArray<RefPtr<nsINode>>& aResult) { return GetChildrenForNode(aNode, aShowingAnonymousContent, aIncludeAssignedNodes, /* aIncludeSubdocuments = */ true, aResult); } static void GetChildrenForNode(nsINode& aNode, bool aShowingAnonymousContent, bool aIncludeAssignedNodes, bool aIncludeSubdocuments, nsTArray<RefPtr<nsINode>>& aResult); /** * Setting and removing content state on an element. Both these functions * call EventStateManager::SetContentState internally; the difference is * that for the remove case we simply pass in nullptr for the element. * Use them accordingly. * * When removing the active state, you may optionally also clear the active * document as well by setting aClearActiveDocument * * @return Returns true if the state was set successfully. See more details * in EventStateManager.h SetContentState. */ static bool SetContentState(GlobalObject& aGlobal, Element& aElement, uint64_t aState, ErrorResult& aRv); static bool RemoveContentState(GlobalObject& aGlobal, Element& aElement, uint64_t aState, bool aClearActiveDocument, ErrorResult& aRv); static uint64_t GetContentState(GlobalObject& aGlobal, Element& aElement); static void GetUsedFontFaces(GlobalObject& aGlobal, nsRange& aRange, uint32_t aMaxRanges, // max number of ranges to // record for each face bool aSkipCollapsedWhitespace, nsLayoutUtils::UsedFontFaceList& aResult, ErrorResult& aRv); /** * Get the names of all the supported pseudo-elements. * Pseudo-elements which are only accepted in UA style sheets are * not included. */ static void GetCSSPseudoElementNames(GlobalObject& aGlobal, nsTArray<nsString>& aResult); // pseudo-class style locking methods. aPseudoClass must be a valid // pseudo-class selector string, e.g. ":hover". ":any-link" and // non-event-state pseudo-classes are ignored. aEnabled sets whether the // psuedo-class should be locked to on or off. static void AddPseudoClassLock(GlobalObject& aGlobal, Element& aElement, const nsAString& aPseudoClass, bool aEnabled); static void RemovePseudoClassLock(GlobalObject& aGlobal, Element& aElement, const nsAString& aPseudoClass); static bool HasPseudoClassLock(GlobalObject& aGlobal, Element& aElement, const nsAString& aPseudoClass); static void ClearPseudoClassLocks(GlobalObject& aGlobal, Element& aElement); static bool IsElementThemed(GlobalObject& aGlobal, Element& aElement); static Element* ContainingBlockOf(GlobalObject&, Element&); MOZ_CAN_RUN_SCRIPT static already_AddRefed<nsINodeList> GetOverflowingChildrenOfElement( GlobalObject& aGlobal, Element& element); /** * Parse CSS and update the style sheet in place. * * @param DOMCSSStyleSheet aSheet * @param UTF8String aInput * The new source string for the style sheet. */ static void ParseStyleSheet(GlobalObject& aGlobal, StyleSheet& aSheet, const nsACString& aInput, ErrorResult& aRv); /** * Check if the provided name can be custom element name. */ static bool IsCustomElementName(GlobalObject&, const nsAString& aName, const nsAString& aNamespaceURI); }; } // namespace mozilla::dom #endif // mozilla_dom_InspectorUtils_h
/** * Option list used to perform the analysis by the DependencyDiscoverer * * @see DependencyDiscoverer */ public class DependencyDiscovererOptions { /** * The entry points of the user application (on the form a.b.C, a.b.*) */ private final ArrayList<String> entryPoints; /** * The classpath used to retrieve .class files */ @Nullable private String classpath; /** * The classpath where {@link #classpath} is compared against. * Optional. May be null. */ @Nullable private String againstClasspath; @Nullable private String outputFile; @Nullable private String outputType; /** * Constructor, only {@code entryPoints} list is initialized to prevent a * {@link NullPointerException} in the * {@link DependencyDiscovererOptions#addEntryPoint(String)} method. */ public DependencyDiscovererOptions(){ entryPoints = new ArrayList<>(); } /** * Adds the given entryPoint to the entryPoints list. * * @param name of the entryPoint to add */ public void addEntryPoint(String name){ entryPoints.add(name); } /** * Gets the entry points list. * * @return the entry points list. */ public List<String> getEntryPoints() { return entryPoints; } /** * * @param classpath path to the directory containing the jars to tests. * @param againstClasspath * @param outputFile name of the output file. * @param outputType type of the output file (list of accepted types in * the CLI description). * @param entryPoints list of entry points, added to the current list. */ public void setOptions(String classpath, String againstClasspath, String outputFile, String outputType, String entryPoints) { this.classpath = classpath; this.againstClasspath = againstClasspath; this.outputFile = outputFile; this.outputType = outputType; addEntryPoint(entryPoints); } /** * Gets the classpath. * * @return the classpath. */ public @Nullable String getClasspath() { return classpath; } /** * Gets the againstClasspath. * * @return the againstClasspath. */ public @Nullable String getAgainstClasspath() { return againstClasspath; } /** * Gets the outputFile. * * @return the outputFile. */ public @Nullable String getOutputFile() { return outputFile; } /** * Gets the outputType. * * @return the outputType. */ public @Nullable String getOutputType() { return outputType; } /** * Sets the classpath. * * @param classpath the classpath to set. */ public void setClasspath(String classpath) { this.classpath = classpath; } /** * Sets the againstClasspath. * * @param againstClasspath the againstClasspath to set. */ public void setAgainstClasspath(@Nullable String againstClasspath) { this.againstClasspath = againstClasspath; } /** * Sets the outputFile. * * @param outputFile the outputFile to set. */ public void setOutputFile(String outputFile) { this.outputFile = outputFile; } /** * Sets the outputType. * * @param outputType the outputType to set. */ public void setOutputType(String outputType) { this.outputType = outputType; } @Override public String toString() { String res = ""; res = res.concat("Classpath : " + this.classpath + "\n"); res = res.concat("AgainstClasspath : " + this.againstClasspath + "\n"); res = res.concat("Output file path : " + this.outputFile + "\n"); res = res.concat("Output type : " + this.outputType + "\n"); for (String entryPoint : this.entryPoints) { res = res.concat("EntryPoint : " + entryPoint + "\n"); } assert (res != null); return res; } }
import {Component, OnInit, OnDestroy, Inject, Optional} from '@angular/core'; import {Router} from '@angular/router'; import {NzMessageService} from 'ng-zorro-antd'; import {Jc} from '@core/jc'; @Component({ selector: 'app-index', templateUrl: './index.component.html', styleUrls: ['./index.component.less'], providers: [] }) export class IndexComponent implements OnInit{ constructor(public msg: NzMessageService) { } ngOnInit(): void { } startWork():void{ Jc.goTo("workbench",{queryParams:{a:1,b:2,c:new Date()}}); } }
25 KitchenAid Stand Mixer Tips & Troubleshooting Help 105 Comments Print Email 105 Comments I love my KitchenAid and although I haven’t had any problems with it yet (knock on wood), I decided to put together a page full of tips and tricks that I’ve bookmarked from around the web so I have them on hand “just in case”. So far there are basic maintenance solutions and fixes but I’ve also found a few neat ideas to try (such as shredding chicken, pulled pork, making homemade butter, etc.). If you’re a lucky duck who has an old workhorse mixer that just won’t quit (pre-1986) and it’s getting a bit beat up, you’ll find a tutorial for how to take it apart and repaint it so it looks shiny new again. Is there a goody I missed? Please feel free to share your experience in the comments section below. I’ll be adding more helpful ideas to this page as I find them so you may want to bookmark it for reference. PS: Don’t miss the appliance cover tutorials I have listed on this page, these will help keep the machine dust-free. And here’s how to do the famous Beater Level Test using a dime: (Source: cakecentral.com) Get a dime and a flat head screwdriver. With the bowl and beater in place, put the dime into the bowl. When the beater is turned onto the “Stir” setting, the beater should be moving the dime 1/4 inch per rotation. If it is not touching the dime, the beater needs to be adjusted. With the flat head screwdriver, turn the screw that is just to the left of the mix handle 1/4 turn counter clockwise and retest. May have to test more than once before it’s fixed. Good luck and I hope these tips helped get things fixed and running smoothly again for you!
/*** * The Movie class is designed for the video rental business. * The class track the information of each movie of Title Name, * Rate, ID Number, and it has the calculate the late fee. * The class is also the base class for other Derived class like * Action , Comedy , Drama and etc, which has a different late fee. * * Century College, CSCI 1082 Spring 2018. * Movie.java, Programming Assignment 04. * @author (Ping) Nalongsone Danddank * @version 1.0 * @since 03/20/2018 ***/ public abstract class Movie { //Initiate private variables. private String rateMPAA; private String id; private String title; //Default constructor. public Movie() { this("X", "X0000", "No name"); } //Initiate constructor with values. public Movie(String rateMPAA, String id, String title) { this.rateMPAA = rateMPAA; this.id = id; this.title = title; } //Accessor method to get rate MPAA. public String getRateMPAA() { return rateMPAA; } //Mutator method to set rate MPAA. public void setRateMPAA(String rateMPAA) { //if user input nothing, //display message and exit the program. if(rateMPAA == null){ System.out.println("Input Invalid Name!\n"); System.exit(0); } this.rateMPAA = rateMPAA; } //Accessor method to get ID number. public String getId() { return id; } //Mutator method to set Id. public void setId(String id) { //if user input nothing, //display message and exit the program. if(id == null){ System.out.println("Input Invalid Name!\n"); System.exit(0); } this.id = id; } //Accessor method to get title name. public String getTitle() { return title; } //Mutator method to set title movie name. public void setTitle(String title) { //if user input nothing, //display message and exit the program. if(title == null){ System.out.println("Input Invalid Name!\n"); System.exit(0); } this.title = title; } //This abstract method uses for another class have to //To calculate the late fee that over 3 day. //The default late fee is $2/day. public abstract double calcLateFees (int numberOfDay); @Override //display the information of the Movie. public String toString() { return "\nThe movie title: " + title + "\nThe MPAA rated: " + rateMPAA + "\nID number: " + id ; } @Override //To compare two movie class type. public boolean equals(Object obj) { if(!(obj instanceof Movie)) return false; Movie movie = (Movie) obj; if (getId().equals(movie.getId())) return true; return false; } }
/** * Copy a pool and all questions * * @param context * The destination context. * @param pool * The source pool. * @param asHistory * If set, make the pool and questions all historical. * @param oldToNew * A map, which, if present, will be filled in with the mapping of the source question id to the destination question id for each question copied. * @param appendTitle * if true, append text to the title, else leave the title an exact copy. * @param attachmentTranslations * A list of Translations for attachments and embedded media. * @param merge * if true, if there is an existing pool with the same title, use it and don't create a new pool. * @param includeQuestions * if not null, only import the pool's question if its id is in the set. * @return The copied pool. */ protected Pool doCopyPool(String context, Pool pool, boolean asHistory, Map<String, String> oldToNew, boolean appendTitle, List<Translation> attachmentTranslations, boolean merge, Set<String> includeQuestions) { String userId = sessionManager.getCurrentSessionUserId(); Date now = new Date(); Pool rv = null; if (merge && (!asHistory)) { List<Pool> pools = getPools(context); for (Pool existingPool : pools) { if (!StringUtil.different(existingPool.getTitle(), pool.getTitle())) { rv = existingPool; break; } } } if (rv == null) { rv = storage.clone((PoolImpl) pool); ((PoolImpl) rv).id = null; rv.setContext(context); rv.getCreatedBy().setDate(now); rv.getCreatedBy().setUserId(userId); rv.getModifiedBy().setDate(now); rv.getModifiedBy().setUserId(userId); if (appendTitle) { rv.setTitle(addDate("copy-text", rv.getTitle(), now)); } rv.setDescription(this.attachmentService.translateEmbeddedReferences(rv.getDescription(), attachmentTranslations)); ((PoolImpl) rv).clearChanged(); storage.savePool((PoolImpl) rv); } this.questionService.copyPoolQuestions(pool, rv, asHistory, oldToNew, attachmentTranslations, merge, includeQuestions); if (asHistory) { ((PoolImpl) rv).makeHistorical(rv); storage.savePool((PoolImpl) rv); } else { eventTrackingService.post(eventTrackingService.newEvent(MnemeService.POOL_NEW, getPoolReference(rv.getId()), true)); } return rv; }
<filename>Development/dotnetshell/IntegratedBuildHTML/HTMLViewer/bin/x86/Debug/dist_orig/app/activity/activity.component.ts import { Component , OnInit} from '@angular/core'; import { ActivatedRoute,Router } from '@angular/router'; import {SharedService} from '../shared.service'; import 'jquery'; declare var $: any; @Component({ selector: 'my-activity', template: require('./activity.component.html'), styles: [require('./activity.component.css')] }) export class ActivityComponent implements OnInit{ constructor(private router: Router, private route: ActivatedRoute,private _sharedService: SharedService) {} optionslist=this._sharedService.navigatetoroute.data[0].optionslist; optionslist_duplicate=this._sharedService.navigatetoroute.data[0].optionslist_duplicate; myoption = this.optionslist[0]; myoption_duplicate = this.optionslist_duplicate[0]; currentIdx = 0; previous(){ if( this.currentIdx > 0) { this.currentIdx--; this.myoption = this.optionslist[this.currentIdx]; this.myoption_duplicate = this.optionslist_duplicate[this.currentIdx]; } } next(){ if( this.currentIdx < (this.optionslist.length-1)) { this.currentIdx++; this.myoption = this.optionslist[this.currentIdx]; this.myoption_duplicate = this.optionslist_duplicate[this.currentIdx]; } } id: number; styles = {}; isaudio = false; audio =new Audio(); selected(option) { if(option.correct1 == true){ this._sharedService.scoreData(10); console.log('Data sent of score',this._sharedService.Activity_Score); } else{ this._sharedService.scoreData(0); console.log('Data sent of score',this._sharedService.Activity_Score); } this.audio.src = option.sound; this.audio.load(); this.audio.play(); this.myoption[0].hideElement = false; this.myoption[1].hideElement = false; this.myoption[2].hideElement = false; option.hideElement= true; } clicked0(event) { var audio = new Audio(); audio.src = this.myoption_duplicate[0].path; if(this.myoption_duplicate[0].path =="null" && this._sharedService.navigatetoroute.type== 1){ this._sharedService.activityfinished(); } audio.load(); audio.play(); } ngOnInit() { this.route.params.subscribe(params => { this.id = +params['id']; // (+) converts string 'id' to a number console.log(this.id) }); } }
// Register adds a new scannable service to the registry. func Register(id string, newFunc interface{}, iface svcIface, roots ...interface{}) struct{} { name := reflect.TypeOf(newFunc).Out(0).String() name = name[1:strings.IndexByte(name, '.')] svcRegistry.register(name, id, newFunc, iface, roots) return struct{}{} }
package com.yntovi.base; import com.baomidou.mybatisplus.extension.activerecord.Model; /** * 抽象实体类:无公共字段 * * @author fanglei * @date 2021/07/28 15:26 **/ public abstract class CommonModel<T extends Model<?>> extends Model<T> { }
/** * Html base class for test reports and links */ public class TestReport extends Report { /** * */ private static final long serialVersionUID = -3105616111390882858L; private Object message = null; private boolean isStatement = false; public TestReport(){ super(); } public TestReport(String title, String message, int isSuccess, boolean bold, boolean ignore) { super(title, isSuccess, bold); this.message = message; this.ignore = ignore; this.cssClass = "test_report"; } public TestReport(String title, String message, int isSuccess, boolean bold, boolean ignore, String directory) { this(title,message,isSuccess,bold,ignore); this.directory = directory; } public TestReport(String title, String message, int isSuccess, boolean bold, boolean ignore, String directory,String cssClass) { this(title,message,isSuccess,bold,ignore,directory); this.cssClass = cssClass; } public void toFile(NameGenerator generator) throws IOException { if (getMessage() != null) { StringBuffer toFile = new StringBuffer(); if (String.valueOf(getMessage()).indexOf("!DOCTYPE HTML") >= 0 || isHtmlMessage()) { toFile.append(String.valueOf(getMessage())); } else { // Add css for pass\fail toFile.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"); toFile.append("<html><head>"); toFile.append(CssUtils.cssPropertyToHtmlHeader(getDirectory()!=null)); toFile.append("</head><body class=\""); toFile.append(getCssClassCanonicalValue()); toFile.append("\"><FONT face=\"Courier New\" size=2>"); toFile.append(StringUtils.toHtmlString(String.valueOf(getMessage()))); toFile.append("</FONT></body></html>"); } if (fileName == null) { fileName = generator.getName(); } String baseDir; if (directory == null) { baseDir = logDirectory; } else { baseDir = logDirectory + File.separator + directory; } File listFile = new File(baseDir, fileName); listFile.getParentFile().mkdirs(); if (!listFile.getParentFile().exists()) { log.log(Level.INFO, "Fail to create log directory: " + listFile.getParent()); } BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(listFile),"UTF-8")); bw.write(toFile.toString().toCharArray()); bw.flush(); bw.close(); bw = null; } setChangedStatus(isSuccess); updateParents(generator); } public void setMessage(String message) { this.message = message; } public Object getMessage() { return message; } public boolean isStatement() { return isStatement; } public void setStatement(boolean statement) { isStatement = statement; } }
from operator import attrgetter import simple_switch_13 from ryu.controller import ofp_event from ryu.controller.handler import MAIN_DISPATCHER, DEAD_DISPATCHER from ryu.controller.handler import set_ev_cls from ryu.lib import hub import socket import threading import SocketServer import subprocess import logging # Logging configuration logging.basicConfig(level=logging.DEBUG) logging.getLogger().setLevel(logging.INFO) logging.getLogger("ofp_event").setLevel(logging.WARNING) # logging.getLogger().addHandler(logging.StreamHandler()) # Receiving requests and passing them to a controller method, # which handles the request class RequestHandler(SocketServer.BaseRequestHandler): # Set to the handle method in the controller thread handler = None def handle(self): data = self.request.recv(1024) RequestHandler.handler(data) # Simple TCP server spawning new thread for each request class Server(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass # Client for sending messages to a server class Client: # Initialize with IP + Port of server def __init__(self, ip, port): self.ip = ip self.port = port # Send an arbitrary message given as a string # Starts a new thread for sending each message. def send(self, message): def do(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.ip, self.port)) try: sock.sendall(message) response = sock.recv(1024) finally: sock.close() thread = threading.Thread(target=do) thread.daemon = True thread.start() # The main controller script, extends the already exisiting # ryu script simple_switch_13 class SimpleMonitor(simple_switch_13.SimpleSwitch13): # Interval for polling switch statistics QUERY_INTERVAL = 2 # Bandwith threshold in Kbit/s for assuming an attack # on a port ATTACK_THRESHOLD = 1000 # Bandwith threshold in Kbit/s for assuming that the # attack has stopped after applying an ingress policy PEACE_THRESHOLD = 10 # Number of repeated poll statistics measurements to # assume that the judgement on either "attack over" # "host under DDoS attack" is correct. SUSTAINED_COUNT = 5 # Threshold of number of repeated polls to remove egress and apply ingress EGRESS_THRESHOLD = 20 # Specifies if polled switch statistics should reported on stout REPORT_STATS = True def __init__(self, *args, **kwargs): # Monitoring super(SimpleMonitor, self).__init__(*args, **kwargs) # Set of currently known (assumed) attackers self.attackers = set() # Sustained counts for the above judgements self.sustainedAttacks, self.sustainedPushbackRequests = 0, 0 # Indicates for each switch to which of its ports we applied an ingress policy self.ingressApplied = {"s1": [False, False, False], "s11": [False, False, False], "s12": [False, False, False], "s21": [False, False, False], "s22": [False, False, False], "s2": [False, False, False]} # Sustained no attack count for switch/port combinations self.noAttackCounts = {"s1": [0] * 3, "s11": [0] * 3, "s12": [0] * 3, "s21": [0] * 3, "s22": [0] * 3, "s2": [0] * 3} # Mapping from switch/port/destination MAC addresses to flow rates self.rates = {"s1": [{}, {}, {}], "s11": [{}, {}, {}], "s12": [{}, {}, {}], "s2": [{}, {}, {}], "s21": [{}, {}, {}], "s22": [{}, {}, {}]} # Mapping from switches and ports to # attached switchtes/hosts self.portMaps = {"s1": ["s11", "s12", "s2"], "s11": ["AAh1", "AAh2", "s1"], "s12": ["ABh1", "ABh2", "s1"], "s21": ["BAh1", "BAh2", "s2"], "s22": ["BBh1", "BBh2", "s2"], "s2": ["s21", "s22", "s1"]} # Mapping from datapath ids to switch names self.dpids = {0x1: "s1", 0xb: "s11", 0xc: "s12", 0x2: "s2", 0x15: "s21", 0x16: "s22"} # Storing which switches egress has been applied to, along with a count # and set of attackers which caused the egress self.egressApplied = {"s21": [False, set(), 0], "s22": [False, set(), 0]} # Flow datapaths identified by statistics polling self.datapaths = {} # Last acquired byte counts for each FLOW # to calculate deltas for bandwith usage calculation self.flow_byte_counts = {} # Last acquired byte counts for each PORT # to calculate deltas for bandwith usage calculation self.port_byte_counts = {} # Thread for polling flow and port statistics self.monitor_thread = hub.spawn(self._monitor) # Pushback state # Set of hosts, which we suspect to be victims of an attack originating # in the other network self.pushbacks = set() # Set of hosts in other domain to which we were reported an attack self.other_victims = set() ########################################### # Server Code ########################################### # Lock for the set of victims reported by the other server self.lock = threading.Lock() # IP + PORT for the TCP Server on this controller ip, port = "localhost", 2001 # IP + PORT for the TCP Server on the other controller ip_other, port_other = "localhost", 2000 # Handler for incoming requests to the server RequestHandler.handler = self.handlePushbackMessage # Server instance self.server = Server((ip, port), RequestHandler) # Initiate server thread server_thread = threading.Thread(target=self.server.serve_forever) # Server thread will terminate when controller terminates server_thread.daemon = True server_thread.start() # Start client for sending pushbacks to the other server self.client = Client(ip_other, port_other) # Handler receipt of a pushback message def handlePushbackMessage(self, data): victim = data.strip()[len("Pushback attack to "):] print("Received pushback message for victim: %s" % victim) # Avoid race conditions for pushback messages self.lock.acquire() try: self.other_victims.add(victim) finally: self.lock.release() ########################################### # Monitoring Code ########################################### # Handler for registering new datapaths # Taken from http://osrg.github.io/ryu-book/en/html/traffic_monitor.html @set_ev_cls(ofp_event.EventOFPStateChange, [MAIN_DISPATCHER, DEAD_DISPATCHER]) def _state_change_handler(self, ev): datapath = ev.datapath if ev.state == MAIN_DISPATCHER: if not datapath.id in self.datapaths: # logging.debug('register datapath: %016x', datapath.id) self.datapaths[datapath.id] = datapath elif ev.state == DEAD_DISPATCHER: if datapath.id in self.datapaths: # logging.debug('unregister datapath: %016x', datapath.id) del self.datapaths[datapath.id] # Main function of the monitoring thread # Simply polls switches for statistics # in the interval given by QUERY_INTERVAL def _monitor(self): while True: for dp in self.datapaths.values(): self._request_stats(dp) hub.sleep(SimpleMonitor.QUERY_INTERVAL) # Helper function for polling statistics of a datapath # Again, taken from http://osrg.github.io/ryu-book/en/html/traffic_monitor.html def _request_stats(self, datapath): # logging.debug('send stats request: %016x', datapath.id) ofproto = datapath.ofproto parser = datapath.ofproto_parser req = parser.OFPFlowStatsRequest(datapath) datapath.send_msg(req) req = parser.OFPPortStatsRequest(datapath, 0, ofproto.OFPP_ANY) datapath.send_msg(req) # Handler for receipt of flow statistics # Main entry point for our DDoS detection code. @set_ev_cls(ofp_event.EventOFPFlowStatsReply, MAIN_DISPATCHER) def _flow_stats_reply_handler(self, ev): domainHosts = ['0b:0a:00:00:00:01', '0b:0a:00:00:00:02', '0b:0b:00:00:00:01', '0b:0b:00:00:00:02'] # The (suspected) set of victims identified by the statistics victims = set() body = ev.msg.body # Get id of datapath for which statistics are reported as int dpid = int(ev.msg.datapath.id) switch = self.dpids[dpid] if SimpleMonitor.REPORT_STATS: print "-------------- Flow stats for switch", switch, "---------------" # Iterate through all statistics reported for the flow for stat in sorted([flow for flow in body if flow.priority == 1], key=lambda flow: (flow.match['in_port'], flow.match['eth_dst'])): # Get in and out port + MAC dest of flow in_port = stat.match['in_port'] out_port = stat.instructions[0].actions[0].port eth_dst = stat.match['eth_dst'] # Check if we have a previous byte count reading for this flow # and calculate bandwith usage over the last polling interval key = (dpid, in_port, eth_dst, out_port) rate = 0 if key in self.flow_byte_counts: cnt = self.flow_byte_counts[key] rate = self.bitrate(stat.byte_count - cnt) self.flow_byte_counts[key] = stat.byte_count if SimpleMonitor.REPORT_STATS: print "In Port %8x Eth Dst %17s Out Port %8x Bitrate %f" % (in_port, eth_dst, out_port, rate) # Save the bandwith calculated for this flow self.rates[switch][in_port - 1][str(eth_dst)] = rate # If we find the bandwith for this flow to be higher than # the provisioned limit, we mark the corresponding # host as potential vicitim if rate > SimpleMonitor.ATTACK_THRESHOLD: self.noAttackCounts[switch][in_port - 1] = 0 victim = str(eth_dst) if victim in domainHosts: # if not in domain, ignore it. Will be handled by pushback requests. victims.add(victim) # Calculate no sustained attack counts for port in range(len(self.ingressApplied[switch])): if not self.ingressApplied[switch][port]: continue # If ingress is not applied, skip # If rate for all flows on the links is below safe level, # increase the sustained no attack count for this link if all(x <= SimpleMonitor.PEACE_THRESHOLD for x in self.rates[switch][port].values()): self.noAttackCounts[switch][port] += 1 else: self.noAttackCounts[switch][port] = 0 victims = victims.intersection({'0a:0a:00:00:00:01', '0a:0a:00:00:00:02'}) # only consider the protected hosts # Handle pushback requests from the other host self.dealWithPushbackRequests() # Identify the set of victims attacked by hosts located in the other domain # and directly apply policies to the attackers in the local domain pushbacks = self.dealWithAttackers(victims) if pushbacks == self.pushbacks and len(pushbacks) > 0: # Send pushback messages self.sustainedPushbackRequests += 1 logging.debug("Sustained Pushback Count %s" % str(self.sustainedPushbackRequests)) if self.sustainedPushbackRequests > SimpleMonitor.SUSTAINED_COUNT: for victim in pushbacks: self.client.send("Pushback attack to " + victim) self.sustainedPushbackRequests = 0 elif len(pushbacks) > 0: self.sustainedPushbackRequests = 0 self.pushbacks = pushbacks for switch in self.egressApplied: if self.egressApplied[switch][0]: self.egressApplied[switch][2] += 1 if self.egressApplied[switch][2] > SimpleMonitor.EGRESS_THRESHOLD: self.removeEgress(switch) self.checkForIngressRemoval( victims) # If there are no victims, for a sustained duration, try remove ingress policies if SimpleMonitor.REPORT_STATS: print "--------------------------------------------------------" # Handle pushback requests issued by the controller in the other domain def dealWithPushbackRequests(self): victims = set() # Avoid race conditions pertaining to pushbacks self.lock.acquire() try: victims = self.other_victims self.other_victims = set() finally: self.lock.release() for victim in victims: # Identify attackers for the victims victimAttackers = self.getAttackers(victim) for victimAttacker in victimAttackers: attackerSwitch, _ = self.getSwitch(victimAttacker) print ("Responding to pushback request, applying egress on %s" % attackerSwitch) self.applyEgress(victimAttacker) # Identify the set of victims attacked by hosts located in the other domain # and directly apply policies to the attackers in the local domain def dealWithAttackers(self, victims): # Set of victims attacked by the other domain pushbacks = set() # Set of attackers in the local domain attackers = set() for victim in victims: victimHost, victimSwitch, victimPort = self.getVictim(victim) print ( "Identified victim: MAC %s Host %s Switch %s Port %s" % (victim, victimHost, victimSwitch, victimPort)) victimAttackers = self.getAttackers(victim) print ("Attackers for vicim %s: %s" % (victimAttackers, victimHost)) if not victimAttackers: # No attackers identified, thus assume it's originating in the other domain pushbacks.add(victim) else: attackers = attackers.union(victimAttackers) # Increase the count for confidence in a suspected attack # by the identifed attacker set if applicable if len(attackers) > 0: self.sustainedAttacks += 1 logging.debug("Sustained Attack Count %s" % self.sustainedAttacks / 3) elif len(attackers) == 0: self.sustainedAttacks = 0 # If we have exceeded the confidence count for the local attacker # set, apply ingress policies to all attackers if self.sustainedAttacks / 3 > SimpleMonitor.SUSTAINED_COUNT: for attacker in self.attackers: self.applyIngress(attacker) return pushbacks # Check if the ingress policy should be removed for any port def checkForIngressRemoval(self, victims): self.sustainedAttacks = 0 # If the confidence count for no ongoing attack exceeds the provisioned limit # check if the bandwith consumption on one of the rate-limited links # dropped below a "safe" level and remove ingress policy for switch in self.ingressApplied: # Iterate through all switches/ports for port in range(len(self.ingressApplied[switch])): # If rate for all flows on the links for this port have been below a safe level # for the last couple of statistic readings, remove the ingress policy if self.noAttackCounts[switch][port] >= self.SUSTAINED_COUNT and self.ingressApplied[switch][port]: self.removeIngress(self.portMaps[switch][port]) # Apply ingress to a given attacker's switch/port def applyIngress(self, attacker, shouldApply=True): attackerSwitch, attackerPort = self.getSwitch(attacker) if self.ingressApplied[attackerSwitch][int(attackerPort) - 1] == shouldApply: return ingressPolicingBurst, ingressPolicingRate = "ingress_policing_burst=0", "ingress_policing_rate=0" if shouldApply: self.noAttackCounts[attackerSwitch][int(attackerPort) - 1] = 0 print("Applying ingress filters on %s, on switch %s at port %s" % (attacker, attackerSwitch, attackerPort)) ingressPolicingBurst, ingressPolicingRate = "ingress_policing_burst=100", "ingress_policing_rate=40" else: print("Removing ingress filters on %s, on switch %s at port %s" % (attacker, attackerSwitch, attackerPort)) subprocess.call( ["sudo", "ovs-vsctl", "set", "interface", attackerSwitch + "-eth" + attackerPort, ingressPolicingBurst]) subprocess.call( ["sudo", "ovs-vsctl", "set", "interface", attackerSwitch + "-eth" + attackerPort, ingressPolicingRate]) self.ingressApplied[attackerSwitch][int(attackerPort) - 1] = shouldApply # Remove ingress on a given attacker's switch/port def removeIngress(self, attacker): self.applyIngress(attacker, False) # Apply egress to the attacker's switch's outgoing port (connected to s2) def applyEgress(self, attacker): attackerSwitch, attackerPort = self.getSwitch(attacker) self.egressApplied[attackerSwitch][1].add(self.portMaps[attackerSwitch][int(attackerPort) - 1]) if self.egressApplied[attackerSwitch][0]: return egressCommand = ["sudo", "ovs-vsctl", "--", "set", "Port", attackerSwitch + "-eth3", "qos=@newqos", "--", "--id=@newqos", "create", "QoS", "type=linux-htb", "queues=0=@q0", "--", "--id=@q0", "create", "Queue", "other-config:max-rate=40000"] subprocess.call(egressCommand) self.egressApplied[attackerSwitch][0] = True self.egressApplied[attackerSwitch][2] = 0 # Removes egress to the attacker's switch's outgoing port, and also calls # applyIngress(attacker) to immediately apply ingress to that attacker def removeEgress(self, attackerSwitch): if not self.egressApplied[attackerSwitch]: return subprocess.call(["sudo", "ovs-vsctl", "--", "clear", "port", attackerSwitch + "-eth3", "qos"]) subprocess.call(["sudo", "ovs-vsctl", "--", "--all", "destroy", "QoS", "--", "--all", "destroy", "Queue"]) self.egressApplied[attackerSwitch][0] = False self.egressApplied[attackerSwitch][2] = 0 for attacker in self.egressApplied[attackerSwitch][1]: self.applyIngress(attacker) self.egressApplied[attackerSwitch][1] = set() # Gets the victim's switch and port it is connected to def getVictim(self, victim): victimHost = victim[1].upper() + victim[4].upper() + "h" + victim[16] for switch in self.portMaps: for port in range(len(self.portMaps[switch])): if self.portMaps[switch][port] == victimHost: return victimHost, switch, str(port + 1) # Gets the local attackers of a victim def getAttackers(self, victim): attackers = set() for switch in self.rates: for port in range(len(self.rates[switch])): if victim not in self.rates[switch][port]: continue if self.rates[switch][port][victim] > SimpleMonitor.ATTACK_THRESHOLD: attacker = self.portMaps[switch][port] if not self.isSwitch(attacker): attackers.add(attacker) return attackers @staticmethod def isSwitch(victim): return victim[0] == "s" def getSwitch(self, node): for switch in self.portMaps: if node in self.portMaps[switch]: return switch, str(self.portMaps[switch].index(node) + 1) # Convert from byte count delta to bitrate @staticmethod def bitrate(bytes): return bytes * 8.0 / (SimpleMonitor.QUERY_INTERVAL * 1000) # Handle receipt of port traffic statistics @set_ev_cls(ofp_event.EventOFPPortStatsReply, MAIN_DISPATCHER) def _port_stats_reply_handler(self, ev): body = ev.msg.body for stat in sorted(body, key=attrgetter('port_no')): key = (ev.msg.datapath.id, stat.port_no) rx_bitrate, tx_bitrate = 0, 0 if key in self.port_byte_counts: cnt1, cnt2 = self.port_byte_counts[key] rx_bitrate = self.bitrate(stat.rx_bytes - cnt1) tx_bitrate = self.bitrate(stat.tx_bytes - cnt2) self.port_byte_counts[key] = (stat.rx_bytes, stat.tx_bytes)
#include<cstdio> #include<cmath> #include<cstring> #include<iostream> #include<algorithm> #include<vector> #include<queue> using namespace std; typedef long long ll; int main() { int a,b,c,d; scanf("%d%d%d%d",&a,&b,&c,&d); if(a<c||b<c||a<d||b<d) { printf("-1\n"); return 0; } if(c>=d) { if(d<c-1) { printf("-1\n"); } else if(d==c-1) { for(int i=0;i<a-c;i++) printf("4"); for(int i=0;i<c;i++) printf("47"); for(int i=0;i<b-c;i++) printf("7"); printf("\n"); } else if(d==c&&c!=0) { if(a>c&&b>=c){ for(int i=0;i<a-c-1;i++) printf("4"); for(int i=0;i<c;i++) printf("47"); for(int i=0;i<b-c;i++) printf("7"); printf("4"); printf("\n"); } else if(a==c&&b>c) { printf("7");; for(int i=0;i<a-c;i++) printf("4"); for(int i=0;i<c;i++) printf("47"); for(int i=0;i<b-c-1;i++) printf("7"); printf("\n"); } else printf("-1\n"); } else printf("-1\n"); } else { if(c<d-1) { printf("-1\n"); } else { printf("7"); for(int i=0;i<a-d;i++) cout<<'4'; cout<<'4'; for(int i=0;i<d-2;i++) cout<<"74"; if(d>1)cout<<'7'; for(int i=0;i<b-d;i++) cout<<'7'; if(d>1) cout<<'4'; } } }
#include <bits/stdc++.h> using namespace std; #define pb push_back #define mp make_pair typedef long long ll; typedef vector<int> vi; typedef vector<vi> vvi; #define sz(c) (int)(c).size() #define ALL(c) (c).begin(), (c).end() void solve (int tp) { assert(tp == 12 || tp == 24); string tm; cin >> tm; assert(sz(tm) == 5 && tm[2] == ':'); int bst = 10; string ans = ""; for (int rm = 0; rm < 60; rm++) { int l = (tp == 12 ? 1 : 0); int r = (tp == 12 ? 13 : 24); for (int rh = l; rh < r; rh++) { string cur; cur += (rh / 10) + '0'; cur += (rh % 10) + '0'; cur += ':'; cur += (rm / 10) + '0'; cur += (rm % 10) + '0'; int cnt = 0; for (int i = 0; i < 5; i++) cnt += (cur[i] != tm[i]); if (cnt < bst) bst = cnt, ans = cur; } } cout << ans << endl; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "rt", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(0); int n; while (cin >> n) solve(n); }
<filename>src/runtime_src/core/common/module_loader.h /** * Copyright (C) 2016-2020 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #ifndef xrtcore_util_module_loader_h_ #define xrtcore_util_module_loader_h_ // This file contains a loader utility class for plugin modules // that are loaded from either OpenCL or XRT level applications. #include <functional> #include <string> #include "core/common/config.h" namespace xrt_core { /** * This class is responsible for loading a plugin module from the * appropriate directory under the XILINX_XRT installation. The * loading happens at object construction time, so the XRT side * implementation should contain a function that instantiates a single * static instance of this class to handle the loading of a module * once in a thread safe manner. */ class module_loader { public: /** * module_loader() - Open a plugin module at runtime * * @plugin_name : The name of the plugin (without prefix or extension) * @registration_function : A function responsible for connecting * plugin functionality with XRT callback functions via dlsym * @warning_function : A function that will issue warnings specific to * the plugin after the plugin has been loaded * @error_function : A function that will check preconditions before loading * the plugin and halt the loading if an error condition is detected * * A module is used only for runtime loading using dlopen. * */ XRT_CORE_COMMON_EXPORT module_loader(const std::string& plugin_name, std::function<void (void*)> registration_function, std::function<void ()> warning_function, std::function<int ()> error_function = nullptr); }; /** * Load XRT core library at runtime */ class shim_loader { public: /** * shim_loader() - Load a versioned core XRT library * * The shim library is the XRT core library. The actual library * loaded at runtime depends on XCL_EMULATION_MODE set or not. * * The shim library is also a link library and as such located * in the $XILINX_XRT/lib folder. This function loads the * versioned core XRT library. */ XRT_CORE_COMMON_EXPORT shim_loader(); }; } // end namespace xrt_core #endif
<gh_stars>1-10 import React from "react"; import { IonPage, IonContent, IonItem, IonLabel, IonHeader, IonTitle, IonToolbar, isPlatform, IonCard, IonCol, IonGrid, IonRow, IonThumbnail, } from "@ionic/react"; import { PageHeader, AndroidBackButtonExit } from "../../components"; const About: React.FC = () => { return ( <IonPage> {isPlatform("android") && <AndroidBackButtonExit />} <PageHeader title="About" /> <IonContent fullscreen> <IonHeader collapse="condense"> <IonToolbar> <IonTitle size="large">About</IonTitle> </IonToolbar> </IonHeader> <IonGrid> <IonRow> <IonCol> <IonCard> <IonItem lines="none"> <IonThumbnail slot="start"> <img src="/assets/icon/icon.png" alt="logo" /> </IonThumbnail> <IonLabel> <h1>GeoNode Mobile Client</h1> by{" "} <a href="http://cartologic.com/">Cartologic</a> </IonLabel> </IonItem> </IonCard> </IonCol> </IonRow> </IonGrid> </IonContent> </IonPage> ); }; export default About;
""" =============================================== DL8.5 classifier : python side iterative search =============================================== Iterative search is the idea that the algorithm starts with finding an optimal shallow tree, and then uses the quality of this tree to bound the quality of deeper trees. This class shows how to perform this type of search by repeatedly calling the DL8.5 algorithm. A second implementation is illustrated in plot_classifier_iterative_c_plus.py, and uses C++. """ import numpy as np from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import time from pydl85 import DL85Classifier dataset = np.genfromtxt("../datasets/anneal.txt", delimiter=' ') X, y = dataset[:, 1:], dataset[:, 0] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) print("###########################################################################\n" "# DL8.5 default classifier using python-based iterative search #\n" "###########################################################################") start = time.perf_counter() error = 0 # default max error value expressing no bound clf = None remaining_time = 600 for i in range(1, 3): # max depth = 2 clf = DL85Classifier(max_depth=i, max_error=error, time_limit=remaining_time) clf.fit(X_train, y_train) error = clf.error_ remaining_time -= clf.runtime_ duration = time.perf_counter() - start print("Model built. Duration of building =", round(duration, 4)) y_pred = clf.predict(X_test) print("Confusion Matrix below") print(confusion_matrix(y_test, y_pred)) print("Accuracy DL8.5 on training set =", round(clf.accuracy_, 4)) print("Accuracy DL8.5 on test set =", round(accuracy_score(y_test, y_pred), 4))
from itertools import chain import logging from flask import redirect, request, url_for, flash from flask_admin import BaseView, expose from flask_mail import Message from flask_wtf import Form from wtforms import ( StringField, TextAreaField, validators, HiddenField, BooleanField, SelectMultipleField, ) from wtforms.widgets import CheckboxInput from wtforms.fields.html5 import EmailField from sqlalchemy.orm import lazyload from sqlalchemy.sql.expression import distinct from sqlalchemy.sql.functions import count from pmg.models import ( EmailTemplate, User, Committee, user_committee_alerts, CommitteeMeeting, db, ) from pmg.models.emails import send_sendgrid_email from .rbac import RBACMixin log = logging.getLogger(__name__) class EmailAlertView(RBACMixin, BaseView): required_roles = ["editor"] @expose("/") def index(self): templates = db.session.query(EmailTemplate).order_by(EmailTemplate.name).all() return self.render("admin/alerts/index.html", templates=templates) @expose("/new", methods=["GET", "POST"]) def new(self): template = None if request.values.get("template_id"): template = db.session.query(EmailTemplate).get( request.values.get("template_id") ) if not template: return redirect(url_for("alerts.index")) form = EmailAlertForm(obj=template) form.template_id.data = form.template_id.data or template.id # pull in some values from the querystring for field in ("committee_meeting_id",): if field in request.args: getattr(form, field).data = request.args[field] if "committee_ids" in request.args: form.committee_ids.data = [ int(i) for i in request.args.getlist("committee_ids") ] if "prefill" in request.args: form.process_substitutions() if form.validate_on_submit() and form.previewed.data == "1": # send it form.generate_email() if not form.recipients: flash("There are no recipients to send this email to.", "error") else: form.send_email() flash( "Your email alert with subject '%s' has been sent to %d recipients." % (form.message.subject, len(form.recipients)) ) return redirect(url_for("alerts.index")) # force a preview before being sent again form.previewed.data = "0" return self.render("admin/alerts/new.html", form=form) @expose("/preview", methods=["POST"]) def preview(self): form = EmailAlertForm() if form.validate_on_submit(): form.generate_email() return self.render("admin/alerts/preview.html", form=form) else: return ("validation failed", 400) @expose("/sent", methods=["GET"]) def sent(self): return self.render("admin/alerts/sent.html") class EmailAlertForm(Form): template_id = HiddenField("template_id", [validators.Required()]) previewed = HiddenField("previewed", default="0") subject = StringField("Subject", [validators.Required()]) # This MUST be an email address, the Mandrill API doesn't allow us to do names and emails in one field from_email = EmailField( "From address", [validators.Required()], default="<EMAIL>" ) body = TextAreaField("Content of the alert") # recipient options daily_schedule_subscribers = BooleanField("Daily schedule subscribers") committee_ids = SelectMultipleField( "Committee Subscribers", [validators.Optional()], coerce=int, widget=CheckboxInput, ) # linked models committee_meeting_id = HiddenField("committee_meeting_id") def __init__(self, *args, **kwargs): super(EmailAlertForm, self).__init__(*args, **kwargs) committee_list = ( Committee.query.order_by(Committee.house_id.desc()) .order_by(Committee.name) .filter_by(monitored=True) .all() ) # count of daily schedule subscribers subs = User.query.filter( User.subscribe_daily_schedule == True, User.confirmed_at != None ).count() # noqa self.daily_schedule_subscribers.label.text += " (%d)" % subs # count subscribers for committees subscriber_counts = { t[0]: t[1] for t in db.session.query(user_committee_alerts.c.committee_id, count(1)) .join(User, User.id == user_committee_alerts.c.user_id) .filter(User.confirmed_at != None) .group_by(user_committee_alerts.c.committee_id) .all() } self.committee_ids.choices = [ ( c.id, "%s - %s (%d)" % (c.house.name, c.name, subscriber_counts.get(c.id, 0)), ) for c in committee_list ] self.message = None self.ad_hoc_mapper = [] for committee in committee_list: if committee.ad_hoc: self.ad_hoc_mapper.append(committee.id) @property def template(self): if not hasattr(self, "_template"): self._template = EmailTemplate.query.get(self.template_id.data) return self._template @property def committee_meeting(self): if self.committee_meeting_id.data: return CommitteeMeeting.query.get(self.committee_meeting_id.data) def process_substitutions(self): committee_meeting = self.committee_meeting committee_meeting.date = committee_meeting.date.strftime("%Y-%m-%d") for field in (self.subject, self.body): try: field.data = field.data.format(committee_meeting=self.committee_meeting) except KeyError as e: if not field.errors: field.errors = [] field.errors.append("Couldn't substitute field %s" % e) def send_email(self): if not self.message: self.generate_email() send_sendgrid_email( subject=self.message.subject, from_name="PMG Notifications", from_email=self.message.sender, recipient_users=self.recipients, html=self.message.html, utm_campaign=self.template.utm_campaign, ) def generate_email(self): self.recipients = self.get_recipient_users() self.message = Message( subject=self.subject.data, sender=self.from_email.data, html=self.body.data ) def get_recipient_users(self): groups = [] if self.daily_schedule_subscribers.data: log.info("Email recipients includes daily schedule subscribers") groups.append( User.query.options( lazyload(User.organisation), lazyload(User.committee_alerts), ) .filter(User.subscribe_daily_schedule == True) .filter(User.confirmed_at != None) .all() ) if self.committee_ids.data: log.info( "Email recipients includes subscribers for these committees: %s" % self.committee_ids.data ) user_ids = ( db.session.query(distinct(user_committee_alerts.c.user_id)) .filter( user_committee_alerts.c.committee_id.in_(self.committee_ids.data) ) .all() ) user_ids = [u[0] for u in user_ids] groups.append( User.query.options( lazyload(User.organisation), lazyload(User.committee_alerts), ) .filter(User.id.in_(user_ids)) .filter(User.confirmed_at != None) .all() ) return set(u for u in chain(*groups))
// 对 __bl.js 提供的方法的封装,不必判断是否初始化完成(但必须已安装) export { default as armsSetConfig } from './util/arms/set-config'; export { default as armsSetPage } from './util/arms/set-page'; export { default as armsSetCommonInfo } from './util/arms/set-common-info'; export { default as armsCustom } from './util/arms/custom'; export { default as armsApi } from './util/arms/api'; export { default as armsApiSuccess } from './util/arms/api-success'; export { default as armsApiFail } from './util/arms/api-fail'; export { default as armsError } from './util/arms/error'; export { default as armsSpeed } from './util/arms/speed'; export { default as armsSum } from './util/arms/sum'; export { default as armsAvg } from './util/arms/avg'; export { default as armsPercent } from './util/arms/percent'; export { default as armsResource } from './util/arms/resource'; // 其他方法 export { default as getBlConfig } from './util/get-bl-config'; export { default as installBl } from './util/install-bl'; export type { IBlConfigBeforeReady as ArmsBlConfigBeforeReady, IBlConfig as ArmsBlConfig, IErrorInfo as ArmsErrorInfo, IErrorPosition as ArmsErrorPosition, TSpeedPoint as ArmsSpeedPoint, IResourceData as ArmsResourceData } from './types';
<reponame>awbear/json-schema-viewer import { TreeListNode } from '@stoplight/tree-list'; import { Dictionary, JsonPath } from '@stoplight/types'; import { JSONSchema4, JSONSchema4TypeName } from 'json-schema'; export const enum SchemaKind { Any = 'any', String = 'string', Number = 'number', Integer = 'integer', Boolean = 'boolean', Null = 'null', Array = 'array', Object = 'object', } export type JSONSchema4CombinerName = 'allOf' | 'anyOf' | 'oneOf'; export type JSONSchema4Annotations = 'title' | 'description' | 'default' | 'examples'; export type JSONSchema4Metadata = 'id' | '$schema'; export interface ICombinerNode { id: string; readonly combiner: JSONSchema4CombinerName; properties?: JSONSchema4[]; annotations: Pick<JSONSchema4, JSONSchema4Annotations>; readonly type?: JSONSchema4TypeName | JSONSchema4TypeName[]; } export interface IBaseNode extends Pick<JSONSchema4, 'enum'> { id: string; readonly type?: JSONSchema4TypeName | JSONSchema4TypeName[]; annotations: Pick<JSONSchema4, JSONSchema4Annotations>; validations: Dictionary<unknown>; } export interface IRefNode { id: string; $ref: string; } export interface IArrayNode extends IBaseNode, Pick<JSONSchema4, 'items' | 'additionalItems'> {} export interface IObjectNode extends IBaseNode, Pick<JSONSchema4, 'properties' | 'patternProperties' | 'additionalProperties'> {} export interface IObjectPropertyNode extends IBaseNode { name: string; } export type SchemaNode = ICombinerNode | IBaseNode | IArrayNode | IObjectNode | IObjectPropertyNode | IRefNode; export interface ITreeNodeMeta { name?: string; additional?: IArrayNode['additionalItems'] | IObjectNode['additionalProperties']; path: JsonPath; divider?: string; subtype?: IBaseNode['type'] | string; expanded?: boolean; required?: boolean; inheritedFrom?: string; pattern?: boolean; $ref?: string; } export type SchemaNodeWithMeta = SchemaNode & ITreeNodeMeta; export type SchemaTreeListNode = TreeListNode<SchemaNodeWithMeta>; export type GoToRefHandler = (path: string, node: SchemaTreeListNode) => void;
Molecular variation in Leymus species and populations Icelandic populations of European lymegrass were examined using amplified fragment length polymorphism (AFLP) and restriction fragment length polymorphism (RFLP) of the major ribosomal genes (18S–5.8S–26S rDNA), in comparison with Alaskan populations of its closely related species L. mollis (Trin.) Pilger. The AFLP profiles emerged as two distinct entities, clearly separating the two species, and based on species‐specific bands it was simple to distinguish these two morphologically similar species. The rDNA–RFLPs also differentiated the species. Within species, the Icelandic L. arenarius was more homogeneous than the Alaskan L. mollis, and its variation was dispersed over geographically different populations, suggesting a common gene pool. The variation among the Alaskan L. mollis was more extensive and its interrupted pattern may be the result of gene introgression at subspecies level. Within a 40‐year‐old population of L. mollis established in Iceland from Alaskan material, the molecular profiles separated old and new genotypes. Both AFLP and rDNA revealed the new genotypes to be extremely similar. This rapid change in allele frequency is thought to be the result of adaptation to a new environment.
Get the biggest daily news stories by email Subscribe Thank you for subscribing We have more newsletters Show me See our privacy notice Could not subscribe, try again later Invalid Email As the sonographer paused the ultrasound scan and zoomed in on the picture of her unborn baby, first-time mum Sarah Radford and her husband Tom couldn’t have been happier. Like thousands of parents-to-be each year, they decided to find out the sex of their baby at their 20-week scan and despite both sides of their family giving birth to sons first, to their surprise the sonographer pointed out all the features of a baby girl. Clutching the ultrasound picture of her daughter and imagining the little girl her baby would become, Sarah, 30, hit the shops. Picking out pink, girlie outfits and creating a nursery with pink floral wall stickers, bedding, curtains and lampshades, she spent over £1,000. But when Sarah finally gave birth at Norfolk and Norwich University Hospital in January, after a five-day labour which ended in a caesarean, she watched the colour drain from 29-year-old Tom’s face - their longed-for baby girl was in fact a boy. Sarah, a primary school teacher who lives in Norwich, says: “Tom’s face dropped as though something was wrong. The hospital staff all knew we were expecting a girl but nobody thought to check – it was Tom who noticed he was in fact a boy.” In the drama of the operating theatre, where Sarah’s surgery still had to be completed, it was 15 minutes before the sex of their baby was confirmed and Sarah learnt she had indeed given birth to a boy. She says: “It was such a shock. The sonographer had said she was 100% certain we were having a girl and even stopped the ultrasound image on the screen and pointed it all out to show us. We couldn’t believe it.” After Sarah was moved to the postnatal ward, news of the “mistake” spread among the mums and midwives, who laughingly congratulated her on her new arrival. But Sarah wasn’t quite so amused. “One mum on the ward came over and congratulated me. I asked her how she knew what had happened,” says Sarah. “She said a midwife had told her. "I felt like I’d lost a child and I needed to deal with it privately but there was no confidentiality at all. “I’d imagined the ballet lessons and the periods talk with my daughter. I felt like I’d lost something yet my beautiful, healthy baby was beside me. "No one at the hospital asked whether I was OK – the first person to ask me how I was feeling about the mistake was a health worker during a home visit weeks later.” Still in shock, Sarah left hospital when her son, who was unnamed for five days because the couple had never even considered boys’ names, was two days old. He had to spend his first night at home in a pink Moses basket. Sarah says: “We got home at 1am so there was no time to buy an alternative. Everything I’d bought was pink or lilac. We had just one item of clothing that was neutral and I didn’t feel like I’d bought him anything at all. It felt like I hadn’t given birth to the baby I expected to.” Like Sarah and Tom, a fuel injection engineer, the couple’s family responded to the unexpected delivery with mixed emotions. “My mum screamed down the phone and my father-in-law almost dropped his cup of tea,” says Sarah. “My mother-in-law really understood how I was feeling, and she had to mourn the loss of a granddaughter.” The day after she left hospital, despite still recovering from the major surgery of her caesarean, Sarah and Tom went straight to Toys R Us, where they began to replace their “daughter’s” pink clothes and bedding with much-needed blue instead. “The hardest thing I’ve ever had to do was pack away ‘her’ clothes,” says Sarah. “Tom and I both cried. It was such a strange feeling.” By the end of the week, Sarah had named her son Ryan but it has taken almost six months for her to deal with the shock and disappointment the mistaken scan result caused, and only now is she starting to enjoy motherhood and put the ordeal behind her. “I can look back on it now and see the funny side but at the time it was very hard,” she says. “It’s really hard to explain to people how I was feeling.” Sarah decided not to pursue the lapse of patient confidentiality at the hospital, preferring to put the incident behind her, and instead sought comfort from parenting websites such as babycentre.co.uk where she found other mums sharing their feelings about “gender disappointment”. “It isn’t a recognised medical term but is very real,” says Sarah. “Lots of mums go through it and it helped me to deal with what happened. I feel lucky I haven’t had postnatal depression as a result.” Sarah says she will still find out the sex of her unborn baby next time. “I like to plan ahead and I want to be able to bond with my child,” she says. “Next time we’ll have a private 3D scan too and triple-check. “I still feel guilty that when Ryan was born, my first thought was, ‘Where’s my little girl?’ but I’m so excited to have a boy now.”
import { ChakraProvider, useDisclosure } from "@chakra-ui/react"; import theme from "./theme"; import Header from "./components/Header"; import ConnectButton from "./components/ConnectButton"; import AccountModal from "./components/AccountModal"; import Swap from "./components/Swap"; import "@fontsource/inter"; import "./global.css"; function App() { const { isOpen, onOpen, onClose } = useDisclosure(); return ( <ChakraProvider theme={theme}> <Header> <ConnectButton handleOpenModal={onOpen} /> <AccountModal isOpen={isOpen} onClose={onClose} /> </Header> <Swap /> </ChakraProvider> ); } export default App;
Asymptotic Robust Adaptive Tracking of Parametric Strict-Feedback Systems with Additive Disturbance This paper deals with the tracking control of multi-inut/multi-output nonlinear parametric strict-feedback systems in the presence of additive disturbances and parametric uncertainties. For such systems, robust adaptive controllers usually cannot ensure asymptotic tracking or even regulation. In this work, under the assumption the disturbances are C2with bounded time derivatives, we present a C0robust adaptive control construction that guarantees the tracking error is asymptotically driven to zero.
package splash import ( "fmt" "strings" "time" "github.com/kyokomi/emoji" "github.com/qdm12/cloudflare-dns-server/internal/constants" ) // Splash returns the welcome spash message func Splash(version, vcsRef, buildDate string) string { lines := title() lines = append(lines, "") lines = append(lines, fmt.Sprintf("Running version %s built on %s (commit %s)", version, buildDate, vcsRef)) lines = append(lines, "") lines = append(lines, announcement()...) lines = append(lines, "") lines = append(lines, links()...) return strings.Join(lines, "\n") } func title() []string { return []string{ "=========================================", "========= DNS over TLS container ========", "=========================================", "=========================================", "=== Made with " + emoji.Sprint(":heart:") + " by github.com/qdm12 ====", "=========================================", } } func announcement() []string { if len(constants.Announcement) == 0 { return nil } expirationDate, _ := time.Parse("2006-01-02", constants.AnnouncementExpiration) // error covered by a unit test if time.Now().After(expirationDate) { return nil } return []string{emoji.Sprint(":mega: ") + constants.Announcement} } func links() []string { return []string{ emoji.Sprint(":wrench: ") + "Need help? " + constants.IssueLink, emoji.Sprint(":computer: ") + "Email? <EMAIL>", emoji.Sprint(":coffee: ") + "Slack? Join from the Slack button on Github", emoji.Sprint(":money_with_wings: ") + "Help me? https://github.com/sponsors/qdm12", } }
def SaveVariables(self, variables, filename, env): proxy = self.VarEnvProxy(env) _VariablesWrapper(variables).Save(filename, proxy)
def convert_dat_to_pdb(infile, outfile): with open(infile, "rb") as f_in, open(outfile, "w") as f_out: f_out.write(_from_dat(f_in))
def compute(self, atomic_input: AtomicInput) -> AtomicResult: job_input_msg = atomic_input_to_job_input(atomic_input) self._send_msg(pb.JOBINPUT, job_input_msg) status = self._recv_msg(pb.STATUS) while not status.accepted: print("JobInput not accepted. Retrying...") sleep(0.5) self._send_msg(pb.JOBINPUT, job_input_msg) status = self._recv_msg(pb.STATUS) print(status) while not self.check_job_complete(): sleep(0.5) job_output = self._recv_msg(pb.JOBOUTPUT) return job_output_to_atomic_result( atomic_input=atomic_input, job_output=job_output )
import { SharedModule } from './../shared/shared.module'; import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { LeafletModule } from '@asymmetrik/ngx-leaflet'; import { MapsdRoutingModule } from './maps-routing.module'; import { DetailDistributionCenterModalComponent } from './map2d/detail-distribution-center-modal/detail-distribution-center-modal.component'; import { DetailVehicleModalComponent } from './map2d/detail-vehicle-modal/detail-vehicle-modal.component'; import { MapComponent } from './map2d/map/map.component'; import { Map2dComponent } from './map2d/map2d.component'; import { TruckIncidentModalComponent } from './map2d/truck-incident-modal/truck-incident-modal.component'; import { TruckComponent } from './map2d/truck/truck.component'; import { StatisticsComponent } from './map2d/statistics/statistics.component'; import { MagicPlacesComponent } from './map2d/magic-places/magic-places.component'; import { ReactiveFormsModule } from '@angular/forms'; import { GenericProblemModalComponent } from './map2d/generic-problem-modal/generic-problem-modal.component'; import { RouteDetailedComponent } from './map2d/route-detailed/route-detailed.component'; import { NgxEchartsModule } from 'ngx-echarts'; import { TruckReducedInfoModalComponent } from './map2d/truck-reduced-info-modal/truck-reduced-info-modal.component'; @NgModule({ declarations: [ Map2dComponent, MapComponent, DetailDistributionCenterModalComponent, DetailVehicleModalComponent, TruckIncidentModalComponent, TruckReducedInfoModalComponent, GenericProblemModalComponent, TruckComponent, StatisticsComponent, MagicPlacesComponent, RouteDetailedComponent, ], imports: [ CommonModule, ReactiveFormsModule, MapsdRoutingModule, LeafletModule, SharedModule, NgxEchartsModule.forRoot({ echarts: () => import('echarts'), }), ], }) export class MapsModule {}
/* istanbul ignore file: no usefull tests to build */ import EnvParam from './EnvParam'; import IEnvParam from './IEnvParam'; // ATTENTION subtilité sur ConfigurationService et STATIC_ENV_PARAMS, on // a besoin de ces fichiers en JS également pour la conf de webpack, donc il faut // recopier le JS à chaque compilation d'une nouvelle version de ces 2 fichiers. export default class ConfigurationService { public static getInstance(): ConfigurationService { if (!ConfigurationService.instance) { ConfigurationService.instance = new ConfigurationService(); } return ConfigurationService.instance; } private static instance: ConfigurationService = null; /** * Local thread cache ----- */ public nodeInstall: boolean; public nodeInstallFullSegments: boolean; /** * Just an helper for webpack conf */ public shared_params: any; private nodeEnv: string; private STATIC_ENV_PARAMS: { [env: string]: IEnvParam }; /** * ----- Local thread cache */ private constructor() { this.nodeEnv = process.env.NODE_ENV || 'DEV'; this.nodeInstall = (process.env.NODE_INSTALL == 'true'); this.nodeInstallFullSegments = (process.env.NODE_INSTALL_FULL_SEGMENTS == 'true'); ConfigurationService.instance = this; } public setEnvParams(STATIC_ENV_PARAMS: { [env: string]: IEnvParam }) { this.STATIC_ENV_PARAMS = STATIC_ENV_PARAMS; } public getNodeConfiguration<T extends IEnvParam>(): T { return Object.assign(new EnvParam(), this.STATIC_ENV_PARAMS[this.nodeEnv]) as T; } }
//Serialize argument to its byte representation. func (a BinaryArgument) Serialize(s *serializer.Serializer) error { err := s.Byte(byte(ArgumentBinary)) if err != nil { return err } return s.BytesWithUInt32Len(a.Value) }
/** A sample customer code handler class that implements a simple getTime() method */ public class TimeHandler extends CustomCodeHandler { @CustomCodeTarget(name = "get_time") public byte[] getTime(byte[] data) throws InvalidProtocolBufferException { TimeRequest request = TimeRequest.parseFrom(data); String time = getTime(request.getFormat()); TimeResponse.Builder timeResponseBuilder = TimeResponse.newBuilder(); timeResponseBuilder.setTime(time); return timeResponseBuilder.build().toByteArray(); } private static String getTime(String format) { SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(new Date()); } }
/** * @author Anindya Chatterjee */ class NitriteDocument extends LinkedHashMap<String, Object> implements Document { private static final long serialVersionUID = 1477462374L; private static final List<String> reservedFields = listOf(DOC_ID, DOC_REVISION, DOC_SOURCE, DOC_MODIFIED); NitriteDocument(Map<String, Object> objectMap) { super(objectMap); } @Override public Document put(String key, Object value) { if (DOC_ID.contentEquals(key) && !validId(value)) { throw new InvalidOperationException("_id is an auto generated value and cannot be set"); } if (value != null && !Serializable.class.isAssignableFrom(value.getClass())) { throw new ValidationException("type " + value.getClass().getName() + " does not implement java.io.Serializable"); } super.put(key, value); return this; } @Override public Object get(String key) { if (key != null && key.contains(NitriteConfig.getFieldSeparator()) && !containsKey(key)) { return deepGet(key); } return super.get(key); } @Override public <T> T get(String key, Class<T> type) { notNull(type, "type cannot be null"); return type.cast(get(key)); } @Override public NitriteId getId() { String id; try { if (!containsKey(DOC_ID)) { id = newId().getIdValue(); super.put(DOC_ID, id); } else { id = (String) get(DOC_ID); } return createId(id); } catch (ClassCastException cce) { throw new InvalidIdException("invalid _id found " + get(DOC_ID)); } } @Override public Set<String> getFields() { return getFieldsInternal(""); } @Override public boolean hasId() { return super.containsKey(DOC_ID); } @Override public void remove(String key) { super.remove(key); } @Override @SuppressWarnings("unchecked") public Document clone() { Map<String, Object> clone = (Map<String, Object>) super.clone(); return new NitriteDocument(clone); } @Override public Document merge(Document document) { if (document instanceof NitriteDocument) { super.putAll((NitriteDocument) document); } return this; } @Override public boolean containsKey(String key) { return super.containsKey(key); } @Override public boolean equals(Object other) { if (other == this) return true; if (!(other instanceof NitriteDocument)) return false; NitriteDocument m = (NitriteDocument) other; if (m.size() != size()) return false; try { for (Map.Entry<String, Object> e : entrySet()) { String key = e.getKey(); Object value = e.getValue(); if (value == null) { if (!(m.get(key) == null && m.containsKey(key))) return false; } else { if (!Objects.deepEquals(value, m.get(key))) { return false; } } } } catch (ClassCastException | NullPointerException unused) { return false; } return true; } @Override public Iterator<KeyValuePair<String, Object>> iterator() { return new PairIterator(super.entrySet().iterator()); } private Set<String> getFieldsInternal(String prefix) { Set<String> fields = new HashSet<>(); for (KeyValuePair<String, Object> entry : this) { if (reservedFields.contains(entry.getKey())) continue; Object value = entry.getValue(); if (value instanceof NitriteDocument) { if (isNullOrEmpty(prefix)) { fields.addAll(((NitriteDocument) value).getFieldsInternal(entry.getKey())); } else { fields.addAll(((NitriteDocument) value).getFieldsInternal(prefix + NitriteConfig.getFieldSeparator() + entry.getKey())); } } else if (!(value instanceof Iterable)) { if (isNullOrEmpty(prefix)) { fields.add(entry.getKey()); } else { fields.add(prefix + NitriteConfig.getFieldSeparator() + entry.getKey()); } } } return fields; } private Object deepGet(String field) { if (field.contains(NitriteConfig.getFieldSeparator())) { return getByEmbeddedKey(field); } else { return null; } } private Object getByEmbeddedKey(String embeddedKey) { String regex = MessageFormat.format("\\{0}", NitriteConfig.getFieldSeparator()); String[] path = embeddedKey.split(regex); if (path.length < 1) { return null; } return recursiveGet(get(path[0]), Arrays.copyOfRange(path, 1, path.length)); } @SuppressWarnings("unchecked") private Object recursiveGet(Object object, String[] remainingPath) { if (object == null) { return null; } if (remainingPath.length == 0) { return object; } if (object instanceof Document) { return recursiveGet(((Document) object).get(remainingPath[0]), Arrays.copyOfRange(remainingPath, 1, remainingPath.length)); } if (object.getClass().isArray()) { String accessor = remainingPath[0]; Object[] array = convertToObjectArray(object); if (isInteger(accessor)) { int index = asInteger(accessor); if (index < 0) { throw new ValidationException("invalid array index " + index + " to access item inside a document"); } if (index >= array.length) { throw new ValidationException("index " + index + " is not less than the size of the array " + array.length); } return recursiveGet(array[index], Arrays.copyOfRange(remainingPath, 1, remainingPath.length)); } else { return decompose(listOf(array), remainingPath); } } if (object instanceof Iterable) { String accessor = remainingPath[0]; Iterable<Object> iterable = (Iterable<Object>) object; List<Object> collection = Iterables.toList(iterable); if (isInteger(accessor)) { int index = asInteger(accessor); if (index < 0) { throw new ValidationException("invalid collection index " + index + " to access item inside a document"); } if (index >= collection.size()) { throw new ValidationException("index " + accessor + " is not less than the size of the list " + collection.size()); } return recursiveGet(collection.get(index), Arrays.copyOfRange(remainingPath, 1, remainingPath.length)); } else { return decompose(collection, remainingPath); } } return null; } @SuppressWarnings("unchecked") private List<Object> decompose(List<Object> collection, String[] remainingPath) { Set<Object> items = new HashSet<>(); for (Object item : collection) { Object value = recursiveGet(item, remainingPath); if (value != null) { if (value instanceof Iterable) { List<Object> list = Iterables.toList((Iterable<Object>) value); items.addAll(list); } else if (value.getClass().isArray()) { List<Object> list = Arrays.asList(convertToObjectArray(value)); items.addAll(list); } else { items.add(value); } } } return new ArrayList<>(items); } private int asInteger(String number) { try { return Integer.parseInt(number); } catch (NumberFormatException e) { return -1; } } private boolean isInteger(String value) { try { Integer.parseInt(value); return true; } catch (NumberFormatException e) { return false; } } private void writeObject(ObjectOutputStream stream) throws IOException { stream.writeInt(size()); for (KeyValuePair<String, Object> keyValuePair : this) { stream.writeObject(keyValuePair); } } @SuppressWarnings("unchecked") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { int size = stream.readInt(); for (int i = 0; i < size; i++) { KeyValuePair<String, Object> keyValuePair = (KeyValuePair<String, Object>) stream.readObject(); super.put(keyValuePair.getKey(), keyValuePair.getValue()); } } private static class PairIterator implements Iterator<KeyValuePair<String, Object>> { private Iterator<Map.Entry<String, Object>> iterator; PairIterator(Iterator<Map.Entry<String, Object>> iterator) { this.iterator = iterator; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public KeyValuePair<String, Object> next() { Map.Entry<String, Object> next = iterator.next(); return new KeyValuePair<>(next.getKey(), next.getValue()); } @Override public void remove() { iterator.remove(); } } }
<gh_stars>0 pub fn hello() { println!("Hello from first module"); }
The Durbar Hall at Diggi Palace, the venue for the Festival. The Durbar Hall at Diggi Palace, the venue for the Festival. Over 200 authors including two Nobel Prize winners will be in attendance at this year's festival. EVERY January, the world gets divided into those who are - and those who are not attending the Jaipur Literature Festival (JLF). But in the year of the aam aadmi - there cannot be a more compelling argument for its success thus far, than the fact that it staunchly remains a free festival open to the masses. This, combined with an assured A-list of authors, has made JLF into one of the world's largest literature festivals, a completely democratic (and demographic!) cultural bonanza. (L) Amartya Sen, Jhumpa Lahiri and Irrfan Khan (L) Amartya Sen, Jhumpa Lahiri and Irrfan Khan This trend continues this year as well, as the authors are as diverse as the audience, a heady mix of national and international, established as well as unknown. In recent years JLF has been occasionally critiqued for courting a celebrity cult - (the Oprah Winfrey episode is frequently quoted) but this year the programme designed by festival directors Namita Gokhale and William Dalrymple is bold yet balanced.In an election year there is an important emphasis on political and voting patterns - but there is also a special section on publishing trends, and literature remains on top of the agenda. Especially exciting for crime writers such as myself - Crime and Punishment is a significant theme - but more about that, later.Among those not attending are many who claim a sudden onslaught of agoraphobia - but for others (like me) the lure of luxuriating in literature grows exponentially along with the festival size. Like any other book junkie, I am prepared to attend sessions whilst being swept in and out of sessions, almost in a zombie like trance - often just following the crowds. Those unused to situations such as Churchgate Station at peak hour, might have to indulge in a spot of planning to grab a place (well perfected by some who request friends to lay down shawls and handbags across unreserved rows). Another cunning idea is to tiptoe out of some sessions a trifle early to queue up at the one you want to listen to next - keeping a beady eye on those who shuffling their feet as the session ends, so that you can charge across and grab their space.But most of all, it might be useful to already begin to go through details available on the festival website - and start thinking of whom you really want to listen to, so that strategies can be worked out - including where to grab the coffee in-between and how to gobble a quick lunch. Yes, that's because even lunch time sessions can have an interesting book launch - leaving little time to dawdle over dal bati churma (a perpetual favourite on the JLF menu).Fortunately because the venues are all within five minutes of each other, a brisk pace will ensure you manage to gain access.Most tented venues offer extra space - if you don't stand on dignity and just sit on the grass! The only area that you cannot charm your way into is the Durbar Hall in the main Diggy Palace, once it is packed to capacity - so try to keep that as priority, if there is anything that interests you there.Let me also warn you that literature lovers are nonnegotiable creatures, and are known to bite! Abandon your seat at your peril- because this year too, the festival has a lot to offer: from Jonathan Franzen (author of Freedom and Corrections) to Pulitzer Prize winner Jhumpa Lahiri (who has just written The Lowlands ) to Gloria Steinem (the iconic feminist author). I would strongly recommend listening to the discussion between Jhumpa Lahiri, Jonathan Franzen and Jim Crace (who was shortlisted for the Man Booker award for Harvest ) on their views about The Global Novel. Alongside there will be equally interesting sessions with some debutante authors such as the much loved Mary Kom who will be launching her biography.There are over 200 authors to choose from, and many of them international awardees, including two Nobel Prize winners as well, Amartya Sen - who will give the keynote address, and Harold Varmus.Varmus was the co-recipient of the Nobel Prize on the genetic basis of cancer. He has also been the president of the Sloan Kettering Cancer centre and was chosen by President Obama to head National Cancer Institute. Both Sen and Varmus add to the festival agenda of engaging with social issues and change.As JLF continues to grow, an exciting initiative this year is through the launch of Bookmark - a platform specially for the publishing industry, which has seen some rather seismic changes, even within India. The talented Alexandra Pringle (who can forget her success with the Harry Potter series?) will be in discussion about The Synergies of the Glocal with the equally impressive Ameena Saiyed from Oxford University Press and Ravi DeeCee - a well established independent publisher.These sessions are as important for authors as they are for publishers as the content often morphs according to marketing and technology needs.Another major focus of the festival is on Crime and Punishment.This has been specially curated and introduced by Namita Gokhale - reflecting the fact that crime writing deals with rapidly changing values and a growing emphasis on accountability.In fact, the Crime Writer's Association of South Asia (of which I must confess I am the convener and a founder member) will also be launched during the festival, with the agenda of bringing together all crime writers in this region. So hailing all crime writers - please head for JLF! Overall, the festival offers a range of themes and different platforms for discussions as well as opportunities for learning and growth. And just in case none of that appeals - you could just ' chill' at the festival venue listening to some of the world's foremost authors and thinkers. And then unwind at a music session in the evening, after the hard intellectual work is over!
Design and testing of a four-sided permanent magnet linear generator prototype In the perspective of the fossil fuels deposits depletion new energy resources must be developed; amongst them the renewable energy sector seems to be able to provide a long term solution. Besides the already popular wind, solar or thermal energies, the ocean energy sector offers a virtually infinite energy potential; many solutions for harvesting and converting this energy into usable form are under investigation, most of them using complex mechanical or hydraulic systems to convert the slow, linear movement specific to waves into rotational movement, compatible with the classical electric generators. Our focus is on systems using linear electric generators, offering higher efficiency and reliability, the present paper presenting the stages covered to choosing, designing, building and testing a linear generator.
def alt_to_s3(chart, bucket, key): s3 = boto3.client("s3") fname = f"{tempfile.gettempdir()}/{str(uuid4())}.json" save(chart, fname) with open(fname, "rb") as f: s3.upload_fileobj( f, bucket, key, ExtraArgs={"ContentType": "text/json", "ACL": "public-read"}, ) os.remove(fname)
/** Copyright 2008 University of Rochester 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 edu.ur.hibernate.ir.item.db; import org.springframework.context.ApplicationContext; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.testng.annotations.Test; import edu.ur.hibernate.ir.test.helper.ContextHolder; import edu.ur.ir.item.GenericItem; import edu.ur.ir.item.GenericItemDAO; import edu.ur.ir.item.ItemVersion; import edu.ur.ir.item.ItemVersionDAO; import edu.ur.ir.item.VersionedItem; import edu.ur.ir.item.VersionedItemDAO; import edu.ur.ir.user.IrUser; import edu.ur.ir.user.IrUserDAO; import edu.ur.ir.user.UserEmail; /** * Test the persistence methods for Item Version Information * * @author <NAME> * */ @Test(groups = { "baseTests" }, enabled = true) public class ItemVersionDAOTest { /** get the application context */ ApplicationContext ctx = ContextHolder.getApplicationContext(); /** transaction manager */ PlatformTransactionManager tm = (PlatformTransactionManager) ctx.getBean("transactionManager"); /** Transaction definition */ TransactionDefinition td = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED); /** versioned item data access */ ItemVersionDAO itemVersionDAO = (ItemVersionDAO)ctx.getBean("itemVersionDAO"); /** user data access */ IrUserDAO userDAO= (IrUserDAO) ctx.getBean("irUserDAO"); /** Versioned item data access */ VersionedItemDAO versionedItemDAO = (VersionedItemDAO) ctx.getBean("versionedItemDAO"); GenericItemDAO itemDAO= (GenericItemDAO) ctx.getBean("itemDAO"); /** * Makes sure an item version can be saved and retrieved. */ public void basicItemVersionDAOTest() { TransactionStatus ts = tm.getTransaction(td); UserEmail userEmail = new UserEmail("email"); GenericItem item = new GenericItem("myItem"); IrUser user = new IrUser("user", "password"); user.setPasswordEncoding("<PASSWORD>"); user.addUserEmail(userEmail, true); VersionedItem versionedItem = new VersionedItem(user, item); ItemVersion itemVersion = versionedItem.getCurrentVersion(); userDAO.makePersistent(user); itemVersionDAO.makePersistent(itemVersion); ItemVersion otherItemVersion = itemVersionDAO.getById(itemVersion.getId(), false); versionedItem = otherItemVersion.getVersionedItem(); assert versionedItem != null : "otherItemVersion version is null " + otherItemVersion; assert versionedItem.getId() != null : "versioned item id is null " + versionedItem.getId(); assert otherItemVersion != null : "should be able to find item version with id " + itemVersion.getId(); assert otherItemVersion.equals(itemVersion) : "GenericItem version " + itemVersion + " should equal other " + otherItemVersion; tm.commit(ts); ts = tm.getTransaction(td); assert itemVersionDAO.getById(itemVersion.getId(), false) != null : "should be able to find item " + itemVersion; assert versionedItemDAO.getById(versionedItem.getId(), false) != null : "Should be able to get versionedItem " + versionedItem; versionedItemDAO.makeTransient(versionedItemDAO.getById(versionedItem.getId(), false)); assert itemVersionDAO.getById(itemVersion.getId(), false) == null : "Should not be able to find " + itemVersion.getId(); itemDAO.makeTransient(itemDAO.getById(item.getId(), false)); userDAO.makeTransient(userDAO.getById(user.getId(), true)); tm.commit(ts); } }
import { Component, Input, OnChanges, OnInit } from '@angular/core'; import { EDMBarChartModel } from '../edm-bar-chart.model'; @Component({ selector: 'app-edm-perf-summ-mil1', templateUrl: './edm-perf-summ-mil1.component.html', styleUrls: ['./edm-perf-summ-mil1.component.scss', '../../reports.scss'] }) export class EdmPerfSummMil1Component implements OnInit, OnChanges { @Input() domains: any[]; /** * Constructor. */ constructor() { } /** * */ ngOnInit(): void { } ngOnChanges(): void { this.buildHeaderTripleBarChart(); } /** * Returns the list of domains in MIL-1. This section does not * display MIL2-5. */ getDomainsForDisplay() { return this.domains?.filter(x => x.abbreviation != "MIL"); } /** * Returns the goals for the specified domain. * @param domain */ getGoals(domain: any) { return domain.subGroupings.filter(x => x.groupingType == "Goal"); } /** * Constructs an answer distribution 'grand total' object */ buildHeaderTripleBarChart() { const chart = new EDMBarChartModel(); chart.title = 'EDM MIL-1 Summary'; chart.green = 0; chart.yellow = 0; chart.red = 0; // total up the non-MIL domains this.domains?.filter(d => d.abbreviation !== 'MIL').forEach(d => { const totals = this.buildTriple(d); chart.green += totals.green; chart.yellow += totals.yellow; chart.red += totals.red; }); return chart; } /** * Builds the object for the vertical bar chart */ buildTriple(d: any) { const chart = new EDMBarChartModel(); chart.title = d.title; chart.green = 0; chart.yellow = 0; chart.red = 0; const goals = this.getGoals(d); goals?.forEach(g => { g.questions?.forEach(q => { if (!q.isParentQuestion) { this.addAnswerToChart(chart, q.answer); } }); }); return chart; } /** * Returns an object with the answer distribution for a goal */ buildHoriz(g: any) { const chart = new EDMBarChartModel(); chart.title = g.title; chart.green = 0; chart.yellow = 0; chart.red = 0; g.questions.forEach(q => { if (!q.isParentQuestion) { this.addAnswerToChart(chart, q.answer); } }); return chart; } /** * */ addAnswerToChart(chart, answer) { switch (answer) { case "Y": chart.green++; break; case "I": chart.yellow++; break; case "N": default: chart.red++; break; } } }
def _RetrieveAlias(self): alias = '' while not alias: alias = raw_input('Enter a valid alias email address' '([email protected]): ') response = self.multidomain_client.RetrieveAlias(alias) self._PrintAliasDetails(response)
""" This module defines helper class for the purpose of linearization. (Named as a helper instead of util since it doesn't directly do liniearization.) """ import numpy as np import cvxpy as cvx class LinearizationHelper(object): """ Delegate class to take care of obtaining a value used to make make a constraint to be linear, in order to make the optimization problem to be convex optimization problem. """ def __init__(self, solver_type='ECOS'): """ Keyword arguments ----------------- solver_type : SolverType Enum Type of solver. See statistical_clear_sky.solver_type.SolverType for valid solvers. """ self._solver_type = solver_type def obtain_component_r0(self, initial_r_cs_value, index_set=None): """ Obtains the initial r0 values that are used in place of variables denominator of degradation equation. Removed duplicated code from the original implementation. Arguments ----------------- initial_r_cs_value : numpy array Initial low dimension right matrix. Returns ------- numpy array The values that is used in order to make the constraint of degradation to be linear. """ component_r0 = initial_r_cs_value[0] if index_set is None: index_set = component_r0 > 1e-3 * np.percentile(component_r0, 95) x = cvx.Variable(initial_r_cs_value.shape[1]) objective = cvx.Minimize( cvx.sum(0.5 * cvx.abs(component_r0[index_set] - x[index_set]) + (.9 - 0.5) * (component_r0[index_set] - x[index_set])) + 1e3 * cvx.norm(cvx.diff(x, k=2))) if initial_r_cs_value.shape[1] > 365: constraints = [cvx.abs(x[365:] - x[:-365]) <= 1e-2 * np.percentile(component_r0, 95)] else: constraints = [] problem = cvx.Problem(objective, constraints) problem.solve(solver=self._solver_type) result_component_r0 = x.value return result_component_r0
<filename>src/app/usuarios/interceptors/auth.interceptor.ts import { AuthService } from '../auth.service'; import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import swal from 'sweetalert2'; import { Router } from '@angular/router'; @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(public authService: AuthService, private router: Router) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).pipe( catchError (e => { console.log(e); if (e.status == 401) { if (this.authService.isAuthenticated()) { this.authService.logout(); } swal.fire('AuthInterceptor ha detectado que no estás autenticado', 'por favor Sign In', 'warning'); //this.router.navigate(['/login']); } if (e.status == 403) { swal.fire('AuthInterceptor ha detectado que no tienes permisos', `${this.authService.usuario.username}, tu role es ${this.authService.usuario.roles}`, 'warning'); /// this.router.navigate(['/clientes']); } return throwError (e); }) ) } }
/** * adds a card to the active hand of the player if the player is able to hit */ public void hit() { if (rules.canHit(player.getActiveHand())) { stackCheck(); player.takeCard(cardstack.drawCard()); status = "player took a card"; } else { status = "player unable to hit"; } notifyObservers(); }
Insulin resistance and beta-cell hypersecretion in essential hypertension. To determine whether a decreased sensitivity to insulin is involved in the pathogenesis of essential hypertension, fasting blood glucose, serum insulin, serum C peptide, the glucose:insulin ratio and the insulin:C-peptide ratio were measured in 14 lean normotensives, 17 overweight normotensives, 17 lean hypertensives and 20 overweight hypertensives. Compared with the lean normotensives, the patients who were overweight, those with hypertension and those who were both overweight and hypertensive showed increased fasting serum insulin and C-peptide levels, and a lower glucose:insulin ratio. No significant difference between the normotensive and the hypertensive subjects was found in the insulin:C-peptide ratio. Diastolic blood pressure was directly correlated with serum insulin (P less than 0.01) and with C-peptide levels (P less than 0.01), and inversely correlated with the glucose:insulin ratio (P less than 0.02). We conclude that insulin resistance is present in both essential hypertensive and overweight subjects. Since the present study showed that hepatic insulin clearance was normal in hypertensives, the hyperinsulinaemia in essential hypertension appears to be due to beta-cell hypersecretion in response to a defective peripheral action of the hormone.
#include<bits/stdc++.h> #define fi first #define se second #define ll long long #define pb push_back #define mp make_pair #define mt make_tuple #define pi 3.14159265359 using namespace std; const int INF = 100000000; int niz[200000]; int pref[200000][26]; int rez[26]; int podeli(int l, int r, int c) { if(l == r) { if(niz[l] == c) return 0; return 1; } int op1 = podeli(l, (l + r)/2, c + 1); int op2 = (r-l+1)/2 - (pref[r][c] - pref[(l + r)/2][c]); int broj = INF; broj = op1 + op2; op1 = podeli((l + r)/2+1, r, c + 1); int k; if(l == 0) k = 0; else k = pref[l-1][c]; op2 = (r-l+1)/2 - (pref[(l + r)/2][c] - k); broj = min(broj, op1+op2); /*if(l == 0 && r == 7) cout << op1 << " ... " << op2 << "\n"; if(l == 4 && r == 7) cout << l << " " << r << " " << c << " " << broj << "\n"; if(l == 0 && r == 7) cout << l << " " << r << " " << c << " " << broj << "\n";*/ return broj; } void resi() { int n; cin >> n; for(int i = 0; i < n; i++) { char x; cin >> x; niz[i] = x - 'a'; if(i > 0) for(int j = 0; j < 26; j++) pref[i][j] = pref[i-1][j]; else for(int j = 0; j < 26; j++) pref[i][j] = 0; pref[i][niz[i]]++; } cout << podeli(0, n-1, 0) << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while(t--) resi(); return 0; } /* 1 8 ceaaaabb */
/** * Servlet implementation class RTCStatsServlet for verify page */ @WebServlet("/verify") public class RTCStatsServlet extends HttpServlet { private static final long serialVersionUID = -6712086996275183628L; private static final Log log = LogFactory.getLog(RTCStatsServlet.class); /** * @see HttpServlet#HttpServlet() */ public RTCStatsServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { final String resultTable = new RTCStatsDao(Utility.getDBConnection(this.getServletContext())).getResultTable(); if(resultTable!=null) { String requestString = "rtcstatsjson?name=" + resultTable; request.setAttribute("rtcstatsRequest", requestString); } } catch (SQLException e) { e.printStackTrace(); throw new KiteSQLException(e.getLocalizedMessage()); } // todo remove this - not necessary if we don't need hosting csio verify page, and other library in seperate host response.addHeader("Access-Control-Allow-Origin", "*"); // get UI if (log.isDebugEnabled()) log.debug("Displaying: rtcstats.vm"); RequestDispatcher requestDispatcher = request.getRequestDispatcher("rtcstats.vm"); requestDispatcher.forward(request, response); } }
/** * Modifies m_ranking ordering attributes in decreasing order of Fleuret's * CMIM approximation of I(Xi;C|m_selected) for all Xi in m_ranking. CMIM * approximates this value with formula: max_Xi min_Xj I(Xi;C|m_selected) * for all Xi in m_ranking and all Xj in m_selected * * @param data from which to compute conditional mutual informations * */ protected void rerankCMIM(Instances data) throws Exception { double[][] I_XiC_givenS = new double[m_ranking.length][m_selected.length]; for (int i = 0; i < m_ranking.length; i++) { for (int j = 0; j < m_selected.length; j++) { I_XiC_givenS[i][j] = getConditionalMutualInformation( m_ranking[i], data.numAttributes() - 1, m_selected[j], data); } } int[] maxToMin = minMaxOrder(I_XiC_givenS); I_XiC_givenS = null; int[] auxRanking = new int[m_ranking.length]; for (int i = 0; i < auxRanking.length; i++) { auxRanking[i] = m_ranking[maxToMin[i]]; } m_ranking = auxRanking; }
It’s been a long time coming, but CCP is about to make good on the promise of an integrated MMO and FPS this coming Thursday, January 10th 2013. On Thursday the 10th of January, following a slightly longer than usual scheduled downtime, we will be migrating over players currently participating in the DUST 514 closed beta from Singularity to Tranquility. This is not only significant for those of us who’ve been playing EVE, but for the gaming industry as a whole. This simply has never really been done before, and in true CCP style they are taking slow baby steps to make sure the delicate balance of both games aren’t going to be totally ruined. While you won’t be able to send billions of ISK to your DUST characters yet, you will be able to drop truckloads of searing hot plasma on them from orbit. Bombardment is a go folks, for now limited to low security systems involved with faction warfare. Personally I wish I didn’t have to coordinate with DUST soldiers at all, and just be able to pull into orbit and provide random gameplay enhancement to the soldiers on the ground. There’s a weird quote from the dev blog where they mention “the first flavor being the Tactical Strike”. That implies other flavors, and I hope one of those flavors is Random EVE Asshole Messing With DUST Players. With local chat integration, ISK sellers will be able to reach more people now since we can openly communicate with DUST mercenaries. Actually that alone should make things interesting since the beta is still closed and the NDA is still technically in effect. They will be dealing with NDA violations left and right so I can only imagine that it will be lifted soon. I’d love to post my thoughts about DUST. With this integration now happening so soon, how are you going to participate in DUST related activities – PC or PS3? Source:
def dimension(self, obj): if not obj: raise NoSuchDimensionError("Requested dimension should not be " "none (cube '{}')".forma(self.name)) name = str(obj) try: return self._dimensions[str(name)] except KeyError: raise NoSuchDimensionError("cube '{}' has no dimension '{}'" .format(self.name, name))
def calculate_risk_surface(lyr, age, dist, halflife, halfdist): dist_raster = arcpy.sa.EucDistance(lyr, dist) max_temporal_risk = 1.0 k_temporal = math.log(0.5)/-halflife k_spatial = math.log(0.5)/-halfdist dist_raster = arcpy.sa.Exp(dist_raster * -k_spatial) inc_raster = max_temporal_risk * math.exp(-age * k_temporal) * dist_raster null_locations = arcpy.sa.IsNull(inc_raster) inc_raster = arcpy.sa.Con(null_locations, 0, inc_raster, where_clause="Value = 1") return inc_raster
import React from "react"; import { Story } from "@storybook/react"; import { NewRoomNotification, NewRoomNotificationProps, } from "../../ui/NotificationElement/NewRoomNotification"; export default { title: "Notification/NewRoomNotification", component: NewRoomNotification, }; export const Default: Story<NewRoomNotificationProps> = ({ ...props }) => ( <NewRoomNotification {...props} username={props.username || "johndoe"} /> ); Default.bind({});
// Spring WS Implementation @Service @Transactional public class AccountReceivableServiceImpl implements AccountReceivableService { @Autowired AccountReceivableDao accountReceivableDao; @Override public InvoicedProducts getInvProduct(Integer id) { InvoicedProducts invProdWS = new InvoicedProducts(); Invoice invWS = new Invoice(); PaymentAp paymentWS = new PaymentAp(); invProdWS.setId(accountReceivableDao.getInvoicedProduct(id).getId()); invProdWS.setCatId(accountReceivableDao.getInvoicedProduct(id).getCatId()); invProdWS.setInvId(accountReceivableDao.getInvoicedProduct(id).getInvId()); invWS.setId(accountReceivableDao.getInvoicedProduct(id).getInvoice().getId()); invWS.setCatId(accountReceivableDao.getInvoicedProduct(id).getInvoice().getCatId()); invWS.setCustId(accountReceivableDao.getInvoicedProduct(id).getInvoice().getCustId()); paymentWS.setId(accountReceivableDao.getInvoicedProduct(id).getInvoice().getPaymentAp().getId()); paymentWS.setTerm(accountReceivableDao.getInvoicedProduct(id).getInvoice().getPaymentAp().getTerm()); invWS.setDate(null); invWS.setPaymentAp(paymentWS); invProdWS.setInvoice(invWS); return invProdWS; } @Override public List<InvoicedProducts> getInvProducts() { List<InvoicedProducts> lists = new ArrayList<>(); return lists; } @Override public void setInvoicedProduct(InvoicedProducts invoicedProduct) { // TODO Auto-generated method stub } }
/* * Convert string input module parms. Accept either the * number of the mode or its string name. */ static inline int bond_parse_parm(char *mode_arg, struct bond_parm_tbl *tbl) { int i; for (i = 0; tbl[i].modename; i++) { if ((isdigit(*mode_arg) && tbl[i].mode == simple_strtol(mode_arg, NULL, 0)) || (strncmp(mode_arg, tbl[i].modename, strlen(tbl[i].modename)) == 0)) { return tbl[i].mode; } } return -1; }
// UseReward use reward by id. func (d *Dao) UseReward(id int64, usePlat string) (rst bool, err error) { if err := d.orm. Model(&model.AnchorReward{}). Where("id=?", id). Update(map[string]interface{}{"status": model.RewardUsed, "use_plat": usePlat, "use_time": xtime.Time(time.Now().Unix())}).Error; err != nil { log.Error("useReward (%v) error(%v)", id, err) return rst, err } rst = true return }