content
stringlengths
10
4.9M
Treatment of leber congenital amaurosis due to RPE65 mutations by ocular subretinal injection of adeno-associated virus gene vector: short-term results of a phase I trial. Leber congenital amaurosis (LCA) is a group of autosomal recessive blinding retinal diseases that are incurable. One molecular form is caused by mutations in the RPE65 (retinal pigment epithelium-specific 65-kDa) gene. A recombinant adeno-associated virus serotype 2 (rAAV2) vector, altered to carry the human RPE65 gene (rAAV2-CBSB-hRPE65), restored vision in animal models with RPE65 deficiency. A clinical trial was designed to assess the safety of rAAV2-CBSB-hRPE65 in subjects with RPE65-LCA. Three young adults (ages 21-24 years) with RPE65-LCA received a uniocular subretinal injection of 5.96 x 10(10) vector genomes in 150 microl and were studied with follow-up examinations for 90 days. Ocular safety, the primary outcome, was assessed by clinical eye examination. Visual function was measured by visual acuity and dark-adapted full-field sensitivity testing (FST); central retinal structure was monitored by optical coherence tomography (OCT). Neither vector-related serious adverse events nor systemic toxicities were detected. Visual acuity was not significantly different from baseline; one patient showed retinal thinning at the fovea by OCT. All patients self-reported increased visual sensitivity in the study eye compared with their control eye, especially noticeable under reduced ambient light conditions. The dark-adapted FST results were compared between baseline and 30-90 days after treatment. For study eyes, sensitivity increases from mean baseline were highly significant (p < 0.001); whereas, for control eyes, sensitivity changes were not significant (p = 0.99). Comparisons are drawn between the present work and two other studies of ocular gene therapy for RPE65-LCA that were carried out contemporaneously and reported.
import { Injectable } from '@angular/core'; import { DefaultBinaryConverter, DefaultStringConverter } from '@diplomatiq/convertibles'; import { RegisterUserV1RequestPasswordStretchingAlgorithmEnum } from '../../openapi/api'; import { ApiService } from './api.service'; import { CryptoService } from './crypto.service'; import { SrpService } from './srp.service'; @Injectable({ providedIn: 'root', }) export class SignupService { private readonly binaryConverter = new DefaultBinaryConverter(); private readonly stringConverter = new DefaultStringConverter(); private lastSignupEmailAddress?: string; public constructor( private readonly cryptoService: CryptoService, private readonly srpService: SrpService, private readonly apiService: ApiService, ) {} public async signup(emailAddress: string, password: string, firstName: string, lastName: string): Promise<void> { const saltBytes = await this.cryptoService.randomGenerator.bytes(32); const saltHex = this.binaryConverter.encodeToHex(saltBytes); const passwordBytes = this.stringConverter.encodeToBytes(password); const passwordScryptBytes = await this.cryptoService.scrypt(passwordBytes, saltBytes); const passwordScryptHex = this.binaryConverter.encodeToHex(passwordScryptBytes); const verifierHex = this.srpService.createVerifier(emailAddress, passwordScryptHex, saltHex); await this.apiService.unauthenticatedMethodsApi.registerUserV1({ registerUserV1Request: { emailAddress, firstName, lastName, srpSaltHex: saltHex, srpVerifierHex: verifierHex, passwordStretchingAlgorithm: RegisterUserV1RequestPasswordStretchingAlgorithmEnum.ScryptV1, }, }); this.setValidationEmailAddress(emailAddress); } public setValidationEmailAddress(emailAddress: string): void { this.lastSignupEmailAddress = emailAddress; } public flushValidationEmailAddress(): string | undefined { const emailAddress = this.lastSignupEmailAddress; this.lastSignupEmailAddress = undefined; return emailAddress; } }
/** * Add a new event to the google calendar and redirect to events page. * * @param calendarEvent * @return */ @PostMapping("/events") public String addNewEvent(@ModelAttribute CalendarEvent calendarEvent, Model model) { try { logger.info("Adding a new calendar event"); calendarService.createNewEvent(calendarEvent); return CommonUtil.REDIRECT_TO_EVENTS_PAGE; } catch (Exception e) { logger.error("Exception occured when adding new event. {}", e); model.addAttribute(CommonUtil.ERROR, e.getMessage()); return CommonUtil.ERROR; } }
<filename>src/webparts/vikingTrainingSimulator/models/IUnit.ts export interface IUnit { id: string; firstName: string; lastName: string; xp: number; level: number; rank: string; dead: boolean; }
import * as mongoose from 'mongoose'; import { IS3File, IS3FilePublic, S3FileSchema } from '../../types/scheme'; import { DaoIds, DaoModelNames } from '../../types/constants'; import { IUserDocument } from '../../users/schemas/user.schema'; import { ITokenCollectionDocument } from '../../tokenCollections/schemas/token-collection.schema'; import { ISchemaQuery, schemaCreator } from '../../helpers/schema-creator'; import { ICategoryDocument } from '../../categories/schemas/categories.schema'; import { ICardSaleDocument } from '../../cardSales/schemas/card-sales.schema'; import { EIP } from '../../config/types/constants'; export interface IFileCard { original: IS3File | null; preview?: IS3File; } export interface IFilePublicCard { original: IS3FilePublic; preview: IS3FilePublic; } export interface IPropertyCard { property: string; value: string; } export interface IBalanceCard { balanceId: string; tokenAmount: number; userId: mongoose.Schema.Types.ObjectId | IUserDocument | string; user?: mongoose.VirtualType | mongoose.Schema.Types.ObjectId | IUserDocument; ethAddress: string; } export interface ICardDocument extends mongoose.Document { tokenId: string; eipVersion: EIP; identifier: number; uri: string | null; totalSupply: number; creator: mongoose.Schema.Types.ObjectId | IUserDocument | string; balances: IBalanceCard[]; hasSale: boolean; tokenCollectionId: mongoose.Schema.Types.ObjectId | ITokenCollectionDocument | string; tokenCollection?: mongoose.VirtualType | mongoose.Schema.Types.ObjectId | ITokenCollectionDocument; categoryId?: mongoose.Schema.Types.ObjectId | ICategoryDocument | string | null; category?: mongoose.VirtualType | mongoose.Schema.Types.ObjectId | ICategoryDocument; name: string | null; file: IFileCard; filePublic?: mongoose.VirtualType | IFilePublicCard; preview?: mongoose.VirtualType | IS3File; isPrivate?: boolean; description?: string; properties?: Array<IPropertyCard>; lockedData?: string; sales?: mongoose.VirtualType | Array<ICardSaleDocument>; viewersCount?: number; likes?: mongoose.Types.ObjectId[] | string[]; dislikes?: mongoose.Types.ObjectId[] | string[]; } export type ICardLeanDocument = mongoose.LeanDocument<ICardDocument>; export type ICardQuery<T> = ISchemaQuery<T, ICardDocument>; const FileSchema = new mongoose.Schema({ original: { type: S3FileSchema, default: null }, preview: S3FileSchema }); const PropertySchema = new mongoose.Schema({ property: { type: String, required: true }, value: { type: mongoose.Schema.Types.Mixed, required: true } }); const BalanceSchema = new mongoose.Schema({ balanceId: { type: String, required: true }, tokenAmount: { type: Number, required: true }, userId: { type: mongoose.Schema.Types.ObjectId, ref: DaoModelNames.user, alias: 'user', required: true }, ethAddress: { type: String, required: true } }); const Schema = schemaCreator( { tokenId: { type: String, required: true, unique: true, }, eipVersion: { type: String, enum: Object.values(EIP), required: true }, identifier: { type: Number, required: true }, uri: { type: String, default: null }, totalSupply: { type: Number, required: true }, creator: { type: mongoose.Schema.Types.ObjectId, ref: DaoModelNames.user, required: true }, balances: { type: [BalanceSchema], required: true }, hasSale: { type: Boolean, required: true, default: false }, tokenCollectionId: { type: mongoose.Schema.Types.ObjectId, ref: DaoModelNames.tokenCollection, required: true, alias: 'tokenCollection' }, categoryId: { type: mongoose.Schema.Types.ObjectId, ref: DaoModelNames.category, alias: 'category', default: null }, name: { type: String, default: null, index: { text: true } }, file: { type: FileSchema, required: true }, isPrivate: { type: Boolean, default: false }, description: String, properties: [PropertySchema], lockedData: { type: String, default: null }, viewersCount: { type: Number, default: 0 }, likes: { type: [mongoose.Schema.Types.ObjectId], ref: DaoModelNames.user, default: [] }, dislikes: { type: [mongoose.Schema.Types.ObjectId], ref: DaoModelNames.user, default: [] } }, { collection: DaoIds.cards } ); Schema.virtual('preview').get(function () { return this.file?.preview || this.file?.original; }); Schema.virtual('filePublic').get(function () { if (!this.file) { return { original: {}, preview: {} }; } const { original, preview } = this.file; return { original: { key: original.key, location: original.location, bucket: original.bucket, extension: original.extension, mimetype: original.mimetype, }, preview: { key: preview?.key, location: preview?.location, bucket: preview?.bucket, extension: preview?.extension, mimetype: preview?.mimetype, } }; }); Schema.virtual('sales', { ref: DaoModelNames.cardSale, localField: '_id', foreignField: 'cardId', justOne: false }); Schema.set('toObject', { virtuals: true }); Schema.set('toJSON', { virtuals: true }); export const CardSchema = Schema;
def _construct_partial_parser(self): if hasattr(self._commands.get(self._command), Application.OPTIONS_ATTR): return self.command_parser(self._command) else: return self._main_parser().values(copy.deepcopy(self._option_values))
Influence of the Level of Renal Insufficiency on Endoscopic Changes in the Upper Gastrointestinal Tract Aim:Lesions of the gastrointestinal tract are frequent finding in uremic patients but their actual nature is not completely clear. The aim of this study was to detect any correlation between endoscopic lesions of patients with different levels of renal insufficiency. Methods:This prospective study involved 244 cases, with dyspeptic difficulties including 124 patients in different stages of renal insufficiency, and a control group of 120 patients with normal renal function. Upper esophagogastroscopy was performed in all patients because of the appearance of dyspeptic difficulties. Helicobacter pylori infection was detected by the urease test. Results:H. pylori infection (P = 0.009), gastric erosions (P = 0.019), gastric ulcer (P = 0.002), and duodenal ulcer (P < 0.001) were more common in the control group of patients. Significant negative correlations were found between the level of renal insufficiency and H. pylori infection (Kendall’s &tgr; = −0.346; P = 0.003), stomach erosions (Kendall’s &tgr; = −0.272; P = 0.019), stomach ulcer (Kendall’s &tgr; = −0.347; P = 0.003), and duodenal ulcer (Kendall’s &tgr; = −0.531; P < 0.001). Conclusions:In patients with end stage renal disease, endoscopic lesions of the gastrointestinal tract are detected less frequently in relation to patients without kidney disease.
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0. //! Implementations of [Codec] for stdlib types. use crate::Codec; impl Codec for () { fn codec_name() -> &'static str { "()" } fn size_hint(&self) -> usize { 0 } fn encode<E: for<'a> Extend<&'a u8>>(&self, _buf: &mut E) { // No-op. } fn decode<'a>(buf: &'a [u8]) -> Result<Self, String> { if !buf.is_empty() { return Err(format!("decode expected empty buf got {} bytes", buf.len())); } Ok(()) } } impl Codec for String { fn codec_name() -> &'static str { "String" } fn size_hint(&self) -> usize { self.as_bytes().len() } fn encode<E: for<'a> Extend<&'a u8>>(&self, buf: &mut E) { buf.extend(self.as_bytes()) } fn decode<'a>(buf: &'a [u8]) -> Result<Self, String> { String::from_utf8(buf.to_owned()).map_err(|err| err.to_string()) } } impl Codec for Vec<u8> { fn codec_name() -> &'static str { "Vec<u8>" } fn size_hint(&self) -> usize { self.len() } fn encode<E: for<'a> Extend<&'a u8>>(&self, buf: &mut E) { buf.extend(self) } fn decode<'a>(buf: &'a [u8]) -> Result<Self, String> { Ok(buf.to_owned()) } }
IRST: a key system in modern warfare A naval infra red search and track (IRST) system is a passive surveillance device capable of detecting and tracking air and surface threats in the region where electromagnetic sensors are less efficient, typically within a few degrees around the horizon. The evolution in anti ship sea skimming missiles performances has outlined the benefit that can be gained from infrared systems in ship self-defense. The complementary nature of radar and IRST systems can also be exploited to full advantage in the field of multisensor data fusion. The combined use of radar and infrared secures the detection by redundancy of data; it substantially enhances target tracking, classification and identification and reduces the combat system's reaction time. Designing an IRST implies matching technical choices with operational requirements, and this under increasingly stringent cost constraints. This paper first reminds the benefits that can be obtained with an IRST system in the context of modern naval warfare, then retraces the evolutions from the first generation IRST systems, such as VAMPIR, to the second-generation systems now entering service. A general presentation of the current SAGEM SA IRST family is also made for naval, air and ground-based applications.
<gh_stars>0 package main import ( "fmt" "os" "github.com/gobwas/glob" ) type GlobFilter struct { include []glob.Glob exclude []glob.Glob } func NewGlobFilter(includePatterns, excludePatterns []string) (GlobFilter, error) { var globFilter GlobFilter for _, p := range includePatterns { g, err := glob.Compile(p, os.PathSeparator) if err != nil { return globFilter, fmt.Errorf("bad include pattern: %s", p) } globFilter.include = append(globFilter.include, g) } for _, p := range excludePatterns { g, err := glob.Compile(p, os.PathSeparator) if err != nil { return globFilter, fmt.Errorf("bad exclude pattern: %s", p) } globFilter.exclude = append(globFilter.exclude, g) } return globFilter, nil } // Match return true if path doesn't matches any exclude pattern and matches any include pattern (if there include patterns) func (f GlobFilter) Match(path string) bool { if matchAnyPattern(f.exclude, path) { return false } if len(f.include) != 0 && !matchAnyPattern(f.include, path) { return false } return true } func matchAnyPattern(globs []glob.Glob, filePath string) bool { for _, g := range globs { if g.Match(filePath) { return true } } return false }
Jesus’ apostles and other followers are clad in chic gray street wear and tumble and slide across the stage with impressive athleticism in the show’s opening minutes, presumably in flight from their black-leather-clad oppressors. The daily countdown to the Crucifixion is displayed on an electronic ticker of the kind that snakes around buildings in Times Square. This is a story for all times, the production asserts, if not for all tastes. It arrives with much of its original Canadian cast intact. The standout performance comes from Josh Young as a vocally lustrous and charismatic Judas Iscariot, well known for betraying his onetime mentor with a fatal kiss. In Mr. McAnuff’s production that kiss is particularly fraught, since the show trains a subtle focus on the tense triangle among its three central characters — Jesus, Judas and Mary Magdalene (Chilina Kennedy). Photo Mr. Young’s Judas sings repeatedly of his disappointment at Jesus’ betrayal of his ideals. But the hungry looks Judas repeatedly casts suggest that sexual jealousy plays no small role in his decision to turn the object of his agonized affection over to the Roman rulers, to whom this “King of the Jews” is a prickly thorn in the side. Mr. McAnuff’s staging is rich in portentous looks, actually. Mr. Nolan’s serenely suffering Jesus is often to be found at or near the lip of the stage, peering into the middle distance with his piercing blue eyes, as if stoically watching his destiny unfolding on an HDTV screen at the back of the theater. Ms. Kennedy sometimes joins him in this pastime, as do some members of the chorus. If a musical were to be judged by the amount of time its characters spent gazing meaningfully into the audience, this production would be trumps. Vocally it is impressive. Mr. Young’s voice is rangy, powerful and pure. Ms. Kennedy performs her solo, the onetime pop hit “I Don’t Know How to Love Him,” with a graceful simplicity, although her Mary Magdalene tends to be overshadowed throughout by the more intense histrionics of Mr. Young’s conniving Judas. Mr. Nolan manages the murderous tessitura of the climactic “Gethsemane” number with impressive aplomb. Newsletter Sign Up Continue reading the main story Please verify you're not a robot by clicking the box. Invalid email address. Please re-enter. You must select a newsletter to subscribe to. Sign Up You will receive emails containing news content , updates and promotions from The New York Times. You may opt-out at any time. You agree to receive occasional updates and special offers for The New York Times's products and services. Thank you for subscribing. An error has occurred. Please try again later. View all New York Times newsletters. But even during this highly dramatic passage, I found myself wincing at Mr. Rice’s lyrics: “Show me there’s a reason for your wanting me to die,” Jesus sings, “You’re far too keen on where and how but not so hot on why.” (Not so hot, that.) The agonies of Jesus are terrible to behold, of course, but on a far more trivial level one of the agonies of “Jesus Christ Superstar” is the unhappy combination of Mr. Lloyd Webber’s stick-in-your-head melodies and the often flat-footed lyrics they are wedded to. In 1971, when the show was first produced on Broadway, Mr. Rice’s slangy libretto presumably struck a with-it note that now hits the ear — well, my ear at least — as distinctly silly. Speaking of which, the musical’s one overtly comic number, in which Herod, played with lascivious glee by Bruce Dow, taunts Jesus with mocking references to his spiritual powers (“Prove to me that you’re no fool/Walk across my swimming pool”) isn’t really the camp highlight of the production. Nor does Tom Hewitt, got up in a louche purple velvet suit as Pontius Pilate, pour on the villainy in lavish doses. No, the kitsch apotheosis is surely the garish scene in which Jesus chases the money lenders from the temple. Here Mr. McAnuff dresses the chorus in the costume designer Paul Tazewell’s leather harnesses and gold hot pants (that’s the men) and slinky minidresses. As Jesus throws his temper tantrum, the dancers gyrate suggestively on metallic risers, performing Lisa Shriver’s choreography, which is a liability from start to finish and could be transplanted wholesale into a Britney Spears concert. Advertisement Continue reading the main story The effect is of a mildly naughty floor show at Caesars Palace. And in fact Las Vegas, where Mr. McAnuff’s “Jersey Boys” has recently reopened, might be the ideal destination for this slick production of a show that turns martyrdom into a splashy pop spectacle. Nothing like witnessing a Crucifixion to whet your appetite for the slot machines.
class YeelightScanner: """Scan for Yeelight devices.""" _scanner = None @classmethod @callback def async_get(cls, hass: HomeAssistant): """Get scanner instance.""" if cls._scanner is None: cls._scanner = cls(hass) return cls._scanner def __init__(self, hass: HomeAssistant) -> None: """Initialize class.""" self._hass = hass self._host_discovered_events = {} self._unique_id_capabilities = {} self._host_capabilities = {} self._track_interval = None self._listeners = [] self._connected_events = [] async def async_setup(self): """Set up the scanner.""" if self._connected_events: await self._async_wait_connected() return for idx, source_ip in enumerate(await self._async_build_source_set()): self._connected_events.append(asyncio.Event()) def _wrap_async_connected_idx(idx): """Create a function to capture the idx cell variable.""" async def _async_connected(): self._connected_events[idx].set() return _async_connected source = (str(source_ip), 0) self._listeners.append( SsdpSearchListener( async_callback=self._async_process_entry, service_type=SSDP_ST, target=SSDP_TARGET, source=source, async_connect_callback=_wrap_async_connected_idx(idx), ) ) results = await asyncio.gather( *(listener.async_start() for listener in self._listeners), return_exceptions=True, ) failed_listeners = [] for idx, result in enumerate(results): if not isinstance(result, Exception): continue _LOGGER.warning( "Failed to setup listener for %s: %s", self._listeners[idx].source, result, ) failed_listeners.append(self._listeners[idx]) self._connected_events[idx].set() for listener in failed_listeners: self._listeners.remove(listener) await self._async_wait_connected() self._track_interval = async_track_time_interval( self._hass, self.async_scan, DISCOVERY_INTERVAL ) self.async_scan() async def _async_wait_connected(self): """Wait for the listeners to be up and connected.""" await asyncio.gather(*(event.wait() for event in self._connected_events)) async def _async_build_source_set(self) -> set[IPv4Address]: """Build the list of ssdp sources.""" adapters = await network.async_get_adapters(self._hass) sources: set[IPv4Address] = set() if network.async_only_default_interface_enabled(adapters): sources.add(IPv4Address("0.0.0.0")) return sources return { source_ip for source_ip in await network.async_get_enabled_source_ips(self._hass) if not source_ip.is_loopback and not isinstance(source_ip, IPv6Address) } async def async_discover(self): """Discover bulbs.""" _LOGGER.debug("Yeelight discover with interval %s", DISCOVERY_SEARCH_INTERVAL) await self.async_setup() for _ in range(DISCOVERY_ATTEMPTS): self.async_scan() await asyncio.sleep(DISCOVERY_SEARCH_INTERVAL.total_seconds()) return self._unique_id_capabilities.values() @callback def async_scan(self, *_): """Send discovery packets.""" _LOGGER.debug("Yeelight scanning") for listener in self._listeners: listener.async_search() async def async_get_capabilities(self, host): """Get capabilities via SSDP.""" if host in self._host_capabilities: return self._host_capabilities[host] host_event = asyncio.Event() self._host_discovered_events.setdefault(host, []).append(host_event) await self.async_setup() for listener in self._listeners: listener.async_search((host, SSDP_TARGET[1])) with contextlib.suppress(asyncio.TimeoutError): await asyncio.wait_for(host_event.wait(), timeout=DISCOVERY_TIMEOUT) self._host_discovered_events[host].remove(host_event) return self._host_capabilities.get(host) def _async_discovered_by_ssdp(self, response): @callback def _async_start_flow(*_): asyncio.create_task( self._hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_SSDP}, data=ssdp.SsdpServiceInfo( ssdp_usn="", ssdp_st=SSDP_ST, ssdp_headers=response, upnp={}, ), ) ) # Delay starting the flow in case the discovery is the result # of another discovery async_call_later(self._hass, 1, _async_start_flow) async def _async_process_entry(self, headers: SsdpHeaders): """Process a discovery.""" _LOGGER.debug("Discovered via SSDP: %s", headers) unique_id = headers["id"] host = urlparse(headers["location"]).hostname current_entry = self._unique_id_capabilities.get(unique_id) # Make sure we handle ip changes if not current_entry or host != urlparse(current_entry["location"]).hostname: _LOGGER.debug("Yeelight discovered with %s", headers) self._async_discovered_by_ssdp(headers) self._host_capabilities[host] = headers self._unique_id_capabilities[unique_id] = headers for event in self._host_discovered_events.get(host, []): event.set()
<filename>src/Middleware/Drapo/js/DrapoDrag.d.ts declare class DrapoDrag { private _code; private _action; private _contextItem; private _tags; private _notify; private _onBefore; private _onAfter; private _dataKey; private _sector; private _custom; get Code(): string; set Code(value: string); get Action(): string; set Action(value: string); get Item(): DrapoContextItem; set Item(value: DrapoContextItem); get Tags(): string[]; set Tags(value: string[]); get Notify(): boolean; set Notify(value: boolean); get OnBefore(): string; set OnBefore(value: string); get OnAfter(): string; set OnAfter(value: string); get DataKey(): string; set DataKey(value: string); get Sector(): string; set Sector(value: string); get Custom(): string; set Custom(value: string); constructor(); IsMatch(tags: string[]): boolean; }
use indoc::indoc; use migration_core::json_rpc::types::*; use migration_engine_tests::test_api::*; use std::fmt::Write as _; // We need to test this specifically for mysql, because foreign keys are indexes, and they are // inferred as both foreign key and index by the sql-schema-describer. We do not want to // create/delete a second index. #[test_connector(tags(Mysql), exclude(Vitess))] fn indexes_on_foreign_key_fields_are_not_created_twice(api: TestApi) { let schema = r#" model Human { id String @id catname String cat_rel Cat @relation(fields: [catname], references: [name]) } model Cat { id String @id name String @unique humans Human[] } "#; api.schema_push_w_datasource(schema).send(); let sql_schema = api .assert_schema() .assert_table("Human", |table| { table .assert_foreign_keys_count(1) .assert_fk_on_columns(&["catname"], |fk| fk.assert_references("Cat", &["name"])) .assert_indexes_count(1) .assert_index_on_columns(&["catname"], |idx| idx.assert_is_not_unique()) }) .into_schema(); // Test that after introspection, we do not migrate further. api.schema_push_w_datasource(schema) .force(true) .send() .assert_green() .assert_no_steps(); api.assert_schema().assert_equals(&sql_schema); } // We have to test this because one enum on MySQL can map to multiple enums in the database. #[test_connector(tags(Mysql))] fn enum_creation_is_idempotent(api: TestApi) { let dm1 = r#" model Cat { id String @id mood Mood } model Human { id String @id mood Mood } enum Mood { HAPPY HUNGRY } "#; api.schema_push_w_datasource(dm1).send().assert_green(); api.schema_push_w_datasource(dm1) .send() .assert_green() .assert_no_steps(); } #[test_connector(tags(Mysql))] fn enums_work_when_table_name_is_remapped(api: TestApi) { let schema = r#" model User { id String @default(uuid()) @id status UserStatus @map("currentStatus___") @@map("users") } enum UserStatus { CONFIRMED CANCELED BLOCKED } "#; api.schema_push_w_datasource(schema).send().assert_green(); } #[test_connector(tags(Mysql))] fn arity_of_enum_columns_can_be_changed(api: TestApi) { let dm1 = r#" enum Color { RED GREEN BLUE } model A { id Int @id primaryColor Color secondaryColor Color? } "#; api.schema_push_w_datasource(dm1).send().assert_green(); api.assert_schema().assert_table("A", |table| { table .assert_column("primaryColor", |col| col.assert_is_required()) .assert_column("secondaryColor", |col| col.assert_is_nullable()) }); let dm2 = r#" enum Color { RED GREEN BLUE } model A { id Int @id primaryColor Color? secondaryColor Color } "#; api.schema_push_w_datasource(dm2).send().assert_green(); api.assert_schema().assert_table("A", |table| { table .assert_column("primaryColor", |col| col.assert_is_nullable()) .assert_column("secondaryColor", |col| col.assert_is_required()) }); } #[test_connector(tags(Mysql))] fn arity_is_preserved_by_alter_enum(api: TestApi) { let dm1 = r#" enum Color { RED GREEN BLUE } model A { id Int @id primaryColor Color secondaryColor Color? } "#; api.schema_push_w_datasource(dm1).send().assert_green(); api.assert_schema().assert_table("A", |table| { table .assert_column("primaryColor", |col| col.assert_is_required()) .assert_column("secondaryColor", |col| col.assert_is_nullable()) }); let dm2 = r#" enum Color { ROT GRUEN BLAU } model A { id Int @id primaryColor Color secondaryColor Color? } "#; api.schema_push_w_datasource(dm2) .force(true) .send() .assert_executable() .assert_has_executed_steps(); api.assert_schema().assert_table("A", |table| { table .assert_column("primaryColor", |col| col.assert_is_required()) .assert_column("secondaryColor", |col| col.assert_is_nullable()) }); } #[test_connector(tags(Mysql))] fn native_type_columns_can_be_created(api: TestApi) { let types = &[ ("int", "Int", "Int", if api.is_mysql_8() { "int" } else { "int(11)" }), ( "smallint", "Int", "SmallInt", if api.is_mysql_8() { "smallint" } else { "smallint(6)" }, ), ("tinyint", "Boolean", "TinyInt", "tinyint(1)"), ( "tinyintInt", "Int", "TinyInt", if api.is_mysql_8() { "tinyint" } else { "tinyint(4)" }, ), ( "mediumint", "Int", "MediumInt", if api.is_mysql_8() { "mediumint" } else { "mediumint(9)" }, ), ( "bigint", "BigInt", "BigInt", if api.is_mysql_8() { "bigint" } else { "bigint(20)" }, ), ("decimal", "Decimal", "Decimal(5, 3)", "decimal(5,3)"), ("float", "Float", "Float", "float"), ("double", "Float", "Double", "double"), ("bits", "Bytes", "Bit(10)", "bit(10)"), ("bit", "Boolean", "Bit(1)", "bit(1)"), ("chars", "String", "Char(10)", "char(10)"), ("varchars", "String", "VarChar(500)", "varchar(500)"), ("binary", "Bytes", "Binary(230)", "binary(230)"), ("varbinary", "Bytes", "VarBinary(150)", "varbinary(150)"), ("tinyBlob", "Bytes", "TinyBlob", "tinyblob"), ("blob", "Bytes", "Blob", "blob"), ("mediumBlob", "Bytes", "MediumBlob", "mediumblob"), ("longBlob", "Bytes", "LongBlob", "longblob"), ("tinytext", "String", "TinyText", "tinytext"), ("text", "String", "Text", "text"), ("mediumText", "String", "MediumText", "mediumtext"), ("longText", "String", "LongText", "longtext"), ("date", "DateTime", "Date", "date"), ("timeWithPrecision", "DateTime", "Time(3)", "time(3)"), ("dateTimeWithPrecision", "DateTime", "DateTime(3)", "datetime(3)"), ( "timestampWithPrecision", "DateTime @default(now())", "Timestamp(3)", "timestamp(3)", ), ("year", "Int", "Year", if api.is_mysql_8() { "year" } else { "year(4)" }), ]; let mut dm = r#" model A { id Int @id "# .to_string(); for (field_name, prisma_type, native_type, _) in types { writeln!(&mut dm, " {} {} @db.{}", field_name, prisma_type, native_type).unwrap(); } dm.push_str("}\n"); api.schema_push_w_datasource(&dm).send().assert_green(); api.assert_schema().assert_table("A", |table| { types.iter().fold( table, |table, (field_name, _prisma_type, _native_type, database_type)| { table.assert_column(field_name, |col| col.assert_full_data_type(database_type)) }, ) }); // Check that the migration is idempotent api.schema_push_w_datasource(dm).send().assert_green().assert_no_steps(); } #[test_connector(tags(Mysql))] fn default_current_timestamp_precision_follows_column_precision(api: TestApi) { let migrations_directory = api.create_migrations_directory(); let dm = api.datamodel_with_provider( " model A { id Int @id createdAt DateTime @db.DateTime(7) @default(now()) } ", ); let expected_migration = indoc!( r#" -- CreateTable CREATE TABLE `A` ( `id` INTEGER NOT NULL, `createdAt` DATETIME(7) NOT NULL DEFAULT CURRENT_TIMESTAMP(7), PRIMARY KEY (`id`) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; "# ); api.create_migration("01init", &dm, &migrations_directory) .send_sync() .assert_migration("01init", |migration| migration.assert_contents(expected_migration)); } #[test_connector(tags(Mysql))] fn datetime_dbgenerated_defaults(api: TestApi) { let migrations_directory = api.create_migrations_directory(); let dm = indoc::indoc! {r#" model A { id Int @id @default(autoincrement()) d1 DateTime @default(dbgenerated("'2020-01-01'")) @db.Date d2 DateTime @default(dbgenerated("'2038-01-19 03:14:08'")) @db.DateTime(0) d3 DateTime @default(dbgenerated("'16:20:00'")) @db.Time(0) } "#}; let dm = api.datamodel_with_provider(dm); let expected_migration = indoc!( r#" -- CreateTable CREATE TABLE `A` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `d1` DATE NOT NULL DEFAULT '2020-01-01', `d2` DATETIME(0) NOT NULL DEFAULT '2038-01-19 03:14:08', `d3` TIME(0) NOT NULL DEFAULT '16:20:00', PRIMARY KEY (`id`) ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; "# ); api.create_migration("01init", &dm, &migrations_directory) .send_sync() .assert_migration("01init", |migration| migration.assert_contents(expected_migration)); } #[test_connector(tags(Mysql))] fn mysql_apply_migrations_errors_gives_the_failed_sql(api: TestApi) { let dm = ""; let migrations_directory = api.create_migrations_directory(); let migration = r#" CREATE TABLE `Cat` ( id INTEGER PRIMARY KEY ); DROP TABLE `Emu`; CREATE TABLE `Emu` ( size INTEGER ); "#; let migration_name = api .create_migration("01init", dm, &migrations_directory) .draft(true) .send_sync() .modify_migration(|contents| { contents.clear(); contents.push_str(migration); }) .into_output() .generated_migration_name .unwrap(); let err = api .apply_migrations(&migrations_directory) .send_unwrap_err() .to_string() .replace(&migration_name, "<migration-name>"); let expectation = if api.is_vitess() { expect![[r#" A migration failed to apply. New migrations cannot be applied before the error is recovered from. Read more about how to resolve migration issues in a production database: https://pris.ly/d/migrate-resolve Migration name: <migration-name> Database error code: 1051 Database error: target: test.0.primary: vttablet: rpc error: code = InvalidArgument desc = Unknown table 'vt_test_0.Emu' (errno 1051) (sqlstate 42S02) (CallerID: userData1): Sql: "drop table Emu", BindVars: {} Please check the query number 2 from the migration file. "#]] } else if cfg!(windows) { expect![[r#" A migration failed to apply. New migrations cannot be applied before the error is recovered from. Read more about how to resolve migration issues in a production database: https://pris.ly/d/migrate-resolve Migration name: <migration-name> Database error code: 1051 Database error: Unknown table 'mysql_apply_migrations_errors_gives_the_failed_sql.emu' Please check the query number 2 from the migration file. "#]] } else { expect![[r#" A migration failed to apply. New migrations cannot be applied before the error is recovered from. Read more about how to resolve migration issues in a production database: https://pris.ly/d/migrate-resolve Migration name: <migration-name> Database error code: 1051 Database error: Unknown table 'mysql_apply_migrations_errors_gives_the_failed_sql.Emu' Please check the query number 2 from the migration file. "#]] }; let first_segment = err .split_terminator("DbError {") .next() .unwrap() .split_terminator(" 0: ") .next() .unwrap(); expectation.assert_eq(first_segment) } // https://github.com/prisma/prisma/issues/12351 #[test] fn dropping_m2m_relation_from_datamodel_works() { let schema = r#" datasource db { provider = "mysql" url = env("DBURL") } model Puppy { name String @id motherId String mother Dog @relation(fields: [motherId], references: [name]) dogFriends Dog[] @relation("puppyFriendships") } model Dog { name String @id puppies Puppy[] puppyFriends Puppy[] @relation("puppyFriendships") } "#; let schema2 = r#" datasource db { provider = "mysql" url = env("DBURL") } model Puppy { name String @id motherId String mother Dog @relation(fields: [motherId], references: [name]) } model Dog { name String @id puppies Puppy[] } "#; let tmpdir = tempfile::tempdir().unwrap(); let path = super::diff::write_file_to_tmp(schema, &tmpdir, "schema.prisma"); let path2 = super::diff::write_file_to_tmp(schema2, &tmpdir, "schema2.prisma"); let (_result, diff) = super::diff::diff_result(DiffParams { exit_code: None, from: DiffTarget::SchemaDatamodel(SchemaContainer { schema: path.to_str().unwrap().to_owned(), }), to: DiffTarget::SchemaDatamodel(SchemaContainer { schema: path2.to_str().unwrap().to_owned(), }), script: true, shadow_database_url: None, }); let expected = expect![[r#" -- DropForeignKey ALTER TABLE `_puppyFriendships` DROP FOREIGN KEY `_puppyFriendships_A_fkey`; -- DropForeignKey ALTER TABLE `_puppyFriendships` DROP FOREIGN KEY `_puppyFriendships_B_fkey`; -- DropTable DROP TABLE `_puppyFriendships`; "#]]; expected.assert_eq(&diff); }
A comparative study of gland cells implicated in the nerve dependence of salamander limb regeneration Limb regeneration in salamanders proceeds by formation of the blastema, a mound of proliferating mesenchymal cells surrounded by a wound epithelium. Regeneration by the blastema depends on the presence of regenerating nerves and in earlier work it was shown that axons upregulate the expression of newt anterior gradient (nAG) protein first in Schwann cells of the nerve sheath and second in dermal glands underlying the wound epidermis. The expression of nAG protein after plasmid electroporation was shown to rescue a denervated newt blastema and allow regeneration to the digit stage. We have examined the dermal glands by scanning and transmission electron microscopy combined with immunogold labelling of the nAG protein. It is expressed in secretory granules of ductless glands, which apparently discharge by a holocrine mechanism. No external ducts were observed in the wound epithelium of the newt and axolotl. The larval skin of the axolotl has dermal glands but these are absent under the wound epithelium. The nerve sheath was stained post‐amputation in innervated but not denervated blastemas with an antibody to axolotl anterior gradient protein. This antibody reacted with axolotl Leydig cells in the wound epithelium and normal epidermis. Staining was markedly decreased in the wound epithelium after denervation but not in the epidermis. Therefore, in both newt and axolotl the regenerating axons induce nAG protein in the nerve sheath and subsequently the protein is expressed by gland cells, under (newt) or within (axolotl) the wound epithelium, which discharge by a holocrine mechanism. These findings serve to unify the nerve dependence of limb regeneration.
import React, { FC } from "react"; import { DOCS_CODELINE_CLASS } from "../utils"; import DocsTitle from "./DocsTitle"; interface ILocalizableProperty { name: string; type: string; } export interface IDocsLocale { localizableProps?: ILocalizableProperty[]; } const DocsLocale: FC<IDocsLocale> = ({ localizableProps }) => { if (!localizableProps) { return null; } return ( <div> <DocsTitle text="Intl" subtitle /> <p> This component supports localization of its properties, using the{" "} <code className={DOCS_CODELINE_CLASS}>localized</code> boolean property. <br /> When setting <code className={DOCS_CODELINE_CLASS}>localized = true</code> all the localizable props will be localized using their value as id for{" "} <code className={DOCS_CODELINE_CLASS}>{`intl.formatMessage({ id: 'property-value'})`}</code>. </p> <b>Localizable props:</b> <ul> {localizableProps.map(({ name, type }, index) => ( <li key={index}>{name}</li> ))} </ul> <p> <u>Important!</u> <br /> If one of the properties above is an array of strings or object, all the values for that path will get localized. </p> </div> ); }; export default DocsLocale;
/** * Test geometry wrapper holder. * * @throws Exception the exception */ @Test void testGeometryWrapperHolder() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); Geometry geometry = GeometryUtils.createPoint(1., 2.); GeometryWrapper wrapper = new GeometryWrapper(geometry); GeometryWrapperHolder holder = new GeometryWrapperHolder(); holder.id = "test"; holder.geometry = wrapper; String jsonStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(holder); System.out.println(jsonStr); GeometryWrapperHolder readHolder = objectMapper .readValue(jsonStr, GeometryWrapperHolder.class); assertEquals(holder.geometry, readHolder.geometry); geometry = GeometryUtils.createLineString(null); wrapper = new GeometryWrapper(geometry); holder.geometry = wrapper; jsonStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(holder); System.out.println(jsonStr); readHolder = objectMapper .readValue(jsonStr, GeometryWrapperHolder.class); assertEquals(holder.geometry.getGeometry(), readHolder.geometry.getGeometry()); holder.geometry = null; jsonStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(holder); System.out.println(jsonStr); readHolder = objectMapper .readValue(jsonStr, GeometryWrapperHolder.class); assertNull(readHolder.geometry); }
<filename>sharedcpp/audio_effect/libaudio_effect/audio_effect_processor/post/audio_effect_post_processor.h #ifndef AUDIOEFFECT_POST_PROCESSOR_H_ #define AUDIOEFFECT_POST_PROCESSOR_H_ #include "../../audio_effect/audio_effect.h" #include "../../audio_effect_filter/audio_effect_filter_chain.h" #include "../audio_effect_processor.h" #include "../../audio_effect_filter_impl/specific/mix_effect_filter.h" #include "../../audio_effect_filter_impl/specific/pitch_shift_mix_effect_filter.h" /** * AGCFilter->CompressorFilter->....->ReverbFilter * | * vocalEffectFilterChain----------------------- * |---->MIX/Mono2Stereo-->mixPostEffectFilterChain * accompanyEffectFilterChain--------------------- | * | FadeOutFilter->.... * AGCFilter->PitchShiftFilter->....->ReverbFilter * */ class AudioEffectPostProcessor: public AudioEffectProcessor{ protected: AudioEffectFilterChain* vocalEffectFilterChain; AudioEffectFilterChain* mixPostEffectFilterChain; AudioEffectFilterChain* accompanyEffectFilterChain; MixEffectFilter* mixEffectFilter; bool isAudioEffectChanged; AudioEffect* audioEffect; void detectRebuildFilterChain(); virtual void initFilterChains(); virtual void destroyFilterChains(); public: AudioEffectPostProcessor(); ~AudioEffectPostProcessor(); virtual void init(AudioEffect *audioEffect); virtual AudioResponse* process(short *vocalBuffer, int vocalBufferSize, short *accompanyBuffer, int accompanyBufferSize, float position, long frameNum); virtual AudioResponse* process(short *vocalBuffer, int vocalBufferSize, float position, long frameNum); virtual AudioResponse* processAccompany(short *accompanyBuffer, int accompanyBufferSize, float position, long frameNum); virtual void destroy(); virtual void setAudioEffect(AudioEffect *audioEffect); virtual void resetFilterChains(); protected: bool isAccompanyPitchShift(AudioEffect *audioEffect); bool isRobotAudioEffectFilter(AudioEffect *audioEffect); }; #endif /* AUDIOEFFECT_POST_PROCESSOR_H_ */
/** * Returns {@code true} if this exception indicates that guest language application was * cancelled during its execution. * * @deprecated Use {@link InteropLibrary#getExceptionType(Object)}. * @since 20.3 */ @Deprecated @Override public final boolean isCancelled() { return false; }
import * as cdk from '@aws-cdk/core'; import { IResolvable, Duration, Size } from '@aws-cdk/core'; import { Resource } from './resource'; import * as lambda from '@aws-cdk/aws-lambda'; import * as gg from '@aws-cdk/aws-greengrass'; export declare namespace Functions { interface RunAs { /** * The linux user id of the user executing the process */ readonly uid: number; /** * The linux group id of the user executing the process */ readonly gid: number; } enum IsolationMode { /** * Run lambda function in isolated mode */ CONTAINER_MODE = "GreengrassContainer", /** * Run lambda function as processes. This must be used when * running Greengrass in a docker container */ NO_CONTAINER_MODE = "NoContainer" } enum ResourceAccessPermission { READ_ONLY = "ro", READ_WRITE = "rw" } interface Execution { /** The mode in which the process for the function is run */ readonly isolationMode: IsolationMode; /** The user running the process */ readonly runAs?: RunAs; } interface ResourceAccessPolicy { /** * The Resource to associate to this function */ readonly resource: Resource; /** * The permissions of the function on the resource */ readonly permission: ResourceAccessPermission; } /** * The encoding type of the `event` paramter passed to the handler */ enum EncodingType { JSON = "json", BINARY = "binary" } } export interface FunctionProps { /** * The Lambda function whose code will be used for this Greengrass function */ readonly function: lambda.Function; /** * THe alias of the function. This is the recommended way to refer to the function */ readonly alias?: lambda.Alias; /** The version of the function to use */ readonly version?: lambda.Version; /** If set to true, the function is long running */ readonly pinned: boolean | IResolvable; /** The memory allocated to the lambda. Must be specified for Container Mode, * and omitted in no container mode */ readonly memorySize?: Size; /** The timeout for the execution of the handler */ readonly timeout: Duration; /** THe name of the executable when using compiled executables */ readonly executable?: string; /** The arguments to pass to the executable */ readonly execArgs?: string; /** The encoding type of the event message. */ readonly encodingType?: Functions.EncodingType; /** Determines if the lambda is run in containerized or non-containerized mode */ readonly isolationMode?: Functions.IsolationMode; /** The user running the lambda */ readonly runAs?: Functions.RunAs; /** The resource access policies for the function to associated resources */ readonly resourceAccessPolicies?: Functions.ResourceAccessPolicy[]; /** Environment variables to associate to the Lambda */ readonly variables?: any; /** Allow access to the SysFs */ readonly accessSysFs?: boolean | IResolvable; } export declare class Function extends cdk.Resource { get reference(): string; constructor(scope: cdk.Construct, id: string, props: FunctionProps); addResource(resource: Resource, permission: Functions.ResourceAccessPermission): Function; resolve(): gg.CfnFunctionDefinition.FunctionProperty; readonly name: string; readonly lambdaFunction: lambda.Function; readonly alias?: lambda.Alias; readonly version?: lambda.Version; readonly pinned: boolean | IResolvable; readonly memorySize?: Size; readonly timeout: Duration; readonly executable?: string; readonly execArgs?: string; readonly encodingType?: Functions.EncodingType; readonly isolationMode?: Functions.IsolationMode; readonly runAs?: Functions.RunAs; resourceAccessPolicies?: Functions.ResourceAccessPolicy[]; readonly variables?: any; readonly accessSysFs?: boolean | IResolvable; }
What are the roles and functions of the Attorney General? The Attorney General of Trinidad and Tobago has a dual role. He is a member of Government with two separate constitutional roles: a governmental role and a role as the guardian of the public interest. In his governmental role, he acts as a member of Government in the performance of his duties and in his role as the guardian of the public interest, he acts independently in a quasi-judicial capacity, representing the community at large. In accordance with the provisions of the Constitution of the Republic of Trinidad and Tobago, the Attorney General is responsible for the administration of legal affairs in Trinidad and Tobago. Legal Proceedings for and against the State must be taken: a) In the case of civil proceedings, in the name of the Attorney General and; b) In the case of criminal proceedings, in the name of the State. The Attorney General has responsibility for the following departments: Wholly Owned Enterprises Appointment to Quasi Judicial Bodies Law Reform Office of the Solicitor General Civil Litigation Legal Advice to the Government Office of Chief State Solicitor Administrator General Provisional Liquidator Provisional Receiver Public Trustee/Official Receiver Office of Chief Parliamentary Counsel Legislative Drafting Statutory Boards and other Bodies Corruption Investigation Bureau Anti-Corruption Squad Council of Legal Education Environmental Commission Equal Opportunity Commission Equal Opportunity Tribunal Hugh Wooding Law School Industrial Court Law Reform Commission Tax Appeal Board Prepared by the Trinidad & Tobago Gazette No.74A, Vol. No.49, June 16 2010
Living Paradoxes: On Agamben, Taylor, and Human Subjectivity Over the last few decades, Giorgio Agamben and Charles Taylor have produced important and influential genealogical works on the philosophical and political conceptions of secularity—from Taylor's 900-page study of modern identity and secularity in A Secular Age to Agamben's series of investigations into religious notions and practices in The Kingdom and the Glory, The Highest Poverty, and Opus Dei.1 Yet in their recent monographs, both of these thinkers have respectively returned to a prominent theme in their earlier works: human subjectivity. While Taylor's return to the philosophical anthropology of his early work is evident in the title of his latest…
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #ifndef FASTTEXT_VECTOR_H #define FASTTEXT_VECTOR_H #include <cstdint> #include <ostream> #include "real.h" namespace fasttext { class Matrix; class QMatrix; class Vector { public: int64_t m_; real* data_; explicit Vector(int64_t); ~Vector(); real& operator[](int64_t); const real& operator[](int64_t) const; int64_t size() const; void zero(); void mul(real); real norm() const; void addVector(const Vector& source); void addVector(const Vector&, real); void addRow(const Matrix&, int64_t); void addRow(const QMatrix&, int64_t); void addRow(const Matrix&, int64_t, real); void mul(const QMatrix&, const Vector&); void mul(const Matrix&, const Vector&); int64_t argmax(); }; std::ostream& operator<<(std::ostream&, const Vector&); } #endif
""" oas3.objects.components.example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from marshmallow import fields from oas3.base import BaseObject, BaseSchema class Example(BaseObject): """ .. note: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#exampleObject """ class Schema(BaseSchema): summary = fields.Str() description = fields.Str() value = fields.Raw() def represents(self): return Example def __init__(self, summary=None, description=None, value=None): self.summary = summary self.description = description self.value = value
/* * Open the specified slave side of the pty, * making sure that we have a clean tty. */ static int cleanopen(char *lyne) { register int t; chown(lyne, 0, 0); chmod(lyne, 0600); # if !defined(CRAY) && (BSD > 43) revoke(lyne); # endif t = open(lyne, O_RDWR|O_NOCTTY); if (t < 0) return(-1); # if !defined(__linux__) # if !defined(CRAY) && (BSD <= 43) signal(SIGHUP, SIG_IGN); vhangup(); signal(SIGHUP, SIG_DFL); t = open(lyne, O_RDWR|O_NOCTTY); if (t < 0) return(-1); # endif # endif # if defined(CRAY) && defined(TCVHUP) { register int i; signal(SIGHUP, SIG_IGN); ioctl(t, TCVHUP, (char *)0); signal(SIGHUP, SIG_DFL); setpgrp(); i = open(lyne, O_RDWR); if (i < 0) return(-1); close(t); t = i; } # endif return(t); }
/** * The method will get triggered from Rule Engine with following parameters * * @param ruleParam * ************** Following are the Rule Parameters********* <br><br> * * ruleKey : check-for-unused-ebs-rule <br><br> * * threadsafe : if true , rule will be executed on multiple threads <br><br> * * esEbsWithInstanceUrl : Enter the ebs es api <br><br> * * severity : Enter the value of severity <br><br> * * ruleCategory : Enter the value of category <br><br> * * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine * */ public RuleResult execute(final Map<String, String> ruleParam,Map<String, String> resourceAttributes) { logger.debug("========UnusedEBSRule started========="); Annotation annotation = null; String volumeId = null; String region = null; String severity = ruleParam.get(PacmanRuleConstants.SEVERITY); String category = ruleParam.get(PacmanRuleConstants.CATEGORY); String ebsUrl = null; String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_EBS_WITH_INSTANCE_URL); if(!StringUtils.isNullOrEmpty(formattedUrl)){ ebsUrl = formattedUrl; } MDC.put("executionId", ruleParam.get("executionId")); MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); List<LinkedHashMap<String,Object>>issueList = new ArrayList<>(); LinkedHashMap<String,Object>issue = new LinkedHashMap<>(); if (!PacmanUtils.doesAllHaveValue(severity,category,ebsUrl)) { logger.info(PacmanRuleConstants.MISSING_CONFIGURATION); throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION); } if (resourceAttributes != null) { volumeId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.VOLUME_ID)); region = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.REGION_ATTR)); boolean isEbsWithEc2Exists = false; try{ isEbsWithEc2Exists = PacmanUtils.checkResourceIdFromElasticSearch(volumeId,ebsUrl,PacmanRuleConstants.VOLUME_ID,region); } catch (Exception e) { logger.error("unable to determine",e); throw new RuleExecutionFailedExeption("unable to determine"+e); } if (!isEbsWithEc2Exists) { annotation = Annotation.buildAnnotation(ruleParam,Annotation.Type.ISSUE); annotation.put(PacmanSdkConstants.DESCRIPTION,"Unused EBS found!!"); annotation.put(PacmanRuleConstants.SEVERITY, severity); annotation.put(PacmanRuleConstants.SUBTYPE, Annotation.Type.RECOMMENDATION.toString()); annotation.put(PacmanRuleConstants.CATEGORY, category); issue.put(PacmanRuleConstants.VIOLATION_REASON, "EBS volume is not attached to an ec2 instance"); issueList.add(issue); annotation.put("issueDetails",issueList.toString()); logger.debug("========UnusedEBSRule ended with annotation {} :=========",annotation); return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation); } } logger.debug("========UnusedEBSRule ended========="); return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE); }
/** * Used to index incoming Tokens * * @since 0.9.2 * @author zzz */ class TokenKey extends SHA1Hash { public TokenKey(NID nID, InfoHash ih) { super(DataHelper.xor(nID.getData(), ih.getData())); } }
Spread the love On his first day as a senior at Hoover High School, Keyshawn found himself in a struggle with a Fresno Police officer who put his hands around the student’s neck, slammed him to the ground, and then employed a controversial chokehold — similar to that which killed Eric Garner — while his friend Johnny recorded the incident. His ‘crime’ was jaywalking. Although video uploaded to Facebook shows no evidence of weapons, much less violence or significant resistance against the cop who choked Keyshawn or other officers arriving on scene, both were arrested. What precipitated this scuffle and the arrests of two juveniles? Jaywalking and filming the police — two nonviolent, victimless acts. The latter such a minor infraction that it remains enforceable at all seriously stretches the limits of logic; and the former, a constitutional right, if not — amid this epidemic of police violence and brutality — an imperative civilian duty. According to the description posted with footage to Facebook, the two students attempted to cross the street, but Keyshawn (who goes by ‘KC’) jay-walked, “so this cop from Fresno PD started disrespecting him and grabbed him” — just for crossing the street outside the State’s designated pedestrian pathway. In the video, the as-yet unidentified officer alternately places his hands and KC’s backpack around the student’s neck because he refuses to sit down, given a physical response to jaywalking is highly disproportionate. KC and Johnny repeatedly tell the cop to let him go. This lopsided tussle continues for a minute and a half — during which KC’s only physical responses are to place his hands between the backpack strap and his neck to avoid being choked and similar defensive moves disproportional to the officer’s force. “Get on the ground!” the officer yells several times, completely ignoring their requests. “You’re under arrest,” the cop declares. “For what?” Apparently considering the question for a moment, the officer responds, “Right now, for battery on an officer.” Battery on an officer is largely a catchall term, akin to ‘I feared for my life,’ used to effect an arrest when no other reason exists to do so — as in this case, where KC’s only physical contact with the cop is to defend himself from being choked, even then, only in reflexively grasping the officer’s wrist, not violently, and decisively not in any way that could be considered battery. “I didn’t do nothing wrong!” KC yells in perplexed response. “I didn’t do nothing wrong!” Shortly after declaring this farcical cause for arrest, the officer brings KC to the ground, where he immediately performs the controversial chokehold that, as noted by Fresno People’s Media, “[m]ost departments have banned their officers from using … due to the likelihood of permanent injury or death.” “I can’t breathe!” KC says. Clearly drunk with the arrogance of power and control, the officer doesn’t release KC or even loosen his potentially deadly grip on the student’s neck. “He’s not resisting!” Johnny screams, gravely concerned for his friend’s safety. “He can’t breathe!” A motorcycle cop then appears on the scene, nearly running Johnny over. “Back up,” the first officer bellows at the student videographer, as the second approaches to put KC in handcuffs. “He’s a high school student and you’re fucking with him,” Johnny reiterates the absurdity of police response in this situation. After the second cop successfully cuffs KC, the first officer immediately approaches Johnny and the video lurches and then stops. Again, to reiterate, this incident only occurred because Keyshawn tried to cross the street outside the state-sanctioned pedestrian crosswalk — neither he nor the student filming produced weapons — nor did Keyshawn resist the officer beyond the minimum necessary to protect his safety, and not with violence at any point. Further, to head off any ‘if you can speak you can breathe’ naysayers, that argument is patently false — in fact, science and biology proves precisely the opposite to be true: You can speak even if you cannot breathe, right up until the point the last air in your lungs expires. Besides lung “capacities” and “volumes,” a person’s physical condition and state of health also play a role. Though the reasons are too detailed for this article to delve into, one decent summary of many can be found here. While some will predictably side with police in this incident, they should consider extenuating circumstances. Keyshawn did nothing wrong of import — he committed no crime; he did not resist the officer with violence; he did not steal the property of another; he committed no act of violence against any person. He stepped outside a line. Similarly, Johnny did nothing wrong — he filmed the incident without interfering, despite serious concern for his friend’s safety; he maintained an appropriate distance from police action while doing so; he committed no act that should have resulted in any contact with police. He filmed the police. Such a disproportionately brutal response to an infraction of no consequence illustrates everything wrong with policing in the United States. These students committed no act of harm against anyone or anything. What they did, instead, was bruise the ego of a control-intoxicated cop, whose worship of the letter of the law upstaged logic and thus performed an arrest wholly incommensurate to the infraction.
/** * Checks for CopyTo actions and correctly sets the path for targetField by setting the indexes specified in each action */ private void applyCopyToActions(List<Field> sourceFields, Mapping mapping) { for (Field sourceField : sourceFields) { if (sourceField instanceof FieldGroup) { applyCopyToActions(((FieldGroup) sourceField).getField(), mapping); continue; } if (sourceField.getActions() == null) { continue; } List<CopyTo> copyTos = sourceField.getActions().stream().filter(a -> a instanceof CopyTo).map(a -> (CopyTo) a).collect(Collectors.toList()); if (copyTos.size() == 0) { return; } if (copyTos.stream().flatMap(c -> c.getIndexes().stream().filter(i -> i < 0)).count() > 0) { throw new IllegalArgumentException("Indexes must be >= 0"); } /* * For each index present in CopyTo, set the corresponding index in the path. * each index of copyTo is supposed to have a counterpart in the path. */ for (CopyTo copyTo : copyTos) { for (Field field : mapping.getOutputField()) { AtlasPath path = new AtlasPath(field.getPath()); List<AtlasPath.SegmentContext> segments = path.getCollectionSegments(true); for (int i = 0; i < copyTo.getIndexes().size(); i++) { if (i < segments.size()) { path.setCollectionIndex(i + 1, copyTo.getIndexes().get(i)); } } field.setPath(path.toString()); } sourceField.getActions().remove(copyTo); } } }
Evaluation of Medicinal Effects of Isoxazole Ring Isosteres on Zonisamide for Autism Treatment by Binding to Potassium Voltage-Gated Channel Subfamily D Member 2 (Kv 4.2) Received: 19 October 2019 Revised: 13 December 2019 Accepted: 25 December 2019 Available online: 28 December 2019 K E Y W O R D S The present research study discusses discovery of the novel drugs based on Zonisamide (FDA-approved drug) to treat the autism disease. We designed novel compounds by changing the pyrazole ring of the molecular structure with its isosteric rings. The main goal of the present study is evaluation of isosterism effect on Zonisamide compound. The studied pyrazole isosters are isothiazole, azaphosphole, azaphosphole, oxaphosphole, thiaphosphole and diphosphole. First, all designed molecular structures were optimized using density functional theory (DFT) computational method by B3LYP/6311++G(d,p) basis set of theory. All the computations were performed in isolated form at room temperature. Then, making complex of all optimized molecular structures with A-type potassium voltage gated subfamily d member 2 (Kv 4.2) was studied. The ligand-receptor complexes energy data showed all designed molecules except (1H-indazol-3-yl)methanesulfonamide interct with channel weakly. The residues Phe 75, Asp 86, Phe 84, and Phe 74 played main role in making complex with (1H-indazol-3-yl)methanesulfonamide. However, the ADME and biological properties of the designed molecules were carried out using swissADME and FAF-Drugs4 web tools. Based on the ligand-channel complexes docking data and biochemical properties of the compounds, the pyrazole pentet ring is a suitable isostere for isoxazole ring in Zonisamide. Autism Introduction Zonisamide or benzo isoxazol-3ylmethanesulfonamide is a sulfonamide, first introduced in 1972 as an antipsychotic drug . Zonisamide later received its FDA approval as an adjuvant treatment for partial seizures in 2000. Over the years, the ameliorative effect of this drug in both partial and generalized seizures as well as several other neurological disorders namely, psychotic conditions , Parkinson disease , neuropathic pain and essential tremor have been investigated. Although the precise mechanism of Zonisamide has not yet fully understood, blockage of voltagegated sodium channels and T-type calcium channels seems to be the principle route of action. Furthermore, Zonisamide has been observed to interact with A-type potassium channels in hippocampal cells and actively block them . Since the introduction of A-type potassium voltage gated subfamily d member 2 (Kv 4.2) as a key player in pathogenesis of Autism spectrum disorders, the use of potassium channel blockers which specifically interact with Kv 4.2 subunit became an area of interest in management of autism . In our previous study, we focused on design and introduction of novel Zonisamide analogs which presented us with the best efficiency and structural interactions with Kv 4.2 subunits . In this regard, we analyzed the effect of alterations in Zonisamide's backbone and addition of functional groups such as NH2, OH, OCH3, and COOH in drug-receptor docking properties. In addition, biological behavior of the investigated compounds was predicted using SwissADME and FAF-drugs4. Based on the gathered results, P3TZ, H2P3TZ, M2P3TZ, H4P3TZ and M4P3TZ as novel molecular structures with the optimum efficiency and pharmacokinetic attributes were introduced . thiaphosphole and diphosphole were designed, investigated and compared with the base compound. The efficiency and affinity towards Kv 4.2 subunit were evaluated using molecular docking methods and computational chemistry. In addition, the physicochemical and biological attributes of each compound was predicted using SwissADME and FAF-drugs4 web tools. Computational methods Design of novel drugs is a new field of chemistry to introduce the new molecular structures as a medicine based on their interactions with a biologically receptor . These new medicines are commonly the organic small molecules that inhibit, activating the specific biomolecules . The results of these interactions make therapeutic effects on the patients . A drug design process comprises two main parts: molecular simulation and molecular docking . Simulation of small molecules is done using quantum mechanical (QM) equations solving . Molecular docking is analysis of the interactions of the ligandbiomolecule complex . Here, the molecular structures of all designed chemical compounds based on the medicinal molecule Zonisamide are optimized using density functional theory (DFT) computational method. In first step, optimization of all molecular structures are carried out using B3LYP/6-311++G(d,p) level of theory in isolated form at room temperature. We use the Gaussian 03 software for our computations. In second step, all optimized molecular structures are embedded into the potassium voltage-gated channel subfamily D member 2 (Kv 4.2) and the ligandbiomolecule docking is analyzed. It is necessary to say that the crystal structure of the title potassium channel was taken from the PDB (https://www.rcsb.org/). The Molegro Virtual Docker (MVD) software is used to the molecular docking analyses. On the other hand, the physicochemical properties of the studied compounds are gained using the online web tool www.swissadme.ca and discussed. The druglikeness properties are analyzed using the FAF-Drugs4 server. Molecular docking analysis of the designed compounds binding to the potassium voltagegated channel subfamily D member 2 (Kv 4.2) As mentioned above, we studied the electronic properties, stability and reactivity of Zonisamide in our previous article. We showed the B3LYP/6-311++G(d,p) basis set of theory is the best computational method to study this compound and its analogues . So, this computational method will be used to optimize our new designed compounds. Scheme 1 shows the molecular structure of the novel designed molecules. It was said Zonisamide can make complex with the potassium voltage-gated channel Kv 4.2. As seen in Scheme 1, new compounds were designed based on changing the isoxazole pentet ring to its isosteres. To attain the study of possibility of compounds interaction with the title receptor, all molecular structures were optimized at B3LYP/6-311++G(d,p) level of theory. Then, the optimized molecular structures were docked into the potassium voltage-gated channel Kv 4.2. Table 1 indicates the molecular structures-receptor docking data. We can see all new compounds except the compound containing pyrazole ring show low interaction energy with the channel. So, only the (1H-indazol-3-yl)methanesulfonamide can make complex with the channel as well as Zonisamide. The interactions of the Zonisamide optimized molecular structure with the potassium voltage-gated channel subfamily D member 2 (Kv 4.2) were analyzed in our previous research work . Here, we want to evaluate docking of (1H-indazol-3yl)methanesulfonamide analog into the title receptor ( Figure 1). As seen from the data of Table 1, the Mol Dock total energy score of the compound binding to the channel is -81.6029. Physicochemical descriptors and ADME parameters of the designed compounds The prediction of physiochemical descriptors and ADME behavior of molecular compounds is considered a predominant factor in early stages of drug discovery . SwissADME web tool was used for prediction and computed analysis of ADME properties and the results are presented in Tables 2 and 3. Molecular formula, molecular weight, the number of heavy atoms and aromatic heavy atoms, fraction csp3, the number of rotatable bond, H-bond receptors and H-bond donors, molar refractivity and TPSA (Topological Polar Surface Area) are calculated and presented in physiochemical properties section. Lipophilicity is of great importance in areas of drug discovery and design as it affects several attributes of the compound such as membrane permeability, solubility, selectivity, toxicity and potency. Lipophilicity values are presented as the partition coefficient between n-octanol and water (log PO/W). Five predictive models (iLOGP, XLOGP, WLOGP, MLOGP and SILICOS-IT) are utilized in SwissADME to analyze compound's lipophilicity. Oral pharmaceutical formulations are especially reliant on this factor for their optimal concentration in systemic circulation. Water solubility of each investigated compound was determined using ESOL model, a topical method to evaluate Log S. In this regard, compounds are generally categorized in six groups: Insoluble (Log S<-10), poorly soluble (-10<Log S<-6), moderately soluble (-6<Log S<-4), soluble (-4<Log S<-2), very soluble (-2<Log S<0) and highly soluble (Log S ˃ 0). As observed in Tables 2 and 3, all substitutions fall into soluble and very soluble category. Individual ADME behaviors of the molecules under investigation are evaluated in pharmacokinetics section which evaluates the compounds passive gastrointestinal (GI) absorption, Blood Brain Barrier (BBB) permeability, P-gp efflux, inhibition of Cytochrome P450 enzymes (CYP1A2, CYP2C19, CYP2C9, CYP2D6 and CYP3A4). GI absorption is presented as high and low values. All compounds displayed high GI absorptions. Furthermore, none of the investigated structures are BBB permeant and P-gp efflux pump substrates. Cytochrome P450 enzymes are key players in the process of drug's metabolic biotransformation and further elimination. As a result, the evaluation of inhibitory capacity of compounds is essential in order to predict their possible interactions with other drugs and adverse effects resulting from decreased clearance and accumulation of the drug or its metabolites. Neither of the mentioned compounds inhibits cytochrome P450 enzymes. Lipinski's rule of five and bioavailability score of the investigated compounds determines their drug-likeness. All 8 compounds abide Lipinski's rule (MLOGP≤4.15, relative MW≤500, N or O≤10, NH or OH≤5). Bioavailability score is used to forecast the permeability and bioavailability properties of a compound in discovery setting. The values are 0.55 in all investigated compounds. The molecular structures were further analyzed using the FAF-drugs4 web tool. The results are presented in Figures 2-7. The Figure 2 is Physchem Filter Positioning which provides a radar plot, incorporating all predicted physiochemical descriptors. The compound's values (blue line) should reside in the drug-like filter area (pale blue and red). As observed in Figure 2, all compounds fall within the designated ranges. Figure 3 visualizes the compound complexity. It involves the number of system ring, stereo centers, rotatable and rigid bonds, the flexibility (ration between rotatable and rigid bonds), the carbon saturation (fsp3 ratio) and the maximum size of system rings. The values for all 8 compounds (blue line) are superimposed on the oral library min and max ranges (determined by red and pink areas). analyses Golden Triangle Rule which is a visualization tool used to optimize clearance and oral absorption of drug candidates. The compounds located in the triangle are likely to have an optimal permeability (low clearance) and a good metabolic stability. As presented in Figure 4, all compounds are positioned inside the golden triangle. Figure 5 represents the Oral Property Space, which is obtained by applying the PCA (Principal Component Analysis) of the 15 main physico-chemical descriptors of the chosen compounds (red), compared with two oral libraries extracted from eDrugs (blue) and DrugBank (orange). All compounds are located within the specified range. Oral Absorption Estimation is presented in Figure 6. The compounds values are represented by the blue line, which should fall within the optimal green area (Rule of 5 and Verber rule area). The white area is the extreme maximum zone and the red one is the extreme minimum zone. These zones are determined by the following descriptors ranges: LOGP (-2 to 5), MW (150 to 500), tPSA (20 to 150), Rotatable Bonds (0 to 10), H-Bonds Acceptors (0 to 10) and Donors (0 to 5). All 8 compounds are located within acceptable ranges. Lastly, Pfizer 3/75 rule is exhibited in Figure 7. Molecules located in red square are more likely to cause toxicity. The compounds under investigation are all placed in the green square predicting them to be non-toxic. Regarding the obtained data from predictive models, all 7 analogs exhibited satisfactory physiochemical properties and biological behaviors same as the base compound (Zonisamide). However, as discussed in the previous section, only (1Hindazol-3-yl)methanesulfonamide possessed a similar docking capability to Zonisamide while other structures did not show acceptable interactions with Kv 4.2 receptor. In conclusion, considering both biological and docking results, Pyrazole pentet ring in (1H-indazol-3yl)methanesulfonamide could be introduced as a suitable isostere for Isoxazole pentet ring in Zonisamide. Conclusion Zonisamide is a FDA-approved drug for treatment of the epilepsy and autism. In this work, we surveyed the novel compounds based on the Zonisamide by changing the pentet ring of the molecular structure with its isosteric rings. So, we designed 7 new analogs containing isothiazole, pyrazole, azaphosphole, azaphosphole, oxaphosphole, thiaphosphole and diphosphole rings. First, we optimized all molecular structures using density functional theory (DFT) computational method by functional B3LYP and 6-311++G(d,p) level of theory. After that, the optimized molecular structures were interacted with the said potassium channel using molecular docking technique. The docking analysis data showed all designed compounds except (1H-indazol-3-yl)methanesulfonamide have weaker interaction with channel than Zonisamide. Prediction of the designed compounds' biochemical properties was performed using the swissADME and FAF-Drugs4 websites. In overall, both the biological and docking results revealed that, Pyrazole pentet ring in (1H-indazol-3-yl)methanesulfonamide could be introduced as a suitable isostere for Isoxazole pentet ring in Zonisamide. We strongly believe that this method of Zonisamide-based compound screening and evaluation will be of great interest in future endeavors in drug design and drug delivery.
async def aggregate_weights(self, updates): update = await self.federated_averaging(updates) updated_weights = self.algorithm.update_weights(update) self.algorithm.load_weights(updated_weights)
/** * This class is generated by jOOQ. */ @Generated(value = { "http://www.jooq.org", "jOOQ version:3.10.6"}, comments = "This class is generated by jOOQ") @SuppressWarnings({ "all", "unchecked", "rawtypes"}) public class Tue4Championship extends TableImpl<ChampionshipRecord> { private static final long serialVersionUID = -1123768586; /** * The reference instance of <code>tue4_championship</code> */ public static final Tue4Championship CHAMPIONSHIP = new Tue4Championship(); /** * The class holding records for this type */ @Override public Class<ChampionshipRecord> getRecordType() { return ChampionshipRecord.class; } /** * The column <code>tue4_championship.cha_id</code>. */ public final TableField<ChampionshipRecord, String> CHA_ID = createField("cha_id", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, ""); /** * The column <code>tue4_championship.cha_name</code>. */ public final TableField<ChampionshipRecord, String> CHA_NAME = createField("cha_name", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, ""); /** * The column <code>tue4_championship.cha_description</code>. */ public final TableField<ChampionshipRecord, String> CHA_DESCRIPTION = createField("cha_description", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, ""); /** * The column <code>tue4_championship.cha_date_init</code>. */ public final TableField<ChampionshipRecord, Date> CHA_DATE_INIT = createField("cha_date_init", org.jooq.impl.SQLDataType.DATE.nullable(false), this, ""); /** * The column <code>tue4_championship.cha_date_end</code>. */ public final TableField<ChampionshipRecord, Date> CHA_DATE_END = createField("cha_date_end", org.jooq.impl.SQLDataType.DATE.nullable(false), this, ""); /** * Create a <code>tue4_championship</code> table reference */ public Tue4Championship() { this(DSL.name("tue4_championship"), null); } /** * Create an aliased <code>tue4_championship</code> table reference */ public Tue4Championship(String alias) { this(DSL.name(alias), CHAMPIONSHIP); } /** * Create an aliased <code>tue4_championship</code> table reference */ public Tue4Championship(Name alias) { this(alias, CHAMPIONSHIP); } private Tue4Championship(Name alias, Table<ChampionshipRecord> aliased) { this(alias, aliased, null); } private Tue4Championship(Name alias, Table<ChampionshipRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return DefaultSchema.DEFAULT_SCHEMA; } /** * {@inheritDoc} */ @Override public List<Index> getIndexes() { return Arrays.<Index>asList(Indexes.CHAMPIONSHIP_PKEY); } /** * {@inheritDoc} */ @Override public UniqueKey<ChampionshipRecord> getPrimaryKey() { return Keys.CHAMPIONSHIP_PKEY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<ChampionshipRecord>> getKeys() { return Arrays.<UniqueKey<ChampionshipRecord>>asList(Keys.CHAMPIONSHIP_PKEY); } /** * {@inheritDoc} */ @Override public Tue4Championship as(String alias) { return new Tue4Championship(DSL.name(alias), this); } /** * {@inheritDoc} */ @Override public Tue4Championship as(Name alias) { return new Tue4Championship(alias, this); } /** * Rename this table */ @Override public Tue4Championship rename(String name) { return new Tue4Championship(DSL.name(name), null); } /** * Rename this table */ @Override public Tue4Championship rename(Name name) { return new Tue4Championship(name, null); } }
A smart switchable module for the detection of multiple ions via turn-on dual-optical readout and their cell imaging studies. A module switchable as a function of multi-stimuli response has been designed. The module displays sequential logic gate-based detection of multiple ions (Fe(3+), Hg(2+), CN(-) and S(2-)) at ppm levels via a "turn on" signature which potentially meets real-world-challenges through a simple synthetic route, a fast response, water based-activity, naked-eye visualization, regenerative-action, high selectivity and multiple readout for precise analysis. Living cell imaging of Fe(3+) and Hg(2+) has also been carried out in HeLa cell lines.
/* * app-data-container.cpp * Copyright (C) 2010-2018 Belledonne Communications SARL * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "linphone/utils/utils.h" #include "app-data-container.h" // ============================================================================= using namespace std; LINPHONE_BEGIN_NAMESPACE // ----------------------------------------------------------------------------- class AppDataContainerPrivate { public: shared_ptr<unordered_map<string, string>> appData; }; // ----------------------------------------------------------------------------- AppDataContainer::AppDataContainer () : mPrivate(new AppDataContainerPrivate) { L_D(); d->appData = make_shared<unordered_map<string, string>>(); } AppDataContainer::AppDataContainer (const AppDataContainer &other) : mPrivate(new AppDataContainerPrivate) { L_D(); d->appData = other.getPrivate()->appData; } AppDataContainer::~AppDataContainer () { delete mPrivate; } AppDataContainer &AppDataContainer::operator= (const AppDataContainer &other) { L_D(); if (this != &other) d->appData = other.getPrivate()->appData; return *this; } const unordered_map<string, string> &AppDataContainer::getAppDataMap () const { L_D(); return *d->appData.get(); } const string &AppDataContainer::getAppData (const string &name) const { L_D(); auto it = d->appData->find(name); return it == d->appData->cend() ? Utils::getEmptyConstRefObject<string>() : it->second; } void AppDataContainer::setAppData (const string &name, const string &appData) { L_D(); (*d->appData)[name] = appData; } void AppDataContainer::setAppData (const string &name, string &&appData) { L_D(); (*d->appData)[name] = move(appData); } LINPHONE_END_NAMESPACE
. One hundred and eighty eight outpatients with community acquired pneumonia have been treated by spiramycin in general practice. Community acquired pneumonia was defined by the association of fever > or = 38 degrees C, respiratory symptoms as cough, sputum production, dyspnea or thoracic pain, and pulmonary opacity on the chest X-Ray. The mean age of patients was 44.7 +/- 16.6 and few of them had concomitant chronic illness, as cardiovascular (9%) or bronchopulmonary disease (9%). Twenty one percent of patients have been included after a previous antibiotherapy failure. In 92% on these cases, prior antibiotherapy was a beta lactam. At inclusion, the fever was greater than 39 degrees C in 56% of patients, 58% had localized crepitations at the chest auscultation. The chest X-Ray was performed 1.4 +/- 2.1 days after inclusion and showed a lobar consolidation in 77%. One third of patients presented a clinical picture evoking acute bacterial pneumonia. One hundred and seventy one patients have been reviewed for a second evaluation 4 +/- 1.5 days after inclusion. One hundred and eighty seven patients have visited for the long term follow up 19 +/- 6.5 days after the onset of treatment. Ninety six per cent of them have consulted with a control chest X-ray. At this visit, the antibiotherapy was changed in 2 other patients with of failure. Overall, 83% of patients were clinically and radiologically cured by Spiramycin 3 MU twice a day for 13 +/- 3.5 days. Fourteen percent of patients were improved without necessity of changing the antibiotic regimen. This study confirms the efficacy of spiramycin in the management of community acquired pneumoniae in general practice, either in first line therapy of after the failure of beta lactam.
This section is intended for developers only (or the confident, adventurous user). Before reading you may want to read what other developers are doing at the XDA developer forum. Find below the Linux kernel source code packages. Package 1: Source code for the Linux kernel used on the Fairphone http://storage.googleapis.com/fairphone-updates/alps-fairphone-gpl-kernel-2015-07-20.tar.bz2 Package 2: Source code for the GPL licensed programs used on the Fairphone (dbus, dnsmasq, e2fsprogs, iproute2, iptables) http://www.fairphone.com/downloads/software/open_source/fp1/alps-fairphone-gpl-userland-2014-09-08.tar.bz2 This product contains open source software including software released under the GNU General Public License (GPL) version 2 and Library/Lesser General Public License version 2/2.1. As per the terms of these licenses Fairphone is offering you to ship the source code on a physical medium for up to three years after support for the product has ended for a charge of EUR 10. To receive the source code write to [email protected] or to Fairphone: Jollemanhof 17 1019 GW Amsterdam The Netherlands. To ensure smooth handling of your request, please indicate the model number for which you would like to receive the source code. We have done our best to keep this page up-to-date. If you have any questions or feel like we could provide more information on this page, please contact us at [email protected].
pub struct Player { pub player_id: i32, pub player_control_net_id: u32, pub player_physics_net_id: u32, pub player_transform_net_id: u32, }
def indices_from_symbol(self, symbol: str) -> Tuple[int, ...]: return tuple((i for i, specie in enumerate(self.species) if specie.symbol == symbol))
#include <iostream> #include <iomanip> #include <stdio.h> #include <cmath> #include <fstream> #include "../include/residuals.hpp" #include "../include/parameters.hpp" using namespace std; void getResiduals(int nb, int *nx, int *ny, int gp, int it, double t_total, int iter, double &resU, double &resUNorm, double &resV, double &resVNorm, double &resP, double &resPNorm, double &resDiv, double &resDivNorm, double ****pv0, double ****pv, int transient, double eps, bool &solutionHasConverged) { resU = 0.0; resV = 0.0; resP = 0.0; resDiv = 0.0; for (int ib = 0; ib < nb; ++ib) { for (int i = gp+1; i < nx[ib]+gp-1; ++i) { for (int j = gp+1; j < ny[ib]+gp-1; ++j) { if(fabs(pv[ib][i][j][velocityX]-pv0[ib][i][j][velocityX]) > resU) { resU = fabs(pv[ib][i][j][velocityX]-pv0[ib][i][j][velocityX]); } if(fabs(pv[ib][i][j][velocityY]-pv0[ib][i][j][velocityY]) > resV) { resV = fabs(pv[ib][i][j][velocityY]-pv0[ib][i][j][velocityY]); } if(fabs(pv[ib][i][j][pressure ]-pv0[ib][i][j][pressure ]) > resP) { resP = fabs(pv[ib][i][j][pressure ]-pv0[ib][i][j][pressure ]); } if(fabs(pv[ib][i][j][divergence]-pv0[ib][i][j][divergence]) > resDiv) { resDiv = fabs(pv[ib][i][j][divergence]-pv0[ib][i][j][divergence]); } } } } if (iter == 0 ) { if (resU == 0.0) { resUNorm = 1.0; } else { resUNorm = resU; } if (resV == 0.0) { resVNorm = 1.0; } else { resVNorm = resV; } if (resP == 0.0) { resPNorm = 1.0; } else { resPNorm = resP; } if (resDiv == 0.0) { resDivNorm = 1.0; } else { resDivNorm = resDiv; } if (transient == steady) { printf(" iteration ====== u-momentum ====== v-momentum ======== pressure ====== divergence \n"); } else if (transient == unsteady) { printf(" time step(total time) ======= iteration ====== u-momentum ====== v-momentum ======== pressure ====== divergence \n"); } } // normalise residuals resU = resU/resUNorm; resV = resV/resVNorm; resP = resP/resPNorm; resDiv = resDiv/resDivNorm; // print residuals to screen if (iter % 100 == 0) { if (transient == steady) { printf("%12d %15.5e %15.5e %15.5e %15.5e\n", iter, resU, resV, resP, resDiv); } else if (transient == unsteady) { printf("%12d(%15.5e) %12d %15.5e %15.5e %15.5e %15.5e\n", it, t_total, iter, resU, resV, resP, resDiv); } } // file identifiers ofstream resFile; // write residuals to file if(iter == 0) { // open new file, replace previous file resFile.open("output/residuals.dat"); } else { // open and append data to existing file resFile.open("output/residuals.dat", fstream::app); } resFile << fixed << setprecision(10) << setw(10) << iter << " " << scientific << resU << " " << resV << " " << resP << " " << resDiv << endl; resFile.close(); // check if residuals is smaller than threshold if(resDiv < eps && iter > 10) { if (transient == steady) { printf("%12d %15.5e %15.5e %15.5e %15.5e\n", iter, resU, resV, resP, resDiv); } else if (transient == unsteady) { printf(" %12d %15.5e %15.5e %15.5e %15.5e\n", iter, resU, resV, resP, resDiv); } solutionHasConverged = true; } }
// ConsumeByteSlice consumes a single string of raw binary data from the buffer. // A string is a uint32 length, followed by that number of raw bytes. // If the buffer does not have enough data, or defines a length larger than available, it will return ErrShortPacket. // // The returned slice aliases the buffer contents, and is valid only as long as the buffer is not reused // (that is, only until the next call to Reset, PutLength, StartPacket, or UnmarshalBinary). // // In no case will any Consume calls return overlapping slice aliases, // and Append calls are guaranteed to not disturb this slice alias. func (b *Buffer) ConsumeByteSlice() ([]byte, error) { length, err := b.ConsumeUint32() if err != nil { return nil, err } if b.Len() < int(length) { return nil, ErrShortPacket } v := b.b[b.off:] if len(v) > int(length) { v = v[:length:length] } b.off += int(length) return v, nil }
<reponame>bangbang00/tidb // Copyright 2021 PingCAP, Inc. // // 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 mock import ( "github.com/pingcap/errors" "github.com/pingcap/tidb/kv" ) // SliceIter is used to iterate slice type SliceIter struct { data []*kv.Entry cur int } // NewSliceIter creates a new SliceIter func NewSliceIter(data []*kv.Entry) *SliceIter { return &SliceIter{ data, 0, } } // GetSlice returns the inner slice func (i *SliceIter) GetSlice() []*kv.Entry { return i.data } // Valid returns true if the current iterator is valid. func (i *SliceIter) Valid() bool { return i.cur >= 0 && i.cur < len(i.data) } // Key returns the current key. func (i *SliceIter) Key() kv.Key { if !i.Valid() { return nil } return i.data[i.cur].Key } // Value returns the current value. func (i *SliceIter) Value() []byte { if !i.Valid() { return nil } return i.data[i.cur].Value } // Next goes the next position. Always return error for this iterator func (i *SliceIter) Next() error { if !i.Valid() { return errors.New("iterator is invalid") } i.cur++ return nil } // Close closes the iterator. func (i *SliceIter) Close() { i.cur = -1 }
<reponame>malyvsen/snippeteer import functools import ast from .nodes import node_children def descend(ast_node, handlers, combiner=list.__add__, initial=[]): if isinstance(ast_node, str): raise TypeError("descend should only be used for parsed code, not strings") for node_type, handler in handlers.items(): if isinstance(ast_node, node_type): return handler(ast_node) if isinstance(ast_node, list): return functools.reduce( combiner, [ descend( child_node, handlers=handlers, combiner=combiner, initial=initial, ) for child_node in ast_node ], initial, ) return descend_children( ast_node, handlers=handlers, combiner=combiner, initial=initial ) def descend_children(ast_node, handlers, combiner, initial): for node_type, children in node_children.items(): if isinstance(ast_node, node_type): return descend( [getattr(ast_node, child) for child in children], handlers=handlers, combiner=combiner, initial=initial, ) raise NotImplementedError(f"Cannot parse {type(ast_node)}!")
/* If IN is a string that is >= MIN_COMPRESS_SIZE and the COMPRESSION_LEVEL is not SVN_DELTA_COMPRESSION_LEVEL_NONE, zlib compress it and places the result in OUT, with an integer prepended specifying the original size. If IN is < MIN_COMPRESS_SIZE, or if the compressed version of IN was no smaller than the original IN, OUT will be a copy of IN with the size prepended as an integer. */ static svn_error_t * zlib_encode(const char *data, apr_size_t len, svn_stringbuf_t *out, int compression_level) { unsigned long endlen; apr_size_t intlen; svn_stringbuf_setempty(out); append_encoded_int(out, len); intlen = out->len; if ( (len < MIN_COMPRESS_SIZE) || (compression_level == SVN_DELTA_COMPRESSION_LEVEL_NONE)) { svn_stringbuf_appendbytes(out, data, len); } else { int zerr; svn_stringbuf_ensure(out, svnCompressBound(len) + intlen); endlen = out->blocksize; zerr = compress2((unsigned char *)out->data + intlen, &endlen, (const unsigned char *)data, len, compression_level); if (zerr != Z_OK) return svn_error_trace(svn_error__wrap_zlib( zerr, "compress2", _("Compression of svndiff data failed"))); if (endlen >= len) { svn_stringbuf_appendbytes(out, data, len); return SVN_NO_ERROR; } out->len = endlen + intlen; out->data[out->len] = 0; } return SVN_NO_ERROR; }
/** * Called to get a user's existing payment method, if any. If your user already has an existing * payment method, you may not need to show Drop-In. * * Note: a client token must be used and will only return a payment method if it contains a * customer id. * * @param activity the current {@link AppCompatActivity} * @param clientToken A client token from your server. Note that this method will only return a * result if the client token contains a customer id. * @param listener The {@link DropInResultListener} to handle the error or {@link DropInResult} * response. */ public static void fetchDropInResult(AppCompatActivity activity, String clientToken, @NonNull final DropInResultListener listener) { try { if (!(Authorization.fromString(clientToken) instanceof ClientToken)) { listener.onError(new InvalidArgumentException("DropInResult#fetchDropInResult must " + "be called with a client token")); return; } } catch (InvalidArgumentException e) { listener.onError(e); return; } final BraintreeFragment fragment; try { fragment = BraintreeFragment.newInstance(activity, clientToken); } catch (InvalidArgumentException e) { listener.onError(e); return; } final List<BraintreeListener> previousListeners = fragment.getListeners(); final ListenerHolder listenerHolder = new ListenerHolder(); BraintreeErrorListener errorListener = new BraintreeErrorListener() { @Override public void onError(Exception error) { resetListeners(fragment, listenerHolder, previousListeners); listener.onError(error); } }; listenerHolder.listeners.add(errorListener); PaymentMethodNoncesUpdatedListener paymentMethodsListener = new PaymentMethodNoncesUpdatedListener() { @Override public void onPaymentMethodNoncesUpdated(java.util.List<PaymentMethodNonce> paymentMethodNonces) { resetListeners(fragment, listenerHolder, previousListeners); if (paymentMethodNonces.size() > 0) { PaymentMethodNonce paymentMethod = paymentMethodNonces.get(0); listener.onResult(new DropInResult() .paymentMethodNonce(paymentMethod)); } else { listener.onResult(new DropInResult()); } } }; listenerHolder.listeners.add(paymentMethodsListener); fragment.addListener(errorListener); fragment.addListener(paymentMethodsListener); final PaymentMethodType lastUsedPaymentMethodType = PaymentMethodType.forType(BraintreeSharedPreferences.getSharedPreferences(activity) .getString(LAST_USED_PAYMENT_METHOD_TYPE, null)); if (lastUsedPaymentMethodType == PaymentMethodType.GOOGLE_PAYMENT) { BraintreeResponseListener<Boolean> isReadyToPayCallback = new BraintreeResponseListener<Boolean>() { @Override public void onResponse(Boolean isReadyToPay) { if (isReadyToPay) { resetListeners(fragment, listenerHolder, previousListeners); DropInResult result = new DropInResult(); result.mPaymentMethodType = lastUsedPaymentMethodType; listener.onResult(result); } else { PaymentMethod.getPaymentMethodNonces(fragment); } } }; GooglePayment.isReadyToPay(fragment, isReadyToPayCallback); } else { PaymentMethod.getPaymentMethodNonces(fragment); } }
<gh_stars>0 // svg/diving-scuba-tank-multiple.svg import { createSvgIcon } from './createSvgIcon'; export const SvgDivingScubaTankMultiple = createSvgIcon( `<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="mdi-diving-scuba-tank-multiple" width="24" height="24" viewBox="0 0 24 24"> <path d="M22,18.5A2.5,2.5 0 0,1 19.5,21A2.5,2.5 0 0,1 17,18.5C17,17.47 17.62,16.59 18.5,16.21V6H14V7.35C15.22,7.93 16,9.15 16,10.5V22H2V10.5C2,9.15 2.78,7.93 4,7.35V6H2V4H4V3.5A1.5,1.5 0 0,1 5.5,2A1.5,1.5 0 0,1 7,3.5V4H11V3.5A1.5,1.5 0 0,1 12.5,2A1.5,1.5 0 0,1 14,3.5V4H18.5A2,2 0 0,1 20.5,6V16.21C21.38,16.59 22,17.47 22,18.5M11,7.35V6H7V7.35C8.22,7.93 9,9.15 9,10.5C9,9.15 9.78,7.93 11,7.35Z"/> </svg>` );
/** * Protect html input from Server-side Request Forgery (SSRF) attacks * Detects SSRF (Server-side request forgery) attacks and unsafe URL attacks from HTML text input, where attackers can attempt to access unsafe local or network paths in the server environment by injecting them into HTML. * @param value User-facing HTML input. (required) * @return ApiResponse&lt;HtmlSsrfDetectionResult&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<HtmlSsrfDetectionResult> textInputCheckHtmlSsrfWithHttpInfo(String value) throws ApiException { com.squareup.okhttp.Call call = textInputCheckHtmlSsrfValidateBeforeCall(value, null, null); Type localVarReturnType = new TypeToken<HtmlSsrfDetectionResult>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
One of the worst-kept secrets of the technology industry is that the next big product category will be smartwatches, wearable computers that sources have all but confirmed will be released soon by Apple, Microsoft, Google and Samsung. But no matter how useful, how beautiful and how advanced these wristwatch-like devices end up being, at least one group of people likely won’t be moved by them: hardcore watch collectors, who favor wind-up watches with analog dials, gears, and springs over any hypothetical touchscreen or voice-activated product. "I doubt I’d wear it on my wrist." "It’s not going to disturb the market for serious watch collectors," said William Massena, a New York-based consultant who’s collected luxury wristwatches for the past 20 years. Massena shares his passion with other like-minded collectors on Twitter and the discussion forum of a watch collecting website called TimeZone. "If they came out with an iWatch tomorrow, I would consider it a tool more than anything else. I’m sure I’d use it, but I would probably put it in my pocket. I doubt I’d wear it on my wrist." Two luxury watches from William Massena's collection. The collector, an NYC-based consultant, says he's lost track of how many pieces he has in total. (Credit: William Massena) Massena is not alone: other avid watch collectors and industry-watchers reached by The Verge said that they would certainly take a look at Apple’s rumored iWatch or competing smartwatches, and might even purchase a few for kicks. But they adamantly maintain no computerized device, no matter how advanced and beautifully designed, could ever disrupt the lucrative market for new and vintage mechanical watches, which are made with technology that originated in the Medieval era. $10,000 to multimillion-dollar range per watch The luxury watches prized by collectors technically start at $1,000 — though prices in the $10,000 to multimillion-dollar range per watch are more common — and are primarily made by Swiss companies including Rolex, Audemars Piguet, Vacheron Constantin and Patek Philippe. These watches have hundreds, and sometimes thousands, of moving parts and regal, austere names like Royal Oak and The Saltarello, or numeric designations, like the 5196R. They have internal jewels to prevent wear. There’s a whole system of classification for the types of features and functions they offer beyond the time, known fittingly as "complications." "For so many people, a watch is not a timepiece." "For so many people, a watch is not a timepiece," said Gene Stone, a wristwatch collector, journalist and author of The Watch, a book on luxury timepieces. "For people who love watches, it’s like having a piece of history sitting on your wrist. That’s a whole different psychology from having a computer on your wrist." Stone, who said he owns 10 luxury wristwatches and numerous other clocks, is part of a small group of collectors in New York City known as the Watch Enthusiasts of New York (WENY), or "Weenies," who meet monthly to talk watches and show off their favorites. "I could see myself wearing a Royal Oak on my left wrist and a Microsoft computer watch on my right," Stone said, but added the Microsoft smartwatch would have to be "beautiful." Hardcore watch collectors may be forgiven for shrugging off the arrival of a new breed of multifunction smartwatches. After all, the old-school, wind-up mechanical watches they favor, most of which come from Switzerland — known as the "watchmaking capital of the world" — have survived disruption by more advanced technology multiple times before. "It's glanceable information." Indeed, just under a decade ago, Microsoft partnered with several lower-end watch consumer companies — Fossil, Suunto, and Swatch — to introduce a line of digital smartwatches. These were based on a Microsoft technology called SPOT, "Smart Personal Objects Technology," which used FM signals to deliver live-updating information to watch faces, such as local weather forecasts, stock quotes and news headlines. "It's glanceable information and it's a combination of the two things that I think people really care about — fashion, something that's fun and exciting, and technology that brings them personal information," Bill Gates said at the time (sound familiar?). Consumers, however, did not agree, and after four years of low adoption, the clock ran out on SPOT in 2008. "Microsoft tried and completely failed, and here we are, they are trying again," Massena said of the failure of the company's smartwatches. Microsoft SPOT watch. "probably the last people on Earth who need to know what time it is." As for mechanical watches, their persistence across the ages is something of a technological anomaly, driven by a relatively small group of generally wealthy, generally male consumers who value them not as tools for telling time, but as works of art. "People who collect wristwatches are probably the last people on earth who need to know what time it is," Stone said. "If you have an expensive wristwatch, you probably already have a smartphone, a tablet, an assistant, and other gadgets to help tell you the time." Stone added that at Weenies meetings, it wasn’t uncommon for everyone to be looking at each other’s watches, only for someone to ask what time it is and everyone to have to check again, because they were paying attention to other facets of the watches. The art of mechanical watchmaking arose in Switzerland back in the mid-1500s, a reaction to religiously motivated bans on other forms of jewelry. Mechanical timepieces use springs and a series of gears to keep time, and must be physically re-wound by the wearer periodically. They were massively popular for centuries and their heyday lasted from World War I until 1969, when Japanese company Seiko launched the Astron, the first quartz wristwatch for the consumer market. The Seiko Astron used a vibrating quartz crystal instead of a spring, which kept time more accurately than mechanical watches, and without requiring winding. In the years that followed, quartz watches made primarily by Japanese and Chinese companies, such as Casio in Tokyo, quickly surpassed the popularity of mechanical watches made by the Swiss. They even enabled a new generation of electronic watches with digital displays. The so-called "quartz crisis" decimated the Swiss mechanical watchmaking industry — bankrupting many companies, while others were slower to catch up and release their own quartz products. Rolex, though, proved to be one of the few Swiss companies to not only adapt, but prove instrumental in popularizing quartz for luxury watches. Its 1977 Oysterquartz line is still considered by many watch enthusiasts to be some of the finest quartz models ever made. Today about 88 percent of Swiss watch sales are quartz, according to WatchTime, a bimonthly magazine for luxury watch collectors. Rolex promotional image of a mechanical watch being assembled. Here the balance wheel and mainspring are being fitted. (Credit: ©Rolex/Jean-Daniel Meyer.) And yet, in a strange twist of fate, mechanical watches not only hung on throughout the quartz crisis, but in recent years, newly made mechanical timepieces have become the most profitable part of the Swiss watch industry all over again. In 2012, new mechanical watches accounted for over $17 billion out of $23.5 billion total watch exports from Switzerland, according to the Federation of the Swiss Watch Industry group. "The fact that the market for this 400-year-old technology, which is completely obsolete, exists, is astonishing," said Joe Thompson, WatchTime’s editor-in-chief. "It’s a miracle really." "A watch is generally the only piece of jewelry a man will have on." Thompson, who has been covering the industry since the thick of the quartz crisis in the 1970s, told The Verge that he first observed the revival for the mechanical watch in the late '80s and early '90s as a status symbol for newly wealthy American men on Wall Street and in Silicon Valley. And it is men, primarily, who collect watches, according to WatchTime’s readership statistics (98 percent of their 50,000 subscribers are men). "A watch is generally the only piece of jewelry a man will have on at any given time," agreed Stone. While there's been some handwringing in the industry over the fact that the younger generation doesn't appear to be buying or sporting wristwatches — why would they be, when a mobile phone usually close at hand? — the appetite seems to develop as they age and accrue more money. "Young people tend not to be interested, but as you get older, you may acquire one," Stone explained, "Maybe you inherit your father's watch, or retire after 10 years at a company and get a nice watch, and that's how it starts." After the financial crisis of 2008 wiped out the fortunes of many of the post-quartz generation of luxury watch collectors, Swiss mechanical watch exports plunged an alarming 22.1 percent in 2009. Then, in 2010, Swiss watch experts resurged and have pretty much climbed steadily every year ever since, driven in large part by a class of newly wealthy Chinese collectors. At least until now — the early statistics from the first half of 2013 show a worrying slowdown in the Swiss watch industry’s growth. Collectors and industry analysts aren’t so concerned about the mechanical watch’s future, though. "Mechanical watches are enormously complex, and the process to make them is very hi-tech," Thompson said, pointing out that precision machines are used to make and assemble the hundreds of moving parts of luxury mechanical watches. "There’s a tremendous amount of science that goes into it, which is why it’s stayed alive." Chris Ziegler contributed to this report.
<reponame>srmagura/iti-react import moment from 'moment-timezone' /** * A configurable function for formatting a moment. * * @param mo any moment object * @param options * - `onlyShowDateIfNotToday`: when true, does not display the day if `mo` is today * - `convertToLocal`: if `mo` should be converted to local time * - `dateTimeFormat`: format used if date & time are displayed * - `timeFormat`: format used if only time is displayed */ export function formatDateTimeConfigurable( mo: moment.Moment, options: { onlyShowDateIfNotToday: boolean convertToLocal: boolean dateTimeFormat: string timeFormat: string } ): string { if (options.convertToLocal) mo = moment(mo).local() const alwaysShowDate = !options.onlyShowDateIfNotToday const isToday = mo.isSame(moment(), 'day') if (!isToday || alwaysShowDate) { return mo.format(options.dateTimeFormat) } return mo.format(options.timeFormat) }
/** * Opens the specified <tt>ChatPanel</tt> and optinally brings it to the * front. * * @param chatPanel the <tt>ChatPanel</tt> to be opened * @param setSelected <tt>true</tt> if <tt>chatPanel</tt> (and respectively * this <tt>ChatContainer</tt>) should be brought to the front; otherwise, * <tt>false</tt> */ public void openChat(ChatPanel chatPanel, boolean setSelected) { MainFrame mainWindow = GuiActivator.getUIService().getMainFrame(); if(mainWindow.getExtendedState() != JFrame.ICONIFIED) { if(ConfigurationUtils.isAutoPopupNewMessage() || setSelected) mainWindow.toFront(); } else { if(setSelected) { mainWindow.setExtendedState(JFrame.NORMAL); mainWindow.toFront(); } String chatWindowTitle = "TEST"; if(!chatWindowTitle.startsWith("*")) setTitle("*" + chatWindowTitle); } if(setSelected) { setCurrentChat(chatPanel); } else if(!getCurrentChat().equals(chatPanel) && tabbedPane.getTabCount() > 0) { highlightTab(chatPanel); } }
<filename>packages/viewer/src/stores/url-parameters.ts /* * Copyright 2015 Trim-marks Inc. * Copyright 2019 Vivliostyle Foundation * * This file is part of Vivliostyle UI. * * Vivliostyle UI is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vivliostyle UI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Vivliostyle UI. If not, see <http://www.gnu.org/licenses/>. */ import stringUtil from "../utils/string-util"; function getRegExpForParameter(name: string): RegExp { return new RegExp(`[#&]${stringUtil.escapeUnicodeString(name)}=([^&]*)`, "g"); } class URLParameterStore { history: History | null; location: Location | { href: "" }; storedUrl: string; constructor() { this.history = window ? window.history : null; this.location = window ? window.location : { href: "" }; this.storedUrl = this.location.href; } getBaseURL(): string { let url = this.location.href; url = url.replace(/#.*$/, ""); return url.replace(/\/[^/]*$/, "/"); } hasParameter(name: string): boolean { const url = this.location.href; const regexp = getRegExpForParameter(name); return regexp.test(url); } getParameter(name: string): Array<string> { const url = this.location.href; const regexp = getRegExpForParameter(name); const results = []; let r; while ((r = regexp.exec(url))) { results.push(r[1]); } return results; } /** * @param {string} name * @param {string} value * @param {number=} index specifies index in multiple parameters with same name. */ setParameter(name: string, value: string, index?: number): void { const url = this.location.href; let updated; const regexp = getRegExpForParameter(name); let r = regexp.exec(url); if (r && index) { while (index-- >= 1) { r = regexp.exec(url); } } if (r) { const l = r[1].length; const start = r.index + r[0].length - l; updated = url.substring(0, start) + value + url.substring(start + l); } else { updated = `${url + (url.match(/[#&]$/) ? "" : url.match(/#/) ? "&" : "#") + name}=${value}`; } if (this.history !== null && this.history.replaceState) { this.history.replaceState(null, "", updated); } else { this.location.href = updated; } this.storedUrl = updated; } /** * @param {string} name * @param {boolean=} keepFirst If true, not remove the first one in multiple parameters with same name. */ removeParameter(name: string, keepFirst?: boolean): void { const url = this.location.href; let updated; const regexp = getRegExpForParameter(name); let r = regexp.exec(url); if (r && keepFirst) { r = regexp.exec(url); } if (r) { updated = url; for (; r; r = regexp.exec(updated)) { const end = r.index + r[0].length; if (r[0].charAt(0) == "#") { updated = updated.substring(0, r.index + 1) + updated.substring(end + 1); } else { updated = updated.substring(0, r.index) + updated.substring(end); } regexp.lastIndex -= r[0].length; } updated = updated.replace(/^(.*?)[#&]$/, "$1"); if (this.history !== null && this.history.replaceState) { this.history.replaceState(null, "", updated); } else { this.location.href = updated; } } this.storedUrl = updated; } } const instance = new URLParameterStore(); export default instance;
# 1283F - DIY Garland if __name__ == "__main__": n = int(input()) inp = input().rstrip().split(" ") assert len(inp) == n-1 for a in range(len(inp)): inp[a] = int(inp[a]) marked = {} edges = [[inp[i], None] for i in range(n-1)] next_largest_unseen = n # mark the root node: root = inp[0] marked[inp[0]] = True for i in range(1, n-1): parent = edges[i][0] if parent not in marked: edges[i-1][1] = parent marked[parent] = True else: while (next_largest_unseen in marked): next_largest_unseen -= 1 edges[i-1][1] = next_largest_unseen marked[next_largest_unseen] = True while next_largest_unseen in marked: next_largest_unseen -= 1 marked[next_largest_unseen] = True edges[n-2][1] = next_largest_unseen print(root) for edge in edges: edge = [str(edge[0]), str(edge[1])] print(" ".join(edge))
// (2) Set setDisplayHomeAsUpEnabled to true on the support ActionBar @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_settings); this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); }
<reponame>vain0x/text-position<filename>src/position/composite_position.rs // LICENSE: CC0-1.0 use crate::{TextPosition, Utf16Position, Utf8Index, Utf8Position}; use std::{ cmp::Ordering, fmt::{self, Display, Formatter}, hash::{Hash, Hasher}, ops::{Add, AddAssign}, }; /// Text position represented by multiple measure: /// /// - index: UTF-8 index /// - row: Line number. /// - column8: Column number as number of UTF-8 code units (bytes). /// - column16: Column number as number of UTF-16 code units (basically half of bytes). /// /// All of them start from 0. #[derive(Copy, Clone, Debug, Default)] pub struct CompositePosition { /// UTF-8 index. pub index: u32, /// Line number. pub row: u32, /// Column number as number of UTF-8 code units (bytes). pub column8: u32, /// Column number as number of UTF-16 code units (basically half of bytes). pub column16: u32, } impl CompositePosition { pub const fn new(index: u32, row: u32, column8: u32, column16: u32) -> Self { Self { index, row, column8, column16, } } } impl TextPosition for CompositePosition { const ZERO: Self = Self { index: 0, row: 0, column8: 0, column16: 0, }; fn from_str(s: &str) -> Self { let mut row = 0; let mut head = 0; while let Some(offset) = s[head..].find('\n') { row += 1; head += offset + 1; } Self { index: s.len() as u32, row: row as u32, column8: (s.len() - head) as u32, column16: s[head..].encode_utf16().count() as u32, } } fn saturating_sub(self, rhs: Self) -> Self { match self.row.cmp(&rhs.row) { Ordering::Less => Self::ZERO, Ordering::Equal => Self { index: self.index.saturating_sub(rhs.index), row: 0, column8: self.column8.saturating_sub(rhs.column8), column16: self.column16.saturating_sub(rhs.column16), }, Ordering::Greater => Self { index: self.index.saturating_sub(rhs.index), row: self.row - rhs.row, column8: self.column8, column16: self.column16, }, } } } impl From<char> for CompositePosition { fn from(c: char) -> Self { if c == '\n' { Self { index: 1, row: 1, column8: 0, column16: 0, } } else { let index = c.len_utf8() as u32; Self { index, row: 0, column8: index, column16: c.len_utf16() as u32, } } } } impl From<&'_ str> for CompositePosition { fn from(s: &str) -> Self { Self::from_str(s) } } impl AddAssign for CompositePosition { fn add_assign(&mut self, rhs: Self) { let sum = *self + rhs; *self = sum; } } impl Add for CompositePosition { type Output = Self; fn add(self, rhs: Self) -> Self { let index = self.index + rhs.index; if rhs.row == 0 { Self { index, row: self.row, column8: self.column8 + rhs.column8, column16: self.column16 + rhs.column16, } } else { Self { index, row: self.row + rhs.row, column8: rhs.column8, column16: rhs.column16, } } } } impl From<CompositePosition> for Utf8Index { fn from(pos: CompositePosition) -> Self { Utf8Index::new(pos.index) } } impl From<CompositePosition> for Utf8Position { fn from(pos: CompositePosition) -> Self { Utf8Position::new(pos.row, pos.column8) } } impl From<CompositePosition> for Utf16Position { fn from(pos: CompositePosition) -> Self { Utf16Position::new(pos.row, pos.column16) } } // Compare to Utf8Index: impl PartialEq<Utf8Index> for CompositePosition { fn eq(&self, other: &Utf8Index) -> bool { Utf8Index::from(*self).eq(other) } } impl PartialEq<CompositePosition> for Utf8Index { fn eq(&self, other: &CompositePosition) -> bool { self.eq(&Utf8Index::from(*other)) } } impl PartialOrd<Utf8Index> for CompositePosition { fn partial_cmp(&self, other: &Utf8Index) -> Option<Ordering> { Utf8Index::from(*self).partial_cmp(other) } } impl PartialOrd<CompositePosition> for Utf8Index { fn partial_cmp(&self, other: &CompositePosition) -> Option<Ordering> { self.partial_cmp(&Utf8Index::from(*other)) } } // Compare to Utf8Position: impl PartialEq<Utf8Position> for CompositePosition { fn eq(&self, other: &Utf8Position) -> bool { Utf8Position::from(*self).eq(other) } } impl PartialEq<CompositePosition> for Utf8Position { fn eq(&self, other: &CompositePosition) -> bool { self.eq(&Utf8Position::from(*other)) } } impl PartialOrd<Utf8Position> for CompositePosition { fn partial_cmp(&self, other: &Utf8Position) -> Option<Ordering> { Utf8Position::from(*self).partial_cmp(other) } } impl PartialOrd<CompositePosition> for Utf8Position { fn partial_cmp(&self, other: &CompositePosition) -> Option<Ordering> { self.partial_cmp(&Utf8Position::from(*other)) } } // Compare to Utf16Position: impl PartialEq<Utf16Position> for CompositePosition { fn eq(&self, other: &Utf16Position) -> bool { Utf16Position::from(*self).eq(other) } } impl PartialEq<CompositePosition> for Utf16Position { fn eq(&self, other: &CompositePosition) -> bool { self.eq(&Utf16Position::from(*other)) } } impl PartialOrd<Utf16Position> for CompositePosition { fn partial_cmp(&self, other: &Utf16Position) -> Option<Ordering> { Utf16Position::from(*self).partial_cmp(other) } } impl PartialOrd<CompositePosition> for Utf16Position { fn partial_cmp(&self, other: &CompositePosition) -> Option<Ordering> { self.partial_cmp(&Utf16Position::from(*other)) } } #[allow(unused)] fn assert_equality_consistency(it: &CompositePosition, other: &CompositePosition, equal: bool) { if equal { assert_eq!(Utf8Position::from(*it), Utf8Position::from(*other)); assert_eq!(Utf16Position::from(*it), Utf16Position::from(*other)); } else { assert_ne!(Utf8Position::from(*it), Utf8Position::from(*other)); assert_ne!(Utf16Position::from(*it), Utf16Position::from(*other)); } } #[allow(unused)] fn assert_ordering_consistency( it: &CompositePosition, other: &CompositePosition, ordering: Option<Ordering>, ) { assert_eq!( Utf8Position::from(*it).partial_cmp(&Utf8Position::from(*other)), ordering ); assert_eq!( Utf16Position::from(*it).partial_cmp(&Utf16Position::from(*other)), ordering ); } impl PartialEq for CompositePosition { fn eq(&self, other: &Self) -> bool { let equal = self.index == other.index; #[cfg(feature = "checked")] assert_equality_consistency(self, other, equal); equal } } impl Eq for CompositePosition {} impl PartialOrd for CompositePosition { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { let ordering = self.index.partial_cmp(&other.index); #[cfg(feature = "checked")] assert_ordering_consistency(self, other, ordering); ordering } } impl Ord for CompositePosition { fn cmp(&self, other: &Self) -> Ordering { let ordering = self.index.cmp(&other.index); #[cfg(feature = "checked")] assert_ordering_consistency(self, other, Some(ordering)); ordering } } impl Display for CompositePosition { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}:{}", self.row + 1, self.column8 + 1) } } impl Hash for CompositePosition { fn hash<H: Hasher>(&self, state: &mut H) { self.index.hash(state) } } #[cfg(test)] mod tests { use crate::{position::TextPosition, CompositePosition}; const ZERO: CompositePosition = CompositePosition::ZERO; fn pos_of(s: &str) -> CompositePosition { CompositePosition::from_str(s) } #[test] fn test_from_str_empty() { assert_eq!(pos_of(""), CompositePosition::ZERO); } #[test] fn test_from_str_ascii_single_line() { assert_eq!( pos_of("Hello, world!"), CompositePosition::new(13, 0, 13, 13) ); } #[test] fn test_from_str_ascii_multiple_line() { assert_eq!( pos_of("12345\n1234567\n12345"), CompositePosition::new(19, 2, 5, 5) ); } #[test] fn test_from_str_unicode() { assert_eq!( pos_of("いろはにほへと\nちりぬるを\nわかよたれそ\nつねならむ"), CompositePosition::new(72, 3, 15, 15) ); } #[test] fn test_from_str_surrogate_pair() { assert_eq!(pos_of("🐧"), CompositePosition::new(4, 0, 4, 2)); } #[test] fn test_from_str_crlf() { assert_eq!(pos_of("\r\n"), CompositePosition::new(2, 1, 0, 0)); } #[test] fn test_add_single_line() { assert_eq!( pos_of("12345") + pos_of("6789"), CompositePosition::new(9, 0, 9, 9) ) } #[test] fn test_add_newline() { assert_eq!(pos_of("12345") + pos_of("\n"), pos_of("12345\n")); } #[test] fn test_add_multiple_line() { assert_eq!( pos_of("12345\n12345") + pos_of("67\n12345"), CompositePosition::new(19, 2, 5, 5) ) } #[test] fn test_saturating_sub_minus_row() { assert_eq!( pos_of("\n\n\n\n123456").saturating_sub(pos_of("\n\n\n\n\n1")), ZERO ); } #[test] fn test_saturating_sub_minus_column() { assert_eq!( pos_of("\n\n\n\n123456").saturating_sub(pos_of("\n\n\n\n1234567")), ZERO ); } #[test] fn test_saturating_sub_equal() { let pos = pos_of("\n\n\n\n123456"); assert_eq!(pos.saturating_sub(pos), ZERO); } #[test] fn test_saturating_sub_plus_row() { assert_eq!( pos_of("\n\n\n12\n123456").saturating_sub(pos_of("\n\n\n12")), pos_of("\n123456") ); } #[test] fn test_saturating_sub_plus_column() { assert_eq!( pos_of("\n\n\n\n123456").saturating_sub(pos_of("\n\n\n\n1")), pos_of("23456") ); } #[test] fn test_display_zero() { assert_eq!(format!("{}", ZERO), "1:1"); } #[test] fn test_display_nonzero() { assert_eq!(format!("{}", pos_of("\n\n\nxx")), "4:3"); } }
def analyze(self, item): source = item.path if item.format not in ALLOWED_FORMATS: if config['echonest']['convert']: source = self.convert(item) if not source: log.debug(u'echonest: failed to convert file') return else: return log.info(u'echonest: uploading file, please be patient') track = self._echofun(pyechonest.track.track_from_filename, filename=source) if not track: log.debug(u'echonest: failed to upload file') return from_track = {} for key in ATTRIBUTES: try: from_track[key] = getattr(track, key) except AttributeError: pass from_track['duration'] = track.duration try: song_id = track.song_id except AttributeError: return from_track songs = self._echofun(pyechonest.song.profile, ids=[song_id], track_ids=[track.id], buckets=['audio_summary']) if songs: pick = self._pick_song(songs, item) if pick: return self._flatten_song(pick) return from_track
package net.ninjacat.cql.shell; /** * Thrown when internal shell failure happened, usually invalid command syntax */ public class ShellException extends RuntimeException { public ShellException(final String message) { super(message); } public ShellException(final String message, final Throwable cause) { super(message, cause); } }
<reponame>n01e0/ARIA<filename>tests/test_instruction.rs extern crate aria; #[cfg(test)] mod instruction { use aria::emulator:: { *, instruction::* }; #[test] fn instructions_name() { assert_eq!(instructions_with_name(0x01).1, "add_rm32_r32"); assert_eq!(instructions_with_name(0x3B).1, "cmp_r32_rm32"); assert_eq!(instructions_with_name(0x3C).1, "cmp_al_imm8"); assert_eq!(instructions_with_name(0x3D).1, "cmp_eax_imm32"); for i in 0x40 ..= 0x47 { assert_eq!(instructions_with_name(i).1, "inc_r32"); } for i in 0x50 ..= 0x57 { assert_eq!(instructions_with_name(i).1, "push_r32"); } for i in 0x58 ..= 0x5F { assert_eq!(instructions_with_name(i).1, "pop_r32"); } assert_eq!(instructions_with_name(0x68).1, "push_imm32"); assert_eq!(instructions_with_name(0x6A).1, "push_imm8"); assert_eq!(instructions_with_name(0x70).1, "jump_overflow"); assert_eq!(instructions_with_name(0x71).1, "jump_not_overflow"); assert_eq!(instructions_with_name(0x72).1, "jump_carry"); assert_eq!(instructions_with_name(0x73).1, "jump_not_carry"); assert_eq!(instructions_with_name(0x74).1, "jump_zero"); assert_eq!(instructions_with_name(0x75).1, "jump_not_zero"); assert_eq!(instructions_with_name(0x78).1, "jump_sign"); assert_eq!(instructions_with_name(0x79).1, "jump_not_sign"); assert_eq!(instructions_with_name(0x7C).1, "jump_less"); assert_eq!(instructions_with_name(0x7E).1, "jump_less_or_eq"); assert_eq!(instructions_with_name(0x83).1, "code_83"); assert_eq!(instructions_with_name(0x88).1, "mov_rm8_r8"); assert_eq!(instructions_with_name(0x89).1, "mov_rm32_r32"); assert_eq!(instructions_with_name(0x8A).1, "mov_r8_rm8"); assert_eq!(instructions_with_name(0x8B).1, "mov_r32_rm32"); for i in 0xB0 ..= 0xB7 { assert_eq!(instructions_with_name(i).1, "mov_r8_imm8"); } for i in 0xB8 ..= 0xBE { assert_eq!(instructions_with_name(i).1, "mov_r32_imm32"); } assert_eq!(instructions_with_name(0xC3).1, "ret"); assert_eq!(instructions_with_name(0xC7).1, "mov_rm32_imm32"); assert_eq!(instructions_with_name(0xC9).1, "leave"); assert_eq!(instructions_with_name(0xCD).1, "int"); assert_eq!(instructions_with_name(0xE8).1, "call_rel32"); assert_eq!(instructions_with_name(0xE9).1, "near_jump"); assert_eq!(instructions_with_name(0xEB).1, "short_jump"); assert_eq!(instructions_with_name(0xEC).1, "in_al_dx"); assert_eq!(instructions_with_name(0xEE).1, "out_dx_al"); assert_eq!(instructions_with_name(0xFF).1, "code_ff"); } #[test] fn instruction_mov_r32_imm32() { let mut emu = Emulator { registers: [0, 0, 0, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0xB8, 0x00, 0x00, 0x00, 0x00], eip: 0, }; emu.set_memory32(1, 0x01234567); instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.registers[0] as u32, 0x01234567 as u32); } #[test] fn instruction_mov_rm32_imm32() { let mut emu = Emulator { registers: [0, 0, 0, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0xC7, 0xC0, 0x00, 0x00, 0x00, 0x00], eip: 0, }; emu.set_memory32(2, 0x01234567); instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.registers[0], 0x01234567); } #[test] fn instruction_mov_rm32_r32() { let mut emu = Emulator { registers: [2, 0, 0, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x89, 0x00, 0x00, 0x00, 0x00, 0x00], eip: 0, }; instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.registers[0], emu.get_memory32(2)); } #[test] fn instruction_mov_r32_rm32() { let mut emu = Emulator { registers: [0, 2, 0, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x8B, 0x11, 0x00, 0x00, 0x00, 0x00], eip: 0, }; emu.set_memory32(2, 0x12345678); instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.registers[2], emu.get_memory32(2)); } #[test] fn instruction_mov_r8_imm8() { let mut emu = Emulator { registers: [0, 0, 0, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0xB0, 0xFF], eip: 0, }; instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.registers[0], 0xFF); } #[test] fn instruction_mov_r8_rm8() { let mut emu = Emulator { registers: [0, 2, 0, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x8A, 0b00000001, 0xFF], eip: 0, }; instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.registers[0], 0xFF); } #[test] fn instruction_mov_rm8_r8() { let mut emu = Emulator { registers: [0, 0xFF, 0x02, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x88, 0b00001010, 0x00], eip: 0, }; instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.memory[2], 0xFF); } #[test] fn instruction_add_rm32_r32() { let mut emu = Emulator { registers: [0, 0xF0, 0x0F, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x01, 0b11010001, 0x00], eip: 0, }; instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.registers[1], 0xFF); } #[test] fn instruction_add_rm32_imm8() { let mut emu = Emulator { registers: [0, 0xF0, 0x0F, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x83, 0b11000001, 0x0F], eip: 0, }; instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.registers[1], 0xFF); } #[test] fn instruction_update_eflags_sub() { let mut emu = Emulator { registers: [0, 0, 0, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x0], eip: 0, }; emu.update_eflags_sub(0x10, 0x01, (2u64).wrapping_sub(1u64)); assert!(!emu.eflags.is_carry()); assert!(!emu.eflags.is_zero()); assert!(!emu.eflags.is_sign()); assert!(!emu.eflags.is_overflow()); emu.update_eflags_sub(0x11, 0x11, 3u64.wrapping_sub(3u64)); assert!(!emu.eflags.is_carry()); assert!(emu.eflags.is_zero()); assert!(!emu.eflags.is_sign()); assert!(!emu.eflags.is_overflow()); emu.update_eflags_sub(0b10, 0b11, (2u64).wrapping_sub(3u64)); assert!(emu.eflags.is_carry()); assert!(!emu.eflags.is_zero()); assert!(emu.eflags.is_sign()); assert!(!emu.eflags.is_overflow()); emu.update_eflags_sub(0x80000000, 0x1, (-2147483648_i32).wrapping_sub(1i32) as u64); assert!(!emu.eflags.is_carry()); assert!(!emu.eflags.is_zero()); assert!(!emu.eflags.is_sign()); assert!(emu.eflags.is_overflow()); } #[test] fn instruction_sub_rm32_imm8() { let mut emu = Emulator { registers: [0, 0, 0, 0, 0xF0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x83, 0xec, 0x10], eip: 0, }; instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.get_register32(0x4), 0xE0); } #[test] fn instruction_inc_r32() { let mut emu = Emulator { registers: [0, 1, 0, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x41], eip: 0, }; instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.registers[1], 2); } #[test] fn instruction_inc_rm32() { let mut emu = Emulator { registers: [0, 0, 0, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0xFF, 0b11000111], eip: 0, }; instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.registers[7], 1); } #[test] fn instruction_push_r32() { let mut emu = Emulator { registers: [0, 0xFF, 0, 0, 0x5, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x51, 0x00, 0x00, 0x00, 0x00, 0x00], eip: 0, }; instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.get_memory32(1), 0xFF); } #[test] fn instruction_push_imm32() { let mut emu = Emulator { registers: [0, 0, 0, 0, 0x8, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x68, 0, 0, 0, 0, 0, 0, 0, 0], eip: 0, }; emu.set_memory32(1, 0x12345678); instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.get_memory32(4), 0x12345678); } #[test] fn instruction_push_imm8() { let mut emu = Emulator { registers: [0, 0, 0, 0, 0x6, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x6A, 0, 0, 0, 0, 0], eip: 0, }; emu.set_memory8(1, 0xFF); instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.get_memory32(2), 0xFF); } #[test] fn instruction_pop_r32() { let mut emu = Emulator { registers: [0, 0, 0, 0, 1, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0x58, 0, 0, 0, 0], eip: 0, }; emu.set_memory32(1, 0x12345678); instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.registers[0], 0x12345678); } #[test] fn instruction_short_jump() { let mut emu = Emulator { registers: [0, 0, 0, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0xEB, 0xFF], eip: 0, }; instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.eip, 1); } #[test] fn instruction_near_jump() { let mut emu = Emulator { registers: [0, 0, 0, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0xE9, 0, 0, 0, 0], eip: 0, }; emu.set_memory32(1, 0x12345673); instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.eip, 0x12345678); } #[test] fn instruction_call_rel32() { let mut emu = Emulator { registers: [0, 0, 0, 0, 5, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0xE8, 0, 0, 0, 0], eip: 0, }; emu.set_memory32(1, 0x12345673); instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.eip, 0x12345678); assert_eq!(emu.get_memory32(1), 5); } #[test] fn instruction_ret() { let mut emu = Emulator { registers: [0, 0, 0, 0, 1, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0xC3, 0, 0, 0, 0], eip: 0, }; emu.set_memory32(1, 0x12345678); instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.eip, 0x12345678); } #[test] fn instruction_leave() { let mut emu = Emulator { registers: [0, 0, 0, 0, 0, 0, 0, 0], eflags: Eflags { raw: 0 }, memory: vec![0xC9, 0, 0, 0, 0], eip: 0, }; emu.set_register32(Register::EBP as usize, 1); emu.set_memory32(1, 0x12345678); instructions(emu.get_code8(0)).unwrap()(&mut emu); assert_eq!(emu.registers[Register::EBP as usize], 0x12345678); } }
#include<iostream> using namespace std; int main() { long long n, a; cin>>n; n++; if(n==1) {cout<<0;return 0;} if(n%2) a=n; else a = n/2; cout<<a; }
Researchers in the US have made a graphene loudspeaker that has an excellent frequency response across the entire audio frequency range (20 Hz–20 kHz). While the speaker has no specific design, it is already as good as, or even better than, certain commercial speakers and earphones in terms of both frequency response and power consumption. Loudspeakers work by vibrating a thin diaphragm. These vibrations then create pressure waves in surrounding air that produce different sounds depending on their frequency. The human ear can detect frequencies of between 20 Hz (very low pitch) and 20 KHz (very high pitch), and the quality of a loudspeaker depends on how flat its frequency response is – that is, the consistency of the sound it produces over the entire 20 Hz–20 KHz range. “Thanks to its ultralow mass, our new graphene loudspeaker fulfils this important requirement because it has a fairly flat frequency response in the human audible region,” says team leader Alex Zettl of the University of California, Berkeley. He told physicsworld.com that the fact that “graphene is also an exceptionally strong material means that it can be used to make very large, extremely thin film membranes that efficiently generate sound”. Because the graphene diaphragm is so thin, the speaker does not need to be artificially damped (unlike commercial devices) to prevent unwanted frequency responses, but is simply damped by surrounding air. This means that the device can operate at just a few nano-amps and so uses much less power than conventional speakers – a substantial advantage if it were to be employed in portable devices, such as smartphones, notebooks and tablets. High-fidelity sound The Berkeley researchers made their loudspeaker from a 30 nm thick, 7 mm wide sheet of graphene that they had grown by chemical vapour deposition (CVD). They then sandwiched this diaphragm between two actuating perforated silicon electrodes coated with silicon dioxide to prevent the graphene from accidentally shorting to the electrodes at very large drive amplitudes. When power is applied to the electrodes, an electrostatic force is created that makes the graphene sheet vibrate, so creating sound. By changing the level of power applied, different sounds can be produced. “These sounds can easily be heard by the human ear and also have high fidelity, making them excellent for listening to music, for example,” says Zettl. The researchers have already tested their device against high-quality commercial earphones of a similar size (Sennheiser® MX-400) and found that its frequency response over the 20 Hz to 20 kHz range is comparable, if not better. The Berkeley team says that its CVD technique for fabricating the speaker is very straightforward and could easily be scaled up to produce even larger-area diaphragms and thus bigger speakers. “The configuration we describe could also serve as a microphone,” adds Zettl. A preprint of the research is available on the arXiv server.
/** * {@link StackedAreaRenderer} that delegates tooltip generation to * a separate object. * * @author Ulli Hafner */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("Eq") public class ToolTipAreaRenderer extends StackedAreaRenderer2 { /** Unique identifier of this class. */ private static final long serialVersionUID = -7373322043128362094L; /** The tooltip generator for the clickable map. */ private final SerializableToolTipGenerator toolTipGenerator; /** * Creates a new instance of {@link ToolTipAreaRenderer}. * * @param toolTipGenerator * the tooltip generator for the clickable map */ public ToolTipAreaRenderer(final SerializableToolTipGenerator toolTipGenerator) { super(); this.toolTipGenerator = toolTipGenerator; } @Override public String generateToolTip(final CategoryDataset dataset, final int row, final int column) { return toolTipGenerator.generateToolTip(dataset, row, column); } }
def db_create(self, name, type=DB_TYPE_DOCUMENT, storage=STORAGE_TYPE_PLOCAL): self.get_message("DbCreateMessage") \ .prepare((name, type, storage)).send().fetch_response() return None
def register_task_service(app: Flask) -> None: if os.environ.get("WERKZEUG_RUN_MAIN") != 'true': celery_app = create_celery_app(app) return None
async def visibility_service_handler(service): visible = service.data.get(ATTR_VISIBLE) tasks = [] for group in component.async_extract_from_service(service, expand_group=False): group.visible = visible tasks.append(group.async_update_ha_state()) if tasks: await asyncio.wait(tasks, loop=hass.loop)
/** * Builds instances of {@link RyaDetails}. */ @DefaultAnnotation(NonNull.class) public static class Builder { // General metadata about the instance. private String instanceName; private String version; private final List<String> users = new ArrayList<>(); // Secondary Index Details. private EntityCentricIndexDetails entityCentricDetails; private GeoIndexDetails geoDetails; private PCJIndexDetails.Builder pcjIndexDetailsBuilder; private TemporalIndexDetails temporalDetails; private FreeTextIndexDetails freeTextDetails; // Statistics Details. private ProspectorDetails prospectorDetails; private JoinSelectivityDetails joinSelectivityDetails; /** * Construcst an empty instance of {@link Builder}. */ public Builder() { } /** * Constructs an instance of {@link Builder} that is initialized with * a {@link RyaDetails}'s values. * * @param detials - The builder will be initialized with this object's values. (not null) */ public Builder(final RyaDetails details) { requireNonNull(details); instanceName = details.instanceName; version = details.version; users.addAll( details.users ); entityCentricDetails = details.entityCentricDetails; //RYA-215 geoDetails = details.geoDetails; pcjIndexDetailsBuilder = PCJIndexDetails.builder( details.pcjDetails ); temporalDetails = details.temporalDetails; freeTextDetails = details.freeTextDetails; prospectorDetails = details.prospectorDetails; joinSelectivityDetails = details.joinSelectivityDetails; } /** * @param instanceName - The name that uniquely identifies the instance of Rya within * the system that hosts it. * @return This {@link Builder} so that method invocations may be chained. */ public Builder setRyaInstanceName(@Nullable final String instanceName) { this.instanceName = instanceName; return this; } /** * @param version - The version of Rya this instance uses. * @return This {@link Builder} so that method invocations may be chained. */ public Builder setRyaVersion(@Nullable final String version) { this.version = version; return this; } /** * @param user - A user who is granted access to the Rya instance. * @return This {@link Builder} so that method invocations may be chained. */ public Builder addUser(final String user) { users.add( user ); return this; } /** * @param user - A user who is revoked access to the Rya isntance. * @return This {@link Builder} so that method invocations may be chained. */ public Builder removeUser(final String user) { users.remove( user ); return this; } /** * @param entityCentricDetails - Information about the instance's Entity Centric Index. * @return This {@link Builder} so that method invocations may be chained. */ public Builder setEntityCentricIndexDetails(@Nullable final EntityCentricIndexDetails entityCentricDetails) { this.entityCentricDetails = entityCentricDetails; return this; } /** * * @param geoDetails - Information about the instance's Geospatial Index. * @return This {@link Builder} so that method invocations may be chained. */ /*//RYA-215 * public Builder setGeoIndexDetails(@Nullable final GeoIndexDetails geoDetails) { this.geoDetails = geoDetails; return this; }*/ /** * @param temporalDetails - Information about the instance's Temporal Index. * @return This {@link Builder} so that method invocations may be chained. */ public Builder setTemporalIndexDetails(@Nullable final TemporalIndexDetails temporalDetails) { this.temporalDetails = temporalDetails; return this; } /** * @param freeTextDetails - Information about the instance's Free Text Index. * @return This {@link Builder} so that method invocations may be chained. */ public Builder setFreeTextDetails(@Nullable final FreeTextIndexDetails freeTextDetails) { this.freeTextDetails = freeTextDetails; return this; } /** * @param pcjDetails - Information about the instance's Precomputed Join Index. * @return This {@link Builder} so that method invocations may be chained. */ public Builder setPCJIndexDetails(@Nullable final PCJIndexDetails.Builder pcjDetailsBuilder) { pcjIndexDetailsBuilder = pcjDetailsBuilder; return this; } /** * @return Get the {@link PCJIndexDetails.Builder} used to build the * PCJ Index's details. */ public @Nullable PCJIndexDetails.Builder getPCJIndexDetails() { return pcjIndexDetailsBuilder; } /** * @param prospectorDetails - Information about the instance's Prospector Statistics. * @return This {@link Builder} so that method invocations may be chained. */ public Builder setProspectorDetails(@Nullable final ProspectorDetails prospectorDetails) { this.prospectorDetails = prospectorDetails; return this; } /** * @param joinSelectivityDetails - Information about the instance's Join Selectivity Statistics. * @return This {@link Builder} so that method invocations may be chained. */ public Builder setJoinSelectivityDetails(@Nullable final JoinSelectivityDetails joinSelectivityDetails) { this.joinSelectivityDetails = joinSelectivityDetails; return this; } /** * @return An instance of {@link RyaDetails} built using this * builder's values. */ public RyaDetails build() { return new RyaDetails( instanceName, version, ImmutableList.copyOf( users ), entityCentricDetails, //RYA-215 geoDetails, pcjIndexDetailsBuilder.build(), temporalDetails, freeTextDetails, prospectorDetails, joinSelectivityDetails); } }
James Myburgh on what the Trayvon Martin case says about the US media and judicial systems Introduction Last month's not guilty verdict in the trial of George Zimmerman on second degree murder and manslaughter charges for the killing of the black 17-year-old Trayvon Martin, in Sanford, Florida, on February 26 last year, has provoked a flurry of discussion in the US mainstream media on the issues of racial profiling and Stand Your Ground laws (which remove the duty to retreat in self-defence cases.) President Barack Obama even weighed in again on the case stating that Martin "could have been me 35 years ago" while calling for the problem of racial profiling of black Americans in the US to be recognised and addressed and Stand Your Ground Laws re-examined. Somewhat awkwardly, however, neither were ultimately key issues in the case. Zimmerman's defence rested on a pure self-defence claim (he was not in a position to retreat when he shot Martin), while the prosecution, much as they would have liked to, could produce no evidence of racial profiling or bias on Zimmerman's part. The question this raises is why the US political and media elites are so determined to link the Zimmerman acquittal to these racially-infused issues, though they turned out to be effectively irrelevant to the case? One possible answer is, perhaps, that it is a way of avoiding through misdirection having to face up to certain hard questions the trial raised about their own conduct. Following the verdict Zimmerman's two lawyers - Don West and Mark O'Mara - held a press conference. West commented that the verdict prevented the tragedy of Trayvon Martin's death from becoming a travesty of justice. O'Mara was asked by a reporter whether his client had ever cried or shown emotion. He noted in reply that Zimmerman had been turned into the "most hated man in America" (as some had called him) for having defended his own life. He had also been a great believer in a justice system that he had always wanted to be part of, either as a cop or a prosecutor. O'Mara continued: "Two systems went against George Zimmerman that he can't understand: You guys, the media. He was like a patient in an operating table where mad-scientists were committing experiments on him and he had no anaesthesia. He didn't know why he was turned into this monster but quite honestly, you guys had a lot to do with it. You just did because you took a story that was fed to you, and you ran with it, and you ran right over him. And that was horrid to him. Then he comes into a system that he trusts. Let's not forget, six voluntary statements, voluntary surrender, and he believes in the system that he really wanted to be part of... right? And then he gets prosecutors that charge him with a crime they could never ever prove. They didn't lose evidence along the way... right? So, I don't think anyone would argue with me in this room that they had evidence of second degree murder. This, in your heart kind of stuff [prosecutors asked the jury to ‘look into their hearts' rather than at the evidence when deciding the verdict during closing arguments], is not what we're supposed to do and not what they are supposed to do. So those two systems failed him." This challenge, though reported on, has provoked very little serious introspection by the mainstream media in the US. This is a pity, for if O'Mara is right about how those two systems failed Zimmerman, they will sooner or later fail others - with possibly more deadly results. This article then will trace the evolution of the controversy over the shooting death of Trayvon Martin and the way information was presented (or "fed") to the press, and measure it against what we now know. It will then go on to discuss what this case says about the "two systems" that sought to have George Zimmerman arrested, tried and sent to jail for life. The shooting On the evening of February 26 George Zimmerman shot and killed Trayvon Martin in the Retreat at Twin Lakes townhouse development in Sanford, Florida. Zimmerman surrendered to police at the scene, was handcuffed, disarmed, and taken into custody. He waived his Miranda rights and gave both a verbal and written statement of what had happened, explaining that he had shot Martin in self-defence. He was released that night and the following afternoon (February 27) he walked the investigators through the scene of the incident - and explained the events that had led up to the shooting, this time placing them in their physical context. That day he also voluntarily underwent a Voice Stress Test (a kind of lie detector test) which he passed. Initially the police had been unable to identify Trayvon Martin. But on the morning of February 27 Tracy Martin, Trayvon's father, phoned in to report his son missing. The investigating officer Chris Serino drove out to meet him at his girlfriend Brandy Green's home at the Retreat - where Trayvon Martin had been staying - and Tracy Martin identified the dead teenager as his son from a crime scene photograph. At 10:30am the following day (February 28) Serino briefed Tracy Martin on the case and explained Zimmerman's account of what had happened, why no arrest had yet been made (given the available evidence), and that investigations were continuing. He also played a recording of various 911 recordings. In one of these a voice can be heard desperately screaming for help. Serino asked Tracy Martin whether that was his son's voice. Martin responded "no". Serino did not, however, play the recording of Zimmerman's call to the police non-emergency number (NEN) before the shooting though Martin was informed of its existence. Martin, through a contact, proceeded to reach out to Benjamin Crump - a Tallahassee lawyer, who had secured a settlement for $7.2 million in damages from the state of Florida and Bay County for the family of a black teenager who had died in a boot-camp style detention centre in 2006. Crump brought in another lawyer, Natalie Jackson, whose mother lived in Sanford and she, in turn, engaged Ryan Julison a publicist with whom she had worked in the past. Trayvon Martin's body was released to the family that week, and his funeral was held on March 3. Up until this point there had been a few limited reports (see here and here) in the local news media - but most did not name either Trayvon Martin or George Zimmerman. The controversy It is important to note what Tracy Martin and Sybrina Fulton, his ex-wife and the mother of Trayvon, knew at this time. Tracy Martin had been fully briefed about George Zimmerman's account of what had happened and the evidence, such as it was, that seemed to support it. Martin and Fulton were also obviously familiar with their son and his background, particularly his recent record at school. The police had already collected substantial evidence as well as numerous statements from Zimmerman. But the investigation was ongoing and they were keeping the information they had collected confidential. George Zimmerman and his family meanwhile were not talking to reporters. There was a critical two week gap in which the Martin family and their legal and public relations team were able to aggressively push their account of what had happened, with very weak contestation from the police and none from Zimmerman himself. In this period the Martin team was able to frame the story in the public imagination, and instigate the national outcry which ultimately drove the arrest and prosecution. On March 7 Reuters ran an article on the shooting based almost entirely on information provided to it by Crump and Julison. In the article Crump describes Trayvon Martin as a "good kid" in junior high who wanted to be a pilot, and Zimmerman (whom he named) as the white "Neighbourhood Watch loose cannon" who shot and killed him. Crump said that Trayvon lived in Miami with his mother, but was visiting his father and stepmother, Brandy Green. He had taken a break from watching the NBA All Stars game to go to a local convenience store to buy snacks, including skittles for Green's son Chad. On his return to the Retreat Zimmerman had spotted him and phoned "911" (actually the NEN) to report a suspicious person in the neighbourhood. Crump said Zimmerman had not waited for the police to arrive and instead got out of his car and confronted Martin. By the time the police got to the scene Martin was dead of a single gunshot to the chest. "What do the police find in his pocket? Skittles," Crump told Reuters. "A can of Arizona ice tea in his jacket pocket and Skittles in his front pocket for his brother Chad." Crump said the family was demanding the release of Zimmerman's call to police. "If he never gets out of his car, there is no reason for self-defense. Trayvon only has skittles. He has the gun." Crump added that given that Trayvon Martin was black and Zimmerman was white, race was "the 600 pound elephant in the room. Why is this kid suspicious in the first place? I think a stereotype must have been placed on the kid." The following morning CBS This Morning aired a report on the case. Although it was fairly soberly reported it did contain an animated graphic showing the Zimmerman figure shooting the Martin figure from several feet away. The programme quoted Tracy Martin as saying of Trayvon "He was up here to relax. He wasn't up here to return home in a body bag. That's the part that tears me up." Tracy Martin questioned Zimmerman's self-defence claim stating: "Why would he attack this guy? He don't know this guy. What was he going to do -- attack him with a pack of skittles?" That day the Martin family team released several pictures of Trayvon Martin "throughout his young life." These included a picture of a cherubic looking Trayvon Martin in a maroon Hollister t-shirt which would be used in many subsequent reports of the case. That day Tracy Martin and Sybrina Fulton posted a petition on the www.change.org website initially directed towards Florida's 18th District State's Attorney Norm Wolfinger*, Florida Attorney General Pam Bondi, Sanford Police Chief Bill Lee. Their appeal for signatories stated: On February 26, our son Trayvon Martin was shot and killed as he walked to a family member's home from a convenience store where he had just bought some candy. He was only 17 years-old. Trayvon's killer, George Zimmerman, admitted to police that he shot Trayvon in the chest. Zimmerman, the community's self appointed "neighborhood watch leader," called the police to report a suspicious person when he saw Travyon, a young black man, walking from the store. But Zimmerman still hasn't been charged for murdering our son. Trayvon was our hero. At the age 9, Trayvon pulled his father from a burning kitchen, saving his life. He loved sports and horseback riding. At only 17 he had a bright future ahead of him with dreams of attending college and becoming an aviation mechanic. Now that's all gone. When Zimmerman reported Trayvon to the police, they told him not to confront him. But he did anyway. All we know about what happened next is that our 17 year-old son, who was completely unarmed, was shot and killed. It's been nearly two weeks and the Sanford Police have refused to arrest George Zimmerman. In their public statements, they even go so far as to stand up for the killer - saying he's "a college grad" who took a class in criminal justice. Please join us in calling on Norman Wolfinger, Florida's 18th District State's Attorney, to investigate my son's murder and prosecute George Zimmerman for the shooting and killing of Trayvon Martin. On Friday March 9 Crump filed paperwork demanding the release of all 911 and NEN calls. The same day the Martin family team held a protest outside of the Sanford Police Department along with some two dozen protestors. It was at this point that WFTV uncovered a mug shot of a heavy-set, unshaven and scowling George Zimmerman following his arrest for "Battery on a Law Enforcement Officer" and "resisting arrest with violence", charges it said were later dismissed. This photo of George Zimmerman was, for the next few weeks, the only one available and media reports would consistently juxtapose it against the Hollister picture of Trayvon Martin. See picture below. On being presented with this new information a tearful Sybrina Fulton told WFTV that "as a mother my heart is broken." The WFTV report claimed that Zimmerman had phoned police to "report a suspicious black man in the neighbourhood and even though dispatchers reportedly told him not to confront the teenager he did. They got into a scuffle and Zimmerman shot the teenager in the chest." On Monday, March 12, Sanford Police Department Chief Bill Lee held a press conference on the status of the investigation. He said that the police didn't have any evidence to dispute Zimmerman's claim of self-defence but the matter was being turned over to State Attorney Norman Wolfinger for a determination. The WFTV report on Lee's press conference again stated that Zimmerman had phoned police to "report a suspicious black man in the predominantly white neighbourhood." A WESH 2 report said that police had called for anyone that they hadn't interviewed, who knew anything about what happened, to please get in contact with them. On March 15 2012 the Miami Herald interviewed Sybrina Fulton. A journalist asked Fulton: "Were you surprised to know that your son might have been in such an altercation, in Sanford, knowing his personality, knowing who he was...?" She replied: "Yes it surprised me that he got into an altercation..." "Why?" the reported asked. "Because that is not something that normally happens," Fulton replied, "He doesn't normally... he gets along with... he respects adults. He gets along with his peers. That wasn't something that's normal for him, to get into a fist fight, especially with an adult. So, of course I was surprised." On March 15 WFTV ran an interview with Mary Cutcher, a witness it said had heard "a Sanford vigilante gun down a teenager on February 26". Cutcher told WFTV's Darlene Jones that "the cries stopped as soon as the gun went off. So I know it was the little boy." She said that she knew this was not self defence as "there was no punching, no hitting going on at the time. No wrestling." WFTV said Cutcher believed that Zimmerman tried to chase down Martin as he tried to get home. Early the following morning another WFTV reporter interviewed Crump and Tracy Martin on their way out to their car. Asked why George Zimmerman should be charged with murder Tracy Martin replied: "My son was murdered. It wasn't an accident. My son did nothing to warrant it." Asked "how do you know it wasn't an accident? And why are you calling for Sanford Police Chief Bill Lee to resign?" Crump interjected: "We have no faith in the investigation. We believe it hasn't been fair and impartial at all... that this kid was killed in cold blood but yet they chose at every step of the way to protect George Zimmerman." Later that morning the Martin family team held a press conference with Mary Cutcher and her housemate Selma Mora. Cutcher told journalists that "she heard the crying. It was a little boy. As soon as the gun went off the crying stopped. Therefore it tells me it was not Zimmerman crying." Mora meanwhile said that she had "heard the whine of a kid". Natalie Jackson told the journalists that "George Zimmerman profiled Trayvon because of race." She said Zimmerman "followed, stalked and pulled the trigger on Trayvon because he thought he had the authority to do so. He thought he was the police." She added that that day Zimmerman "was patrolling the neighbourhood as armed security." A journalist at the press conference noted that the police report had said that George Zimmerman had had a bloody nose and bloodied back of his head after the incident. She then asked Sybrina Fulton "has your son been known to fight?" Fulton replied: "He has never been in trouble. He has never been arrested. The only thing I can say is that he was afraid and he was trying to defend himself." The journalist then asked: "He's never been in a fight ever...?" Fulton replied: "He's never been in a fight that I know of." During the press conference Crump reiterated that Trayvon Martin was "shot down and killed in cold blood." He also stated that the Martin family had no faith in the police investigation and that they had written to State Attorney Eric Holder asking him to launch a Department of Justice investigation. Later that day the Martin family was played George Zimmerman's NEN call to police as well as the various 911 calls before and after the shooting, ahead of their public release later that evening. Bill Lee had argued against the release of the tapes but was overruled by Mayor Jeff Triplett. The tapes were played to the Martin family and their lawyers, as a group, in Triplett's office, with no law enforcement officers present. In comments to the media afterwards Crump said that Tracy Martin and Sybrina Fulton were completely devastated "to hear their son being killed on that 911 tape, to hear his pleas, to hear - what now three witness have said... the young man crying out for help before George Zimmerman shot him in cold blood." Natalie Jackson commented that "The most shocking thing to me is you hear a shot, a warning shot. Then you hear a 17-year-old boy begging for his life, and then you hear another shot." In an interview a few days later CNN's Anderson Cooper asked Sybrina Fulton whether she believed the person crying out for help on the 911 tape was her son. She replied: "Yes I do. I believe that is Trayvon Martin. That is my baby's voice. Every mother knows their child. And that's his voice." Asked by Cooper what the significance of this was Tracy Martin stated: "He was afraid for his life. He saw his death coming. He saw his death coming. The screams got more frantic-er... and at that second that we heard the shot the screams just completely stopped. He saw his death. He was pleading for his life." In the same interview Crump - who was sitting on the sofa with Tracy Martin and Sybrina Fulton - commented: "This really came down to the fact that he [Zimmerman] saw a young black male coming into a gated community and he made a conscious decision in his mind that he [Trayvon Martin] is not supposed to be here. He must be up to no good, he must be high... all these stereotypes he put on this kid. And when you look how these parents raised their son they did a good job raising their son... He was almost adult. He was almost a man. 17 years old. He was beating all the statistics that they try to put on young minorities." The pictures the family had released of a young and innocent looking Trayvon Martin were reinforced by the testimonials of good conduct by his family, friends and teachers. A March 17 article in the Orlando Sentinel said that Michelle Kypriss, Trayvon Martin's English teacher at Dr. Michael M. Krop Senior High School in Miami, "described Trayvon, a junior, as an A and B student who majored in cheerfulness." The article noted however that "Trayvon was under a five-day suspension when he was shot that Sunday night, but Kypriss said it was due to tardiness and not misbehaviour. ‘Trayvon was not a violent or dangerous child. He was not known for misbehaving,' the teacher said. ‘He was suspended because he was late too many times'." A New York Times article that same day stated that: "Trayvon had no criminal record. He was suspended from his Miami high school for 10 days in February, which is the reason he was visiting his father. The family said the suspension was not for violent or criminal behaviour but for a violation of school policy." A Miami Herald feature a few days later described Trayvon Martin as "6-foot-3, 140 pounds, a former Optimist League football player with a narrow frame and a voracious appetite. He wanted to fly or fix planes, struggled in chemistry, loved sports video games and went to New York for the first time two summers ago... He hoped to attend the University of Miami or Florida A&M University, enamored by both schools' bright orange and green hues." The article stated that "Trayvon's parents - his mother is a Miami-Dade government employee and his dad is a truck driver - divorced in 1999 but lived near each other in Miami Gardens, working hard to raise Trayvon with family values and lift him above the statistics." The article quoted Sybrina Fulton as saying that Trayvon Martin "had been so looking forward to going to his junior prom, and he had already started talking about all the senior activities in high school. He will never do any of those things.'' Tracy Martin described his son to the newspaper as "a beautiful child. He was raised to have manners and be respectful. He was a teenager who still had a lot of kid in him." Trayvon Martin had attended Miami Carol City High School before being transferred to Dr. Michael M. Krop. One of his teachers at Carol City, Ashley Gantt, described him as "just a sweet kid. He got As and Bs. If he received a C on an assignment, it was because he was just being a kid that day. He was very smart." The article noted that "Still, Trayvon had nonviolent behavioral issues in school, and on the day he was killed, he had been suspended for 10 days from Dr. Michael M. Krop Senior High School in North Miami-Dade. ‘He was not suspended for something dealing with violence or anything like that. It wasn't a crime he committed, but he was in an unauthorized area [on school property]," Martin said, declining to offer more details'." On Tuesday March 20 Crump held a press conference where he announced the existence of an ear-witness whose testimony, he said, "blows George Zimmerman's absurd self defence claim out of the water." Crump said that on Sunday evening (March 18) Tracy Martin was examining phone records when he noticed that Trayvon had been on the phone with someone for some 400 minutes on the day of the shooting and, indeed, had been speaking with Trayvon until shortly before he was shot and killed. The following day (Monday, March 19) Crump conducted a telephonic interview with the witness - in the presence of inter alia Tracy Martin, Sybrina Fulton and Matt Guttman of ABC News. In his press conference on the Tuesday Crump described this witness in the following terms: "She is a minor. Her parents are very worried about her. She is traumatized over this. This was her really, really close personal friend. They were dating. And so it's a situation where to know that you were the last person to talk to the young man who you thought was one of the most special people in the world to you, and know that he got killed moments after he was talking to you, is just riveting to this young lady. In fact, she couldn't even go to his wake she was so sick. Her mother had to take her to the hospital. She spent the night in the hospital. She is traumatized beyond anything you could imagine." Guttman, who also interviewed the witness, described her as Martin's "girlfriend". Guttman said she was a "16-year-old girl, who is only being identified as DeeDee." Crump then claimed that DeeDee (though he did not call her this in the press conference) "connects the dots" in George Zimmerman's NEN call. He stated that Trayvon Martin had decided "to go to the store to get some snacks before the NBA all-star game is about to start." Martin was talking to her on the way there and back again. Martin was "his regular self, all this stuff about him being high and stuff is preposterous. It's what Zimmerman wants you to believe so he can justify killing this kid in cold blood. Trayvon Martin's mother and dad and all of his teachers, they have given the information about what kind of person Trayvon Martin was." He also described as preposterous the claim that Trayvon Martin "was the aggressor". Crump added that when Martin "came out from the store, he said it was starting to rain, he was going to try to make it home before it rained. Then he tells her it starts raining hard. He runs into the apartment complex and runs to the first building he sees to try to get out of the rain. He was trying to get shelter. So he tries to get out of the rain. And unbeknownst to him, he is being watched...." According to DeeDee's account, transmitted by Crump, Martin then desperately tried to escape from Zimmerman who chased him down before finally confronting him. "She says that Trayvon says he's going to try to lose him. He's running trying to lose him. He tells her, I think I lost him. So, he's walking and then she says that he says very simply, oh, he's right behind me. He's right behind me again. And so she says "run." He says, I'm not going to run. I'm going to walk fast. At that point, she says Trayvon -- she hears Trayvon say, why are you following me. She hears the other boy say, what are you doing around here. And again, Trayvon says, why are you following me. And that's when she says again he said, what are you doing around here. Trayvon is pushed. The reason she concludes, because his voice changes like something interrupted his speech. Then the other thing, she believes the earplug fell out of his ear. She can hear faint noises but no longer has the contact. She hears an altercation going and she says, then suddenly, somebody must have hit the phone and it went out because that's the last she hears." This was proof, Crump argued, that George Zimmerman had continue to pursue Trayvon Martin after the NEN dispatcher told him not to do so. Crump concluded the press conference by demanding: "Arrest George Zimmerman for the killing of Trayvon Martin in cold blood today. Arrest this killer. He killed this child in cold blood. Right now, he is free as a jay bird, he's allowed to go and come as he please while Trayvon Martin is in a grave." In a March 22 2012 interview Anderson Cooper asked Tracy Martin about the police report indicating that Zimmerman had "had blood on the back of his head, on his face. Have they said anything to you about how it got there? If it was his blood or your son's blood. Have they given you details?" Martin replied: "They told me that it was an altercation between the two individuals. But the details, they didn't give them to me." (Ten days later he gave a detailed and largely accurate exposition to a Reuters journalist of Zimmerman's account - as related to him by Chris Serino on February 28.) On March 26 the Miami Herald reported that Trayvon Martin had been suspended from school on at least three occasions - and it provided the reasons for two of those suspensions. As to the third suspension the article quoted the family as saying, "Trayvon had earlier been suspended for tardiness and truancy." In reaction to this report Crump replied angrily: "Trayvon was an average kid. He never gave evidence of any violence. Trayvon is dead and can't defend himself. Had Zimmerman not disobeyed the dispatcher and gotten out of the car, Trayvon would be alive. That we do know." Following Crump's press conference on March 20 the Federal, State and Local Government authorities obediently lined up behind the Martin team's demands. On that day the Department of Justice announced that the Federal Bureau of Investigation would be looking into the case. On March 21 the Sanford City Commission voted 3 to 2 that they had "no confidence" in Police Chief Bill Lee. Lee announced the next day he would "temporarily" step down. (He was fired permanently a few months later.) On March 22 Florida Governor Rick Scott and his Attorney General Pam Bondi prevailed upon Norman Wolfinger to step down from the investigation - and hand it over to Angela Corey. Then, during a press conference at the White House, President Obama made very clear where his sympathies lay. He told reporters: "I think all of us have to do some soul searching to figure out how does something like this happen. And that means that examine the laws and the context for what happened, as well as the specifics of the incident. But my main message is to the parents of Trayvon Martin. If I had a son, he'd look like Trayvon. And I think they are right to expect that all of us as Americans are going to take this with the seriousness it deserves, and that we're going to get to the bottom of exactly what happened." Obama's comments helped turn a growing wave of outrage over the killing and the non-arrest of Zimmerman into a tsunami. On March 21 over a million people had signed the Martin family petition calling for the arrest of George Zimmerman. By March 26 this had risen to two million. Hoodie marches were held across the country. Zimmerman and his family were subjected to numerous public death threats and were living in fear of their lives - as various celebrities decided to try and out their home addresses on Twitter. Much of the media too seemed to have largely bought into the version of events that had been provided to them by the Martin team - and they started publishing inadequately vetted information that appeared to buttress that account. WFTV described Zimmerman as a "vigilante" in its reports. NBC edited Zimmerman's NEN call to make it appear that he had racially profiled Martin. ABC News screened blurred CCTV footage from the Sanford police station following the shooting on February 26 which apparently showed Zimmerman being led in without blood or bruises. NBC News also reported that "In August 2005, Zimmerman's ex-fiancee, Veronica Zuazo, filed a civil motion for a restraining order alleging domestic violence. Zimmerman counterfiled for a restraining order against Zuazo. The competing claims were resolved with both restraining orders being granted." The Orlando Sentinel found a "leading expert in the field of forensic voice identification" who analyzed the screams on the 911 call and concluded: "It was not George Zimmerman who called for help." WFTV, ABC News and CNN suggested that Zimmerman had muttered the racial slur "fucking coons" under his breath on the NEN call as he followed after Trayvon Martin. CNN would later walk back this claim stating that Zimmerman had muttered "fucking cold" (he had actually said "fucking punks.") In a front page story the New York Times claimed that Zimmerman had made 46 calls to 911 over the past fourteen months (it was actually over an eight year time period.). On CNN Anderson Cooper stated that "dispatchers told Zimmerman not to even get out of his car... He apparently followed Trayvon Martin, and at about 100 yards away from where Trayvon was going to meet his dad, confronted him." These and other reports were rapidly picked up by other media and transmitted across the world as proven fact. On Tuesday, April 10, the Grand Jury was due to convene to consider the evidence in the case and decide whether there was probable cause to charge George Zimmerman. However on April 9 Angela Corey said that she was going to bypass the Grand Jury process and make the decision on whether to charge Zimmerman herself. On April 11 she announced that she was charging Zimmerman with Second Degree Murder - a crime which carried with it a sentence of up to life in prison. The probable cause affidavit produced to justify the arrest regurgitated many of the claims made by the Martin family through the course of March. The affidavit said Zimmerman "profiled" Trayvon Martin and "assumed he was a criminal." It cited Trayvon Martin's "friend's" testimony and stated that Zimmerman had continued to pursue Martin after the police dispatcher had told him not to do so. It also relied upon Sybrina Fulton's claim that the cries heard on the 911 recording were those of Trayvon Martin. The affidavit made no reference to Zimmerman's claim of self-defence or any evidence that may have supported it. Images of Trayvon Martin and George Zimmerman The image presented of George Zimmerman in those first two weeks was of a thuggish-looking, white, violence prone, gun toting vigilante who had pursued, confronted and then shot Martin in cold blood (despite the latter's desperate pleas for mercy) after racially profiling him as a criminal. By contrast, Martin - who looked "younger than his 17 years", as one article put it - was an innocent. He was an A and B student planning on going to University whom, it was initially claimed, had never got in trouble or been involved in crime or violence. It later turned out that George Zimmerman was neither white nor racially-minded. Indeed, he was something of a poster-child for post-racial America. His mother was Peruvian and of mixed racial ancestry (including black African ancestry). His father was a white American. He was fluent in both Spanish and English. He grew up in a completely multi-racial family environment, had black foster-siblings as a child, took a black girl to the prom, had close black friends and mentored two black children from the ghetto along with his wife. The FBI interviews of over 30 of his colleagues and acquaintances could find no evidence of anti-black prejudice or stereotyping. He had been arrested in 2005 after, according to his version, he went to the aid of a friend in the bar who was being accosted by someone in civilian dress. It turned out that person was an undercover drug and alcohol agent and he was promptly arrested. The charges were later reduced to nothing after he agreed to undergo a pre-trial diversion programme. He had helped initiate, and went on to be duly appointed as co-ordinator for, the neighbourhood watch programme at the Retreat at Twin Lakes. This was after a spate of burglaries, and one home invasion, mostly by young black males. His ex-fiancée - with whom he had had an acrimonious relationship that ended in both taking out restraining orders against the other - told the FBI that Zimmerman "was not the type of person to place himself in a physical confrontation." In the trial he was described as "meek" by the Sanford Police's neighbour watch organiser, Wendy Dorival, and "physically soft" by his gym instructor Adam Pollock. The picture of Trayvon Martin, presented by the Martin team, in March 2012, has subsequently been proven to be highly misleading; in one respect literally so. The photograph of Martin in a Hollister shirt was of when he was, according to one article, twelve years old. The first tranche of images released by Martin's family, all of a much younger Trayvon, appear to have tainted a number of witnesses' testimony. Martin was not a "little boy" on February 26 2012. He was over 6 foot and weighed over 158lbs. For many boys making the transition from adolescence to successful adulthood can be a treacherous game of snakes and ladders. It is now apparent that, whatever his earlier promise, Trayvon Martin was on a rapid downward slide at the time his path intersected with that of Zimmerman's. According to a sympathetic profile in Esquire he had failed the FCAT, the Florida standardised test that he needed in order to graduate and progress on to college. He had also "missed fifty-three days of school between August and February." He regularly smoked marijuana, had an interest in street fighting and, it seems, was involved in petty criminality as well. This was reflected in his three suspensions from school in the four months leading up to February 26. The first of these occurred on October 20 2011 after Trayvon Martin was observed by the principal Francisco Garnica on the school's CCTV camera system in "an unauthorised area (3122 hallway) hiding and being suspicious". As Martin exited the hallway door he was seen writing on it. "Upon reading the graffiti it read W.T.F (what the fuck)." The following day Garnica found Martin, who was known to him, and looked for the marker in the bag. "There he discovered numerous women's jewelry and a large screwdriver (burglary tool)." Miami Dade School Resource Officer Darryl Dunn was called. "When asked did the items belong to his mother, family members or girlfriend Martin replied it's not mine. A friend gave it to me. Martin declined to give his friends name." Martin was "suspended, warned and dismissed for the graffiti." The various items of jewelry and the burglary tool were impounded. However, they were listed as "found" not "stolen" property as, it appears, the Miami-Dade School Police Department were under pressure to keep crime statistics down. As a result the case was buried within the school disciplinary system and not subjected to criminal investigation (or linked to any recent burglaries in the area). The second suspension appears to have been for fighting. In a text message exchange extracted from his cellphone, dated November 7 2011, he was asked by a correspondent "You Didn't Go to School?" He replied: Naw I'm suspended SMH Just chill Wat Yhuu Did? Fightn In another exchange two weeks later (November 21 2011) he commented that he was "Tired nd sore": His correspondent replied: Me too, but wat happen tah yuhh?? Fight Y!? Cause man dat nigga snitched on me Bae y yuu always fightinqq man, yu got suspended? Naw we thumped afta skool in a ducked off spot Oh well Damee I lost da 1st [round] :( but won da 2nd nd 3rd Ohh So It Wass 3 Rounds? Damee well at least yu won lol but yuu needa stop fightinqq bae Forreal Naw im not done wit fool...he gone have 2 see me a again Nooe bae Stop, yuu aint qonn bee satisfied till yuh qet suspended again huh? Naw but he aint breed [bleed] nuff 4 me, only his nose... but afta dat im done. Wow Smh! In a text message sent the follow day he commented on his loss in the first round: "Yea cause he got mo hits cause in da 1st round he had me on da ground nd i couldn't do ntn." That evening he told a correspondent via text message that his mother had just told him she was kicking him out the house: My mom just told me i gotta move wit my dad So what does that mean? She just kicked me out :( Stop lying I promise u my mom just told me i gotta move What did you do now? Da police caught me outta skool Lol really dude? Yea So you just turning into a lil hoodlum No not at all Yes U a hoodlum Naw I'm a gangsta Lies.com...lol u soft Boy don't get one planted in your chest Lol im scared You should be This decision was given effect the following month and he moved in with his father on December 22 2011. In mid-February 2012 Trayvon Martin was again suspended (until the 29th), after being bust at school with a marijuana pipe and a baggie with marijuana residue in it. On Tuesday February 21 2012 he was sent by bus to Orlando to stay with Brandy Green and her son Chad in the Retreat at Twin Lakes. He took marijuana with him, which he smuggled on his person. Thus, although the Martin family's initial testimony about Trayvon's good character had done much to generate public sympathy for their cause, a huge amount of evidence subsequently emerged painting a very different picture. Significantly, the prosecution fought to exclude from trial any reference to Trayvon Martin's school records, his suspensions, marijuana use, involvement in fights, among other things, as this would all "prejudice the jury" against him. When Martin's family members testified at trial prosecutors were careful not to speak positively about Trayvon as this would have allowed the defence to unleash a flood of evidence in rebuttal. The prosecution also argued against the presentation to the jury of the post-mortem toxicology report which showed that Martin had some traces of THC and its metabolite in his blood after the shooting. (Although the judge ruled in favour of the defence, and permitted the introduction of this evidence, they eventually chose not to present it.) Trayvon Martin and George Zimmerman's paths intersect At 18:22 on the evening of February 26 2012 Trayvon Martin entered the local 711 - a 10 to 15 minute walk away from the Retreat at Twin Lakes (see image "1" in Graphic 2). At 18:25 he exited, after paying for a packet of Skittles and a can of Arizona Watermelon Fruit Juice Cocktail. He put the skittles in his pocket and was given a 711 plastic bag in which he carried the can out of the store. The NBA All Stars game was due to start at 19:30, so just over an hour later. It appears that Martin was in no rush to get back home for it was only at around 19:08 that he was spotted by George Zimmerman near an informal pedestrian short cut into the Retreat (see arrow "A" on Graphic 1). It was dark, raining and windy by this time. Graphic 1: Google map of the Retreat at Twin Lakes as marked by George Zimmerman during police interview (annotated by Politicsweb) A: Where George Zimmerman says he saw Trayvon Martin; B: the clubhouse where he parked to phone the NEN; C: Where he says he parked his car; D: The "T" where the altercation began. Zimmerman was in his Honda, driving along Retreat View Circle on his way to Target to do his regular weekly grocery shopping, when he spotted Martin outside the house of Frank Taaffe, over whose property the short cut ran. A few weeks before Zimmerman had seen Taaffe's house being scoped out by a suspicious person, and had called the police. It turned out that this individual, who lived in the neighbourhood, had been involved in a number of burglaries in the area. According to Zimmerman's account to police the following day Martin was standing on the grassy area outside of the house and looking around. He was not walking with any sense of purpose, even though it was raining. Wendy Dorival had told the meeting setting up the neighbourhood watch to phone 911 if they saw any criminal activity, and to phone the police non-emergency number if they saw any suspicious behaviour. Zimmerman phoned the NEN. He drove on past Martin and stopped at the Retreat's club house further up the road (arrow "B"). At some point Martin walked past Zimmerman and down to the road to the right. Zimmerman followed after him to maintain line of sight, parking some way down Twin Trees Lane (arrow "C"). At a certain point Martin disappeared into the darkness between two rows of townhouses then came back out and circled Zimmerman's car. The call initiated at 19:09:34 and proceeded as follows: Zimmerman: Hey we've had some break-ins in my neighbourhood, and there's a real suspicious guy, uh, [near] Retreat View Circle, um, the best address I can give you is 111 Retreat View Circle. This guy looks like he's up to no good, or he's on drugs or something. It's raining and he's just walking around, looking about. Dispatcher: OK, and this guy is he white, black, or Hispanic? Zimmerman: He looks black. Dispatcher: Did you see what he was wearing? Zimmerman: Yeah. A dark hoodie, like a grey hoodie, and either jeans or sweatpants and white tennis shoes. He's here now. He's just staring... Dispatcher: OK, he's just walking around the area... Zimmerman: ...looking at all the houses. Dispatcher: OK... Zimmerman: Now he's just staring at me. Zimmerman: Yeah, now he's coming towards me. Dispatcher: OK. Zimmerman: He's got his hand in his waistband. And he's a black male. Dispatcher: How old would you say he looks? Zimmerman: He's got button on his shirt, late teens. Dispatcher: Late teens ok. Zimmerman: Something's wrong with him. Yup, he's coming to check me out, he's got something in his hands, I don't know what his deal is. Dispatcher: Just let me know if he does anything ok Zimmerman: See if you can get an officer over here Dispatcher: Yeah we've got someone on the way, just let me know if this guy does anything else. Zimmerman: Okay. ... These assholes they always get away. For 26 seconds the dispatcher and Zimmerman discuss where to meet, and Zimmerman gives confused directions on how to get to him. Zimmerman then interrupts to say: "Shit he's running". The dispatcher asks: "He's running? Which way is he running?" Martin had run up through a pedestrian cut through between two sets of townhouses; so could not be followed by car. In response to the question Zimmerman can be heard unbuckling his seat belt and opening his car door. Zimerman states: "Down towards the other entrance to the neighbourhood." He can then be heard shutting the car door. Dispatcher: Which entrance is that that he's heading towards? Zimmerman: The back entrance... Wind sounds are audible at this point and Zimmerman can be heard muttering under his breath, "fucking punks". Dispatcher: Are you following him? Zimmerman: Yeah Dispatcher: Ok, we don't need you to do that. Zimmerman: Ok A few seconds later Zimmerman says "he ran" meaning, it seems, "he's gone". He then discusses with the dispatcher where to meet, at some point noting further on, "I don't know where this kid is". Zimmerman later told police that he was not chasing after Martin, but rather trying to keep him in line of sight so that he could report to the dispatcher where "the suspect" had gone. Although he had a torch with him it was dead, and he can be heard on the call hitting it to try to get it to work again. Zimmerman told police that during the course of the conversation he walked from his car, past the "T" (arrow "D) - the pedestrian path to the right through two sets of townhouses (which was pitch dark at the time) - and up to Retreat View Circle which was lit. Again Zimmerman provides hopelessly confused directions, and he and the dispatcher eventually agree that the police will call him on his cellphone on their arrival. There is about a twenty second gap between when Zimmerman says "he's running" to the dispatcher asking "are you following him?" They carried on talking for another minute and forty seconds. Even at average walking pace this would have been more than enough time for Trayvon Martin to reach Brandy Green's house. It was approximately another two minutes after Zimmerman's call to the NEN ended before the altercation began. According to Zimmerman's account to police, later that evening, he thought that Martin was long gone and was walking back towards the truck when, at the "T" (arrow "D"), Martin emerged out of the darkness and asked "do you have a problem?" He replied "I don't have a problem" and was reaching for his cellphone to call 911 when Martin said "you do now", punched him in the nose, and, after a struggle, pushed him onto the ground. Zimmerman fell onto his back and Martin got on top of him and continued beating him. Zimmerman says he started calling out for help. When he tried to sit up Martin slammed his head into the concrete sidewalk. "My head felt it was it was going to explode." As he continued to yell for help Martin put his hand on Zimmerman's mouth and broken nose and told him to "shut the fuck up". Zimmerman told police that as he was squirming to get his head away from the concrete and onto the grass his firearm, which had been completely concealed up until this point, was exposed. Martin said "you gonna die tonight motherfucker" and Zimmerman felt him reaching for his gun. Zimmerman unholstered the gun, pulled it out, and fired a single shot into Martin's chest. Martin then sat back saying "you got me". Zimmerman then got out from under him and Martin toppled over, face first, into the grass. Zimmerman then, in turn, got on top of Martin and spread out his arms to see whether Martin had any weapon in his hands. Sanford police officer Tim Smith arrived at the scene very shortly afterwards. He found Zimmerman standing over Martin with a bleeding nose and watery eyes. The back of Zimmerman's reddish jacket was wet and covered in grass. Smith handcuffed Zimmerman and took his gun out of its holster. Zimmerman, he said, was completely co-operative. Smith testified at trial that as he was walking Zimmerman to his police car Zimmerman told him, in a confused state, that he had been yelling for help and no-one would come help him. At the scene two photographs were taken of Zimmerman's injuries (see image "2" and "3" in Graphic 2): One of his back of his head, bleeding in two places, and the other of his face, with his nose bloodied and broken. Martin was found lying face down: The can of Arizona Watermelon Fruit Juice Cocktail in the front pocket of his hooded sweatshirt, and the plastic bag from 711 lying on the concrete path a short distance away. He died at the scene despite efforts by police and paramedics to resuscitate him. Graphic 2: Trayvon Martin at the 711 shortly before, and George Zimmerman shortly after, their altercation There was only one eyewitness to the actual fight. John Good testified at trial that he saw Martin on top of Zimmerman subjecting him to a Mixed Martial Arts style "ground and pound" beating. He also said he heard Zimmerman crying out for help. However, he then went back into the house to call 911 so did not see the fatal gunshot. At the trial Vincent de Maio, a renowned forensic pathologist, testified as an expert witness for the defence. He said that he agreed with the firearms examiner that Zimmerman's gun had been discharged against Trayvon Martin's clothing. From the powder tattooing around the wound, however, he estimated that the muzzle of the gun was two-to-four inches from the skin when it went off. "If you're lying on your back, the clothing is going to be against your chest," DiMaio told the court. "So the fact that we know the clothing was 2 to 4 inches away is consistent with someone leaning over the person doing the shooting." De Maio also testified that Martin would have been conscious for at least 10 to 15 seconds after the shot. He said that Zimmerman's injuries were consistent both with being punched in the face and having his head bashed against concrete. He identified six separate injuries. (By contrast, Martin had an offensive injury on one of his knuckles and no defensive injuries - other than the gunshot wound in his chest.) The trail of items dropped by Zimmerman and Martin during their scuffle, and documented by the crime scene technician, was also consistent with Zimmerman's claim that the confrontation had begun at the T. Graphic 4 is a reconstruction of the crime scene by Contrast Forensics, which was used by the defence in court. As can be seen from it Zimmerman's key chain and mini-torch, which he had been using instead of his main flashlight, was found close to the "T" (Marker 1). Zimmerman and Martin ended up some distance further along the path just outside of John Good's house. Jenna Lauer - whose 911 call captured the screams - lived in the house to the right of Good's. Graphic 3: Reconstruction of the scene layout by Contrast Forensics The "T" in turn was a short distance, perhaps a thirty second walk, from Zimmerman's car. The laws of time and space seem to dictate then that Martin would have had to circle back in order for his path to intersect with Zimmerman's again. By the end of the trial there was little serious dispute that Martin had punched Zimmerman in the face, bashed his head against the concrete, and that he was sitting on top of him when the fatal gunshot went off. It was also very clear from the totality of the evidence presented that it was Zimmerman's voice that was recorded screaming for help on Jenna Lauer's 911 call, despite Sybrina Fulton's testimony to the contrary, something that the police had actually determined very early on in their investigation. The only serious evidence that stood at odds with Zimmerman's account was that of "DeeDee" whose real name, it emerged at trial, was Rachel Jeantel. (Mary Cutcher's testimony was regarded as being of so little value that she wasn't even called to testify by the prosecution). Phone records presented to court did confirm that Martin was on the phone to Jeantel's cellphone number in the lead up to the altercation. Jeantel testified under oath that she had been 18 years at the time of the shooting (so not a minor), that she wasn't Trayvon Martin's girlfriend, hadn't dated him, and also had not been hospitalised for high blood pressure at the time of the wake. In other words Crump's description of her in his March 20 press conference was entirely false. In an affidavit submitted before the trial Crump claimed that at the time of the interview he did not know either Jeantel's surname or address. He was also unable to produce an uninterrupted recording of his initial interview with her - having, he said, stopped and restarted the recording multiple times. Jeantel testified in court that the exchange had begun with Martin asking "why are you following me for?" and a "hard breath man" replying "what are you doing around here?" Then she said she heard what she thought was the headset being bumped. Then she heard "wet grass sounds" and then "I kinda heard Trayvon saying get off, get off." The phone call then cut off. By the end of the trial were two areas of residual doubt. These were, firstly, what exactly happened during the two minutes from the end of Zimmerman's NEN call to the beginning of the altercation. And, secondly, how the verbal altercation was initiated - with Zimmerman's and Jeantel's testimony of what was said in direct conflict with each other. Setting these aside, it was evident by the end of the trial that very few of the claims made by the Martin family team, in March 2012, still stood up to any kind of scrutiny. The prosecution produced no credible evidence that Zimmerman had either pursued Trayvon Martin after being told, by the dispatcher, that he didn't need to follow after him, or that he had initiated the confrontation. It is clear from a careful reading of the NEN call that the dispatcher never told Zimmerman "not to get out of his car". In fact Zimmerman had exited his vehicle in an effort to comply with an apparent request, by the dispatcher, to tell him in which direction Martin was running. The claim that Martin was "completely unarmed" was misleading, given the documented injuries he had inflicted on Zimmerman with his fists and the concrete. The assertion that it was Martin crying out for help on the 911 call, though harder to disprove, was also clearly false. So was the incendiary claim, repeated many times by Crump, that Zimmerman had shot Martin "in cold blood". Analysis In the chapter on "national delusions" in his 1852 work Extraordinary Popular Delusions and the Madness of Crowds, Charles MacKay noted how "In reading the history of nations, we find that, like individuals, they have their whims and their peculiarities; their seasons of excitement and recklessness, when they care not what they do. We find that whole communities suddenly fix their minds upon one object, and go mad in its pursuit; that millions of people become simultaneously impressed with one delusion, and run after it, till their attention is caught by some new folly more captivating than the first. " The Trayvon Martin story is a case study in how, even in the modern day, an advanced industrialised democracy can completely lose its senses; and how difficult it is for it to then recover them. In this particular matter a whole society seemingly fixed its mind on the one object of having George Zimmerman arrested, convicted and sent to jail for life, in reckless disregard of the evidence and the law. The mainstream media, so-called civil rights organisations, the Democrat President of the US, the US Attorney General, the Republican Governor of Florida and his Attorney General, and State Attorney Angela Corey all combined forces in an effort to destroy a single, isolated individual. Yet, as documented above, we now know that the incendiary claims made by the Martin family team - which ignited and then fuelled this state of national hysteria - were almost all bogus. Zimmerman's legal team came very close to proving, beyond reasonable doubt, that their client had acted in reasonable fear of his life and great bodily injury in shooting Trayvon Martin; an inversion of the usual burden of proof. The Sanford police knew from the beginning that the evidence tended to support Zimmerman's self-defence claim which is why they had been reluctant to make an arrest. The failures of the mainstream media in their reporting on this case were manifold. The claims of the Martin family team should have, from the beginning, been treated with some degree of caution. Sybrina Fulton and Tracy Martin, and their lawyers, had two motivations in campaigning in the way that they did for the arrest of George Zimmerman. The one was obviously vengeance, the other greed. Following the arrest of Zimmerman Benjamin Crump sent a letter on May 9 to the Retreat at Twin Lakes' Homeowners' Association announcing the intention of Tracy Martin and Sybrina Fulton to file suit. This had always been the intention of the Martin family and their lawyers. Natalie Jackson had sent a letter to the HOA on March 14 2012 demanding that they preserve any evidence relating to the shooting death of Trayvon Martin. The Martin team reached a settlement agreement with the HOA's insurers in early April 2013, which Zimmerman's lawyers estimated amounted to over a million dollars. Such precautionary scepticism should have been redoubled once the Martin family team had been caught out, very early on, lying about Trayvon Martin's school record and the existence of and reasons for his multiple suspensions. Instead, they were repeatedly given a free pass, even by the more critically minded journalists and commentators. The media should also have known to hold back from judgment during the crucial period in which the Sanford police were not publicly divulging the evidence they had at their disposal. Reporters and editors also needed to keep their cool as the mood of national hysteria started building; instead many lost their heads and ran off to join the mob. From late March 2012 evidence started emerging both of Trayvon Martin's troubled recent past and of what had actually transpired on the night of February 26 2012. But while individual pieces of evidence were reported on, the mainstream media appeared to be disinterested in seriously challenging the narrative that had been constructed by the Martin family team. Indeed, much media reporting of this time displayed all the symptoms of confirmatory bias: Poorly vetted and inflammatory stories were run in support of the Martin team's narrative, while substantive evidence that contradicted it was ignored or its significance downplayed. Most noticeably, no effort was made to get to the bottom of who Trayvon Martin really was or to interrogate the curious (and convenient) emergence of "DeeDee" as an ear-witness just after the public release of Zimmerman's NEN call. Such critical forensic analysis, as there was, was performed not by the mainstream media but on marginal websites such as The Wagist (initially), TalkLeft and The Conservative Treehouse. This misreporting of the case continued after Zimmerman's acquittal, with the New York Times, Guardian and Washington Post all running grudging editorials in response. The New York Times decreed that the case was all about race and suggested that a conviction might have "provided an emotional catharsis." The Washington Post continued to repeat, as fact, the Crump claim that "Mr. Zimmerman could have done what police told him to do and stayed in his vehicle." Ultimately it appears that much of the mainstream media was too compromised by its earlier misreporting to seriously review their own conduct, or even belatedly straighten out the facts, let alone challenge the conduct of the Martin team or the prosecutors in the case. It could be argued that the judicial system worked - with Zimmerman being found "not guilty" by the jury of six. This was regarded as the correct verdict by serious-minded Florida lawyers who had followed the trial closely. However, a gross miscarriage of justice was more narrowly averted than might appear in hindsight. Zimmerman had lost his job after the incident and been forced to go into hiding. He was thus utterly impecunious. He was able to present a proper defence only due to donations from ordinary people, raised through an internet site, and the willingness of two fine lawyers to defend him, though he had no means of paying them. No "human rights" or "civil rights" organisation came to his aid and no significant mainstream liberal publication spoke out on his behalf. Meanwhile, Angela Corey's prosecution team - led by Bernie de la Rionda - were absolutely committed to securing his conviction. The first law enforcement interview of Rachel Jeantel was conducted by De la Rionda in Sybrina Fulton's living room, in front of Fulton. This killed off any possibility of getting untainted testimony from Jeantel as to what she had actually heard on the night of February 26. The prosecution were repeatedly and justifiably accused by Zimmerman's defence team of withholding crucial exculpatory material in the run up to the trial. In the court itself the prosecution conducted themselves like unscrupulous defence lawyers - calling (or trying to call) dodgy ‘expert witnesses' to shore up their non-case, relying on tainted and conflicted witness testimony, doing whatever they could to raise doubts over the most clear-cut of evidence, and making base appeals to the emotions of the jury. If and when Judge Debra Nelson exhibited any bias, it was always in favour of the prosecution. She rushed the case to trial - despite the defence's repeated appeals for a postponement - and also ruled Trayvon Martin's text messages on his fighting prowess inadmissible on highly questionable grounds. The response of the prosecution to the verdict, as with their allies in the media, was surly and resentful. When asked by an interviewer for one word to describe Zimmerman Angela Corey responded: "murderer". Barack Obama and Eric Holder meanwhile have chosen not to call off their dogs and Zimmerman remains under investigation by the FBI and DOJ. Such responses, though disturbing, are perhaps not surprising. For, as Mackay wrote: "Men, it has been well said, think in herds; it will be seen that they go mad in herds, while they only recover their senses slowly, and one by one." * CORRECTION August 14 2013: This article originally stated that the petition was originally directed to inter alia State Attorney Angela Corey and US Attorney General Eric Holder. These names were added later, with Corey being substituted for Wolfinger following his removal from the case. Click here to sign up to receive our free daily headline email newsletter
def optimize(self, log, T, lambd, step, verbose=False): transitions_cnt = len([1 for i in log.flat_log for j in log.flat_log[i]]) \ + len(log.flat_log.keys()) ADS = ADS_matrix(log, T.T) N = len(log.activities) M = len([1 for a in T.T for b in T.T[a] if (a != 'start') & (b != 'end')]) def Q(theta1, theta2, lambd): self.update(log, theta1, theta2, T) n, m = len(self.nodes)+2, len(self.edges) losses = self.fitness(log, T.T, ADS) compl = m / n return losses, compl Q_val = dict() per_done = 0 if type(step) in [int, float]: per_step = 100 / (100 // step + 1) ** 2 grid = range(0, 101, step) else: per_step = 100 / len(step) grid = step for a in grid: for p in grid: Q_val[(a,p)] = Q(a, p, lambd) if not verbose: continue per_done += per_step sys.stdout.write("\rOptimization ..... {0:.2f}%".\ format(per_done)) sys.stdout.flush() max_loss = Q(0, 0, lambd)[0] max_compl = Q(100, 100, lambd)[1] for theta in Q_val: Q_val[theta] = (1 - lambd) * Q_val[theta][0] / max_loss + \ lambd * Q_val[theta][1] / max_compl Q_opt = min(Q_val, key=lambda theta: Q_val[theta]) self.update(log, Q_opt[0], Q_opt[1], T) return {'activities': Q_opt[0], 'paths': Q_opt[1]}
/** * Test for single BridgeWriter used across two regions:If notify by * subscription is false , both the regions should receive invalidates for the * updates on server in their respective regions * */ public void testInvalidatesPropagateOnTwoRegionsHavingCommonBridgeWriter() throws Exception { PORT1 = initServerCache(false); createClientCache(getServerHostName(Host.getHost(0)), PORT1); registerInterestForInvalidatesInBothTheRegions(); populateCache(); server1.invoke(BridgeWriterMiscDUnitTest.class, "put"); verifyInvalidatesOnBothRegions(); }
/** * @author Joe Walker [joe at getahead dot ltd dot uk] */ public class LoginRequiredException extends SecurityException { /** * @param s The exception message */ public LoginRequiredException(String s) { super(s); } }
/////////////////////////////// Test the end of HashTable Output ///////////////////////// @Test public void testHashReaderEmpty() throws IOException { assertEquals(Arrays.asList(), SourceTestUtils.readFromSource(hashTableSource, null)); }
<filename>src/record_stack.h // record_stack.h - Stack class deals with individual elements while // RecordStack class handles variable size records. Hence, // RecordStack is derived from Stack. // // ##Copyright## // // Copyright 2000-2016 <NAME> (<EMAIL>) // // 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.00 // // 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. // // ##Copyright## // // $Id: record_stack.h,v 1.3 2001/06/07 05:18:12 qp Exp $ #ifndef RECORD_STACK_H #define RECORD_STACK_H #include "area_offsets.h" #include "defs.h" #include "stack_qp.h" // // After a record is pushed onto the stack, the previous top of stack is // pushed onto the stack. So poping a record is a matter restoring the top of // stack to previous value. Hence, the size of the record is not required. // This approach makes the stack management simplier in the multiple page // model because no record is not allowed to break up and store in two pages, // and no need to worry about the amount of unused space left on previous // page. // class RecordStack : public PrologStack <StackWord> { protected: // // Return the name of the table. // virtual const char *getAreaName(void) const { return("record stack"); } // // Push a record onto the stack. // The old top of stack is pushed after the allocation of the record. // This makes internal maintenance easier. // StackLoc pushRecord(const word32 size) { StackLoc OldTop, record; OldTop = getTopOfStack(); record = allocateBlock(size); // Allocate record. pushElement((StackWord)(OldTop)); // Push the old top of stack. return(record); } // // Pop the topmost record off the stack. // void popRecord(void) { setTopOfStack((StackLoc)(popElement())); } // // Reduce the size of the record on the top of the stack, pointed by // 'loc', to 'size'. The size is defined in bytes. // void trimRecord(const StackLoc loc, const word32 size) { StackLoc OldTop; OldTop = (StackLoc)(popElement()); setTopOfStack(loc + roundBasicUnit(size, sizeof(StackWord))); pushElement((StackWord)(OldTop)); } // // Return the previous top of stack, which is stored at the location // beneath the start of the record. // StackLoc previousTop(const StackLoc loc) const { return(*inspectAddr(loc - 1)); } // // Change the value for the previous top of stack. // void changePreviousTop(const StackLoc loc, const StackLoc NewValue) { *fetchAddr(loc - 1) = NewValue; } // // Get the number of StackWords in a record of size bytes // including the internal maintenance data. // word32 numberOfStackWords(const word32 size) const { return(roundBasicUnit(size,sizeof(StackWord)) + 1); } // // Reset the top of stack to after the record pointed by 'loc', // including the internal maintenance data. The size of the record is // defined by 'size' in bytes. // void resetTopOfStack(const StackLoc loc, const word32 size) { setTopOfStack(loc + roundBasicUnit(size, sizeof(StackWord)) + 1); } public: RecordStack(word32 size, word32 overflow) : PrologStack <StackWord> (size, overflow) {} }; #endif // RECORD_STACK_H
// NewCreateOrderResponseBody builds the HTTP response body from the result of // the "create_order" endpoint of the "order" service. func NewCreateOrderResponseBody(res *order.CreateOrderResponse) *CreateOrderResponseBody { body := &CreateOrderResponseBody{} if res.Order != nil { body.Order = marshalOrderOrderToOrderResponseBody(res.Order) } if res.OrderFailure != nil { body.OrderFailure = marshalOrderOrderFailureToOrderFailureResponseBody(res.OrderFailure) } return body }
use std::env; use term::terminfo::TermInfo; #[derive(PartialEq, Clone, Copy)] pub enum Color { Reset, Red, Green, Gray, Yellow, Orange, Blue, Purple, Cyan, RedBG, YellowBG, OrangeBG, NonText, Invert, } impl Color { pub fn has_bg_color(self) -> bool { use Color::*; matches!(self, YellowBG | RedBG | OrangeBG) } } #[inline] fn true_colors_sequence(color: Color) -> &'static [u8] { macro_rules! rgb_color { (fg, $r:expr, $g:expr, $b:expr) => { concat!("\x1b[38;2;", $r, ';', $g, ';', $b, "m") }; (bg, $r:expr, $g:expr, $b:expr) => { concat!("\x1b[48;2;", $r, ';', $g, ';', $b, "m") }; } use Color::*; match color { Reset => concat!( "\x1b[39;0m", rgb_color!(fg, 0xfb, 0xf1, 0xc7), rgb_color!(bg, 0x28, 0x28, 0x28), ) .as_bytes(), Red => rgb_color!(fg, 0xfb, 0x49, 0x34).as_bytes(), Green => rgb_color!(fg, 0xb8, 0xbb, 0x26).as_bytes(), Gray => rgb_color!(fg, 0xa8, 0x99, 0x84).as_bytes(), Yellow => rgb_color!(fg, 0xfa, 0xbd, 0x2f).as_bytes(), Orange => rgb_color!(fg, 0xfe, 0x80, 0x19).as_bytes(), Blue => rgb_color!(fg, 0x83, 0xa5, 0x98).as_bytes(), Purple => rgb_color!(fg, 0xd3, 0x86, 0x9b).as_bytes(), Cyan => rgb_color!(fg, 0x8e, 0xc0, 0x7c).as_bytes(), RedBG => concat!( rgb_color!(fg, 0xfb, 0xf1, 0xc7), rgb_color!(bg, 0xcc, 0x24, 0x1d), ) .as_bytes(), YellowBG => concat!( rgb_color!(fg, 0x28, 0x28, 0x28), rgb_color!(bg, 0xd7, 0x99, 0x21), ) .as_bytes(), OrangeBG => concat!( rgb_color!(fg, 0x28, 0x28, 0x28), rgb_color!(bg, 0xd6, 0x5d, 0x0e), ) .as_bytes(), NonText => rgb_color!(fg, 0x66, 0x5c, 0x54).as_bytes(), Invert => b"\x1b[7m", } } // From color palette of gruvbox: https://github.com/morhetz/gruvbox#palette // // 'm' sets attributes to text printed after: https://vt100.net/docs/vt100-ug/chapter3.html#SGR // Color table: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors // // 256 colors sequences are '\x1b[38;5;<n>m' (for fg) or '\x1b[48;5;<n>m (for bg) // https://www.xfree86.org/current/ctlseqs.html // // 24bit colors sequences are '\x1b[38;2;<r>;<g>;<b>m' (for fg) or '\x1b[48;2;<r>;<g>;<b>m' (for fg) // https://en.wikipedia.org/wiki/ANSI_escape_code#Colors #[inline] fn colors_256_sequence(color: Color) -> &'static [u8] { use Color::*; match color { Reset => b"\x1b[39;0m\x1b[38;5;230m\x1b[48;5;235m", Red => b"\x1b[38;5;167m", Green => b"\x1b[38;5;142m", Gray => b"\x1b[38;5;246m", Yellow => b"\x1b[38;5;214m", Orange => b"\x1b[38;5;208m", Blue => b"\x1b[38;5;109m", Purple => b"\x1b[38;5;175m", Cyan => b"\x1b[38;5;108m", RedBG => b"\x1b[38;5;230m\x1b[48;5;124m", YellowBG => b"\x1b[38;5;235m\x1b[48;5;214m", OrangeBG => b"\x1b[38;5;235m\x1b[48;5;166m", NonText => b"\x1b[38;5;241m", Invert => b"\x1b[7m", } } #[inline] fn colors_16_sequence(color: Color) -> &'static [u8] { use Color::*; match color { Reset => b"\x1b[39;0m", Red => b"\x1b[91m", Green => b"\x1b[32m", Gray => b"\x1b[90m", Yellow => b"\x1b[93m", Orange => b"\x1b[33m", // No orange color in 16 colors. Use darker yellow instead Blue => b"\x1b[94m", Purple => b"\x1b[95m", Cyan => b"\x1b[96m", RedBG => b"\x1b[97m\x1b[41m", YellowBG => b"\x1b[103m\x1b[30m", OrangeBG => b"\x1b[107m\x1b[30m", // White BG color is used instead of orange NonText => b"\x1b[37m", Invert => b"\x1b[7m", } } #[derive(Clone, Copy)] pub enum TermColor { TrueColors, Colors256, Colors16, } impl TermColor { pub fn from_env() -> TermColor { env::var("COLORTERM") .ok() .and_then(|v| { if v == "truecolor" { Some(TermColor::TrueColors) } else { None } }) .or_else(|| { TermInfo::from_env().ok().and_then(|info| { info.numbers.get("colors").map(|colors| { if *colors == 256 { TermColor::Colors256 } else { TermColor::Colors16 } }) }) }) .unwrap_or(TermColor::Colors16) } pub fn sequence(self, color: Color) -> &'static [u8] { match self { TermColor::TrueColors => true_colors_sequence(color), TermColor::Colors256 => colors_256_sequence(color), TermColor::Colors16 => colors_16_sequence(color), } } }
import * as utils from "./utils"; function transformRequest(data) { if ( utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isBlob(data) ) { return data; } // Object and Array: returns a deep copy if (utils.isObjectOrArray(data)) { return JSON.parse(JSON.stringify(data)); } // for primitives like string, undefined, null, number return data; } function makeResponse(result, config) { return { status: result[0], data: transformRequest(result[1]), headers: result[2], config: config, request: { responseURL: config.url, }, }; } export default function handleRequest(mockAdapter, resolve, reject, config) { let url = config.url || ""; // TODO we're not hitting this `if` in any of the tests, investigate if ( config.baseURL && url.substr(0, config.baseURL.length) === config.baseURL ) { url = url.slice(config.baseURL.length); } delete config.adapter; mockAdapter.history[config.method].push(config); const handler = utils.findHandler( mockAdapter.handlers, config.method, url, config.data, config.params, config.headers, config.baseURL ); if (handler) { if (handler.length === 7) { utils.purgeIfReplyOnce(mockAdapter, handler); } if (handler.length === 2) { // passThrough handler mockAdapter.originalAdapter(config).then(resolve, reject); } else if (typeof handler[3] !== "function") { utils.settle( resolve, reject, makeResponse(handler.slice(3), config), mockAdapter.delayResponse ); } else { const result = handler[3](config); // TODO throw a sane exception when return value is incorrect if (typeof result.then !== "function") { utils.settle( resolve, reject, makeResponse(result, config), mockAdapter.delayResponse ); } else { result.then( function (result) { if (result.config && result.status) { utils.settle( resolve, reject, makeResponse( [result.status, result.data, result.headers], result.config ), 0 ); } else { utils.settle( resolve, reject, makeResponse(result, config), mockAdapter.delayResponse ); } }, function (error) { if (mockAdapter.delayResponse > 0) { setTimeout(function () { reject(error); }, mockAdapter.delayResponse); } else { reject(error); } } ); } } } else { // handler not found switch (mockAdapter.onNoMatch) { case "passthrough": mockAdapter.originalAdapter(config).then(resolve, reject); break; case "throwException": throw utils.createCouldNotFindMockError(config); default: utils.settle( resolve, reject, { status: 404, config: config, }, mockAdapter.delayResponse ); } } }
// angular import { NgModule } from '@angular/core'; import { CommonModule as CommonAngularModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; // app import { MaterialModule } from '~/app/framework/material'; // module import { LoadingOverlayComponent } from './components/loading-overlay/loading-overlay.component'; import { MenuGroupComponent } from './components/menu/menu-group.component'; import { MenuItemComponent } from './components/menu/menu-item.component'; const COMPONENTS = [ LoadingOverlayComponent, MenuGroupComponent, MenuItemComponent ]; @NgModule({ imports: [ CommonAngularModule, FormsModule, MaterialModule ], declarations: [ COMPONENTS ], exports: [ CommonAngularModule, COMPONENTS ] }) export class CommonModule { }
package uk.gov.hmcts.probate.service.template.printservice; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.test.util.ReflectionTestUtils; import uk.gov.hmcts.probate.insights.AppInsights; import uk.gov.hmcts.probate.model.ApplicationType; import uk.gov.hmcts.probate.model.ccd.raw.request.CaseData; import uk.gov.hmcts.probate.model.ccd.raw.request.CaseDetails; import uk.gov.hmcts.probate.model.template.DocumentResponse; import uk.gov.hmcts.probate.service.FileSystemResourceService; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; public class PrintServiceTest { @InjectMocks private PrintService underTest; @Mock private FileSystemResourceService fileSystemResourceServiceMock; @Mock private CaseDetails caseDetailsMock; @Mock private CaseData caseDataMock; @Mock AppInsights appInsights; @Before public void setup() { initMocks(this); ReflectionTestUtils.setField(underTest, "templatesDirectory", "someTemplateDirectory/"); ReflectionTestUtils.setField(underTest, "printServiceHost", "somePrintServiceHost"); ReflectionTestUtils.setField(underTest, "printServicePath", "somePrintServicePath/%s/probate/"); when(fileSystemResourceServiceMock.getFileFromResourceAsString("someTemplateDirectory/caseDetailsSOL.html")) .thenReturn("some Solicitor template"); when(fileSystemResourceServiceMock.getFileFromResourceAsString("someTemplateDirectory/caseDetailsPA.html")) .thenReturn("some Personal template"); } @Test public void shouldReturnAllSolicitorDocuments() { when(caseDetailsMock.getId()).thenReturn(1000L); when(caseDetailsMock.getData()).thenReturn(caseDataMock); when(caseDataMock.getApplicationType()).thenReturn(ApplicationType.SOLICITOR); List<DocumentResponse> docs = underTest.getAllDocuments(caseDetailsMock); assertEquals(1, docs.size()); assertEquals("Print Case Details", docs.get(0).getName()); assertEquals("HTML", docs.get(0).getType()); assertEquals("somePrintServiceHostsomePrintServicePath/1000/probate/sol", docs.get(0).getUrl()); } @Test public void shouldReturnAllPADocuments() { when(caseDetailsMock.getId()).thenReturn(1000L); when(caseDetailsMock.getData()).thenReturn(caseDataMock); when(caseDataMock.getApplicationType()).thenReturn(ApplicationType.PERSONAL); List<DocumentResponse> docs = underTest.getAllDocuments(caseDetailsMock); assertEquals(1, docs.size()); assertEquals("Print Case Details", docs.get(0).getName()); assertEquals("HTML", docs.get(0).getType()); assertEquals("somePrintServiceHostsomePrintServicePath/1000/probate/pa", docs.get(0).getUrl()); } @Test public void shouldGetSolicitorTemplateForCaseDetails() { String template = underTest.getSolicitorCaseDetailsTemplateForPrintService(); assertEquals("some Solicitor template", template); } @Test public void shouldGetPATemplateForCaseDetails() { String template = underTest.getPACaseDetailsTemplateForPrintService(); assertEquals("some Personal template", template); } }
/** * @author mzawirsk * @param <V> */ public class AddOnlySetCRDT<V> extends BaseCRDT<AddOnlySetCRDT<V>> { private Set<V> elements; // Kryo public AddOnlySetCRDT() { } public AddOnlySetCRDT(CRDTIdentifier id) { super(id); elements = new HashSet<V>(); } private AddOnlySetCRDT(CRDTIdentifier id, TxnHandle txn, CausalityClock clock, Set<V> elements) { super(id, txn, clock); this.elements = elements; } public void add(V element) { elements.add(element); registerLocalOperation(new AddOnlySetUpdate<V>(element)); } public void applyAdd(V element) { elements.add(element); } @Override public Set<V> getValue() { return Collections.unmodifiableSet(elements); } @Override public AddOnlySetCRDT<V> copy() { return new AddOnlySetCRDT<V>(id, txn, clock, new HashSet<V>(elements)); } }
<filename>tools/onni/Interpreter.h //===- Interpreter.h ------------------------------------------------------===// // // The ONNC Project // // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef ONNC_INTERPRETER_INTERPRETER_H #define ONNC_INTERPRETER_INTERPRETER_H #include <onnc/IR/ComputeVisitor.h> #include <onnc/IR/Compute/Value.h> #include <onnc/IR/ComputeMemOperand.h> #include <unordered_map> #include <cstddef> namespace onnc { /** \class Interpreter * \brief Interpreter dispatch compute ir to runtime. */ class Interpreter : public ComputeVisitor { public: // XXX typedef std::unordered_map<Value *, void *> AddressTable; AddressTable m_ATable; void *m_pContext; virtual void visit(Abs& pAbs); virtual void visit(Acos& pAcos); virtual void visit(Add& pAdd); virtual void visit(And& pAnd); virtual void visit(ArgMax& pArgMax); virtual void visit(ArgMin& pArgMin); virtual void visit(Asin& pAsin); virtual void visit(Atan& pAtan); virtual void visit(AveragePool& pAveragePool); virtual void visit(BatchNormalization& pBatchNormalization); virtual void visit(Cast& pCast); virtual void visit(Ceil& pCeil); virtual void visit(Clip& pClip); virtual void visit(Concat& pConcat); virtual void visit(Constant& pConstant); virtual void visit(Conv& pConv); virtual void visit(ConvTranspose& pConvTranspose); virtual void visit(Cos& pCos); virtual void visit(DepthToSpace& pDepthToSpace); virtual void visit(Div& pDiv); virtual void visit(Dropout& pDropout); virtual void visit(Elu& pElu); virtual void visit(Equal& pEqual); virtual void visit(Exp& pExp); virtual void visit(Expand& pExpand); virtual void visit(Flatten& pFlatten); virtual void visit(Floor& pFloor); virtual void visit(GRU& pGRU); virtual void visit(Gather& pGather); virtual void visit(Gemm& pGemm); virtual void visit(GlobalAveragePool& pGlobalAveragePool); virtual void visit(GlobalLpPool& pGlobalLpPool); virtual void visit(GlobalMaxPool& pGlobalMaxPool); virtual void visit(Greater& pGreater); virtual void visit(HardSigmoid& pHardSigmoid); virtual void visit(Hardmax& pHardmax); virtual void visit(Identity& pIdentity); virtual void visit(InstanceNormalization& pInstanceNormalization); virtual void visit(LRN& pLRN); virtual void visit(LSTM& pLSTM); virtual void visit(LeakyRelu& pLeakyRelu); virtual void visit(Less& pLess); virtual void visit(Log& pLog); virtual void visit(LogSoftmax& pLogSoftmax); virtual void visit(LpNormalization& pLpNormalization); virtual void visit(LpPool& pLpPool); virtual void visit(MatMul& pMatMul); virtual void visit(Max& pMax); virtual void visit(MaxPool& pMaxPool); virtual void visit(MaxRoiPool& pMaxRoiPool); virtual void visit(Mean& pMean); virtual void visit(Min& pMin); virtual void visit(Mul& pMul); virtual void visit(Multinomial& pMultinomial); virtual void visit(Neg& pNeg); virtual void visit(Not& pNot); virtual void visit(Or& pOr); virtual void visit(PRelu& pPRelu); virtual void visit(Pad& pPad); virtual void visit(Pow& pPow); virtual void visit(RNN& pRNN); virtual void visit(RandomNormal& pRandomNormal); virtual void visit(RandomNormalLike& pRandomNormalLike); virtual void visit(RandomUniform& pRandomUniform); virtual void visit(RandomUniformLike& pRandomUniformLike); virtual void visit(Reciprocal& pReciprocal); virtual void visit(ReduceL1& pReduceL1); virtual void visit(ReduceL2& pReduceL2); virtual void visit(ReduceLogSum& pReduceLogSum); virtual void visit(ReduceLogSumExp& pReduceLogSumExp); virtual void visit(ReduceMax& pReduceMax); virtual void visit(ReduceMean& pReduceMean); virtual void visit(ReduceMin& pReduceMin); virtual void visit(ReduceProd& pReduceProd); virtual void visit(ReduceSum& pReduceSum); virtual void visit(ReduceSumSquare& pReduceSumSquare); virtual void visit(Relu& pRelu); virtual void visit(Reshape& pReshape); virtual void visit(Selu& pSelu); virtual void visit(Shape& pShape); virtual void visit(Sigmoid& pSigmoid); virtual void visit(Sin& pSin); virtual void visit(Size& pSize); virtual void visit(Slice& pSlice); virtual void visit(Softmax& pSoftmax); virtual void visit(Softplus& pSoftplus); virtual void visit(Softsign& pSoftsign); virtual void visit(SpaceToDepth& pSpaceToDepth); virtual void visit(Split& pSplit); virtual void visit(Sqrt& pSqrt); virtual void visit(Squeeze& pSqueeze); virtual void visit(Sub& pSub); virtual void visit(Sum& pSum); virtual void visit(Tan& pTan); virtual void visit(Tanh& pTanh); virtual void visit(Tile& pTile); virtual void visit(TopK& pTopK); virtual void visit(Transpose& pTranspose); virtual void visit(Unsqueeze& pUnsqueeze); virtual void visit(Upsample& pUpsample); virtual void visit(Xor& pXor); virtual void visit(ATen& pATen); virtual void visit(Affine& pAffine); virtual void visit(ConstantFill& pConstantFill); virtual void visit(Crop& pCrop); virtual void visit(GRUUnit& pGRUUnit); virtual void visit(GivenTensorFill& pGivenTensorFill); virtual void visit(ImageScaler& pImageScaler); virtual void visit(MeanVarianceNormalization& pMeanVarianceNormalization); virtual void visit(ParametricSoftplus& pParametricSoftplus); virtual void visit(Scale& pScale); virtual void visit(ScaledTanh& pScaledTanh); virtual void visit(ThresholdedRelu& pThresholdedRelu); }; } // namespace of onnc #endif
Image caption Bleddyn King filmed himself stamping upon David Evans's face An 18-year-old man who stabbed a 64-year-old widower 72 times in his bungalow after meeting him on a website has been jailed for life for murder. After Bleddyn King was told he will serve at least 28 years, his family and police warned of the dangers of meeting strangers over the internet. King, of Abercynon, killed David Evans in Pentyrch, near Cardiff, and used his mobile phone to film his body. The judge told him at Cardiff Crown Court that he was "evil and dangerous". After the case Mr Evans's son Richard said: "My father met his murderer over the internet, which I hope will serve as a warning to others who meet strangers in this way." Det Chief Insp Ceri Hughes of South Wales Police said: "David Evans was highly respected in the community and deeply loved by all his family. "The brutal murder of such a gentle and trusting man tragically highlights the dangers of meeting strangers over the internet. The brutal murder of such a gentle and trusting man tragically highlights the dangers of meeting strangers over the internet Det Chief Insp Ceri Hughes, South Wales Police "David's family have shown tremendous dignity and, while they remain devastated by what has happened, I hope the verdict and today's sentencing helps them in someway to move forward." King was left covered in Mr Evans's blood after the attack. The court was told that he made a chilling soundtrack on a two-minute video of the murder scene. Powerfully-built King pulled a knife on Mr Evans and stabbed him so forcefully the blade was left bent, the court heard. Image caption Bleddyn King targeted David Evans before killing him in his home King was convicted on Monday after a 10-day trial. Judge Mr Justice MacDuff said: "David Evans was in the sanctuary of his own home when you committed a wicked attack on him." The judge said King tricked his way in and "gained his confidence" before murdering him. Mr Justice MacDuff added: "You targeted this kind mild man because he was not a match for you. He lived alone and would be easy pickings. 'Lost soul' "You punched, cut and stabbed him to death. It was a vicious, brutal attack - the fear and pain he must have felt in his dying minutes is unimaginable. Statement by David Evans's family Speaking on behalf of the family, Mr Evans' son Richard Evans, said: "David was a gentle and loving father, brother, uncle and grandfather. "His death earlier this year in such a violent and needless manner has devastated our family. "We would like to thank the South Wales Police team who have investigated my father's murder and the jury for their attentiveness during the trial. "My father met his murderer over the internet, which I hope will serve as a warning to others who meet strangers in this way." "It is wickedness beyond comprehension - you are evil and dangerous." King's video of the death scene was too horrific to be shown to the jury. Mr Justice MacDuff told the court he saw it for the first time just moments before sentencing King. He said: "That recording is a chilling record of your wickedness. You filmed yourself stamping repeatedly on Mr Evans's face as you shouted obscenities." During the trial, the court heard that King killed Mr Evans's cat before setting his home on fire and escaping. But police stopped him as he drove off in the victim's Citroen car and he was found to have two bank cards belonging to his victim in January. Image caption Police officers in Pentyrch after the discovery of a David Evans's body in his bungalow Michael Mather-Lees QC, prosecuting, said: "After he was dead, King videoed his body while giving a dialogue of what he had done and why he was doing it. "He made the video to scare people he may have owed money to. The film was made to instil fear of him in somebody else." Mr Evans, a retired RAF fireman, was described as a "lost soul" since the death of his wife in 2008. He met King on a gay website and invited him to his home. The court heard that King was desperate for money after being turned down for 10 bank loans on the day of the killing. The judge paid tribute to Mr Evans's family for their "grace and compassion". After Tuesday's court hearing, Janine Davies, of the Crown Prosecution Service, said King's arrest was a result of swift and decisive action by an off-duty police radio controller, who noticed and reported his erratic driving late at night.
/** * Translate a region by a specified offset. * * @param rgn The region to translate. * @param x The X offset. * @param y The Y offset. */ void GdOffsetRegion(MWCLIPREGION *rgn, MWCOORD x, MWCOORD y) { int nbox = rgn->numRects; MWRECT *pbox = rgn->rects; if(nbox && (x || y)) { while(nbox--) { pbox->left += x; pbox->right += x; pbox->top += y; pbox->bottom += y; pbox++; } rgn->extents.left += x; rgn->extents.right += x; rgn->extents.top += y; rgn->extents.bottom += y; } }
/** * This is the implementation of the "rl" command. * * @author austin.brehob */ public class RLCommand extends PicocliSoarCommand { public static class Provider implements SoarCommandProvider { @Override public void registerCommands(SoarCommandInterpreter interp, Adaptable context) { interp.addCommand("rl", new RLCommand((Agent) context)); } } public RLCommand(Agent agent) { super(agent, new RL(agent)); } @Command( name = "rl", description = "Controls how numeric indifferent preference " + "values in RL rules are updated via reinforcement learning", subcommands = {HelpCommand.class}) public static class RL implements Runnable { private final Agent agent; private final ReinforcementLearning rl; public RL(Agent agent) { this.agent = agent; this.rl = Adaptables.require(getClass(), agent, ReinforcementLearning.class); } @Option( names = {"-s", "--set"}, description = "Sets the given parameter value") String setParam = null; @Parameters(arity = "0..1", description = "The new value of the parameter") String newVal = null; @Option( names = {"-g", "--get"}, description = "Prints the current setting of the given parameter") String getParam = null; @Override public void run() { if (setParam != null) { if (newVal == null) { agent.getPrinter().startNewLine().print("Error: no parameter value provided"); return; } agent.getPrinter().startNewLine().print(doSet(setParam, newVal)); } else if (getParam != null) { agent.getPrinter().startNewLine().print(doGet(getParam)); } else { agent.getPrinter().startNewLine().print(doRl()); } // TODO: Soar Manual version 9.6.0 includes RL options "-t/--trace" and "-S/--stats" } private String doSet(String paramToSet, String value) { final PropertyManager props = rl.getParams().getProperties(); try { if (paramToSet.equals("learning")) { props.set(ReinforcementLearningParams.LEARNING, Learning.valueOf(value)); } else if (paramToSet.equals("discount-rate")) { props.set(ReinforcementLearningParams.DISCOUNT_RATE, Double.parseDouble(value)); return "Set discount-rate to " + Double.parseDouble(value); } else if (paramToSet.equals("learning-policy")) { // TODO if (value.equals("off-policy-gq-lambda") || value.equals("on-policy-gq-lambda")) { agent .getPrinter() .startNewLine() .print("RL learning-policy '" + value + "' has not yet been implemented in JSoar"); return ""; } props.set(ReinforcementLearningParams.LEARNING_POLICY, LearningPolicy.valueOf(value)); return "Set learning-policy to " + LearningPolicy.valueOf(value); } else if (paramToSet.equals("step-size-parameter")) { // TODO agent .getPrinter() .startNewLine() .print( "RL GQ parameter 'step-size-parameter' " + "has not yet been implemented in JSoar"); return ""; } else if (paramToSet.equals("learning-rate")) { props.set(ReinforcementLearningParams.LEARNING_RATE, Double.parseDouble(value)); return "Set learning-rate to " + Double.parseDouble(value); } else if (paramToSet.equals("hrl-discount")) { props.set(ReinforcementLearningParams.HRL_DISCOUNT, HrlDiscount.valueOf(value)); return "Set hrl-discount to " + HrlDiscount.valueOf(value); } else if (paramToSet.equals("temporal-discount")) { props.set(ReinforcementLearningParams.TEMPORAL_DISCOUNT, TemporalDiscount.valueOf(value)); return "Set temporal-discount to " + TemporalDiscount.valueOf(value); } else if (paramToSet.equals("temporal-extension")) { props.set( ReinforcementLearningParams.TEMPORAL_EXTENSION, TemporalExtension.valueOf(value)); return "Set temporal-extension to " + TemporalExtension.valueOf(value); } else if (paramToSet.equals("eligibility-trace-decay-rate")) { props.set(ReinforcementLearningParams.ET_DECAY_RATE, Double.parseDouble(value)); return "Set eligibility-trace-decay-rate to " + Double.parseDouble(value); } else if (paramToSet.equals("eligibility-trace-tolerance")) { props.set(ReinforcementLearningParams.ET_TOLERANCE, Double.parseDouble(value)); return "Set eligibility-trace-tolerance to " + Double.parseDouble(value); } else if (paramToSet.equals("chunk-stop")) { props.set(ReinforcementLearningParams.CHUNK_STOP, ChunkStop.valueOf(value)); return "Set chunk-stop to " + ChunkStop.valueOf(value); } else if (paramToSet.equals("decay-mode")) { props.set(ReinforcementLearningParams.DECAY_MODE, DecayMode.valueOf(value)); return "Set decay-mode to " + DecayMode.valueOf(value); } else if (paramToSet.equals("meta")) { props.set(ReinforcementLearningParams.META, Meta.valueOf(value)); return "Set meta to " + Meta.valueOf(value); } else if (paramToSet.equals("meta-learning-rate")) { props.set(ReinforcementLearningParams.META_LEARNING_RATE, Double.parseDouble(value)); return "Set meta-learning-rate to " + Double.parseDouble(value); } else if (paramToSet.equals("update-log-path")) { props.set(ReinforcementLearningParams.UPDATE_LOG_PATH, value); return "Set update-log-path to " + value; } else if (paramToSet.equals("apoptosis")) { props.set(ReinforcementLearningParams.APOPTOSIS, ApoptosisChoices.getEnum(value)); return "Set apoptosis to " + ApoptosisChoices.getEnum(value); } else if (paramToSet.equals("apoptosis-decay")) { props.set(ReinforcementLearningParams.APOPTOSIS_DECAY, Double.parseDouble(value)); return "Set apoptosis-decay to " + Double.parseDouble(value); } else if (paramToSet.equals("apoptosis-thresh")) { props.set(ReinforcementLearningParams.APOPTOSIS_THRESH, Double.parseDouble(value)); return "Set apoptosis-thresh to " + Double.parseDouble(value); } else if (paramToSet.equals("trace")) { props.set(ReinforcementLearningParams.TRACE, Trace.valueOf(value)); return "Set trace to " + Trace.valueOf(value); } else { agent.getPrinter().startNewLine().print("Unknown rl parameter '" + paramToSet + "'"); return ""; } } catch ( IllegalArgumentException e) // this is thrown by the enums if a bad value is passed in { agent.getPrinter().startNewLine().print("Invalid value."); } return ""; } private String doGet(String paramToGet) { final PropertyKey<?> key = ReinforcementLearningParams.getProperty(rl.getParams().getProperties(), paramToGet); if (key == null) { agent.getPrinter().startNewLine().print("Unknown parameter '" + paramToGet + "'"); return ""; } return rl.getParams().getProperties().get(key).toString(); } private String doRl() { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); final ReinforcementLearningParams p = rl.getParams(); pw.printf(RLPrintHelper.generateHeader("", 0)); pw.printf(RLPrintHelper.generateItem("Soar-RL learning:", p.learning.get(), 40)); pw.printf(RLPrintHelper.generateItem("temporal-extension:", p.temporal_extension.get(), 40)); pw.printf(RLPrintHelper.generateSection("Discount", 40)); pw.printf(RLPrintHelper.generateItem("discount-rate:", p.discount_rate.get(), 40)); pw.printf(RLPrintHelper.generateSection("Learning", 40)); pw.printf(RLPrintHelper.generateItem("learning-policy:", p.learning_policy.get(), 40)); pw.printf(RLPrintHelper.generateItem("learning-rate:", p.learning_rate.get(), 40)); pw.printf(RLPrintHelper.generateItem("hrl-discount:", p.hrl_discount.get(), 40)); // This is commented out here since the CSoar report does not show it, // even though it is there in CSoar as well. // pw.printf(RLPrintHelper.generateItem("temporal-discount:", p.temporal_discount.get(), 40)); pw.printf(RLPrintHelper.generateSection("Eligibility Traces", 40)); pw.printf( RLPrintHelper.generateItem("eligibility-trace-decay-rate:", p.et_decay_rate.get(), 40)); pw.printf( RLPrintHelper.generateItem("eligibility-trace-tolerance:", p.et_tolerance.get(), 40)); pw.printf(RLPrintHelper.generateSection("Experimental", 40)); pw.printf(RLPrintHelper.generateItem("chunk-stop:", p.chunk_stop.get(), 40)); pw.printf(RLPrintHelper.generateItem("decay-mode:", p.decay_mode.get(), 40)); pw.printf(RLPrintHelper.generateItem("meta:", p.meta.get(), 40)); pw.printf(RLPrintHelper.generateItem("meta-learning-rate:", p.meta_learning_rate.get(), 40)); pw.printf(RLPrintHelper.generateItem("update-log-path:", p.update_log_path.get(), 40)); pw.printf(RLPrintHelper.generateItem("", "0", 0)); // The following are not implemented yet, except for being faked here pw.printf(RLPrintHelper.generateItem("apoptosis:", p.apoptosis.get(), 40)); pw.printf(RLPrintHelper.generateItem("apoptosis-decay:", p.apoptosis_decay.get(), 40)); pw.printf(RLPrintHelper.generateItem("apoptosis-thresh:", p.apoptosis_thresh.get(), 40)); pw.printf(RLPrintHelper.generateItem("", "0", 0)); pw.printf(RLPrintHelper.generateItem("trace:", p.trace.get(), 40)); pw.printf(RLPrintHelper.generateItem("", "0", 0)); pw.flush(); return sw.toString(); } } }
/** * Initialize a specific device. * * The parent should be initialized first to avoid having an ordering problem. * This is done by calling the parent's init() method before its childrens' * init() methods. * * @param dev The device to be initialized. */ static void init_dev(struct device *dev) { if (!dev->enabled) return; if (!dev->initialized && dev->ops && dev->ops->init) { if (dev->path.type == DEVICE_PATH_I2C) { printk(BIOS_DEBUG, "smbus: %s[%d]->", dev_path(dev->bus->dev), dev->bus->link_num); } printk(BIOS_DEBUG, "%s init\n", dev_path(dev)); dev->initialized = 1; dev->ops->init(dev); } }
<filename>src/main/java/org/apache/commons/text/similarity/CosineSimilarity.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.text.similarity; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Measures the Cosine similarity of two vectors of an inner product space and * compares the angle between them. * * <p> * For further explanation about the Cosine Similarity, refer to * http://en.wikipedia.org/wiki/Cosine_similarity. * </p> * * @since 1.0 */ public class CosineSimilarity { /** * Calculates the cosine similarity for two given vectors. * * @param leftVector left vector * @param rightVector right vector * @return cosine similarity between the two vectors */ public Double cosineSimilarity(final Map<CharSequence, Integer> leftVector, final Map<CharSequence, Integer> rightVector) { if (leftVector == null || rightVector == null) { throw new IllegalArgumentException("Vectors must not be null"); } final Set<CharSequence> intersection = getIntersection(leftVector, rightVector); final double dotProduct = dot(leftVector, rightVector, intersection); double d1 = 0.0d; for (final Integer value : leftVector.values()) { d1 += Math.pow(value, 2); } double d2 = 0.0d; for (final Integer value : rightVector.values()) { d2 += Math.pow(value, 2); } double cosineSimilarity; if (d1 <= 0.0 || d2 <= 0.0) { cosineSimilarity = 0.0; } else { cosineSimilarity = dotProduct / (Math.sqrt(d1) * Math.sqrt(d2)); } return cosineSimilarity; } /** * Returns a set with strings common to the two given maps. * * @param leftVector left vector map * @param rightVector right vector map * @return common strings */ private Set<CharSequence> getIntersection(final Map<CharSequence, Integer> leftVector, final Map<CharSequence, Integer> rightVector) { final Set<CharSequence> intersection = new HashSet<>(leftVector.keySet()); intersection.retainAll(rightVector.keySet()); return intersection; } /** * Computes the dot product of two vectors. It ignores remaining elements. It means * that if a vector is longer than other, then a smaller part of it will be used to compute * the dot product. * * @param leftVector left vector * @param rightVector right vector * @param intersection common elements * @return The dot product */ private double dot(final Map<CharSequence, Integer> leftVector, final Map<CharSequence, Integer> rightVector, final Set<CharSequence> intersection) { long dotProduct = 0; for (final CharSequence key : intersection) { dotProduct += leftVector.get(key) * (long) rightVector.get(key); } return dotProduct; } }
def _get_gene_indices(self): end_indices = list(accumulate(self.lengths)) start_indices = [0] + end_indices[: -1] return list(zip(start_indices, end_indices))
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { IUserLikeData } from './like-button.interface'; export interface ILike { entityId: string; entityType: string; } export interface IAddLikeRequest extends ILike { } export interface IRemoveLikeRequest extends ILike { } @Injectable({ providedIn: 'root' }) export class LikeButtonService { private routePrefix = '/ubaseline/api/likes/'; constructor(private httpClient: HttpClient) { } public addLike = ({ entityId, entityType }: ILike): Observable<Array<IUserLikeData>> => this.httpClient.post<Array<IUserLikeData>>(`${this.routePrefix}AddLike?entityId=${entityId}&entityType=${entityType}`, {}) public removeLike = ({ entityId, entityType }: ILike): Observable<Array<IUserLikeData>> => this.httpClient.post<Array<IUserLikeData>>(`${this.routePrefix}RemoveLike?entityId=${entityId}&entityType=${entityType}`, {}) }
Millennials now make up the largest portion of the workforce of any generation. With approximately 73 million members, the Millennial generation – defined roughly as those born between 1980 and 1996 – has surpassed the Baby Boomers as the largest age-determined demographic in America. What’s more, according to an extensive 2016 Gallup study with Boomers retiring en masse in recent years, Millennials now account for one-third of all American workers. Still, Millennials also have the highest rates of unemployment. Further, even those who have found steady work are not likely to remain with their employers for any extended period of time, a tendency which appears to lend credence to characterisations of Millennials as “job-hoppers.” Increase in Google searches for “quit job” since 2009. 😯 As they rapidly approach their prime spending years, the influence Millennials wield over the economy will only grow, meaning businesses and employers would be wise to consider how Millennials think and what Millennials want. Unfortunately, for employers, this “job-hopping” trend is extremely costly. In this guide for working with millennials, we’ll discuss why Millennials job-hop, what they really want out of a workplace, and how we can attract and retain Millennial employees for the long haul. True Cost of Losing a Millennial Employee In its survey, Gallup found that 60% of employed Millennials claim to be “open to” a different job opportunity, a figure that plummets to around 45% among non-Millennials. In terms of more concrete behavior, 36% of Millennials plan on actively looking for a new job over the course of the next year as long as the general job market continues to improve. This response rate is, once again, 15% higher than among non-Millennials. According to Beyond.com’s research, it costs a company about $15,000 to $25,000 to replace each millennial employee. Estimates place the aggregate annual cost to the American economy of this Millennial turnover at more than $30 billion. It costs a company upto $25,000 to replace each millennial employee. During the twelve months prior to Gallup’s study, 21% of the Millennial workforce had switched jobs, nearly tripling the rate at which non-Millennials found new positions. Notably, very little of this job-hopping occurred intra-company: 93% of Millennials report that they changed employers the last time they entered a new professional role. Why are Millennials Job-Hopping? There remains plenty of uncertainty regarding the precise cause(s) of the fitfulness of Millennials’ professional journeys. One oft-cited argument highlights the fact that, on the whole, Millennials have pushed back a number of significant life events which, taken together, historically have indicated “settling down.” 1. Delaying “settling down” and adulthood milestones According to Goldman Sachs Global Investment Research, in the 1970s, the median age of marriage in the United States was 23; seven years into the present decade it sits at 30. In 2014, Gallup found that only 20% of 18 to 30 year-olds were married, a metric that in 1962 exceeded 60%. Baby Boomers reduced the figure to 40% before Gen X-ers depressed it all the way to 32%, but Millennials have, if anything, accelerated the historical trend. Among Millennials who do choose to marry, a mere 23% live in a residence they own, down from 56% in 1968, 43% in 1981, and 27% in 2007. Because shifting social mores have destigmatized having children out of wedlock, parenthood is one area where Millennials more closely mirror previous generations. Still, the fraction of women having children by the age of 25 has continued to decline from 12.9% in the 1970s to 7.9% in the 2010s. Delaying marriage, home ownership, and parenthood has surely unburdened many Millennials of certain responsibilities that compelled their parents and grandparents to stick with a steady job, but this isn’t the only consideration. On account of a combination of factors too numerous to recount here in any detail – the astronomical inflation of higher education costs, the worst financial crisis since the Great Depression, an ongoing set of wars of record-setting length, et al. – only half of Millennials profess to feeling comfortable with the amount of money they net. Gallup found that fewer than 40% of Millennials are “thriving” in any one aspect of “well-being,” and as a generation, Millennials overall well-being merely matches that of Gen X-ers and Baby Boomers. It’s heartening that the challenges alluded to above haven’t resulted in generational regression, but improvement in overall well-being from generation to generation is something that all parents hope for and most economists suggest indicates broad economic growth. Though stagnant well-being need not automatically result in an increase in employment conservatism among Millennials – it’s reasonable to argue that such stagnation is caused by pervasive job-hopping – these metrics may countervail those underlying the dominant narrative outlined above. 2. Lack of engagement in the workplace Despite being marginally more difficult to measure, one would be remiss if they failed to consider a “cultural” explanation of Millennial job-hopping. Among employed Millennials, only 29% are engaged at work, that is, only about three in ten are emotionally invested in and connected to their job. More than 16% are actively disengaged, meaning they represent an imminent threat to smooth workplace functioning. In sum, over half of Millennials find themselves unengaged to greater or lesser degrees at work. This is clearly far from an ideal state of affairs from employers’ points-of-view, but it exposes a significant insight into the job-hopping trend: Millennials, rightly or wrongly, are frequently dissatisfied with what their jobs have to offer. It’s hardly absurd to postulate that many Millennials aren’t attracted to job-hopping as such, but simply feel their employers consistently fail to provide them with any compelling reason to stay put. Consequently, when an ostensibly better opportunity presents itself, the disaffected Millennial has no reason not to give it try. What Millennials Care About Rather unhelpfully, discussions among non-Millennials about Millennials’ workplace preferences often involve more snide remarks about ping pong tables, bean bag chairs, expensive espresso machines, and relaxed dress codes than attempts at penetrating insight. 1. Purpose & Meaning (really!) Generally speaking, Millennials’ primary requirement of a job is not a healthy paycheck or a “fun” work environment – though employees of every generation justifiably expect and appreciate fair pay and a supportive workplace – but a defined sense of purpose. Perhaps because they put off starting families and, in many areas, either have abandoned or lack access to close-knit residential communities – sources of meaning that their parents and grandparents cherished – Millennials strive to find meaning in their job. As such, companies hoping to attract Millennial workers must not only be able to articulate a clear, ambitious vision, they must also be prepared to elucidate precisely how they hope each particular applicant will contribute to the organization’s overarching mission. 2. Work/Life Balance As the integration of meaning and purpose into the professional sphere suggests, Millennials have a much higher tolerance for the intertwining of work and life than previous generations. While most Millennials still advocate for striking the proper work/life balance, they understand “balance” less as a hard separation and more as a well-considered synthesis. This attitude appears to play out in their employee-supervisor relationships as well, as, according to Gallup, 62% of Millennials who feel they can talk to their manager about non-work-related issues plan to remain at their current company for at least a year. 3. Coaching and Recognition Millennials don’t want bosses – they want coaches. In practice, this means that, in the words of Gallup Chairman and CEO Jim Clifton, “Millennials don’t want bosses – they want coaches.” Clifton continues, “The role of an old-style boss is command and control. Millennials care about having managers who can coach them, who value them as both people and employees, and who help them understand and build their strengths.” How to Engage Millennials in the Workplace Ideally, there are three ways: 1. Open Up for Better Communication One way to move towards a more coach-like style of management is to open up and relax the communication and evaluation loops. Millennials are the first “digital natives,” meaning they came of age just as technologies such as text messaging, social media, and video chatting were achieving critical mass. This coincidence was the primary factor in determining the contours of their communication, and as a result, Millennials are accustomed to real-time, continuous streams-of-thought, not finite, self-contained conversations. Needless to say, Millennials tend to find standard annual performance reviews lamentably insufficient. Indeed, a 2013 PwC report showed that 41% of Millennials prefer to have their successes recognized at least once every month, whereas only 30% of non-Millennials found such frequency of recognition to be preferable. 2. Keep Doors Open As an employer, providing additional feedback and making oneself more available and approachable is painless enough thanks to services like Slack and Google Hangouts, but demonstrating substantial professional investment in a Millennial employee can be a more complex challenge. How can a supervisor “help [employees] understand and build their strengths?” 3. Invest in the Right Tools Implementing a learning management system (such as Continu) in your workplace can go a long way into offering Millennial workers the resources and opportunities needed to consistently engage in on-the-job learning. You will not only build a more skilled and competent workforce, but also demonstrate that you are interested and invested in your employees’ success and professional development. Even if a Millennial’s role remains fundamentally unchanged, if, through exposure to continuing education materials, they are able to execute their duties in increasingly efficient and adept ways, the likelihood they will experience discontent associated with professional plateauing greatly decreases. And the best thing – learning management systems don’t cost much. If Millennials are afforded the chance to become demonstrably better at their job – and if they receive recognition for doing so thanks to improved employee-supervisor communication – chances are they will feel that they are becoming an important part of something bigger than themselves. Purpose: found. Final Thoughts It would be naïve to pretend that the insights outlined above amount to a skeleton key for the Millennial generation. After all, Millennials are the most diverse – in any number of ways – generation America has ever produced. That being said, the record-breaking size of their cohort means that Millennials will be the country’s dominant economic force for years to come. We need only observe the meteoric rise and far-reaching dispersion of the sharing economy to understand the paradigm-altering shifts that Millennials are capable of triggering when they act in something approaching unison. As such, acknowledging that no group is completely alike, companies should dedicate time to make changes that will have a broad appeal in the Millennial age. The companies that can break the job-hopping cycle and attract and retain the best Millennial talent will establish a near-unassailable advantage over their competitors and be optimally-positioned to rule the marketplace for the foreseeable future.
#include <iostream> #include <vector> using namespace std; vector<vector<char> > grid; vector<vector<int> > vi; void move_robot(const char& o, int& x, int& y, int& obj); void change_direction(const char & d, char& o); int main() { int n, m, s, x, y, obj; char o, d; while(cin >> n >> m >> s && n && m && s) { obj = x = y = 0; grid.assign(n, vector<char>(m, '.')); vi.assign(n, vector<int>(m, 0)); for (int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { cin >> grid[i][j]; if(isalpha(grid[i][j])) { o = grid[i][j]; x = i; y = j; } } } while(s--) { cin >> d; if(d != 'F') change_direction(d, o); else move_robot(o, x, y, obj); } cout << obj << endl; } return 0; } void change_direction(const char & d, char& o) { if(d == 'E') { if(o == 'N') o = 'O'; else if (o == 'S') { o = 'L'; } else if (o == 'L') { o = 'N'; } else { o = 'S'; } } else { if(o == 'N') o = 'L'; else if (o == 'S') { o = 'O'; } else if (o == 'L') { o = 'S'; } else { o = 'N'; } } } void move_robot(const char& o, int& x, int& y, int& obj) { int line = 0, col = 0; if(o == 'N') { line = -1; col = 0; } else if (o == 'S') { line = 1; col = 0; } else if (o == 'L') { line = 0; col = 1; } else { line = 0; col = -1; } if(x + line >= 0 && x + line < (int)grid.size() && y + col >= 0 && y + col < (int)grid[0].size()) { if(grid[x+line][y + col] != '#') { if(grid[x+line][y + col] == '*' && !vi[x + line][y + col]) { vi[x + line][y + col] = 1; obj++; } x = x + line; y = y + col; } } }
<gh_stars>0 from tkinter import * import string root=Tk() root.geometry("500x700") topFrame=Frame(root) topFrame.pack() KeyBox=Entry(topFrame,width=40) KeyBox.pack() MessageBox=Text(topFrame, height=15, width=50) MessageBox.pack() ResultBox=Text(topFrame, height=15, width=50) ResultBox.pack() key='' def encryption(): ResultBox.delete('1.0', END) ResultBox.update() global key key=KeyBox.get() if key == '': key='EGE' key=key.upper() message=MessageBox.get("1.0","end-1c") message=message.replace(' ','') message=message.upper() message=message.translate(str.maketrans('', '', string.punctuation)) message=message.replace('\n', '') message=message.replace('\r', '') res=int() chiperText='' for i in range(len(message)): b=message[i] if b.isalpha(): a=i%len(key) if key[a] == ' ': if message[i]!='A': res=ord(message[i])-1 chiperText+=chr(res) else: continue else: res=(ord(message[i])+ord(key[a])) %26 res+=ord('A') chiperText+=chr(res) elif b.isdigit(): #mod 9 chiperText+= str((int(b)+len(key))%10) else: continue ResultBox.insert(END,chiperText) def decryption(): global key ResultBox.delete('1.0', END) ResultBox.update() global key key=KeyBox.get() if key == '': key='EGE' key=key.upper() message=MessageBox.get("1.0","end-1c") message=message.upper() res='' originalText='' a=0 for i in range(len(message)): b=message[i] if b.isalpha(): a=i%len(key) #boşluk casei ? if key[a] == ' ': if message[i]!='A': res=ord(message[i])+1 originalText+=chr(res) else: continue else : res=(ord(message[i])-ord(key[a])) %26 res+=ord('A') originalText+=chr(res) elif b.isdigit(): originalText+=str((int(b)-len(key)+10)%10) else: continue ResultBox.insert(END,originalText) EncButton=Button(topFrame,height=1, width=15, text="Encrypt", command=lambda: encryption()) EncButton.pack(side=LEFT) DecButton=Button(topFrame,height=1, width=15, text="Decrypt", command=lambda: decryption()) DecButton.pack(side=LEFT) mainloop()
/// Deserializes the given type from binary NBT data. /// /// The NBT data must start with a compound tag and represent the type `T` correctly, else the /// deserializer will return with an error. pub fn deserialize<T: DeserializeOwned>( bytes: &[u8], flavor: Flavor, ) -> Result<(T, String), NbtIoError> { deserialize_from(&mut Cursor::new(bytes), flavor) }
/** * Writes this class into a <b>XML</b> string that is ready * to be published or sent to a queue or topic. * @return A String of <b>XML</b> with * variables as <b>XML</b> elements. * @throws JAXBException Thrown when there was an error in * converting the {@link Event} class into <b>XML</b>. */ @Override public String toXML() throws JAXBException { StringWriter writer = new StringWriter(); JAXBContext jaxbContext = JAXBContext.newInstance(this.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(this, writer); return writer.toString(); }
import * as base62 from './utils/base62'; import type * as G from './game'; const reverseMapping = <T>(map: T[]) => { const ret: any = {}; for (let index = 0; index < map.length; index++) { ret[map[index]] = index; } return ret as T extends number ? { [index: number]: number } : { [index: string]: number }; }; const jobDecode: { job: G.Job, statDecode: G.Stat[] }[] = [ { job: 'PLD', statDecode: ['CRT', 'DET', 'DHT', 'SKS', 'TEN'] }, { job: 'WAR', statDecode: ['CRT', 'DET', 'DHT', 'SKS', 'TEN'] }, { job: 'DRK', statDecode: ['CRT', 'DET', 'DHT', 'SKS', 'TEN'] }, { job: 'GNB', statDecode: ['CRT', 'DET', 'DHT', 'SKS', 'TEN'] }, { job: 'WHM', statDecode: ['CRT', 'DET', 'DHT', 'SPS', 'PIE'] }, { job: 'SCH', statDecode: ['CRT', 'DET', 'DHT', 'SPS', 'PIE'] }, { job: 'AST', statDecode: ['CRT', 'DET', 'DHT', 'SPS', 'PIE'] }, { job: 'SGE', statDecode: ['CRT', 'DET', 'DHT', 'SPS', 'PIE'] }, { job: 'MNK', statDecode: ['CRT', 'DET', 'DHT', 'SKS'] }, { job: 'DRG', statDecode: ['CRT', 'DET', 'DHT', 'SKS'] }, { job: 'NIN', statDecode: ['CRT', 'DET', 'DHT', 'SKS'] }, { job: 'SAM', statDecode: ['CRT', 'DET', 'DHT', 'SKS'] }, { job: 'RPR', statDecode: ['CRT', 'DET', 'DHT', 'SKS'] }, { job: 'BRD', statDecode: ['CRT', 'DET', 'DHT', 'SKS'] }, { job: 'MCH', statDecode: ['CRT', 'DET', 'DHT', 'SKS'] }, { job: 'DNC', statDecode: ['CRT', 'DET', 'DHT', 'SKS'] }, { job: 'BLM', statDecode: ['CRT', 'DET', 'DHT', 'SPS'] }, { job: 'SMN', statDecode: ['CRT', 'DET', 'DHT', 'SPS'] }, { job: 'RDM', statDecode: ['CRT', 'DET', 'DHT', 'SPS'] }, { job: 'BLU', statDecode: ['CRT', 'DET', 'DHT', 'SPS'] }, { job: 'CRP', statDecode: ['CMS', 'CRL', 'CP'] }, { job: 'BSM', statDecode: ['CMS', 'CRL', 'CP'] }, { job: 'ARM', statDecode: ['CMS', 'CRL', 'CP'] }, { job: 'GSM', statDecode: ['CMS', 'CRL', 'CP'] }, { job: 'LTW', statDecode: ['CMS', 'CRL', 'CP'] }, { job: 'WVR', statDecode: ['CMS', 'CRL', 'CP'] }, { job: 'ALC', statDecode: ['CMS', 'CRL', 'CP'] }, { job: 'CUL', statDecode: ['CMS', 'CRL', 'CP'] }, { job: 'MIN', statDecode: ['GTH', 'PCP', 'GP'] }, { job: 'BTN', statDecode: ['GTH', 'PCP', 'GP'] }, { job: 'FSH', statDecode: ['GTH', 'PCP', 'GP'] }, ]; const jobEncode: { [index in G.Job]?: { index: number, statEncode: { [index in G.Stat]?: number } } } = {}; for (let index = 0; index < jobDecode.length; index++) { const item = jobDecode[index]; const statEncode = reverseMapping(item.statDecode); jobEncode[item.job] = { index, statEncode }; } const jobLevelDecode: G.JobLevel[] = [50, 60, 70, 80, 90]; const jobLevelEncode = reverseMapping(jobLevelDecode); enum GearType { // NormalWithoutMateria = 0, // NormalWith1Materia = 1, // NormalWith2Materia = 2, // NormalWith3Materia = 3, // NormalWith4Materia = 4, // NormalWith5Materia = 5, Special = 6, Customizable = 7, } const specialGearDecode = [ 10337, 10338, 10339, 10340, 10341, 10342, 10343, 10344, // Soul of the Crafter 17726, // Spearfishing Gig ] as G.GearId[]; const specialGearEncode = reverseMapping(specialGearDecode); class Ranges { public version = 77; public job = 0; public jobLevel = 0; public syncLevel = 0; public gearType = 0; public gearId = 0; public materiaSlot = 0; public materiaStat = 0; public materiaGrade = 0; public specialGear = 0; public customStat = 0; private _version = 4; public useVersion(version: number) { this._version = version; if (version >= 4) { this.job = 31; // jobDecode.length this.jobLevel = 5; // jobLevelDecode.length this.syncLevel = 670; this.gearType = 8; // gearTypes.length this.gearId = 50000; this.materiaSlot = 6; this.materiaGrade = 10; this.specialGear = 9; // specialGearDecode.length this.customStat = 1001; } } public useJob(job: G.Job) { this.materiaStat = jobDecode[jobEncode[job]!.index].statDecode.length; // TODO: version } } export function stringify({ job, jobLevel, syncLevel, gears }: G.Gearset): string { const version = 4; const ranges = new Ranges(); ranges.useVersion(version); ranges.useJob(job); const { statEncode } = jobEncode[job]!; const { statDecode } = jobDecode[jobEncode[job]!.index]; const gearTypeEncode: number[] = []; const materiaEncode: number[][] = []; // materiaEncode[grade][statIndex] let hasInvalidMateria = false; materiaEncode[ranges.materiaGrade] = []; for (const { id, materias, customStats } of gears) { if (id in specialGearEncode) { gearTypeEncode[GearType.Special] = 1; } else if (customStats !== undefined) { gearTypeEncode[GearType.Customizable] = 1; } else { gearTypeEncode[materias.length] = 1; for (const materia of materias) { if (materia !== null && statEncode[materia[0]] !== undefined) { materiaEncode[materia[1]] ??= []; materiaEncode[materia[1]][statEncode[materia[0]]!] = 1; } else { hasInvalidMateria = true; } } } } let gearTypeRange = 0; for (let i = 0; i < ranges.gearType; i++) { if (gearTypeEncode[i] !== undefined) { gearTypeEncode[i] = gearTypeRange; gearTypeRange += 1; } } let materiaRange = 0; for (let grade = ranges.materiaGrade; grade >= 1; grade--) { if (materiaEncode[grade] === undefined) continue; for (let statIndex = 0; statIndex < ranges.materiaStat; statIndex++) { if (materiaEncode[grade][statIndex] !== undefined) { materiaEncode[grade][statIndex] = materiaRange; materiaRange += 1; } } } if (hasInvalidMateria) { materiaRange += 1; } let minMateriaGrade = 0; // eslint-disable-next-line no-unmodified-loop-condition while (!hasInvalidMateria && materiaEncode[minMateriaGrade] === undefined) minMateriaGrade++; const gearCodes: { id: G.GearId, materias: number[], customStats?: G.Stats }[] = []; const specialGears: G.GearId[] = []; for (const { id, materias, customStats } of gears) { if (!(id > 0)) { console.warn(`share.stringify: gear id ${id} invalid.`); continue; } if (id in specialGearEncode) { specialGears.push(id); } else { const materiaCodes = []; for (const materia of materias) { materiaCodes.push(materia === null || statEncode[materia[0]] === undefined ? materiaRange - 1 // use the largest materia code for empty slot : materiaEncode[materia[1]][statEncode[materia[0]]!]); } gearCodes.push({ id, materias: materiaCodes, customStats }); } } if (gearCodes.length === 0 && specialGears.length === 0) return ''; // try to preserve the original order of left ring and right ring // this may mismatch other slots in some cases, but these order won't affect anything let ringIndex = gearCodes.length - 1; while (gearCodes[ringIndex]?.materias.length === 0) ringIndex--; const ringsInversed = gearCodes[ringIndex - 1]?.id > gearCodes[ringIndex ]?.id; gearCodes.sort((a, b) => a.id - b.id); let gearIdDeltaRange = 0; for (let i = 1; i < gearCodes.length; i++) { const delta = gearCodes[i].id - gearCodes[i - 1].id; if (delta > gearIdDeltaRange) { gearIdDeltaRange = delta; } } gearIdDeltaRange += 1; let gearIdDeltaDirection = 1; if (gearCodes.length > 1) { // reverse pack order in two case: // delta range is too large to be encoded into the first gear id // the first delta is smaller than the last, encode small value earlier can slightly shorten encoded string if (gearIdDeltaRange >= gearCodes[0].id || gearCodes[1].id - gearCodes[0].id < gearCodes[gearCodes.length - 1].id - gearCodes[gearCodes.length - 2].id) { gearIdDeltaDirection = -1; gearCodes.reverse(); } // the last id delta might be 0, it could break endding detect when decode // so we always increase it by 1, but do this can make it larger than delta range if (gearCodes[gearCodes.length - 1].id - gearCodes[gearCodes.length - 2].id === gearIdDeltaDirection * gearIdDeltaRange - 1) { gearIdDeltaRange += 1; } } let result = BigInt(0); const write = (value: number, range: number) => { // console.debug('write', value, range); result = result * BigInt(range) + BigInt(value < range ? value : range - 1); }; const writeBoolean = (value: boolean) => write(value ? 1 : 0, 2); for (let i = gearCodes.length - 1; i >= 0; i--) { const { id, materias, customStats } = gearCodes[i]; if (i > 0) { const delta = (id - gearCodes[i - 1].id) * gearIdDeltaDirection; write(delta + (i === gearCodes.length - 1 ? 1 : 0), gearIdDeltaRange); } else { writeBoolean(ringsInversed); writeBoolean(gearIdDeltaDirection === 1); write(gearIdDeltaRange, id); write(id, ranges.gearId); } if (customStats !== undefined) { for (let i = statDecode.length - 1; i >= 0; i--) { write(customStats[statDecode[i]] ?? 0, ranges.customStat); } } else { for (let i = materias.length - 1; i >= 0; i--) { write(materias[i], materiaRange); } } write(gearTypeEncode[customStats === undefined ? materias.length : GearType.Customizable], gearTypeRange); } for (const id of specialGears) { write(specialGearEncode[id], ranges.specialGear); write(gearTypeEncode[GearType.Special], gearTypeRange); } for (let grade = minMateriaGrade; grade <= ranges.materiaGrade; grade++) { if (grade === 0) continue; for (let statIndex = ranges.materiaStat - 1; statIndex >= 0; statIndex--) { writeBoolean(materiaEncode[grade]?.[statIndex] !== undefined); } } write(minMateriaGrade, ranges.materiaGrade + 1); for (let i = ranges.gearType - 1; i >= 0; i--) { writeBoolean(gearTypeEncode[i] !== undefined); } if (syncLevel !== undefined || jobLevel !== jobLevelDecode[ranges.jobLevel - 1]) { write(syncLevel ?? 0, ranges.syncLevel); write(jobLevelEncode[jobLevel], ranges.jobLevel); writeBoolean(true); } else { writeBoolean(false); } write(jobEncode[job]!.index, ranges.job); write(version, ranges.version); return base62.encode(result); } export function parse(s: string): G.Gearset | 'legacy' { let input = base62.decode(s); const read = (range: number): number => { const rangeBI = BigInt(range); const ret = input % rangeBI; input = input / rangeBI; return Number(ret); }; const readBoolean = () => read(2) === 1; const ranges = new Ranges(); const version = read(ranges.version); if (version < 4) return 'legacy'; ranges.useVersion(version); const { job, statDecode } = jobDecode[read(ranges.job)]; ranges.useJob(job); const synced = readBoolean(); const jobLevel = jobLevelDecode[synced ? read(ranges.jobLevel) : ranges.jobLevel - 1]; const syncLevel = synced && read(ranges.syncLevel) || undefined; const gearTypeDecode: number[] = []; for (let i = 0; i < ranges.gearType; i++) { if (readBoolean()) { gearTypeDecode.push(i); } } const minMateriaGrade = read(ranges.materiaGrade + 1); const materiaDecode: G.GearsetMaterias = []; for (let grade = ranges.materiaGrade; grade >= minMateriaGrade; grade--) { if (grade === 0) continue; for (let statIndex = 0; statIndex < ranges.materiaStat; statIndex++) { if (readBoolean()) { materiaDecode.push([statDecode[statIndex], grade as G.MateriaGrade]); } } } if (minMateriaGrade === 0) { materiaDecode.push(null); } const gears: G.Gearset['gears'] = []; let gearIdDeltaRange = 0; let gearIdDeltaDirection = 0; let ringsInversed = false; let id = -1; while (input !== BigInt(0)) { // eslint-disable-line no-unmodified-loop-condition const gearType = gearTypeDecode[read(gearTypeDecode.length)]; const materias: G.GearsetMaterias = []; let customStats: G.Stats | undefined; if (gearType === GearType.Special) { const id = specialGearDecode[read(ranges.specialGear)]; gears.push({ id, materias }); continue; } if (gearType === GearType.Customizable) { customStats = {}; for (const stat of statDecode) { const value = read(ranges.customStat); if (value > 0) { customStats[stat] = value; } } } else { for (let i = 0; i < gearType; i++) { materias[i] = materiaDecode[read(materiaDecode.length)]; } } if (id === -1) { id = read(ranges.gearId); gearIdDeltaRange = read(id); gearIdDeltaDirection = readBoolean() ? 1 : -1; ringsInversed = readBoolean(); } else { id += (read(gearIdDeltaRange) - (input === BigInt(0) ? 1 : 0)) * gearIdDeltaDirection; } gears.push({ id: id as G.GearId, materias, customStats }); } if (ringsInversed !== (gearIdDeltaDirection === -1)) { gears.reverse(); } return { job, jobLevel, syncLevel, gears }; } // const s = '1OUOJLa40M28M25Zx9onPbVFINb9tatYuSsZ'; // console.assert(stringify(parse(s)) === s);
/** * Object containing the elements of an HTTP request to the Talk2M/M2Web APIs. * * @author HMS Networks, MU Americas Solution Center */ public class TMHttpRequest { /** HTTP request URL */ private final String url; /** HTTP request headers */ private final Map<String, String> headers; /** HTTP request body */ private final String body; /** * Creates a new HTTP request object with the specified URL, headers and body. * * @param url HTTP request URL * @param headers HTTP request headers * @param body HTTP request body */ public TMHttpRequest(String url, Map<String, String> headers, String body) { this.url = url; this.headers = headers; this.body = body; } /** * Gets the URL of the HTTP request * * @return HTTP request URL */ public String getUrl() { return url; } /** * Gets the headers of the HTTP request * * @return HTTP request headers */ public Map<String, String> getHeaders() { return headers; } /** * Gets the body of the HTTP request * * @return HTTP request body */ public String getBody() { return body; } }
<reponame>uk-gov-mirror/hmcts.cmc-citizen-frontend import { InterestBreakdown } from 'claims/models/interestBreakdown' import { InterestDate } from 'claims/models/interestDate' import { Moment } from 'moment' import { MomentFactory } from 'shared/momentFactory' export class Interest { constructor (public type?: string, public rate?: number, public reason?: string, public specificDailyAmount?: number, public interestBreakdown?: InterestBreakdown, public interestDate?: InterestDate, public lastInterestCalculationDate?: Moment) {} deserialize (input?: any): Interest { if (input) { this.type = input.type if (input.rate) { this.rate = input.rate } if (input.reason) { this.reason = input.reason } if (input.specificDailyAmount) { this.specificDailyAmount = input.specificDailyAmount } if (input.interestBreakdown) { this.interestBreakdown = new InterestBreakdown().deserialize(input.interestBreakdown) } if (input.interestDate) { this.interestDate = new InterestDate().deserialize(input.interestDate) } if (input.lastInterestCalculationDate) { this.lastInterestCalculationDate = MomentFactory.parse(input.lastInterestCalculationDate) } } return this } }
// NOTE: Assumes that Xattribute is present func StripXattrAndGetBody(bodyWithXattr []byte) ([]byte, error) { xattrSize, err := GetXattrSize(bodyWithXattr) if err != nil { return nil, err } return bodyWithXattr[xattrSize+4:], nil }
N = int(input()) X = list(map(int, input().split())) def calc_power(p): P = list(map(lambda x: (x-p)**2, X)) return sum(P) power = [] _min = min(X) _max = max(X) if _min != _max: for p in range(_min, _max): power.append(calc_power(p)) print(min(power)) else: power = calc_power(_min) print(power)
''' weapon component (for items) base weapons ''' import pygame import random import assets import item pygame.init() #with open('docs/weapon table.csv', newline='') as csvfile: # weapon_reader = csv.reader(csvfile, delimiter=' ', quotechar='|') # for row in weapon_reader: # print(', '.join(row)) class Weapon(object): def __init__(self, name, ddie_count, ddie_size, cdie, cmult, melee=True, hands=1, skill='sword', throw=False, ammo=None, reach=False, slash=False, stab=False, strike=False, parry=False, riposte=False, feint=False, trip=False, disarm=False, enhance_list = None): self.name = name self.ddie_count = ddie_count self.ddie_size = ddie_size self.cdie = cdie self.cmult = cmult self.melee = melee self.hands = hands self.skill = skill self.throw = throw self.ammo = ammo self.reach = reach self.slash = slash self.stab = stab self.strike = strike self.parry = parry self.riposte = riposte self.feint = feint self.trip = trip self.disarm = disarm if self.slash: self.bleed = True self.cleave = True self.amputate = True if self.stab: self.bleed = True self.pierce = True if self.strike: self.pierce = True self.daze = True self.holy = True self.enhance_list = enhance_list # components fist_com = Weapon('fist', 1, 3, 20, 3, skill='unarmed', strike=True, feint=True, trip=True, disarm=True) fist = item.Item(name='fist', x=0, y=0, sprite=None, shadow_sprite=None, quantity=1, action_set=['wield', 'sheathe'], weapon_com=fist_com) # corpses small_corpse = Weapon('small corpse', 1, 2, 20, 4, skill='unarmed', throw=True) # items banana = Weapon('banana', 1, 2, 18, 2, skill='unarmed', throw=True, trip=True) battleax = Weapon('battleax', 1, 8, 20, 3, skill='axe', slash=True) tomahawk = Weapon('tomahawk', 1, 6, 20, 2, skill='axe', throw=True, slash=True) cleaver = Weapon('cleaver', 1, 4, 19, 2, skill='axe', throw=True, slash=True) halberd = Weapon('halberd', 1, 10, 20, 3, hands=2, skill='axe', reach=True, slash=True, stab=True, feint=True, trip=True) pollaxe = Weapon('pollaxe', 1, 8, 20, 4, hands=2, skill='axe', reach=True, slash=True, stab=True, trip=True) daneaxe = Weapon('daneaxe', 1, 12, 20, 3, hands=2, skill='axe', slash=True) warpick = Weapon('warpick', 1, 6, 20, 4, skill='axe', stab=True) claymore = Weapon('claymore', 1, 12, 19, 2, hands=2, slash=True, stab=True, feint=True) zweihander = Weapon('zweihander', 2, 6, 19, 2, hands=2, slash=True, stab=True, strike=True) svardstav = Weapon('svardstav', 1, 10, 19, 2, hands=2, reach=True, slash=True, feint=True, trip=True) sabre = Weapon('sabre', 1, 8, 19, 2, stab=True, riposte=True, feint=True) gladius = Weapon('gladius', 1, 8, 20, 3, slash=True, stab=True, riposte=True, feint=True) dirk = Weapon('dirk', 1, 4, 19, 2, throw=True, slash=True, stab=True, riposte=True, feint=True) rapier = Weapon('rapier', 1, 6, 18, 2, stab=True, riposte=True, feint=True) hooksword = Weapon('hooksword', 1, 6, 19, 2, slash=True, disarm=True) katana = Weapon('katana', 2, 4, 18, 2, hands=2, slash=True, feint=True) cutlass = Weapon('cutlass', 1, 8, 18, 2, slash=True) javelin = Weapon('javelin', 1, 8, 19, 2, skill='spear', throw=True, reach=True, stab=True) trident = Weapon('trident', 1, 8, 20, 2, skill='spear', throw=True, reach=True, stab=True, disarm=True) guisarme = Weapon('guisarme', 2, 4, 20, 3, hands=2, skill='spear', reach=True, stab=True, feint=True, trip=True, disarm=True) glaive = Weapon('glaive', 1, 10, 20, 3, hands=2, skill='spear', reach=True, slash=True, feint=True) naginata = Weapon('naginata', 2, 6, 20, 2, hands=2, reach=True, slash=True) scythe = Weapon('scythe', 2, 4, 20, 4, hands=2, skill='spear', slash=True, trip=True) spear = Weapon('spear', 1, 10, 20, 2, skill='spear', throw=True, reach=True, stab=True) pike = Weapon('pike', 1, 12, 20, 2, hands=2, skill='spear', reach=True, stab=True, feint=True) partizan = Weapon('partizan', 2, 4, 20, 3, hands=2, skill='spear', reach=True, slash=True, stab=True, feint=True) shillelagh = Weapon('shillelagh', 1, 8, 20, 3, skill='club', strike=True) morningstar = Weapon('morningstar', 1, 10, 20, 3, skill='club', stab=True, strike=True) nunchaku = Weapon('nunchaku', 1, 4, 18, 20, skill='club', strike=True, feint=True, disarm=True) mace = Weapon('mace', 1, 6, 20, 3, skill='club', strike=True) kanabo = Weapon('kanabo', 2, 6, 19, 2, hands=2, skill='club', strike=True) cudgel = Weapon('cudgel', 1, 12, 20, 3, hands=2, skill='club', strike=True) flail = Weapon('flail', 2, 4, 20, 4, skill='club', reach=True, strike=True, trip=True, disarm=True) warhammer = Weapon('warhammer', 1, 12, 20, 2, skill='club', throw=True, strike=True) maul = Weapon('maul', 1, 10, 18, 20, 3, hands=2, skill='club', strike=True) lucerne = Weapon('lucerne', 2, 4, 20, 3, hands=2, skill='club', reach=True, stab=True, strike=True, feint=True) harpoon = Weapon('harpoon', 1, 6, 20, 2, melee=False, hands=2, skill='bow', ammo='none', stab=True) recurve_bow = Weapon('recurve_bow', 1, 12, 19, 2, melee=False, hands=2, skill='bow', ammo='arrow', stab=True) longbow = Weapon('longbow', 1, 12, 20, 3, melee=False, hands=2, skill='bow', ammo='arrow', stab=True) arbalest = Weapon('arbalest', 2, 6, 20, 3, melee=False, hands=2, skill='bow', ammo='bolt', stab=True) crossbow = Weapon('crossbow', 2, 6, 19, 2, melee=False, hands=2, skill='bow', ammo='bolt', stab=True) bola = Weapon('bola', 1, 4, 20, 2, melee=False, skill='throw', ammo='self', strike=True) dart = Weapon('dart', 1, 4, 19, 3, melee=False, skill='throw', ammo='self', stab=True) shuriken = Weapon('shuriken', 1, 4, 18, 2, melee=False, skill='throw', ammo='self', slash=True) boomerang = Weapon('boomerang', 1, 4, 20, 2, melee=False, skill='throw', ammo='none', strike=True) roundshield = Weapon('roundshield', 1, 12, 20, 2, melee=False, skill='shield', throw=True, parry=True) kiteshield = Weapon('kiteshield', 1, 12, 20, 3, melee=False, skill='shield', parry=True) heatershield = Weapon('heatershield', 1, 8, 19, 2, melee=False, skill='shield', parry=True) scutum = Weapon('scutum', 2, 6, 20, 2, melee=False, skill='shield', parry=True) buckler = Weapon('buckler', 1, 6, 18, 3, melee=False, skill='shield', parry=True) # enhancements ''' flaming - sets target on fire freezing - cools target slimy - covers target in acid moist - douses target in water oily - douses target in oil spiky - deals 1d4 thrust to attackers volcanic - douses target in lava chaotic - max rolls on damage are rerolled and added to total damage lucky - crit range becomes 10-20 vorpal - crit multiplier becomes 6 refined - skill influences double large - ddie count becomes 4 heavy - ddie size becomes 20 ''' # weapon creators def gen(com, x, y): sprite, shadow_sprite = assets.from_file('tiles/weapons/' + com.name + '.png') mainhand_sprite, mainhand_shadow_sprite = assets.from_file('tiles/weapons/' + com.name + '_mainhand.png') offhand_sprite = pygame.transform.flip(mainhand_sprite, True, False) offhand_shadow_sprite = pygame.transform.flip(mainhand_shadow_sprite, True, False) new_weapon = item.Item(name=com.name.replace('_', ' '), x=x, y=y, sprite=sprite, shadow_sprite=shadow_sprite, quantity=1, action_set=['wield', 'sheathe'], weapon_com=com, mainhand_sprite=mainhand_sprite, mainhand_shadow_sprite=mainhand_shadow_sprite, offhand_sprite=offhand_sprite, offhand_shadow_sprite=offhand_shadow_sprite) return new_weapon def small_weapon(x, y): return gen(random.choice([tomahawk, javelin, dirk, gladius, mace]), x, y) def small_shield(x, y): return gen(random.choice([buckler, roundshield, kiteshield, heatershield]), x, y) def good_weapon(x, y): return gen(random.choice([halberd, pollaxe, spear, pike, partizan, cudgel, flail, morningstar, lucerne]), x, y)
Shape and fatigue life prediction of chip resistor solder joints In order to increase the fatigue life of chip resistor, it is necessary to optimize the shape of solder joints. Shape and fatigue life of chip resistor solder joint were predicted by using finite element analysis methods. Through changing the solder volume, four typical solder joint shape prediction were conducted, and three-dimensional mechanical model of fatigue life analysis was set up. The distribution characteristics of the stress and strain in solder joints under thermal cycle load were analyzed. Based on this, fatigue life of solder joints with different solder volumes was predicted. Analysis results show that under thermal cycling conditions solder joints of tiny concave acquired the best mechanical properties, and the its life is the longest.
/** * Returns a new {@code CallOptions} with the given call credentials. */ @ExperimentalApi("https//github.com/grpc/grpc-java/issues/1914") public CallOptions withCallCredentials(@Nullable CallCredentials credentials) { CallOptions newOptions = new CallOptions(this); newOptions.credentials = credentials; return newOptions; }
<gh_stars>0 import { Refine, Resource } from "@pankod/refine"; import "@pankod/refine/dist/styles.min.css"; import { authProvider, dataProvider, useI18nProvider } from "providers"; import { AppFooter, AppHeader, AppSider, AppTitle } from "components"; import { Login } from "pages/login"; import { PostList, PostCreate, PostEdit, PostShow } from "pages/posts"; import { UserList } from "pages/users"; function App() { const i18nProvider = useI18nProvider(); return ( <Refine dataProvider={dataProvider} authProvider={authProvider} i18nProvider={i18nProvider} LoginPage={Login} Header={AppHeader} Footer={AppFooter} Title={AppTitle} Sider={AppSider} mutationMode="undoable" undoableTimeout={3500} > <Resource name="user" list={UserList} /> {/* <Resource name="post" list={PostList} create={PostCreate} edit={PostEdit} show={PostShow} canDelete /> */} </Refine> ); } export default App;
class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 dp = [0]*len(prices) dp2 = [0]*len(prices) for i in range(len(prices)-2,-1,-1): for j in range(len(prices)-1, i, -1): dp[i] = max(dp[i], prices[j]-prices[i] + (dp2[j+2] if j+2<len(prices) else 0)) dp2[i] = max(dp2[i+1], dp[i]) return dp2[0]
def _pid_time(self, pid, time): if not self.want_pid_time: return '' try: i = self._thread_id() % 99999 return '{:%b %d %H:%M:%S} {:5d} {:5d} '.format(time, pid, i) except Exception: self.exception_count += 1 self._err('error formatting pid and time', pkdexc()) return 'Xxx 00 00:00:00 00000.0'
//============================================================================== // // Copyright (c) 2013- // Authors: // * Ernst Moritz Hahn <[email protected]> (University of Oxford) // //------------------------------------------------------------------------------ // // This file is part of PRISM. // // PRISM is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // PRISM is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with PRISM; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //============================================================================== package param; import java.math.BigInteger; import java.util.ArrayList; import java.util.Random; /** * Implements a region representation by a box (hyper-rectangle). * This means that for each parameter we have a lower and upper bound, and * the region contains all points so that the corresponding dimensions are * (not strictly) between these lower and upper bounds. * * @author Ernst Moritz Hahn <[email protected]> (University of Oxford) * @see BoxRegionFactory */ final class BoxRegion extends Region { /** used to produce random inner points of box regions */ static Random random = new Random(); /** regions are only to be split at longest side */ static final int SPLIT_LONGEST = 1; /** regions are to be split at all sides on each split */ static final int SPLIT_ALL = 2; /** lower bound for each parameter */ private BigRational[] lower; /** upper bound for each parameter */ private BigRational[] upper; // constructors /** * Constructs a new box region. * Does not assign lower and upper bounds, that is the regions is * not direcly usable after construction. * * @param factory factory this box region belongs to */ private BoxRegion(BoxRegionFactory factory) { this.factory = factory; lower = new BigRational[factory.numVariables()]; upper = new BigRational[factory.numVariables()]; } /** * Constructs a new box region. * * @param factory factory this box region belongs to * @param lower lower bounds for each parameter * @param upper upper bounds for each parameter */ BoxRegion(BoxRegionFactory factory, BigRational[] lower, BigRational[] upper) { this.factory = factory; this.lower = new BigRational[lower.length]; this.upper = new BigRational[upper.length]; System.arraycopy(lower, 0, this.lower, 0, lower.length); System.arraycopy(upper, 0, this.upper, 0, upper.length); } /** * Copy constructor for box regions. * For internal use, because regions are generally immutable, so that * there is no need to have external copy constructors. * * @param other region to copy from */ private BoxRegion(BoxRegion other) { this.factory = other.factory; this.lower = new BigRational[other.lower.length]; this.upper = new BigRational[other.upper.length]; System.arraycopy(other.lower, 0, this.lower, 0, other.lower.length); System.arraycopy(other.upper, 0, this.upper, 0, other.upper.length); } /** * Sets lower and upper bound of given parameter. * * @param dim parameter to set bounds of * @param lower new lower bound of parameter * @param upper new upper bound of parameter */ private void setDimension(int dim, BigRational lower, BigRational upper) { this.lower[dim] = lower; this.upper[dim] = upper; } @Override int getDimensions() { return lower.length; } /** * Get lower bound of given parameter in region. * * @param dim parameter to get lower bound of * @return lower bound of given parameter in region */ BigRational getDimensionLower(int dim) { return lower[dim]; } /** * Get upper bound of given parameter in region. * * @param dim parameter to get lower bound of * @return upper bound of given parameter in region */ BigRational getDimensionUpper(int dim) { return upper[dim]; } @Override public boolean equals(Object object) { if (!(object instanceof BoxRegion)) { return false; } BoxRegion other = (BoxRegion) object; if (this.getDimensions() != other.getDimensions()) { return false; } for (int i = 0; i < getDimensions(); i++) { if (!this.lower[i].equals(other.lower[i])) { return false; } if (!this.upper[i].equals(other.upper[i])) { return false; } } return true; } @Override public int hashCode() { int hash = 0; for (int i = 0; i < getDimensions(); i++) { hash = lower[i].hashCode() + (hash << 6) + (hash << 16) - hash; hash = upper[i].hashCode() + (hash << 6) + (hash << 16) - hash; } return hash; } /** * Gets the central points of the region. * * @return point in the centre of the region */ Point getMidPoint() { BigRational[] point = new BigRational[lower.length]; for (int dim = 0; dim < lower.length; dim++) { BigRational mid = lower[dim].add(upper[dim]).divide(2); point[dim] = mid; } return new Point(point); } /** * Get volume of the region. * The volumes of disjoint region which cover the whole parameter * space sum up to 1. This implies that the volumes are normalised * according to the upper and lower bounds of the parameters. * * @return volume of this region */ @Override BigRational volume() { BigRational volume = BigRational.ONE; for (int dim = 0; dim < lower.length; dim++) { volume = volume.multiply(upper[dim].subtract(lower[dim])); volume = volume.divide(factory.sideWidth(dim)); } return volume; } @Override boolean contains(Point point) { for (int dim = 0; dim < getDimensions(); dim++) { if (point.getDimension(dim).compareTo(lower[dim]) < 0) { return false; } if (point.getDimension(dim).compareTo(upper[dim]) > 0) { return false; } } return true; } @Override boolean contains(Region region) { BoxRegion other = (BoxRegion) region; for (int dim = 0; dim < getDimensions(); dim++) { if (other.lower[dim].compareTo(this.lower[dim]) == -1) { return false; } if (other.upper[dim].compareTo(this.upper[dim]) == +1) { return false; } } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("("); for (int dim = 0; dim < getDimensions(); dim++) { builder.append("["); builder.append(lower[dim].doubleValue()); builder.append(","); builder.append(upper[dim].doubleValue()); builder.append("]"); if (dim < getDimensions() - 1) { builder.append(","); } } builder.append(")"); return builder.toString(); } @Override RegionValues binaryOp(int op, StateValues values1, StateValues values2) { RegionValues result; if ((op == Region.EQ || op == Region.NE || op == Region.GT || op == Region.GE || op == Region.LT || op == Region.LE)) { result = cmpOp(op, values1, values2); } else { result = new RegionValues(factory); int numStates = values1.getNumStates(); StateValues values = new StateValues(numStates, factory.getInitialState()); for (int state = 0; state < numStates; state++) { if (op == Region.IMPLIES || op == Region.IFF || op == Region.OR || op == Region.AND) { boolean stateVal = booleanOp(op, values1.getStateValueAsBoolean(state), values2.getStateValueAsBoolean(state)); values.setStateValue(state, stateVal); } else if (op == Region.PLUS || op == Region.MINUS || op == Region.TIMES || op == Region.DIVIDE) { Function stateVal = arithOp(op, values1.getStateValueAsFunction(state), values2.getStateValueAsFunction(state)); values.setStateValue(state, stateVal); } else { throw new UnsupportedOperationException("operator not yet implemented for parametric analyses"); } } result.add(this, values); } return result; } private RegionValues cmpOp(int op, StateValues op1, StateValues op2) { ConstraintChecker checker = factory.getConstraintChecker(); RegionsTODO remaining = new RegionsTODO(); remaining.add(this); BigRational requiredVolume = this.volume().multiply(BigRational.ONE.subtract(factory.getPrecision())); BigRational doneVolume = BigRational.ZERO; RegionValues result = new RegionValues(factory); Function lastFunction = null; while (doneVolume.compareTo(requiredVolume) == -1) { BoxRegion region = (BoxRegion) remaining.poll(); StateValues newValues = new StateValues(op1.getNumStates(), factory.getInitialState()); boolean allDecided = true; for (int state = 0; state < op1.getNumStates(); state++) { StateValue op1Val = op1.getStateValue(state); StateValue op2Val = op2.getStateValue(state); Function op1ValFn = op1Val instanceof Function ? (Function) op1Val : null; Function op2ValFn = op2Val instanceof Function ? (Function) op2Val : null; if (op == Region.EQ) { if (op1Val instanceof StateBoolean) { newValues.setStateValue(state, op1Val.equals(op2Val)); } else if (op1Val.equals(op2Val)) { newValues.setStateValue(state, true); } else if (checker.check(region, op1ValFn.subtract(op2ValFn), true)) { newValues.setStateValue(state, false); } else if (checker.check(region, op2ValFn.subtract(op1ValFn), true)) { newValues.setStateValue(state, false); } else { allDecided = false; break; } } else if (op == Region.NE) { if (op1Val instanceof StateBoolean) { newValues.setStateValue(state, !op1Val.equals(op2Val)); } else if (op1Val.equals(op2Val)) { newValues.setStateValue(state, false); } else if (checker.check(region, op1ValFn.subtract(op2ValFn), true)) { newValues.setStateValue(state, true); } else if (checker.check(region, op2ValFn.subtract(op1ValFn), true)) { newValues.setStateValue(state, true); } else { allDecided = false; break; } } else { boolean strict = op == Region.GT || op == Region.LT; Function cmpTrue = (op == Region.LT || op == Region.LE) ? op2ValFn.subtract(op1ValFn) : op1ValFn.subtract(op2ValFn); if (checker.check(region, cmpTrue, strict)) { newValues.setStateValue(state, true); } else { Function cmpFalse = (op == Region.LT || op == Region.LE) ? op1ValFn.subtract(op2ValFn) : op2ValFn.subtract(op1ValFn); if (checker.check(region, cmpFalse, !strict)) { newValues.setStateValue(state, false); } else { allDecided = false; lastFunction = op2ValFn.subtract(op1ValFn); break; } } } } if (allDecided) { result.add(region, newValues); doneVolume = doneVolume.add(region.volume()); } else { remaining.addAll(region.split(lastFunction)); } } return result; } /** * Performs given operation on two rational functions. * * @param op operation to perform, see values in {@code Region} * @param op1 first operand * @param op2 second operand * @return value of operation */ private Function arithOp(int op, Function op1, Function op2) { Function result = null; switch (op) { case Region.PLUS: result = op1.add(op2); break; case Region.MINUS: result = op1.subtract(op2); break; case Region.TIMES: result = op1.multiply(op2); break; case Region.DIVIDE: result = op1.divide(op2); break; default: throw new IllegalArgumentException("unsupported arithmetic operator number " + op); } return result; } /** * Performs given operation on two booleans. * * @param op operation to perform, see values in {@code Region} * @param op1 first operand * @param op2 second operand * @return value of operation */ private boolean booleanOp(int op, boolean op1, boolean op2) { boolean result = false; switch (op) { case Region.IMPLIES: result = !op1 || op2; break; case Region.IFF: result = op1 == op2; break; case Region.OR: result = op1 || op2; break; case Region.AND: result = op1 && op2; break; default: throw new IllegalArgumentException("unsupported boolean operator number " + op); } return result; } @Override RegionValues ITE(StateValues valuesI, StateValues valuesT, StateValues valuesE) { RegionValues result = new RegionValues(factory); int numStates = valuesI.getNumStates(); StateValues values = new StateValues(numStates, factory.getInitialState()); for (int state = 0; state < numStates; state++) { if (valuesI.getStateValueAsBoolean(state)) { values.setStateValue(state, valuesT.getStateValue(state)); } else { values.setStateValue(state, valuesE.getStateValue(state)); } } result.add(this, values); return result; } /** * Split region in longest dimension. * * @return set of new regions covering same area */ private ArrayList<Region> splitLongest() { int longestSide = -1; BigRational longestLength = BigRational.ZERO; for (int side = 0; side < lower.length; side++) { BigRational sideLength = upper[side].subtract(lower[side]); if (sideLength.compareTo(longestLength) == 1) { longestSide = side; longestLength = sideLength; } } ArrayList<Region> result = new ArrayList<Region>(); BoxRegion region1 = new BoxRegion(this); BoxRegion region2 = new BoxRegion(this); BigRational mid = (lower[longestSide].add(upper[longestSide])).divide(2); region1.upper[longestSide] = mid; region2.lower[longestSide] = mid; result.add(region1); result.add(region2); return result; } /** * Split region in all dimensions. * * @return set of new regions covering same area */ private ArrayList<Region> splitAll() { ArrayList<Region> result = new ArrayList<Region>(); final int numParts = 2; final int numNewRegions = (int) Math.pow(numParts, lower.length); BigRational[] newLower = new BigRational[lower.length]; BigRational[] newUpper = new BigRational[upper.length]; for (int newRegionNr = 0; newRegionNr < numNewRegions; newRegionNr++) { int regionRest = newRegionNr; for (int var = 0; var < lower.length; var++) { int lowerPart = regionRest % numParts; regionRest /= numParts; BigRational partLength = upper[var].subtract(lower[var]).divide(numParts); newLower[var] = lower[var].add(partLength.multiply(lowerPart)); newUpper[var] = lower[var].add(partLength.multiply(lowerPart + 1)); } result.add(new BoxRegion((BoxRegionFactory) factory, newLower, newUpper)); } return result; } @Override ArrayList<Region> split(Function constraint) { // TODO could implement more clever splitting using constraints return split(); } @Override ArrayList<Region> split() { if (((BoxRegionFactory) factory).getSplitMethod() == SPLIT_LONGEST) { return splitLongest(); } else if (((BoxRegionFactory) factory).getSplitMethod() == SPLIT_ALL) { return splitAll(); } else { throw new RuntimeException(); } } @Override ArrayList<Point> specialPoints() { ArrayList<Point> result = new ArrayList<Point>(); int numEdges = (int) Math.pow(2, lower.length); for (int edgeNr = 0; edgeNr < numEdges; edgeNr++) { int regionRest = edgeNr; BigRational[] point = new BigRational[lower.length]; for (int dim = 0; dim < lower.length; dim++) { boolean useLower = ( 0 == (regionRest % 2)); regionRest /= 2; if (useLower) { point[dim] = lower[dim]; } else { point[dim] = upper[dim]; } } result.add(new Point(point)); } return result; } @Override Point randomPoint() { BigRational[] point = new BigRational[lower.length]; BigInteger maxInt = new BigInteger(Long.toString((long) Math.pow(2, 60))); for (int dim = 0; dim < lower.length; dim++) { BigInteger rndInt = new BigInteger(60, random); BigRational rndRat = new BigRational(rndInt, maxInt); rndRat = lower[dim].add(upper[dim].subtract(lower[dim]).multiply(rndRat)); point[dim] = rndRat; } return new Point(point); } @Override BoxRegion conjunct(Region region) { BoxRegion other = (BoxRegion) region; BoxRegion result = new BoxRegion((BoxRegionFactory) factory); for (int dim = 0; dim < lower.length; dim++) { if (this.upper[dim].compareTo(other.lower[dim]) <= 0) { return null; } if (this.lower[dim].compareTo(other.upper[dim]) >= 0) { return null; } BigRational newLower = this.lower[dim].max(other.lower[dim]); BigRational newUpper = this.upper[dim].min(other.upper[dim]); if (newLower.equals(newUpper)) { return null; } result.setDimension(dim, newLower, newUpper); } return result; } /** * Checks whether this region is adjacent to another region in given dimension. * In this case, both can be glued by @{code glue}. * * @param other region to check whether adjacent in given dimension * @param adjDim dimension where to check adjacency * @return true iff regions are adjacent in given dimension */ private boolean adjacent(Region region, int adjDim) { BoxRegion other = (BoxRegion) region; for (int dim = 0; dim < this.getDimensions(); dim++) { if (dim != adjDim) { if (!this.getDimensionLower(dim).equals(other.getDimensionLower(dim))) { return false; } if (!this.getDimensionUpper(dim).equals(other.getDimensionUpper(dim))) { return false; } } } return this.getDimensionUpper(adjDim).equals(other.getDimensionLower(adjDim)); } @Override boolean adjacent(Region region) { BoxRegion other = (BoxRegion) region; for (int dim = 0; dim < getDimensions(); dim++) { if (adjacent(other, dim)) { return true; } } return false; } @Override Region glue(Region region) { BoxRegion other = (BoxRegion) region; BoxRegion result = new BoxRegion((BoxRegionFactory) this.getFactory()); for (int dim = 0; dim < result.getDimensions(); dim++) { result.setDimension(dim, this.getDimensionLower(dim), other.getDimensionUpper(dim)); } return result; } }