content
stringlengths
10
4.9M
# include <cstdio> int main() { char x = getchar(); if( x >= 'a' && x <= 'z' ) putchar(x-32); else putchar(x); while( (x=getchar()) != '\n' ) putchar(x); return 0; }
def _transform_depthmap(self, verts_3d, intrinsics, R_mat, t_mat, orig_size): verts_3d_cam = self.convert_depthmap_to_cam(verts_3d, intrinsics, orig_size) verts_3d_cam = verts_3d_cam.transpose(2, 1) pose_mat = torch.cat([R_mat, t_mat], dim=2) verts_3d_ones = torch.ones_like(verts_3d_cam[:, :1, :]) verts_3d_cam_hom = torch.cat((verts_3d_cam, verts_3d_ones), 1) verts_3d_cam2 = (pose_mat @ verts_3d_cam_hom).transpose(2, 1) verts_3d_depth2 = self.project_cam_to_depthmap(verts_3d_cam2, intrinsics, orig_size) return verts_3d_depth2
import { Component, FormEvent } from "react"; import { Navigate } from "react-router"; import UsuarioService from "../../service/usuario.service"; type UsuarioForm = { nome: string; email: string; redirect: boolean; } class UserCreate extends Component<{}, UsuarioForm> { constructor(props: any) { super(props); this.state = { nome: '', email: '', redirect: false }; this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e: FormEvent<HTMLFormElement>) { e.preventDefault(); const { nome, email } = this.state; if (nome && email) { UsuarioService.adicionar({ nome: this.state.nome, email: this.state.email }); alert('Usuário cadastrado com sucesso!'); this.setState({ ...this.state, redirect: true }); } } render() { const { redirect } = this.state; if (redirect) { return <Navigate to='/users' />; } return ( <form onSubmit={this.handleSubmit}> <div className="mb-3"> <label htmlFor="nome" className="form-label">Nome</label> <input type="text" className="form-control" id="nome" placeholder="Digite o nome" required onChange={(e) => this.setState({ nome: e.target.value })} /> </div> <div className="mb-3"> <label htmlFor="email" className="form-label">E-mail</label> <input type="email" className="form-control" id="email" placeholder="Digite o e-mail" required onChange={(e) => this.setState({ email: e.target.value })} /> </div> <button type="submit" className="btn btn-primary">Salvar</button> </form> ); } } export default UserCreate;
/** Sort the array, according to the comparator. */ @SuppressWarnings("unchecked") private static <E> void sort( Object[] array, Comparator<? super E> comparator) { Arrays.sort(array, (Comparator<Object>) comparator); }
// Level to stat string conversion func (level Level) statString() *string { switch level { case PanicLevel: return &panicStat case FatalLevel: return &fatalStat case ErrorLevel: return &errorStat case WarnLevel: return &warnStat case TraceLevel: return &traceStat case InfoLevel: return &infoStat case DebugLevel: return &debugStat } return &noStat }
import { commandRunner, getCommitMessage, gitSHASerializer, initFixtureFactory } from "@lerna/test-helpers"; import path from "path"; // eslint-disable-next-line jest/no-mocks-import jest.mock("@lerna/core", () => require("@lerna/test-helpers/__mocks__/@lerna/core")); jest.mock("./git-push"); jest.mock("./is-anything-committed", () => ({ isAnythingCommitted: jest.fn().mockReturnValue(true), })); jest.mock("./is-behind-upstream", () => ({ isBehindUpstream: jest.fn().mockReturnValue(false), })); jest.mock("./remote-branch-exists", () => ({ remoteBranchExists: jest.fn().mockResolvedValue(true), })); const initFixture = initFixtureFactory(path.resolve(__dirname, "../../../publish")); // test command // eslint-disable-next-line @typescript-eslint/no-var-requires const lernaVersion = commandRunner(require("../command")); // stabilize commit SHA expect.addSnapshotSerializer(gitSHASerializer); test("publish --message %s", async () => { const cwd = await initFixture("normal"); await lernaVersion(cwd)("--message", "chore: Release %s :rocket:"); const message = await getCommitMessage(cwd); expect(message).toMatch("chore: Release v1.0.1 :rocket:"); }); test("publish --message %v", async () => { const cwd = await initFixture("normal"); await lernaVersion(cwd)("--message", "chore: Version %v without prefix"); const message = await getCommitMessage(cwd); expect(message).toMatch("chore: Version 1.0.1 without prefix"); }); test("publish -m --independent", async () => { const cwd = await initFixture("independent"); await lernaVersion(cwd)("-m", "chore: Custom publish message subject"); const message = await getCommitMessage(cwd); expect(message).toMatch("chore: Custom publish message subject"); });
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "smtk/extension/paraview/widgets/plugin/pqSMTKWidgetsAutoStart.h" #include "smtk/view/Selection.h" #include "smtk/extension/paraview/widgets/plugin/pqSMTKConeItemWidget.h" #include "smtk/extension/paraview/widgets/plugin/pqSMTKInfiniteCylinderItemWidget.h" #include "smtk/extension/paraview/widgets/plugin/pqSMTKLineItemWidget.h" #include "smtk/extension/paraview/widgets/plugin/pqSMTKPlaneItemWidget.h" #include "smtk/extension/paraview/widgets/plugin/pqSMTKPointItemWidget.h" #include "smtk/extension/paraview/widgets/plugin/pqSMTKSphereItemWidget.h" #include "smtk/extension/paraview/widgets/plugin/pqSMTKSplineItemWidget.h" #include "smtk/extension/paraview/widgets/pqSMTKBoxItemWidget.h" #include "smtk/extension/paraview/widgets/pqSMTKTransformWidget.h" #include "smtk/extension/paraview/widgets/qtSimpleExpressionEvaluationView.h" #include "smtk/extension/qt/qtSMTKUtilities.h" #include "pqApplicationCore.h" #include "pqObjectBuilder.h" pqSMTKWidgetsAutoStart::pqSMTKWidgetsAutoStart(QObject* parent) : Superclass(parent) { } pqSMTKWidgetsAutoStart::~pqSMTKWidgetsAutoStart() = default; void pqSMTKWidgetsAutoStart::startup() { /* auto pqCore = pqApplicationCore::instance(); if (pqCore) { } */ // Register qtItem widget subclasses implemented using ParaView 3-D widgets: qtSMTKUtilities::registerItemConstructor("Box", pqSMTKBoxItemWidget::createBoxItemWidget); qtSMTKUtilities::registerItemConstructor("Cone", pqSMTKConeItemWidget::createConeItemWidget); qtSMTKUtilities::registerItemConstructor( "Cylinder", pqSMTKConeItemWidget::createCylinderItemWidget); qtSMTKUtilities::registerItemConstructor( "InfiniteCylinder", pqSMTKInfiniteCylinderItemWidget::createCylinderItemWidget); qtSMTKUtilities::registerItemConstructor("Line", pqSMTKLineItemWidget::createLineItemWidget); qtSMTKUtilities::registerItemConstructor("Plane", pqSMTKPlaneItemWidget::createPlaneItemWidget); qtSMTKUtilities::registerItemConstructor("Point", pqSMTKPointItemWidget::createPointItemWidget); qtSMTKUtilities::registerItemConstructor( "Sphere", pqSMTKSphereItemWidget::createSphereItemWidget); qtSMTKUtilities::registerItemConstructor( "Spline", pqSMTKSplineItemWidget::createSplineItemWidget); qtSMTKUtilities::registerItemConstructor( "Transform", pqSMTKTransformWidget::createTransformWidget); } void pqSMTKWidgetsAutoStart::shutdown() { /* auto pqCore = pqApplicationCore::instance(); if (pqCore) { } */ }
<filename>fuzz/input-fuzzer.c /* * Copyright (c) 2020 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stddef.h> #include <assert.h> #include <fcntl.h> #include "tmux.h" #define FUZZER_MAXLEN 512 #define PANE_WIDTH 80 #define PANE_HEIGHT 25 struct event_base *libevent; int LLVMFuzzerTestOneInput(const u_char *data, size_t size) { struct bufferevent *vpty[2]; struct window *w; struct window_pane *wp; int error; /* * Since AFL doesn't support -max_len paramenter we have to * discard long inputs manually. */ if (size > FUZZER_MAXLEN) return 0; w = window_create(PANE_WIDTH, PANE_HEIGHT, 0, 0); wp = window_add_pane(w, NULL, 0, 0); bufferevent_pair_new(libevent, BEV_OPT_CLOSE_ON_FREE, vpty); wp->ictx = input_init(wp, vpty[0], NULL); window_add_ref(w, __func__); wp->fd = open("/dev/null", O_WRONLY); if (wp->fd == -1) errx(1, "open(\"/dev/null\") failed"); wp->event = bufferevent_new(wp->fd, NULL, NULL, NULL, NULL); input_parse_buffer(wp, (u_char *)data, size); while (cmdq_next(NULL) != 0) ; error = event_base_loop(libevent, EVLOOP_NONBLOCK); if (error == -1) errx(1, "event_base_loop failed"); assert(w->references == 1); window_remove_ref(w, __func__); bufferevent_free(vpty[0]); bufferevent_free(vpty[1]); return 0; } int LLVMFuzzerInitialize(__unused int *argc, __unused char ***argv) { const struct options_table_entry *oe; global_environ = environ_create(); global_options = options_create(NULL); global_s_options = options_create(NULL); global_w_options = options_create(NULL); for (oe = options_table; oe->name != NULL; oe++) { if (oe->scope & OPTIONS_TABLE_SERVER) options_default(global_options, oe); if (oe->scope & OPTIONS_TABLE_SESSION) options_default(global_s_options, oe); if (oe->scope & OPTIONS_TABLE_WINDOW) options_default(global_w_options, oe); } libevent = osdep_event_init(); options_set_number(global_w_options, "monitor-bell", 0); options_set_number(global_w_options, "allow-rename", 1); options_set_number(global_options, "set-clipboard", 2); socket_path = xstrdup("dummy"); return 0; }
Athletic Director Dave Brandon is dreaming. It’s the night of Michigan’s Spring Game, which took place on the same weekend that Brandon unveiled the lavish new Schembechler Hall as well as the announcement of a preseason international soccer game that will be played in Michigan Stadium in August. In the dream, Brandon is interrupted on the walk to his car by a statue. The imposing figure is Bo Schembechler, the most famous figure in Michigan sports. It’s the first outdoor statue of an individual in the 197 years of the University, all part of the new renovation to the football facilities. Confused, Brandon walks over to the statue. Bo Schembechler: Dave, it’s been a while. Gotta admit, I don’t love this new statue, but you’re the boss now, not me. Dave Brandon: I knew you’d be too humble to be a fan of it, but it’s a great opportunity to draw attention to the Michigan brand. Did you see the Towsley Museum inside the new Hall? It’ll be a great recruiting tool. BS: Looks great. Has getting recruits really been an issue over the last few years? DB: Well, no. We’ve had a top-20 recruiting class every year for the past three seasons, actually. Our ‘J. Ira and Nicki Harris Family Head Football Coach,’ Brady Hoke, is quite the recruiter. BS: Sounds like it. The team has got to be pretty successful then, right? DB: Well, sort of. We won the Sugar Bowl in 2011, but last season we got to just seven wins. Had one of the worst offensive lines in college football even though an NFL team will draft two of the five starters in May. Rushed for minus-48 yards against Michigan State. Got beat up by Kansas State in the Buffalo Wild Wings Bowl. But, we’ve got an exciting schedule the next two years against non-rivalry teams. Appalachian State. Utah. Miami (Ohio). BYU. Oregon State. UNLV. Playing against new opponents is a great way to build our brand, plus, we’re almost through with having to play Notre Dame. Thank God. Those games were always so boring. BS: But is the team going to be any good? How’d they do in the Spring Game? DB: Bo, sorry, but it’s the Spring Game presented by PNC. Sponsoring every event we run helps build the brand. Anyway, it went fine. Devin Gardner threw an interception on the first play of the day and couldn’t place any throws, the offensive line could be even worse than last season’s and we didn’t have enough depth to play an actual game, but besides that, I think people were excited! Must be leftover from the Big House soccer announcement. BS: What soccer announcement? I didn’t think the Michigan soccer team could draw that many people! DB: Well, err, it’s not exactly related to Michigan. But it’s very exciting. Two of the most famous clubs in the word, Real Madrid and Manchester United, will be playing a friendly in the Big House in August. Trying to set the record for most fans to ever witness a soccer game. After the success of the Winter Classic, I think it’ll go well. Great for the brand. BS: So in the span of nine months, Michigan will be hosting two events that have nothing to do with the University? What’s next, Dave? A WWE match? An NBA game? A NASCAR race? DB: Those are actually great ideas! Let me write some of those down. Can’t ever have too many opportunities to build the brand. BS: I mean, is the money at least going toward something worthwhile? DB: Of course! Some of it’s going toward general student scholarships, but we’re also going to construct a new soccer facility. BS: The old stadium must be pretty run down, then? DB: Oh, yeah. I mean the thing was built in 2010. How am I supposed to build the brand with all these decrepit old facilities? BS: So you’re doing a lot of construction projects, then? DB: Of course! Yost Ice Arena and the Crisler Center just got facelifts, and we’re redoing the entire South Campus. We’re getting rid of all the old buildings and facilities, like Ferry Field, and creating the shiny new Stephen M. Ross Athletic Campus. All of these brand new buildings will really show off the rich tradition and history of Michigan. BS: You’re getting rid of historic Ferry Field? Where Jesse Owens set four world records in 45 minutes? What new facility is going there? DB: Well, actually, a parking lot. But that’s beside the point. BS: Dave, I don’t know about that. Can I give you some advice? DB: Always, coach. BS: You’re focusing too much on building up a brand that already exists. The influence and power of Michigan existed well before you, and it will exist far after you. You know what builds brands? Winning. The basketball team didn’t build up its brand with that fancy new Crisler Center or with those highlighter Adidas jerseys. It built up that brand by making two Elite Eight games in two seasons, without excuses about age or anything else. That team just won, plain and simple, and that’s why that brand is so popular. The same thing will happen with football, or anything else. Start treating Michigan like the historic place it is, not like a second-rate university that needs to make a splash on the national scene. This was Michigan well before you got here, Dave. Don’t lose sight of that. Brandon begins to respond, but the Schembechler statue is frozen again. The athletic director stands there for a few seconds, scratching his head, before getting into his car and driving home. His dream only ends when every last piece of pizza from the Domino’s box in Brandon’s car is gone. Cook can be reached at [email protected] and on Twitter @everettcook
While past presidential candidates have done all they can to appear relatable and responsible when it comes to their personal finances, it has become clear that those rules don’t seem to apply to Donald Trump. Trump’s wealth and perceived independence from donors and their concerns allows him to almost circle back around. His cartoonish displays, most recently chronicled in a New York Times profile of his longtime Palm Beach butler, are so outlandish as to appear relatable once more. After all, if you woke up one morning and found yourself facing a Brewster’s Millions scenario (most Americans’ best shot at social mobility), you might conduct yourself in a similar fashion. Rubio: Trump is 'an embarrassment' and Republicans will pay big in November Read more With Trump we get both stereotypes of the uber-wealthy in one: the savvy miser and the clueless, good-time goober. This is a man who already managed to buy the so-called “Winter White House” for a relative pittance and turned it into a private club. He’s the hedonist who doesn’t drink. Butler Arthur Senecal has worked at Mar-a-Lago for Trump for 30 years. While he makes sure the gold-pot dictator’s Shangri-La runs smoothly, Senecal is more than just domestic help. He’s something between a wet nurse and a cheering squad, a real-life Mr Smithers. In one of many juicy tidbits from the Times profile, it is revealed that Senecal once arranged for a bugler to play Hail to the Chief upon his boss’s arrival. He also routinely fluffs Trump’s golf drives and calls the airport tower to complain about the noise of passing planes. This level of delusion and pageantry is much more extreme than any of the 1%-ish missteps that have shaken or derailed recent so-called “establishment” candidates of both parties. In 2012, Mitt Romney was ridiculed for his appreciation of “Papa” John Schnatter’s Kentucky estate (including personal golf course), not to mention the infamous, secretly recorded “47%” address. Go back a bit further and there’s John Kerry’s disastrous windsurfing habit, John McCain’s eight houses and George HW Bush’s inability to price-check a gallon of milk. But those assets and vulnerabilities belonged to less seismic campaigns and less bombastic candidates. And perhaps if previous candidates had embraced their wealth and privilege to the same extent as Trump, they might have been lauded in much the same way. Most Americans don’t want a “loser” in the Oval Office. We appreciate success and understand the resources it takes to even consider launching a campaign on a national scale. Voters know that no matter how fervent their support, they won’t be welcome at Mar-a-Lago any time soon. But most appreciate Trump’s desire to shape his world to his exact specifications. And the end result – the gaudy echo chamber maintained by Senecal – is not much different from the blinkered thinking of establishment politicians who send their kids to private schools while stripping education budgets, and worship wealth but refuse to speak its name or acknowledge its influence. Given those choices, voters might figure they’re better off with an ostentatious type. Perhaps for all the pomp and gold leaf, Trump and Mar-a-Lago remain more relatable than the traditional outposts of Wasp wealth. Because while not everybody can point out Nantucket or Walker’s Point on the map, everybody knows Richie Rich.
use std::env; use std::process; use std::error::Error; use std::fs; struct Config { day: String, filename: String, } impl Config { fn new (mut args: env::Args) -> Result<Config, &'static str> { args.next(); let day = match args.next() { Some(arg) => arg, None => return Err("didn't get a day"), }; let filename = match args.next() { Some(arg) => arg, None => return Err("didnt get a filename"), }; Ok(Config { day, filename, }) } } fn main() { let args = env::args(); let config = Config::new(args).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); process::exit(1); }); if let Err(e) = run(config) { eprintln!("Application error: {}", e); process::exit(1); } } fn run(config: Config) -> Result<(), Box<dyn Error>> { let filepath = format!("./Files/{}/{}",config.day, config.filename); let contents = fs::read_to_string(filepath)?; match config.day.as_str() { "day1" => day1(&contents), "day2" => day2(&contents), "day3" => day3(&contents), _ => (), } Ok(()) } fn day1(contents: &str) { let mut result = 0; for line in contents.lines() { for line1 in contents.lines() { let line_as_int = line.parse::<i32>().unwrap(); let line1_as_int = line1.parse::<i32>().unwrap(); if line_as_int + line1_as_int == 2020 { //println!{"{}, {}", line_as_int, line1_as_int} result = line_as_int * line1_as_int } } } println!{"{}", result} let mut result1 = 0; for line in contents.lines() { for line1 in contents.lines() { for line2 in contents.lines() { let line_as_int = line.parse::<i32>().unwrap(); let line1_as_int = line1.parse::<i32>().unwrap(); let line2_as_int = line2.parse::<i32>().unwrap(); if line_as_int + line1_as_int + line2_as_int== 2020 { result1 = line_as_int * line1_as_int * line2_as_int } } } } println!{"{}", result1} } fn day2(contents: &str) { #[derive(Debug)] struct Entry<'a>{ policy: (u32, u32), letter: char, password: &'a str, } impl Entry<'_> { fn validate_password(&self) -> bool { let count = self.password.matches(|ch| ch == self.letter).count(); //println!("{}", count); let count = count as u32; self.policy.0 <= count && count <= self.policy.1 } fn validate_password1 (&self) -> bool { let chars: Vec<(usize, char)> = self.password.char_indices().collect(); let pos_one = chars[self.policy.0 as usize -1]; let pos_two = chars[self.policy.1 as usize -1]; if pos_one.1 == self.letter && pos_two.1 != self.letter || pos_one.1 != self.letter && pos_two.1 == self.letter { return true } false } } let mut count = 0; let mut count_1 = 0; for line in contents.lines() { let mut iter = line.split_ascii_whitespace(); let mut policy: (u32, u32) = (0,0); if let Some(first) = iter.next() { let mut char_iter = first.split("-"); // println!("{}", first); let lower_bound = char_iter.next().expect("no lower bound"); let upper_bound = char_iter.next().expect("no upper bound"); // println!("{}-{}", upper_bound, lower_bound); policy = (lower_bound.parse().unwrap(), upper_bound.parse().unwrap()); }; let mut letter: char = ' '; if let Some(given_letter) = iter.next() { let mut char_iter = given_letter.chars(); letter = char_iter.next().expect("no given char"); } let mut password: &str = " "; if let Some(pw) = iter.next() { password = pw; } let entry = Entry { policy, letter, password, }; let result = entry.validate_password(); let result1 = entry.validate_password1(); //println!("{}", result); if result { count = count + 1; } if result1 { count_1 = count_1 + 1; } } println!("{}", count); println!("{}", count_1) } fn day3(contents: &str) { let lines = contents.lines(); let mut base: Vec<Vec<char>> = vec![]; for line in lines { let second_dimension: Vec<char> = line.chars().collect(); base.push(second_dimension); } fn check_slope(terrain: &mut Vec<Vec<char>>, row_increment: usize, column_increment: usize) -> usize { let compare = '#'; let mut count = 0; let mut row_index = 0; let mut column_index = 0; while row_index < terrain.len() { if terrain[row_index][column_index % terrain[0].len()] == compare { count = count + 1; } row_index = row_index + row_increment; column_index = column_index + column_increment; } println!("Count of #: {}", count); return count; } let mut row_increment = 1; let mut column_increment = 1; let count_1 = check_slope(& mut base, row_increment, column_increment); column_increment = 3; let count_2 = check_slope(& mut base, row_increment, column_increment); column_increment = 5; let count_3 = check_slope(& mut base, row_increment, column_increment); column_increment = 7; let count_4 = check_slope(& mut base, row_increment, column_increment); column_increment = 1; row_increment = 2; let count_5 = check_slope(& mut base, row_increment, column_increment); let counts_multiplied = count_1 * count_2 * count_3 * count_4 * count_5; println!("Count of # with 1,3: {}", count_2); println!("Count of #: {}", counts_multiplied); }
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #define inf 0x3fffffff #define rep(i,s,e) for (int i=(s);i<(e);i++) using namespace std; struct da { int dt,nx; }a[400000]; int fir[200000],v[200000],w[200000],f[200000]; int asd[200000]; int ans,a0; void build(int x,int y) { a0++; a[a0].dt=y; a[a0].nx=fir[x]; fir[x]=a0; } void dfs(int x,int d,int sum1,int sum2) { int tmp1=sum1,tmp2=sum2; if (d%2==0) v[x]^=sum1; else v[x]^=sum2; if (v[x]!=w[x]) { asd[ans++]=x; if (d%2==0) tmp1^=1; else tmp2^=1; } int t=fir[x]; while (t>0) { if (a[t].dt!=f[x]) { f[a[t].dt]=x; dfs(a[t].dt,d+1,tmp1,tmp2); } t=a[t].nx; } return ; } int main() { int n; scanf("%d",&n); rep(i,0,n-1) { int x,y; scanf("%d %d",&x,&y); build(x,y); build(y,x); } rep(i,1,n+1) scanf("%d",&v[i]); rep(i,1,n+1) scanf("%d",&w[i]); ans=0; f[1]=0; dfs(1,0,0,0); cout<<ans<<endl; rep(i,0,ans) cout<<asd[i]<<endl; return 0; }
/** * Reads a single line from the server, using either \r\n or \n as the delimiter. The delimiter * char(s) are not included in the result. */ public String readLine(boolean loggable) throws IOException { StringBuffer sb = new StringBuffer(); InputStream in = getInputStream(); int d; while ((d = in.read()) != -1) { if (((char) d) == '\r') { continue; } else if (((char) d) == '\n') { break; } else { sb.append((char) d); } } if (d == -1) { LogUtils.d(TAG, "End of stream reached while trying to read line."); } String ret = sb.toString(); if (loggable) { LogUtils.d(TAG, "<<< " + ret); } return ret; }
<reponame>mythoss/midpoint /* * Copyright (c) 2010-2017 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.schema.processor; import java.util.Collection; import java.util.List; import javax.xml.namespace.QName; import com.evolveum.midpoint.prism.Definition; import org.jetbrains.annotations.NotNull; import com.evolveum.midpoint.prism.PrismContainerDefinition; import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAttributesType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; /** * TODO review docs * * Resource Object Definition (Object Class). * * Object Class refers to a type of object on the Resource. Unix account, Active * Directory group, inetOrgPerson LDAP objectclass or a schema of USERS database * table are all Object Classes from the midPoint point of view. Object class * defines a set of attribute names, types for each attributes and few * additional properties. * * This class represents schema definition for resource object (object class). * See {@link Definition} for more details. * * Resource Object Definition is immutable. TODO: This will probably need to be changed to a mutable object. * * @author <NAME> */ public interface ResourceAttributeContainerDefinition extends PrismContainerDefinition<ShadowAttributesType> { @Override ResourceObjectDefinition getComplexTypeDefinition(); /** * TODO review docs * * Returns the definition of primary identifier attributes of a resource object. * * May return empty set if there are no identifier attributes. Must not * return null. * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. * * @return definition of identifier attributes * @throws IllegalStateException * if there is no definition for the referenced attributed */ Collection<? extends ResourceAttributeDefinition<?>> getPrimaryIdentifiers(); /** * TODO review docs * * Returns the definition of secondary identifier attributes of a resource * object. * * May return empty set if there are no secondary identifier attributes. * Must not return null. * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. * * @return definition of secondary identifier attributes * @throws IllegalStateException * if there is no definition for the referenced attributed */ Collection<? extends ResourceAttributeDefinition<?>> getSecondaryIdentifiers(); Collection<? extends ResourceAttributeDefinition<?>> getAllIdentifiers(); /** * TODO review docs * * Returns the definition of description attribute of a resource object. * * Returns null if there is no description attribute. * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. * * @return definition of secondary identifier attributes * @throws IllegalStateException * if there is more than one description attribute. But this * should never happen. * @throws IllegalStateException * if there is no definition for the referenced attributed */ ResourceAttributeDefinition<?> getDescriptionAttribute(); /** * TODO review docs * * Specifies which resource attribute should be used as a "technical" name * for the account. This name will appear in log files and other troubleshooting * tools. The name should be a form of unique identifier that can be used to * locate the resource object for diagnostics. It should not contain white chars and * special chars if that can be avoided and it should be reasonable short. * It is different from a display name attribute. Display name is intended for a * common user or non-technical administrator (such as role administrator). The * naming attribute is intended for technical IDM administrators and developers. * * @return resource attribute definition that should be used as a "technical" name * for the account. */ ResourceAttributeDefinition<?> getNamingAttribute(); /** * TODO review docs * * Returns the native object class string for the resource object. * * Native object class is the name of the Resource Object Definition (Object * Class) as it is seen by the resource itself. The name of the Resource * Object Definition may be constrained by XSD or other syntax and therefore * may be "mangled" to conform to such syntax. The <i>native object * class</i> value will contain un-mangled name (if available). * * Returns null if there is no native object class. * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. * * @return native object class * @throws IllegalStateException * if there is more than one description attribute. */ String getNativeObjectClass(); /** * TODO review docs * * Indicates whether definition is should be used as default account type. * * If true value is returned then the definition should be used as a default * account type definition. This is a way how a resource connector may * suggest applicable object classes (resource object definitions) for * accounts. * * If no information about account type is present, false should be * returned. This method must return true only if isAccountType() returns * true. * * The exception should be never thrown unless there is some bug in the * code. The validation of at-most-one value should be done at the time of * schema parsing. The exception may not even be thrown at all if the * implementation is not able to determine duplicity. * * @return true if the definition should be used as account type. * @throws IllegalStateException * if more than one default account is suggested in the schema. */ boolean isDefaultAccountDefinition(); /** * TODO review docs * * Returns the definition of display name attribute. * * Display name attribute specifies which resource attribute should be used * as title when displaying objects of a specific resource object class. It * must point to an attribute of String type. If not present, primary * identifier should be used instead (but this method does not handle this * default behavior). * * Returns null if there is no display name attribute. * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. * * @return native object class * @throws IllegalStateException * if there is more than one display name attribute or the * definition of the referenced attribute does not exist. */ ResourceAttributeDefinition<?> getDisplayNameAttribute(); @NotNull ResourceAttributeContainer instantiate(); @NotNull ResourceAttributeContainer instantiate(QName name); @NotNull ResourceAttributeContainerDefinition clone(); <T> ResourceAttributeDefinition<T> findAttributeDefinition(QName elementQName, boolean caseInsensitive); ResourceAttributeDefinition<?> findAttributeDefinition(ItemPath elementPath); ResourceAttributeDefinition<?> findAttributeDefinition(String localName); List<? extends ResourceAttributeDefinition<?>> getAttributeDefinitions(); // Only attribute definitions should be here. @Override @NotNull List<? extends ResourceAttributeDefinition<?>> getDefinitions(); @NotNull <T extends ShadowType> PrismObjectDefinition<T> toShadowDefinition(); }
package android.io.mobilestudio.fcmNotification; import android.content.DialogInterface; import android.content.SharedPreferences; import android.io.piso.fcmNotification.managers.FCMSubscriptionManager; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class FCMSubscriptionActivity extends AppCompatActivity implements View.OnClickListener { ListView listView; List<String> values; Button subscribe, unSubscribeAll; ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fcmsubscription); values = new ArrayList<>(); listView = (ListView) findViewById(R.id.list_item); subscribe = (Button) findViewById(R.id.bt_subscribe); unSubscribeAll = (Button) findViewById(R.id.bt_unsubscribeAll); subscribe.setOnClickListener(this); unSubscribeAll.setOnClickListener(this); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values); listView.setAdapter(adapter); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) { FCMSubscriptionManager.getInstance(FCMSubscriptionActivity.this).unsubscribeFromTopic(values.get(i)); values.remove(i); adapter.notifyDataSetChanged(); return true; } }); } @Override public void onClick(View view) { switch ((view.getId())) { case R.id.bt_subscribe: launchAddExtraData(); break; case R.id.bt_unsubscribeAll: UnSubscribeAll(); values.clear(); adapter.notifyDataSetChanged(); break; } } private void launchAddExtraData() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(FCMSubscriptionActivity.this); alertDialog.setMessage("Enter channel name"); final EditText name = new EditText(FCMSubscriptionActivity.this); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); name.setLayoutParams(lp); name.setHint("Name"); alertDialog.setView(name); LinearLayout LL = new LinearLayout(this); LL.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams LLParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); LL.setWeightSum(6f); LL.setLayoutParams(LLParams); LL.addView(name); alertDialog.setView(LL); alertDialog.setPositiveButton("Add", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (!name.getText().toString().isEmpty()) { values.add(name.getText().toString()); adapter.notifyDataSetChanged(); FCMSubscriptionManager.getInstance(FCMSubscriptionActivity.this).subscribeToTopic(name.getText().toString()); } else { Toast.makeText(FCMSubscriptionActivity.this, "Please enter name ", Toast.LENGTH_SHORT).show(); } } }); alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } public void UnSubscribeAll() { for (String value : values) { FCMSubscriptionManager.getInstance(this).unsubscribeFromTopic(value); } } private boolean saveArray() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor mEdit1 = sp.edit(); mEdit1.putInt("Status_size1", values.size()); for (int i = 0; i < values.size(); i++) { mEdit1.remove("Status_" + i); mEdit1.putString("Status1_" + i, values.get(i)); } mEdit1.apply(); return mEdit1.commit(); } private void loadArray() { SharedPreferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(this); values.clear(); int size = mSharedPreference1.getInt("Status_size1", 0); for (int i = 0; i < size; i++) { values.add(mSharedPreference1.getString("Status1_" + i, null)); } } @Override protected void onPause() { super.onPause(); saveArray(); } @Override protected void onResume() { super.onResume(); loadArray(); adapter.notifyDataSetChanged(); } }
Membrane Phosphatidylserine Regulates Surface Charge and Protein Localization Electrostatic interactions with negatively charged membranes contribute to the subcellular targeting of proteins with polybasic clusters or cationic domains. Although the anionic phospholipid phosphatidylserine is comparatively abundant, its contribution to the surface charge of individual cellular membranes is unknown, partly because of the lack of reagents to analyze its distribution in intact cells. We developed a biosensor to study the subcellular distribution of phosphatidylserine and found that it binds the cytosolic leaflets of the plasma membrane, as well as endosomes and lysosomes. The negative charge associated with the presence of phosphatidylserine directed proteins with moderately positive charge to the endocytic pathway. More strongly cationic proteins, normally associated with the plasma membrane, relocalized to endocytic compartments when the plasma membrane surface charge decreased on calcium influx.
// Given a cubic and a t-range, determine if the stroke can be described by a quadratic. SkPathStroker::ResultType SkPathStroker::tangentsMeet(const SkPoint cubic[4], SkQuadConstruct* quadPts) { this->cubicQuadEnds(cubic, quadPts); return this->intersectRay(quadPts, kResultType_RayType STROKER_DEBUG_PARAMS(fRecursionDepth)); }
<gh_stars>1-10 import { Field, ID, ObjectType } from '@nestjs/graphql' import { ProposalStatus } from 'src/common/enums' import { Coin } from 'src/common/models' import { ProposalContentUnion, ProposalContentType } from 'src/common/unions' import { Tally } from './tally.model' @ObjectType() export class Proposal { @Field(() => ID) id!: number @Field(() => ProposalContentUnion) content!: ProposalContentType @Field(() => ProposalStatus) status!: number @Field(() => Tally) final_tally_result?: Tally @Field() submit_time!: string @Field() deposit_end_time!: string @Field(() => [Coin]) total_deposit!: Coin[] @Field() voting_start_time!: string @Field() voting_end_time!: string }
from bs4 import BeautifulSoup import requests import dconlib from time import sleep def getlist(pg,url2): namelist = [] web_url = "https://dccon.dcinside.com/hot/"+str(pg)+url2 with requests.get(web_url) as response: #html = response.read() soup = BeautifulSoup(response.text, 'html.parser') unorder = soup.find('ul', {'class' : 'dccon_shop_list hotdccon clear'}) lis = unorder.find_all('li') for i in lis: a = i.find('a') name = a.find('strong') namelist.append([name.text,i['package_idx']]) return namelist def main(): url2 = "/title/" + str(input("검색어를 입력하세요: ")) web_url = "https://dccon.dcinside.com/hot/1"+url2 selindex=[] i=1 with requests.get(web_url) as response: #html = response.read() soup = BeautifulSoup(response.text, 'html.parser') if type(soup.find('div', {'class' : 'dccon_search_none'})) == type(None): if type(soup.find('a', {'class' : 'page_end'})) != type(None): endpg = soup.find('a', {'class' : 'page_end'})['href'].split("/")[4] else: if type(soup.find('div', {'class':'bottom_paging_box'}).find('a')) != type(None): endpg = soup.find('div', {'class':'bottom_paging_box'}).find_all('a')[0]['href'].split("/")[4] else: endpg = 1 else: print("검색결과가 없습니다. 프로그램을 종료합니다.") sleep(2) exit() while True: try: print() dclist=getlist(i,url2) for idx, con in enumerate(dclist): print("[ {:^3} ]:".format(idx),con[0]) print("페이지 (",i,"/",endpg,")") inps = str(input("번호를 입력하세요(이전:b,다음:n): ")).split() for inp in inps: if inp == 'n' or inp == 'N': if i==endpg: print("마지막 페이지입니다.") else: i+=1 elif inp == 'b' or inp == 'B': if i==1: print("첫번째 페이지입니다.") else: i-=1 elif int(inp) >= 0 and int(inp)<len(dclist): selindex.append(dclist[int(inp)][1]) else: print("잘못 입력했습니다.") if len(selindex) >= 1: break except ValueError: print("값이 잘못됐습니다.") print() for dlist in selindex: dconlib.condown(dlist) print("\n다운로드를 완료했습니다.") sleep(2) if __name__ == '__main__': main()
import { ProvenanceGraph } from '@visdesignlab/provenance-lib-core'; import { createContext } from 'react'; import { AppConfig } from './AppConfig'; import { ProvenanceActions } from './Store/Provenance'; import { StudyActions } from './Store/StudyStore/StudyProvenance'; import { TaskDescription } from './Study/TaskList'; import { EndTaskFunction } from './StudyMode'; import { Data } from './Utils/Dataset'; export type StudyCommands = { endTask: EndTaskFunction; currentTaskNumber: number; totalTasks: number; actions: StudyActions; }; export type TaskConfig = { task: TaskDescription; isManual: boolean; isTraining: boolean; hasCenter: boolean; hasCategory: boolean; isCoding: boolean; }; const DataContext = createContext<Data>(null as any); const ActionContext = createContext<ProvenanceActions>(null as any); const TaskConfigContext = createContext<TaskConfig>(null as any); const StudyActionContext = createContext<StudyCommands>(null as any); const ProvenanceContext = createContext<() => ProvenanceGraph<any, any, any>>( null as any ); const ConfigContext = createContext<AppConfig>(null as any); export { DataContext, ActionContext, TaskConfigContext, StudyActionContext, ProvenanceContext, ConfigContext };
/** * We have already handled etag, and will add 'If-Match' & 'Range' value if it works. * <p/> * Created by Jacksgong on 1/17/16. */ public class FileDownloadHeader implements Parcelable { private Headers.Builder headerBuilder; private String nameAndValuesString; private String[] namesAndValues; /** * We have already handled etag, and will add 'If-Match' & 'Range' value if it works. * * @see com.liulishuo.filedownloader.services.FileDownloadRunnable#addHeader(Request.Builder) * @see okhttp3.Headers.Builder#add(String, String) */ public void add(String name, String value) { if (headerBuilder == null) { headerBuilder = new Headers.Builder(); } headerBuilder.add(name, value); } /** * We have already handled etag, and will add 'If-Match' & 'Range' value if it works. * * @see com.liulishuo.filedownloader.services.FileDownloadRunnable#addHeader(Request.Builder) * @see okhttp3.Headers.Builder#add(String, String) */ public void add(String line) { if (headerBuilder == null) { headerBuilder = new Headers.Builder(); } headerBuilder.add(line); } /** * @see okhttp3.Headers.Builder#removeAll(String) */ public void removeAll(String name) { if (headerBuilder == null) { return; } headerBuilder.removeAll(name); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { if (headerBuilder != null) { nameAndValuesString = headerBuilder.build().toString(); } dest.writeString(nameAndValuesString); } public FileDownloadHeader() { } protected FileDownloadHeader(Parcel in) { this.nameAndValuesString = in.readString(); } /** * Invoke by :filedownloader progress * * @return for {@link Headers#Headers(String[])} * @see com.liulishuo.filedownloader.services.FileDownloadRunnable#addHeader(Request.Builder) */ public String[] getNamesAndValues() { do { if (namesAndValues != null) { // has already converted. break; } if (nameAndValuesString == null) { // give up break; } synchronized (this) { if (namesAndValues != null) { break; } namesAndValues = FileDownloadUtils.convertHeaderString(nameAndValuesString); } } while (false); return namesAndValues; } public static final Creator<FileDownloadHeader> CREATOR = new Creator<FileDownloadHeader>() { public FileDownloadHeader createFromParcel(Parcel source) { return new FileDownloadHeader(source); } public FileDownloadHeader[] newArray(int size) { return new FileDownloadHeader[size]; } }; @Override public String toString() { return this.nameAndValuesString; } }
/** @jsx jsx */ import * as React from 'react' import { jsx } from 'theme-ui' import { css } from '@emotion/react' import { colors } from '@uswitch/trustyle.styles' import * as st from './styles' type Position = 'first' | 'middle' | 'last' interface BulletProps { children: React.ReactNode position: Position } interface Props { stages: React.ReactNode[] className?: string } const EmailSVG = () => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36"> <g fill="none"> <ellipse cx="17.848" cy="17.864" fill="#008FE9" rx="17.848" ry="17.864" /> <path fill={colors.white} d="M10.598 24.02h14.68c.608 0 1.101-.493 1.101-1.102v-9.52c0-.608-.493-1.101-1.101-1.101h-14.68c-.608 0-1.102.493-1.102 1.1v9.521c0 .609.494 1.102 1.102 1.102z" /> <path fill={colors.azure} d="M17.958 20.225a1.78 1.78 0 01-1.108-.383l-5.156-4.099.744-.892 5.155 4.098a.59.59 0 00.73-.001l5.126-4.097.746.892-5.124 4.096a1.782 1.782 0 01-1.113.386" /> </g> </svg> ) const CalSVG = () => ( <svg width="36" height="36" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M18 36c9.941 0 18-8.059 18-18S27.941 0 18 0 0 8.059 0 18s8.059 18 18 18z" fill={colors.blueGrey} /> <path d="M11.578 24.358h12.595v-7.995H11.578v7.995zm14.029-11.654H10.144a.653.653 0 00-.668.64v12.387c0 .354.299.64.668.64h15.463c.37 0 .669-.286.669-.64V13.344c0-.354-.3-.64-.67-.64h.001zm-13.235-1.139h1.738V9.287h-1.738v2.278zm9.848 0h1.738V9.287H22.22v2.278z" fill={colors.white} /> </svg> ) const CheckSVG = () => ( <svg width="36" height="36" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M18 36c9.941 0 18-8.059 18-18S27.941 0 18 0 0 8.059 0 18s8.059 18 18 18z" fill={colors.blueGrey} /> <path d="M18 27.9c5.468 0 9.9-4.432 9.9-9.9S23.468 8.1 18 8.1 8.1 12.532 8.1 18s4.432 9.9 9.9 9.9z" fill={colors.white} /> <path d="M21.452 14.7l1.498 1.399-5.952 6.026-3.948-3.808 1.559-1.342 2.45 2.364 4.393-4.639z" fill={colors.blueGrey} /> </svg> ) const Bullet: React.FC<BulletProps> = ({ position, children }) => ( <li css={css([st.highlight, st[position]])}> <div css={st.highlightBulletIconContainer}> <i css={st.highlightBullet}> {position === 'first' && <EmailSVG />} {position === 'middle' && <CalSVG />} {position === 'last' && <CheckSVG />} </i> </div> <div css={st.highlightBulletContent}>{children}</div> </li> ) export const BulletListTimeline: React.FC<Props> = ({ stages, className }) => ( <ul css={st.highlights} className={className}> {stages.map((stage, index) => { const isFirst = index === 0 const isLast = index === stages.length - 1 return ( <Bullet key={index} position={isFirst ? 'first' : isLast ? 'last' : 'middle'} > {stage} </Bullet> ) })} </ul> ) export default BulletListTimeline
Competition between Naegleria fowleri and Free Living Amoeba Colonizing Laboratory Scale and Operational Drinking Water Distribution Systems. Free living amoebae (FLA), including pathogenic Naegleria fowleri, can colonize and grow within pipe wall biofilms of drinking water distribution systems (DWDSs). Studies on the interactions between various FLA species in biofilms are limited. Understanding the interaction between FLA and the broader biofilm ecology could help better predict DWDS susceptibility to N. fowleri colonization. The aim of this study was to determine if N. fowleri and other FLAs ( Naegleria, Vermamoeba, Willaertia, and Vahlkampfia spp.) cocolonize DWDS biofilm. FLAs commonly isolated from DWDSs ( N. fowleri, V. vermiformis, and N. lovaniensis) were introduced into laboratory-scale biomonitors to determine the impact of these amoebae on N. fowleri's presence and viability. Over 18 months, a single viable amoebae ( N. fowleri, N. lovaniensis, or V. vermiformis) was detected in each biofilm sample, with the exception of N. lovaniensis and N. fowleri, which briefly cocolonized biofilm following their coinoculation. The analysis of biofilm and bulk water samples from operational DWDSs revealed a similar lack of cocolonization with a single FLA detected in 99% ( n = 242) of samples. Interestingly, various Naegleria spp. did colonize the same DWDS locations but at different times. This knowledge furthers the understanding of ecological factors which enable N. fowleri to colonize and survive within operational DWDSs and could aid water utilities to control its occurrence.
# https://codeforces.com/problemset/problem/1343/C import math def sign(x: int): if x > 0: return 1 if x < 0: return -1 return 0 def solve(arr): prev_sign = sign(arr[0]) acc_sum, i = 0, 0 while i < len(arr): block_max = float('-inf') while i < len(arr) and sign(arr[i]) == prev_sign: block_max = max(block_max, arr[i]) i += 1 acc_sum += block_max prev_sign *= -1 return acc_sum TESTS = int(input()) for i in range(TESTS): input() arr_txt = input() arr = [int(v) for v in arr_txt.split()] print(solve(arr))
def assign_override_material(rpr_context, rpr_shape, obj, material_override) -> bool: rpr_material = material.sync(rpr_context, material_override, obj=obj) rpr_displacement = material.sync(rpr_context, material_override, 'Displacement', obj=obj) rpr_shape.set_material(rpr_material) rpr_shape.set_displacement_material(rpr_displacement) return bool(rpr_material or rpr_displacement)
class Solution: """ @param A : a list of integers @param target : an integer to be searched @return : a list of length 2, [index1, index2] """ def searchRange(self, A, target): # write your code here length = len(A) start = 0 end = length - 1 if end < 0: return [-1,-1] while start + 1 < end: mid = start + (end - start) /2 if A[mid] < target: start = mid else: end = mid if A[start]!=target and A[end]!=target: return[-1, -1] if A[start] == target and A[end] == target: pos1 = min(start, end) elif A[end] == target: pos1 = end elif A[start] == target: pos1 = start start = 0 end = length - 1 while start + 1 < end: mid = start + (end - start) /2 if A[mid] > target: end = mid else: start = mid if A[start] == target and A[end] == target: pos2 = max(start, end) elif A[end] == target: pos2 = end elif A[start] == target: pos2 = start return [pos1, pos2]
import { Injectable } from '@nestjs/common'; import { CreateMileStoneDto } from './dtos/create-milestone.dto'; import { Milestone } from './entities/milestone.entity'; import { v4 as uuid } from 'uuid'; import MilestoneStore from './milestone-store.service'; @Injectable() export class MilestoneService { async createMilestone( createMilestoneDto: CreateMileStoneDto, ): Promise<Milestone> { const { title } = createMilestoneDto; const milestone = { id: uuid(), title, }; MilestoneStore.addItem(milestone); return milestone; } async getMilestones(): Promise<Milestone[]> { return MilestoneStore.getStore(); } }
/** * KafkaClientHelperTest * author: gaohaoxiang * date: 2020/4/9 */ public class KafkaClientHelperTest { @Test public void simpleTest() { Assert.assertEquals("test_app", KafkaClientHelper.parseClient("test_app")); Assert.assertEquals("test_app", KafkaClientHelper.parseClient("test_app-0")); Assert.assertEquals("test_app", KafkaClientHelper.parseClient("test_app-1")); Assert.assertEquals("test_app", KafkaClientHelper.parseClient("test_app-spark-executor-")); Assert.assertEquals("test_app", KafkaClientHelper.parseClient("test_app-MetadataFuzzySearch")); Assert.assertEquals("test_app", KafkaClientHelper.parseClient("test_app-1-MetadataFuzzySearch")); Assert.assertEquals(false, KafkaClientHelper.isMetadataFuzzySearch("test_app-spark-executor-")); Assert.assertEquals(true, KafkaClientHelper.isMetadataFuzzySearch("test_app-MetadataFuzzySearch")); Assert.assertEquals(true, KafkaClientHelper.isMetadataFuzzySearch("test_app-1-MetadataFuzzySearch")); Assert.assertEquals("test_app", KafkaClientHelper.parseClient("test_app@test_token")); Assert.assertEquals("test_app", KafkaClientHelper.parseClient("test_app@test_token-0")); Assert.assertEquals("test_app", KafkaClientHelper.parseClient("test_app@test_token-spark-executor-")); Assert.assertEquals("test_app", KafkaClientHelper.parseClient("test_app@test_token-MetadataFuzzySearch")); Assert.assertEquals("test_app", KafkaClientHelper.parseClient("test_app@test_token-1-MetadataFuzzySearch")); Assert.assertEquals("test_token", KafkaClientHelper.parseToken("test_app@test_token")); Assert.assertEquals("test_token", KafkaClientHelper.parseToken("test_app@test_token-0")); Assert.assertEquals("test_token", KafkaClientHelper.parseToken("test_app@test_token-spark-executor-")); Assert.assertEquals("test_token", KafkaClientHelper.parseToken("test_app@test_token-MetadataFuzzySearch")); Assert.assertEquals("test_token", KafkaClientHelper.parseToken("test_app@test_token-1-MetadataFuzzySearch")); Assert.assertEquals(null, KafkaClientHelper.parseToken("test_app-1-MetadataFuzzySearch")); } }
<reponame>Buzzec/concurrency_traits use crate::mutex::{Mutex, SpinLock}; use crate::queue::*; use crate::semaphore::*; use crate::ThreadFunctions; use alloc::boxed::Box; use alloc::collections::VecDeque; use async_trait::async_trait; use core::time::Duration; use num::Zero; /// A queue based on a semaphore to block on. #[derive(Debug)] pub struct SemaphoreQueue<T, S, CS> { queue: SpinLock<VecDeque<T>, CS>, semaphore: S, } impl<T, S, CS> SemaphoreQueue<T, S, CS> where S: ReadoutSemaphore, { /// Gets the length of the queue. pub fn len(&self) -> S::Count { self.semaphore.count() } /// Tells whether the queue is empty. pub fn is_empty(&self) -> bool where S::Count: Zero, { self.semaphore.count().is_zero() } } impl<T, S, CS> Default for SemaphoreQueue<T, S, CS> where S: Default, { fn default() -> Self { Self { queue: Default::default(), semaphore: S::default(), } } } impl<T, S, CS> TryQueue for SemaphoreQueue<T, S, CS> where S: TrySemaphore, CS: ThreadFunctions, { type Item = T; fn try_push(&self, value: Self::Item) -> Result<(), Self::Item> { self.queue.lock().push_back(value); self.semaphore.signal(); Ok(()) } fn try_pop(&self) -> Option<Self::Item> { match self.semaphore.try_wait() { true => Some(self.queue.lock().pop_front().unwrap()), false => None, } } } impl<T, S, CS> Queue for SemaphoreQueue<T, S, CS> where S: Semaphore, CS: ThreadFunctions, { fn push(&self, value: Self::Item) { self.try_push(value) .unwrap_or_else(|_| panic!("try_push failed!")); } fn pop(&self) -> Self::Item { self.semaphore.wait(); self.queue.lock().pop_front().unwrap() } } #[async_trait] impl<T, S, CS> AsyncQueue for SemaphoreQueue<T, S, CS> where T: Send, S: AsyncSemaphore + Send + Sync, CS: ThreadFunctions, { async fn push_async(&self, value: Self::Item) { self.try_push(value) .unwrap_or_else(|_| panic!("try_push failed!")) } async fn pop_async(&self) -> Self::Item { self.semaphore.wait_async().await; self.queue.lock().pop_front().unwrap() } } impl<T, S, CS> TryPrependQueue for SemaphoreQueue<T, S, CS> where S: TrySemaphore, CS: ThreadFunctions, { fn try_push_front(&self, value: Self::Item) -> Result<(), Self::Item> { self.queue.lock().push_front(value); self.semaphore.signal(); Ok(()) } } impl<T, S, CS> PrependQueue for SemaphoreQueue<T, S, CS> where S: Semaphore, CS: ThreadFunctions, { fn push_front(&self, value: Self::Item) { self.try_push_front(value) .unwrap_or_else(|_| panic!("try_push_front failed!")); } } #[async_trait] impl<T, S, CS> AsyncPrependQueue for SemaphoreQueue<T, S, CS> where T: Send, S: AsyncSemaphore + Send + Sync, CS: ThreadFunctions, { async fn push_front_async(&self, value: Self::Item) { self.try_push_front(value) .unwrap_or_else(|_| panic!("try_push_front failed!")); } } impl<T, S, CS> TryReverseQueue for SemaphoreQueue<T, S, CS> where S: TrySemaphore, CS: ThreadFunctions, { fn try_pop_back(&self) -> Option<Self::Item> { match self.semaphore.try_wait() { true => Some(self.queue.lock().pop_back().unwrap()), false => None, } } } impl<T, S, CS> ReverseQueue for SemaphoreQueue<T, S, CS> where S: Semaphore, CS: ThreadFunctions, { fn pop_back(&self) -> Self::Item { self.try_pop_back().unwrap() } } #[async_trait] impl<T, S, CS> AsyncReverseQueue for SemaphoreQueue<T, S, CS> where T: Send, S: AsyncSemaphore + Send + Sync, CS: ThreadFunctions, { async fn pop_back_async(&self) -> Self::Item { self.semaphore.wait_async().await; self.queue.lock().pop_back().unwrap() } } impl<T, S, CS> TryDoubleEndedQueue for SemaphoreQueue<T, S, CS> where S: TrySemaphore, CS: ThreadFunctions, { } impl<T, S, CS> DoubleEndedQueue for SemaphoreQueue<T, S, CS> where S: Semaphore, CS: ThreadFunctions, { } impl<T, S, CS> AsyncDoubleEndedQueue for SemaphoreQueue<T, S, CS> where T: Send, S: AsyncSemaphore + Send + Sync, CS: ThreadFunctions, { } impl<T, S, CS> TimeoutQueue for SemaphoreQueue<T, S, CS> where S: TimeoutSemaphore, CS: ThreadFunctions, { fn push_timeout(&self, value: Self::Item, _: Duration) -> Result<(), Self::Item> { self.try_push(value) } fn pop_timeout(&self, timeout: Duration) -> Option<Self::Item> { match self.semaphore.wait_timeout(timeout) { true => Some(self.queue.lock().pop_front().unwrap()), false => None, } } } #[async_trait] impl<T, S, CS> AsyncTimeoutQueue for SemaphoreQueue<T, S, CS> where T: Send, S: AsyncTimeoutSemaphore + Send + Sync, CS: ThreadFunctions, { async fn push_timeout_async(&self, value: Self::Item, _: Duration) -> Result<(), Self::Item> { self.try_push(value) } async fn pop_timeout_async(&self, timeout: Duration) -> Option<Self::Item> { match self.semaphore.wait_timeout_async(timeout).await { true => Some(self.queue.lock().pop_front().unwrap()), false => None, } } }
<gh_stars>0 import * as React from 'react'; import {Link, NavLink} from 'react-router-dom'; const activeStyle = { color: '#ececec', fontSize: '18px' }; const Navigator: React.SFC = (): JSX.Element => ( <div> <ul> <li><NavLink to="/" activeStyle={activeStyle} exact={true}>Home</NavLink></li> <li><NavLink to="/signin" activeClassName="active" activeStyle={activeStyle}>Signin</NavLink></li> <li><NavLink to="/signup" activeClassName="active" activeStyle={activeStyle}>Signup</NavLink></li> <li><NavLink to="/register" activeClassName="active" activeStyle={activeStyle}>Register</NavLink></li> </ul> </div> ); export default Navigator;
// plain or tls class Connection : public boost::enable_shared_from_this<Connection<endpoint_type> >{ public: typedef typename endpoint_type::handler::connection_ptr connection_ptr; Connection(connection_ptr con, boost::asio::io_service &io_service) : websocket_connection(con), readBuffer(1024), mqttMessage(""), connected(false), closed(false){ #ifdef DEBUG std::cerr << "In Connection Constructor: creating socket" << std::endl; #endif socket = Socket::create(io_service); } ~Connection(){ #ifdef DEBUG std::cerr << "Beginning of Destructor of Connection" << std::endl << " Connection address is: " << this << " websocket: " << websocket_connection << std::endl; #endif websocket_connection->close(websocketpp::close::status::NORMAL, "closing"); #ifdef DEBUG std::cerr << "End of Destructor of Connection. Address was " << this << " (" << websocket_connection << ")" << std::endl; #endif } void init(){ #ifdef DEBUG std::cerr << "Init Connection: connecting to broker" << std::endl; #endif socket->on_fail = boost::bind(&Connection::fail, this->shared_from_this()); socket->on_success = boost::bind(&Connection::first_start, this->shared_from_this()); socket->on_end = boost::bind(&Connection::cleanup, this->shared_from_this()); socket->do_connect(); } void first_start(){ #ifdef DEBUG std::cerr << "broker connection established" << std::endl; std::cerr << "queued stuff: " << queued_messages.size() << " bytes: " ; unsigned int i = 0; for(std::string::const_iterator it = queued_messages.begin(); it != queued_messages.end() && i <= queued_messages.size(); it++, i++) std::cerr << std::setw(2) << std::setfill('0') << std::hex << (short)*it << " "; std::cerr << std::dec << std::endl; #endif socket->async_write( SharedBuffer(queued_messages), boost::bind( &Connection::async_tcp_write_handler, this->shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred ) ); #ifdef DEBUG std::cerr << "sending queued messages" << queued_messages << std::endl; #endif connected = true; start_receive(); } void fail(){ #ifdef DEBUG std::cerr << "socket error in connection " << this << std::endl; #endif try{ if(!closed) websocket_connection->close(websocketpp::close::status::NORMAL, "failed"); }catch(std::exception &e){ std::cerr << e.what() << std::endl; } } void cleanup(){ #ifdef DEBUG std::cerr << "in cleanup of connection" << std::endl; #endif if(socket->getSocketForAsio().is_open()){ socket->getSocketForAsio().cancel(); socket->getSocketForAsio().close(); } socket.reset(); #ifdef DEBUG std::cerr << " stopped async TCP receive" << std::endl; #endif } void receive_header(const boost::system::error_code& error, size_t bytes_transferred){ if (!error && bytes_transferred == 2 && websocket_connection->get_state() == websocketpp::session::state::OPEN){ #ifdef DEBUG std::cerr << "received header from broker." << std::endl << "Length: " << bytes_transferred << " Bytes" << std::endl << std::setw(2) << std::setfill('0') << std::hex << "Payload: " << (short)mqtt_header[0] << " " << (short)mqtt_header[1] << std::endl << std::endl << std::dec; #endif mqttMessage = std::string(mqtt_header, bytes_transferred); if(mqtt_header[1] == 0){ #ifdef DEBUG std::cerr << "there is nothing more -> sending it to the websocket." << std::endl << std::endl; #endif websocket_connection->send(mqttMessage, websocketpp::frame::opcode::BINARY); start_receive(); } else if(mqtt_header[1] & 0x80){ #ifdef DEBUG std::cerr << "need to read extra bytes for remaining length field" << std::endl << std::endl; #endif multiplier = 1; remaining_length = mqtt_header[1] & 0x7F; #ifdef DEBUG std::cerr << "length initially is: " << remaining_length << std::endl; #endif socket->async_read( boost::asio::buffer(&next_byte, 1), 1, boost::bind( &Connection::receive_remaining_length, this->shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred ) ); } else{ remaining_length = mqtt_header[1]; #ifdef DEBUG std::cerr << "the remaining message length is: " << remaining_length << std::endl << std::endl; #endif readBuffer.resize(remaining_length); socket->async_read( boost::asio::buffer(readBuffer, remaining_length), remaining_length, boost::bind( &Connection::receive_mqtt_message, this->shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred ) ); } } else { #ifdef DEBUG std::cerr << "stopped receiving header " << std::endl << bytes_transferred << " bytes arrived so far. error " << error << " websocket: " << websocket_connection << " connection " << this << std::endl << std::endl; #endif if(error && error != boost::asio::error::operation_aborted){ if(options.verbose) std::cerr << "error mqtt header " << error.message() << std::endl; websocket_connection->close(websocketpp::close::status::NORMAL, "connection problem while reading MQTT header"); } } } void receive_remaining_length(const boost::system::error_code& error, size_t bytes_transferred){ if (!error && bytes_transferred == 1 && websocket_connection->get_state() == websocketpp::session::state::OPEN) { #ifdef DEBUG std::cerr << "received one more byte with remaining length: " << std::setw(2) << std::setfill('0') << std::hex << (short)next_byte << std::endl << std::dec; #endif mqttMessage.append(std::string(&next_byte, 1)); #ifdef DEBUG std::cerr << "there is still work to do" << mqtt_header[1] << std::endl << std::endl; #endif multiplier *= 128; remaining_length += (next_byte & 0x7F) * multiplier; #ifdef DEBUG std::cerr << "remaining length is now: " << remaining_length << std::endl; #endif if(next_byte & 0x80){ socket->async_read( boost::asio::buffer(&next_byte, 1), 1, boost::bind( &Connection::receive_remaining_length, this->shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred ) ); } else { #ifdef DEBUG std::cerr << "length finally is: " << remaining_length << std::endl; #endif readBuffer.resize(remaining_length); socket->async_read( boost::asio::buffer(readBuffer, remaining_length), remaining_length, boost::bind( &Connection::receive_mqtt_message, this->shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred ) ); } } else { #ifdef DEBUG std::cerr << "error reading length bytes " << std::endl << bytes_transferred << "bytes arrived so far " << error << " websocket: " << websocket_connection << " connection " << this << std::endl << std::endl; #endif if(error && error != boost::asio::error::operation_aborted){ if(options.verbose) std::cerr << "error reading remaining length of mqtt message " << error.message() << std::endl; websocket_connection->close(websocketpp::close::status::NORMAL, "connection problem while reading remaining length"); } } } void receive_mqtt_message(const boost::system::error_code& error, size_t bytes_transferred) { if (!error && websocket_connection->get_state() == websocketpp::session::state::OPEN){ #ifdef DEBUG std::cerr << "received message body from broker " << bytes_transferred << " bytes: "; for(std::vector<char>::iterator it = readBuffer.begin(); it != readBuffer.end(); it++) std::cerr << std::setw(2) << std::setfill('0') << std::hex << (short)*it << " "; std::cerr << std::dec << std::endl; std::cerr << "plaintext: " << std::string(readBuffer.data(), bytes_transferred) << std::endl; #endif mqttMessage.append(std::string(readBuffer.data(), bytes_transferred)); websocket_connection->send(mqttMessage, websocketpp::frame::opcode::BINARY); start_receive(); } else { #ifdef DEBUG std::cerr << "error reading mqtt message (or operation was canceled)" << std::endl << bytes_transferred << "bytes arrived so far " << error << " websocket: " << websocket_connection << " connection " << this << std::endl << std::endl; #endif if(error && error != boost::asio::error::operation_aborted){ if(options.verbose) std::cerr << "error reading mqtt message " << error.message() << std::endl; websocket_connection->close(websocketpp::close::status::NORMAL, "connection problem in receice_message"); } } } void async_tcp_write_handler(const boost::system::error_code& error, std::size_t bytes_transferred){ if(error){ if(options.verbose) std::cerr << "error writing to the broker " << error.message() << std::endl; if(websocket_connection) websocket_connection->close(websocketpp::close::status::NORMAL, "problem while writing to the broker"); } } void send(const std::string &message) { #ifdef DEBUG std::cerr << "sent TCP segment to broker " << message.size() << " bytes: " ; unsigned int i = 0; for(std::string::const_iterator it = message.begin(); it != message.end() && i <= message.size(); it++, i++) std::cerr << std::setw(2) << std::setfill('0') << std::hex << (short)*it << " "; std::cerr << std::dec << std::endl; std::cerr << "plaintext: " << message << std::endl; #endif if(connected){ #ifdef DEBUG std::cerr << "broker connection had been established. sending this message ..." << std::endl; #endif socket->async_write( SharedBuffer(message), boost::bind( &Connection::async_tcp_write_handler, this->shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred ) ); } else { #ifdef DEBUG std::cerr << "broker connection has not been established yet. queuing this message ..." << std::endl; #endif queued_messages.append(message); } } void start_receive() { #ifdef DEBUG std::cerr << "Begin of start_receive() in Connection at: " << this << std::endl; #endif socket->async_read( boost::asio::buffer(mqtt_header, 2), 2, boost::bind( &Connection::receive_header, this->shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred ) ); #ifdef DEBUG std::cerr << " started async TCP read" << std::endl; #endif } void stop(){ #ifdef DEBUG std::cerr << "stop() in Connection at " << this << std::endl; #endif socket->end(); closed = true; } private: connection_ptr websocket_connection; std::string queued_messages; boost::shared_ptr<Socket> socket; std::vector<char> readBuffer; char mqtt_header[2]; char next_byte; unsigned int remaining_length; std::string mqttMessage; unsigned int multiplier; bool connected; bool closed; }
/** Convert Java data type to Java VM type signature. */ public static final String javaTypeSig(Class<?> cls) throws InvalidNameException { if (cls.isArray()) return "[" + javaTypeSig(cls.getComponentType()); if (cls.equals(void.class)) return "V"; if (cls.equals(boolean.class)) return "Z"; if (cls.equals(byte.class)) return "B"; if (cls.equals(short.class)) return "S"; if (cls.equals(int.class)) return "I"; if (cls.equals(long.class)) return "J"; if (cls.equals(float.class)) return "F"; if (cls.equals(double.class)) return "D"; if (cls.equals(String.class)) return "Ljava/lang/String;"; throw new InvalidNameException("Unsupported data type '" + cls.toString() + "'."); }
NBC 7's Omari Fleming reports from Imperial Valley after a military jet crashes and creates a firestorm, destroyed three homes. No one was injured. (Published Thursday, June 5, 2014) Military officials are investigating what caused a military plane to crash into homes in an Imperial Valley neighborhood about two hours southeast of San Diego County Wednesday. The pilot safely ejected from the plane before it crashed, officials said, and no civilians on the ground were injured. Three homes were destroyed in the crash. The American Red Cross told NBC News that 5 families have been displaced (a total of 22 people). The emergency organization also said chemicals at the site are being handled by military haz mat crews, who also put in a request with American Red Cross to talk to the affected families. According to California Highway Patrol El Centro, the plane crashed in a residential area at Cross Road and Fonzie Avenue in Imperial, Calif., near the U.S.-Mexico border, about 115 miles from San Diego. One house caught fire as a result of the crash, and two additional homes were also impacted, CHP officials said. Military Plane Crashes Into Neighborhood NBC 7's Omari Fleming reports from an Imperial, Calif., neighborhood where a small military plane crashed near homes on June 4, 2014. (Published Wednesday, June 4, 2014) Immediately after the incident, Marine Corps Air Station (MCAS) Miramar also confirmed via Twitter that the Harrier jet crash impacted civilian structures. Eight homes were evacuated, according to Imperial County officials, MCAS Miramar confirmed. Again, none of those residents were harmed. Military Plane Crashes in Imperial Valley MCAS Miramar officials said the Third Marine Aircraft Wing AV-8B Harrier was stationed at MCAS Yuma and crashed around 4:20 p.m. The pilot was transported to a local hospital for evaluation. He sustained minor injuries but is expected to make a full recovery. Early Thursday, MCAS Miramar updated his condition via Twitter saying he had been released from the hospital and was "doing well." MCAS Miramar 1st Lt. Jose Negrete said authorities were on scene collecting evidence and assessing the damage. An investigation has been launched to determine the cause of the crash. MCAS Miramar Official Gives Plane Crash Update From MCAS Miramar in San Diego, 1st Lt. Jose Negrete shares a few details on the military plane that crashed into a residential area in Imperial, Calif., on June 4, 2014. (Published Wednesday, June 4, 2014) Patricia and Nestr Roblas live a few house down from the crash site and said the impact of the plane striking the area caused an explosion. “I heard a large explosion, and it felt like an earthquake. My dad thought a car hit our house. It was just a loud explosion and I felt a jolt,” Patricia told NBC 7 San Diego. “It smelled really bad, like toxic fumes.” Patricia said authorities came to their front door after the crash and told them to turn off their air conditioning unit so as not to let the fumes in. Officials Investigate Military Plane Crash A small military plane crashed into a neighborhood in Imperial, Calif., on June 4, 2014. This raw footage from NBC 7 shows authorities surveying the damage left behind in the aftermath of the crash. (Published Wednesday, June 4, 2014) Patricia said the ordeal was extremely frightening, to say the least. “It was really scary. After they put the fires out, a few minutes later, we saw another huge fire so we didn’t know if there was an explosion because of gas or what,” she explained. “I was scared there would be more explosions and the fires would reach our house.” Nestr said he was watching television when he heard an explosion. As he walked outside, he saw a "big, black wall of smoke" stemming from the crash site. He said it felt as if he was watching a movie up close. “If you’re watching a movie, [something like this] doesn’t look that scary but in real life you get freaked out," he said. Imperial resident Cathie Blackburn lives about one mile from the site of the crash and told NBC 7 she heard a "loud boom" when the aircraft went down. The impact was so strong, Blackburn thought it may have been an earthquake. Blackburn said some friends who live in the neighborhood saw the pilot eject. She said the fire was put out quickly. As of 6:45 p.m., Blackburn said authorities were telling residents that streets in the surrounding area would be closed for the rest of the night as officials continue their investigation. According to NBC News, this is the second crash in less than one month involving a Harrier jet from the MCAS Yuma base. On May 9, another crashed in a remote desert area near the Gila River Indian Community in Arizona during a routine training exercise. In that case, the jet was destroyed and the pilot ejected safely as well. No one else was injured. NBC 7 Coverage:
Widespread mass-wasting processes off NE Sicily (Italy): insights from morpho-bathymetric analysis Abstract The NE Sicilian continental margin is largely affected by canyons and related landslide scars. Two main types of submarine canyons are recognizable: the first type carves the shelf up to depths <20 m, a few hundred metres from the coast, acting as a main collector for sediments transported by hyperpycnal flows and/or littoral drift. These canyons mostly have a V-shaped cross-section and are characterized by a strong axial incision, where a network of dendritic gullies carving the canyon flanks converges. The second type of canyon occurs where the shelf is wider, hindering the direct connection between the subaerial and submarine drainage system. This setting exhibits canyon heads mostly confined to the shelf break, characterized by a weaker axial incision of the canyon and U-shaped cross-section. A total of 280 landslide scars are recognized in the study area and these are divided into three groups according to their morphology and location. A morphometric analysis of these scars is performed to investigate which parameters might be key factors in controlling instability processes and how they correlate with each other. We also try to assess the possible tsunamigenic potential associated with these landslide events by coupling the morphometric analysis with semi-empirical relationships available in the literature.
/** Gets an existing UserRecord object in the database under the specified data 'Store' and with the specified 'Key'. Parameters: Store- the data store name to retrieve the UserRecord from Key- the unique key that was used when creating the UserRecord Returns: the requested UserRecord object, or null if no matching record was found Since: 7.0 */ public static Object GetUserRecord (java.lang.String Store, java.lang.String Key) { Object o = sagex.SageAPI.call("GetUserRecord", new Object[] {Store,Key}); if (o!=null) return (Object) o; return null; }
Every journey is a series of choices. Früher hatte ich einen immer wiederkehrenden Albtraum. In diesem Traum wurde ich in einem Labyrinth, oder zumindest in etwas das danach aussah, von einer riesigen Kugel oder Murmel verfolgt. So wie bei Indiana Jones – ihr wisst schon, diese große Steinkugel – nur alles in surreal und ohne coole Musik im Hintergrund. »Antichamber« ist ein bisschen wie dieser Traum. Zwar verfolgt mich keine Murmel und ich wache nicht schweißgebadet in meinem Bett auf, doch ein wenig beklemmend und surreal ist es dennoch. Keine heroisch anmutenden Orchesterklänge, sondern mysteriös wabernder Ambient untermalt das Szenario. Zu Anfang stehe ich in einem schwarzen Raum. Hinter einer Glaswand ist ein Ausgang zu sehen. Zu erreichen ist dieser nicht. Auf einer der Wände ist ein Teil einer Karte abgebildet. Unterschrieben mit dem Hinweis, eine Richtung zu wählen. Erst ein Punkt ist auswählbar. Die große schwarze Wand wartet darauf, mit meinen Entdeckungen beschrieben zu werden. Ein Klick weiter und ich stehe bereits im ersten Gang. Meine Reise beginnt. Wohin sie mich führen wird und warum ich sie überhaupt antrete, ist unklar. Lediglich der Ausblick auf einen Ausgang treibt mich an. Keine Informationen, keine Geschichte. Tabula Rasa. Nur Hinweisschilder mit mysteriösen Tipps und mal philosophisch anmutenden Botschaften zieren meinen Weg. Ob man ihnen vertrauen kann ist stets unklar. Der erste Schritt führt mich in einen Raum mit einem Abgrund. Die Worte „Walk“ schweben darüber. Wie Indiana Jones wage ich also den Leap Of Faith – und tatsächlich erscheint unter meinen Füßen eine Brücke. Schon hier wird deutlich, in welche Richtung sich »Antichamber« bewegen wird. Doch das war erst der Anfang. Venturing into the unknown can lead to great rewards. „Gefangen in einem MC Escher Gemälde“, war mein erster Eindruck, und tatsächlich benutzt Entwickler Alexander Bruce genau diese Worte um sein Spiel zu beschreiben: „A mind-bending psychological exploration game, set within an Escher like world.“ Ich bahne mich also durch ein Labyrinth von Gängen und Räumen und muss zwischendurch Rätsel lösen, welche mir Türen öffnen oder auf andere Art einen neuen Weg offerieren. Doch nichts ist wie es scheint. Linearität gibt es nicht. Wo hinter mir gerade noch ein Gang war, kann plötzlich eine Wand sein. Der bloße Blick durch ein simples Fenster kann meine Umgebung verändern. Wie im Traum. Wo die Badezimmertür nicht wie gewohnt in die Nasszelle führt, sondern man plötzlich im Wohnzimmer der Großmutter steht. Um die Ecke denken und Mechaniken nachvollziehen sind jederzeit der Schlüssel zum Erfolg. Seine Umgebung beobachten und auf Details achten. Doch bloß nicht nur den eigenen Augen trauen. Old skills are usefull even after we learned new ones. Ausgangspunkt meiner Entdeckungstour ist immer wieder der schwarze Raum vom Anfang. Er dient als Knotenpunkt und ich kehre hierhin zurück, wenn ich in einer Sackgasse gelandet bin oder ein Rätsel einfach noch nicht lösbar ist. Um diverse Aufgaben zu lösen, muss ich mit einer Art „Waffe“ – man könnte sie wohl am ehesten mit der Portal-Gun vergleichen – die Umgebung beeinflussen. Zu Beginn kann diese lediglich quaderförmige Steine aufnehmen und an anderer Stelle wieder einfügen. Nach klassischem Metroidvania-Prinzip finde ich aber nach und nach verbesserte Versionen dieses Devices und kann zurück zu Stellen gehen, die vorher schlicht nicht passierbar waren. Anders als bei »Portal« hatte ich bei Antichamber aber oft das Gefühl, dass manche Rätsel auf verschiedene Art gelöst werden können und ich wesentlich mehr Spielraum zum Ausprobieren hatte. »Antichamber« hat viele schöne Ideen, die mich zum Schmunzeln brachten, aber auch Momente, die mich an meinen Fähigkeiten zweifeln ließen. In anderen Situationen hätte ich gerne jemanden gehabt, der mir nach dem Entkommen aus einer prekär wirkenden Situation zustimmend auf die Schulter klopft. Wo ich zuerst noch dachte, dass die Beschreibung „mind-bending psychological exploration game“ eine stumpf-prätentiöse Übertreibung ist, stellte sich diese Vermutung schon nach weniger als einer Stunde als falsch heraus. Kein Text, den ich in der Lage bin zu schreiben, kann dieses Spiel perfekt beschreiben, denn es ist gleichzeitig auch eine persönliche Erfahrung, die man erlebt. Wo ich in anderen Spielen schon längst aufgegeben hätte, war ich hier stets motiviert, die Zähne zusammenzubeißen und eine weitere Stunde durch die Gänge zu irren. Irgendwo geht es immer weiter. Irgendwo hab ich vielleicht ein Detail übersehen. Irgendwo traf ich die falsche Entscheidung. »Antichamber« ist ein Spiel, das recht schnell fesselt und sich durch neue, frische Ideen von anderen „Puzzle“-Spielen abhebt. Der minimalistische Artstyle und auch der sphärische Soundtrack tragen ihren Teil dazu bei, dass man sich dem Mysterium nicht entziehen kann. Ein Traum zum Durchspielen, mit einer Prise »Portal«. Braucht es noch mehr Kaufgründe? Eigentlich ist jede gelesene Zeile verschwendete Zeit – denn je weniger man weiß, desto besser stelle ich mir die Erfahrung vor. Worauf also warten? »Antichamber« ist seit heute bei Steam erhältlich und ist jeden seiner zur Zeit 14 Euros wert! Youtube-Videos sind im „privacy enhanced mode“ eingebunden, erst beim Abspielen werden Daten an Youtube übertragen. Beim Abspielen stimmst du dem zu, mehr Informationen findest du in unserer Datenschutzerklärung. Gefällt mir: Gefällt mir Wird geladen...
<gh_stars>0 import os import unittest from pynwb.form.data_utils import DataChunkIterator from pynwb.form.backends.hdf5.h5tools import HDF5IO from pynwb.form.build import DatasetBuilder import h5py import tempfile import numpy as np class H5IOTest(unittest.TestCase): """Tests for h5tools IO tools""" def setUp(self): self.test_temp_file = tempfile.NamedTemporaryFile() # On Windows h5py cannot truncate an open file in write mode. # The temp file will be closed before h5py truncates it # and will be removed during the tearDown step. name = self.test_temp_file.name self.test_temp_file.close() self.f = h5py.File(name, 'w') self.io = HDF5IO(self.test_temp_file.name) def tearDown(self): path = self.f.filename self.f.close() os.remove(path) del self.f del self.test_temp_file self.f = None self.test_temp_file = None ########################################## # __chunked_iter_fill__(...) tests ########################################## def test__chunked_iter_fill_iterator_matched_buffer_size(self): dci = DataChunkIterator(data=range(10), buffer_size=2) my_dset = HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci) self.assertListEqual(my_dset[:].tolist(), list(range(10))) def test__chunked_iter_fill_iterator_unmatched_buffer_size(self): dci = DataChunkIterator(data=range(10), buffer_size=3) my_dset = HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci) self.assertListEqual(my_dset[:].tolist(), list(range(10))) def test__chunked_iter_fill_numpy_matched_buffer_size(self): a = np.arange(30).reshape(5, 2, 3) dci = DataChunkIterator(data=a, buffer_size=1) my_dset = HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci) self.assertTrue(np.all(my_dset[:] == a)) self.assertTupleEqual(my_dset.shape, a.shape) def test__chunked_iter_fill_numpy_unmatched_buffer_size(self): a = np.arange(30).reshape(5, 2, 3) dci = DataChunkIterator(data=a, buffer_size=3) my_dset = HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci) self.assertTrue(np.all(my_dset[:] == a)) self.assertTupleEqual(my_dset.shape, a.shape) def test__chunked_iter_fill_list_matched_buffer_size(self): a = np.arange(30).reshape(5, 2, 3) dci = DataChunkIterator(data=a.tolist(), buffer_size=1) my_dset = HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci) self.assertTrue(np.all(my_dset[:] == a)) self.assertTupleEqual(my_dset.shape, a.shape) def test__chunked_iter_fill_numpy_unmatched_buffer_size(self): # noqa: F811 a = np.arange(30).reshape(5, 2, 3) dci = DataChunkIterator(data=a.tolist(), buffer_size=3) my_dset = HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci) self.assertTrue(np.all(my_dset[:] == a)) self.assertTupleEqual(my_dset.shape, a.shape) ########################################## # write_dataset tests ########################################## def test_write_dataset_scalar(self): a = 10 self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) dset = self.f['test_dataset'] self.assertTupleEqual(dset.shape, ()) self.assertEqual(dset[()], a) def test_write_dataset_string(self): a = 'test string' self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) dset = self.f['test_dataset'] self.assertTupleEqual(dset.shape, ()) # self.assertEqual(dset[()].decode('utf-8'), a) self.assertEqual(dset[()], a) def test_write_dataset_list(self): a = np.arange(30).reshape(5, 2, 3) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a.tolist(), attributes={})) dset = self.f['test_dataset'] self.assertTrue(np.all(dset[:] == a)) def test_write_table(self): cmpd_dt = np.dtype([('a', np.int32), ('b', np.float64)]) data = np.zeros(10, dtype=cmpd_dt) data['a'][1] = 101 data['b'][1] = 0.1 dt = [{'name': 'a', 'dtype': 'int32', 'doc': 'a column'}, {'name': 'b', 'dtype': 'float64', 'doc': 'b column'}] self.io.write_dataset(self.f, DatasetBuilder('test_dataset', data, attributes={}, dtype=dt)) dset = self.f['test_dataset'] self.assertEqual(dset['a'].tolist(), data['a'].tolist()) self.assertEqual(dset['b'].tolist(), data['b'].tolist()) def test_write_table_nested(self): b_cmpd_dt = np.dtype([('c', np.int32), ('d', np.float64)]) cmpd_dt = np.dtype([('a', np.int32), ('b', b_cmpd_dt)]) data = np.zeros(10, dtype=cmpd_dt) data['a'][1] = 101 data['b']['c'] = 202 data['b']['d'] = 10.1 b_dt = [{'name': 'c', 'dtype': 'int32', 'doc': 'c column'}, {'name': 'd', 'dtype': 'float64', 'doc': 'd column'}] dt = [{'name': 'a', 'dtype': 'int32', 'doc': 'a column'}, {'name': 'b', 'dtype': b_dt, 'doc': 'b column'}] self.io.write_dataset(self.f, DatasetBuilder('test_dataset', data, attributes={}, dtype=dt)) dset = self.f['test_dataset'] self.assertEqual(dset['a'].tolist(), data['a'].tolist()) self.assertEqual(dset['b'].tolist(), data['b'].tolist()) def test_write_dataset_iterable(self): self.io.write_dataset(self.f, DatasetBuilder('test_dataset', range(10), attributes={})) dset = self.f['test_dataset'] self.assertListEqual(dset[:].tolist(), list(range(10))) def test_write_dataset_iterable_multidimensional_array(self): a = np.arange(30).reshape(5, 2, 3) aiter = iter(a) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', aiter, attributes={})) dset = self.f['test_dataset'] self.assertListEqual(dset[:].tolist(), a.tolist()) def test_write_dataset_data_chunk_iterator(self): dci = DataChunkIterator(data=np.arange(10), buffer_size=2) self.io.write_dataset(self.f, DatasetBuilder('test_dataset', dci, attributes={})) dset = self.f['test_dataset'] self.assertListEqual(dset[:].tolist(), list(range(10))) if __name__ == '__main__': unittest.main()
/// <reference path="typings/tsd.d.ts" /> /// <reference path="sandbox.d.ts" /> import acorn = require('acorn/dist/acorn_loose'); import walk = require('acorn/dist/walk'); var literals = []; var names = []; var vars = {}; var builtins = {}; function tryParseInt(s: string) { return parseInt(s); } function ins(i: string, args = []) { var argStr = args.join(' '); console.log(`\t${i}\t\t${argStr}`); } function lbl(l: string) { console.log(`${l}:`); } function dir(d: string, args = []) { var argStr = args.join(' '); console.log(`.${d} ${argStr}`); } class IntermediateWalker implements Walker { Program(node, state, c) { // Strict doesn't do anything for now; // (might require declarations later). dir('strict', [0]); for(var i = 0; i < node.body.length; i++) { c(node.body[i], state); } } AssignmentExpression(node, state, c) { // We only support simple assignment (ident = expr) // and hab no checks for built-ins just yet. c(node.right, state); let name = node.left.name; ins(`put`, [name]); } ArrayExpression(node, state, c) { ins(`make_empty_list`); for (let x of node.elements) { c(x, state); ins(`list_append`); } } ForStatement(node, state, c) { console.log(node); c(node, state); } ForInStatement(node, state, c) { c(node.right, state); ins(`num`, [0]); lbl(`top`); ins(`for`, [node.left.name, 'done']); for (var i = 0; i < node.body.body.length; i++) { c(node.body.body[i], state); } lbl(`done`); } Literal(node, state, c) { ins(`ìmm`, [node.raw]); } Identifier(node, state, c) { // Should always be in rhs context (i.e. reading). ins(`push`, [node.name]) } ReturnStatement(node, state, c) { // Only support return with explicit argument for now. ins(`return`); } } var code = ` things = ['foo', 123, 'quux', $0]; for (thing in things) { otherThing = thing; } return 0; `; var node = acorn.parse_dammit(code); var logger = { Program: (node) => console.log(node), Expression: (node) => console.log(node), ForStatement: (node) => console.log(node), ForInStatement: (node) => console.log(node) }; // walk.simple(node, logger); var intermediate = new IntermediateWalker(); var state = {}; walk.recursive(node, state, intermediate);
Response Time Analysis and Priority Assignment of Processing Chains on ROS2 Executors ROS (Robot Operating System) is currently the most popular robotic software development framework. Robotic software in safe-critical domain are usually subject to hard real-time constraints, so designers must formally model and analyze their timing behaviors to guarantee that real-time constraints are always honored at runtime. This paper studies real-time scheduling and analysis of processing chains in ROS2, the second-generation ROS with a major consideration of real-time capability. First, we study response time analysis of processing chains on ROS2 executors. We show that the only existing result of this problem is both optimistic and pessimistic, and develop new techniques to address these problems and significantly improve the analysis precision. Second, we reveal that the response time of a processing chain on an executor only depends on its last scheduling entity (callback), which provides useful guidance for designers to improve not only the response time bound, but also the actual worst-case/average response time of the system at little design cost. We conduct experiments with both randomly generated workload and a case study on realistic ROS2 platforms to evaluate and demonstrate our results.
/** * A Wizard style dialog with back, next, finish, and cancel buttons. */ public abstract class Wizard extends JPanel { protected JButton btnNext = new JButton("Next"); protected JButton btnBack = new JButton("Back"); protected JButton btnCancel = new JButton("Cancel"); protected JPanel top; protected JDialog dialog; protected Dimension mySize = null; protected boolean exitOnClose = false; protected boolean cancel = false; protected Stack panels = new Stack(); public Wizard() { this(false); } public Wizard(boolean exitOnClose) { this.exitOnClose = exitOnClose; guiInit(); setCommands(); } private void setCommands() { btnNext.setActionCommand("next"); btnBack.setActionCommand("back"); btnCancel.setActionCommand("cancel"); } protected void guiInit() { setLayout(new BorderLayout()); if (top != null) add(top, BorderLayout.CENTER); JPanel bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JPanel left = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT)); left.add(btnBack); left.add(btnNext); right.add(btnCancel); bottom.add(left); bottom.add(right); add(bottom, BorderLayout.SOUTH); btnNext.setMnemonic('n'); btnBack.setMnemonic('b'); btnCancel.setMnemonic('c'); } public void setTopPanel(JPanel topPanel) { if (top != null) { this.remove(top); top = null; } top = topPanel; add(top, BorderLayout.CENTER); invalidate(); validate(); repaint(); } public void display(JFrame owner, String title, boolean centerOnOwner) { if (owner == null) { owner = new JFrame(); } dialog = new JDialog(owner, true); dialog.setTitle(title); java.awt.Container c = dialog.getContentPane(); c.setLayout(new java.awt.BorderLayout()); c.add(this, java.awt.BorderLayout.CENTER); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { cancel = true; close(); } }); if (mySize == null) { dialog.pack(); //System.out.println(f.getSize().width + ", " + f.getSize().height); } else { dialog.setSize(mySize); } //GuiUtilities.centerComponentOnComponent(dialog, owner); if (centerOnOwner) { dialog.setLocationRelativeTo(owner); } else { GuiUtilities.centerComponentOnScreen(dialog); } dialog.setVisible(true); } public void display(JDialog owner, String title, boolean centerOnOwner) { if (owner == null) { owner = new JDialog(); } dialog = new JDialog(owner, true); dialog.setTitle(title); java.awt.Container c = dialog.getContentPane(); c.setLayout(new java.awt.BorderLayout()); c.add(this, java.awt.BorderLayout.CENTER); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { cancel = true; close(); } }); if (mySize == null) { dialog.pack(); //System.out.println(f.getSize().width + ", " + f.getSize().height); } else { dialog.setSize(mySize); } //GuiUtilities.centerComponentOnComponent(dialog, owner); if (centerOnOwner) { dialog.setLocationRelativeTo(owner); } else { GuiUtilities.centerComponentOnScreen(dialog); } dialog.setVisible(true); } public void setSize(int width, int height) { mySize = new Dimension(width, height); } public void close() { //System.out.println(dialog.getSize()); if (dialog != null) { dialog.dispose(); } if (exitOnClose) { System.exit(0); } } public void setNextEnabled(boolean enabled) { btnNext.setEnabled(enabled); } public void setBackEnabled(boolean enabled) { btnBack.setEnabled(enabled); } public void setNextToFinish() { btnNext.setText("Finished"); } }
<filename>samples/dump_points.cpp<gh_stars>0 #include <iostream> #include <fstream> #include <chrono> #include <string> #include <memory> #include <cassert> #include <cmath> #include <cmdline.h> #include "evolvents.hpp" void initParser(cmdline::parser& parser); int main(int argc, char** argv) { cmdline::parser parser; initParser(parser); parser.parse_check(argc, argv); double t_start = 0., t_end = 1.; std::vector<double> lb(10, -0.5); std::vector<double> ub(10, 0.5); int l = parser.get<int>("evolventsNum"); int dim = parser.get<int>("dim"); int m = parser.get<int>("evolventTightness"); std::shared_ptr<Evolvent> evolvent; if(parser.get<std::string>("evolventType") == "rotated") evolvent = std::shared_ptr<Evolvent>(new RotatedEvolvent(dim, m, l, lb.data(), ub.data())); else if(parser.get<std::string>("evolventType") == "shifted") evolvent = std::shared_ptr<Evolvent>(new ShiftedEvolvent(dim, m, l, lb.data(), ub.data())); else if(parser.get<std::string>("evolventType") == "noninjective") { assert(parser.get<int>("evolventsNum") == 1); evolvent = std::shared_ptr<Evolvent>(new Evolvent(dim, m, lb.data(), ub.data(), MapType::Noninjective)); } else if(parser.get<std::string>("evolventType") == "multilevel") { assert(parser.get<int>("evolventsNum") == 1); assert(parser.get<int>("dim") % 2 == 0); evolvent = std::shared_ptr<Evolvent>(new MultiLevelEvolvent(dim, m, lb.data(), ub.data())); } else if(parser.get<std::string>("evolventType") == "smooth") { assert(parser.get<int>("evolventsNum") == 1); evolvent = std::shared_ptr<Evolvent>(new SmoothEvolvent(dim, m, lb.data(), ub.data())); t_end = 1. - pow(2, -m*dim); } int nPoints = parser.get<int>("pointsNum"); assert(nPoints > 2); double dt = (t_end - t_start) / (nPoints); auto fileName = parser.get<std::string>("outFile"); const std::string sep = "_"; std::string generatedName = parser.get<std::string>("evolventType") + sep + "l_" + std::to_string(parser.get<int>("evolventsNum")) + sep + "n_" + std::to_string(parser.get<int>("dim")) + sep + "m_" + std::to_string(parser.get<int>("evolventTightness")); if(fileName.empty()) fileName = generatedName + ".csv"; std::ofstream fout; fout.open(fileName, std::ios_base::out); fout << generatedName << std::endl; std::vector<double> y(dim); auto start = std::chrono::system_clock::now(); for(int i = 0; i < nPoints; i++) { double t = dt*i + (l - 1); evolvent->GetImage(t, y.data()); for(int j = 0; j < dim - 1; j++) fout << y[j] << ", "; fout << y.back() << std::endl; } auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::cout << "Time elapsed: " << elapsed_seconds.count() << "s\n"; std::cout << "Generated file name: " << fileName << std::endl; return 0; } void initParser(cmdline::parser& parser) { parser.add<int>("evolventTightness", 'm', "", false, 12, cmdline::range(1, 20)); parser.add<int>("pointsNum", 'n', "", false, 500); parser.add<std::string>("evolventType", 't', "Type of the used evolvent", false, "rotated", cmdline::oneof<std::string>("rotated", "shifted", "noninjective", "multilevel", "smooth")); parser.add<int>("evolventsNum", 'l', "number of active evolvents (actually depends" "on evolvent type, tightness and dimenstion)", false, 1, cmdline::range(1, 20)); parser.add<int>("dim", 'd', "evolvent dimension", false, 2); parser.add<std::string>("outFile", 'f', "Name of the output .csv file with points", false, ""); }
// AddEntry adds an entry to the chain func (c *Chain) AddEntry(entry []byte) error { if !c.writable { return fmt.Errorf("chain opened as read-only") } c.merkle.AddHash(entry) return nil }
<reponame>bugvm/robovm /* * Copyright (C) 2013-2015 RoboVM AB * * 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 com.bugvm.apple.audiotoolbox; /*<imports>*/ import java.io.*; import java.nio.*; import java.util.*; import com.bugvm.objc.*; import com.bugvm.objc.annotation.*; import com.bugvm.objc.block.*; import com.bugvm.rt.*; import com.bugvm.rt.annotation.*; import com.bugvm.rt.bro.*; import com.bugvm.rt.bro.annotation.*; import com.bugvm.rt.bro.ptr.*; import com.bugvm.apple.foundation.*; import com.bugvm.apple.corefoundation.*; import com.bugvm.apple.audiounit.*; import com.bugvm.apple.coreaudio.*; import com.bugvm.apple.coremidi.*; /*</imports>*/ /*<javadoc>*/ /*</javadoc>*/ /*<annotations>*/@Library("AudioToolbox")/*</annotations>*/ /*<visibility>*/public/*</visibility>*/ class /*<name>*/AudioFile/*</name>*/ extends /*<extends>*/NativeObject/*</extends>*/ /*<implements>*//*</implements>*/ { public interface Callbacks { int read(long position, int requestCount, ByteBuffer buffer) throws OSStatusException; int write(long position, int requestCount, ByteBuffer buffer) throws OSStatusException; long getSize(); void setSize(long size); } /*<ptr>*/public static class AudioFilePtr extends Ptr<AudioFile, AudioFilePtr> {}/*</ptr>*/ private static java.util.concurrent.atomic.AtomicLong callbackId = new java.util.concurrent.atomic.AtomicLong(); private static final LongMap<Callbacks> callbacks = new LongMap<>(); private static final java.lang.reflect.Method cbRead; private static final java.lang.reflect.Method cbWrite; private static final java.lang.reflect.Method cbGetSize; private static final java.lang.reflect.Method cbSetSize; static { try { cbRead = AudioFile.class.getDeclaredMethod("cbRead", Long.TYPE, Long.TYPE, Integer.TYPE, Long.TYPE, IntPtr.class); cbWrite = AudioFile.class.getDeclaredMethod("cbWrite", Long.TYPE, Long.TYPE, Integer.TYPE, Long.TYPE, IntPtr.class); cbGetSize = AudioFile.class.getDeclaredMethod("cbGetSize", Long.TYPE); cbSetSize = AudioFile.class.getDeclaredMethod("cbSetSize", Long.TYPE, Long.TYPE); } catch (Throwable e) { throw new Error(e); } } /*<bind>*/static { Bro.bind(AudioFile.class); }/*</bind>*/ /*<constants>*//*</constants>*/ /*<constructors>*/ protected AudioFile() {} /*</constructors>*/ /*<properties>*//*</properties>*/ /*<members>*//*</members>*/ @Callback private static final OSStatus cbRead(@Pointer long clientData, long position, int requestCount, @Pointer long buffer, IntPtr actualCount) { synchronized (callbacks) { try { int actualRead = callbacks.get(clientData).read(position, requestCount, VM.newDirectByteBuffer(buffer, requestCount)); actualCount.set(actualRead); } catch (OSStatusException e) { return e.getStatus(); } return OSStatus.NO_ERR; } } @Callback private static final OSStatus cbWrite(@Pointer long clientData, long position, int requestCount, @Pointer long buffer, IntPtr actualCount) { synchronized (callbacks) { try { int actualWrite = callbacks.get(clientData).write(position, requestCount, VM.newDirectByteBuffer(buffer, requestCount)); actualCount.set(actualWrite); } catch (OSStatusException e) { return e.getStatus(); } return OSStatus.NO_ERR; } } @Callback private static final long cbGetSize(@Pointer long clientData) { synchronized (callbacks) { return callbacks.get(clientData).getSize(); } } @Callback private static final OSStatus cbSetSize(@Pointer long clientData, long size) { synchronized (callbacks) { callbacks.get(clientData).setSize(size); return OSStatus.NO_ERR; } } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public static AudioFile create(NSURL fileRef, AudioFileType fileType, AudioStreamBasicDescription format, AudioFileFlags flags) throws OSStatusException { AudioFile.AudioFilePtr ptr = new AudioFile.AudioFilePtr(); OSStatus status = create0(fileRef, fileType, format, flags, ptr); OSStatusException.throwIfNecessary(status); return ptr.get(); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public static AudioFile openURL(NSURL fileRef, byte permissions, AudioFileType fileTypeHint) throws OSStatusException { AudioFile.AudioFilePtr ptr = new AudioFile.AudioFilePtr(); OSStatus status = openURL0(fileRef, permissions, fileTypeHint, ptr); OSStatusException.throwIfNecessary(status); return ptr.get(); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public static AudioFile initialize(Callbacks callback, AudioFileType fileType, AudioStreamBasicDescription format, AudioFileFlags flags) throws OSStatusException { if (callback == null) { throw new NullPointerException("callbacks"); } AudioFile.AudioFilePtr ptr = new AudioFile.AudioFilePtr(); long cid = callbackId.getAndIncrement(); OSStatus status = initialize0(cid, new FunctionPtr(cbRead), new FunctionPtr(cbWrite), new FunctionPtr(cbGetSize), new FunctionPtr(cbSetSize), fileType, format, flags, ptr); if (OSStatusException.throwIfNecessary(status)) { synchronized (callbacks) { callbacks.put(cid, callback); } return ptr.get(); } return null; } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public static AudioFile open(Callbacks callback, AudioFileType fileTypeHint) throws OSStatusException { if (callback == null) { throw new NullPointerException("callbacks"); } AudioFile.AudioFilePtr ptr = new AudioFile.AudioFilePtr(); long cid = callbackId.getAndIncrement(); OSStatus status = open0(cid, new FunctionPtr(cbRead), new FunctionPtr(cbWrite), new FunctionPtr(cbGetSize), new FunctionPtr(cbSetSize), fileTypeHint, ptr); if (OSStatusException.throwIfNecessary(status)) { synchronized (callbacks) { callbacks.put(cid, callback); } return ptr.get(); } return null; } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public void closeFile() throws OSStatusException { OSStatus status = closeFile0(); OSStatusException.throwIfNecessary(status); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public void optimize() throws OSStatusException { OSStatus status = optimize0(); OSStatusException.throwIfNecessary(status); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public byte[] readBytes(boolean useCache, long startingByte, int bytesToRead) throws OSStatusException { IntPtr numBytesPtr = new IntPtr(); BytePtr ptr = new BytePtr(); OSStatus status = readBytes0(useCache, startingByte, numBytesPtr, ptr); OSStatusException.throwIfNecessary(status); return ptr.toByteArray(numBytesPtr.get()); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public int writeBytes(boolean useCache, long startingByte, byte[] buffer) throws OSStatusException { IntPtr ptr = new IntPtr(buffer.length); OSStatus status = writeBytes0(useCache, startingByte, ptr, VM.getArrayValuesAddress(buffer)); OSStatusException.throwIfNecessary(status); return ptr.get(); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public int countUserData(int userDataID) throws OSStatusException { IntPtr ptr = new IntPtr(); OSStatus status = countUserData0(userDataID, ptr); OSStatusException.throwIfNecessary(status); return ptr.get(); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public int getUserDataSize(int userDataID, int index) throws OSStatusException { IntPtr ptr = new IntPtr(); OSStatus status = getUserDataSize0(userDataID, index, ptr); OSStatusException.throwIfNecessary(status); return ptr.get(); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public <T extends Struct<T>> T getUserData(int userDataID, int index, Class<T> type) throws OSStatusException { T data = Struct.allocate(type); IntPtr dataSize = new IntPtr(Struct.sizeOf(data)); OSStatus status = getUserData0(userDataID, index, dataSize, data.as(VoidPtr.class)); OSStatusException.throwIfNecessary(status); return data; } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public void setUserData(int userDataID, int index, Struct<?> userData) throws OSStatusException { OSStatus status = setUserData0(userDataID, index, userData == null ? 0 : Struct.sizeOf(userData), userData == null ? null : userData.as(VoidPtr.class)); OSStatusException.throwIfNecessary(status); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public void removeUserData(int userDataID, int index) throws OSStatusException { OSStatus status = removeUserData0(userDataID, index); OSStatusException.throwIfNecessary(status); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public int getPropertySize(AudioFileProperty id) throws OSStatusException { IntPtr ptr = new IntPtr(); OSStatus status = getPropertyInfo0(id, ptr, null); OSStatusException.throwIfNecessary(status); return ptr.get(); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public boolean isPropertyWritable(AudioFileProperty id) throws OSStatusException { IntPtr ptr = new IntPtr(); OSStatus status = getPropertyInfo0(id, null, ptr); OSStatusException.throwIfNecessary(status); return ptr.get() != 0; } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public <T extends Struct<T>> T getProperty(AudioFileProperty id, Class<T> type) throws OSStatusException { T data = Struct.allocate(type); IntPtr dataSize = new IntPtr(Struct.sizeOf(data)); OSStatus status = getProperty0(id, dataSize, data.as(VoidPtr.class)); OSStatusException.throwIfNecessary(status); return data; } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public <T extends Struct<T>> void setProperty(AudioFileProperty id, T data) throws OSStatusException { OSStatus status = setProperty0(id, data == null ? 0 : Struct.sizeOf(data), data == null ? null : data.as(VoidPtr.class)); OSStatusException.throwIfNecessary(status); } public int getPropertyAsInt(AudioFileProperty id) throws OSStatusException { IntPtr ptr = getProperty(id, IntPtr.class); return ptr.get(); } public long getPropertyAsLong(AudioFileProperty id) throws OSStatusException { LongPtr ptr = getProperty(id, LongPtr.class); return ptr.get(); } public float getPropertyAsFloat(AudioFileProperty id) throws OSStatusException { FloatPtr ptr = getProperty(id, FloatPtr.class); return ptr.get(); } public double getPropertyAsDouble(AudioFileProperty id) throws OSStatusException { DoublePtr ptr = getProperty(id, DoublePtr.class); return ptr.get(); } public void setProperty(AudioFileProperty id, int value) throws OSStatusException { setProperty(id, new IntPtr(value)); } public void setProperty(AudioFileProperty id, long value) throws OSStatusException { setProperty(id, new LongPtr(value)); } public void setProperty(AudioFileProperty id, float value) throws OSStatusException { setProperty(id, new FloatPtr(value)); } public void setProperty(AudioFileProperty id, double value) throws OSStatusException { setProperty(id, new DoublePtr(value)); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public static int getGlobalInfoSize(AudioFileProperty id, Struct<?> specifier) throws OSStatusException { IntPtr ptr = new IntPtr(); OSStatus status = getGlobalInfoSize0(id, specifier == null ? 0 : Struct.sizeOf(specifier), specifier == null ? null : specifier.as(VoidPtr.class), ptr); OSStatusException.throwIfNecessary(status); return ptr.get(); } /** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public static <T extends Struct<T>> T getGlobalInfo(AudioFileProperty id, Struct<?> specifier, Class<T> type) throws OSStatusException { T data = Struct.allocate(type); IntPtr dataSize = new IntPtr(Struct.sizeOf(data)); OSStatus status = getGlobalInfo0(id, specifier == null ? 0 : Struct.sizeOf(specifier), specifier == null ? null : specifier.as(VoidPtr.class), dataSize, data.as(VoidPtr.class)); OSStatusException.throwIfNecessary(status); return data; } /*<methods>*/ /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileCreateWithURL", optional=true) protected static native OSStatus create0(NSURL inFileRef, AudioFileType inFileType, AudioStreamBasicDescription inFormat, AudioFileFlags inFlags, AudioFile.AudioFilePtr outAudioFile); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileOpenURL", optional=true) protected static native OSStatus openURL0(NSURL inFileRef, byte inPermissions, AudioFileType inFileTypeHint, AudioFile.AudioFilePtr outAudioFile); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileInitializeWithCallbacks", optional=true) protected static native OSStatus initialize0(@Pointer long inClientData, FunctionPtr inReadFunc, FunctionPtr inWriteFunc, FunctionPtr inGetSizeFunc, FunctionPtr inSetSizeFunc, AudioFileType inFileType, AudioStreamBasicDescription inFormat, AudioFileFlags inFlags, AudioFile.AudioFilePtr outAudioFile); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileOpenWithCallbacks", optional=true) protected static native OSStatus open0(@Pointer long inClientData, FunctionPtr inReadFunc, FunctionPtr inWriteFunc, FunctionPtr inGetSizeFunc, FunctionPtr inSetSizeFunc, AudioFileType inFileTypeHint, AudioFile.AudioFilePtr outAudioFile); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileClose", optional=true) protected native OSStatus closeFile0(); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileOptimize", optional=true) protected native OSStatus optimize0(); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileReadBytes", optional=true) protected native OSStatus readBytes0(boolean inUseCache, long inStartingByte, IntPtr ioNumBytes, BytePtr outBuffer); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileWriteBytes", optional=true) protected native OSStatus writeBytes0(boolean inUseCache, long inStartingByte, IntPtr ioNumBytes, @Pointer long inBuffer); /** * @since Available in iOS 2.2 and later. */ @Bridge(symbol="AudioFileReadPacketData", optional=true) protected native OSStatus readPacketData0(boolean inUseCache, IntPtr ioNumBytes, AudioStreamPacketDescription outPacketDescriptions, long inStartingPacket, IntPtr ioNumPackets, VoidPtr outBuffer); /** * @since Available in iOS 2.0 and later. * @deprecated Deprecated in iOS 8.0. */ @Deprecated @Bridge(symbol="AudioFileReadPackets", optional=true) protected native OSStatus readPackets0(boolean inUseCache, IntPtr outNumBytes, AudioStreamPacketDescription outPacketDescriptions, long inStartingPacket, IntPtr ioNumPackets, VoidPtr outBuffer); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileWritePackets", optional=true) protected native OSStatus writePackets0(boolean inUseCache, int inNumBytes, AudioStreamPacketDescription inPacketDescriptions, long inStartingPacket, IntPtr ioNumPackets, VoidPtr inBuffer); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileCountUserData", optional=true) protected native OSStatus countUserData0(int inUserDataID, IntPtr outNumberItems); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileGetUserDataSize", optional=true) protected native OSStatus getUserDataSize0(int inUserDataID, int inIndex, IntPtr outUserDataSize); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileGetUserData", optional=true) protected native OSStatus getUserData0(int inUserDataID, int inIndex, IntPtr ioUserDataSize, VoidPtr outUserData); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileSetUserData", optional=true) protected native OSStatus setUserData0(int inUserDataID, int inIndex, int inUserDataSize, VoidPtr inUserData); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileRemoveUserData", optional=true) protected native OSStatus removeUserData0(int inUserDataID, int inIndex); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileGetPropertyInfo", optional=true) protected native OSStatus getPropertyInfo0(AudioFileProperty inPropertyID, IntPtr outDataSize, IntPtr isWritable); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileGetProperty", optional=true) protected native OSStatus getProperty0(AudioFileProperty inPropertyID, IntPtr ioDataSize, VoidPtr outPropertyData); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileSetProperty", optional=true) protected native OSStatus setProperty0(AudioFileProperty inPropertyID, int inDataSize, VoidPtr inPropertyData); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileGetGlobalInfoSize", optional=true) protected static native OSStatus getGlobalInfoSize0(AudioFileProperty inPropertyID, int inSpecifierSize, VoidPtr inSpecifier, IntPtr outDataSize); /** * @since Available in iOS 2.0 and later. */ @Bridge(symbol="AudioFileGetGlobalInfo", optional=true) protected static native OSStatus getGlobalInfo0(AudioFileProperty inPropertyID, int inSpecifierSize, VoidPtr inSpecifier, IntPtr ioDataSize, VoidPtr outPropertyData); /*</methods>*/ }
<filename>src/components/basic/CustomScroll/index.tsx import React, { ReactNode } from 'react'; import classNames from 'classnames'; import { useThemeContext, ScrollBar } from '@biffbish/aave-ui-kit'; interface CustomScrollProps { children: ReactNode; className?: string; onUpdate?: (value: any) => void; } export default function CustomScroll({ children, className, onUpdate }: CustomScrollProps) { const { currentTheme } = useThemeContext(); return ( <> <ScrollBar className={classNames('CustomScroll', className)} onUpdate={onUpdate}> {children} </ScrollBar> <style jsx={true} global={true}>{` .CustomScroll > div { &:last-of-type { div { background-color: ${currentTheme.lightBlue.hex} !important; } } } `}</style> </> ); }
package ackhandler import ( "time" "github.com/lucas-clemente/quic-go/internal/protocol" "github.com/lucas-clemente/quic-go/internal/utils" "github.com/lucas-clemente/quic-go/internal/wire" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Received Packet Tracker", func() { var ( tracker *receivedPacketTracker rttStats *utils.RTTStats ) BeforeEach(func() { rttStats = &utils.RTTStats{} tracker = newReceivedPacketTracker(rttStats, utils.DefaultLogger, protocol.VersionWhatever) }) Context("accepting packets", func() { It("saves the time when each packet arrived", func() { tracker.ReceivedPacket(protocol.PacketNumber(3), protocol.ECNNon, time.Now(), true) Expect(tracker.largestObservedReceivedTime).To(BeTemporally("~", time.Now(), 10*time.Millisecond)) }) It("updates the largestObserved and the largestObservedReceivedTime", func() { now := time.Now() tracker.largestObserved = 3 tracker.largestObservedReceivedTime = now.Add(-1 * time.Second) tracker.ReceivedPacket(5, protocol.ECNNon, now, true) Expect(tracker.largestObserved).To(Equal(protocol.PacketNumber(5))) Expect(tracker.largestObservedReceivedTime).To(Equal(now)) }) It("doesn't update the largestObserved and the largestObservedReceivedTime for a belated packet", func() { now := time.Now() timestamp := now.Add(-1 * time.Second) tracker.largestObserved = 5 tracker.largestObservedReceivedTime = timestamp tracker.ReceivedPacket(4, protocol.ECNNon, now, true) Expect(tracker.largestObserved).To(Equal(protocol.PacketNumber(5))) Expect(tracker.largestObservedReceivedTime).To(Equal(timestamp)) }) }) Context("ACKs", func() { Context("queueing ACKs", func() { receiveAndAck10Packets := func() { for i := 1; i <= 10; i++ { tracker.ReceivedPacket(protocol.PacketNumber(i), protocol.ECNNon, time.Time{}, true) } Expect(tracker.GetAckFrame(true)).ToNot(BeNil()) Expect(tracker.ackQueued).To(BeFalse()) } It("always queues an ACK for the first packet", func() { tracker.ReceivedPacket(1, protocol.ECNNon, time.Now(), true) Expect(tracker.ackQueued).To(BeTrue()) Expect(tracker.GetAlarmTimeout()).To(BeZero()) Expect(tracker.GetAckFrame(true).DelayTime).To(BeNumerically("~", 0, time.Second)) }) It("works with packet number 0", func() { tracker.ReceivedPacket(0, protocol.ECNNon, time.Now(), true) Expect(tracker.ackQueued).To(BeTrue()) Expect(tracker.GetAlarmTimeout()).To(BeZero()) Expect(tracker.GetAckFrame(true).DelayTime).To(BeNumerically("~", 0, time.Second)) }) It("sets ECN flags", func() { tracker.ReceivedPacket(0, protocol.ECT0, time.Now(), true) pn := protocol.PacketNumber(1) for i := 0; i < 2; i++ { tracker.ReceivedPacket(pn, protocol.ECT1, time.Now(), true) pn++ } for i := 0; i < 3; i++ { tracker.ReceivedPacket(pn, protocol.ECNCE, time.Now(), true) pn++ } ack := tracker.GetAckFrame(false) Expect(ack.ECT0).To(BeEquivalentTo(1)) Expect(ack.ECT1).To(BeEquivalentTo(2)) Expect(ack.ECNCE).To(BeEquivalentTo(3)) }) It("queues an ACK for every second ack-eliciting packet", func() { receiveAndAck10Packets() p := protocol.PacketNumber(11) for i := 0; i <= 20; i++ { tracker.ReceivedPacket(p, protocol.ECNNon, time.Time{}, true) Expect(tracker.ackQueued).To(BeFalse()) p++ tracker.ReceivedPacket(p, protocol.ECNNon, time.Time{}, true) Expect(tracker.ackQueued).To(BeTrue()) p++ // dequeue the ACK frame Expect(tracker.GetAckFrame(true)).ToNot(BeNil()) } }) It("resets the counter when a non-queued ACK frame is generated", func() { receiveAndAck10Packets() rcvTime := time.Now() tracker.ReceivedPacket(11, protocol.ECNNon, rcvTime, true) Expect(tracker.GetAckFrame(false)).ToNot(BeNil()) tracker.ReceivedPacket(12, protocol.ECNNon, rcvTime, true) Expect(tracker.GetAckFrame(true)).To(BeNil()) tracker.ReceivedPacket(13, protocol.ECNNon, rcvTime, true) Expect(tracker.GetAckFrame(false)).ToNot(BeNil()) }) It("only sets the timer when receiving a ack-eliciting packets", func() { receiveAndAck10Packets() tracker.ReceivedPacket(11, protocol.ECNNon, time.Now(), false) Expect(tracker.ackQueued).To(BeFalse()) Expect(tracker.GetAlarmTimeout()).To(BeZero()) rcvTime := time.Now().Add(10 * time.Millisecond) tracker.ReceivedPacket(12, protocol.ECNNon, rcvTime, true) Expect(tracker.ackQueued).To(BeFalse()) Expect(tracker.GetAlarmTimeout()).To(Equal(rcvTime.Add(protocol.MaxAckDelay))) }) It("queues an ACK if it was reported missing before", func() { receiveAndAck10Packets() tracker.ReceivedPacket(11, protocol.ECNNon, time.Now(), true) tracker.ReceivedPacket(13, protocol.ECNNon, time.Now(), true) ack := tracker.GetAckFrame(true) // ACK: 1-11 and 13, missing: 12 Expect(ack).ToNot(BeNil()) Expect(ack.HasMissingRanges()).To(BeTrue()) Expect(tracker.ackQueued).To(BeFalse()) tracker.ReceivedPacket(12, protocol.ECNNon, time.Now(), true) Expect(tracker.ackQueued).To(BeTrue()) }) It("doesn't queue an ACK if it was reported missing before, but is below the threshold", func() { receiveAndAck10Packets() // 11 is missing tracker.ReceivedPacket(12, protocol.ECNNon, time.Now(), true) tracker.ReceivedPacket(13, protocol.ECNNon, time.Now(), true) ack := tracker.GetAckFrame(true) // ACK: 1-10, 12-13 Expect(ack).ToNot(BeNil()) // now receive 11 tracker.IgnoreBelow(12) tracker.ReceivedPacket(11, protocol.ECNNon, time.Now(), false) ack = tracker.GetAckFrame(true) Expect(ack).To(BeNil()) }) It("doesn't recognize in-order packets as out-of-order after raising the threshold", func() { receiveAndAck10Packets() Expect(tracker.lastAck.LargestAcked()).To(Equal(protocol.PacketNumber(10))) Expect(tracker.ackQueued).To(BeFalse()) tracker.IgnoreBelow(11) tracker.ReceivedPacket(11, protocol.ECNNon, time.Now(), true) Expect(tracker.GetAckFrame(true)).To(BeNil()) }) It("recognizes out-of-order packets after raising the threshold", func() { receiveAndAck10Packets() Expect(tracker.lastAck.LargestAcked()).To(Equal(protocol.PacketNumber(10))) Expect(tracker.ackQueued).To(BeFalse()) tracker.IgnoreBelow(11) tracker.ReceivedPacket(12, protocol.ECNNon, time.Now(), true) ack := tracker.GetAckFrame(true) Expect(ack).ToNot(BeNil()) Expect(ack.AckRanges).To(Equal([]wire.AckRange{{Smallest: 12, Largest: 12}})) }) It("doesn't queue an ACK if for non-ack-eliciting packets arriving out-of-order", func() { receiveAndAck10Packets() tracker.ReceivedPacket(11, protocol.ECNNon, time.Now(), true) Expect(tracker.GetAckFrame(true)).To(BeNil()) tracker.ReceivedPacket(13, protocol.ECNNon, time.Now(), false) // receive a non-ack-eliciting packet out-of-order Expect(tracker.GetAckFrame(true)).To(BeNil()) }) It("doesn't queue an ACK if packets arrive out-of-order, but haven't been acknowledged yet", func() { receiveAndAck10Packets() Expect(tracker.lastAck).ToNot(BeNil()) tracker.ReceivedPacket(12, protocol.ECNNon, time.Now(), false) Expect(tracker.GetAckFrame(true)).To(BeNil()) // 11 is received out-of-order, but this hasn't been reported in an ACK frame yet tracker.ReceivedPacket(11, protocol.ECNNon, time.Now(), true) Expect(tracker.GetAckFrame(true)).To(BeNil()) }) }) Context("ACK generation", func() { It("generates an ACK for an ack-eliciting packet, if no ACK is queued yet", func() { tracker.ReceivedPacket(1, protocol.ECNNon, time.Now(), true) // The first packet is always acknowledged. Expect(tracker.GetAckFrame(true)).ToNot(BeNil()) }) It("doesn't generate ACK for a non-ack-eliciting packet, if no ACK is queued yet", func() { tracker.ReceivedPacket(1, protocol.ECNNon, time.Now(), true) // The first packet is always acknowledged. Expect(tracker.GetAckFrame(true)).ToNot(BeNil()) tracker.ReceivedPacket(2, protocol.ECNNon, time.Now(), false) Expect(tracker.GetAckFrame(false)).To(BeNil()) tracker.ReceivedPacket(3, protocol.ECNNon, time.Now(), true) ack := tracker.GetAckFrame(false) Expect(ack).ToNot(BeNil()) Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(1))) Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(3))) }) Context("for queued ACKs", func() { BeforeEach(func() { tracker.ackQueued = true }) It("generates a simple ACK frame", func() { tracker.ReceivedPacket(1, protocol.ECNNon, time.Now(), true) tracker.ReceivedPacket(2, protocol.ECNNon, time.Now(), true) ack := tracker.GetAckFrame(true) Expect(ack).ToNot(BeNil()) Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(2))) Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(1))) Expect(ack.HasMissingRanges()).To(BeFalse()) }) It("generates an ACK for packet number 0", func() { tracker.ReceivedPacket(0, protocol.ECNNon, time.Now(), true) ack := tracker.GetAckFrame(true) Expect(ack).ToNot(BeNil()) Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(0))) Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(0))) Expect(ack.HasMissingRanges()).To(BeFalse()) }) It("sets the delay time", func() { tracker.ReceivedPacket(1, protocol.ECNNon, time.Now(), true) tracker.ReceivedPacket(2, protocol.ECNNon, time.Now().Add(-1337*time.Millisecond), true) ack := tracker.GetAckFrame(true) Expect(ack).ToNot(BeNil()) Expect(ack.DelayTime).To(BeNumerically("~", 1337*time.Millisecond, 50*time.Millisecond)) }) It("uses a 0 delay time if the delay would be negative", func() { tracker.ReceivedPacket(0, protocol.ECNNon, time.Now().Add(time.Hour), true) ack := tracker.GetAckFrame(true) Expect(ack).ToNot(BeNil()) Expect(ack.DelayTime).To(BeZero()) }) It("saves the last sent ACK", func() { tracker.ReceivedPacket(1, protocol.ECNNon, time.Now(), true) ack := tracker.GetAckFrame(true) Expect(ack).ToNot(BeNil()) Expect(tracker.lastAck).To(Equal(ack)) tracker.ReceivedPacket(2, protocol.ECNNon, time.Now(), true) tracker.ackQueued = true ack = tracker.GetAckFrame(true) Expect(ack).ToNot(BeNil()) Expect(tracker.lastAck).To(Equal(ack)) }) It("generates an ACK frame with missing packets", func() { tracker.ReceivedPacket(1, protocol.ECNNon, time.Now(), true) tracker.ReceivedPacket(4, protocol.ECNNon, time.Now(), true) ack := tracker.GetAckFrame(true) Expect(ack).ToNot(BeNil()) Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(4))) Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(1))) Expect(ack.AckRanges).To(Equal([]wire.AckRange{ {Smallest: 4, Largest: 4}, {Smallest: 1, Largest: 1}, })) }) It("generates an ACK for packet number 0 and other packets", func() { tracker.ReceivedPacket(0, protocol.ECNNon, time.Now(), true) tracker.ReceivedPacket(1, protocol.ECNNon, time.Now(), true) tracker.ReceivedPacket(3, protocol.ECNNon, time.Now(), true) ack := tracker.GetAckFrame(true) Expect(ack).ToNot(BeNil()) Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(3))) Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(0))) Expect(ack.AckRanges).To(Equal([]wire.AckRange{ {Smallest: 3, Largest: 3}, {Smallest: 0, Largest: 1}, })) }) It("doesn't add delayed packets to the packetHistory", func() { tracker.IgnoreBelow(7) tracker.ReceivedPacket(4, protocol.ECNNon, time.Now(), true) tracker.ReceivedPacket(10, protocol.ECNNon, time.Now(), true) ack := tracker.GetAckFrame(true) Expect(ack).ToNot(BeNil()) Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(10))) Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(10))) }) It("deletes packets from the packetHistory when a lower limit is set", func() { for i := 1; i <= 12; i++ { tracker.ReceivedPacket(protocol.PacketNumber(i), protocol.ECNNon, time.Now(), true) } tracker.IgnoreBelow(7) // check that the packets were deleted from the receivedPacketHistory by checking the values in an ACK frame ack := tracker.GetAckFrame(true) Expect(ack).ToNot(BeNil()) Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(12))) Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(7))) Expect(ack.HasMissingRanges()).To(BeFalse()) }) It("resets all counters needed for the ACK queueing decision when sending an ACK", func() { tracker.ReceivedPacket(1, protocol.ECNNon, time.Now(), true) tracker.ackAlarm = time.Now().Add(-time.Minute) Expect(tracker.GetAckFrame(true)).ToNot(BeNil()) Expect(tracker.GetAlarmTimeout()).To(BeZero()) Expect(tracker.ackElicitingPacketsReceivedSinceLastAck).To(BeZero()) Expect(tracker.ackQueued).To(BeFalse()) }) It("doesn't generate an ACK when none is queued and the timer is not set", func() { tracker.ReceivedPacket(1, protocol.ECNNon, time.Now(), true) tracker.ackQueued = false tracker.ackAlarm = time.Time{} Expect(tracker.GetAckFrame(true)).To(BeNil()) }) It("doesn't generate an ACK when none is queued and the timer has not yet expired", func() { tracker.ReceivedPacket(1, protocol.ECNNon, time.Now(), true) tracker.ackQueued = false tracker.ackAlarm = time.Now().Add(time.Minute) Expect(tracker.GetAckFrame(true)).To(BeNil()) }) It("generates an ACK when the timer has expired", func() { tracker.ReceivedPacket(1, protocol.ECNNon, time.Now(), true) tracker.ackQueued = false tracker.ackAlarm = time.Now().Add(-time.Minute) Expect(tracker.GetAckFrame(true)).ToNot(BeNil()) }) }) }) }) })
class Topology: """ This class unifies the functions to deal with **Complex Networks** as a network topology within of the simulator. In addition, it facilitates its creation, and assignment of attributes. """ LINK_BW = "BW" "Link feature: Bandwidth" LINK_PR = "PR" "Link feauture: Propagation delay" # LINK_LATENCY = "LATENCY" # " A edge or a network link has a Bandwidth" NODE_IPT = "IPT" "Node feature: IPS . Instructions per Simulation Time " def __init__(self, logger=None): # G is a nx.networkx graph self.G = None self.nodeAttributes = {} self.logger = logger or logging.getLogger(__name__) def __init_uptimes(self): for key in self.nodeAttributes: self.nodeAttributes[key]["uptime"] = (0, None) def get_edges(self): """ Returns: list: a list of graph edges, i.e.: ((1,0),(0,2),...) """ return self.G.edges def get_edge(self,key): """ Args: key (str): a edge identifier, i.e. (1,9) Returns: list: a list of edge attributes """ return self.G.edges[key] def get_nodes(self): """ Returns: list: a list of all nodes features """ return self.G.nodes def get_node(self, key): """ Args: key (int): a node identifier Returns: list: a list of node features """ return self.G.node[key] def get_info(self): return self.nodeAttributes def create_topology_from_graph(self, G): """ It generates the topology from a NetworkX graph Args: G (*networkx.classes.graph.Graph*) """ if isinstance(G, nx.classes.graph.Graph): self.G = G else: raise TypeError def create_random_topology(self, nxGraphGenerator, params): """ It generates the topology from a Graph generators of NetworkX Args: nxGraphGenerator (function): a graph generator function Kwargs: params (dict): a list of parameters of *nxGraphGenerator* function """ try: self.G = nxGraphGenerator(*params) except: raise Exception def load(self, data): warnings.warn("The load function will merged with load_all_node_attr function", FutureWarning, stacklevel=8 ) """ It generates the topology from a JSON file see project example: Tutorial_JSONModelling Args: data (str): a json """ self.G = nx.Graph() for edge in data["link"]: self.G.add_edge(edge["s"], edge["d"], BW=edge[self.LINK_BW],PR=edge[self.LINK_PR]) #TODO This part can be removed in next versions for node in data["entity"]: self.nodeAttributes[node["id"]] = node #end remove # Correct way to use custom and mandatory topology attributes valuesIPT = {} # valuesRAM = {} for node in data["entity"]: try: valuesIPT[node["id"]] = node["IPT"] except KeyError: valuesIPT[node["id"]] = 0 # try: # valuesRAM[node["id"]] = node["RAM"] # except KeyError: # valuesRAM[node["id"]] = 0 nx.set_node_attributes(self.G,values=valuesIPT,name="IPT") # nx.set_node_attributes(self.G,values=valuesRAM,name="RAM") self.__init_uptimes() def load_all_node_attr(self,data): self.G = nx.Graph() for edge in data["link"]: self.G.add_edge(edge["s"], edge["d"], BW=edge[self.LINK_BW], PR=edge[self.LINK_PR]) dc = {str(x): {} for x in data["entity"][0].keys()} for ent in data["entity"]: for key in ent.keys(): dc[key][ent["id"]] = ent[key] for x in data["entity"][0].keys(): nx.set_node_attributes(self.G, values=dc[x], name=str(x)) for node in data["entity"]: self.nodeAttributes[node["id"]] = node self.__idNode = len(self.G.nodes) self.__init_uptimes() def load_graphml(self,filename): warnings.warn("The load_graphml function is deprecated and " "will be removed in version 2.0.0. " "Use NX.READ_GRAPHML function instead.", FutureWarning, stacklevel=8 ) self.G = nx.read_graphml(filename) attEdges = {} for k in self.G.edges(): attEdges[k] = {"BW": 1, "PR": 1} nx.set_edge_attributes(self.G, values=attEdges) attNodes = {} for k in self.G.nodes(): attNodes[k] = {"IPT": 1} nx.set_node_attributes(self.G, values=attNodes) for k in self.G.nodes(): self.nodeAttributes[k] = self.G.node[k] #it has "id" att. TODO IMPROVE def get_nodes_att(self): """ Returns: A dictionary with the features of the nodes """ return self.nodeAttributes def find_IDs(self,value): """ Search for nodes with the same attributes that value Args: value (dict). example value = {"model": "m-"}. Only one key is admitted Returns: A list with the ID of each node that have the same attribute that the value.value """ keyS = list(value.keys())[0] result = [] for key in self.nodeAttributes.keys(): val = self.nodeAttributes[key] if keyS in val: if value[keyS] == val[keyS]: result.append(key) return result def size(self): """ Returns: an int with the number of nodes """ return len(self.G.nodes) def add_node(self, nodes, edges=None): """ Add a list of nodes in the topology Args: nodes (list): a list of identifiers edges (list): a list of destination edges """ self.__idNode = + 1 self.G.add_node(self.__idNode) self.G.add_edges_from(zip(nodes, [self.__idNode] * len(nodes))) return self.__idNode def remove_node(self, id_node): """ Remove a node of the topology Args: id_node (int): node identifier """ self.G.remove_node(id_node) return self.size()
#include<bits/stdc++.h> using namespace std; int main() { int m, num, x, i; bool chk; cin >> num; if(num==1) { cout << '3' <<endl; return 0; } if(num==2) { cout << '4' <<endl; return 0; } for(chk=false,m=1; m<num; m++) { x = (m*num)+1; if(!(x%2)) chk = true; else if(x>2) { for(i=3; i<x; i+=2) { if(x%i==0) { chk = true; break; } } } if(chk) { cout << m <<endl; break; } } return 0; }
<reponame>huongdg/Apache-Spark-2x-for-Java-Developers<gh_stars>0 package com.packt.sfjd.ch7; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.spark.HashPartitioner; import org.apache.spark.RangePartitioner; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.rdd.RDD; import scala.Tuple2; public class Partitioning { public static void main(String[] args) { System.setProperty("hadoop.home.dir", "C:\\softwares\\Winutils"); SparkConf conf = new SparkConf().setMaster("local").setAppName("Partitioning"); JavaSparkContext jsc = new JavaSparkContext(conf); JavaPairRDD<Integer, String> pairRdd = jsc.parallelizePairs( Arrays.asList(new Tuple2<Integer, String>(1, "A"),new Tuple2<Integer, String>(2, "B"), new Tuple2<Integer, String>(3, "C"),new Tuple2<Integer, String>(4, "D"), new Tuple2<Integer, String>(5, "E"),new Tuple2<Integer, String>(6, "F"), new Tuple2<Integer, String>(7, "G"),new Tuple2<Integer, String>(8, "H")),3); RDD<Tuple2<Integer, String>> rdd = JavaPairRDD.toRDD(pairRdd); System.out.println(pairRdd.getNumPartitions()); // JavaPairRDD<Integer, String> hashPartitioned = pairRdd.partitionBy(new HashPartitioner(2)); // // System.out.println(hashPartitioned.getNumPartitions()); RangePartitioner rangePartitioner = new RangePartitioner(4, rdd, true, scala.math.Ordering.Int$.MODULE$ , scala.reflect.ClassTag$.MODULE$.apply(Integer.class)); JavaPairRDD<Integer, String> rangePartitioned = pairRdd.partitionBy(rangePartitioner); JavaRDD<String> mapPartitionsWithIndex = rangePartitioned.mapPartitionsWithIndex((index, tupleIterator) -> { List<String> list=new ArrayList<>(); while(tupleIterator.hasNext()){ list.add("Partition number:"+index+",key:"+tupleIterator.next()._1()); } return list.iterator(); }, true); System.out.println(mapPartitionsWithIndex.collect()); } }
<filename>unn/models/heads/utils/accuracy.py<gh_stars>1-10 from functools import reduce import torch def binary_accuracy(output, target, thresh=0.5, ignore_index=-1): """binary classification accuracy. e.g sigmoid""" output = output.view(-1) target = target.view(-1) keep = torch.nonzero(target != ignore_index).squeeze() if keep.dim() <= 0: return [torch.cuda.FloatTensor([1]).zero_()] assert (keep.dim() == 1) target = target[keep] output = output[keep] binary = (output > thresh).type_as(target) tp = (binary == target).float().sum(0, keepdim=True) return [tp.mul_(100.0 / target.numel())] def accuracy(output, target, topk=(1, ), ignore_indices=[-1]): """Computes the precision@k for the specified values of k""" if output.numel() != target.numel(): C = output.shape[-1] output = output.view(-1, C) target = target.view(-1) masks = [target != idx for idx in ignore_indices] mask = reduce(lambda x, y: x & y, masks) keep = torch.nonzero(mask).squeeze() if keep.numel() <= 0: return [torch.cuda.FloatTensor([1]).zero_()] if keep.dim() == 0: keep = keep.view(-1) assert keep.dim() == 1, keep.dim() target = target[keep] output = output[keep] maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res
export * from './config.util' export * from './consts.util' export * from './objs.util'
// putValueByPath puts the value in the user specified sr.ByPath func (sr *SearchReplace) putValueByPath(object *yaml.RNode) error { path := strings.Split(sr.ByPath, PathDelimiter) node, err := object.Pipe(yaml.LookupCreate(yaml.MappingNode, path[:len(path)-1]...)) if err != nil { return errors.Wrap(err) } sn := yaml.NewScalarRNode(sr.PutValue) sn.YNode().Tag = yaml.NodeTagEmpty err = node.PipeE(yaml.SetField(path[len(path)-1], sn)) if err != nil { return errors.Wrap(err) } res := SearchResult{ FilePath: sr.filePath, FieldPath: sr.ByPath, Value: sr.PutValue, } sr.Results = append(sr.Results, res) sr.Count++ return nil }
def _gather_points(self): x = self.index.get_data() y = self.value.get_data() rad= min(self.width/2.0,self.height/2.0) sx = x*rad+ self.x + self.width/2.0 sy = y*rad+ self.y + self.height/2.0 points = transpose(array((sx,sy))) self._cached_data_pts = points self._cache_valid = True return
Electroweak single-pion production off the nucleon: from threshold to high invariant masses Neutrino-induced single-pion production (SPP) provides an important contribution to neutrino-nucleus interactions, ranging from intermediate to high energies. There exists a good number of low-energy models in the literature to describe the neutrinoproduction of pions in the region around the Delta resonance. Those models consider only lowest-order interaction terms and, therefore, fail in the high-energy region (pion-nucleon invariant masses, $W$>2 GeV). Our goal is to develop a model for electroweak SPP off the nucleon, which is applicable to the entire energy range of interest for present and future neutrino-oscillation experiments. We start with the low-energy model of , which includes resonant contributions and background terms derived from the pion-nucleon Lagrangian of chiral-perturbation theory. Then, from the background contributions, we build a high-energy model using a Regge approach. The low- and high-energy models are combined, in a phenomenological way, into a hybrid model. The Hybrid model is identical to the low-energy model in the low-W region, but, for W>2 GeV, it implements the desired high-energy behavior dictated by Regge theory. We have tested the high-energy model by comparing with one-pion production data from electron and neutrino reactions. The Hybrid model is compared with electron-proton scattering data, with neutrino SPP data and with the predictions of the NuWro Monte Carlo event generator. Our model is able to provide satisfactory predictions of the electroweak one-pion production cross section from pion threshold to high $W$. Further investigation and more data are needed to better understand the mechanisms playing a role in the electroweak SPP process in the high-W region, in particular, those involving the axial current contributions. I. INTRODUCTION Single-pion production constitutes an important contribution to the neutrino-nucleus cross section in the region covered by accelerator-based neutrino-oscillation experiments such as Mini-BooNE and T2K , with a beam energy of ε ν ∼ 0.5 − 2 GeV. These experiments, which use nuclei as target material, select the events of the dominant charged-current (CC) quasielastic (QE) ν µ n → µ − p channel to reconstruct the neutrino energy. Single-pion production ν µ N → µ − N ′ π is an important background in the identification process: if the produced pion is absorbed in the nucleus the signal mimics a QE event in the detector. These events are subtracted from the QE sample * [email protected] using event generators which base their predictions on theoretical models. Thus, if such predictions are not accurate, the error is propagated systematically to the reconstructed energy which is subsequently used to obtain the neutrino oscillation parameters. Weak-neutral current (WNC) π 0 production, νN → νN ′ π 0 , is also an important background in ν e (ν e ) appearance experiments due to the difficulty to distinguish between a π 0 and an electron (positron) signal. Therefore, in order to make precise estimates for the desired oscillation parameters, it is essential to have theoretical models capable of providing reliable predictions for the pion-production process at the vertex level as well as for the pion propagation through the nuclear medium. In addition, weak pion production offers a unique opportunity to learn about the axial form factors of the nucleon resonances and, in general, about the nucleon axial current. In this line, the recent sets of neutrino-induced SPP data from MiniBooNE and MINERvA , as well as the inclusive neutrino-nucleus data from T2K and SciBooNE , offer an excellent opportunity to test and improve the existing models on pion production in the nuclear medium. There exists a good number of models in the literature describing the neutrinoproduction of pions in the region around the Delta resonance (see Refs. for a review), that is, from the pion threshold to W ≈ 1.4 GeV (where W is the πN -invariant mass). In spite of the differences between these models, all of them describe the reaction amplitude using lowest order interaction terms, which is appropriate near the pion-production threshold. At increasing energies, however, higher order contributions must be taken into account to properly model the dynamics of the reaction. It is not surprising, therefore, that lowenergy models fail when they are applied in the high-energy region (W 2 GeV). It is well-known that the relative importance of SPP in the inclusive cross section gradually decreases for increasing invariant masses due to the contribution of a multitude of new opened channels, such as twopion production, production of other mesons, deep inelastic scattering (DIS), etc. In spite of that, it remains highly desirable to have models that are able to make reliable predictions for the SPP channel in the entire energy domain covered by experiments. This is evident, for instance, in the MINERvA experiment, where the neutrino flux peaks around 4 GeV and extends to 10 GeV, which allows for invariant masses much larger than 1.4 GeV. The same will happen in future acceleratorbased neutrino-oscillation experiments, such as NOvA and DUNE , where the beam flux covers a similar energy range as the MINERvA experiment. In this work, we propose to extend the description of neutrino-induced pion production to higher W . For that, we use Regge phenomenology . As a first step, we focus on neutrinoinduced SPP off the nucleon. Work on applying this model to the pion production on nuclei is in progress. Our starting point is the model first presented by Hernández, Nieves and Valverde in Ref. , and later improved in Refs. . This model provides a microscopic description of the SPP by working at the amplitude level. The pion-production mechanism includes, in addition to the dominant Delta-resonance decay, the background contributions deduced from the chiral-perturbation theory Lagrangian of the pionnucleon system (ChPT background or, simply, background terms in what follows). Later on, the D 13 (1520) resonance was included in the model in order to improve the comparison with MiniBooNE data . Recently, the model was further improved by incorporating the relative phases between the background diagrams and the dominant partial wave of the Delta pole, which partially restores unitarity (see Ref. for details). This model has been used by several groups with notable success in reproducing electron-and neutrino-induced SPP data in the region W 1.4 GeV . Regge phenomenology is a well-tested method that allows one to make predictions in the highenergy domain (W > 2 GeV) without having to resort to partonic degrees of freedom. It has proven successful in modeling purely hadronic interactions , as well as photo-and electroproduction on nucleons . For increasing W , the number of overlapping nucleon resonances grows and the typical peaked resonance structures observed at low energies tends to disappear. The main idea that drives Regge theory is that at high energies the dynamics can be understood in terms of crosschannel contributions only. This observation is generally explained by a duality argument, which states that the amplitude obtained by summing over all s-channel resonances is, on average, equivalent to the amplitude obtained by summing over all t-channel meson-exchange amplitudes (or Regge poles). Thus, only background terms are normally considered in Regge-based models. Care must be taken, since a truncated set of cross-channel contributions continued into the direct channel generally results in a disastrous overshoot of the cross section. Therefore, in Regge theory, one analytically continues a summation of an infinite number of cross-channel partial waves into the direct channel. We propose to reggeize the ChPT-background contributions by following the method originally presented by Levy, Majerotto, and Read , and further developed by Guidal, Laget, and Vanderhaeghen for charged-meson photoproduction at high W and forward scattering angles of the pion. The method consists in replacing the propagator of the t-channel meson-exchange diagrams by the corresponding Regge propagators. In this way, each (t-channel) Regge amplitude includes an entire family of hadrons. The great success achieved by this model in reproducing highenergy forward-scattering photoproduction data, motivated its extension to other reactions such as electroproduction , which is of major interest to us. In the framework of Ref. , the sand u-channel nucleon poles are considered along with the t-channel pion-exchanged diagram in order to preserve vector-current conservation. While this approach allowed to understand the behavior of the longitudinal component of the electropro-duction cross section, it did not provide a satisfactory description of the transverse one. This was remedied by Kaskulov and Mosel in Ref. , by taking into account the fact that the nucleon in the s-and u-channel Born diagrams may be highly off its mass shell. We will use this model as a guide to reggeize the ChPT-background terms. Based on the mentioned previous works, it is straightforward to reggeize the vector current of the ChPT background, the novelty of this work resides in the reggeization of the axial current, which allows us to make predictions for neutrino interaction. The outline of this article is as follows. In Sec. II, we present the kinematic relations and the cross section formula. In Sec. III, we briefly summarize the low-energy model. In Sec. IV, we discuss, in detail, the procedure to build the high-energy model by reggeizing the background contributions of the low-energy model. In Sec. V, we propose a phenomenological way of combining the low-and high-energy models into a hybrid model. Our conclusions are summarized in Sec. VI. We have tried to make this article as self-contained as possible. For this reason, we have included in Appendix A the derivation of the axial and vector currents of the pion-nucleon system in the ChPT framework. Finally, in Appendix B we have included the formulas and parameters related to the nucleon resonances that are considered in this work. II. KINEMATICS AND CROSS SECTION We aim at modeling the electroweak one-pion production on free nucleons. Electroweak refers to the fact that the same model is used to describe electron-induced one-pion production, mediated by the exchange of a virtual photon (electromagnetic interaction, EM), as well as neutrinoinduced one-pion production, mediated by the exchange of W ± boson (CC interaction) or Z boson (WNC interaction). The process is depicted in Fig. 1 along with the notation employed for the kinematic variables. All four-vectors involved in the 2 → 3 process (Fig. 1) are completely determined by six independent variables. We therefore introduce the "lab variables" ε i , ε f , θ f , φ f , θ π , and φ π 1 . The most exclusive cross section for the process 1 Since the process is symmetric under rotation over the angle φ f , we can set φ f = 0. Thus, the actual number of independent variables needed to characterize the process reduces to five. FIG. 1. One-pion production on a free nucleon in the laboratory system. An incoming lepton K µ i along theẑ direction is scattered by a free nucleon at rest P µ i = (M, 0). The final state is given by a lepton K µ f , a nucleon P µ N , and a pion K µ π . depicted in Fig. 1 is given by the nucleon recoil factor. The factor F depends on the particular process under study and includes the boson propagator as well as the coupling constants at the leptonic vertex: We have introduced Q 2 = −(K i − K f ) 2 = q 2 − ω 2 > 0, with ω and q the energy and momentum transfer in the lab system. We define the dimensionless lepton tensor l µν as with h = −1(+1) for neutrinos (antineutrinos). The lepton tensor has been decomposed in terms of the symmetric (s µν ) and antisymmetric (a µν ) tensors: with ǫ 0123 = +1. The hadronic tensor is given by where sN ,s implies a sum over the spin of the final nucleon (s N ) and an average over the spin of the initial nucleon (s). The hadronic current J µ is evaluated between initial and final states and, in general, depends on all independent variables of the process. For simplicity, in what follows we will simply write J µ . It reads where O µ 1π represents the operator which induces the transition between the initial one-nucleon state and the final one-nucleon one-pion state. u(p N , s N ) and u(p, s) are free Dirac spinors describing the scattered and initial nucleon, respectively. C is the electroweak coupling constant of the hadronic current: It is convenient to introduce variables which intuitively describe the hadronic 2 → 2 subprocess (Fig. 2). In the hadronic center of mass system (cms) 2 , where p * i + q * = 0 and q * is defined along theẑ direction (see Fig. 2), only three independent variables are required to describe the kinematics of this subsystem. Therefore, we introduce the set of variables s, t and Q 2 , with s and t the usual Mandelstam variables. To facilitate discussions about the dynamics of the system, we determine the kinematic regime of the hadronic subprocess related to a given lab configuration. In general, the invariant mass W is given by 2 The variables in the cms are denoted by the * index. Some of the results presented in the next sections are computed in two extreme kinematic scenarios: backward scattering (θ f → 180 deg), which correspond to high Q 2 , and forward scattering (θ f → 0 deg), corresponding to Q 2 ≈ 0. The idea is that given the results at these kinematics, it is possible to intuit or extrapolate the behavior at any other intermediate situation. In Fig. 3, we show the relation between the invariant mass W and Q 2 , according to Eq. 9: we fix (θ f , ε i ) and vary ε f . Thus, for a fixed value of ε i , any curve corresponding to an intermediate scattering angle θ f will fall in the region between the two extreme curves. In the cms (Fig. 2), the Mandelstam variable t = (Q − K π ) 2 can be related to the cms-pion scattering angle θ * π by t = m 2 π − Q 2 − 2(ω * E * π − q * k * π cos θ * π ) , (10) where In the case cos θ * π = −1 and cos θ * π = 1, Eq. 10 provides the maximum and minimum t values allowed by energy-momentum conservation. This is shown in Fig. 4 for the same set of kinematics as in Fig. 3. Fixing (θ f , ε i , cos θ * π = ±1) and varying ε f we generate the solid and dashed lines, which correspond to the extreme values of t. The shadowed area between these curves represents the allowed kinematic region. The blue solid line is the parabola corresponding to −t = s. We set the limit of applicability of our high-energy model (based on Regge-trajectory exchanges) to the region below this line and W > 2 GeV (see Sec. IV). The −t-maximum (dashed) and −t-minimum (solid) lines are solutions of Eq. 10 for cos θ * π = −1 and cos θ * π = 1, respectively. The blue solid line is the curve corresponding to −t = W 2 . III. LOW ENERGY MODEL: RESONANCES AND CHPT BACKGROUND In this section, we describe the low-energy model. It contains the s-and u-channel diagrams of the P 33 (1232) (Delta) and D 13 (1520) resonances and the background terms from the ChPT πN -Lagrangian (Appendix A), as presented in Refs. . In addition, we also consider the s-and uchannel contributions from the spin-1/2 resonances S 11 (1535) and P 11 (1440). The corresponding Feynman diagrams are shown in Figs. 5 and 6. In the following, we summarize the expressions for the hadronic current operators (see Eq. 7) for each contribution. The hadronic current operators for the background terms of Fig. 5 are: with K µ s = P µ + Q µ , andΓ µ QN N (Q µ ) given in ChPT-background contributions (from left to right and top to bottom): s channel (nucleon pole, N P ), u channel (cross-nucleon pole, CN P ), contact term (CT ), pion pole (P P ), and t channel (pion-inflight term, P F ). Eqs. A15, A20 and A29, CT a with the axial (CT a) and a vector (CT v) contributions given by I is the isospin coefficient of each diagram (see Tables I and II). We have introduced the nucleon form factors (F p,n 1,2 for neutral-current interactions and F V 1,2 for CC interaction) in the N P and CN P amplitudes (see Eqs. A15, A20 and A29). Therefore, to respect conservation of vector current (CVC) we have included the isovector nucleon form factors, F V 1,2 , in the P F and CT v amplitudes : The form factor F ρ (t) = m 2 ρ /(m 2 ρ − t), with m ρ = 775. 8 MeV, has been introduced in the P P term to account for the ρ-dominance of the ππN N coupling . Consequently, to preserve partial conservation of axial current (PCAC) the same form factor was inserted in the CT a amplitude. In the case of the WNC interaction, one has to replace the isovector vector form factor by the corresponding WNC one, i.e. For nucleon resonances with spin S = 3/2 (quoted as R 3 ) the direct and cross terms are In the CR 3 P operator (Eq. 21) we introduced the electroweak vertex function Γ βµ The explicit expressions for the strong RπN and electroweak QRN vertices, and the resonance propagators (S R ) are given in Appendix B. The isospin coefficients of the Delta resonance are shown in Tables I and II. The isospin coefficients of the S 11 (1535) and P 11 (1440) resonances coincide with those of the N P and CN P terms. The vector form factors that enter in the electroweak QRN vertices were fitted to reproduce pion photo-and electroproduction data given in terms of helicity amplitudes for the EM current. The information on the axial form factors is limited to restrictions provided by the PCAC hypothesis and the BNL and ANL experimental data. In this work, we use the parametrization of the vector form factors from Ref. (for the P 33 , D 13 , and S 11 ) and Ref. (for the P 11 ). For the axial form factors we use the parametrizations presented in Ref. (for the P 33 ), Ref. (for the S 11 and D 13 ), and Ref. (for the P 11 ). The explicit expressions for the form factors are given in Appendix B. The current operator that enters in the hadronic current of Eq. 7 is given by and Channel ∆P C∆P N P CN P Others p → π + + p 3/2 1/6 0 1 1 n → π 0 + p − 1/3 1/3 O µ R is the current operator of a resonance R. We have taken into account the relative phases between the ChPT background and the ∆P contribution making use of the parameterization of the Olsson phases presented in Ref. . In this way, unitarity is partially restored (see Ref. for details). In principle, the same should be done for the other higher mass resonances, however, those phases are unknown within this model. Although not shown here, we have compared all the results presented in this work with the results in the case of adding the higher mass resonances incoherently (i.e., avoiding interferences). We concluded that, given the large uncertainties from others sources such as resonance form factors, the differences between the two approaches are not significant. In this regard, the dynamical coupled-channels model for neutrino-induced meson production presented in Refs. is worth mentioning. To our knowledge, this is the only model that fully controls the interferences between resonant and non-resonant amplitudes. The low-energy model described above, in particular the model containing the ChPTbackground terms and the s-and u-channel Delta resonance, has been extensively tested versus photon-, electron-and neutrino-induced one-pion production data . The agreement with data is generally good in the region W 1.3−1.4 GeV where the chiral expansion is expected to be valid and the pathological highenergy behavior of the tree-level diagrams still does not manifest itself. The incorporation of higher mass resonances does not significantly change the results in this W region so we do not repeat such systematic comparisons with data here. Instead, in Sec. V we present some results in which this model (referred as LEM in that section) is compared with electron and neutrino cross section data. IV. HIGH ENERGY MODEL: REGGEIZING THE CHPT BACKGROUND It is well-known that low-energy models, like the one described above, are not reliable at high invariant masses (W > 1.4 GeV), due to the fact that only the lowest-order contributions are considered. For increasing energies, one needs to consider higher-order contributions to the amplitude, a procedure that soon becomes intractable and cumbersome. The starting point of Regge theory is an infinite summation over all partial waves in the t-channel amplitude. This can be done by reformulating this infinite series in terms of a contour integral in the complex angular momentum plane. A Regge pole then corresponds to a pole in the complex angular momentum plane, which physically represents a whole family of t-channel contributions. This formalism allows one to incorporate an infinite number of contributions to the scattering amplitude in an efficient way. Regge theory provides one with the s-dependence of the hadronic amplitude at high energies. However, it does not predict the t-dependence of the residues 3 . In spite of that, as shown by Guidal, Laget and Vanderhaeghen , a good approximation for the t-dependence of the residues at forward θ * π scattering angles (corresponding to small −t values) can be made from the t-dependence of background contributions in low-energy models. This is inspired by the fact that the physical region of the direct channel is not too far from the nearest pole of the Regge trajectory. In this section, we focus on the modeling of electroweak pion production in the high W and forward θ * π scattering region, equivalently, −t/s << 1. To this end, we reggeize the ChPTbackground model introduced in the previous section following the method proposed in Ref. for photoproduction. This method boils down to replacing the propagator of the t-channel mesonexchange diagrams with the corresponding Regge propagators. At backward θ * π scattering angles (corresponding to large −t values), the pion pole is too far from the actual kinematics of the reaction to cause any significant effect in the physical amplitude. Therefore, the t-dependence of the amplitude cannot be modeled by t-channel meson-exchange diagrams. Instead, at backward θ * π , small u values are approached, which places the u-channel nucleon pole closer to the kinematics of the reaction. Consequently, the amplitude should be modeled by the exchange of baryon trajectories in the u channel. This modeling of the backward reaction is out of the scope of the present work. Hence, we expect to underestimate the cross section in the backward region. This should not be too big a problem as, at high W , the magnitude of the cross section at forward θ * π scattering is generally orders of magnitude larger than the cross section at intermediate or backward scattering angles (this is shown, for instance, in Fig. 1 of Ref. ). It is expected, therefore, that t-channel meson-exchange models, as the one presented here, will also provide good predictions of the θ * π -integrated cross section. First, we reggeize the EM current and compare our predictions with exclusive p(e, e ′ π + )n and n(e, e ′ π − )p experimental data. Then, using this model as a benchmark, the formalism is extended to CC and WNC neutrino-induced SPP. A. Electroproduction of charge pions The building blocks of the Regge-based models for π ± production presented in Refs. are the pion-exchange t-channel amplitude and the s-and u-channel amplitudes with pseudoscalar coupling, which are included to restore CVC. In Ref. , only the CVC-restoring component of the s(u)-channel amplitude are kept (i.e. only the "electric" coupling is included, which is equivalent to setting F n 1 = F p,n 2 = 0 and F p 1 = 0). Under this assumption, the photon does not couple to the neutron and the p(e, e ′ π + )n amplitude reduces to while the n(e, e ′ π − )p amplitude is given by Once the t-dependence of the amplitude is set up by the tree-level Feynman diagrams, the model is reggeized by replacing the pion propagator with a Regge trajectory: (t − m 2 π ) −1 → P π , where α π (t) is determined by the experimentally observed spin-mass relation of the pion and its excitation spectrum. Since the t-channel amplitude is multiplied by the factor P π (t − m 2 π ), CVC requires that also the s(u)-channel diagrams are multiplied by the same factor. In Ref. , this gauge-invariant electric Regge model was applied to meson photoproduction (Q 2 = 0) and, therefore, a point-like γN N coupling F p 1 = 1 was used. In case of pion electroproduction one has Q 2 > 0 and, in principle, However, Kaskulov and Mosel argued in Ref. that since the intermediate proton might be highly off-shell, it is too naive to use the proton Dirac form factor in the γN N vertex. They proposed a transition (off-shell) proton form factor F p 1 (Q 2 , s) that absorbs all effects from the virtual proton which oscillates into higher mass and spin resonances. This introduces extra strength in the hard sector (large Q 2 ) of the scattering cross section, where the effect of nucleon resonances is expected to be important, and improves the agreement with the electroproduction data in the transverse cross section. Later on, this idea was employed by Vrancx and Ryckebusch who proposed an alternative and more intuitive description of F p 1 (Q 2 , s). In contrast to the original form factor introduced by Kaskulov and Mosel, the form factor of Ref. respects the on-shell limit: . It is given by with In the case of the u-channel contribution, Eq. 28 holds under replacement of s by u with Λ γpp ≡ M V = 0.84 GeV such that Λ γpp * (M ) = Λ γpp and the on-shell Dirac form factor is recovered. Λ ∞ is a free parameter of the model which was fitted to experimental data obtaining Λ ∞ = 2.194 GeV . It was shown by Vrancx and Ryckebusch that this form factor provides predictions quantitatively similar to those obtained by Kaskulov and Mosel. In case of on-shell initial and final nucleons and F p,n 2 = 0, the gauge-invariant current containing the pion-exchanged t-channel diagram and the s(u)-channel amplitude with pseudoscalar coupling (Eqs. 26 and 27), provides exactly the same gaugeinvariant current as the ChPT-background model presented in Sec. III, where the EM current is described by the pion-exchanged t-channel diagram, the s(u)-channel amplitude with pseudovector coupling and the CT amplitude (Eq. 24). Since the pion-exchanged t-channel diagram is exactly the same in both approaches, one has (for F p,n 2 = 0): A key ingredient for Eq. 31 to be fulfilled is that, for the p(e, e ′ π + )n reaction, the same proton form factor has to be used in the CT v as in the N P v. Analogously, for the n(e, e ′ π − )p reaction the same proton form factor has to be used in the CT v as in the CN P v 4 . We shall reggeize the ChPT-background terms by exploiting the ideas described above. Thus, by construction, the predictions of the reggeized ChPT-electric background model (ReChi model in what follows) must be similar to those in Ref. , which we use as a benchmark. In what follows, we summarize the ingredients of the ReChi model. The vector-current operator is defined by For pion electroproduction, the non-resonant background contributions are simply O µ given by Eq. 28) of the background contributions described in Eqs. 12, 13 and 17. Also, in the P F term O µ P F , we include the pion transition form factor with pion cut-off parameter Λ γππ = 0.655 GeV. P π (t, s) is the strongly degenerate 4 Note that this is not in contradiction with the fact that the CT v is an isovector operator since F V 1 = F p 1 in the electric model. π(140)/b 1 (1235)-Regge propagator 5 with the Regge trajectory α π (t) = α ′ π (t − m 2 π ) and α ′ π = 0.74 GeV −2 . The trajectory can be extracted from the pion spectrum. For clarity, one can write Γ = −π/{sin Γ }, which contains the pole-generating factor sin . The Γ removes the unphysical contribution of negative-integer spin exchanges. It is interesting to show that the Regge propagator reduces to the pion propagator near the pion pole In Refs. the Regge phases ϕ π (t) = exp for p(e, e ′ π + )n and ϕ π (t) = 1 for n(e, e ′ π − )p were employed. The choice of phase is related to the relative sign of the degenerate Regge contributions. Since α π is the only trajectory that we include in our model, the phase is irrelevant. For that reason, we fix ϕ π (t) = 1 for both reaction channels. In Refs. and , an "antishrinkage" effect which takes into account the decrease of the slope of partonic contributions for increasing values of Q 2 was introduced by modifying the slope of the pion trajectory. This correction improves the agreement with the transverse data dσ T /dt in the region −t < 0.5 GeV 2 (see Ref. ). On the other hand, it was shown in Ref. that this model clearly overshoots the experimental data in the region 1 < −t < 5 GeV 2 . They found that the predictions can be brought closer to data by fitting a t-dependent strong coupling constant g πN N (t). The use of that t-dependent coupling constant, however, notably deteriorates the agreement with data in the low −t region , where the cross sections are much larger. We checked that if the antishrinkage effect is not included, the model presents an acceptable agreement with data in the entire studied region 0 < −t < 4 GeV 2 without the need of the t-dependent coupling g πN N (t) (see Figs. 7-8). Thus, in order to keep the model as basic as possible, we did not include any of these corrections. In Fig. 7, the predictions of the ReChi model (solid lines) for the unseparated dσ U /dt = dσ T /dt + ǫdσ L /dt and the interference cross sections dσ T T /dt and dσ T L /dt are compared with the exclusive p(e, e ′ π + )n and n(e, e ′ π − )p data in the region −t < 0.5 GeV 2 , for two different Q 2 values 6 . We observe a good agreement with the unseparated dσ U /dt data and a reasonable prediction of the interference dσ T T /dt and dσ T L /dt cross sections. Actually, our predictions are similar to those of Refs. , which was expected since they share the main ingredients. In Fig. 8, we show the cross section dσ U /dt for the process p(e, e ′ π + )n in the region 0 < −t < 5 GeV 2 , for different fixed values of Q 2 and W . The ReChi model reproduces well the general behavior of the data in the region −t < 4, where the condition −t/s < 1 is satisfied. The agreement is better in the panels corresponding to lower Q 2 . For increasing Q 2 , it seems that the ReChi model systematically underestimates the data. As in Fig. 7, our results are in good agreement with the ones in Ref. . The dashed-blue lines in Figs. 7 and 8 are the results from the ChPT-background model of Section III. This model is practically t independent for −t > 1 GeV 2 and does not reproduce the behavior of the data. For increasing −t-values, it clearly overestimates the data, in some cases by several orders of magnitude. In summary, the predictions of the ReChi model for charged-pion electroproduction are, by construction, quantitatively similar to those from the model of Ref. , which was used as a benchmark. Actually, the only differences between the two models are: i) we only include the dominant π(140)/b 1 (1235)-Regge trajectory, while in Ref. (as well as, in Ref. ) the vector ρ(770)/a 2 (1320) and axial-vector a 1 (1260) trajectories were also considered, ii) we do not include the "antishrinkage" effect nor the t-dependent strong coupling constant g πN N (t). In Fig. 9, we compare the ReChi model (dashed lines) with the ChPT model (solid lines). We show the double differential cross section dσ/(dΩ e dε e ) for the set of kinematics studied in Sec. II. Note that, for a given W value, an integral over t is performed and, therefore, all t values allowed by kinematics contribute (see Fig. 4). In what follows, we qualitatively analyze the behavior of the ReChi and ChPT models in the possible kinematic scenarios. Low-energy region: W 1.4 GeV. This is the region where the ChPT model is reliable. Our Regge-based model should not be applied here for 1GeV, 4deg 10GeV, 4deg the reasons explained below. At small −t, the Regge propagator tends to the pion propagator (Eq. 35), therefore, the predictions of the reggeized and non-reggeized models tend to be similar. In spite of that, the ReChi model, by construction, lacks some ingredients that are relevant at low W , such as the possibility of coupling to the neutron (F n 1 = 0) and the contribution from the anomalous tensor coupling (F p,n 2 = 0). For that reason, in this regime the ChPT model is preferable to the ReChi model. In Fig. 9, the results of panels (a), (b), (c) and (d) in the region W < 1.4 GeV fit in this situation. Note that only small −t values contribute (see Fig. 4). At large −t, one has −t/s > 1 and we are far from the Regge limit. The ReChi model is not valid in this situation. This is the case in the low-W region of panel (e) and (f), where the ReChi model provides non-sense cross sections. High-energy region: W 2 GeV. Regge-based models are a good alternative in this region, where low-energy models fail. At small −t, we enter in the pure Regge limit (−t/s << 1). This is the natural domain of Regge-based models. For increasing −t values, however, one may enter the region −t/s 1. The predictions of the ReChi model are less reliable than in the previous situation, but still preferable to the ChPT model. One expects that the ReChi model slightly underestimates the t-integrated cross sections due to the lack of the u-channel baryon-exchange contribution at backward θ * π scattering. In panels (e) and (f) of Fig. 9, we show the predictions of the ReChi model when the kinematic condition −t/s < 1 is applied (dashed-dotted lines) 7 . As expected, the unphysically high responses observed in the low-W region of panels (e) and (f) disappear. Also, the predictions with and without the kinematic cut overlap from a certain W value, which could be expected since low-t contributions strongly dominate the cross sections. Thus, we will use the condition −t/s < 1 as the limit of applicability for the ReChi model. We want to stress that, provided the condition −t/s 1 is fulfilled, the ReChi model works reasonably well even at relatively low W (W ≈ 2 GeV), while the ChPT model clamorously fails (Figs. 7 and 8). Transition region: 1.4 W 2 GeV. The pathologies of the low-energy models become manifest in this region. Also, this is not the natural domain of Regge-based models. In a phenomenological sense, one may consider that, in this transition region, more realistic results could arise from a compromise between the low-energy and the Regge-based predictions. B. Neutrinoproduction of pions The ReChi model presented above for EM interaction is extended here to CC and WNC neutrino-induced pion production. In this case, the non-resonant current operator contains a vector (V) and an axial (A) contribution: Reggeizing the vector current Based on CVC and by isospin rotation, the vector current for neutrinoproduction can be determined from the electroproduction current. In the case of the WNC interaction, the nucleon form factors are given in terms of the EM ones by Eq. A30. Hence, under the assumption (electric model) F n 1 = F p,n 2 = 0, one obtains: This means that, contrary to the situation in charged-pion electroproduction, the Z boson also couples to neutrons and, therefore, both N P v and CN P v contribute to the reactions p(ν, ν ′ π + )n and n(ν, ν ′ π − )p. Taking that into account, it is easy to define the form factor that enters in the CT v amplitude. For p(ν, ν ′ π + )n one has while for n(ν, ν ′ π − )p one obtains In the case of the CC interaction, we need the isovector form factors for the CT v, N P v and CN P v amplitudes. In the electric model these are: Additionally, for CC neutral-pion production, both N P v and CN P v amplitudes contribute (see table I). In this case, Eq. 31 implies that the form factor that enters in the CT v amplitude has to be: Finally, the ReChi vector-current operator for neutrino-induced SPP takes the form of Eq. 32. Reggeizing the axial current The presence of the P F diagram in the vector current enabled us to apply the reggeizing procedure by identifying the pion exchange as the main Regge trajectory. However, what is the analogous t-channel meson-exchange diagram in the axial current? In the ππN N and QπN N vertices which are present in the P P and CT a diagrams, the form factor F ρ (t) was introduced to, phenomenologically, account for the ρ-dominance of the ππN N vertex (see Sec. III). Actually, the CT a and the P P diagrams with this form factor can be interpreted as effective ρ-exchange diagrams. This is illustrated in Fig. 10 8 . Thus, we identify the ρ exchange as the main Regge trajectory in the axial current, this will allow us to reggeize the axial current by using the ρ-exchanged Regge propagator. In the left side we present the CT a and P P diagrams used in the low-energy model of Sec. III. In the high-energy model we reinterpret these diagrams as ρ-exchange diagrams (right side): CT ρ and P P ρ. In this figure, Q represents the axial-vector part of the weak (W ± or Z) boson. The current operator for the CT ρ in Fig. 10 is For the coupling constants, we have assumed g ρN N and g Aρπ being the coupling constants of the strong and weak vertices, respectively. We also introduced a transition form factor in the weak vertex, F Aρπ (Q 2 ), in analogy with what was done in the P F diagram (see Eq. 33). Within a mesondominance framework, the axial-vector part of the W ± (or Z) boson transforms into an a 1 (1260) axial-vector meson . This suggests the form factor with Λ ρ = m a1(1260) . The P P contribution to the cross section is generally small, because its amplitude is proportional to Q µ : for WNC interactions it vanishes when it is contracted with the leptonic tensor, while for CC interactions one gets a contribution proportional to the squared mass of the charged lepton. Still, the P P amplitude is needed to preserve PCAC, and we keep it in our calculations 9 . Using PCAC, the P P ρ current operator results We now follow the same steps as in the case of charged-pion electroproduction and introduce an off-shell axial form factor in the N P a and CN P a amplitudes. By analogy with the off-shell proton form factor F p 1 of Eq. 28, we propose and In order to recover the on-shell axial form factor for Λ Anp * (M ), we use Λ Apn ≡ M A = 1.05 GeV. Λ A ∞ is a free parameter of the model. While in the vector current, CVC tells us that the N P v and CN P v amplitudes have to be multiplied by the same Regge propagator as the 9 It is shown in Ref. that the contribution from the P P term is important for CC pion production in the low Q 2 region since it may partially explain the deficit of forward-going muons observed at Q 2 < 0.1 GeV 2 in the K2K experiment . P F diagram, in the axial current there is no such constraint: the N P a and CN P a fulfill PCAC by themselves as well as the combination of CT ρ and P P ρ. Thus, just by analogy with the procedure followed in the vector-current case, we multiply the N P a and CN P a with the same Regge propagator used in the meson-exchange diagrams (CT ρ and P P ρ). Other options may be explored. In summary, the axial-current operator in the ReChi model reads where O µ ChP T,A is given in Eq. 36 and P ρ (t, s) is the strongly degenerate ρ(770)/a 2 (1320)-Regge propagator The ρ trajectory is parameterized by α ρ (t) = 0.53 + α ′ ρ t with α ′ ρ = 0.85 GeV −2 . Since we are considering a strongly degenerate trajectory, we should choose between a rotating or a constant phase, ϕ ρ (t). In case of inclusive cross sections (in which the information about the hadronic system is integrated), it can be shown from general symmetry arguments that the vector/axial (VA) interference contribution to the hadronic tensor is a purely antisymmetric tensor . As a consequence, the VA contribution to the cross section arises from its contraction with the antisymmetric leptonic tensor, a µν (Eq. 5). On the other hand, it is easy to show that, at high energies and very forward lepton scattering angles, a µν vanishes. Therefore, one expects the VA contribution to be considerably smaller than the axial/axial (AA) and vector/vector (VV) ones. This, together with the fact that α ρ is the only trajectory included in the axial current of our model, allows us to conclude that a constant or rotating phase will produce basically the same squared amplitudes. We fix ϕ ρ (t) = 1. The only difference between Eqs. 16 and 15 and Eqs. 41 and 44 is the contribution in the latter of the term proportional to the anomalous tensor coupling constant κ ρ , and the transition form factors F Aρπ (Q 2 ). Therefore, in this work we will assume κ ρ = 0 10 , such that the background amplitudes of the original low-energy model are recovered in the limits t → m 2 ρ and Q 2 → 0. Other approaches may be investigated. Results In Fig. 11, we compare the ReChi model with total cross section data for the CC reactions νp → µ + π − p and νp → µ − π + p in the energy range between 10 and 90 GeV. The data and the predictions include the kinematic condition W > 2 GeV, so one expects that only residual effects from the resonance region affect the data. Thus, this is an excellent opportunity to test the ReChi model. Additionally, we have applied the condition −t/s < 1 in our model (see Sec. IV A). For the free parameter in the transition axial form factor Λ A ∞ , we have used, as reference, the same value as in the analogous parameter of the vector current, i.e. Λ A ∞ = Λ ∞ = 2.194 GeV. In this case, the ReChi model underestimates the data by more than a factor two . In panel (a), we show the VV, AA and VA contributions separately. The VV and AA contributions are similar while, as expected, the VA one is significantly smaller. In panel (b), we show the contributions to the cross section from the different diagrams of the model: the N P v (CN P v), the CT v and the P F amplitudes in the VV sector; the CT ρ + P P ρ and the N P a (CN P a) amplitudes in the AA sector. It is interesting that, separately, the N P v (CN P v) and the CT v clearly overshoot the data, while the combination CT v + N P v (CN P v) lays far below data. This is a consequence of the destructive interference between the different contributions. Note that the interferences between all the diagrams are determined by the (lowenergy) ChPT model. In Fig. 12, we present the same results as in Fig. 11 when the parameter Λ A ∞ = 7.20 ± 2.09 1.32 GeV (50) is employed. This is the results of a χ 2 fit to the 8 experimental data points. The errors in Λ A ∞ define the 1σ region (χ 2 < χ 2 min + 1). In this case, our result is quantitatively similar to the one in Ref. . By increasing Λ A ∞ one obtains a much larger AA contribution , which is a consequence of the augment of the N P a (CN P a) term . This increment of the N P a (CN P a) term breaks the equilibrium that exist between the CT ρ + P P ρ and the N P a (CN P a), which translates into a net increment of the cross section. The large value Λ A ∞ = 7.20 GeV which is needed to reproduce the data, may be a consequence of the lack of other missing ingredients in the model. For instance, the contributions of other mesonexchange trajectories in both the axial and the vector currents may increase the magnitude of the cross section. Note that, as shown in Fig. 8, the ReChi model systematically underestimates the charged-pion electroproduction data for Q 2 2.5 GeV 2 . Also, a proper modeling of the backward θ * π scattering cross section is missing. Another possibility is, simply, a wrong interpretention of the experimental data, which may contain contributions beyond the purely one-pion production process. In panel (a) of Fig. 12, we included the predictions of the NuWro Monte Carlo event generator . In NuWro, in the kinematical regime W > 2 GeV, the inclusive cross sections are evaluated using the DIS formalism by Bodek-Yang and the hadronic final states are obtained using PYTHIA 6 hadronization routines (see Ref. for details). The SPP channel is defined by selecting those events with only one pion and one nucleon in the final state. The NuWro predictions for the channelνp → µ + π − p are approximately a factor 2.3 larger than those for the channel νp → µ − π + p, contrary to the predicitons of the ReChi model that produces almost identical results for the two channels. As mentioned, the NuWro predictions are based on the DIS formalism, which uses quarks as degrees of freedom. Thus, a possible explanation for this factor ∼2 arises from the fact that a proton consists of two up quarks and one down quark, which couple to the antineutrino and the neutrino, respectively: The ratio of antineutrino to neutrino data in Fig. 12 is close to one, which may be interpreted as a sign that DIS is not the dominant reaction mechanism. A different problem is that the NuWro predictions overestimate the data, except for the highest energy data point for the neutrino reaction. We conclude that further investigations are needed, especially, when more recent and differential cross section data become available. In Fig. 13, we further explore the effect of the parameter Λ A ∞ on the cross sections. To this end, we show the differential cross section dσ/(dW dQ 2 dt) as a function of t for some fixed values of Q 2 and W . The predictions of the ReChi model were obtained with the values Λ A ∞ = 7.2 and 2.2 GeV. The effect of the parameter Λ A ∞ is important for increasing Q 2 , being almost independent of t. The predictions of the ChPT model are also shown. As for electroproduction (Fig. 8), the ChPT results are, in general, several orders of magnitude larger than those of the ReChi model. To end this section, the ReChi model is compared with the ChPT-background in Fig. 14 for WNC neutrino-induced charged-pion production and in Fig. 15 for CC neutrino-induced chargedand neutral-pion production. The value Λ A ∞ = 7.20 GeV is used. The discussion of the results is similar to that of Fig. 9. Here, we only comment on the main differences. At backward scattering angles and at low W , the ReChi cross sections for neutrinos present a different behavior compared to the ChPT ones. This is due to the effect of the large parameter Λ A ∞ in the axial transition form factor G A whose contribution is especially important at high Q 2 (backward lepton angles). Also, neutrino cross sections, contrary to electron ones, go to zero when ε f → 0 (or, equivalently, for increasing W values). This is a purely kinematic effect: neutrino cross sections are proportional to σ ∼ ε 2 f /M 4 W,Z while for electron cross sections one has σ ∼ ε 2 f /Q 4 . V. FROM LOW TO HIGH INVARIANT MASSES: HYBRID MODEL In this section, we combine the low-energy model presented in Sec. III and the high-energy model presented in Sec. IV into a hybrid model, that can be applied over the entire W region of interest for present and future accelerator-based neutrino experiments. Similar approaches have previously been proposed in the literature in different contexts . In particular, the so-called Regge-plus-resonance (RPR) model developed by the Ghent group was used with remarkable success in photoproduction of strange hadrons . However, due to the important differences between the RPR model and the present approach, we refer to the latter as Hybrid model. Among these differences, we point out the fact that we do not apply the Regge-based model in the low-W region. The first step towards the Hybrid model is to regularize the high-energy behavior of the resonance amplitudes. Then, we introduce a phenomenological transition function to move from the low-energy model of Sec. III to the ReChi model of Sec. IV. A. Resonance cut-off form factors In order to extend the low-energy model to higher invariant masses (W > 1.4 GeV) it is mandatory to regularize the unphysical behavior of the resonance tree-level amplitudes in the kinematic regions far from the peak of the resonances, s ≈ M 2 R . We do that by introducing phenomenological cut-off form factors. Since we are including s-and u-channel amplitudes for all resonances, the form factors should also depend on s and u variables. We choose the following cut-off form factor (53) which multiplies both the s-and u-channel amplitudes . F (s) is given by a combination of a Gaussian and a dipole form factor where λ R is the cut-off parameter. The same expression holds for , this explains the need of a harder form factor for spin-3/2 than for spin-1/2 resonances. The effect of these form factors in the resonances P 33 and D 13 (P 11 and S 11 ) is illustrated in Fig. 16 (Fig. 17). We have represented the double differential cross sections dσ/(dΩ e dε e ) for some of the kinematic situations explained in Fig. 3 and for the reaction p(e, e ′ π + )n (the same discussion applies to the other reaction channels). It is clear from the results in Figs. 16 and 17 that the predictions without the cut-off form factors present an unphysical behavior for the W region beyond the resonance peaks. The pathological behavior is more pronounced at backward scattering angles (higher Q 2 ), when the cross sections are much smaller, than at forward scattering angles. The incorporation of the cut-off form factors eliminates these tails by constraining the resonance responses to a symmetric area defined by the Gaussian-dipole shape of the form factors. B. Hybrid model The Hybrid model is constructed as follows. We use the hadronic current operator as described in Sec. III, i.e., the ChPT background and the s-and u-channel resonance diagrams are added coherently. The high-energy behavior of the resonances is regularized by the resonance cut-off form factors described in Sec. Fig. 9 but for CC neutrino-induced charged-and neutral-pion production. The results of the channel n(ν − µ , µ − π + )n (not shown here) are similar to the p(ν − µ , µ − π + )p ones. is given by the transition function 11 where φ(W ) is a W -dependent function given by W 0 and L are two parameters setting the center and the width of the transition, respectively. For 11 This transition function was previously used in Ref. to build the SuSAv2 model. In summary, for W < 1.4 GeV the Hybrid model is basically identical to the low energy model of Sec. III: ChPT-background terms plus resonances. For W > 2 GeV, the contributions from the resonances considered in this work are very small (see Figs. 16 and 17), therefore, it is safe to say that for W > 2 GeV our model contains only Regge-background contributions. In this way, only in the transition region 1.4 < W < 2 GeV, the nucleon resonances coexist with the background contributions from the ReChi model. In Fig. 18, we compare our predictions with inclusive electron-proton scattering data for several values of the electron scattering angle and the incoming energy. In the inclusive process, only the scattered electron is detected. Therefore, since we are modeling the one-pion production channel only, we expect to underestimate the inclusive data, which include reaction channels beyond onepion production. Hence, our goal is not to fit the inclusive data but to analyze the different ingredients of the model, the experimental data being an upper bound. For this purpose, we have represented the results from three approaches: • LEM: Low-energy model presented in Sec. III. • LEM(wff): The same as LEM but with the resonance cut-off form factors of Sec. V A. • Hybrid model: The same as LEM(wff) but using the current operator O of Eq. 55 instead of O ChP T . We used the value Λ A ∞ = 7.20 GeV in our calculations. As expected, the three models provide basically the same results for low invariant masses W < 1.3 GeV. Beyond W > 1.5 GeV, LEM overshoots the data and makes the need of the cut-off form factors in the resonances evident. LEM(wff) and Hybrid model are exactly the same until W ≈ 1.6 GeV. For larger W , we observe huge differences between them. We want to stress that, in the high-W region, the Hybrid model provides the right magnitude of the one-pion production cross section. It is therefore evident that the LEM(wff) should not be used beyond W = 2 GeV. This is particularly obvious from the results in panel (a) and (b) where the LEM(wff) even overpredicts the inclusive data. Finally, it should be mentioned that in the results of the Hybrid model, the contribution from the p(e, e ′ π 0 )p channel is absent in (and only in) the reggeized background. In spite of that, since the magnitude of the neutral-pion electroproduction cross section is, in general, similar or smaller than the charged-pion electroproduction one , the present discussion is not affected. In Fig. 19, we show the SPP total cross section for the three possible reaction channels in the neutrino-induced CC interaction. The three models described above are compared with the recent reanalysis of the BNL and ANL data . We have not considered deuteron effects in this work. In the left panels, a cut in the invariant mass W < 1.4 GeV is applied and, as expected, the LEM(wff) and the Hybrid model coincide. The effect of the cut-off form factor in the Delta resonance, which is the only resonance playing a significant role at W < 1.4 GeV, produces a reduction of the cross sections of approximately 5 − 15%, depending on the neutrino energy and the reaction channel. In general, 19. (Color online) (Left panels) Total cross section as a function of the neutrino energy for exclusive CC neutrino-induced one-pion production. The model predictions are compared with data from Refs. . A cut in the invariant mass W < 1.4 GeV is applied to both model and data. (Right panels) As in left panels but without the kinematic cut. the three models reproduce the p(ν µ , µ − π + )p and n(ν µ , µ − π 0 )p data well, but they underestimate the n(ν µ , µ − π + )n data. This is a well-known problem of the low-energy model , which may be related to the role of the cross-Delta-pole diagram and deuteron effects . There is no cut in the right panels in Fig. 19, so higher invariant masses contribute to the cross sections. We will focus on the comparison between models and data in the energy region ε i > 2 GeV, where the predictions of the three models are clearly different. In this region, the LEM overestimates the data while the Hybrid model underestimates them. LEM(wff) lays in between the others and seems to be the one in better agreement with data. However, LEM(wff) cannot be consider realistic at these energies since it contains unphysical strength from the W > 2 GeV region (see, for instance, panel (b) of Fig. 19). Therefore, we interpret this apparent agreement as a mere coincidence. Finally, in Fig. 20 we compare the WNC n(ν, νπ − )p total cross section data with our predictions. In this case, only low energy data (ε i < 1.5 GeV) are available and Hybrid model is the one with the better agreement with data. In Figs. 19 and 20, we have included the predictions of NuWro (see previous discussion in Sect. IV). In NuWro, the reaction mechanisms in the region W < 1.6 GeV are the Delta resonance pole and an effective background extrapolated from the DIS contribution. For W > 1.6 GeV the predictions are based on the DIS formalism and the PYTHIA 6 hadronization routines . A smooth transition between the resonance and DIS regions is performed in the region 1.4 < W < 1.6 GeV (see Ref. for details). The parameters of the axial form factor of the Delta resonance, C A 5 (0) = 1.19 and M A = 0.94 GeV, were fitted to reproduce the original BNL and ANL data . This can partially explain why the NuWro predictions are systematically larger than the Hybrid model. Finally, in Fig. 21 we compare the predictions of NuWro and the Hybrid model as a function of W for three values of Q 2 . The predictions of the LEM and the LEM(wff) are also shown as reference. This comparison helps to further understand the differences between the two models. First we analyze the resonance region. In NuWro, only the Delta is present while, in the Hybrid model, the peak from higher mass resonances appears around W ≈ 1.5 GeV. Also, the width of the Delta is considerably larger in NuWro than in the other models. In the high energy region (W > 2 GeV), both NuWro and the Hybrid model predict a rapidly decreasing behavior for increasing W values. Still, the predictions show a different Q 2 behavior. The bump in the cross section, appearing at W ≈ 1.8 GeV for the Hybrid model and at W ≈ 1.6 GeV in NuWro, are caused by the modeling of the transition region. The incorporation of higher mass resonances may push the reliability of the low-energy model further in W , what would help to solve this problem. Further studies in the modeling of both the resonance and the high energy regions are needed. VI. CONCLUSIONS AND OUTLOOK We have developed a model for electroweak SPP off the nucleon that is applicable for invariant masses from the pion-production threshold to the high-W limit. Within our approach, the reaction is modeled at the amplitude level, this allows one to make predictions for fully exclusive reactions, with information on the angular distributions of all outgoing particles. Our starting point is the electroweak SPP low-energy model summarized in Sec. III. It includes contributions from nucleon resonances and background terms derived from the ChPT Lagrangian of the πN system (Appendix A). We have shown that this model works well for small invariant masses, W 1.4 GeV, but fails beyond. In Sec. IV, this low energy-model was extended to the high-energy region using Regge phenomenology. By the "standard procedure" of replacing the t-channel Feynman propagators with the corresponding Regge trajectories, we reggeized the ChPT-background contributions. The result is a high-energy model for electroweak SPP (ReChi model) whose validity, by construction, is restricted to the region W > 2 GeV and forward θ * π scattering angles. Since the forward θ * π scattering region strongly dominates the one-pion production cross section, one expects that the predictions of the ReChi model underestimate only slightly the θ * π -integrated cross sections. In a scheme of strong degeneracy, we reggeized the EM current considering only the π(140)/b 1 (1235)-Regge trajectory. To obey CVC, the CT v and the s(u)-channel Born terms were included, with phenomenological transition form factors as in Refs. . We found an acceptable agreement between the ReChi model and charged-pion electroproduction data in the region 0 < −t < 4 GeV 2 , W ≈ 2 GeV and Q 2 < 4 GeV 2 . In spite of the dominance of the degenerate π(140)/b 1 (1235) Regge trajectory in the vector current, more sophisticated models containing additional trajectories such as ρ(770)/a 2 (1320) and a 1 (1260) , as well as other ingredients beyond the tree-level amplitudes , may be preferable. However, the main goal of this work is to make predictions in the weak sector. For that, one also needs to model the axial current, which is absent in the above mentioned EM models. The vector current for neutrino interactions was obtained from the EM one by isospin rotation. The real challenge is the reggeization of the axial current, which has no analogous counterpart in electron scattering, and experimental information is scarce. For that, we have reinterpreted the P P and the axial part of the CT as effective ρ-exchange t-channel diagrams. This allowed us to reggeize the axial current by considering the ρ exchange as the main Regge trajectory. We have compared the ReChi model with total cross section data for the CC reactionsνp → µ + π − p and νp → µ − π + p in the energy range between 10 and 90 GeV. The data does not include contributions from the W < 2 GeV region, so only residual effects from the resonance region are expected. We showed that, to reproduce the magnitude of the experimental data, we needed a large value of the axial transition form factor parameter, Λ A ∞ , which is difficult to interpret. We believe that other ingredients not considered in the ReChi model may still play an important role in the one-pion production cross section at high invariant masses. In particular, the contribution of other meson trajectories and the modeling of the backward θ * π scattering region need to be further investigated. Also, we may be missing strength from the high-Q 2 sector of the cross section. At high Q 2 and high W , one enters in the DIS region, where the direct interaction with partons makes the use of hadrons as effective degrees of freedom rather questionable. We have included predictions of the NuWro Monte Carlo event generator. The NuWro predictions for the antineutrino reaction are a factor ∼ 2 larger than those of the neutrino counterpart. This result is consistent with the DIS treatment of the problem that is implemented in NuWro, but it does not seem to be supported by data. More experimental data would certainly help to clarify which are the main reaction mechanisms playing a role in SPP in the region W > 2 GeV. Finally, in Sec. V we have proposed a phenomenological way of combining the low-and highenergy models into a Hybrid model that can be applied in the entire region of interest for acceleratorbased neutrino oscillation experiments. For that, it was also necessary to regularize the W > M R behavior of the s and u channels of the resonances, this was done by using phenomenological form factors (Sec. V A). The Hybrid model was compared with the neutrino-induced SPP total cross section data from the BNL and ANL experiments, as well as with the NuWro predictions. We showed that the low-energy model and the Hybrid model agree well up to neutrino energies around ∼ 1 GeV. Beyond that, the contributions from the region W > 1.4 GeV start to be important, and the lowenergy model fails. The resonance cutoff form fac-tors and the reggeization of the ChPT background allowed us to provide reliable predictions in this region. NuWro predicts systematically larger cross sections than the Hybrid model. This is due to the fact that the Delta and the high-W contributions in NuWro are larger than in the Hybrid model. In order to perform predictions of neutrino cross sections, in particular, in the case of neutrinonucleus interaction, one needs computationally efficient models. The low-energy model employed in this work has been used by several collaborations . Our proposal for extending this model to higher invariant masses is technically and formally straightforward, and does not involve any additional cost from a computational point of view. Work is in progress to apply this model to the case of neutrino-induced one-pion production off nuclei. A preliminary work in which the nucleons are described within a relativistic mean-field model was presented in Ref. . Only the lowenergy model was considered in that reference. We end this paper by providing some final remarks about possible future improvements. The ReChi model does not describe neutral-pion production induced by neutral-current (EM and WNC) interactions because the meson-exchange diagrams needed to reggeize the ChPT model do not contribute to the amplitude: the isospin factors of the P F , CT and P P diagrams are zero (Table II). This is also explained by the fact that the vertices ρ 0 → π 0 π 0 and a 0 1 (1260) → ρ 0 π 0 are forbidden by isospin symmetry. In Refs. , the neutral-pion electroproduction data are reasonably well described within a Regge framework. However, ingredients beyond the ChPT diagrams considered in this work are needed and, obviously, the description of the axial current is missing. The recent publication by the MINERvA collaboration of "evidence for WNC-diffractive π 0 production from hydrogen" points out the urgency of theoretical predictions for this process. Other higher mass resonances, beyond the D 13 (1520) and S 11 (1535) considered in this work, still play an important role and should be included in order to reproduce the broad peak in the cross section observed around W ≈ 1.7 GeV (Fig. 18). The ReChi and Hybrid model presented here are flexible and there is still room for improvements. A proper fit and fine tunning of the parameters and form factors of the model as well as more investigations regarding the modeling of the axial current in the high-energy model are requiered, in particular, if more neutrino-induced SPP data is available. In this sense, this work should be understood as a first approach to the problem, further analyses and improvements are desired and expected in forthcoming publications. Appendix A: Pion-nucleon system in ChPT: Background contributions The ChPT Lagrangian for the pion-nucleon system provides all the necessary vertices for computing the background Feynman diagrams considered in this model. In this appendix we present a detailed derivation of those vertices. We also show how to identify the vector and axial currents of the electroweak process. A different derivation of the vector and axial currents of the pion-nucleon system based on the transformation properties of the fields can be found in Ref. . We closely follow the procedure and convention of Ref. . Some of the expressions presented here can be found in Refs. , we refer the reader to those references for further details. ChPT applied to the pion-nucleon system with coupling to external fields provides the following effective Lagrangian: where The covariant derivative D µ is defined as and The matrix u is the square root of the matrix U containing the pion fields ( φ): The fields r µ , l µ and v (s) µ provide the coupling to the external boson fields: where A µ , W +/− µ and Z µ are the fields of the photon, W +/− boson and Z boson, respectively. An expansion in terms of the pion decay constant f π = 93 MeV, where only the interaction terms of the Lagrangian which contribute to one-pion production at first order in f π are kept, results in the following effective Lagrangian: Each term of the effective Lagrangian in Eq. A11 provides a different vertex function. According to this, the possible Feynman diagrams contributing to the one-pion production amplitude (at first order in 1/f π ) are shown in Fig. 5. In what follows, we present the explicit expressions for each term of the Lagrangian in Eq. A11. Using these expressions together with the appropriate Feynman rules, it is straightforward to obtain the background contributions to the hadronic current of Eq. 7. We define the physical fields of the pion The convention is such that φ 0 creates or annihilates a π 0 , and φ + (φ − ) annihilates a π + (π − ) or creates a π − (π + ). The same convention is used for the boson fields. a. Pion-nucleon Lagrangians. The terms containing pion and nucleon fields only are: b. Couplings to external fields: photon. The γN N vertex reads: withΓ µ p,n ≡ F p,n In Eq. A14 we have replaced the point-like photon-proton-proton coupling by the vertex function which takes into account the inner structure of the nucleon. F p,n 1,2 are the proton and neutron electromagnetic form factors for which we use the Galster parametrization . The γππ and γπN N vertices are: We can rewrite the previous expressions of the Lagrangians as L = J µ EM A µ , where the photon couples to a current J µ . This current can be identified as the EM current of the pion-nucleon system: It is easy to show that J µ EM transforms as a vector under parity transformation. c. Couplings to external fields: W boson. The W N N vertex reads: As in Eq. A14, we have replaced the point-like coupling by the vertex function which takes into account the inner structure of the nucleon. The isovector vector form factor is F V 1,2 = F p 1,2 − F n 1,2 . G A is the isovector axial form factor given by the usual dipole form G A (Q 2 ) = g A /(1 − Q 2 /M 2 A ) 2 with g A = 1.26 and M A = 1.05 GeV. The W π, W ππ vertices are: The W πN N vertex has a vector and an axial contributions: The current which couples to the W boson and that can be identified as the weak charged-current of the pion-nucleon system (L = J µ CC W ± µ ) has a vector part and an axial part: which, under parity transformations, transforms as a vector and an axial vector, respectively. d. Couplings to external fields: Z boson. The ZN N vertex reads: Q p,n W represent the weak vector charge of the proton and neutron seen by the neutrino. Neglecting higher order radiative corrections their values are given by Q p W = (1 − 4 sin 2 θ W ) and Q n W = −1. To take into account the inner structure of the nucleon we have introduced The WNC vector form factors of the proton and neutron can be related to the EM ones by with F s 1,2 the strange form factor of the nucleon. The WNC axial form factor can be related to the isovector axial form factor G A (Q 2 ) that enter in the CC interaction by with for + (−) for proton (neutron) and G s A the axial strange nucleon form factor. The strange form factors of the nucleon have recently been studied using the parity-violating electron scattering asymmetry and the proton-to-neutron ratio in WNC neutrino-nucleus quasielastic interaction . A general conclusion from these works is that we are still far from a precise determination of the strange form factor of the nucleon. Therefore, given the large uncertainties in our model from other sources, for simplicity, in this work we fix all strangeness contributions to zero. The Zπ, Zππ vertices are: The ZπN N vertex has a vector and an axial contributions: The current which couples to the Z boson and that can be identified as the weak neutral-current of the pion-nucleon system (L = J µ W N C Z µ ) has a vector part: and an axial part: spin-3/2 and spin-1/2 resonances. Spin-3/2 resonances The electroweak vertex QN R 3 (Q stands for the boson, N for the nucleon and R 3 for the spin-3/2 resonance) is given by the parametrization with γ 5 = 1 1 if the parity of the resonance is even, and γ 5 = γ 5 if odd. The vector part is given by and the axial part is The form factors of the resonance, C V,A i (Q 2 ), are described below. ∆(1232) form factors. As mentioned in Sec. III, we have included the relative Olsson phases between ChPT and the ∆P contribution according to Ref. . We do that by multiplying the vector form factors by the phase Ψ V and the axial ones by Ψ A . In particular, we use the parameterization corresponding to 'FIT A'. To be consistent, we have used the same vector and axial form factors as in that fit (which in turn are from Ref. ), they are summarized below. The vector form factors are C V 6 = 0 and , GeV. The axial form factors are C A 3 = 0 and with C A 5 (0) = 1.12 and M A,∆ = 953.7 MeV. The general structure of the hadronic electroweak currents at quark level, along with isospin symmetry allow to relate the WNC, EM and CC form factors with each other (see, for instance, Section 3 in Ref. for details). In this case, since the excitation of the Delta resonance is a purely isovector transition, the form factors that parameterize the nucleon-Delta transition vertex are the same for CC and EM interactions. Note that in the case of EM interactions only vector form factors should be considered. On the other hand, the WNC form factors (denoted here as C V,A i ) are given by D 13 (1520) form factors. We describe the proton and neutron EM form factors by the parameterization given in Refs. . For the proton one has = 0. We changed a global relative sign compared to Ref. because of a different convention in the definition of the isovector form factors (see below). The excitation of the D 13 resonance contains isovector and isoscalar contributions. Isospin symmetry allows one to relate proton and neutron form factors to isovector and isoscalar ones. One has where the labels iv and is stand for isovector and isoscalar. (In Ref. the convention C V,iv i = −(C V,p i − C V,n i ) was used.) C V,iv i are the form factors that enter in the CC interaction. For the isovector axial form factors that enter in the CC interaction we use C A,iv , C A,iv with G A D = (1−Q 2 /M 2 A ) −2 and M A = 1 GeV. This is also used in Refs. . The WNC form factors are given by where the + (−) in the last equation stands for proton (neutron). The strange contributions C V (A),s i are unknown and, given the large uncertainties in the non-strange form factors, we fix them to zero. The propagator of a spin-3/2 resonance S R3,αβ is described by which depends on the resonance-decay width Γ width (W ). Finally, the R 3 πN vertex Γ α R3πN reads where the values of f πN R3 are given in Table III. Decay width. We define the resonance-decay width as follows: where W is the π − N invariant mass and br is the branching ratio for the pion-nucleon decay channel of the resonance. Γ exp width is the experimental value of the resonance-decay width (see Table III). Γ πN width (W ) is the pion-nucleon resonance-decay width computed in the rest frame of the resonance Γ πN width (W ) = I iso 12π The positive (negative) sign stands for even (odd) parity and I iso = 1 (3) for isospin 3/2 (1/2). k * π is the pion center of mass momentum given by Eq. 11 and E N = (k * π ) 2 + M 2 . The values of the strong coupling constants f πN R3 are obtained from Eq. B15 by imposing Γ width (W = M R ) = brΓ exp width . We use this value of f πN R3 both in the decay width (denominator of the current) and in the decay vertex (numerator of the current). Therefore, in the case br < 1 our model will underestimate inclusive (no pion detected) cross-section data, since in the numerator we are only considering pion production through the process R 3 → πN , while in the denominator we are considering the full resonance-decay width, which may contain other decay channels such as R 3 → π∆, R 3 → ηN , etc. Spin-1/2 resonances For spin-1/2 resonances the structure of the current and vertices is the same as that of the N P and CN P contributions. The QR 1 N vertex is given by the sum of vector and axial contributions: The vector and axial vector parts are given by Γ µ QR1N,V = with µ = M R + M . The form factors are given below. P 11 (1440) form factors. For the vector form factor of the proton and neutron we use the parameterization of Lalakulich et al. . For the proton F p 2 = −0.76 G V D {1 − 2.8 ln } . Given the large uncertainties, in Ref. they considered that the isoscalar contribution is negligible compare to the isovector one. Therefore, the neutron form factors are F n 1,2 = −F p 1,2 . Due to the different convention for defining the isovector vector contribution, we have defined the proton form factors with a relative sign respect to those in Ref. . Also, we have corrected for a relative wrong sign between F p 1 and F p 2 as it was pointed out in Ref. . The isovector vector form factors that enter in the CC interaction are defined as usual F iv 1,2 = F p 1,2 − F n 1,2 . The isovector axial form factor is We changed the sign of this axial form factor respect to Ref. so that the relative sign between vector and axial contributions match with the convention used in Refs. . The pseudoscalar form factor is given by G P = µM m 2 π −Q 2 G A . As in the case of the D 13 resonance, the WNC form factors are given by where the + (−) in the last equation stands for proton (neutron). We fix the strange contributions to zero. I S P MR πN -br Γ exp width fπNR P33 3/2 3/2 + 1232 100% 120 2.18 D13 1/2 3/2 − 1515 60% 115 1.62 P11 1/2 1/2 + 1430 65% 350 0.391 S11 1/2 1/2 − 1535 45% 150 0.16 TABLE III. Properties of the resonances taken from Ref. . Masses and width are in MeV. I, S and P represent isospin, spin and parity, respectively. The coupling constants fπNR are computed using Eqs. B15 and B25 (see text for details). S 11 (1535) form factors. We use the form factors of Ref. . For the proton Given the large uncertainties, in Ref. the isoscalar contribution was considered to be negligible in comparison with the isovector one. Therefore, the neutron form factors are F n 1,2 = −F p 1,2 . The isovector vector form factors are F iv 1,2 = (F p 1,2 − F n 1,2 ) = 2F p 1,2 . Due to a different convention in the definition of the isovector vector contribution, we have defined the proton form factors with a relative sign respect to those in Ref. . The isovector axial form factors are : with M A = 1.05 GeV. The WNC form factors are given by Eqs. B20 and B20. The propagator of a spin-1/2 resonance S R1 is . (B23) The resonance-decay width Γ width (W ) is described below. Finally, the R 1 πN vertex Γ R1πN is where the values of f πN R1 are given in Table III. Decay width. We use the same procedure as for spin-3/2 resonances. In this case, the resonance-decay width computed in the rest frame of the resonance reads : The upper (lower) sign corresponds to even (odd) parity.
# encoding: utf-8 import os import sys import time import random import argparse import logging from collections import OrderedDict, defaultdict import torch import torch.utils.model_zoo as model_zoo import torch.distributed as dist class LogFormatter(logging.Formatter): log_fout = None date_full = '[%(asctime)s %(lineno)d@%(filename)s:%(name)s] ' date = '%(asctime)s ' msg = '%(message)s' def format(self, record): if record.levelno == logging.DEBUG: mcl, mtxt = self._color_dbg, 'DBG' elif record.levelno == logging.WARNING: mcl, mtxt = self._color_warn, 'WRN' elif record.levelno == logging.ERROR: mcl, mtxt = self._color_err, 'ERR' else: mcl, mtxt = self._color_normal, '' if mtxt: mtxt += ' ' if self.log_fout: self.__set_fmt(self.date_full + mtxt + self.msg) formatted = super(LogFormatter, self).format(record) # self.log_fout.write(formatted) # self.log_fout.write('\n') # self.log_fout.flush() return formatted self.__set_fmt(self._color_date(self.date) + mcl(mtxt + self.msg)) formatted = super(LogFormatter, self).format(record) return formatted if sys.version_info.major < 3: def __set_fmt(self, fmt): self._fmt = fmt else: def __set_fmt(self, fmt): self._style._fmt = fmt @staticmethod def _color_dbg(msg): return '\x1b[36m{}\x1b[0m'.format(msg) @staticmethod def _color_warn(msg): return '\x1b[1;31m{}\x1b[0m'.format(msg) @staticmethod def _color_err(msg): return '\x1b[1;4;31m{}\x1b[0m'.format(msg) @staticmethod def _color_omitted(msg): return '\x1b[35m{}\x1b[0m'.format(msg) @staticmethod def _color_normal(msg): return msg @staticmethod def _color_date(msg): return '\x1b[32m{}\x1b[0m'.format(msg) _default_level_name = os.getenv('ENGINE_LOGGING_LEVEL', 'INFO') _default_level = logging.getLevelName(_default_level_name.upper()) def get_logger(log_dir=None, log_file=None, formatter=LogFormatter): logger = logging.getLogger() logger.setLevel(_default_level) del logger.handlers[:] if log_dir and log_file: ensure_dir(log_dir) LogFormatter.log_fout = True file_handler = logging.FileHandler(log_file, mode='a') file_handler.setLevel(logging.INFO) file_handler.setFormatter(formatter) logger.addHandler(file_handler) stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter(datefmt='%d %H:%M:%S')) stream_handler.setLevel(0) logger.addHandler(stream_handler) return logger logger = get_logger() model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', } def reduce_tensor(tensor, dst=0, op=dist.ReduceOp.SUM, world_size=1): tensor = tensor.clone() dist.reduce(tensor, dst, op) if dist.get_rank() == dst: tensor.div_(world_size) return tensor def all_reduce_tensor(tensor, op=dist.ReduceOp.SUM, world_size=1): tensor = tensor.clone() dist.all_reduce(tensor, op) tensor.div_(world_size) return tensor def load_restore_model(model, model_file): t_start = time.time() if model_file is None: return model if isinstance(model_file, str): state_dict = torch.load(model_file) if 'model' in state_dict.keys(): state_dict = state_dict['model'] elif 'state_dict' in state_dict.keys(): state_dict = state_dict['state_dict'] elif 'module' in state_dict.keys(): state_dict = state_dict['module'] else: state_dict = model_file t_ioend = time.time() model.load_state_dict(state_dict, strict=True) del state_dict t_end = time.time() logger.info( "Load model, Time usage:\n\tIO: {}, initialize parameters: {}".format( t_ioend - t_start, t_end - t_ioend)) return model def load_model(model, model_file, is_restore=False): t_start = time.time() if model_file is None: return model if isinstance(model_file, str): state_dict = torch.load(model_file) if 'model' in state_dict.keys(): state_dict = state_dict['model'] elif 'state_dict' in state_dict.keys(): state_dict = state_dict['state_dict'] elif 'module' in state_dict.keys(): state_dict = state_dict['module'] else: state_dict = model_file t_ioend = time.time() if is_restore: new_state_dict = OrderedDict() for k, v in state_dict.items(): name = 'module.' + k new_state_dict[name] = v state_dict = new_state_dict model.load_state_dict(state_dict, strict=True) ckpt_keys = set(state_dict.keys()) own_keys = set(model.state_dict().keys()) missing_keys = own_keys - ckpt_keys unexpected_keys = ckpt_keys - own_keys del state_dict t_end = time.time() logger.info( "Load model, Time usage:\n\tIO: {}, initialize parameters: {}".format( t_ioend - t_start, t_end - t_ioend)) return model def parse_devices(input_devices): if input_devices.endswith('*'): devices = list(range(torch.cuda.device_count())) return devices devices = [] for d in input_devices.split(','): if '-' in d: start_device, end_device = d.split('-')[0], d.split('-')[1] assert start_device != '' assert end_device != '' start_device, end_device = int(start_device), int(end_device) assert start_device < end_device assert end_device < torch.cuda.device_count() for sd in range(start_device, end_device + 1): devices.append(sd) else: device = int(d) assert device < torch.cuda.device_count() devices.append(device) logger.info('using devices {}'.format( ', '.join([str(d) for d in devices]))) return devices def extant_file(x): """ 'Type' for argparse - checks that file exists but does not open. """ if not os.path.exists(x): # Argparse uses the ArgumentTypeError to give a rejection message like: # error: argument input: x does not exist raise argparse.ArgumentTypeError("{0} does not exist".format(x)) return x def link_file(src, target): if os.path.isdir(target) or os.path.isfile(target): os.system('rm -rf {}'.format(target)) os.system('ln -s {} {}'.format(src, target)) def ensure_dir(path): if not os.path.isdir(path): try: sleeptime = random.randint(0, 3) time.sleep(sleeptime) os.makedirs(path) except: print('conflict !!!') def _dbg_interactive(var, value): from IPython import embed embed()
def on_set_fraction( self, value ): if not len(self.key) or not len(self.keyValue): return previous = None previousKey = None start,stop = -1,-1 for index,(key,orient) in enumerate(zip( self.key, self.keyValue )): if key > value: if previous is None: self.value_changed = orient return else: segmentFraction = (value-previousKey)/float(key-previousKey) self.value_changed = self.interpolate( previous, orient, segmentFraction, ) return self.value_changed elif key == value: self.value_changed = orient return self.value_changed previous,previousKey = orient,key self.value_changed = self.keyValue[-1] return self.value_changed
<gh_stars>0 /** * Copyright (C) 2011-2019 Red Hat, Inc. (https://github.com/Commonjava/indy) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.commonjava.indy.revisions.jaxrs; import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.commonjava.indy.audit.ChangeSummary; import org.commonjava.indy.bind.jaxrs.IndyResources; import org.commonjava.indy.bind.jaxrs.util.REST; import org.commonjava.indy.bind.jaxrs.util.ResponseHelper; import org.commonjava.indy.model.core.StoreKey; import org.commonjava.indy.model.core.StoreType; import org.commonjava.indy.revisions.RevisionsManager; import org.commonjava.indy.revisions.jaxrs.dto.ChangeSummaryDTO; import org.commonjava.indy.subsys.git.GitSubsystemException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.util.Date; import java.util.List; @Path( "/api/revisions/changelog" ) @REST public class ChangelogResource implements IndyResources { private final Logger logger = LoggerFactory.getLogger( getClass() ); private static final int DEFAULT_CHANGELOG_COUNT = 10; @Inject private RevisionsManager revisions; @Inject private ObjectMapper objectMapper; @Inject private ResponseHelper responseHelper; @ApiOperation( "Retrieve the changelog for the Indy group/repository definition with the start-index and number of results" ) @ApiResponses( { @ApiResponse( code = 200, message = "JSON containing changelog entries", response = ChangeSummaryDTO.class ), @ApiResponse( code = 400, message = "Requested group/repository type is not one of: {remote, hosted, group}" ) } ) @Path( "/store/{type}/{name}" ) public Response getStoreChangelog( @ApiParam( allowableValues = "hosted,group,remote", required = true ) final @PathParam( "type" ) String t, @PathParam( "name" ) final String storeName, @QueryParam( "start" ) int start, @QueryParam( "count" ) int count ) { final StoreType storeType = StoreType.get( t ); if ( storeType == null ) { return Response.status( Status.BAD_REQUEST ).entity( "Invalid store type: '" + t + "'" ).build(); } final StoreKey key = new StoreKey( storeType, storeName ); if ( start < 0 ) { start = 0; } if ( count < 1 ) { count = DEFAULT_CHANGELOG_COUNT; } Response response; try { final List<ChangeSummary> dataChangeLog = revisions.getDataChangeLog( key, start, count ); response = responseHelper.formatOkResponseWithJsonEntity( new ChangeSummaryDTO( dataChangeLog ) ); logger.info( "\n\n\n\n\n\n{} Sent changelog for: {}\n\n{}\n\n\n\n\n\n\n", new Date(), key, dataChangeLog ); } catch ( final GitSubsystemException e ) { final String message = String.format( "Failed to lookup changelog for: %s. Reason: %s", key, e.getMessage() ); logger.error( message, e ); response = responseHelper.formatResponse( e ); } return response; } }
<gh_stars>0 import React from 'react' import PropTypes from 'prop-types' import Image from 'next/image' HeroImage.propTypes = { img: PropTypes.string, } export default function HeroImage({img}) { return ( <div className="hero-image-wrapper"> <Image src={img} layout="intrinsic" width={560} height={550} objectFit={'scale-down'} alt="Headshot" quality={50} priority={true} unoptimized={true} /> </div> ) }
<reponame>christopher-burke/warmups #!/usr/bin/env python3 """Baseball stat formulas. Collection of baseball formulas used for statistical analysis. """ from fractions import Fraction def innings(innings: str): """Convert the partial innings pitched (outs) to a fraction. Baseball represents the thirds of innings in the following: * 0.1 = 1 of the 3 outs made, meaning 1/3. * 0.2 = 2 of the 3 outs made, meaning 2/3. These fractions need to be converted properly in order to be processed. """ try: innings, fraction = innings.split('.') fraction = Fraction(int(fraction), 3) return int(innings) + fraction except ValueError: return int(innings) def era(innings_pitched: float, er: int, total_innings: int=9) -> float: """Calculate a baseball pitcher's ERA. ERA = ('earned runs' / 'innings pitched') * 'total innings' er = Earned Runs """ ERA = (er * total_innings) / innings(str(innings_pitched)) return round(float(ERA), 2) def whip(innings_pitched: float, bb: int, h: int) -> float: """Calculate a baseball pitcher's WHIP. WHIP = (BB + H) / IP bb = Walks / Base on balls h = hits """ WHIP = (bb + h) / innings(str(innings_pitched)) return round(float(WHIP), 2) def main(): """Run era and whip samples.""" print(era(innings_pitched=6.0, er=3)) print(era(innings_pitched=6.2, er=3)) print(era(innings_pitched=154.1, er=52)) print(whip(innings_pitched=202.1, bb=43, h=190)) print(whip(innings_pitched=140.0, bb=38, h=130)) print(whip(innings_pitched=154.1, bb=38, h=148)) if __name__ == "__main__": main()
<reponame>MartinPippel/DAmar #pragma once #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include "dalign/align.h" #define LAZ_MAGIC 0x254c415a typedef struct { uint32_t magic; uint16_t version; uint16_t twidth; uint64_t novl; uint64_t reserved1; uint64_t reserved2; uint64_t reserved3; uint64_t reserved4; } LAZ_HEADER; typedef struct { uint64_t a_from; uint64_t a_to; uint64_t novl; uint64_t next; uint64_t data; uint64_t reserved1; uint64_t reserved2; uint64_t reserved3; uint64_t reserved4; } LAZ_INDEX; typedef struct { FILE* file; uint16_t version; uint16_t twidth; uint64_t novl; Overlap* ovl; uint32_t on; uint32_t omax; uint32_t ocur; void* buf; uint32_t bmax; } LAZ; LAZ* laz_open(char* fpath, int create); int laz_close(LAZ* laz); Overlap* laz_read(LAZ* laz); int laz_write(LAZ* laz, Overlap* ovl);
<gh_stars>0 import { MockRuntimeError } from '@jamashita/anden-error'; import { Contradiction } from '../Contradiction'; import { Schrodinger } from '../Schrodinger'; describe('Contradiction', () => { describe('get', () => { it('throws given error', () => { const error1: MockRuntimeError = new MockRuntimeError(); const error2: MockRuntimeError = new MockRuntimeError(); const contradiction1: Contradiction<number, MockRuntimeError> = Contradiction.of<number, MockRuntimeError>(error1); const contradiction2: Contradiction<number, MockRuntimeError> = Contradiction.of<number, MockRuntimeError>(error2); expect(() => { contradiction1.get(); }).toThrow(error1); expect(() => { contradiction2.get(); }).toThrow(error2); }); }); describe('getCause', () => { it('returns thrown error', () => { const error1: MockRuntimeError = new MockRuntimeError(); const error2: MockRuntimeError = new MockRuntimeError(); const contradiction1: Contradiction<number, MockRuntimeError> = Contradiction.of<number, MockRuntimeError>(error1); const contradiction2: Contradiction<number, MockRuntimeError> = Contradiction.of<number, MockRuntimeError>(error2); expect(contradiction1.getCause()).toBe(error1); expect(contradiction2.getCause()).toBe(error2); }); }); describe('isAlive', () => { it('always returns false', () => { const error: MockRuntimeError = new MockRuntimeError(); const contradiction: Contradiction<number, MockRuntimeError> = Contradiction.of<number, MockRuntimeError>(error); expect(contradiction.isAlive()).toBe(false); }); }); describe('isDead', () => { it('always returns false', () => { const error: MockRuntimeError = new MockRuntimeError(); const contradiction: Contradiction<number, MockRuntimeError> = Contradiction.of<number, MockRuntimeError>(error); expect(contradiction.isDead()).toBe(false); }); }); describe('isContradiction', () => { it('always returns true', () => { const error: MockRuntimeError = new MockRuntimeError(); const contradiction: Contradiction<number, MockRuntimeError> = Contradiction.of<number, MockRuntimeError>(error); expect(contradiction.isContradiction()).toBe(true); }); }); describe('ifAlive', () => { it('will not be invoked', () => { const value: number = 1; const fn: jest.Mock = jest.fn(); const contradiction: Schrodinger<number, MockRuntimeError> = Contradiction.of<number, MockRuntimeError>(value); contradiction.ifAlive(() => { fn(); }); expect(fn.mock.calls).toHaveLength(0); }); }); describe('ifDead', () => { it('will not be invoked', () => { const value: number = 1; const fn: jest.Mock = jest.fn(); const contradiction: Schrodinger<number, MockRuntimeError> = Contradiction.of<number, MockRuntimeError>(value); contradiction.ifDead(() => { fn(); }); expect(fn.mock.calls).toHaveLength(0); }); }); describe('ifContradiction', () => { it('will be invoked', () => { const value: number = 1; const fn: jest.Mock = jest.fn(); const contradiction: Schrodinger<number, MockRuntimeError> = Contradiction.of<number, MockRuntimeError>(value); contradiction.ifContradiction((v: unknown) => { fn(); expect(v).toBe(value); }); expect(fn.mock.calls).toHaveLength(1); }); }); describe('toString', () => { it('returns Contradiction and its retaining cause', () => { expect(Contradiction.of<number, MockRuntimeError>(null).toString()).toBe('Contradiction: null'); }); }); });
package main import ( "fmt" "math" ) func leftmostDigit(n int) int { for n >= 10 { n = n / 10 } return n } func numDigits(n int) int { var count int = 0 for n > 0 { n = n / 10 count = count + 1 } return count } // assumes leftDigit and E are valid constraints for producing a sequential number, per validSequentialNumberConstraints func getSequentialNumber(leftDigit int, E int) int { if leftDigit > 9 || E < 0 { return 0 } var n int = leftDigit * int(math.Pow(10, float64(E))) return n + getSequentialNumber(leftDigit+1, E-1) } func validSequentialNumberConstraints(leftDigit int, E int) bool { return leftDigit+E <= 9 } // https://leetcode.com/problems/sequential-digits/ // An integer has sequential digits if and only if each digit in the number is one more than the previous digit. // Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. func sequentialDigits(low int, high int) []int { var startingDigit int = leftmostDigit(low) var startingE int = numDigits(low) - 1 // e.g. if low is in range 10 - 99, E is 1 var maxE int = numDigits(high) - 1 var result []int = make([]int, 0) E := startingE leftDigit := startingDigit for E <= maxE { for leftDigit < 10 { if validSequentialNumberConstraints(leftDigit, E) { var sequentialNumber int = getSequentialNumber(leftDigit, E) if low <= sequentialNumber && sequentialNumber <= high { result = append(result, sequentialNumber) } } leftDigit = leftDigit + 1 } E = E + 1 leftDigit = 1 } return result } func main() { fmt.Println("hello") fmt.Println(leftmostDigit(123)) fmt.Println(leftmostDigit(456)) fmt.Println(numDigits(12345)) fmt.Println(numDigits(10)) fmt.Println(numDigits(11)) fmt.Println(getSequentialNumber(1, 2)) // expects 123 fmt.Println(getSequentialNumber(2, 4)) // expects 23456 fmt.Println(getSequentialNumber(7, 2)) // expects 789 fmt.Println(validSequentialNumberConstraints(7, 2)) // expects true fmt.Println(validSequentialNumberConstraints(8, 2)) // expects false fmt.Println(sequentialDigits(100, 300)) // expects [123, 234] fmt.Println(sequentialDigits(1000, 13000)) // expects [1234,2345,3456,4567,5678,6789,12345] }
/** * Paints the renderer part of a row. The receiver should NOT modify * clipBounds, or insets. * * @param g - the graphics configuration * @param clipBounds - * @param insets - * @param bounds - bounds of expand control * @param path - path to draw control for * @param row - row to draw control for * @param isExpanded - is the row expanded * @param hasBeenExpanded - has the row already been expanded * @param isLeaf - is the path a leaf */ protected void paintRow(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { boolean selected = tree.isPathSelected(path); boolean hasIcons = false; Object node = path.getLastPathComponent(); paintExpandControl(g, clipBounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf); TreeCellRenderer dtcr = currentCellRenderer; boolean focused = false; if (treeSelectionModel != null) focused = treeSelectionModel.getLeadSelectionRow() == row && tree.isFocusOwner(); Component c = dtcr.getTreeCellRendererComponent(tree, node, selected, isExpanded, isLeaf, row, focused); rendererPane.paintComponent(g, c, c.getParent(), bounds); }
Dictyostelium RbrA is a putative Ariadne‐like ubiquitin ligase required for development The RBR family of ubiquitin ligases is a large and complex family with members present in animals, plants, fungi, and protists. The Ariadne subfamily appears to be the most ancient. The Dictyostelium rbrA gene encodes a protein with similarity to Ariadne ubiquitin ligases. Disruption of rbrA results in cells that form defective slugs that cannot produce fruiting bodies. Prestalk cell numbers were greatly reduced in rbrA‐ slugs, and these cells did not localize to the tip of the slug. Developing rbrA‐ cells on conditioned medium does not rescue the defect. However, mixing a few wild‐type cells with developing rbrA‐ cells did partially rescue the defect. The chimeric slugs formed fruiting bodies; however, rbrA‐ cells in the sori produce a low percentage of viable spores. When chimeras containing 90% rbrA cells were stained with fluorescein diacetate and propidium iodide, some sori stained like wild‐type while others were red indicating cell death. To identify other genes involved in the rbrA pathway, we screened for second site suppressors of the rbrA mutation. In one putative suppressor, SRA1, normal cell‐type distribution appears to be restored. The disrupted gene in SRA1 encodes a hypothetical 163 kDa protein.
import java.util.Scanner; public class NewClass { public static void main(String[] args) { Scanner s = new Scanner (System.in); int n=s.nextInt() , l ,v=0; boolean bool=false; String str ,ar[]=new String[n]; for (int i = 0; i < n; i++) { l=s.nextInt(); str=s.next(); if(str.charAt(0)=='8' && str.length()>=11){ar[i]="Yes";} if(str.length()<11) {ar[i]="No";} if(str.charAt(0)!='8' && str.length()==11) {ar[i]="No";} if(str.charAt(0)!='8' && str.length()>11){ for (int j = 1; j < str.length(); j++) { if(str.charAt(j)=='8'){bool=true;v=str.length()-j;break;} } if(bool==true &&v>=11){bool=false ;ar[i]="Yes";} else {ar[i]="No";} } } for (int i = 0; i < n; i++) { System.out.println(ar[i]); } } }
/** @file * * Copyright (c) 2007-2014, Allwinner Technology Co., Ltd. All rights reserved. * http://www.allwinnertech.com * * tangmanliang <<EMAIL>> * * This program and the accompanying materials * are licensed and made available under the terms and conditions of the BSD License * which accompanies this distribution. The full text of the license may be found at * http://opensource.org/licenses/bsd-license.php * * THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, * WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. * **/ #include "disp_features.h" int bsp_disp_feat_get_num_screens(void) { return de_feat_get_num_screens(); } int bsp_disp_feat_get_num_devices(void) { return de_feat_get_num_devices(); } int bsp_disp_feat_get_num_channels(unsigned int disp) { return de_feat_get_num_chns(disp); } int bsp_disp_feat_get_num_layers(unsigned int disp) { return de_feat_get_num_layers(disp); } int bsp_disp_feat_get_num_layers_by_chn(unsigned int disp, unsigned int chn) { return de_feat_get_num_layers_by_chn(disp, chn); } /* * Query whether specified timing controller support the output_type passed as parameter * @disp: the index of timing controller * @output_type: the display output type * On support, returns 1. Otherwise, returns 0. */ int bsp_disp_feat_is_supported_output_types(unsigned int disp, unsigned int output_type) { return de_feat_is_supported_output_types(disp, output_type); } int disp_feat_is_support_smbl(unsigned int disp) { return de_feat_is_support_smbl(disp); } int bsp_disp_feat_is_support_capture(unsigned int disp) { return de_feat_is_support_wb(disp); } int disp_init_feat(void) { #if 0 { unsigned int num_screens, disp; DE_INF("------------FEAT---------\n"); num_screens = bsp_disp_feat_get_num_screens(); DE_INF("screens:%d\n", num_screens); for (disp=0; disp<num_screens; disp++) { unsigned int num_chns = bsp_disp_feat_get_num_channels(disp); unsigned int num_layers = bsp_disp_feat_get_num_layers(disp); unsigned int i; DE_INF("screen %d: %d chns, %d layers\n", disp, num_chns, num_layers); for (i=0; i<num_chns; i++) { num_layers = bsp_disp_feat_get_num_layers_by_chn(disp, i); DE_INF("screen %d, chn %d: %d layers\n", disp, i, num_layers); } } DE_INF("-------------------------\n"); } #endif return 0; }
#! /usr/bin/env python3 # # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """An example CompilerGym service in python.""" import logging from concurrent import futures from multiprocessing import cpu_count from pathlib import Path from typing import Dict import grpc from absl import app, flags import compiler_gym from compiler_gym.service import proto from compiler_gym.service.proto import compiler_gym_service_pb2_grpc flags.DEFINE_string( "working_dir", "/tmp/example_compiler_gym_service", "Path to use as service working directory", ) flags.DEFINE_integer("port", 0, "The service listening port") flags.DEFINE_integer("nproc", cpu_count(), "The number of server worker threads") flags.DEFINE_integer("logbuflevel", 0, "Flag for compatability with C++ service.") FLAGS = flags.FLAGS # For development / debugging, set environment variable COMPILER_GYM_DEBUG=3. # This will cause all output of this script to be logged to stdout. Otherwise # all output from this process is silently thrown away. logging.basicConfig(level=logging.DEBUG) # The names of the benchmarks that are supported BENCHMARKS = ["foo", "bar"] # The list of actions that are supported by this service. This example uses a # static (unchanging) action space, but this could be extended to support a # dynamic action space. ACTION_SPACE = proto.ActionSpace( name="default", action=[ "a", "b", "c", ], ) # A list of observation spaces supported by this service. Each of these # ObservationSpace protos describes an observation space. OBSERVATION_SPACES = [ proto.ObservationSpace( name="ir", string_size_range=proto.ScalarRange(min=proto.ScalarLimit(value=0)), deterministic=True, platform_dependent=False, default_value=proto.Observation(string_value=""), ), proto.ObservationSpace( name="features", int64_range_list=proto.ScalarRangeList( range=[ proto.ScalarRange( min=proto.ScalarLimit(value=-100), max=proto.ScalarLimit(value=100) ), proto.ScalarRange( min=proto.ScalarLimit(value=-100), max=proto.ScalarLimit(value=100) ), proto.ScalarRange( min=proto.ScalarLimit(value=-100), max=proto.ScalarLimit(value=100) ), ] ), ), proto.ObservationSpace( name="runtime", scalar_double_range=proto.ScalarRange(min=proto.ScalarLimit(value=0)), deterministic=False, platform_dependent=True, default_value=proto.Observation( scalar_double=0, ), ), ] class CompilationSession(object): """Represents an instance of an interactive compilation session.""" def __init__(self, benchmark: str): # Do any of the set up required to start a compilation "session". self.benchmark = benchmark def set_observation(self, observation_space, observation): logging.debug("Compute observation %d", observation_space) if observation_space == 0: # ir observation.string_value = "Hello, world!" elif observation_space == 1: # features observation.int64_list.value[:] = [0, 0, 0] elif observation_space == 1: # runtime observation.scalar_double = 0 return observation def step(self, request: proto.StepRequest, context) -> proto.StepReply: reply = proto.StepReply() # Apply a list of actions from the user. Each value is an index into the # ACTIONS_SPACE.action list. for action in request.action: logging.debug("Apply action %d", action) if action < 0 or action >= len(ACTION_SPACE.action): context.set_code(grpc.StatusCode.INVALID_ARGUMENT) context.set_details("Out-of-range") return # Compute a list of observations from the user. Each value is an index # into the OBSERVATION_SPACES list. for observation_space in request.observation_space: self.set_observation(observation_space, reply.observation.add()) return reply class ExampleCompilerGymService(proto.CompilerGymServiceServicer): """The service creates and manages sessions, and is responsible for reporting the service capabilities to the user.""" def __init__(self, working_dir: Path): self.working_dir = working_dir self.sessions: Dict[int, CompilationSession] = {} def GetVersion( self, request: proto.GetVersionRequest, context ) -> proto.GetVersionReply: del context # Unused del request # Unused logging.debug("GetVersion()") return proto.GetVersionReply( service_version=compiler_gym.__version__, compiler_version="1.0.0", # Arbitrary version tag. ) def GetSpaces( self, request: proto.GetSpacesRequest, context ) -> proto.GetSpacesReply: del context # Unused del request # Unused logging.debug("GetSpaces()") return proto.GetSpacesReply( action_space_list=[ACTION_SPACE], observation_space_list=OBSERVATION_SPACES, ) def GetBenchmarks( self, request: proto.GetBenchmarksRequest, context ) -> proto.GetBenchmarksReply: del context # Unused # Report the available benchmarks to the user. logging.debug("GetBenchmarks()") return proto.GetBenchmarksReply(benchmark=BENCHMARKS) def StartSession( self, request: proto.StartSessionRequest, context ) -> proto.StartSessionReply: """Create a new compilation session.""" logging.debug("StartSession(benchmark=%s)", request.benchmark) reply = proto.StartSessionReply() if not request.benchmark: benchmark = "foo" # Pick a default benchmark is none was requested. else: benchmark = request.benchmark if benchmark not in BENCHMARKS: context.set_code(grpc.StatusCode.INVALID_ARGUMENT) context.set_details("Unknown program name") return session = CompilationSession(benchmark=benchmark) # Generate the initial observations. for observation_space in request.observation_space: session.set_observation(observation_space, reply.observation.add()) reply.session_id = len(self.sessions) reply.benchmark = session.benchmark self.sessions[reply.session_id] = session return reply def EndSession( self, request: proto.EndSessionRequest, context ) -> proto.EndSessionReply: """End a compilation session.""" del context # Unused logging.debug("EndSession()") if request.session_id in self.sessions: del self.sessions[request.session_id] return proto.EndSessionReply(remaining_sessions=len(self.sessions)) def Step(self, request: proto.StepRequest, context) -> proto.StepReply: logging.debug("Step()") if request.session_id not in self.sessions: context.set_code(grpc.StatusCode.INVALID_ARGUMENT) context.set_details("Session ID not found") return return self.sessions[request.session_id].step(request, context) def main(argv): assert argv # Unused working_dir = Path(FLAGS.working_dir) working_dir.mkdir(exist_ok=True, parents=True) # Create the service. server = grpc.server(futures.ThreadPoolExecutor(max_workers=FLAGS.nproc)) compiler_gym_service_pb2_grpc.add_CompilerGymServiceServicer_to_server( ExampleCompilerGymService(working_dir), server ) port = server.add_insecure_port("0.0.0.0:0") logging.info("Starting service on %s with working dir %s", port, working_dir) with open(working_dir / "port.txt", "w") as f: f.write(str(port)) server.start() server.wait_for_termination() if __name__ == "__main__": app.run(main)
package io.ebeaninternal.dbmigration.ddlgeneration.platform; import io.ebean.config.dbplatform.DatabasePlatform; public class Postgres9Ddl extends PostgresDdl { public Postgres9Ddl(DatabasePlatform platform) { super(platform); } /** * Map bigint, integer and smallint into their equivalent serial types. */ @Override public String asIdentityColumn(String columnDefn, DdlIdentity identity) { if ("bigint".equalsIgnoreCase(columnDefn)) { return "bigserial"; } if ("integer".equalsIgnoreCase(columnDefn)) { return "serial"; } if ("smallint".equalsIgnoreCase(columnDefn)) { return "smallserial"; } return columnDefn; } }
<filename>rotor_connect.py<gh_stars>0 #!/usr/bin/python from bluepy import btle import time import binascii dev_name_uuid = btle.UUID(0x2A00) rotorServicesUUID = btle.UUID("fb8e8220-1797-11e6-900b-0002a5d5c51b") bootloaderServices = btle.UUID("00060000-f8ce-11e4-abf4-0002a5d5c51b") genericServices = btle.UUID("8ab07720-1797-11e6-a7d5-0002a5d5c51b") device_id = "00:a0:50:ae:51:de" print("Connecting to '%s'..." % device_id) dev = btle.Peripheral(device_id) device_name = ""; ch = dev.getCharacteristics(uuid=dev_name_uuid)[0] if (ch.supportsRead()): device_name = ch.read() print("Services in '%s' %s (%s), RSSI=%d dB" % (device_name, dev.addr, dev.addrType, -900)) rotorServicesCmd = { 0x00 : "Push Button Indication Button pressed", 0x04 : "Charging Control", 0x08 : "Structured Light Detect Indication", 0x0c : "Structured Light Control", 0x10 : "Stepper Power Control", 0x14 : "Rotor Move Completion Success (response to 0x8c)", 0x18 : "Rotor Move Completion Aborted (response to 0x8c)", 0x1c : "Reset Motor Origin", 0x40 : "Board Revision", 0x48 : "ADC Readout : ", 0x4c : "Run Current Control (mA)", 0x50 : "Hold Current Control (mA)", 0x54 : "Rotor Move Completion With ID Success (response to 0xcc)", 0x58 : "Rotor Move Completion With ID Aborted (response to 0xcc)", 0x5c : "Battery level in percents", 0x80 : "Firmware Version (0.9.1 would be 0x91 0x00)", 0x84 : "Axis Limit Min. (in 1/10 deg)", 0x88 : "Axis Limit Max. (in 1/10 deg)", 0x8c : "Axis Position (in 1/10 deg)", 0x90 : "Run Voltage (mV)", 0x94 : "Hold Voltage (mV)", 0x98 : "Max Speed (in deg/s)", 0x9c : "Acceleration (in deg/s2)", 0xa0 : "Speed Limit Min. (in deg/s)", 0xa4 : "Speed Limit Max. (in deg/s)", 0xa8 : "Acceleration Limit Min. (in deg/s2)", 0xac : "Acceleration Limit Max. (in deg/s2)", 0xb0 : "Internal resistance of battery (in mOhms)", 0xc4 : "LED Control (RGB components as payload, 1 byte each)", 0xcc : "Axis Position With ID (in 1/10 deg)", 0xd0 : "MAC address least significant part", 0xd4 : "MAC address most significant part" } #for svc in dev.services: # print(str(svc)) rotorService=dev.getServiceByUUID(rotorServicesUUID) def parseString(data): i=0; datalen = len(data); while (i<datalen): val_ch = ord(data[i]) payload = (val_ch & 0xC0) >> 6 cmd = (val_ch & 0xFC) chn = val_ch & 0x3 cmd_str = "UNKNOWN" val=0 i+=1 if (payload == 0) : val = chn if (payload == 1) : val=ord(data[i]) if (payload == 2) : val=ord(data[i+1])*255 + ord(data[i]) if (payload == 3) : val=ord(data[i+1])*255*255 + ord(data[i+1])*255 + ord(data[i]) i+=payload if (rotorServicesCmd.has_key(cmd)): cmd_str=rotorServicesCmd.get(cmd) print("0x%02x %40s chn=0x%x val:%d" % (cmd,cmd_str,chn,val)) ch = rotorService.getCharacteristics()[0] while 1: ch_read = ch.read() parseString(ch_read); val = binascii.b2a_hex(ch_read) print ("%s" % (val)) time.sleep(0.2)
<gh_stars>1-10 // Package jsons implements encoding and decoding of JSONS files and streams. // The JSONS format is defined as compact JSON objects delimited by one // newline. Each JSON object resides on its own line. package jsons
//special case, because do not overwrite the spellchecking styles protected void applyHighlighting(StyleSpans<Collection<String>> highlighting) { int currentPosition = 0; List<Replacement<Collection<String>, String, Collection<String>>> replacements = new ArrayList<>(); for (StyleSpan<Collection<String>> styleSpan : highlighting) { Collection<String> styles = styleSpan.getStyle(); if (!styles.isEmpty()) { String text = getCodeArea().getText(currentPosition, currentPosition + styleSpan.getLength()); ReadOnlyStyledDocument<Collection<String>, String, Collection<String>> rosd = ReadOnlyStyledDocument.fromString(text, getCodeArea().getInitialParagraphStyle(), styles, getCodeArea().getSegOps()); Replacement<Collection<String>, String, Collection<String>> replacement = new Replacement<>(currentPosition, currentPosition + styleSpan.getLength(), rosd); replacements.add(replacement); } currentPosition += styleSpan.getLength(); } ((EditableStyledDocument<Collection<String>, String, Collection<String>>)getCodeArea().getDocument()).replaceMulti(replacements); }
/** This method should clearly display all the contents of the structure in * textual form, sending it to a CStream. * The default implementation in this base class relies on \a * saveToConfigFile() to generate a plain text representation of all the * parameters. */ void CLoadableOptions::dumpToTextStream(mrpt::utils::CStream& out) const { CConfigFileMemory cfg; this->saveToConfigFile(cfg, ""); out.printf("%s", cfg.getContent().c_str()); }
// isWinning returns true if the board is winning. func (b *board) isWinning(winningNumbers []int) bool { var markedSquares []square for _, square := range b.squares { if contains(winningNumbers, square.value) { markedSquares = append(markedSquares, square) } } xOccurrences := map[int]int{} yOccurrences := map[int]int{} for _, square := range markedSquares { xOccurrences[square.x] = xOccurrences[square.x] + 1 yOccurrences[square.y] = yOccurrences[square.y] + 1 } for _, occ := range xOccurrences { if occ == 5 { return true } } for _, occ := range yOccurrences { if occ == 5 { return true } } return false }
package com.netflix.eureka.registry; import javax.annotation.Nullable; import java.util.concurrent.atomic.AtomicLong; /** * @author David Liu */ public interface ResponseCache { void invalidate(String appName, @Nullable String vipAddress, @Nullable String secureVipAddress); AtomicLong getVersionDelta(); AtomicLong getVersionDeltaWithRegions(); /** * Get the cached information about applications. * * <p> * If the cached information is not available it is generated on the first * request. After the first request, the information is then updated * periodically by a background thread. * </p> * * @param key the key for which the cached information needs to be obtained. * @return payload which contains information about the applications. */ String get(Key key); /** * Get the compressed information about the applications. * * @param key the key for which the compressed cached information needs to be obtained. * @return compressed payload which contains information about the applications. */ byte[] getGZIP(Key key); /** * Performs a shutdown of this cache by stopping internal threads and unregistering * Servo monitors. */ void stop(); }
/** * Return a page from the buffer, or null if none exists */ public synchronized Page poll() { if (settableFuture != null) { settableFuture.set(null); settableFuture = null; } return pages.poll(); }
<filename>src/app/app.pipes.ts import { Pipe, PipeTransform } from '@angular/core'; import {DataPoint, XMLSource} from "./app.reducer"; @Pipe({name: 'getValue'}) export class GetValuePipe implements PipeTransform { transform(file: File, dataPoint: DataPoint): string{ // const node = file.document?.getElementsByTagName(dataPoint.nodeName)[0] // return (node && ( dataPoint.attribute ? node.getAttribute(dataPoint.attribute) : node.textContent ) || '') return ''; } }
/** * Test the parsing of the game summary<br> * Passed game */ @Test public void testParseGameSummary_PassedGame() { final String gameSummary = "(;GM[Skat]PC[International Skat Server]CO[]SE[32407]ID[756788]DT[2011-05-28/08:46:19/UTC]P0[xskat]P1[bonsai]P2[bernie]R0[]R1[0.0]R2[]MV[w C8.DQ.DJ.HK.S9.SK.SQ.HQ.CK.D9.S8.DT.SJ.C9.CQ.SA.DK.HT.D7.H7.ST.HJ.C7.H8.S7.DA.CJ.CT.D8.H9.CA.HA 1 p 2 p 0 p ]R[passed] ;)"; final SkatGameData gameData = MessageParser.parseGameSummary(gameSummary); assertTrue(gameData.isGamePassed()); assertThat(gameData.getResult().getGameValue()).isEqualTo(0); assertThat(gameData.getPlayerName(Player.FOREHAND)).isEqualTo("xskat"); assertThat(gameData.getPlayerName(Player.MIDDLEHAND)).isEqualTo("bonsai"); assertThat(gameData.getPlayerName(Player.REARHAND)).isEqualTo("bernie"); assertThat(gameData.getMaxPlayerBid(Player.FOREHAND)).isEqualTo(0); assertThat(gameData.getMaxPlayerBid(Player.MIDDLEHAND)).isEqualTo(0); assertThat(gameData.getMaxPlayerBid(Player.REARHAND)).isEqualTo(0); assertThat(gameData.getMaxBidValue()).isEqualTo(0); assertNull(gameData.getDeclarer()); assertTrue(gameData.getDealtSkat().contains(Card.CA)); assertTrue(gameData.getDealtSkat().contains(Card.HA)); assertThat(gameData.getGameType()).isEqualTo(GameType.PASSED_IN); assertFalse(gameData.isHand()); assertFalse(gameData.isOuvert()); assertFalse(gameData.isSchneider()); assertFalse(gameData.isSchneiderAnnounced()); assertFalse(gameData.isSchwarz()); assertFalse(gameData.isSchwarzAnnounced()); assertThat(gameData.getTricks().size()).isEqualTo(0); assertFalse(gameData.isGameWon()); assertThat(gameData.getResult().getGameValue()).isEqualTo(0); assertThat(gameData.getDeclarerScore()).isEqualTo(0); assertThat(gameData.getOpponentScore()).isEqualTo(0); assertFalse(gameData.isSchneider()); assertFalse(gameData.isSchwarz()); assertFalse(gameData.isOverBidded()); }
def _calculate_roc_points(data, sensitive_feature_value, flip=True): scores, labels, n, n_positive, n_negative = _get_scores_labels_and_counts(data) if n_positive == 0 or n_negative == 0: raise ValueError(DEGENERATE_LABELS_ERROR_MESSAGE.format(sensitive_feature_value)) scores.append(-np.inf) labels.append(np.nan) x_list, y_list, operation_list = [0], [0], [ThresholdOperation('>', np.inf)] i = 0 count = [0, 0] while i < n: threshold = scores[i] while scores[i] == threshold: count[labels[i]] += 1 i += 1 x, y = count[0] / n_negative, count[1] / n_positive threshold = (threshold + scores[i]) / 2 operation = ThresholdOperation('>', threshold) if flip and x > y: x, y = 1 - x, 1 - y operation = ThresholdOperation('<', threshold) x_list.append(x) y_list.append(y) operation_list.append(operation) return pd.DataFrame({'x': x_list, 'y': y_list, 'operation': operation_list}) \ .sort_values(by=['x', 'y'])
Squamous Cell Carcinoma Associated with Cosmetic Use of Bleaching Agents: About a Case in Ivory Coast Voluntary skin depigmentation is defined as a set of procedures for obtaining skin clarification for cosmetic purposes. Skin cancers are possible complications, but rarely reported. We describe a case observed in Ivory Coast. A 52-year-old Ivorian woman consulted the Dermatology Department of the University Hospital of Treichville, Abidjan for an ulceration of the middle third of the right clavicle evolving for 10 months. A diagnosis of squamous cell carcinoma (SCC) was confirmed by histological examination of the tumour biopsy. Retroviral serology (HIV) was negative. An excision of the tumour was performed. The postoperative consequences were simple. We report a case of SCC following long-term use of depigmenting cosmetic products in a female phototype VI. SCC is the most common skin cancer among black Africans. It is secondary to precancerous lesions or takes place on a damaged skin. Concerning our patient, the onset of this carcinoma could be associated with the carcinogenic effect of hydroquinone and topical corticoids used for a long time. In addition, no precancerous lesion or preexisting condition were found. The chronic evolution without healing was in favour of a neoplastic origin achieved through the analysis of the biopsy sample. Introduction Voluntary skin depigmentation is defined as a set of procedures for obtaining skin clarification for cosmetic purposes . The use of depigmenting cosmetic products carries risk of skin and systemic complications . Skin cancers are possible complications, but rarely reported. A few cases have been reported in Ghana, Senegal, and Mali . We describe a case observed in Ivory Coast. Case Description A 52-year old Ivorian woman, a shopkeeper, consulted the Dermatology Department of the University Hospital of Treichville, Abidjan for an ulceration of the middle third of the right clavicle evolving for 10 months (Fig. 1). The lesion began with a pruritic nodule of the right clavicle that gradually ulcerated without pain or bleeding. The patient applied traditional poultices to the lesion without beneficial effect. There was no particular history other than the daily use of depigmenting cosmetic products in the form of ointment and body lotions based on lemon, hydroquinone, and dermocorticoid extracts for several years. Physical examination revealed a large ulcer-budding tumour (4 × 5 cm) at the middle third of the right clavicle, associated with skin atrophy and severe skin xerosis. There were no peripheral adenopathies. The rest of the physical examination was without particularity. Retroviral serology (HIV) was negative. An excision was performed ( Fig. 2) with histological examination that confirmed a moderately differentiated and mature squamous cell carcinoma (SCC). The postoperative consequences were simple. Discussion We report a case of SCC following long-term use of depigmenting cosmetic products in a female phototype VI. The complications of voluntary skin depigmentation are well known and documented . They are local and systemic. Local complications are numerous and frequent, including dermatophytic diseases, scabies, acne, pyoderma, bacterial dermohypodermitis, exogenous ochronosis, and stretchmarks . Systemic complications are represented by diabetes, high blood pressure, exogenous hypercorticism, and the risk of adrenal insufficiency at the end of the practice . Other complications related to general corticosteroid therapy have been reported, namely bone necrosis, cataract, and glaucoma . A study conducted by Ndoye Roth et al. in Senegal showed that artificial depigmentation was responsible for ocular lesions, and these were dominated by exogenous ochronosis lesions of the eyelid and ocular ochronosis. Two cases of SCC in black women of phototype VI using long-term depigmenting products have been described in Senegal . Our observation confirms the occurrence of cancer on depigmentation sites and contributes to the description of this complaint associated with voluntary depigmentation. SCC, although rare on black skin, is the most common skin cancer in African black people. It represented 0.09% of dermatoses in consultation in a study in Senegal . This carcinoma is secondary to precancerous lesions or occurs on damaged skin. There are several arguments to suspect the role of depigmenting products in the occurrence of these carcinomas: the relatively young age of the patients, their high phototype, and the absence of any known risk factors for SCC, including no infection with human papillomavirus or other preneoplastic dermatoses such as burn scars, discoid lupus erythematosus, or genodermatoses such as xeroderma pigmentosum or Lutz-Lewandowsky epidermodysplasia verruciformis . In our patient, no precancerous lesions or other preexisting pathology were found. The occurrence of this carcinoma may be related to the carcinogenic action hypothetically attributed to hydroquinone and long-term corticosteroids. Ly et al. suspected hydroquinone to be the causative factor in the occurrence of SCCs in their patients. Our observation points in this direction, all the more so since hydroquinone, suspected to play a role of carcinogen or cocarcinogen, is involved in the occurrence of kidney, liver, and leukaemia tumours in rodents . Due to the combination of lemon extracts, hydroquinone, and dermocorticoids, the cocarcinogenic action of hydroquinone appears to have been reinforced in our patient. However, there are no data from published studies that can be used to confirm the effectiveness of the carcinogenicity of depigmenting agents . The SCC lesion found in our patient was located at the middle third of the right clavicle. SCC can reach all parts of the body, including the oral and genital mucosa, but is more common in sun-exposed areas. These photoexposed areas are the face, ears, lower lip, bald scalp, neck, back of hands, arms, and legs. A study conducted by Ly et al. in Senegal from 2005 to 2016 identified 8 cases of SCCs associated with voluntary skin depigmentation in which lesions were localized to lichenoid lesions or exogenous ochronotic lesions on photoexposed areas (face, neck, or upper back). Voluntary skin depigmentation practitioners aim to make their skin lighter and even whiter. A study has shown that ultraviolet radiation is an important factor in most cases of SCCs . In our regions, people are constantly exposed to the sun. Dermocorticoids, used for artificial depigmentation, lead to a progressive disappearance of melanin, resulting in a decrease in photoprotection. The development of SCCs such as our patient's could be explained by the disappearance of photoprotection and chronic solar exposure. In addition, people with fair skin were shown to be more prone to skin cancer . The chronic evolution without tendency to heal militated in favour of a neoplastic origin, confirmed by histological examination. Total excision of the lesion was performed. The absence of remote locations explained the non-use of chemotherapy. Conclusion Voluntary skin depigmentation is a predominant practice in our countries. Its complications are numerous and well known. Skin cancers secondary to use of depigmenting cosmetics are rarely reported. However, due to the products used, their incidence would tend to increase more and more within our populations. This requires special attention from the users of these products. Awareness campaigns should be initiated, with a particular focus on the risk of skin cancer. Statement of Ethics Our clinical case did not require any special interventions concerning the patient. No experimentation was performed on the patient. Only the photos of the lesion before and after
import React from "react"; import { Story, Meta } from "@storybook/react"; import Section, { SectionProps } from "../layout/section"; export default { title: "Layout/Section", component: Section, } as Meta; const Template: Story<SectionProps> = (args) => ( <Section {...args}> <p> This is a long child. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </Section> ); export const defaultConfig = Template.bind({}); export const withColor = Template.bind({}); withColor.args = { color: "blue", }; export const withContainer = Template.bind({}); withContainer.args = { color: "purple", container: "smish", }; export const withSpacingOption = Template.bind({}); withSpacingOption.args = { color: "teal-green", space: "aura", };
<filename>core/cache_thread_member.go package core import "github.com/DisgoOrg/snowflake" type ( ThreadMemberFindFunc func(threadMember *ThreadMember) bool ThreadMemberCache interface { Get(threadID snowflake.Snowflake, userID snowflake.Snowflake) *ThreadMember GetCopy(threadID snowflake.Snowflake, userID snowflake.Snowflake) *ThreadMember Set(threadMember *ThreadMember) *ThreadMember Remove(threadID snowflake.Snowflake, userID snowflake.Snowflake) RemoveAll(threadID snowflake.Snowflake) Cache() map[snowflake.Snowflake]map[snowflake.Snowflake]*ThreadMember All() map[snowflake.Snowflake][]*ThreadMember ThreadCache(threadID snowflake.Snowflake) map[snowflake.Snowflake]*ThreadMember ThreadAll(threadID snowflake.Snowflake) []*ThreadMember FindFirst(threadMemberFindFunc ThreadMemberFindFunc) *ThreadMember FindAll(threadMemberFindFunc ThreadMemberFindFunc) []*ThreadMember } threadMemberCacheImpl struct { cacheFlags CacheFlags threadMembers map[snowflake.Snowflake]map[snowflake.Snowflake]*ThreadMember } ) func NewThreadMemberCache(cacheFlags CacheFlags) ThreadMemberCache { return &threadMemberCacheImpl{ cacheFlags: cacheFlags, threadMembers: map[snowflake.Snowflake]map[snowflake.Snowflake]*ThreadMember{}, } } func (c *threadMemberCacheImpl) Get(threadID snowflake.Snowflake, userID snowflake.Snowflake) *ThreadMember { if _, ok := c.threadMembers[threadID]; !ok { return nil } return c.threadMembers[threadID][userID] } func (c *threadMemberCacheImpl) GetCopy(threadID snowflake.Snowflake, userID snowflake.Snowflake) *ThreadMember { if threadMember := c.Get(threadID, userID); threadMember != nil { m := *threadMember return &m } return nil } func (c *threadMemberCacheImpl) Set(threadMember *ThreadMember) *ThreadMember { // always cache self threadMembers if c.cacheFlags.Missing(CacheFlagRoles) && threadMember.UserID != threadMember.Bot.ClientID { return threadMember } if _, ok := c.threadMembers[threadMember.ThreadID]; !ok { c.threadMembers[threadMember.ThreadID] = map[snowflake.Snowflake]*ThreadMember{} } rol, ok := c.threadMembers[threadMember.ThreadID][threadMember.UserID] if ok { *rol = *threadMember return rol } c.threadMembers[threadMember.ThreadID][threadMember.UserID] = threadMember return threadMember } func (c *threadMemberCacheImpl) Remove(threadID snowflake.Snowflake, userID snowflake.Snowflake) { if _, ok := c.threadMembers[threadID]; !ok { return } delete(c.threadMembers[threadID], userID) } func (c *threadMemberCacheImpl) RemoveAll(threadID snowflake.Snowflake) { delete(c.threadMembers, threadID) } func (c *threadMemberCacheImpl) Cache() map[snowflake.Snowflake]map[snowflake.Snowflake]*ThreadMember { return c.threadMembers } func (c *threadMemberCacheImpl) All() map[snowflake.Snowflake][]*ThreadMember { threadMembers := make(map[snowflake.Snowflake][]*ThreadMember, len(c.threadMembers)) for threadID, guildThreadMembers := range c.threadMembers { threadMembers[threadID] = make([]*ThreadMember, len(guildThreadMembers)) i := 0 for _, threadMember := range guildThreadMembers { threadMembers[threadID] = append(threadMembers[threadID], threadMember) } i++ } return threadMembers } func (c *threadMemberCacheImpl) ThreadCache(threadID snowflake.Snowflake) map[snowflake.Snowflake]*ThreadMember { if _, ok := c.threadMembers[threadID]; !ok { return nil } return c.threadMembers[threadID] } func (c *threadMemberCacheImpl) ThreadAll(threadID snowflake.Snowflake) []*ThreadMember { if _, ok := c.threadMembers[threadID]; !ok { return nil } threadMembers := make([]*ThreadMember, len(c.threadMembers[threadID])) i := 0 for _, threadMember := range c.threadMembers[threadID] { threadMembers = append(threadMembers, threadMember) i++ } return threadMembers } func (c *threadMemberCacheImpl) FindFirst(threadMemberFindFunc ThreadMemberFindFunc) *ThreadMember { for _, guildThreadMembers := range c.threadMembers { for _, threadMember := range guildThreadMembers { if threadMemberFindFunc(threadMember) { return threadMember } } } return nil } func (c *threadMemberCacheImpl) FindAll(threadMemberFindFunc ThreadMemberFindFunc) []*ThreadMember { var threadMembers []*ThreadMember for _, guildThreadMembers := range c.threadMembers { for _, threadMember := range guildThreadMembers { if threadMemberFindFunc(threadMember) { threadMembers = append(threadMembers, threadMember) } } } return threadMembers }
# 860. Lemonade Change # At a lemonade stand, each lemonade costs $5. # Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills). # Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer, so that the net transaction is that the customer pays $5. # Note that you don't have any change in hand at first. # Return true if and only if you can provide every customer with correct change. # GREEDY # ervey time give the biggest change available class Solution(object): def lemonadeChange(self, bills): """ :type bills: List[int] :rtype: bool """ if not bills: return True # till = [0]*3 no need to record no. of 20s till = [0] * 2 for i in bills: if i == 5: till[0] += 1 elif i == 10: till[0] -= 1 till[1] += 1 elif i == 20: if till[1] == 0: till[0] -= 3 else: till[1] -= 1 till[0] -= 1 # till[2] += 1 if till[0] < 0 or till[1] < 0: return False return True
import { Attribute } from './attribute'; import { D3Node } from './node'; import { GravityPoint } from '../'; export interface View { _rev?: string; description?: string; links?: { [key: string]: ViewLink }; name?: string; userState?: ViewUserState; nodes?: { [key: string]: ViewNode }; url?: string; } export interface ViewUserState { autoConnectivity?: string; cascadingCollapse?: boolean; filters?: ViewUserStateFilters[]; forceChargeStrength?: number; forceGravityX?: number; forceGravityY?: number; forceLinkDistance?: number; forceLinkStrength?: number; forceVelocityDecay?: number; gravityPoints?: { [key: string]: GravityPoint; }; linkType?: string; runSimulation?: boolean; scale?: number; showLinkLabels?: boolean; showNodeLabels?: boolean; traverseDepth?: number; treeMode?: boolean; } export interface ViewUserStateFilters { attributes?: Array<Attribute>; types?: { [key: string]: boolean }; } export interface ViewNav { 'date-slider': Number; scale: String; 'show-node-label': Boolean; } export interface ViewNode { collapsed?: boolean; collapsedAutomatically?: boolean; fx?: number; fy?: number; gravityPoint?: string; hidden?: boolean; x?: number; y?: number; } export interface ViewLink { originalSource?: string; originalTarget?: string; source?: string; target?: string; } export interface Views { data: View[]; } export interface ViewNav { 'date-slider': Number; scale: String; 'show-node-label': Boolean; } export interface Views { data: View[]; }
def olcnt(s): i = 0 lst = [] while i < len(s): j = 1 while i + j < len(s) and s[i] == s[i + j]: j += 1 lst.append((s[i], j)) i += j return lst s = list(input()) k = int(input()) if len(set(s)) == 1: print(int(len(s)*k/2)) else: cnt1 = sum([int(x[1]/2) for x in olcnt(s)]) cnt2 = sum([int(x[1]/2) for x in olcnt(s+s)]) print(cnt1 + (cnt2-cnt1)*(k-1))
/** * A reader-writer lock from "Java Threads" by Scott Oak and Henry Wong. * * @author Scott Oak and Henry Wong */ public class ReaderWriterLock { /** * A node for the waiting list. * * @author Scott Oak and Henry Wong */ private static class ReaderWriterNode { /** A reader. */ protected static final int READER = 0; /** A writer. */ protected static final int WRITER = 1; /** The thread. */ protected Thread t; /** The state. */ protected int state; /** The number of acquires.*/ protected int nAcquires; /** * Creates a new node. * * @param t the thread. * @param state the state. */ private ReaderWriterNode(final Thread t, final int state) { this.t = t; this.state = state; this.nAcquires = 0; } } /** The waiting threads. */ private ArrayList waiters; /** * Default constructor. */ public ReaderWriterLock() { this.waiters = new ArrayList(); } /** * Grab the read lock. */ public synchronized void lockRead() { final ReaderWriterNode node; final Thread me = Thread.currentThread(); final int index = getIndex(me); if (index == -1) { node = new ReaderWriterNode(me, ReaderWriterNode.READER); this.waiters.add(node); } else { node = (ReaderWriterNode) this.waiters.get(index); } while (getIndex(me) > firstWriter()) { try { wait(); } catch (Exception e) { System.err.println("ReaderWriterLock.lockRead(): exception."); System.err.print(e.getMessage()); } } node.nAcquires++; } /** * Grab the write lock. */ public synchronized void lockWrite() { final ReaderWriterNode node; final Thread me = Thread.currentThread(); final int index = getIndex(me); if (index == -1) { node = new ReaderWriterNode(me, ReaderWriterNode.WRITER); this.waiters.add(node); } else { node = (ReaderWriterNode) this.waiters.get(index); if (node.state == ReaderWriterNode.READER) { throw new IllegalArgumentException("Upgrade lock"); } node.state = ReaderWriterNode.WRITER; } while (getIndex(me) != 0) { try { wait(); } catch (Exception e) { System.err.println("ReaderWriterLock.lockWrite(): exception."); System.err.print(e.getMessage()); } } node.nAcquires++; } /** * Unlock. */ public synchronized void unlock() { final ReaderWriterNode node; final Thread me = Thread.currentThread(); final int index = getIndex(me); if (index > firstWriter()) { throw new IllegalArgumentException("Lock not held"); } node = (ReaderWriterNode) this.waiters.get(index); node.nAcquires--; if (node.nAcquires == 0) { this.waiters.remove(index); } notifyAll(); } /** * Returns the index of the first waiting writer. * * @return The index. */ private int firstWriter() { final Iterator e = this.waiters.iterator(); int index = 0; while (e.hasNext()) { final ReaderWriterNode node = (ReaderWriterNode) e.next(); if (node.state == ReaderWriterNode.WRITER) { return index; } index += 1; } return Integer.MAX_VALUE; } /** * Returns the index of a thread. * * @param t the thread. * * @return The index. */ private int getIndex(final Thread t) { final Iterator e = this.waiters.iterator(); int index = 0; while (e.hasNext()) { final ReaderWriterNode node = (ReaderWriterNode) e.next(); if (node.t == t) { return index; } index += 1; } return -1; } }
/** * Check file extension for containing in list of needless extensions. * @param fileName File name. * @param extensions List of files extensions. * @return True if file extension not contains in list of extensions. */ boolean checkExtension(String fileName, List<String> extensions) { boolean result = true; for (String extension : extensions) { if (fileName.endsWith(extension)) { result = false; break; } } return result; }
<reponame>shc0743/CLearn  // MFCLoginGUIDlg.cpp: 实现文件 // #include "pch.h" #include "framework.h" #include "MFCLoginGUI.h" #include "MFCLoginGUIDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif #include <fstream> #include "CDlgMainLoginBox.h" #include "user.h" #include "resource.h" // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CMFCLoginGUIDlg 对话框 CMFCLoginGUIDlg::CMFCLoginGUIDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_MFCLOGINGUI_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CMFCLoginGUIDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_TAB_MAIN, m_tabmain); DDX_Control(pDX, IDC_PROGRESS_MAIN, m_mprog); } BEGIN_MESSAGE_MAP(CMFCLoginGUIDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_CLOSE, &CMFCLoginGUIDlg::OnClickedButtonClose) ON_BN_CLICKED(IDC_BUTTON_EXITLOG, &CMFCLoginGUIDlg::OnBnClickedButtonExitlog) ON_BN_CLICKED(IDC_BUTTON_CHGEPW, &CMFCLoginGUIDlg::OnBnClickedButtonChgepw) ON_BN_CLICKED(IDC_BUTTON_MYINF, &CMFCLoginGUIDlg::OnBnClickedButtonMyinf) END_MESSAGE_MAP() // CMFCLoginGUIDlg 消息处理程序 LoginedUser MainUser; bool isinited = false; void CALLBACK TimerProcDlgMainInit(HWND hWnd, UINT nMsg, UINT_PTR nTimerid, DWORD dwTime) { if (isinited) return; isinited = true; std::wstring un = s2ws(MainUser.getUserName()); AfxGetApp()->m_pMainWnd/*->GetDlgItem(IDC_STATIC_WELNAME)*/->SetDlgItemText(IDC_STATIC_WELNAME, un.c_str()); } BOOL CMFCLoginGUIDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 using namespace std; SetWindowText(L"用户中心"); fstream userd; userd.open("users.data.pwd", ios::in | ios::binary); if (!userd) { userd.close(); if (MessageBox(L"users不存在,是否创建?", L"Login", MB_ICONQUESTION | MB_YESNO) == IDYES) { fstream userdcing; userdcing.open("users.data.pwd", ios::app | ios::binary); userud rootuser("root", "root"); userdcing.write((char*)&rootuser, sizeof(rootuser)); userdcing.close(); } else exit(-1); } if (userd) userd.close(); fstream luserd; luserd.open("login.user.pwd", ios::in | ios::binary); if (luserd) { luserd.read((char*)&MainUser, sizeof(MainUser)); luserd.close(); SetTimer(1487,500,TimerProcDlgMainInit); //TODO /*m_tabmain.InsertItem(0, "欢迎"); m_tabmain.InsertItem(1, "我的信息"); m_tabmain.InsertItem(2, "我的隐私"); m_tabmain.InsertItem(3, "我的密码"); m_welpage.Create (IDD_U_WELCOME,&m_tabmain); m_myinfomainbox.Create (IDD_U_MYINFO,&m_tabmain); CRect rect; m_tabmain.GetClientRect(&rect); rect.top += 20; rect.bottom -= 4; rect.left += 4; rect.right -= 4; m_welpage.MoveWindow(&rect); m_myinfomainbox.MoveWindow(&rect); m_welpage.ShowWindow(FALSE); m_myinfomainbox.ShowWindow(FALSE); m_welpage.SetWindowPos(NULL, rect.left, rect.top, rect.Width(), rect.Height(), SWP_SHOWWINDOW); m_tabmain.SetCurSel(0);*/ m_mprog.SetRange(0,100); m_mprog.SetPos(100); return true; } CDlgMainLoginBox lm; lm.DoModal(); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CMFCLoginGUIDlg::OnSysCommand(UINT nID, LPARAM lParam) { if (nID == SC_CLOSE) exit(0); if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CMFCLoginGUIDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CMFCLoginGUIDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CMFCLoginGUIDlg::OnClickedButtonClose() { // TODO: 在此添加控件通知处理程序代码 exit(0); } void CMFCLoginGUIDlg::OnBnClickedButtonExitlog() { // TODO: 在此添加控件通知处理程序代码 if (MessageBox(L"真的要退出登录吗?", L"提示", MB_YESNO | MB_ICONQUESTION) == IDNO) return; system("DEL /f /s /q login.user.pwd"); std::ostringstream oss; oss << "powershell Start-Process -FilePath " << ::ws2s(GetCommandLine()) << ""; system(oss.str().c_str()); exit(0); } #include "CDlgChangePwd.h" #include "CDlgMyInfo.h" void CMFCLoginGUIDlg::OnBnClickedButtonChgepw() { // TODO: 在此添加控件通知处理程序代码 CDlgChangePwd cd; cd.DoModal(); } void CMFCLoginGUIDlg::OnBnClickedButtonMyinf() { // TODO: 在此添加控件通知处理程序代码 CDlgMyInfo mi; this->ShowWindow(SW_HIDE); mi.SetDlgItemText(IDC_SHOW_UNAME,s2ws(MainUser.getUserName()).c_str()); mi.DoModal(); this->ShowWindow(SW_SHOW); }
Pamela Anderson has attacked Donald Trump during a speech in which she calls on people not to use pornography. The former Baywatch star - who recently wrote an opinion piece about porn for the Wall Street Journal - hit out at the Presidential candidate's comments about women. A recording emerged last week in which the Republican nominee bragged about being able to grope women because of his fame. Speaking to the Oxford Union, Anderson said: "It's terrible and I've heard other men speak that way, even about me, and it cannot be swept under the rug because how we deal with it - how he is ... it's not okay. "So I was completely offended, like everybody else, and I don't like the way he said it was just locker room behaviour because I don't believe that's true of the men who do speak that way. "It's got to stop, you've got to have respect for women, behind closed doors, around women and around men." The 49-year-old former Playmate was taking part in a joint event with American orthodox Rabbi and prolific author Shmuley Boteach. This proves Mr Trumps insane insensitivity. No woman in the universe will ever support him- #nevertrump https://t.co/id4FBzlFAi — Pamela Anderson (@pamfoundation) September 30, 2016 The unlikely duo are in the UK for a series of talks for an awareness campaign they are calling "Take The Pledge", advising people to be aware of the consequences of what they are exposing themselves to. She said she was aware her criticism of porn might seem hypocritical but that she was speaking out because "I am afraid that the world might forget how to make love". Talking about some of the material she had seen online, she told the packed chamber: "It is not fine to be slapped, called a whore and spat on - it's sick, it's hurtful, it's demeaning and it's terrible, terrible sex." Anderson has said she is working on a book called The Sensual Revolution about the increasing disconnection between sensuality and sexuality. On Friday, she was seen delivering a vegan lunch and a copy of designer Vivienne Westwood's diaries to Wikileaks founder Julian Assange at the Ecuadorian embassy. She has been a campaigner for animal rights for many years.
// GetSource returns the Source with the given ID func GetSource(node sqalx.Node, id string) (*Source, error) { if value, present := node.Load(getCacheKey("source", id)); present { return value.(*Source), nil } s := sdb.Select(). Where(sq.Eq{"id": id}) sources, err := getSourcesWithSelect(node, s) if err != nil { return nil, err } if len(sources) == 0 { return nil, errors.New("Source not found") } node.Store(getCacheKey("source", id), sources[0]) return sources[0], nil }
<reponame>krapnikkk/FairyGUI-createjs import { UISprite } from './display/UISprite' import { GObject } from './GObject' import { IColorGear } from './interface/IColorGear' import { StringUtil } from './utils/StringUtil' import { Utils } from './utils/Utils' import { XmlNode } from './utils/XMLParser' export class GGraph extends GObject implements IColorGear { private $type: number = 0 private $lineSize: number = 1 private $lineColor: string private $sides: number = 0 private $fillColor: string private $corner: number[] private $startAngle: number = 0 private $points: Array<number> = [] public constructor() { super() this.$lineSize = 1 this.$lineColor = '#000000' this.$fillColor = '#FFFFFF' } public drawRect(lineSize: number, lineColor: string, fillColor: string): void { this.$type = 1 this.$lineSize = lineSize this.$lineColor = lineColor this.$fillColor = fillColor this.drawGraph() } public drawEllipse(lineSize: number, lineColor: string, fillColor: string): void { this.$type = 2 this.$lineSize = lineSize this.$lineColor = lineColor this.$fillColor = fillColor this.drawGraph() } public get color(): string { return this.$fillColor } public set color(value: string) { this.$fillColor = value if (this.$type != 0) this.drawGraph() } private drawGraph(): void { let shape: createjs.Shape = this.$displayObject as createjs.Shape let g: createjs.Graphics = shape.graphics g.clear() let w: number = this.width let h: number = this.height if (w == 0 || h == 0) return g.beginStroke(this.$lineColor) if (this.$lineSize == 0) { g.setStrokeStyle(0.1) // see https://github.com/CreateJS/EaselJS/issues/734 } else { g.setStrokeStyle(this.$lineSize) w -= this.$lineSize h -= this.$lineSize } g.beginFill(this.$fillColor) if (this.$type == 1) { if (this.$corner && this.$corner.length >= 1) { if (this.$corner.length == 1) { g.drawRoundRect(this.$lineSize / 2, this.$lineSize / 2, w, h, this.$corner[0]) } else { g.drawRoundRectComplex( this.$lineSize / 2, this.$lineSize / 2, w, h, this.$corner[0], this.$corner[1], this.$corner[3], this.$corner[2] ) } } else { g.drawRect(this.$lineSize / 2, this.$lineSize / 2, w, h) } } else if (this.$type == 2) { let halfW: number = w * 0.5 if (w == h) g.drawCircle(halfW + this.$lineSize / 2, halfW + this.$lineSize / 2, halfW) else { w = w - this.$lineSize h = h - this.$lineSize g.drawEllipse(this.$lineSize / 2, this.$lineSize / 2, w, h) } } else if (this.$type == 3) { let radius = w > h ? w / 2 : h / 2 g.drawPolyStar(0 + radius, 0 + radius, radius, this.$sides, 0, this.$startAngle) } else if (this.$type == 4) { Utils.fillPath(g, this.$points, 0, 0) } g.endFill() shape.cache(0, 0, this.$width, this.$height) } public replaceMe(target: GObject): void { if (!this.$parent) throw new Error('parent not set') target.name = this.name target.alpha = this.alpha target.rotation = this.rotation target.visible = this.visible target.touchable = this.touchable target.grayed = this.grayed target.setXY(this.x, this.y) target.setSize(this.width, this.height) let index: number = this.$parent.getChildIndex(this) this.$parent.addChildAt(target, index) target.relations.copyFrom(this.relations) this.$parent.removeChild(this, true) } public addBeforeMe(target: GObject): void { if (this.$parent == null) throw new Error('parent not set') let index: number = this.$parent.getChildIndex(this) this.$parent.addChildAt(target, index) } public addAfterMe(target: GObject): void { if (this.$parent == null) throw new Error('parent not set') let index: number = this.$parent.getChildIndex(this) index++ this.$parent.addChildAt(target, index) } protected createDisplayObject(): void { this.$displayObject = new UISprite(this) this.$displayObject.mouseEnabled = true; } protected handleSizeChanged(): void { if (this.$type != 0) this.drawGraph() } public setupBeforeAdd(xml: XmlNode): void { super.setupBeforeAdd(xml) let type: string = xml.attributes.type if (type && type != 'empty') { let str: string str = xml.attributes.lineSize if (str) this.$lineSize = parseInt(str) let c: string str = xml.attributes.lineColor if (str) { c = StringUtil.convertToRGBA(str) this.$lineColor = c } str = xml.attributes.fillColor if (str) { c = StringUtil.convertToRGBA(str) this.$fillColor = c } let arr: string[] str = xml.attributes.corner if (str) { arr = str.split(',') if (arr.length > 1) this.$corner = [parseInt(arr[0]), parseInt(arr[1]), parseInt(arr[2]), parseInt(arr[3])] else this.$corner = [parseInt(arr[0])] } if (type == 'rect') { this.$type = 1 } else if (type == 'eclipse') { this.$type = 2 } else if (type == 'regular_polygon') { this.$type = 3 str = xml.attributes.sides if (str) { this.$sides = parseInt(str) } str = xml.attributes.startAngle if (str) { this.$startAngle = parseInt(str) } } else if (type == 'polygon') { this.$type = 4 str = xml.attributes.points if (str) { arr = str.split(',') this.$points = arr.map(point => { return parseInt(point) }) } } this.drawGraph() } } }
<reponame>huazhouwang/electrum package org.haobtc.onekey.event; /** * Created by 小米粒 on 2019/4/12. */ public class FirstEvent { //11 --> update wallet list //22 --> update transaction list //33 --> Whether the custom node is added successfully private String mMsg; public FirstEvent(String msg) { // TODO Auto-generated constructor stub mMsg = msg; } public String getMsg(){ return mMsg; } }
<gh_stars>1-10 // tslint:disable:no-expression-statement import test from 'ava'; import * as child_process from 'child_process'; import { echoChildProcessOutput } from './echo'; test('echo child process (expect two lines of output)', async t => { await t.notThrowsAsync(async () => { const child = child_process.spawn('bash', ['-c', 'echo answer 42']); echoChildProcessOutput(child); echoChildProcessOutput(child, { outPrefix: 'life, universe and everything:' }); echoChildProcessOutput(child, { echoStderr: false }); echoChildProcessOutput(child, { echoStdout: false }); echoChildProcessOutput(child); }); });
import { Post, modelManager, createData } from './models'; (async () => { await createData(); // Read all published posts, sorted by Title const postsByTitle = await modelManager.read(Post, { where: { published: true }, limit: 100, orderBy: ['title'] }); console.log('Posts by Title:', postsByTitle.results); // Read all posts, sorted by Title in descending order const postsByTitleDesc = await modelManager.read(Post, { limit: 100, orderBy: ['title desc'] }); console.log('Posts by Titie in descending order:', postsByTitleDesc.results); // Read the first 10 posts sorted by Rating, then by Title const top10Posts = await modelManager.read(Post, { limit: 10, orderBy: ['rating desc', 'title'] }); console.log('Top Posts:', top10Posts.results); })();
<filename>LuoGu/1525.cc /** * luogu 1525 * * binary check anwser * */ #include <iostream> #include <cstring> #include <cstdio> #include <algorithm> const int N = 2e4 + 5; const int M = 1e5 + 5; struct Edge { int next, to, val; } e[M * 2]; int head[N], color[N]; int n, m; void insert(int u, int v, int w) { static int ind = 0; e[++ind] = { head[u], v, w }; head[u] = ind; } bool dfs(int it, int val) { for (int i = head[it]; i; i = e[i].next) if (e[i].val >= val) { if (!color[e[i].to]) { color[e[i].to] = color[it] ^ 3; if (!dfs(e[i].to, val)) return false; } else if (color[it] == color[e[i].to]) { return false; } } return true; } bool check(int val) { std::fill(color + 1, color + 1 + n, 0); for (int i = 1; i <= n; ++i) if (!color[i]) { color[i] = 1; if (!dfs(i, val)) return false; } return true; } int main() { std::ios::sync_with_stdio(false); std::cin >> n >> m; int l = 0, r = 0; for (int i = 1, u, v, w; i <= m; ++i) { std::cin >> u >> v >> w; insert(u, v, w); insert(v, u, w); r = std::max(r, w); } while (l < r) { int mid = (l + r) >> 1; if (check(mid)) r = mid; else l = mid + 1; } std::cout << std::max(0, l - 1) << std::endl; return 0; }
#include<bits/stdc++.h> using namespace std; #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); typedef long long ll; const int maxn=1e6+10; #define mod 1000000007 int main(){ fast; int n,m; cin>>n>>m; vector<vector<int>> a(n,vector<int>(m,0)),sv; for(auto i=0;i<n;++i){ for(auto j=0;j<m;++j)cin>>a[i][j]; } int sum=0; sv=a; for(auto i=1;i<n-1;++i){ for(auto j=1;j<m-1;++j){ if(a[i][j]==0){ a[i][j]=max(a[i-1][j],a[i][j-1])+1; if(a[i][j]>=a[i][j+1]&&sv[i][j+1]!=0 || a[i][j]>=a[i+1][j]&&sv[i+1][j]!=0){ cout<<-1<<'\n'; return 0; } } } } for(auto i=n-2;i>=1;--i){ for(auto j=m-2;j>=1;--j){ if(sv[i][j]==0){ if(min(a[i+1][j],a[i][j+1])-1>=a[i][j]){ a[i][j]=min(a[i+1][j],a[i][j+1])-1; }else{ cout<<-1<<'\n'; return 0; } } } } for(auto i=0;i<n;++i){ for(auto j=0;j<m;++j){ sum+=a[i][j]; } } for(auto i=0;i<n;++i){ bool ok=1; for(auto j=1;j<m;++j){ ok&=(a[i][j]>a[i][j-1]); } if(!ok){ cout<<-1<<'\n'; return 0; } }for(auto i=0;i<m;++i){ bool ok=1; for(auto j=1;j<n;++j){ ok&=(a[j][i]>a[j-1][i]); } if(!ok){ cout<<-1<<'\n'; return 0; } } cout<<sum<<'\n'; return 0; } // combnatorics(pigeonhole principle, stars and bars (n+k-1)C(k-1)) // comparator in inbuilt sorting // lcs // period of a string(prefix-function) with KMP // prime func // subset production // factorization // modpow // modinv ( a^(p-2)=a^(-1) (mod p) ) // sieve // ncr // euler totien func (co prime divisiors upto n) // matrix exponentation(fast fibonacci) // dsu // Trees // Graphs(dfs,bfs,shortes path etc.) // DP-Recursion
import { Box, Button, Input, Modal } from "@artsy/palette" import { FormikActions } from "formik" import React from "react" import * as Yup from "yup" import { CreateSmsSecondFactorMutationResponse } from "__generated__/CreateSmsSecondFactorMutation.graphql" import { useSystemContext } from "Artsy" import { Step, Wizard } from "Components/Wizard" import { FormValues, StepElement } from "Components/Wizard/types" import { DeliverSecondFactor } from "./Mutation/DeliverSecondFactor" import { UpdateSmsSecondFactor } from "./Mutation/UpdateSmsSecondFactor" // TODO: Replace with ModalProps from artsy/palette // https://github.com/artsy/palette/blob/master/packages/palette/src/elements/Modal/Modal.tsx#L18 interface ModalProps { onClose: () => void show?: boolean title?: string forcedScroll?: boolean } interface SmsSecondFactorModalProps extends ModalProps { handleSubmit: (values: FormValues, actions: FormikActions<object>) => void secondFactor: CreateSmsSecondFactorMutationResponse["createSmsSecondFactor"]["secondFactorOrErrors"] } export const SmsSecondFactorModal: React.FC<SmsSecondFactorModalProps> = props => { const { secondFactor, handleSubmit } = props const { relayEnvironment } = useSystemContext() if (!secondFactor || secondFactor.__typename !== "SmsSecondFactor") { return null } const handleDeliver = async (event: React.FormEvent<any>, form: any) => { UpdateSmsSecondFactor(relayEnvironment, { secondFactorID: secondFactor.internalID, attributes: { phoneNumber: form.values.phoneNumber, countryCode: "US" }, }).then(updateResponse => { if ( updateResponse.updateSmsSecondFactor.secondFactorOrErrors.__typename === "Errors" ) { console.error(updateResponse.updateSmsSecondFactor.secondFactorOrErrors) } DeliverSecondFactor(relayEnvironment, { secondFactorID: secondFactor.internalID, }).then(deliverResponse => { if ( deliverResponse.deliverSecondFactor.secondFactorOrErrors .__typename === "Errors" ) { console.error( deliverResponse.deliverSecondFactor.secondFactorOrErrors ) } }) }) } const steps: StepElement[] = [ <Step label="Name" validationSchema={Yup.object().shape({ phoneNumber: Yup.string().required("Enter your phone number"), })} > {({ form, wizard }) => ( <Box> <Input autoComplete="off" name="phoneNumber" error={form.touched.phoneNumber && form.errors.phoneNumber} value={form.values.phoneNumber} onBlur={form.handleBlur} placeholder="+1 (555) 123-7878" onChange={form.handleChange} title="Phone Number" /> <Button mt={1} onClick={event => handleDeliver(event, form)}> Continue </Button> </Box> )} </Step>, <Step label="Terms" validationSchema={Yup.object().shape({ code: Yup.string().required("Enter a code"), })} > {({ form, wizard }) => ( <Box> <Input error={form.touched.code && form.errors.code} onBlur={form.handleBlur} autoComplete="off" name="code" value={form.values.code} onChange={form.handleChange} title="Authentication Code" /> <Button mt={1} onClick={form.handleSubmit}> Finish </Button> <Button ml={1} variant="secondaryGray" mt={1} onClick={wizard.previous} > Back </Button> </Box> )} </Step>, ] return ( <Modal forcedScroll={false} title="Enable 2FA" show={props.show} onClose={props.onClose} > <Wizard onComplete={handleSubmit} steps={steps}> {wizardProps => { const { wizard } = wizardProps const { currentStep } = wizard return <Box>{currentStep}</Box> }} </Wizard> </Modal> ) }
// // Function: cmdLineValidate // // Validate a single command line for use in a command list and, if needed, // add or find a program counter control block and associate it with the // command line. // Return values: // -1 : invalid command // 0 : success (with valid command or only white space without command) // >0 : starting line number of block in which command cannot be matched // static int cmdLineValidate(cmdPcCtrl_t **cmdPcCtrlLast, cmdPcCtrl_t **cmdPcCtrlRoot, cmdLine_t *cmdLine) { int lineNumErr = 0; cmdCommand_t *cmdCommand; char *input; u08 retVal; input = cmdLine->input; retVal = cmdArgInit(&input, cmdLine); if (retVal != CMD_RET_OK) return -1; if (cmdLine->cmdCommand == NULL) return 0; cmdCommand = cmdLine->cmdCommand; if (cmdCommand->cmdPcCtrlType != PC_CONTINUE) { if (cmdCommand->cmdPcCtrlType == PC_REPEAT_NEXT) { lineNumErr = cmdPcCtrlLink(*cmdPcCtrlLast, cmdLine); } else if (cmdCommand->cmdPcCtrlType == PC_REPEAT_FOR) { *cmdPcCtrlLast = cmdPcCtrlCreate(*cmdPcCtrlLast, cmdPcCtrlRoot, cmdLine); } else if (cmdCommand->cmdPcCtrlType == PC_IF_ELSE_IF) { lineNumErr = cmdPcCtrlLink(*cmdPcCtrlLast, cmdLine); if (lineNumErr == 0) *cmdPcCtrlLast = cmdPcCtrlCreate(*cmdPcCtrlLast, cmdPcCtrlRoot, cmdLine); } else if (cmdCommand->cmdPcCtrlType == PC_IF_END) { lineNumErr = cmdPcCtrlLink(*cmdPcCtrlLast, cmdLine); } else if (cmdCommand->cmdPcCtrlType == PC_IF_ELSE) { lineNumErr = cmdPcCtrlLink(*cmdPcCtrlLast, cmdLine); if (lineNumErr == 0) *cmdPcCtrlLast = cmdPcCtrlCreate(*cmdPcCtrlLast, cmdPcCtrlRoot, cmdLine); } else if (cmdCommand->cmdPcCtrlType == PC_IF) { *cmdPcCtrlLast = cmdPcCtrlCreate(*cmdPcCtrlLast, cmdPcCtrlRoot, cmdLine); } } return lineNumErr; }
<reponame>TheArtistGuy/scion use std::ops::Range; use wgpu::util::BufferInitDescriptor; use crate::{ core::components::{material::Material, maths::coordinates::Coordinates}, rendering::{gl_representations::TexturedGlVertex, scion2d::Renderable2D}, }; const INDICES: &[u16] = &[0, 1, 3, 3, 1, 2]; /// Renderable 2D Rectangle. pub struct Rectangle { pub vertices: [Coordinates; 4], pub uvs: Option<[Coordinates; 4]>, contents: [TexturedGlVertex; 4], } impl Rectangle { pub fn new(length: f32, height: f32, uvs: Option<[Coordinates; 4]>) -> Self { let a = Coordinates::new(0., 0.); let b = Coordinates::new(a.x(), a.y() + height); let c = Coordinates::new(a.x() + length, a.y() + height); let d = Coordinates::new(a.x() + length, a.y()); let uvs_ref = uvs.unwrap_or(default_uvs()); let contents = [ TexturedGlVertex::from((&a, &uvs_ref[0])), TexturedGlVertex::from((&b, &uvs_ref[1])), TexturedGlVertex::from((&c, &uvs_ref[2])), TexturedGlVertex::from((&d, &uvs_ref[3])), ]; Self { vertices: [a, b, c, d], uvs, contents } } } fn default_uvs() -> [Coordinates; 4] { [ Coordinates::new(0., 0.), Coordinates::new(0., 1.), Coordinates::new(1., 1.), Coordinates::new(1., 0.), ] } impl Renderable2D for Rectangle { fn vertex_buffer_descriptor(&mut self, _material: Option<&Material>) -> BufferInitDescriptor { wgpu::util::BufferInitDescriptor { label: Some("Rectangle Vertex Buffer"), contents: bytemuck::cast_slice(&self.contents), usage: wgpu::BufferUsage::VERTEX, } } fn indexes_buffer_descriptor(&self) -> BufferInitDescriptor { wgpu::util::BufferInitDescriptor { label: Some("Rectangle Index Buffer"), contents: bytemuck::cast_slice(&INDICES), usage: wgpu::BufferUsage::INDEX, } } fn range(&self) -> Range<u32> { 0..INDICES.len() as u32 } fn dirty(&self) -> bool { false } fn set_dirty(&mut self, _is_dirty: bool) {} }
// ********************************************************************* // Count the number of bits set // ********************************************************************* inline uint32_t udCountBits32(uint32_t v) { v = v - ((v >> 1) & 0x55555555); v = (v & 0x33333333) + ((v >> 2) & 0x33333333); return (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; }
// Function createJobObject creates a new job object. func createJobObject(jobAttrs *syscall.SecurityAttributes, name *uint16) (handle syscall.Handle, err error) { r1, _, e1 := CreateJobObjectW.Call( uintptr(unsafe.Pointer(jobAttrs)), uintptr(unsafe.Pointer(name))) handle = syscall.Handle(r1) if handle == 0 { if e1 != nil { err = error(e1) } else { err = syscall.EINVAL } } return }
import math def getSeq(n, g, b): need = math.ceil(n/2) d = math.ceil(need/g)-1 td = d*(g+b) td += need-d*g return max(td, n) T = int(input()) for i in range(T): n, g, b = list(map(int, input().split())) print(getSeq(n, g, b))