text
stringlengths
1
1.04M
language
stringclasses
25 values
Lebanon and Kuwait won’t be playing "Death on the Nile," Deadline has confirmed, and that’s unfortunately due to both countries’ protest of Israeli native star Gal Gadot. Gadot served in the Israeli military for two years prior to becoming a model and actress, as her native country mandates it. Given her connection to the IDF, Lebanon previously blocked the actress’ movie "Wonder Woman" from release in May 2017. At the time, the country was reportedly prompted to do so by the group Campaign to Boycott Supporters of Israel-Lebanon. "Wonder Woman" was also banned in Qatar. "Wonder Woman 1984" was banned in Lebanon as well, however, at the time Kuwait theaters were closed at that point in time during the pandemic. "Death of the Nile" is being released in the rest of the Middle East as of this weekend. No requests were made by Lebanon or Kuwait for any edits to the print. The Daily Mail, which first had the news about "Death on the Nile‘s" ban in Kuwait, cited the local Al-Qabas newspaper saying that country caved into a ban of the Kenneth Branagh directed Agatha Christie adaptation due to protests on social media. The newspaper also quoted a country official source saying that they would not book a movie starring a former soldier in the Zionist occupying army. In May 2021, Gadot disabled Twitter comments over a tweet about the Israel–Hamas rocket attacks conflict. What was meant as a message of unity by the actress, was perceived by critics as propaganda for Israel. Gadot left the post up, which you can read below. Meanwhile, "Death on the Nile" is one of the few U. S. movies to receive a release in China (Feb. 19) after several notable Hollywood movies went undated last year. All notable offshore territories are going day-and-date for the film this weekend with the exception of Spain (Feb 18) and Japan (Feb 25) as well as Hong Kong, Croatia and Hungary. "Death on the Nile" is expected to be No. 1 at the weekend domestic box office with a take in the mid-teens.
english
The twin issues of CAB and NRC kept the first day of the winter session of the Assam Legislative Assembly stormy on Thursday with the opposition parties staging a walkout amid the ruckus. The Congress and All India United Democratic Front (AIUDF) legislators demanded the Speaker Hintendra Nath Goswami to cancel the question hour to discuss on Citizenship (Amendment) Bill and National Register of Citizens. The Speaker, however, refused to cancel the question hour following which the Congress and AIUDF legislators staged a walkout shouting slogans and displaying placards. Reiterating the government’s stand on CAB and NRC, Assam finance minister Himanta Biswa Sarma later told media that the CAB is likely to be passed in the Lok Sabha during the ongoing session of the parliament. He further informed that Assam is also going to be a part of the national NRC, which will be prepared after the CAB. He said union home minister Amit Shah is likely to meet the Chief Ministers of the eight northeastern states, opposition leaders and other organizations on November 29 and 30 to discuss the issue of CAB threadbare. “A meeting has been scheduled with all stakeholders and invitations have already been sent. All the doubts are likely to be cleared during the meeting,” said Sarma. “The whole country is going to have an NRC and Assam will be a part of it,” Sarma added. “The new pan India NRC will be done with one cut off date for the entire country to ensure that those excluded in Assam cannot enrol as citizens in other states and vice versa,” he reiterated. Slamming the opposition, the minister said that while a few opposition leaders have been opposing the national NRC, the All Assam Students’ Union (AASU), Assam Public Work (APW) and other organizations have expressed unhappiness over the present NRC and have sought a review. He also said that the names of a lot of genuine Indian citizens were left out of the NRC. “The present NRC is 100 per cent incorrect. We are going to table in the assembly how former NRC coordinator Prateek Hajela had done financial irregularities,” said the Minister.
english
Manage your notification subscription by clicking on the icon. To Start receiving timely alerts please follow the below steps: Click on the Menu icon of the browser, it opens up a list of options. Click on the “Options ”, it opens up the settings page, Here click on the “Privacy & Security” options listed on the left hand side of the page. Scroll down the page to the “Permission” section . Here click on the “Settings” tab of the Notification option. A pop up will open with all listed sites, select the option “ALLOW“, for the respective site under the status head to allow the notification. Once the changes is done, click on the “Save Changes” option to save the changes. यामी गौतम और अतुल कुलकर्णी के दमदार परफॉमेंस के साथ इस वीकेंड एक अच्छी संस्पेंस- थ्रिलर देखना चाहते हैं, तो 'अ थर्सडे' जरूर देख सकते हैं। Do you want to clear all the notifications from your inbox?
english
<filename>config/artisantools/generated/datapack/data/artisantools/tags/items/type/hammer.json<gh_stars>0 { "replace": false, "values": [ "artisantools:hammer_wood", "artisantools:hammer_stone", "artisantools:hammer_iron", "artisantools:hammer_diamond", "artisantools:hammer_netherite", "artisantools:hammer_flint", "artisantools:hammer_bronze" ] }
json
/* Siesta 2.0.5 Copyright(c) 2009-2013 Bryntum AB http://bryntum.com/contact http://bryntum.com/products/siesta/license */ .icon-delete { background : transparent url(../images/cross.png) no-repeat left center !important; cursor : pointer; height : 10px; width : 10px; background-size : 8px 8px !important; margin : 4px 2px; } .recorder-tool { background : none !important; border : none !important; } .recorder-tool-icon { font-size : 1.1em; color : rgb(7, 89, 133); padding-top : 0.1em; } .recorder-tool-icon:hover { color : #222; } .icon-record { border-radius : 10px; width : 10px !important; height : 10px !important; margin-top : 3px; background : #ff1111; margin-left : 2px; } .icon-record:hover { background : darkred; } .recorder-tool-icon.icon-close { font-size : 0.9em; padding-top : 0.2em; } .cheatsheet { background : #eee; padding : 5px; } .cheatsheet-type { width : 135px; font-weight : bold; margin-top : 5px; } .cheatsheet td { white-space : nowrap; color : #555; } .eventview-offsetcolumn > .x-grid-cell-inner { position : relative; color : #777; } .eventview-clearoffset { position : absolute; width : 11px; height : 11px; right : 4px; top : 0px; cursor : pointer; } .x-grid-row-over .eventview-clearoffset { background : transparent url(../images/bullet_delete.png) no-repeat left center !important; } @keyframes blink { 0% { opacity : 0; } 100% { opacity : 1; } } @-webkit-keyframes blink { 0% { opacity : 0; } 100% { opacity : 1; } } .recorder-recording .icon-record { -webkit-animation : blink 0.5s linear infinite; -moz-animation : blink 0.5s linear infinite; animation : blink 0.5s linear infinite; -webkit-animation-timing-function : cubic-bezier(1.0, 0, 0, 1.0); -webkit-animation-direction : alternate; animation-direction : alternate; } .siesta-recorder-codeeditor .CodeMirror { background-image : url(../images/ok.png); background-repeat : no-repeat; background-position : right top; background-size : 10px 10px; } .siesta-recorder-codeeditor.x-form-invalid .CodeMirror { background-image : url(../images/cross.png); }
css
package org.devgateway.toolkit.forms.wicket.events; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; public class ComponentAjaxUpdateEvent extends AjaxUpdateEvent { private final String componentId; public ComponentAjaxUpdateEvent(final AjaxRequestTarget target, Component component) { super(target); componentId = component.getId(); } public final String getComponentId() { return componentId; } }
java
import os import wget import paddle from .tokenizer import Tokenizer from .model import CLIP from paddle.vision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize tokenizer = Tokenizer() def get_transforms(image_resolution): transforms = Compose([ Resize(image_resolution, interpolation='bicubic'), CenterCrop(image_resolution), lambda image: image.convert("RGB"), ToTensor(), Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), ]) return transforms def clip_rn50(): model = CLIP( embed_dim=1024, image_resolution=224, vision_layers=(3, 4, 6, 3), vision_width=64, vision_patch_size=None, context_length=77, vocab_size=49408, transformer_width=512, transformer_heads=8, transformer_layers=12 ) return model, get_transforms(224) def clip_rn101(): model = CLIP( embed_dim=512, image_resolution=224, vision_layers=(3, 4, 23, 3), vision_width=64, vision_patch_size=None, context_length=77, vocab_size=49408, transformer_width=512, transformer_heads=8, transformer_layers=12 ) return model, get_transforms(224) def clip_rn50x4(): model = CLIP( embed_dim=640, image_resolution=288, vision_layers=(4, 6, 10, 6), vision_width=80, vision_patch_size=None, context_length=77, vocab_size=49408, transformer_width=640, transformer_heads=10, transformer_layers=12 ) return model, get_transforms(288) def clip_vit_b_32(): model = CLIP( embed_dim=512, image_resolution=224, vision_layers=12, vision_width=768, vision_patch_size=32, context_length=77, vocab_size=49408, transformer_width=512, transformer_heads=8, transformer_layers=12 ) return model, get_transforms(224) def tokenize(texts, context_length=77): """ Returns the tokenized representation of given input string(s) Parameters ---------- texts : Union[str, List[str]] An input string or a list of input strings to tokenize context_length : int The context length to use; all CLIP models use 77 as the context length Returns ------- A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] """ if isinstance(texts, str): texts = [texts] sot_token = tokenizer.encoder["<|startoftext|>"] eot_token = tokenizer.encoder["<|endoftext|>"] all_tokens = [[sot_token] + tokenizer.encode(text) + [eot_token] for text in texts] result = paddle.zeros((len(all_tokens), context_length), dtype='int64') for i, tokens in enumerate(all_tokens): if len(tokens) > context_length: raise RuntimeError( f"Input {texts[i]} is too long for context length {context_length}") result[i, :len(tokens)] = paddle.to_tensor(tokens) return result model_dict = { 'RN50': [clip_rn50, r'https://bj.bcebos.com/v1/ai-studio-online/6ffc89246e974a809e6e4b40fdb58063a112a0153e674dae8ed5b6dfe5d46d86?responseContentDisposition=attachment%3B%20filename%3DRN50.pdparams', 'RN50.pdparams'], 'RN50x4': [clip_rn50x4, r'https://bj.bcebos.com/v1/ai-studio-online/9f874e0174da48ffbd7c17e77b1fb278632620a9995e476ba873e334caec9037?responseContentDisposition=attachment%3B%20filename%3DRN50x4.pdparams', 'RN50x4.pdparams'], 'RN101': [clip_rn101, r'https://bj.bcebos.com/v1/ai-studio-online/484592d98c584785bc8f6f9f7badbf4a9fb7a96f6102470697ed974e8eeee2a9?responseContentDisposition=attachment%3B%20filename%3DRN101.pdparams', 'RN101.pdparams'], 'ViT_B_32': [clip_vit_b_32, r'https://bj.bcebos.com/v1/ai-studio-online/eb5e4dbf1ec142caa003a27cefd510ef46a8a6c3932a4d60bfecb3f3ab746c02?responseContentDisposition=attachment%3B%20filename%3DViT-B-32.pdparams', 'ViT-B-32.pdparams'] } def load_model(model_name, pretrained=False): model_fn, url, file_name = model_dict[model_name] model, transforms = model_fn() if pretrained: model_path = os.path.join('pretrained_models', file_name) if not os.path.isfile(model_path): if not os.path.exists('pretrained_models'): os.mkdir('pretrained_models') wget.download(url, out=model_path) params = paddle.load(model_path) model.set_dict(params) model.eval() return model, transforms
python
import { Message } from '@source-health/client' export interface ThreadState { threadId: string | null isLoading: boolean hasMoreMessages: boolean messages: Message[] } interface InitializeThreadAction { type: 'initializeThread' id: string } interface InitializeThreadSuccessAction { type: 'initializeThreadSuccess' messages: Message[] hasMore: boolean } interface LoadMoreMessagesAction { type: 'loadMoreMessages' } interface LoadMoreMessagesSuccessAction { type: 'loadMoreMessagesSuccess' messages: Message[] hasMore: boolean } interface SendMessageAction { type: 'sendMessage' message: Message } interface SendMessageSuccessAction { type: 'sendMessageSuccess' temporaryMessage: Message message: Message } interface SendMessageFailureAction { type: 'sendMessageFailure' temporaryMessage: Message } export type ThreadActions = | InitializeThreadAction | InitializeThreadSuccessAction | LoadMoreMessagesAction | LoadMoreMessagesSuccessAction | SendMessageAction | SendMessageSuccessAction | SendMessageFailureAction export function threadReducer(state: ThreadState, action: ThreadActions): ThreadState { switch (action.type) { case 'initializeThread': return { ...state, isLoading: true, threadId: action.id, } case 'initializeThreadSuccess': return { ...state, isLoading: false, messages: action.messages, hasMoreMessages: action.hasMore, } case 'loadMoreMessages': return { ...state, isLoading: true, } case 'loadMoreMessagesSuccess': return { ...state, isLoading: false, messages: [...action.messages, ...state.messages], hasMoreMessages: action.hasMore, } case 'sendMessage': return { ...state, messages: [...state.messages, action.message], } case 'sendMessageSuccess': return { ...state, messages: [ ...state.messages.filter((temp) => temp.id !== action.temporaryMessage.id), action.message, ], } case 'sendMessageFailure': return { ...state, messages: state.messages.map((message) => message.id !== action.temporaryMessage.id ? message : { ...message, }, ), } } } export const threadInitialState: ThreadState = { threadId: null, isLoading: false, hasMoreMessages: false, messages: [], }
typescript
<gh_stars>0 { "date": "2019-03", "title": "You say Potato, I say Po-Data: Physical Template Tools for Authoring Visualizations", "authors": [ "<NAME>", "<NAME>", "<NAME>", "<NAME>" ], "series": "TEI 2019", "doi": "https://doi.org/10.1145/3294109.3295627", "keywords": "potato, tangible tools, authoring visualizations, block-printing, physical template tools, information visualization", "pages": 10, "talk": "https://www.youtube.com/watch?v=ZS7lU60xChI", "abstract": "Providing data visualization authoring tools for the general public remains an ongoing challenge. Inspired by block-printing, we explore how visualization stamps as a physical visualization authoring tool could leverage both visual freedom and ease of repetition. We conducted a workshop with two groups---visualization experts and non-experts---where participants authored visualizations on paper using hand-carved stamps made from potatoes and sponges. The low-fidelity medium freed participants to test new stamp patterns and accept mistakes. From the created visualizations, we observed several unique traits and uses of block-printing tools for visualization authoring, including: modularity of patterns, annotation guides, creation of multiple patterns from one stamp, and various techniques to apply data onto paper. We discuss the issues around expressivity and effectiveness of block-printed stamps in visualization authoring, and identify implications for the design and assembly of primitives in potential visualization stamp kits, as well as applications for future use in non-digital environments.", "dir": "content/output/publications", "base": "tei-2019-wun.json", "ext": ".json", "sourceBase": "tei-2019-wun.yaml", "sourceExt": ".yaml" }
json
# Copyright (c) 2019-2020, <NAME> # License: MIT-License import math import re from typing import TYPE_CHECKING, List, Sequence, Iterable from typing import Tuple, Optional from xml.etree import ElementTree from ezdxf.lldxf import validator from ezdxf.lldxf.attributes import ( DXFAttributes, DefSubclass, DXFAttr, XType, RETURN_DEFAULT, ) from ezdxf.lldxf.const import ( SUBCLASS_MARKER, DXFStructureError, DXF2010, DXFTypeError, DXFValueError, InvalidGeoDataException, ) from ezdxf.lldxf.packedtags import VertexArray from ezdxf.lldxf.tags import Tags, DXFTag from ezdxf.math import NULLVEC, Z_AXIS, Y_AXIS, Vertex, Vec3, Vec2 from .dxfentity import base_class, SubclassProcessor from .dxfobj import DXFObject from .factory import register_entity from .mtext import split_mtext_string from .. import units from ..math import Matrix44 if TYPE_CHECKING: from ezdxf.eztypes import TagWriter, DXFNamespace __all__ = ['GeoData', 'MeshVertices'] acdb_geo_data = DefSubclass('AcDbGeoData', { # 1 = R2009, but this release has no DXF version, # 2 = R2010 'version': DXFAttr(90, default=2), # Handle to host block table record 'block_record_handle': DXFAttr(330, default='0'), # 0 = unknown # 1 = local grid # 2 = projected grid # 3 = geographic (latitude/longitude) 'coordinate_type': DXFAttr( 70, default=3, validator=validator.is_in_integer_range(0, 4), fixer=RETURN_DEFAULT, ), # Design point, reference point in WCS coordinates: 'design_point': DXFAttr(10, xtype=XType.point3d, default=NULLVEC), # Reference point in coordinate system coordinates, valid only when # coordinate type is Local Grid: 'reference_point': DXFAttr(11, xtype=XType.point3d, default=NULLVEC), # Horizontal unit scale, factor which converts horizontal design coordinates # to meters by multiplication: 'horizontal_unit_scale': DXFAttr( 40, default=1, validator=validator.is_not_zero, fixer=RETURN_DEFAULT, ), # Horizontal units per UnitsValue enumeration. Will be kUnitsUndefined if # units specified by horizontal unit scale is not supported by AutoCAD # enumeration: 'horizontal_units': DXFAttr(91, default=1), # Vertical unit scale, factor which converts vertical design coordinates # to meters by multiplication: 'vertical_unit_scale': DXFAttr(41, default=1), # Vertical units per UnitsValue enumeration. Will be kUnitsUndefined if # units specified by vertical unit scale is not supported by AutoCAD # enumeration: 'vertical_units': DXFAttr(92, default=1), 'up_direction': DXFAttr( 210, xtype=XType.point3d, default=Z_AXIS, validator=validator.is_not_null_vector, fixer=RETURN_DEFAULT, ), # North direction vector (2D) 'north_direction': DXFAttr( 12, xtype=XType.point2d, default=Y_AXIS, validator=validator.is_not_null_vector, fixer=RETURN_DEFAULT, ), # Scale estimation methods: # 1 = None # 2 = User specified scale factor; # 3 = Grid scale at reference point; # 4 = Prismoidal 'scale_estimation_method': DXFAttr( 95, default=1, validator=validator.is_in_integer_range(0, 5), fixer=RETURN_DEFAULT, ), 'user_scale_factor': DXFAttr( 141, default=1, validator=validator.is_not_zero, fixer=RETURN_DEFAULT, ), # Bool flag specifying whether to do sea level correction: 'sea_level_correction': DXFAttr( 294, default=0, validator=validator.is_integer_bool, fixer=RETURN_DEFAULT, ), 'sea_level_elevation': DXFAttr(142, default=0), 'coordinate_projection_radius': DXFAttr(143, default=0), # 303, 303, ..., 301: Coordinate system definition string 'geo_rss_tag': DXFAttr(302, default='', optional=True), 'observation_from_tag': DXFAttr(305, default='', optional=True), 'observation_to_tag': DXFAttr(306, default='', optional=True), 'observation_coverage_tag': DXFAttr(307, default='', optional=True), # 93: Number of Geo-Mesh points # mesh definition: # source mesh point (13, 23) repeat, mesh_point_count? # target mesh point (14, 24) repeat, mesh_point_count? # 96: # Number of faces # face index 97 repeat, faces_count # face index 98 repeat, faces_count # face index 99 repeat, faces_count }) EPSG_3395 = """<?xml version="1.0" encoding="UTF-16" standalone="no" ?> <Dictionary version="1.0" xmlns="http://www.osgeo.org/mapguide/coordinatesystem"> <ProjectedCoordinateSystem id="WORLD-MERCATOR"> <Name>WORLD-MERCATOR</Name> <AdditionalInformation> <ParameterItem type="CsMap"> <Key>CSQuadrantSimplified</Key> <IntegerValue>1</IntegerValue> </ParameterItem> </AdditionalInformation> <DomainOfValidity> <Extent> <GeographicElement> <GeographicBoundingBox> <WestBoundLongitude>-180.75</WestBoundLongitude> <EastBoundLongitude>180.75</EastBoundLongitude> <SouthBoundLatitude>-80.75</SouthBoundLatitude> <NorthBoundLatitude>84.75</NorthBoundLatitude> </GeographicBoundingBox> </GeographicElement> </Extent> </DomainOfValidity> <DatumId>WGS84</DatumId> <Axis uom="Meter"> <CoordinateSystemAxis> <AxisOrder>1</AxisOrder> <AxisName>Easting</AxisName> <AxisAbbreviation>E</AxisAbbreviation> <AxisDirection>East</AxisDirection> </CoordinateSystemAxis> <CoordinateSystemAxis> <AxisOrder>2</AxisOrder> <AxisName>Northing</AxisName> <AxisAbbreviation>N</AxisAbbreviation> <AxisDirection>North</AxisDirection> </CoordinateSystemAxis> </Axis> <Conversion> <Projection> <OperationMethodId>Mercator (variant B)</OperationMethodId> <ParameterValue><OperationParameterId>Longitude of natural origin</OperationParameterId><Value uom="degree">0</Value></ParameterValue> <ParameterValue><OperationParameterId>Standard Parallel</OperationParameterId><Value uom="degree">0</Value></ParameterValue> <ParameterValue><OperationParameterId>Scaling factor for coord differences</OperationParameterId><Value uom="unity">1</Value></ParameterValue> <ParameterValue><OperationParameterId>False easting</OperationParameterId><Value uom="Meter">0</Value></ParameterValue> <ParameterValue><OperationParameterId>False northing</OperationParameterId><Value uom="Meter">0</Value></ParameterValue> </Projection> </Conversion> </ProjectedCoordinateSystem> <Alias id="3395" type="CoordinateSystem"> <ObjectId>WORLD-MERCATOR</ObjectId> <Namespace>EPSG Code</Namespace> </Alias> <GeodeticDatum id="WGS84"> <Name>WGS84</Name> <PrimeMeridianId>Greenwich</PrimeMeridianId> <EllipsoidId>WGS84</EllipsoidId> </GeodeticDatum> <Alias id="6326" type="Datum"> <ObjectId>WGS84</ObjectId> <Namespace>EPSG Code</Namespace> </Alias> <Ellipsoid id="WGS84"> <Name>WGS84</Name> <SemiMajorAxis uom="meter">6.37814e+06</SemiMajorAxis> <SecondDefiningParameter> <SemiMinorAxis uom="meter">6.35675e+06</SemiMinorAxis> </SecondDefiningParameter> </Ellipsoid> <Alias id="7030" type="Ellipsoid"> <ObjectId>WGS84</ObjectId> <Namespace>EPSG Code</Namespace> </Alias> </Dictionary> """ class MeshVertices(VertexArray): VERTEX_SIZE = 2 @register_entity class GeoData(DXFObject): """ DXF GEODATA entity """ DXFTYPE = 'GEODATA' DXFATTRIBS = DXFAttributes(base_class, acdb_geo_data) MIN_DXF_VERSION_FOR_EXPORT = DXF2010 # coordinate_type const UNKNOWN = 0 LOCAL_GRID = 1 PROJECTED_GRID = 2 GEOGRAPHIC = 3 # scale_estimation_method const NONE = 1 USER_SCALE = 2 GRID_SCALE = 3 PRISMOIDEAL = 4 def __init__(self): super().__init__() self.source_vertices = MeshVertices() self.target_vertices = MeshVertices() self.faces: List[Sequence[int]] = [] self.coordinate_system_definition = "" def copy(self): raise DXFTypeError(f'Cloning of {self.DXFTYPE} not supported.') def load_dxf_attribs( self, processor: SubclassProcessor = None) -> 'DXFNamespace': dxf = super().load_dxf_attribs(processor) if processor: tags = processor.load_dxfattribs_into_namespace(dxf, acdb_geo_data) tags = self.load_coordinate_system_definition(tags) self.load_mesh_data(tags) return dxf def load_coordinate_system_definition(self, tags: Tags) -> Iterable[DXFTag]: # 303, 303, 301, Coordinate system definition string, always XML? lines = [] for tag in tags: if tag.code in (301, 303): lines.append(tag.value.replace('^J', '\n')) else: yield tag if len(lines): self.coordinate_system_definition = ''.join(lines) def load_mesh_data(self, tags: Iterable[DXFTag]): face = [] for tag in tags: code, value = tag if code == 13: self.source_vertices.append(value) elif code == 14: self.target_vertices.append(value) elif code in {97, 98, 99}: if code == 97 and len(face): if len(face) != 3: raise DXFStructureError( f"GEODATA face definition error: invalid index " f"count {len(face)}.") self.faces.append(tuple(face)) face = [] face.append(value) if len(face): # collect last face self.faces.append(tuple(face)) if len(self.source_vertices) != len(self.target_vertices): raise DXFStructureError( "GEODATA mesh definition error: source and target point count " "does not match.") def export_entity(self, tagwriter: 'TagWriter') -> None: """ Export entity specific data as DXF tags. """ super().export_entity(tagwriter) tagwriter.write_tag2(SUBCLASS_MARKER, acdb_geo_data.name) self.dxf.export_dxf_attribs(tagwriter, [ 'version', 'block_record_handle', 'coordinate_type', 'design_point', 'reference_point', 'horizontal_unit_scale', 'horizontal_units', 'vertical_unit_scale', 'vertical_units', 'up_direction', 'north_direction', 'scale_estimation_method', 'user_scale_factor', 'sea_level_correction', 'sea_level_elevation', 'coordinate_projection_radius' ]) self.export_coordinate_system_definition(tagwriter) self.dxf.export_dxf_attribs(tagwriter, [ 'geo_rss_tag', 'observation_from_tag', 'observation_to_tag', 'observation_coverage_tag' ]) self.export_mesh_data(tagwriter) def export_mesh_data(self, tagwriter: 'TagWriter'): if len(self.source_vertices) != len(self.target_vertices): raise DXFTypeError( "GEODATA mesh definition error: source and target point count " "does not match." ) tagwriter.write_tag2(93, len(self.source_vertices)) for s, t in zip(self.source_vertices, self.target_vertices): tagwriter.write_vertex(13, s) tagwriter.write_vertex(14, t) tagwriter.write_tag2(96, len(self.faces)) for face in self.faces: if len(face) != 3: raise DXFTypeError( f"GEODATA face definition error: invalid index " f"count {len(face)}.") f1, f2, f3 = face tagwriter.write_tag2(97, f1) tagwriter.write_tag2(98, f2) tagwriter.write_tag2(99, f3) def export_coordinate_system_definition(self, tagwriter: 'TagWriter'): text = self.coordinate_system_definition.replace('\n', '^J') chunks = split_mtext_string(text, size=255) if len(chunks) == 0: chunks.append("") while len(chunks) > 1: tagwriter.write_tag2(303, chunks.pop(0)) tagwriter.write_tag2(301, chunks[0]) def decoded_units(self) -> Tuple[Optional[str], Optional[str]]: return units.decode(self.dxf.horizontal_units), \ units.decode(self.dxf.vertical_units) def get_crs(self) -> Tuple[int, bool]: """ Returns the EPSG index and axis-ordering, axis-ordering is ``True`` if fist axis is labeled "E" or "W" and ``False`` if first axis is labeled "N" or "S". If axis-ordering is ``False`` the CRS is not compatible with the ``__geo_interface__`` or GeoJSON (see chapter 3.1.1). Raises: InvalidGeoDataException: for invalid or unknown XML data The EPSG number is stored in a tag like: .. code:: <Alias id="27700" type="CoordinateSystem"> <ObjectId>OSGB1936.NationalGrid</ObjectId> <Namespace>EPSG Code</Namespace> </Alias> The axis-ordering is stored in a tag like: .. code:: <Axis uom="METER"> <CoordinateSystemAxis> <AxisOrder>1</AxisOrder> <AxisName>Easting</AxisName> <AxisAbbreviation>E</AxisAbbreviation> <AxisDirection>east</AxisDirection> </CoordinateSystemAxis> <CoordinateSystemAxis> <AxisOrder>2</AxisOrder> <AxisName>Northing</AxisName> <AxisAbbreviation>N</AxisAbbreviation> <AxisDirection>north</AxisDirection> </CoordinateSystemAxis> </Axis> """ definition = self.coordinate_system_definition try: # Remove namespaces so that tags can be searched without prefixing # their namespace: definition = _remove_xml_namespaces(definition) root = ElementTree.fromstring(definition) except ElementTree.ParseError: raise InvalidGeoDataException( 'failed to parse coordinate_system_definition as xml') crs = None for alias in root.findall('Alias'): if alias.get('type') == 'CoordinateSystem' and \ alias.find('Namespace').text == 'EPSG Code': try: crs = int(alias.get('id')) except ValueError: raise InvalidGeoDataException( f'invalid epsg number: {alias.get("id")}') break xy_ordering = None for axis in root.findall('.//CoordinateSystemAxis'): if axis.find('AxisOrder').text == '1': first_axis = axis.find('AxisAbbreviation').text if first_axis in ('E', 'W'): xy_ordering = True elif first_axis in ('N', 'S'): xy_ordering = False else: raise InvalidGeoDataException( f'unknown first axis: {first_axis}') break if crs is None: raise InvalidGeoDataException('no EPSG code associated with CRS') elif xy_ordering is None: raise InvalidGeoDataException('could not determine axis ordering') else: return crs, xy_ordering def get_crs_transformation( self, *, no_checks: bool = False) -> Tuple[Matrix44, int]: """ Returns the transformation matrix and the EPSG index to transform WCS coordinates into CRS coordinates. Because of the lack of proper documentation this method works only for tested configurations, set argument `no_checks` to ``True`` to use the method for untested geodata configurations, but the results may be incorrect. Supports only "Local Grid" transformation! Raises: InvalidGeoDataException: for untested geodata configurations """ epsg, xy_ordering = self.get_crs() if not no_checks: if (self.dxf.coordinate_type != GeoData.LOCAL_GRID or self.dxf.scale_estimation_method != GeoData.NONE or not math.isclose(self.dxf.user_scale_factor, 1.0) or self.dxf.sea_level_correction != 0 or not math.isclose(self.dxf.sea_level_elevation, 0) or self.faces or not self.dxf.up_direction.isclose((0, 0, 1)) or self.dxf.observation_coverage_tag != '' or self.dxf.observation_from_tag != '' or self.dxf.observation_to_tag != '' or not xy_ordering): raise InvalidGeoDataException( f'Untested geodata configuration: ' f'{self.dxf.all_existing_dxf_attribs()}.\n' f'You can try with no_checks=True but the ' f'results may be incorrect.' ) source = self.dxf.design_point # in CAD WCS coordinates target = self.dxf.reference_point # in the CRS of the geodata north = self.dxf.north_direction # -pi/2 because north is at pi/2 so if the given north is at pi/2, no # rotation is necessary: theta = -(math.atan2(north.y, north.x) - math.pi / 2) transformation = ( Matrix44.translate(-source.x, -source.y, 0) @ Matrix44.scale(self.dxf.horizontal_unit_scale, self.dxf.vertical_unit_scale, 1) @ Matrix44.z_rotate(theta) @ Matrix44.translate(target.x, target.y, 0)) return transformation, epsg def setup_local_grid(self, *, design_point: Vertex, reference_point: Vertex, north_direction: Vertex = (0, 1), crs: str = EPSG_3395, ) -> None: """ Setup local grid coordinate system. This method is designed to setup CRS similar to `EPSG:3395 World Mercator`, the basic features of the CRS should fulfill this assumptions: - base unit of reference coordinates is 1 meter - right-handed coordinate system: +Y=north/+X=east/+Z=up The CRS string is not validated nor interpreted! .. hint:: The reference point must be a 2D cartesian map coordinate and not a globe (lon/lat) coordinate like stored in GeoJSON or GPS data. Args: design_point: WCS coordinates of the CRS reference point reference_point: CRS reference point in 2D cartesian coordinates north_direction: north direction a 2D vertex, default is (0, 1) crs: Coordinate Reference System definition XML string, default is the definition string for `EPSG:3395 World Mercator` """ doc = self.doc if doc is None: raise DXFValueError('Valid DXF document required.') wcs_units = doc.units if units == 0: raise DXFValueError('DXF document requires units to be set, ' 'current state is "unitless".') meter_factor = units.METER_FACTOR[wcs_units] if meter_factor is None: raise DXFValueError(f'Unsupported document units: {wcs_units}') unit_factor = 1.0 / meter_factor # Default settings: self.dxf.up_direction = Z_AXIS self.dxf.observation_coverage_tag = '' self.dxf.observation_from_tag = '' self.dxf.observation_to_tag = '' self.dxf.scale_estimation_method = GeoData.NONE self.dxf.coordinate_type = GeoData.LOCAL_GRID self.dxf.sea_level_correction = 0 self.dxf.horizontal_units = wcs_units # Factor from WCS -> CRS (m) e.g. 0.01 for horizontal_units==5 (cm), # 1cm = 0.01m self.dxf.horizontal_unit_scale = unit_factor self.dxf.vertical_units = wcs_units self.dxf.vertical_unit_scale = unit_factor # User settings: self.dxf.design_point = Vec3(design_point) self.dxf.reference_point = Vec3(reference_point) self.dxf.north_direction = Vec2(north_direction) self.coordinate_system_definition = str(crs) def _remove_xml_namespaces(xml_string: str) -> str: return re.sub('xmlns=\"[^\"]*\"', '', xml_string)
python
{ "schema_version": "1.2.0", "id": "GHSA-wqjr-3h8v-rgjg", "modified": "2022-05-13T01:49:17Z", "published": "2022-05-13T01:49:17Z", "aliases": [ "CVE-2018-11509" ], "details": "ASUSTOR ADM 3.1.0.RFQ3 uses the same default root:admin username and password as it does for the NAS itself for applications that are installed from the online repository. This may allow an attacker to login and upload a webshell.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-11509" }, { "type": "WEB", "url": "https://www.exploit-db.com/exploits/45200/" }, { "type": "WEB", "url": "http://packetstormsecurity.com/files/148919/ASUSTOR-NAS-ADM-3.1.0-Remote-Command-Execution-SQL-Injection.html" } ], "database_specific": { "cwe_ids": [ "CWE-798" ], "severity": "CRITICAL", "github_reviewed": false } }
json
<gh_stars>0 { "Live": { "AbandonedCartSummary": "%1$s%2$s verlassene Warenkörbe%3$s und %4$s verlassene Produkte %5$sim Gesamtwert von %6$s%7$s.", "AveragePageGenerationTime": "Jede Seite benötigte im Durchschnitt %1$s um bei diesem Besucher zu laden.", "CalculatedOverNPageViews": "Berechnet mithilfe der letzten %1$s Seitenansichten dieses Besuchers.", "ClickToViewMoreAboutVisit": "Klicken Sie um nähere Informationen zu diesem Besuch zu sehen", "ConvertedNGoals": "%s Ziele konvertiert", "EcommerceSummaryConversions": "%1$s%2$s Bestellungen für insgesamt %3$s%4$s, bestellte %5$s Produkte.", "FirstVisit": "Erster Besuch", "GoalType": "Typ", "HideMap": "Karte ausblenden", "KeywordRankedOnSearchResultForThisVisitor": "Der Begriff %1$s war für diesen Besucher auf Platz %2$s der Suchergebnisseite von %3$s", "LastHours": "Letzte %s Stunden", "LastMinutes": "Letzte %s Minuten", "LastVisit": "Letzter Besuch", "LinkVisitorLog": "detailiertes Besucher-Log anzeigen", "LoadMoreVisits": "Mehr Besuche laden", "MorePagesNotDisplayed": "weitere Seiten von diesem Besucher werden nicht angezeigt", "NbVisitor": "1 Besucher", "NbVisitors": "%s Besucher", "NextVisitor": "Nächster Besucher", "NoMoreVisits": "Für diesen Besucher sind keine weiteren Besuche vorhanden.", "PageRefreshed": "Die Anzahl wie oft diese Seite hintereinander angeschaut\/aktualisiert worden ist.", "PluginDescription": "Unterstützt den Live Besucher-Log und lässt Sie Ihre Besucher live im Echtzeit-Dashboard-Widget anzeigen. Das Plugin lässt Sie auch ein Besucherprofil für einen vorgegebenen Benutzer anzeigen.", "PreviousVisitor": "Vorheriger Besucher", "RealTimeVisitorCount": "Echtzeit-Besucherzähler", "Referrer_URL": "Herkunftsseite", "RowActionTooltipDefault": "Zeige Besucher-Log aufgeteilt durch diese Zeile", "RowActionTooltipTitle": "Log segmentierter Besucher öffnen", "RowActionTooltipWithDimension": "Zeige Besucher-Log segmentiert durch %s", "SegmentedVisitorLogTitle": "Besucher-Log zeigt Besuche bei denen gilt: %s ist \\\"%s\\\"", "ShowMap": "Karte einblenden", "SimpleRealTimeWidget_Message": "%s und %s in den letzten %s.", "ViewVisitorProfile": "Besucherprofil ansehen", "VisitedPages": "Besuchte Seiten", "VisitorLog": "Besucher-Log", "VisitorLogDocumentation": "Diese Tabelle zeigt die letzten Besuche innerhalb der ausgewählten Periode. Sie können sehen, wann der Besucher die Seite zuletzt besucht hat, wenn Sie die Maus über das Datum eines Besuches bewegen. %s Wenn die gewählte Periode den heutigen Tag enthält, können Sie die Besuche in Echtzeit sehen! %s Die angezeigten Daten sind immer live, egal ob und in welchem Intervall Sie den Archivierungs-Cronjob verwenden.", "VisitorProfile": "Besucherprofil", "VisitorsInRealTime": "Besucher in Echtzeit", "VisitorsLastVisit": "Der letzte Besuch dieses Besuchers war vor %s Tagen.", "VisitsFrom": "%1$s%2$s Besuche%3$s aus", "VisitSummary": "Verbrachte insgesamt %1$s%2$s auf der Webseite%3$s, und %4$sgezeigten %5$s Seiten in %6$s Besuchen.%7$s" } }
json
// // Model main game stage // function GameStage() { var self = this; // Inter-state transition handling this.transitionLinks = { EndGame : null }; this.setTransition = function(id, target) { self.transitionLinks[id] = target; } // Main game-state specific variables this.background = null; this.gamestate = { started : false, speed : 1, size : 1 }; this.startTimer = 5; this.players = []; this.powerupTypes = []; // Pickup TYPES this.powerupArray = []; // Pickup INSTANCES this.pickup_timer = 0; // Number of seconds between pickups appearing this.showStats = true; // End of game state this.gameWinner = null; // "Internal" state functions this.drawScene = function() { if (self.gamestate.started) { // Draw background if (self.background) { self.background.draw(system.canvas); } // Draw drawObjects(system.context, self.gamestate, self.players); drawObjects(system.context, self.gamestate, self.powerupArray); } else { // Draw UI drawHUD(system.context, self.startTimer); } if (self.showStats) { document.getElementById("actualTime").innerHTML = "Seconds elapsed = " + system.gameClock.actualTimeElapsed().toFixed(2) + " s"; document.getElementById("timeDelta").innerHTML = "Time Delta = " + Math.round(system.gameClock.deltaTime).toFixed() + " ms"; document.getElementById("fps").innerHTML = "FPS = " + system.gameClock.frameCounter.getAverageFPS().toFixed(); document.getElementById("spf").innerHTML = "SPF = " + (system.gameClock.frameCounter.getAverageSPF() * 1000.0).toFixed() + " ms"; } } // Data passed from previous stage (or main app if first stage of entry) that is relevant for initialisation this.initPacket = null; // Initialise stage with data passed from previous stage or web app initialisation. Data passed in via initPacket - this is because // the stage model is based on the idea that the host browser calls each stage function directly. This is not necessary however - if we called // stages directly, when each function exists, we'd unravel the stack call hierarchy anyway and a subsequent frame callback will be // directly to the correct stage function. this.init = function(obj) { // Load background self.background = new Background('black'); // Setup players for (var i = 0; i < playerArray.length; i++) { var playerinfo = playerArray[i]; self.players.push(new Player( { pid : "Player " + (i + 1), x : spawns[i].x, y : spawns[i].y, spriteURI : 'Assets/Images/Avatars/avatar' + (i + 2) + '.png', world : system.engine.world, mass : 20, boundingVolumeScale : 0.75, collisionGroup : -1, leftKey : playerinfo.left, rightKey : playerinfo.right, color : colors[i], preUpdate : function(player, deltaTime, env) { updatePlayer(player, deltaTime, env); }, postUpdate : function() {} })); } // Powerups self.powerupTypes['fast'] = new PickupType( { spriteURI : 'Assets/Images/Powerups/fast.png', collisionGroup : 0, handler : function(collector) { self.gamestate.speed *= 2; } } ); self.powerupTypes['slow'] = new PickupType( { spriteURI : 'Assets/Images/Powerups/slow.png', collisionGroup : 0, handler : function(collector) { self.gamestate.speed /= 2; } } ); self.powerupTypes['thick'] = new PickupType( { spriteURI : 'Assets/Images/Powerups/thick.png', collisionGroup : 0, handler : function(collector) { self.gamestate.size *= 2; } } ); self.powerupTypes['thin'] = new PickupType( { spriteURI : 'Assets/Images/Powerups/thin.png', collisionGroup : 0, handler : function(collector) { self.gamestate.size /= 2; } } ); self.pickup_timer = pickup_time_delay; // Setup gravity configuration for this stage system.engine.world.gravity.y = 0; // Register on-collision event Matter.Events.on(system.engine, 'collisionStart', function(event) { let pairs = event.pairs; for (var i=0; i<pairs.length; ++i) { if (pairs[i].bodyA.hostObject !== undefined && pairs[i].bodyB.hostObject !== undefined) { pairs[i].bodyA.hostObject.doCollision(pairs[i].bodyB.hostObject, { gamestate : self.gamestate, started : self.gamestate.started, players : self.players, powerupTypes : self.powerupTypes, powerupArray : self.powerupArray } ); } } }); // Register pre-update call (handle app-specific stuff) Matter.Events.on(system.engine, 'beforeUpdate', function(event) { var world = event.source.world; for (var i=0; i < world.bodies.length; ++i) { if (world.bodies[i].hostObject !== undefined && world.bodies[i].hostObject.preUpdate !== undefined) { world.bodies[i].hostObject.preUpdate(world.bodies[i].hostObject, system.gameClock.deltaTime, { gamestate : self.gamestate, started : self.gamestate.started, players : self.players, powerupTypes : self.powerupTypes, powerupArray : self.powerupArray } ); } }; }); // Register post-update call (handle app-specific stuff) Matter.Events.on(system.engine, 'afterUpdate', function(event) { var world = event.source.world; for (var i=0; i < world.bodies.length; ++i) { if (world.bodies[i].hostObject !== undefined && world.bodies[i].hostObject.postUpdate !== undefined) { world.bodies[i].hostObject.postUpdate(world.bodies[i].hostObject, system.gameClock.deltaTime, { gamestate : self.gamestate, started : self.gamestate.started, players : self.players, powerupTypes : self.powerupTypes, powerupArray : self.powerupArray } ); } }; }); console.log("init done"); // Setup done - go to phase-in stage window.requestAnimationFrame(self.phaseInLoop); } // Once initialisation has complete, enter phase-in loop (perform initial animation for example) this.phaseInLoop = function() { console.log("phase-in"); var phaseIn = false; if (phaseIn) { window.requestAnimationFrame(self.phaseInLoop); } else { // Phase-in complete - enter main loop window.requestAnimationFrame(self.mainLoop); } } // Once phase-in stage has finished, enter the main loop (perform main stage operations here) this.mainLoop = function() { // Update system clock system.gameClock.tick(); if (!self.gamestate.started) { self.startTimer -= system.gameClock.deltaTime / 1000; if (self.startTimer <= 0) self.gamestate.started = true; } // Update main physics engine state Matter.Engine.update(system.engine, system.gameClock.deltaTime); // Manage pickups let pickupStatus = processPickups(self.powerupTypes, system.engine, self.pickup_timer, system.gameClock.convertTimeIntervalToSeconds(system.gameClock.deltaTime)); self.pickup_timer = pickupStatus.timer; if (pickupStatus.newPickup) { Matter.World.add(system.engine.world, [pickupStatus.newPickup.mBody]); self.powerupArray.push(pickupStatus.newPickup); } // Render latest frame self.drawScene(); // Check for end-of-game state // TODO // Repeat gameloop, or start phase-out if end of game condition(s) met var alive = 0; for (var i = 0; i < self.players.length; i++) { if (!self.players[i].dead) alive++; } if (alive > 1) { window.requestAnimationFrame(self.mainLoop); } else { // Conditions arise to exit stage - leave mainLoop and enter initPhaseOut for (var i = 0; i < self.players.length; i++) { if (!self.players[i].dead) window.alert(self.players[i].pid + " won."); } window.requestAnimationFrame(self.initPhaseOut); } } this.initPhaseOut = function() { console.log("init phaseOut"); //console.log(self.gameWinner.pid + " Wins!!!"); window.requestAnimationFrame(self.phaseOutLoop); } // When transitioning to another stage, first perform any phase-out operations / animation this.phaseOutLoop = function() { console.log("phase out"); /* if (true) { window.requestAnimationFrame(phaseOutLoop); } else { // Phase-out loop complete - call leaveStage to clean-up and enter next stage if one is given (if not leave and fall-out to main) window.requestAnimationFrame(this.leaveStage); } */ window.requestAnimationFrame(self.leaveStage); } // Finally, leaveStage clears state and moves on to the next state this.leaveStage = function(id, params) { console.log("leave stage"); /*if (id !== undefined && this.transitionLinks[id]) { // Head to initialisation of next stage (pass relevant parameter object along) transitionLinks[id].initPacket = params; window.requestAnimationFrame(transitionLinks[id].init); }*/ } }
javascript
# preferences panel to allow inputting cutom parameters for the structure of a project and its # naming conventions. # -------------------------------------------------------------------------------------------------- import hashlib import nuke from nukescripts.panels import PythonPanel import fileinput import os import smtplib import sys class Preferences(PythonPanel): def __init__(self): PythonPanel.__init__(self, 'C1 Preferences') # C1 Preferences self.email = None self.localDir = None self.projectDir = None # custom regex definitions for validation engine self.regex = {} self.projectStructure = { 'root': {} } self.scriptDir = { 'root': os.path.join(os.path.join(os.path.realpath(__file__), os.pardir), os.pardir), 'c1_tools': os.path.join(os.path.realpath(__file__), os.pardir) } # define knobs self.inp_email = nuke.String_Knob('email', 'C1 Initials: ') self.inp_localDir = nuke.String_Knob( 'localDir', 'Local Working Directory: ') self.btn_localDir = nuke.PyScript_Knob("Set Working Dir") self.loginButton = nuke.PyScript_Knob("Login") self.cancelButton = nuke.PyScript_Knob("Cancel") # Project Map Tab self.projectMapTab = nuke.Tab_Knob("Project Map") self.setProjectButton = nuke.File_Knob( 'projectDir', 'Project Location') self.inp_projectLocation = nuke.String_Knob('projectDir', '<b><font size="3" color="red">Remote Project Directory</font></b>') self.inp_projectName = nuke.String_Knob('projectName', 'Project Name') self.inp_projectNum = nuke.Int_Knob('projectNum') # self.inp_projectNum.clearFlag( nuke.STARTLINE ) self.inp_projectCode = nuke.String_Knob('projectCode', 'Project Code') self.inp_projectCode.clearFlag(nuke.STARTLINE) # add knobs self.addKnob(self.inp_localDir) self.addKnob(self.btn_localDir) self.addKnob(self.inp_email) self.addKnob(self.loginButton) self.addKnob(self.cancelButton) # Project Map Tab self.addKnob(self.projectMapTab) self.addKnob(self.setProjectButton) self.addKnob(self.inp_projectName) self.addKnob(self.inp_projectNum) self.addKnob(self.inp_projectCode) # retrieve previous login from login.txt self.retrieveLogin() return def validate(self): self.retrieveLogin() return # Retrieve login.txt data def retrieveLogin(self): if os.path.exists(os.path.join(self.scriptDir['c1_tools'], 'login.txt')): text = open(os.path.join(self.scriptDir[ 'c1_tools'], 'login.txt'), 'r+') lines = [] for line in text: # append each line of the found login.txt lines.append(line) text.close() self.email = lines[0] self.localDir = lines[1] else: self.prompt() print('Succsessfully logged in as: ' + self.email) return # create login.txt data def createLogin(self): try: text = open(os.path.join(self.scriptDir[ 'c1_tools'], 'login.txt'), 'w') text.write(self.inp_email.value() + '\n') text.write(self.inp_localDir.value()) text.close() except: print('Failed to save login info! ') return def prompt(self): PythonPanel.showModal(self) return def knobChanged(self, knob): if knob.name() == 'Login': self.email = self.inp_email.value() self.localDir = self.inp_localDir.value() # write login.txt self.createLogin() self.status = 'online' self.ok() elif knob.name() == 'Set Working Dir': self.inp_localDir.setValue(os.path.abspath(nuke.getFilename( 'Navigate to Local Working Directory...'))) elif knob.name() == 'Project Location': self.inp_projectLocation.setValue(os.path.abspath(nuke.getFilename( 'Navigate to Remote \'Root\' Project Directory...'))) return
python
New Delhi: The Aam Aadmi Party Thursday slammed the BJP for “standing” with saffron party leader and former union minister Swami Chinmayanand, who has been accused of sexually exploiting a law student, and slammed the media’s “silence” on the matter. AAP Rajya Sabha MP Sanjay Singh told reporters that even after the victim submitted all evidence against Chinmayanand no concrete action has been taken yet. “She (victim) submitted proof of repeated rape and blackmail by Chinmayanand to SIT and it is also available with the media but it has maintained its silence in the issue. BJP is standing with Chinmayanand and why is media keeping mum on the issue and turning a blind eye to it,” he said. No immediate response was available from the BJP. The postgraduate student, who had levelled harassment charges against Chinmayanand Monday alleged she was raped by the BJP leader and also physically exploited for one year. She also approached the Delhi Police with a complaint accusing the BJP leader of raping her. A senior Delhi Police official said they received a complaint at a police station in south district which has been forwarded to the special investigation team of the Uttar Pradesh Police. The special investigation team Wednesday quizzed the lawyer of Chinmayanand.
english
package androidx.fragment.app; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Context; import android.content.ContextWrapper; import android.content.res.Configuration; import android.os.Bundle; import android.os.Looper; import android.os.Parcelable; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import androidx.activity.OnBackPressedCallback; import androidx.activity.OnBackPressedDispatcher; import androidx.collection.ArraySet; import androidx.core.p005os.CancellationSignal; import androidx.core.util.LogWriter; import androidx.fragment.C0273R; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentAnim; import androidx.fragment.app.FragmentTransition; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.ViewModelStore; import androidx.lifecycle.ViewModelStoreOwner; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; public abstract class FragmentManager { private static boolean DEBUG = false; public static final int POP_BACK_STACK_INCLUSIVE = 1; static final String TAG = "FragmentManager"; ArrayList<BackStackRecord> mBackStack; private ArrayList<OnBackStackChangedListener> mBackStackChangeListeners; private final AtomicInteger mBackStackIndex = new AtomicInteger(); FragmentContainer mContainer; private ArrayList<Fragment> mCreatedMenus; int mCurState = -1; private boolean mDestroyed; private Runnable mExecCommit = new Runnable() { public void run() { FragmentManager.this.execPendingActions(true); } }; private boolean mExecutingActions; private ConcurrentHashMap<Fragment, HashSet<CancellationSignal>> mExitAnimationCancellationSignals = new ConcurrentHashMap<>(); private FragmentFactory mFragmentFactory = null; private final FragmentStore mFragmentStore = new FragmentStore(); private final FragmentTransition.Callback mFragmentTransitionCallback = new FragmentTransition.Callback() { public void onStart(Fragment fragment, CancellationSignal cancellationSignal) { FragmentManager.this.addCancellationSignal(fragment, cancellationSignal); } public void onComplete(Fragment fragment, CancellationSignal cancellationSignal) { if (!cancellationSignal.isCanceled()) { FragmentManager.this.removeCancellationSignal(fragment, cancellationSignal); } } }; private boolean mHavePendingDeferredStart; FragmentHostCallback<?> mHost; private FragmentFactory mHostFragmentFactory = new FragmentFactory() { public Fragment instantiate(ClassLoader classLoader, String str) { return FragmentManager.this.mHost.instantiate(FragmentManager.this.mHost.getContext(), str, (Bundle) null); } }; private final FragmentLayoutInflaterFactory mLayoutInflaterFactory = new FragmentLayoutInflaterFactory(this); private final FragmentLifecycleCallbacksDispatcher mLifecycleCallbacksDispatcher = new FragmentLifecycleCallbacksDispatcher(this); private boolean mNeedMenuInvalidate; private FragmentManagerViewModel mNonConfig; private final OnBackPressedCallback mOnBackPressedCallback = new OnBackPressedCallback(false) { public void handleOnBackPressed() { FragmentManager.this.handleOnBackPressed(); } }; private OnBackPressedDispatcher mOnBackPressedDispatcher; private Fragment mParent; private final ArrayList<OpGenerator> mPendingActions = new ArrayList<>(); private ArrayList<StartEnterTransitionListener> mPostponedTransactions; Fragment mPrimaryNav; private boolean mStateSaved; private boolean mStopped; private ArrayList<Fragment> mTmpAddedFragments; private ArrayList<Boolean> mTmpIsPop; private ArrayList<BackStackRecord> mTmpRecords; public interface BackStackEntry { @Deprecated CharSequence getBreadCrumbShortTitle(); @Deprecated int getBreadCrumbShortTitleRes(); @Deprecated CharSequence getBreadCrumbTitle(); @Deprecated int getBreadCrumbTitleRes(); int getId(); String getName(); } public static abstract class FragmentLifecycleCallbacks { public void onFragmentActivityCreated(FragmentManager fragmentManager, Fragment fragment, Bundle bundle) { } public void onFragmentAttached(FragmentManager fragmentManager, Fragment fragment, Context context) { } public void onFragmentCreated(FragmentManager fragmentManager, Fragment fragment, Bundle bundle) { } public void onFragmentDestroyed(FragmentManager fragmentManager, Fragment fragment) { } public void onFragmentDetached(FragmentManager fragmentManager, Fragment fragment) { } public void onFragmentPaused(FragmentManager fragmentManager, Fragment fragment) { } public void onFragmentPreAttached(FragmentManager fragmentManager, Fragment fragment, Context context) { } public void onFragmentPreCreated(FragmentManager fragmentManager, Fragment fragment, Bundle bundle) { } public void onFragmentResumed(FragmentManager fragmentManager, Fragment fragment) { } public void onFragmentSaveInstanceState(FragmentManager fragmentManager, Fragment fragment, Bundle bundle) { } public void onFragmentStarted(FragmentManager fragmentManager, Fragment fragment) { } public void onFragmentStopped(FragmentManager fragmentManager, Fragment fragment) { } public void onFragmentViewCreated(FragmentManager fragmentManager, Fragment fragment, View view, Bundle bundle) { } public void onFragmentViewDestroyed(FragmentManager fragmentManager, Fragment fragment) { } } public interface OnBackStackChangedListener { void onBackStackChanged(); } interface OpGenerator { boolean generateOps(ArrayList<BackStackRecord> arrayList, ArrayList<Boolean> arrayList2); } static int reverseTransit(int i) { if (i == 4097) { return 8194; } if (i == 4099) { return FragmentTransaction.TRANSIT_FRAGMENT_FADE; } if (i != 8194) { return 0; } return FragmentTransaction.TRANSIT_FRAGMENT_OPEN; } @Deprecated public static void enableDebugLogging(boolean z) { DEBUG = z; } static boolean isLoggingEnabled(int i) { return DEBUG || Log.isLoggable(TAG, i); } private void throwException(RuntimeException runtimeException) { Log.e(TAG, runtimeException.getMessage()); Log.e(TAG, "Activity state:"); PrintWriter printWriter = new PrintWriter(new LogWriter(TAG)); FragmentHostCallback<?> fragmentHostCallback = this.mHost; if (fragmentHostCallback != null) { try { fragmentHostCallback.onDump(" ", (FileDescriptor) null, printWriter, new String[0]); } catch (Exception e) { Log.e(TAG, "Failed dumping state", e); } } else { try { dump(" ", (FileDescriptor) null, printWriter, new String[0]); } catch (Exception e2) { Log.e(TAG, "Failed dumping state", e2); } } throw runtimeException; } @Deprecated public FragmentTransaction openTransaction() { return beginTransaction(); } public FragmentTransaction beginTransaction() { return new BackStackRecord(this); } public boolean executePendingTransactions() { boolean execPendingActions = execPendingActions(true); forcePostponedTransactions(); return execPendingActions; } /* JADX WARNING: Code restructure failed: missing block: B:10:0x001a, code lost: if (getBackStackEntryCount() <= 0) goto L_0x0025; */ /* JADX WARNING: Code restructure failed: missing block: B:12:0x0022, code lost: if (isPrimaryNavigation(r3.mParent) == false) goto L_0x0025; */ /* JADX WARNING: Code restructure failed: missing block: B:13:0x0025, code lost: r2 = false; */ /* JADX WARNING: Code restructure failed: missing block: B:14:0x0026, code lost: r0.setEnabled(r2); */ /* JADX WARNING: Code restructure failed: missing block: B:15:0x0029, code lost: return; */ /* JADX WARNING: Code restructure failed: missing block: B:9:0x0014, code lost: r0 = r3.mOnBackPressedCallback; */ /* Code decompiled incorrectly, please refer to instructions dump. */ private void updateOnBackPressedCallbackEnabled() { /* r3 = this; java.util.ArrayList<androidx.fragment.app.FragmentManager$OpGenerator> r0 = r3.mPendingActions monitor-enter(r0) java.util.ArrayList<androidx.fragment.app.FragmentManager$OpGenerator> r1 = r3.mPendingActions // Catch:{ all -> 0x002a } boolean r1 = r1.isEmpty() // Catch:{ all -> 0x002a } r2 = 1 if (r1 != 0) goto L_0x0013 androidx.activity.OnBackPressedCallback r1 = r3.mOnBackPressedCallback // Catch:{ all -> 0x002a } r1.setEnabled(r2) // Catch:{ all -> 0x002a } monitor-exit(r0) // Catch:{ all -> 0x002a } return L_0x0013: monitor-exit(r0) // Catch:{ all -> 0x002a } androidx.activity.OnBackPressedCallback r0 = r3.mOnBackPressedCallback int r1 = r3.getBackStackEntryCount() if (r1 <= 0) goto L_0x0025 androidx.fragment.app.Fragment r1 = r3.mParent boolean r1 = r3.isPrimaryNavigation(r1) if (r1 == 0) goto L_0x0025 goto L_0x0026 L_0x0025: r2 = 0 L_0x0026: r0.setEnabled(r2) return L_0x002a: r1 = move-exception monitor-exit(r0) // Catch:{ all -> 0x002a } throw r1 */ throw new UnsupportedOperationException("Method not decompiled: androidx.fragment.app.FragmentManager.updateOnBackPressedCallbackEnabled():void"); } /* access modifiers changed from: package-private */ public boolean isPrimaryNavigation(Fragment fragment) { if (fragment == null) { return true; } FragmentManager fragmentManager = fragment.mFragmentManager; if (!fragment.equals(fragmentManager.getPrimaryNavigationFragment()) || !isPrimaryNavigation(fragmentManager.mParent)) { return false; } return true; } /* access modifiers changed from: package-private */ public void handleOnBackPressed() { execPendingActions(true); if (this.mOnBackPressedCallback.isEnabled()) { popBackStackImmediate(); } else { this.mOnBackPressedDispatcher.onBackPressed(); } } public void popBackStack() { enqueueAction(new PopBackStackState((String) null, -1, 0), false); } public boolean popBackStackImmediate() { return popBackStackImmediate((String) null, -1, 0); } public void popBackStack(String str, int i) { enqueueAction(new PopBackStackState(str, -1, i), false); } public boolean popBackStackImmediate(String str, int i) { return popBackStackImmediate(str, -1, i); } public void popBackStack(int i, int i2) { if (i >= 0) { enqueueAction(new PopBackStackState((String) null, i, i2), false); return; } throw new IllegalArgumentException("Bad id: " + i); } public boolean popBackStackImmediate(int i, int i2) { if (i >= 0) { return popBackStackImmediate((String) null, i, i2); } throw new IllegalArgumentException("Bad id: " + i); } private boolean popBackStackImmediate(String str, int i, int i2) { execPendingActions(false); ensureExecReady(true); Fragment fragment = this.mPrimaryNav; if (fragment != null && i < 0 && str == null && fragment.getChildFragmentManager().popBackStackImmediate()) { return true; } boolean popBackStackState = popBackStackState(this.mTmpRecords, this.mTmpIsPop, str, i, i2); if (popBackStackState) { this.mExecutingActions = true; try { removeRedundantOperationsAndExecute(this.mTmpRecords, this.mTmpIsPop); } finally { cleanupExec(); } } updateOnBackPressedCallbackEnabled(); doPendingDeferredStart(); this.mFragmentStore.burpActive(); return popBackStackState; } public int getBackStackEntryCount() { ArrayList<BackStackRecord> arrayList = this.mBackStack; if (arrayList != null) { return arrayList.size(); } return 0; } public BackStackEntry getBackStackEntryAt(int i) { return this.mBackStack.get(i); } public void addOnBackStackChangedListener(OnBackStackChangedListener onBackStackChangedListener) { if (this.mBackStackChangeListeners == null) { this.mBackStackChangeListeners = new ArrayList<>(); } this.mBackStackChangeListeners.add(onBackStackChangedListener); } public void removeOnBackStackChangedListener(OnBackStackChangedListener onBackStackChangedListener) { ArrayList<OnBackStackChangedListener> arrayList = this.mBackStackChangeListeners; if (arrayList != null) { arrayList.remove(onBackStackChangedListener); } } /* access modifiers changed from: package-private */ public void addCancellationSignal(Fragment fragment, CancellationSignal cancellationSignal) { if (this.mExitAnimationCancellationSignals.get(fragment) == null) { this.mExitAnimationCancellationSignals.put(fragment, new HashSet()); } this.mExitAnimationCancellationSignals.get(fragment).add(cancellationSignal); } /* access modifiers changed from: package-private */ public void removeCancellationSignal(Fragment fragment, CancellationSignal cancellationSignal) { HashSet hashSet = this.mExitAnimationCancellationSignals.get(fragment); if (hashSet != null && hashSet.remove(cancellationSignal) && hashSet.isEmpty()) { this.mExitAnimationCancellationSignals.remove(fragment); if (fragment.mState < 3) { destroyFragmentView(fragment); moveToState(fragment, fragment.getStateAfterAnimating()); } } } public void putFragment(Bundle bundle, String str, Fragment fragment) { if (fragment.mFragmentManager != this) { throwException(new IllegalStateException("Fragment " + fragment + " is not currently in the FragmentManager")); } bundle.putString(str, fragment.mWho); } public Fragment getFragment(Bundle bundle, String str) { String string = bundle.getString(str); if (string == null) { return null; } Fragment findActiveFragment = findActiveFragment(string); if (findActiveFragment == null) { throwException(new IllegalStateException("Fragment no longer exists for key " + str + ": unique id " + string)); } return findActiveFragment; } public static <F extends Fragment> F findFragment(View view) { F findViewFragment = findViewFragment(view); if (findViewFragment != null) { return findViewFragment; } throw new IllegalStateException("View " + view + " does not have a Fragment set"); } private static Fragment findViewFragment(View view) { while (view != null) { Fragment viewFragment = getViewFragment(view); if (viewFragment != null) { return viewFragment; } ViewParent parent = view.getParent(); view = parent instanceof View ? (View) parent : null; } return null; } static Fragment getViewFragment(View view) { Object tag = view.getTag(C0273R.C0276id.fragment_container_view_tag); if (tag instanceof Fragment) { return (Fragment) tag; } return null; } static FragmentManager findFragmentManager(View view) { Fragment findViewFragment = findViewFragment(view); if (findViewFragment != null) { return findViewFragment.getChildFragmentManager(); } Context context = view.getContext(); FragmentActivity fragmentActivity = null; while (true) { if (!(context instanceof ContextWrapper)) { break; } else if (context instanceof FragmentActivity) { fragmentActivity = (FragmentActivity) context; break; } else { context = ((ContextWrapper) context).getBaseContext(); } } if (fragmentActivity != null) { return fragmentActivity.getSupportFragmentManager(); } throw new IllegalStateException("View " + view + " is not within a subclass of FragmentActivity."); } public List<Fragment> getFragments() { return this.mFragmentStore.getFragments(); } /* access modifiers changed from: package-private */ public ViewModelStore getViewModelStore(Fragment fragment) { return this.mNonConfig.getViewModelStore(fragment); } private FragmentManagerViewModel getChildNonConfig(Fragment fragment) { return this.mNonConfig.getChildNonConfig(fragment); } /* access modifiers changed from: package-private */ public void addRetainedFragment(Fragment fragment) { if (isStateSaved()) { if (isLoggingEnabled(2)) { Log.v(TAG, "Ignoring addRetainedFragment as the state is already saved"); } } else if (this.mNonConfig.addRetainedFragment(fragment) && isLoggingEnabled(2)) { Log.v(TAG, "Updating retained Fragments: Added " + fragment); } } /* access modifiers changed from: package-private */ public void removeRetainedFragment(Fragment fragment) { if (isStateSaved()) { if (isLoggingEnabled(2)) { Log.v(TAG, "Ignoring removeRetainedFragment as the state is already saved"); } } else if (this.mNonConfig.removeRetainedFragment(fragment) && isLoggingEnabled(2)) { Log.v(TAG, "Updating retained Fragments: Removed " + fragment); } } /* access modifiers changed from: package-private */ public List<Fragment> getActiveFragments() { return this.mFragmentStore.getActiveFragments(); } /* access modifiers changed from: package-private */ public int getActiveFragmentCount() { return this.mFragmentStore.getActiveFragmentCount(); } public Fragment.SavedState saveFragmentInstanceState(Fragment fragment) { FragmentStateManager fragmentStateManager = this.mFragmentStore.getFragmentStateManager(fragment.mWho); if (fragmentStateManager == null || !fragmentStateManager.getFragment().equals(fragment)) { throwException(new IllegalStateException("Fragment " + fragment + " is not currently in the FragmentManager")); } return fragmentStateManager.saveInstanceState(); } public boolean isDestroyed() { return this.mDestroyed; } public String toString() { StringBuilder sb = new StringBuilder(128); sb.append("FragmentManager{"); sb.append(Integer.toHexString(System.identityHashCode(this))); sb.append(" in "); Fragment fragment = this.mParent; if (fragment != null) { sb.append(fragment.getClass().getSimpleName()); sb.append("{"); sb.append(Integer.toHexString(System.identityHashCode(this.mParent))); sb.append("}"); } else { FragmentHostCallback<?> fragmentHostCallback = this.mHost; if (fragmentHostCallback != null) { sb.append(fragmentHostCallback.getClass().getSimpleName()); sb.append("{"); sb.append(Integer.toHexString(System.identityHashCode(this.mHost))); sb.append("}"); } else { sb.append("null"); } } sb.append("}}"); return sb.toString(); } public void dump(String str, FileDescriptor fileDescriptor, PrintWriter printWriter, String[] strArr) { int size; int size2; String str2 = str + " "; this.mFragmentStore.dump(str, fileDescriptor, printWriter, strArr); ArrayList<Fragment> arrayList = this.mCreatedMenus; if (arrayList != null && (size2 = arrayList.size()) > 0) { printWriter.print(str); printWriter.println("Fragments Created Menus:"); for (int i = 0; i < size2; i++) { printWriter.print(str); printWriter.print(" #"); printWriter.print(i); printWriter.print(": "); printWriter.println(this.mCreatedMenus.get(i).toString()); } } ArrayList<BackStackRecord> arrayList2 = this.mBackStack; if (arrayList2 != null && (size = arrayList2.size()) > 0) { printWriter.print(str); printWriter.println("Back Stack:"); for (int i2 = 0; i2 < size; i2++) { BackStackRecord backStackRecord = this.mBackStack.get(i2); printWriter.print(str); printWriter.print(" #"); printWriter.print(i2); printWriter.print(": "); printWriter.println(backStackRecord.toString()); backStackRecord.dump(str2, printWriter); } } printWriter.print(str); printWriter.println("Back Stack Index: " + this.mBackStackIndex.get()); synchronized (this.mPendingActions) { int size3 = this.mPendingActions.size(); if (size3 > 0) { printWriter.print(str); printWriter.println("Pending Actions:"); for (int i3 = 0; i3 < size3; i3++) { printWriter.print(str); printWriter.print(" #"); printWriter.print(i3); printWriter.print(": "); printWriter.println(this.mPendingActions.get(i3)); } } } printWriter.print(str); printWriter.println("FragmentManager misc state:"); printWriter.print(str); printWriter.print(" mHost="); printWriter.println(this.mHost); printWriter.print(str); printWriter.print(" mContainer="); printWriter.println(this.mContainer); if (this.mParent != null) { printWriter.print(str); printWriter.print(" mParent="); printWriter.println(this.mParent); } printWriter.print(str); printWriter.print(" mCurState="); printWriter.print(this.mCurState); printWriter.print(" mStateSaved="); printWriter.print(this.mStateSaved); printWriter.print(" mStopped="); printWriter.print(this.mStopped); printWriter.print(" mDestroyed="); printWriter.println(this.mDestroyed); if (this.mNeedMenuInvalidate) { printWriter.print(str); printWriter.print(" mNeedMenuInvalidate="); printWriter.println(this.mNeedMenuInvalidate); } } /* access modifiers changed from: package-private */ public void performPendingDeferredStart(Fragment fragment) { if (!fragment.mDeferStart) { return; } if (this.mExecutingActions) { this.mHavePendingDeferredStart = true; return; } fragment.mDeferStart = false; moveToState(fragment, this.mCurState); } /* access modifiers changed from: package-private */ public boolean isStateAtLeast(int i) { return this.mCurState >= i; } /* access modifiers changed from: package-private */ /* JADX WARNING: Code restructure failed: missing block: B:15:0x0040, code lost: if (r2 != 3) goto L_0x0209; */ /* JADX WARNING: Removed duplicated region for block: B:123:0x0203 */ /* JADX WARNING: Removed duplicated region for block: B:43:0x00f0 */ /* JADX WARNING: Removed duplicated region for block: B:45:0x00f5 */ /* JADX WARNING: Removed duplicated region for block: B:47:0x0102 */ /* JADX WARNING: Removed duplicated region for block: B:49:0x0107 */ /* Code decompiled incorrectly, please refer to instructions dump. */ public void moveToState(androidx.fragment.app.Fragment r13, int r14) { /* r12 = this; androidx.fragment.app.FragmentStore r0 = r12.mFragmentStore java.lang.String r1 = r13.mWho androidx.fragment.app.FragmentStateManager r0 = r0.getFragmentStateManager(r1) r1 = 1 if (r0 != 0) goto L_0x0015 androidx.fragment.app.FragmentStateManager r0 = new androidx.fragment.app.FragmentStateManager androidx.fragment.app.FragmentLifecycleCallbacksDispatcher r2 = r12.mLifecycleCallbacksDispatcher r0.<init>(r2, r13) r0.setFragmentManagerState(r1) L_0x0015: int r2 = r0.computeMaxState() int r14 = java.lang.Math.min(r14, r2) int r2 = r13.mState r3 = 0 java.lang.String r4 = "FragmentManager" r5 = -1 r6 = 2 r7 = 3 if (r2 > r14) goto L_0x010c int r2 = r13.mState if (r2 >= r14) goto L_0x0036 java.util.concurrent.ConcurrentHashMap<androidx.fragment.app.Fragment, java.util.HashSet<androidx.core.os.CancellationSignal>> r2 = r12.mExitAnimationCancellationSignals boolean r2 = r2.isEmpty() if (r2 != 0) goto L_0x0036 r12.cancelExitAnimation(r13) L_0x0036: int r2 = r13.mState if (r2 == r5) goto L_0x0044 if (r2 == 0) goto L_0x00e9 if (r2 == r1) goto L_0x00ee if (r2 == r6) goto L_0x0100 if (r2 == r7) goto L_0x0105 goto L_0x0209 L_0x0044: if (r14 <= r5) goto L_0x00e9 boolean r2 = isLoggingEnabled(r7) if (r2 == 0) goto L_0x0060 java.lang.StringBuilder r2 = new java.lang.StringBuilder r2.<init>() java.lang.String r8 = "moveto ATTACHED: " r2.append(r8) r2.append(r13) java.lang.String r2 = r2.toString() android.util.Log.d(r4, r2) L_0x0060: androidx.fragment.app.Fragment r2 = r13.mTarget java.lang.String r8 = " that does not belong to this FragmentManager!" java.lang.String r9 = " declared target fragment " java.lang.String r10 = "Fragment " if (r2 == 0) goto L_0x00ae androidx.fragment.app.Fragment r2 = r13.mTarget androidx.fragment.app.Fragment r11 = r13.mTarget java.lang.String r11 = r11.mWho androidx.fragment.app.Fragment r11 = r12.findActiveFragment(r11) boolean r2 = r2.equals(r11) if (r2 == 0) goto L_0x008e androidx.fragment.app.Fragment r2 = r13.mTarget int r2 = r2.mState if (r2 >= r1) goto L_0x0085 androidx.fragment.app.Fragment r2 = r13.mTarget r12.moveToState((androidx.fragment.app.Fragment) r2, (int) r1) L_0x0085: androidx.fragment.app.Fragment r2 = r13.mTarget java.lang.String r2 = r2.mWho r13.mTargetWho = r2 r13.mTarget = r3 goto L_0x00ae L_0x008e: java.lang.IllegalStateException r14 = new java.lang.IllegalStateException java.lang.StringBuilder r0 = new java.lang.StringBuilder r0.<init>() r0.append(r10) r0.append(r13) r0.append(r9) androidx.fragment.app.Fragment r13 = r13.mTarget r0.append(r13) r0.append(r8) java.lang.String r13 = r0.toString() r14.<init>(r13) throw r14 L_0x00ae: java.lang.String r2 = r13.mTargetWho if (r2 == 0) goto L_0x00e2 java.lang.String r2 = r13.mTargetWho androidx.fragment.app.Fragment r2 = r12.findActiveFragment(r2) if (r2 == 0) goto L_0x00c2 int r3 = r2.mState if (r3 >= r1) goto L_0x00e2 r12.moveToState((androidx.fragment.app.Fragment) r2, (int) r1) goto L_0x00e2 L_0x00c2: java.lang.IllegalStateException r14 = new java.lang.IllegalStateException java.lang.StringBuilder r0 = new java.lang.StringBuilder r0.<init>() r0.append(r10) r0.append(r13) r0.append(r9) java.lang.String r13 = r13.mTargetWho r0.append(r13) r0.append(r8) java.lang.String r13 = r0.toString() r14.<init>(r13) throw r14 L_0x00e2: androidx.fragment.app.FragmentHostCallback<?> r2 = r12.mHost androidx.fragment.app.Fragment r3 = r12.mParent r0.attach(r2, r12, r3) L_0x00e9: if (r14 <= 0) goto L_0x00ee r0.create() L_0x00ee: if (r14 <= r5) goto L_0x00f3 r0.ensureInflatedView() L_0x00f3: if (r14 <= r1) goto L_0x0100 androidx.fragment.app.FragmentContainer r1 = r12.mContainer r0.createView(r1) r0.activityCreated() r0.restoreViewState() L_0x0100: if (r14 <= r6) goto L_0x0105 r0.start() L_0x0105: if (r14 <= r7) goto L_0x0209 r0.resume() goto L_0x0209 L_0x010c: int r2 = r13.mState if (r2 <= r14) goto L_0x0209 int r2 = r13.mState if (r2 == 0) goto L_0x0200 r8 = 0 if (r2 == r1) goto L_0x01bd if (r2 == r6) goto L_0x012a if (r2 == r7) goto L_0x0125 r9 = 4 if (r2 == r9) goto L_0x0120 goto L_0x0209 L_0x0120: if (r14 >= r9) goto L_0x0125 r0.pause() L_0x0125: if (r14 >= r7) goto L_0x012a r0.stop() L_0x012a: if (r14 >= r6) goto L_0x01bd boolean r2 = isLoggingEnabled(r7) if (r2 == 0) goto L_0x0146 java.lang.StringBuilder r2 = new java.lang.StringBuilder r2.<init>() java.lang.String r6 = "movefrom ACTIVITY_CREATED: " r2.append(r6) r2.append(r13) java.lang.String r2 = r2.toString() android.util.Log.d(r4, r2) L_0x0146: android.view.View r2 = r13.mView if (r2 == 0) goto L_0x0159 androidx.fragment.app.FragmentHostCallback<?> r2 = r12.mHost boolean r2 = r2.onShouldSaveFragmentState(r13) if (r2 == 0) goto L_0x0159 android.util.SparseArray<android.os.Parcelable> r2 = r13.mSavedViewState if (r2 != 0) goto L_0x0159 r0.saveViewState() L_0x0159: android.view.View r2 = r13.mView if (r2 == 0) goto L_0x01ae android.view.ViewGroup r2 = r13.mContainer if (r2 == 0) goto L_0x01ae android.view.ViewGroup r2 = r13.mContainer android.view.View r6 = r13.mView r2.endViewTransition(r6) android.view.View r2 = r13.mView r2.clearAnimation() boolean r2 = r13.isRemovingParent() if (r2 != 0) goto L_0x01ae int r2 = r12.mCurState r6 = 0 if (r2 <= r5) goto L_0x0196 boolean r2 = r12.mDestroyed if (r2 != 0) goto L_0x0196 android.view.View r2 = r13.mView int r2 = r2.getVisibility() if (r2 != 0) goto L_0x0196 float r2 = r13.mPostponedAlpha int r2 = (r2 > r6 ? 1 : (r2 == r6 ? 0 : -1)) if (r2 < 0) goto L_0x0196 androidx.fragment.app.FragmentHostCallback<?> r2 = r12.mHost android.content.Context r2 = r2.getContext() androidx.fragment.app.FragmentContainer r3 = r12.mContainer androidx.fragment.app.FragmentAnim$AnimationOrAnimator r3 = androidx.fragment.app.FragmentAnim.loadAnimation(r2, r3, r13, r8) L_0x0196: r13.mPostponedAlpha = r6 android.view.ViewGroup r2 = r13.mContainer android.view.View r5 = r13.mView if (r3 == 0) goto L_0x01a6 r13.setStateAfterAnimating(r14) androidx.fragment.app.FragmentTransition$Callback r6 = r12.mFragmentTransitionCallback androidx.fragment.app.FragmentAnim.animateRemoveFragment(r13, r3, r6) L_0x01a6: r2.removeView(r5) android.view.ViewGroup r3 = r13.mContainer if (r2 == r3) goto L_0x01ae return L_0x01ae: java.util.concurrent.ConcurrentHashMap<androidx.fragment.app.Fragment, java.util.HashSet<androidx.core.os.CancellationSignal>> r2 = r12.mExitAnimationCancellationSignals java.lang.Object r2 = r2.get(r13) if (r2 != 0) goto L_0x01ba r12.destroyFragmentView(r13) goto L_0x01bd L_0x01ba: r13.setStateAfterAnimating(r14) L_0x01bd: if (r14 >= r1) goto L_0x0200 boolean r2 = r13.mRemoving if (r2 == 0) goto L_0x01ca boolean r2 = r13.isInBackStack() if (r2 != 0) goto L_0x01ca r8 = 1 L_0x01ca: if (r8 != 0) goto L_0x01ea androidx.fragment.app.FragmentManagerViewModel r2 = r12.mNonConfig boolean r2 = r2.shouldDestroy(r13) if (r2 == 0) goto L_0x01d5 goto L_0x01ea L_0x01d5: java.lang.String r2 = r13.mTargetWho if (r2 == 0) goto L_0x01ed java.lang.String r2 = r13.mTargetWho androidx.fragment.app.Fragment r2 = r12.findActiveFragment(r2) if (r2 == 0) goto L_0x01ed boolean r3 = r2.getRetainInstance() if (r3 == 0) goto L_0x01ed r13.mTarget = r2 goto L_0x01ed L_0x01ea: r12.makeInactive(r0) L_0x01ed: java.util.concurrent.ConcurrentHashMap<androidx.fragment.app.Fragment, java.util.HashSet<androidx.core.os.CancellationSignal>> r2 = r12.mExitAnimationCancellationSignals java.lang.Object r2 = r2.get(r13) if (r2 == 0) goto L_0x01f9 r13.setStateAfterAnimating(r14) goto L_0x0201 L_0x01f9: androidx.fragment.app.FragmentHostCallback<?> r1 = r12.mHost androidx.fragment.app.FragmentManagerViewModel r2 = r12.mNonConfig r0.destroy(r1, r2) L_0x0200: r1 = r14 L_0x0201: if (r1 >= 0) goto L_0x0208 androidx.fragment.app.FragmentManagerViewModel r14 = r12.mNonConfig r0.detach(r14) L_0x0208: r14 = r1 L_0x0209: int r0 = r13.mState if (r0 == r14) goto L_0x023b boolean r0 = isLoggingEnabled(r7) if (r0 == 0) goto L_0x0239 java.lang.StringBuilder r0 = new java.lang.StringBuilder r0.<init>() java.lang.String r1 = "moveToState: Fragment state for " r0.append(r1) r0.append(r13) java.lang.String r1 = " not updated inline; expected state " r0.append(r1) r0.append(r14) java.lang.String r1 = " found " r0.append(r1) int r1 = r13.mState r0.append(r1) java.lang.String r0 = r0.toString() android.util.Log.d(r4, r0) L_0x0239: r13.mState = r14 L_0x023b: return */ throw new UnsupportedOperationException("Method not decompiled: androidx.fragment.app.FragmentManager.moveToState(androidx.fragment.app.Fragment, int):void"); } private void cancelExitAnimation(Fragment fragment) { HashSet hashSet = this.mExitAnimationCancellationSignals.get(fragment); if (hashSet != null) { Iterator it = hashSet.iterator(); while (it.hasNext()) { ((CancellationSignal) it.next()).cancel(); } hashSet.clear(); destroyFragmentView(fragment); this.mExitAnimationCancellationSignals.remove(fragment); } } /* access modifiers changed from: package-private */ public void setExitAnimationOrder(Fragment fragment, boolean z) { ViewGroup fragmentContainer = getFragmentContainer(fragment); if (fragmentContainer != null && (fragmentContainer instanceof FragmentContainerView)) { ((FragmentContainerView) fragmentContainer).setDrawDisappearingViewsLast(!z); } } private void destroyFragmentView(Fragment fragment) { fragment.performDestroyView(); this.mLifecycleCallbacksDispatcher.dispatchOnFragmentViewDestroyed(fragment, false); fragment.mContainer = null; fragment.mView = null; fragment.mViewLifecycleOwner = null; fragment.mViewLifecycleOwnerLiveData.setValue(null); fragment.mInLayout = false; } /* access modifiers changed from: package-private */ public void moveToState(Fragment fragment) { moveToState(fragment, this.mCurState); } private void completeShowHideFragment(final Fragment fragment) { if (fragment.mView != null) { FragmentAnim.AnimationOrAnimator loadAnimation = FragmentAnim.loadAnimation(this.mHost.getContext(), this.mContainer, fragment, !fragment.mHidden); if (loadAnimation == null || loadAnimation.animator == null) { if (loadAnimation != null) { fragment.mView.startAnimation(loadAnimation.animation); loadAnimation.animation.start(); } fragment.mView.setVisibility((!fragment.mHidden || fragment.isHideReplaced()) ? 0 : 8); if (fragment.isHideReplaced()) { fragment.setHideReplaced(false); } } else { loadAnimation.animator.setTarget(fragment.mView); if (!fragment.mHidden) { fragment.mView.setVisibility(0); } else if (fragment.isHideReplaced()) { fragment.setHideReplaced(false); } else { final ViewGroup viewGroup = fragment.mContainer; final View view = fragment.mView; viewGroup.startViewTransition(view); loadAnimation.animator.addListener(new AnimatorListenerAdapter() { public void onAnimationEnd(Animator animator) { viewGroup.endViewTransition(view); animator.removeListener(this); if (fragment.mView != null && fragment.mHidden) { fragment.mView.setVisibility(8); } } }); } loadAnimation.animator.start(); } } if (fragment.mAdded && isMenuAvailable(fragment)) { this.mNeedMenuInvalidate = true; } fragment.mHiddenChanged = false; fragment.onHiddenChanged(fragment.mHidden); } /* access modifiers changed from: package-private */ /* JADX WARNING: Code restructure failed: missing block: B:9:0x0049, code lost: r0 = r0.mView; r1 = r4.mContainer; r0 = r1.indexOfChild(r0); */ /* Code decompiled incorrectly, please refer to instructions dump. */ public void moveFragmentToExpectedState(androidx.fragment.app.Fragment r4) { /* r3 = this; androidx.fragment.app.FragmentStore r0 = r3.mFragmentStore java.lang.String r1 = r4.mWho boolean r0 = r0.containsActiveFragment(r1) if (r0 != 0) goto L_0x003a r0 = 3 boolean r0 = isLoggingEnabled(r0) if (r0 == 0) goto L_0x0039 java.lang.StringBuilder r0 = new java.lang.StringBuilder r0.<init>() java.lang.String r1 = "Ignoring moving " r0.append(r1) r0.append(r4) java.lang.String r4 = " to state " r0.append(r4) int r4 = r3.mCurState r0.append(r4) java.lang.String r4 = "since it is not added to " r0.append(r4) r0.append(r3) java.lang.String r4 = r0.toString() java.lang.String r0 = "FragmentManager" android.util.Log.d(r0, r4) L_0x0039: return L_0x003a: r3.moveToState(r4) android.view.View r0 = r4.mView if (r0 == 0) goto L_0x00a3 androidx.fragment.app.FragmentStore r0 = r3.mFragmentStore androidx.fragment.app.Fragment r0 = r0.findFragmentUnder(r4) if (r0 == 0) goto L_0x0061 android.view.View r0 = r0.mView android.view.ViewGroup r1 = r4.mContainer int r0 = r1.indexOfChild(r0) android.view.View r2 = r4.mView int r2 = r1.indexOfChild(r2) if (r2 >= r0) goto L_0x0061 r1.removeViewAt(r2) android.view.View r2 = r4.mView r1.addView(r2, r0) L_0x0061: boolean r0 = r4.mIsNewlyAdded if (r0 == 0) goto L_0x00a3 android.view.ViewGroup r0 = r4.mContainer if (r0 == 0) goto L_0x00a3 float r0 = r4.mPostponedAlpha r1 = 0 int r0 = (r0 > r1 ? 1 : (r0 == r1 ? 0 : -1)) if (r0 <= 0) goto L_0x0077 android.view.View r0 = r4.mView float r2 = r4.mPostponedAlpha r0.setAlpha(r2) L_0x0077: r4.mPostponedAlpha = r1 r0 = 0 r4.mIsNewlyAdded = r0 androidx.fragment.app.FragmentHostCallback<?> r0 = r3.mHost android.content.Context r0 = r0.getContext() androidx.fragment.app.FragmentContainer r1 = r3.mContainer r2 = 1 androidx.fragment.app.FragmentAnim$AnimationOrAnimator r0 = androidx.fragment.app.FragmentAnim.loadAnimation(r0, r1, r4, r2) if (r0 == 0) goto L_0x00a3 android.view.animation.Animation r1 = r0.animation if (r1 == 0) goto L_0x0097 android.view.View r1 = r4.mView android.view.animation.Animation r0 = r0.animation r1.startAnimation(r0) goto L_0x00a3 L_0x0097: android.animation.Animator r1 = r0.animator android.view.View r2 = r4.mView r1.setTarget(r2) android.animation.Animator r0 = r0.animator r0.start() L_0x00a3: boolean r0 = r4.mHiddenChanged if (r0 == 0) goto L_0x00aa r3.completeShowHideFragment(r4) L_0x00aa: return */ throw new UnsupportedOperationException("Method not decompiled: androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(androidx.fragment.app.Fragment):void"); } /* access modifiers changed from: package-private */ public void moveToState(int i, boolean z) { FragmentHostCallback<?> fragmentHostCallback; if (this.mHost == null && i != -1) { throw new IllegalStateException("No activity"); } else if (z || i != this.mCurState) { this.mCurState = i; for (Fragment moveFragmentToExpectedState : this.mFragmentStore.getFragments()) { moveFragmentToExpectedState(moveFragmentToExpectedState); } for (Fragment next : this.mFragmentStore.getActiveFragments()) { if (next != null && !next.mIsNewlyAdded) { moveFragmentToExpectedState(next); } } startPendingDeferredFragments(); if (this.mNeedMenuInvalidate && (fragmentHostCallback = this.mHost) != null && this.mCurState == 4) { fragmentHostCallback.onSupportInvalidateOptionsMenu(); this.mNeedMenuInvalidate = false; } } } private void startPendingDeferredFragments() { for (Fragment next : this.mFragmentStore.getActiveFragments()) { if (next != null) { performPendingDeferredStart(next); } } } /* access modifiers changed from: package-private */ public void makeActive(Fragment fragment) { if (!this.mFragmentStore.containsActiveFragment(fragment.mWho)) { FragmentStateManager fragmentStateManager = new FragmentStateManager(this.mLifecycleCallbacksDispatcher, fragment); fragmentStateManager.restoreState(this.mHost.getContext().getClassLoader()); this.mFragmentStore.makeActive(fragmentStateManager); if (fragment.mRetainInstanceChangedWhileDetached) { if (fragment.mRetainInstance) { addRetainedFragment(fragment); } else { removeRetainedFragment(fragment); } fragment.mRetainInstanceChangedWhileDetached = false; } fragmentStateManager.setFragmentManagerState(this.mCurState); if (isLoggingEnabled(2)) { Log.v(TAG, "Added fragment to active set " + fragment); } } } private void makeInactive(FragmentStateManager fragmentStateManager) { Fragment fragment = fragmentStateManager.getFragment(); if (this.mFragmentStore.containsActiveFragment(fragment.mWho)) { if (isLoggingEnabled(2)) { Log.v(TAG, "Removed fragment from active set " + fragment); } this.mFragmentStore.makeInactive(fragmentStateManager); removeRetainedFragment(fragment); } } /* access modifiers changed from: package-private */ public void addFragment(Fragment fragment) { if (isLoggingEnabled(2)) { Log.v(TAG, "add: " + fragment); } makeActive(fragment); if (!fragment.mDetached) { this.mFragmentStore.addFragment(fragment); fragment.mRemoving = false; if (fragment.mView == null) { fragment.mHiddenChanged = false; } if (isMenuAvailable(fragment)) { this.mNeedMenuInvalidate = true; } } } /* access modifiers changed from: package-private */ public void removeFragment(Fragment fragment) { if (isLoggingEnabled(2)) { Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting); } boolean z = !fragment.isInBackStack(); if (!fragment.mDetached || z) { this.mFragmentStore.removeFragment(fragment); if (isMenuAvailable(fragment)) { this.mNeedMenuInvalidate = true; } fragment.mRemoving = true; setVisibleRemovingFragment(fragment); } } /* access modifiers changed from: package-private */ public void hideFragment(Fragment fragment) { if (isLoggingEnabled(2)) { Log.v(TAG, "hide: " + fragment); } if (!fragment.mHidden) { fragment.mHidden = true; fragment.mHiddenChanged = true ^ fragment.mHiddenChanged; setVisibleRemovingFragment(fragment); } } /* access modifiers changed from: package-private */ public void showFragment(Fragment fragment) { if (isLoggingEnabled(2)) { Log.v(TAG, "show: " + fragment); } if (fragment.mHidden) { fragment.mHidden = false; fragment.mHiddenChanged = !fragment.mHiddenChanged; } } /* access modifiers changed from: package-private */ public void detachFragment(Fragment fragment) { if (isLoggingEnabled(2)) { Log.v(TAG, "detach: " + fragment); } if (!fragment.mDetached) { fragment.mDetached = true; if (fragment.mAdded) { if (isLoggingEnabled(2)) { Log.v(TAG, "remove from detach: " + fragment); } this.mFragmentStore.removeFragment(fragment); if (isMenuAvailable(fragment)) { this.mNeedMenuInvalidate = true; } setVisibleRemovingFragment(fragment); } } } /* access modifiers changed from: package-private */ public void attachFragment(Fragment fragment) { if (isLoggingEnabled(2)) { Log.v(TAG, "attach: " + fragment); } if (fragment.mDetached) { fragment.mDetached = false; if (!fragment.mAdded) { this.mFragmentStore.addFragment(fragment); if (isLoggingEnabled(2)) { Log.v(TAG, "add from attach: " + fragment); } if (isMenuAvailable(fragment)) { this.mNeedMenuInvalidate = true; } } } } public Fragment findFragmentById(int i) { return this.mFragmentStore.findFragmentById(i); } public Fragment findFragmentByTag(String str) { return this.mFragmentStore.findFragmentByTag(str); } /* access modifiers changed from: package-private */ public Fragment findFragmentByWho(String str) { return this.mFragmentStore.findFragmentByWho(str); } /* access modifiers changed from: package-private */ public Fragment findActiveFragment(String str) { return this.mFragmentStore.findActiveFragment(str); } private void checkStateLoss() { if (isStateSaved()) { throw new IllegalStateException("Can not perform this action after onSaveInstanceState"); } } public boolean isStateSaved() { return this.mStateSaved || this.mStopped; } /* access modifiers changed from: package-private */ public void enqueueAction(OpGenerator opGenerator, boolean z) { if (!z) { if (this.mHost != null) { checkStateLoss(); } else if (this.mDestroyed) { throw new IllegalStateException("FragmentManager has been destroyed"); } else { throw new IllegalStateException("FragmentManager has not been attached to a host."); } } synchronized (this.mPendingActions) { if (this.mHost != null) { this.mPendingActions.add(opGenerator); scheduleCommit(); } else if (!z) { throw new IllegalStateException("Activity has been destroyed"); } } } /* access modifiers changed from: package-private */ public void scheduleCommit() { synchronized (this.mPendingActions) { boolean z = false; boolean z2 = this.mPostponedTransactions != null && !this.mPostponedTransactions.isEmpty(); if (this.mPendingActions.size() == 1) { z = true; } if (z2 || z) { this.mHost.getHandler().removeCallbacks(this.mExecCommit); this.mHost.getHandler().post(this.mExecCommit); updateOnBackPressedCallbackEnabled(); } } } /* access modifiers changed from: package-private */ public int allocBackStackIndex() { return this.mBackStackIndex.getAndIncrement(); } private void ensureExecReady(boolean z) { if (this.mExecutingActions) { throw new IllegalStateException("FragmentManager is already executing transactions"); } else if (this.mHost == null) { if (this.mDestroyed) { throw new IllegalStateException("FragmentManager has been destroyed"); } throw new IllegalStateException("FragmentManager has not been attached to a host."); } else if (Looper.myLooper() == this.mHost.getHandler().getLooper()) { if (!z) { checkStateLoss(); } if (this.mTmpRecords == null) { this.mTmpRecords = new ArrayList<>(); this.mTmpIsPop = new ArrayList<>(); } this.mExecutingActions = true; try { executePostponedTransaction((ArrayList<BackStackRecord>) null, (ArrayList<Boolean>) null); } finally { this.mExecutingActions = false; } } else { throw new IllegalStateException("Must be called from main thread of fragment host"); } } /* access modifiers changed from: package-private */ public void execSingleAction(OpGenerator opGenerator, boolean z) { if (!z || (this.mHost != null && !this.mDestroyed)) { ensureExecReady(z); if (opGenerator.generateOps(this.mTmpRecords, this.mTmpIsPop)) { this.mExecutingActions = true; try { removeRedundantOperationsAndExecute(this.mTmpRecords, this.mTmpIsPop); } finally { cleanupExec(); } } updateOnBackPressedCallbackEnabled(); doPendingDeferredStart(); this.mFragmentStore.burpActive(); } } private void cleanupExec() { this.mExecutingActions = false; this.mTmpIsPop.clear(); this.mTmpRecords.clear(); } /* JADX INFO: finally extract failed */ /* access modifiers changed from: package-private */ public boolean execPendingActions(boolean z) { ensureExecReady(z); boolean z2 = false; while (generateOpsForPendingActions(this.mTmpRecords, this.mTmpIsPop)) { this.mExecutingActions = true; try { removeRedundantOperationsAndExecute(this.mTmpRecords, this.mTmpIsPop); cleanupExec(); z2 = true; } catch (Throwable th) { cleanupExec(); throw th; } } updateOnBackPressedCallbackEnabled(); doPendingDeferredStart(); this.mFragmentStore.burpActive(); return z2; } private void executePostponedTransaction(ArrayList<BackStackRecord> arrayList, ArrayList<Boolean> arrayList2) { int indexOf; int indexOf2; ArrayList<StartEnterTransitionListener> arrayList3 = this.mPostponedTransactions; int size = arrayList3 == null ? 0 : arrayList3.size(); int i = 0; while (i < size) { StartEnterTransitionListener startEnterTransitionListener = this.mPostponedTransactions.get(i); if (arrayList != null && !startEnterTransitionListener.mIsBack && (indexOf2 = arrayList.indexOf(startEnterTransitionListener.mRecord)) != -1 && arrayList2 != null && arrayList2.get(indexOf2).booleanValue()) { this.mPostponedTransactions.remove(i); i--; size--; startEnterTransitionListener.cancelTransaction(); } else if (startEnterTransitionListener.isReady() || (arrayList != null && startEnterTransitionListener.mRecord.interactsWith(arrayList, 0, arrayList.size()))) { this.mPostponedTransactions.remove(i); i--; size--; if (arrayList == null || startEnterTransitionListener.mIsBack || (indexOf = arrayList.indexOf(startEnterTransitionListener.mRecord)) == -1 || arrayList2 == null || !arrayList2.get(indexOf).booleanValue()) { startEnterTransitionListener.completeTransaction(); } else { startEnterTransitionListener.cancelTransaction(); } } i++; } } private void removeRedundantOperationsAndExecute(ArrayList<BackStackRecord> arrayList, ArrayList<Boolean> arrayList2) { if (!arrayList.isEmpty()) { if (arrayList.size() == arrayList2.size()) { executePostponedTransaction(arrayList, arrayList2); int size = arrayList.size(); int i = 0; int i2 = 0; while (i < size) { if (!arrayList.get(i).mReorderingAllowed) { if (i2 != i) { executeOpsTogether(arrayList, arrayList2, i2, i); } i2 = i + 1; if (arrayList2.get(i).booleanValue()) { while (i2 < size && arrayList2.get(i2).booleanValue() && !arrayList.get(i2).mReorderingAllowed) { i2++; } } executeOpsTogether(arrayList, arrayList2, i, i2); i = i2 - 1; } i++; } if (i2 != size) { executeOpsTogether(arrayList, arrayList2, i2, size); return; } return; } throw new IllegalStateException("Internal error with the back stack records"); } } private void executeOpsTogether(ArrayList<BackStackRecord> arrayList, ArrayList<Boolean> arrayList2, int i, int i2) { int i3; ArrayList<BackStackRecord> arrayList3 = arrayList; ArrayList<Boolean> arrayList4 = arrayList2; int i4 = i; int i5 = i2; boolean z = arrayList3.get(i4).mReorderingAllowed; ArrayList<Fragment> arrayList5 = this.mTmpAddedFragments; if (arrayList5 == null) { this.mTmpAddedFragments = new ArrayList<>(); } else { arrayList5.clear(); } this.mTmpAddedFragments.addAll(this.mFragmentStore.getFragments()); Fragment primaryNavigationFragment = getPrimaryNavigationFragment(); boolean z2 = false; for (int i6 = i4; i6 < i5; i6++) { BackStackRecord backStackRecord = arrayList3.get(i6); if (!arrayList4.get(i6).booleanValue()) { primaryNavigationFragment = backStackRecord.expandOps(this.mTmpAddedFragments, primaryNavigationFragment); } else { primaryNavigationFragment = backStackRecord.trackAddedFragmentsInPop(this.mTmpAddedFragments, primaryNavigationFragment); } z2 = z2 || backStackRecord.mAddToBackStack; } this.mTmpAddedFragments.clear(); if (!z) { FragmentTransition.startTransitions(this, arrayList, arrayList2, i, i2, false, this.mFragmentTransitionCallback); } executeOps(arrayList, arrayList2, i, i2); if (z) { ArraySet arraySet = new ArraySet(); addAddedFragments(arraySet); int postponePostponableTransactions = postponePostponableTransactions(arrayList, arrayList2, i, i2, arraySet); makeRemovedFragmentsInvisible(arraySet); i3 = postponePostponableTransactions; } else { i3 = i5; } if (i3 != i4 && z) { FragmentTransition.startTransitions(this, arrayList, arrayList2, i, i3, true, this.mFragmentTransitionCallback); moveToState(this.mCurState, true); } while (i4 < i5) { BackStackRecord backStackRecord2 = arrayList3.get(i4); if (arrayList4.get(i4).booleanValue() && backStackRecord2.mIndex >= 0) { backStackRecord2.mIndex = -1; } backStackRecord2.runOnCommitRunnables(); i4++; } if (z2) { reportBackStackChanged(); } } private void makeRemovedFragmentsInvisible(ArraySet<Fragment> arraySet) { int size = arraySet.size(); for (int i = 0; i < size; i++) { Fragment valueAt = arraySet.valueAt(i); if (!valueAt.mAdded) { View requireView = valueAt.requireView(); valueAt.mPostponedAlpha = requireView.getAlpha(); requireView.setAlpha(0.0f); } } } private int postponePostponableTransactions(ArrayList<BackStackRecord> arrayList, ArrayList<Boolean> arrayList2, int i, int i2, ArraySet<Fragment> arraySet) { int i3 = i2; for (int i4 = i2 - 1; i4 >= i; i4--) { BackStackRecord backStackRecord = arrayList.get(i4); boolean booleanValue = arrayList2.get(i4).booleanValue(); if (backStackRecord.isPostponed() && !backStackRecord.interactsWith(arrayList, i4 + 1, i2)) { if (this.mPostponedTransactions == null) { this.mPostponedTransactions = new ArrayList<>(); } StartEnterTransitionListener startEnterTransitionListener = new StartEnterTransitionListener(backStackRecord, booleanValue); this.mPostponedTransactions.add(startEnterTransitionListener); backStackRecord.setOnStartPostponedListener(startEnterTransitionListener); if (booleanValue) { backStackRecord.executeOps(); } else { backStackRecord.executePopOps(false); } i3--; if (i4 != i3) { arrayList.remove(i4); arrayList.add(i3, backStackRecord); } addAddedFragments(arraySet); } } return i3; } /* access modifiers changed from: package-private */ public void completeExecute(BackStackRecord backStackRecord, boolean z, boolean z2, boolean z3) { if (z) { backStackRecord.executePopOps(z3); } else { backStackRecord.executeOps(); } ArrayList arrayList = new ArrayList(1); ArrayList arrayList2 = new ArrayList(1); arrayList.add(backStackRecord); arrayList2.add(Boolean.valueOf(z)); if (z2) { FragmentTransition.startTransitions(this, arrayList, arrayList2, 0, 1, true, this.mFragmentTransitionCallback); } if (z3) { moveToState(this.mCurState, true); } for (Fragment next : this.mFragmentStore.getActiveFragments()) { if (next != null && next.mView != null && next.mIsNewlyAdded && backStackRecord.interactsWith(next.mContainerId)) { if (next.mPostponedAlpha > 0.0f) { next.mView.setAlpha(next.mPostponedAlpha); } if (z3) { next.mPostponedAlpha = 0.0f; } else { next.mPostponedAlpha = -1.0f; next.mIsNewlyAdded = false; } } } } private static void executeOps(ArrayList<BackStackRecord> arrayList, ArrayList<Boolean> arrayList2, int i, int i2) { while (i < i2) { BackStackRecord backStackRecord = arrayList.get(i); boolean z = true; if (arrayList2.get(i).booleanValue()) { backStackRecord.bumpBackStackNesting(-1); if (i != i2 - 1) { z = false; } backStackRecord.executePopOps(z); } else { backStackRecord.bumpBackStackNesting(1); backStackRecord.executeOps(); } i++; } } private void setVisibleRemovingFragment(Fragment fragment) { ViewGroup fragmentContainer = getFragmentContainer(fragment); if (fragmentContainer != null) { if (fragmentContainer.getTag(C0273R.C0276id.visible_removing_fragment_view_tag) == null) { fragmentContainer.setTag(C0273R.C0276id.visible_removing_fragment_view_tag, fragment); } ((Fragment) fragmentContainer.getTag(C0273R.C0276id.visible_removing_fragment_view_tag)).setNextAnim(fragment.getNextAnim()); } } private ViewGroup getFragmentContainer(Fragment fragment) { if (fragment.mContainerId > 0 && this.mContainer.onHasView()) { View onFindViewById = this.mContainer.onFindViewById(fragment.mContainerId); if (onFindViewById instanceof ViewGroup) { return (ViewGroup) onFindViewById; } } return null; } private void addAddedFragments(ArraySet<Fragment> arraySet) { int i = this.mCurState; if (i >= 1) { int min = Math.min(i, 3); for (Fragment next : this.mFragmentStore.getFragments()) { if (next.mState < min) { moveToState(next, min); if (next.mView != null && !next.mHidden && next.mIsNewlyAdded) { arraySet.add(next); } } } } } private void forcePostponedTransactions() { if (this.mPostponedTransactions != null) { while (!this.mPostponedTransactions.isEmpty()) { this.mPostponedTransactions.remove(0).completeTransaction(); } } } private void endAnimatingAwayFragments() { if (!this.mExitAnimationCancellationSignals.isEmpty()) { for (Fragment next : this.mExitAnimationCancellationSignals.keySet()) { cancelExitAnimation(next); moveToState(next, next.getStateAfterAnimating()); } } } private boolean generateOpsForPendingActions(ArrayList<BackStackRecord> arrayList, ArrayList<Boolean> arrayList2) { synchronized (this.mPendingActions) { if (this.mPendingActions.isEmpty()) { return false; } int size = this.mPendingActions.size(); boolean z = false; for (int i = 0; i < size; i++) { z |= this.mPendingActions.get(i).generateOps(arrayList, arrayList2); } this.mPendingActions.clear(); this.mHost.getHandler().removeCallbacks(this.mExecCommit); return z; } } private void doPendingDeferredStart() { if (this.mHavePendingDeferredStart) { this.mHavePendingDeferredStart = false; startPendingDeferredFragments(); } } private void reportBackStackChanged() { if (this.mBackStackChangeListeners != null) { for (int i = 0; i < this.mBackStackChangeListeners.size(); i++) { this.mBackStackChangeListeners.get(i).onBackStackChanged(); } } } /* access modifiers changed from: package-private */ public void addBackStackState(BackStackRecord backStackRecord) { if (this.mBackStack == null) { this.mBackStack = new ArrayList<>(); } this.mBackStack.add(backStackRecord); } /* access modifiers changed from: package-private */ public boolean popBackStackState(ArrayList<BackStackRecord> arrayList, ArrayList<Boolean> arrayList2, String str, int i, int i2) { int i3; ArrayList<BackStackRecord> arrayList3 = this.mBackStack; if (arrayList3 == null) { return false; } if (str == null && i < 0 && (i2 & 1) == 0) { int size = arrayList3.size() - 1; if (size < 0) { return false; } arrayList.add(this.mBackStack.remove(size)); arrayList2.add(true); } else { if (str != null || i >= 0) { int size2 = this.mBackStack.size() - 1; while (size2 >= 0) { BackStackRecord backStackRecord = this.mBackStack.get(size2); if ((str != null && str.equals(backStackRecord.getName())) || (i >= 0 && i == backStackRecord.mIndex)) { break; } size2--; } if (size2 < 0) { return false; } if ((i2 & 1) != 0) { while (true) { size2--; if (size2 < 0) { break; } BackStackRecord backStackRecord2 = this.mBackStack.get(size2); if ((str == null || !str.equals(backStackRecord2.getName())) && (i < 0 || i != backStackRecord2.mIndex)) { break; } } } i3 = size2; } else { i3 = -1; } if (i3 == this.mBackStack.size() - 1) { return false; } for (int size3 = this.mBackStack.size() - 1; size3 > i3; size3--) { arrayList.add(this.mBackStack.remove(size3)); arrayList2.add(true); } } return true; } /* access modifiers changed from: package-private */ @Deprecated public FragmentManagerNonConfig retainNonConfig() { if (this.mHost instanceof ViewModelStoreOwner) { throwException(new IllegalStateException("You cannot use retainNonConfig when your FragmentHostCallback implements ViewModelStoreOwner.")); } return this.mNonConfig.getSnapshot(); } /* access modifiers changed from: package-private */ public Parcelable saveAllState() { int size; forcePostponedTransactions(); endAnimatingAwayFragments(); execPendingActions(true); this.mStateSaved = true; ArrayList<FragmentState> saveActiveFragments = this.mFragmentStore.saveActiveFragments(); BackStackState[] backStackStateArr = null; if (saveActiveFragments.isEmpty()) { if (isLoggingEnabled(2)) { Log.v(TAG, "saveAllState: no fragments!"); } return null; } ArrayList<String> saveAddedFragments = this.mFragmentStore.saveAddedFragments(); ArrayList<BackStackRecord> arrayList = this.mBackStack; if (arrayList != null && (size = arrayList.size()) > 0) { backStackStateArr = new BackStackState[size]; for (int i = 0; i < size; i++) { backStackStateArr[i] = new BackStackState(this.mBackStack.get(i)); if (isLoggingEnabled(2)) { Log.v(TAG, "saveAllState: adding back stack #" + i + ": " + this.mBackStack.get(i)); } } } FragmentManagerState fragmentManagerState = new FragmentManagerState(); fragmentManagerState.mActive = saveActiveFragments; fragmentManagerState.mAdded = saveAddedFragments; fragmentManagerState.mBackStack = backStackStateArr; fragmentManagerState.mBackStackIndex = this.mBackStackIndex.get(); Fragment fragment = this.mPrimaryNav; if (fragment != null) { fragmentManagerState.mPrimaryNavActiveWho = fragment.mWho; } return fragmentManagerState; } /* access modifiers changed from: package-private */ public void restoreAllState(Parcelable parcelable, FragmentManagerNonConfig fragmentManagerNonConfig) { if (this.mHost instanceof ViewModelStoreOwner) { throwException(new IllegalStateException("You must use restoreSaveState when your FragmentHostCallback implements ViewModelStoreOwner")); } this.mNonConfig.restoreFromSnapshot(fragmentManagerNonConfig); restoreSaveState(parcelable); } /* access modifiers changed from: package-private */ public void restoreSaveState(Parcelable parcelable) { FragmentStateManager fragmentStateManager; if (parcelable != null) { FragmentManagerState fragmentManagerState = (FragmentManagerState) parcelable; if (fragmentManagerState.mActive != null) { this.mFragmentStore.resetActiveFragments(); Iterator<FragmentState> it = fragmentManagerState.mActive.iterator(); while (it.hasNext()) { FragmentState next = it.next(); if (next != null) { Fragment findRetainedFragmentByWho = this.mNonConfig.findRetainedFragmentByWho(next.mWho); if (findRetainedFragmentByWho != null) { if (isLoggingEnabled(2)) { Log.v(TAG, "restoreSaveState: re-attaching retained " + findRetainedFragmentByWho); } fragmentStateManager = new FragmentStateManager(this.mLifecycleCallbacksDispatcher, findRetainedFragmentByWho, next); } else { fragmentStateManager = new FragmentStateManager(this.mLifecycleCallbacksDispatcher, this.mHost.getContext().getClassLoader(), getFragmentFactory(), next); } Fragment fragment = fragmentStateManager.getFragment(); fragment.mFragmentManager = this; if (isLoggingEnabled(2)) { Log.v(TAG, "restoreSaveState: active (" + fragment.mWho + "): " + fragment); } fragmentStateManager.restoreState(this.mHost.getContext().getClassLoader()); this.mFragmentStore.makeActive(fragmentStateManager); fragmentStateManager.setFragmentManagerState(this.mCurState); } } for (Fragment next2 : this.mNonConfig.getRetainedFragments()) { if (!this.mFragmentStore.containsActiveFragment(next2.mWho)) { if (isLoggingEnabled(2)) { Log.v(TAG, "Discarding retained Fragment " + next2 + " that was not found in the set of active Fragments " + fragmentManagerState.mActive); } moveToState(next2, 1); next2.mRemoving = true; moveToState(next2, -1); } } this.mFragmentStore.restoreAddedFragments(fragmentManagerState.mAdded); if (fragmentManagerState.mBackStack != null) { this.mBackStack = new ArrayList<>(fragmentManagerState.mBackStack.length); for (int i = 0; i < fragmentManagerState.mBackStack.length; i++) { BackStackRecord instantiate = fragmentManagerState.mBackStack[i].instantiate(this); if (isLoggingEnabled(2)) { Log.v(TAG, "restoreAllState: back stack #" + i + " (index " + instantiate.mIndex + "): " + instantiate); PrintWriter printWriter = new PrintWriter(new LogWriter(TAG)); instantiate.dump(" ", printWriter, false); printWriter.close(); } this.mBackStack.add(instantiate); } } else { this.mBackStack = null; } this.mBackStackIndex.set(fragmentManagerState.mBackStackIndex); if (fragmentManagerState.mPrimaryNavActiveWho != null) { Fragment findActiveFragment = findActiveFragment(fragmentManagerState.mPrimaryNavActiveWho); this.mPrimaryNav = findActiveFragment; dispatchParentPrimaryNavigationFragmentChanged(findActiveFragment); } } } } /* access modifiers changed from: package-private */ public Fragment getParent() { return this.mParent; } /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r4v6, resolved type: androidx.activity.OnBackPressedDispatcherOwner} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r4v7, resolved type: androidx.fragment.app.Fragment} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r4v8, resolved type: androidx.fragment.app.Fragment} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r4v9, resolved type: androidx.fragment.app.Fragment} */ /* access modifiers changed from: package-private */ /* JADX WARNING: Multi-variable type inference failed */ /* Code decompiled incorrectly, please refer to instructions dump. */ public void attachController(androidx.fragment.app.FragmentHostCallback<?> r3, androidx.fragment.app.FragmentContainer r4, androidx.fragment.app.Fragment r5) { /* r2 = this; androidx.fragment.app.FragmentHostCallback<?> r0 = r2.mHost if (r0 != 0) goto L_0x004b r2.mHost = r3 r2.mContainer = r4 r2.mParent = r5 if (r5 == 0) goto L_0x000f r2.updateOnBackPressedCallbackEnabled() L_0x000f: boolean r4 = r3 instanceof androidx.activity.OnBackPressedDispatcherOwner if (r4 == 0) goto L_0x0026 r4 = r3 androidx.activity.OnBackPressedDispatcherOwner r4 = (androidx.activity.OnBackPressedDispatcherOwner) r4 androidx.activity.OnBackPressedDispatcher r0 = r4.getOnBackPressedDispatcher() r2.mOnBackPressedDispatcher = r0 if (r5 == 0) goto L_0x001f r4 = r5 L_0x001f: androidx.activity.OnBackPressedDispatcher r0 = r2.mOnBackPressedDispatcher androidx.activity.OnBackPressedCallback r1 = r2.mOnBackPressedCallback r0.addCallback(r4, r1) L_0x0026: if (r5 == 0) goto L_0x0031 androidx.fragment.app.FragmentManager r3 = r5.mFragmentManager androidx.fragment.app.FragmentManagerViewModel r3 = r3.getChildNonConfig(r5) r2.mNonConfig = r3 goto L_0x004a L_0x0031: boolean r4 = r3 instanceof androidx.lifecycle.ViewModelStoreOwner if (r4 == 0) goto L_0x0042 androidx.lifecycle.ViewModelStoreOwner r3 = (androidx.lifecycle.ViewModelStoreOwner) r3 androidx.lifecycle.ViewModelStore r3 = r3.getViewModelStore() androidx.fragment.app.FragmentManagerViewModel r3 = androidx.fragment.app.FragmentManagerViewModel.getInstance(r3) r2.mNonConfig = r3 goto L_0x004a L_0x0042: androidx.fragment.app.FragmentManagerViewModel r3 = new androidx.fragment.app.FragmentManagerViewModel r4 = 0 r3.<init>(r4) r2.mNonConfig = r3 L_0x004a: return L_0x004b: java.lang.IllegalStateException r3 = new java.lang.IllegalStateException java.lang.String r4 = "Already attached" r3.<init>(r4) throw r3 */ throw new UnsupportedOperationException("Method not decompiled: androidx.fragment.app.FragmentManager.attachController(androidx.fragment.app.FragmentHostCallback, androidx.fragment.app.FragmentContainer, androidx.fragment.app.Fragment):void"); } /* access modifiers changed from: package-private */ public void noteStateNotSaved() { if (this.mHost != null) { this.mStateSaved = false; this.mStopped = false; for (Fragment next : this.mFragmentStore.getFragments()) { if (next != null) { next.noteStateNotSaved(); } } } } /* access modifiers changed from: package-private */ public void dispatchCreate() { this.mStateSaved = false; this.mStopped = false; dispatchStateChange(1); } /* access modifiers changed from: package-private */ public void dispatchActivityCreated() { this.mStateSaved = false; this.mStopped = false; dispatchStateChange(2); } /* access modifiers changed from: package-private */ public void dispatchStart() { this.mStateSaved = false; this.mStopped = false; dispatchStateChange(3); } /* access modifiers changed from: package-private */ public void dispatchResume() { this.mStateSaved = false; this.mStopped = false; dispatchStateChange(4); } /* access modifiers changed from: package-private */ public void dispatchPause() { dispatchStateChange(3); } /* access modifiers changed from: package-private */ public void dispatchStop() { this.mStopped = true; dispatchStateChange(2); } /* access modifiers changed from: package-private */ public void dispatchDestroyView() { dispatchStateChange(1); } /* access modifiers changed from: package-private */ public void dispatchDestroy() { this.mDestroyed = true; execPendingActions(true); endAnimatingAwayFragments(); dispatchStateChange(-1); this.mHost = null; this.mContainer = null; this.mParent = null; if (this.mOnBackPressedDispatcher != null) { this.mOnBackPressedCallback.remove(); this.mOnBackPressedDispatcher = null; } } /* JADX INFO: finally extract failed */ private void dispatchStateChange(int i) { try { this.mExecutingActions = true; this.mFragmentStore.dispatchStateChange(i); moveToState(i, false); this.mExecutingActions = false; execPendingActions(true); } catch (Throwable th) { this.mExecutingActions = false; throw th; } } /* access modifiers changed from: package-private */ public void dispatchMultiWindowModeChanged(boolean z) { for (Fragment next : this.mFragmentStore.getFragments()) { if (next != null) { next.performMultiWindowModeChanged(z); } } } /* access modifiers changed from: package-private */ public void dispatchPictureInPictureModeChanged(boolean z) { for (Fragment next : this.mFragmentStore.getFragments()) { if (next != null) { next.performPictureInPictureModeChanged(z); } } } /* access modifiers changed from: package-private */ public void dispatchConfigurationChanged(Configuration configuration) { for (Fragment next : this.mFragmentStore.getFragments()) { if (next != null) { next.performConfigurationChanged(configuration); } } } /* access modifiers changed from: package-private */ public void dispatchLowMemory() { for (Fragment next : this.mFragmentStore.getFragments()) { if (next != null) { next.performLowMemory(); } } } /* access modifiers changed from: package-private */ public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater menuInflater) { if (this.mCurState < 1) { return false; } ArrayList<Fragment> arrayList = null; boolean z = false; for (Fragment next : this.mFragmentStore.getFragments()) { if (next != null && next.performCreateOptionsMenu(menu, menuInflater)) { if (arrayList == null) { arrayList = new ArrayList<>(); } arrayList.add(next); z = true; } } if (this.mCreatedMenus != null) { for (int i = 0; i < this.mCreatedMenus.size(); i++) { Fragment fragment = this.mCreatedMenus.get(i); if (arrayList == null || !arrayList.contains(fragment)) { fragment.onDestroyOptionsMenu(); } } } this.mCreatedMenus = arrayList; return z; } /* access modifiers changed from: package-private */ public boolean dispatchPrepareOptionsMenu(Menu menu) { boolean z = false; if (this.mCurState < 1) { return false; } for (Fragment next : this.mFragmentStore.getFragments()) { if (next != null && next.performPrepareOptionsMenu(menu)) { z = true; } } return z; } /* access modifiers changed from: package-private */ public boolean dispatchOptionsItemSelected(MenuItem menuItem) { if (this.mCurState < 1) { return false; } for (Fragment next : this.mFragmentStore.getFragments()) { if (next != null && next.performOptionsItemSelected(menuItem)) { return true; } } return false; } /* access modifiers changed from: package-private */ public boolean dispatchContextItemSelected(MenuItem menuItem) { if (this.mCurState < 1) { return false; } for (Fragment next : this.mFragmentStore.getFragments()) { if (next != null && next.performContextItemSelected(menuItem)) { return true; } } return false; } /* access modifiers changed from: package-private */ public void dispatchOptionsMenuClosed(Menu menu) { if (this.mCurState >= 1) { for (Fragment next : this.mFragmentStore.getFragments()) { if (next != null) { next.performOptionsMenuClosed(menu); } } } } /* access modifiers changed from: package-private */ public void setPrimaryNavigationFragment(Fragment fragment) { if (fragment == null || (fragment.equals(findActiveFragment(fragment.mWho)) && (fragment.mHost == null || fragment.mFragmentManager == this))) { Fragment fragment2 = this.mPrimaryNav; this.mPrimaryNav = fragment; dispatchParentPrimaryNavigationFragmentChanged(fragment2); dispatchParentPrimaryNavigationFragmentChanged(this.mPrimaryNav); return; } throw new IllegalArgumentException("Fragment " + fragment + " is not an active fragment of FragmentManager " + this); } private void dispatchParentPrimaryNavigationFragmentChanged(Fragment fragment) { if (fragment != null && fragment.equals(findActiveFragment(fragment.mWho))) { fragment.performPrimaryNavigationFragmentChanged(); } } /* access modifiers changed from: package-private */ public void dispatchPrimaryNavigationFragmentChanged() { updateOnBackPressedCallbackEnabled(); dispatchParentPrimaryNavigationFragmentChanged(this.mPrimaryNav); } public Fragment getPrimaryNavigationFragment() { return this.mPrimaryNav; } /* access modifiers changed from: package-private */ public void setMaxLifecycle(Fragment fragment, Lifecycle.State state) { if (!fragment.equals(findActiveFragment(fragment.mWho)) || !(fragment.mHost == null || fragment.mFragmentManager == this)) { throw new IllegalArgumentException("Fragment " + fragment + " is not an active fragment of FragmentManager " + this); } fragment.mMaxState = state; } public void setFragmentFactory(FragmentFactory fragmentFactory) { this.mFragmentFactory = fragmentFactory; } public FragmentFactory getFragmentFactory() { FragmentFactory fragmentFactory = this.mFragmentFactory; if (fragmentFactory != null) { return fragmentFactory; } Fragment fragment = this.mParent; if (fragment != null) { return fragment.mFragmentManager.getFragmentFactory(); } return this.mHostFragmentFactory; } /* access modifiers changed from: package-private */ public FragmentLifecycleCallbacksDispatcher getLifecycleCallbacksDispatcher() { return this.mLifecycleCallbacksDispatcher; } public void registerFragmentLifecycleCallbacks(FragmentLifecycleCallbacks fragmentLifecycleCallbacks, boolean z) { this.mLifecycleCallbacksDispatcher.registerFragmentLifecycleCallbacks(fragmentLifecycleCallbacks, z); } public void unregisterFragmentLifecycleCallbacks(FragmentLifecycleCallbacks fragmentLifecycleCallbacks) { this.mLifecycleCallbacksDispatcher.unregisterFragmentLifecycleCallbacks(fragmentLifecycleCallbacks); } /* access modifiers changed from: package-private */ public boolean checkForMenus() { boolean z = false; for (Fragment next : this.mFragmentStore.getActiveFragments()) { if (next != null) { z = isMenuAvailable(next); continue; } if (z) { return true; } } return false; } private boolean isMenuAvailable(Fragment fragment) { return (fragment.mHasMenu && fragment.mMenuVisible) || fragment.mChildFragmentManager.checkForMenus(); } /* access modifiers changed from: package-private */ public LayoutInflater.Factory2 getLayoutInflaterFactory() { return this.mLayoutInflaterFactory; } private class PopBackStackState implements OpGenerator { final int mFlags; final int mId; final String mName; PopBackStackState(String str, int i, int i2) { this.mName = str; this.mId = i; this.mFlags = i2; } public boolean generateOps(ArrayList<BackStackRecord> arrayList, ArrayList<Boolean> arrayList2) { if (FragmentManager.this.mPrimaryNav != null && this.mId < 0 && this.mName == null && FragmentManager.this.mPrimaryNav.getChildFragmentManager().popBackStackImmediate()) { return false; } return FragmentManager.this.popBackStackState(arrayList, arrayList2, this.mName, this.mId, this.mFlags); } } static class StartEnterTransitionListener implements Fragment.OnStartEnterTransitionListener { final boolean mIsBack; private int mNumPostponed; final BackStackRecord mRecord; StartEnterTransitionListener(BackStackRecord backStackRecord, boolean z) { this.mIsBack = z; this.mRecord = backStackRecord; } public void onStartEnterTransition() { int i = this.mNumPostponed - 1; this.mNumPostponed = i; if (i == 0) { this.mRecord.mManager.scheduleCommit(); } } public void startListening() { this.mNumPostponed++; } public boolean isReady() { return this.mNumPostponed == 0; } /* access modifiers changed from: package-private */ public void completeTransaction() { boolean z = this.mNumPostponed > 0; for (Fragment next : this.mRecord.mManager.getFragments()) { next.setOnStartEnterTransitionListener((Fragment.OnStartEnterTransitionListener) null); if (z && next.isPostponed()) { next.startPostponedEnterTransition(); } } this.mRecord.mManager.completeExecute(this.mRecord, this.mIsBack, !z, true); } /* access modifiers changed from: package-private */ public void cancelTransaction() { this.mRecord.mManager.completeExecute(this.mRecord, this.mIsBack, false, false); } } }
java
<filename>data/ecchi/zxoggi4mlofk56w2p.json {"title":"【Tickle】結月ゆ〇りローションくすぐり調教18歳以上!","author":"__azero","description":"ほぼ定点カメラ。","thumb":"//i.iwara.tv/sites/default/files/styles/thumbnail/public/videos/thumbnails/2219737/thumbnail-2219737_0012.jpg?itok=ZDxqXiNm","download":"https://ecchi.iwara.tv/api/video/zxoggi4mlofk56w2p","origin":"https://ecchi.iwara.tv/videos/zxoggi4mlofk56w2p"}
json
{ "@context": { "Period": { "@id": "http://purl.org/onto-ocds/ocds#Period" }, "startDate": { "@id": "http://purl.org/onto-ocds/ocds#startDate", "@type": "http://www.w3.org/2001/XMLSchema#dateTime" }, "endDate": { "@id": "http://purl.org/onto-ocds/ocds#endDate", "@type": "http://www.w3.org/2001/XMLSchema#dateTime" } } }
json
<filename>src/utils/src/unit_config_parser.rs extern crate toml; use std::fs::File; use std::io::prelude::*; use std::io::{Error, ErrorKind}; #[derive(Deserialize)] #[derive(Debug)] struct ConfUnit { #[serde(alias = "Description")] description: Option<String>, #[serde(alias = "Documentation")] documentation: Option<String>, #[serde(alias = "Requires")] requires: Option<String>, #[serde(alias = "Wants")] wants: Option<String>, } #[derive(Deserialize)] #[derive(Debug)] struct ConfService { #[serde(alias = "ExecStart")] exec_start: Option<String>, #[serde(alias = "Sockets")] sockets: Option<String>, #[serde(alias = "Restart")] restart: Option<String>, #[serde(alias = "RestrictRealtime")] restrict_realtime: Option<String>, #[serde(alias = "RebootArgument")] reboot_argument: Option<String>, #[serde(alias = "ExecReload")] exec_reload: Option<String>, #[serde(alias = "OOMScoreAdjust")] oom_score_adjust: Option<String>, #[serde(alias = "RestartSec")] restart_sec: Option<u64>, #[serde(alias = "Slice")] slice: Option<String>, #[serde(alias = "MemoryLimit")] memory_limit: Option<u64>, #[serde(alias = "MemoryLow")] memory_low: Option<u64>, #[serde(alias = "MemoryMin")] memory_min: Option<u64>, #[serde(alias = "MemoryMax")] memory_max: Option<u64>, #[serde(alias = "MemoryHigh")] memory_high: Option<u64>, #[serde(alias = "MemorySwapMax")] memory_swap_max: Option<u64>, } #[derive(Deserialize)] #[derive(Debug)] struct ConfInstall { #[serde(alias = "WantedBy")] wanted_by: Option<String>, #[serde(alias = "Alias")] alias: Option<String>, #[serde(alias = "RequiredBy")] required_by: Option<String>, #[serde(alias = "DefaultInstance")] default_instance: Option<String>, } #[derive(Deserialize)] #[derive(Debug)] pub struct Conf { unit: Option<ConfUnit>, service: Option<ConfService>, install: Option<ConfInstall>, } pub fn unit_file_load(file_path: String) -> Result<Conf, Error> { let mut file = match File::open(file_path) { Ok(f) => f, Err(_e) => { return Err(Error::new(ErrorKind::Other, "Error: Open file failed"));} }; let mut buf = String::new(); match file.read_to_string(&mut buf) { Ok(s) => s, Err(_e) => {return Err(Error::new(ErrorKind::Other, "read file content failed"));} }; let conf: Conf = match toml::from_str(&buf) { Ok(conf) => conf, Err(_e) => {return Err(Error::new(ErrorKind::Other, "translate string to struct failed"));} }; return Ok(conf); } #[cfg(test)] mod tests { use super::*; #[test] fn test_unit_file_load() -> Result<(), Error>{ let file: String = String::from("config.toml"); let conf = match unit_file_load(file) { Ok(conf) => { match conf.Install { Some(c) => assert_eq!(c.wanted_by, Some("dbus".to_string())), None => { return Err(Error::new(ErrorKind::Other, "no install field")); } } } Err(e) => { return Err(Error::new(ErrorKind::Other, e.to_string()));} }; Ok(()) } }
rust
<reponame>aRay33/MyDesign [ { "merged": "/home/rythm/AndroidStudioProjects/Design Kita/app/build/intermediates/res/merged/debug/drawable-v23/abc_control_background_material.xml", "source": "/home/rythm/.android/build-cache/6323ceb2330eac5b24d02cac82f5dfa5e4bbba2e/output/res/drawable-v23/abc_control_background_material.xml" } ]
json
Kanpur, May 15, 2023: The Indian Institute of Technology (IIT) Kanpur, is proud to announce the successful development of an upgraded version of Shuddham, a water purifier-cum-cooler designed to provide affordable and innovative solutions to rural households and urban middle-class society. The product has been developed by the Imagineering Laboratory, IIT Kanpur. Led by Prof. J. Ramkumar, who is also the coordinator for Imagineering Laboratory and Rural Technology Action Group (RuTAG), and Dr. Amandeep Singh, the Research Establishment Officer (REO), the team was approached by Mr. Jitendra Singh Chaudhary from New Unnat India Techno Solution & Innovations Pvt. Ltd. to address the challenge of providing water purification and cooling at affordable rates to the public. Mr. Chaudhary had earlier developed the initial model of Shuddham as a water filter. The IIT Kanpur team addressed its limitations and has improvised it into a low-cost water purifier-cum-cooler. At IIT Kanpur’s Imagineering Laboratory, the invention went through several stages of development to ensure higher efficiency and better purifying capacity. Shuddham is user-friendly, easy to maintain, and economical, and would cost around INR 4000, once launched. The purifier undergoes multi-stage purification, and cooling of the water takes place simultaneously. The upper part of the system is a storage tank for the impure water, while the lower tank is a reserve tank for the purified water. There are three stages of purification: the water passes through a cotton filter in the first stage for the removal of solid impurities, followed by the removal of bad odours and chlorine through a cartridge with activated carbon. The activated carbon was prepared in MedTech Lab, under the Imagineering Laboratory, IIT Kanpur, using coconut shells and a heating furnace called "MITRA." In the next stage, a polymer membrane is used for ion exchange. The purified water is then stored in a lower reserve tank with copper fins that diffuse copper and add medicinal properties to the water. Both tanks are encased in a clay pot that offers natural cooling, further reducing the temperature with the help of a convection fan. Additionally, the system is designed to run on a mini solar plate of 10 watts for areas with limited access to electricity. "The Imagineering Lab's mission is to provide innovative and affordable solutions to the people of India. We are committed to developing products that address the most pressing needs of our society, and Shuddham is a perfect example of this. We are proud to have developed a system that not only provides clean water but also cools it, making it accessible to those who cannot afford both. Our team is continuously working to improve cost-effective products, making them available to everyone in need," says Prof. J Ramkumar, Coordinator of Imagineering Laboratory and Rural Technology Action Group (RuTAG) at IIT Kanpur. Prof. Ramkumar's team is now working on developing a multilayer single filter bulb to reduce the number of stages in the process, further lowering the cost and making the product available to all. The Imagineering Laboratory is a central facility for concept design and product realization at IIT Kanpur. Under the laboratory, there are different labs and centres, including Central Workshop, 4-i Lab, MedTech Lab, Tinkering Lab, and RuTAG, all supporting various innovations in line with the ‘Make in India’ initiative of the Government of India. Shuddham is another remarkable accomplishment from the Imagineering Lab of IIT Kanpur that addresses the challenge of providing clean water and cooling at an affordable cost to rural and urban households. About IIT Kanpur: Indian Institute of Technology (IIT) Kanpur was established on 2nd November 1959 by an Act of Parliament. The institute has a sprawling campus spread over 1055 acres with large pool of academic and research resources spanning across 19 departments, 22 centres, and 3 Interdisciplinary programs in engineering, science, design, humanities, and management disciplines with 540 full-time faculty members and approximately 9000 students. In addition to formal undergraduate and postgraduate courses, the institute has been active in research and development in areas of value to both industry and government. For more information, visit www.iitk.ac.in.
english
<filename>examples/advanced/dub.json { "name": "advanced-plugin", "authors": [ "Mark" ], "dependencies": { "dxx:app" : { "path" : "../.."} }, "subConfigurations": { "dxx:app": "dxx-plugin" }, "debugs" : [ "Plugin","Loader","Module" ], "description": "DXX example module", "copyright": "Copyright © 2018, Mark", "license": "MIT", "targetType": "dynamicLibrary", "versions" : ["DXX_Plugin","DXX_Module"], "targetPath": "bin", "stringImportPaths" : [ "resources" ], "sourceFiles-windows": [ "dxx_advanced.def" ] }
json
interface RunSpiderDialogProps { spider?: Spider; }
typescript
Salmon is a favorite delicacy, which often appears on the festive table. Fans of Japanese cuisine have a special love for this type of fish, because this is the kind of fish that is part of the most famous sushi and rolls. Find out how this product is safe for the figure, you can from this article, which examines the calorie content of the salmon fillet, prepared in various ways. This fish is unique - it can be eaten both raw and slightly salted, and cooked in various ways. Typically, the Japanese cuisine uses the first and second of the listed options. The calorie content of a salmon per 100 grams is 208 kcal - this is the basic number that speaks of fresh fish that has not been subjected to any treatments and preparations. It should be noted that in such fish there are many useful fatty acids, sodium, potassium, calcium, iron, magnesium, as well as vitamins A, B and C. In dietary nutrition is often used this gentle and easy-to-prepare dish - salmon steamed. Its calorific value per 100 g is 187 kcal - less than in fresh fish. This is achieved through the frying of fats during cooking. Grilled salmon is an incredibly tasty and healthy dish! It is 199 kcal per 100 g of product. It should be borne in mind that much depends on the marinade: if you added oil, wine, sugar or ready-made sauces, you increase the final calorie content of the dish. From the point of view of dietary nutrition, the optimal marinade is salt and black pepper. You can also add freshly squeezed lemon juice. Very delicious is salmon, if you cook it in a conventional frying pan. In this case, the calorie content of the dish will be 204 kcal per 100 grams of the ready meal. If you serve to a dish sauces like mayonnaise or ketchup, you significantly increase its caloric value. Extraordinary popularity in different cuts and snacks is salted salmon, which is slightly more high calorie: from 255 to 269 kcal, depending on the method of pickling and marinade. As a rule, salmon is first kept in salt, and then - in vegetable oil, to give the dish a soft and delicate taste. Despite the relatively high calorie content, a couple of times a week should afford such a delicacy, because it is very useful for health.
english
.indexTitle { text-align: center; } .indexBody { display: flex; flex-direction: column; height: 100vh; } .indexFrame { flex: auto; height: 100vh; } .itembody { margin-left: 8px; } .appDiv { display: flex; flex-direction: column; } .appSelect { width: 180px; height: 30px; overflow: hidden; } .appSelect select { padding-left: 10px; width: 180px; -webkit-appearance: none; -moz-appearance: none; background: transparent; } button { width: 180px; color: #ffffff; } .demoBody { display: flex; flex-direction: row; flex-wrap: wrap; } .btnContainer { display: flex; flex-direction: column; } .divdemofunction { flex: auto; display: flex; flex-direction: row; } .divFunction { flex: 1; } .divDemo{ text-align: center; } #demoBtn { height: 50px; }
css
// Copyright 2019 JanusGraph Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.janusgraph.diskstorage.inmemory; import com.google.common.base.Preconditions; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.janusgraph.diskstorage.BackendException; import org.janusgraph.diskstorage.Entry; import org.janusgraph.diskstorage.EntryList; import org.janusgraph.diskstorage.StaticBuffer; import org.janusgraph.diskstorage.keycolumnvalue.*; import org.janusgraph.diskstorage.util.RecordIterator; import org.apache.commons.lang.StringUtils; import org.janusgraph.diskstorage.util.StaticArrayBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.*; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import static java.util.zip.Deflater.BEST_SPEED; import static org.janusgraph.diskstorage.StaticBuffer.ARRAY_FACTORY; /** * An in-memory implementation of {@link KeyColumnValueStore}. * This implementation is thread-safe. All data is held in memory, which means that the capacity of this store is * determined by the available heap space. No data is persisted and all data lost when the jvm terminates or store closed. * * The implementation also provides basic dump/restore capabilities, so that a "snapshot" of its contents can be saved to filesystem * and loaded back. * * Finally, it provides a means to assess the fragmentation of the data across allocated memory storage, and to defragment it if required. * NOTE: with usual "populate then query" and "add only" use cases, fragmentation is of no concern. Only if your application performs * a lot of deletes interleaved with additions for a prolong periods of time, and if you are experiencing a "bigger than expected" memory * footprint, is it worth looking at fragmentation report. * */ public class InMemoryKeyColumnValueStore implements KeyColumnValueStore { private static final boolean USE_COMPRESSION = true; private static final int READ_BUFFER_SIZE = 1024 * 1024 * 8; private static final int WRITE_BUFFER_SIZE = READ_BUFFER_SIZE; private static final Logger log = LoggerFactory.getLogger(InMemoryKeyColumnValueStore.class); private final String name; private final ConcurrentNavigableMap<StaticBuffer, InMemoryColumnValueStore> kcv; public InMemoryKeyColumnValueStore(final String name) { Preconditions.checkArgument(StringUtils.isNotBlank(name)); this.name = name; this.kcv = new ConcurrentSkipListMap<>(); } @Override public EntryList getSlice(KeySliceQuery query, StoreTransaction txh) throws BackendException { InMemoryColumnValueStore cvs = kcv.get(query.getKey()); if (cvs == null) return EntryList.EMPTY_LIST; else return cvs.getSlice(query, txh); } @Override public Map<StaticBuffer,EntryList> getSlice(List<StaticBuffer> keys, SliceQuery query, StoreTransaction txh) throws BackendException { Map<StaticBuffer,EntryList> result = Maps.newHashMap(); for (StaticBuffer key : keys) result.put(key,getSlice(new KeySliceQuery(key,query),txh)); return result; } @Override public void mutate(StaticBuffer key, List<Entry> additions, List<StaticBuffer> deletions, StoreTransaction txh) throws BackendException { InMemoryColumnValueStore cvs = kcv.get(key); if (cvs == null) { kcv.putIfAbsent(key, new InMemoryColumnValueStore()); cvs = kcv.get(key); } cvs.mutate(additions, deletions, txh); } @Override public void acquireLock(StaticBuffer key, StaticBuffer column, StaticBuffer expectedValue, StoreTransaction txh) throws BackendException { throw new UnsupportedOperationException(); } @Override public KeyIterator getKeys(final KeyRangeQuery query, final StoreTransaction txh) throws BackendException { return new RowIterator(kcv.subMap(query.getKeyStart(), query.getKeyEnd()).entrySet().iterator(), query, txh); } @Override public KeyIterator getKeys(SliceQuery query, StoreTransaction txh) throws BackendException { return new RowIterator(kcv.entrySet().iterator(), query, txh); } @Override public KeySlicesIterator getKeys(MultiSlicesQuery queries, StoreTransaction txh) throws BackendException { throw new UnsupportedOperationException(); } @Override public String getName() { return name; } public void clear() { kcv.clear(); } @Override public void close() throws BackendException { kcv.clear(); } public InMemoryKeyColumnValueStoreFragmentationReport createFragmentationReport(StoreTransaction txh) throws BackendException { int totalPageCount = 0; int numMultipageStores = 0; int[] pageLevels = new int[]{0, 1, 3, 5, 10, 100, 500}; int[] pageCounts = new int[pageLevels.length + 1]; int[] compressablePageLevels = new int[]{0, 1, 3, 5, 10, 100, 500}; int[] compressablePageCounts = new int[compressablePageLevels.length + 1]; int[] reductionLevels = new int[]{0, 1, 3, 5, 10, 100, 500}; int[] reductionCounts = new int[reductionLevels.length + 1]; int[] entryLevels = new int[]{3, 5, 10, 100, 500, 5000, 20000, 100000, 500000, 1000000}; int[] entryCounts = new int[entryLevels.length + 1]; List<InMemoryColumnValueStore> storesToDefragment = new ArrayList<>(0); int keysByteSize = 0; int numFragmentedStores = 0; int totalFragmentedPages = 0; int numCompressableStores = 0; int totalCompressablePages = 0; int totalAchievablePageReduction = 0; for (Map.Entry<StaticBuffer, InMemoryColumnValueStore> e : kcv.entrySet()) { keysByteSize += e.getKey().length(); int i; int numEntries = e.getValue().numEntries(txh); for (i = 0; i < entryLevels.length; i++) { if (numEntries <= entryLevels[i]) { break; } } entryCounts[i]++; if (e.getValue() instanceof InMemoryColumnValueStore) { InMemoryColumnValueStore pbCvs = (InMemoryColumnValueStore) e.getValue(); SharedEntryBufferFragmentationReport fr = pbCvs.createFragmentationReport(txh); int pageCount = fr.getPageCount(); totalPageCount += pageCount; if (pageCount > 1) { numMultipageStores++; } for (i = 0; i < pageLevels.length; i++) { if (pageCount <= pageLevels[i]) { break; } } pageCounts[i]++; if (fr.getFragmentedPageCount() > 0) { numFragmentedStores++; totalFragmentedPages += fr.getFragmentedPageCount(); if (fr.getCompressableChunksCount() > 0) { numCompressableStores++; totalCompressablePages += fr.getCompressablePageCount(); totalAchievablePageReduction += fr.getAchievablePageReduction(); storesToDefragment.add(pbCvs); for (i = 0; i < compressablePageLevels.length; i++) { if (fr.getCompressablePageCount() <= compressablePageLevels[i]) { break; } } compressablePageCounts[i]++; for (i = 0; i < reductionLevels.length; i++) { if (fr.getAchievablePageReduction() <= reductionLevels[i]) { break; } } reductionCounts[i]++; } } } } return new InMemoryKeyColumnValueStoreFragmentationReport.Builder().name(name) .numStores(kcv.size()) .numMultipageStores(numMultipageStores) .totalPageCount(totalPageCount) .numFragmentedStores(numFragmentedStores) .totalFragmentedPages(totalFragmentedPages) .numCompressableStores(numCompressableStores) .totalCompressablePages(totalCompressablePages) .totalAchievablePageReduction(totalAchievablePageReduction) .keysByteSize(keysByteSize) .entryLevels(entryLevels) .entryCounts(entryCounts) .pageLevels(pageLevels) .pageCounts(pageCounts) .compressablePageLevels(compressablePageLevels) .compressablePageCounts(compressablePageCounts) .reductionLevels(reductionLevels) .reductionCounts(reductionCounts) .storesToDefragment(storesToDefragment) .build(); } public void quickDefragment(Collection<InMemoryColumnValueStore> stores, StoreTransaction txh) throws BackendException { for (InMemoryColumnValueStore cvs : stores) { cvs.quickDefragment(txh); } } public void quickDefragment(StoreTransaction txh) throws BackendException { quickDefragment(kcv.values(), txh); } private static OutputStream compressedOutputStream(OutputStream streamToWrap) { return new DeflaterOutputStream(streamToWrap, new Deflater(BEST_SPEED, true), true); } private static InputStream compressedInputStream(InputStream streamToWrap) { return new InflaterInputStream(streamToWrap, new Inflater(true)); } public void dumpTo(Path storePath, ForkJoinPool parallelOperationsExecutor) { if (kcv.size() < 1) return; int numChunks = Runtime.getRuntime().availableProcessors() * 2; int chunkSize = kcv.size() > 1000 ? kcv.size() / numChunks : kcv.size(); ArrayList<List<Map.Entry<StaticBuffer, InMemoryColumnValueStore>>> chunks = Lists.newArrayList(Iterators.partition(kcv.entrySet().iterator(), chunkSize)); IntStream.range(0, chunks.size()).mapToObj(i -> { Path filePath = Paths.get(storePath.toString(), getName() + "_" + i); return parallelOperationsExecutor.submit(() -> dumpChunk(filePath, chunks.get(i))); }).collect(Collectors.toList()) //collecting here to make sure all tasks are submitted eagerly .stream().map(ForkJoinTask::join).collect(Collectors.toList()); } private void dumpChunk(Path filePath, List<Map.Entry<StaticBuffer, InMemoryColumnValueStore>> chunk) { if (log.isDebugEnabled()) { log.debug("number of column stores in chunk " + filePath + ": " + chunk.size() + " " + Thread.currentThread().getName()); } try (OutputStream rawStream = Files.newOutputStream(filePath, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); BufferedOutputStream bufferedStream = new BufferedOutputStream(rawStream, WRITE_BUFFER_SIZE); OutputStream compressedStream = USE_COMPRESSION ? compressedOutputStream(bufferedStream) : null; DataOutputStream out = new DataOutputStream(USE_COMPRESSION ? compressedStream : bufferedStream)) { //write number of kcvs out.writeInt(chunk.size()); for (Map.Entry<StaticBuffer, InMemoryColumnValueStore> e : chunk) { //write key length then actual key bytes out.writeInt(e.getKey().length()); out.write(e.getKey().as(ARRAY_FACTORY)); InMemoryColumnValueStore sbKcv = (InMemoryColumnValueStore) e.getValue(); sbKcv.dumpTo(out); } if (log.isDebugEnabled()) { log.debug("finished writing chunk " + filePath + " " + Thread.currentThread().getName()); } } catch (IOException ex) { throw new RuntimeException(ex); } } public static InMemoryKeyColumnValueStore readFrom(Path storePath, String name, ForkJoinPool parallelOperationsExecutor) throws IOException { InMemoryKeyColumnValueStore store = new InMemoryKeyColumnValueStore(name); Files.list(storePath).map(p -> parallelOperationsExecutor.submit(() -> readChunkFrom(p, store))) .collect(Collectors.toList()).stream() //force it to submit all tasks .map(ForkJoinTask::join).collect(Collectors.toList()); return store; } private static int readChunkFrom(Path filePath, InMemoryKeyColumnValueStore store) { try (InputStream rawStream = Files.newInputStream(filePath, StandardOpenOption.READ); BufferedInputStream bufferedStream = new BufferedInputStream(rawStream, READ_BUFFER_SIZE); InputStream compressedStream = USE_COMPRESSION ? compressedInputStream(bufferedStream) : null; DataInputStream in = new DataInputStream(USE_COMPRESSION ? compressedStream : bufferedStream)) { int numKcvs = in.readInt(); if (log.isDebugEnabled()) { log.debug("number of column stores in chunk " + filePath + ": " + numKcvs + " " + Thread.currentThread().getName()); } for (int i = 0; i < numKcvs; i++) { int keyLength = in.readInt(); if (log.isDebugEnabled()) { log.debug("column " + i + " key size is " + keyLength); } byte[] keyData = new byte[keyLength]; BufferPageUtils.readWholeArray(in, keyData); //NOTE: here we know that kcv is a concurrent map so safe to put in parallel from different chunks store.kcv.put(StaticArrayBuffer.of(keyData), InMemoryColumnValueStore.readFrom(in)); } if (log.isDebugEnabled()) { log.debug("finished reading chunk " + filePath + " " + Thread.currentThread().getName()); } return numKcvs; } catch (Exception ex) { throw new RuntimeException("Problem while reading chunk " + filePath + " of store " + store.getName(), ex); } } private static class RowIterator implements KeyIterator { private final Iterator<Map.Entry<StaticBuffer, InMemoryColumnValueStore>> rows; private final SliceQuery columnSlice; private final StoreTransaction transaction; private Map.Entry<StaticBuffer, InMemoryColumnValueStore> currentRow; private Map.Entry<StaticBuffer, InMemoryColumnValueStore> nextRow; private boolean isClosed; public RowIterator(Iterator<Map.Entry<StaticBuffer, InMemoryColumnValueStore>> rows, @Nullable SliceQuery columns, final StoreTransaction transaction) { this.rows = Iterators.filter(rows, entry -> entry != null && !entry.getValue().isEmpty(transaction)); this.columnSlice = columns; this.transaction = transaction; } @Override public RecordIterator<Entry> getEntries() { ensureOpen(); if (columnSlice == null) throw new IllegalStateException("getEntries() requires SliceQuery to be set."); final KeySliceQuery keySlice = new KeySliceQuery(currentRow.getKey(), columnSlice); return new RecordIterator<Entry>() { private final Iterator<Entry> items = currentRow.getValue().getSlice(keySlice, transaction).iterator(); @Override public boolean hasNext() { ensureOpen(); return items.hasNext(); } @Override public Entry next() { ensureOpen(); return items.next(); } @Override public void close() { isClosed = true; } @Override public void remove() { throw new UnsupportedOperationException("Column removal not supported"); } }; } @Override public boolean hasNext() { ensureOpen(); if (null != nextRow) return true; while (rows.hasNext()) { nextRow = rows.next(); List<Entry> entries = nextRow.getValue().getSlice(new KeySliceQuery(nextRow.getKey(), columnSlice), transaction); if (null != entries && 0 < entries.size()) break; } return null != nextRow; } @Override public StaticBuffer next() { ensureOpen(); Preconditions.checkNotNull(nextRow); currentRow = nextRow; nextRow = null; return currentRow.getKey(); } @Override public void close() { isClosed = true; } private void ensureOpen() { if (isClosed) throw new IllegalStateException("Iterator has been closed."); } @Override public void remove() { throw new UnsupportedOperationException("Key removal not supported"); } } }
java
<reponame>sheymanidze/Mini-Project-Landing-Page * { margin:0; padding:0; } body { font-family: 'Times New Roman', Times, serif; position: relative; background-color: #ffffff; font-size: 23px; color:#4d0000; } header { justify-content: flex-end; } header, footer { background-color: lightcoral; display:flex; padding: 15px; color: #ffffff; } a { color: #ffffff; padding: 12px; } a:link { text-decoration: none; } h1 { text-align: center; color:#4d0000; } img { margin:center; height: 300px; width: 400px; display: block; margin: 20px auto; border: 5px solid #4d0000; padding: 20px solid lightcoral; } figure { margin-bottom: 40px; } figcaption { text-align: center; } section { padding: 50px; text-align: center; background: silver; color:#4d0000; margin-top: auto; font-size: 20px; border-top: 3px solid darkgray; } label { display: inline; width: 100px; } form { margin: 0 auto; margin-top: 2%; width: 500px; padding: 10px; border: 3px solid lightcoral; border-radius: 20px; } input { box-sizing: border-box; width: 300px; border: 1px solid #4d0000; } button { height: 30px; width: 100px; background-color:lightcoral; color:#ffffff; text-align: center; margin-top: 2%; } footer { justify-content: center; font-size: 15px; } .text-right { text-align: right; }
css
<reponame>hammer/data_pipeline import logging from distutils.util import strtobool class SaferCast(object): """ SaferCast represents a customised cast function with an optional way to bypass an exception by using a fallback value. This base class wraps the generalisation and common functions. """ def _catch_with_fallback(self, func, value, fallback): """ It executes func(value) wrapped by try catch finally if fallback is not None :param func: function to execute with at least one formal parameter :param value: the value to be passed to func(value) :param fallback: if is not None then the fallback will be used instead raising exceptions :return: func(value) if it raises an exception and fallback is None the exception is thrown if fallback is not None then fallback will be returned if func(value) raises exceptions """ if fallback is not None: v = fallback try: v = func(value) except: self._logger.warning("fallback '%s' was used as the str value to cast '%s' but caused an exception", v, value) pass finally: return v else: return func(value) def __init__(self, func, with_fallback=None): """ Create an object representing a higher order funcion calling func bypassing exceptions if with_fallback is not None and returning the later instead the raised one. :param func: the function to be used later :param with_fallback: if is not None func(v) will be wrapped and if exception will return with_fallback """ self._logger = logging.getLogger(__name__) if callable(func): self._logger.debug("save callable object and set lambda for a later use") self._fallback = lambda v: self._catch_with_fallback(func, v, with_fallback) else: msg = "constructor parameter must be a callable, function or method (lambda included)" self._logger.debug(msg + ", but you passed %s", str(type(func))) raise TypeError(msg) def __call__(self, value): """ call func(value) with_fallback if it is not None :param value: :return: func(value) or with_fallback if an exception was thrown """ return self._fallback(value) class SaferBool(SaferCast): """ safer way to cast to a boolean from a string. the string provided is not case-sensitive The domain to mean True is defined as: 'true', '1', 't', 'y', 'yes' and to mean False is defined as: 'false', '0', 'f', 'n', 'no'. If with_fallback is None and string is not in either True domain or False domain a ValueError will be raised """ @staticmethod def _str_to_boolean(s): return bool(strtobool(s.lower())) def __init__(self, with_fallback): super(SaferBool, self).__init__(SaferBool._str_to_boolean, with_fallback=with_fallback) class SaferInt(SaferCast): def __init__(self, with_fallback): super(SaferInt, self).__init__(int, with_fallback=with_fallback) class SaferFloat(SaferCast): def __init__(self, with_fallback): super(SaferFloat, self).__init__(float, with_fallback=with_fallback)
python
Using widely-available audio editing software (I prefer Audacity for simple tasks), it's possible to speed up or slow down any recording, while leaving the pitch the same. Aside from enabling advertisers to include lengthy warnings read lightning-quick at the end of their ads (the ones that say "side-effects-may-include-drowsiness-irritibility-or-blah-blah-blah," etc.), time-stretching technology allows digital DJs to beatmatch songs, and producers to record a part at a lower tempo and then speed it up to make it sound "tighter." You can't tell the difference... or can you? Researchers at the University of Amsterdam have constructed an online study that attempts to determine whether humans can identify music that has been manipulated in this way. If you have about 20 spare minutes and feel like helping them out, participate. If you do so before April 15th, you'll be entered to win one of 5 Amazon gift certificates (no dollar amount indicated). When they're available, the results will be posted here. The Listening Experiment (image from stretchbreak)
english
Doctors have discovered a way to potentially prevent the spread of glioblastoma – the deadliest form of brain cancer, Medical News Today reported. In a study published in the journal Nature Materials, researchers developed special nanofibers, made out of polycaprolactone (PCL) polymer surrounded by a polyurethane. These nanofibers were meant to mimic the blood vessels and nerve fibers that glioblastoma cells typically travel along within the brain. "The cancer cells normally latch onto these natural structures and ride them like a monorail to other parts of the brain," said study author Ravi Bellamkonda, professor and chair of the Wallace H. Coulter Department of Biomedical Engineering at Georgia Tech and Emory University in Atlanta. "By providing an attractive alternative fiber, we can efficiently move the tumors along a different path to a destination that we choose. " Researchers implanted the nanofibers into the brains of rats infected with human glioblastomas and compared them to a group of rats implanted with nanofibers not made with PCL, according to Medical News Today. After 18 days, rats implanted with PCL nanofibers showed significant reductions in tumor size compared to rats treated with non-PCL nanofibers. Instead of travelling along the brain’s blood vessels and nerve fibers to spread to other parts of the brain, the glioblastoma cells travelled along the nanofiber implants into a “tumor collector” that the researchers had implanted outside the brain. The collector contained a gel toxic to cancer cells and effectively killed the spreading gioblastoma. Researchers said they hope this technique may someday provide people an opportunity to live with certain inoperable cancers. However, they noted it could be more than 10 years before the technique is able to be used in a clinical setting. "Perhaps with ideas like this, we may be able to live with cancer just as we live with diabetes or high blood pressrue," Bellamkonda said.
english
######################################## # Automatically generated, do not edit. ######################################## from pyvisdk.thirdparty import Enum VirtualMachineHtSharing = Enum( 'any', 'internal', 'none', )
python
/** * Created by <NAME> on 5/10/2016. */ import bodyParser from 'body-parser'; import cors from 'cors'; import dotenv from 'dotenv'; import express from 'express'; import http from 'http'; import jwToken from '../services/token'; dotenv.config(); const env = process.env; const environment = env.DEFAULT_ENV; const host: string = env[`${environment}_SERVER`] || 'localhost'; const port: number = Number(env[`${environment}_SERVER_PORT`]) || 3000; const app = express(); const router = express.Router(); const unprotectedPath = [ '/', '/api/customers/login', '/api/customers/register', '/api/members/login' ]; app.use(cors()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(jwToken.jwtExpress.unless({ path: unprotectedPath })); require('../routes/main')(app, router); function startServer() { http.createServer(app).listen(port); console.log('Server running at http://' + host + ':' + port + '/'); } export default startServer;
typescript
package com.ms.silverking.cloud.dht.client.crypto; public interface Encrypter { public byte[] encrypt(byte[] bytesToStore); }
java
{ "id": 69211938, "name": "Orka-Server", "fullName": "haikarthikssk/Orka-Server", "owner": { "login": "haikarthikssk", "id": 6438247, "avatarUrl": "https://avatars2.githubusercontent.com/u/6438247?v=3", "gravatarId": "", "url": "https://api.github.com/users/haikarthikssk", "htmlUrl": "https://github.com/haikarthikssk", "followersUrl": "https://api.github.com/users/haikarthikssk/followers", "subscriptionsUrl": "https://api.github.com/users/haikarthikssk/subscriptions", "organizationsUrl": "https://api.github.com/users/haikarthikssk/orgs", "reposUrl": "https://api.github.com/users/haikarthikssk/repos", "receivedEventsUrl": "https://api.github.com/users/haikarthikssk/received_events", "type": "User" }, "private": false, "htmlUrl": "https://github.com/haikarthikssk/Orka-Server", "description": "Raspberry Pi Monitor and Controller", "fork": false, "url": "https://api.github.com/repos/haikarthikssk/Orka-Server", "forksUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/forks", "teamsUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/teams", "hooksUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/hooks", "eventsUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/events", "tagsUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/tags", "languagesUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/languages", "stargazersUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/stargazers", "contributorsUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/contributors", "subscribersUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/subscribers", "subscriptionUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/subscription", "mergesUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/merges", "downloadsUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/downloads", "deploymentsUrl": "https://api.github.com/repos/haikarthikssk/Orka-Server/deployments", "createdAt": "2016-09-26T04:10:46.000Z", "updatedAt": "2017-03-06T19:24:56.000Z", "pushedAt": "2016-10-12T06:10:17.000Z", "gitUrl": "git://github.com/haikarthikssk/Orka-Server.git", "sshUrl": "git@github.com:haikarthikssk/Orka-Server.git", "cloneUrl": "https://github.com/haikarthikssk/Orka-Server.git", "svnUrl": "https://github.com/haikarthikssk/Orka-Server", "homepage": "https://haikarthikssk.github.io/Orka-Server/", "size": 3014, "stargazersCount": 22, "watchersCount": 22, "language": "JavaScript", "hasIssues": true, "hasDownloads": true, "hasWiki": true, "hasPages": true, "forksCount": 1, "mirrorUrl": null, "openIssuesCount": 0, "openIssues": 0, "watchers": 22, "defaultBranch": "master", "permissions": { "admin": false, "push": false, "pull": true }, "license": { "key": "mit", "name": "MIT License", "spdxId": "MIT", "url": "https://api.github.com/licenses/mit", "featured": true }, "networkCount": 1, "subscribersCount": 3, "status": 200, "packageJSON": { "name": "orka", "productName": "Orka Server", "description": "Orka Monitor and Controller", "version": "0.1.0", "author": "<NAME>", "copyright": "MIT License", "main": "server.js", "dependencies": { "electron-settings": "^2.1.1", "request": "^2.74.0", "socket.io": "^1.4.8", "socket.io-client": "^1.4.8" }, "scripts": { "start": "electron .", "build": "electron-packager . --out=dist --asar --overwrite --all" }, "devDependencies": { "electron-packager": "^8.0.0", "electron": "^1.0.1", "eslint": "^3.3.1", "eslint-config-standard": "^6.0.0-beta.3", "eslint-plugin-import": "^1.14.0", "eslint-plugin-promise": "^2.0.1", "eslint-plugin-react": "^6.1.2", "eslint-plugin-standard": "^2.0.0" } }, "packageStatus": 200, "firstCommit": { "sha": "78a81b4e80fdc437a07429c46751d2479048392a", "commit": { "author": { "name": "<NAME>", "email": "<EMAIL>", "date": "2016-09-26T04:10:47Z" }, "committer": { "name": "<NAME>", "email": "<EMAIL>", "date": "2016-09-26T04:10:47Z" }, "message": "Initial commit", "tree": { "sha": "854de754bdea47e7f68225b7731650770cd0764a", "url": "https://api.github.com/repos/haikarthikssk/Orka-Server/git/trees/854de754bdea47e7f68225b7731650770cd0764a" }, "url": "https://api.github.com/repos/haikarthikssk/Orka-Server/git/commits/78a81b4e80fdc437a07429c46751d2479048392a", "commentCount": 0 } }, "filename": "haikarthikssk___Orka-Server.json", "hasProjects": true, "lastFetchedAt": "2017-05-04T21:18:17.019Z", "packageLastFetchedAt": "2017-05-04T21:56:46.363Z" }
json
<gh_stars>1-10 #include "carlikerobot.hpp" #define DEBUG false namespace gazebo{ namespace carlikerobot{ /* axletrack : the distance between the wheels as you look the car frontal wheelbase : the distance between the wheels as you look the car from side */ /// FRONT CFrontWheelsSpeed::CFrontWheelsSpeed(float axletrack, float wheelbase, float wheelradius, physics::JointPtr jointRight, physics::JointPtr jointLeft, common::PID pidRight, common::PID pidLeft, physics::ModelPtr model) { this->_axletrack = axletrack; this->_wheelbase = wheelbase; this->_wheelradius = wheelradius; this->_jointRight = jointRight; this->_jointLeft = jointLeft; this->_pidRight = pidRight; this->_pidLeft = pidLeft; this->_model = model; this->_model->GetJointController()->SetVelocityPID(this->_jointRight->GetScopedName(), this->_pidRight); this->_model->GetJointController()->SetVelocityPID(this->_jointLeft->GetScopedName(), this->_pidLeft); } void CFrontWheelsSpeed::update(float steeringAngle_deg, float speed_meter_per_sec) { // Convert from m/s in rads/sec float speed_rad_per_sec = speed_meter_per_sec / this->_wheelradius; float l_K = tan(steeringAngle_deg / 180.0 * PI)/this->_wheelbase; float l_Vr_R = speed_rad_per_sec*sqrt((pow(2.0-this->_axletrack*l_K,2.0)+pow(2.0*l_K*this->_wheelbase,2))/(4.0*(1.0+pow(_wheelbase*l_K,2.0)))); float l_Vr_L = speed_rad_per_sec*sqrt((pow(2.0+_axletrack*l_K,2.0)+pow(2.0*l_K*_wheelbase,2))/(4.0*(1.0+pow(_wheelbase*l_K,2.0)))); if(DEBUG) { ROS_INFO("Front speed:\t\t[%f, %f]", l_Vr_L, l_Vr_R); } _model->GetJointController()->SetVelocityTarget(this->_jointLeft->GetScopedName(),l_Vr_L); _model->GetJointController()->SetVelocityTarget(this->_jointRight->GetScopedName(),l_Vr_R); } /// REAR CRearWheelsSpeed::CRearWheelsSpeed(float f_axletrack, float f_wheelbase, float f_wheelradius, physics::JointPtr f_jointRight, physics::JointPtr f_jointLeft, common::PID f_pidRight, common::PID f_pidLeft, physics::ModelPtr f_model) { this->_axletrack = f_axletrack; this->_wheelbase = f_wheelbase; this->_wheelradius = f_wheelradius; this->_jointRight = f_jointRight; this->_jointLeft = f_jointLeft; this->_pidRight = f_pidRight; this->_pidLeft = f_pidLeft; this->_model = f_model; this->_model->GetJointController()->SetVelocityPID(this->_jointRight->GetScopedName(), this->_pidRight); this->_model->GetJointController()->SetVelocityPID(this->_jointLeft->GetScopedName(), this->_pidLeft); } void CRearWheelsSpeed::update(float f_steerAngle_deg,float f_Vr_m_meterpsec) { float l_Vr_m_radpsec = f_Vr_m_meterpsec/_wheelradius; float l_K = tan(f_steerAngle_deg/180.0*PI)/this->_wheelbase; float l_Vr_R = l_Vr_m_radpsec*(2-_axletrack*l_K)/2; float l_Vr_L = l_Vr_m_radpsec*(2+_axletrack*l_K)/2; if(DEBUG) { ROS_INFO("Rear speed:\t\t[%f, %f]",l_Vr_L, l_Vr_R); } this->_model->GetJointController()->SetVelocityTarget(this->_jointLeft->GetScopedName(),l_Vr_L); this->_model->GetJointController()->SetVelocityTarget(this->_jointRight->GetScopedName(),l_Vr_R); } /// STEERING ANGLE CSteerWheelsAngle::CSteerWheelsAngle(float f_axletrack, float f_wheelbase, physics::JointPtr f_jointRight, physics::JointPtr f_jointLeft, common::PID f_pidRight, common::PID f_pidLeft, physics::ModelPtr f_model) { this->_axletrack = f_axletrack; this->_wheelbase = f_wheelbase; this->_jointRight = f_jointRight; this->_jointLeft = f_jointLeft; this->_pidRight = f_pidRight; this->_pidLeft = f_pidLeft; this->_model = f_model; this->_model->GetJointController()->SetPositionPID(this->_jointRight->GetScopedName(), this->_pidRight); this->_model->GetJointController()->SetPositionPID(this->_jointLeft->GetScopedName(), this->_pidLeft); } void CSteerWheelsAngle::update(float f_steerAngle_deg) { float l_K = tan(f_steerAngle_deg / 180.0 * PI) / this->_wheelbase; float l_steer_right = -1.0 * atan(_wheelbase * 2.0 * l_K / (2.0 - this->_axletrack * l_K)); float l_steer_left = -1.0 * atan(_wheelbase * 2.0 * l_K / (2.0 + this->_axletrack * l_K)); if(DEBUG) { ROS_INFO("Angle:\t\t\t[%f, %f]", l_steer_left*180.0/PI,l_steer_right*180.0/PI); ROS_INFO_STREAM("===================================================================="); } _model->GetJointController()->SetPositionTarget(this->_jointLeft->GetScopedName(), l_steer_left); _model->GetJointController()->SetPositionTarget(this->_jointRight->GetScopedName(), l_steer_right); } }; // namespace carlikerobot } // namespace gazebo
cpp
{ "name": "gitbook-plugin-coolimages", "description": "Gitbook plugin to add images with cool format", "main": "index.js", "license": "MIT", "homepage": "https://github.com/amartinr1977/gitbook-plugin-coolimages", "version": "1.1.1", "engines": { "gitbook": ">2.5.0" }, "keywords": [ "gitbook", "plugin", "vitalinux", "amartinromero", "coolimages" ], "author": { "name": "<NAME>", "email": "<EMAIL>" }, "bugs": { "url": "https://github.com/amartinr1977/gitbook-plugin-coolimages/issues" }, "gitbook": { "properties": {} } }
json
Shah Rukh Khan, Deepika Padukone and John Abraham starrer Pathaan have surpassed Prabhas, Anushka Shetty starrer Baahubali 2's Hindi Nett Box Office collection. The producer of Baahubali 2 has reacted to the same. Shah Rukh Khan has dethroned Prabhas from the highest-grossing actor's title. Shah Rukh Khan starrer Pathaan has taken the spot of being the highest-grossing Hindi movie of all time from Prabhas starrer movie Baahubali 2. It was just a couple of days ago that Pathaan crossed the mark of Baahubali 2 Hindi dubbed version's earnings. Fans of Shah Rukh Khan have been heaping praises and showering love on the actor who made his comeback, in a way after four years. Shah Rukh Khan's fans and family members have been celebrating the same. Even Baahubali 2 producer has reacted to Pathaan breaking the record of the SS Rajamouli movie. Entertainment News has been full of updates on the box office collection of Shah Rukh Khan, Deepika Padukone and John Abraham starrer Pathaan. And now that the movie has crossed Baahubali 2's nett collections of the Hindi version, it has yet again grabbed headlines. Prabhas starrer Baahubali 2 Hindi did a business of Rs 510.99 crores. On the other hand, Pathaan has now done a business of Rs 528.89 crores. Fans are rejoicing the same and even Gauri Khan tweeted about it. On the other hand, the producer of SS Rajamouli-directed Baahubali 2, Shobhu Yarlagadda has reacted to Shah Rukh Khan's movie Pathaan beating the record. He congratulated SRK, Siddharth Anand and the team of Pathaan on the same. Shobhu also added that he is glad that it was SRK who broke the record. Check out the tweets here: Meanwhile, on the work front, Shah Rukh Khan is busy working on his next two projects which are Dunki and Jawan. While Dunki is directed by Rajkumar Hirani, Jawan is being helmed by Atlee. Dunki also stars Taapsee Pannu in it. Jawan stars Vijay Sethupathi and Nayanthara. Bigg Boss 16 fame MC Stan and Priyanka Chahar Choudhary grabbed headlines for allegedly being approached for Jawan and Dunki. Stay tuned to BollywoodLife for the latest scoops and updates from Bollywood, Hollywood, South, TV and Web-Series. Click to join us on Facebook, Twitter, Youtube and Instagram. Also follow us on Facebook Messenger for latest updates.
english
<reponame>collinjackson93/ApartmentHunter<filename>public/dependency/angular-snap/angular-snap-only.css snap-content, [snap\:content], [snap-content], [data-snap-content], [x-snap-content], .snap-content, .x-snap-content, snap-drawers, [snap\:drawers], [snap-drawers], [data-snap-drawers], [x-snap-drawers], .snap-drawers, .x-snap-drawers { position: absolute; height: auto; top: 0; bottom: 0; width: 100%; left: 0; right: 0; } snap-drawer, [snap\:drawer], [snap-drawer], [data-snap-drawer], [x-snap-drawer], .snap-drawer, .x-snap-drawer { position: absolute; height: auto; top: 0; bottom: 0; overflow: auto; -webkit-transition: top 0.2s linear; -moz-transition: top 0.2s linear; -o-transition: top 0.2s linear; transition: top 0.2s linear; -webkit-transition: bottom 0.2s linear; -moz-transition: bottom 0.2s linear; -o-transition: bottom 0.2s linear; transition: bottom 0.2s linear; -webkit-overflow-scrolling: touch; -moz-overflow-scrolling: touch; -o-overflow-scrolling: touch; overflow-scrolling: touch; }
css
{ "id": 2094, "surahNumber": "017", "ayatNumber": "065", "arabic": "إِنَّ عِبَادِي لَيْسَ لَكَ عَلَيْهِمْ سُلْطَانٌ ۚ وَكَفَىٰ بِرَبِّكَ وَكِيلًا", "english": "\"Verily! My slaves (i.e. the true believers of Islamic Monotheism), you have no authority over them. And All-Sufficient is your Lord as a Guardian.\"", "bengali": "আমার বান্দাদের উপর তোর কোন ক্ষমতা নেই আপনার পালনকর্তা যথেষ্ট কার্যনির্বাহী।" }
json
<gh_stars>1-10 const jsf = require('json-schema-faker'); function deref(_schema, validate) { let schema = _schema; if (typeof schema === undefined) { throw new Error(); } if (!validate.refs) { throw new Error(`cyclic dependency ${validate.root.schema.id} -> ${schema.$ref}`); } if (Array.isArray(schema)) { schema.forEach((item, i) => { schema[i] = deref(item, validate); }); return schema; } if (typeof schema === 'object' && schema !== null) { if (schema.$ref) { const ref = schema.$ref.replace(/#\/?$/, ''); // { normalizeId } from 'ajv/lib/compile/resolve' const resolved = validate.refVal[validate.refs[ref]]; if (typeof resolved === 'function') { return deref(resolved.schema, resolved); } else { return resolved; } } if (schema.properties) { Object.keys(schema.properties).forEach(key => { schema.properties[key] = deref(schema.properties[key], validate); }); } if (schema.patternProperties) { Object.keys(schema.patternProperties).forEach(key => { schema.patternProperties[key] = deref(schema.patternProperties[key], validate); }); } // won't deref $ref in definitions and links, this will make jsf try to deref it and throw errors, // just delete them, jsf don't need them. delete schema.definitions; delete schema.links; return schema; } return schema; } jsf.extend('faker', function(faker) { faker.prmd = { enum: function() { return arguments[Math.floor(Math.random() * arguments.length)]; } }; return faker; }); module.exports = function (ajv, schemaId, link) { return function * (next) { const validate = ajv.getSchema(schemaId); const mockSchema = deref(validate.schema, validate); if (link.rel !== 'empty') { let sample; if (link.rel === 'instances') { sample = jsf({ type: 'array', items: mockSchema, }); } else { sample = jsf(mockSchema); } this.body = sample; } yield next; } }
javascript
pub mod encoding; pub mod escape_stm; pub mod string_tokenizer; pub mod string; pub mod binary;
rust
/************************************************************************ > File Name: variable_v1.cpp > Author: deqi > Mail: <EMAIL> > Created Time: Sat 30 Jan 2021 01:11:54 PM CST ************************************************************************/ //#include "atomsciflow/abinit/utils.h" #include "atomsciflow/abinit/variable_v1.h" #include <string> //#include <vector> namespace atomsciflow { using namespace utils; // inline functions // inline std::string to_string_same_line(const AbinitVariableV1& var, std::string indent, int n) { if (false == var.status) { return ""; } std::string out = ""; if (0 == var.value.size()) { return out + var.key; } if (1 == var.value.size()) { if (1 == var.value[0].size()) { out += indent + var.key + n_to_string(n) + " " + var.value[0][0]; } else { out += indent + var.key + n_to_string(n); for (auto item : var.value[0]) { out += " " + item; } } } else { out += indent + var.key + n_to_string(n); for (auto val : var.value[0]) { out += " " + val; } out += "\n"; for (int row = 1; row < var.value.size() - 1; ++row) { out += indent; for (auto val : var.value[row]) { out += " " + val; } out += "\n"; } out += indent; for (auto val : var.value[var.value.size()-1]) { out += " " + val; } } return out; } inline std::string to_string_second_line(const AbinitVariableV1& var, std::string indent, int n) { if (false == var.status) { return ""; } std::string out = ""; if (0 == var.value.size()) { return out + var.key; } if (1 == var.value.size()) { if (1 == var.value[0].size()) { out += indent + var.key + n_to_string(n) + " " + var.value[0][0]; } else { out += indent + var.key + n_to_string(n) + "\n"; out += indent; for (auto item : var.value[0]) { out += " " + item; } } } else { out += indent + var.key + n_to_string(n) + "\n"; for (auto row : var.value) { out += indent; for (auto val : row) { out += " " + val; } out += "\n"; } } return out; } void AbinitVariableV1::set(std::string key, int value) { this->key = key; this->value.clear(); this->value.push_back(std::vector<std::string>{std::to_string(value)}); } void AbinitVariableV1::set(std::string key, double value) { this->key = key; this->value.clear(); this->value.push_back(std::vector<std::string>{std::to_string(value)}); } void AbinitVariableV1::set(std::string key, std::string value) { this->key = key; this->value.clear(); this->value.push_back(std::vector<std::string>{value}); } void AbinitVariableV1::set(std::string key, std::vector<int> value) { this->key = key; this->value.clear(); std::vector<std::string> vec_str; for (auto& i : value) { vec_str.push_back(std::to_string(i)); } this->value.push_back(vec_str); } void AbinitVariableV1::set(std::string key, std::vector<double> value) { this->key = key; this->value.clear(); std::vector<std::string> vec_str; for (auto& i : value) { vec_str.push_back(std::to_string(i)); } this->value.push_back(vec_str); } void AbinitVariableV1::set(std::string key, std::vector<std::string> value) { this->key = key; this->value.clear(); std::vector<std::string> vec_str; for (auto& val : value) { vec_str.push_back(val); } this->value.push_back(vec_str); } void AbinitVariableV1::set(std::string key, std::vector<std::vector<int> > value) { this->key = key; this->value.clear(); std::vector<std::string> vec_str; for (auto& row : value) { vec_str.clear(); for (auto& val : row) { vec_str.push_back(std::to_string(val)); } this->value.push_back(vec_str); } } void AbinitVariableV1::set(std::string key, std::vector<std::vector<double> > value) { this->key = key; this->value.clear(); std::vector<std::string> vec_str; for (auto& row : value) { vec_str.clear(); for (auto& val : row) { vec_str.push_back(std::to_string(val)); } this->value.push_back(vec_str); } } void AbinitVariableV1::set(std::string key, std::vector<std::vector<std::string> > value) { this->key = key; this->value.clear(); std::vector<std::string> vec_str; for (auto& row : value) { vec_str.clear(); for (auto& val : row) { vec_str.push_back(val); } this->value.push_back(vec_str); } } void AbinitVariableV1::to(int& value) { value = std::atoi(this->value[0][0].c_str()); } void AbinitVariableV1::to(double& value) { value = std::atof(this->value[0][0].c_str()); } void AbinitVariableV1::to(std::string& value) { value = this->value[0][0]; } void AbinitVariableV1::to(std::vector<int>& value) { value.clear(); for (auto& val : this->value[0]) { value.push_back(std::atoi(val.c_str())); } } void AbinitVariableV1::to(std::vector<double>& value) { value.clear(); for (auto& val : this->value[0]) { value.push_back(std::atof(val.c_str())); } } void AbinitVariableV1::to(std::vector<std::string>& value) { value.clear(); //for (auto& val : this->value[0]) { // value.push_back(val); //} value = this->value[0]; } void AbinitVariableV1::to(std::vector<std::vector<int>>& value) { value.clear(); std::vector<int> vec_int; for (auto& row : this->value) { vec_int.clear(); for (auto& val : row) { vec_int.push_back(std::atoi(val.c_str())); } value.push_back(vec_int); } } void AbinitVariableV1::to(std::vector<std::vector<double>>& value) { value.clear(); std::vector<double> vec_double; for (auto& row : this->value) { vec_double.clear(); for (auto& val : row) { vec_double.push_back(std::atof(val.c_str())); } value.push_back(vec_double); } } void AbinitVariableV1::to(std::vector<std::vector<std::string>>& value) { value.clear(); //std::vector<std::string> vec_str; //for (auto& row : this->value) { // vec_double.clear(); // for (auto& val : row) { // vec_double.push_back(val); // } // value.push_back(vec_str); //} value = this->value; } std::string AbinitVariableV1::to_string() { if (false == this->status) { return ""; } return this->to_string(0); } std::string AbinitVariableV1::to_string(int n) { if (false == this->status) { return ""; } std::string out = ""; if (9 == this->value.size()) { return out + this->key; } if (this->value.size() == 1) { if (this->value[0].size() == 1) { out += this->key + n_to_string(n) + " " + this->value[0][0]; } else { out += this->key + n_to_string(n) + "\n"; for (auto item : this->value[0]) { out += " " + item; } } } else { out += this->key + n_to_string(n) + "\n"; for (auto row : this->value) { for (auto val : row) { out += " " + val; } out += "\n"; } } return out; } std::string AbinitVariableV1::to_string(std::string layout, std::string indent) { if (false == this->status) { return ""; } return this->to_string(layout, indent, 0); } std::string AbinitVariableV1::to_string(std::string layout, std::string indent, int n) { /* * layout: * "same-line"; * "second-line"'' */ if (false == this->status) { return ""; } if ("same-line" == layout) { return to_string_same_line(*this, indent, n); } else if ("second-line" == layout) { return to_string_second_line(*this, indent, n); } else { return to_string(n); } } // } // namespace atomsciflow
cpp
Holi Khele Re Nandlal song is a Hindi devotional song from the Barsane Ki Holi released on 2017. Music of Holi Khele Re Nandlal song is composed by Snehlata. Holi Khele Re Nandlal was sung by Snehlata. Download Holi Khele Re Nandlal song from Barsane Ki Holi on Raaga.com.
english
/// create a bullet btMultiBody model of a tree structured multibody system, /// convert that model to a MultiBodyTree model. /// Then - run inverse dynamics on random input data (q, u, dot_u) to get forces /// - run forward dynamics on (q,u, forces) to get accelerations /// - compare input accelerations to inverse dynamics to output from forward dynamics #include <cmath> #include <cstdio> #include <cstdlib> #include <functional> #include <string> #include <btBulletDynamicsCommon.h> #include <btMultiBodyTreeCreator.hpp> #include <BulletDynamics/Featherstone/btMultiBodyConstraintSolver.h> #include <BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.h> #include <BulletDynamics/Featherstone/btMultiBodyPoint2Point.h> #include <BulletDynamics/Featherstone/btMultiBodyLinkCollider.h> #include <gtest/gtest.h> #include "../../examples/CommonInterfaces/CommonGUIHelperInterface.h" #include "../../examples/Importers/ImportURDFDemo/BulletUrdfImporter.h" #include "../../examples/Importers/ImportURDFDemo/URDF2Bullet.h" #include "../../examples/Importers/ImportURDFDemo/MyMultiBodyCreator.h" #include "../../examples/Importers/ImportURDFDemo/URDF2Bullet.h" #include "../../examples/Utils/b3ResourcePath.h" #include <invdyn_bullet_comparison.hpp> #include <btMultiBodyFromURDF.hpp> #include <MultiBodyTreeCreator.hpp> #include <MultiBodyTreeDebugGraph.hpp> #include "Bullet3Common/b3CommandLineArgs.h" #include "Bullet3Common/b3Random.h" using namespace btInverseDynamics; bool FLAGS_verbose = false; static btVector3 gravity(0, 0, -10); static const bool kBaseFixed = false; static const char kUrdfFile[] = "r2d2.urdf"; /// this test loads the a urdf model with fixed, floating, prismatic and rotational joints, /// converts in to an inverse dynamics model and compares forward to inverse dynamics for /// random input TEST(InvDynCompare, bulletUrdfR2D2) { MyBtMultiBodyFromURDF mb_load(gravity, kBaseFixed); char relativeFileName[1024]; ASSERT_TRUE(b3ResourcePath::findResourcePath(kUrdfFile, relativeFileName, 1024)); mb_load.setFileName(relativeFileName); mb_load.init(); btMultiBodyTreeCreator id_creator; btMultiBody *btmb = mb_load.getBtMultiBody(); ASSERT_EQ(id_creator.createFromBtMultiBody(btmb), 0); MultiBodyTree *id_tree = CreateMultiBodyTree(id_creator); ASSERT_EQ(0x0 != id_tree, true); vecx q(id_tree->numDoFs()); vecx u(id_tree->numDoFs()); vecx dot_u(id_tree->numDoFs()); vecx joint_forces(id_tree->numDoFs()); const int kNLoops = 10; double max_pos_error = 0; double max_acc_error = 0; b3Srand(0); for (int loop = 0; loop < kNLoops; loop++) { for (int i = 0; i < q.size(); i++) { q(i) = b3RandRange(-B3_PI, B3_PI); u(i) = b3RandRange(-B3_PI, B3_PI); dot_u(i) = b3RandRange(-B3_PI, B3_PI); } double pos_error; double acc_error; btmb->clearForcesAndTorques(); id_tree->clearAllUserForcesAndMoments(); // call inverse dynamics once, to get global position & velocity of root body // (fixed, so q, u, dot_u arbitrary) EXPECT_EQ(id_tree->calculateInverseDynamics(q, u, dot_u, &joint_forces), 0); EXPECT_EQ(compareInverseAndForwardDynamics(q, u, dot_u, gravity, FLAGS_verbose, btmb, id_tree, &pos_error, &acc_error), 0); if (pos_error > max_pos_error) { max_pos_error = pos_error; } if (acc_error > max_acc_error) { max_acc_error = acc_error; } } if (FLAGS_verbose) { printf("max_pos_error= %e\n", max_pos_error); printf("max_acc_error= %e\n", max_acc_error); } EXPECT_LT(max_pos_error, std::numeric_limits<idScalar>::epsilon() * 1e4); EXPECT_LT(max_acc_error, std::numeric_limits<idScalar>::epsilon() * 1e5); } int main(int argc, char **argv) { b3CommandLineArgs myArgs(argc, argv); FLAGS_verbose = myArgs.CheckCmdLineFlag("verbose"); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
cpp
<section id="contact" class="container"> <div class="p-5 bg-dark"> <h2 class="d-block bg-primary text-center text-light"> VW and Audi Dealer Repair Alternative </h2> <div class="row"> <div class="col-md-6 d-block mb-3"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d4168.173031520687!2d-97.20071865121137!3d33.238475931441485!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x86d45215bdfd095d!2sDigi+Sport+Performance%2C+LLC!5e0!3m2!1sen!2sus!4v1541470733961" width="100%" height="400px" frameborder="0" style="border:0" allowfullscreen ></iframe> </div> <div class="col-md-1"></div> <div class="col-md-5 d-block bg-light text-center"> <p> We are two lights west from I-35 on 380/University. North 1 mile on Masch Branch </p> <p> Digi Sport Performance, LLC<br /> 2321 N. Masch Branch Road<br /> Suite 325<br /> Denton, TX 76207 </p> <a href="tel:214-257-8221" class="btn btn-outline-primary my-5 d-block" >214-257-8221</a > <a href="mailto:<EMAIL>" class="btn btn-outline-primary my-5 d-block" >Email us</a > </div> </div> </div> </section>
html
module.exports = { init:function(){ this.SPDR = 0; this.SPIF = 0; this.WCOL = 0; this.SPI2X = 0; this.SPIE = 0; this.SPE = 0; this.DORD = 0; this.MSTR = 0; this.CPOL = 0; this.CPHA = 0; this.SPR1 = 0; this.SPR0 = 0; this.core.pins.spiOut = this.core.pins.spiOut || []; }, write:{ 0x4C:function( value, oldValue ){ this.SPIE = value >> 7; this.SPE = value >> 6; this.DORD = value >> 5; this.MSTR = value >> 4; this.CPOL = value >> 3; this.CPHA = value >> 2; this.SPR1 = value >> 1; this.SPR0 = value >> 0; }, 0x4D:function( value, oldValue ){ this.SPI2X = value & 1; return (this.SPIF << 7) | (this.WCOL << 6) | this.SPI2X; }, 0x4E:function( value ){ this.SPDR = value; this.core.pins.spiOut.push( value ); this.SPIF = 1; } }, read:{ 0x4D:function(){ this.SPIF = (!!this.core.pins.spiIn.length) | 0; return (this.SPIF << 7) | (this.WCOL << 6) | this.SPI2X; }, 0x4E:function(){ let spiIn = this.core.pins.spiIn; if( spiIn.length ) return this.SPDR = spiIn.shift(); return this.SPDR; } }, update:function( tick, ie ){ if( this.SPIF && this.SPIE && ie ){ this.SPIF = 0; return "SPI"; } } };
javascript
Beatles songs will now be on American Idol, which is now on iTunes. Clearly the natural line of progression is to proclaim that the Beatles catalogue is one step closer to iTunes, right? I’d say that’s a leap of faith I’m not willing to take just yet. If word can leak about Prince Harry being in Afghanistan, then word should be able to leak about any potential Beatles-iTunes deal. But if y’all wanna speculate, be my guest. It’s not like you can’t find the whole Beatles discography on every BitTorrent site out there anyway.
english
Amidst all the lore-based speculation surrounding the "Lost City of Flowers," Valorant's design lead, Joe Lansford, revealed an exciting tidbit regarding the upcoming map. It will come with a new mechanic that, as he says, will not be very "crazy," and won't be a teleporter like those featured in Bind either. In a brief discussion with popular Valorant athlete Adam "ec1s" Eccles, at Red Bull Home Ground 2022 grand finale, Lansford spoke about how Riot Games designs maps, their plans for those that are currently present in the title, popular player behavior on levels, and how the developers see them, and finally, the much-anticipated new addition. Valorant's upcoming map has been causing immense hype among fans due to its connection to an Indian city. This may be the second in-game representation of the popular South Asian country, following Harbor, the new water-bending Indian Agent, who was introduced in October. When asked about the new map, Lansford revealed limited but exciting information: As one can decipher, the unamed map will not let players teleport through set routes. The promised mechanic could be based out of something players have seen already, or could be an entirely new way to tackle a particular region. As Lansford proclaimed, the new addition will be similar to another map that is already present in the pool. Taking a guess is difficult, as Lansford's statement provided very vague hints. The ongoing Episode 5 Act 3 will end in early January, paving the way for a brand new Episode 6 in the game. As announced by Riot earlier, two maps - Bind and Breeze - will see their way out with Episode 6's kickoff. To compensate for the removal, Split will be making its return. However, there will still be a place in the seven-map rotating pool. Even though an official nod is missing, the new one will most likely launch as part of Valorant's Episode 6. It's possible that the new map may be similar to one of the those scheduled to exit the pool soon. Both Breeze and Bind are pretty popular in the tactical hero-based shooter game. However, the developers chose to reimagine a few features here and there to promote more diverse plays. The new map might be inspired by either of these, or it may also have a mixture of features from both.
english
<reponame>sepidehhosseinzadeh/Naive-Bayes-Classifier<filename>pywikibot/scripts/i18n/followlive/sv.json<gh_stars>1-10 { "@metadata": { "authors": [ "<NAME>", "<NAME>" ] }, "followlive-blanking": "Rensad, innehållet var '%(content)s'." }
json
If you think that Coronavirus Pandemic is on a decline, you are seriously mistaken. Europe, Kerala and Delhi give us the real picture. Covid-19 will stay here till we get vaccines for all. Buck stops with us. Unless we take precaution and follow Covid-19 guidelines, India may witness a similar Covid peak leading to another lockdown.
english
{"resources":{"Scripts/Script-1.sql":{"sql-editor-data-source-id":"oracle_thin-16e95869316-6e8186b394f0698c"},"Scripts/Script-2.sql":{"sql-editor-data-source-id":"oracle_thin-16ec8583c0a-3ec9b76c2549f4e4"},"Scripts/Script-3.sql":{"sql-editor-data-source-id":"oracle_thin-16e98106980-ca3587e180e6a59"},"Scripts/Script.sql":{"sql-editor-data-source-id":"oracle_thin-16e95869316-6e8186b394f0698c"}}}
json
<reponame>Finnerale/Zeitig<gh_stars>1-10 use druid::{ widget::{prelude::*, SizedBox}, Data, WidgetPod, }; /// A widget that switches between two possible child views, for `Data` that /// is `Option<T>`. pub struct Maybe<T> { some_initialized: bool, some: WidgetPod<T, Box<dyn Widget<T>>>, none: WidgetPod<(), Box<dyn Widget<()>>>, } impl<T: Data> Maybe<T> { /// Create a new `Maybe` widget with a `Some` and a `None` branch. pub fn new(some: impl Widget<T> + 'static, none: impl Widget<()> + 'static) -> Maybe<T> { Maybe { some_initialized: false, some: WidgetPod::new(Box::new(some)), none: WidgetPod::new(Box::new(none)), } } /// Create a new `Maybe` widget where the `None` branch is an empty widget. #[allow(dead_code)] pub fn or_empty(some: impl Widget<T> + 'static) -> Maybe<T> { Maybe { some_initialized: false, some: WidgetPod::new(Box::new(some)), none: WidgetPod::new(Box::new(SizedBox::empty())), } } } impl<T: Data> Widget<Option<T>> for Maybe<T> { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut Option<T>, env: &Env) { match data { Some(data) if self.some_initialized => self.some.event(ctx, event, data, env), Some(_) => (), None => self.none.event(ctx, event, &mut (), env), } } fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &Option<T>, env: &Env, ) { if let LifeCycle::WidgetAdded = event { if let Some(data) = data { self.some.lifecycle(ctx, event, data, env); self.some_initialized = true; } self.none.lifecycle(ctx, event, &(), env); } else { match data { Some(data) => self.some.lifecycle(ctx, event, data, env), None => self.none.lifecycle(ctx, event, &(), env), }; } } fn update(&mut self, ctx: &mut UpdateCtx, old_data: &Option<T>, data: &Option<T>, env: &Env) { if old_data.is_some() != data.is_some() { ctx.children_changed(); } else { match data { Some(new) => self.some.update(ctx, new, env), None => self.none.update(ctx, &(), env), }; } } fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &Option<T>, env: &Env, ) -> Size { match data { Some(data) => { let size = self.some.layout(ctx, bc, data, env); self.some.set_layout_rect(ctx, data, env, size.to_rect()); size } None => { let size = self.none.layout(ctx, bc, &(), env); self.none.set_layout_rect(ctx, &(), env, size.to_rect()); size } } } fn paint(&mut self, ctx: &mut PaintCtx, data: &Option<T>, env: &Env) { match data { Some(data) => self.some.paint(ctx, data, env), None => self.none.paint(ctx, &(), env), }; } }
rust
Kolkata boy Pubarun Basu became the first Indian to win the Youth Competition of Sony World Photography Awards 2021 and bagged the title of the 'Youth Photographer of the Year 2021' by the World Photography Organization. He got talking to us about his journey and shared a few tips for fellow photographers. By Roshni Chakrabarty: Pubarun Basu was just four when he first got his hands on his father’s camera. His father is a professional photographer and there were all kinds of photographic equipment lying about his house in North Kolkata, a place which is quintessentially a street photographer’s paradise. “I would often explore them on my own, not knowing what to really do with them. My father never interfered in that process, but at times he would sit me down and give me little pieces of advice, advice I would never ever forget,” says Pubarun. The Covid-19 pandemic and lockdown were a blow to photographers who love exploring India’s colourful alleyways but for the 20-year-old Kolkata boy, the pandemic was an opportunity to intensify his photography studies. He dedicated his time to an online photography course by the Museum of Modern Art, New York, and this broadened his perspective about what photography was all about. One evening, he spotted sunlight coming in through the windows and noted the shadows of the iron bars falling on the curtain; he asked his mother to stand behind them and put her hands out. The photo of that silhouette went on to bag him the title of ‘Youth Photographer of the Year 2021’ by the World Photography Organization. Pubarun became the first Indian in the 14-year-old history of the Sony World Photography Awards to become the winner. We got talking to the youngster about his journey in photography and asked him to share a few tips for his fellow photographers. There’s no doubt that Pubarun’s biggest inspiration has been his photographer dad. His equipment and photography magazines were regular teachers in Pubarun’s hands. But his mother too has always supported him by ensuing that he got the best possible environment to work with. It is almost divine justice that it was his mother’s photograph shot with his father’s full-frame Nikon D800e that bagged Pubarun the photography award. “I got to know about the Sony World Photography Awards on the internet. I was blown away by the winning pictures of all the previous editions of the competition, and decided that I would participate in the Youth category myself,” says Pubarun. This was the second time he tried his hand at the annual World Photography Awards. His first submission in 2019 was highlighted by the editor but didn’t win an award. He also participated in the monthly competitions to challenge himself with the various themes. This year, he was supposed to select an image from his surroundings, owing to the lockdown. Puburan Basu’s winning shot ‘No Escape from Reality’ was submitted in July 2020. He learned of his win in March 2021 but kept it hushed. His prize includes photography equipment and a certificate. However, the usual felicitation ceremony and London exhibition couldn’t be carried out this year because of the pandemic. “Honestly, I have still not come to terms with the fact that I am this year's ‘Sony Youth Photographer of the Year’. I am overwhelmed to see myself representing India on an international level. I'm grateful to Sony and World Photography Organization for sending me a mirrorless camera to experiment with,” says Pubarun. Top-notch mobile cameras vs DSLRs: What difference does it make? We live in an age where almost everyone has access to at least a mobile camera, and those too are rapidly being upgraded to suit a generation which is visual to the core. So, does it make a difference anymore whether you have a high-end mobile camera or if you have a DSLR? “There is a significant difference in image quality when it comes to mobile cameras as opposed to high-end DLSRs. Although the technical limitations of gadgets might not limit a photographer's creativity, the tonal quality of an image taken with a full frame DSLR is, in a way, irreplaceable,” says Pubarun. He explains that there must be a reason why professional photographers spend a fortune trying to buy the perfect gear for their field of work. “However, in today's world, creativity knows no bounds. I have seen some spectacular shots or even entire movies captured on iPhones. I think it all depends on how an individual envisions his aesthetic journey and how s/he plans to use photography as a tool,” he adds. Is building a photography career one of privilege? Unlike various other common career options or skill-building opportunities, many might think becoming a professional photographer needs much more investment and is an expensive process in general. Pubarun Basu notes that this depends on the genre of photography one chooses to pursue. “For instance, wildlife photography can be really expensive, especially with the telephoto lenses that are a prerequisite. The same goes for studio photography, where the cost of lights alone sum up for more than the cost of the cameras,” he says. “But at the same time, I have seen many Indian street photographers make use of their situation in the best possible way and produce some phenomenal images,” he adds. Originality is the name of the game, explains Pubarun. “Creativity thrives in the presence of an open mind, so keep yourselves open to all sorts of ideas before settling on a particular style. Being active on social media is really helpful and motivating, but getting influenced by trends all the time might adversely affect your originality,” he says. He also advises looking out for competitions and exhibitions, and participate in them as much as possible. Moreover, he encourages all the budding photographers to explore the works of legendary Indian artists for inspiration. “And lastly, indulge yourselves totally into the world of photography. Explore the subject from your own perspectives, learn about the history and evolution of this medium and try to practice your skills on a daily basis,” he adds. A fan of Henri Cartier Bresson, Steve McCurry and Raghu Rai, Pubarun wants to tell stories from around the globe with his photography and even try his hand in filmmaking in the future. He is an Indian classical musician as well and is deeply intrigued by indigenous music from various corners of the world. “I love documenting people and their culture. My only wish is to live my life as an artist in the truest sense and indulge myself into the various forms of art,” he says. We wish our Youth Photographer of the Year 2021 all the best for a bright future!
english
import { sanitize } from 'ember-sanitize/utils/sanitize'; import { module, test } from 'qunit'; module('SanitizeHelper', function() { test('sanitizes with the defaults', function(assert) { var result = sanitize("some <b>html</b> here"); assert.equal(result, "some html here"); }); test('sanitizes with a custom config', function(assert) { var config = { elements: ['i'] }; var result = sanitize("some <b>html</b> <i>here</i>", config); assert.equal(result, "some html <i>here</i>"); }); test("doesn't execute code whilst sanitizing", function(assert) { var done = assert.async(); var executed = false; window.oops = function() { executed = true; }; sanitize(`<img src='' onerror='oops()'>`); setTimeout(function() { assert.ok(!executed, "should not have executed the code"); window.oops = undefined; done(); }, 0); }); });
javascript
<reponame>automaidan/judges {"2010":"","2016":"","AdditionalNote":"","Department":"Київський апеляційний суд","Link":"https://drive.google.com/open?id=0BygiyWAl79DMZ1BORG9FNUFKeFE","Link 2015":"","Name":"<NAME>","Note":"У меня","Position":"Суддя Київського апеляційного суду","Region":"м. Київ","Youtube":"","analytics":[{"c":1,"fc":3,"ff":54.4,"ffa":1,"fh":461.4,"fha":3,"fi":1002540.87,"fl":48994,"fla":4,"h":268.9,"ha":1,"i":235826.46,"l":1502,"la":1,"y":2013},{"c":2,"fc":4,"ff":54.4,"ffa":1,"fh":553.2,"fha":3,"fi":277597,"fl":49089,"fla":5,"h":268.9,"ha":1,"i":242186,"k":54.4,"ka":1,"l":1502,"la":1,"y":2014},{"c":2,"fi":10517,"h":134.5,"ha":1,"i":249672,"j":3,"k":17.82,"ka":1,"l":751,"la":1,"y":2015},{"c":2,"fi":78571,"h":134.5,"ha":1,"i":349897,"k":17.82,"ka":1,"l":751,"la":1,"y":2016},{"c":2,"fi":52132,"h":134.5,"ha":1,"i":1224001,"k":17.82,"ka":1,"l":751,"la":1,"y":2017},{"c":2,"fi":214002,"h":134.5,"ha":1,"i":1487395,"k":17.82,"ka":1,"l":751,"la":1,"m":300000,"y":2018},{"b":250260,"c":2,"fi":2729002,"h":134.5,"ha":1,"k":17.82,"ka":1,"l":751,"la":1,"m":900000,"y":2019},{"y":2020}],"declarationsLinks":[{"id":"vulyk_47_33","provider":"declarations.com.ua.opendata","url":"http://static.declarations.com.ua/declarations/sudy/apeliatsiini_sudy_oblastei__m.kyieva/kyivska/kashperska.pdf","year":2013},{"id":"vulyk_62_91","provider":"declarations.com.ua.opendata","url":"http://static.declarations.com.ua/declarations/chosen_ones/mega_batch/kashperska_tamara_tsezarivna.pdf","year":2014},{"id":"nacp_b390cdb0-0109-4220-84fd-de222b7700d6","provider":"declarations.com.ua.opendata","year":2015},{"id":"nacp_f5b85e32-0df5-4bdf-b9e5-a4aab1625ea8","provider":"declarations.com.ua.opendata","year":2016},{"id":"nacp_9deff546-ff66-420a-b9a5-262ad8389ce8","provider":"declarations.com.ua.opendata","year":2017},{"id":"nacp_174f5ebd-db23-40c9-a4db-609955a1084a","provider":"declarations.com.ua.opendata","year":2018},{"id":"nacp_f3849789-ec64-48a9-b607-1bde6fa0d9b7","provider":"declarations.com.ua.opendata","year":2019},{"id":"nacp_450d9dd6-af7a-4c95-81a6-e4f5e3558c6a","provider":"declarations.com.ua.opendata","year":2020}],"field8":"","field9":"","key":"kashperska_tamara_cezarivna","type":"judge","Декларація доброчесності судді подано у 2016 році (вперше)":"http://vkksu.gov.ua/userfiles/declaracii-suddiv/asko/kashperskatts.PDF","Декларація родинних зв’язків судді подано у 2016 році":"http://vkksu.gov.ua/userfiles/declaracii-suddiv/asko/kashperskattsrz.PDF","Декларації 2013":"","Декларації 2014":"","Декларації 2015":"","Декларації 2016":"","Клейма":"","Кількість дисциплінарних стягнень":"","Кількість скарг":"3","Кількість справ":"","Оскаржені":"","ПІБ2":"","Фото":"https://picua.org/images/2021/01/15/0746190977cce87fc70c3dfce1ea519e.png","Як живе":"","декларації 2015":"","судові рішення по справах Майдану":""}
json
export var __esModule: boolean; export function useOverlay({ overlayRef: _overlayRef, returnFocusRef, initialFocusRef, onEscape, ignoreClickRefs, onClickOutside }: { overlayRef: any; returnFocusRef: any; initialFocusRef: any; onEscape: any; ignoreClickRefs: any; onClickOutside: any; }): { ref: any; };
typescript
<reponame>falopez10/sportaholic # sportaholic Web App designed for latest, customized, sports news
markdown
The government on Thursday revealed that as many as 829 teachers and 575 students in Andhra Pradesh have contracted coronavirus. The news comes just three days after the reopening of schools in the Telugu State. However, the infections are not because of the reopening of schools. The School Education Department has said that the test results pertain to tests conducted in October. Since the results have been declared only today, an impression has gained ground that it's the effect of the decision to reopen schools. DEOs have reportedly found that several WhatsApp messages attributing the infections to the reopening of schools have been found to be inaccurate. As per the government, students are attending classes in very good numbers despite the fear of the pandemic. However, the latest test results are likely to create a sense of panic, given how the media has been projecting them. Follow us on Google News and stay updated with the latest!
english
<reponame>yohm/caravan-lib // // Created by <NAME> on 2021/02/23. // #ifndef CARAVAN_LIB_PRODUCER_HPP #define CARAVAN_LIB_PRODUCER_HPP #include <iostream> #include <vector> #include <queue> #include <map> #include <set> #include <chrono> #include <mpi.h> #include "Base.hpp" #include "TaskResult.hpp" #include "Logger.hpp" namespace caravan_impl { using namespace caravan; enum MsgTag { PROD_BUF_SEND_TASKS = 1, PROD_BUF_TERMINATE_REQUEST, BUF_PROD_TASK_REQUEST, BUF_PROD_SEND_RESULT, BUF_CONS_SEND_TASK, BUF_CONS_TERMINATE_REQUEST, CONS_BUF_TASK_REQUEST, CONS_BUF_SEND_RESULT }; int my_MPI_Probe(int source, int tag, MPI_Comm comm, MPI_Status *status) { int received = 0, ret = 0; while (true) { ret = MPI_Iprobe(source, tag, comm, &received, status); if (received) break; usleep(1000); } return ret; } class Producer { public: Producer(Logger &_logger, const std::string& _dump_log = "") : logger(_logger), dump_log(_dump_log) {}; Queue tasks; Logger &logger; std::string dump_log; std::map<int, long > elapse_times; // {rank_id, elapse_time_sum } void Run(const std::vector<int> &buffers, const std::function<void(int64_t, const json&, const json&, Queue&)>& callback) { logger.d("Producer started : ", buffers.size()); std::set<int64_t> running_task_ids; std::map<int, size_t> requesting_buffers; MPI_Request send_req = MPI_REQUEST_NULL; std::vector<uint8_t> send_buf; bool save_dump = !dump_log.empty(); std::map<int64_t, TaskResult> results_map; while (true) { logger.d("Producer has %d tasks %d running_tasks", tasks.Size(), running_task_ids.size()); bool has_something_to_send = (tasks.Size() > 0 && !requesting_buffers.empty()); bool has_something_to_receive = (!running_task_ids.empty() || requesting_buffers.size() < buffers.size()); if (!has_something_to_send && !has_something_to_receive) { break; } MPI_Status st; int received = 0; int sent = 0; if (has_something_to_receive && has_something_to_send) { while (true) { // wait until message is ready MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &received, &st); if (received) break; MPI_Test(&send_req, &sent, MPI_STATUS_IGNORE); // MPI_Test on MPI_REQUEST_NULL returns true if (sent) break; usleep(1000); } } else if (has_something_to_receive) { my_MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &st); received = 1; } else if (has_something_to_send) { MPI_Wait(&send_req, MPI_STATUS_IGNORE); sent = 1; } // receiving if (received) { if (st.MPI_TAG == MsgTag::BUF_PROD_TASK_REQUEST) { std::pair<int, int> worker_nreq = ReceiveRequest(st); requesting_buffers.insert(worker_nreq); } else if (st.MPI_TAG == MsgTag::BUF_PROD_SEND_RESULT) { TaskResult result = ReceiveResult(st); int64_t task_id = result.task_id; logger.d("Producer received result for %d", task_id); if (save_dump) { results_map.emplace(task_id, result); } running_task_ids.erase(task_id); if (elapse_times.find(result.rank) == elapse_times.end() ) { elapse_times[result.rank] = 0; } elapse_times[result.rank] += (result.finish_at - result.start_at); callback(task_id, result.input, result.output, tasks); } else { // must not happen assert(false); MPI_Abort(MPI_COMM_WORLD, 1); } } else if (sent) { auto it = requesting_buffers.begin(); int worker = it->first; size_t n_request = it->second; const auto task_ids = SendTasks(worker, n_request, &send_req, send_buf); for (long task_id: task_ids) { running_task_ids.insert(task_id); } requesting_buffers.erase(worker); } } MPI_Wait(&send_req, MPI_STATUS_IGNORE); for (auto req_w: requesting_buffers) { TerminateWorker(req_w.first); } if (save_dump) { std::ofstream binout(dump_log, std::ios::binary); const std::vector<uint8_t> dumped = json::to_msgpack(results_map); binout.write((const char *) dumped.data(), dumped.size()); binout.flush(); binout.close(); } } std::vector<int64_t> SendTasks(int worker, size_t num_tasks, MPI_Request *p_req, std::vector<uint8_t> &send_buf) { json j; std::vector<int64_t> task_ids; for (size_t i = 0; i < num_tasks && tasks.Size() > 0; i++) { const task_t t = tasks.Pop(); j.push_back(t); task_ids.push_back(t.first); } send_buf = std::move(json::to_msgpack(j)); size_t n = send_buf.size(); MPI_Isend(send_buf.data(), n, MPI_BYTE, worker, MsgTag::PROD_BUF_SEND_TASKS, MPI_COMM_WORLD, p_req); logger.d("%d tasks are assigned to %d", task_ids.size(), worker); return task_ids; } void TerminateWorker(int worker) { logger.d("terminating %d", worker); std::vector<char> buf; MPI_Send(&buf[0], 0, MPI_BYTE, worker, MsgTag::PROD_BUF_TERMINATE_REQUEST, MPI_COMM_WORLD); } std::pair<int, int> ReceiveRequest(const MPI_Status &st) { assert(st.MPI_TAG == MsgTag::BUF_PROD_TASK_REQUEST); int n_req = 0; MPI_Recv(&n_req, 1, MPI_INT, st.MPI_SOURCE, st.MPI_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); assert(n_req > 0); logger.d("Producer received request %d from %d", n_req, st.MPI_SOURCE); return std::make_pair(st.MPI_SOURCE, n_req); } TaskResult ReceiveResult(const MPI_Status &st) { assert(st.MPI_TAG == MsgTag::BUF_PROD_SEND_RESULT); int msg_size; MPI_Get_count(&st, MPI_CHAR, &msg_size); std::vector<unsigned char> buf(msg_size); MPI_Recv(&buf[0], msg_size, MPI_BYTE, st.MPI_SOURCE, st.MPI_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); logger.d("result was sent by %d", st.MPI_SOURCE); const json j = json::from_msgpack(buf); return j.get<TaskResult>(); } }; } #endif //CARAVAN_LIB_PRODUCER_HPP
cpp
/* * 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.nlpcraft.model.tools.embedded; import org.apache.nlpcraft.common.*; import org.apache.nlpcraft.model.tools.test.*; import org.apache.nlpcraft.probe.*; import org.apache.nlpcraft.probe.mgrs.nlp.*; import java.util.Collection; import java.util.concurrent.*; import java.util.function.*; /** * Embedded probe controller. Typically, data probes are launched in their own independent JVMs. However, * in some cases it is more convenient for model implementation or preferable for performance reasons to host * a data model (and hence the data probe) in the same "client" JVM. * <p> * The standard processing flow with the data probe running in a separate JVM looks like this: * <br> * <code> * App ⇒ <b>JVM</b><sub>1</sub>(REST Server) ⇒ <b>JVM</b><sub>2</sub>(Probe) ⇒ <b>JVM</b><sub>1</sub>(REST Server) ⇒ App * </code> * <br> * There are at least 4 networks hops between client application request and response. * <p> * However, when using native Java Client or {@link NCTestClient Java Test Client} in embedded probe mode * the processing flow is shortened: * <br> * <code> * <b>JVM</b><sub>1</sub>(App) ⇒ <b>JVM</b><sub>2</sub>(REST Server) ⇒ <b>JVM</b><sub>1</sub>(Probe ⇒ App) * </code> * <br> * In this case there are only 2 hops as both client application and the data probe (and the model) are hosted * in the same JVM. * <p> * Notes: * <ul> * <li> * Embedded probe is only available for JVM processes (and can be used with any JVM languages). * </li> * <li> * There can be only one embedded probe per JVM. * </li> * <li> * Once data probe is stopped and cannot be started again in the same JVM. * </li> * <li> * Even though the caller can register local-JVM listener for the query results, these results * will still be asynchronously delivered to the REST server in the usual manner so that other clients * could fetch these results to maintain internal logging, tracing and metrics. If the client * application hosting data model and its probe <i>is the only client</i> for that model it needs to cancel the * request on the REST server after receiving a local-JVM callback to release associated * resources on the REST server. * </li> * </ul> */ public class NCEmbeddedProbe { private static boolean waitForFuture(CompletableFuture<Integer> fut) { while (!fut.isDone()) try { return fut.get() == 0; } catch (InterruptedException | ExecutionException ignored) {} return false; } /** * Start the embedded probe with optional configuration file and models overrides. * * @param cfgFile Optional configuration file path. It should be either a full path or the file name * that can be found in the current working directory or on the classpath as a class loader * resource. If provided - it is equivalent to starting a probe using <code>-config=cfgFile</code> * command line argument. If {@code null} - the probe will start with the default configuration. * @param mdlClasses Optional data model classes to be deployed by the embedded probe. If provided - * these will override {@code nlpcraft.probe.models} configuration property. If {@code null} - the models * defined in the configuration (default or provided via {@code cfgFile} parameter) will be used. * Each class should be a fully qualified class name. * @throws NCException Thrown in case of any errors starting the data probe. * @return Whether probe started ok. */ public static boolean start(String cfgFile, Collection<String> mdlClasses) { CompletableFuture<Integer> fut = new CompletableFuture<>(); NCProbeBoot$.MODULE$.startEmbedded(cfgFile, mdlClasses, fut); return waitForFuture(fut); } /** * Starts the embedded probe with default configuration and specified overrides. * * @param probeId Probe ID override. * @param tok Probe token override. * @param upLink Probe up-link to the server override. * @param dnLink Probe down-link from the server override. * @param mdlClasses One or more data model classes overrides to be deployed by the embedded probe. At least * model must be provided. Each class should be a fully qualified class name. * @throws NCException Thrown in case of any errors starting the data probe. * @return Whether probe started ok. */ public static boolean start( String probeId, String tok, String upLink, String dnLink, String... mdlClasses) { if (mdlClasses.length == 0) throw new NCException("At least one model class must be provided when starting embedded probe."); CompletableFuture<Integer> fut = new CompletableFuture<>(); NCProbeBoot$.MODULE$.startEmbedded(probeId, tok, upLink, dnLink, mdlClasses, fut); return waitForFuture(fut); } /** * Stops the embedded probe, if it was started before. Note that the probe cannot be started again * in the same JVM process. * * @throws NCException Thrown in case of any errors stopping the data probe. */ public static void stop() { NCProbeBoot$.MODULE$.stop(); } /** * Registers the callback on query processing results. Results from all models deployed on this embedded probe * will trigger this callback. * * @param cb Callback to register. * @throws NCException Thrown in case of any errors registering a callback. */ public static void registerCallback(Consumer<NCEmbeddedResult> cb) { NCProbeEnrichmentManager$.MODULE$.addEmbeddedCallback(cb); } /** * Unregisters previously registered callback. Ignored if given callback wasn't registered before. * * @param cb Callback to unregister. * @throws NCException Thrown in case of any errors unregistering a callback. */ public static void unregisterCallback(Consumer<NCEmbeddedResult> cb) { NCProbeEnrichmentManager$.MODULE$.removeEmbeddedCallback(cb); } }
java
Vokkaliga Sangha, Mysuru, has invited applications from meritorious students of the community from Mysuru and Chamarajanagar districts who have scored high marks in SSLC and Second PUC exams (2021-22) for presentation of Pratibha Puraskar. Students may obtain applications at the Sangha Office in Vidyaranyapuram. Last date to apply along with copies of Aadhaar card, caste certificate, marks cards and photographs is before 4 pm on June 25. Prathibha Puraskar will be presented at a programme to be held as part of Kempegowda Jayanthi celebrations on June 27. For details, call Ph: 0821-2482944.
english
A special judge had described the Shiv Sena MP’s arrest illegal and said that the central agency was working with a ‘pick and choose attitude’. The observations made by Special Judge MG Deshpande in his order while granting bail to Shiv Sena MP Sanjay Raut earlier this week were uncalled for, the Enforcement Directorate told the Bombay High Court, reported Bar and Bench. The central agency has moved the High Court challenging the order granting bail to Raut. On November 9, Raut had walked out of jail after being granted bail in the Patra Chawl scam, which involves an alleged fraud of Rs 1,034 crore. The agency has alleged that Raut and his aides made fraudulent financial transactions related to the redevelopment of the chawl – a building consisting of several tenements – in Mumbai. Raut had been arrested on July 31. In his bail order, Special Judge Deshpande had described Raut’s arrest as illegal. He said the Enforcement Directorate was making arrests with a “pick and choose attitude”, Live Law reported. Deshpande also criticised the central agency for arresting accused persons at “extraordinary pace”, but carrying out trials at a “snail’s pace”. On Friday, Additional Solictor General Anil Singh, appearing for the Enforcement Directorate, told the Bombay High Court that the observations made by the special judge were having an adverse impact on other cases the central agency is investigating, Bar and Bench reported. The additional solicitor general then requested for time to amend the plea challenging the bail order, to add certain grounds, Live Law reported. Senior Advocate Ashok Mundargi, appearing for Raut, also requested two weeks’ time to respond to the Enforcement Directorate’s plea. The matter will now be heard on November 25.
english
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>class Gem::Resolver::Conflict - RDoc Documentation</title> <script type="text/javascript"> var rdoc_rel_prefix = "../../"; var index_rel_prefix = "../../"; </script> <script src="../../js/jquery.js"></script> <script src="../../js/darkfish.js"></script> <link href="../../css/fonts.css" rel="stylesheet"> <link href="../../css/rdoc.css" rel="stylesheet"> <body id="top" role="document" class="class"> <nav role="navigation"> <div id="project-navigation"> <div id="home-section" role="region" title="Quick navigation" class="nav-section"> <h2> <a href="../../index.html" rel="home">Home</a> </h2> <div id="table-of-contents-navigation"> <a href="../../table_of_contents.html#pages">Pages</a> <a href="../../table_of_contents.html#classes">Classes</a> <a href="../../table_of_contents.html#methods">Methods</a> </div> </div> <div id="search-section" role="search" class="project-section initially-hidden"> <form action="#" method="get" accept-charset="utf-8"> <div id="search-field-wrapper"> <input id="search-field" role="combobox" aria-label="Search" aria-autocomplete="list" aria-controls="search-results" type="text" name="search" placeholder="Search" spellcheck="false" title="Type to search, Up and Down to navigate, Enter to load"> </div> <ul id="search-results" aria-label="Search Results" aria-busy="false" aria-expanded="false" aria-atomic="false" class="initially-hidden"></ul> </form> </div> </div> <div id="class-metadata"> <div id="parent-class-section" class="nav-section"> <h3>Parent</h3> <p class="link"><a href="../../Object.html">Object</a> </div> <!-- Method Quickref --> <div id="method-list-section" class="nav-section"> <h3>Methods</h3> <ul class="link-list" role="directory"> <li ><a href="#method-c-new">::new</a> <li ><a href="#method-i-conflicting_dependencies">#conflicting_dependencies</a> <li ><a href="#method-i-explain">#explain</a> <li ><a href="#method-i-explanation">#explanation</a> <li ><a href="#method-i-for_spec-3F">#for_spec?</a> <li ><a href="#method-i-request_path">#request_path</a> <li ><a href="#method-i-requester">#requester</a> </ul> </div> </div> </nav> <main role="main" aria-labelledby="class-Gem::Resolver::Conflict"> <h1 id="class-Gem::Resolver::Conflict" class="class"> class Gem::Resolver::Conflict </h1> <section class="description"> <p>Used internally to indicate that a dependency conflicted with a spec that would be activated.</p> </section> <section id="5Buntitled-5D" class="documentation-section"> <section class="attribute-method-details" class="method-section"> <header> <h3>Attributes</h3> </header> <div id="attribute-i-activated" class="method-detail"> <div class="method-heading attribute-method-heading"> <span class="method-name">activated</span><span class="attribute-access-type">[R]</span> </div> <div class="method-description"> <p>The specification that was activated prior to the conflict</p> </div> </div> <div id="attribute-i-dependency" class="method-detail"> <div class="method-heading attribute-method-heading"> <span class="method-name">dependency</span><span class="attribute-access-type">[R]</span> </div> <div class="method-description"> <p>The dependency that is in conflict with the activated gem.</p> </div> </div> </section> <section id="public-class-5Buntitled-5D-method-details" class="method-section"> <header> <h3>Public Class Methods</h3> </header> <div id="method-c-new" class="method-detail "> <div class="method-heading"> <span class="method-name">new</span><span class="method-args">(dependency, activated, failed_dep=dependency)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>Creates a new resolver conflict when <code>dependency</code> is in conflict with an already <code>activated</code> specification.</p> <div class="method-source-code" id="new-source"> <pre><span class="ruby-comment"># File lib/rubygems/resolver/conflict.rb, line 24</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier ruby-title">initialize</span>(<span class="ruby-identifier">dependency</span>, <span class="ruby-identifier">activated</span>, <span class="ruby-identifier">failed_dep</span>=<span class="ruby-identifier">dependency</span>) <span class="ruby-ivar">@dependency</span> = <span class="ruby-identifier">dependency</span> <span class="ruby-ivar">@activated</span> = <span class="ruby-identifier">activated</span> <span class="ruby-ivar">@failed_dep</span> = <span class="ruby-identifier">failed_dep</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> </section> <section id="public-instance-5Buntitled-5D-method-details" class="method-section"> <header> <h3>Public Instance Methods</h3> </header> <div id="method-i-conflicting_dependencies" class="method-detail "> <div class="method-heading"> <span class="method-name">conflicting_dependencies</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>Return the 2 dependency objects that conflicted</p> <div class="method-source-code" id="conflicting_dependencies-source"> <pre><span class="ruby-comment"># File lib/rubygems/resolver/conflict.rb, line 47</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier ruby-title">conflicting_dependencies</span> [<span class="ruby-ivar">@failed_dep</span>.<span class="ruby-identifier">dependency</span>, <span class="ruby-ivar">@activated</span>.<span class="ruby-identifier">request</span>.<span class="ruby-identifier">dependency</span>] <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-explain" class="method-detail "> <div class="method-heading"> <span class="method-name">explain</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>A string explanation of the conflict.</p> <div class="method-source-code" id="explain-source"> <pre><span class="ruby-comment"># File lib/rubygems/resolver/conflict.rb, line 40</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier ruby-title">explain</span> <span class="ruby-node">&quot;&lt;Conflict wanted: #{@failed_dep}, had: #{activated.spec.full_name}&gt;&quot;</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-explanation" class="method-detail "> <div class="method-heading"> <span class="method-name">explanation</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>Explanation of the conflict used by exceptions to print useful messages</p> <div class="method-source-code" id="explanation-source"> <pre><span class="ruby-comment"># File lib/rubygems/resolver/conflict.rb, line 54</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier ruby-title">explanation</span> <span class="ruby-identifier">activated</span> = <span class="ruby-ivar">@activated</span>.<span class="ruby-identifier">spec</span>.<span class="ruby-identifier">full_name</span> <span class="ruby-identifier">dependency</span> = <span class="ruby-ivar">@failed_dep</span>.<span class="ruby-identifier">dependency</span> <span class="ruby-identifier">requirement</span> = <span class="ruby-identifier">dependency</span>.<span class="ruby-identifier">requirement</span> <span class="ruby-identifier">alternates</span> = <span class="ruby-identifier">dependency</span>.<span class="ruby-identifier">matching_specs</span>.<span class="ruby-identifier">map</span> { <span class="ruby-operator">|</span><span class="ruby-identifier">spec</span><span class="ruby-operator">|</span> <span class="ruby-identifier">spec</span>.<span class="ruby-identifier">full_name</span> } <span class="ruby-keyword">unless</span> <span class="ruby-identifier">alternates</span>.<span class="ruby-identifier">empty?</span> <span class="ruby-identifier">matching</span> = <span class="ruby-identifier">&lt;&lt;-MATCHING</span>.<span class="ruby-identifier">chomp</span> <span class="ruby-value"> Gems matching %s: %s </span><span class="ruby-identifier"> MATCHING</span> <span class="ruby-identifier">matching</span> = <span class="ruby-identifier">matching</span> <span class="ruby-operator">%</span> [ <span class="ruby-identifier">dependency</span>, <span class="ruby-identifier">alternates</span>.<span class="ruby-identifier">join</span>(<span class="ruby-string">&#39;, &#39;</span>), ] <span class="ruby-keyword">end</span> <span class="ruby-identifier">explanation</span> = <span class="ruby-identifier">&lt;&lt;-EXPLANATION</span> <span class="ruby-value"> Activated %s which does not match conflicting dependency (%s) Conflicting dependency chains: %s versus: %s %s </span><span class="ruby-identifier"> EXPLANATION</span> <span class="ruby-identifier">explanation</span> <span class="ruby-operator">%</span> [ <span class="ruby-identifier">activated</span>, <span class="ruby-identifier">requirement</span>, <span class="ruby-identifier">request_path</span>(<span class="ruby-ivar">@activated</span>).<span class="ruby-identifier">reverse</span>.<span class="ruby-identifier">join</span>(<span class="ruby-string">&quot;, depends on\n &quot;</span>), <span class="ruby-identifier">request_path</span>(<span class="ruby-ivar">@failed_dep</span>).<span class="ruby-identifier">reverse</span>.<span class="ruby-identifier">join</span>(<span class="ruby-string">&quot;, depends on\n &quot;</span>), <span class="ruby-identifier">matching</span>, ] <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-for_spec-3F" class="method-detail "> <div class="method-heading"> <span class="method-name">for_spec?</span><span class="method-args">(spec)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>Returns true if the conflicting dependency&#39;s name matches <code>spec</code>.</p> <div class="method-source-code" id="for_spec-3F-source"> <pre><span class="ruby-comment"># File lib/rubygems/resolver/conflict.rb, line 96</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier ruby-title">for_spec?</span>(<span class="ruby-identifier">spec</span>) <span class="ruby-ivar">@dependency</span>.<span class="ruby-identifier">name</span> <span class="ruby-operator">==</span> <span class="ruby-identifier">spec</span>.<span class="ruby-identifier">name</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-request_path" class="method-detail "> <div class="method-heading"> <span class="method-name">request_path</span><span class="method-args">(current)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>Path of activations from the <code>current</code> list.</p> <div class="method-source-code" id="request_path-source"> <pre><span class="ruby-comment"># File lib/rubygems/resolver/conflict.rb, line 124</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier ruby-title">request_path</span>(<span class="ruby-identifier">current</span>) <span class="ruby-identifier">path</span> = [] <span class="ruby-keyword">while</span> <span class="ruby-identifier">current</span> <span class="ruby-keyword">do</span> <span class="ruby-keyword">case</span> <span class="ruby-identifier">current</span> <span class="ruby-keyword">when</span> <span class="ruby-constant">Gem</span><span class="ruby-operator">::</span><span class="ruby-constant">Resolver</span><span class="ruby-operator">::</span><span class="ruby-constant">ActivationRequest</span> <span class="ruby-keyword">then</span> <span class="ruby-identifier">path</span> <span class="ruby-operator">&lt;&lt;</span> <span class="ruby-node">&quot;#{current.request.dependency}, #{current.spec.version} activated&quot;</span> <span class="ruby-identifier">current</span> = <span class="ruby-identifier">current</span>.<span class="ruby-identifier">parent</span> <span class="ruby-keyword">when</span> <span class="ruby-constant">Gem</span><span class="ruby-operator">::</span><span class="ruby-constant">Resolver</span><span class="ruby-operator">::</span><span class="ruby-constant">DependencyRequest</span> <span class="ruby-keyword">then</span> <span class="ruby-identifier">path</span> <span class="ruby-operator">&lt;&lt;</span> <span class="ruby-node">&quot;#{current.dependency}&quot;</span> <span class="ruby-identifier">current</span> = <span class="ruby-identifier">current</span>.<span class="ruby-identifier">requester</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Gem</span><span class="ruby-operator">::</span><span class="ruby-constant">Exception</span>, <span class="ruby-node">&quot;[BUG] unknown request class #{current.class}&quot;</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-identifier">path</span> = [<span class="ruby-string">&#39;user request (gem command or Gemfile)&#39;</span>] <span class="ruby-keyword">if</span> <span class="ruby-identifier">path</span>.<span class="ruby-identifier">empty?</span> <span class="ruby-identifier">path</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-requester" class="method-detail "> <div class="method-heading"> <span class="method-name">requester</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>Return the Specification that listed the dependency</p> <div class="method-source-code" id="requester-source"> <pre><span class="ruby-comment"># File lib/rubygems/resolver/conflict.rb, line 151</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier ruby-title">requester</span> <span class="ruby-ivar">@failed_dep</span>.<span class="ruby-identifier">requester</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> </section> </section> </main> <footer id="validator-badges" role="contentinfo"> <p><a href="https://validator.w3.org/check/referer">Validate</a> <p>Generated by <a href="https://ruby.github.io/rdoc/">RDoc</a> 6.1.0. <p>Based on <a href="http://deveiate.org/projects/Darkfish-RDoc/">Darkfish</a> by <a href="http://deveiate.org"><NAME></a>. </footer>
html
Technology giant Microsoft and Austrian researchers have developed FlexCase - a prototype smartphone case that acts as a secondary e-ink display. Microsoft Research and the University of Applied Sciences Upper Austria created the device that can act as an extended touchscreen to mobile devices and can power the device, Tech Times reported. The smartphone case prototype can be flexed, tapped and twisted to control the main display. The FlexCase works similar to YotaPhone - the world's first smartphone that had two screens released in 2013. It had an e-ink display on the back and a regular LCD front screen. FlexCase allows users to interact with their phone in many ways. Its cover can be used as an extended visual clipboard that makes searching and typing easier. By simply bending the cover forward or backward, users can easily flip pages, zoom in and out, navigate pages and even rotate maps. Everyday motions can generate enough energy to be converted to electricity. The piezoelectric effect (push or pull) can be of use within multiple applications, including electronic frequency generation, detection and production of sound. The same principle is applied on the FlexCase prototype that uses piezoelectricity current to power the device. By allowing users to stretch, compress, flex, tap and twist the cover, an appropriate amount of energy is being applied that generates an electrical charge to operate the device. The FlexCase is scheduled to be presented at the "Computer-Human Interaction Conference" in May in California.
english
<reponame>Timehouse-Henri/wopi-proof-validator<filename>src/payloadBuilder.js const BN = require("bn.js"); module.exports = { build: function(input) { const fullUrl = percentEncode(input.url).toUpperCase(); //not sure about the escaping yet. const fullUrlBuffer = Buffer.from(fullUrl, "utf8"); const accessTokenBuffer = Buffer.from(input.accessToken, "utf8"); const timeBuffer = new BN(input.timestamp).toBuffer('big', 8); // <------- const expectedProofBuffer = Buffer.concat([ getLengthIn4Bytes(accessTokenBuffer), accessTokenBuffer, getLengthIn4Bytes(fullUrlBuffer), fullUrlBuffer, getLengthIn4Bytes(timeBuffer), timeBuffer ]); return expectedProofBuffer; } }; function getLengthIn4Bytes(buff) { const lengthBuffer = Buffer.alloc(4); lengthBuffer.writeUIntBE(buff.length, 0, 4); return lengthBuffer; } function percentEncode(url) { return url; }
javascript
<gh_stars>1-10 package org.arrowhead.wp5.aggmanager.impl.resources.entities; /*- * #%L * ARROWHEAD::WP5::Aggregator Manager * %% * Copyright (C) 2016 The ARROWHEAD Consortium * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class CustomerStat { private String customerId; private int numFlexOffers; private double totalRewardForFlexibility; public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public int getNumFlexOffers() { return numFlexOffers; } public void setNumFlexOffers(int numFlexOffers) { this.numFlexOffers = numFlexOffers; } public double getTotalRewardForFlexibility() { return totalRewardForFlexibility; } public void setTotalRewardForFlexibility(double totalRewardForFlexibility) { this.totalRewardForFlexibility = totalRewardForFlexibility; } }
java
@import be.objectify.deadbolt.java.views.html._ @import be.objectify.deadbolt.core.utils.TemplateUtils._ @(moviments:List[MovimentNota],nota:Nota, page:Page) @import play.i18n.Messages @main(Messages.get("moviments")) { <div id="maincontent" > <h4 class="titol">@Messages.get("comunitat")@nota.comunitat.pare.nom @nota.comunitat.nom (@nota.comunitat.nif)</h4> <h2 class="titol">@Messages.get("moviments_nota") @nota.codi - @nota.descripcio - (@Messages.get(nota.estat.estat)) </h2> <br> <style> </style> <table class="table table-striped"> <thead> <tr> <th class="text-right">@Messages.get("codi")</th> <th class="text-center">@Messages.get("data")</th> <th >@Messages.get("detall")</th> <th>@Messages.get("previsio")</th> <th>@Messages.get("estat")</th> <th>@Messages.get("autor")</th> <th class="text-center">@Messages.get("notificat")</th> @restrict(la(as("A"))) { <th class="text-center">@Messages.get("opcions")</th> } <th></th> </tr> </thead> <tbody> @if(page!=null){ @for( moviment <- moviments) { <tr> <td class="text-right">@moviment.codi</td> <td class="text-center">@moviment.fecha.format("dd/MM/yyyy")</td> <td style="width: 20%;">@moviment.detall</td> <td>@if(moviment.previsio!=null){@moviment.previsio.format("dd/MM/yyyy")}</td> <td>@Messages.get(moviment.estat.estat)</td> <td>@moviment.usuari.nom @moviment.usuari.cognoms </td> <td class="text-center">@if(moviment.notificada==true){Si}else{No} </td> <td class="text-center"> @restrict(la(as("A"))) { <a href="@routes.Notes.detallMovimentNota(moviment)"><i class="glyphicon glyphicon-pencil" data-toggle="tooltip" data-placement="top" title="@Messages.get("editar_movnota")"></i>&nbsp </a> <a onclick="javascript:del('@routes.Notes.borrarMovimentNota(moviment)')"><i class="glyphicon glyphicon-trash" data-toggle="tooltip" data-placement="top" title="@Messages.get("eliminar_movnota")"></i>&nbsp</a> } </td> </tr> } } </tbody> </table> <div id="page-selection" text-align="left"> </div> &nbsp&nbsp<a class="btn btn-info" href="@routes.Notes.llistarNotesFiltrades(1)"><span class="glyphicon glyphicon-backward" aria-hidden="true"></span> @Messages.get("back")</a> @restrict(la(as("P"),as("A"))) { &nbsp&nbsp <a class="btn btn-primary" href="@routes.Notes.nouMovimentNota(nota)"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> @Messages.get("registre")</a> <script> // init bootpag $('#page-selection').bootpag({ total: @page.totalPages, href: "@nota.codi?page={{number}}" }).on("page", function(event, /* page number here */ num){ }); </script> } </div> }
html
Airbags provide safety to the occupants of a car in the event of a crash. But car seats and airbags are a dangerous combination for children. Airbag deployment is rapid and forceful and can injure a child. If you transport your children in a car, car seat safety and safe seat choices are crucial matters. All modern cars come equipped with front airbags. These protect a driver and front-seat passenger from being flung forward toward the steering column and dashboard if there is a crash. Car airbags save lives. Some cars also have side airbags. These protect the occupants from impacts from the sides. Car airbags are designed to protect adults and teenagers but are a hazard for young children. The car seat, airbag combination can be deadly. Your child should never sit where an airbag deployment could reach them. A child in a rear-facing car seat in the front seat can be injured by the airbag hitting the back of the head or seat. Severe brain injury and even death can happen. A car seat is an essential piece of safety equipment for your child. It protects their head, neck, and back during the journey, during sudden stops, or in a crash. Children have heavy heads and weak neck muscles. A crash can severely injure their brain and spinal cord. A rear-facing car seat is protective. Your child depends on the car seat for safe travel. Make sure it meets the certification standards of your country and region before buying it. Avoid buying used since you can't know if it has been in a collision and is damaged within. The seat, when fitted right, should not move more than 1 inch (2.5 cms) in any direction. It is vital to learn the proper use of the 5-point harness to keep your child safe. - The harness straps should be in the slot level with or just below your child's shoulders, in a rear-facing car seat. - The harness straps should be in the slot level with or just above your child's shoulders, in a front-facing car seat. - Fasten the harness so there are no twists, and the harness cannot be pinched at the shoulder. - The chest clip should be at your child's armpit level. - Bulky suits or clothing prevent proper harness use. Where Should Children Ride? Children under 2 years should be in a rear-facing car seat secured to the back seat. They should continue to use this until they pass the height and weight limit specified by the manufacturer of the car seat. These seats protect their head, neck, and back if there is a crash. Children over 2 years can ride in a forward-facing safety seat. These seats also have a harness to keep your child safe and should be used till your child is 18 kg (40 lb) and can sit erect through the journey. This usually happens at age 4 to 6 years. Once your child has outgrown the forward-facing car seat, they should use a booster seat that enables them to use a seat belt effectively. Make sure the lap and shoulder belts are both snug. Children over 4 feet 9 inches (145 cms) can use a car seat belt without a booster seat. This usually happens between 8 to 12 years. Once your child is 13, they can ride in the front passenger seat, with lap and shoulder seat belts fastened. The lap belt should be across your child's upper thighs and not the stomach. Similarly, the shoulder belt should be across the shoulder and chest and not off the shoulder or on the neck or face. Your child's size is more important than age. For every transition (from a rear-facing seat to a front-facing safety seat, and so on), your child must be a good fit in the new position. A rear-facing car seat is advised as long as the child can fit into it, even beyond 2 years. Most currently available seats can accommodate children up to 40 lb (18 kg). The safest place for children under 13 is the rear seat. Children in car seats should preferably be placed in the center seat, as that is the safest place in the car. Your older child should also use this position, unless the center seat in the rear has only a lap seat belt. Your child may need constant watching during travel because of a health condition. They should ride in the back seat with an adult. If no adult is available, you can have them in the front seat, but push it as far back as possible. If possible, you should turn off the airbag on the passenger side. In general, it is not advisable to turn airbags off, as they reduce the safety of adults and teenagers. You should only travel with as many children as can be safely seated in the back seat with car seats and seat belts. If your older child has to ride in the front seat, move the seat as far from the airbag as possible. You should make sure the lap and shoulder seat belts are well-fitting. Teach your child in the front passenger seat to sit back in their seat at all times. They should never lean forward to adjust the music system or for any reason. Car crashes are the most frequent cause of death of children under age 4. Hundreds of children succumb to injuries sustained in car accidents. Many of these injuries and deaths are avoidable. You can keep your children safe by always using age- and weight-appropriate car seats, booster seats, and seat belts. This care reduces serious and fatal injuries by up to 80%. Airbags are a particular concern. Airbag deployment happens even with low-impact crashes, and several children have died as a result of being struck by the airbag. This is particularly tragic as the children were almost certain to have survived these low-speed accidents. When traveling with your children, seat them in the back seat and not within reach of any airbags. Make sure they're securely restrained, even for short distances, and set a good example by always using seat belts yourself.
english
<filename>src/process.cpp #include <unistd.h> #include <cctype> #include <sstream> #include <string> #include <vector> #include "process.h" #include "linux_parser.h" using std::string; using std::to_string; using std::vector; // TODO: Return this process's ID int Process::Pid() { return pid_;} // TODO: Return this process's CPU utilization float Process::CpuUtilization() const{ long uptime = LinuxParser::UpTime(); float hertz = sysconf(_SC_CLK_TCK); string line; string value; int total_time, utime, stime, cutime, cstime, starttime; int seconds; float cpu_usage; std::ifstream stream(LinuxParser::kProcDirectory + std::to_string(pid_) + LinuxParser::kStatFilename); if(stream.is_open()){ std::getline(stream, line); std::istringstream linestream(line); for(int i = 1; i <= 22; i++){ linestream >> value; if(i == 14){ utime = stoi(value); }else if(i == 15){ stime = stoi(value); }else if(i == 16){ cutime = stoi(value); }else if(i == 17){ cstime = stoi(value); }else if(i == 22){ starttime = stoi(value); } } total_time = utime + stime; total_time = total_time + cutime + cstime; seconds = uptime - starttime / hertz; cpu_usage = total_time / hertz / seconds; } return cpu_usage; } // TODO: Return the command that generated this process string Process::Command() { string command = LinuxParser::Command(pid_); string cmd = ""; if(command.size() > 40){ for(int i = 0; i <= 40; i++){ cmd = cmd + command[i]; } cmd = cmd + "..."; return cmd; } return command; } // TODO: Return this process's memory utilization string Process::Ram() { return LinuxParser::Ram(pid_); } // TODO: Return the user (name) that generated this process string Process::User() { return LinuxParser::User(pid_); } // TODO: Return the age of this process (in seconds) long int Process::UpTime() { return LinuxParser::UpTime() - LinuxParser::UpTime(pid_); } // TODO: Overload the "less than" comparison operator for Process objects // REMOVE: [[maybe_unused]] once you define the function bool Process::operator<(Process const& a) const { return a.CpuUtilization() < this->CpuUtilization(); }
cpp
<filename>src/models/r4b/Questionnaire_Item.rs<gh_stars>0 #![allow(unused_imports, non_camel_case_types)] use crate::models::r4b::Coding::Coding; use crate::models::r4b::Element::Element; use crate::models::r4b::Extension::Extension; use crate::models::r4b::Questionnaire_AnswerOption::Questionnaire_AnswerOption; use crate::models::r4b::Questionnaire_EnableWhen::Questionnaire_EnableWhen; use crate::models::r4b::Questionnaire_Initial::Questionnaire_Initial; use serde_json::json; use serde_json::value::Value; use std::borrow::Cow; /// A structured set of questions intended to guide the collection of answers from /// end-users. Questionnaires provide detailed control over order, presentation, /// phraseology and grouping to allow coherent, consistent data collection. #[derive(Debug)] pub struct Questionnaire_Item<'a> { pub(crate) value: Cow<'a, Value>, } impl Questionnaire_Item<'_> { pub fn new(value: &Value) -> Questionnaire_Item { Questionnaire_Item { value: Cow::Borrowed(value), } } pub fn to_json(&self) -> Value { (*self.value).clone() } /// Extensions for definition pub fn _definition(&self) -> Option<Element> { if let Some(val) = self.value.get("_definition") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for enableBehavior pub fn _enable_behavior(&self) -> Option<Element> { if let Some(val) = self.value.get("_enableBehavior") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for linkId pub fn _link_id(&self) -> Option<Element> { if let Some(val) = self.value.get("_linkId") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for maxLength pub fn _max_length(&self) -> Option<Element> { if let Some(val) = self.value.get("_maxLength") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for prefix pub fn _prefix(&self) -> Option<Element> { if let Some(val) = self.value.get("_prefix") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for readOnly pub fn _read_only(&self) -> Option<Element> { if let Some(val) = self.value.get("_readOnly") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for repeats pub fn _repeats(&self) -> Option<Element> { if let Some(val) = self.value.get("_repeats") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for required pub fn _required(&self) -> Option<Element> { if let Some(val) = self.value.get("_required") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for text pub fn _text(&self) -> Option<Element> { if let Some(val) = self.value.get("_text") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for type pub fn _type(&self) -> Option<Element> { if let Some(val) = self.value.get("_type") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// One of the permitted answers for a "choice" or "open-choice" question. pub fn answer_option(&self) -> Option<Vec<Questionnaire_AnswerOption>> { if let Some(Value::Array(val)) = self.value.get("answerOption") { return Some( val.into_iter() .map(|e| Questionnaire_AnswerOption { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// A reference to a value set containing a list of codes representing permitted /// answers for a "choice" or "open-choice" question. pub fn answer_value_set(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("answerValueSet") { return Some(string); } return None; } /// A terminology code that corresponds to this group or question (e.g. a code from /// LOINC, which defines many questions and answers). pub fn code(&self) -> Option<Vec<Coding>> { if let Some(Value::Array(val)) = self.value.get("code") { return Some( val.into_iter() .map(|e| Coding { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// This element is a URI that refers to an [ElementDefinition] /// (elementdefinition.html) that provides information about this item, including /// information that might otherwise be included in the instance of the Questionnaire /// resource. A detailed description of the construction of the URI is shown in /// Comments, below. If this element is present then the following element values /// MAY be derived from the Element Definition if the corresponding elements of this /// Questionnaire resource instance have no value: * code (ElementDefinition.code) /// * type (ElementDefinition.type) * required (ElementDefinition.min) * /// repeats (ElementDefinition.max) * maxLength (ElementDefinition.maxLength) * /// answerValueSet (ElementDefinition.binding) * options (ElementDefinition.binding). pub fn definition(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("definition") { return Some(string); } return None; } /// Controls how multiple enableWhen values are interpreted - whether all or any must /// be true. pub fn enable_behavior(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("enableBehavior") { return Some(string); } return None; } /// A constraint indicating that this item should only be enabled (displayed/allow /// answers to be captured) when the specified condition is true. pub fn enable_when(&self) -> Option<Vec<Questionnaire_EnableWhen>> { if let Some(Value::Array(val)) = self.value.get("enableWhen") { return Some( val.into_iter() .map(|e| Questionnaire_EnableWhen { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// May be used to represent additional information that is not part of the basic /// definition of the element. To make the use of extensions safe and manageable, /// there is a strict set of governance applied to the definition and use of /// extensions. Though any implementer can define an extension, there is a set of /// requirements that SHALL be met as part of the definition of the extension. pub fn extension(&self) -> Option<Vec<Extension>> { if let Some(Value::Array(val)) = self.value.get("extension") { return Some( val.into_iter() .map(|e| Extension { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// Unique id for the element within a resource (for internal references). This may be /// any string value that does not contain spaces. pub fn id(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("id") { return Some(string); } return None; } /// One or more values that should be pre-populated in the answer when initially /// rendering the questionnaire for user input. pub fn initial(&self) -> Option<Vec<Questionnaire_Initial>> { if let Some(Value::Array(val)) = self.value.get("initial") { return Some( val.into_iter() .map(|e| Questionnaire_Initial { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// Text, questions and other groups to be nested beneath a question or group. pub fn item(&self) -> Option<Vec<Questionnaire_Item>> { if let Some(Value::Array(val)) = self.value.get("item") { return Some( val.into_iter() .map(|e| Questionnaire_Item { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// An identifier that is unique within the Questionnaire allowing linkage to the /// equivalent item in a QuestionnaireResponse resource. pub fn link_id(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("linkId") { return Some(string); } return None; } /// The maximum number of characters that are permitted in the answer to be considered /// a "valid" QuestionnaireResponse. pub fn max_length(&self) -> Option<i64> { if let Some(val) = self.value.get("maxLength") { return Some(val.as_i64().unwrap()); } return None; } /// May be used to represent additional information that is not part of the basic /// definition of the element and that modifies the understanding of the element /// in which it is contained and/or the understanding of the containing element's /// descendants. Usually modifier elements provide negation or qualification. To make /// the use of extensions safe and manageable, there is a strict set of governance /// applied to the definition and use of extensions. Though any implementer can define /// an extension, there is a set of requirements that SHALL be met as part of the /// definition of the extension. Applications processing a resource are required to /// check for modifier extensions. Modifier extensions SHALL NOT change the meaning /// of any elements on Resource or DomainResource (including cannot change the meaning /// of modifierExtension itself). pub fn modifier_extension(&self) -> Option<Vec<Extension>> { if let Some(Value::Array(val)) = self.value.get("modifierExtension") { return Some( val.into_iter() .map(|e| Extension { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// A short label for a particular group, question or set of display text within the /// questionnaire used for reference by the individual completing the questionnaire. pub fn prefix(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("prefix") { return Some(string); } return None; } /// An indication, when true, that the value cannot be changed by a human respondent /// to the Questionnaire. pub fn read_only(&self) -> Option<bool> { if let Some(val) = self.value.get("readOnly") { return Some(val.as_bool().unwrap()); } return None; } /// An indication, if true, that the item may occur multiple times in the response, /// collecting multiple answers for questions or multiple sets of answers for groups. pub fn repeats(&self) -> Option<bool> { if let Some(val) = self.value.get("repeats") { return Some(val.as_bool().unwrap()); } return None; } /// An indication, if true, that the item must be present in a "completed" /// QuestionnaireResponse. If false, the item may be skipped when answering the /// questionnaire. pub fn required(&self) -> Option<bool> { if let Some(val) = self.value.get("required") { return Some(val.as_bool().unwrap()); } return None; } /// The name of a section, the text of a question or text content for a display item. pub fn text(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("text") { return Some(string); } return None; } /// The type of questionnaire item this is - whether text for display, a grouping of /// other items or a particular type of data to be captured (string, integer, coded /// choice, etc.). pub fn fhir_type(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("type") { return Some(string); } return None; } pub fn validate(&self) -> bool { if let Some(_val) = self._definition() { if !_val.validate() { return false; } } if let Some(_val) = self._enable_behavior() { if !_val.validate() { return false; } } if let Some(_val) = self._link_id() { if !_val.validate() { return false; } } if let Some(_val) = self._max_length() { if !_val.validate() { return false; } } if let Some(_val) = self._prefix() { if !_val.validate() { return false; } } if let Some(_val) = self._read_only() { if !_val.validate() { return false; } } if let Some(_val) = self._repeats() { if !_val.validate() { return false; } } if let Some(_val) = self._required() { if !_val.validate() { return false; } } if let Some(_val) = self._text() { if !_val.validate() { return false; } } if let Some(_val) = self._type() { if !_val.validate() { return false; } } if let Some(_val) = self.answer_option() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.answer_value_set() {} if let Some(_val) = self.code() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.definition() {} if let Some(_val) = self.enable_behavior() {} if let Some(_val) = self.enable_when() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.extension() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.id() {} if let Some(_val) = self.initial() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.item() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.link_id() {} if let Some(_val) = self.max_length() {} if let Some(_val) = self.modifier_extension() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.prefix() {} if let Some(_val) = self.read_only() {} if let Some(_val) = self.repeats() {} if let Some(_val) = self.required() {} if let Some(_val) = self.text() {} if let Some(_val) = self.fhir_type() {} return true; } } #[derive(Debug)] pub struct Questionnaire_ItemBuilder { pub(crate) value: Value, } impl Questionnaire_ItemBuilder { pub fn build(&self) -> Questionnaire_Item { Questionnaire_Item { value: Cow::Owned(self.value.clone()), } } pub fn with(existing: Questionnaire_Item) -> Questionnaire_ItemBuilder { Questionnaire_ItemBuilder { value: (*existing.value).clone(), } } pub fn new() -> Questionnaire_ItemBuilder { let mut __value: Value = json!({}); return Questionnaire_ItemBuilder { value: __value }; } pub fn _definition<'a>(&'a mut self, val: Element) -> &'a mut Questionnaire_ItemBuilder { self.value["_definition"] = json!(val.value); return self; } pub fn _enable_behavior<'a>(&'a mut self, val: Element) -> &'a mut Questionnaire_ItemBuilder { self.value["_enableBehavior"] = json!(val.value); return self; } pub fn _link_id<'a>(&'a mut self, val: Element) -> &'a mut Questionnaire_ItemBuilder { self.value["_linkId"] = json!(val.value); return self; } pub fn _max_length<'a>(&'a mut self, val: Element) -> &'a mut Questionnaire_ItemBuilder { self.value["_maxLength"] = json!(val.value); return self; } pub fn _prefix<'a>(&'a mut self, val: Element) -> &'a mut Questionnaire_ItemBuilder { self.value["_prefix"] = json!(val.value); return self; } pub fn _read_only<'a>(&'a mut self, val: Element) -> &'a mut Questionnaire_ItemBuilder { self.value["_readOnly"] = json!(val.value); return self; } pub fn _repeats<'a>(&'a mut self, val: Element) -> &'a mut Questionnaire_ItemBuilder { self.value["_repeats"] = json!(val.value); return self; } pub fn _required<'a>(&'a mut self, val: Element) -> &'a mut Questionnaire_ItemBuilder { self.value["_required"] = json!(val.value); return self; } pub fn _text<'a>(&'a mut self, val: Element) -> &'a mut Questionnaire_ItemBuilder { self.value["_text"] = json!(val.value); return self; } pub fn _type<'a>(&'a mut self, val: Element) -> &'a mut Questionnaire_ItemBuilder { self.value["_type"] = json!(val.value); return self; } pub fn answer_option<'a>( &'a mut self, val: Vec<Questionnaire_AnswerOption>, ) -> &'a mut Questionnaire_ItemBuilder { self.value["answerOption"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn answer_value_set<'a>(&'a mut self, val: &str) -> &'a mut Questionnaire_ItemBuilder { self.value["answerValueSet"] = json!(val); return self; } pub fn code<'a>(&'a mut self, val: Vec<Coding>) -> &'a mut Questionnaire_ItemBuilder { self.value["code"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn definition<'a>(&'a mut self, val: &str) -> &'a mut Questionnaire_ItemBuilder { self.value["definition"] = json!(val); return self; } pub fn enable_behavior<'a>(&'a mut self, val: &str) -> &'a mut Questionnaire_ItemBuilder { self.value["enableBehavior"] = json!(val); return self; } pub fn enable_when<'a>( &'a mut self, val: Vec<Questionnaire_EnableWhen>, ) -> &'a mut Questionnaire_ItemBuilder { self.value["enableWhen"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn extension<'a>(&'a mut self, val: Vec<Extension>) -> &'a mut Questionnaire_ItemBuilder { self.value["extension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn id<'a>(&'a mut self, val: &str) -> &'a mut Questionnaire_ItemBuilder { self.value["id"] = json!(val); return self; } pub fn initial<'a>( &'a mut self, val: Vec<Questionnaire_Initial>, ) -> &'a mut Questionnaire_ItemBuilder { self.value["initial"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn item<'a>( &'a mut self, val: Vec<Questionnaire_Item>, ) -> &'a mut Questionnaire_ItemBuilder { self.value["item"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn link_id<'a>(&'a mut self, val: &str) -> &'a mut Questionnaire_ItemBuilder { self.value["linkId"] = json!(val); return self; } pub fn max_length<'a>(&'a mut self, val: i64) -> &'a mut Questionnaire_ItemBuilder { self.value["maxLength"] = json!(val); return self; } pub fn modifier_extension<'a>( &'a mut self, val: Vec<Extension>, ) -> &'a mut Questionnaire_ItemBuilder { self.value["modifierExtension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn prefix<'a>(&'a mut self, val: &str) -> &'a mut Questionnaire_ItemBuilder { self.value["prefix"] = json!(val); return self; } pub fn read_only<'a>(&'a mut self, val: bool) -> &'a mut Questionnaire_ItemBuilder { self.value["readOnly"] = json!(val); return self; } pub fn repeats<'a>(&'a mut self, val: bool) -> &'a mut Questionnaire_ItemBuilder { self.value["repeats"] = json!(val); return self; } pub fn required<'a>(&'a mut self, val: bool) -> &'a mut Questionnaire_ItemBuilder { self.value["required"] = json!(val); return self; } pub fn text<'a>(&'a mut self, val: &str) -> &'a mut Questionnaire_ItemBuilder { self.value["text"] = json!(val); return self; } pub fn fhir_type<'a>(&'a mut self, val: &str) -> &'a mut Questionnaire_ItemBuilder { self.value["type"] = json!(val); return self; } }
rust
In news Recently, the Government of India has accorded sanction to Team CLAW to lead a team of people with disabilities to scale Siachen Glacier and create a new world record for the largest team of people with disabilities. - This is the land world record expedition part of ‘Operation Blue Freedom Triple World Records’ being undertaken. - Triple Elemental World Records is a series of world records being attempted by the team in 2021 of collectives of people with disabilities achieving great feats on land, in air and underwater. What is Team CLAW and Operation Blue Freedom? - Team CLAW: Team CLAW (Conquer Land Air Water) is a team of ex-Indian Special Forces commandos. - Generally, all are either from Indian Army Para Commandos or the Naval Marine Commandos, also known as the MARCOS. - These veterans have multiple specialisations such as skydiving, scuba diving, mountaineering, etc. - The initiative was taken by Major Vivek Jacob, a Para (Special Forces) officer. - Operation Blue Freedom: It is a social impact venture aimed at rehabilitating people with disabilities through adaptive adventure sports. - Aim: To shatter the common perception of pity, charity and inability associated with people with disabilities and recreate it to one of dignity, freedom and ability. - It was launched in 2019 by Team CLAW. What is Siachen Glacier? - The Siachen Glacier is located in the Eastern Karakoram range in the Himalayas, just northeast of Point NJ9842 where the Line of Control between India and Pakistan ends. - It is the Second-Longest glacier in the World’s Non-Polar areas. - Fedchenko Glacier, located in Yazgulem Range, Tajikistan is the Longest glacier in the World’s Non-Polar areas. - The Siachen Glacier lies immediately south of the great drainage divide that separates the Eurasian Plate from the Indian subcontinent in the extensively glaciated portion of the Karakoram sometimes called the “Third Pole”. - It is the world’s highest battlefield. - The entire Siachen Glacier has been under the administration of India since 1984 (Operation Meghdoot).
english
[{"province":"新疆维吾尔自治区","city":"巴音郭楞蒙古自治州","area":"轮台县","name":"轮台县哈尔巴克乡邮政代办所","code":"841601","address":"新疆巴州轮台县哈尔巴克","phone":"0996-4691500"},{"province":"新疆维吾尔自治区","city":"巴音郭楞蒙古自治州","area":"轮台县","name":"轮台县群巴克邮政支局","code":"841601","address":"轮台县群巴克镇","phone":"0996-4934004"}]
json
import React, { Component } from 'react'; import { View, DeviceEventEmitter, StyleSheet, TouchableOpacity, ScrollView, Text, Alert, } from 'react-native'; import ViewUtils from '../../util/ViewUtils'; import ComponentWithNavigationBar from '../../common/NavigatorBar'; import LanguageDAO, { FLAG_LANGUAGE } from '../../expand/dao/LanguageDAO'; import Checkbox from 'react-native-check-box'; import ArrayUtils from '../../util/ArrayUtils'; import GlobalStyles from '../../../res/styles/GlobalStyles'; import { ACTION_HOME, FLAG_TAB } from '../HomePage'; import { Icon } from 'react-native-elements'; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, tips: { fontSize: 29, }, line: { backgroundColor: 'darkgray', height: 1, }, item: { flexDirection: 'row', alignItems: 'center', }, }); export default class CustomKeyPage extends Component { constructor(props) { super(props); this.changeValues = []; const { state } = this.props.navigation; try { this.isRemoveKey = !!state.params.isRemoveKey; } catch (e) { this.isRemoveKey = false; } this.state = { dataArray: [], }; } componentDidMount() { const { state } = this.props.navigation; this.flag = state.params.flag; this.languageDAO = new LanguageDAO(this.flag); this.loadData(); } loadData() { this.languageDAO .fetch() .then(result => { this.setState({ dataArray: result, }); this.renderView(); }) .catch(error => { console.log(error); }); } renderCheckBox(data) { let leftText = data.name; // let isChecked = this.isRemoveKey ? false : data.checked; let isChecked = data.checked; return ( <View style={{ flex: 1, padding: 10 }}> <Checkbox leftText={leftText} onClick={() => this.onClick(data)} isChecked={isChecked} checkedImage={ <Icon color={this.props.theme.themeColor} name="check-box" /> } unCheckedImage={ <Icon color={this.props.theme.themeColor} name="check-box-outline-blank" /> } /> </View> ); } renderView() { if (!this.state.dataArray || this.state.dataArray.length === 0) return null; let len = this.state.dataArray.length; let views = []; for (let i = 0, l = len - 2; i < l; i += 2) { views.push( <View key={i}> <View style={styles.item}> {this.renderCheckBox(this.state.dataArray[i])} {this.renderCheckBox(this.state.dataArray[i + 1])} </View> <View style={styles.line} /> </View> ); } // deal with the rest keys views.push( <View key={len - 1}> <View style={styles.item}> {len % 2 === 0 ? this.renderCheckBox(this.state.dataArray[len - 2]) : null} {this.renderCheckBox(this.state.dataArray[len - 1])} </View> <View style={styles.line} /> </View> ); this.setState({ selectionSection: views, }); } onSave() { if (this.changeValues.length === 0) { this.props.navigation.goBack(); return; } if (this.isRemoveKey) { for (let i = 0, l = this.changeValues.length; i < l; i++) { ArrayUtils.remove(this.state.dataArray, this.changeValues[i]); } } this.languageDAO.save(this.state.dataArray); const { state } = this.props.navigation; let jumpToTab = state.params.flag === FLAG_LANGUAGE.flag_key ? FLAG_TAB.flag_popularTab : FLAG_TAB.flag_trendingTab; DeviceEventEmitter.emit('ACTION_HOME', ACTION_HOME.A_RESTART, { jumpToTab: jumpToTab, }); } onClick(data) { // if (!this.isRemoveKey) data.checked = !data.checked; data.checked = !data.checked; this.renderView(); ArrayUtils.updateArray(this.changeValues, data); } onBack() { if (this.changeValues.length === 0) { this.props.navigation.goBack(); return; } Alert.alert( 'Note', 'Do you want to save?', [ { text: 'NO', onPress: () => this.props.navigation.goBack() }, { text: 'YES', onPress: () => this.onSave() }, ], { cancelable: false } ); } render() { let title = this.isRemoveKey ? 'Remove Key' : 'Custom Key'; title = this.flag === FLAG_LANGUAGE.flag_language ? 'Custom Language' : title; let rightButtonTitle = this.isRemoveKey ? 'Remove' : 'Save'; let rightButton = ( <View style={{ flexDirection: 'row', alignItems: 'center', }} > {!this.isRemoveKey ? ( <TouchableOpacity onPress={() => { this.props.navigation.navigate('searchPage', { ...this.props, }); }} > <Icon name="search" size={24} color="white" /> </TouchableOpacity> ) : null} {ViewUtils.getRightButton(() => this.onBack(), rightButtonTitle)} </View> ); let titleText = <Text style={GlobalStyles.titleText}>{title}</Text>; let leftButton = ViewUtils.getLeftButton(() => this.onBack()); return ( <View style={styles.container}> {ComponentWithNavigationBar( titleText, leftButton, rightButton, this.props.theme.themeColor )} <ScrollView>{this.state.selectionSection}</ScrollView> </View> ); } }
javascript
{ "title": "Advert Tile", "version": "1.00", "name": "AdvertTile", "description": "Tiles to present offers and products", "author": "<NAME>" }
json
Meanwhile, the dollar index, which gauges the greenback's strength against a basket of six currencies, advanced 0. 25 per cent to 90. 39. The rupee edged higher by 2 paise to settle at 72. 92 (provisional) against the US dollar on Wednesday, ahead of the outcome of the US central bank's meeting. At the interbank forex market, the rupee opened at 72. 91 against the American currency and hit an intra-day high of 72. 78 and a low of 72. 94 in day trade. It finally finished at 72. 92, higher by 2 paise over its last close. On Monday, the rupee had settled at 72. 94 against the American currency. Meanwhile, the dollar index, which gauges the greenback's strength against a basket of six currencies, advanced 0. 25 per cent to 90. 39. "Indian Rupee appreciated ahead of US Federal Reserve monetary policy meeting. US Federal Reserve is expected to continue with its ultra-lose monetary policy," said Saif Mukadam, Research Analyst, Sharekhan by BNP Paribas. Additionally, market participants are careful ahead of the progress on US stimulus package, Mukadam noted. Further, the rupee gained strength as hopes of global economic recovery from pandemic got a boost after IMF upgraded its Global Economic Outlook for 2021, he said. The IMF on Tuesday projected an impressive 11. 5 per cent growth rate for India in 2021, making the country the only major economy of the world to register double-digit growth this year amid the coronavirus pandemic. However, sharp gain in the local unit was prevented due to a plunge in domestic markets, Mukadam noted. On the domestic equity market front, the BSE Sensex ended 937. 66 points or 1. 94 per cent lower at 47,409. 93, while the broader NSE Nifty declined 271. 40 points or 1. 91 per cent to 13,967. 50. Foreign institutional investors were net sellers in the capital market as they offloaded shares worth ₹765. 30 crore on a net basis on Monday, according to exchange data. Forex and equity markets were closed on Tuesday on account of Republic Day. Brent crude futures, the global oil benchmark, rose 0. 61 per cent to USD 56. 25 per barrel.
english
The CSK owner warns against SC action in relation to the IPL corruption case. India Cements Limited – owner of Indian Premier League (IPL) franchise Chennai Super Kings (CSK) – told the Supreme Court on Friday that any action against it would have disastrous consequences for the cash-rich Twenty20 tournament. If any orders are passed against India Cements it could have “disastrous consequences not only for this respondent [India Cements] but also for the entire league, the cricketers involved, third parties such as sponsors, apart from millions of fans, CSK being arguably the most valuable and popular team in IPL,” India Cements said in its response to the Mudgal Committee report. Mudgal Committee inquired into the allegations of match fixing and betting on the direction of the apex court and had submitted its final report November 1. The committee, in its report, said that N Srinivasan‘s son-in-law Gurunath Meiyappan was involved in betting while exonerating him of spot fixing charges. The committee described Meiyappan as a “team official” of CSK. Stating that Meiyappan had nothing to do with it, India Cements said the company has over 89,000 share-holders including a large percentage of public institutional shareholding. Meiyappan was earlier described as “cricket enthusiast”. “Mr. Guruynath Meiyappan is neither shareholder, nor a director nor an employee and has not drawn any salary, honorarium or compensation of any kind from Chennai Super Kings or from India Cements,” the company said in its response. “The material on the basis of which such a finding has been arrived at ought to be provided to this respondent to enable this respondent to deal with the same if and when necessitated,” India Cements said. Having said that Meiyappan had no official relation with CSK, India Cements said that there was no “infraction of the IPL Code of Conduct, Rules and Regulations that have been pointed out by the probe committee” against it in its present report.
english
// Copyright 2022 LiYechao // // 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. import { useApolloClient } from '@apollo/client' import { useCallback } from 'react' import Storage, { Token } from '../Storage' export function useLogin() { const client = useApolloClient() return useCallback((account: { token: Token }) => { Storage.token = account.token client.resetStore() }, []) } export function useSignOut() { const client = useApolloClient() return useCallback(() => { Storage.token = null client.resetStore() }, []) }
typescript
<gh_stars>0 // // main.cpp // Zad6 // // Created by <NAME> on 31/03/16. // Copyright © 2016 <NAME>. All rights reserved. // #include <iostream> typedef int (*PTRFUN)(); class B { public: virtual int prva() = 0; virtual int druga() = 0; }; class D: public B { public: virtual int prva() { return 0; } virtual int druga() { return 42; } }; int main(int argc, const char * argv[]) { D *obj = new D(); size_t *vTable = *(size_t**)obj; int prva = ((PTRFUN) vTable[0])(); int druga = ((PTRFUN) vTable[1])(); printf("Prva: %d\nDruga: %d\n", prva, druga); }
cpp
<reponame>navikt/eskattekortbestilling-schema<gh_stars>0 package no.nav.os.eskatt.eskattekortbestilling; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.bind.annotation.adapters.XmlAdapter; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; public class LocalDateTimeAdapter extends XmlAdapter<String,LocalDateTime> { private static final Logger LOGGER = LoggerFactory.getLogger(LocalDateTimeAdapter.class); @Override public LocalDateTime unmarshal(String localDateTimeAsString) { try { return LocalDateTime.parse(localDateTimeAsString, DateTimeFormatter.ISO_DATE_TIME); } catch (DateTimeParseException e) { LOGGER.error("Parsing av dato '{}' feilet!", localDateTimeAsString); return null; } } @Override public String marshal(LocalDateTime localDateTime) { return localDateTime != null ? localDateTime.format(DateTimeFormatter.ISO_DATE_TIME) : null; } }
java
::marker { color: var(--roxo); font-size: 1.2em; } a{ color: var(--roxo); } p{ margin-bottom: 10px; margin-top: 10px; } h1{ margin-bottom: 15px; margin-top: 15px; color: var(--yellow-2); } h2{ margin-bottom: 15px; margin-top: 15px; } #markdown{ height: calc( 100vh + 72px - 268px - 64px) !important; padding: 20px; color: var(--white); padding-left: 50px } em{ font-style: italic; } strong{ font-weight: bold; color: var(--yellow-2); } code{ background: var(--brown); color: #151925; padding: 4px; border-radius: 8px; max-width: 100%; } ul{ margin-left: 44px; } ol{ margin-left: 54px; } p{ line-height: 28px } pre{ margin: 14px; max-width: 100%; } blockquote{ margin: 24px; background: #1f2238; padding: 10px; border-radius: 8px; padding-left: 14px; padding-right: 14px; }
css
# anno-vt annotation binary vector tiles generated from GSI vector tile engineering experiment
markdown
{ "body": "BUT AS THEY SERVE TO SECURE THAT PERFECT DURABLE HAPPINESS HEREAFTER.", "next": "https://raw.githubusercontent.com/CAPSELOCKE/CAPSELOCKE/master/tweets/4767.json" }
json
<gh_stars>10-100 #include <iostream> using namespace std; int divisors(int n){ int count=0; int num = n; while(n>0){ int digit = n%10; if(digit!=0 && num%digit==0){ count++; } n=n/10; } return count; } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; cout<<divisors(n)<<endl; } }
cpp
<reponame>faisalsyfl/dinamik12<filename>kompetisijaringan/theme/standard/style/course.css /** Course formats **/ .course-content ul.weeks li.section {border:1px solid #DDD;} .course-content ul.weeks li.section .content {background-color:#FAFAFA;padding:5px 10px;} .course-content ul.weeks li.section .content h3 {margin:0;color:#777;font-weight: normal;} .course-content ul.weeks li.section .left {padding:4px 0;} .course-content ul.weeks li.section .right {padding:4px 0;} /** Course **/ #page-course-recent h2 {font-size:1.1em;} #page-course-recent .user {font-size:0.75em;} #page-course-recent .grade {font-style: italic;font-size:0.9em;} #page-course-recent .forum-recent .reply .title {font-style: italic;font-size:0.9em;} #page-course-recent .forum-recent .discussion .title {font-weight:bold;font-style: italic;font-size:0.9em;} .path-site .availabilityinfo, .path-course-view .availabilityinfo {font-size:0.85em;color:#aaa;} .path-site .availabilityinfo strong, .path-course-view .availabilityinfo strong {font-weight:normal;color:black;} .path-course-view .dimmed_text img {opacity:0.3;filter: alpha(opacity='30');} .path-course-view .section {font-size:1em;line-height:1.2em;} .path-course-view .section .weekdates {margin: 0;font-weight: normal;font-size: 1em;} .path-course-view .section .groupinglabel {color: #666666;} .path-course-view .section .groupinglabel.dimmed_text {color: #AAA;} .path-course-view .section .left {font-weight:bold;} .path-course-view .weeks .section, .path-course-view .topics .section, .path-course-view .section td {border-color:#DDDDDD;} .path-course-view .weeks .content , .path-course-view .topics .content, .path-course-view .weeks .section, .path-course-view .topics .section {background: #FAFAFA;} .path-course-view .section td.side {background: #FFFFFF;} .path-course-view .weeks .current, .path-course-view .topics .current, .path-course-view .current td.side {background: #9fc6fb;} .path-course-view .section-summary.current {border-color: #9fc6fb;} .path-course-view .weeks .hidden, .path-course-view .topics .hidden, .path-course-view .hidden td.side {background: #DDDDDD;} .path-course-view .section .weekdates {color: #777777;} .path-course-view .weeks .weekdates , .path-course-view .topics .weekdates {color: #333333;} .weeks li.section , .topics li.section {border-style:solid;border-width:1px;} .weeks .content, .topics .content {padding: 5px;} #page-report-outline-user .section {border-color:#AAAAAA;} #page-admin-report .plugin, #page-report .plugin, #page-import .plugin {margin-bottom: 20px;margin-left:10%;margin-right:10%;border: 1px solid #cecece;background-color: #fdfdfd;} .path-course-view .unread {background: #9EBEFF;} .path-course-view .completionprogress {font-size:0.80em; margin-right: 1.5em; } #page-report #content {padding-top:15px;padding-bottom:15px;} #page-report #region-main p, #page-report-log-index #region-main .info, #page-report-loglive-index #region-main .info, #page-report-stats-index #region-main .graph {text-align: center;} #page-report .logselectform, #page-report .participationselectform, #page-report-log-index .logselectform, #page-report-participation-index .participationselectform {text-align:center;} .addcoursebutton {text-align:center;} .categorypicker {text-align:center;margin-bottom:10px;} .path-report-outline .loginfo {text-align:center;margin: 1em;} /* Courses and categories lists */ .coursebox {border:1px solid #DDD;border-color:#DDDDDD;padding:3px 0;} #page-enrol-index .generalbox.info, #page-course-info .generalbox.info {border:none;} .coursebox .content .teachers, .coursebox .content .coursecat, .coursebox .content .summary, .coursebox .content .courseimage, .coursebox .content .coursefile, .coursebox.remotecoursebox .remotecourseinfo {font-size:0.9em;} .course_category_tree .category >.info {background-image:url([[pix:theme|hgradient]]);background-repeat: repeat-x;background-color:#e1e1df;border:1px solid #ddd;margin:3px 0;} .course_category_tree.frontpage-category-names .category >.info {background:none;border:none;margin:0;} .courses .coursebox.collapsed {border:1px solid #eeeeee;padding:3px 0;} .courses .coursebox.even {background-color:#f6f6f6;} .courses .coursebox:hover, .course_category_tree .courses > .paging.paging-morelink:hover {background-color:#eeeeee;} .course_category_tree .paging.paging-morelink a {font-size:90%} /* Publication */ #page-course-publish-metadata .metadatatext {width: 400px;} #page-course-publish-metadata .hubscreenshot { display:inline; float:left; margin-right:10px; } #page-course-publish-metadata .hubscreenshot img {vertical-align: bottom;} #page-course-publish-metadata .hubdescription {} #page-course-publish-metadata .hubinfo {display:block; margin-bottom:20px;} #page-course-publish-metadata .hublink {} #page-course-publish-backup .courseuploadtextinfo {text-align: center;} #page-course-publish-backup .sharecoursecontinue {text-align: center;}
css
Why don't we show the price? As a retailer, we independently set our prices. However, due to manufacturer restrictions, we sometimes can't display the price until you take further action. Sprout Living, Organic Broccoli Kale Sprout Mix , 4 oz (113 g) Shipping Weight: Shipping WeightThe Shipping Weight includes the product, protective packaging material and the actual shipping box. In addition, the Shipping Weight may be adjusted for the Dimensional Weight (e.g. length, width & height) of a package. It is important to note that certain types of products (e.g. glass containers, liquids, fragile, refrigerated or ice packed) will often require protective packaging material. As such, these products will reflect a higher Shipping Weight compared to the unprotected product. Product rank: 100% Pure Sprout Powder: Our Organic Broccoli Kale Sprout Mix starts with organic, non-GMO broccoli and kale seeds, Two members of the Brassica family, broccoli and kale have potent antioxidants, plant compounds such as sulforaphane, vitamins and minerals. Freshly Sprouted & Freeze-Dried: We carefully sprout the seeds to enhance and unlock their full nutritional potential. At the peak of harvest, we freeze-dry and gently mill the fresh sprouts into a concentrated and functional powder. Powerful Plant Nutrients: These attentive steps ensure maximum preservation of essential nutrients and enzymes while dramatically increasing shelf-life. Now you can conveniently enjoy the powerful benefits of fresh sprouts in a variety of new ways. Add two teaspoons of our Organic Broccoli Kale Sprout Mix to boost your salad, soup, smoothie or simply eat it straight. Broccoli sprout powder°, kale sprout powder°. Produced in a cGMP certified facility that follows strict sanitary and regulatory procedures while occasionally processing wheat and mustard. Store in a cool, dry place. Do not eat the desiccant packet. While iHerb strives to ensure the accuracy of its product images and information, some manufacturing changes to packaging and/or ingredients may be pending update on our site. Although items may occasionally ship with alternate packaging, freshness is always guaranteed. We recommend that you read labels, warnings and directions of all products before use and not rely solely on the information provided by iHerb. |Serving Size: 2 teaspoon (3.5 g)
english
{ "type": "service_account", "project_id": "g-drive-clone-mm", "private_key_id": "<KEY>", "private_key": "-----<KEY>", "client_email": "<EMAIL>", "client_id": "111544393579325771943", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/mfc-4bgow62x48osfoz6at-f8j6n89%40g-drive-clone-mm.iam.gserviceaccount.com" }
json
<reponame>marcelbuesing/mqtt-async-client-rs<filename>src/client/client.rs use bytes::BytesMut; #[cfg(feature = "websocket")] use tokio_tungstenite::tungstenite::http::Uri; use crate::{ client::{ builder::ClientBuilder, value_types::{ KeepAlive, Publish, ReadResult, Subscribe, SubscribeResult, Unsubscribe, }, }, Error, Result, util::{ AsyncStream, FreePidList, TokioRuntime, } }; use futures_util::{ future::{ FutureExt, pending, }, select, }; #[cfg(feature = "websocket")] use http::request::Request; use log::{debug, error, info, trace}; use mqttrs::{ ConnectReturnCode, Packet, Pid, QoS, QosPid, self, SubscribeTopic, }; #[cfg(feature = "tls")] use rustls; use std::{ cmp::min, collections::BTreeMap, fmt, sync::{ Arc, atomic::{AtomicBool, Ordering}, Mutex, }, }; use tokio::{ io::{ AsyncReadExt, AsyncWriteExt, }, net::TcpStream, sync::{ mpsc, oneshot, }, time::{ sleep, sleep_until, Duration, error::Elapsed, Instant, timeout, }, }; #[cfg(feature = "tls")] use tokio_rustls::{self, webpki::DNSNameRef, TlsConnector}; use url::Url; /// An MQTT client. /// /// Start building an instance by calling Client::builder() to get a /// ClientBuilder, using the fluent builder pattern on ClientBuilder, /// then calling ClientBuilder::build(). For example: /// /// ``` /// # use mqtt_async_client::client::Client; /// let client = /// Client::builder() /// .set_url_string("mqtt://example.com").unwrap() /// .build(); /// ``` /// /// `Client` is expected to be `Send` (passable between threads), but not /// `Sync` (usable by multiple threads at the same time). pub struct Client { /// Options configured for the client options: ClientOptions, /// Handle values to communicate with the IO task io_task_handle: Option<IoTaskHandle>, /// Tracks which Pids (MQTT packet IDs) are in use. /// /// This field uses a Mutex for interior mutability so that /// `Client` is `Send`. It's not expected to be `Sync`. free_write_pids: Mutex<FreePidList>, } impl fmt::Debug for Client { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Client") .field("options", &self.options) .finish() } } #[derive(Clone)] pub(crate) struct ClientOptions { // See ClientBuilder methods for per-field documentation. pub(crate) url: Url, pub(crate) username: Option<String>, pub(crate) password: Option<<PASSWORD>>>, pub(crate) keep_alive: KeepAlive, pub(crate) runtime: TokioRuntime, pub(crate) client_id: Option<String>, pub(crate) packet_buffer_len: usize, pub(crate) max_packet_len: usize, pub(crate) operation_timeout: Duration, pub(crate) connection_mode: ConnectionMode, pub(crate) automatic_connect: bool, pub(crate) connect_retry_delay: Duration, } impl fmt::Debug for ClientOptions { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ClientOptions") .field("url", &self.url) .field("username", &self.username) // Deliberately skipping password field here to // avoid accidentially leaking it .field("keep_alive", &self.keep_alive) .field("client_id", &self.client_id) .field("packet_buffer_len", &self.packet_buffer_len) .field("max_packet_len", &self.max_packet_len) .field("operation_timeout", &self.operation_timeout) .field("automatic_connect", &self.automatic_connect) .field("connect_retry_delay", &self.connect_retry_delay) .finish() } } /// The client side of the communication channels to an IO task. struct IoTaskHandle { /// Sender to send IO requests to the IO task. tx_io_requests: mpsc::Sender<IoRequest>, /// Receiver to receive Publish packets from the IO task. rx_recv_published: mpsc::Receiver<Result<Packet>>, /// Signal to the IO task to shutdown. Shared with IoTask. halt: Arc<AtomicBool>, } /// The state held by the IO task, a long-running tokio future. The IO /// task manages the underlying TCP connection, sends periodic /// keep-alive ping packets, and sends response packets to tasks that /// are waiting. struct IoTask { /// Options configured for the client. options: ClientOptions, /// Receiver to receive IO requests for the IO task. rx_io_requests: mpsc::Receiver<IoRequest>, /// Sender to send Publish packets from the IO task. tx_recv_published: mpsc::Sender<Result<Packet>>, /// enum value describing the current state as disconnected or connected. state: IoTaskState, /// Keeps track of active subscriptions in case they need to be /// replayed after reconnecting. subscriptions: BTreeMap<String, QoS>, /// Signal to the IO task to shutdown. Shared with IoTaskHandle. halt: Arc<AtomicBool>, } enum IoTaskState { Halted, Disconnected, Connected(IoTaskConnected), } /// The state associated with a network connection to an MQTT broker struct IoTaskConnected { /// The stream connected to an MQTT broker. stream: AsyncStream, /// A buffer with data read from `stream`. read_buf: BytesMut, /// The number of bytes at the start of `read_buf` that have been /// read from `stream`. read_bufn: usize, /// The time the last packet was written to `stream`. /// Used to calculate when to send a Pingreq last_write_time: Instant, /// The time the last Pingreq packet was written to `stream`. last_pingreq_time: Instant, /// The time the last Pingresp packet was read from `stream`. last_pingresp_time: Instant, /// A map from response Pid to the IoRequest that initiated the /// request that will be responded to. pid_response_map: BTreeMap<Pid, IoRequest>, } /// An IO request from `Client` to the IO task. #[derive(Debug)] struct IoRequest { /// A one-shot channel Sender to send the result of the IO request. tx_result: Option<oneshot::Sender<IoResult>>, /// Represents the data needed to carry out the IO request. io_type: IoType, } /// The data the IO task needs to carry out an IO request. #[derive(Debug)] enum IoType { /// A packet to write that expects no response. WriteOnly { packet: Packet }, /// A packet to write that expects a response with a certain `Pid`. WriteAndResponse { packet: Packet, response_pid: Pid }, /// A request to shut down the TCP connection gracefully. ShutdownConnection, } /// The result of an IO request sent by the IO task, which may contain a packet. #[derive(Debug)] struct IoResult { result: Result<Option<Packet>>, } impl Client { /// Start a fluent builder interface to construct a `Client`. pub fn builder() -> ClientBuilder { ClientBuilder::default() } pub(crate) fn new(opts: ClientOptions) -> Result<Client> { Ok(Client { options: opts, io_task_handle: None, free_write_pids: Mutex::new(FreePidList::new()), }) } /// Open a connection to the configured MQTT broker. pub async fn connect(&mut self) -> Result<()> { self.spawn_io_task()?; Ok(()) } fn spawn_io_task(&mut self) -> Result<()> { self.check_no_io_task()?; let (tx_io_requests, rx_io_requests) = mpsc::channel::<IoRequest>(self.options.packet_buffer_len); // TODO: Change this to allow control messages, e.g. disconnected? let (tx_recv_published, rx_recv_published) = mpsc::channel::<Result<Packet>>(self.options.packet_buffer_len); let halt = Arc::new(AtomicBool::new(false)); self.io_task_handle = Some(IoTaskHandle { tx_io_requests, rx_recv_published, halt: halt.clone(), }); let io = IoTask { options: self.options.clone(), rx_io_requests, tx_recv_published, state: IoTaskState::Disconnected, subscriptions: BTreeMap::new(), halt, }; self.options.runtime.spawn(io.run()); Ok(()) } /// Publish some data on a topic. /// /// Note that this method takes `&self`. This means a caller can /// create several publish futures to publish several payloads of /// data simultaneously without waiting for responses. pub async fn publish(&self, p: &Publish) -> Result<()> { let qos = p.qos(); if qos == QoS::ExactlyOnce { return Err("QoS::ExactlyOnce is not supported".into()); } let p2 = Packet::Publish(mqttrs::Publish { dup: false, // TODO. qospid: match qos { QoS::AtMostOnce => QosPid::AtMostOnce, QoS::AtLeastOnce => QosPid::AtLeastOnce(self.alloc_write_pid()?), QoS::ExactlyOnce => panic!("Not reached"), }, retain: p.retain(), topic_name: p.topic().to_owned(), payload: p.payload().to_owned(), }); match qos { QoS::AtMostOnce => { let res = timeout(self.options.operation_timeout, self.write_only_packet(&p2)).await; if let Err(Elapsed { .. }) = res { return Err(format!("Timeout writing publish after {}ms", self.options.operation_timeout.as_millis()).into()); } res.expect("No timeout")?; } QoS::AtLeastOnce => { let res = timeout(self.options.operation_timeout, self.write_response_packet(&p2)).await; if let Err(Elapsed { .. }) = res { // We report this but can't really deal with it properly. // The protocol says we can't re-use the packet ID so we have to leak it // and potentially run out of packet IDs. return Err(format!("Timeout waiting for Puback after {}ms", self.options.operation_timeout.as_millis()).into()); } let res = res.expect("No timeout")?; match res { Packet::Puback(pid) => self.free_write_pid(pid)?, _ => error!("Bad packet response for publish: {:#?}", res), } }, QoS::ExactlyOnce => panic!("Not reached"), }; Ok(()) } /// Subscribe to some topics.`read_subscriptions` will return /// data for them. pub async fn subscribe(&mut self, s: Subscribe) -> Result<SubscribeResult> { let pid = self.alloc_write_pid()?; // TODO: Support subscribe to qos == ExactlyOnce. if s.topics().iter().any(|t| t.qos == QoS::ExactlyOnce) { return Err("Qos::ExactlyOnce is not supported right now".into()) } let p = Packet::Subscribe(mqttrs::Subscribe { pid, topics: s.topics().to_owned(), }); let res = timeout(self.options.operation_timeout, self.write_response_packet(&p)).await; if let Err(Elapsed { .. }) = res { // We report this but can't really deal with it properly. // The protocol says we can't re-use the packet ID so we have to leak it // and potentially run out of packet IDs. return Err(format!("Timeout waiting for Suback after {}ms", self.options.operation_timeout.as_millis()).into()); } let res = res.expect("No timeout")?; match res { Packet::Suback(mqttrs::Suback { pid: suback_pid, return_codes: rcs, }) if suback_pid == pid => { self.free_write_pid(pid)?; Ok(SubscribeResult { return_codes: rcs }) }, _ => { return Err(format!("Unexpected packet waiting for Suback(Pid={:?}): {:#?}", pid, res) .into()); } } } /// Unsubscribe from some topics. `read_subscriptions` will no /// longer return data for them. pub async fn unsubscribe(&mut self, u: Unsubscribe) -> Result<()> { let pid = self.alloc_write_pid()?; let p = Packet::Unsubscribe(mqttrs::Unsubscribe { pid, topics: u.topics().iter().map(|ut| ut.topic_name().to_owned()) .collect::<Vec<String>>(), }); let res = timeout(self.options.operation_timeout, self.write_response_packet(&p)).await; if let Err(Elapsed { .. }) = res { // We report this but can't really deal with it properly. // The protocol says we can't re-use the packet ID so we have to leak it // and potentially run out of packet IDs. return Err(format!("Timeout waiting for Unsuback after {}ms", self.options.operation_timeout.as_millis()).into()); } let res = res.expect("No timeout")?; match res { Packet::Unsuback(ack_pid) if ack_pid == pid => { self.free_write_pid(pid)?; Ok(()) }, _ => { return Err(format!("Unexpected packet waiting for Unsuback(Pid={:?}): {:#?}", pid, res) .into()); } } } /// Wait for the next Publish packet for one of this Client's subscriptions. pub async fn read_subscriptions(&mut self) -> Result<ReadResult> { let h = self.check_io_task_mut()?; let r = match h.rx_recv_published.recv().await { Some(r) => r?, None => { // Sender closed. self.io_task_handle = None; return Err(Error::Disconnected); } }; match r { Packet::Publish(p) => { match p.qospid { QosPid::AtMostOnce => (), QosPid::AtLeastOnce(pid) => { self.write_only_packet(&Packet::Puback(pid)).await?; }, QosPid::ExactlyOnce(_) => { error!("Received publish with unimplemented QoS: ExactlyOnce"); } } let rr = ReadResult { topic: p.topic_name, payload: p.payload, }; Ok(rr) }, _ => { return Err(format!("Unexpected packet waiting for read: {:#?}", r).into()); } } } /// Gracefully close the connection to the server. pub async fn disconnect(&mut self) -> Result<()> { self.check_io_task()?; debug!("Disconnecting"); let p = Packet::Disconnect; let res = timeout(self.options.operation_timeout, self.write_only_packet(&p)).await; if let Err(Elapsed { .. }) = res { return Err(format!("Timeout waiting for Disconnect to send after {}ms", self.options.operation_timeout.as_millis()).into()); } res.expect("No timeout")?; self.shutdown().await?; Ok(()) } fn alloc_write_pid(&self) -> Result<Pid> { match self.free_write_pids.lock().expect("not poisoned").alloc() { Some(pid) => Ok(Pid::try_from(pid).expect("Non-zero Pid")), None => Err(Error::from("No free Pids")), } } fn free_write_pid(&self, p: Pid) -> Result<()> { match self.free_write_pids.lock().expect("not poisoned").free(p.get()) { true => Err(Error::from("Pid was already free")), false => Ok(()) } } async fn shutdown(&mut self) -> Result <()> { let c = self.check_io_task()?; c.halt.store(true, Ordering::SeqCst); self.write_request(IoType::ShutdownConnection, None).await?; self.io_task_handle = None; Ok(()) } async fn write_only_packet(&self, p: &Packet) -> Result<()> { self.write_request(IoType::WriteOnly { packet: p.clone(), }, None) .await.map(|_v| ()) } async fn write_response_packet(&self, p: &Packet) -> Result<Packet> { let io_type = IoType::WriteAndResponse { packet: p.clone(), response_pid: packet_pid(p).expect("packet_pid"), }; let (tx, rx) = oneshot::channel::<IoResult>(); self.write_request(io_type, Some(tx)) .await?; // TODO: Add a timeout? let res = rx.await.map_err(Error::from_std_err)?; res.result.map(|v| v.expect("return packet")) } async fn write_request(&self, io_type: IoType, tx_result: Option<oneshot::Sender<IoResult>>) -> Result<()> { // NB: Some duplication in IoTask::replay_subscriptions. let c = self.check_io_task()?; let req = IoRequest { tx_result, io_type }; c.tx_io_requests.clone().send(req).await .map_err(|e| Error::from_std_err(e))?; Ok(()) } fn check_io_task_mut(&mut self) -> Result<&mut IoTaskHandle> { match self.io_task_handle { Some(ref mut h) => Ok(h), None => Err("No IO task, did you call connect?".into()), } } fn check_io_task(&self) -> Result<&IoTaskHandle> { match self.io_task_handle { Some(ref h) => Ok(h), None => Err("No IO task, did you call connect?".into()), } } fn check_no_io_task(&self) -> Result<()> { match self.io_task_handle { Some(_) => Err("Already spawned IO task".into()), None => Ok(()), } } } /// Start network connection to the server. async fn connect_stream(opts: &ClientOptions) -> Result<AsyncStream> { debug!("Connecting to {}", opts.url); let host = opts .url .host_str() .ok_or(Error::String("Missing host".to_owned()))?; match opts.connection_mode { #[cfg(feature = "tls")] ConnectionMode::Tls(ref c) => { let port = opts.url.port().unwrap_or(8883); let connector = TlsConnector::from(c.clone()); let domain = DNSNameRef::try_from_ascii_str(host) .map_err(|e| Error::from_std_err(e))?; let tcp = TcpStream::connect((host, port)).await?; let conn = connector.connect(domain, tcp).await?; Ok(AsyncStream::TlsStream(conn)) }, ConnectionMode::Tcp => { let port = opts.url.port().unwrap_or(1883); let tcp = TcpStream::connect((host, port)).await?; Ok(AsyncStream::TcpStream(tcp)) } #[cfg(feature = "websocket")] ConnectionMode::Websocket => { let port = opts.url.port().unwrap_or(80); let path_and_query = format!( "{}{}", opts.url.path(), opts.url .query() .map_or("".to_owned(), |q| format!("?{}", q)) ); let tcp_connection = tokio_tungstenite::MaybeTlsStream::Plain(TcpStream::connect((host, port)).await?); let websocket = tokio_tungstenite::client_async( Request::get( Uri::builder() .scheme("ws") .authority(format!("{}:{}", host, port).as_str()) .path_and_query(path_and_query) .build() .map_err(Error::from_std_err)?, ) .header("Sec-WebSocket-Protocol", "mqtt") .body(()) .unwrap(), tcp_connection, ) .await .map_err(crate::util::tungstenite_error_to_std_io_error)? .0; Ok(AsyncStream::WebSocket(websocket)) } #[cfg(feature = "websocket")] ConnectionMode::WebsocketSecure(ref c) => { let port = opts.url.port().unwrap_or(443); let tls_stream = TlsConnector::from(c.clone()) .connect( DNSNameRef::try_from_ascii_str(host).map_err(|e| Error::from_std_err(e))?, TcpStream::connect((host, port)).await?, ) .await?; let path_and_query = format!( "{}{}", opts.url.path(), opts.url .query() .map_or("".to_owned(), |q| format!("?{}", q)) ); let websocket = tokio_tungstenite::client_async( Request::get( Uri::builder() .scheme("wss") .authority(format!("{}:{}", host, port).as_str()) .path_and_query(path_and_query) .build() .map_err(Error::from_std_err)?, ) .header("Sec-WebSocket-Protocol", "mqtt") .body(()) .unwrap(), tokio_tungstenite::MaybeTlsStream::Rustls(tls_stream), ) .await .map_err(crate::util::tungstenite_error_to_std_io_error)? .0; Ok(AsyncStream::WebSocket(websocket)) } } } /// Build a connect packet from ClientOptions. fn connect_packet(opts: &ClientOptions) -> Result<Packet> { Ok(Packet::Connect(mqttrs::Connect { protocol: mqttrs::Protocol::MQTT311, keep_alive: match opts.keep_alive { KeepAlive::Disabled => 0, KeepAlive::Enabled { secs } => secs, }, client_id: match &opts.client_id { None => "".to_owned(), Some(cid) => cid.to_owned(), }, clean_session: true, // TODO last_will: None, // TODO username: opts.username.clone(), password: <PASSWORD>(), })) } fn packet_pid(p: &Packet) -> Option<Pid> { match p { Packet::Connect(_) => None, Packet::Connack(_) => None, Packet::Publish(publish) => publish.qospid.pid(), Packet::Puback(pid) => Some(pid.to_owned()), Packet::Pubrec(pid) => Some(pid.to_owned()), Packet::Pubrel(pid) => Some(pid.to_owned()), Packet::Pubcomp(pid) => Some(pid.to_owned()), Packet::Subscribe(sub) => Some(sub.pid), Packet::Suback(suback) => Some(suback.pid), Packet::Unsubscribe(unsub) => Some(unsub.pid), Packet::Unsuback(pid) => Some(pid.to_owned()), Packet::Pingreq => None, Packet::Pingresp => None, Packet::Disconnect => None, } } /// Represents what happened "next" that we should handle. enum SelectResult { /// An IO request from the Client IoReq(Option<IoRequest>), /// Read a packet from the network Read(Result<Packet>), /// Time to send a keep-alive ping request packet. Ping, /// Timeout waiting for a Pingresp. PingrespExpected, } impl IoTask { async fn run(mut self) { loop { if self.halt.load(Ordering::SeqCst) { self.shutdown_conn().await; debug!("IoTask: halting by request."); self.state = IoTaskState::Halted; return; } match self.state { IoTaskState::Halted => return, IoTaskState::Disconnected => match Self::try_connect(&mut self).await { Err(e) => { error!("IoTask: Error connecting: {}", e); if self.options.automatic_connect { sleep(self.options.connect_retry_delay).await; } else { info!("IoTask: halting due to connection failure, auto connect is off."); self.state = IoTaskState::Halted; return; } }, Ok(()) => { if let Err(e) = Self::replay_subscriptions(&mut self).await { error!("IoTask: Error replaying subscriptions on reconnect: {}", e); } }, }, IoTaskState::Connected(_) => match Self::run_once_connected(&mut self).await { Err(Error::Disconnected) => { info!("IoTask: Disconnected, resetting state"); self.state = IoTaskState::Disconnected; }, Err(e) => { error!("IoTask: Quitting run loop due to error: {}", e); return; }, _ => {}, }, } } } async fn try_connect(&mut self) -> Result<()> { let stream = connect_stream(&self.options).await?; self.state = IoTaskState::Connected(IoTaskConnected { stream, read_buf: BytesMut::with_capacity(self.options.max_packet_len), read_bufn: 0, last_write_time: Instant::now(), last_pingreq_time: Instant::now(), last_pingresp_time: Instant::now(), pid_response_map: BTreeMap::new(), }); let c = match self.state { IoTaskState::Connected(ref mut c) => c, _ => panic!("Not reached"), }; let conn = connect_packet(&self.options)?; debug!("IoTask: Sending connect packet"); Self::write_packet(&self.options, c, &conn).await?; let read = Self::read_packet(&mut c.stream, &mut c.read_buf, &mut c.read_bufn, self.options.max_packet_len); let res = match timeout(self.options.operation_timeout, read).await { // Timeout Err(Elapsed { .. }) => Err(format!("Timeout waiting for Connack after {}ms", self.options.operation_timeout.as_millis()).into()), // Non-timeout error Ok(Err(e)) => Err(e), Ok(Ok(Packet::Connack(ca))) => { match ca.code { ConnectReturnCode::Accepted => { debug!("IoTask: connack with code=Accepted."); Ok(()) }, _ => Err(format!("Bad connect return code: {:?}", ca.code).into()), } }, // Other unexpected packets. Ok(Ok(p)) => Err(format!("Received packet not CONNACK after connect: {:?}", p).into()), }; match res { Ok(()) => Ok(()), Err(e) => { self.shutdown_conn().await; Err(e) }, } } /// Shutdown the network connection to the MQTT broker. /// /// Logs and swallows errors. async fn shutdown_conn(&mut self) { debug!("IoTask: shutdown_conn"); let c = match self.state { // Already disconnected / halted, nothing more to do. IoTaskState::Disconnected | IoTaskState::Halted => return, IoTaskState::Connected(ref mut c) => c, }; if let Err(e) = c.stream.shutdown().await { if e.kind() != std::io::ErrorKind::NotConnected { error!("IoTask: Error on stream shutdown in shutdown_conn: {:?}", e); } } self.state = IoTaskState::Disconnected; } async fn replay_subscriptions(&mut self) -> Result<()> { // NB: Some duplication in Client::subscribe and Client::write_request. let subs = self.subscriptions.clone(); for (t, qos) in subs.iter() { trace!("Replaying subscription topic='{}' qos={:?}", t, qos); // Pick a high pid to probably avoid collisions with one allocated // by the Client. let pid = Pid::try_from(65535).expect("non-zero pid"); let p = Packet::Subscribe(mqttrs::Subscribe { pid, topics: vec![SubscribeTopic { topic_path: t.to_owned(), qos: qos.to_owned() }] }); let req = IoRequest { io_type: IoType::WriteAndResponse { packet: p, response_pid: pid }, // TODO: I'm not sure how to receive the result; ignore it for now. tx_result: None, }; self.handle_io_req(req).await?; } Ok(()) } /// Unhandled errors are returned and terminate the run loop. async fn run_once_connected(&mut self) -> Result<()> { let c = match self.state { IoTaskState::Connected(ref mut c) => c, _ => panic!("Not reached"), }; let pingreq_next = self.options.keep_alive.as_duration() .map(|dur| c.last_write_time + dur); let pingresp_expected_by = if self.options.keep_alive.is_enabled() && c.last_pingreq_time > c.last_pingresp_time { // Expect a ping response before the operation timeout and the keepalive interval. // If the keepalive interval expired first then the "next operation" as // returned by SelectResult below would be Ping even when Pingresp is expected, // and we would never time out the connection. let ka = self.options.keep_alive.as_duration().expect("enabled"); Some(c.last_pingreq_time + min(self.options.operation_timeout, ka)) } else { None }; // Select over futures to determine what to do next: // * Handle a write request from the Client // * Handle an incoming packet from the network // * Handle a keep-alive period elapsing and send a ping request // * Handle a PingrespExpected timeout and disconnect // // From these futures we compute an enum value in sel_res // that encapsulates what to do next, then match over // sel_res to actually do the work. The reason for this // structure is just to keep the borrow checker happy. // The futures calculation uses a mutable borrow on `stream` // for the `read_packet` call, but the mutable borrow ends there. // Then when we want to do the work we can take a new, separate mutable // borrow to write packets based on IO requests. // These two mutable borrows don't overlap. let sel_res: SelectResult = { let mut req_fut = Box::pin(self.rx_io_requests.recv().fuse()); let mut read_fut = Box::pin( Self::read_packet(&mut c.stream, &mut c.read_buf, &mut c.read_bufn, self.options.max_packet_len).fuse()); let mut ping_fut = match pingreq_next { Some(t) => Box::pin(sleep_until(t).boxed().fuse()), None => Box::pin(pending().boxed().fuse()), }; let mut pingresp_expected_fut = match pingresp_expected_by { Some(t) => Box::pin(sleep_until(t).boxed().fuse()), None => Box::pin(pending().boxed().fuse()), }; select! { req = req_fut => SelectResult::IoReq(req), read = read_fut => SelectResult::Read(read), _ = ping_fut => SelectResult::Ping, _ = pingresp_expected_fut => SelectResult::PingrespExpected, } }; match sel_res { SelectResult::Read(read) => return self.handle_read(read).await, SelectResult::IoReq(req) => match req { None => { // Sender closed. debug!("IoTask: Req stream closed, shutting down."); self.shutdown_conn().await; return Err(Error::Disconnected); }, Some(req) => return self.handle_io_req(req).await, }, SelectResult::Ping => return self.send_ping().await, SelectResult::PingrespExpected => { // We timed out waiting for a ping response from // the server, shutdown the stream. debug!("IoTask: Timed out waiting for Pingresp, shutting down."); self.shutdown_conn().await; return Err(Error::Disconnected); } } } async fn handle_read(&mut self, read: Result<Packet>) -> Result<()> { let c = match self.state { IoTaskState::Connected(ref mut c) => c, _ => panic!("Not reached"), }; match read { Err(Error::Disconnected) => { self.tx_recv_published.send(Err(Error::Disconnected)).await .map_err(Error::from_std_err)?; } Err(e) => { self.tx_recv_published.send( Err(format!("IoTask: Failed to read packet: {:?}", e).into()) ) .await .map_err(Error::from_std_err)?; }, Ok(p) => { match p { Packet::Pingresp => { debug!("IoTask: Received Pingresp"); c.last_pingresp_time = Instant::now(); }, Packet::Publish(_) => { if let Err(e) = self.tx_recv_published.send(Ok(p)).await { error!("IoTask: Failed to send Packet: {:?}", e); } }, Packet::Connack(_) => { error!("IoTask: Unexpected CONNACK in handle_read(): {:?}", p); self.shutdown_conn().await; return Err(Error::Disconnected); } _ => { let pid = packet_pid(&p); if let Some(pid) = pid { let pid_response = c.pid_response_map.remove(&pid); match pid_response { None => error!("Unknown PID: {:?}", pid), Some(req) => { trace!("Sending response PID={:?} p={:?}", pid, p); let res = IoResult { result: Ok(Some(p)) }; Self::send_io_result(req, res)?; }, } } }, } }, } Ok(()) } async fn handle_io_req(&mut self, req: IoRequest) -> Result<()> { let c = match self.state { IoTaskState::Connected(ref mut c) => c, _ => panic!("Not reached"), }; let packet = req.io_type.packet(); if let Some(p) = packet { c.last_write_time = Instant::now(); let res = Self::write_packet(&self.options, c, &p).await; if let Err(e) = res { error!("IoTask: Error writing packet: {:?}", e); let res = IoResult { result: Err(e) }; Self::send_io_result(req, res)?; return Ok(()) } match p { Packet::Subscribe(s) => { for st in s.topics.iter() { trace!("Tracking subscription topic='{}', qos={:?}", st.topic_path, st.qos); let _ = self.subscriptions.insert(st.topic_path.clone(), st.qos); } }, Packet::Unsubscribe(u) => { for t in u.topics.iter() { trace!("Tracking unsubscription topic='{}'", t); let _ = self.subscriptions.remove(t); } }, _ => {}, } match req.io_type { IoType::WriteOnly { .. } => { let res = IoResult { result: res.map(|_| None) }; Self::send_io_result(req, res)?; }, IoType::WriteAndResponse { response_pid, .. } => { c.pid_response_map.insert(response_pid, req); }, IoType::ShutdownConnection => { panic!("Not reached because ShutdownConnection has no packet") }, } } else { match req.io_type { IoType::ShutdownConnection => { debug!("IoTask: IoType::ShutdownConnection."); self.shutdown_conn().await; let res = IoResult { result: Ok(None) }; Self::send_io_result(req, res)?; return Err(Error::Disconnected); } _ => (), } } Ok(()) } fn send_io_result(req: IoRequest, res: IoResult) -> Result<()> { match req.tx_result { Some(tx) => { if let Err(e) = tx.send(res) { error!("IoTask: Failed to send IoResult={:?}", e); } }, None => { debug!("IoTask: Ignored IoResult: {:?}", res); }, } Ok(()) } async fn send_ping(&mut self) -> Result<()> { let c = match self.state { IoTaskState::Connected(ref mut c) => c, _ => panic!("Not reached"), }; debug!("IoTask: Writing Pingreq"); c.last_write_time = Instant::now(); c.last_pingreq_time = Instant::now(); let p = Packet::Pingreq; if let Err(e) = Self::write_packet(&self.options, c, &p).await { error!("IoTask: Failed to write ping: {:?}", e); } Ok(()) } async fn write_packet( opts: &ClientOptions, c: &mut IoTaskConnected, p: &Packet, ) -> Result<()> { if cfg!(feature = "unsafe-logging") { trace!("write_packet p={:#?}", p); } // TODO: Test long packets. let mut bytes = BytesMut::with_capacity(opts.max_packet_len); mqttrs::encode(&p, &mut bytes)?; if cfg!(feature = "unsafe-logging") { trace!("write_packet bytes p={:?}", &*bytes); } c.stream.write_all(&*bytes).await?; Ok(()) } async fn read_packet( stream: &mut AsyncStream, read_buf: &mut BytesMut, read_bufn: &mut usize, max_packet_len: usize ) -> Result<Packet> { // TODO: Test long packets. loop { if cfg!(feature = "unsafe-logging") { trace!("read_packet Decoding buf={:?}", &read_buf[0..*read_bufn]); } if *read_bufn > 0 { // We already have some bytes in the buffer. Try to decode a packet read_buf.split_off(*read_bufn); let old_len = read_buf.len(); let decoded = mqttrs::decode(read_buf)?; if cfg!(feature = "unsafe-logging") { trace!("read_packet decoded={:#?}", decoded); } if let Some(p) = decoded { let new_len = read_buf.len(); trace!("read_packet old_len={} new_len={} read_bufn={}", old_len, new_len, *read_bufn); *read_bufn -= old_len - new_len; if cfg!(feature = "unsafe-logging") { trace!("read_packet Remaining buf={:?}", &read_buf[0..*read_bufn]); } return Ok(p); } } read_buf.resize(max_packet_len, 0u8); let readlen = read_buf.len(); trace!("read_packet read read_bufn={} readlen={}", *read_bufn, readlen); let nread = stream.read(&mut read_buf[*read_bufn..readlen]).await?; *read_bufn += nread; if nread == 0 { // Socket disconnected error!("IoTask: Socket disconnected"); return Err(Error::Disconnected); } } } } impl IoType { fn packet(&self) -> Option<&Packet> { match self { IoType::ShutdownConnection => None, IoType::WriteOnly { packet } => Some(&packet), IoType::WriteAndResponse { packet, .. } => Some(&packet), } } } /// An enum for specifying which mode we will use to connect to the broker #[derive(Clone)] pub enum ConnectionMode { /// Insecure TCP connection Tcp, #[cfg(feature = "websocket")] /// Insecure Websocket connection Websocket, #[cfg(feature = "websocket")] /// TLS secured websocket connection WebsocketSecure(Arc<rustls::ClientConfig>), #[cfg(feature = "tls")] /// TLS secured connection Tls(Arc<rustls::ClientConfig>), } impl Default for ConnectionMode { fn default() -> Self { Self::Tcp } } #[cfg(test)] mod test { use super::Client; #[test] fn client_is_send() { let c = Client::builder() .set_url_string("mqtt://localhost") .unwrap() .build() .unwrap(); let _s: &dyn Send = &c; } }
rust
export class CreateSession { user: string; token: string; }
typescript
<gh_stars>1-10 <!DOCTYPE html> <html> <head> <title>Minicurso de introdução ao Shiny</title> <meta charset="utf-8"> <meta name="author" content="<NAME>" /> <link href="libs/remark-css/default.css" rel="stylesheet" /> <link href="libs/remark-css/default-fonts.css" rel="stylesheet" /> </head> <body> <textarea id="source"> class: center, middle, inverse, title-slide # Minicurso de introdução ao Shiny ## 2º EPEI ### <NAME> ### 4 de dezembro de 2018 --- &lt;br&gt; # Sobre mim - IME-USP (2007-2019) -- &lt;br&gt; - Pesquisa em poluição do ar - Blog: [www.rpollution.com](www.rpollution.com) &lt;img src="img/rpollution.png" style="position: fixed; top: 220px; right: 100px; z-index: 1; width: 18%;"&gt; -- &lt;br&gt; - Curso-R &lt;img src="img/cursor.png" style="position: fixed; top: 475px; left: 110px; z-index: 1; width: 30%;"&gt; --- # Sobre o Shiny &lt;img src="img/ciclo.png" style=" display: block; margin-left: auto; margin-right: auto;"&gt; --- # Sobre o Shiny &lt;img src="img/como-funciona.jpg" style=" display: block; margin-left: auto; margin-right: auto;"&gt; --- # Neste minicurso Vamos contruir um app do zero falando sobre: - como construir a interface do usuário e como conectá-la com o servidor. - como programar o *server side*. - os conceitos básicos de reatividade. Não vamos: - Falar sobre [customização](https://shiny.rstudio.com/articles/#customize). - Falar de tópicos mais avançados, como [modularização](https://shiny.rstudio.com/articles/#modules), [debbuging](https://shiny.rstudio.com/articles/debugging.html), [tratamento de erros](https://shiny.rstudio.com/articles/#code-quality) e [testes automatizados](https://shiny.rstudio.com/articles/#testing). - Falar (com detalhes) sobre [Shiny server](https://www.rstudio.com/products/shiny/shiny-server/), [shinyapp.io](https://www.shinyapps.io/) e outras formas de hospedagem. --- # Para aprender mais - Para começar: https://shiny.rstudio.com/tutorial/ - Para se aprimorar: https://shiny.rstudio.com/articles/ - Para se inspirar: https://shiny.rstudio.com/gallery/ &lt;br&gt; &lt;img src="img/cat_book.gif" style=" display: block; margin-left: auto; margin-right: auto;"&gt; --- # Vamos ao R! &lt;br&gt; &lt;br&gt; &lt;img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" style=" display: block; margin-left: auto; margin-right: auto;" width = "300" height = "300"&gt; </textarea> <script src="https://remarkjs.com/downloads/remark-latest.min.js"></script> <script>var slideshow = remark.create({ "highlightStyle": "github", "highlightLines": true, "countIncrementalSlides": false }); if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) { window.dispatchEvent(new Event('resize')); }); (function() { var d = document, s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler"); if (!r) return; s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }"; d.head.appendChild(s); })();</script> <script> (function() { var i, text, code, codes = document.getElementsByTagName('code'); for (i = 0; i < codes.length;) { code = codes[i]; if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) { text = code.textContent; if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) || /^\$\$(.|\s)+\$\$$/.test(text) || /^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) { code.outerHTML = code.innerHTML; // remove <code></code> continue; } } i++; } })(); </script> <!-- dynamically load mathjax for compatibility with self-contained --> <script> (function () { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML'; if (location.protocol !== 'file:' && /^https?:/.test(script.src)) script.src = script.src.replace(/^https?:/, ''); document.getElementsByTagName('head')[0].appendChild(script); })(); </script> </body> </html>
html
/* ==UserStyle== @name New site - old icons @namespace USO Archive @author Maxim_B @description `Replaced the new blue icons with the old colorful ones.` @version 20161216.13.31 @license CC0-1.0 @preprocessor uso ==/UserStyle== */ @-moz-document domain("minerva.ugent.be") { .toolshortcut_agenda{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') top left no-repeat; } .toolshortcut_announcement{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -24px no-repeat; } .toolshortcut_document{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -48px no-repeat; } .toolshortcut_link{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -72px no-repeat; } .toolshortcut_homepage_link{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -72px no-repeat; } .toolshortcut_learnpath{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -96px no-repeat; } .toolshortcut_wiki{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -120px no-repeat; } .toolshortcut_forum{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -144px no-repeat; } .toolshortcut_quiz{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -168px no-repeat; } .toolshortcut_student_publication{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -192px no-repeat; } .toolshortcut_dropbox{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -216px no-repeat; } .toolshortcut_poll{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -240px no-repeat; } .toolshortcut_curios{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -264px no-repeat; } .toolshortcut_studiefiche{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -288px no-repeat; } .toolshortcut_course_description{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -288px no-repeat; } .toolshortcut_user{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -312px no-repeat; } .toolshortcut_group{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -336px no-repeat; } .toolshortcut_reservation{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -360px no-repeat; } .toolshortcut_portfolio{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -384px no-repeat; } .toolshortcut_ephorus{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -408px no-repeat; } .toolshortcut_gradebook{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -432px no-repeat; } .toolshortcut_class{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -456px no-repeat; } .toolshortcut_typology{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -480px no-repeat; } .toolshortcut_meeting{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -504px no-repeat; } .toolshortcut_dissertation, .toolshortcut_bachelor_paper{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -528px no-repeat; } .toolshortcut_glossary{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -552px no-repeat; } .toolshortcut_webpa{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -576px no-repeat; } .toolshortcut_usolvit{ background: transparent url('http://minerva.ugent.be/main/img/coursetools24x24.png') 0px -600px no-repeat; } .tool_agenda{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') top left no-repeat; } .tool_announcement{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -32px no-repeat; } .tool_document{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -64px no-repeat; } .tool_link{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -96px no-repeat; } .tool_homepage_link{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -96px no-repeat; } .tool_learnpath{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -128px no-repeat; } .tool_wiki{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -160px no-repeat; } .tool_forum{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -192px no-repeat; } .tool_quiz{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -224px no-repeat; } .tool_student_publication{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -256px no-repeat; } .tool_dropbox{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -288px no-repeat; } .tool_poll{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -320px no-repeat; } .tool_curios{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -352px no-repeat; } .tool_studiefiche{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -384px no-repeat; } .tool_course_description{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -384px no-repeat; } .tool_user{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -416px no-repeat; } .tool_group{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -448px no-repeat; } .tool_reservation{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -480px no-repeat; } .tool_portfolio{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -512px no-repeat; } .tool_ephorus{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -544px no-repeat; } .tool_gradebook{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -576px no-repeat; } .tool_class{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -608px no-repeat; } .tool_typology{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -640px no-repeat; } .tool_meeting{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -672px no-repeat; } .tool_dissertation, .tool_bachelor_paper{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -704px no-repeat; } .tool_glossary{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -736px no-repeat; } .tool_webpa{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -768px no-repeat; } .tool_usolvit{ background: transparent url('http://minerva.ugent.be/main/img/coursetools32x32.png') 0px -800px no-repeat; } }
css
<reponame>Clementp57/typescript.java<filename>eclipse/ts.eclipse.ide.ui/src/ts/eclipse/ide/ui/hover/ProblemTypeScriptHover.java /** * Copyright (c) 2015-2016 <NAME>. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * <NAME> <<EMAIL>> - initial API and implementation */ package ts.eclipse.ide.ui.hover; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.eclipse.core.resources.IFile; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.source.Annotation; import ts.client.CommandNames; import ts.client.codefixes.CodeAction; import ts.eclipse.ide.core.resources.IIDETypeScriptProject; import ts.eclipse.ide.core.utils.TypeScriptResourceUtil; import ts.eclipse.ide.ui.TypeScriptUIPlugin; import ts.resources.ITypeScriptFile; import ts.resources.ITypeScriptProject; /** * Problem Hover used to display errors when mouse over a JS content which have * a TypeScript error. * */ public class ProblemTypeScriptHover extends AbstractAnnotationHover { protected static class ProblemInfo extends AnnotationInfo { private static final Class<?>[] EMPTY_CLASS = new Class[0]; private static final Object[] EMPTY_OBJECT = new Object[0]; private static final String GET_ATTRIBUTES_METHOD_NAME = "getAttributes"; private static final ICompletionProposal[] NO_PROPOSALS = new ICompletionProposal[0]; public ProblemInfo(Annotation annotation, Position position, ITextViewer textViewer) { super(annotation, position, textViewer); } @Override public ICompletionProposal[] getCompletionProposals() { IDocument document = viewer.getDocument(); IFile file = TypeScriptResourceUtil.getFile(document); try { IIDETypeScriptProject tsProject = TypeScriptResourceUtil.getTypeScriptProject(file.getProject()); if (tsProject.canSupport(CommandNames.GetCodeFixes)) { // Get code fixes with TypeScript 2.1.1 ITypeScriptFile tsFile = tsProject.openFile(file, document); List<Integer> errorCodes = createErrorCodes(tsProject); if (errorCodes != null) { final List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>(); List<CodeAction> codeActions = tsFile.getCodeFixes(position.getOffset(), position.getOffset() + position.getLength(), errorCodes) .get(5000, TimeUnit.MILLISECONDS); for (CodeAction codeAction : codeActions) { proposals.add(new CodeActionCompletionProposal(codeAction, tsFile.getName())); } return proposals.toArray(new ICompletionProposal[proposals.size()]); } return NO_PROPOSALS; } } catch (Exception e) { e.printStackTrace(); } return NO_PROPOSALS; } private List<Integer> createErrorCodes(ITypeScriptProject tsProject) { List<Integer> errorCodes = null; try { // Try to retrieve the TypeScript error code from the SSE // TemporaryAnnotation. Method getAttributesMethod = annotation.getClass().getMethod(GET_ATTRIBUTES_METHOD_NAME, EMPTY_CLASS); Map getAttributes = (Map) getAttributesMethod.invoke(annotation, EMPTY_OBJECT); Integer tsCode = (Integer) getAttributes.get("tsCode"); if (tsCode != null) { Integer errorCode = tsCode; if (tsProject.canFix(errorCode)) { if (errorCodes == null) { errorCodes = new ArrayList<Integer>(); } errorCodes.add(errorCode); } } } catch (NoSuchMethodException e) { // The annotation is not a // org.eclipse.wst.sse.ui.internal.reconcile.TemporaryAnnotation // ignore the error. } catch (Throwable e) { TypeScriptUIPlugin.log("Error while getting TypeScript error code", e); } return errorCodes; } } public ProblemTypeScriptHover() { super(false); } @Override protected AnnotationInfo createAnnotationInfo(Annotation annotation, Position position, ITextViewer textViewer) { return new ProblemInfo(annotation, position, textViewer); } }
java
SUB-DIVISIONS AND INTERESTING PLACES. Area, &c. TALUK KULDABAD belongs to the Sarfa-khas or crown lands of His Highness the Nizam, and consists of 44 villages, scattered about in small groups throughout the Aurangabad taluk. Its area is 93 square miles; its population in 1881 was 12,406, or 133.39 to the square mile; and its land revenue realized in 1,290 Fasli (A.D. 1880-81) was H. S. Rs. 35,617. The cultivated area was 15,272 acres. The revenue survey and settlement was introduced in 1202 Fasli, when the cultivated area was 23,827 acres, assessment H. S. Rs. 32,732 and the culturable waste land 19,988 acres. In 1290 Fasli, the number of cultivators holding lands was 603, and in 1292 it was 561. The average holding of each registered occupant in the latter year was 42.5 acres, and the yearly rental H. S. Rs. 58.3. There were 2,616 cattle and 518 ploughs. The greater portion of the taluk is situated in the hilly regions of the Balaghat. Two ranges of hills near Kuldabad are known as Mhaismala and Kalakadha. Several rivers traverse portions of the taluk in their upper courses, such as the Girja, Phulmasta, Sukna, and Ganda. The principal tanks are the Hauzkhas, Dabarao talao, Pangra talao, Khaksar talao, and Ganj Rawan talao, all situated about Roza. The Hauz Katlag is in the village of Mausala. The soils are regar, masab, and garab. Very fine lands for the cultivation of the sugarcane are met with in the villages of the Balaghat, situated in hollows and valleys; bat otherwise the soils are shallow and rooky. 300 acres, and makkai 225 acres. The pulses occupied 3,727 acres or 21.47 per cent., of which 1,031 acres were devoted to tur, 956 acres to chana, 825 to mung, 431 to kulti, 284 to batana, and 200 to lakh. Oilseeds occupied 1,573 acres or 9.06 per cent., of which 442 acres were cultivated with kardi, 400 acres with alsi, 356 with bhoi-mung, 225 with karla, and 150 with til. Cotton was raised on 206 acres or 1.18 per cent., and the miscellaneous crops on 1,174 acres or 6.76 per cent. The latter comprised 268 acres chillies, 206 acres sugarcane, 150 acres tobacco, 75 acres poppy, and 375 acres vegetables, &c. The total population in 1881 was 12,406 inhabitants, of whom 9,552 or 76.91 per cent, were Hindus, 2,849 or 22.87 per cent. Mahomedans, and there were besides 4 Parsis and 1 Christian. The details of the Hindu castes are as follows:-372 Brahmans, 86 Golaks, Brahman-zais and Vidurs; 304 Rajputs, 2 Kapurs, 2 Khayats, 267 Pardesis, 10 Kathars, 2 Halvais, 3 Purbhais, 161 Marwaris, 82 Lingaiat Vanis, 26 Jains, 78 Gosains, &c., 16 Mang-bhaus, 4,411 Kunbis, 197 Malis, 71 Sonars, 81 Sutars, 43 Lohars, 17 Wattaris, 18 Kasars, 53 Shimpis, 4 Kalhals, 84 Kumhars, 5 Gaundis, 15 Lonaris, 114 Tailis, 162 Salis, 19 Tagwalas, 37 Ran-garis, 165 Variks, 56 Parrits, 1 Telangi, 499 Dhangars, 40 Kolis, 11 Guraus, 11 Bhats and Thakurs; 49 Bharadis and Gondhalis, 7 Buruds, 46 Dhors, 237 Chamhars, 1,058 Mahars, 277 Mangs, 199 Banjaras, 81 Bhils, 3 Ramusis, 3 Pardhis, 7 Kaikadis, 29 Wadars. of the Haidarabad dynasty, his second son Nazir Jang, Nizam Shah king of Ahmadnagar, Malik Ambar, Tana Shah king of Golkonda, and a host of minor celebrities. The place contains from 15 to 20 domed tombs, and about 1,400 plain sepulchres. It was once an important town, but is now in great part deserted; and the gardens which surround many of the tombs are overgrown with jungle. Roza is surrounded by a high fortified wall built by Aurangzib, and contains seven gates,-Nakarkhana, Pangra, Langra, Mungupait, Kunbeli, Haddi, and a wicket called Azam Shahi. The gateway on the Aurangabad side is approached by a paved ascent, which continues inside the city for about 200 or 300 feet. The sepulchre of Aurangzib lies almost midway between the north and south gates; and a steep paved ascent some 30 yards in length, leads from the road side to the entrance of the building which contains the tomb. remains of Aurangzib's second son, prince Azam Shah, and of the hitter's wife. The grave of the daughter of a Mahomedan saint lies close by. The marble screen contains 18 panels, each 6 feet in height, and the sides and corners are surmounted with small minarets of the same material. The interior is paved with marble; and prince Azam Shah's grave has a small marble headstone carved with floral devices. richly embroidered pall, and has the usual string of ostrich eggs suspended over it. A small room in an angle of the courtyard wall is said to contain the robe of the prophet, which is exhibited once a year on the 12th Rabi-ul-awal. Opposite the building which contains the tombs of Aurangzib, latter also has a large quadrangular courtyard, having open fronted buildings on all sides, and a nakhar-khana at the east end. Two large native drums are in the courtyard; one of them is in fair order, but the parchment of the other has been destroyed, and only the huge iron hemisphere remains, The west-end of the quadrangle is used as a school; and a door here gives access to an inner courtyard containing several graves. Facing the entrance is the grave of Saiad Burhanu-d-din, who died at Roza in 744 Hijri (A.D. 1344); and within the shrine are some hairs of the prophet's board. The shrine doors are covered with plates of metal wrought into fanciful designs of trees and flowers. To the right of the tomb are the resting places of Asaf Jah, and of one of his consorts, covered with white cloth. The graves are on a platform of porphyry inlaid with white marble, and are surrounded by a screen of red porphyry, 10 feet high. scolloped arches of red porphyry. Lall bagh. Roza, and according to Ferishta, was erected during his lifetime. Near it stands the tomb of his wife Bibi Karima; and a short distance farther on is the open grave of Tana Shah, king of Golkonda. has been converted into a traveller's bungalow, by the officers of the Contingent stationed at Aurangabad. The mausoleum at the base of the hill close by was erected for himself by Khoja Firoz, when engaged in building the tomb of Nizam Shah Bhairi. presented by king Tana Shah. are the mausoleums of Saiad Khaksar and Ganj Rawan Ganj Baksh, attached to which are two fine tanks. an ancient city, locally known as Budra vanti or Budda vanti; which, according to tradition, was ruled by a raja Yunas. The materials for constructing Roza, as well as Aurangabad, were probably obtained from these ruins. Roza has now a population of 2,201 inhabitants, of whom 1,489 are Musalmans, 314 Kunbis, and 135 Salia. It contains 7 Mohallas or quarters; and is set apart as a jagir for the maintenance of several dargas. [Many of the villager of the Kuldabad and Aurangabad taluks are set apart for the maintenance of the dargas of Roza. The revennes of the villages of Jasgaon, Birdi, Sankarpur, Rel, and Saidapur, go for the maintenance of Aurangzib's tomb; while Talnapur, Sultanpur, Gosala, Jaiwantkher and Muradabad are set apart for the expenses of Asaf Jah's tomb. Similarly, there are 4 villages held in jagir for Burhanu-d-din's tomb, 3 for Zainu-d-din's tomb, and 2 for Ganj Rawan's tomb.] A weekly market is held here, and a large annual fair takes place in honor of Zar Zari Baksh. Roza is the head-quarters of the Tahsildar, and has a post office and a school. KAGASPUR is situated 2 miles north of Daulatabad, midway between the latter and Roza. It is famous for its paper manufacture, and is chiefly inhabited by Mahomedans, the majority of whom earn their livelihood by working in the various factories. The industry has fallen away considerably of late years, owing to the more general use of English-made paper. SULTANPUR is in a very dilapidated condition, never having been repaired since it was sacked and burnt by the Pindharis. There are some vineyards in this village KINGAON and GUDANA are famous for their sugarcane lands.
english
.navbar { margin-bottom: 0; border-radius: 0; background-color:#194d30; color:white; height: 55px; font-size:18px; letter-spacing: 1px; } .navbar-inverse .navbar-brand { font-size:17px; color:white; } .navbar-inverse .navbar-nav>.active>a, .navbar-inverse .navbar-nav>.active>a:focus, .navbar-inverse .navbar-nav>.active>a:hover { color: black; background-color: #b8dc6f; border-bottom-color: black; border-bottom-style: solid; border-width: 2px; font-weight:bold; } /* Set height of the grid so .sidenav can be 100% (adjust as needed) */ .row.content {height: 450px} /* Set background color and 100% height */ .sidenav { padding-top: 20px; background-color: #b8dc6f; height: 200%; } /* On small screens, set height to 'auto' for sidenav and grid */ @media screen and (max-width: 767px) { .sidenav { height: auto; padding: 15px; } .row.content {height:auto;} } .container{ top: 20%; box-sizing: border-box; } .col-sm-8{ align-items: center; justify-content: center; text-align: center; vertical-align: baseline; padding:10px 50px; } h1 { text-align: center; text-transform: uppercase; color: #006400; letter-spacing: 3px; font-size:70px; text-shadow: 2px 4px black; border-bottom-style: groove; border-bottom-color: #006400; border-bottom-width: 7px; margin-top:50px; } p{ padding-top:40px; font-size:20px; }
css
Vince Russo thinks Sami Zayn won't be able to last for more than two minutes in a match against Undisputed WWE Universal Champion Roman Reigns. The Honorary Uce is one of the biggest stars in WWE today. No matter what Zayn does, the fans rally behind him. Despite being a part of The Bloodline, a heel stable, viewers wildly cheer them on, thanks to the former Intercontinental Champion's infectious charm and lovable persona. This has, naturally, led to many proclaiming that the 20-year veteran deserves a shot at Roman Reigns' Undisputed WWE Universal Championship. However, while speaking on Sportskeeda Wrestling's The Wrestling Outlaws, Vince Russo explained why he wasn't in favor of Sami Zayn challenging Reigns. The former WWE writer feels that Zayn is not at Reigns' level and would last for hardly two minutes if they squared off inside the ring. Russo added that Zayn is not a believable contender and would never draw casual fans, just like Daniel Bryan, CM Punk, and Kofi Kingston never did. "Listen, bro, here's the bottom line at the end of the day. Bottom line to a casual fan like Vince Russo. Here's Sami Zayn, here's Roman Reigns, period, end of story. This guy would last two minutes with Roman Reigns in a fight, period, end of story. That's what every casual viewer sees. You cannot take this guy seriously, bro. That's why Daniel Bryan didn't draw, that's why Kofi didn't draw, that's why CM Punk didn't draw, because to casual fans, it is not believable," said Vince Russo. (6:58 - 7:39) Check out the full video below: The wrestling veteran was perplexed that despite having behemoths like Bobby Lashley, Brock Lesnar, Roman Reigns, and Braun Strowman under its umbrella, WWE was still pushing Sami Zayn. "You got guys in your company like Bobby Lashley and Brock Lesnar and Roman Reigns and Braun Strowman and this guy is gonna be the champ?" added Vince Russo. (7:40 - 7:50) Considering Zayn's importance as a Bloodline member, it's safe to say a match between him and Reigns won't materialize soon. Do you agree with Vince Russo's take on a possible Sami Zayn vs. The Tribal Chief clash? Sound off in the comments section below. If you take any quotes from this article, please credit Sportskeeda Wrestling and embed the YouTube video.
english
What is a Heart Attack? A heart attack is a serious condition with potentially fatal consequences. It is a situation where there is a lack of blood supply to the heart muscle due to a block in the blood vessel supplying the heart muscle. Why this important to treat? A heart attack is the number one killer disease in the world. Sadly India will become the ‘Heart attack capital’ of the world in addition to the dubious distinction of ‘Diabetes Capital’ of the world. The heart is a pump and supplies blood (food and oxygen) to all the body parts to function properly. Once there is no blood supply, there is damage to the heart muscle which is usually permanent. Therefore the treatment goal is to act before there is much heart muscle damage by opening the blocked blood vessel to re-establish the blood flow. How soon should treatment be given? As mentioned, before the goal is to prevent any heart muscle damage which can be permanent. According to evidence from multiple clinical trials, the best time frame is before 60-90 minutes. This gives the patient the best chance to have a successful outcome. The process of opening the blocked artery and inserting a stent is called Angioplasty. The procedure performed in this situation is called Primary Angioplasty (the medical term being Primary Percutaneous Coronary Intervention). In addition to the procedure, medications play an important role in managing these patients. The chances of complications from heart attack including the risk of dying significantly increases with time. Is this treatment available widely? Yes, this treatment is widely available throughout the country, particularly in all major cardiac centers. It is not yet available in the smaller districts and villages, unfortunately. It is performed by the Interventional Cardiologist who specializes in the treatment of this condition. Both the Government of India and the Karnataka State Governments have made provisions for free treatment not only in Government hospitals but also in Private (Corporate) hospitals for Below Poverty Level (BPL) patients. What is the first step any concerned patient should do? Once the patient has any of the concerned symptoms (chest pain, discomfort, chest uneasiness, left shoulder/arm pain and or breathlessness), he/she should consult the nearest available doctor. If there is a suspicion of a heart attack, the patient should come to the nearest cardiac center for further diagnosis and treatment. The time delay should be as minimal as possible. Is there an alternative to Primary angioplasty? For those who are not able to afford this treatment or are too far away from a cardiac centre that can provide for this treatment, there is an alternative called ‘Thrombolysis’ (clot-busting injection treatment). Although this is less superior compared to Primary angioplasty, this can be a lifesaver in many situations. Most patients still need angioplasty afterwards.
english
Fact Check: Are There More Muslim Undertrials In Indian Jails? India’s Union Home Minister Sushil Kumar Shinde recently addressed a letter to the Chief Ministers of different states, urging them not to wrongfully detain ‘Muslim’ youth in cases. He later clarified that comment saying that the letter meant all innocent youth being harassed by the police. IndiaSpend decided to Fact Check his statement in as much as asking if the suggestion of discrimination had some factual weight behind it. The answer, from a pure data point of view, is yes. Whether he ought to have expressed it in the manner he did and thus leaving it open to interpretation is a different question. We looked at the numbers for Muslim and Hindu undertrials in different states and also Muslim/Hindu detenues in jails across the country. India had a total of 254,857 undertrial prisoners from various religions under different crime heads at the end of 2012. There were 53,638 Muslim undertrials across states. Uttar Pradesh has the highest number of Muslim undertrials at 14,707 followed by West Bengal and Maharashtra. The 2001 Census has been used for the demographic break-up of the population for states as the 2011 demographic data is not yet available. Figure 1(a) In Maharashtra, the number of Muslim undertrials for every 100,000 Muslims (58) is higher than the corresponding figure for UP (47) although the number of Muslim undertrials in UP as a whole is higher. The same is the case with West Bengal where there are 32 Muslim undertrials for every 100,000 Muslims. Figure 1(b) Figure 2(a) If we look at the same numbers for Hindus in these states, we see that Uttar Pradesh has 28.5 undertrials for every 100,000 Hindus. And we can see similar difference in other states: West Bengal (12), Maharashtra (11.7), Bihar (29), Jharkhand (44), Rajasthan (20), Madhya Pradesh (27), Assam (15), Gujarat (10) and Kerala (9). Figure 2(b) So we see that the number of Hindus undertrials for 100,000 persons is much less than the corresponding figures for Muslim undertrial prisoners. There were a total of 1,922 detenues in the country at the end of 2012 of which 543 were Muslims. Gujarat had a total of 151 Muslim detenues at the end of 2012 out of 519 detenues in the state. Jammu & Kashmir, where the majority population is Muslim, comes after Gujarat and is also the only state where Muslim detenues are significantly more that Hindu detenues. If we look at the numbers of Hindu detenues, Tamil Nadu with 371 Hindu detenues out of a total of 523 detenues has the highest followed by Gujarat and Manipur. UP has less number of Hindu detenues than Manipur although the difference in Hindu population between the two states is extremely high. We see from the numbers that there is a need to examine the issue more closely to find out why there are more Muslim undertrial prisoners in proportion to the population in states as compared to Hindu undertrial prisoners. The Home Minister also made a point about expediting cases where Muslims were implicated in terror cases and provide legal aid to Muslim undertrial prisoners in terror cases. That being said, the Minister might have unwittingly (or wittingly) re-drawn attention to larger socio-economic issues of disparities and what they could lead to, at least in theory. Inmates in Indian jails are categorised as convicts, undertrials and detenues. (1) A convict is a person found guilty of a crime and sentenced by a court or a person serving a sentence in prison. (3)A detenu is any person held in custody.
english
Physically as well as mentally Fatima Sana Shaikh will be very courageous during this period. This is a good phase for Fatima Sana Shaikh's relatives. Go for attempts in Fatima Sana Shaikh's career life as the success is assured. Gain of material things is also indicated. Fatima Sana Shaikh will purchase land and machinery during this period. Substantial gains in Fatima Sana Shaikh's business and trades are assured. Fatima Sana Shaikh's enemies will not be able to plunk before Fatima Sana Shaikh. Fatima Sana Shaikh will come into contact with people from far off places. This period is also very good as far as love life is concerned. Fatima Sana Shaikh will receive full support from Fatima Sana Shaikh's family members. Fatima Sana Shaikh is an eternal optimist, and events of the period will further strengthen Fatima Sana Shaikh's optimistic instincts. Fatima Sana Shaikh can do reasonably well if Fatima Sana Shaikh time Fatima Sana Shaikh's investments intelligently based on the best periods hinted for Fatima Sana Shaikh's sign. All round cooperation and happiness can be the reward from Fatima Sana Shaikh's loved ones and associates, victory over opponents and pleasant functions such as marriage or romantic situations parties are also the likely outcomes. Family atmosphere will be quite satisfactory. Some restlessness is likely, mainly because of a deep feeling of wanderlust. Fatima Sana Shaikh don't like to get backed into a corner, so this can cause some strain. Fatima Sana Shaikh's mind will be inclined towards religious activities, and Fatima Sana Shaikh might make journey to sacred places. The period will begin with a phase of volatility and pressure in career. Tuning with Fatima Sana Shaikh's own people and Fatima Sana Shaikh's relatives may get disturbed. Give proper attention to our day to day pursuits. Fatima Sana Shaikh will not be able to fulfill Fatima Sana Shaikh's family's expectations. This is not a perfect time for Fatima Sana Shaikh to indulge in any type of business matters. This will be testing time for Fatima Sana Shaikh's mother. A visit to a holy place of Fatima Sana Shaikh's interest is on the charts. Fatima Sana Shaikh will, however, have a romantic and charismatic attitude, and this will help Fatima Sana Shaikh maintain cordial relations with the ones Fatima Sana Shaikh know and establish contacts with the ones Fatima Sana Shaikh don't. There is certain amount of wish fulfillment which generally means gains in dealings or promotions in the hierarchy of the organization Fatima Sana Shaikh work for. Acqusition of a new vehicle or buying new land is on the cards. Overall, the period is very good. This is a good time for self-expression and the use of Fatima Sana Shaikh's creative abilities in various fields. The most unexpected changes could be expected in Fatima Sana Shaikh's work area and in professional activities which are outstanding for Fatima Sana Shaikh. There will be favor from the higher authorities and seniors. Positive changes in Fatima Sana Shaikh's personal and professional life will take place. Fatima Sana Shaikh may gain paternal properties. Fatima Sana Shaikh would surely be successful during this period and see fulfillment of Fatima Sana Shaikh's wishes. Fatima Sana Shaikh will not be able to grab the chances coming Fatima Sana Shaikh's way though Fatima Sana Shaikh will have a lot of opportunities but all in ruin. Fatima Sana Shaikh may face problems related to Fatima Sana Shaikh's health or Fatima Sana Shaikh's parents so get good care of them as well as yours. Long distance travel is on Fatima Sana Shaikh's cards but would not be very beneficial and should be avoided. This is a period of mixed results for Fatima Sana Shaikh. There can be dispute with the public and Fatima Sana Shaikh's colleagues. Fatima Sana Shaikh will be prone to diseases like cold and fever. There will be mental worry without any visible causes. Success in examinations, or promotion, or increased recognition in occupation is assured. Increased corporation from the family is seen. Help from people who live in faraway places or foreign associates. Fatima Sana Shaikh may get a new assignment which will be very beneficial to Fatima Sana Shaikh. Fatima Sana Shaikh will have tremendous confidence to handle any kind of adverse situation. This period would be an excellent stepping stone for growth vertically and a rise on Fatima Sana Shaikh's career. There are chances of getting benefits from the associates/partners. Fatima Sana Shaikh may be inclined towards earning through unjust means. Fatima Sana Shaikh's self-discipline, self-monitoring and control over Fatima Sana Shaikh's daily routine will be beneficial to Fatima Sana Shaikh. Fatima Sana Shaikh's relationship with seniors/ authorities will be very cordial and at the sometime Fatima Sana Shaikh's business circle will increase. Health related problems may disturb Fatima Sana Shaikh's peace of mind. This is not a very adequate period for Fatima Sana Shaikh. Fatima Sana Shaikh's opponents will try to damage Fatima Sana Shaikh's reputation. Fatima Sana Shaikh may have to be involved in unprofitable deeds. Sudden financial loss is on the cards. A tendency of taking risks should be curbed as it is not a very harmonious period for Fatima Sana Shaikh. Dispute on small issues with relatives and friends is on cards. Don't take major decisions otherwise Fatima Sana Shaikh will be in trouble. Beside this, Fatima Sana Shaikh might have to get indulge in thankless job. The period indicates menstrual trouble to ladies, dysentery and eye trouble. What will you get in 250+ pages Colored Brihat Horoscope. Are money matters a reason for the dark-circles under your eyes? Is there any question or problem lingering. Worried about your career? don't know what is. AstroSage Yearbook is a channel to fulfill your dreams and destiny. The CogniAstro Career Counselling Report is the most comprehensive report available on this topic. Buy Genuine Gemstones at Best Prices. Energised Yantras for You. Original Rudraksha to Bless Your Way. Bring Good Luck to your Place with Feng Shui. Praise the Lord with Divine Energies of Mala. Jadi (Tree Roots) Keep Your Place Holy with Jadi.
english
Finally ChatGPT can talk! Discover what ChatGPT Voice is, how to use it on your mobile, and how treat it as your personal assistant. Protect yourself from unwanted spams and data leaks. Here are two tips to hide your real email and use aliases instead! Check out our guide to find the best free AI meme generators that let you unleash your creativity and effortlessly make funny memes. Learn powerful methods to block or restrict websites on your Mac and iPhone. Restrict unwanted content using these simple strategies. Journal is a new app from Apple to create daily entries. Let’s compare it with everyone’s favorite Day One to find the differences. Increase productivity, generate innovative code snippets, and enhance your coding experience with these best ChatGPT extensions for VS Code. Boost your productivity and track your time with the help of these 6 best time tracking apps for your iPhone and Android. AI has taken the world by storm, and here are the best AI comic makers you can use to transform your imagination into vibrant comics. Want to know how to transcribe your Voice Memos? Here are top 5 methods to transcribe the Voice Memos on your iPhone. Stay organized and in control of your finances effortlessly. Discover the best expense tracker apps for your iPhone and Android. Planning to print a Word document with tracked changes and comments? Here’s how you can ensure the tracked changes show on the printed doc. Looking to watch a video to keep yourself entertained while completing a task? Here’s how to enable picture-in-picture on Microsoft Edge. Don’t want to read long articles? No problem. You can listen to it instead. Here’s how to make Safari read aloud a webpage to you in iOS 17. Learn how to get the most out of Google Calendar. Here’s how to use, share, and do much more with Google Calendar on your iPhone. If Word is automatically deleting text, you should ensure there are no hardware or keyboard isuues, then try other solutions in this guide. Your Notion page looks insufficient without columns. Here are the best ways to create and customize columns in notion. Want to copy your Google Sheets workbook? Here are 3 easy ways to make a copy of your Google Sheets worksheet. Never struggle again to remove or delete a calendar from your iPhone. Here are the top 6 ways to remove a calendar on your iPhone. Want to make the best of OneNote? Check out some of the templates to get started and manage information using OneNote.
english
{ "directions": [ "Stir together vodka and soda in a large punch bowl. Add ice cream and sherbet; stir and serve immediately." ], "ingredients": [ "2 cups lime vodka", "2 (2 liter) bottles chilled lemon-lime soda", "1/2 gallon vanilla ice cream", "1/2 gallon lime sherbet" ], "language": "en-US", "source": "allrecipes.com", "tags": [], "title": "Lime-Vodka Punch", "url": "http://allrecipes.com/recipe/68294/lime-vodka-punch/" }
json
New Entry Level Plan: S No. Bandwidth (Download Speed) Hi, As the title suggests i am in need of buying one above. I am totally clueless on how to go about selecting. This much i have decided: It should be an invertor A/C for reduced power consumption. Please suggest a good optical USB mouse for Office/Home use( No Gaming) in a 500/- budget. Have been using logitech for a while and have replaced several due to problem with left or right button.Please suggest. Hi, I have recently bought a LG G2 Mobile and now i am looking for a good power bank for charging it as i travel a lot. I have previously not thought a bout buying one so not familiar with what to look for. Here are my requirements: Hi , It seems currently LG G2 D802T is available on lesser or same price than Nexus 5 in both online as well as local market (In local market G2 is 5000 Rs/- lesser than N5). Which would be a safer bet to buy currently? 1. Budget? 2. Display type and size? 3. Dual sim? 4. Preferred choice of brand? Hi All, My existing PSU Corsair VX 450 has become faulty and since warranty period is over and same model is not available, i need suggestion for a replacement. Current configuration attached. I would prefer to buy online and require a model with 3 to 5 years warranty. 1. Budget? Ans: I would prefer to go for something below 10-15 K. But can go upto 21 for the right one. 2. Display type and size? 3. Dual sim? 4. Preferred choice of brand? Hi, i don't know were else to post this. I am searching for old Hindi, English, Malayalam, Tamil mp3 songs(preferably in 320 kbps). Flyte was my major source. but now it is shutdown. Any help in this search would be deeply appreciated.
english