content
stringlengths
228
999k
pred_label
stringclasses
1 value
pred_score
float64
0.5
1
CameraIcon CameraIcon SearchIcon MyQuestionIcon Question If we have ∠ABC as θ, reflex ∠ABC is equal to ________________. 1. 180 - θ    2. 360 + θ    3. -180 + θ  ​ 4. 360 - θ  Solution The correct option is D 360 - θ  From the figure, we can see that ∠ABC + Reflex ∠ABC = 360 So, Reflex ∠ABC = 360 - θ ​​ flag  Suggest corrections thumbs-up   0 Upvotes footer-image
__label__pos
0.995063
🌉 【React】Mapboxを使用して検索機能付きの地図を表示してみる 2022/04/14に公開 概要 Mapboxは、GoogleMapと同様の地図を表示するサービスです。王者Googleマップにライバル登場!「Mapbox」はどこまで使えるか?の記事に、概要や値段等紹介されていますが、GoogleMapと比べて無料枠も多いし安く使えるようなサービスになっています。 今回はReactでこのMapboxを使用し、検索機能付きの地図を表示してみます。 実装する内容 以下のイメージの内容のものを表示します。 実装時に考慮する内容としては、主に以下の3点です。 • 地図の検索ボックスが表示されるようにする。 • 検索結果の地点にピンを表示する。 • 地名が日本語で表示されるようにする。 前準備や参考にしたものなど 実装サンプル まずは地図本体の表示と、言語切り替えの実装部分です。 緯度経度の初期値については、propから渡すことを想定しています。 MapboxComponent.js import Map, { Marker, NavigationControl } from "react-map-gl"; import "mapbox-gl/dist/mapbox-gl.css"; import MapboxLanguage from "@mapbox/mapbox-gl-language"; import GeocoderControl from "./GeocoderControl"; import MarkerPin from "./MarkerPin"; export default function MapboxComponent(prop) { const [markerPin, setMarkerPin] = useState({ latitude: prop?.initialGeographicPoint?.latitude, longitude: prop?.initialGeographicPoint?.longitude, }); function onDragEnd(e) { const viewState = e.viewState; if (viewState) { setMarkerPin({ latitude: viewState.latitude, longitude: viewState.longitude, }); } } function onLoadMap(e) { const map = e?.target; if (map) { // 言語設定 const language = new MapboxLanguage({ defaultLanguage: "ja", }); map.addControl(language); language._initialStyleUpdate(); } } return ( <Map initialViewState={{ latitude: markerPin.latitude, longitude: markerPin.longitude, zoom: 13, }} mapStyle="mapbox://styles/mapbox/streets-v11" mapboxAccessToken={process.env.MAPBOX_TOKEN} style={{ height: "350px", width: "100%" }} attributionControl={false} onDragEnd={onDragEnd} onLoad={onLoadMap} > <Marker latitude={markerPin.latitude} longitude={markerPin.longitude} > <MarkerPin /> </Marker> <NavigationControl /> <GeocoderControl setMarkerPin={setMarkerPin} position="top-left" /> </Map> ); } 以下がピンの表示部分です。上記で紹介したExample: Draggable Markerのピンの表示部分のコードと、ほぼ同様です。 MarkerPin.js export default function MarkerPin() { const ICON = `M20.2,15.7L20.2,15.7c1.1-1.6,1.8-3.6,1.8-5.7c0-5.6-4.5-10-10-10S2,4.5,2,10c0,2,0.6,3.9,1.6,5.4c0,0.1,0.1,0.2,0.2,0.3 c0,0,0.1,0.1,0.1,0.2c0.2,0.3,0.4,0.6,0.7,0.9c2.6,3.1,7.4,7.6,7.4,7.6s4.8-4.5,7.4-7.5c0.2-0.3,0.5-0.6,0.7-0.9 C20.1,15.8,20.2,15.8,20.2,15.7z`; const pinStyle = { fill: "#d00", stroke: "none", }; return ( <svg height={20} viewBox="0 0 24 24" style={pinStyle}> <path d={ICON} /> </svg> ); } 最後に検索ボックスの表示部分です。上記で紹介したExample: Geocoderのほぼそのままですが、検索結果のMarkerについては親からpropで渡したものにセットしています。 GeocoderControl.js import { useControl } from "react-map-gl"; import MapboxGeocoder from "@mapbox/mapbox-gl-geocoder"; import "@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css"; export default function GeocoderControl(prop) { const noop = () => {}; const geocoder = useControl( () => { const ctrl = new MapboxGeocoder({ ...prop, accessToken: process.env.MAPBOX_TOKEN, }); ctrl.on("loading", noop); ctrl.on("results", noop); ctrl.on("result", (evt) => { const { result } = evt; const location = result && (result.center || (result.geometry?.type === "Point" && result.geometry.coordinates)); if (location) { prop.setMarkerPin({ longitude: location[0], latitude: location[1] }); } }); ctrl.on("error", noop); return ctrl; }, { position: prop.position, } ); if (geocoder._map) { if ( geocoder.getProximity() !== prop.proximity && prop.proximity !== undefined ) { geocoder.setProximity(prop.proximity); } if ( geocoder.getRenderFunction() !== prop.render && prop.render !== undefined ) { geocoder.setRenderFunction(prop.render); } if ( geocoder.getLanguage() !== prop.language && prop.language !== undefined ) { geocoder.setLanguage(prop.language); } if (geocoder.getZoom() !== prop.zoom && prop.zoom !== undefined) { geocoder.setZoom(prop.zoom); } if (geocoder.getFlyTo() !== prop.flyTo && prop.flyTo !== undefined) { geocoder.setFlyTo(prop.zoom); } if ( geocoder.getPlaceholder() !== prop.placeholder && prop.placeholder !== undefined ) { geocoder.setPlaceholder(prop.zoom); } if ( geocoder.getCountries() !== prop.countries && prop.countries !== undefined ) { geocoder.setCountries(prop.zoom); } if (geocoder.getTypes() !== prop.types && prop.types !== undefined) { geocoder.setTypes(prop.zoom); } if ( geocoder.getMinLength() !== prop.minLength && prop.minLength !== undefined ) { geocoder.setMinLength(prop.zoom); } if (geocoder.getLimit() !== prop.limit && prop.limit !== undefined) { geocoder.setLimit(prop.zoom); } if (geocoder.getFilter() !== prop.filter && prop.filter !== undefined) { geocoder.setFilter(prop.zoom); } if (geocoder.getOrigin() !== prop.origin && prop.origin !== undefined) { geocoder.setOrigin(prop.zoom); } if ( geocoder.getAutocomplete() !== prop.autocomplete && prop.autocomplete !== undefined ) { geocoder.setAutocomplete(prop.zoom); } if ( geocoder.getFuzzyMatch() !== prop.fuzzyMatch && prop.fuzzyMatch !== undefined ) { geocoder.setFuzzyMatch(prop.zoom); } if (geocoder.getRouting() !== prop.routing && prop.routing !== undefined) { geocoder.setRouting(prop.zoom); } if ( geocoder.getWorldview() !== prop.worldview && prop.worldview !== undefined ) { geocoder.setWorldview(prop.zoom); } } return <></>; } Discussion
__label__pos
0.988679
MRuby.each_target do file libfile("#{build_dir}/lib/libmruby") => libmruby.flatten do |t| archiver.run t.name, t.prerequisites end file "#{build_dir}/lib/libmruby.flags.mak" => [__FILE__, libfile("#{build_dir}/lib/libmruby")] do |t| open(t.name, 'w') do |f| f.puts "MRUBY_CFLAGS = #{cc.all_flags.gsub('"', '\\"')}" gem_flags = gems.map { |g| g.linker.flags } gem_library_paths = gems.map { |g| g.linker.library_paths } f.puts "MRUBY_LDFLAGS = #{linker.all_flags(gem_library_paths, gem_flags).gsub('"', '\\"')} #{linker.option_library_path % "#{build_dir}/lib"}" gem_flags_before_libraries = gems.map { |g| g.linker.flags_before_libraries } f.puts "MRUBY_LDFLAGS_BEFORE_LIBS = #{[linker.flags_before_libraries, gem_flags_before_libraries].flatten.join(' ').gsub('"', '\\"')}" gem_libraries = gems.map { |g| g.linker.libraries } f.puts "MRUBY_LIBS = #{linker.option_library % 'mruby'} #{linker.library_flags(gem_libraries).gsub('"', '\\"')}" end end task :all => "#{build_dir}/lib/libmruby.flags.mak" end Generated with Rubydoc Rdoc Generator 0.28.0.
__label__pos
0.855875
Next: , Previous: , Up: Binaries   [Contents][Index] 10.1 Invoking the msgfmt Program msgfmt [option] filename.po … The msgfmt programs generates a binary message catalog from a textual translation description. 10.1.1 Input file location filename.po … -D directory --directory=directory Add directory to the list of directories. Source files are searched relative to this list of directories. The resulting binary file will be written relative to the current directory, though. If an input file is ‘-’, standard input is read. 10.1.2 Operation mode -j --java Java mode: generate a Java ResourceBundle class. --java2 Like –java, and assume Java2 (JDK 1.2 or higher). --csharp C# mode: generate a .NET .dll file containing a subclass of GettextResourceSet. --csharp-resources C# resources mode: generate a .NET .resources file. --tcl Tcl mode: generate a tcl/msgcat .msg file. --qt Qt mode: generate a Qt .qm file. --desktop Desktop Entry mode: generate a .desktop file. --xml XML mode: generate an XML file. 10.1.3 Output file location -o file --output-file=file Write output to specified file. --strict Direct the program to work strictly following the Uniforum/Sun implementation. Currently this only affects the naming of the output file. If this option is not given the name of the output file is the same as the domain name. If the strict Uniforum mode is enabled the suffix .mo is added to the file name if it is not already present. We find this behaviour of Sun’s implementation rather silly and so by default this mode is not selected. If the output file is ‘-’, output is written to standard output. 10.1.4 Output file location in Java mode -r resource --resource=resource Specify the resource name. -l locale --locale=locale Specify the locale name, either a language specification of the form ll or a combined language and country specification of the form ll_CC. -d directory Specify the base directory of classes directory hierarchy. --source Produce a .java source file, instead of a compiled .class file. The class name is determined by appending the locale name to the resource name, separated with an underscore. The ‘-d’ option is mandatory. The class is written under the specified directory. 10.1.5 Output file location in C# mode -r resource --resource=resource Specify the resource name. -l locale --locale=locale Specify the locale name, either a language specification of the form ll or a combined language and country specification of the form ll_CC. -d directory Specify the base directory for locale dependent .dll files. The ‘-l’ and ‘-d’ options are mandatory. The .dll file is written in a subdirectory of the specified directory whose name depends on the locale. 10.1.6 Output file location in Tcl mode -l locale --locale=locale Specify the locale name, either a language specification of the form ll or a combined language and country specification of the form ll_CC. -d directory Specify the base directory of .msg message catalogs. The ‘-l’ and ‘-d’ options are mandatory. The .msg file is written in the specified directory. 10.1.7 Desktop Entry mode operations --template=template Specify a .desktop file used as a template. -k[keywordspec] --keyword[=keywordspec] Specify keywordspec as an additional keyword to be looked for. Without a keywordspec, the option means to not use default keywords. -l locale --locale=locale Specify the locale name, either a language specification of the form ll or a combined language and country specification of the form ll_CC. -d directory Specify the directory where PO files are read. The directory must contain the ‘LINGUAS’ file. To generate a ‘.desktop’ file for a single locale, you can use it as follows. msgfmt --desktop --template=template --locale=locale \ -o file filename.po … msgfmt provides a special "bulk" operation mode to process multiple .po files at a time. msgfmt --desktop --template=template -d directory -o file msgfmt first reads the ‘LINGUAS’ file under directory, and then processes all ‘.po’ files listed there. You can also limit the locales to a subset, through the ‘LINGUAS’ environment variable. For either operation modes, the ‘-o’ and ‘--template’ options are mandatory. 10.1.8 XML mode operations --template=template Specify an XML file used as a template. -L name --language=name Specifies the language of the input files. -l locale --locale=locale Specify the locale name, either a language specification of the form ll or a combined language and country specification of the form ll_CC. -d directory Specify the base directory of .po message catalogs. To generate an XML file for a single locale, you can use it as follows. msgfmt --xml --template=template --locale=locale \ -o file filename.po … msgfmt provides a special "bulk" operation mode to process multiple .po files at a time. msgfmt --xml --template=template -d directory -o file msgfmt first reads the ‘LINGUAS’ file under directory, and then processes all ‘.po’ files listed there. You can also limit the locales to a subset, through the ‘LINGUAS’ environment variable. For either operation modes, the ‘-o’ and ‘--template’ options are mandatory. 10.1.9 Input file syntax -P --properties-input Assume the input files are Java ResourceBundles in Java .properties syntax, not in PO file syntax. --stringtable-input Assume the input files are NeXTstep/GNUstep localized resource files in .strings syntax, not in PO file syntax. 10.1.10 Input file interpretation -c --check Perform all the checks implied by --check-format, --check-header, --check-domain. --check-format Check language dependent format strings. If the string represents a format string used in a printf-like function both strings should have the same number of ‘%’ format specifiers, with matching types. If the flag c-format or possible-c-format appears in the special comment #, for this entry a check is performed. For example, the check will diagnose using ‘%.*s’ against ‘%s’, or ‘%d’ against ‘%s’, or ‘%d’ against ‘%x’. It can even handle positional parameters. Normally the xgettext program automatically decides whether a string is a format string or not. This algorithm is not perfect, though. It might regard a string as a format string though it is not used in a printf-like function and so msgfmt might report errors where there are none. To solve this problem the programmer can dictate the decision to the xgettext program (see c-format). The translator should not consider removing the flag from the #, line. This "fix" would be reversed again as soon as msgmerge is called the next time. --check-header Verify presence and contents of the header entry. See Header Entry, for a description of the various fields in the header entry. --check-domain Check for conflicts between domain directives and the --output-file option -C --check-compatibility Check that GNU msgfmt behaves like X/Open msgfmt. This will give an error when attempting to use the GNU extensions. --check-accelerators[=char] Check presence of keyboard accelerators for menu items. This is based on the convention used in some GUIs that a keyboard accelerator in a menu item string is designated by an immediately preceding ‘&’ character. Sometimes a keyboard accelerator is also called "keyboard mnemonic". This check verifies that if the untranslated string has exactly one ‘&’ character, the translated string has exactly one ‘&’ as well. If this option is given with a char argument, this char should be a non-alphanumeric character and is used as keyboard accelerator mark instead of ‘&’. -f --use-fuzzy Use fuzzy entries in output. Note that using this option is usually wrong, because fuzzy messages are exactly those which have not been validated by a human translator. 10.1.11 Output details -a number --alignment=number Align strings to number bytes (default: 1). --endianness=byteorder Write out 32-bit numbers in the given byte order. The possible values are big and little. The default depends on the platform, namely on the endianness of the CPU. MO files of any endianness can be used on any platform. When a MO file has an endianness other than the platform’s one, the 32-bit numbers from the MO file are swapped at runtime. The performance impact is negligible. This option can be useful to produce MO files that are independent of the platform. --no-hash Don’t include a hash table in the binary file. Lookup will be more expensive at run time (binary search instead of hash table lookup). 10.1.12 Informative output -h --help Display this help and exit. -V --version Output version information and exit. --statistics Print statistics about translations. When the option --verbose is used in combination with --statistics, the input file name is printed in front of the statistics line. -v --verbose Increase verbosity level. Next: , Previous: , Up: Binaries   [Contents][Index]
__label__pos
0.606097
DQ #1 300 pts ended Discuss the advantages and disadvantages of the following non-experimental designs: 1. Naturalistic observations, 2. Phenomenolgical studies 3. Case studies 4. Archival studies If you were asked to use one of these studies in the next week which one of these non-experimental studies would you use and why? Answers (0) Step-by-step solutions to problems in 2,500 textbooks Fast expert answers 24/7 Ask a question
__label__pos
0.999963
Libsodium v1.0.12 and v1.0.13 Security Assessment Posted on Aug 16, 2017 by PIA Team   Contents 1 Executive Summary 2 Introduction 2.1 Scope  2.2 Approach 2.3 Classification and Severity Rating 3 Findings 3.1 Summary of Findings 3.2 Overview of Cryptographic Design 3.3 Static Analysis Results 3.4 Dynamic Analysis Results 3.5 Detailed Findings 3.5.1 SD-01: Randomness source on Windows based on unofficial APIs only 3.5.2 SD-02: Possible null pointer dereference in key exchange API 3.5.3 SD-03: Potential issues with abort() to terminate program on error conditions 3.5.4 SD-04: Potential risks with the custom RNG API 3.5.5 SD-05: Missing APIs in the libsodium documentation 3.5.6 SD-06: Lack of elliptic curves at higher security levels 3.5.7 Formal Verification (In progress) 3.5.8 Diffs between version 1.0.12 and 1.0.13 4 Conclusions 1 Executive Summary Libsodium1 is an open-source, easy-to-use fork of the C-language NaCl crypto library that is portable, cross-platform and provides many common cryptographic functions. These include public-key encryption, signatures, key derivation, password hashing, message authentication codes, stream ciphers, pseudo-random number generators, random number generation, and support for elliptic curves such as Curve25519. This review was funded by Private Internet Access TM (PIA), although PIA did not direct the review or modify the results. We performed a security review of the libsodium v1.0.12 and v1.0.13 releases to uncover various types of security weaknesses in its core code. During this limited engagement, our security review included the components of libsodium that handle: authenticated symmetric encryption, public key encryption, hashing, key derivation and key exchange. In addition we analyzed the underlying cryptographic primitives for correctness and security. Overall our finding is that libsodium is a secure, high-quality library that meets its stated usability and efficiency goals. We did not uncover any major vulnerabilities in the version of libsodium that we reviewed. During our review, we did identify a few low severity issues in libsodium related to the usability of the API and software security. In addition, we identified some potential risks with allowing developers to customize the random number generation that developers should take into consideration to prevent introducing vulnerabilities. 1https://github.com/jedisct1/libsodium 2 Introduction Libsodium1 is an open-source, easy-to-use fork of the C-language NaCl crypto library that is portable, cross-platform and provides many common cryptographic functions. These include public-key encryption, signatures, key derivation, password hashing, message authentication codes, stream ciphers, pseudo-random number generators, random number generation, and support for elliptic curves such as Curve25519. Libsodium was designed to provide high-level APIs that abstract the implementation details of these common cryptographic operations. Moreover, the well-written API was designed to prevent misuse by application developers. Several programming language bindings exist for libsodium and have been ported to the major operating systems (e.g., Unix/Linux, Windows, Mac OS X). The library has also been ported to support browsers using Emscripten2 and native client in addition to support for microarchitectures such as ARM and MIPS. Given this extensive support, it is no surprise that libsodium is widely used by several companies, open-source libraries and applications.3 1https://github.com/jedisct1/libsodium 2Emscripten compiles C/C++ via LLVM bitcode into JavaScript which can run on the web: https://github.com/kripken/emscripten. 3Companies such as Digital Ocean, Zerocoin Electric Coin Company and Keybase. Open source projects such as ZeroMQ, Macaroons, and MEGA SDK. 2.1 Scope We performed a security review of the libsodium v1.0.12 and v1.0.13 releases to uncover various types of security weaknesses in its core code. During this limited engagement, our security review included the following components of libsodium: – Interfaces for generating random numbers. We analyzed the interface for each type of platform (Unix/Linux, Windows and Mac OS X), as well as the interface for customizing the random number generator (RNG) if none of the existing options apply. – Authenticated symmetric encryption. This includes the secret-key authenticated encryption (or crypto_secretbox) and the authenticated encryption with associated data (AEAD) constructions. It also includes advanced features like precomputation. – Authenticated public-key encryption. This include the crypto_box implementation which adds public-key authenticated encryption and message authentication code (MAC) constructions in addition to the crypto_secretbox and the one-time secret-key message authentication constructions. – Generic hash API. This is used for computing a fixed-length digest for arbitrary-sized messages based on a secure hash function. It includes the short input hashing API for data structures such as hash tables and bloom filters. – Key derivation API. These are used for deriving keys from passwords or subkeys based on a given master key and key identifier. This includes password hashing and password storage constructions. – Key exchange API. This provides an interface for two parties to securely compute shared secrets using the peer’s public key and the communicating party’s secret key. – Underlying primitives. This includes the Elliptic Curve Diffie Hellman (or ECDH) implementation, public-key signatures, and stream cipher constructions. 2.2 Approach The security analysis of the libsodium code base involves a manual and automated analysis to uncover common vulnerabilities in the cryptographic library design and implementation. We first manually analyzed the design for various security weaknesses as well as for several classes of C vulnerabilities which include stack or heap-based buffer overflows, off-by-one errors, use-after-free, possible null pointer dereferences, and other related memory corruption bugs. We then checked the core code for possible vulnerabilities which includes weaknesses in the random number generation, possible timing attacks against various cryptographic algorithms, invalid curve style attacks against the elliptic curves supported and other types of crypto-related weaknesses. Moreover, we performed an automated memory analysis of the code base using both static analysis tools and dynamic analysis tools to uncover security vulnerabilities. We also investigated potential ways for a developer to potentially misuse the API using the library documentation. Finally, we attempted to use formal verification tools developed by Galois, Inc to prove equivalence between algorithm implementations in libsodium and a Galois formal specification, however after significant consultation with Galois, we were unable to complete this task as of the report deadline (see §3.5.7 for details). Future versions of this report may include these results. 2.3 Classification and Severity Rating We classified the issues found during the security review of libsodium according to the Common Weakness Enumeration (CWE) list. We followed a straightforward severity rating system of low, medium or high based on best practices for securely coding in C, best practices for cryptographic design, common use cases of libsodium and the potential security impact. – Low. A low severity rating indicates that the issue poses a relatively small or limited risk to applications/users of the library. – Medium. A medium severity rating indicates that the issue could potentially be exploited and an individual user could be compromised. – High. A high severity rating indicates that a large number of users are at significant risk of compromise and the issue should be addressed immediately. Lastly, we designate the Info rating to indicate non-security risks that could negatively impact users/applications that build on the library. This rating should be treated as ways that the open-source project could be improved to better serve users.  3 Findings Our review of libsodium began with the v1.0.12 release from March 13th, 2017 and continued with commits since then to the release of v1.0.13 in the Github repository.1 We attempted to identify weaknesses and vulnerabilities in the cryptographic library by manually reviewing the source, and using static and dynamic memory analysis tools. In this section, we provide a summary of our findings in addition to reporting details on issues that were uncovered during our review. 3.1 Summary of Findings Overall our finding is that libsodium is indeed a secure, high-quality library that meets its stated usability and efficiency goals. We did not uncover any major vulnerabilities in the version of libsodium that we reviewed. During our review, we did identify several low severity issues in the libsodium 1.0.12 release related to the usability of the API and software security. In addition, we identified some potential risks with allowing developers to customize the random number generation that developers should take into consideration to prevent introducing vulnerabilities. We report on the summary of our findings in Table 3.1 and provide further details in Section 3.5. Next, we provide a high-level summary of our review. In terms of mitigating common C vulnerabilities, libsodium developers follow best practices with respect to preventing buffer overflows and providing helper routines for handling sensitive data in memory. Specifically, the libsodium memory allocation routines are provided for locking memory pages (sodium_mlock()), and wiping sensitive data (sodium_memzero()) in a way that is not optimized out by a compiler or linker. sodium_mlock() is ideal for preventing swapping sensitive data to disk. For added security, the library provides guarded heap allocators (sodium_malloc()) specifically for storing sensitive data in memory. The allocated memory is placed at the end of a page boundary followed by the guarded page. Any access beyond the end of the memory region will terminate the application. This type of memory allocation comes at a cost (requires up to 4 extra virtual memory pages), slower than the C malloc(), and is not ideal for variable-length data. In this same direction, libsodium provides three routines to deal with memory page protections. The sodium_mprotect_noaccess() function makes allocated memory inaccessible (cannot read or write) but the data are preserved. The sodium_mprotect_readonly() function marks data read only to prevent modifications until a specific operation. The sodium_mprotect_readwrite() marks data read and write accessible only after having been protected by either of the former routines. We reviewed the routines for generating cryptographically strong random numbers on each supported platform. Generally speaking, the randomness used for key generation, nonces and encryption are from strong sources. Weak (or deterministic) sources are clearly marked as such and only used in the test suite to ensure reproducibility. However, we found some potential API risks associated with Windows and provide further details in Section 3.5.1. We analyzed the underlying core primitives implemented in libsodium to check for various security properties.2 For instance, we confirmed that each operation was free from branche or array lookups based on secret information. We also confirmed that sensitive data and keys in buffers are securely erased (via sodium_memzero()) after specific operations. Similarly, we confirmed that verification operations for password hashing and MACs are done in constant-time using sodium_memcmp(). Based on our analysis, we can conclude that libsodium follows cryptographic best practices in terms of resistance to side channels and protecting confidential data. We checked how libsodium handles user inputs in terms of array bounds checking, null pointer dereferences and error handling. By default, libsodium takes a conservative approach and terminates the program immediately if invalid inputs are supplied by the user. To gracefully recover from these types of errors, the application must intercept the SIGABRT signal. In terms of error handling, libsodium routines return -1 in some cases to indicate invalid inputs, decryption or verification failure. In addition, errno is set to indicate the specific error. Lastly, we found only two cases in which it might be possible to dereference a null pointer. This is described in more detail in Section 3.5.2. In summary, we did not find any critical flaws or vulnerabilities in libsodium and we suggest minor improvements based on our findings described in Section 3.5. Lastly, we also report on the results of static analysis (Section 3.3) and dynamic analysis tools (Section 3.4) on the libsodium core code. 1https://github.com/jedisct1/libsodium 2The core primitives include Curve25519, Poly1305 MAC, AES-CTR/GCM, Blake2b, ChaCha20, Salsa, and etc. 3.2 Overview of Cryptographic Design Libsodium provides many cryptographic constructions and variants. In this section, we explore the notable cryptographic choices of the library and where it differs from the NaCl library. In addition, we mention the associated high-level APIs and the advanced features that are exposed to application developers. Table 3.1: Summary of Findings Hash Functions, Short Input Hashing and Message Authentication Codes. The library includes the SHA family of hash functions (SHA-256 and SHA-512) for interoperability, and BLAKE2b (as part of the generic hash function interface) for speed and security. The library includes secure constructions for keyed-message authentication via HMAC-SHA-256 and HMAC-SHA-512 (with multi-part API for streaming messages). In cases where hashing support for data structures like hash tables are required, libsodium provides a short input hash function based on SipHash [1] that outputs 64-bits. SipHash is optimized for this use case, but is not a cryptographic hash function. The Poly1305 [2] Carter-Wegman message authenticator (inherited from NaCl) is used for multiple purposes in libsodium. In addition to being used as part of authenticated encryption constructions, it is also provided as a standalone primitive for one-time authentication of short messages (or crypto_onetimeauth()). This interface takes as input a single-use key, message and produces a 128-bit authentication tag. Password Hashing and Password Storage. The password hashing and password storage APIs and constructions are new and not part of the NaCl library. Specifically, the password hashing primitive is based on memory-hard functions Argon2 and scrypt.3 Libsodium implements the Argon2i variant which uses data-independent memory access and this is also ideal for password-based key derivation (or crypto_pwhash()) in addition to password hashing (or crypto_pwhash_str()). The high-level primitives are based on Argon2i by default. In addition, these functions are provided with safe default parameters that require a large amount of memory to execute brute-force attacks. In the documentation, there are also guidelines for picking the parameters (opslimit and memlimit) to balance between efficiency and security which consider interactive and non-interactive scenarios. Libsodium provides a similar API specifically for scrypt, which is a widely deployed safe alternative to Argon2 via crypto_pwhash_scryptsalsa208sha256() for deriving keys from passwords and crypto_pwhash_scryptsalsa208sha256_str() for password hashing. It is recommended in the documentation that users pre-hash the passwords (via BLAKE2b) prior to applying scrypt if passwords are 65 bytes or longer and potentially hashed via unsalted SHA-256 elsewhere. Given the security implications, we suggest that a separate high-level wrapper could be provided in libsodium that pre-hashes by default for such scenarios to prevent misuse by uninformed users. Key Derivation. Libsodium recently introduced a key derivation API (or crypto_kdf_derive_from_key) in version 1.0.12 specifically for deriving subkeys from a single master key, a subkey identifier (64 bits) and a context string. This API uses BLAKE2b as the underlying hash function and can produce up to 2 64 keys with key lengths varying from 128 to 512 bits. The required context string ensures that the same master key can be used in two domains of subkeys and prevents potential bugs. Authenticated Encryption. Libsodium is based on NaCl, and thus inherited a secure secret-key authenticated encryption primitive (or crypto_secretbox()) based on the XSalsa20 stream cipher and the Poly1305 message authentication code. Both were originally designed by Bernstein. The XSalsa20 stream cipher increases the nonce size to 192-bits from 64-bits in the original Salsa20 cipher design [3]. One notable improvement in libsodium: the library introduces new wrappers (crypto_secretbox_easy() and crypto_secretbox_detached()) around the original NaCl crypto_secretbox() API to remove the need for message padding and pointer arithmetic prior to encryption. This eliminates potential misuse by developers. The crypto_secretbox_easy() function encrypts a message with a single key and nonce and computes a tag over the resulting ciphertext. The crypto_secretbox_open_ easy() function verifies the tag and decrypts the ciphertext if successful. In combined mode (or *_easy()), the authentication tag and ciphertext are written to the same output buffer (tag is prepended to the encrypted message). In detached mode (or *_detached()), the tag and ciphertext are written into separate buffers. Authenticated Encryption with Associated Data. For AEADs, there are two provably secure constructions to choose from in libsodium: AES-GCM [10] and ChaCha20Poly1305 [9]. The AES-GCM implementation is hardware-accelerated using AES-NI instruc- tions and resistant to timing attacks. The ChaCha20-Poly1305 implementation combines a stream cipher and is resistant to timing attacks by design. In addition, this particular construction has two additional variants implemented in libsodium: an IETF version [7] and one with an extended nonce (XChaCha20-Poly1305) [4]. One benefit of the XChaCha20Poly1305 construction is that it enables nonce misuse-resistant schemes. These constructions are not only fast in software and hardware but also maintain interoperability with other popular cryptographic libraries such as OpenSSL. The only exception is that AES-GCM is slower compared to the other possible constructions when AES-NI is unavailable. Public-key Authenticated Encryption. In the public-key authenticated encryption construction (or crypto_box() from NaCl), the scheme is based on X25519 [8] for key exchange, XSalsa20 stream cipher for the encryption, and Poly1305 for the message authentication. Using the curve X25519, users can randomly generate an ephemeral keypair (public key and secret key) or can deterministically generate one from a given seed. The crypto_box_easy() routine takes as input the message, a nonce, the recipient’s public key and the sender’s secret key. This routine computes the shared key from the public and secret key (via scalar multiplication), encrypts the message via the stream cipher with the nonce as input and computes a tag over the ciphertext.4 The crypto_box_open_easy() verifies the tag then decrypts the ciphertext and returns the message on success. Also, libsodium includes an advanced precomputation interface for crypto_box() which allows computing the shared key once and then reusing that key structure to encrypt and decrypt several messages between the sender and receiver. With this interface, the user is mainly responsible for securely wiping the memory associated with the shared secret key. Public-key Signatures. For public-key signatures, libsodium also inherited the crypto_sign() API from NaCl. This is based on a Schnorr variant (Ed25519) [?] and adds a new multi-part signature API for authenticating multiple messages. This multi-part signature system is based on Ed25519 with message pre-hashing (via SHA-512). As an extension, libsodium provides a utility for converting Ed25519 keys to Curve25519 keys [?, Section 2] such that one keypair could be used for both authenticated encryption (via crypto_box) and signatures (via crypto_sign). However, the library does not support going in the other direction (Curve25519 to Ed25519 keys).5 Sealed Public-key Encryption. To support encryption with sender anonymity, libsodium includes a crypto_box_seal() API to allow encrypting a message such that even the sender cannot decrypt the message later (by destroying the sender’s secret key when generating the ephemeral keypair). The crypto_box_seal_open() function then allows a recipient to verify the integrity of the message without identifying the sender. Unauthenticated Encryption. Also inherited from NaCl, libsodium provides stream ciphers (or crypto_stream()) directly to users. However, users are warned in the source (or crypto_stream.h) from using these ciphers directly unless generating pseudo-random data from a key or building a larger cryptographic construction or protocol. The ciphers include ChaCha20, Salsa20, Salsa2012, Salsa208, XChaCha20 (new in 1.0.12), Xsalsa20 and AES-128 in counter mode.6 If reusing a key with this API, it is recommended that the nonces be incremented rather than randomly generated for each new message stream. Elliptic Curve Diffie-Hellman. Libsodium includes a dedicated interface for Elliptic Curve Diffie-Hellman over Curve25519 [6] that is used in the public-key encryption and key exchange protocol implementations. One important aspect of the scalar multiplication functionality is that it is optimized for different architectures and processors. In terms of security, one difference in libsodium compared to NaCl is that the computed shared secret is rejected if equal to 0 (thereby ensuring that Curve25519 public keys are valid). This validation removes the possibility of an attacker controlling the key without detection by communicating peers. 3Argon2/scrypt are designed to make it expensive to perform large-scale hardware attacks by requiring large amounts of memory and CPU. 4Reuses crypto_secretbox_*() 5We noted that the conversion routine does not include a check to verify that the input point is on the elliptic curve. We determined that this is unlikely to have a security impact, but the library developers have opted to incorporate a check in future versions of the library. 6Note that the ciphers are all implemented to resist timing attacks. nb 3.3 Static Analysis Results We applied the clang static analyzer to find possible bugs in the libsodium 1.0.12 release. The clang static analyzer is a source code level analyzer built on top of the clang/LLVM compiler toolchain. Using the clang static analysis tool, we only found 2 possible null pointer dereference bugs (CWE-476) in the key exchange API when used with Curve25519. These results are discussed in Section 3.5. We also ran the static analyzer on the libsodium source with commits since the libsodium 1.0.12 release and after the 1.0.13 release. There were no new issues reported by clang and the aforementioned bugs described have been fixed. As indicated in the libsodium documentation, static analysis is part of each release of the project which contributes to the overall quality of the crypto library. 3.4 Dynamic Analysis Results We analyzed the memory handling in libsodium 1.0.12 using dynamic analysis tools on a Ubuntu 16.04 LTS system. In particular, we used the address sanitizer tool (a memory corruption detector for C/C++ code) to find possible memory corruption bugs in libsodium crypto modules. We simultaneously applied valgrind as well to detect possible memory leaks that might arise while using the crypto API. As a result of applying both tools, we could not find any memory corruption related issues in the core library. One reason for this is that libsodium dynamically allocates memory mainly in the password hashing component.7 In this component, the libsodium developers follow best practices and always release memory even on error conditions. In addition, the developers execute dynamic analysis tools before each minor release and this process helps catch potential memory corruption bugs as new features are added to the code base. 7We note here that sodium_malloc also allocates memory on the heap. However, this is not used in the core library and meant for users of the library. 3.5 Detailed Findings In this section, we describe the detailed findings from the security review of libsodium. 3.5.1 SD-01: Randomness source on Windows based on unofficial APIs only On Windows-based platforms, the main source of entropy for cryptographic operations in libsodium comes from the RtlGenRandom() function. This involves loading the ADVAPI32.DLL dynamic library and then retrieving the SystemFunction036 function (also known as RtlGenRandom()). While this API provides a direct and low-overhead API to obtain randomness, libsodium developers made an explicit choice not to support the traditional CryptGenRandom() due to the memory overhead of Window’s Crypto API. Libsodium depends only on this unofficial API and if Microsoft decides to remove it at any point in the future, then there is no fallback option. We recommend adding an alternative method using e.g., CryptGenRandom() despite the increased memory overhead. This could be optionally enabled at compile time for users that prefer to use CryptGenRandom() with libsodium on Windows. 3.5.2 SD-02: Possible null pointer dereference in key exchange API Using the clang static analyzer, we found possible null pointer dereferences in crypto_kx_client_session_keys() and crypto_kx_server_session_keys() of the new key exchange API. The key exchange protocol allows two parties to securely derive a set of shared keys. The purpose of the crypto_kx_server_session_keys() function is to compute one or two session keys (or shared secrets) using the client’s public and private key, and the server’s public key. The input into this routine are pointers to output buffers rx and tx. If only one session key is required, then the user can simply set either rx or tx to NULL. In the expected use of this API, there is no possibility of a null pointer dereference. This is not the case if the user were to accidentally set both rx to tx to null. As a result, there is a null pointer dereference on line 100 in the code shown below. Note that the same issue exists in crypto_kx_client_session_keys() on line 62. 3.5.3 SD-03: Potential issues with abort() to terminate program on error conditions We found several places in libsodium in which the program is terminated via abort() due to the user specifying a larger than expected buffer length or insufficient randomness generated, for example. Given that bindings are important to the libsodium ecosystem (exposing the C API to PHP, Go, Java and many other programming languages), it may not be possible or convenient to handle the termination of a program in this fashion. Program termination prevents the application from gracefully recovering from such errors. One option would be to set a unique error code via errno for such error conditions (similar to other cases in libsodium) and propagate the error accordingly. This could be provided as a compile time option for users that would prefer such error handling. SD-04: Potential risks with the custom RNG API The interface to customize the random number generator provides a means to change how libsodium obtains randomness for a given platform. For some embedded platforms, using this API may be the only option for secure randomness. Libsodium ships a secure pseudo-random number generator (PRNG) construction which obtains a small amount of entropy from /dev/random or /dev/urandom (if available) to seed the Salsa20 stream cipher. Moreover, the default implementation includes random_stir() to occasionally reseed the PRNG. To use this PRNG, the user simply calls randombytes_set_implementation(&randombytes_salsa20_implementation) prior to initializing libsodium’s core via sodium_init(). The RNG implementation is comprised of 6 function pointers and only 3 are required. There are known issues with this approach. It is not thread-safe and a randombytes_stir() implementation is optional. Generally speaking, users could abuse this API in ways that would result in a weak PRNG for sensitive cryptographic operations. As such, we recommend limiting this interface to prevent such misuse. One possible approach would be to provide a generic PRNG implementation (similar to randombytes_salsa20_implementation()) but that takes as input a stream cipher (or hash function). Thus, users would be able to swap Salsa20 with ChaCha20 for example. 3.5.5 SD-05: Missing APIs in the libsodium documentation Libsodium ships with extensive documentation regarding how to use the library API and the rationale for the design. Extending such a document with each library release is a heroic effort for the libsodium project. Unfortunately, there are some inconsistencies between what is in the version 1.0.12 release and what is presently documented. For instance, some of the helper functions designed to simplify key and nonce generation primitives have been recently added to the library but have not been documented. We recommend that libsodium developers take a pass over the documentation to ensure consistency with the latest release.8 8Project source docs can be found at https://github.com/jedisct1/libsodium-doc. 3.5.6 SD-06: Lack of elliptic curves at higher security levels The main curve supported by the library is Curve25519 which is equivalent to the 128-bit security level. Currently, libsodium does not offer any curve support at the 224 and 256-bit security levels. While it is our understanding that Ed448-Goldilocks is on the roadmap for a future release (for 224-bit security), we recommend adding one additional curve at the 256-bit security level as well. This would provide sufficient curve options at different security levels for application developers. 3.5.7 Formal Verification (In progress) Libsodium originally started as a fork of NaCl with the same core cryptographic algorithms and a compatible API. However, it has been improved and extended to support additional features. For example, libsodium provides optimized implementations of ChaCha20, Salsa20 and Poly1305 for specific processors (e.g., SSE3/AVX2). One potential problem is that subtle changes in libsodium might impact correctness and passing known answer tests alone do not provide sufficient guarantees that the cryptographic algorithms are correct on all inputs. To this end, we attempted to use the existing formal verification tools developed by Galois, Inc to prove equivalence between certain implementations in libsodium and its formal specification. The tools consists of Cryptol, a domain-specific language for specifying cryptographic algorithms.9 For example, Cryptol provides a set of example specifications for stream ciphers such as Salsa20 and ChaCha20. It also includes the software analysis workbench (SAW) which is a powerful tool for extracting formal models from cryptographic implementations and analyzing those models using automated reasoning tools. One such reasoning tool is ABC developed at UC Berkeley which is a system for synthesis and verification.10 This includes the Microsoft Z3 theorem prover [5]. Unfortunately, due to incompatibilities between libsodium and SAW we were unablesp to complete this task by the report deadline. We are currently consulting with Galois, Inc. to address these issues and will include results in a future version of this report, if possible. 9 http://cryptol.net/files/cryptol_whitepaper.pdf 10 https://people.eecs.berkeley.edu/~alanmi/abc/ 3.5.8 Diffs between version 1.0.12 and 1.0.13 This report originally focused on the security review of libsodium 1.0.12. However, version 1.0.13 was released recently on July 13th, 2017 and we further analyzed the differences to date. There are approximately 98 commits between the 1.0.12 and 1.0.13 version and we provide a summary of the notable differences (excluding documentation improvements, fixes to various software build issues and readability of the source code): – Fixed the crypto_pwhash_argon2i_MEMLIMIT_MAX constant which was incorrectly defined for 32-bit platforms. – Added an AVX2 optimized implementation of the Argon2 round function. – Added the Argon2id variant of Argon2 in addition to a high-level API that integrates both Argon2i and Argon2id. The password hashing API (crypto_pwhash_str_verify()) can work with either Argon2i and Argon2id variants by checking for the appropriate prefix in the hashed password. – Added an XChaCha version for the crypto_box_seal() primitive. This version is implemented as crypto_box_curve25519xchacha20poly1305_seal*() and does not include a high-level API. To the best of our knowledge, we could not identify any new vulnerabilities as a result of the commits during this period. 4 Conclusions Our review of libsodium did not uncover any critical flaws or vulnerabilities in the core library. Libsodium developers have followed best practices in terms of cryptographic design and secure development in C. The library provides the right level of abstraction for application developers that need a secure, easy-to-use API for cryptography. Moreover, the library provides secure defaults for every cryptographic primitive with production-level quality. To maintain support for a variety of applications and protocols, we recommend that the libsodium project remain focused on providing simple cryptographic functions for common problems to users. As new cryptographic primitives, features and high-level APIs are added to the library, it is important that the libsodium developers continue to highlight the intended use cases and provide example code to prevent misuse. 5 Bibliography [1] Jean-Philippe Aumasson and Daniel J Bernstein. SipHash: a fast short-input PRF. In International Conference on Cryptology in India, pages 489–508. Springer, 2012. [2] Daniel J Bernstein. The Poly1305-AES message-authentication code. In International Workshop on Fast Software Encryption, pages 32–49. Springer, 2005. [3] Daniel J Bernstein. Salsa20 specification. eSTREAM Project algorithm description, http://www.ecrypt.eu.org/stream/salsa20pf.html, 2005. [4] Daniel J Bernstein. Extending the Salsa20 nonce. In Workshop record of Symmetric Key Encryption Workshop, volume 2011, 2011. [5] Leonardo De Moura and Nikolaj Bjørner. Z3: An efficient SMT solver. In Proceedings of the Theory and Practice of Software, 14th International Conference on Tools and Algorithms for the Construction and Analysis of Systems, TACAS’08/ETAPS’08, pages 337–340, Berlin, Heidelberg, 2008. Springer-Verlag. [6] Adam Langley, Mike Hamburg, and Sean Turner. Elliptic curves for security. RFC7748, January 2016. [7] Adam Langley and Yoav Nir. ChaCha20 and Poly1305 for IETF protocols. 2015. [8] Y Nir and S Josefsson. Curve25519 and Curve448 for the Internet Key Exchange protocol version 2 (IKEv2) key agreement. Technical report, 2016. [9] Gordon Procter. A security analysis of the composition of ChaCha20 and Poly1305. IACR Cryptology ePrint Archive, 2014:613, 2014. [10] Joseph Salowey, Abhijit Choudhury, and David McGrew. AES Galois Counter Mode (GCM) cipher suites for TLS. Technical report, 2008. PDF: libsodium.pdf MD5 hash: 19cd86b2a571070ccfd62088f87d5417 VPN Service Comments are closed. 1 Comments 1. James Ross-Gowan For what it’s worth, SD-01 is wrong. There is absolutely no chance that SystemFunction036() will ever disappear from future versions of Windows. This is because it’s used by the rand_s() CRT function, so if it was ever removed, C and C++ programs that use the CRT redistributables and use rand_s() as a CSPRNG would be broken as well. Since the CRT is designed to be distributed with applications that use it, SystemFunction036 can never be removed, because the number of broken applications would be too large. 3 years ago
__label__pos
0.673303
vim-jp / vimdoc-en / builtin builtin - Vim Documentation Return to main English | 日本語 builtin.txt   For Vim version 9.1.  Last change: 2024 Feb 25                   VIM REFERENCE MANUAL    by Bram Moolenaar Builtin functions                               builtin-functions Note: Expression evaluation can be disabled at compile time, the builtin functions are not available then.  See +eval and no-eval-feature. For functions grouped by what they are used for see function-list. 1. Overview                             builtin-function-list 2. Details                              builtin-function-details 3. Feature list                         feature-list 4. Matching a pattern in a String       string-match ============================================================================== 1. Overview                                     builtin-function-list Use CTRL-] on the function name to jump to the full explanation. USAGE                           RESULT  DESCRIPTION abs({expr})                     Float or Number  absolute value of {expr} acos({expr})                    Float   arc cosine of {expr} add({object}{item})           List/Blob   append {item} to {object} and({expr}{expr})             Number  bitwise AND append({lnum}{text})          Number  append {text} below line {lnum} appendbufline({expr}{lnum}{text})                                 Number  append {text} below line {lnum}                                         in buffer {expr} argc([{winid}])                 Number  number of files in the argument list argidx()                        Number  current index in the argument list arglistid([{winnr} [, {tabnr}]]) Number argument list id argv({nr} [, {winid}])          String  {nr} entry of the argument list argv([-1, {winid}])             List    the argument list asin({expr})                    Float   arc sine of {expr} assert_beeps({cmd})             Number  assert {cmd} causes a beep assert_equal({exp}{act} [, {msg}])                                 Number  assert {exp} is equal to {act} assert_equalfile({fname-one}{fname-two} [, {msg}])                                 Number  assert file contents are equal assert_exception({error} [, {msg}])                                 Number  assert {error} is in v:exception assert_fails({cmd} [, {error} [, {msg} [, {lnum} [, {context}]]]])                                 Number  assert {cmd} fails assert_false({actual} [, {msg}])                                 Number  assert {actual} is false assert_inrange({lower}{upper}{actual} [, {msg}])                                 Number  assert {actual} is inside the range assert_match({pat}{text} [, {msg}])                                 Number  assert {pat} matches {text} assert_nobeep({cmd})            Number  assert {cmd} does not cause a beep assert_notequal({exp}{act} [, {msg}])                                 Number  assert {exp} is not equal {act} assert_notmatch({pat}{text} [, {msg}])                                 Number  assert {pat} not matches {text} assert_report({msg})            Number  report a test failure assert_true({actual} [, {msg}]) Number  assert {actual} is true atan({expr})                    Float   arc tangent of {expr} atan2({expr1}{expr2})         Float   arc tangent of {expr1} / {expr2} autocmd_add({acmds})            Bool    add a list of autocmds and groups autocmd_delete({acmds})         Bool    delete a list of autocmds and groups autocmd_get([{opts}])           List    return a list of autocmds balloon_gettext()               String  current text in the balloon balloon_show({expr})            none    show {expr} inside the balloon balloon_split({msg})            List    split {msg} as used for a balloon blob2list({blob})               List    convert {blob} into a list of numbers browse({save}{title}{initdir}{default})                                 String  put up a file requester browsedir({title}{initdir})   String  put up a directory requester bufadd({name})                  Number  add a buffer to the buffer list bufexists({buf})                Number  TRUE if buffer {buf} exists buflisted({buf})                Number  TRUE if buffer {buf} is listed bufload({buf})                  Number  load buffer {buf} if not loaded yet bufloaded({buf})                Number  TRUE if buffer {buf} is loaded bufname([{buf}])                String  Name of the buffer {buf} bufnr([{buf} [, {create}]])     Number  Number of the buffer {buf} bufwinid({buf})                 Number  window ID of buffer {buf} bufwinnr({buf})                 Number  window number of buffer {buf} byte2line({byte})               Number  line number at byte count {byte} byteidx({expr}{nr} [, {utf16}])                                 Number  byte index of {nr}'th char in {expr} byteidxcomp({expr}{nr} [, {utf16}])                                 Number  byte index of {nr}'th char in {expr} call({func}{arglist} [, {dict}])                                 any     call {func} with arguments {arglist} ceil({expr})                    Float   round {expr} up ch_canread({handle})            Number  check if there is something to read ch_close({handle})              none    close {handle} ch_close_in({handle})           none    close in part of {handle} ch_evalexpr({handle}{expr} [, {options}])                                 any     evaluate {expr} on JSON {handle} ch_evalraw({handle}{string} [, {options}])                                 any     evaluate {string} on raw {handle} ch_getbufnr({handle}{what})   Number  get buffer number for {handle}/{what} ch_getjob({channel})            Job     get the Job of {channel} ch_info({handle})               String  info about channel {handle} ch_log({msg} [, {handle}])      none    write {msg} in the channel log file ch_logfile({fname} [, {mode}])  none    start logging channel activity ch_open({address} [, {options}])                                 Channel open a channel to {address} ch_read({handle} [, {options}]) String  read from {handle} ch_readblob({handle} [, {options}])                                 Blob    read Blob from {handle} ch_readraw({handle} [, {options}])                                 String  read raw from {handle} ch_sendexpr({handle}{expr} [, {options}])                                 any     send {expr} over JSON {handle} ch_sendraw({handle}{expr} [, {options}])                                 any     send {expr} over raw {handle} ch_setoptions({handle}{options})                                 none    set options for {handle} ch_status({handle} [, {options}])                                 String  status of channel {handle} changenr()                      Number  current change number char2nr({expr} [, {utf8}])      Number  ASCII/UTF-8 value of first char in {expr} charclass({string})             Number  character class of {string} charcol({expr} [, {winid}])     Number  column number of cursor or mark charidx({string}{idx} [, {countcc} [, {utf16}]])                                 Number  char index of byte {idx} in {string} chdir({dir})                    String  change current working directory cindent({lnum})                 Number  C indent for line {lnum} clearmatches([{win}])           none    clear all matches col({expr} [, {winid}])         Number  column byte index of cursor or mark complete({startcol}{matches}) none    set Insert mode completion complete_add({expr})            Number  add completion match complete_check()                Number  check for key typed during completion complete_info([{what}])         Dict    get current completion information confirm({msg} [, {choices} [, {default} [, {type}]]])                                 Number  number of choice picked by user copy({expr})                    any     make a shallow copy of {expr} cos({expr})                     Float   cosine of {expr} cosh({expr})                    Float   hyperbolic cosine of {expr} count({comp}{expr} [, {ic} [, {start}]])                                 Number  count how many {expr} are in {comp} cscope_connection([{num}{dbpath} [, {prepend}]])                                 Number  checks existence of cscope connection cursor({lnum}{col} [, {off}])                                 Number  move cursor to {lnum}{col}{off} cursor({list})                  Number  move cursor to position in {list} debugbreak({pid})               Number  interrupt process being debugged deepcopy({expr} [, {noref}])    any     make a full copy of {expr} delete({fname} [, {flags}])     Number  delete the file or directory {fname} deletebufline({buf}{first} [, {last}])                                 Number  delete lines from buffer {buf} did_filetype()                  Number  TRUE if FileType autocmd event used diff({fromlist}{tolist} [, {options}])                                 List    diff two Lists of strings diff_filler({lnum})             Number  diff filler lines about {lnum} diff_hlID({lnum}{col})        Number  diff highlighting at {lnum}/{col} digraph_get({chars})            String  get the digraph of {chars} digraph_getlist([{listall}])    List    get all digraphs digraph_set({chars}{digraph}) Boolean register digraph digraph_setlist({digraphlist})  Boolean register multiple digraphs echoraw({expr})                 none    output {expr} as-is empty({expr})                   Number  TRUE if {expr} is empty environ()                       Dict    return environment variables err_teapot([{expr}])            none    give E418, or E503 if {expr} is TRUE escape({string}{chars})       String  escape {chars} in {string} with '\' eval({string})                  any     evaluate {string} into its value eventhandler()                  Number  TRUE if inside an event handler executable({expr})              Number  1 if executable {expr} exists execute({command})              String  execute {command} and get the output exepath({expr})                 String  full path of the command {expr} exists({expr})                  Number  TRUE if {expr} exists exists_compiled({expr})         Number  TRUE if {expr} exists at compile time exp({expr})                     Float   exponential of {expr} expand({expr} [, {nosuf} [, {list}]])                                 any     expand special keywords in {expr} expandcmd({string} [, {options}])                                 String  expand {string} like with :edit extend({expr1}{expr2} [, {expr3}])                                 List/Dict insert items of {expr2} into {expr1} extendnew({expr1}{expr2} [, {expr3}])                                 List/Dict like extend() but creates a new                                         List or Dictionary feedkeys({string} [, {mode}])   Number  add key sequence to typeahead buffer filereadable({file})            Number  TRUE if {file} is a readable file filewritable({file})            Number  TRUE if {file} is a writable file filter({expr1}{expr2})        List/Dict/Blob/String                                         remove items from {expr1} where                                         {expr2} is 0 finddir({name} [, {path} [, {count}]])                                 String  find directory {name} in {path} findfile({name} [, {path} [, {count}]])                                 String  find file {name} in {path} flatten({list} [, {maxdepth}])  List    flatten {list} up to {maxdepth} levels flattennew({list} [, {maxdepth}])                                 List    flatten a copy of {list} float2nr({expr})                Number  convert Float {expr} to a Number floor({expr})                   Float   round {expr} down fmod({expr1}{expr2})          Float   remainder of {expr1} / {expr2} fnameescape({fname})            String  escape special characters in {fname} fnamemodify({fname}{mods})    String  modify file name foldclosed({lnum})              Number  first line of fold at {lnum} if closed foldclosedend({lnum})           Number  last line of fold at {lnum} if closed foldlevel({lnum})               Number  fold level at {lnum} foldtext()                      String  line displayed for closed fold foldtextresult({lnum})          String  text for closed fold at {lnum} foreach({expr1}{expr2})       List/Dict/Blob/String                                         for each item in {expr1} call {expr2} foreground()                    Number  bring the Vim window to the foreground fullcommand({name} [, {vim9}])  String  get full command from {name} funcref({name} [, {arglist}] [, {dict}])                                 Funcref reference to function {name} function({name} [, {arglist}] [, {dict}])                                 Funcref named reference to function {name} garbagecollect([{atexit}])      none    free memory, breaking cyclic references get({list}{idx} [, {def}])    any     get item {idx} from {list} or {def} get({dict}{key} [, {def}])    any     get item {key} from {dict} or {def} get({func}{what})             any     get property of funcref/partial {func} getbufinfo([{buf}])             List    information about buffers getbufline({buf}{lnum} [, {end}])                                 List    lines {lnum} to {end} of buffer {buf} getbufoneline({buf}{lnum})    String  line {lnum} of buffer {buf} getbufvar({buf}{varname} [, {def}])                                 any     variable {varname} in buffer {buf} getcellwidths()                 List    get character cell width overrides getchangelist([{buf}])          List    list of change list items getchar([expr])                 Number or String                                         get one character from the user getcharmod()                    Number  modifiers for the last typed character getcharpos({expr})              List    position of cursor, mark, etc. getcharsearch()                 Dict    last character search getcharstr([expr])              String  get one character from the user getcmdcompltype()               String  return the type of the current                                         command-line completion getcmdline()                    String  return the current command-line getcmdpos()                     Number  return cursor position in command-line getcmdscreenpos()               Number  return cursor screen position in                                         command-line getcmdtype()                    String  return current command-line type getcmdwintype()                 String  return current command-line window type getcompletion({pat}{type} [, {filtered}])                                 List    list of cmdline completion matches getcurpos([{winnr}])            List    position of the cursor getcursorcharpos([{winnr}])     List    character position of the cursor getcwd([{winnr} [, {tabnr}]])   String  get the current working directory getenv({name})                  String  return environment variable getfontname([{name}])           String  name of font being used getfperm({fname})               String  file permissions of file {fname} getfsize({fname})               Number  size in bytes of file {fname} getftime({fname})               Number  last modification time of file getftype({fname})               String  description of type of file {fname} getimstatus()                   Number  TRUE if the IME status is active getjumplist([{winnr} [, {tabnr}]])                                 List    list of jump list items getline({lnum})                 String  line {lnum} of current buffer getline({lnum}{end})          List    lines {lnum} to {end} of current buffer getloclist({nr})                List    list of location list items getloclist({nr}{what})        Dict    get specific location list properties getmarklist([{buf}])            List    list of global/local marks getmatches([{win}])             List    list of current matches getmousepos()                   Dict    last known mouse position getmouseshape()                 String  current mouse shape name getpid()                        Number  process ID of Vim getpos({expr})                  List    position of cursor, mark, etc. getqflist()                     List    list of quickfix items getqflist({what})               Dict    get specific quickfix list properties getreg([{regname} [, 1 [, {list}]]])                                 String or List   contents of a register getreginfo([{regname}])         Dict    information about a register getregion({pos1}{pos2}{type})                                 List    get the text from {pos1} to {pos2} getregtype([{regname}])         String  type of a register getscriptinfo([{opts}])         List    list of sourced scripts gettabinfo([{expr}])            List    list of tab pages gettabvar({nr}{varname} [, {def}])                                 any     variable {varname} in tab {nr} or {def} gettabwinvar({tabnr}{winnr}{name} [, {def}])                                 any     {name} in {winnr} in tab page {tabnr} gettagstack([{nr}])             Dict    get the tag stack of window {nr} gettext({text})                 String  lookup translation of {text} getwininfo([{winid}])           List    list of info about each window getwinpos([{timeout}])          List    X and Y coord in pixels of Vim window getwinposx()                    Number  X coord in pixels of the Vim window getwinposy()                    Number  Y coord in pixels of the Vim window getwinvar({nr}{varname} [, {def}])                                 any     variable {varname} in window {nr} glob({expr} [, {nosuf} [, {list} [, {alllinks}]]])                                 any     expand file wildcards in {expr} glob2regpat({expr})             String  convert a glob pat into a search pat globpath({path}{expr} [, {nosuf} [, {list} [, {alllinks}]]])                                 String  do glob({expr}) for all dirs in {path} has({feature} [, {check}])      Number  TRUE if feature {feature} supported has_key({dict}{key})          Number  TRUE if {dict} has entry {key} haslocaldir([{winnr} [, {tabnr}]])                                 Number  TRUE if the window executed :lcd                                         or :tcd hasmapto({what} [, {mode} [, {abbr}]])                                 Number  TRUE if mapping to {what} exists histadd({history}{item})      Number  add an item to a history histdel({history} [, {item}])   Number  remove an item from a history histget({history} [, {index}])  String  get the item {index} from a history histnr({history})               Number  highest index of a history hlID({name})                    Number  syntax ID of highlight group {name} hlexists({name})                Number  TRUE if highlight group {name} exists hlget([{name} [, {resolve}]])   List    get highlight group attributes hlset({list})                   Number  set highlight group attributes hostname()                      String  name of the machine Vim is running on iconv({expr}{from}{to})     String  convert encoding of {expr} indent({lnum})                  Number  indent of line {lnum} index({object}{expr} [, {start} [, {ic}]])                                 Number  index in {object} where {expr} appears indexof({object}{expr} [, {opts}]])                                 Number  index in {object} where {expr} is true input({prompt} [, {text} [, {completion}]])                                 String  get input from the user inputdialog({prompt} [, {text} [, {cancelreturn}]])                                 String  like input() but in a GUI dialog inputlist({textlist})           Number  let the user pick from a choice list inputrestore()                  Number  restore typeahead inputsave()                     Number  save and clear typeahead inputsecret({prompt} [, {text}]) String like input() but hiding the text insert({object}{item} [, {idx}]) List insert {item} in {object} [before {idx}] instanceof({object}{class})   Number  TRUE if {object} is an instance of {class} interrupt()                     none    interrupt script execution invert({expr})                  Number  bitwise invert isabsolutepath({path})          Number  TRUE if {path} is an absolute path isdirectory({directory})        Number  TRUE if {directory} is a directory isinf({expr})                   Number  determine if {expr} is infinity value                                         (positive or negative) islocked({expr})                Number  TRUE if {expr} is locked isnan({expr})                   Number  TRUE if {expr} is NaN items({dict})                   List    key-value pairs in {dict} job_getchannel({job})           Channel get the channel handle for {job} job_info([{job}])               Dict    get information about {job} job_setoptions({job}{options}) none   set options for {job} job_start({command} [, {options}])                                 Job     start a job job_status({job})               String  get the status of {job} job_stop({job} [, {how}])       Number  stop {job} join({list} [, {sep}])          String  join {list} items into one String js_decode({string})             any     decode JS style JSON js_encode({expr})               String  encode JS style JSON json_decode({string})           any     decode JSON json_encode({expr})             String  encode JSON keys({dict})                    List    keys in {dict} keytrans({string})              String  translate internal keycodes to a form                                         that can be used by :map len({expr})                     Number  the length of {expr} libcall({lib}{func}{arg})   String  call {func} in library {lib} with {arg} libcallnr({lib}{func}{arg}) Number  idem, but return a Number line({expr} [, {winid}])        Number  line nr of cursor, last line or mark line2byte({lnum})               Number  byte count of line {lnum} lispindent({lnum})              Number  Lisp indent for line {lnum} list2blob({list})               Blob    turn {list} of numbers into a Blob list2str({list} [, {utf8}])     String  turn {list} of numbers into a String listener_add({callback} [, {buf}])                                 Number  add a callback to listen to changes listener_flush([{buf}])         none    invoke listener callbacks listener_remove({id})           none    remove a listener callback localtime()                     Number  current time log({expr})                     Float   natural logarithm (base e) of {expr} log10({expr})                   Float   logarithm of Float {expr} to base 10 luaeval({expr} [, {expr}])      any     evaluate Lua expression map({expr1}{expr2})           List/Dict/Blob/String                                         change each item in {expr1} to {expr2} maparg({name} [, {mode} [, {abbr} [, {dict}]]])                                 String or Dict                                         rhs of mapping {name} in mode {mode} mapcheck({name} [, {mode} [, {abbr}]])                                 String  check for mappings matching {name} maplist([{abbr}])               List    list of all mappings, a dict for each mapnew({expr1}{expr2})        List/Dict/Blob/String                                         like map() but creates a new List or                                         Dictionary mapset({mode}{abbr}{dict})  none    restore mapping from maparg() result match({expr}{pat} [, {start} [, {count}]])                                 Number  position where {pat} matches in {expr} matchadd({group}{pattern} [, {priority} [, {id} [, {dict}]]])                                 Number  highlight {pattern} with {group} matchaddpos({group}{pos} [, {priority} [, {id} [, {dict}]]])                                 Number  highlight positions with {group} matcharg({nr})                  List    arguments of :match matchbufline({buf}{pat}{lnum}{end}, [, {dict})                                 List    all the {pat} matches in buffer {buf} matchdelete({id} [, {win}])     Number  delete match identified by {id} matchend({expr}{pat} [, {start} [, {count}]])                                 Number  position where {pat} ends in {expr} matchfuzzy({list}{str} [, {dict}])                                 List    fuzzy match {str} in {list} matchfuzzypos({list}{str} [, {dict}])                                 List    fuzzy match {str} in {list} matchlist({expr}{pat} [, {start} [, {count}]])                                 List    match and submatches of {pat} in {expr} matchstr({expr}{pat} [, {start} [, {count}]])                                 String  {count}'th match of {pat} in {expr} matchstrlist({list}{pat} [, {dict})                                 List    all the {pat} matches in {list} matchstrpos({expr}{pat} [, {start} [, {count}]])                                 List    {count}'th match of {pat} in {expr} max({expr})                     Number  maximum value of items in {expr} menu_info({name} [, {mode}])    Dict    get menu item information min({expr})                     Number  minimum value of items in {expr} mkdir({name} [, {flags} [, {prot}]])                                 Number  create directory {name} mode([expr])                    String  current editing mode mzeval({expr})                  any     evaluate MzScheme expression nextnonblank({lnum})            Number  line nr of non-blank line >= {lnum} nr2char({expr} [, {utf8}])      String  single char with ASCII/UTF-8 value {expr} or({expr}{expr})              Number  bitwise OR pathshorten({expr} [, {len}])   String  shorten directory names in a path perleval({expr})                any     evaluate Perl expression popup_atcursor({what}{options}) Number create popup window near the cursor popup_beval({what}{options})  Number  create popup window for 'ballooneval' popup_clear()                   none    close all popup windows popup_close({id} [, {result}])  none    close popup window {id} popup_create({what}{options}) Number  create a popup window popup_dialog({what}{options}) Number  create a popup window used as a dialog popup_filter_menu({id}{key})  Number  filter for a menu popup window popup_filter_yesno({id}{key}) Number  filter for a dialog popup window popup_findecho()                Number  get window ID of popup for :echowin popup_findinfo()                Number  get window ID of info popup window popup_findpreview()             Number  get window ID of preview popup window popup_getoptions({id})          Dict    get options of popup window {id} popup_getpos({id})              Dict    get position of popup window {id} popup_hide({id})                none    hide popup menu {id} popup_list()                    List    get a list of window IDs of all popups popup_locate({row}{col})      Number  get window ID of popup at position popup_menu({what}{options})   Number  create a popup window used as a menu popup_move({id}{options})     none    set position of popup window {id} popup_notification({what}{options})                                 Number  create a notification popup window popup_setoptions({id}{options})                                 none    set options for popup window {id} popup_settext({id}{text})     none    set the text of popup window {id} popup_show({id})                none    unhide popup window {id} pow({x}{y})                   Float   {x} to the power of {y} prevnonblank({lnum})            Number  line nr of non-blank line <= {lnum} printf({fmt}{expr1}...)       String  format text prompt_getprompt({buf})         String  get prompt text prompt_setcallback({buf}{expr}) none  set prompt callback function prompt_setinterrupt({buf}{text}) none set prompt interrupt function prompt_setprompt({buf}{text}) none    set prompt text prop_add({lnum}{col}{props})  none  add one text property prop_add_list({props}, [[{lnum}{col}{end-lnum}{end-col}], ...])                                 none    add multiple text properties prop_clear({lnum} [, {lnum-end} [, {props}]])                                 none    remove all text properties prop_find({props} [, {direction}])                                 Dict    search for a text property prop_list({lnum} [, {props}])   List    text properties in {lnum} prop_remove({props} [, {lnum} [, {lnum-end}]])                                 Number  remove a text property prop_type_add({name}{props})  none    define a new property type prop_type_change({name}{props})                                 none    change an existing property type prop_type_delete({name} [, {props}])                                 none    delete a property type prop_type_get({name} [, {props}])                                 Dict    get property type values prop_type_list([{props}])       List    get list of property types pum_getpos()                    Dict    position and size of pum if visible pumvisible()                    Number  whether popup menu is visible py3eval({expr})                 any     evaluate python3 expression pyeval({expr})                  any     evaluate Python expression pyxeval({expr})                 any     evaluate python_x expression rand([{expr}])                  Number  get pseudo-random number range({expr} [, {max} [, {stride}]])                                 List    items from {expr} to {max} readblob({fname} [, {offset} [, {size}]])                                 Blob    read a Blob from {fname} readdir({dir} [, {expr} [, {dict}]])                                 List    file names in {dir} selected by {expr} readdirex({dir} [, {expr} [, {dict}]])                                 List    file info in {dir} selected by {expr} readfile({fname} [, {type} [, {max}]])                                 List    get list of lines from file {fname} reduce({object}{func} [, {initial}])                                 any     reduce {object} using {func} reg_executing()                 String  get the executing register name reg_recording()                 String  get the recording register name reltime([{start} [, {end}]])    List    get time value reltimefloat({time})            Float   turn the time value into a Float reltimestr({time})              String  turn time value into a String remote_expr({server}{string} [, {idvar} [, {timeout}]])                                 String  send expression remote_foreground({server})     Number  bring Vim server to the foreground remote_peek({serverid} [, {retvar}])                                 Number  check for reply string remote_read({serverid} [, {timeout}])                                 String  read reply string remote_send({server}{string} [, {idvar}])                                 String  send key sequence remote_startserver({name})      none    become server {name} remove({list}{idx} [, {end}]) any/List                                         remove items {idx}-{end} from {list} remove({blob}{idx} [, {end}]) Number/Blob                                         remove bytes {idx}-{end} from {blob} remove({dict}{key})           any     remove entry {key} from {dict} rename({from}{to})            Number  rename (move) file from {from} to {to} repeat({expr}{count})         List/Blob/String                                         repeat {expr} {count} times resolve({filename})             String  get filename a shortcut points to reverse({obj})                  List/Blob/String                                         reverse {obj} round({expr})                   Float   round off {expr} rubyeval({expr})                any     evaluate Ruby expression screenattr({row}{col})        Number  attribute at screen position screenchar({row}{col})        Number  character at screen position screenchars({row}{col})       List    List of characters at screen position screencol()                     Number  current cursor column screenpos({winid}{lnum}{col}) Dict  screen row and col of a text character screenrow()                     Number  current cursor row screenstring({row}{col})      String  characters at screen position search({pattern} [, {flags} [, {stopline} [, {timeout} [, {skip}]]]])                                 Number  search for {pattern} searchcount([{options}])        Dict    get or update search stats searchdecl({name} [, {global} [, {thisblock}]])                                 Number  search for variable declaration searchpair({start}{middle}{end} [, {flags} [, {skip} [...]]])                                 Number  search for other end of start/end pair searchpairpos({start}{middle}{end} [, {flags} [, {skip} [...]]])                                 List    search for other end of start/end pair searchpos({pattern} [, {flags} [, {stopline} [, {timeout} [, {skip}]]]])                                 List    search for {pattern} server2client({clientid}{string})                                 Number  send reply string serverlist()                    String  get a list of available servers setbufline({expr}{lnum}{text})                                 Number  set line {lnum} to {text} in buffer                                         {expr} setbufvar({buf}{varname}{val})                                 none    set {varname} in buffer {buf} to {val} setcellwidths({list})           none    set character cell width overrides setcharpos({expr}{list})      Number  set the {expr} position to {list} setcharsearch({dict})           Dict    set character search from {dict} setcmdline({str} [, {pos}])     Number  set command-line setcmdpos({pos})                Number  set cursor position in command-line setcursorcharpos({list})        Number  move cursor to position in {list} setenv({name}{val})           none    set environment variable setfperm({fname}{mode})       Number  set {fname} file permissions to {mode} setline({lnum}{line})         Number  set line {lnum} to {line} setloclist({nr}{list} [, {action}])                                 Number  modify location list using {list} setloclist({nr}{list}{action}{what})                                 Number  modify specific location list props setmatches({list} [, {win}])    Number  restore a list of matches setpos({expr}{list})          Number  set the {expr} position to {list} setqflist({list} [, {action}])  Number  modify quickfix list using {list} setqflist({list}{action}{what})                                 Number  modify specific quickfix list props setreg({n}{v} [, {opt}])      Number  set register to value and type settabvar({nr}{varname}{val}) none  set {varname} in tab page {nr} to {val} settabwinvar({tabnr}{winnr}{varname}{val})                                 none    set {varname} in window {winnr} in tab                                         page {tabnr} to {val} settagstack({nr}{dict} [, {action}])                                 Number  modify tag stack using {dict} setwinvar({nr}{varname}{val}) none  set {varname} in window {nr} to {val} sha256({string})                String  SHA256 checksum of {string} shellescape({string} [, {special}])                                 String  escape {string} for use as shell                                         command argument shiftwidth([{col}])             Number  effective value of 'shiftwidth' sign_define({name} [, {dict}])  Number  define or update a sign sign_define({list})             List    define or update a list of signs sign_getdefined([{name}])       List    get a list of defined signs sign_getplaced([{buf} [, {dict}]])                                 List    get a list of placed signs sign_jump({id}{group}{buf})                                 Number  jump to a sign sign_place({id}{group}{name}{buf} [, {dict}])                                 Number  place a sign sign_placelist({list})          List    place a list of signs sign_undefine([{name}])         Number  undefine a sign sign_undefine({list})           List    undefine a list of signs sign_unplace({group} [, {dict}])                                 Number  unplace a sign sign_unplacelist({list})        List    unplace a list of signs simplify({filename})            String  simplify filename as much as possible sin({expr})                     Float   sine of {expr} sinh({expr})                    Float   hyperbolic sine of {expr} slice({expr}{start} [, {end}])  String, List or Blob                                         slice of a String, List or Blob sort({list} [, {how} [, {dict}]])                                 List    sort {list}, compare with {how} sound_clear()                   none    stop playing all sounds sound_playevent({name} [, {callback}])                                 Number  play an event sound sound_playfile({path} [, {callback}])                                 Number  play sound file {path} sound_stop({id})                none    stop playing sound {id} soundfold({word})               String  sound-fold {word} spellbadword()                  String  badly spelled word at cursor spellsuggest({word} [, {max} [, {capital}]])                                 List    spelling suggestions split({expr} [, {pat} [, {keepempty}]])                                 List    make List from {pat} separated {expr} sqrt({expr})                    Float   square root of {expr} srand([{expr}])                 List    get seed for rand() state([{what}])                 String  current state of Vim str2float({expr} [, {quoted}])  Float   convert String to Float str2list({expr} [, {utf8}])     List    convert each character of {expr} to                                         ASCII/UTF-8 value str2nr({expr} [, {base} [, {quoted}]])                                 Number  convert String to Number strcharlen({expr})              Number  character length of the String {expr} strcharpart({str}{start} [, {len} [, {skipcc}]])                                 String  {len} characters of {str} at                                         character {start} strchars({expr} [, {skipcc}])   Number  character count of the String {expr} strdisplaywidth({expr} [, {col}]) Number display length of the String {expr} strftime({format} [, {time}])   String  format time with a specified format strgetchar({str}{index})      Number  get char {index} from {str} stridx({haystack}{needle} [, {start}])                                 Number  index of {needle} in {haystack} string({expr})                  String  String representation of {expr} value strlen({expr})                  Number  length of the String {expr} strpart({str}{start} [, {len} [, {chars}]])                                 String  {len} bytes/chars of {str} at                                         byte {start} strptime({format}{timestring})                                 Number  Convert {timestring} to unix timestamp strridx({haystack}{needle} [, {start}])                                 Number  last index of {needle} in {haystack} strtrans({expr})                String  translate string to make it printable strutf16len({string} [, {countcc}])                                 Number  number of UTF-16 code units in {string} strwidth({expr})                Number  display cell length of the String {expr} submatch({nr} [, {list}])       String or List                                         specific match in ":s" or substitute() substitute({expr}{pat}{sub}{flags})                                 String  all {pat} in {expr} replaced with {sub} swapfilelist()                  List    swap files found in 'directory' swapinfo({fname})               Dict    information about swap file {fname} swapname({buf})                 String  swap file of buffer {buf} synID({lnum}{col}{trans})   Number  syntax ID at {lnum} and {col} synIDattr({synID}{what} [, {mode}])                                 String  attribute {what} of syntax ID {synID} synIDtrans({synID})             Number  translated syntax ID of {synID} synconcealed({lnum}{col})     List    info about concealing synstack({lnum}{col})         List    stack of syntax IDs at {lnum} and {col} system({expr} [, {input}])      String  output of shell command/filter {expr} systemlist({expr} [, {input}])  List    output of shell command/filter {expr} tabpagebuflist([{arg}])         List    list of buffer numbers in tab page tabpagenr([{arg}])              Number  number of current or last tab page tabpagewinnr({tabarg} [, {arg}]) Number number of current window in tab page tagfiles()                      List    tags files used taglist({expr} [, {filename}])  List    list of tags matching {expr} tan({expr})                     Float   tangent of {expr} tanh({expr})                    Float   hyperbolic tangent of {expr} tempname()                      String  name for a temporary file term_dumpdiff({filename}{filename} [, {options}])                                 Number  display difference between two dumps term_dumpload({filename} [, {options}])                                 Number  displaying a screen dump term_dumpwrite({buf}{filename} [, {options}])                                 none    dump terminal window contents term_getaltscreen({buf})        Number  get the alternate screen flag term_getansicolors({buf})       List    get ANSI palette in GUI color mode term_getattr({attr}{what})    Number  get the value of attribute {what} term_getcursor({buf})           List    get the cursor position of a terminal term_getjob({buf})              Job     get the job associated with a terminal term_getline({buf}{row})      String  get a line of text from a terminal term_getscrolled({buf})         Number  get the scroll count of a terminal term_getsize({buf})             List    get the size of a terminal term_getstatus({buf})           String  get the status of a terminal term_gettitle({buf})            String  get the title of a terminal term_gettty({buf}, [{input}])   String  get the tty name of a terminal term_list()                     List    get the list of terminal buffers term_scrape({buf}{row})       List    get row of a terminal screen term_sendkeys({buf}{keys})    none    send keystrokes to a terminal term_setansicolors({buf}{colors})                                 none    set ANSI palette in GUI color mode term_setapi({buf}{expr})      none    set terminal-api function name prefix term_setkill({buf}{how})      none    set signal to stop job in terminal term_setrestore({buf}{command}) none  set command to restore terminal term_setsize({buf}{rows}{cols})                                 none    set the size of a terminal term_start({cmd} [, {options}]) Number  open a terminal window and run a job term_wait({buf} [, {time}])     Number  wait for screen to be updated terminalprops()                 Dict    properties of the terminal test_alloc_fail({id}{countdown}{repeat})                                 none    make memory allocation fail test_autochdir()                none    enable 'autochdir' during startup test_feedinput({string})        none    add key sequence to input buffer test_garbagecollect_now()       none    free memory right now for testing test_garbagecollect_soon()      none    free memory soon for testing test_getvalue({string})         any     get value of an internal variable test_gui_event({event}{args}) bool    generate a GUI event for testing test_ignore_error({expr})       none    ignore a specific error test_mswin_event({event}{args})                                 bool    generate MS-Windows event for testing test_null_blob()                Blob    null value for testing test_null_channel()             Channel null value for testing test_null_dict()                Dict    null value for testing test_null_function()            Funcref null value for testing test_null_job()                 Job     null value for testing test_null_list()                List    null value for testing test_null_partial()             Funcref null value for testing test_null_string()              String  null value for testing test_option_not_set({name})     none    reset flag indicating option was set test_override({expr}{val})    none    test with Vim internal overrides test_refcount({expr})           Number  get the reference count of {expr} test_setmouse({row}{col})     none    set the mouse position for testing test_settime({expr})            none    set current time for testing test_srand_seed([seed])         none    set seed for testing srand() test_unknown()                  any     unknown value for testing test_void()                     any     void value for testing timer_info([{id}])              List    information about timers timer_pause({id}{pause})      none    pause or unpause a timer timer_start({time}{callback} [, {options}])                                 Number  create a timer timer_stop({timer})             none    stop a timer timer_stopall()                 none    stop all timers tolower({expr})                 String  the String {expr} switched to lowercase toupper({expr})                 String  the String {expr} switched to uppercase tr({src}{fromstr}{tostr})   String  translate chars of {src} in {fromstr}                                         to chars in {tostr} trim({text} [, {mask} [, {dir}]])                                 String  trim characters in {mask} from {text} trunc({expr})                   Float   truncate Float {expr} type({expr})                    Number  type of value {expr} typename({expr})                String  representation of the type of {expr} undofile({name})                String  undo file name for {name} undotree([{buf}])               List    undo file tree for buffer {buf} uniq({list} [, {func} [, {dict}]])                                 List    remove adjacent duplicates from a list utf16idx({string}{idx} [, {countcc} [, {charidx}]])                                 Number  UTF-16 index of byte {idx} in {string} values({dict})                  List    values in {dict} virtcol({expr} [, {list} [, {winid}])                                 Number or List                                         screen column of cursor or mark virtcol2col({winid}{lnum}{col})                                 Number  byte index of a character on screen visualmode([expr])              String  last visual mode used wildmenumode()                  Number  whether 'wildmenu' mode is active win_execute({id}{command} [, {silent}])                                 String  execute {command} in window {id} win_findbuf({bufnr})            List    find windows containing {bufnr} win_getid([{win} [, {tab}]])    Number  get window ID for {win} in {tab} win_gettype([{nr}])             String  type of window {nr} win_gotoid({expr})              Number  go to window with ID {expr} win_id2tabwin({expr})           List    get tab and window nr from window ID win_id2win({expr})              Number  get window nr from window ID win_move_separator({nr})        Number  move window vertical separator win_move_statusline({nr})       Number  move window status line win_screenpos({nr})             List    get screen position of window {nr} win_splitmove({nr}{target} [, {options}])                                 Number  move window {nr} to split of {target} winbufnr({nr})                  Number  buffer number of window {nr} wincol()                        Number  window column of the cursor windowsversion()                String  MS-Windows OS version winheight({nr})                 Number  height of window {nr} winlayout([{tabnr}])            List    layout of windows in tab {tabnr} winline()                       Number  window line of the cursor winnr([{expr}])                 Number  number of current window winrestcmd()                    String  returns command to restore window sizes winrestview({dict})             none    restore view of current window winsaveview()                   Dict    save view of current window winwidth({nr})                  Number  width of window {nr} wordcount()                     Dict    get byte/char/word statistics writefile({object}{fname} [, {flags}])                                 Number  write Blob or List of lines to file xor({expr}{expr})             Number  bitwise XOR ============================================================================== 2. Details                                      builtin-function-details Not all functions are here, some have been moved to a help file covering the specific functionality. abs({expr})                                                     abs()                 Return the absolute value of {expr}.  When {expr} evaluates to                 a Float abs() returns a Float.  When {expr} can be                 converted to a Number abs() returns a Number.  Otherwise                 abs() gives an error message and returns -1.                 Examples:                         echo abs(1.456)                         1.456                          echo abs(-5.456)                         5.456                          echo abs(-4)                         4                 Can also be used as a method:                         Compute()->abs() acos({expr})                                                    acos()                 Return the arc cosine of {expr} measured in radians, as a                 Float in the range of [0, pi].                 {expr} must evaluate to a Float or a Number in the range                 [-1, 1].  Otherwise acos() returns "nan".                 Examples:                         :echo acos(0)                         1.570796                         :echo acos(-0.5)                         2.094395                 Can also be used as a method:                         Compute()->acos() add({object}{expr})                                   add()                 Append the item {expr} to List or Blob {object}.  Returns                 the resulting List or Blob.  Examples:                         :let alist = add([1, 2, 3], item)                         :call add(mylist, "woodstock")                 Note that when {expr} is a List it is appended as a single                 item.  Use extend() to concatenate Lists.                 When {object} is a Blob then  {expr} must be a number.                 Use insert() to add an item at another position.                 Returns 1 if {object} is not a List or a Blob.                 Can also be used as a method:                         mylist->add(val1)->add(val2) and({expr}{expr})                                     and()                 Bitwise AND on the two arguments.  The arguments are converted                 to a number.  A List, Dict or Float argument causes an error.                 Also see or() and xor().                 Example:                         :let flag = and(bits, 0x80)                 Can also be used as a method:                         :let flag = bits->and(0x80) append({lnum}{text})                                  append()                 When {text} is a List: Append each item of the List as a                 text line below line {lnum} in the current buffer.                 Otherwise append {text} as one text line below line {lnum} in                 the current buffer.                 Any type of item is accepted and converted to a String.                 {lnum} can be zero to insert a line before the first one.                 {lnum} is used like with getline().                 Returns 1 for failure ({lnum} out of range or out of memory),                 0 for success.  When {text} is an empty list zero is returned,                 no matter the value of {lnum}.                 In Vim9 script an invalid argument or negative number                 results in an error.  Example:                         :let failed = append(line('$'), "# THE END")                         :let failed = append(0, ["Chapter 1", "the beginning"])                 Can also be used as a method after a List, the base is                 passed as the second argument:                         mylist->append(lnum) appendbufline({buf}{lnum}{text})                    appendbufline()                 Like append() but append the text in buffer {buf}.                 This function works only for loaded buffers. First call                 bufload() if needed.                 For the use of {buf}, see bufname().                 {lnum} is the line number to append below.  Note that using                 line() would use the current buffer, not the one appending                 to.  Use "$" to append at the end of the buffer.  Other string                 values are not supported.                 On success 0 is returned, on failure 1 is returned.                 In Vim9 script an error is given for an invalid {lnum}.                 If {buf} is not a valid buffer or {lnum} is not valid, an                 error message is given. Example:                         :let failed = appendbufline(13, 0, "# THE START")                 However, when {text} is an empty list then no error is given                 for an invalid {lnum}, since {lnum} isn't actually used.                 Can also be used as a method after a List, the base is                 passed as the second argument:                         mylist->appendbufline(buf, lnum) argc([{winid}])                                 argc()                 The result is the number of files in the argument list.  See                 arglist.                 If {winid} is not supplied, the argument list of the current                 window is used.                 If {winid} is -1, the global argument list is used.                 Otherwise {winid} specifies the window of which the argument                 list is used: either the window number or the window ID.                 Returns -1 if the {winid} argument is invalid.                                                         argidx() argidx()        The result is the current index in the argument list.  0 is                 the first file.  argc() - 1 is the last one.  See arglist.                                                         arglistid() arglistid([{winnr} [, {tabnr}]])                 Return the argument list ID.  This is a number which                 identifies the argument list being used.  Zero is used for the                 global argument list.  See arglist.                 Returns -1 if the arguments are invalid.                 Without arguments use the current window.                 With {winnr} only use this window in the current tab page.                 With {winnr} and {tabnr} use the window in the specified tab                 page.                 {winnr} can be the window number or the window-ID.                                                         argv() argv([{nr} [, {winid}]])                 The result is the {nr}th file in the argument list.  See                 arglist.  "argv(0)" is the first one.  Example:         :let i = 0         :while i < argc()         :  let f = escape(fnameescape(argv(i)), '.')         :  exe 'amenu Arg.' .. f .. ' :e ' .. f .. '<CR>'         :  let i = i + 1         :endwhile                 Without the {nr} argument, or when {nr} is -1, a List with                 the whole arglist is returned.                 The {winid} argument specifies the window ID, see argc().                 For the Vim command line arguments see v:argv.                 Returns an empty string if {nr}th argument is not present in                 the argument list.  Returns an empty List if the {winid}                 argument is invalid. asin({expr})                                            asin()                 Return the arc sine of {expr} measured in radians, as a Float                 in the range of [-pi/2, pi/2].                 {expr} must evaluate to a Float or a Number in the range                 [-1, 1].                 Returns "nan" if {expr} is outside the range [-1, 1].  Returns                 0.0 if {expr} is not a Float or a Number.                 Examples:                         :echo asin(0.8)                         0.927295                         :echo asin(-0.5)                         -0.523599                 Can also be used as a method:                         Compute()->asin() assert_ functions are documented here: assert-functions-details atan({expr})                                            atan()                 Return the principal value of the arc tangent of {expr}, in                 the range [-pi/2, +pi/2] radians, as a Float.                 {expr} must evaluate to a Float or a Number.                 Returns 0.0 if {expr} is not a Float or a Number.                 Examples:                         :echo atan(100)                         1.560797                         :echo atan(-4.01)                         -1.326405                 Can also be used as a method:                         Compute()->atan() atan2({expr1}{expr2})                                 atan2()                 Return the arc tangent of {expr1} / {expr2}, measured in                 radians, as a Float in the range [-pi, pi].                 {expr1} and {expr2} must evaluate to a Float or a Number.                 Returns 0.0 if {expr1} or {expr2} is not a Float or a                 Number.                 Examples:                         :echo atan2(-1, 1)                         -0.785398                         :echo atan2(1, -1)                         2.356194                 Can also be used as a method:                         Compute()->atan2(1) autocmd_add({acmds})                                    autocmd_add()                 Adds a List of autocmds and autocmd groups.                 The {acmds} argument is a List where each item is a Dict with                 the following optional items:                     bufnr       buffer number to add a buffer-local autocmd.                                 If this item is specified, then the "pattern"                                 item is ignored.                     cmd         Ex command to execute for this autocmd event                     event       autocmd event name. Refer to autocmd-events.                                 This can be either a String with a single                                 event name or a List of event names.                     group       autocmd group name. Refer to autocmd-groups.                                 If this group doesn't exist then it is                                 created.  If not specified or empty, then the                                 default group is used.                     nested      boolean flag, set to v:true to add a nested                                 autocmd.  Refer to autocmd-nested.                     once        boolean flag, set to v:true to add an autocmd                                 which executes only once. Refer to                                 autocmd-once.                     pattern     autocmd pattern string. Refer to                                 autocmd-patterns.  If "bufnr" item is                                 present, then this item is ignored.  This can                                 be a String with a single pattern or a List of                                 patterns.                     replace     boolean flag, set to v:true to remove all the                                 commands associated with the specified autocmd                                 event and group and add the {cmd}.  This is                                 useful to avoid adding the same command                                 multiple times for an autocmd event in a group.                 Returns v:true on success and v:false on failure.                 Examples:                         " Create a buffer-local autocmd for buffer 5                         let acmd = {}                         let acmd.group = 'MyGroup'                         let acmd.event = 'BufEnter'                         let acmd.bufnr = 5                         let acmd.cmd = 'call BufEnterFunc()'                         call autocmd_add([acmd])                 Can also be used as a method:                         GetAutocmdList()->autocmd_add() autocmd_delete({acmds})                                 autocmd_delete()                 Deletes a List of autocmds and autocmd groups.                 The {acmds} argument is a List where each item is a Dict with                 the following optional items:                     bufnr       buffer number to delete a buffer-local autocmd.                                 If this item is specified, then the "pattern"                                 item is ignored.                     cmd         Ex command for this autocmd event                     event       autocmd event name. Refer to autocmd-events.                                 If '*' then all the autocmd events in this                                 group are deleted.                     group       autocmd group name. Refer to autocmd-groups.                                 If not specified or empty, then the default                                 group is used.                     nested      set to v:true for a nested autocmd.                                 Refer to autocmd-nested.                     once        set to v:true for an autocmd which executes                                 only once. Refer to autocmd-once.                     pattern     autocmd pattern string. Refer to                                 autocmd-patterns.  If "bufnr" item is                                 present, then this item is ignored.                 If only {group} is specified in a {acmds} entry and {event},                 {pattern} and {cmd} are not specified, then that autocmd group                 is deleted.                 Returns v:true on success and v:false on failure.                 Examples:                         " :autocmd! BufLeave *.vim                         let acmd = #{event: 'BufLeave', pattern: '*.vim'}                         call autocmd_delete([acmd]})                         " :autocmd! MyGroup1 BufLeave                         let acmd = #{group: 'MyGroup1', event: 'BufLeave'}                         call autocmd_delete([acmd])                         " :autocmd! MyGroup2 BufEnter *.c                         let acmd = #{group: 'MyGroup2', event: 'BufEnter',                                                         \ pattern: '*.c'}                         " :autocmd! MyGroup2 * *.c                         let acmd = #{group: 'MyGroup2', event: '*',                                                         \ pattern: '*.c'}                         call autocmd_delete([acmd])                         " :autocmd! MyGroup3                         let acmd = #{group: 'MyGroup3'}                         call autocmd_delete([acmd])                 Can also be used as a method:                         GetAutocmdList()->autocmd_delete() autocmd_get([{opts}])                                   autocmd_get()                 Returns a List of autocmds. If {opts} is not supplied, then                 returns the autocmds for all the events in all the groups.                 The optional {opts} Dict argument supports the following                 items:                     group       Autocmd group name. If specified, returns only                                 the autocmds defined in this group. If the                                 specified group doesn't exist, results in an                                 error message.  If set to an empty string,                                 then the default autocmd group is used.                     event       Autocmd event name. If specified, returns only                                 the autocmds defined for this event.  If set                                 to "*", then returns autocmds for all the                                 events.  If the specified event doesn't exist,                                 results in an error message.                     pattern     Autocmd pattern. If specified, returns only                                 the autocmds defined for this pattern.                 A combination of the above three times can be supplied in                 {opts}.                 Each Dict in the returned List contains the following items:                     bufnr       For buffer-local autocmds, buffer number where                                 the autocmd is defined.                     cmd         Command executed for this autocmd.                     event       Autocmd event name.                     group       Autocmd group name.                     nested      Boolean flag, set to v:true for a nested                                 autocmd. See autocmd-nested.                     once        Boolean flag, set to v:true, if the autocmd                                 will be executed only once. See autocmd-once.                     pattern     Autocmd pattern.  For a buffer-local                                 autocmd, this will be of the form "<buffer=n>".                 If there are multiple commands for an autocmd event in a                 group, then separate items are returned for each command.                 Returns an empty List if an autocmd with the specified group                 or event or pattern is not found.                 Examples:                         " :autocmd MyGroup                         echo autocmd_get(#{group: 'Mygroup'})                         " :autocmd G BufUnload                         echo autocmd_get(#{group: 'G', event: 'BufUnload'})                         " :autocmd G * *.ts                         let acmd = #{group: 'G', event: '*', pattern: '*.ts'}                         echo autocmd_get(acmd)                         " :autocmd Syntax                         echo autocmd_get(#{event: 'Syntax'})                         " :autocmd G BufEnter *.ts                         let acmd = #{group: 'G', event: 'BufEnter',                                                         \ pattern: '*.ts'}                         echo autocmd_get(acmd)                 Can also be used as a method:                         Getopts()->autocmd_get() balloon_gettext()                                       balloon_gettext()                 Return the current text in the balloon.  Only for the string,                 not used for the List.  Returns an empty string if balloon                 is not present. balloon_show({expr})                                    balloon_show()                 Show {expr} inside the balloon.  For the GUI {expr} is used as                 a string.  For a terminal {expr} can be a list, which contains                 the lines of the balloon.  If {expr} is not a list it will be                 split with balloon_split().                 If {expr} is an empty string any existing balloon is removed.                 Example:                         func GetBalloonContent()                            " ... initiate getting the content                            return ''                         endfunc                         set balloonexpr=GetBalloonContent()                         func BalloonCallback(result)                           call balloon_show(a:result)                         endfunc                 Can also be used as a method:                         GetText()->balloon_show()                 The intended use is that fetching the content of the balloon                 is initiated from 'balloonexpr'.  It will invoke an                 asynchronous method, in which a callback invokes                 balloon_show().  The 'balloonexpr' itself can return an                 empty string or a placeholder, e.g. "loading...".                 When showing a balloon is not possible then nothing happens,                 no error message is given.                 {only available when compiled with the +balloon_eval or                 +balloon_eval_term feature} balloon_split({msg})                                    balloon_split()                 Split String {msg} into lines to be displayed in a balloon.                 The splits are made for the current window size and optimize                 to show debugger output.                 Returns a List with the split lines.  Returns an empty List                 on error.                 Can also be used as a method:                         GetText()->balloon_split()->balloon_show()                 {only available when compiled with the +balloon_eval_term                 feature} blob2list({blob})                                       blob2list()                 Return a List containing the number value of each byte in Blob                 {blob}.  Examples:                         blob2list(0z0102.0304)  returns [1, 2, 3, 4]                         blob2list(0z)           returns []                 Returns an empty List on error.  list2blob() does the                 opposite.                 Can also be used as a method:                         GetBlob()->blob2list()                                                         browse() browse({save}{title}{initdir}{default})                 Put up a file requester.  This only works when "has("browse")"                 returns TRUE (only in some GUI versions).                 The input fields are:                     {save}      when TRUE, select file to write                     {title}     title for the requester                     {initdir}   directory to start browsing in                     {default}   default file name                 An empty string is returned when the "Cancel" button is hit,                 something went wrong, or browsing is not possible.                                                         browsedir() browsedir({title}{initdir})                 Put up a directory requester.  This only works when                 "has("browse")" returns TRUE (only in some GUI versions).                 On systems where a directory browser is not supported a file                 browser is used.  In that case: select a file in the directory                 to be used.                 The input fields are:                     {title}     title for the requester                     {initdir}   directory to start browsing in                 When the "Cancel" button is hit, something went wrong, or                 browsing is not possible, an empty string is returned. bufadd({name})                                          bufadd()                 Add a buffer to the buffer list with name {name} (must be a                 String).                 If a buffer for file {name} already exists, return that buffer                 number.  Otherwise return the buffer number of the newly                 created buffer.  When {name} is an empty string then a new                 buffer is always created.                 The buffer will not have 'buflisted' set and not be loaded                 yet.  To add some text to the buffer use this:                         let bufnr = bufadd('someName')                         call bufload(bufnr)                         call setbufline(bufnr, 1, ['some', 'text'])                 Returns 0 on error.                 Can also be used as a method:                         let bufnr = 'somename'->bufadd() bufexists({buf})                                        bufexists()                 The result is a Number, which is TRUE if a buffer called                 {buf} exists.                 If the {buf} argument is a number, buffer numbers are used.                 Number zero is the alternate buffer for the current window.                 If the {buf} argument is a string it must match a buffer name                 exactly.  The name can be:                 - Relative to the current directory.                 - A full path.                 - The name of a buffer with 'buftype' set to "nofile".                 - A URL name.                 Unlisted buffers will be found.                 Note that help files are listed by their short name in the                 output of :buffers, but bufexists() requires using their                 long name to be able to find them.                 bufexists() may report a buffer exists, but to use the name                 with a :buffer command you may need to use expand().  Esp                 for MS-Windows 8.3 names in the form "c:\DOCUME~1"                 Use "bufexists(0)" to test for the existence of an alternate                 file name.                 Can also be used as a method:                         let exists = 'somename'->bufexists()                 Obsolete name: buffer_exists().         buffer_exists() buflisted({buf})                                        buflisted()                 The result is a Number, which is TRUE if a buffer called                 {buf} exists and is listed (has the 'buflisted' option set).                 The {buf} argument is used like with bufexists().                 Can also be used as a method:                         let listed = 'somename'->buflisted() bufload({buf})                                          bufload()                 Ensure the buffer {buf} is loaded.  When the buffer name                 refers to an existing file then the file is read.  Otherwise                 the buffer will be empty.  If the buffer was already loaded                 then there is no change.  If the buffer is not related to a                 file then no file is read (e.g., when 'buftype' is "nofile").                 If there is an existing swap file for the file of the buffer,                 there will be no dialog, the buffer will be loaded anyway.                 The {buf} argument is used like with bufexists().                 Can also be used as a method:                         eval 'somename'->bufload() bufloaded({buf})                                        bufloaded()                 The result is a Number, which is TRUE if a buffer called                 {buf} exists and is loaded (shown in a window or hidden).                 The {buf} argument is used like with bufexists().                 Can also be used as a method:                         let loaded = 'somename'->bufloaded() bufname([{buf}])                                        bufname()                 The result is the name of a buffer.  Mostly as it is displayed                 by the :ls command, but not using special names such as                 "[No Name]".                 If {buf} is omitted the current buffer is used.                 If {buf} is a Number, that buffer number's name is given.                 Number zero is the alternate buffer for the current window.                 If {buf} is a String, it is used as a file-pattern to match                 with the buffer names.  This is always done like 'magic' is                 set and 'cpoptions' is empty.  When there is more than one                 match an empty string is returned.                 "" or "%" can be used for the current buffer, "#" for the                 alternate buffer.                 A full match is preferred, otherwise a match at the start, end                 or middle of the buffer name is accepted.  If you only want a                 full match then put "^" at the start and "$" at the end of the                 pattern.                 Listed buffers are found first.  If there is a single match                 with a listed buffer, that one is returned.  Next unlisted                 buffers are searched for.                 If the {buf} is a String, but you want to use it as a buffer                 number, force it to be a Number by adding zero to it:                         :echo bufname("3" + 0)                 Can also be used as a method:                         echo bufnr->bufname()                 If the buffer doesn't exist, or doesn't have a name, an empty                 string is returned.         bufname("#")            alternate buffer name         bufname(3)              name of buffer 3         bufname("%")            name of current buffer         bufname("file2")        name of buffer where "file2" matches.                                                         buffer_name()                 Obsolete name: buffer_name().                                                         bufnr() bufnr([{buf} [, {create}]])                 The result is the number of a buffer, as it is displayed by                 the :ls command.  For the use of {buf}, see bufname()                 above.                 If the buffer doesn't exist, -1 is returned.  Or, if the                 {create} argument is present and TRUE, a new, unlisted,                 buffer is created and its number is returned.  Example:                         let newbuf = bufnr('Scratch001', 1)                 Using an empty name uses the current buffer. To create a new                 buffer with an empty name use bufadd().                 bufnr("$") is the last buffer:                         :let last_buffer = bufnr("$")                 The result is a Number, which is the highest buffer number                 of existing buffers.  Note that not all buffers with a smaller                 number necessarily exist, because ":bwipeout" may have removed                 them.  Use bufexists() to test for the existence of a buffer.                 Can also be used as a method:                         echo bufref->bufnr()                 Obsolete name: buffer_number().         buffer_number()                                                         last_buffer_nr()                 Obsolete name for bufnr("$"): last_buffer_nr(). bufwinid({buf})                                         bufwinid()                 The result is a Number, which is the window-ID of the first                 window associated with buffer {buf}.  For the use of {buf},                 see bufname() above.  If buffer {buf} doesn't exist or                 there is no such window, -1 is returned.  Example:         echo "A window containing buffer 1 is " .. (bufwinid(1))                 Only deals with the current tab page.  See win_findbuf() for                 finding more.                 Can also be used as a method:                         FindBuffer()->bufwinid() bufwinnr({buf})                                         bufwinnr()                 Like bufwinid() but return the window number instead of the                 window-ID.                 If buffer {buf} doesn't exist or there is no such window, -1                 is returned.  Example:         echo "A window containing buffer 1 is " .. (bufwinnr(1))                 The number can be used with CTRL-W_w and ":wincmd w"                 :wincmd.                 Can also be used as a method:                         FindBuffer()->bufwinnr() byte2line({byte})                                       byte2line()                 Return the line number that contains the character at byte                 count {byte} in the current buffer.  This includes the                 end-of-line character, depending on the 'fileformat' option                 for the current buffer.  The first character has byte count                 one.                 Also see line2byte()go and :goto.                 Returns -1 if the {byte} value is invalid.                 Can also be used as a method:                         GetOffset()->byte2line()                 {not available when compiled without the +byte_offset                 feature} byteidx({expr}{nr} [, {utf16}])                       byteidx()                 Return byte index of the {nr}'th character in the String                 {expr}.  Use zero for the first character, it then returns                 zero.                 If there are no multibyte characters the returned value is                 equal to {nr}.                 Composing characters are not counted separately, their byte                 length is added to the preceding base character.  See                 byteidxcomp() below for counting composing characters                 separately.                 When {utf16} is present and TRUE, {nr} is used as the UTF-16                 index in the String {expr} instead of as the character index.                 The UTF-16 index is the index in the string when it is encoded                 with 16-bit words.  If the specified UTF-16 index is in the                 middle of a character (e.g. in a 4-byte character), then the                 byte index of the first byte in the character is returned.                 Refer to string-offset-encoding for more information.                 Example :                         echo matchstr(str, ".", byteidx(str, 3))                 will display the fourth character.  Another way to do the                 same:                         let s = strpart(str, byteidx(str, 3))                         echo strpart(s, 0, byteidx(s, 1))                 Also see strgetchar() and strcharpart().                 If there are less than {nr} characters -1 is returned.                 If there are exactly {nr} characters the length of the string                 in bytes is returned.                 See charidx() and utf16idx() for getting the character and                 UTF-16 index respectively from the byte index.                 Examples:                         echo byteidx('a😊😊', 2)        returns 5                         echo byteidx('a😊😊', 2, 1)     returns 1                         echo byteidx('a😊😊', 3, 1)     returns 5                 Can also be used as a method:                         GetName()->byteidx(idx) byteidxcomp({expr}{nr} [, {utf16}])                   byteidxcomp()                 Like byteidx(), except that a composing character is counted                 as a separate character.  Example:                         let s = 'e' .. nr2char(0x301)                         echo byteidx(s, 1)                         echo byteidxcomp(s, 1)                         echo byteidxcomp(s, 2)                 The first and third echo result in 3 ('e' plus composing                 character is 3 bytes), the second echo results in 1 ('e' is                 one byte).                 Only works differently from byteidx() when 'encoding' is set                 to a Unicode encoding.                 Can also be used as a method:                         GetName()->byteidxcomp(idx) call({func}{arglist} [, {dict}])                      call() E699                 Call function {func} with the items in List {arglist} as                 arguments.                 {func} can either be a Funcref or the name of a function.                 a:firstline and a:lastline are set to the cursor line.                 Returns the return value of the called function.                 {dict} is for functions with the "dict" attribute.  It will be                 used to set the local variable "self". Dictionary-function                 Can also be used as a method:                         GetFunc()->call([arg, arg], dict) ceil({expr})                                                    ceil()                 Return the smallest integral value greater than or equal to                 {expr} as a Float (round up).                 {expr} must evaluate to a Float or a Number.                 Examples:                         echo ceil(1.456)                         2.0                          echo ceil(-5.456)                         -5.0                          echo ceil(4.0)                         4.0                 Returns 0.0 if {expr} is not a Float or a Number.                 Can also be used as a method:                         Compute()->ceil() ch_ functions are documented here: channel-functions-details changenr()                                              changenr()                 Return the number of the most recent change.  This is the same                 number as what is displayed with :undolist and can be used                 with the :undo command.                 When a change was made it is the number of that change.  After                 redo it is the number of the redone change.  After undo it is                 one less than the number of the undone change.                 Returns 0 if the undo list is empty. char2nr({string} [, {utf8}])                                    char2nr()                 Return Number value of the first char in {string}.                 Examples:                         char2nr(" ")            returns 32                         char2nr("ABC")          returns 65                 When {utf8} is omitted or zero, the current 'encoding' is used.                 Example for "utf-8":                         char2nr("á")            returns 225                         char2nr("á"[0])         returns 195                 When {utf8} is TRUE, always treat as UTF-8 characters.                 A combining character is a separate character.                 nr2char() does the opposite.                 To turn a string into a list of character numbers:                     let str = "ABC"                     let list = map(split(str, '\zs'), {_, val -> char2nr(val)})                 Result: [65, 66, 67]                 Returns 0 if {string} is not a String.                 Can also be used as a method:                         GetChar()->char2nr() charclass({string})                                     charclass()                 Return the character class of the first character in {string}.                 The character class is one of:                         0       blank                         1       punctuation                         2       word character                         3       emoji                         other   specific Unicode class                 The class is used in patterns and word motions.                 Returns 0 if {string} is not a String. charcol({expr} [, {winid}])                             charcol()                 Same as col() but returns the character index of the column                 position given with {expr} instead of the byte position.                 Example:                 With the cursor on '세' in line 5 with text "여보세요":                         charcol('.')            returns 3                         col('.')                returns 7                 Can also be used as a method:                         GetPos()->col()                                                         charidx() charidx({string}{idx} [, {countcc} [, {utf16}]])                 Return the character index of the byte at {idx} in {string}.                 The index of the first character is zero.                 If there are no multibyte characters the returned value is                 equal to {idx}.                 When {countcc} is omitted or FALSE, then composing characters                 are not counted separately, their byte length is added to the                 preceding base character.                 When {countcc} is TRUE, then composing characters are                 counted as separate characters.                 When {utf16} is present and TRUE, {idx} is used as the UTF-16                 index in the String {expr} instead of as the byte index.                 Returns -1 if the arguments are invalid or if there are less                 than {idx} bytes. If there are exactly {idx} bytes the length                 of the string in characters is returned.                 An error is given and -1 is returned if the first argument is                 not a string, the second argument is not a number or when the                 third argument is present and is not zero or one.                 See byteidx() and byteidxcomp() for getting the byte index                 from the character index and utf16idx() for getting the                 UTF-16 index from the character index.                 Refer to string-offset-encoding for more information.                 Examples:                         echo charidx('áb́ć', 3)          returns 1                         echo charidx('áb́ć', 6, 1)       returns 4                         echo charidx('áb́ć', 16)         returns -1                         echo charidx('a😊😊', 4, 0, 1)  returns 2                 Can also be used as a method:                         GetName()->charidx(idx) chdir({dir})                                            chdir()                 Change the current working directory to {dir}.  The scope of                 the directory change depends on the directory of the current                 window:                         - If the current window has a window-local directory                           (:lcd), then changes the window local directory.                         - Otherwise, if the current tabpage has a local                           directory (:tcd) then changes the tabpage local                           directory.                         - Otherwise, changes the global directory.                 {dir} must be a String.                 If successful, returns the previous working directory.  Pass                 this to another chdir() to restore the directory.                 On failure, returns an empty string.                 Example:                         let save_dir = chdir(newdir)                         if save_dir != ""                            " ... do some work                            call chdir(save_dir)                         endif                 Can also be used as a method:                         GetDir()->chdir() cindent({lnum})                                         cindent()                 Get the amount of indent for line {lnum} according the C                 indenting rules, as with 'cindent'.                 The indent is counted in spaces, the value of 'tabstop' is                 relevant.  {lnum} is used just like in getline().                 When {lnum} is invalid -1 is returned.                 See C-indenting.                 Can also be used as a method:                         GetLnum()->cindent() clearmatches([{win}])                                   clearmatches()                 Clears all matches previously defined for the current window                 by matchadd() and the :match commands.                 If {win} is specified, use the window with this number or                 window ID instead of the current window.                 Can also be used as a method:                         GetWin()->clearmatches() col({expr} [, {winid}])                                 col()                 The result is a Number, which is the byte index of the column                 position given with {expr}.  The accepted positions are:                     .       the cursor position                     $       the end of the cursor line (the result is the                             number of bytes in the cursor line plus one)                     'x      position of mark x (if the mark is not set, 0 is                             returned)                     v       In Visual mode: the start of the Visual area (the                             cursor is the end).  When not in Visual mode                             returns the cursor position.  Differs from '< in                             that it's updated right away.                 Additionally {expr} can be [lnum, col]: a List with the line                 and column number. Most useful when the column is "$", to get                 the last column of a specific line.  When "lnum" or "col" is                 out of range then col() returns zero.                 With the optional {winid} argument the values are obtained for                 that window instead of the current window.                 To get the line number use line().  To get both use                 getpos().                 For the screen column position use virtcol().  For the                 character position use charcol().                 Note that only marks in the current file can be used.                 Examples:                         col(".")                column of cursor                         col("$")                length of cursor line plus one                         col("'t")               column of mark t                         col("'" .. markname)    column of mark markname                 The first column is 1.  Returns 0 if {expr} is invalid or when                 the window with ID {winid} is not found.                 For an uppercase mark the column may actually be in another                 buffer.                 For the cursor position, when 'virtualedit' is active, the                 column is one higher if the cursor is after the end of the                 line.  Also, when using a <Cmd> mapping the cursor isn't                 moved, this can be used to obtain the column in Insert mode:                         :imap <F2> <Cmd>echowin col(".")<CR>                 Can also be used as a method:                         GetPos()->col() complete({startcol}{matches})                 complete() E785                 Set the matches for Insert mode completion.                 Can only be used in Insert mode.  You need to use a mapping                 with CTRL-R = (see i_CTRL-R).  It does not work after CTRL-O                 or with an expression mapping.                 {startcol} is the byte offset in the line where the completed                 text start.  The text up to the cursor is the original text                 that will be replaced by the matches.  Use col('.') for an                 empty string.  "col('.') - 1" will replace one character by a                 match.                 {matches} must be a List.  Each List item is one match.                 See complete-items for the kind of items that are possible.                 "longest" in 'completeopt' is ignored.                 Note that the after calling this function you need to avoid                 inserting anything that would cause completion to stop.                 The match can be selected with CTRL-N and CTRL-P as usual with                 Insert mode completion.  The popup menu will appear if                 specified, see ins-completion-menu.                 Example:         inoremap <F5> <C-R>=ListMonths()<CR>         func ListMonths()           call complete(col('.'), ['January', 'February', 'March',                 \ 'April', 'May', 'June', 'July', 'August', 'September',                 \ 'October', 'November', 'December'])           return ''         endfunc                 This isn't very useful, but it shows how it works.  Note that                 an empty string is returned to avoid a zero being inserted.                 Can also be used as a method, the base is passed as the                 second argument:                         GetMatches()->complete(col('.')) complete_add({expr})                            complete_add()                 Add {expr} to the list of matches.  Only to be used by the                 function specified with the 'completefunc' option.                 Returns 0 for failure (empty string or out of memory),                 1 when the match was added, 2 when the match was already in                 the list.                 See complete-functions for an explanation of {expr}.  It is                 the same as one item in the list that 'omnifunc' would return.                 Can also be used as a method:                         GetMoreMatches()->complete_add() complete_check()                                complete_check()                 Check for a key typed while looking for completion matches.                 This is to be used when looking for matches takes some time.                 Returns TRUE when searching for matches is to be aborted,                 zero otherwise.                 Only to be used by the function specified with the                 'completefunc' option. complete_info([{what}])                         complete_info()                 Returns a Dictionary with information about Insert mode                 completion.  See ins-completion.                 The items are:                    mode         Current completion mode name string.                                 See complete_info_mode for the values.                    pum_visible  TRUE if popup menu is visible.                                 See pumvisible().                    items        List of completion matches.  Each item is a                                 dictionary containing the entries "word",                                 "abbr", "menu", "kind", "info" and "user_data".                                 See complete-items.                    selected     Selected item index.  First index is zero.                                 Index is -1 if no item is selected (showing                                 typed text only, or the last completion after                                 no item is selected when using the <Up> or                                 <Down> keys)                    inserted     Inserted string. [NOT IMPLEMENTED YET]                                                         complete_info_mode                 mode values are:                    ""                Not in completion mode                    "keyword"         Keyword completion i_CTRL-X_CTRL-N                    "ctrl_x"          Just pressed CTRL-X i_CTRL-X                    "scroll"          Scrolling with i_CTRL-X_CTRL-E or                                      i_CTRL-X_CTRL-Y                    "whole_line"      Whole lines i_CTRL-X_CTRL-L                    "files"           File names i_CTRL-X_CTRL-F                    "tags"            Tags i_CTRL-X_CTRL-]                    "path_defines"    Definition completion i_CTRL-X_CTRL-D                    "path_patterns"   Include completion i_CTRL-X_CTRL-I                    "dictionary"      Dictionary i_CTRL-X_CTRL-K                    "thesaurus"       Thesaurus i_CTRL-X_CTRL-T                    "cmdline"         Vim Command line i_CTRL-X_CTRL-V                    "function"        User defined completion i_CTRL-X_CTRL-U                    "omni"            Omni completion i_CTRL-X_CTRL-O                    "spell"           Spelling suggestions i_CTRL-X_s                    "eval"            complete() completion                    "unknown"         Other internal modes                 If the optional {what} list argument is supplied, then only                 the items listed in {what} are returned.  Unsupported items in                 {what} are silently ignored.                 To get the position and size of the popup menu, see                 pum_getpos(). It's also available in v:event during the                 CompleteChanged event.                 Returns an empty Dictionary on error.                 Examples:                         " Get all items                         call complete_info()                         " Get only 'mode'                         call complete_info(['mode'])                         " Get only 'mode' and 'pum_visible'                         call complete_info(['mode', 'pum_visible'])                 Can also be used as a method:                         GetItems()->complete_info()                                                 confirm() confirm({msg} [, {choices} [, {default} [, {type}]]])                 confirm() offers the user a dialog, from which a choice can be                 made.  It returns the number of the choice.  For the first                 choice this is 1.                 Note: confirm() is only supported when compiled with dialog                 support, see +dialog_con and +dialog_gui.                 {msg} is displayed in a dialog with {choices} as the                 alternatives.  When {choices} is missing or empty, "&OK" is                 used (and translated).                 {msg} is a String, use '\n' to include a newline.  Only on                 some systems the string is wrapped when it doesn't fit.                 {choices} is a String, with the individual choices separated                 by '\n', e.g.                         confirm("Save changes?", "&Yes\n&No\n&Cancel")                 The letter after the '&' is the shortcut key for that choice.                 Thus you can type 'c' to select "Cancel".  The shortcut does                 not need to be the first letter:                         confirm("file has been modified", "&Save\nSave &All")                 For the console, the first letter of each choice is used as                 the default shortcut key.  Case is ignored.                 The optional {default} argument is the number of the choice                 that is made if the user hits <CR>.  Use 1 to make the first                 choice the default one.  Use 0 to not set a default.  If                 {default} is omitted, 1 is used.                 The optional {type} String argument gives the type of dialog.                 This is only used for the icon of the GTK, Mac, Motif and                 Win32 GUI.  It can be one of these values: "Error",                 "Question", "Info", "Warning" or "Generic".  Only the first                 character is relevant.  When {type} is omitted, "Generic" is                 used.                 If the user aborts the dialog by pressing <Esc>CTRL-C,                 or another valid interrupt key, confirm() returns 0.                 An example:                    let choice = confirm("What do you want?",                                         \ "&Apples\n&Oranges\n&Bananas", 2)                    if choice == 0                         echo "make up your mind!"                    elseif choice == 3                         echo "tasteful"                    else                         echo "I prefer bananas myself."                    endif                 In a GUI dialog, buttons are used.  The layout of the buttons                 depends on the 'v' flag in 'guioptions'.  If it is included,                 the buttons are always put vertically.  Otherwise,  confirm()                 tries to put the buttons in one horizontal line.  If they                 don't fit, a vertical layout is used anyway.  For some systems                 the horizontal layout is always used.                 Can also be used as a methodin:                         BuildMessage()->confirm("&Yes\n&No")                                                         copy() copy({expr})    Make a copy of {expr}.  For Numbers and Strings this isn't                 different from using {expr} directly.                 When {expr} is a List a shallow copy is created.  This means                 that the original List can be changed without changing the                 copy, and vice versa.  But the items are identical, thus                 changing an item changes the contents of both Lists.                 A Dictionary is copied in a similar way as a List.                 Also see deepcopy().                 Can also be used as a method:                         mylist->copy() cos({expr})                                             cos()                 Return the cosine of {expr}, measured in radians, as a Float.                 {expr} must evaluate to a Float or a Number.                 Returns 0.0 if {expr} is not a Float or a Number.                 Examples:                         :echo cos(100)                         0.862319                         :echo cos(-4.01)                         -0.646043                 Can also be used as a method:                         Compute()->cos() cosh({expr})                                            cosh()                 Return the hyperbolic cosine of {expr} as a Float in the range                 [1, inf].                 {expr} must evaluate to a Float or a Number.                 Returns 0.0 if {expr} is not a Float or a Number.                 Examples:                         :echo cosh(0.5)                         1.127626                         :echo cosh(-0.5)                         -1.127626                 Can also be used as a method:                         Compute()->cosh() count({comp}{expr} [, {ic} [, {start}]])              count() E706                 Return the number of times an item with value {expr} appears                 in StringList or Dictionary {comp}.                 If {start} is given then start with the item with this index.                 {start} can only be used with a List.                 When {ic} is given and it's TRUE then case is ignored.                 When {comp} is a string then the number of not overlapping                 occurrences of {expr} is returned. Zero is returned when                 {expr} is an empty string.                 Can also be used as a method:                         mylist->count(val)                                                         cscope_connection() cscope_connection([{num} , {dbpath} [, {prepend}]])                 Checks for the existence of a cscope connection.  If no                 parameters are specified, then the function returns:                         0, if cscope was not available (not compiled in), or                            if there are no cscope connections;                         1, if there is at least one cscope connection.                 If parameters are specified, then the value of {num}                 determines how existence of a cscope connection is checked:                 {num}   Description of existence check                 -----   ------------------------------                 0       Same as no parameters (e.g., "cscope_connection()").                 1       Ignore {prepend}, and use partial string matches for                         {dbpath}.                 2       Ignore {prepend}, and use exact string matches for                         {dbpath}.                 3       Use {prepend}, use partial string matches for both                         {dbpath} and {prepend}.                 4       Use {prepend}, use exact string matches for both                         {dbpath} and {prepend}.                 Note: All string comparisons are case sensitive!                 Examples.  Suppose we had the following (from ":cs show"):   # pid    database name                        prepend path   0 27664  cscope.out                           /usr/local                 Invocation                                      Return Val                 ----------                                      ----------                 cscope_connection()                                     1                 cscope_connection(1, "out")                             1                 cscope_connection(2, "out")                             0                 cscope_connection(3, "out")                             0                 cscope_connection(3, "out", "local")                    1                 cscope_connection(4, "out")                             0                 cscope_connection(4, "out", "local")                    0                 cscope_connection(4, "cscope.out", "/usr/local")        1 cursor({lnum}{col} [, {off}])                         cursor() cursor({list})                 Positions the cursor at the column (byte count) {col} in the                 line {lnum}.  The first column is one.                 When there is one argument {list} this is used as a List                 with two, three or four item:                         [{lnum}{col}]                         [{lnum}{col}{off}]                         [{lnum}{col}{off}{curswant}]                 This is like the return value of getpos() or getcurpos(),                 but without the first item.                 To position the cursor using {col} as the character count, use                 setcursorcharpos().                 Does not change the jumplist.                 {lnum} is used like with getline(), except that if {lnum} is                 zero, the cursor will stay in the current line.                 If {lnum} is greater than the number of lines in the buffer,                 the cursor will be positioned at the last line in the buffer.                 If {col} is greater than the number of bytes in the line,                 the cursor will be positioned at the last character in the                 line.                 If {col} is zero, the cursor will stay in the current column.                 If {curswant} is given it is used to set the preferred column                 for vertical movement.  Otherwise {col} is used.                 When 'virtualedit' is used {off} specifies the offset in                 screen columns from the start of the character.  E.g., a                 position within a <Tab> or after the last character.                 Returns 0 when the position could be set, -1 otherwise.                 Can also be used as a method:                         GetCursorPos()->cursor() debugbreak({pid})                                       debugbreak()                 Specifically used to interrupt a program being debugged.  It                 will cause process {pid} to get a SIGTRAP.  Behavior for other                 processes is undefined. See terminal-debugger.                 {only available on MS-Windows}                 Returns TRUE if successfully interrupted the program.                 Otherwise returns FALSE.                 Can also be used as a method:                         GetPid()->debugbreak() deepcopy({expr} [, {noref}])                            deepcopy() E698                 Make a copy of {expr}.  For Numbers and Strings this isn't                 different from using {expr} directly.                 When {expr} is a List a full copy is created.  This means                 that the original List can be changed without changing the                 copy, and vice versa.  When an item is a List or                 Dictionary, a copy for it is made, recursively.  Thus                 changing an item in the copy does not change the contents of                 the original List.                 A Dictionary is copied in a similar way as a List.                 When {noref} is omitted or zero a contained List or                 Dictionary is only copied once.  All references point to                 this single copy.  With {noref} set to 1 every occurrence of a                 List or Dictionary results in a new copy.  This also means                 that a cyclic reference causes deepcopy() to fail.                                                                 E724                 Nesting is possible up to 100 levels.  When there is an item                 that refers back to a higher level making a deep copy with                 {noref} set to 1 will fail.                 Also see copy().                 Can also be used as a method:                         GetObject()->deepcopy() delete({fname} [, {flags}])                             delete()                 Without {flags} or with {flags} empty: Deletes the file by the                 name {fname}.                 This also works when {fname} is a symbolic link.  The symbolic                 link itself is deleted, not what it points to.                 When {flags} is "d": Deletes the directory by the name                 {fname}.  This fails when directory {fname} is not empty.                 When {flags} is "rf": Deletes the directory by the name                 {fname} and everything in it, recursively.  BE CAREFUL!                 Note: on MS-Windows it is not possible to delete a directory                 that is being used.                 The result is a Number, which is 0/false if the delete                 operation was successful and -1/true when the deletion failed                 or partly failed.                 Use remove() to delete an item from a List.                 To delete a line from the buffer use :delete or                 deletebufline().                 Can also be used as a method:                         GetName()->delete() deletebufline({buf}{first} [, {last}])                deletebufline()                 Delete lines {first} to {last} (inclusive) from buffer {buf}.                 If {last} is omitted then delete line {first} only.                 On success 0 is returned, on failure 1 is returned.                 This function works only for loaded buffers. First call                 bufload() if needed.                 For the use of {buf}, see bufname() above.                 {first} and {last} are used like with getline()Note that                 when using line() this refers to the current buffer. Use "$"                 to refer to the last line in buffer {buf}.                 Can also be used as a method:                         GetBuffer()->deletebufline(1)                                                         did_filetype() did_filetype()  Returns TRUE when autocommands are being executed and the                 FileType event has been triggered at least once.  Can be used                 to avoid triggering the FileType event again in the scripts                 that detect the file type. FileType                 Returns FALSE when :setf FALLBACK was used.                 When editing another file, the counter is reset, thus this                 really checks if the FileType event has been triggered for the                 current buffer.  This allows an autocommand that starts                 editing another buffer to set 'filetype' and load a syntax                 file. diff({fromlist}{tolist} [, {options}])                diff()                 Returns a String or a List containing the diff between the                 strings in {fromlist} and {tolist}.  Uses the Vim internal                 diff library to compute the diff.                                                         E106                 The optional "output" item in {options} specifies the returned                 diff format.  The following values are supported:                     indices     Return a List of the starting and ending                                 indices and a count of the strings in each                                 diff hunk.                     unified     Return the unified diff output as a String.                                 This is the default.                 If the "output" item in {options} is "indices", then a List is                 returned.  Each List item contains a Dict with the following                 items for each diff hunk:                     from_idx    start index in {fromlist} for this diff hunk.                     from_count  number of strings in {fromlist} that are                                 added/removed/modified in this diff hunk.                     to_idx      start index in {tolist} for this diff hunk.                     to_count    number of strings in {tolist} that are                                 added/removed/modified in this diff hunk.                 The {options} Dict argument also specifies diff options                 (similar to 'diffopt') and supports the following items:                     algorithm           Dict specifying the diff algorithm to                                         use.  Supported boolean items are                                         "myers", "minimal", "patience" and                                         "histogram".                     context             diff context length.  Default is 0.                     iblank              ignore changes where lines are all                                         blank.                     icase               ignore changes in case of text.                     indent-heuristic    use the indent heuristic for the                                         internal diff library.                     iwhite              ignore changes in amount of white                                         space.                     iwhiteall           ignore all white space changes.                     iwhiteeol           ignore white space changes at end of                                         line.                 For more information about these options, refer to 'diffopt'.                 To compute the unified diff, all the items in {fromlist} are                 concatenated into a string using a newline separator and the                 same for {tolist}.  The unified diff output uses line numbers.                 Returns an empty List or String if {fromlist} and {tolist} are                 identical.                 Examples:                     :echo diff(['abc'], ['xxx'])                      @@ -1 +1 @@                      -abc                      +xxx                     :echo diff(['abc'], ['xxx'], {'output': 'indices'})                      [{'from_idx': 0, 'from_count': 1, 'to_idx': 0, 'to_count': 1}]                     :echo diff(readfile('oldfile'), readfile('newfile'))                     :echo diff(getbufline(5, 1, '$'), getbufline(6, 1, '$'))                 For more examples, refer to diff-func-examples                 Can also be used as a method:                         GetFromList->diff(to_list) diff_filler({lnum})                                     diff_filler()                 Returns the number of filler lines above line {lnum}.                 These are the lines that were inserted at this point in                 another diff'ed window.  These filler lines are shown in the                 display but don't exist in the buffer.                 {lnum} is used like with getline().  Thus "." is the current                 line, "'m" mark m, etc.                 Returns 0 if the current window is not in diff mode.                 Can also be used as a method:                         GetLnum()->diff_filler() diff_hlID({lnum}{col})                                diff_hlID()                 Returns the highlight ID for diff mode at line {lnum} column                 {col} (byte index).  When the current line does not have a                 diff change zero is returned.                 {lnum} is used like with getline().  Thus "." is the current                 line, "'m" mark m, etc.                 {col} is 1 for the leftmost column, {lnum} is 1 for the first                 line.                 The highlight ID can be used with synIDattr() to obtain                 syntax information about the highlighting.                 Can also be used as a method:                         GetLnum()->diff_hlID(col) digraph_get({chars})                                    digraph_get() E1214                 Return the digraph of {chars}.  This should be a string with                 exactly two characters.  If {chars} are not just two                 characters, or the digraph of {chars} does not exist, an error                 is given and an empty string is returned.                 The character will be converted from Unicode to 'encoding'                 when needed.  This does require the conversion to be                 available, it might fail.                 Also see digraph_getlist().                 Examples:                 " Get a built-in digraph                 :echo digraph_get('00')         " Returns '∞'                 " Get a user-defined digraph                 :call digraph_set('aa', 'あ')                 :echo digraph_get('aa')         " Returns 'あ'                 Can also be used as a method:                         GetChars()->digraph_get()                 This function works only when compiled with the +digraphs                 feature.  If this feature is disabled, this function will                 display an error message. digraph_getlist([{listall}])                            digraph_getlist()                 Return a list of digraphs.  If the {listall} argument is given                 and it is TRUE, return all digraphs, including the default                 digraphs.  Otherwise, return only user-defined digraphs.                 The characters will be converted from Unicode to 'encoding'                 when needed.  This does require the conservation to be                 available, it might fail.                 Also see digraph_get().                 Examples:                 " Get user-defined digraphs                 :echo digraph_getlist()                 " Get all the digraphs, including default digraphs                 :echo digraph_getlist(1)                 Can also be used as a method:                         GetNumber()->digraph_getlist()                 This function works only when compiled with the +digraphs                 feature.  If this feature is disabled, this function will                 display an error message. digraph_set({chars}{digraph})                         digraph_set()                 Add digraph {chars} to the list.  {chars} must be a string                 with two characters.  {digraph} is a string with one UTF-8                 encoded character.  E1215                 Be careful, composing characters are NOT ignored.  This                 function is similar to :digraphs command, but useful to add                 digraphs start with a white space.                 The function result is v:true if digraph is registered.  If                 this fails an error message is given and v:false is returned.                 If you want to define multiple digraphs at once, you can use                 digraph_setlist().                 Example:                         call digraph_set('  ', 'あ')                 Can be used as a method:                         GetString()->digraph_set('あ')                 This function works only when compiled with the +digraphs                 feature.  If this feature is disabled, this function will                 display an error message. digraph_setlist({digraphlist})                          digraph_setlist()                 Similar to digraph_set() but this function can add multiple                 digraphs at once.  {digraphlist} is a list composed of lists,                 where each list contains two strings with {chars} and                 {digraph} as in digraph_set()E1216                 Example:                     call digraph_setlist([['aa', 'あ'], ['ii', 'い']])                 It is similar to the following:                     for [chars, digraph] in [['aa', 'あ'], ['ii', 'い']]                           call digraph_set(chars, digraph)                     endfor                 Except that the function returns after the first error,                 following digraphs will not be added.                 Can be used as a method:                     GetList()->digraph_setlist()                 This function works only when compiled with the +digraphs                 feature.  If this feature is disabled, this function will                 display an error message. echoraw({string})                                       echoraw()                 Output {string} as-is, including unprintable characters.                 This can be used to output a terminal code. For example, to                 disable modifyOtherKeys:                         call echoraw(&t_TE)                 and to enable it again:                         call echoraw(&t_TI)                 Use with care, you can mess up the terminal this way. empty({expr})                                           empty()                 Return the Number 1 if {expr} is empty, zero otherwise.                 - A List or Dictionary is empty when it does not have any                   items.                 - A String is empty when its length is zero.                 - A Number and Float are empty when their value is zero.                 - v:falsev:none and v:null are empty, v:true is not.                 - A Job is empty when it failed to start.                 - A Channel is empty when it is closed.                 - A Blob is empty when its length is zero.                 For a long List this is much faster than comparing the                 length with zero.                 Can also be used as a method:                         mylist->empty() environ()                                               environ()                 Return all of environment variables as dictionary. You can                 check if an environment variable exists like this:                         :echo has_key(environ(), 'HOME')                 Note that the variable name may be CamelCase; to ignore case                 use this:                         :echo index(keys(environ()), 'HOME', 0, 1) != -1 err_teapot([{expr}])                                    err_teapot()                 Produce an error with number 418, needed for implementation of                 RFC 2324.                 If {expr} is present and it is TRUE error 503 is given,                 indicating that coffee is temporarily not available.                 If {expr} is present it must be a String. escape({string}{chars})                               escape()                 Escape the characters in {chars} that occur in {string} with a                 backslash.  Example:                         :echo escape('c:\program files\vim', ' \')                 results in:                         c:\\program\ files\\vim                 Also see shellescape() and fnameescape().                 Can also be used as a method:                         GetText()->escape(' \')                                                         eval() eval({string})  Evaluate {string} and return the result.  Especially useful to                 turn the result of string() back into the original value.                 This works for Numbers, Floats, Strings, Blobs and composites                 of them.  Also works for Funcrefs that refer to existing                 functions.                 Can also be used as a method:                         argv->join()->eval() eventhandler()                                          eventhandler()                 Returns 1 when inside an event handler.  That is that Vim got                 interrupted while waiting for the user to type a character,                 e.g., when dropping a file on Vim.  This means interactive                 commands cannot be used.  Otherwise zero is returned. executable({expr})                                      executable()                 This function checks if an executable with the name {expr}                 exists.  {expr} must be the name of the program without any                 arguments.                 executable() uses the value of $PATH and/or the normal                 searchpath for programs.                PATHEXT                 On MS-Windows the ".exe", ".bat", etc. can optionally be                 included.  Then the extensions in $PATHEXT are tried.  Thus if                 "foo.exe" does not exist, "foo.exe.bat" can be found.  If                 $PATHEXT is not set then ".com;.exe;.bat;.cmd" is used.  A dot                 by itself can be used in $PATHEXT to try using the name                 without an extension.  When 'shell' looks like a Unix shell,                 then the name is also tried without adding an extension.                 On MS-Windows it only checks if the file exists and is not a                 directory, not if it's really executable.                 On MS-Windows an executable in the same directory as Vim is                 normally found.  Since this directory is added to $PATH it                 should also work to execute it win32-PATH.  This can be                 disabled by setting the $NoDefaultCurrentDirectoryInExePath                 environment variable.  NoDefaultCurrentDirectoryInExePath                 The result is a Number:                         1       exists                         0       does not exist                         -1      not implemented on this system                 exepath() can be used to get the full path of an executable.                 Can also be used as a method:                         GetCommand()->executable() execute({command} [, {silent}])                                 execute()                 Execute an Ex command or commands and return the output as a                 string.                 {command} can be a string or a List.  In case of a List the                 lines are executed one by one.                 This is more or less equivalent to:                         redir => var                         {command}                         redir END                 Except that line continuation in {command} is not recognized.                 The optional {silent} argument can have these values:                         ""              no :silent used                         "silent"        :silent used                         "silent!"       :silent! used                 The default is "silent".  Note that with "silent!", unlike                 :redir, error messages are dropped.  When using an external                 command the screen may be messed up, use system() instead.                                                         E930                 It is not possible to use :redir anywhere in {command}.                 To get a list of lines use split() on the result:                         execute('args')->split("\n")                 To execute a command in another window than the current one                 use win_execute().                 When used recursively the output of the recursive call is not                 included in the output of the higher level call.                 Can also be used as a method:                         GetCommand()->execute() exepath({expr})                                         exepath()                 If {expr} is an executable and is either an absolute path, a                 relative path or found in $PATH, return the full path.                 Note that the current directory is used when {expr} starts                 with "./", which may be a problem for Vim:                         echo exepath(v:progpath)                 If {expr} cannot be found in $PATH or is not executable then                 an empty string is returned.                 Can also be used as a method:                         GetCommand()->exepath()                                                         exists() exists({expr})  The result is a Number, which is TRUE if {expr} is defined,                 zero otherwise.                 Note: In a compiled :def function the evaluation is done at                 runtime.  Use exists_compiled() to evaluate the expression                 at compile time.                 For checking for a supported feature use has().                 For checking if a file exists use filereadable().                 The {expr} argument is a string, which contains one of these:                         varname         internal variable (see                         dict.key        internal-variables).  Also works                         list[i]         for curly-braces-namesDictionary                         import.Func     entries, List items, class and                         class.Func      object methods, imported items, etc.                         object.Func     Does not work for local variables in a                         class.varname   compiled :def function.                         object.varname  Also works for a function in Vim9                                         script, since it can be used as a                                         function reference.                                         Beware that evaluating an index may                                         cause an error message for an invalid                                         expression.  E.g.:                                            :let l = [1, 2, 3]                                            :echo exists("l[5]")                                            0                                            :echo exists("l[xx]")                                            E121: Undefined variable: xx                                            0                         &option-name    Vim option (only checks if it exists,                                         not if it really works)                         +option-name    Vim option that works.                         $ENVNAME        environment variable (could also be                                         done by comparing with an empty                                         string)                         *funcname       built-in function (see functions)                                         or user defined function (see                                         user-functions) that is implemented.                                         Also works for a variable that is a                                         Funcref.                         ?funcname       built-in function that could be                                         implemented; to be used to check if                                         "funcname" is valid                         :cmdname        Ex command: built-in command, user                                         command or command modifier :command.                                         Returns:                                         1  for match with start of a command                                         2  full match with a command                                         3  matches several user commands                                         To check for a supported command                                         always check the return value to be 2.                         :2match         The :2match command.                         :3match         The :3match command (but you                                         probably should not use it, it is                                         reserved for internal usage)                         #event          autocommand defined for this event                         #event#pattern  autocommand defined for this event and                                         pattern (the pattern is taken                                         literally and compared to the                                         autocommand patterns character by                                         character)                         #group          autocommand group exists                         #group#event    autocommand defined for this group and                                         event.                         #group#event#pattern                                         autocommand defined for this group,                                         event and pattern.                         ##event         autocommand for this event is                                         supported.                 Examples:                         exists("&shortname")                         exists("$HOSTNAME")                         exists("*strftime")                         exists("*s:MyFunc")     " only for legacy script                         exists("*MyFunc")                         exists("bufcount")                         exists(":Make")                         exists("#CursorHold")                         exists("#BufReadPre#*.gz")                         exists("#filetypeindent")                         exists("#filetypeindent#FileType")                         exists("#filetypeindent#FileType#*")                         exists("##ColorScheme")                 There must be no space between the symbol (&/$/*/#) and the                 name.                 There must be no extra characters after the name, although in                 a few cases this is ignored.  That may become stricter in the                 future, thus don't count on it!                 Working example:                         exists(":make")                 NOT working example:                         exists(":make install")                 Note that the argument must be a string, not the name of the                 variable itself.  For example:                         exists(bufcount)                 This doesn't check for existence of the "bufcount" variable,                 but gets the value of "bufcount", and checks if that exists.                 Can also be used as a method:                         Varname()->exists() exists_compiled({expr})                                 exists_compiled()                 Like exists() but evaluated at compile time.  This is useful                 to skip a block where a function is used that would otherwise                 give an error:                         if exists_compiled('*ThatFunction')                            ThatFunction('works')                         endif                 If exists() were used then a compilation error would be                 given if ThatFunction() is not defined.                 {expr} must be a literal string. E1232                 Can only be used in a :def function. E1233                 This does not work to check for arguments or local variables. exp({expr})                                                     exp()                 Return the exponential of {expr} as a Float in the range                 [0, inf].                 {expr} must evaluate to a Float or a Number.                 Returns 0.0 if {expr} is not a Float or a Number.                 Examples:                         :echo exp(2)                         7.389056                         :echo exp(-1)                         0.367879                 Can also be used as a method:                         Compute()->exp() expand({string} [, {nosuf} [, {list}]])                         expand()                 Expand wildcards and the following special keywords in                 {string}.  'wildignorecase' applies.                 If {list} is given and it is TRUE, a List will be returned.                 Otherwise the result is a String and when there are several                 matches, they are separated by <NL> characters.  [Note: in                 version 5.0 a space was used, which caused problems when a                 file name contains a space]                 If the expansion fails, the result is an empty string.  A name                 for a non-existing file is not included, unless {string} does                 not start with '%', '#' or '<', see below.                 For a :terminal window '%' expands to a '!' followed by                 the command or shell that is run terminal-bufname                 When {string} starts with '%', '#' or '<', the expansion is                 done like for the cmdline-special variables with their                 associated modifiers.  Here is a short overview:                         %               current file name                         #               alternate file name                         #n              alternate file name n                         <cfile>         file name under the cursor                         <afile>         autocmd file name                         <abuf>          autocmd buffer number (as a String!)                         <amatch>        autocmd matched name                         <cexpr>         C expression under the cursor                         <sfile>         sourced script file or function name                         <slnum>         sourced script line number or function                                         line number                         <sflnum>        script file line number, also when in                                         a function                         <SID>           "<SNR>123_"  where "123" is the                                         current script ID  <SID>                         <script>        sourced script file, or script file                                         where the current function was defined                         <stack>         call stack                         <cword>         word under the cursor                         <cWORD>         WORD under the cursor                         <client>        the {clientid} of the last received                                         message server2client()                 Modifiers:                         :p              expand to full path                         :h              head (last path component removed)                         :t              tail (last path component only)                         :r              root (one extension removed)                         :e              extension only                 Example:                         :let &tags = expand("%:p:h") .. "/tags"                 Note that when expanding a string that starts with '%', '#' or                 '<', any following text is ignored.  This does NOT work:                         :let doesntwork = expand("%:h.bak")                 Use this:                         :let doeswork = expand("%:h") .. ".bak"                 Also note that expanding "<cfile>" and others only returns the                 referenced file name without further expansion.  If "<cfile>"                 is "~/.cshrc", you need to do another expand() to have the                 "~/" expanded into the path of the home directory:                         :echo expand(expand("<cfile>"))                 There cannot be white space between the variables and the                 following modifier.  The fnamemodify() function can be used                 to modify normal file names.                 When using '%' or '#', and the current or alternate file name                 is not defined, an empty string is used.  Using "%:p" in a                 buffer with no name, results in the current directory, with a                 '/' added.                 When 'verbose' is set then expanding '%', '#' and <> items                 will result in an error message if the argument cannot be                 expanded.                 When {string} does not start with '%', '#' or '<', it is                 expanded like a file name is expanded on the command line.                 'suffixes' and 'wildignore' are used, unless the optional                 {nosuf} argument is given and it is TRUE.                 Names for non-existing files are included.  The "**" item can                 be used to search in a directory tree.  For example, to find                 all "README" files in the current directory and below:                         :echo expand("**/README")                 expand() can also be used to expand variables and environment                 variables that are only known in a shell.  But this can be                 slow, because a shell may be used to do the expansion.  See                 expr-env-expand.                 The expanded variable is still handled like a list of file                 names.  When an environment variable cannot be expanded, it is                 left unchanged.  Thus ":echo expand('$FOOBAR')" results in                 "$FOOBAR".                 See glob() for finding existing files.  See system() for                 getting the raw output of an external command.                 Can also be used as a method:                         Getpattern()->expand() expandcmd({string} [, {options}])                       expandcmd()                 Expand special items in String {string} like what is done for                 an Ex command such as :edit.  This expands special keywords,                 like with expand(), and environment variables, anywhere in                 {string}.  "~user" and "~/path" are only expanded at the                 start.                 The following items are supported in the {options} Dict                 argument:                     errmsg      If set to TRUE, error messages are displayed                                 if an error is encountered during expansion.                                 By default, error messages are not displayed.                 Returns the expanded string.  If an error is encountered                 during expansion, the unmodified {string} is returned.                 Example:                         :echo expandcmd('make %<.o')                         make /path/runtime/doc/builtin.o                         :echo expandcmd('make %<.o', {'errmsg': v:true})                 Can also be used as a method:                         GetCommand()->expandcmd() extend({expr1}{expr2} [, {expr3}])                    extend()                 {expr1} and {expr2} must be both Lists or both                 Dictionaries.                 If they are Lists: Append {expr2} to {expr1}.                 If {expr3} is given insert the items of {expr2} before the                 item with index {expr3} in {expr1}.  When {expr3} is zero                 insert before the first item.  When {expr3} is equal to                 len({expr1}) then {expr2} is appended.                 Examples:                         :echo sort(extend(mylist, [7, 5]))                         :call extend(mylist, [2, 3], 1)                 When {expr1} is the same List as {expr2} then the number of                 items copied is equal to the original length of the List.                 E.g., when {expr3} is 1 you get N new copies of the first item                 (where N is the original length of the List).                 Use add() to concatenate one item to a list.  To concatenate                 two lists into a new list use the + operator:                         :let newlist = [1, 2, 3] + [4, 5]                 If they are Dictionaries:                 Add all entries from {expr2} to {expr1}.                 If a key exists in both {expr1} and {expr2} then {expr3} is                 used to decide what to do:                 {expr3} = "keep": keep the value of {expr1}                 {expr3} = "force": use the value of {expr2}                 {expr3} = "error": give an error message                E737                 When {expr3} is omitted then "force" is assumed.                 {expr1} is changed when {expr2} is not empty.  If necessary                 make a copy of {expr1} first.                 {expr2} remains unchanged.                 When {expr1} is locked and {expr2} is not empty the operation                 fails.                 Returns {expr1}.  Returns 0 on error.                 Can also be used as a method:                         mylist->extend(otherlist) extendnew({expr1}{expr2} [, {expr3}])                 extendnew()                 Like extend() but instead of adding items to {expr1} a new                 List or Dictionary is created and returned.  {expr1} remains                 unchanged. feedkeys({string} [, {mode}])                           feedkeys()                 Characters in {string} are queued for processing as if they                 come from a mapping or were typed by the user.                 By default the string is added to the end of the typeahead                 buffer, thus if a mapping is still being executed the                 characters come after them.  Use the 'i' flag to insert before                 other characters, they will be executed next, before any                 characters from a mapping.                 The function does not wait for processing of keys contained in                 {string}.                 To include special keys into {string}, use double-quotes                 and "\..." notation expr-quote. For example,                 feedkeys("\<CR>") simulates pressing of the <Enter> key. But                 feedkeys('\<CR>') pushes 5 characters.                 A special code that might be useful is <Ignore>, it exits the                 wait for a character without doing anything.  <Ignore>                 {mode} is a String, which can contain these character flags:                 'm'     Remap keys. This is default.  If {mode} is absent,                         keys are remapped.                 'n'     Do not remap keys.                 't'     Handle keys as if typed; otherwise they are handled as                         if coming from a mapping.  This matters for undo,                         opening folds, etc.                 'L'     Lowlevel input.  Only works for Unix or when using the                         GUI. Keys are used as if they were coming from the                         terminal.  Other flags are not used.  E980                         When a CTRL-C interrupts and 't' is included it sets                         the internal "got_int" flag.                 'i'     Insert the string instead of appending (see above).                 'x'     Execute commands until typeahead is empty.  This is                         similar to using ":normal!".  You can call feedkeys()                         several times without 'x' and then one time with 'x'                         (possibly with an empty {string}) to execute all the                         typeahead.  Note that when Vim ends in Insert mode it                         will behave as if <Esc> is typed, to avoid getting                         stuck, waiting for a character to be typed before the                         script continues.                         Note that if you manage to call feedkeys() while                         executing commands, thus calling it recursively, then                         all typeahead will be consumed by the last call.                 'c'     Remove any script context when executing, so that                         legacy script syntax applies, "s:var" does not work,                         etc.  Note that if the string being fed sets a script                         context this still applies.                 '!'     When used with 'x' will not end Insert mode. Can be                         used in a test when a timer is set to exit Insert mode                         a little later.  Useful for testing CursorHoldI.                 Return value is always 0.                 Can also be used as a method:                         GetInput()->feedkeys() filereadable({file})                                    filereadable()                 The result is a Number, which is TRUE when a file with the                 name {file} exists, and can be read.  If {file} doesn't exist,                 or is a directory, the result is FALSE.  {file} is any                 expression, which is used as a String.                 If you don't care about the file being readable you can use                 glob().                 {file} is used as-is, you may want to expand wildcards first:                         echo filereadable('~/.vimrc')                         0                         echo filereadable(expand('~/.vimrc'))                         1                 Can also be used as a method:                         GetName()->filereadable()                                                         file_readable()                 Obsolete name: file_readable(). filewritable({file})                                    filewritable()                 The result is a Number, which is 1 when a file with the                 name {file} exists, and can be written.  If {file} doesn't                 exist, or is not writable, the result is 0.  If {file} is a                 directory, and we can write to it, the result is 2.                 Can also be used as a method:                         GetName()->filewritable() filter({expr1}{expr2})                                filter()                 {expr1} must be a ListStringBlob or Dictionary.                 For each item in {expr1} evaluate {expr2} and when the result                 is zero or false remove the item from the List or                 Dictionary.  Similarly for each byte in a Blob and each                 character in a String.                 {expr2} must be a string or Funcref.                 If {expr2} is a string, inside {expr2} v:val has the value                 of the current item.  For a Dictionary v:key has the key                 of the current item and for a List v:key has the index of                 the current item.  For a Blob v:key has the index of the                 current byte. For a String v:key has the index of the                 current character.                 Examples:                         call filter(mylist, 'v:val !~ "OLD"')                 Removes the items where "OLD" appears.                         call filter(mydict, 'v:key >= 8')                 Removes the items with a key below 8.                         call filter(var, 0)                 Removes all the items, thus clears the List or Dictionary.                 Note that {expr2} is the result of expression and is then                 used as an expression again.  Often it is good to use a                 literal-string to avoid having to double backslashes.                 If {expr2} is a Funcref it must take two arguments:                         1. the key or the index of the current item.                         2. the value of the current item.                 The function must return TRUE if the item should be kept.                 Example that keeps the odd items of a list:                         func Odd(idx, val)                           return a:idx % 2 == 1                         endfunc                         call filter(mylist, function('Odd'))                 It is shorter when using a lambda.  In Vim9 syntax:                         call filter(myList, (idx, val) => idx * val <= 42)                 In legacy script syntax:                         call filter(myList, {idx, val -> idx * val <= 42})                 If you do not use "val" you can leave it out:                         call filter(myList, {idx -> idx % 2 == 1})                 In Vim9 script the result must be true, false, zero or one.                 Other values will result in a type error.                 For a List and a Dictionary the operation is done                 in-place.  If you want it to remain unmodified make a copy                 first:                         :let l = filter(copy(mylist), 'v:val =~ "KEEP"')                 Returns {expr1}, the List or Dictionary that was filtered,                 or a new Blob or String.                 When an error is encountered while evaluating {expr2} no                 further items in {expr1} are processed.                 When {expr2} is a Funcref errors inside a function are ignored,                 unless it was defined with the "abort" flag.                 Can also be used as a method:                         mylist->filter(expr2) finddir({name} [, {path} [, {count}]])                          finddir()                 Find directory {name} in {path}.  Supports both downwards and                 upwards recursive directory searches.  See file-searching                 for the syntax of {path}.                 Returns the path of the first found match.  When the found                 directory is below the current directory a relative path is                 returned.  Otherwise a full path is returned.                 If {path} is omitted or empty then 'path' is used.                 If the optional {count} is given, find {count}'s occurrence of                 {name} in {path} instead of the first one.                 When {count} is negative return all the matches in a List.                 Returns an empty string if the directory is not found.                 This is quite similar to the ex-command :find.                 Can also be used as a method:                         GetName()->finddir() findfile({name} [, {path} [, {count}]])                         findfile()                 Just like finddir(), but find a file instead of a directory.                 Uses 'suffixesadd'.                 Example:                         :echo findfile("tags.vim", ".;")                 Searches from the directory of the current file upwards until                 it finds the file "tags.vim".                 Can also be used as a method:                         GetName()->findfile() flatten({list} [, {maxdepth}])                                  flatten()                 Flatten {list} up to {maxdepth} levels.  Without {maxdepth}                 the result is a List without nesting, as if {maxdepth} is                 a very large number.                 The {list} is changed in place, use flattennew() if you do                 not want that.                 In Vim9 script flatten() cannot be used, you must always use                 flattennew().                                                                 E900                 {maxdepth} means how deep in nested lists changes are made.                 {list} is not modified when {maxdepth} is 0.                 {maxdepth} must be positive number.                 If there is an error the number zero is returned.                 Example:                         :echo flatten([1, [2, [3, 4]], 5])                         [1, 2, 3, 4, 5]                         :echo flatten([1, [2, [3, 4]], 5], 1)                         [1, 2, [3, 4], 5]                 Can also be used as a method:                         mylist->flatten() flattennew({list} [, {maxdepth}])                       flattennew()                 Like flatten() but first make a copy of {list}. float2nr({expr})                                        float2nr()                 Convert {expr} to a Number by omitting the part after the                 decimal point.                 {expr} must evaluate to a Float or a Number.                 Returns 0 if {expr} is not a Float or a Number.                 When the value of {expr} is out of range for a Number the                 result is truncated to 0x7fffffff or -0x7fffffff (or when                 64-bit Number support is enabled, 0x7fffffffffffffff or                 -0x7fffffffffffffff).  NaN results in -0x80000000 (or when                 64-bit Number support is enabled, -0x8000000000000000).                 Examples:                         echo float2nr(3.95)                         3                          echo float2nr(-23.45)                         -23                          echo float2nr(1.0e100)                         2147483647  (or 9223372036854775807)                         echo float2nr(-1.0e150)                         -2147483647 (or -9223372036854775807)                         echo float2nr(1.0e-100)                         0                 Can also be used as a method:                         Compute()->float2nr() floor({expr})                                                   floor()                 Return the largest integral value less than or equal to                 {expr} as a Float (round down).                 {expr} must evaluate to a Float or a Number.                 Returns 0.0 if {expr} is not a Float or a Number.                 Examples:                         echo floor(1.856)                         1.0                          echo floor(-5.456)                         -6.0                          echo floor(4.0)                         4.0                 Can also be used as a method:                         Compute()->floor() fmod({expr1}{expr2})                                  fmod()                 Return the remainder of {expr1} / {expr2}, even if the                 division is not representable.  Returns {expr1} - i * {expr2}                 for some integer i such that if {expr2} is non-zero, the                 result has the same sign as {expr1} and magnitude less than                 the magnitude of {expr2}.  If {expr2} is zero, the value                 returned is zero.  The value returned is a Float.                 {expr1} and {expr2} must evaluate to a Float or a Number.                 Returns 0.0 if {expr1} or {expr2} is not a Float or a                 Number.                 Examples:                         :echo fmod(12.33, 1.22)                         0.13                         :echo fmod(-12.33, 1.22)                         -0.13                 Can also be used as a method:                         Compute()->fmod(1.22) fnameescape({string})                                   fnameescape()                 Escape {string} for use as file name command argument.  All                 characters that have a special meaning, such as '%' and '|'                 are escaped with a backslash.                 For most systems the characters escaped are                 " \t\n*?[{`$\\%#'\"|!<".  For systems where a backslash                 appears in a filename, it depends on the value of 'isfname'.                 A leading '+' and '>' is also escaped (special after :edit                 and :write).  And a "-" by itself (special after :cd).                 Returns an empty string on error.                 Example:                         :let fname = '+some str%nge|name'                         :exe "edit " .. fnameescape(fname)                 results in executing:                         edit \+some\ str\%nge\|name                 Can also be used as a method:                         GetName()->fnameescape() fnamemodify({fname}{mods})                            fnamemodify()                 Modify file name {fname} according to {mods}.  {mods} is a                 string of characters like it is used for file names on the                 command line.  See filename-modifiers.                 Example:                         :echo fnamemodify("main.c", ":p:h")                 results in:                         /home/user/vim/vim/src                 If {mods} is empty or an unsupported modifier is used then                 {fname} is returned.                 When {fname} is empty then with {mods} ":h" returns ".", so                 that :cd can be used with it.  This is different from                 expand('%:h') without a buffer name, which returns an empty                 string.                 Note: Environment variables don't work in {fname}, use                 expand() first then.                 Can also be used as a method:                         GetName()->fnamemodify(':p:h') foldclosed({lnum})                                      foldclosed()                 The result is a Number.  If the line {lnum} is in a closed                 fold, the result is the number of the first line in that fold.                 If the line {lnum} is not in a closed fold, -1 is returned.                 {lnum} is used like with getline().  Thus "." is the current                 line, "'m" mark m, etc.                 Can also be used as a method:                         GetLnum()->foldclosed() foldclosedend({lnum})                                   foldclosedend()                 The result is a Number.  If the line {lnum} is in a closed                 fold, the result is the number of the last line in that fold.                 If the line {lnum} is not in a closed fold, -1 is returned.                 {lnum} is used like with getline().  Thus "." is the current                 line, "'m" mark m, etc.                 Can also be used as a method:                         GetLnum()->foldclosedend() foldlevel({lnum})                                       foldlevel()                 The result is a Number, which is the foldlevel of line {lnum}                 in the current buffer.  For nested folds the deepest level is                 returned.  If there is no fold at line {lnum}, zero is                 returned.  It doesn't matter if the folds are open or closed.                 When used while updating folds (from 'foldexpr') -1 is                 returned for lines where folds are still to be updated and the                 foldlevel is unknown.  As a special case the level of the                 previous line is usually available.                 {lnum} is used like with getline().  Thus "." is the current                 line, "'m" mark m, etc.                 Can also be used as a method:                         GetLnum()->foldlevel()                                                         foldtext() foldtext()      Returns a String, to be displayed for a closed fold.  This is                 the default function used for the 'foldtext' option and should                 only be called from evaluating 'foldtext'.  It uses the                 v:foldstartv:foldend and v:folddashes variables.                 The returned string looks like this:                         +-- 45 lines: abcdef                 The number of leading dashes depends on the foldlevel.  The                 "45" is the number of lines in the fold.  "abcdef" is the text                 in the first non-blank line of the fold.  Leading white space,                 "//" or "/*" and the text from the 'foldmarker' and                 'commentstring' options is removed.                 When used to draw the actual foldtext, the rest of the line                 will be filled with the fold char from the 'fillchars'                 setting.                 Returns an empty string when there is no fold.                 {not available when compiled without the +folding feature} foldtextresult({lnum})                                  foldtextresult()                 Returns the text that is displayed for the closed fold at line                 {lnum}.  Evaluates 'foldtext' in the appropriate context.                 When there is no closed fold at {lnum} an empty string is                 returned.                 {lnum} is used like with getline().  Thus "." is the current                 line, "'m" mark m, etc.                 Useful when exporting folded text, e.g., to HTML.                 {not available when compiled without the +folding feature}                 Can also be used as a method:                         GetLnum()->foldtextresult() foreach({expr1}{expr2})                                       foreach()                 {expr1} must be a ListStringBlob or Dictionary.                 For each item in {expr1} execute {expr2}{expr1} is not                 modified; its values may be, as with :lockvar 1. E741                 See map() and filter() to modify {expr1}.                 {expr2} must be a string or Funcref.                 If {expr2} is a string, inside {expr2} v:val has the value                 of the current item.  For a Dictionary v:key has the key                 of the current item and for a List v:key has the index of                 the current item.  For a Blob v:key has the index of the                 current byte. For a String v:key has the index of the                 current character.                 Examples:                         call foreach(mylist, 'used[v:val] = true')                 This records the items that are in the {expr1} list.                 Note that {expr2} is the result of expression and is then used                 as a command.  Often it is good to use a literal-string to                 avoid having to double backslashes.                 If {expr2} is a Funcref it must take two arguments:                         1. the key or the index of the current item.                         2. the value of the current item.                 With a legacy script lambda you don't get an error if it only                 accepts one argument, but with a Vim9 lambda you get "E1106:                 One argument too many", the number of arguments must match.                 If the function returns a value, it is ignored.                 Returns {expr1} in all cases.                 When an error is encountered while executing {expr2} no                 further items in {expr1} are processed.                 When {expr2} is a Funcref errors inside a function are ignored,                 unless it was defined with the "abort" flag.                 Can also be used as a method:                         mylist->foreach(expr2)                                                         foreground() foreground()    Move the Vim window to the foreground.  Useful when sent from                 a client to a Vim server. remote_send()                 On Win32 systems this might not work, the OS does not always                 allow a window to bring itself to the foreground.  Use                 remote_foreground() instead.                 {only in the Win32, Motif and GTK GUI versions and the                 Win32 console version} fullcommand({name} [, {vim9}])                          fullcommand()                 Get the full command name from a short abbreviated command                 name; see 20.2 for details on command abbreviations.                 The string argument {name} may start with a : and can                 include a [range], these are skipped and not returned.                 Returns an empty string if a command doesn't exist, if it's                 ambiguous (for user-defined commands) or cannot be shortened                 this way. vim9-no-shorten                 Without the {vim9} argument uses the current script version.                 If {vim9} is present and FALSE then legacy script rules are                 used.  When {vim9} is present and TRUE then Vim9 rules are                 used, e.g. "en" is not a short form of "endif".                 For example fullcommand('s')fullcommand('sub'),                 fullcommand(':%substitute') all return "substitute".                 Can also be used as a method:                         GetName()->fullcommand()                                                 funcref() funcref({name} [, {arglist}] [, {dict}])                 Just like function(), but the returned Funcref will lookup                 the function by reference, not by name.  This matters when the                 function {name} is redefined later.                 Unlike function(){name} must be an existing user function.                 It only works for an autoloaded function if it has already                 been loaded (to avoid mistakenly loading the autoload script                 when only intending to use the function name, use function()                 instead). {name} cannot be a builtin function.                 Returns 0 on error.                 Can also be used as a method:                         GetFuncname()->funcref([arg])                                 function() partial E700 E923 function({name} [, {arglist}] [, {dict}])                 Return a Funcref variable that refers to function {name}.                 {name} can be the name of a user defined function or an                 internal function.                 {name} can also be a Funcref or a partial.  When it is a                 partial the dict stored in it will be used and the {dict}                 argument is not allowed. E.g.:                         let FuncWithArg = function(dict.Func, [arg])                         let Broken = function(dict.Func, [arg], dict)                 When using the Funcref the function will be found by {name},                 also when it was redefined later.  Use funcref() to keep the                 same function.                 When {arglist} or {dict} is present this creates a partial.                 That means the argument list and/or the dictionary is stored in                 the Funcref and will be used when the Funcref is called.                 The arguments are passed to the function in front of other                 arguments, but after any argument from method.  Example:                         func Callback(arg1, arg2, name)                         ...                         let Partial = function('Callback', ['one', 'two'])                         ...                         call Partial('name')                 Invokes the function as with:                         call Callback('one', 'two', 'name')                 With a method:                         func Callback(one, two, three)                         ...                         let Partial = function('Callback', ['two'])                         ...                         eval 'one'->Partial('three')                 Invokes the function as with:                         call Callback('one', 'two', 'three')                 The function() call can be nested to add more arguments to the                 Funcref.  The extra arguments are appended to the list of                 arguments.  Example:                         func Callback(arg1, arg2, name)                         "...                         let Func = function('Callback', ['one'])                         let Func2 = function(Func, ['two'])                         "...                         call Func2('name')                 Invokes the function as with:                         call Callback('one', 'two', 'name')                 The Dictionary is only useful when calling a "dict" function.                 In that case the {dict} is passed in as "self". Example:                         function Callback() dict                            echo "called for " .. self.name                         endfunction                         "...                         let context = {"name": "example"}                         let Func = function('Callback', context)                         "...                         call Func()     " will echo: called for example                 The use of function() is not needed when there are no extra                 arguments, these two are equivalent, if Callback() is defined                 as context.Callback():                         let Func = function('Callback', context)                         let Func = context.Callback                 The argument list and the Dictionary can be combined:                         function Callback(arg1, count) dict                         "...                         let context = {"name": "example"}                         let Func = function('Callback', ['one'], context)                         "...                         call Func(500)                 Invokes the function as with:                         call context.Callback('one', 500)                 Returns 0 on error.                 Can also be used as a method:                         GetFuncname()->function([arg]) garbagecollect([{atexit}])                              garbagecollect()                 Cleanup unused ListsDictionariesChannels and Jobs                 that have circular references.                 There is hardly ever a need to invoke this function, as it is                 automatically done when Vim runs out of memory or is waiting                 for the user to press a key after 'updatetime'.  Items without                 circular references are always freed when they become unused.                 This is useful if you have deleted a very big List and/or                 Dictionary with circular references in a script that runs                 for a long time.                 When the optional {atexit} argument is one, garbage                 collection will also be done when exiting Vim, if it wasn't                 done before.  This is useful when checking for memory leaks.                 The garbage collection is not done immediately but only when                 it's safe to perform.  This is when waiting for the user to                 type a character.  To force garbage collection immediately use                 test_garbagecollect_now(). get({list}{idx} [, {default}])                        get()                 Get item {idx} from List {list}.  When this item is not                 available return {default}.  Return zero when {default} is                 omitted.                 Preferably used as a method:                         mylist->get(idx) get({blob}{idx} [, {default}])                 Get byte {idx} from Blob {blob}.  When this byte is not                 available return {default}.  Return -1 when {default} is                 omitted.                 Preferably used as a method:                         myblob->get(idx) get({dict}{key} [, {default}])                 Get item with key {key} from Dictionary {dict}.  When this                 item is not available return {default}.  Return zero when                 {default} is omitted.  Useful example:                         let val = get(g:, 'var_name', 'default')                 This gets the value of g:var_name if it exists, and uses                 'default' when it does not exist.                 Preferably used as a method:                         mydict->get(key) get({func}{what})                 Get item {what} from Funcref {func}.  Possible values for                 {what} are:                         "name"  The function name                         "func"  The function                         "dict"  The dictionary                         "args"  The list with arguments                 Returns zero on error.                 Preferably used as a method:                         myfunc->get(what)                                                         getbufinfo() getbufinfo([{buf}]) getbufinfo([{dict}])                 Get information about buffers as a List of Dictionaries.                 Without an argument information about all the buffers is                 returned.                 When the argument is a Dictionary only the buffers matching                 the specified criteria are returned.  The following keys can                 be specified in {dict}:                         buflisted       include only listed buffers.                         bufloaded       include only loaded buffers.                         bufmodified     include only modified buffers.                 Otherwise, {buf} specifies a particular buffer to return                 information for.  For the use of {buf}, see bufname()                 above.  If the buffer is found the returned List has one item.                 Otherwise the result is an empty list.                 Each returned List item is a dictionary with the following                 entries:                         bufnr           Buffer number.                         changed         TRUE if the buffer is modified.                         changedtick     Number of changes made to the buffer.                         command         TRUE if the buffer belongs to the                                         command-line window cmdwin.                         hidden          TRUE if the buffer is hidden.                         lastused        Timestamp in seconds, like                                         localtime(), when the buffer was                                         last used.                                         {only with the +viminfo feature}                         listed          TRUE if the buffer is listed.                         lnum            Line number used for the buffer when                                         opened in the current window.                                         Only valid if the buffer has been                                         displayed in the window in the past.                                         If you want the line number of the                                         last known cursor position in a given                                         window, use line():                                                 :echo line('.', {winid})                         linecount       Number of lines in the buffer (only                                         valid when loaded)                         loaded          TRUE if the buffer is loaded.                         name            Full path to the file in the buffer.                         signs           List of signs placed in the buffer.                                         Each list item is a dictionary with                                         the following fields:                                             id    sign identifier                                             lnum  line number                                             name  sign name                         variables       A reference to the dictionary with                                         buffer-local variables.                         windows         List of window-IDs that display this                                         buffer                         popups          List of popup window-IDs that                                         display this buffer                 Examples:                         for buf in getbufinfo()                             echo buf.name                         endfor                         for buf in getbufinfo({'buflisted':1})                             if buf.changed                                 ....                             endif                         endfor                 To get buffer-local options use:                         getbufvar({bufnr}, '&option_name')                 Can also be used as a method:                         GetBufnr()->getbufinfo()                                                         getbufline() getbufline({buf}{lnum} [, {end}])                 Return a List with the lines starting from {lnum} to {end}                 (inclusive) in the buffer {buf}.  If {end} is omitted, a                 List with only the line {lnum} is returned.  See                 getbufoneline() for only getting the line.                 For the use of {buf}, see bufname() above.                 For {lnum} and {end} "$" can be used for the last line of the                 buffer.  Otherwise a number must be used.                 When {lnum} is smaller than 1 or bigger than the number of                 lines in the buffer, an empty List is returned.                 When {end} is greater than the number of lines in the buffer,                 it is treated as {end} is set to the number of lines in the                 buffer.  When {end} is before {lnum} an empty List is                 returned.                 This function works only for loaded buffers.  For unloaded and                 non-existing buffers, an empty List is returned.                 Example:                         :let lines = getbufline(bufnr("myfile"), 1, "$")                 Can also be used as a method:                         GetBufnr()->getbufline(lnum)                                                         getbufoneline() getbufoneline({buf}{lnum})                 Just like getbufline() but only get one line and return it                 as a string. getbufvar({buf}{varname} [, {def}])                           getbufvar()                 The result is the value of option or local buffer variable                 {varname} in buffer {buf}.  Note that the name without "b:"                 must be used.                 The {varname} argument is a string.                 When {varname} is empty returns a Dictionary with all the                 buffer-local variables.                 When {varname} is equal to "&" returns a Dictionary with all                 the buffer-local options.                 Otherwise, when {varname} starts with "&" returns the value of                 a buffer-local option.                 This also works for a global or buffer-local option, but it                 doesn't work for a global variable, window-local variable or                 window-local option.                 For the use of {buf}, see bufname() above.                 When the buffer or variable doesn't exist {def} or an empty                 string is returned, there is no error message.                 Examples:                         :let bufmodified = getbufvar(1, "&mod")                         :echo "todo myvar = " .. getbufvar("todo", "myvar")                 Can also be used as a method:                         GetBufnr()->getbufvar(varname) getcellwidths()                                         getcellwidths()                 Returns a List of cell widths of character ranges overridden                 by setcellwidths().  The format is equal to the argument of                 setcellwidths().  If no character ranges have their cell                 widths overridden, an empty List is returned. getchangelist([{buf}])                                  getchangelist()                 Returns the changelist for the buffer {buf}. For the use                 of {buf}, see bufname() above. If buffer {buf} doesn't                 exist, an empty list is returned.                 The returned list contains two entries: a list with the change                 locations and the current position in the list.  Each                 entry in the change list is a dictionary with the following                 entries:                         col             column number                         coladd          column offset for 'virtualedit'                         lnum            line number                 If buffer {buf} is the current buffer, then the current                 position refers to the position in the list. For other                 buffers, it is set to the length of the list.                 Can also be used as a method:                         GetBufnr()->getchangelist() getchar([expr])                                         getchar()                 Get a single character from the user or input stream.                 If [expr] is omitted, wait until a character is available.                 If [expr] is 0, only get a character when one is available.                         Return zero otherwise.                 If [expr] is 1, only check if a character is available, it is                         not consumed.  Return zero if no character available.                 If you prefer always getting a string use getcharstr().                 Without [expr] and when [expr] is 0 a whole character or                 special key is returned.  If it is a single character, the                 result is a Number.  Use nr2char() to convert it to a String.                 Otherwise a String is returned with the encoded character.                 For a special key it's a String with a sequence of bytes                 starting with 0x80 (decimal: 128).  This is the same value as                 the String "\<Key>", e.g., "\<Left>".  The returned value is                 also a String when a modifier (shift, control, alt) was used                 that is not included in the character.                 When [expr] is 0 and Esc is typed, there will be a short delay                 while Vim waits to see if this is the start of an escape                 sequence.                 When [expr] is 1 only the first byte is returned.  For a                 one-byte character it is the character itself as a number.                 Use nr2char() to convert it to a String.                 Use getcharmod() to obtain any additional modifiers.                 When the user clicks a mouse button, the mouse event will be                 returned.  The position can then be found in v:mouse_col,                 v:mouse_lnumv:mouse_winid and v:mouse_win.                 getmousepos() can also be used.  Mouse move events will be                 ignored.                 This example positions the mouse as it would normally happen:                         let c = getchar()                         if c == "\<LeftMouse>" && v:mouse_win > 0                           exe v:mouse_win .. "wincmd w"                           exe v:mouse_lnum                           exe "normal " .. v:mouse_col .. "|"                         endif                 When using bracketed paste only the first character is                 returned, the rest of the pasted text is dropped.                 xterm-bracketed-paste.                 There is no prompt, you will somehow have to make clear to the                 user that a character has to be typed.  The screen is not                 redrawn, e.g. when resizing the window.  When using a popup                 window it should work better with a popup-filter.                 There is no mapping for the character.                 Key codes are replaced, thus when the user presses the <Del>                 key you get the code for the <Del> key, not the raw character                 sequence.  Examples:                         getchar() == "\<Del>"                         getchar() == "\<S-Left>"                 This example redefines "f" to ignore case:                         :nmap f :call FindChar()<CR>                         :function FindChar()                         :  let c = nr2char(getchar())                         :  while col('.') < col('$') - 1                         :    normal l                         :    if getline('.')[col('.') - 1] ==? c                         :      break                         :    endif                         :  endwhile                         :endfunction                 You may also receive synthetic characters, such as                 <CursorHold>. Often you will want to ignore this and get                 another character:                         :function GetKey()                         :  let c = getchar()                         :  while c == "\<CursorHold>"                         :    let c = getchar()                         :  endwhile                         :  return c                         :endfunction getcharmod()                                            getcharmod()                 The result is a Number which is the state of the modifiers for                 the last obtained character with getchar() or in another way.                 These values are added together:                         2       shift                         4       control                         8       alt (meta)                         16      meta (when it's different from ALT)                         32      mouse double click                         64      mouse triple click                         96      mouse quadruple click (== 32 + 64)                         128     command (Mac) or super (GTK)                 Only the modifiers that have not been included in the                 character itself are obtained.  Thus Shift-a results in "A"                 without a modifier.  Returns 0 if no modifiers are used.                                                         getcharpos() getcharpos({expr})                 Get the position for String {expr}. Same as getpos() but the                 column number in the returned List is a character index                 instead of a byte index.                 If getpos() returns a very large column number, equal to                 v:maxcol, then getcharpos() will return the character index                 of the last character.                 Example:                 With the cursor on '세' in line 5 with text "여보세요":                         getcharpos('.')         returns [0, 5, 3, 0]                         getpos('.')             returns [0, 5, 7, 0]                 Can also be used as a method:                         GetMark()->getcharpos() getcharsearch()                                         getcharsearch()                 Return the current character search information as a {dict}                 with the following entries:                     char        character previously used for a character                                 search (tfT, or F); empty string                                 if no character search has been performed                     forward     direction of character search; 1 for forward,                                 0 for backward                     until       type of character search; 1 for a t or T                                 character search, 0 for an f or F                                 character search                 This can be useful to always have ; and , search                 forward/backward regardless of the direction of the previous                 character search:                         :nnoremap <expr> ; getcharsearch().forward ? ';' : ','                         :nnoremap <expr> , getcharsearch().forward ? ',' : ';'                 Also see setcharsearch(). getcharstr([expr])                                      getcharstr()                 Get a single character from the user or input stream as a                 string.                 If [expr] is omitted, wait until a character is available.                 If [expr] is 0 or false, only get a character when one is                         available.  Return an empty string otherwise.                 If [expr] is 1 or true, only check if a character is                         available, it is not consumed.  Return an empty string                         if no character is available.                 Otherwise this works like getchar(), except that a number                 result is converted to a string. getcmdcompltype()                                       getcmdcompltype()                 Return the type of the current command-line completion.                 Only works when the command line is being edited, thus                 requires use of c_CTRL-\_e or c_CTRL-R_=.                 See :command-completion for the return string.                 Also see getcmdtype()setcmdpos()getcmdline() and                 setcmdline().                 Returns an empty string when completion is not defined. getcmdline()                                            getcmdline()                 Return the current command-line.  Only works when the command                 line is being edited, thus requires use of c_CTRL-\_e or                 c_CTRL-R_=.                 Example:                         :cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR>                 Also see getcmdtype()getcmdpos()setcmdpos() and                 setcmdline().                 Returns an empty string when entering a password or using                 inputsecret(). getcmdpos()                                             getcmdpos()                 Return the position of the cursor in the command line as a                 byte count.  The first column is 1.                 Only works when editing the command line, thus requires use of                 c_CTRL-\_e or c_CTRL-R_= or an expression mapping.                 Returns 0 otherwise.                 Also see getcmdtype()setcmdpos()getcmdline() and                 setcmdline(). getcmdscreenpos()                                       getcmdscreenpos()                 Return the screen position of the cursor in the command line                 as a byte count.  The first column is 1.                 Instead of getcmdpos(), it adds the prompt position.                 Only works when editing the command line, thus requires use of                 c_CTRL-\_e or c_CTRL-R_= or an expression mapping.                 Returns 0 otherwise.                 Also see getcmdpos()setcmdpos()getcmdline() and                 setcmdline(). getcmdtype()                                            getcmdtype()                 Return the current command-line type. Possible return values                 are:                     :   normal Ex command                     >   debug mode command debug-mode                     /   forward search command                     ?   backward search command                     @   input() command                     -   :insert or :append command                     =   i_CTRL-R_=                 Only works when editing the command line, thus requires use of                 c_CTRL-\_e or c_CTRL-R_= or an expression mapping.                 Returns an empty string otherwise.                 Also see getcmdpos()setcmdpos() and getcmdline(). getcmdwintype()                                         getcmdwintype()                 Return the current command-line-window type. Possible return                 values are the same as getcmdtype(). Returns an empty string                 when not in the command-line window. getcompletion({pat}{type} [, {filtered}])             getcompletion()                 Return a list of command-line completion matches. The String                 {type} argument specifies what for.  The following completion                 types are supported:                 arglist         file names in argument list                 augroup         autocmd groups                 buffer          buffer names                 behave          :behave suboptions                 breakpoint      :breakadd and :breakdel suboptions                 color           color schemes                 command         Ex command                 cmdline         cmdline-completion result                 compiler        compilers                 cscope          :cscope suboptions                 custom,{func}   custom completion, defined via {func}                 customlist,{func} custom completion, defined via {func}                 diff_buffer     :diffget and :diffput completion                 dir             directory names                 environment     environment variable names                 event           autocommand events                 expression      Vim expression                 file            file and directory names                 file_in_path    file and directory names in 'path'                 filetype        filetype names 'filetype'                 function        function name                 help            help subjects                 highlight       highlight groups                 history         :history suboptions                 keymap          keyboard mappings                 locale          locale names (as output of locale -a)                 mapclear        buffer argument                 mapping         mapping name                 menu            menus                 messages        :messages suboptions                 option          options                 packadd         optional package pack-add names                 runtime         :runtime completion                 scriptnames     sourced script names :scriptnames                 shellcmd        Shell command                 sign            :sign suboptions                 syntax          syntax file names 'syntax'                 syntime         :syntime suboptions                 tag             tags                 tag_listfiles   tags, file names                 user            user names                 var             user variables                 If {pat} is an empty string, then all the matches are                 returned.  Otherwise only items matching {pat} are returned.                 See wildcards for the use of special characters in {pat}.                 If the optional {filtered} flag is set to 1, then 'wildignore'                 is applied to filter the results.  Otherwise all the matches                 are returned. The 'wildignorecase' option always applies.                 If the 'wildoptions' option contains 'fuzzy', then fuzzy                 matching is used to get the completion matches. Otherwise                 regular expression matching is used.  Thus this function                 follows the user preference, what happens on the command line.                 If you do not want this you can make 'wildoptions' empty                 before calling getcompletion() and restore it afterwards.                 If {type} is "cmdline", then the cmdline-completion result is                 returned.  For example, to complete the possible values after                 a ":call" command:                         echo getcompletion('call ', 'cmdline')                 If there are no matches, an empty list is returned.  An                 invalid value for {type} produces an error.                 Can also be used as a method:                         GetPattern()->getcompletion('color')                                                         getcurpos() getcurpos([{winid}])                 Get the position of the cursor.  This is like getpos('.'), but                 includes an extra "curswant" item in the list:                     [0, lnum, col, off, curswant]                 The "curswant" number is the preferred column when moving the                 cursor vertically.  After $ command it will be a very large                 number equal to v:maxcol.  Also see getcursorcharpos() and                 getpos().                 The first "bufnum" item is always zero. The byte position of                 the cursor is returned in 'col'. To get the character                 position, use getcursorcharpos().                 The optional {winid} argument can specify the window.  It can                 be the window number or the window-ID.  The last known                 cursor position is returned, this may be invalid for the                 current value of the buffer if it is not the current window.                 If {winid} is invalid a list with zeroes is returned.                 This can be used to save and restore the cursor position:                         let save_cursor = getcurpos()                         MoveTheCursorAround                         call setpos('.', save_cursor)                 Note that this only works within the window.  See                 winrestview() for restoring more state.                 Can also be used as a method:                         GetWinid()->getcurpos()                                                         getcursorcharpos() getcursorcharpos([{winid}])                 Same as getcurpos() but the column number in the returned                 List is a character index instead of a byte index.                 Example:                 With the cursor on '보' in line 3 with text "여보세요":                         getcursorcharpos()      returns [0, 3, 2, 0, 3]                         getcurpos()             returns [0, 3, 4, 0, 3]                 Can also be used as a method:                         GetWinid()->getcursorcharpos()                                                         getcwd() getcwd([{winnr} [, {tabnr}]])                 The result is a String, which is the name of the current                 working directory.  'autochdir' is ignored.                 With {winnr} return the local current directory of this window                 in the current tab page.  {winnr} can be the window number or                 the window-ID.                 If {winnr} is -1 return the name of the global working                 directory.  See also haslocaldir().                 With {winnr} and {tabnr} return the local current directory of                 the window in the specified tab page. If {winnr} is -1 return                 the working directory of the tabpage.                 If {winnr} is zero use the current window, if {tabnr} is zero                 use the current tabpage.                 Without any arguments, return the actual working directory of                 the current window.                 Return an empty string if the arguments are invalid.                 Examples:                         " Get the working directory of the current window                         :echo getcwd()                         :echo getcwd(0)                         :echo getcwd(0, 0)                         " Get the working directory of window 3 in tabpage 2                         :echo getcwd(3, 2)                         " Get the global working directory                         :echo getcwd(-1)                         " Get the working directory of tabpage 3                         :echo getcwd(-1, 3)                         " Get the working directory of current tabpage                         :echo getcwd(-1, 0)                 Can also be used as a method:                         GetWinnr()->getcwd() getenv({name})                                          getenv()                 Return the value of environment variable {name}.  The {name}                 argument is a string, without a leading '$'.  Example:                         myHome = getenv('HOME')                 When the variable does not exist v:null is returned.  That                 is different from a variable set to an empty string, although                 some systems interpret the empty value as the variable being                 deleted.  See also expr-env.                 Can also be used as a method:                         GetVarname()->getenv() getfontname([{name}])                                   getfontname()                 Without an argument returns the name of the normal font being                 used.  Like what is used for the Normal highlight group                 hl-Normal.                 With an argument a check is done whether String {name} is a                 valid font name.  If not then an empty string is returned.                 Otherwise the actual font name is returned, or {name} if the                 GUI does not support obtaining the real name.                 Only works when the GUI is running, thus not in your vimrc or                 gvimrc file.  Use the GUIEnter autocommand to use this                 function just after the GUI has started.                 Note that the GTK GUI accepts any font name, thus checking for                 a valid name does not work. getfperm({fname})                                       getfperm()                 The result is a String, which is the read, write, and execute                 permissions of the given file {fname}.                 If {fname} does not exist or its directory cannot be read, an                 empty string is returned.                 The result is of the form "rwxrwxrwx", where each group of                 "rwx" flags represent, in turn, the permissions of the owner                 of the file, the group the file belongs to, and other users.                 If a user does not have a given permission the flag for this                 is replaced with the string "-".  Examples:                         :echo getfperm("/etc/passwd")                         :echo getfperm(expand("~/.vimrc"))                 This will hopefully (from a security point of view) display                 the string "rw-r--r--" or even "rw-------".                 Can also be used as a method:                         GetFilename()->getfperm()                 For setting permissions use setfperm(). getfsize({fname})                                       getfsize()                 The result is a Number, which is the size in bytes of the                 given file {fname}.                 If {fname} is a directory, 0 is returned.                 If the file {fname} can't be found, -1 is returned.                 If the size of {fname} is too big to fit in a Number then -2                 is returned.                 Can also be used as a method:                         GetFilename()->getfsize() getftime({fname})                                       getftime()                 The result is a Number, which is the last modification time of                 the given file {fname}.  The value is measured as seconds                 since 1st Jan 1970, and may be passed to strftime().  See also                 localtime() and strftime().                 If the file {fname} can't be found -1 is returned.                 Can also be used as a method:                         GetFilename()->getftime() getftype({fname})                                       getftype()                 The result is a String, which is a description of the kind of                 file of the given file {fname}.                 If {fname} does not exist an empty string is returned.                 Here is a table over different kinds of files and their                 results:                         Normal file             "file"                         Directory               "dir"                         Symbolic link           "link"                         Block device            "bdev"                         Character device        "cdev"                         Socket                  "socket"                         FIFO                    "fifo"                         All other               "other"                 Example:                         getftype("/home")                 Note that a type such as "link" will only be returned on                 systems that support it.  On some systems only "dir" and                 "file" are returned.  On MS-Windows a symbolic link to a                 directory returns "dir" instead of "link".                 Can also be used as a method:                         GetFilename()->getftype() getimstatus()                                           getimstatus()                 The result is a Number, which is TRUE when the IME status is                 active and FALSE otherwise.                 See 'imstatusfunc'. getjumplist([{winnr} [, {tabnr}]])                      getjumplist()                 Returns the jumplist for the specified window.                 Without arguments use the current window.                 With {winnr} only use this window in the current tab page.                 {winnr} can also be a window-ID.                 With {winnr} and {tabnr} use the window in the specified tab                 page.  If {winnr} or {tabnr} is invalid, an empty list is                 returned.                 The returned list contains two entries: a list with the jump                 locations and the last used jump position number in the list.                 Each entry in the jump location list is a dictionary with                 the following entries:                         bufnr           buffer number                         col             column number                         coladd          column offset for 'virtualedit'                         filename        filename if available                         lnum            line number                 Can also be used as a method:                         GetWinnr()->getjumplist()                                                         getline() getline({lnum} [, {end}])                 Without {end} the result is a String, which is line {lnum}                 from the current buffer.  Example:                         getline(1)                 When {lnum} is a String that doesn't start with a                 digit, line() is called to translate the String into a Number.                 To get the line under the cursor:                         getline(".")                 When {lnum} is a number smaller than 1 or bigger than the                 number of lines in the buffer, an empty string is returned.                 When {end} is given the result is a List where each item is                 a line from the current buffer in the range {lnum} to {end},                 including line {end}.                 {end} is used in the same way as {lnum}.                 Non-existing lines are silently omitted.                 When {end} is before {lnum} an empty List is returned.                 Example:                         :let start = line('.')                         :let end = search("^$") - 1                         :let lines = getline(start, end)                 Can also be used as a method:                         ComputeLnum()->getline()                 To get lines from another buffer see getbufline() and                 getbufoneline() getloclist({nr} [, {what}])                             getloclist()                 Returns a List with all the entries in the location list for                 window {nr}.  {nr} can be the window number or the window-ID.                 When {nr} is zero the current window is used.                 For a location list window, the displayed location list is                 returned.  For an invalid window number {nr}, an empty list is                 returned. Otherwise, same as getqflist().                 If the optional {what} dictionary argument is supplied, then                 returns the items listed in {what} as a dictionary. Refer to                 getqflist() for the supported items in {what}.                 In addition to the items supported by getqflist() in {what},                 the following item is supported by getloclist():                         filewinid       id of the window used to display files                                         from the location list. This field is                                         applicable only when called from a                                         location list window. See                                         location-list-file-window for more                                         details.                 Returns a Dictionary with default values if there is no                 location list for the window {nr}.                 Returns an empty Dictionary if window {nr} does not exist.                 Examples (See also getqflist-examples):                         :echo getloclist(3, {'all': 0})                         :echo getloclist(5, {'filewinid': 0}) getmarklist([{buf}])                                    getmarklist()                 Without the {buf} argument returns a List with information                 about all the global marks. mark                 If the optional {buf} argument is specified, returns the                 local marks defined in buffer {buf}.  For the use of {buf},                 see bufname().  If {buf} is invalid, an empty list is                 returned.                 Each item in the returned List is a Dict with the following:                     mark   name of the mark prefixed by "'"                     pos    a List with the position of the mark:                                 [bufnum, lnum, col, off]                            Refer to getpos() for more information.                     file   file name                 Refer to getpos() for getting information about a specific                 mark.                 Can also be used as a method:                         GetBufnr()->getmarklist() getmatches([{win}])                                     getmatches()                 Returns a List with all matches previously defined for the                 current window by matchadd() and the :match commands.                 getmatches() is useful in combination with setmatches(),                 as setmatches() can restore a list of matches saved by                 getmatches().                 If {win} is specified, use the window with this number or                 window ID instead of the current window.  If {win} is invalid,                 an empty list is returned.                 Example:                         :echo getmatches()                         [{'group': 'MyGroup1', 'pattern': 'TODO',                         'priority': 10, 'id': 1}, {'group': 'MyGroup2',                         'pattern': 'FIXME', 'priority': 10, 'id': 2}]                         :let m = getmatches()                         :call clearmatches()                         :echo getmatches()                         []                         :call setmatches(m)                         :echo getmatches()                         [{'group': 'MyGroup1', 'pattern': 'TODO',                         'priority': 10, 'id': 1}, {'group': 'MyGroup2',                         'pattern': 'FIXME', 'priority': 10, 'id': 2}]                         :unlet m getmousepos()                                           getmousepos()                 Returns a Dictionary with the last known position of the                 mouse.  This can be used in a mapping for a mouse click or in                 a filter of a popup window.  The items are:                         screenrow       screen row                         screencol       screen column                         winid           Window ID of the click                         winrow          row inside "winid"                         wincol          column inside "winid"                         line            text line inside "winid"                         column          text column inside "winid"                         coladd          offset (in screen columns) from the                                         start of the clicked char                 All numbers are 1-based.                 If not over a window, e.g. when in the command line, then only                 "screenrow" and "screencol" are valid, the others are zero.                 When on the status line below a window or the vertical                 separator right of a window, the "line" and "column" values                 are zero.                 When the position is after the text then "column" is the                 length of the text in bytes plus one.                 If the mouse is over a popup window then that window is used.                 When using getchar() the Vim variables v:mouse_lnum,                 v:mouse_col and v:mouse_winid also provide these values. getmouseshape()                                         getmouseshape()                 Returns the name of the currently showing mouse pointer.                 When the +mouseshape feature is not supported or the shape                 is unknown an empty string is returned.                 This function is mainly intended for testing.                                                         getpid() getpid()        Return a Number which is the process ID of the Vim process.                 On Unix and MS-Windows this is a unique number, until Vim                 exits.                                                         getpos() getpos({expr})  Get the position for String {expr}.  For possible values of                 {expr} see line().  For getting the cursor position see                 getcurpos().                 The result is a List with four numbers:                     [bufnum, lnum, col, off]                 "bufnum" is zero, unless a mark like '0 or 'A is used, then it                 is the buffer number of the mark.                 "lnum" and "col" are the position in the buffer.  The first                 column is 1.                 The "off" number is zero, unless 'virtualedit' is used.  Then                 it is the offset in screen columns from the start of the                 character.  E.g., a position within a <Tab> or after the last                 character.                 Note that for '< and '> Visual mode matters: when it is "V"                 (visual line mode) the column of '< is zero and the column of                 '> is a large number equal to v:maxcol.                 The column number in the returned List is the byte position                 within the line. To get the character position in the line,                 use getcharpos().                 A very large column number equal to v:maxcol can be returned,                 in which case it means "after the end of the line".                 If {expr} is invalid, returns a list with all zeros.                 This can be used to save and restore the position of a mark:                         let save_a_mark = getpos("'a")                         ...                         call setpos("'a", save_a_mark)                 Also see getcharpos()getcurpos() and setpos().                 Can also be used as a method:                         GetMark()->getpos() getqflist([{what}])                                     getqflist()                 Returns a List with all the current quickfix errors.  Each                 list item is a dictionary with these entries:                         bufnr   number of buffer that has the file name, use                                 bufname() to get the name                         module  module name                         lnum    line number in the buffer (first line is 1)                         end_lnum                                 end of line number if the item is multiline                         col     column number (first column is 1)                         end_col end of column number if the item has range                         vcol    TRUE: "col" is visual column                                 FALSE: "col" is byte index                         nr      error number                         pattern search pattern used to locate the error                         text    description of the error                         type    type of the error, 'E', '1', etc.                         valid   TRUE: recognized error message                         user_data                                 custom data associated with the item, can be                                 any type.                 When there is no error list or it's empty, an empty list is                 returned. Quickfix list entries with a non-existing buffer                 number are returned with "bufnr" set to zero (Note: some                 functions accept buffer number zero for the alternate buffer,                 you may need to explicitly check for zero).                 Useful application: Find pattern matches in multiple files and                 do something with them:                         :vimgrep /theword/jg *.c                         :for d in getqflist()                         :   echo bufname(d.bufnr) ':' d.lnum '=' d.text                         :endfor                 If the optional {what} dictionary argument is supplied, then                 returns only the items listed in {what} as a dictionary. The                 following string items are supported in {what}:                         changedtick     get the total number of changes made                                         to the list quickfix-changedtick                         context get the quickfix-context                         efm     errorformat to use when parsing "lines". If                                 not present, then the 'errorformat' option                                 value is used.                         id      get information for the quickfix list with                                 quickfix-ID; zero means the id for the                                 current list or the list specified by "nr"                         idx     get information for the quickfix entry at this                                 index in the list specified by 'id' or 'nr'.                                 If set to zero, then uses the current entry.                                 See quickfix-index                         items   quickfix list entries                         lines   parse a list of lines using 'efm' and return                                 the resulting entries.  Only a List type is                                 accepted.  The current quickfix list is not                                 modified. See quickfix-parse.                         nr      get information for this quickfix list; zero                                 means the current quickfix list and "$" means                                 the last quickfix list                         qfbufnr number of the buffer displayed in the quickfix                                 window. Returns 0 if the quickfix buffer is                                 not present. See quickfix-buffer.                         size    number of entries in the quickfix list                         title   get the list title quickfix-title                         winid   get the quickfix window-ID                         all     all of the above quickfix properties                 Non-string items in {what} are ignored. To get the value of a                 particular item, set it to zero.                 If "nr" is not present then the current quickfix list is used.                 If both "nr" and a non-zero "id" are specified, then the list                 specified by "id" is used.                 To get the number of lists in the quickfix stack, set "nr" to                 "$" in {what}. The "nr" value in the returned dictionary                 contains the quickfix stack size.                 When "lines" is specified, all the other items except "efm"                 are ignored.  The returned dictionary contains the entry                 "items" with the list of entries.                 The returned dictionary contains the following entries:                         changedtick     total number of changes made to the                                         list quickfix-changedtick                         context quickfix list context. See quickfix-context                                 If not present, set to "".                         id      quickfix list ID quickfix-ID. If not                                 present, set to 0.                         idx     index of the quickfix entry in the list. If not                                 present, set to 0.                         items   quickfix list entries. If not present, set to                                 an empty list.                         nr      quickfix list number. If not present, set to 0                         qfbufnr number of the buffer displayed in the quickfix                                 window. If not present, set to 0.                         size    number of entries in the quickfix list. If not                                 present, set to 0.                         title   quickfix list title text. If not present, set                                 to "".                         winid   quickfix window-ID. If not present, set to 0                 Examples (See also getqflist-examples):                         :echo getqflist({'all': 1})                         :echo getqflist({'nr': 2, 'title': 1})                         :echo getqflist({'lines' : ["F1:10:L10"]}) getreg([{regname} [, 1 [, {list}]]])                    getreg()                 The result is a String, which is the contents of register                 {regname}.  Example:                         :let cliptext = getreg('*')                 When register {regname} was not set the result is an empty                 string.                 The {regname} argument must be a string.  E1162                 getreg('=') returns the last evaluated value of the expression                 register.  (For use in maps.)                 getreg('=', 1) returns the expression itself, so that it can                 be restored with setreg().  For other registers the extra                 argument is ignored, thus you can always give it.                 If {list} is present and TRUE, the result type is changed                 to List. Each list item is one text line. Use it if you care                 about zero bytes possibly present inside register: without                 third argument both NLs and zero bytes are represented as NLs                 (see NL-used-for-Nul).                 When the register was not set an empty list is returned.                 If {regname} is "", the unnamed register '"' is used.                 If {regname} is not specified, v:register is used.                 In Vim9-script {regname} must be one character.                 Can also be used as a method:                         GetRegname()->getreg() getreginfo([{regname}])                                 getreginfo()                 Returns detailed information about register {regname} as a                 Dictionary with the following entries:                         regcontents     List of lines contained in register                                         {regname}, like                                         getreg({regname}, 1, 1).                         regtype         the type of register {regname}, as in                                         getregtype().                         isunnamed       Boolean flag, v:true if this register                                         is currently pointed to by the unnamed                                         register.                         points_to       for the unnamed register, gives the                                         single letter name of the register                                         currently pointed to (see quotequote).                                         For example, after deleting a line                                         with dd, this field will be "1",                                         which is the register that got the                                         deleted text.                 The {regname} argument is a string.  If {regname} is invalid                 or not set, an empty Dictionary will be returned.                 If {regname} is "" or "@", the unnamed register '"' is used.                 If {regname} is not specified, v:register is used.                 The returned Dictionary can be passed to setreg().                 In Vim9-script {regname} must be one character.                 Can also be used as a method:                         GetRegname()->getreginfo() getregion({pos1}{pos2}{type})                       getregion()                 Returns the list of strings from {pos1} to {pos2} as if it's                 selected in visual mode of {type}.                 For possible values of {pos1} and {pos2} see line().                 {type} is the selection type:                         "v" for characterwise mode                         "V" for linewise mode                         "<CTRL-V>" for blockwise-visual mode                 You can get the last selection type by visualmode().                 If Visual mode is active, use mode() to get the Visual mode                 (e.g., in a :vmap).                 This function uses the line and column number from the                 specified position.                 It is useful to get text starting and ending in different                 columns, such as characterwise-visual selection.                 Note that:                 - Order of {pos1} and {pos2} doesn't matter, it will always                   return content from the upper left position to the lower                   right position.                 - If 'virtualedit' is enabled and selection is past the end of                   line, resulting lines are filled with blanks.                 - If the selection starts or ends in the middle of a multibyte                   character, it is not included but its selected part is                   substituted with spaces.                 - If {pos1} or {pos2} equals "v" (see line()) and it is not in                   visual-mode, an empty list is returned.                 - If {pos1}{pos2} or {type} is an invalid string, an empty                   list is returned.                 - If {pos1} or {pos2} is a mark in different buffer, an empty                   list is returned.                 Examples:                         :xnoremap <CR>                         \ <Cmd>echow getregion('v', '.', mode())<CR>                 Can also be used as a method:                         '.'->getregion("'a", 'v') getregtype([{regname}])                                 getregtype()                 The result is a String, which is type of register {regname}.                 The value will be one of:                     "v"                 for characterwise text                     "V"                 for linewise text                     "<CTRL-V>{width}"   for blockwise-visual text                     ""                  for an empty or unknown register                 <CTRL-V> is one character with value 0x16.                 The {regname} argument is a string.  If {regname} is "", the                 unnamed register '"' is used.  If {regname} is not specified,                 v:register is used.                 In Vim9-script {regname} must be one character.                 Can also be used as a method:                         GetRegname()->getregtype() getscriptinfo([{opts}])                                 getscriptinfo()                 Returns a List with information about all the sourced Vim                 scripts in the order they were sourced, like what                 :scriptnames shows.                 The optional Dict argument {opts} supports the following                 optional items:                     name        Script name match pattern. If specified,                                 and "sid" is not specified, information about                                 scripts with a name that match the pattern                                 "name" are returned.                     sid         Script ID <SID>.  If specified, only                                 information about the script with ID "sid" is                                 returned and "name" is ignored.                 Each item in the returned List is a Dict with the following                 items:                     autoload    Set to TRUE for a script that was used with                                 import autoload but was not actually sourced                                 yet (see import-autoload).                     functions   List of script-local function names defined in                                 the script.  Present only when a particular                                 script is specified using the "sid" item in                                 {opts}.                     name        Vim script file name.                     sid         Script ID <SID>.                     sourced     Script ID of the actually sourced script that                                 this script name links to, if any, otherwise                                 zero                     variables   A dictionary with the script-local variables.                                 Present only when a particular script is                                 specified using the "sid" item in {opts}.                                 Note that this is a copy, the value of                                 script-local variables cannot be changed using                                 this dictionary.                     version     Vim script version (scriptversion)                 Examples:                         :echo getscriptinfo({'name': 'myscript'})                         :echo getscriptinfo({'sid': 15}).variables gettabinfo([{tabnr}])                                   gettabinfo()                 If {tabnr} is not specified, then information about all the                 tab pages is returned as a List. Each List item is a                 Dictionary.  Otherwise, {tabnr} specifies the tab page                 number and information about that one is returned.  If the tab                 page does not exist an empty List is returned.                 Each List item is a Dictionary with the following entries:                         tabnr           tab page number.                         variables       a reference to the dictionary with                                         tabpage-local variables                         windows         List of window-IDs in the tab page.                 Can also be used as a method:                         GetTabnr()->gettabinfo() gettabvar({tabnr}{varname} [, {def}])                         gettabvar()                 Get the value of a tab-local variable {varname} in tab page                 {tabnr}t:var                 Tabs are numbered starting with one.                 The {varname} argument is a string.  When {varname} is empty a                 dictionary with all tab-local variables is returned.                 Note that the name without "t:" must be used.                 When the tab or variable doesn't exist {def} or an empty                 string is returned, there is no error message.                 Can also be used as a method:                         GetTabnr()->gettabvar(varname) gettabwinvar({tabnr}{winnr}{varname} [, {def}])             gettabwinvar()                 Get the value of window-local variable {varname} in window                 {winnr} in tab page {tabnr}.                 The {varname} argument is a string.  When {varname} is empty a                 dictionary with all window-local variables is returned.                 When {varname} is equal to "&" get the values of all                 window-local options in a Dictionary.                 Otherwise, when {varname} starts with "&" get the value of a                 window-local option.                 Note that {varname} must be the name without "w:".                 Tabs are numbered starting with one.  For the current tabpage                 use getwinvar().                 {winnr} can be the window number or the window-ID.                 When {winnr} is zero the current window is used.                 This also works for a global option, buffer-local option and                 window-local option, but it doesn't work for a global variable                 or buffer-local variable.                 When the tab, window or variable doesn't exist {def} or an                 empty string is returned, there is no error message.                 Examples:                         :let list_is_on = gettabwinvar(1, 2, '&list')                         :echo "myvar = " .. gettabwinvar(3, 1, 'myvar')                 To obtain all window-local variables use:                         gettabwinvar({tabnr}, {winnr}, '&')                 Can also be used as a method:                         GetTabnr()->gettabwinvar(winnr, varname) gettagstack([{winnr}])                                  gettagstack()                 The result is a Dict, which is the tag stack of window {winnr}.                 {winnr} can be the window number or the window-ID.                 When {winnr} is not specified, the current window is used.                 When window {winnr} doesn't exist, an empty Dict is returned.                 The returned dictionary contains the following entries:                         curidx          Current index in the stack. When at                                         top of the stack, set to (length + 1).                                         Index of bottom of the stack is 1.                         items           List of items in the stack. Each item                                         is a dictionary containing the                                         entries described below.                         length          Number of entries in the stack.                 Each item in the stack is a dictionary with the following                 entries:                         bufnr           buffer number of the current jump                         from            cursor position before the tag jump.                                         See getpos() for the format of the                                         returned list.                         matchnr         current matching tag number. Used when                                         multiple matching tags are found for a                                         name.                         tagname         name of the tag                 See tagstack for more information about the tag stack.                 Can also be used as a method:                         GetWinnr()->gettagstack() gettext({text})                                         gettext()                 Translate String {text} if possible.                 This is mainly for use in the distributed Vim scripts.  When                 generating message translations the {text} is extracted by                 xgettext, the translator can add the translated message in the                 .po file and Vim will lookup the translation when gettext() is                 called.                 For {text} double quoted strings are preferred, because                 xgettext does not understand escaping in single quoted                 strings. getwininfo([{winid}])                                   getwininfo()                 Returns information about windows as a List with Dictionaries.                 If {winid} is given Information about the window with that ID                 is returned, as a List with one item.  If the window does not                 exist the result is an empty list.                 Without {winid} information about all the windows in all the                 tab pages is returned.                 Each List item is a Dictionary with the following entries:                         botline         last complete displayed buffer line                         bufnr           number of buffer in the window                         height          window height (excluding winbar)                         loclist         1 if showing a location list                                         {only with the +quickfix feature}                         quickfix        1 if quickfix or location list window                                         {only with the +quickfix feature}                         terminal        1 if a terminal window                                         {only with the +terminal feature}                         tabnr           tab page number                         topline         first displayed buffer line                         variables       a reference to the dictionary with                                         window-local variables                         width           window width                         winbar          1 if the window has a toolbar, 0                                         otherwise                         wincol          leftmost screen column of the window;                                         "col" from win_screenpos()                         textoff         number of columns occupied by any                                         'foldcolumn''signcolumn' and line                                         number in front of the text                         winid           window-ID                         winnr           window number                         winrow          topmost screen line of the window;                                         "row" from win_screenpos()                 Can also be used as a method:                         GetWinnr()->getwininfo() getwinpos([{timeout}])                                  getwinpos()                 The result is a List with two numbers, the result of                 getwinposx() and getwinposy() combined:                         [x-pos, y-pos]                 {timeout} can be used to specify how long to wait in msec for                 a response from the terminal.  When omitted 100 msec is used.                 Use a longer time for a remote terminal.                 When using a value less than 10 and no response is received                 within that time, a previously reported position is returned,                 if available.  This can be used to poll for the position and                 do some work in the meantime:                         while 1                           let res = getwinpos(1)                           if res[0] >= 0                             break                           endif                           " Do some work here                         endwhile                 Can also be used as a method:                         GetTimeout()->getwinpos()                                                         getwinposx() getwinposx()    The result is a Number, which is the X coordinate in pixels of                 the left hand side of the GUI Vim window. Also works for an                 xterm (uses a timeout of 100 msec).                 The result will be -1 if the information is not available                 (e.g. on the Wayland backend).                 The value can be used with :winpos.                                                         getwinposy() getwinposy()    The result is a Number, which is the Y coordinate in pixels of                 the top of the GUI Vim window.  Also works for an xterm (uses                 a timeout of 100 msec).                 The result will be -1 if the information is not available                 (e.g. on the Wayland backend).                 The value can be used with :winpos. getwinvar({winnr}{varname} [, {def}])                         getwinvar()                 Like gettabwinvar() for the current tabpage.                 Examples:                         :let list_is_on = getwinvar(2, '&list')                         :echo "myvar = " .. getwinvar(1, 'myvar')                 Can also be used as a method:                         GetWinnr()->getwinvar(varname) glob({expr} [, {nosuf} [, {list} [, {alllinks}]]])              glob()                 Expand the file wildcards in {expr}.  See wildcards for the                 use of special characters.                 Unless the optional {nosuf} argument is given and is TRUE,                 the 'suffixes' and 'wildignore' options apply: Names matching                 one of the patterns in 'wildignore' will be skipped and                 'suffixes' affect the ordering of matches.                 'wildignorecase' always applies.                 When {list} is present and it is TRUE the result is a List                 with all matching files. The advantage of using a List is,                 you also get filenames containing newlines correctly.                 Otherwise the result is a String and when there are several                 matches, they are separated by <NL> characters.                 If the expansion fails, the result is an empty String or List.                 You can also use readdir() if you need to do complicated                 things, such as limiting the number of matches.                 A name for a non-existing file is not included.  A symbolic                 link is only included if it points to an existing file.                 However, when the {alllinks} argument is present and it is                 TRUE then all symbolic links are included.                 For most systems backticks can be used to get files names from                 any external command.  Example:                         :let tagfiles = glob("`find . -name tags -print`")                         :let &tags = substitute(tagfiles, "\n", ",", "g")                 The result of the program inside the backticks should be one                 item per line.  Spaces inside an item are allowed.                 See expand() for expanding special Vim variables.  See                 system() for getting the raw output of an external command.                 Can also be used as a method:                         GetExpr()->glob() glob2regpat({string})                                    glob2regpat()                 Convert a file pattern, as used by glob(), into a search                 pattern.  The result can be used to match with a string that                 is a file name.  E.g.                         if filename =~ glob2regpat('Make*.mak')                 This is equivalent to:                         if filename =~ '^Make.*\.mak$'                 When {string} is an empty string the result is "^$", match an                 empty string.                 Note that the result depends on the system.  On MS-Windows                 a backslash usually means a path separator.                 Can also be used as a method:                         GetExpr()->glob2regpat()                                                                 globpath() globpath({path}{expr} [, {nosuf} [, {list} [, {alllinks}]]])                 Perform glob() for String {expr} on all directories in {path}                 and concatenate the results.  Example:                         :echo globpath(&rtp, "syntax/c.vim")                 {path} is a comma-separated list of directory names.  Each                 directory name is prepended to {expr} and expanded like with                 glob().  A path separator is inserted when needed.                 To add a comma inside a directory name escape it with a                 backslash.  Note that on MS-Windows a directory may have a                 trailing backslash, remove it if you put a comma after it.                 If the expansion fails for one of the directories, there is no                 error message.                 Unless the optional {nosuf} argument is given and is TRUE,                 the 'suffixes' and 'wildignore' options apply: Names matching                 one of the patterns in 'wildignore' will be skipped and                 'suffixes' affect the ordering of matches.                 When {list} is present and it is TRUE the result is a List                 with all matching files. The advantage of using a List is, you                 also get filenames containing newlines correctly. Otherwise                 the result is a String and when there are several matches,                 they are separated by <NL> characters.  Example:                         :echo globpath(&rtp, "syntax/c.vim", 0, 1)                 {alllinks} is used as with glob().                 The "**" item can be used to search in a directory tree.                 For example, to find all "README.txt" files in the directories                 in 'runtimepath' and below:                         :echo globpath(&rtp, "**/README.txt")                 Upwards search and limiting the depth of "**" is not                 supported, thus using 'path' will not always work properly.                 Can also be used as a method, the base is passed as the                 second argument:                         GetExpr()->globpath(&rtp)                                                         has() has({feature} [, {check}])                 When {check} is omitted or is zero: The result is a Number,                 which is 1 if the feature {feature} is supported, zero                 otherwise.  The {feature} argument is a string, case is                 ignored.  See feature-list below.                 When {check} is present and not zero: The result is a Number,                 which is 1 if the feature {feature} could ever be supported,                 zero otherwise.  This is useful to check for a typo in                 {feature} and to detect dead code.  Keep in mind that an older                 Vim version will not know about a feature added later and                 features that have been abandoned will not be known by the                 current Vim version.                 Also see exists() and exists_compiled().                 Note that to skip code that has a syntax error when the                 feature is not available, Vim may skip the rest of the line                 and miss a following endif.  Therefore put the endif on a                 separate line:                         if has('feature')                           let x = this->breaks->without->the->feature                         endif                 If the endif would be moved to the second line as "| endif" it                 would not be found. has_key({dict}{key})                                  has_key()                 The result is a Number, which is TRUE if Dictionary {dict}                 has an entry with key {key}.  FALSE otherwise.                 The {key} argument is a string.  In Vim9 script a number is                 also accepted (and converted to a string) but no other types.                 In legacy script the usual automatic conversion to string is                 done.                 Can also be used as a method:                         mydict->has_key(key) haslocaldir([{winnr} [, {tabnr}]])                      haslocaldir()                 The result is a Number:                     1   when the window has set a local directory via :lcd                     2   when the tab-page has set a local directory via :tcd                     0   otherwise.                 Without arguments use the current window.                 With {winnr} use this window in the current tab page.                 With {winnr} and {tabnr} use the window in the specified tab                 page.                 {winnr} can be the window number or the window-ID.                 If {winnr} is -1 it is ignored and only the tabpage is used.                 Return 0 if the arguments are invalid.                 Examples:                         if haslocaldir() == 1                           " window local directory case                         elseif haslocaldir() == 2                           " tab-local directory case                         else                           " global directory case                         endif                         " current window                         :echo haslocaldir()                         :echo haslocaldir(0)                         :echo haslocaldir(0, 0)                         " window n in current tab page                         :echo haslocaldir(n)                         :echo haslocaldir(n, 0)                         " window n in tab page m                         :echo haslocaldir(n, m)                         " tab page m                         :echo haslocaldir(-1, m)                 Can also be used as a method:                         GetWinnr()->haslocaldir() hasmapto({what} [, {mode} [, {abbr}]])                  hasmapto()                 The result is a Number, which is TRUE if there is a mapping                 that contains {what} in somewhere in the rhs (what it is                 mapped to) and this mapping exists in one of the modes                 indicated by {mode}.                 The arguments {what} and {mode} are strings.                 When {abbr} is there and it is TRUE use abbreviations                 instead of mappings.  Don't forget to specify Insert and/or                 Command-line mode.                 Both the global mappings and the mappings local to the current                 buffer are checked for a match.                 If no matching mapping is found FALSE is returned.                 The following characters are recognized in {mode}:                         n       Normal mode                         v       Visual and Select mode                         x       Visual mode                         s       Select mode                         o       Operator-pending mode                         i       Insert mode                         l       Language-Argument ("r", "f", "t", etc.)                         c       Command-line mode                 When {mode} is omitted, "nvo" is used.                 This function is useful to check if a mapping already exists                 to a function in a Vim script.  Example:                         :if !hasmapto('\ABCdoit')                         :   map <Leader>d \ABCdoit                         :endif                 This installs the mapping to "\ABCdoit" only if there isn't                 already a mapping to "\ABCdoit".                 Can also be used as a method:                         GetRHS()->hasmapto() histadd({history}{item})                              histadd()                 Add the String {item} to the history {history} which can be                 one of:                                 hist-names                         "cmd"    or ":"   command line history                         "search" or "/"   search pattern history                         "expr"   or "="   typed expression history                         "input"  or "@"   input line history                         "debug"  or ">"   debug command history                         empty             the current or last used history                 The {history} string does not need to be the whole name, one                 character is sufficient.                 If {item} does already exist in the history, it will be                 shifted to become the newest entry.                 The result is a Number: TRUE if the operation was successful,                 otherwise FALSE is returned.                 Example:                         :call histadd("input", strftime("%Y %b %d"))                         :let date=input("Enter date: ")                 This function is not available in the sandbox.                 Can also be used as a method, the base is passed as the                 second argument:                         GetHistory()->histadd('search') histdel({history} [, {item}])                           histdel()                 Clear {history}, i.e. delete all its entries.  See hist-names                 for the possible values of {history}.                 If the parameter {item} evaluates to a String, it is used as a                 regular expression.  All entries matching that expression will                 be removed from the history (if there are any).                 Upper/lowercase must match, unless "\c" is used /\c.                 If {item} evaluates to a Number, it will be interpreted as                 an index, see :history-indexing.  The respective entry will                 be removed if it exists.                 The result is TRUE for a successful operation, otherwise FALSE                 is returned.                 Examples:                 Clear expression register history:                         :call histdel("expr")                 Remove all entries starting with "*" from the search history:                         :call histdel("/", '^\*')                 The following three are equivalent:                         :call histdel("search", histnr("search"))                         :call histdel("search", -1)                         :call histdel("search", '^' .. histget("search", -1) .. '$')                 To delete the last search pattern and use the last-but-one for                 the "n" command and 'hlsearch':                         :call histdel("search", -1)                         :let @/ = histget("search", -1)                 Can also be used as a method:                         GetHistory()->histdel() histget({history} [, {index}])                          histget()                 The result is a String, the entry with Number {index} from                 {history}.  See hist-names for the possible values of                 {history}, and :history-indexing for {index}.  If there is                 no such entry, an empty String is returned.  When {index} is                 omitted, the most recent item from the history is used.                 Examples:                 Redo the second last search from history.                         :execute '/' .. histget("search", -2)                 Define an Ex command ":H {num}" that supports re-execution of                 the {num}th entry from the output of :history.                         :command -nargs=1 H execute histget("cmd", 0+<args>)                 Can also be used as a method:                         GetHistory()->histget() histnr({history})                                       histnr()                 The result is the Number of the current entry in {history}.                 See hist-names for the possible values of {history}.                 If an error occurred, -1 is returned.                 Example:                         :let inp_index = histnr("expr")                 Can also be used as a method:                         GetHistory()->histnr() hlexists({name})                                        hlexists()                 The result is a Number, which is TRUE if a highlight group                 called {name} exists.  This is when the group has been                 defined in some way.  Not necessarily when highlighting has                 been defined for it, it may also have been used for a syntax                 item.                                                         highlight_exists()                 Obsolete name: highlight_exists().                 Can also be used as a method:                         GetName()->hlexists() hlget([{name} [, {resolve}]])                           hlget()                 Returns a List of all the highlight group attributes.  If the                 optional {name} is specified, then returns a List with only                 the attributes of the specified highlight group.  Returns an                 empty List if the highlight group {name} is not present.                 If the optional {resolve} argument is set to v:true and the                 highlight group {name} is linked to another group, then the                 link is resolved recursively and the attributes of the                 resolved highlight group are returned.                 Each entry in the returned List is a Dictionary with the                 following items:                         cleared boolean flag, set to v:true if the highlight                                 group attributes are cleared or not yet                                 specified.  See highlight-clear.                         cterm   cterm attributes. See highlight-cterm.                         ctermbg cterm background color.                                 See highlight-ctermbg.                         ctermfg cterm foreground color.                                 See highlight-ctermfg.                         ctermul cterm underline color.  See highlight-ctermul.                         default boolean flag, set to v:true if the highlight                                 group link is a default link. See                                 highlight-default.                         font    highlight group font.  See highlight-font.                         gui     gui attributes. See highlight-gui.                         guibg   gui background color.  See highlight-guibg.                         guifg   gui foreground color.  See highlight-guifg.                         guisp   gui special color.  See highlight-guisp.                         id      highlight group ID.                         linksto linked highlight group name.                                 See :highlight-link.                         name    highlight group name. See group-name.                         start   start terminal keycode.  See highlight-start.                         stop    stop terminal keycode.  See highlight-stop.                         term    term attributes.  See highlight-term.                 The 'term''cterm' and 'gui' items in the above Dictionary                 have a dictionary value with the following optional boolean                 items: 'bold''standout''underline''undercurl''italic',                 'reverse''inverse' and 'strikethrough'.                 Example(s):                         :echo hlget()                         :echo hlget('ModeMsg')                         :echo hlget('Number', v:true)                 Can also be used as a method:                         GetName()->hlget() hlset({list})                                           hlset()                 Creates or modifies the attributes of a List of highlight                 groups.  Each item in {list} is a dictionary containing the                 attributes of a highlight group. See hlget() for the list of                 supported items in this dictionary.                 In addition to the items described in hlget(), the following                 additional items are supported in the dictionary:                         force           boolean flag to force the creation of                                         a link for an existing highlight group                                         with attributes.                 The highlight group is identified using the 'name' item and                 the 'id' item (if supplied) is ignored.  If a highlight group                 with a specified name doesn't exist, then it is created.                 Otherwise the attributes of an existing highlight group are                 modified.                 If an empty dictionary value is used for the 'term' or 'cterm'                 or 'gui' entries, then the corresponding attributes are                 cleared.  If the 'cleared' item is set to v:true, then all the                 attributes of the highlight group are cleared.                 The 'linksto' item can be used to link a highlight group to                 another highlight group.  See :highlight-link.                 Returns zero for success, -1 for failure.                 Example(s):                         " add bold attribute to the Visual highlight group                         :call hlset([#{name: 'Visual',                                         \ term: #{reverse: 1 , bold: 1}}])                         :call hlset([#{name: 'Type', guifg: 'DarkGreen'}])                         :let l = hlget()                         :call hlset(l)                         " clear the Search highlight group                         :call hlset([#{name: 'Search', cleared: v:true}])                         " clear the 'term' attributes for a highlight group                         :call hlset([#{name: 'Title', term: {}}])                         " create the MyHlg group linking it to DiffAdd                         :call hlset([#{name: 'MyHlg', linksto: 'DiffAdd'}])                         " remove the MyHlg group link                         :call hlset([#{name: 'MyHlg', linksto: 'NONE'}])                         " clear the attributes and a link                         :call hlset([#{name: 'MyHlg', cleared: v:true,                                         \ linksto: 'NONE'}])                 Can also be used as a method:                         GetAttrList()->hlset()                                                         hlID() hlID({name})    The result is a Number, which is the ID of the highlight group                 with name {name}.  When the highlight group doesn't exist,                 zero is returned.                 This can be used to retrieve information about the highlight                 group.  For example, to get the background color of the                 "Comment" group:         :echo synIDattr(synIDtrans(hlID("Comment")), "bg")                                                         highlightID()                 Obsolete name: highlightID().                 Can also be used as a method:                         GetName()->hlID() hostname()                                              hostname()                 The result is a String, which is the name of the machine on                 which Vim is currently running.  Machine names greater than                 256 characters long are truncated. iconv({string}{from}{to})                           iconv()                 The result is a String, which is the text {string} converted                 from encoding {from} to encoding {to}.                 When the conversion completely fails an empty string is                 returned.  When some characters could not be converted they                 are replaced with "?".                 The encoding names are whatever the iconv() library function                 can accept, see ":!man 3 iconv".                 Most conversions require Vim to be compiled with the +iconv                 feature.  Otherwise only UTF-8 to latin1 conversion and back                 can be done.                 This can be used to display messages with special characters,                 no matter what 'encoding' is set to.  Write the message in                 UTF-8 and use:                         echo iconv(utf8_str, "utf-8", &enc)                 Note that Vim uses UTF-8 for all Unicode encodings, conversion                 from/to UCS-2 is automatically changed to use UTF-8.  You                 cannot use UCS-2 in a string anyway, because of the NUL bytes.                 Can also be used as a method:                         GetText()->iconv('latin1', 'utf-8')                                                         indent() indent({lnum})  The result is a Number, which is indent of line {lnum} in the                 current buffer.  The indent is counted in spaces, the value                 of 'tabstop' is relevant.  {lnum} is used just like in                 getline().                 When {lnum} is invalid -1 is returned.  In Vim9 script an                 error is given.                 Can also be used as a method:                         GetLnum()->indent() index({object}{expr} [, {start} [, {ic}]])                    index()                 Find {expr} in {object} and return its index.  See                 indexof() for using a lambda to select the item.                 If {object} is a List return the lowest index where the item                 has a value equal to {expr}.  There is no automatic                 conversion, so the String "4" is different from the Number 4.                 And the number 4 is different from the Float 4.0.  The value                 of 'ignorecase' is not used here, case matters as indicated by                 the {ic} argument.                 If {object} is Blob return the lowest index where the byte                 value is equal to {expr}.                 If {start} is given then start looking at the item with index                 {start} (may be negative for an item relative to the end).                 When {ic} is given and it is TRUE, ignore case.  Otherwise                 case must match.                 -1 is returned when {expr} is not found in {object}.                 Example:                         :let idx = index(words, "the")                         :if index(numbers, 123) >= 0                 Can also be used as a method:                         GetObject()->index(what) indexof({object}{expr} [, {opts}])                    indexof()                 Returns the index of an item in {object} where {expr} is                 v:true.  {object} must be a List or a Blob.                 If {object} is a List, evaluate {expr} for each item in the                 List until the expression is v:true and return the index of                 this item.                 If {object} is a Blob evaluate {expr} for each byte in the                 Blob until the expression is v:true and return the index of                 this byte.                 {expr} must be a string or Funcref.                 If {expr} is a string: If {object} is a List, inside                 {expr} v:key has the index of the current List item and                 v:val has the value of the item.  If {object} is a Blob,                 inside {expr} v:key has the index of the current byte and                 v:val has the byte value.                 If {expr} is a Funcref it must take two arguments:                         1. the key or the index of the current item.                         2. the value of the current item.                 The function must return TRUE if the item is found and the                 search should stop.                 The optional argument {opts} is a Dict and supports the                 following items:                     startidx    start evaluating {expr} at the item with this                                 index; may be negative for an item relative to                                 the end                 Returns -1 when {expr} evaluates to v:false for all the items.                 Example:                         :let l = [#{n: 10}, #{n: 20}, #{n: 30}]                         :echo indexof(l, "v:val.n == 20")                         :echo indexof(l, {i, v -> v.n == 30})                         :echo indexof(l, "v:val.n == 20", #{startidx: 1})                 Can also be used as a method:                         mylist->indexof(expr) input({prompt} [, {text} [, {completion}]])             input()                 The result is a String, which is whatever the user typed on                 the command-line.  The {prompt} argument is either a prompt                 string, or a blank string (for no prompt).  A '\n' can be used                 in the prompt to start a new line.                 The highlighting set with :echohl is used for the prompt.                 The input is entered just like a command-line, with the same                 editing commands and mappings.  There is a separate history                 for lines typed for input().                 Example:                         :if input("Coffee or beer? ") == "beer"                         :  echo "Cheers!"                         :endif                 If the optional {text} argument is present and not empty, this                 is used for the default reply, as if the user typed this.                 Example:                         :let color = input("Color? ", "white")                 The optional {completion} argument specifies the type of                 completion supported for the input.  Without it completion is                 not performed.  The supported completion types are the same as                 that can be supplied to a user-defined command using the                 "-complete=" argument.  Refer to :command-completion for                 more information.  Example:                         let fname = input("File: ", "", "file")                 NOTE: This function must not be used in a startup file, for                 the versions that only run in GUI mode (e.g., the Win32 GUI).                 Note: When input() is called from within a mapping it will                 consume remaining characters from that mapping, because a                 mapping is handled like the characters were typed.                 Use inputsave() before input() and inputrestore()                 after input() to avoid that.  Another solution is to avoid                 that further characters follow in the mapping, e.g., by using                 :execute or :normal.                 Example with a mapping:                         :nmap \x :call GetFoo()<CR>:exe "/" .. Foo<CR>                         :function GetFoo()                         :  call inputsave()                         :  let g:Foo = input("enter search pattern: ")                         :  call inputrestore()                         :endfunction                 Can also be used as a method:                         GetPrompt()->input() inputdialog({prompt} [, {text} [, {cancelreturn}]])             inputdialog()                 Like input(), but when the GUI is running and text dialogs                 are supported, a dialog window pops up to input the text.                 Example:                    :let n = inputdialog("value for shiftwidth", shiftwidth())                    :if n != ""                    :  let &sw = n                    :endif                 When the dialog is cancelled {cancelreturn} is returned.  When                 omitted an empty string is returned.                 Hitting <Enter> works like pressing the OK button.  Hitting                 <Esc> works like pressing the Cancel button.                 NOTE: Command-line completion is not supported.                 Can also be used as a method:                         GetPrompt()->inputdialog() inputlist({textlist})                                   inputlist()                 {textlist} must be a List of strings.  This List is                 displayed, one string per line.  The user will be prompted to                 enter a number, which is returned.                 The user can also select an item by clicking on it with the                 mouse, if the mouse is enabled in the command line ('mouse' is                 "a" or includes "c").  For the first string 0 is returned.                 When clicking above the first item a negative number is                 returned.  When clicking on the prompt one more than the                 length of {textlist} is returned.                 Make sure {textlist} has less than 'lines' entries, otherwise                 it won't work.  It's a good idea to put the entry number at                 the start of the string.  And put a prompt in the first item.                 Example:                         let color = inputlist(['Select color:', '1. red',                                 \ '2. green', '3. blue'])                 Can also be used as a method:                         GetChoices()->inputlist() inputrestore()                                          inputrestore()                 Restore typeahead that was saved with a previous inputsave().                 Should be called the same number of times inputsave() is                 called.  Calling it more often is harmless though.                 Returns TRUE when there is nothing to restore, FALSE otherwise. inputsave()                                             inputsave()                 Preserve typeahead (also from mappings) and clear it, so that                 a following prompt gets input from the user.  Should be                 followed by a matching inputrestore() after the prompt.  Can                 be used several times, in which case there must be just as                 many inputrestore() calls.                 Returns TRUE when out of memory, FALSE otherwise. inputsecret({prompt} [, {text}])                        inputsecret()                 This function acts much like the input() function with but                 two exceptions:                 a) the user's response will be displayed as a sequence of                 asterisks ("*") thereby keeping the entry secret, and                 b) the user's response will not be recorded on the input                 history stack.                 The result is a String, which is whatever the user actually                 typed on the command-line in response to the issued prompt.                 NOTE: Command-line completion is not supported.                 Can also be used as a method:                         GetPrompt()->inputsecret() insert({object}{item} [, {idx}])                      insert()                 When {object} is a List or a Blob insert {item} at the start                 of it.                 If {idx} is specified insert {item} before the item with index                 {idx}.  If {idx} is zero it goes before the first item, just                 like omitting {idx}.  A negative {idx} is also possible, see                 list-index.  -1 inserts just before the last item.                 Returns the resulting List or Blob.  Examples:                         :let mylist = insert([2, 3, 5], 1)                         :call insert(mylist, 4, -1)                         :call insert(mylist, 6, len(mylist))                 The last example can be done simpler with add().                 Note that when {item} is a List it is inserted as a single                 item.  Use extend() to concatenate Lists.                 Can also be used as a method:                         mylist->insert(item)                                         instanceof() E614 E616 E693 instanceof({object}{class})                 The result is a Number, which is TRUE when the {object}                 argument is a direct or indirect instance of a Class,                 Interface, or class :type alias specified by {class}.                 If {class} is varargs, the function returns TRUE when                 {object} is an instance of any of the specified classes.                 Example:                         instanceof(animal, Dog, Cat)                 Can also be used as a method:                         myobj->instanceof(mytype) interrupt()                                             interrupt()                 Interrupt script execution.  It works more or less like the                 user typing CTRL-C, most commands won't execute and control                 returns to the user.  This is useful to abort execution                 from lower down, e.g. in an autocommand.  Example:                 :function s:check_typoname(file)                 :   if fnamemodify(a:file, ':t') == '['                 :       echomsg 'Maybe typo'                 :       call interrupt()                 :   endif                 :endfunction                 :au BufWritePre * call s:check_typoname(expand('<amatch>')) invert({expr})                                          invert()                 Bitwise invert.  The argument is converted to a number.  A                 List, Dict or Float argument causes an error.  Example:                         :let bits = invert(bits)                 Can also be used as a method:                         :let bits = bits->invert() isabsolutepath({path})                                  isabsolutepath()                 The result is a Number, which is TRUE when {path} is an                 absolute path.                 On Unix, a path is considered absolute when it starts with '/'.                 On MS-Windows, it is considered absolute when it starts with an                 optional drive prefix and is followed by a '\' or '/'. UNC paths                 are always absolute.                 Example:                         echo isabsolutepath('/usr/share/')      " 1                         echo isabsolutepath('./foobar')         " 0                         echo isabsolutepath('C:\Windows')       " 1                         echo isabsolutepath('foobar')           " 0                         echo isabsolutepath('\\remote\file')    " 1                 Can also be used as a method:                         GetName()->isabsolutepath() isdirectory({directory})                                isdirectory()                 The result is a Number, which is TRUE when a directory                 with the name {directory} exists.  If {directory} doesn't                 exist, or isn't a directory, the result is FALSE.  {directory}                 is any expression, which is used as a String.                 Can also be used as a method:                         GetName()->isdirectory() isinf({expr})                                           isinf()                 Return 1 if {expr} is a positive infinity, or -1 a negative                 infinity, otherwise 0.                         :echo isinf(1.0 / 0.0)                         1                         :echo isinf(-1.0 / 0.0)                         -1                 Can also be used as a method:                         Compute()->isinf() islocked({expr})                                        islocked() E786                 The result is a Number, which is TRUE when {expr} is the                 name of a locked variable.                 The string argument {expr} must be the name of a variable,                 List item or Dictionary entry, not the variable itself!                 Example:                         :let alist = [0, ['a', 'b'], 2, 3]                         :lockvar 1 alist                         :echo islocked('alist')         " 1                         :echo islocked('alist[1]')      " 0                 When {expr} is a variable that does not exist -1 is returned.                 If {expr} uses a range, list or dict index that is out of                 range or does not exist you get an error message.  Use                 exists() to check for existence.                 In Vim9 script it does not work for local function variables.                 Can also be used as a method:                         GetName()->islocked() isnan({expr})                                           isnan()                 Return TRUE if {expr} is a float with value NaN.                         echo isnan(0.0 / 0.0)                         1                 Can also be used as a method:                         Compute()->isnan() items({dict})                                           items()                 Return a List with all the key-value pairs of {dict}.  Each                 List item is a list with two items: the key of a {dict}                 entry and the value of this entry.  The List is in arbitrary                 order.  Also see keys() and values().                 Example:                         for [key, value] in items(mydict)                            echo key .. ': ' .. value                         endfor                 A List or a String argument is also supported.  In these                 cases, items() returns a List with the index and the value at                 the index.                 Can also be used as a method:                         mydict->items() job_ functions are documented here: job-functions-details join({list} [, {sep}])                                  join()                 Join the items in {list} together into one String.                 When {sep} is specified it is put in between the items.  If                 {sep} is omitted a single space is used.                 Note that {sep} is not added at the end.  You might want to                 add it there too:                         let lines = join(mylist, "\n") .. "\n"                 String items are used as-is.  Lists and Dictionaries are                 converted into a string like with string().                 The opposite function is split().                 Can also be used as a method:                         mylist->join() js_decode({string})                                     js_decode()                 This is similar to json_decode() with these differences:                 - Object key names do not have to be in quotes.                 - Strings can be in single quotes.                 - Empty items in an array (between two commas) are allowed and                   result in v:none items.                 Can also be used as a method:                         ReadObject()->js_decode() js_encode({expr})                                       js_encode()                 This is similar to json_encode() with these differences:                 - Object key names are not in quotes.                 - v:none items in an array result in an empty item between                   commas.                 For example, the Vim object:                         [1,v:none,{"one":1},v:none]                 Will be encoded as:                         [1,,{one:1},,]                 While json_encode() would produce:                         [1,null,{"one":1},null]                 This encoding is valid for JavaScript. It is more efficient                 than JSON, especially when using an array with optional items.                 Can also be used as a method:                         GetObject()->js_encode() json_decode({string})                           json_decode() E491                 This parses a JSON formatted string and returns the equivalent                 in Vim values.  See json_encode() for the relation between                 JSON and Vim values.                 The decoding is permissive:                 - A trailing comma in an array and object is ignored, e.g.                   "[1, 2, ]" is the same as "[1, 2]".                 - Integer keys are accepted in objects, e.g. {1:2} is the                   same as {"1":2}.                 - More floating point numbers are recognized, e.g. "1." for                   "1.0", or "001.2" for "1.2". Special floating point values                   "Infinity", "-Infinity" and "NaN" (capitalization ignored)                   are accepted.                 - Leading zeroes in integer numbers are ignored, e.g. "012"                   for "12" or "-012" for "-12".                 - Capitalization is ignored in literal names null, true or                   false, e.g. "NULL" for "null", "True" for "true".                 - Control characters U+0000 through U+001F which are not                   escaped in strings are accepted, e.g. "       " (tab                   character in string) for "\t".                 - An empty JSON expression or made of only spaces is accepted                   and results in v:none.                 - Backslash in an invalid 2-character sequence escape is                   ignored, e.g. "\a" is decoded as "a".                 - A correct surrogate pair in JSON strings should normally be                   a 12 character sequence such as "\uD834\uDD1E", but                   json_decode() silently accepts truncated surrogate pairs                   such as "\uD834" or "\uD834\u"                                                                 E938                 A duplicate key in an object, valid in rfc7159, is not                 accepted by json_decode() as the result must be a valid Vim                 type, e.g. this fails: {"a":"b", "a":"c"}                 Can also be used as a method:                         ReadObject()->json_decode() json_encode({expr})                                     json_encode()                 Encode {expr} as JSON and return this as a string.                 The encoding is specified in:                 https://tools.ietf.org/html/rfc7159.html                 Vim values are converted as follows:   E1161                    Number             decimal number                    Float              floating point number                    Float nan            "NaN"                    Float inf            "Infinity"                    Float -inf           "-Infinity"                    String             in double quotes (possibly null)                    Funcref            not possible, error                    List               as an array (possibly null); when                                         used recursively: []                    Dict               as an object (possibly null); when                                         used recursively: {}                    Blob               as an array of the individual bytes                    v:false              "false"                    v:true               "true"                    v:none               "null"                    v:null               "null"                 Note that NaN and Infinity are passed on as values.  This is                 missing in the JSON standard, but several implementations do                 allow it.  If not then you will get an error.                 If a string contains an illegal character then the replacement                 character 0xfffd is used.                 Can also be used as a method:                         GetObject()->json_encode() keys({dict})                                            keys()                 Return a List with all the keys of {dict}.  The List is in                 arbitrary order.  Also see items() and values().                 Can also be used as a method:                         mydict->keys() keytrans({string})                                      keytrans()                 Turn the internal byte representation of keys into a form that                 can be used for :map.  E.g.                         :let xx = "\<C-Home>"                         :echo keytrans(xx)                         <C-Home>                 Can also be used as a method:                         "\<C-Home>"->keytrans()                                                         len() E701 len({expr})     The result is a Number, which is the length of the argument.                 When {expr} is a String or a Number the length in bytes is                 used, as with strlen().                 When {expr} is a List the number of items in the List is                 returned.                 When {expr} is a Blob the number of bytes is returned.                 When {expr} is a Dictionary the number of entries in the                 Dictionary is returned.                 Otherwise an error is given and returns zero.                 Can also be used as a method:                         mylist->len()                                                 libcall() E364 E368 libcall({libname}{funcname}{argument})                 Call function {funcname} in the run-time library {libname}                 with single argument {argument}.                 This is useful to call functions in a library that you                 especially made to be used with Vim.  Since only one argument                 is possible, calling standard library functions is rather                 limited.                 The result is the String returned by the function.  If the                 function returns NULL, this will appear as an empty string ""                 to Vim.                 If the function returns a number, use libcallnr()!                 If {argument} is a number, it is passed to the function as an                 int; if {argument} is a string, it is passed as a                 null-terminated string.                 This function will fail in restricted-mode.                 libcall() allows you to write your own 'plug-in' extensions to                 Vim without having to recompile the program.  It is NOT a                 means to call system functions!  If you try to do so Vim will                 very probably crash.                 For Win32, the functions you write must be placed in a DLL                 and use the normal C calling convention (NOT Pascal which is                 used in Windows System DLLs).  The function must take exactly                 one parameter, either a character pointer or a long integer,                 and must return a character pointer or NULL.  The character                 pointer returned must point to memory that will remain valid                 after the function has returned (e.g. in static data in the                 DLL).  If it points to allocated memory, that memory will                 leak away.  Using a static buffer in the function should work,                 it's then freed when the DLL is unloaded.                 WARNING: If the function returns a non-valid pointer, Vim may                 crash!  This also happens if the function returns a number,                 because Vim thinks it's a pointer.                 For Win32 systems, {libname} should be the filename of the DLL                 without the ".DLL" suffix.  A full path is only required if                 the DLL is not in the usual places.                 For Unix: When compiling your own plugins, remember that the                 object code must be compiled as position-independent ('PIC').                 {only in Win32 and some Unix versions, when the +libcall                 feature is present}                 Examples:                         :echo libcall("libc.so", "getenv", "HOME")                 Can also be used as a method, the base is passed as the                 third argument:                         GetValue()->libcall("libc.so", "getenv")                                                         libcallnr() libcallnr({libname}{funcname}{argument})                 Just like libcall(), but used for a function that returns an                 int instead of a string.                 {only in Win32 on some Unix versions, when the +libcall                 feature is present}                 Examples:                         :echo libcallnr("/usr/lib/libc.so", "getpid", "")                         :call libcallnr("libc.so", "printf", "Hello World!\n")                         :call libcallnr("libc.so", "sleep", 10)                 Can also be used as a method, the base is passed as the                 third argument:                         GetValue()->libcallnr("libc.so", "printf") line({expr} [, {winid}])                                line()                 The result is a Number, which is the line number of the file                 position given with {expr}.  The {expr} argument is a string.                 The accepted positions are:                      E1209                     .       the cursor position                     $       the last line in the current buffer                     'x      position of mark x (if the mark is not set, 0 is                             returned)                     w0      first line visible in current window (one if the                             display isn't updated, e.g. in silent Ex mode)                     w$      last line visible in current window (this is one                             less than "w0" if no lines are visible)                     v       In Visual mode: the start of the Visual area (the                             cursor is the end).  When not in Visual mode                             returns the cursor position.  Differs from '< in                             that it's updated right away.                 Note that a mark in another file can be used.  The line number                 then applies to another buffer.                 To get the column number use col().  To get both use                 getpos().                 With the optional {winid} argument the values are obtained for                 that window instead of the current window.                 Returns 0 for invalid values of {expr} and {winid}.                 Examples:                         line(".")               line number of the cursor                         line(".", winid)        idem, in window "winid"                         line("'t")              line number of mark t                         line("'" .. marker)     line number of mark marker                 To jump to the last known position when opening a file see                 last-position-jump.                 Can also be used as a method:                         GetValue()->line() line2byte({lnum})                                       line2byte()                 Return the byte count from the start of the buffer for line                 {lnum}.  This includes the end-of-line character, depending on                 the 'fileformat' option for the current buffer.  The first                 line returns 1. 'encoding' matters, 'fileencoding' is ignored.                 This can also be used to get the byte count for the line just                 below the last line:                         line2byte(line("$") + 1)                 This is the buffer size plus one.  If 'fileencoding' is empty                 it is the file size plus one.  {lnum} is used like with                 getline().  When {lnum} is invalid, or the +byte_offset                 feature has been disabled at compile time, -1 is returned.                 Also see byte2line()go and :goto.                 Can also be used as a method:                         GetLnum()->line2byte() lispindent({lnum})                                      lispindent()                 Get the amount of indent for line {lnum} according the lisp                 indenting rules, as with 'lisp'.                 The indent is counted in spaces, the value of 'tabstop' is                 relevant.  {lnum} is used just like in getline().                 When {lnum} is invalid -1 is returned.  In Vim9 script an                 error is given.                 Can also be used as a method:                         GetLnum()->lispindent() list2blob({list})                                       list2blob()                 Return a Blob concatenating all the number values in {list}.                 Examples:                         list2blob([1, 2, 3, 4]) returns 0z01020304                         list2blob([])           returns 0z                 Returns an empty Blob on error.  If one of the numbers is                 negative or more than 255 error E1239 is given.                 blob2list() does the opposite.                 Can also be used as a method:                         GetList()->list2blob() list2str({list} [, {utf8}])                             list2str()                 Convert each number in {list} to a character string can                 concatenate them all.  Examples:                         list2str([32])          returns " "                         list2str([65, 66, 67])  returns "ABC"                 The same can be done (slowly) with:                         join(map(list, {nr, val -> nr2char(val)}), '')                 str2list() does the opposite.                 When {utf8} is omitted or zero, the current 'encoding' is used.                 When {utf8} is TRUE, always return UTF-8 characters.                 With UTF-8 composing characters work as expected:                         list2str([97, 769])     returns "á"                 Returns an empty string on error.                 Can also be used as a method:                         GetList()->list2str() listener_add({callback} [, {buf}])                      listener_add()                 Add a callback function that will be invoked when changes have                 been made to buffer {buf}.                 {buf} refers to a buffer name or number. For the accepted                 values, see bufname().  When {buf} is omitted the current                 buffer is used.                 Returns a unique ID that can be passed to listener_remove().                 The {callback} is invoked with five arguments:                     bufnr       the buffer that was changed                     start       first changed line number                     end         first line number below the change                     added       number of lines added, negative if lines were                                 deleted                     changes     a List of items with details about the changes                 Example:             func Listener(bufnr, start, end, added, changes)               echo 'lines ' .. a:start .. ' until ' .. a:end .. ' changed'             endfunc             call listener_add('Listener', bufnr)                 The List cannot be changed.  Each item in "changes" is a                 dictionary with these entries:                     lnum        the first line number of the change                     end         the first line below the change                     added       number of lines added; negative if lines were                                 deleted                     col         first column in "lnum" that was affected by                                 the change; one if unknown or the whole line                                 was affected; this is a byte index, first                                 character has a value of one.                 When lines are inserted (not when a line is split, e.g. by                 typing CR in Insert mode) the values are:                     lnum        line above which the new line is added                     end         equal to "lnum"                     added       number of lines inserted                     col         1                 When lines are deleted the values are:                     lnum        the first deleted line                     end         the line below the first deleted line, before                                 the deletion was done                     added       negative, number of lines deleted                     col         1                 When lines are changed:                     lnum        the first changed line                     end         the line below the last changed line                     added       0                     col         first column with a change or 1                 The entries are in the order the changes were made, thus the                 most recent change is at the end.  The line numbers are valid                 when the callback is invoked, but later changes may make them                 invalid, thus keeping a copy for later might not work.                 The {callback} is invoked just before the screen is updated,                 when listener_flush() is called or when a change is being                 made that changes the line count in a way it causes a line                 number in the list of changes to become invalid.                 The {callback} is invoked with the text locked, see                 textlock.  If you do need to make changes to the buffer, use                 a timer to do this later timer_start().                 The {callback} is not invoked when the buffer is first loaded.                 Use the BufReadPost autocmd event to handle the initial text                 of a buffer.                 The {callback} is also not invoked when the buffer is                 unloaded, use the BufUnload autocmd event for that.                 Returns zero if {callback} or {buf} is invalid.                 Can also be used as a method, the base is passed as the                 second argument:                         GetBuffer()->listener_add(callback) listener_flush([{buf}])                                 listener_flush()                 Invoke listener callbacks for buffer {buf}.  If there are no                 pending changes then no callbacks are invoked.                 {buf} refers to a buffer name or number. For the accepted                 values, see bufname().  When {buf} is omitted the current                 buffer is used.                 Can also be used as a method:                         GetBuffer()->listener_flush() listener_remove({id})                                   listener_remove()                 Remove a listener previously added with listener_add().                 Returns FALSE when {id} could not be found, TRUE when {id} was                 removed.                 Can also be used as a method:                         GetListenerId()->listener_remove() localtime()                                             localtime()                 Return the current time, measured as seconds since 1st Jan                 1970.  See also strftime()strptime() and getftime(). log({expr})                                             log()                 Return the natural logarithm (base e) of {expr} as a Float.                 {expr} must evaluate to a Float or a Number in the range                 (0, inf].                 Returns 0.0 if {expr} is not a Float or a Number.                 Examples:                         :echo log(10)                         2.302585                         :echo log(exp(5))                         5.0                 Can also be used as a method:                         Compute()->log() log10({expr})                                           log10()                 Return the logarithm of Float {expr} to base 10 as a Float.                 {expr} must evaluate to a Float or a Number.                 Returns 0.0 if {expr} is not a Float or a Number.                 Examples:                         :echo log10(1000)                         3.0                         :echo log10(0.01)                   
__label__pos
0.994301
summaryrefslogtreecommitdiffstats path: root/xyz.openbmc_project.Led.Group.cpp blob: cd32b4b47af6ac30251476a8c2240a9319a483a9 (plain) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 #include <algorithm> #include <sdbusplus/server.hpp> #include <sdbusplus/exception.hpp> #include "xyz/openbmc_project/Led/Group/server.hpp" namespace sdbusplus { namespace xyz { namespace openbmc_project { namespace Led { namespace server { Group::Group(bus::bus& bus, const char* path) : _xyz_openbmc_project_Led_Group_interface( bus, path, _interface, _vtable, this) { } auto Group::asserted() const -> bool { return _asserted; } int Group::_callback_get_Asserted( sd_bus* bus, const char* path, const char* interface, const char* property, sd_bus_message* reply, void* context, sd_bus_error* error) { using sdbusplus::server::binding::details::convertForMessage; try { auto m = message::message(sd_bus_message_ref(reply)); auto o = static_cast<Group*>(context); m.append(convertForMessage(o->asserted())); } catch(sdbusplus::internal_exception_t& e) { sd_bus_error_set_const(error, e.name(), e.description()); return -EINVAL; } return true; } auto Group::asserted(bool value) -> bool { if (_asserted != value) { _asserted = value; _xyz_openbmc_project_Led_Group_interface.property_changed("Asserted"); } return _asserted; } int Group::_callback_set_Asserted( sd_bus* bus, const char* path, const char* interface, const char* property, sd_bus_message* value, void* context, sd_bus_error* error) { try { auto m = message::message(sd_bus_message_ref(value)); auto o = static_cast<Group*>(context); bool v{}; m.read(v); o->asserted(v); } catch(sdbusplus::internal_exception_t& e) { sd_bus_error_set_const(error, e.name(), e.description()); return -EINVAL; } return true; } namespace details { namespace Group { static const auto _property_Asserted = utility::tuple_to_array(message::types::type_id< bool>()); } } const vtable::vtable_t Group::_vtable[] = { vtable::start(), vtable::property("Asserted", details::Group::_property_Asserted .data(), _callback_get_Asserted, _callback_set_Asserted, vtable::property_::emits_change), vtable::end() }; } // namespace server } // namespace Led } // namespace openbmc_project } // namespace xyz } // namespace sdbusplus OpenPOWER on IntegriCloud
__label__pos
0.995438
Answered How do I edit the AsposeTemplateSyntax to add an extra carriage return? I've been testing serveral things in the AsposeTemplate to try and split this line into two but I can't seem to find it. Please find attached the picture of the output I'm getting and the template. Comments (1) photo 1 Good morning Artuur, I believe this is a configuration of Microsoft Word. The Bizagi Modeler tool to export a process documentation is standard, so if you need an specific configuration in the Word document, you will need a manual adjustment. Does this answer your question? Thank you for contacting us.
__label__pos
0.998768
Sign up for Hasura Newsletter Api Calls Now that we've successfully crafted the different queries, mutations and subscriptions needed for our matchmaking, we need to write some code to actually implement the logic. First off, we head into GameData.cs script which is contains some code that determines gameplay and whatnot. GameData.cs can be found in Assets/_Game/Scripts/Data/GameData.cs First off, ensure that we include the necessary namespaces we'd be utilizing. using System; using System.Collections.Generic; using System.Net.WebSockets; using System.Threading.Tasks; using Game.Manager; using GraphQlClient.Core; using GraphQlClient.EventCallbacks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnityEngine; using UnityEngine.Networking; using UnityEngine.SceneManagement; using Random = UnityEngine.Random; Next, we create a Battles class which would have fields matching that of our battles table in Hasura. This is useful in Deserializing the JSON data gotten from Hasura. public class Battles { public List<Battles> returning; public int id; public int shooter_id; public int defender_id; public Game.Data.User.Users shooter; public Game.Data.User.Users defender; public bool shooterReady; public bool defenderReady; } Note, the Battles class is created within the GameData class. As you can see, the Battles class mimics the type of object that can be returned from our Hasura backend. Next, we have to define some variables that would be used in our game logic. Add the code below beneath the other variables that have been declared in GameData.cs. public GraphApi shooterApi; [NonSerialized] public Battles battle; [NonSerialized] public float waitingTime; [NonSerialized] public ClientWebSocket battleCws; Let's understand the use of these variables. • GraphApi shooterApi: This is a variable to house our Api Reference. We need this reference to be able to use the queries, mutations and subscriptions we created. • Battles battle: This is a variable to house battle data gotten from our Hasura backend. Data gotten from the backend will be deserialized into this variable. • float waitingTime: This is the amount of time we intend to wait for an opponent to join our open games. If no one joins before the waiting time runs out, we delete the open battle. • ClientWebSocket battleCws: This is a ClientWebSocket reference we shall use for subscribing to our battles table from our Hasura backend. After adding these variables, your Variable Declaration region should look like #region Variable Declaration public Sounds sounds; public User user; public ColorScheme colorScheme; public GraphApi shooterApi; [NonSerialized] public GameManager gameManager; [NonSerialized] public MenuManager menuManager; [NonSerialized] public AudioSource sfxPlayer; [NonSerialized] public int bullets; [NonSerialized] public List<int> hitTargets; [NonSerialized] public List<int> defendedTargets; [NonSerialized] public bool shouldCount; [NonSerialized] public float time; [NonSerialized] public bool inBattle; public GameObject bulletPrefab; private Vector3 opponentPosition; private int misses; private bool attackComplete; private bool gameComplete; [NonSerialized] public Battles battle; [NonSerialized] public float waitingTime; [NonSerialized] public ClientWebSocket battleCws; #endregion Since GameData.cs is a ScriptableObject, it retains data. Therefore we need a function that resets it to default values. This is the Reset() function that is called when GameData is enabled. We'd add the default values for the new variables we just created by adding the code below into Reset() battle = null; battleCws = null; waitingTime = 20; Your entire Reset() function should look like this. public void Reset(){ bullets = user.role == User.Role.SHOOTER ? 7 : 10; hitTargets = new List<int>(); defendedTargets = new List<int>(); shouldCount = false; time = 0; gameComplete = false; attackComplete = false; misses = 0; opponentPosition = new Vector3(0, 1, 75); battle = null; battleCws = null; waitingTime = 20; } Api Calls We've created variables but now we must write the functions that will get information from our backend. Copy and paste the code below into GameData.cs and function shall be explained. #region Api Calls public async Task<List<Battles>> GetOnlineBattles(){ GraphApi.Query onlineBattle = shooterApi.GetQueryByName("GetOnlineBattles", GraphApi.Query.Type.Query); UnityWebRequest request = await shooterApi.Post(onlineBattle); string result = request.downloadHandler.text; return JsonConvert.DeserializeObject<List<Battles>>(RemoveData(result, onlineBattle.queryString)); } public async Task<Battles> CreateBattle(){ GraphApi.Query createBattle = shooterApi.GetQueryByName("CreateBattle", GraphApi.Query.Type.Mutation); createBattle.SetArgs(new{objects = new{shooter_id = 1}}); UnityWebRequest request = await shooterApi.Post(createBattle); string result = request.downloadHandler.text; return JsonConvert.DeserializeObject<Battles>(RemoveData(result, createBattle.queryString)); } private async void UpdateShooterReady(){ GraphApi.Query updateBattle = shooterApi.GetQueryByName("UpdateOnlineBattle", GraphApi.Query.Type.Mutation); updateBattle.SetArgs(new{where = new{id = new{_eq = battle.id}}, _set = new{shooterReady = true}}); await shooterApi.Post(updateBattle); } public async Task<Battles> UpdateBattle(int id){ GraphApi.Query updateBattle = shooterApi.GetQueryByName("UpdateOnlineBattle", GraphApi.Query.Type.Mutation); updateBattle.SetArgs(new {where = new{id = new{_eq = id}}, _set = new{defender_id = 2, defenderReady = true}}); UnityWebRequest request = await shooterApi.Post(updateBattle); string result = request.downloadHandler.text; return JsonConvert.DeserializeObject<Battles>(RemoveData(result, updateBattle.queryString)); } private async Task DeleteBattles(){ GraphApi.Query deleteBattle = shooterApi.GetQueryByName("DeleteBattle", GraphApi.Query.Type.Mutation); deleteBattle.SetArgs(new{where = new{id = new{_eq = battle?.id}}}); await shooterApi.Post(deleteBattle); } public async Task DeleteOldBattles(){ GraphApi.Query deleteBattle = shooterApi.GetQueryByName("DeleteOldBattles", GraphApi.Query.Type.Mutation); deleteBattle.SetArgs(new{where = new{}}); await shooterApi.Post(deleteBattle); } public async void BattleSubscribe(int battleId){ GraphApi.Query battleSubscribe = shooterApi.GetQueryByName("SubscribeToBattle", GraphApi.Query.Type.Subscription); battleSubscribe.SetArgs(new{id = battleId}); battleCws = await shooterApi.Subscribe(battleSubscribe, "battle"); } private void ReceiveBattleData(OnSubscriptionDataReceived subscriptionDataReceived){ Debug.Log(subscriptionDataReceived.data); battle = JsonConvert.DeserializeObject<Battles>(RemoveSubscriptionData(subscriptionDataReceived.data, shooterApi.GetQueryByName("SubscribeToBattle", GraphApi.Query.Type.Subscription).queryString)); if (battle == null){ shooterApi.CancelSubscription(battleCws, "battle"); return; } if (!battle.shooterReady && battle.defenderReady){ string opponentName = user.role == User.Role.SHOOTER ? battle.defender.username : battle.shooter.username; menuManager.SetWaitingText($"Found an opponent. {opponentName}"); waitingTime = 10; if (user.role == User.Role.SHOOTER) UpdateShooterReady(); } if (battle.shooterReady && battle.defenderReady && SceneManager.GetActiveScene().buildIndex == 0){ string opponentName = user.role == User.Role.SHOOTER ? battle.defender.username : battle.shooter.username; menuManager.SetWaitingText($"Entering battle against. {opponentName}"); if (!inBattle){ inBattle = true; } menuManager.BattleAnimation(); } } public async void StartWaiting(){ while (waitingTime >= 0){ await new WaitForSecondsRealtime(1); waitingTime--; if (battle != null){ if (battle.shooterReady && battle.defenderReady) return; } } inBattle = false; menuManager.SetWaitingText("No opponent found"); shooterApi.CancelSubscription(battleCws, "battle"); await new WaitForSecondsRealtime(1); await DeleteBattles(); menuManager.loading.Disappear(); menuManager.BringPreviousScreen(); Reset(); } #endregion Wow, that's a lot of code! Let's go into breaking it down one function at a time. Don't worry, they're pretty straightforward. Note: Don't forget to read the documentation for the graphql-client-unity as it'll help understand most of what is going on. GetOnlineBattles This function calls our GetOnlineBattles query, waits for data to be returned from our backend and deserializes that data. It returns the deserialized data as List<Battles> which is a list of Battles. CreateBattle This functions calls our CreateBattle mutation. The player that creates the battle is the Shooter and the player that joins is the Defender Within the function, createBattle.SetArgs(new{objects = new{shooter_id = 1}}); sets the shooter_id of the battle to be 1. Later on, when we've implemented authentication, we would be setting the shooter_id to be the id of the user but for now we use the id of one of the mock users we created. void UpdateShooterReady This function calls our UpdateOnlineBattle mutation. It is used to set the shooterReady flag of the battle to true. This can be seen in this line of code updateBattle.SetArgs(new{where = new{id = new{_eq = battle.id}}, _set = new{shooterReady = true}}); where the shooterReady flag of battle row of id = battle.id is set to true At the point we'd use this function, our Battles battle would already have been set. We would use this function to confirm the availability of the player that creates the battle after a player has joined. UpdateBattle This also calls our UpdateOnlineBattle mutation. But this function is used to join a battle. This can be seen by the arguments in updateBattle.SetArgs(new {where = new{id = new{_eq = id}}, _set = new{defender_id = 2, defenderReady = true}}); Which sets the defender_id of a battle to 2. Later on, when we've implemented authentication, we would be setting the defender_id to be the id of the user but for now we use the id of one of the mock users we created. DeleteBattles and DeleteOldBattles These are used to delete individual battles and all old battles from our database. void BattleSubscribe This calls our SubscribeToBattle subscription. We'd use this to watch out for changes to a created battle. If the player is the creator of the battle, data is returned when another player joins because the defender_id changes from null to that players id. If the player is the joiner of the battle, data is returned when the creator confirms availability because the shooterReady flag changes from false to true. void ReceiveBattleData This functions is called every time our subscription returns data from the backend. That is, it is called every time a change is made to the battle row we subscribed to. The function also has the data received within subscriptionDataReceived and this is deserialized into our battle variable so that our battle variable always reflects the current state of the battles row in our database. The contents of this function performs the flow chart in our Matchmaking void StartWaiting() This is used to wait for a particular time. If a battle isn't confirmed by then, it closes the subscription and resets the menu. Event Listening For our function void ReceiveBattleData(OnSubscriptionDataReceived subscriptionDataReceived) to be called every time we receive new subscription data, we have to listen to the right event. This is done by adding this lines of code private void OnEnable(){ OnSubscriptionDataReceived.RegisterListener(ReceiveBattleData); Reset(); } private void OnDisable(){ OnSubscriptionDataReceived.UnregisterListener(ReceiveBattleData); } References Go to GameData at Assets/_Game/ScriptableObjects/GameData and drag your Api Reference in the slot for shooterApi Shooter Api Reference Did you find this page helpful? Start with GraphQL on Hasura for Free • ArrowBuild apps and APIs 10x faster • ArrowBuilt-in authorization and caching • Arrow8x more performant than hand-rolled APIs Promo footer illustration Brand logo © 2021 Hasura Inc. All rights reserved Github Titter Discord Facebook Instagram Youtube Linkedin
__label__pos
0.762178
Vladimir Mootin Vladimir Mootin - 8 months ago 49 ASP.NET (C#) Question How to change img src in view MVC This is my image: <img id="1star" src="~/Content/Images/emptystar.png" onmouseover="setStars(1)" onmouseout="setStarsBack()" onclick="location.href='@Url.Action("SetRating", "CreativeModels", new { id = GlobalVariables.CurrentBookId, rating = 1 })'" /> this is the code of function that should change the image source: function setStars(amount) { if (amount > 0) { document.getElementById("1star").src = "~/Content/Images/filledstar.png"; } } It changes but browser says, that it can't load the image. This is what browser shows after moving mouse to the pictures: image of what browser shows And this is picture of how images looked before moving mouse to them: image with starts rendered How should I change src property? Answer The problem is not with the src attribute. That is changed correctly to what you've set it to. The problem is that it's pointing to the wrong directory. Assuming that you're using razor with your MVC solution try this out: function setStars(amount) { if (amount > 0) { document.getElementById("1star").src = "@Url.Content("~/Content/Images/filledstar.png")"; } }
__label__pos
0.986967
Friday, January 14, 2022 Is Agile Development viable for Business Central customizations?  by Steve Endow To the Agile Advocates (tm) who will immediately protest "Of course it is!" before reading on, I ask:   Hear me out. Reference:  What is Agile? Reference:  What is Agile Development? Reference:  Manifesto for Agile Software Development Book:  Agile Project Management for Dummies 3rd Edition Book:  Agile Estimating and Planning Book:  Scrum: The Art of Doing Twice the Work in Half the Time Disclaimer:  I'm not an Agile expert.  I'm someone who has tried to learn about Agile (on several occasions) and tried to understand if and how some Agile practices might be used in the projects I work on.  I'm asking lots of questions, for which I'm having a difficult time finding answers on my own through part time self-study. "Agile Development". It sounds cool. It sounds compelling. If you've ever suffered on a long, complex project that was over budget and seemed like it would never end, you'll likely appreciate some of the benefits that Agile claims to offer.  You'll read the Principles behind the Agile Manifesto and say, "Yes, please!" It definitely appeals to me. But then there is the reality that I personally work in.  Over the last 26 years, I have done consulting and development work mostly for "mid-market" customers in the US.  Based on my years of experience, admittedly with organizations and teams that didn't have "best practices", I'm having a difficult time trying to map Agile practices to the mid-market ERP projects that I typically encounter. My inquiry is not about whether Agile is good or bad.  I'm trying to understand if Agile is a good fit, or even a viable option, for my customers and my projects. Context:  Project Size and Scope The mid-market projects I've worked on over the years have been thousands of dollars or tens of thousands of dollars in consulting fees.  I think I worked on one large project that was probably well over $100,000, but that was very unusual for me.  So keep in mind that I'm used to delivering solutions to customers that usually cost under $30,000.  Quick.  Complete.  Inexpensive. More context:  None of my customers have dedicated internal project managers.  Very few of them have an internal ERP administrator.  And even fewer have an internal developer.  Also, my current team only has one dedicated developer, one technical project manager, and one functional project manager, so my organization is small as well. For contrast, I had a conversation recently with someone who explained that she won't even consider a consulting project under $6 million.  Six.  Million.  Dollars.  That number rolled off her tongue with a confidence and self-assuredness that amazed me.  A customer "only" wants to spend $4 million?  Nope, not worth her time.  I was speechless for several seconds as my brain tried to confirm the words I heard.  Let's be clear that those are NOT the projects I work on. Question:  Is there a minimum project budget required for Agile Development to be viable?   Related Question:  Is there a minimum project team size or staffing level required for an Agile Development project to be practical? I have several challenges trying to understand if, and how, Agile Development might be used with my projects, but I'll just mention 2 challenges for now, as those are two that I've investigated. Challenge #1:  Proposals and Estimates and Timelines My mid-market customers want 3 answers before approving a project. 1. What exactly am I going to get at the end of the project? 2. How much is this going to cost me? 3. When will the project be done? I started reading Agile Estimating and Planning, but although the book has English words and sentences in it, it felt to me like it was written in a different language.  My impression is that it is based on an entire foundation of Agile concepts that will require months of studying and learning for me to grasp the larger philosophy, terminology, practices, and communication techniques of Agile to even be minimally competent with Agile Estimating. I could be completely wrong due to my lack of knowledge and experience with Agile Estimating, but it seems like I would also have a very difficult time proposing an Agile Estimate to one of my customers.  Unless I'm directly and briefly answering the 3 questions above, they would also think I'm speaking a different language. Question:  Is Agile Estimating viable for a customer who has never been involved with an Agile project and never heard of Agile Estimating? Question:  If a customer wants answers to the 3 questions above before approving a project, does that immediately rule out Agile Estimating? Related question:  If I'm unable to use Agile Estimating on a project, does that automatically and completely rule out Agile Development for the project?  Or are there options for "sort-of-partial-Agile Development" practices on the project?  (see Challenge #2) Challenge #2:  Iteration and Integration is Costly (for my customers) For a moment, let's just assume that my projects aren't suited for an Agile Estimate, and a full blown Agile Development methodology is not appropriate for my projects or my customers.  No problem. Even though the project isn't "full Agile", I can still use some simple Agile tools and practices, right? For example, Business Central development projects can use: 1. Automated Testing and Acceptance Test Driven Development 2. Azure DevOps Pipelines for build automation 3. Continuous Deployment using Business Central Automation APIs  Given that these tools are available, I thought, "Awesome! Let's do some iterative development and crank out releases!"   Let's be "agile"!  Let's push beta releases!  Let's push minimum viable product and get early feedback!   Technically, the tools listed above worked well.  We produced prototypes and alpha releases and beta releases.  We were able to quickly iterate.  We were able to quickly fix bugs and add features and crank out new, tested releases with a click of a button using Azure DevOps. But after several months of trying to provide rapid releases to customers, I came to a realization. My customers are unable to keep up with a rapid release pace.  They simply do not have the time and attention to look at new releases every week or every two weeks, and perhaps not even once a month.   Our application consultants are also challenged to keep up.  They are very busy with dozens of tasks aside from customizations, and in most cases, a new deployment requires a call with the customer to get logged in and upload a new PTE or install a new AppSource release.  And then the customer needs to set aside time to review the changes, bug fixes, or new features. We have not yet had a customer where we could use automation APIs to automatically install or update an extension.  Even if we were able to achieve Continuous Deployment, the problem I'm seeing isn't a technical one, so I don't know that Continuous Deployment would help our projects be much more Agile. In one case, we've released a new version of a PTE and installed it in the customer's environment, and a month later realized that the customer still hadn't used or even reviewed the new release.  I assume they've been busy.  I'm guessing they've had other priorities.  Maybe there was a communication issue--and I'll take the blame for forgetting to follow up, as I'm also busy.  But that lack of follow up happened to provide a valuable lesson:  I learned that the customer still hadn't looked at a new release after a full month. In another case, we released a new version of an app for Business Central v19, but then realized the customer's environment was still on v18.5.  We then had to fix the BC upgrade issue, and now we're still waiting to schedule another call to get the new version installed.  Weeks have passed.  Again, the customer is busy.  A deployment call takes time.  Reviewing the new release takes time.  Etc. Etc. Etc. So even if we are able to technically deliver incremental releases as quickly as every week, I'm seeing some clear signals that my customers are simply unable to consume them at that pace.   Given this, is there really any value in pursuing Agile Development for my typical customer? Is It Really "Agile" At This Point? If I have a project that does not use Agile Estimating, and if the project does not use iterative development with multiple or rapid releases...is that a fundamentally non-Agile project? If I have a waterfall estimate plus a big-bang "Go Live" and a mad scramble of bug fixes and enhancements immediately after go live, I'm assuming that's non-Agile, even if we are using Automated Testing, Continuous Integration, and Continuous Deployment. It's Good to Know We Can Although our current customers may not be comfortable with an Agile Estimate, and may not have the capacity for an Agile project or rapid release cycles, I think it's good to know we seem to have the capability to iterate and deliver quickly if we ever need to.  And that we can at least use the technical tools to support rapid development, testing, and deployment, even if it isn't technically "Agile". Maybe I'll never work on a project that uses Agile Estimation or full Agile Development, but I'm still planning on using Automated Testing and DevOps Pipelines for all of our development projects.  That makes our lives easier, regardless of the release pace. Steve Endow is a Microsoft MVP in Los Angeles.  He works with Dynamics 365 Business Central. You can also find him on these platforms:  https://links.steveendow.com/ No comments: Post a Comment All comments must be reviewed and approved before being published. Your comment will not appear immediately. How many digits can a Business Central Amount field actually support?  by Steve Endow (If anyone has a technical explanation for the discrepancy between the Docs and the BC behavior, let me know!) On Sunday nig...
__label__pos
0.648362
StackOverflow Reputation Points, How to gain it? .. & Why? Not a single developer can live without using StackOverflow, almost daily 🙂, but should you care about building your reputation points on it? .. and how? What is Reputation? As per the official StackOverflow description for the reputation Reputation is a rough measurement of how much the community trusts you; it is earned by convincing your peers that you know what you’re talking about. The more reputation you earn, the more privileges you gain and the more tools you’ll have access to on the site – at the highest privilege levels, you’ll have access to many of the same tools available to the site moderators. That is intentional. We don’t run this site; the community does! The Why part Well, it is a reputation, which tells a lot about you, like: • How much the community trusts you • How you are willing to give the community back • Which specific set of technologies/frameworks are you interested in • Which specific tag you got most of your reputation in (which is probably the most important thing) • And even the way you communicate your thoughts in writing the answers, and how clear and concise are you The How part First let’s see what actions can give you the reputation points: • question is voted up: +10 • answer is voted up: +10 • answer is marked “accepted”: +15 (+2 to acceptor) • suggested edit is accepted: +2 (up to +1000 total per user) (when you get the privilege of reviewing/accepting other edits, you won’t get these points anymore) • bounty related points (It is a rare thing, so let’s not focus on it) but be careful, because you could also lose reputation when: • your question is voted down: −2 • your answer is voted down: −2 • you vote down an answer: −1 • you place a bounty on a question: − full bounty amount • one of your posts receives 6 spam or offensive flags: −100 Now concerning the strategy of getting the points, there are different types of people: • The Legends • The Moderator-like • The Lucky • The Addict • The Hustler • The Genuine (which is my way) The Legends are reserved for people like Jon Skeet, who was the first to pass a One Million reputation points .. yes, you read it right .. one million 🙂. The Moderator-like characters are like the pillars for the whole community, they keep it organized, they review every report/flag in there, & they care about moderating StackOverflow way more than just getting the reputation points, although they get a lot of points too 🙂. The Lucky ones are the ones who got a ton of reputation on a simple questions like pupeno got 120k reputation from a single line question asking about the difference between “git fetch” & “git pull” .. yes that is it 🙈. The Addict character is the person who opens StackOverflow almost everyday, seeking new questions in the fields he know, hoping he would be the first one to answer, which would give his answer a better opportunity in getting accepted or getting more up-votes, he is basically addicted to getting more and more reputation everyday. They can even go all the way, doing every activity mentioned in this paper “Building Reputation in StackOverflow: An Empirical Investigation” like: • answering questions related to tags with lower expertise density • answering questions promptly • being the first one to answer a question • being active during off peak hours • contributing to diverse areas The Hustler is another addict character but his moral compass is not pointing north (If you know what I mean). This character will down vote rival answers no matter how better they are, just to give his answer the better exposure. The Character would also copy other answers with some slight modifications, just to get some up-votes out of it … Simply, Don’t be a Hustler. The Genuine character, which is how I like doing things in an authentic way. For me this is the perfect balance between being passive (who doesn’t care about helping community) and being an addict (who wastes his/her own time contributing a lot in mostly an artificial way). For example, when I’m having a problem that I’m searching for its solution, I always keep an eye for all questions I find about this problem, specially the ones with poor answers or no answers at all, & when I find the perfect solution, here comes my time to add what I just found as an answer for all these related questions (whenever possible). enter image description here My genuine contributions led me to near 7K reputation points till now (2020), by just contributing when it is needed. The only problem with this approach is how to start, and how to be patient?! My advice about how to start is as follows: • Don’t be afraid to write a question or an answer, this is the only way you can get started • Keep an eye on the badges section of your profile, because it is designed to let you track the badges that will help you familiarize yourself with the community & how contributions are being made, like the badge for making a certain number of up-votes, or the other one for up-voting questions more than answers and so on • Keep an eye for questions you searched for, but didn’t like their answers, no matter how old they are, and no matter how many answers they have already, just give your own answer that you think it is better than the others • Keep your questions/answers very clear, short and to the point, and use visual aids whenever possible • Familiarize your self with the Markdown language, which will help you write better questions/answers on StackOverflow, & even on Github Examples: • I was making a chrome-extension where I needed to send a request to my server, it is easy to do it with jQuery’s $.ajax(), but it is not available inside the chrome-extension, so I searched for how to make the request with just vanilla Javascript and saw this question for “How to make an Ajax call without jQuery“. Question already has about 20 answers, with 2 of them exceeding 200 upvotes already, but non of the answers where helpful to me, answers where very long trying to be perfect, and some of them even tried to add the full html needed to make the call (I don’t know why on earth would they do that), So after I found a very concise way of sending the request, I made this answer and now it became the 4th up-voted answer in that question with 104 up-votes and counting 😎 • I had a problem that my node server wasn’t logging the time for its error logs, I searched and reached this question about “How to add dates to pm2 error logs?” but the answer I found was a small one with no details whatsoever on how should this line work! The unhelpful answer so, I searched through the library’s github repo & started digging until I found the exact issue & the exact commit where the logging feature was added to the library, so I added my own answer so I can add the needed details: My final answer and the answer not only got accepted, but got 88 up-votes till now and counting 😎 Conclusion • StackOverflow reputation is important for your career & personal branding. • Don’t be afraid to ask a question or write an answer • Be a Genuine contributor .. not a Hustler • Contribute to the community, & it will trust you with reputation points 🙂 Uploading Extremely Large Files, The Awesome Easy Way [Tus Server] Do you want your users to upload large files? .. I mean real large files, like multiple GB video .. Do your users live in places with a bad or unstable connection? .. If your answer is “yes”, then this article is exactly what you are looking for. Background At Chaino Social Network, we do care about our users, their feedback is our daily fuel, and a smooth enhanced UX is what we seek in everything we do for them. They asked for a video uploads feature, we made it for them .. they asked for a smaller processing time, we made it too .. they asked to upload a larger video files (up to 1 GB), again we made our precautions and increased the size to 1 GB .. but then we felt like hitting a wall, when we were swarmed by users’ feedback complaining that video uploads is easily interrupted by the bad networking, and the problem gets worse and worse when the files gets bigger and bigger where it becomes more vulnerable to interruptions and failures .. that is when we started our hunt for a solution. but let’s first see the current way of uploading. Problem with normal way of Uploading Our normal way of uploading is basically using the change event to start validating the file then uploading it as a multipart request where nginx does all the work for us then delivers the file path to our php backend where we can start processing the video, like the following: $('#uploadBtn').change(function () { var file = this.files[0]; if (typeof file === "undefined") { return; } // some validations goes here using `file.size` & `file.type` var myFormData = new FormData(); myFormData.append('videoFile', this.files[0]); // `videoFile` is the file name expected at the backend $.ajax({ url: '/file/post', type: 'POST', processData: false, contentType: false, dataType: 'json', data: myFormData, xhr: function () { // Custom XMLHttpRequest var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // Check if upload property exists myXhr.upload.addEventListener('progress', handleProgressBar, false); // For handling the progress of the upload } return myXhr; }, success: function(){ // Upload has been completed } }); }); function handleProgressBar(e) { if (e.lengthComputable) { // reflect values on your progress bar using `e.total` & `e.loaded` } } view raw app.js hosted with ❤ by GitHub <?php class FileController { public function postAction() { // Disable views/layout the way suites your framework if (!isset($_FILES['imageFile'])) { // Throw an exception or handle it your way } // Nginx already did all the work for us, & received the file in the `/tmp` folder $uploadedFile = $_FILES['imageFile']; $OriginalFileName = $uploadedFile['name']; $size = $uploadedFile['size']; $completeFilePath = $uploadedFile['tmp_name']; // Do some validations on file's type & file's size (using `$size` & `filesize($filePath)` // & if all is fine, then start processing your file here, & probably return a success message } } As you can see, both client & server sides expect the file to be sent in one shot no matter how big it is, but in the real world, networks get interrupted all the time, which forces the user to upload the file over & over again from the beginning! , which is super frustrating with large files like videos! In our hunt for a solution, At first we found some honorable mentions like Resumable.js, they didn’t really introduce a complete solution because most of these solutions focus only on the client side, where the server side is actually the real challenge! but then we found the only real complete solution out there Tus.io which was beyond our dreams! Solution .. The Awesome One Now we need a solution who can make 2 things: • Protect our users from network interruptions, where the solution should be able to automatically retry sending the file until network is hopefully stable again. • Gives our users a resumable upload in case of total network failures; so after the network comes back, users can continue uploading the file again where they left off. I know these requirements seem like a dream, but this is why Tus.io is so awesome in so many levels, simply this is how it works: How tus.io can increase both speed and reliability of file uploads (Illustration by Alexander Zaytsev) Tus is being adopted & trusted by many products now like Vimeo. Now, if we are going to cook this awesome meal, let’s first list our ingredients: • TusPHP for server side • We used php library, but actually you can use other server side implementations like node.js, Go or others • tus-js-client for client side • TusPHP already has a php client, but I think we all would agree to use the javascript implementations for the client over the php ones. Getting Started Let’s install TusPHP (for server-side) using composer: composer require ankitpokhrel/tus-php and installing tus-js-client (for client-side) using npm: npm install tus-js-client & here are the basic usage for them: var tus = require("tus-js-client"); $('#uploadBtn').change(function () { var file = this.files[0]; if (typeof file === "undefined") { return; } // some validations goes here using `file.size` & `file.type` var upload = new tus.Upload(file, { // https://github.com/tus/tus-js-client#tusdefaultoptions endpoint: "/tus", retryDelays: [0, 1000, 3000, 5000, 10000], metadata: { filename: file.name, filetype: file.type }, onError: function (error) { // Handle errors here }, onProgress: function (bytesUploaded, bytesTotal) { // Reflect values on your progress bar using `bytesTotal` & `bytesUploaded` }, onSuccess: function () { // Upload has been completed } }); // Start the upload upload.start(); }); view raw app.js hosted with ❤ by GitHub <?php class TusController { public function indexAction() { // Disable views/layout the way suites your framework $server = new TusPhp\Tus\Server(); // Using File Cache (over Redis) for simpler setup $server->setApiPath('/tus/index') // tus server endpoint. ->setUploadDir('/tmp'); // uploads dir. $response = $server->serve(); $response->send(); } } I tried this combination locally & everything worked like a charm. But then we deployed the solution to our Beta servers, and this is when the panic begins🙈. Production Shocks I know we deployed on Beta servers only, but let’s face it, most of us expect Beta to be like 5 minutes away from deploying on production .. which wasn’t our case 🙂. So, these are the problems we faced after using a real production-like environment: Permission Denied for File Cache Remember we used File Cache before for simplicity, well, the library expects you to pass a configuration for the cache file’s path or it will just make cache file inside the library’s folder in the vendor folder which gives us a Permission Denied error for trying to write to the vendor folder without the right permissions, so let’s just pass the right configuration with a path accessible by all server’s users like the /tmp folder (no need for keeping a long term cache, after all the cache won’t exceed 24 hours per file by design), and here is how you can do so: TusPhp\Config::set([ /** * File cache configs. * * Adding the cache in the '/tmp/' because it is the only place writable by * all users on the production server. */ 'file' => [ 'dir' => '/tmp/', 'name' => 'tus_php.cache', ], ]); HTTPS at the load-balancer Locally I’m using a self-signed certificate, so all the traffic reaching the backend is totally Https, but on the production, the ssl is at the load balancer level, which redirects the traffic to our servers as Http only, which tricked Tus into believing that the video url is in Http only, which breaks the uploading, so I had to fix the response headers to add the Https back again: // in the file controller before sending the response // get/set headers the way that suits your framework $location = $response->headers->get('location'); if (!empty($location)) {// `location` is sent to the client only the 1st time $location = preg_replace("/^http:/i", "https:", $location); $response->headers->set('location', $location); } PATCH is not supported Yet, still not working, it turns out that our production environment setup doesn’t allow PATCH requests, and this is where tus-js-client came to the rescue with its option overridePatchMethod: true which depends on usual POST requests instead. Re-Uploading starts from 0% !! Now, everything works fine. On my local machine uploads was lightening fast, so I couldn’t actually test the resumability part of our solution, so let’s try it on the beta, let’s cancel the upload at 40% and try to re-upload it again .. Oh Ooh, it started from 0%, What the heck just happened! After digging a lot in my server part (which was my suspect), it turns out that tus-js-client has an option called chunkSize with a default value of Infinity, which means upload the whole file at once 🙈 !!, so I just fixed it with specifying a chunk size of 1MB chunkSize: 1000 * 1000 Wrapping up the whole solution After putting it all together, here is our final version: var tus = require("tus-js-client"); $('#uploadBtn').change(function () { var file = this.files[0]; if (typeof file === "undefined") { return; } // some validations goes here using `file.size` & `file.type` var upload = new tus.Upload(file, { // https://github.com/tus/tus-js-client#tusdefaultoptions endpoint: "/tus", retryDelays: [0, 1000, 3000, 5000, 10000], overridePatchMethod: true, // Because production-servers-setup doesn't support PATCH http requests chunkSize: 1000 * 1000, // Bytes metadata: { filename: file.name, filetype: file.type }, onError: function (error) { // Handle errors here }, onProgress: function (bytesUploaded, bytesTotal) { // Reflect values on your progress bar using `bytesTotal` & `bytesUploaded` }, onSuccess: function () { // Upload has been completed } }); // Start the upload upload.start(); }); view raw app.js hosted with ❤ by GitHub <?php class TusController { public function indexAction() { // Disable views/layout the way suites your framework $server = $this->_getTusServer(); $response = $server->serve(); $this->_fixNonSecureLocationHeader($response); $response->send(); } private function _getTusServer() { TusPhp\Config::set([ /** * File cache configs. * * Adding the cache in the '/tmp/' because it is the only place writable by * all users on the production server. */ 'file' => [ 'dir' => '/tmp/', 'name' => 'tus_php.cache', ], ]); $server = new TusPhp\Tus\Server(); // Using File Cache (over Redis) for simpler setup $server->setApiPath('/tus/index') // tus server endpoint. ->setUploadDir('/tmp'); // uploads dir. return $server; } /** * The `location` header is where the client js library will upload the file through, * But, the load-balancer takes the `https` request & passes it as * `http` only to the servers, which is tricking Tus server, * so, we have to change it back here. * * @param type $response */ private function _fixNonSecureLocationHeader(&$response) { $location = $response->headers->get('location'); if (!empty($location)) {// `location` is sent to the client only the 1st time $location = preg_replace("/^http:/i", "https:", $location); $response->headers->set('location', $location); } } } Conclusion Before Tus I always thought that uploading files has only one traditional way, and no one can touch it, to the extent that I felt that it is pointless even searching for a solution, but never stop at your own boundaries, break them & go beyond, and you will reach new destinations you never thought possible. Now, uploading large files became dead simple, & I really want to thank the team behind Tus.io for what they did. PHP: How to append Google Analytics’ campaign parameters to all your emails at once? Using Google Analytics for tracking your users’ behavior is almost like using Air for breathing, then it comes its Custom Campaigns feature that will help you identify which of your marketing methods are more effective, or which campaigns emails gives you the better traffic, and so on. But, how could I append the custom campaign url parameters to all my emails at once? .. Or what if I want to know which of my transactional emails (notifications, invitations … ) is better in retaining users, how could I append a parameter containing email template’s name to all links in the email? & how to do it in a smart way? Answer #1 (the dumbest answer, but working!) Just go through every single link in your email templates & append your campaign parameters or template’s name referral. Not only this will cost you time & effort, but also you will bang your head against the wall when you try to change it later! Answer #2 (not recommended) Be lazy & use Regex to process the final email’s html (just before sending) & append whatever you like to all the links in it. You can use the one from this answer, or even this one, or even come up with your own super enhanced regex to do the job, it is up to you. Answer #3 (recommended) Why reinvent the wheel by doing your own Regex while you can use an official Dom parser of your choice, since I’m using PHP, then it comes to the awesome DOMDocument class & its pretty effective loadHTML() function & here comes the awesomeness (thx to this answer by Wrikken which I edited after trying it for real): <?php /** * appending campaign parameters to every single link `<a href=''></a>` * in the given $bodyHtml * * @param type $bodyHtml */ public function appendCampaignPrameters($bodyHtml, $utmCampaign) { $newParams = [ 'utm_source' => 'email', 'utm_medium' => 'email', 'utm_campaign' => $utmCampaign ]; $doc = new \DOMDocument(); $internalErrors = libxml_use_internal_errors(true); //http://stackoverflow.com/a/10482622/905801 $doc->loadHTML($bodyHtml); libxml_use_internal_errors($internalErrors); foreach ($doc->getElementsByTagName('a') as $link) { $url = parse_url($link->getAttribute('href')); $gets = $newParams; if (isset($url['query'])) { $query = []; parse_str($url['query'], $query); $gets = array_merge($query, $newParams); } $newHref = ''; if (isset($url['scheme'])) { $newHref .= $url['scheme'] . '://'; } if (isset($url['host'])) { $newHref .= $url['host']; } if (isset($url['port'])) { $newHref .= ':' . $url['port']; } if (isset($url['path'])) { $newHref .= $url['path']; } $newHref .= '?' . http_build_query($gets); if (isset($url['fragment'])) { $newHref .= '#' . $url['fragment']; } $link->setAttribute('href', $newHref); } return $doc->saveHTML(); } Why Answer #3 is the recommended one? Using a regex to parse only the links from the html’s string, seems a lot faster than parsing the whole dom elements, but does speed difference really matters when regex could give you incorrect results?! .. are you really willing to sacrifice speed for correctness? I don’t really think so! .. In this, I’ll go with Gary Pendergast‘s opinion that we shouldn’t use Regex, but we should use the Dom parsing libraries which are well tested in terms of speed & correctness. Hope you have found what you were looking for 🙂 , & thx for sharing it with more people who may need it too. Promises Do you use callbacks only, or .. Promises too? 😉 Amr Abdulrahman Should I read this? If you’re a JavaScript developer who still uses callbacks (on either the client side or server side) then this post is for you. If you don’t know what Promises are, then you probably will find it useful. Back in time, JavaScript was initially built to add interactivity to web pages and to be used on the client side. It has been designed to handle user interactions using events and event handlers. Also to make communications with the server. All of these stuff are Asynchronous operations. we can say: JavaScript is an event-driven programming language. which means, the flow of the program is determined by events such as user actions (mouse clicks, key presses) or messages from other programs/threads. So? So, JavaScript is designed over and encourages the usage of callbacks. Here’s a simple illustration of how a callback way works. #Main script wants to execute #Function_B after View original post 323 more words Android: Should you sign different Apps with the same Key or not? Releasing your first App is a great milestone, but with releasing the second one, here comes the question: Should I use the same key to sign my new app, or should I generate a new key for it?!! Well, it totally depends on your needs, so let’s see different needs: Why using same key for different apps? • When you want to use App modularity features (as recommended by the official documentation): Android allows apps signed by the same certificate to run in the same process, if the applications so requests, so that the system treats them as a single application. In this way you can deploy your app in modules, and users can update each of the modules independently. • When you want to share Code/Data securely between your apps through permissions (also as recommended by the official documentation): Android provides signature-based permissions enforcement, so that an app can expose functionality to another app that is signed with a specified certificate. By signing multiple apps with the same certificate and using signature-based permissions checks, your apps can share code and data in a secure manner. • If you want to avoid the hassle of managing different keys for different apps. Why using different keys for different apps? • If you are somehow paranoid about security (and you should), not to put all the eggs in one basket, which is highly recommended in this article. • When the apps are completely different & won’t ever use the app-modularity or Code/Data sharing described above. • When there is a chance (even a small one) that you will sell one of the apps separately in the future, then that app must have its own key from the beginning. Some useful numbers: As per this article, they made a study on August 2014, they found that Google Play has about 246,000 Android apps but only 11,681 certificates were found! The distribution of the number of apps sharing the same key is shown below. The X-axis is the number of apps sharing the same certificate. The Y-axis is the number of certificates. The distribution of the number of apps sharing the same key. The X-axis is the number of apps sharing the same certificate. The Y-axis is the number of certificates. Be aware that once you signed your app and uploaded it to Google Play, you can’t undo this step, you can’t sign it with a different certificate key. so make your decision wisely! I hope you find here the answer you were searching for, & hope you share your case with us in the comments .. Good Luck 🙂 Querying MongoDB ObjectId by Date range I had a situation where I wanted to query a collection in the production environment for a specific day, but the surprise for me was that the collection has no CreatedAt field in it in the first place :), so I had to rely on the ObjectId of the document. Searching around for a while I found this answer by kate, so I wanted to share it with all of you, & even shared it as an answer on another StackOverflow question. And here it goes, let’s assume we want to query for April 4th 2015, we can do it in the terminal like this: > var objIdMin = ObjectId(Math.floor((new Date('2015/4/4'))/1000).toString(16) + "0000000000000000") > var objIdMax = ObjectId(Math.floor((new Date('2015/4/5'))/1000).toString(16) + "0000000000000000") > db.collection.find({_id:{$gt: objIdMin, $lt: objIdMax}}).pretty() Android: Loading images Super-Fast like WhatsApp – Part 2 We discussed earlier in Part 1 of this tutorial how Zingoo team wants to deliver the best UX possible to the users, & because WhatsApp is doing a great job with images, so we watched what they are doing, like: • Photos are cached, so no need to load them every time you open the app. • They first show a very small thumbnail (about 10KB or less) until the real image is loaded, & this is the real pro-tip for their better UX. • Photos sizes range around 100KB, which loads the images pretty fast on most common mobile-network speeds. First 2 points are already discussed in part 1, so question here in part 2 is how could we compress images to be about 100KB to be sent easily over common mobile-networks. How is it done? After taking the picture and saving it to a file with path imagePath, we start compressing it to be ready for sending over network: ImageCompressionAsyncTask imageCompression = new ImageCompressionAsyncTask() { @Override protected void onPostExecute(byte[] imageBytes) { // image here is compressed & ready to be sent to the server } }; imageCompression.execute(imagePath);// imagePath as a string & here is what we do in ImageCompressionAsyncTask: public abstract class ImageCompressionAsyncTask extends AsyncTask<String, Void, byte[]> { @Override protected byte[] doInBackground(String... strings) { if(strings.length == 0 || strings[0] == null) return null; return ImageUtils.compressImage(strings[0]); } protected abstract void onPostExecute(byte[] imageBytes) ; } It is clear that the real juice exists in ImageUtils.compressImage(). Thanks to Ambalika Saha & her brilliant post that enabled me from using this solution in Zingoo, and even writing this post right here 🙂 . And here is my version of doing it: public class ImageUtils { private static final float maxHeight = 1280.0f; private static final float maxWidth = 1280.0f; public static byte[] compressImage(String imagePath) { Bitmap scaledBitmap = null; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile(imagePath, options); int actualHeight = options.outHeight; int actualWidth = options.outWidth; float imgRatio = (float) actualWidth / (float) actualHeight; float maxRatio = maxWidth / maxHeight; if (actualHeight > maxHeight || actualWidth > maxWidth) { if (imgRatio < maxRatio) { imgRatio = maxHeight / actualHeight; actualWidth = (int) (imgRatio * actualWidth); actualHeight = (int) maxHeight; } else if (imgRatio > maxRatio) { imgRatio = maxWidth / actualWidth; actualHeight = (int) (imgRatio * actualHeight); actualWidth = (int) maxWidth; } else { actualHeight = (int) maxHeight; actualWidth = (int) maxWidth; } } options.inSampleSize = ImageUtils.calculateInSampleSize(options, actualWidth, actualHeight); options.inJustDecodeBounds = false; options.inDither = false; options.inPurgeable = true; options.inInputShareable = true; options.inTempStorage = new byte[16 * 1024]; try { bmp = BitmapFactory.decodeFile(imagePath, options); } catch (OutOfMemoryError exception) { exception.printStackTrace(); } try { scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888); } catch (OutOfMemoryError exception) { exception.printStackTrace(); } float ratioX = actualWidth / (float) options.outWidth; float ratioY = actualHeight / (float) options.outHeight; float middleX = actualWidth / 2.0f; float middleY = actualHeight / 2.0f; Matrix scaleMatrix = new Matrix(); scaleMatrix.setScale(ratioX, ratioY, middleX, middleY); Canvas canvas = new Canvas(scaledBitmap); canvas.setMatrix(scaleMatrix); canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG)); ExifInterface exif; try { exif = new ExifInterface(imagePath); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0); Matrix matrix = new Matrix(); if (orientation == 6) { matrix.postRotate(90); } else if (orientation == 3) { matrix.postRotate(180); } else if (orientation == 8) { matrix.postRotate(270); } scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true); } catch (IOException e) { e.printStackTrace(); } ByteArrayOutputStream out = new ByteArrayOutputStream(); scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 85, out); return out.toByteArray(); } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } final float totalPixels = width * height; final float totalReqPixelsCap = reqWidth * reqHeight * 2; while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) { inSampleSize++; } return inSampleSize; } } I hope you like it. Android: Loading images Super-Fast like WhatsApp – Part 1 Zingoo is a new promising app that will rock your weekends, outings and any happening that you want to easily enjoy watching its moments over & over again (we are now doing the Android version, then the iOS one). Because we want Zingoo to be born strong, it has to deliver the best possible [UX] to all awesome-moments lovers around the world, which means we have to do our best in loading the images. Because we (at Begether) do listen to our users, we heard a lot of comments on how WhatsApp is loading images super-fast, so we dug deeper to know what we can do about it, & here is what we find, What does WhatsApp do? WhatsApp is doing the following (numbers are approximate): • Photos sizes range around 100KB, which loads the images pretty fast on most common mobile-network speeds. (part 2 explains how to achieve this) • Photos are cached, so no need to load them every time you open the app (almost no need to mention this 🙂 ). • They first show a very small thumbnail (about 10KB or less) until the real image is loaded, & this is the real pro-tip for their better UX. The last tip has a different variance by calculating the image dimensions & the approximate color of the image that will be shown & applying it to its placeholder, like the coming 3 minutes in this video: but still, the thumbnail is away more cooler, right? 😉 How is it done? To achieve the caching there are some good Android libraries out there that are doing a good job, but one of them is doing a way better than the others, which is Picasso. Both caching on disk & on memory are built under the hood, with a very developer-friendly API, I just love what Jake Wharton & his mates did for all of us, thanks guys. Using Picasso is pretty easy, just like this example one-liner: Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView); you just need first to add Picasso to your gradle files with the urlConnection library (according to this issue), like this: compile 'com.squareup.picasso:picasso:2.4.0' compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0' After solving the caching issue, we need to apply the thumbnail great tip, we need to use Picasso 2 times, one for loading the thumbnail and the other for loading the real image like the comment I made on this issue. Also to avoid the thumbnail’s pixlation effect (due to its small size), it would be better to make a blurring effect on it, WhatsApp's Thumbnail Loading Effect and here is how it is done: Transformation blurTransformation = new Transformation() { @Override public Bitmap transform(Bitmap source) { Bitmap blurred = Blur.fastblur(LiveImageView.this.context, source, 10); source.recycle(); return blurred; } @Override public String key() { return "blur()"; } }; Picasso.with(context) .load(thumbUrl) // thumbnail url goes here .placeholder(R.drawable.placeholder) .resize(imageViewWidth, imageViewHeight) .transform(blurTransformation) .into(imageView, new Callback() { @Override public void onSuccess() { Picasso.with(context) .load(url) // image url goes here .resize(imageViewWidth, imageViewHeight) .placeholder(imageView.getDrawable()) .into(imageView); } @Override public void onError() { } }); We used the Callback() functionality to start loading the full image after the thumbnail is completely loaded, with using the blurred thumbnail’s drawable as the new placeholder for the real image, & this is how the magic is being done right here :). Also the blurring made here is Blur.fastblur(), thanks to Michael Evans & his EtsyBlurExample example, you can find this class here. The only remaining part is how to compress the large images (which could be 2 to 4 MB) to be only about 100 KB, which is discussed in Part 2. Link All Node.js frameworks in one page Do you wanna use Node.js but don’t know which framework that suits your needs ? well, this page has all available frameworks known today categorized by: So, this is all you need to start choosing the framework that suits your needs, good luck. Tip: look for how many github stars the framework has got, it shows you how much it is trusted by people like you 😉 , which brings us to the incredible record by Meteor which is 22,337 stars till now!! Solved: Restarting node server may stop recurring Agenda jobs Node is the future, it is that simple. With that being said, one of the important things one will look for is how to start cron-jobs, is it by just using cron-tab to start a stand-alone script, or could it be a plugin inside the code base itself, like what is available in Node with its great npm set of packages that you can choose from, one of the very good packages for managing the cron-jobs is Agenda which comes with a great feature for visualizing your jobs by using Agenda-UI which looks like this: enter image description here Problem After starting using Agenda (0.6.27), I faced a serious issue when restarting my node server, because the recurring jobs (i.e agenda.every '30 minutes') may stop working for no reason, my code was like this: agenda.start() agenda.define 'my job', my_job_function agenda.every '30 minutes', 'my job' for a while, I thought in leaving Agenda for good, & using the widely known Cron instead, which is a really great alternative by the way, it is almost an imitation of the linux’s cron-tab interface, with an incredible number of downloads (95,483 downloads in the last month), The only thing kept me trying to find a solution is Agenda’s superior advantage by monitoring the jobs easily using its Agenda-UI interface, so I opened an issue on Agenda’s github page & digged in a little more until I found the solution. Solution 1 Since redefining our jobs on server start didn’t solve it, so I managed to remove the old broken recurring jobs when shutting down the server like this (you can add the following to your startup scripts like putting it in app.js): graceful = ()-> agenda.cancel repeatInterval: { $exists: true, $ne: null }, (err, numRemoved)-> agenda.stop ()-> process.exit 0 and with server start, the jobs will be redefined again & voila, I’m using this workaround now, & it is working like a charm. Solution 2 While observing the broken jobs & what causes them to stop working, I found that they are locked, because restarting the server while they are still running prevented them from releasing the lock, so droppedoncaprica has proposed the following solution to release all locks when starting the server: agenda._db.update {lockedAt: {$exists: true } }, { $set : { lockedAt : null } }, (e, numUnlocked)-> if e console.log e console.log "Unlocked #{numUnlocked} jobs." # redefine your jobs here Once Agenda solves this issue, I’ll update the post with the version containing the fix isA.
__label__pos
0.873061
module DRb Overview dRuby is a distributed object system for Ruby. It is written in pure Ruby and uses its own protocol. No add-in services are needed beyond those provided by the Ruby runtime, such as TCP sockets. It does not rely on or interoperate with other distributed object systems such as CORBA, RMI, or .NET. dRuby allows methods to be called in one Ruby process upon a Ruby object located in another Ruby process, even on another machine. References to objects can be passed between processes. Method arguments and return values are dumped and loaded in marshalled format. All of this is done transparently to both the caller of the remote method and the object that it is called upon. An object in a remote process is locally represented by a DRb::DRbObject instance. This acts as a sort of proxy for the remote object. Methods called upon this DRbObject instance are forwarded to its remote object. This is arranged dynamically at run time. There are no statically declared interfaces for remote objects, such as CORBA's IDL. dRuby calls made into a process are handled by a DRb::DRbServer instance within that process. This reconstitutes the method call, invokes it upon the specified local object, and returns the value to the remote caller. Any object can receive calls over dRuby. There is no need to implement a special interface, or mixin special functionality. Nor, in the general case, does an object need to explicitly register itself with a DRbServer in order to receive dRuby calls. One process wishing to make dRuby calls upon another process must somehow obtain an initial reference to an object in the remote process by some means other than as the return value of a remote method call, as there is initially no remote object reference it can invoke a method upon. This is done by attaching to the server by URI. Each DRbServer binds itself to a URI such as 'druby://example.com:8787'. A DRbServer can have an object attached to it that acts as the server's front object. A DRbObject can be explicitly created from the server's URI. This DRbObject's remote object will be the server's front object. This front object can then return references to other Ruby objects in the DRbServer's process. Method calls made over dRuby behave largely the same as normal Ruby method calls made within a process. Method calls with blocks are supported, as are raising exceptions. In addition to a method's standard errors, a dRuby call may also raise one of the dRuby-specific errors, all of which are subclasses of DRb::DRbError. Any type of object can be passed as an argument to a dRuby call or returned as its return value. By default, such objects are dumped or marshalled at the local end, then loaded or unmarshalled at the remote end. The remote end therefore receives a copy of the local object, not a distributed reference to it; methods invoked upon this copy are executed entirely in the remote process, not passed on to the local original. This has semantics similar to pass-by-value. However, if an object cannot be marshalled, a dRuby reference to it is passed or returned instead. This will turn up at the remote end as a DRbObject instance. All methods invoked upon this remote proxy are forwarded to the local object, as described in the discussion of DRbObjects. This has semantics similar to the normal Ruby pass-by-reference. The easiest way to signal that we want an otherwise marshallable object to be passed or returned as a DRbObject reference, rather than marshalled and sent as a copy, is to include the DRb::DRbUndumped mixin module. dRuby supports calling remote methods with blocks. As blocks (or rather the Proc objects that represent them) are not marshallable, the block executes in the local, not the remote, context. Each value yielded to the block is passed from the remote object to the local block, then the value returned by each block invocation is passed back to the remote execution context to be collected, before the collected values are finally returned to the local context as the return value of the method invocation. Examples of usage For more dRuby samples, see the samples directory in the full dRuby distribution. dRuby in client/server mode This illustrates setting up a simple client-server drb system. Run the server and client code in different terminals, starting the server code first. Server code require 'drb/drb' # The URI for the server to connect to URI="druby://localhost:8787" class TimeServer def get_current_time return Time.now end end # The object that handles requests on the server FRONT_OBJECT=TimeServer.new DRb.start_service(URI, FRONT_OBJECT) # Wait for the drb server thread to finish before exiting. DRb.thread.join Client code require 'drb/drb' # The URI to connect to SERVER_URI="druby://localhost:8787" # Start a local DRbServer to handle callbacks. # # Not necessary for this small example, but will be required # as soon as we pass a non-marshallable object as an argument # to a dRuby call. # # Note: this must be called at least once per process to take any effect. # This is particularly important if your application forks. DRb.start_service timeserver = DRbObject.new_with_uri(SERVER_URI) puts timeserver.get_current_time Remote objects under dRuby This example illustrates returning a reference to an object from a dRuby call. The Logger instances live in the server process. References to them are returned to the client process, where methods can be invoked upon them. These methods are executed in the server process. Server code require 'drb/drb' URI="druby://localhost:8787" class Logger # Make dRuby send Logger instances as dRuby references, # not copies. include DRb::DRbUndumped def initialize(n, fname) @name = n @filename = fname end def log(message) File.open(@filename, "a") do |f| f.puts("#{Time.now}: #{@name}: #{message}") end end end # We have a central object for creating and retrieving loggers. # This retains a local reference to all loggers created. This # is so an existing logger can be looked up by name, but also # to prevent loggers from being garbage collected. A dRuby # reference to an object is not sufficient to prevent it being # garbage collected! class LoggerFactory def initialize(bdir) @basedir = bdir @loggers = {} end def get_logger(name) if [email protected]_key? name # make the filename safe, then declare it to be so fname = name.gsub(/[.\/\\\:]/, "_") @loggers[name] = Logger.new(name, @basedir + "/" + fname) end return @loggers[name] end end FRONT_OBJECT=LoggerFactory.new("/tmp/dlog") DRb.start_service(URI, FRONT_OBJECT) DRb.thread.join Client code require 'drb/drb' SERVER_URI="druby://localhost:8787" DRb.start_service log_service=DRbObject.new_with_uri(SERVER_URI) ["loga", "logb", "logc"].each do |logname| logger=log_service.get_logger(logname) logger.log("Hello, world!") logger.log("Goodbye, world!") logger.log("=== EOT ===") end Security As with all network services, security needs to be considered when using dRuby. By allowing external access to a Ruby object, you are not only allowing outside clients to call the methods you have defined for that object, but by default to execute arbitrary Ruby code on your server. Consider the following: # !!! UNSAFE CODE !!! ro = DRbObject::new_with_uri("druby://your.server.com:8989") class << ro undef :instance_eval # force call to be passed to remote object end ro.instance_eval("`rm -rf *`") The dangers posed by instance_eval and friends are such that a DRbServer should only be used when clients are trusted. A DRbServer can be configured with an access control list to selectively allow or deny access from specified IP addresses. The main druby distribution provides the ACL class for this purpose. In general, this mechanism should only be used alongside, rather than as a replacement for, a good firewall. dRuby internals dRuby is implemented using three main components: a remote method call marshaller/unmarshaller; a transport protocol; and an ID-to-object mapper. The latter two can be directly, and the first indirectly, replaced, in order to provide different behaviour and capabilities. Marshalling and unmarshalling of remote method calls is performed by a DRb::DRbMessage instance. This uses the Marshal module to dump the method call before sending it over the transport layer, then reconstitute it at the other end. There is normally no need to replace this component, and no direct way is provided to do so. However, it is possible to implement an alternative marshalling scheme as part of an implementation of the transport layer. The transport layer is responsible for opening client and server network connections and forwarding dRuby request across them. Normally, it uses DRb::DRbMessage internally to manage marshalling and unmarshalling. The transport layer is managed by DRb::DRbProtocol. Multiple protocols can be installed in DRbProtocol at the one time; selection between them is determined by the scheme of a dRuby URI. The default transport protocol is selected by the scheme 'druby:', and implemented by DRb::DRbTCPSocket. This uses plain TCP/IP sockets for communication. An alternative protocol, using UNIX domain sockets, is implemented by DRb::DRbUNIXSocket in the file drb/unix.rb, and selected by the scheme 'drbunix:'. A sample implementation over HTTP can be found in the samples accompanying the main dRuby distribution. The ID-to-object mapping component maps dRuby object ids to the objects they refer to, and vice versa. The implementation to use can be specified as part of a DRb::DRbServer's configuration. The default implementation is provided by DRb::DRbIdConv. It uses an object's ObjectSpace id as its dRuby id. This means that the dRuby reference to that object only remains meaningful for the lifetime of the object's process and the lifetime of the object within that process. A modified implementation is provided by DRb::TimerIdConv in the file drb/timeridconv.rb. This implementation retains a local reference to all objects exported over dRuby for a configurable period of time (defaulting to ten minutes), to prevent them being garbage-collected within this time. Another sample implementation is provided in sample/name.rb in the main dRuby distribution. This allows objects to specify their own id or “name”. A dRuby reference can be made persistent across processes by having each process register an object using the same dRuby name. Attributes primary_server[RW] The primary local dRuby server. This is the server created by the start_service call. primary_server[RW] The primary local dRuby server. This is the server created by the start_service call. Public Class Methods config() click to toggle source Get the configuration of the current server. If there is no current server, this returns the default configuration. See current_server and DRbServer::make_config. # File lib/drb/drb.rb, line 1835 def config current_server.config rescue DRbServer.make_config end current_server() click to toggle source Get the 'current' server. In the context of execution taking place within the main thread of a dRuby server (typically, as a result of a remote call on the server or one of its objects), the current server is that server. Otherwise, the current server is the primary server. If the above rule fails to find a server, a DRbServerNotFound error is raised. # File lib/drb/drb.rb, line 1792 def current_server drb = Thread.current['DRb'] server = (drb && drb['server']) ? drb['server'] : @primary_server raise DRbServerNotFound unless server return server end fetch_server(uri) click to toggle source Retrieves the server with the given uri. See also regist_server and remove_server. # File lib/drb/drb.rb, line 1937 def fetch_server(uri) @server[uri] end front() click to toggle source Get the front object of the current server. This raises a DRbServerNotFound error if there is no current server. See current_server. # File lib/drb/drb.rb, line 1846 def front current_server.front end here?(uri) click to toggle source Is uri the URI for the current local server? # File lib/drb/drb.rb, line 1825 def here?(uri) current_server.here?(uri) rescue false # (current_server.uri rescue nil) == uri end install_acl(acl) click to toggle source Set the default ACL to acl. See DRb::DRbServer.default_acl. # File lib/drb/drb.rb, line 1891 def install_acl(acl) DRbServer.default_acl(acl) end install_id_conv(idconv) click to toggle source Set the default id conversion object. This is expected to be an instance such as DRb::DRbIdConv that responds to to_id and to_obj that can convert objects to and from DRb references. See DRbServer#default_id_conv. # File lib/drb/drb.rb, line 1883 def install_id_conv(idconv) DRbServer.default_id_conv(idconv) end regist_server(server) click to toggle source Registers server with DRb. This is called when a new DRb::DRbServer is created. If there is no primary server then server becomes the primary server. Example: require 'drb' s = DRb::DRbServer.new # automatically calls regist_server DRb.fetch_server s.uri #=> #<DRb::DRbServer:0x...> # File lib/drb/drb.rb, line 1915 def regist_server(server) @server[server.uri] = server mutex.synchronize do @primary_server = server unless @primary_server end end remove_server(server) click to toggle source Removes server from the list of registered servers. # File lib/drb/drb.rb, line 1924 def remove_server(server) @server.delete(server.uri) mutex.synchronize do if @primary_server == server @primary_server = nil end end end start_service(uri=nil, front=nil, config=nil) click to toggle source Start a dRuby server locally. The new dRuby server will become the primary server, even if another server is currently the primary server. uri is the URI for the server to bind to. If nil, the server will bind to random port on the default local host name and use the default dRuby protocol. front is the server's front object. This may be nil. config is the configuration for the new server. This may be nil. See DRbServer::new. # File lib/drb/drb.rb, line 1771 def start_service(uri=nil, front=nil, config=nil) @primary_server = DRbServer.new(uri, front, config) end stop_service() click to toggle source Stop the local dRuby server. This operates on the primary server. If there is no primary server currently running, it is a noop. # File lib/drb/drb.rb, line 1804 def stop_service @primary_server.stop_service if @primary_server @primary_server = nil end thread() click to toggle source Get the thread of the primary server. This returns nil if there is no primary server. See primary_server. # File lib/drb/drb.rb, line 1872 def thread @primary_server ? @primary_server.thread : nil end to_id(obj) click to toggle source Get a reference id for an object using the current server. This raises a DRbServerNotFound error if there is no current server. See current_server. # File lib/drb/drb.rb, line 1863 def to_id(obj) current_server.to_id(obj) end to_obj(ref) click to toggle source Convert a reference into an object using the current server. This raises a DRbServerNotFound error if there is no current server. See current_server. # File lib/drb/drb.rb, line 1855 def to_obj(ref) current_server.to_obj(ref) end uri() click to toggle source Get the URI defining the local dRuby space. This is the URI of the current server. See current_server. # File lib/drb/drb.rb, line 1813 def uri drb = Thread.current['DRb'] client = (drb && drb['client']) if client uri = client.uri return uri if uri end current_server.uri end Private Instance Methods config() click to toggle source Get the configuration of the current server. If there is no current server, this returns the default configuration. See current_server and DRbServer::make_config. # File lib/drb/drb.rb, line 1835 def config current_server.config rescue DRbServer.make_config end current_server() click to toggle source Get the 'current' server. In the context of execution taking place within the main thread of a dRuby server (typically, as a result of a remote call on the server or one of its objects), the current server is that server. Otherwise, the current server is the primary server. If the above rule fails to find a server, a DRbServerNotFound error is raised. # File lib/drb/drb.rb, line 1792 def current_server drb = Thread.current['DRb'] server = (drb && drb['server']) ? drb['server'] : @primary_server raise DRbServerNotFound unless server return server end fetch_server(uri) click to toggle source Retrieves the server with the given uri. See also regist_server and remove_server. # File lib/drb/drb.rb, line 1937 def fetch_server(uri) @server[uri] end front() click to toggle source Get the front object of the current server. This raises a DRbServerNotFound error if there is no current server. See current_server. # File lib/drb/drb.rb, line 1846 def front current_server.front end here?(uri) click to toggle source Is uri the URI for the current local server? # File lib/drb/drb.rb, line 1825 def here?(uri) current_server.here?(uri) rescue false # (current_server.uri rescue nil) == uri end install_acl(acl) click to toggle source Set the default ACL to acl. See DRb::DRbServer.default_acl. # File lib/drb/drb.rb, line 1891 def install_acl(acl) DRbServer.default_acl(acl) end install_id_conv(idconv) click to toggle source Set the default id conversion object. This is expected to be an instance such as DRb::DRbIdConv that responds to to_id and to_obj that can convert objects to and from DRb references. See DRbServer#default_id_conv. # File lib/drb/drb.rb, line 1883 def install_id_conv(idconv) DRbServer.default_id_conv(idconv) end regist_server(server) click to toggle source Registers server with DRb. This is called when a new DRb::DRbServer is created. If there is no primary server then server becomes the primary server. Example: require 'drb' s = DRb::DRbServer.new # automatically calls regist_server DRb.fetch_server s.uri #=> #<DRb::DRbServer:0x...> # File lib/drb/drb.rb, line 1915 def regist_server(server) @server[server.uri] = server mutex.synchronize do @primary_server = server unless @primary_server end end remove_server(server) click to toggle source Removes server from the list of registered servers. # File lib/drb/drb.rb, line 1924 def remove_server(server) @server.delete(server.uri) mutex.synchronize do if @primary_server == server @primary_server = nil end end end start_service(uri=nil, front=nil, config=nil) click to toggle source Start a dRuby server locally. The new dRuby server will become the primary server, even if another server is currently the primary server. uri is the URI for the server to bind to. If nil, the server will bind to random port on the default local host name and use the default dRuby protocol. front is the server's front object. This may be nil. config is the configuration for the new server. This may be nil. See DRbServer::new. # File lib/drb/drb.rb, line 1771 def start_service(uri=nil, front=nil, config=nil) @primary_server = DRbServer.new(uri, front, config) end stop_service() click to toggle source Stop the local dRuby server. This operates on the primary server. If there is no primary server currently running, it is a noop. # File lib/drb/drb.rb, line 1804 def stop_service @primary_server.stop_service if @primary_server @primary_server = nil end thread() click to toggle source Get the thread of the primary server. This returns nil if there is no primary server. See primary_server. # File lib/drb/drb.rb, line 1872 def thread @primary_server ? @primary_server.thread : nil end to_id(obj) click to toggle source Get a reference id for an object using the current server. This raises a DRbServerNotFound error if there is no current server. See current_server. # File lib/drb/drb.rb, line 1863 def to_id(obj) current_server.to_id(obj) end to_obj(ref) click to toggle source Convert a reference into an object using the current server. This raises a DRbServerNotFound error if there is no current server. See current_server. # File lib/drb/drb.rb, line 1855 def to_obj(ref) current_server.to_obj(ref) end uri() click to toggle source Get the URI defining the local dRuby space. This is the URI of the current server. See current_server. # File lib/drb/drb.rb, line 1813 def uri drb = Thread.current['DRb'] client = (drb && drb['client']) if client uri = client.uri return uri if uri end current_server.uri end
__label__pos
0.691675
aboutsummaryrefslogtreecommitdiffstats path: root/arch/x86/kernel/vmiclock_32.c blob: b1b5ab08b26eaaa26a955eb93f9502f7ed8e89ce (plain) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 /* * VMI paravirtual timer support routines. * * Copyright (C) 2007, VMware, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <linux/smp.h> #include <linux/interrupt.h> #include <linux/cpumask.h> #include <linux/clocksource.h> #include <linux/clockchips.h> #include <asm/vmi.h> #include <asm/vmi_time.h> #include <asm/arch_hooks.h> #include <asm/apicdef.h> #include <asm/apic.h> #include <asm/timer.h> #include <asm/i8253.h> #include <irq_vectors.h> #include "io_ports.h" #define VMI_ONESHOT (VMI_ALARM_IS_ONESHOT | VMI_CYCLES_REAL | vmi_get_alarm_wiring()) #define VMI_PERIODIC (VMI_ALARM_IS_PERIODIC | VMI_CYCLES_REAL | vmi_get_alarm_wiring()) static DEFINE_PER_CPU(struct clock_event_device, local_events); static inline u32 vmi_counter(u32 flags) { /* Given VMI_ONESHOT or VMI_PERIODIC, return the corresponding * cycle counter. */ return flags & VMI_ALARM_COUNTER_MASK; } /* paravirt_ops.get_wallclock = vmi_get_wallclock */ unsigned long vmi_get_wallclock(void) { unsigned long long wallclock; wallclock = vmi_timer_ops.get_wallclock(); // nsec (void)do_div(wallclock, 1000000000); // sec return wallclock; } /* paravirt_ops.set_wallclock = vmi_set_wallclock */ int vmi_set_wallclock(unsigned long now) { return 0; } /* paravirt_ops.sched_clock = vmi_sched_clock */ unsigned long long vmi_sched_clock(void) { return cycles_2_ns(vmi_timer_ops.get_cycle_counter(VMI_CYCLES_AVAILABLE)); } /* paravirt_ops.get_cpu_khz = vmi_cpu_khz */ unsigned long vmi_cpu_khz(void) { unsigned long long khz; khz = vmi_timer_ops.get_cycle_frequency(); (void)do_div(khz, 1000); return khz; } static inline unsigned int vmi_get_timer_vector(void) { #ifdef CONFIG_X86_IO_APIC return FIRST_DEVICE_VECTOR; #else return FIRST_EXTERNAL_VECTOR; #endif } /** vmi clockchip */ #ifdef CONFIG_X86_LOCAL_APIC static unsigned int startup_timer_irq(unsigned int irq) { unsigned long val = apic_read(APIC_LVTT); apic_write(APIC_LVTT, vmi_get_timer_vector()); return (val & APIC_SEND_PENDING); } static void mask_timer_irq(unsigned int irq) { unsigned long val = apic_read(APIC_LVTT); apic_write(APIC_LVTT, val | APIC_LVT_MASKED); } static void unmask_timer_irq(unsigned int irq) { unsigned long val = apic_read(APIC_LVTT); apic_write(APIC_LVTT, val & ~APIC_LVT_MASKED); } static void ack_timer_irq(unsigned int irq) { ack_APIC_irq(); } static struct irq_chip vmi_chip __read_mostly = { .name = "VMI-LOCAL", .startup = startup_timer_irq, .mask = mask_timer_irq, .unmask = unmask_timer_irq, .ack = ack_timer_irq }; #endif /** vmi clockevent */ #define VMI_ALARM_WIRED_IRQ0 0x00000000 #define VMI_ALARM_WIRED_LVTT 0x00010000 static int vmi_wiring = VMI_ALARM_WIRED_IRQ0; static inline int vmi_get_alarm_wiring(void) { return vmi_wiring; } static void vmi_timer_set_mode(enum clock_event_mode mode, struct clock_event_device *evt) { cycle_t now, cycles_per_hz; BUG_ON(!irqs_disabled()); switch (mode) { case CLOCK_EVT_MODE_ONESHOT: case CLOCK_EVT_MODE_RESUME: break; case CLOCK_EVT_MODE_PERIODIC: cycles_per_hz = vmi_timer_ops.get_cycle_frequency(); (void)do_div(cycles_per_hz, HZ); now = vmi_timer_ops.get_cycle_counter(vmi_counter(VMI_PERIODIC)); vmi_timer_ops.set_alarm(VMI_PERIODIC, now, cycles_per_hz); break; case CLOCK_EVT_MODE_UNUSED: case CLOCK_EVT_MODE_SHUTDOWN: switch (evt->mode) { case CLOCK_EVT_MODE_ONESHOT: vmi_timer_ops.cancel_alarm(VMI_ONESHOT); break; case CLOCK_EVT_MODE_PERIODIC: vmi_timer_ops.cancel_alarm(VMI_PERIODIC); break; default: break; } break; default: break; } } static int vmi_timer_next_event(unsigned long delta, struct clock_event_device *evt) { /* Unfortunately, set_next_event interface only passes relative * expiry, but we want absolute expiry. It'd be better if were * were passed an aboslute expiry, since a bunch of time may * have been stolen between the time the delta is computed and * when we set the alarm below. */ cycle_t now = vmi_timer_ops.get_cycle_counter(vmi_counter(VMI_ONESHOT)); BUG_ON(evt->mode != CLOCK_EVT_MODE_ONESHOT); vmi_timer_ops.set_alarm(VMI_ONESHOT, now + delta, 0); return 0; } static struct clock_event_device vmi_clockevent = { .name = "vmi-timer", .features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT, .shift = 22, .set_mode = vmi_timer_set_mode, .set_next_event = vmi_timer_next_event, .rating = 1000, .irq = 0, }; static irqreturn_t vmi_timer_interrupt(int irq, void *dev_id) { struct clock_event_device *evt = &__get_cpu_var(local_events); evt->event_handler(evt); return IRQ_HANDLED; } static struct irqaction vmi_clock_action = { .name = "vmi-timer", .handler = vmi_timer_interrupt, .flags = IRQF_DISABLED | IRQF_NOBALANCING, .mask = CPU_MASK_ALL, }; static void __devinit vmi_time_init_clockevent(void) { cycle_t cycles_per_msec; struct clock_event_device *evt; int cpu = smp_processor_id(); evt = &__get_cpu_var(local_events); /* Use cycles_per_msec since div_sc params are 32-bits. */ cycles_per_msec = vmi_timer_ops.get_cycle_frequency(); (void)do_div(cycles_per_msec, 1000); memcpy(evt, &vmi_clockevent, sizeof(*evt)); /* Must pick .shift such that .mult fits in 32-bits. Choosing * .shift to be 22 allows 2^(32-22) cycles per nano-seconds * before overflow. */ evt->mult = div_sc(cycles_per_msec, NSEC_PER_MSEC, evt->shift); /* Upper bound is clockevent's use of ulong for cycle deltas. */ evt->max_delta_ns = clockevent_delta2ns(ULONG_MAX, evt); evt->min_delta_ns = clockevent_delta2ns(1, evt); evt->cpumask = cpumask_of_cpu(cpu); printk(KERN_WARNING "vmi: registering clock event %s. mult=%lu shift=%u\n", evt->name, evt->mult, evt->shift); clockevents_register_device(evt); } void __init vmi_time_init(void) { /* Disable PIT: BIOSes start PIT CH0 with 18.2hz peridic. */ outb_p(0x3a, PIT_MODE); /* binary, mode 5, LSB/MSB, ch 0 */ vmi_time_init_clockevent(); setup_irq(0, &vmi_clock_action); } #ifdef CONFIG_X86_LOCAL_APIC void __devinit vmi_time_bsp_init(void) { /* * On APIC systems, we want local timers to fire on each cpu. We do * this by programming LVTT to deliver timer events to the IRQ handler * for IRQ-0, since we can't re-use the APIC local timer handler * without interfering with that code. */ clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL); local_irq_disable(); #ifdef CONFIG_X86_SMP /* * XXX handle_percpu_irq only defined for SMP; we need to switch over * to using it, since this is a local interrupt, which each CPU must * handle individually without locking out or dropping simultaneous * local timers on other CPUs. We also don't want to trigger the * quirk workaround code for interrupts which gets invoked from * handle_percpu_irq via eoi, so we use our own IRQ chip. */ set_irq_chip_and_handler_name(0, &vmi_chip, handle_percpu_irq, "lvtt"); #else set_irq_chip_and_handler_name(0, &vmi_chip, handle_edge_irq, "lvtt"); #endif vmi_wiring = VMI_ALARM_WIRED_LVTT; apic_write(APIC_LVTT, vmi_get_timer_vector()); local_irq_enable(); clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL); } void __devinit vmi_time_ap_init(void) { vmi_time_init_clockevent(); apic_write(APIC_LVTT, vmi_get_timer_vector()); } #endif /** vmi clocksource */ static cycle_t read_real_cycles(void) { return vmi_timer_ops.get_cycle_counter(VMI_CYCLES_REAL); } static struct clocksource clocksource_vmi = { .name = "vmi-timer", .rating = 450, .read = read_real_cycles, .mask = CLOCKSOURCE_MASK(64), .mult = 0, /* to be set */ .shift = 22, .flags = CLOCK_SOURCE_IS_CONTINUOUS, }; static int __init init_vmi_clocksource(void) { cycle_t cycles_per_msec; if (!vmi_timer_ops.get_cycle_frequency) return 0; /* Use khz2mult rather than hz2mult since hz arg is only 32-bits. */ cycles_per_msec = vmi_timer_ops.get_cycle_frequency(); (void)do_div(cycles_per_msec, 1000); /* Note that clocksource.{mult, shift} converts in the opposite direction * as clockevents. */ clocksource_vmi.mult = clocksource_khz2mult(cycles_per_msec, clocksource_vmi.shift); printk(KERN_WARNING "vmi: registering clock source khz=%lld\n", cycles_per_msec); return clocksource_register(&clocksource_vmi); } module_init(init_vmi_clocksource);
__label__pos
0.975027
Mac How to Clear DNS on Mac When it comes to cleaning up Mac, people think that Mac need not be cleaned up. But the fact is that the topic of “Mac Cleaning” has been hotly debated. Although the optimization of Mac OS X is better, many small invalid data files will be automatically sorted and removed. Most time some larger data files still remain in the system, which is actually the main reason for less available space on your Mac. As your Mac is slowing down, one of the reasons is that a lot of DNS caches are generated. You can learn how to clean up DNS cache to speed up your Mac. How does it create DNS cache on macOS? Its formation is because the Mac system automatically produces the “local DNS cache” in order to facilitate our access to the same website. When we visit the correct website, the system will store the result, which is the DNS cache. How do we clear the DNS cache? 1. Manual cleaning of DNS cache In Mac OS, we can enter the command “lookupd -flushcache” or “type dscacheutil -flushcache” directly in the Terminal window to clear and refresh the DNS parser cache. But most of the time we don’t remember what command text we need to enter, so we can use another method to clear it. 2. Use CleanMyMac to clear DNS cache in Mac CleanMyMac is good at Mac cleaning, including Mac cache cleaning, which is easy to operate. After starting CleanMyMac and choose Maintenance, we will see several system maintenance options listed on the right, including Flush DNS Cache. We can clean up at any time. Try It Free CleanMyMac provides you with timely suggestions, organizations, updates and protections of your Mac in an extremely fast and fashionable manner. It fully supports macOS 10.15 Catalina and Mojave; it shows you more intelligent algorithms and functions with its simple appearance and has its own security data, which can ensure that the software can correctly select and clean up the junk files on Mac. It is more secure and reliable! CleanMyMac, a cleaning software, can do a lot of maintenance cleaning for its Mac, including detecting malware and viruses, deleting plug-ins on Mac, cleaning up history on Mac and so on. Try It Free Related Articles Check Also Close Back to top button
__label__pos
0.714839
Notebook Search… 使括号平衡的最小交换次数 描述: 给定 2N 长度的字符串,包含N个 '[' ,N个 ']',计算使字符串平衡的最小交换次数 平衡字符串定义:S1[S2], 其中 S1,S2均为平衡字符串 输入: 2N长度字符串 输出: 最小交换次数 举例: Input : []][][ Output : 2 First swap: Position 3 and 4 [][]][ Second swap: Position 5 and 6 [][][] Input : [[][]] Output : 0 String is already balanced. Solution is below 思路 顺序遍历字符串,当遇到不匹配的']'时(遇到相应的'['之前),将其与之后最接近它的']'交换位置 实现 Python C++ def MinSwapBracketBalancing(Brackets: list): # 首先遍历字符串,获取所有左括号的位置 leftBrackets = [] leftBrackets.extend([ idx for idx, x in enumerate(Brackets) if x == '[']) if len(leftBrackets) != len(Brackets) // 2: return 0 count = 0 # 当前还未平衡的左括号数量 pos = 0 # 下一个左括号的位置 sum = 0 # 总共移动次数 i = 0 while i < len(Brackets): if Brackets[i] == '[': # 当前遍历括号为左括号 count += 1 pos += 1 else: # 当前括号为右括号 count -= 1 # 不平衡左括号 - 1 if count < 0: # 右括号在不平衡左括号之前出现 # 交换两括号位置 Brackets[i], Brackets[leftBrackets[pos]] = Brackets[leftBrackets[pos]],Brackets[i] sum += leftBrackets[pos] - i count = 0 pos += 1 i += 1 i += 1 return sum int MinSwapsBracketBalancing(string Brackets) { vector<int> leftBrackets; // Get positions of all left brackets for (auto i = 0;i<Brackets.size(); i++) { if (Brackets[i] == '[') leftBrackets.push_back(i); } auto count = 0; // Current unbalanced left brackets auto pos = 0; // Next position of next left brackets auto sum = 0; // Total moves to balance brackets for (auto i = 0; i < Brackets.size(); i++) { if (Brackets[i] == '[') { count++; pos++; } else if (--count < 0) { // Get unbalanced right bracket // Swap it with next left bracket swap(Brackets[i], Brackets[leftBrackets[pos]]); sum += leftBrackets[pos] - i; } } return sum; } Last modified 3yr ago Copy link On this page 描述: 输入: 输出: 举例: 思路 实现
__label__pos
0.983778
Click here to Skip to main content 16,000,638 members Articles / Desktop Programming / Win32 WinLamb: using C++11 Lambdas to Handle Win32 Messages Rate me: Please Sign up or sign in to vote. 4.83/5 (35 votes) 22 Sep 2019CPOL18 min read 43K   19   56   11 Introducing WinLamb, a modern C++11 object-oriented library to write native Windows programs Table of Contents 1. Spoilers 2. Getting Started 1. Concept 2. Technical Considerations 3. Setting Up a New Project 3. Creating and Using Windows 1. Creating the Main Window 2. Handling Messages 3. Dialog as Main Window 4. Using Controls 5. A Modal Popup Dialog 6. A Modeless Popup Dialog 7. A Custom Control 8. Dialog as a Control 4. Cracking Messages 1. Command and Notify Handling 2. Message Parameters Unpacked 3. Unpacking Common Control Notifications 5. Subclassing Controls 1. Installation and Message Handling 6. Final Topics 1. Window Types Summary 2. Default Message Processing 3. What’s Next? 7. Article History 1. Spoilers First of all, this article assumes the reader is familiar with native Win32 programming and C++11. Before explaining what it is, I’ll start showing what a Win32 program can look like with WinLamb. The following is a full program with a single window. Note that there’s no message loop, no window class registering, no switch statement or message maps. And two messages are handled, each with a C++11 lambda: C++ // Declaration: SimpleMainWindow.h #include "winlamb/window_main.h" class SimpleMainWindow : public wl::window_main { public: SimpleMainWindow(); }; C++ // Implementation: SimpleMainWindow.cpp #include "SimpleMainWindow.h" RUN(SimpleMainWindow); SimpleMainWindow::SimpleMainWindow() { setup.wndClassEx.lpszClassName = L"SOME_CLASS_NAME"; setup.title = L"This is my window"; setup.style |= WS_MINIMIZEBOX; on_message(WM_CREATE, [&](wl::params p)->LRESULT { set_text(L"A new title for the window"); return 0; }); on_message(WM_LBUTTONDOWN, [&](wl::params p)->LRESULT { set_text(L"Window clicked!"); return 0; }); } To compile this code, you’ll need a C++11 compiler. All examples on this article have been compiled and tested with Visual C++ 2017. 2. Getting Started 2.1. Concept The raw & usual way to create a native Windows C program is described in depth by Charles Petzold in his classic Programming Windows book. Since then, many object-oriented libraries – like MFC and WTL – have been written offering C++ approaches to deal with native Windows programming. WinLamb – an uninspired acronym of Windows and lambda – is another object-oriented C++ library. It’s a header-only library which depends on nothing but pure Win32 and the C++ Standard Template Library, and it heavily relies upon modern C++11 features (well, actually C++14 and C++17 too). WinLamb is a thin layer over Win32 API. It can be divided into three main parts: 1. Window management: the infrastructure which allows you to create several types of windows and use lambdas to handle their messages – this is the most import part of the library 2. Basic wrappers to most native Windows controls like edit box, listview, etc. 3. Utility classes like file I/O, device context, internet download, COM wrappers, etc. On the list above, (2) and (3) are optional. If you have another library or your own set of classes, you can use them instead. 2.2. Technical Considerations WinLamb is fully implemented using Unicode Win32, with wchar_t and std::wstring everywhere. Installation is pretty straightforward: since the library is head-only, you just need to download the files and #include them in your project. They should work right away. All the classes are enclosed within wl namespace. Since it heavily relies upon C++11 and even some C++14 and C++17 features, you need a compatible C++ compiler. Current version was developed and tested with Visual C++ 2017. Errors are reported by throwing exceptions. WinLamb doesn’t have any custom exception, it only throws ordinary STL exceptions. All exceptions inherit from std::exception, so if you catch it, you’re guaranteed to catch any possible exception from WinLamb. Last but not least: WinLamb isn’t an excuse to not learn Win32 – before start using WinLamb, I strongly advice the reader to learn the basics on how to write a Win32 program using plain C. WinLamb source is available on GitHub as open-source under the MIT license. 2.3. Setting Up a New Project WinLamb is a header-only C++ library. The most up-do-date code can be found at GitHub, you can clone the repository or simply download the files. The simplest way to have the library in your project is simply keep all the files in a subfolder called, for example, “winlamb”, then #include them in your sources. Here, it is presented how to create a fresh new WinLamb Win32 project using Visual C++ IDE, from scratch. You can skip this section straight into the code. To start, first create the new project: Image 1 Choose “Windows Desktop Wizard”. The “.NET Framework” option doesn”t matter, since we're writing a pure Win32 program, without the .NET Framework. Here, I named the project “example1”. Image 2 Choose “Windows Application”. Uncheck everything but “Empty project”. This will create a completely empty project for us. Image 3 Finally, create a subdirectory named, for example, “winlamb”, and put WinLamb files there. Then create your source files normally; you should be able to include WinLamb files now: Image 4 Notice that the library has an “internals” subdirectory. This is where all internal library files are located; you shouldn’t need to touch these. 3. Creating and Using Windows Once the project is ready, it’s time to use WinLamb to wrap up our Windows. 3.1. Creating the Main Window Under the most common cases, the first thing you must design when creating a Win32 program is the main window. So let’s start with the declaration of the main window class – in WinLamb, each window has a class. It’s a good idea to have 1 header and (at least) 1 source file for each window. Technically, the main window doesn’t need a header, but for consistency, let’s write one. All WinLamb library classes belong to the wl namespace. Our main window class will inherit from window_main class. Let’s also declare the constructor: C++ // Declaration: MyWindow.h #include "winlamb/window_main.h" class MyWindow : public wl::window_main { public: MyWindow(); }; For the program entry point, you can write your WinMain function and instantiate MyWindow manually, if you want. However, if you aren’t doing anything special on WinMain, you can simply use WinLamb’s RUN macro – the only macro in the whole library, I promise –, which will simply expand into a WinMain call instantiating your class on the stack. This is the macro call: C++ RUN(MyWindow); And then implement the class constructor. Thus, that’s what we have in our source file, so far: C++ // Implementation: MyWindow.cpp #include "MyWindow.h" RUN(MyWindow); // will generate a WinMain function MyWindow::MyWindow() { } If you compile and run this code, the window will fail to show, because we didn’t specify the window class name. When the class is instantiated, the base window_main will call RegisterClassEx internally, and it will use a WNDCLASSEX structure with a few predetermined values – these values, however, don’t specify the class name to be registered. The base class provides a setup member variable which holds all initialization values for the class. To an experienced Win32 programmer, the members of this structure will be familiar: they are the parameters of the CreateWindowEx function, plus the wndClassEx member, which is the WNDCLASSEX structure, which is passed to RegisterClassEx. This wndClassEx member, however, hides the members that are internally set by WinLamb. Thus, we must define the class name at lpszClassName member, and do this inside the constructor: C++ // Implementation: MyWindow.cpp #include "MyWindow.h" RUN(MyWindow); MyWindow::MyWindow() { setup.wndClassEx.lpszClassName = L"HAPPY_LITTLE_CLASS_NAME"; } The wndClassEx member has style, and setup itself has style and exStyle. These two fields are already filled with default flags, specified by WinLamb: C++ setup.wndClassEx.style = CS_DBLCLKS; setup.style = WS_CAPTION | WS_SYSMENU | WS_CLIPCHILDREN | WS_BORDER; You can overwrite these values, of course. However, they are common to most windows, and most of the time, you’ll just want to add a flag. For example, if you want your main window to be resizable and minimizable, you just need this: C++ setup.style |= (WS_SIZEBOX | WS_MINIMIZEBOX); Therefore, also adding the window title, we have: C++ // Implementation: MyWindow.cpp #include "MyWindow.h" RUN(MyWindow); MyWindow::MyWindow() { setup.wndClassEx.lpszClassName = L"HAPPY_LITTLE_CLASS_NAME"; setup.title = L"My first window"; setup.style |= (WS_SIZEBOX | WS_MINIMIZEBOX); } The program should compile and run fine now. Yes, this is a fully functional Win32 program, including window class registering, window creation, message loop dispatching and final cleanup – all this infrastructure code is transparent. Note: WinLamb classes make use of Set/GetWindowLongPtr with GWLP_USERDATA and DWLP_USER flags for storing context data. Since you have a class for your window, where you can have all the members you want, I can’t really imagine a reason for using these on your code, but I’m warning you just in case: don’t use GWLP_USERDATA and DWLP_USER to store your data. 3.2. Handling Messages The traditional way to handle window messages is a big switch statement inside the WNDPROC function. Some libraries define macros to avoid the “big switch”. In our program using WinLamb, we’ll use C++11 lambdas. The window_main base class provides the on_message member function, which receives two arguments: the message to be handled and a function to handle it: C++ void on_message(UINT message, std::function<LRESULT(wl::params)>&& func); The easiest way to use it is passing an unnamed lambda function inline. For example, let’s handle the WM_CREATE message in our main window class constructor: C++ MyWindow::MyWindow() { setup.wndClassEx.lpszClassName = L"HAPPY_LITTLE_CLASS_NAME"; on_message(WM_CREATE, [](wl::params p)->LRESULT { return 0; }); } The lambda receives a params argument, which has the WPARAM and LPARAM members – more on this later. Note that the lambda must return an LRESULT value, just like any ordinary WNDPROC message processing. Note: In an ordinary window, you would have to handle WM_DESTROY in order to call PostQuitMessage. WinLamb implements default message processing for a few messages, using the default behavior, so you don’t have to worry about them. But they can be overwritten if you need something specific – in the above example, if we write a handler to WM_DESTROY, the default library code would be completely bypassed. More on this later. Now, if you happen to have two messages which will demand the same processing, on_message also accepts an initializer_list as the first argument: C++ on_message({WM_LBUTTONUP, WM_RBUTTONUP}, [](wl::params p)->LRESULT { UINT currentMsg = p.message; return 0; }); This is functionally equivalent of: C++ switch (LOWORD(wParam)) { case WM_LBUTTONUP: case WM_RBUTTONUP: // some code... return 0; } Tip: If your window handles too many messages, the class constructor can become quite large and hard to follow. In these situations, breaking the handlers into member functions is helpful: C++ // Declaration: MyWindow.h class MyWindow : public wl::window_main { public: MyWindow(); private: void attachHandlers(); void evenMoreHandlers(); }; C++ // Implementation: MyWindow.cpp #include "MyWindow.h" RUN(MyWindow); MyWindow::MyWindow() { setup.wndClassEx.lpszClassName = L"HAPPY_LITTLE_CLASS_NAME"; attachHandlers(); evenMoreHandlers(); } void MyWindow::attachHandlers() { on_message(WM_CREATE, [](wl::params p)->LRESULT { return 0; }); on_message(WM_CLOSE, [](wl::params p)->LRESULT { return 0; }); } void MyWindow::evenMoreHandlers() { on_message(WM_SIZE, [](wl::params p)->LRESULT { WORD width = LOWORD(p.lParam); return 0; }); } To finally work with the window, the hwnd member function can be used to retrieve the window’s HWND: C++ on_message(WM_CREATE, [this](wl::params p)->LRESULT { SetWindowText(hwnd(), L"New window title"); return 0; }); But there’s a set_text method available to be used within the window, so: C++ on_message(WM_CREATE, [this](wl::params p)->LRESULT { set_text(L"New window title"); return 0; }); 3.3. Dialog as Main Window In the previous example, we created an ordinary main window – in pure Win32, it would be the equivalent of calling RegisterClassEx and CreateWindowEx, among other proceedings. But it is also possible to have a dialog box as the main window of your program. This possibility is covered in WinLamb, if you inherit your main window from the dialog_main class: C++ // Declaration: FirstDialog.h #include "winlamb/dialog_main.h" class FirstDialog : public wl::dialog_main { public: FirstDialog(); }; With dialogs, you don’t deal with WNDCLASSEX directly, there’s no need to register a window class name. That’s why the setup member variable doesn’t have the wndClassEx member, instead it allows you to specify the ID of the dialog resource to be loaded. Usually, dialog resources are created with resource editors, like the one Visual Studio has. An example of a dialog creation can be seen here. Now, assuming the dialog resource is already created, let’s use the dialog ID: C++ // Implementation: FirstDialog.cpp #include "FirstDialog.h" #include "resource.h" // contains the dialog resource ID RUN(FirstDialog); FirstDialog::FirstDialog() { setup.dialogId = IDD_MY_FIRST_DIALOG; // specify dialog ID on_message(WM_INITDIALOG, [this](wl::params p)->INT_PTR { set_text(L"A new title for the dialog"); return TRUE; }); } Here, on_message has some minor differences to follow the dialog box DLGPROC message processing, like the INT_PTR return type, and returning TRUE instead of zero. 3.4. Using Controls Still on the previous example, let’s say the dialog resource has an edit box, with IDC_EDIT1 as the resource ID. WinLamb has the textbox class, which wraps an edit box. To use it, declare the textbox object as a member of the parent class: C++ // Declaration: FirstDialog.h #include "winlamb/dialog_main.h" #include "winlamb/textbox.h" class FirstDialog : public wl::dialog_main { private: wl::textbox edit1; // our control object public: FirstDialog(); }; On the control object, call assign method, which will call GetDlgItem and store the HWND inside the object. After that, the widget is ready to be used: C++ // Implementation: FirstDialog.cpp #include "FirstDialog.h" #include "resource.h" // contains the dialog resource IDs RUN(FirstDialog); FirstDialog::FirstDialog() { setup.dialogId = IDD_MY_FIRST_DIALOG; on_message(WM_INITDIALOG, [this](wl::params p)->INT_PTR { edit1.assign(this, IDC_EDIT1) .set_text(L"This is the edit box.") .set_focus(); return TRUE; }); } Note that assign and set_text methods both return a reference to the object itself, so other method calls can be chained. This is a common behavior to most objects in WinLamb. 3.5. A Modal Popup Dialog A modal popup dialog is a window created via DialogBoxParam. Let’s implement a modal dialog with its header and source files. Then, we will instantiate this modal in a parent window. This is the header of our modal dialog, which inherits from dialog_modal class: C++ // Declaration: MyModal.h #include "winlamb/dialog_modal.h" class MyModal : public wl::dialog_modal { public: MyModal(); }; The implementation is pretty much like any other dialog window – you must inform the ID of the dialog resource to be loaded –, but remember modal dialogs are destroyed by calling EndDialog, with the second parameter of this function being the return value of the original dialog call. C++ // Implementation: MyModal.cpp #include "MyModal.h" #include "resource.h" // contains dialog resource ID MyModal::MyModal() { setup.dialogId = IDD_DIALOG2; on_message(WM_COMMAND, [this](wl::params p)->INT_PTR { if (LOWORD(p.wParam) == IDCANCEL) // the ESC key { EndDialog(hwnd(), 33); // modal will return 33, see the next example return TRUE; } return FALSE; }); } Now let’s revisit the implementation of our main window, which will now use the modal dialog by instantiating the object and calling the show method. Since the dialog is modal, the show method will block the execution and will return only after the dialog is closed. C++ // Implementation: MainWindow.cpp #include "MainWindow.h" #include "MyModal.h" // our modal dialog header RUN(MainWindow); MainWindow::MainWindow() { on_message(WM_COMMAND, [this](wl::params p)->LRESULT { if (LOWORD(p.wParam) == IDC_SHOWMODAL) // some button to open the modal { MyModal modalDlg; int retVal = modalDlg.show(this); // blocks until return; retVal receives 33 return 0; } return DefWindowProc(hwnd(), p.message, p.wParam, p.lParam); }); } If the modal asks user input, it’s common for the modal to return constants like IDOK or IDCANCEL. The modal dialog can also receive any parameters on the constructor, just like any class, and have public methods to return something: C++ class MyModal : public wl::dialog_modal { public: MyModal(std::wstring name, int number); std::wstring getName(); }; Then the instantiation by the parent window, with a more elaborated example: C++ on_message(WM_COMMAND, [this](wl::params p)->LRESULT { if (LOWORD(p.wParam) == IDC_BTNSHOWMODAL) { MyModal modalDlg(L"Hello modal", 800); // instantiate the modal if (modalDlg.show(this) != IDCANCEL) { std::wstring foo = modalDlg.getName(); } return 0; } return DefWindowProc(hwnd(), p.message, p.wParam, p.lParam); }); Modal dialogs can pop other modal dialogs, as well. 3.6. A Modeless Popup Dialog A modeless popup dialog differs from the modal, since modeless dialogs are created via CreateDialogParam. This is an example of a declaration: C++ // Declaration: MyModeless.h #include "winlamb/dialog_modeless.h" class MyModeless : public wl::dialog_modeless { public: MyModeless(); }; And the implementation, pretty much like the previous examples: C++ // Implementation: MyModeless.cpp #include "MyModeless.h" #include "resource.h" MyModeless::MyModeless() { setup.dialogId = IDD_DIALOG3; on_message(WM_INITDIALOG, [](wl::params p)->INT_PTR { return TRUE; }); } Very important: Once a modeless dialog is created, it will live alongside its parent window – modeless dialogs have no message loop for themselves. For this reason, attention must be paid to the declaration scope. The modeless object must be declared as a member of its parent: C++ // Declaration: MainWindow.h #include "winlamb/window_main.h" #include "MyModeless.h" // our modeless dialog header class MainWindow : public wl::window_main { private: MyModeless mless; // modeless as a member public: MainWindow(); }; This way, after we created it, the variable won’t go out of scope after the caller function returns: C++ // Implementation: MainWindow.cpp #include "MainWindow.h" RUN(MainWindow); MainWindow::MainWindow() { on_message(WM_CREATE, [this](wl::params p)->LRESULT { mless.show(this); // modeless dialog is now alive return 0; }); } If we had declared mless object inside on_message’s lambda – just like we did on the previous example with the modal dialog –, mless would go out of scope right after the lambda returns, thus being destroyed while the modeless window is still alive. Then, as the modeless would come to process its first message, mless object would no longer exist. Scope is very important with lambdas. A modeless dialog is destroyed with a DestroyWindow call. By default, WinLamb handles WM_CLOSE with a call to DestroyWindow, so if you send WM_CLOSE to your modeless, it will be destroyed right away. Now if you have used modeless windows with pure Win32, you may be wondering about the problems they introduce in the window message dispatching. Worry not: WinLamb was designed to treat these problems internally – this pain is gone. 3.7. A Custom Control A custom control is a window designed to be a child of another window. It will inherit from window_control: C++ // Declaration: MyWidget.h #include "winlamb/window_control.h" class MyWidget : public wl::window_control { public: MyWidget(); }; The implementation can look like this: C++ // Implementation: MyWidget.cpp #include "MyWidget.h" MyWidget::MyWidget() { setup.wndClassEx.lpszClassName = L"HAPPY_LITTLE_WIDGET"; setup.wndClassEx.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BTNFACE + 1); setup.exStyle |= WS_EX_CLIENTEDGE; setup.style |= (WS_TABSTOP | WS_GROUP | WS_HSCROLL); on_message(WM_PAINT, [this](wl::params p)->LRESULT { PAINTSTRUCT ps{}; HDC hdc = BeginPaint(hwnd(), &ps); EndPaint(hwnd(), &ps); return 0; }); on_message(WM_ERASEBKGND, [](wl::params p)->LRESULT { return 0; }); } For the very same reasons of the aforementioned modeless dialog example, you must declare the child window as a member of the parent: C++ // Declaration: ParentWindow.h #include "winlamb/window_main.h" #include "MyWidget.h" // our custom control header class ParentWindow : public wl::window_main { private: MyWidget widgetFoo1, widgetFoo2; // let’s have two of them public: ParentWindow(); }; To create the control, the parent must call its create member function, which receives: the this pointer of the parent, the control ID we want to give it, a SIZE for the control size, and a POINT for the position within the parent: C++ // Implementation: ParentWindow.cpp #include "ParentWindow.h" RUN(ParentWindow); #define WIDG_FIRST 40001 #define WIDG_SECOND WIDG_FIRST + 1 ParentWindow::ParentWindow() { setup.wndClassEx.lpszClassName = L"BEAUTIFUL_PARENT"; on_message(WM_CREATE, [this](wl::params p)->LRESULT { widgetFoo1.create(this, WIDG_FIRST, {10,10}, {150,100}); widgetFoo2.create(this, WIDG_SECOND, {10,200}, {150,320}); return 0; }); } These are the predefined values of style for the window_control: C++ setup.wndClassEx.style = CS_DBLCLKS; setup.style = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; 3.8. Dialog as a Control It is also possible to embed a dialog as a child of a window, or as a child of another dialog. To build such a child dialog, inherit it from dialog_control class: C++ // Declaration: MyDlgWidget.h #include "winlamb/dialog_control.h" class MyDlgWidget : public wl::dialog_control { public: MyDlgWidget(); }; To work properly, a control dialog must have some specific styles – this is a requirement from Win32, not from WinLamb. With Visual Studio resource editor, these are the styles: • Border: none; • Control: true; • Style: child; • Visible: true (otherwise will start invisible); • Client Edge: true if you want a border (will add WS_EX_CLIENTEDGE) Given the previous examples, I believe the implementation of a control dialog is trivial at this point of the article. 4. Cracking Messages Beyond providing the ability to use lambdas to handle messages, WinLamb also offers facilities to deal with the message contents. 4.1. Command and Notify Handling So far, we only used on_message to handle Windows messages on our windows and dialogs. Beyond that, there are two other specialized methods to deal with WM_COMMAND and WM_NOTIFY messages specifically: C++ void on_command(WORD cmd, std::function<INT_PTR(wl::params)>&& func); void on_notify(UINT_PTR idFrom, UINT code, std::function<INT_PTR(wl::params)>&& func); These are shorthands and have the same effect of manually switching within WM_COMMAND and WM_NOTIFY messages. C++ on_command(IDOK, [this](wl::params p)->INT_PTR { set_text(L"OK button clicked."); return TRUE; }); WM_NOTIFY identifier receives two parameters – the ID of the control and the notification code – according to NMHDR structure: C++ on_notify(IDC_LISTVIEW1, LVN_DELETEITEM, [this](wl::params p)->INT_PTR { set_text(L"Item deleted from list view."); return TRUE; }); Both functions also accept an initializer_list to handle multiple messages at once. 4.2. Message Parameters Unpacked When handling a message, your lambda always receives a single wl::params argument: C++ on_message(WM_MENUSELECT, [](wl::params p)->LRESULT { return 0; }); The wl::params is a simple struct with 3 members, which are familiar to anyone who ever wrote a Win32 program. This is the declaration which can be found inside WinLamb: C++ struct params { UINT message; WPARAM wParam; LPARAM lParam; }; However, for almost all Windows messages, the WPARAM and LPARAM members contain packed data, varying according to the message being handled. For example, for WM_MENUSELECT, this is what they carry: • WPARAM, low-order word – menu item index • WPARAM, high-order word – item state flag • LPARAM – handle to clicked menu To retrieve these data, you must perform casts, extract bitflags, and be sure of what you’re doing. To alleviate this burden, WinLamb provides unpackers for (hopefully) all documented Windows messages. These unpackers are simply structs derived from wl::params, adding the unpacking methods. They are enclosed within the wl::wm namespace. For example, let’s take WM_MENUSELECT. In the following example, the declaration of wl::params is replaced by wl::wm::menuselect, and that’s all you need to do. Notice the methods being called on p: C++ on_message(WM_MENUSELECT, [](wl::wm::menuselect p)->LRESULT { if (p.is_checked() || p.has_bitmap()) { HMENU hMenu = p.hmenu(); WORD itemIndex = p.item(); } return 0; }); This is functionally equivalent of painfully unpacking the data manually, like this: C++ on_message(WM_MENUSELECT, [](wl::params p)->LRESULT { if ((HIWORD(p.wParam) & MF_CHECKED) || (HIWORD(p.wParam) & MF_BITMAP)) { HMENU hMenu = reinterpret_cast<HMENU>(p.lParam); WORD itemIndex = LOWORD(p.wParam); } return 0; }); Use the message crackers as much as you can. They are safer and they save you time, plus they look nice under IntelliSense: Image 5 4.3. Unpacking Common Control Notifications Common controls send notifications through WM_NOTIFY message, which has a different approach from ordinary messages. For common controls, the data comes packed into an NMHDR struct, or a struct that contains it. WinLamb also has crackers for these notifications, they are enclosed within the wl::wmn namespace. Notice the separation here: • Ordinary Windows messages belong to wl::wm namespace • WM_NOTIFY notifications belong to wl::wmn namespace Within wl::wmn, there is one nested namespace to each common control, so the notifications of each control are kept separated. These namespaces are named following the same convention of the notification itself. For example, list view notifications, which are prefixed with LVN_, belong to the wl::wmn::lvn namespace. Image 6 For example, this is how we crack a LVN_INSERTITEM notification: C++ on_notify(IDC_LIST1, LVN_INSERTITEM, [](wl::wmn::lvn::insertitem p)->INT_PTR { int newId = p.nmhdr().iItem; return TRUE; }); Notice that p has an nmhdr member function. This function will return the exact type according to the notification; in the above example, nmhdr will return a reference to an NMLISTVIEW struct, which contains NMHDR. IntelliSense will list all the members: Image 7 5. Subclassing Controls Control subclassing is an operation normally done with the aid of SetWindowSubclass Win32 function. You provide a SUBCLASSPROC callback function, which is very similar to WNDPROC and DLGPROC, and handle specific messages from there. 5.1. Installation and Message Handling WinLamb’s approach to control subclassing is to instantiate an object of subclass type, then attach it to an existing control. For example, retaking the edit control example, let’s subclass the edit control. First, we add a subclass member to our class: C++ // Declaration: FirstDialog.h #include "winlamb/dialog_main.h" #include "winlamb/textbox.h" #include "winlamb/subclass.h" class FirstDialog : public wl::dialog_main { private: wl::textbox edit1; // our control object wl::subclass edit1sub; // edit subclasser object public: FirstDialog(); }; To handle the methods within the subclassing, we just call on_message on the subclass object. It works the same way of windows and dialogs, except we’re handling a message from SUBCLASSPROC callback procedure: C++ edit1sub.on_message(WM_RBUTTONDOWN, [](wl::params p)->LRESULT { // subclass code... return 0; }); After adding the messages, we’ll have a subclass object stuffed with handlers, but it still does nothing. We install the subclass after we initialize the control by calling assign. This is the full implementation: C++ // Implementation: FirstDialog.cpp #include "FirstDialog.h" #include "resource.h" RUN(FirstDialog); FirstDialog::FirstDialog() { setup.dialogId = IDD_MY_FIRST_DIALOG; edit1sub.on_message(WM_RBUTTONDOWN, [](wl::params p)->LRESULT { // subclass code for edit1... return 0; }); on_message(WM_INITDIALOG, [this](wl::params p)->INT_PTR { edit1.assign(this, IDC_EDIT1); // init control edit1sub.install_subclass(edit1); // subclass installed and ready return TRUE; }); } Note that, in this example, we added the edit1sub handler before the WM_INITIDALOG, but this is not required. Since the lambdas are called asynchronously, the order we attach them doesn’t matter. We can attach the edit1sub messages after WM_INITDIALOG as well, in any order. The subclass object also has on_command and on_notify member functions, and it can be detached at any time by calling remove_subclass. 6. Final Topics 6.1. Window Types Summary Summing up, these are all WinLamb window base classes your window can inherit from: WinLamb also have wrappers for many native controls, like listview, textbox, combobox, etc. Window subclassing can also be automated. 6.2. Default Message Processing The window classes provide default processing for some messages. If you write a handler to one of these messages, the default processing will be overwritten. Below is a list of the messages which have a default processing, and what they do: 6.3. What’s Next? As far as I can remember, around 2002, I started wrapping all my Win32 routines in classes, to make them reusable to myself, to save my time. Through all these years, it took the form of a real library, a thin abstraction layer over raw Win32. People who saw it often commented that it was good, so in 2017, I decided to publish it on GitHub. Yeah, although it’s a modern C++11 library, actually it was 15 years old when I first published it. Since WinLamb is what I use for my own personal programs, it’s likely to continue evolving with the time. Refactorings surely will occur, but the current architecture has been stable for many years, and it’s unlikely to have big breaking changes. I have a couple full real-world projects tagged on GitHub. Everything is shared under the MIT license. 7. Article History I’ll try to keep this article updated with the latest WinLamb version: • 2018.12.31 – Style scoped enums, updating MSDN links • 2017.11.19 – Library refactoring, native control wrappers merged • 2017.04.26 – First public version This article was originally posted at https://github.com/rodrigocfd/winlamb License This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Written By Systems Engineer Brazil Brazil This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming. Comments and Discussions   GeneralMy vote of 5 Pin fioresoft8-Aug-19 20:29 fioresoft8-Aug-19 20:29  GeneralMy vote of 5 Pin Francisco José Sen del Prado19-Jan-19 2:31 Francisco José Sen del Prado19-Jan-19 2:31  PraiseOutstanding! Pin koothkeeper1-Jan-19 9:22 professionalkoothkeeper1-Jan-19 9:22  QuestionErrors in minimal example (from Github page) Pin Sergio Ferrari8-Sep-18 3:56 professionalSergio Ferrari8-Sep-18 3:56  QuestionThanks for this! Pin BeErikk18-Nov-17 10:51 professionalBeErikk18-Nov-17 10:51  AnswerRe: Thanks for this! Pin Rodrigo Cesar de Freitas Dias20-Nov-17 5:28 Rodrigo Cesar de Freitas Dias20-Nov-17 5:28  GeneralRe: Thanks for this! Pin BeErikk21-Nov-17 5:00 professionalBeErikk21-Nov-17 5:00  QuestionCan WinLamb be used in a DLL? Pin Jon Summers27-Apr-17 4:11 Jon Summers27-Apr-17 4:11  AnswerRe: Can WinLamb be used in a DLL? Pin Rick York27-Apr-17 5:25 mveRick York27-Apr-17 5:25  AnswerRe: Can WinLamb be used in a DLL? Pin Rick York27-Apr-17 6:36 mveRick York27-Apr-17 6:36  GeneralWykobi Pin Jon Summers1-May-17 3:05 Jon Summers1-May-17 3:05  General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin    Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
__label__pos
0.855774
CodePen HTML ! CSS body { margin: 0; } svg { position: absolute; top: 0; left: 0; } rect { fill: transparent; } ! ? ? ? ? Must be a valid URL. + add another resource via CSS Lint JS /* SET UP ENV */ var map = {}; map.width = 960; map.height = 500; map.canvas = d3.select('body') .append('canvas') .attr('width', map.width) .attr('height', map.height) .node().getContext('2d'); map.svg = d3.select('body') .append('svg') .attr('width', map.width) .attr('height', map.height) .append('g'); map.svg.append('rect') .attr('class', 'overlay') .attr('width', map.width) .attr('height', map.height); /* PREPARE DATA and SCALES */ map.canvas.nodes = d3.range(100).map(function(d, i) { return { x: Math.random() * map.width / 2, y: Math.random() * map.height / 2, r: Math.random() * 10 + 3 }; }); map.svg.nodes = d3.range(100).map(function(d, i) { return { x: Math.random() * map.width / 2, y: Math.random() * map.height / 2, r: Math.random() * 10 + 3 }; }); map.nodes = map.svg.nodes.concat( map.canvas.nodes ); var root = map.nodes[0]; root.r = 0; root.fixed = true; var x = d3.scale.linear() .domain([0, map.width]) .range([0, map.width]); var y = d3.scale.linear() .domain([0, map.height]) .range([map.height, 0]); /* PLOT */ map.canvas.draw = function() { map.canvas.clearRect(0, 0, map.width, map.height); map.canvas.beginPath(); var i = -1, cx, cy; while (++i < map.canvas.nodes.length) { d = map.canvas.nodes[i]; cx = x( d.x ); cy = y( d.y ); map.canvas.moveTo(cx, cy); map.canvas.arc(cx, cy, d.r, 0, 2 * Math.PI); } map.canvas.fill(); }; map.svg.draw = function() { circle = map.svg.selectAll('circle') .data(map.svg.nodes).enter() .append('circle') .attr('r', function(d) { return d.r; }) .attr('fill', 'blue') .attr('transform', map.svg.transform); }; map.canvas.draw(); map.svg.draw(); map.redraw = function() { map.canvas.draw(); circle.attr('transform', map.svg.transform); }; map.svg.transform = function(d) { return 'translate(' + x( d.x ) + ',' + y( d.y ) + ')'; }; /* FORCE */ var force = d3.layout.force() .gravity(0.05) .charge( function(d, i) { return i ? 0 : -2000; } ) .nodes(map.nodes) .size([map.width, map.height]) .start(); force.on('tick', function(e) { var q = d3.geom.quadtree(map.nodes), i; for (i = 1; i < map.nodes.length; ++i) { q.visit( collide(map.nodes[i]) ); } map.redraw(); }); function collide(node) { var r = node.r + 16, nx1 = node.x - r, nx2 = node.x + r, ny1 = node.y - r, ny2 = node.y + r; return function(quad, x1, y1, x2, y2) { if (quad.point && (quad.point !== node)) { var x = node.x - quad.point.x, y = node.y - quad.point.y, l = Math.sqrt(x * x + y * y), r = node.r + quad.point.r; if (l < r) { l = (l - r) / l * 0.5; node.x -= x *= l; node.y -= y *= l; quad.point.x += x; quad.point.y += y; } } return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1; }; } /* LISTENERS */ function mousemove() { var p = d3.mouse(this); root.px = x.invert( p[0] ); root.py = y.invert( p[1] ); force.resume(); } d3.select('body') .on('mousemove', mousemove) .call( d3.behavior.zoom().x( x ).y( y ).scaleExtent([1, 8]).on('zoom', map.redraw) ); ! Must be a valid URL. + add another resource via JS Hint Loading ..................
__label__pos
0.998927
Set-HostedContentFilterRule This cmdlet is available only in the cloud-based service. Use the Set-HostedContentFilterRule cmdlet to modify the settings of content filter rules in your cloud-based organization. For information about the parameter sets in the Syntax section below, see Exchange cmdlet syntax (https://technet.microsoft.com/library/bb123552.aspx). Syntax Set-HostedContentFilterRule [-Identity] <RuleIdParameter> [-Comments <String>] [-Confirm] [-ExceptIfRecipientDomainIs <Word[]>] [-ExceptIfSentTo <RecipientIdParameter[]>] [-ExceptIfSentToMemberOf <RecipientIdParameter[]>] [-HostedContentFilterPolicy <HostedContentFilterPolicyIdParameter>] [-Name <String>] [-Priority <Int32>] [-RecipientDomainIs <Word[]>] [-SentTo <RecipientIdParameter[]>] [-SentToMemberOf <RecipientIdParameter[]>] [-WhatIf] [<CommonParameters>] Description You need to be assigned permissions before you can run this cmdlet. Although this topic lists all parameters for the cmdlet, you may not have access to some parameters if they're not included in the permissions assigned to you. To find the permissions required to run any cmdlet or parameter in your organization, see Find the permissions required to run any Exchange cmdlet (https://technet.microsoft.com/library/mt432940.aspx). Examples -------------------------- Example 1 -------------------------- Set-HostedContentFilterRule "Contoso Recipients" -ExceptIfSentToMemberOf "Contoso Human Resources" This example adds an exception to the content filter rule named Contoso Recipients for members of the distribution group named Contoso Human Resources. Required Parameters -Identity The Identity parameter specifies the content filter rule that you want to modify. You can use any value that uniquely identifies the rule. For example, you can specify the name, GUID, or distinguished name (DN) of the content filter rule. Type:RuleIdParameter Position:1 Default value:None Accept pipeline input:True Accept wildcard characters:False Applies to:Exchange Online Protection Optional Parameters -Comments The Comments parameter specifies informative comments for the rule, such as what the rule is used for or how it has changed over time. The length of the comment can't exceed 1024 characters. Type:String Position:Named Default value:None Accept pipeline input:False Accept wildcard characters:False Applies to:Exchange Online Protection -Confirm The Confirm switch specifies whether to show or hide the confirmation prompt. How this switch affects the cmdlet depends on if the cmdlet requires confirmation before proceeding. • Destructive cmdlets (for example, Remove-* cmdlets) have a built-in pause that forces you to acknowledge the command before proceeding. For these cmdlets, you can skip the confirmation prompt by using this exact syntax: -Confirm:$false. • Most other cmdlets (for example, New-* and Set-* cmdlets) don't have a built-in pause. For these cmdlets, specifying the Confirm switch without a value introduces a pause that forces you acknowledge the command before proceeding. Type:SwitchParameter Aliases:cf Position:Named Default value:None Accept pipeline input:False Accept wildcard characters:False Applies to:Exchange Online Protection -ExceptIfRecipientDomainIs The ExceptIfRecipientDomainIs parameter specifies an exception that looks for recipients with email address in the specified domains. You can specify multiple domains separated by commas. Type:Word[] Position:Named Default value:None Accept pipeline input:False Accept wildcard characters:False Applies to:Exchange Online Protection -ExceptIfSentTo The ExceptIfSentTo parameter specifies an exception that looks for recipients in messages. You can use any value that uniquely identifies the recipient. For example: • Name • Distinguished name (DN) • Display name • Email address • GUID To enter multiple values, use the following syntax: <value1>,<value2>,...<valueX>. If the values contain spaces or otherwise require quotation marks, use the following syntax: "<value1>","<value2>",..."<valueX>". Type:RecipientIdParameter[] Position:Named Default value:None Accept pipeline input:False Accept wildcard characters:False Applies to:Exchange Online Protection -ExceptIfSentToMemberOf The ExceptIfSentToMemberOf parameter specifies an exception that looks for messages sent to members of groups. You can use any value that uniquely identifies the group. For example: • Name • Distinguished name (DN) • Display name • Email address • GUID To enter multiple values, use the following syntax: <value1>,<value2>,...<valueX>. If the values contain spaces or otherwise require quotation marks, use the following syntax: "<value1>","<value2>",..."<valueX>". If you remove the group after you create the rule, no exception is made for messages that are sent to members of the group. Type:RecipientIdParameter[] Position:Named Default value:None Accept pipeline input:False Accept wildcard characters:False Applies to:Exchange Online Protection -HostedContentFilterPolicy The HostedContentFilterPolicy parameter specifies the content filter policy to apply to messages that match the conditions defined by this content filter rule. You can use any value that uniquely identifies the policy. For example, you can specify the name, GUID, or distinguished name (DN) of the content filter policy. You can't specify the default content filter policy. And, you can't specify a content filter policy that's already associated with another content filter rule. Type:HostedContentFilterPolicyIdParameter Position:Named Default value:None Accept pipeline input:False Accept wildcard characters:False Applies to:Exchange Online Protection -Name The Name parameter specifies a unique name for the content filter rule. Type:String Position:Named Default value:None Accept pipeline input:False Accept wildcard characters:False Applies to:Exchange Online Protection -Priority The Priority parameter specifies a priority value for the rule that determines the order of rule processing. A lower integer value indicates a higher priority, the value 0 is the highest priority, and rules can't have the same priority value. Valid values and the default value for this parameter depend on the number of existing rules. For example, if there are 8 existing rules: • Valid priority values for the existing 8 rules are from 0 through 7. • Valid priority values for a new rule (the 9th rule) are from 0 through 8. • The default value for a new rule (the 9th rule) is 8. If you modify the priority value of a rule, the position of the rule in the list changes to match the priority value you specify. In other words, if you set the priority value of a rule to the same value as an existing rule, the priority value of the existing rule and all other lower priority rules after it is increased by 1. Type:Int32 Position:Named Default value:None Accept pipeline input:False Accept wildcard characters:False Applies to:Exchange Online Protection -RecipientDomainIs The RecipientDomainIs parameter specifies a condition that looks for recipients with email address in the specified domains. You can specify multiple domains separated by commas. Type:Word[] Position:Named Default value:None Accept pipeline input:False Accept wildcard characters:False Applies to:Exchange Online Protection -SentTo The SentTo parameter specifies a condition that looks for recipients in messages. You can use any value that uniquely identifies the recipient. For example: • Name • Distinguished name (DN) • Display name • Email address • GUID To enter multiple values, use the following syntax: <value1>,<value2>,...<valueX>. If the values contain spaces or otherwise require quotation marks, use the following syntax: "<value1>","<value2>",..."<valueX>". Type:RecipientIdParameter[] Position:Named Default value:None Accept pipeline input:False Accept wildcard characters:False Applies to:Exchange Online Protection -SentToMemberOf The SentToMemberOf parameter specifies a condition that looks for messages sent to members of groups. You can use any value that uniquely identifies the group. For example: • Name • Distinguished name (DN) • Display name • Email address • GUID To enter multiple values, use the following syntax: <value1>,<value2>,...<valueX>. If the values contain spaces or otherwise require quotation marks, use the following syntax: "<value1>","<value2>",..."<valueX>". If you remove the group after you create the rule, no action is taken on messages that are sent to members of the group. Type:RecipientIdParameter[] Position:Named Default value:None Accept pipeline input:False Accept wildcard characters:False Applies to:Exchange Online Protection -WhatIf The WhatIf switch simulates the actions of the command. You can use this switch to view the changes that would occur without actually applying those changes. You don't need to specify a value with this switch. Type:SwitchParameter Aliases:wi Position:Named Default value:None Accept pipeline input:False Accept wildcard characters:False Applies to:Exchange Online Protection Inputs To see the input types that this cmdlet accepts, see Cmdlet Input and Output Types (https://go.microsoft.com/fwlink/p/?linkId=616387). If the Input Type field for a cmdlet is blank, the cmdlet doesn't accept input data. Outputs To see the return types, which are also known as output types, that this cmdlet accepts, see Cmdlet Input and Output Types (https://go.microsoft.com/fwlink/p/?linkId=616387). If the Output Type field is blank, the cmdlet doesn't return data.
__label__pos
0.52822
How to install pymongo? Member by libby , in category: Python , 5 months ago How to install pymongo? Facebook Twitter LinkedIn Telegram Whatsapp 1 answer by jordane.crist , 5 months ago @libby  To install pymongo, follow these steps: 1. Make sure you have Python and pip installed on your system. 2. Open a terminal or command prompt. 3. Run the following command to install pymongo using pip: 1 pip install pymongo 1. Wait for the installation to complete. pymongo should now be installed on your system. To verify the installation, you can run the following Python code in a terminal or Python interpreter: 1 2 import pymongo print(pymongo.__version__) If you see the version number displayed, then pymongo is successfully installed on your system.
__label__pos
0.99996
How to add an element at the end of a List in ColdFusion ListAppend() - add an element at the end of a List ListAppend.cfm <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ListAppend function example: how to add element at the end of a List</title> </head> <body> <h2 style="color:hotpink">ListAppend Function Example</h2> <cfset ColorList="DarkMagenta,DarkOliveGreen,Darkorange"> <cfoutput><b>ColorList: #ColorList#</b></cfoutput> <br /> <cfset Temp = ListAppend(ColorList,"DarkOrchid")> <cfoutput><b>Temp[After append DarkOrchid]: #Temp#</b></cfoutput> </body> </html> More ColdFusion examples
__label__pos
0.69636
Ulti Ulti - 6 months ago 257 SQL Question Doctrine2 - Type timestamp - Default value For some reasons, I need to have tables with TIMESTAMP fields. I created my own Timestamp Type ( Doctrine\DBAL\Types\Type ), it works fine. But when I try to update my database structure, I got this. Command line ede80:~>php app/console doctrine:schema:update --force --complete Updating database schema... [Doctrine\DBAL\Exception\DriverException] An exception occurred while executing 'ALTER TABLE MY_TABLE CHANGE DATE_CREATION DATE_CREATION timestamp DEFAULT NULL' SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'DATE_CREATION' SQL Query If I execute the following query on the database, I works : ALTER TABLE MY_TABLE CHANGE DATE_CREATION DATE_CREATION timestamp DEFAULT CURRENT_TIMESTAMP ORM.YML But when I try to change it in MyTable.orm.yml , like this : dateCreation: type: timestamp nullable: true column: DATE_CREATION options: default: CURRENT_TIMESTAMP The executed query is ALTER TABLE MY_TABLE CHANGE DATE_CREATION DATE_CREATION timestamp DEFAULT 'CURRENT_TIMESTAMP' And it fails. How can I set a working default value, so my database's structure can be up to date ? I already tried to set options: default to 0 , NULL , CURRENT_TIMESTAMP , 00:00:01 ... PHP 5.3.3 MySQL 5.1.63 Here is the Timestamp Type I think that convert*() aren't that well. <?php namespace CNAMTS\PHPK\CoreBundle\Doctrine\Type; use Doctrine\DBAL\Types\Type; use Doctrine\DBAL\Platforms\AbstractPlatform; /** */ class Timestamp extends Type { const TIMESTAMP = 'timestamp'; public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) { return $platform->getDoctrineTypeMapping('TIMESTAMP'); } public function convertToPHPValue($value, AbstractPlatform $platform) { return ($value === null) ? 0 : new \DateTime($value); } public function convertToDatabaseValue($value, AbstractPlatform $platform) { return ($value === null) ? 0 : $value->format(\DateTime::W3C); } public function getName() { return self::TIMESTAMP; } } Answer Here is the solution to have more than one timestamp field in the table. You need to have your own Timestamp type defined and added in AppKernel.php : public function boot() { parent::boot(); /** * SQL type TIMESTAMP */ $em = $this->container->get('doctrine.orm.default_entity_manager'); Doctrine\DBAL\Types\Type::addType('timestamp', 'My\CoreBundle\Doctrine\Type\Timestamp'); $em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('TIMESTAMP', 'timestamp'); } In your entity definition, MyEntity.orm.yml : dateCreation: type: timestamp nullable: false column: DATE_CREATION columnDefinition: TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00' dateModification: type: timestamp nullable: false column: DATE_MODIFICATION columnDefinition: TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP And in the entity MyEntity.php, have a prePersist : public function doPrePersist() { $this->dateCreation = new \DateTime(); } That's how I made it work :-) Thx all for your help ! Comments
__label__pos
0.579752
Visual Basic 2015 Lesson 13: Using If….Then….Else Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone [Lesson 12] << [Contents] >> [Lesson 14] In this lesson, we shall learn how to write Visual Basic 2015 code that can make decisions. We can write a Visual Basic 2015 program that can ask the computer to perform a certain task until certain conditions are met. In order to control the program flow and to make decisions, we can use the conditional operators and the logical operators together with the If..Then…Else keywords. 13.1 Conditional Operators Conditional operators resemble mathematical operators. These operators allow a Visual Basic 2015 program to compare data values and then decide what actions to be taken. They are also known as numerical comparison operators which are used to compare two values to see whether they are equal or one value is greater or less than the other value. The comparison will return a true or false result. These operators are shown in Table 13.1 Table 13.1: Conditional Operators Operator Description  =  Equal to  >  Greater than  <  Less than  >=  Equal to or Greater than <=  Less than or Equal to  <>  Not equal to 13.2 Logical Operators In certain cases, we might need to make more than one comparisons to arrive at a decision.In this case, using numerical comparison operators alone might not be sufficient and we need to use the logical operators, as shown in Table 13.2. Logical operators can be used to compare numerical data as well as non-numeric data such as strings.  In making strings comparison, there are certain rules to follows: Upper case letters are less than lowercase letters, “A”<”B”<”C”<”D”…….<”Z” and number are less than letters. Table 13.2: Logical Operators Operator Description And Both sides must be true Or One side or other must be true Xor One side or other must be true but not both Not Negates true   13.3 Using the If control structure with the Comparison Operators To control the Visual Basic 2015 program flow and to make decisions, we shall use the If control structure together with the conditional operators and logical operators. There are three types of If control structures, namely If….Then statement, If….Then… Else statement and If….Then….ElseIf statement. 13.3(a) If….Then Statement This is the simplest control structure which instructs the computer to perform a certain action specified by the Visual Basic 2015 expression if the condition is true. However, when the condition is false, no action will be performed. The syntax for the if…then.. statement is If condition Then Visual Basic 2015 expressions End If Example 13.1 In this program, we insert a text box and rename it as txtNum and a button and rename it as OK. We write the code so that when the user runs the program and enter a number that is greater than 100, he or she will see the “You win a lucky prize” message. On the other hand, if the number entered is less than or equal to 100, the user will not see any message. The code Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click Dim myNumber As Integer myNumber = TxtNum.Text If myNumber > 100 Then MsgBox(” You win a lucky prize”) End If End Sub The output is as shown in Figure 13.1 and Figure 13.2 vb2015_fig13.1 Figure 13.1 vb2015_fig13.2 Figure 13.2 13.3(b) If….Then…Else Statement As we have seen in example 13.1, using  If….Then statement does not provide alternative output for the user. In order to provide an alternative output, we need to use the If….Then…Else Statement. This control structure will ask the computer to perform a certain action specified by the Visual Basic 2015 expression if the condition is met. And when the condition is false , we  usean alternative action will be executed. The syntax for the if…then… Else statement is If condition Then Visual Basic 2015 expression 1 Else Visual Basic 2015 expression 2 End If Example 13.2 We modified the code in Example 13.1 by adding the Else keyword and an alternative expression MsgBox(“Sorry, You did not win any prize”). When you run the program and enter a number that is greater than 100, the message “Congratulation! You win a lucky prize” will be shown.Otherwise, you will see the “Sorry, You did not win any prize” message, as shown in Figure 13.3 The code Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click Dim myNumber As Integer myNumber = TxtNum.Text If myNumber > 100 Then MsgBox( ” Congratulation! You win a lucky prize”) Else MsgBox( ” Sorry, You did not win any prize”) End If End Sub vb2015_fig13.3 Figure 13.3 Example 13.3 In this prowe usehe logical operator And besides using the conditional operators. This means that both conditions must be met otherwise the second block of code will be executed. In this example, the number entered must be more than 100 and the age must be more than 60 in order to win a lucky prize, any one of the above conditions not fulfilled will disqualify the user from winning a prize. You need to add another text box for the user to enter his or her age. The output is as shown in Figure 13.4 Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click Dim myNumber, MyAge As Integer myNumber = TxtNum.Text MyAge = TxtAge.Text If myNumber > 100 And MyAge > 60 Then MsgBox(" Congratulation! You win a lucky prize") Else MsgBox("Sorry, You did not win any prize") End If End Sub vb2015_fig13.4 Figure 13.4 13.3(c) If….Then…ElseIf Statement In circumstances where there are more than two alternative conditions, using just If….Then….Else statement will not be enough. In this case we can use the If….Then…ElseIf Statement.The general structure for the if…then.. Else statement is If condition Then Visual Basic 2015 expression1 ElseIf condition Then Visual Basic 2015 expression2 ElseIf condition Then Visual Basic 2015 expression3 .. Else Visual Basic 2015 expression4 End If Example 13.4 This program can compute grade for the mark entered by the user. Is uses several ElseIf statements and the logical operator And to achieve the purpose. The outputs are as shown in Figure 13.5 and Figure 13.6 Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click Dim Mark As Integer Dim Grade As String Mark = TxtMark.Text If Mark >= 80 And Mark <= 100 Then Grade = "A" ElseIf Mark >= 60 And Mark < 80 Then Grade = "B" ElseIf Mark >= 40 And Mark < 60 Grade = "C" ElseIf Mark >= 0 And Mark < 40 Grade = "D" Else Grade = "Out of Range" End If MsgBox("You Grade is " & Grade) End Sub vb2015_fig13.5 Figure 13.5 vb2015_fig13.6 Figure 13.6 [Lesson 12] << [Contents] >> [Lesson 14] Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone
__label__pos
0.831059
Visual Basic 2015 Lesson 36: Browsing and Editing Data [Lesson 35] << [Contents]>> [Lesson 37] In preceding lessons, you have learned how to connect to a database as well as filling up the table with data in Visual Basic 2015, now you shall learn how to manipulate the data in the database. Manipulating data means adding news records, editing records, deleting records, browsing records and more. 36.1 Browsing Records  In the previous lesson, we have learned how to display the first record using the showRecords sub procedure.  In this lesson, we will create command buttons and write relevant codes to allow the user to browse the records forward and backward as well as fast forward to the last record and back to the first record.The first button we need to create is for the user to browse the first record. We can use button’s text << to indicate to the user that it is the button to move to the first record and button’s text >> to move to the last record.  Besides we can use button’s text <  for moving to previous record and button’s text >  for moving to next record. The code for moving to the first record is: MyRowPosition = 0 Me.showRecords() The code for moving to the previous record is: If MyRowPosition >0 Then MyRowPosition = MyRowPosition – 1 Me.showRecords() End If The code for moving to next record is: If MyRowPosition < (MyDataTbl.Rows.Count – 1) Then MyRowPosition = MyRowPosition + 1 Me.showRecords() End If The code for moving to the last record is: If MyDataTbl.Rows.Count >0 Then MyRowPosition = MyDataTbl.Rows.Count – 1 Me.showRecords() End If 36.2  Editing, Saving, Adding and Deleting Records You can edit any record by navigating to the record and change the data values. However, you need to save the data after editing them. You need to use the update method of the SqlDataAdapter to save the data. The code  is: If MyDataTbl.Rows.Count <> 0 Then MyDataTbl.Rows(MyRowPosition)(“ContactName”) = txtName.Text MyDataTbl.Rows(MyRowPosition)(“state”) = txtState.Text MyDatAdp.Update(MyDataTbl) End If You can also add a new record or new row to the table using the following code: Dim MyNewRow As DataRow = MyDataTbl.NewRow() MyDataTbl.Rows.Add(MyNewRow) MyRowPosition = MyDataTbl.Rows.Count – 1 Me.showRecords() The code above will present a new record with blank fields for the user to enter the new data. After entering the data, he or she can then click the Save button to save the data. Lastly, the user might want to delete the data. The code to delete the data is: If MyDataTbl.Rows.Count <>0 Then MyDataTbl.Rows(MyRowPosition).Delete() MyDatAdp.Update(MyDataTbl) MyRowPosition = 0 Me.showRecords() End If The Visual Basic 2015 Database program interface is shown below: The Code Public Class Form1 Private MyDatAdp As New SqlDataAdapter Private MyCmdBld As New SqlCommandBuilder Private MyDataTbl As New DataTable Private MyCn As New SqlConnection Private MyRowPosition As Integer = 0 Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed MyCn.Close() MyCn.Dispose() End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load MyCn.ConnectionString = "Data Source=TOSHIBA-PC\SQL2012; AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL11.SQL2012\MSSQL\DATA\Test.mdf; " & _ "User Instance=True;Integrated Security=SSPI" MyCn.Open() MyDatAdp = New SqlDataAdapter("Select* from Contacts", MyCn) MyCmdBld = New SqlCommandBuilder(MyDatAdp) MyDatAdp.Fill(MyDataTbl) Dim MyDataRow As DataRow = MyDataTbl.Rows(0) Dim strName As String Dim strState As String strName = MyDataRow("ContactName") strState = MyDataRow("State") TxtName.Text = strName.ToString TxtState.Text = strState.ToString Me.showRecords() End Sub Private Sub showRecords() If MyDataTbl.Rows.Count = 0 Then txtName.Text = "" txtState.Text = "" Exit Sub End If txtName.Text = MyDataTbl.Rows(MyRowPosition)("ContactName").ToString TxtState.Text = MyDataTbl.Rows(MyRowPosition)("State").ToString End Sub Private Sub BtnMoveFirst_Click(sender As Object, e As EventArgs) Handles BtnMoveFirst.Click MyRowPosition = 0 Me.showRecords() End Sub Private Sub BtnMovePrev_Click(sender As Object, e As EventArgs) Handles BtnMovePrev.Click If MyRowPosition > 0 Then MyRowPosition = MyRowPosition - 1 Me.showRecords() End If End Sub Private Sub BtnMoveNext_Click(sender As Object, e As EventArgs) Handles BtnMoveNext.Click If MyRowPosition < (MyDataTbl.Rows.Count - 1) Then MyRowPosition = MyRowPosition + 1 Me.showRecords() End If End Sub Private Sub BtnMoveLast_Click(sender As Object, e As EventArgs) Handles BtnMoveLast.Click If MyDataTbl.Rows.Count > 0 Then MyRowPosition = MyDataTbl.Rows.Count - 1 Me.showRecords() End If End Sub Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click Dim MyNewRow As DataRow = MyDataTbl.NewRow() MyDataTbl.Rows.Add(MyNewRow) MyRowPosition = MyDataTbl.Rows.Count - 1 Me.showRecords() End Sub Private Sub BtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnDelete.Click If MyDataTbl.Rows.Count <> 0 Then MyDataTbl.Rows(MyRowPosition).Delete() MyRowPosition = 0 MyDatAdp.Update(MyDataTbl) Me.showRecords() End If End Sub Private Sub BtnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnSave.Click If MyDataTbl.Rows.Count <> 0 Then MyDataTbl.Rows(MyRowPosition)("ContactName") = TxtName.Text MyDataTbl.Rows(MyRowPosition)("state") = TxtState.Text MyDatAdp.Update(MyDataTbl) End If End Sub End Class Figure 36.1 [Lesson 35] << [Contents]>> [Lesson 37] Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone
__label__pos
0.92309
TRIGEN = x, BURSTMD = 1 In this case, the memory access is always requested by the scanner. The memory access request is granted to the scanner if no other higher priority source is requesting access. The memory access cycles will not be granted to lower priority sources than the scanner until it completes operation, i.e. SGO = 0. Important: If TRIGEN = 1 and BURSTMD = 1, the user needs to ensure that the trigger source is active for the scanner operation to complete.
__label__pos
0.997937
What Color is Your Function? You Better Know! Terry Crowley 4 min readMay 19, 2022 -- I never got around to commenting on this somewhat notorious post What Color is Your Function, by Bob Nystrom. This was from 2015 so I feel a little guilty about only ranting on it now — but it continues to get traffic and is quite wrong-headed. In any case, the post is your basic “old fashioned programming language rant” (his words). The post is structured as a hypothetical where you are designing a new programming language. The language has the characteristic that each function has to have a color (red or blue). On top of this strange requirement, there are all these “arbitrary” restrictions on how you invoke these functions and how (or whether) you call one color function from another of a different color. What a crazy way to design a language! Of course, in reality “red” and “blue” correspond to “async” functions and “sync” functions. And these constraints and requirements correspond to real constraints in most of the languages we actually use. The whole post (and the related Hacker News thread that was dominated by programming language folks) fails to consider that you are actually writing programs that interact with the real world. The difference between sync and async is not just a random “aspect”; it is fundamental to the world and fundamental to the way you (should) structure your entire system. Sure, you can ignore it for some command line tool (like a compiler), but almost any long running application (like an app with a user in front of it or a server managing lots of requests) needs to fundamentally understand when it is invoking something that is fast and local (typically sync) and when it is invoking something that is potentially long-running and slow. Crucially, that long-running thing will have different error characteristics, will introduce need for timeout control and cancellation capability and will also introduce concerns for how to manage internal program resources and state during the period of execution. You virtually always need to hold on to some resources — at least memory — to be ready to process the response when it finally arrives. In fact one of the most common ways that services “blow up” is when they are holding on to lots of resources and some queue of requests get stalled behind a non-responding dependent service. You usually need to do explicit throttling around how you manage queues and make requests between different components of your system. In a graphical application (browser or native), sync vs. async is absolutely fundamental to how you manage state. At any given time, you need to provide a consistent view of the application model for the user to interact with. Ignoring that you just called a function that could take arbitrarily long to complete (or timeout) is called a “hang”. In fact, we have experience with a system with one color — Win32. Virtually all functions except for a very few low-level routines were designed to be synchronous. It was generally left as an exercise for you as the programmer to figure out how to “wrap a thread” around an API call to keep your application from hanging. There was no red/blue signature — you had no idea whether the routine you were calling was going to take milliseconds, seconds or minutes to complete. This played a fundamental part in the horrendously common hanging behavior of Windows applications. It also played a role in the excessive thread and resource consumption of Windows apps (using threads as an abstraction for waiting rather than an abstraction for computing). In fact, I would argue (have argued) that the explicit characteristic of asynchronous APIs has played a significant role in improving application responsiveness over time. It is certainly possible to design systems where you only have synchronous functions and use message passing and multiple threads of execution (the long-running Midori research system at Microsoft is one example of a system that worked this way). This might make language designers happy but it doesn’t actually simplify the intellectual effort necessary to structure the overall system. You still need to think about how these messages (or other thread rendezvous events) get processed as an asynchronous event to update the stable state of the system. In a graphical application, you often have even more challenging issues around both exposing the intermediate state of some asynchronous computation (e.g. you are laying out the pages of a long document and would like to show the current page even if layout is not complete), or having user actions further impact an ongoing computation (more editing makes the current layout processing out-of-date so you would like to cancel and restart). In practice, it is often the case that one “large” asynchronous operation is composed of a number of smaller asynchronous steps and it may be possible to use techniques like async/await and promises to write parts of the computation in a form that looks generally synchronous. But you still cannot ignore these larger system design issues. Asking why you would need to know the “implementation detail” that a function you are calling needs to invoke an async function internally is like asking why you need to know that some function you are calling can hang your app. It seems pretty clear why you need to know that. You’re better off if you “revel in the asynchrony” — and actually address the higher level system design issues — rather than treat it as an annoying statement or function-level issue to be papered over by programming language syntax. -- -- Terry Crowley Programmer, Ex-Microsoft Technical Fellow, Sometime Tech Blogger, Passionate Ultimate Frisbee Player
__label__pos
0.744731
RSign Logo Pre-fill Form Fields Before Sending a Document This is best suited when the sending organization prefers to configure forms and templates with e-sign rules, logic, dependencies, reminders, encryption, and more; pre-filling data from a sending system into a form, with the option to back-fill form data back into sending system. 1. Authenticate sending server with RSign system 1. Authenticate sender address with RSign (IP authentication, domain verification, SPF, and DKIM set up). 2. Authorize sending address with RSign service plan for sending address. 3. Create eSignature Template 1. Use RSign web interface or iFrame RSign Create interface into sending application 2. Upload form 3. Drag-and-drop fields, rules, settings 4. Save as a template 4. Map Fields 1. Prefill: Map fields for pre-filling data from sending system into template 2. Backfill: Map fields for back-filling data from web form at signer into sending system 5. Send 1. Use RSign APIs to send the template for eSign to recipients 6. Prepare for return signed contracts and data reports. 1. Use RSign APIs to receive esigned PDF and enhanced meta data
__label__pos
0.99901
67 $\begingroup$ One of the traps of imperative-first is how difficult it becomes to help students make sense of recursion when they finally encounter it. And if those kids are fairly competent iterative programmers, they may also resist the new technique, as they feel perfectly comfortable solving problems without it. Many of the obvious examples of recursion (such as Fibonacci numbers) are either faster or cleaner when done iteratively. What examples, then, cleanly motivate recursion? To be honest, they don't have to even be coding examples. What I want is for students to intuitively understand the purpose of this new (to them) technique. (I am aware of this question of course, but, while it is helpful, is is after an explanatory analogy to clarify recursion, while this question is about finding a clear motivation to study it in the first place.) $\endgroup$ 17 • 90 $\begingroup$ This stack exchange question is quite motivating. $\endgroup$ Jan 10, 2018 at 11:10 • 1 $\begingroup$ Please do not attempt to answer the question in the comments. Answers in the comment section break mechanisms that are vital to how SE works such as voting, editing, and accepting. In addition, comments are meant not to be permanent. Please do not engage in extended discussion in the comments, comments are meant for requests for clarification or suggested improvements to the question. This conversation has been moved to chat. $\endgroup$ – thesecretmaster Jan 12, 2018 at 18:17 • 2 $\begingroup$ @Pureferret I was expecting that to link to StackOverflow... you trolled me! $\endgroup$ Jan 14, 2018 at 1:25 • 10 $\begingroup$ @RonJohn This is the worst teaching approach ever. $\endgroup$ – m93a Jan 15, 2018 at 13:49 • 6 $\begingroup$ @RonJohn Yes, fear motivates some, but this kind of motivation will never make them like or enjoy the subject. Good programmers are creative and think for themselves – obeying your rules will never teach them the skill of problem-solving, which is crucial. Furthemore, the point of teaching is preparing students for real-life problems. By not showing scenarios where recursion is beneficial, you would teach them nothing, as they wouldn't recognise recursion as a good tool. $\endgroup$ – m93a Jan 15, 2018 at 14:15 21 Answers 21 102 $\begingroup$ I find a very easy to understand example for recursion is the folder structure on a computer. Look through all folders (within a certain location) and... list all .doc files, for example. First, you look in the location you were given and see what you're looking for... or not, but you see more folders. Then you take each of those folders, look into them and see what you're looking for... or not, but you see more folders. Then you take each of those folders... (you get the idea) It's a simple function to write and understand (at least in pseudocode, actual implementations may vary^^) and a concept that's easy to grasp for even a complete beginner. Introducing the problem and the manual solution, it's already obvious that each time, the same thing happens again and again. Pseudocode implementation is equally simple to write and grasp: function findFiles(folder) { look for .doc files, if found add them to fileList.txt look for folders for each found folder: findFiles(foundFolder) } I've used this example to explain recursion several times, and never had trouble getting the person to understand it. Even non-programmers can grasp the concept like this. $\endgroup$ 11 • 10 $\begingroup$ Welcome to CSEducators. Come back often. I'll also note that this is recursion over a tree, not just a linear structure. Nice. $\endgroup$ – Buffy Jan 10, 2018 at 11:31 • 27 $\begingroup$ I think this is the best approach. Show recursive functions by processing recursive data structures (here: the folder structure)! Other classical examples (like Fibonacci or Factorial) often trigger a reaction like "Nice, but why do I need that?" by the students. But every computer user has seen recursive data strucures at least once in their life (e.g. folders). Showing them that such structures can be processed elegantly by recursive functions gives often the desired "wow"effect. $\endgroup$ – trunklop Jan 10, 2018 at 11:43 • 16 $\begingroup$ +1. Depth-first tree traversal is the simplest example I can think of where the recursive approach is truly easier to understand than the iterative approach. And even students who are not familiar with trees will probably be familiar with folders in a filesystem. $\endgroup$ – BenM Jan 10, 2018 at 12:40 • 4 $\begingroup$ There's a good chance an iterative programmer will already know how to do this without recursion, by use of a stack $\endgroup$ – phflack Jan 10, 2018 at 14:09 • 16 $\begingroup$ Be aware that students nowadays may be more familiar with the various phone & tablet operating systems, which can hide the complexity of their underlying file system. Obviously it can depend on your exact circumstances, but it wouldn't shock me if the upcoming generation ends up knowing about "computers" in a quite different way than I do, as the interface to how they use them is really quite different. Depending on what the audience is familiar with, you may find more luck traversing a graph of social media "friends" than a file system. $\endgroup$ – user3880 Jan 10, 2018 at 14:59 26 $\begingroup$ One good example is to make permutations of all of the letters in a word of arbitrary length. It's quite tricky to do iteratively, since you essentially have to recreate the program stack to get it done. The recursive solution, however, is clean and clear. Let the students try to work in pairs on an iterative solution for just five minutes. The goal would not be to actually implement it, but just to think through an approach. Then show them the short and elegant recursive answer and help them to trace through it. $\endgroup$ 2 • 1 $\begingroup$ I think you've got it. Actually, that's the only example on this page (so far) that can't be answered with just, "Okay, so what? That's just as easy or easier without any recursion." $\endgroup$ – Wildcard Jan 10, 2018 at 5:44 • 1 $\begingroup$ Permutations may be tricky to do iteratively, but a common iterative approach for "next permutation" involves using an array, not anything that resembles a stack. $\endgroup$ – rcgldr Sep 16, 2019 at 6:30 21 $\begingroup$ Writing recursive code to output the Snowflake Curve (Koch snowflake) was something that definitely pushed my buttons early on. It's formed as follows: The Koch snowflake can be constructed by starting with an equilateral triangle, then recursively altering each line segment as follows: • divide the line segment into three segments of equal length. • draw an equilateral triangle that has the middle segment from step 1 as its base and points outward. • remove the line segment that is the base of the triangle from step 2. An animation is also available from Wikimedia which shows the snowflake after the first few iterations. To generalize further, many Fractals are generated by recursive algorithms and are thus excellent visual representations of recursion in action. The Snowflake/Koch curve is an example of a fractal that is produced by a relatively simple and easily visualizable algorithm making it a great entree into the wider world of fractals. $\endgroup$ 5 • 2 $\begingroup$ Welcome to CSEducators. We hope to see you again. Note that we value longer posts over such short ones, especially posts that are just links that require navigating away from the site for explanation. It would be good if you could give a longer explanation of the curve, its algorithm, or why you think it is important pedagogically. $\endgroup$ – Buffy Jan 10, 2018 at 11:33 • $\begingroup$ Whenever I see Koch snowflake it reminds me that in a math course we were asked to prove that snowflake curve is infinite but the area it encloses is finite. $\endgroup$ – Crowley Jan 10, 2018 at 19:03 • 1 $\begingroup$ The Sierpinski Triangle may also be a good one. To draw the triangle, draw 3 triangles (in the right places). $\endgroup$ – user253751 Jan 10, 2018 at 23:58 • 1 $\begingroup$ Fractals are the last thing I consider "motivating"... $\endgroup$ – user541686 Jan 16, 2018 at 5:49 • $\begingroup$ @mehrdad but they make cool t-shirts! $\endgroup$ – pojo-guy Feb 28, 2018 at 3:19 20 $\begingroup$ Other than the obvious merge sort, I really like the minimax algorithm, especially when applied to creating a computer player of a simple game. Start with something simple like tic-tac-toe. When it's your turn, you can think about putting an X on each of the 9 squares. Then you have to think about what your opponent would do in each case. Your opponent would then think about what you would do if they marked an O on each square... To codify this in a computer player, you can create a pretty simple recursive algorithm that exhaustively searches the space, alternating between whose turn it is, and eventually choosing whichever move leads to the most possible wins, or the fewest losses, whatever. Bonus points for pitting student algorithms against each other. Then apply that to something more complicated like checkers or chess (or just larger or multidimensional tic-tac-toe). Here, you apply the same basic idea, but you can no longer exhaustively search the whole space because it's too large. So you have to come up with a heuristic and maybe implement alpha-beta pruning. My point is that the algorithm itself is simple to think about and fun to play with, but it leads to lots of cooler, more complicated topics as well. See also: Analogy for teaching recursion $\endgroup$ 6 • $\begingroup$ That doesn't seem to directly answer the question, as you don't solve such things with recursion. $\endgroup$ – Wildcard Jan 10, 2018 at 5:39 • 3 $\begingroup$ I prefer Quicksort for demonstrating recursion. I learned merge sort back in the days when it would be done non-recursively using sequential I/O streams and O(1) RAM, and I've in fact found it useful in an embedded system for storing records stored on a flash chip (the flash chip had more than enough space to hold two copies of all 5,000 records, but the system had less than 3840 bytes of RAM). $\endgroup$ – supercat Jan 10, 2018 at 7:28 • 2 $\begingroup$ @Wildcard Uhh, what? From Wikipedia: "A minimax algorithm is a recursive algorithm for choosing the next move in an n-player game" $\endgroup$ Jan 10, 2018 at 17:31 • $\begingroup$ @KevinWorkman I meant the part about heuristics and such, but I see your point. Makes sense. $\endgroup$ – Wildcard Jan 10, 2018 at 19:13 • 1 $\begingroup$ @Wildcard: I had a Tic-Tac-Toe assignment I still remember in a first-year CS course. The week after the assignment, our instructor asked who had used recursion to solve it. IIRC, I was the only person to put up their hand. If there was a move that forced a win, my program made it. Otherwise it would play the first (or one of, I forget) the moves that would lead to a draw against best play. I remember adding a random-first-move option so it wouldn't spend a couple seconds fully solving the game before making a move on an empty board :P $\endgroup$ Jan 11, 2018 at 18:15 13 $\begingroup$ I'm going to focus on student's understanding recursion at a fairly deep level, rather than coding. First, to really understand recursion you need a sense of its parts. There is the base case, of course and most teachers spend time working on that, but students often miss it. But Before the process hits the base case there is a winding phase working toward the base case and after the base case is reached there is an unwinding phase in which all of the recursive "calls" unwind. In the execution of the algorithm, the winding phase is associated with the execution stack increasing in "height" and the unwinding case is associate with its subsequent shrinking. One point often missed by novices is that the winding phase has just exactly as many steps as the unwinding phase. Another point often missed by novices is that work can be done on both the winding and unwinding phases as well as in the base case. Therefore, to teach recursion you need a set of examples or exercises in which the student can examine all of these in detail. Complicating this learning is that most students learn recursion in an environment in which they have already learned to count, both upwards and downwards, and that knowledge, while useful in general, can inhibit learning about recursion if the ideas of recursion and counting (by incrementing or decrementing integers) get merged into a single idea. Therefore, I propose a sequence of active learning exercises, that don't involve coding, but in which the students play roles (stack frames, actually, though you needn't discuss that until later), and which lend themselves to immediate discussion and analysis. To do these you will want a deck of index cards on which to write instructions of the various roles. The recursions will all be "list-like" so a subset of your students will stand in front of the room in a row. Each student will have a card for the current exercise. Your role is to keep things moving so that the "execution" corresponds to that of a computer. I assume that the students are arranged "left to right" at the front, with the "base-case" person at the right furthest from you. Exercise one - Work only in the base case. This is a fairly odd example, not likely to be part of a real program, but it can be instructive. One student's instruction card says that when they are given another card they just read aloud what is on it and then pass it back to the person that gave it to them (This person is the base case). A few others (maybe zero) each have an instruction card that says that when they receive another card they just pass it to the next person in the line, though if it is passed from the left it needs to pass to the right. You have one additional card that says "All Done". You pass this card to the first person, who passes it on, and it should eventually reach the base case and be read aloud. You should then get the card passed back to you. Talk with the students about the phases (winding, unwinding, base) and how the number of times the card passed in is the same as the number passed out. Run the "simulation" more than once, with at least one "run" with only the base case. Later you can run it again with a missing base case to see the error that arises. Exercise two - Work on Winding Phase - Tail Recursion The instruction card for the base case is that when handed a card he or she should announce how many marks are on the card and then pass it back. The other student's instructions are that when passed a card "from the left" they just put a mark on it and pass it to the person on the right, but when passed a card from the right they just pass it to the left. Start the simulation by passing a blank card to the first person (who might be the base case in some "runs". The base-case person should announce the number of people prior to the base case and return the card, through the line, back to you. At some point you can talk about how this might be mapped to a while loop and avoid all of the return steps: unwinding tail recursion. As before, have an immediate discussion about what happened to make sure that the students got the points. You can discuss the fact that the number of marks on the card is like a parameter to the function, also. Exercise three: Work on the unwind phase only. The base case instruction is that when handed a card, simply hand it back. The others have instructions that say that they should simply pass on a card if they receive it from the left, but mark it if they receive it from the right and pass it left. Pass a blank card to the first person and you should get back a card with one mark for each person, but no announcements. You will need to make the announcement of the number of marks. Exercise four: Work on both winding and unwinding phases. Here the base-case instruction is that when given a card (from the left) with a certain number of ticks, just write the number of ticks on the card (perhaps on its back) and return it to the person who gave it. The other student's instruction is that when passed a card from the left just put a tick on it but when passed a card from the right find the largest number on it, double that number, write it on the card and pass it back toward the right. Pass the first person an empty card and make sure you get back the correct result. Again, a short discussion question/answer session will help solidify the ideas. While the discussion here was long, these things move quite quickly and only a few minutes are required for each exercise and its retrospective. However, expect that the students will get it wrong as you go, so your job is to be a coach to make sure it works ok and that the appropriate lessons are learned. Emphasize that the "data card" passed through exactly as many hands on the winding phase as on the unwinding phase. If you want to emphasize the stack-frame idea a bit more, then in each of the exercises, don't line up the students initially, but pick on them one at a time when you need a new "frame". Give each student their instruction card when they stand up to join. This will require a bit more time, of course, but is more realistic and viewers won't know the depth of recursion beforehand. I expect that, with the above guidance, you could also devise simple coding exercises with the same characteristics, letting students learn to carefully distinguish the phases of recursion as well as the symmetry. $\endgroup$ 7 • $\begingroup$ Bonus points if you use card instructions to implement the passing out of cards. ;) Actually, that would probably get a LOT more interest than just passing out the cards in the usual manner and then beginning the exercise. $\endgroup$ – Wildcard Jan 10, 2018 at 5:37 • 1 $\begingroup$ When you noted base case I was expecting to see a follow-up with induction which didn't occur. So now I have to ask, when you say base case are alluding to induction or it is just a coincidence of words? $\endgroup$ – Guy Coder Jan 10, 2018 at 13:40 • 2 $\begingroup$ Recursion and induction are related, of course. So the use of base case seems pretty natural to me. You need a base case to avoid infinite recursion, just as you need a base case to avoid infinitely recursive definitions when using induction. $\endgroup$ – Buffy Jan 10, 2018 at 13:52 • 1 $\begingroup$ I don't agree that studying the base case, winding phase and unwinding phase is motivating at all! It feels like overly-abstract gibberish. The point is not to study how recursion works abstractly, the point is to demonstrate how it's useful. Passing cards around also feels too artificial to be a meaningful demonstration. $\endgroup$ – user253751 Jan 10, 2018 at 23:57 • 1 $\begingroup$ I think you missed the point. The phases and the base case are essential to know and understand. You need a set of tailored exercises that solidify the knowledge of all those parts to be sure the student gets it. The instructor also needs to be explicit about how each exercise uses the parts. With an incomplete understanding it is harder to be an effective program designer. This is especially true in languages that do effective tail recursion elimination. $\endgroup$ – Buffy Jan 11, 2018 at 0:10 8 $\begingroup$ Tree Traversal Let's compare the recursive and iterative approaches to doing an in-order traversal of a binary search tree. Recursive approach void orderedTraversal(const Node *node, void (*f)(int)) { if (!node) return; orderedTraversal(node->left, f); f(node->val); orderedTraversal(node->right, f); } Iterative approach typedef struct StackNode { Node *node; int state; struct StackNode *next; } StackNode; StackNode *push(StackNode *stack, Node *node, int state) { StackNode *newNode = malloc(sizeof *newNode); assert(newNode); newNode->next = stack; newNode->node = node; newNode->state = state; return newNode; } StackNode *pop(StackNode *node) { StackNode *next = node->next; free(node); return next; } void orderedTraversalIterative(Node *node, void (*f)(int)) { int state = 0; StackNode *stack = NULL; for (;;) { switch (state) { case 0: if (!node) { state = 2; continue; } stack = push(stack, node, 1); state = 0; node = node->left; continue; case 1: f(node->val); stack = push(stack, node, 2); state = 0; node = node->right; continue; case 2: if (!stack) return; node = stack->node; state = stack->state; stack = pop(stack); continue; } } } Of course, with a few macros, we can make the logic a bit clearer... #define CALL(NODE) \ stack = push(stack, node, __LINE__); \ state = 0; \ node = NODE; \ goto start; \ case __LINE__: \ #define RETURN do { \ if (!stack) return; \ node = stack->node; \ state = stack->state; \ stack = pop(stack); \ goto start; \ } while (0) void orderedTraversalIterative(Node *node, void (*f)(int)) { int state = 0; StackNode *stack = NULL; start: switch (state) { case 0: if (!node) RETURN; CALL(node->left); f(node->val); CALL(node->right); RETURN; } } ...and reveal that the iterative approach to this problem is to manually build a call stack mechanism so we can go back to using the recursive approach. $\endgroup$ 3 • $\begingroup$ Now all we need is a motivating example for using a tree structure. $\endgroup$ Jan 11, 2018 at 8:35 • $\begingroup$ Anything where you need a stack data structure to implement iteratively is a potential candidate, including the en.wikipedia.org/wiki/Ackermann_function (which has the advantage of not needing a data structure as input.) $\endgroup$ Jan 11, 2018 at 18:17 • $\begingroup$ @StigHemmer Lookup over ordered sets (e.g. std::map) or sets with string keys (usually in the form of a trie), abstract syntax trees, network flow (minimum spanning trees), pathfinding (really, almost anything involving graphs will have a tree somewhere), hierarchical clustering, minimax, suffix trees... It's like asking when you'd use an array, or a variable; I'm almost not sure where to start. Of course, some of these also have non-tree-based ways to do them, and the exact functions will differ from the binary search tree example, but they'll all use recursion somewhere. $\endgroup$ – Ray Jan 11, 2018 at 18:40 8 $\begingroup$ Operating on the key word, motivate, I do believe that Andrew T. had the best choice with Tower of Hanoi. Yes, it's an old one, and it does not lead to anything useful once it's done, (the code is not reusable for some other "real world" problem.) Yet it remains a classic for some reason. I'm going to speculate that the reason is that when presented properly it motivates the students to think about using recursion for other purposes. As to what the motivation is - simple: less work! AKA - unmitigated self-interest. Who doesn't like the idea of getting something done fast and easy, preferring instead to do it the long and hard way while getting the exact same results? That suggests that the motivation comes from the presentation, not from the example used. With the Tower of Hanoi example, adding in the "legend" of the back story can help with interest, but it can also be a waste of classroom time. Using the legend, or not, is a judgment call for your class and your style. (I have encountered at least three versions of the legend, and I am partial to the version that mentions the walls of the temple crumbling into dust and the world vanishing.) The key to the presentation is to begin with solving it using an iterative approach. Preferably even before you raise the idea of recursion, leaving the alternative as a way out of the maze later. In a comment, Eric Lippert states that it is easier to solve with an iterative algorithm using these steps and rules: "number the disks in order of size; never move a larger disk onto a smaller disk, never move an odd disk onto an odd disk or an even disk onto an even disk, and never move the same disk twice in a row." That sounds good, and you can present it, just as given, in the classroom. Before trying to code it, however, give it a try physically. Using that rule-set with 5 disks I get the following: • Only disk available is 1, move 1 from A to B. • Disks 1 and 2 are available, just moved 1 so only 2 is left. It cannot go on top of 1 (reverse sizes) so move 2 from A to C. • Disks 1, 2, and 3 are now available. 2 just moved, and 3 cannot go on top of 1 (reverse sizes) or 2 (reverse sizes), so 1 must move. 1 cannot go on 3 (odd on odd), so move 1 from B to C. • Disks 1 and 3 are available. Disk 1 just moved so we must move 3. It cannot go on 1 (reverse sizes) so move 3 from A to B. • Disks 1, 3 and 4 are available. Disk 3 just moved, so only 1 and 4 can move. 4 cannot go anywhere (reverse sizes) so 1 moves. 1 cannot go on 3 (odd on odd), so move 1 from C to A. • Disks 1, 2, and 3 are available. 1 just moved, 3 cannot go anywhere (reverse sizes) so 2 moves. 2 cannot go on 1 (reverse sizes), so move 2 from C to B. • Disks 1 and 2 are available. 2 just moved, so 1 is next. 1 Can go on top of 2, OR to the empty post. The given rules offer no guidance for the next move, and computers must have rules to follow. There is another iterative approach, which does work for creating an algorithm. It has a setup rule, a movement rule and a cycle to repeat. The puzzle usually does not give the arrangement of the posts, only that there are three of them. It is commonly displayed, or presented, with the posts being in a straight line. It can, however, be presented as an arrangement of three posts in a triangular formation, like the image below. In either case, working this iterative approach needs to treat the set of posts as a wrap-around collection, being able to move between the posts infinitely in either direction. The triangular formation makes that easier to visualize than the linear formation. triangular Hanoi puzzle If we consider the top-left as post "A" (the source post), the top-right as post "B" (the target post), and the bottom-center as post "C" (the working post), then the setup rule is: For an odd number of disks, the smallest disk moves clockwise, and for an even number of disks the smallest disk moves counter-clockwise. The movement rule is: With the disks numbered from smallest, as zero, to largest, disks with an even parity always move the same direction as the smallest disk, and disks with an odd parity always move in the reverse direction. Finally, the cycle for the moves is: 1. Move the smallest disk. 2. Move the only other "legal" move. Using that two-move cycle, following the movement rule, will solve the puzzle in the smallest possible set of moves. Performing that in class with a 6-disk set shouldn't take very long (about 90 seconds without commentary, 2 or 3 minutes with decision commentary). Especially true if you have previously labeled the disks with their numbers, and marked them in some fashion to show which way they move so that you don't get confused during the demonstration. (Overheads, projector, or animation on screen works as well, but physical objects may have an enhanced long-term effect.) Now, you have the students primed to learn the power of recursion. The rules for the iterative solution are oh, so simple. Turning those rules into an actual no-fail algorithm, with decisions mapped out, is not so simple after all. As humans, we can see, instantly, where the smallest disk is, which disks are able to move, and almost instantly reject the illegal moves when there are two open disks at the same time. Setting all that human ability into formal codified logic that can be followed blindly and achieve the desired result turns out to be much more difficult than it sounds. Having not dealt with Hanoi since the middle 1980s, I think I can consider myself as having an almost fresh perspective on the problem. Trying to codify the algorithm for the above rules took up quite a bit of my spare time. I cannot put an amount of clock time to it since it was a "between-times" progress when other issues weren't pressing. Still, it took me the better part of a day to be confident in my algorithm and put it into code. With that in mind, I'm not sure if you should task the students with converting the above rules into a formal algorithm or not. Perhaps you can walk the class through developing one or two of the decisions within the algorithm to give them a sense of the work involved. The main objective of the presentation up to this point is to help them to see, or experience, how much effort goes into creating the solution using the coding skills they have. Then they are ready to see the power that recursion can give them when the situation is right. Re-address the Hanoi puzzle to show that is can be reduced to a collection of smaller sub-problems that are the same as the original problem, except for size. Any solution that works for the main problem also works for the smaller sub-problems, and any solution that works for the smaller sub-problems also works for the main problem. Use that recognition to design a recursive approach to the solution. Hopefully, the amount of time spent finding the (un-coded) recursive solution is nearly the same as was spent finding the (un-coded) iterative solution, showing that finding the basics for the solution is pretty much the same for either approach. Then the magic happens when the un-coded recursive solution is written into pseudo code, or live code in the chosen language. If you have a coded version of the iterative solution to present, and then they write, or are shown, the recursive solution, they will see that dozens of lines have been reduced to about a dozen (depending on the language used). Reduced lines, with simpler logic means less typing, less chance for bugs and errors, and less work for them. Once they see the benefits of recursion, you can also deliver the caveats (with examples if you have them) which includes: • The recursive solution may not be the shortest • The recursive solution may not be the fastest • A recursive solution may not exist for a given problem • A recursive solution might take longer to create than an iterative vesrion • Recursive solutions can create issues with the stack, and memory management • Recursion is not, by itself, faster or slower, than iteration • Recursion has to have the base case built in to the model, there is no outside decision maker This is also a case where the recursive solution is faster, significantly, than the iterative solution. Running a series of time trials, with the output comment out and disk count set to 25 (33,554,431 moves), the iterative solution averaged 1m22.4s and the recursive solution averaged 0m28.4s. Granted, my code is in Perl, and most of your classes are in Java, C++, or a functional language, so it would have to be converted for use in your languages. I took advantage of a few of the patterns inherent in the puzzle solution, and stated the "tricks" used in the comments. I did not, however, try for serious optimization or other forms of code cleaning. In spite of that, this is the final version of a tested, and timed, version of the Hanoi puzzle using an iterative approach: #!/usr/bin/perl use strict; use warnings; use 5.10.0; my $disks = 20; # How many disks to use for the game. sub move_tower_iterative { # (height of tower, souce post, destination post, spare post) my ($height, @names) = @_; # Collect the parameters my @posts = ([reverse (0 .. $height-1)], [], []); # The post, to track the state of the game my $rotation = ($height % 2)? 1 : -1; # Direction the smallest disk moves # 1 is source -> destination -> spare -> source ... # -1 is source -> spare -> destination -> source ... my ($disk, $from, $to) = (0) x 2; # Temporary data, pre-loaded for the first move do { # Figure out where the disk to be moved will go $to = ($from + $rotation * (($posts[$from][-1] % 2)? -1 : 1) + 3) % 3; # Take the disk off the top of one post $disk = pop $posts[$from]; # Add it to the top of the other post push $posts[$to], $disk; # Say what we did printf "\tMove disk from %s to %s\n", $names[$from], $names[$to]; # Find the next legal move if ( 0 != $posts[$to][-1] ) { # Was the smallest disk NOT the last move? Then move it. # It will be found where the just moved disk would move to, if it was to move again. $from = ($to + $rotation * (($posts[$to][-1] % 2)? -1 : 1) + 3) % 3; } else { # Not moving the smallest disk means finding the one other legal move while ( # Starting with the same post we just moved from check if ... ( -1 == $#{$posts[$from]} ) # The post is empty || ( # OR both ( -1 != $#{@posts[($from + $rotation * (($posts[$from][-1] % 2)? -1 : 1) + 3) % 3]} ) # The destination post is not empty && ($posts[$from][-1] > $posts[($from + $rotation * (($posts[$from][-1] % 2)? -1 : 1) + 3) % 3][-1]) # AND has a smaller disk ) || ( # OR both ( 0 == $posts[$from][-1]) # The post has the smallest disk && ($#{$posts[$from]} != $height-1) # AND the post is not full ) ) { # Keep looking for by cycling to the next post $from = ++$from % 3; } } } until ($#{$posts[1]} == $height-1); # Stop when the destination post is full } move_tower_iterative $disks, "Back-left", "Back-right", "Front" ; # Start moving. 1; To balance that out, and to show the difference, here is the recursive version, also tested and timed. In this case I've removed the comments, just as a visual enhancement of the difference between the two versions: #!/usr/bin/perl use strict; use warnings; use 5.10.0; my $disks = 20; sub move_tower_recursive { my ($height, $source, $dest, $spare) = @_; if ( 1 <= $height) { move_tower_recursive($height-1, $source, $spare, $dest); printf "\tMove disk from %s to %s\n", $source, $dest; move_tower_recursive($height-1, $spare, $dest, $source); } } move_tower_recursive $disks, "Left side", "Right side", "Center" ; 1; $\endgroup$ 3 • $\begingroup$ This is the best answer for motivating recursion, in my opinion. $\endgroup$ – justhalf Jan 15, 2018 at 17:12 • $\begingroup$ @justhalf Welcome to Computer Science Educators. I hope we see you around here often. I don't like Tower of Hanoi puzzle as a project because the work, or the solution to it, cannot be reused. Yet, when presented well, it can show the power of recursion and motivate students to explore the technique and develop the mental muscles to use recursion when appropriate. $\endgroup$ Jan 15, 2018 at 17:22 • $\begingroup$ Which is exactly what the question is about! =) And I said your answer is great, not just the Tower of Hanoi. $\endgroup$ – justhalf Jan 15, 2018 at 18:32 6 $\begingroup$ Several answers have said things like "We need recursion to handle tree structures." The problem with this type of answer is that the student then asks "Why would we have a tree structure in the first place?" @Syndic's example of handling directories with subdirectories is probably the best answer, but there are others. My favorite example where recursion feels natural is Parsing. For many parsing tasks, a recursive descent parser is the easiest approach to take. For example, parsing JSON: The top level will something like ParseItem, a function that takes an input stream and returns an data item corresponding to the JSON found there. This function looks at the first characer to find out what type of item it should parse. Depending on this, it will call ParseObject, ParseNumber, ParseArray, ParseString or whatever. Now, ParseArray will set up an array and starts parsing items to fill it with. How does it do that? Why, it calls ParseItem! Recursion! $\endgroup$ 2 • $\begingroup$ Thank you for coming back to improve your answer! I hope that you'll continue to share your knowledge here at Computer Science Educators. $\endgroup$ – thesecretmaster Jan 15, 2018 at 13:14 • $\begingroup$ Whatever language they are coding in, their understanding/definition of it is recursive. $\endgroup$ – philipxy Nov 14, 2018 at 21:20 4 $\begingroup$ Construct an immutable nested structure It's obvious (to us instructors) that in a purely functional language, recursion is the only way to create nested structures. And immutable data is imperative (pun intended) for proper semantical reasoning about values. So what kind of examples lend themselves to an intuitive recursive approach where an imperative approach is much harder? • Nested data structures like linked lists, trees and graphs are most easily traversed and constructed recursively. Linked lists are too simple, the tail recursion has the same idea as the equal imperative loop and can be written as such without involving an explicit stack. Graphs are too complicated as keeping state (e.g. to avoid infinite descend) and creating cycles is easiest to do using mutation, and many introductory graph algorithms do keep an explicit queue of nodes. Graphs without cycles are just trees. Here I would avoid n-ary trees where nodes keeps lists/arrays/vectors of children, as those again would typically be accessed in an (imperative) loop, which confuses the students (making the gist of recursion harder to recognise, and obfuscating the base case). So binary trees it is. A simple tree of integers can be summed, scanned for its maximum and/or minimum, and mapped over with e.g. an incrementing or doubling transformation. It might even be filtered for odd/even numbers. Later you can introduce the respective abstractions (fold, map, filter) if you want. I would recommend to avoid algorithms for balancing trees here, those are often rather unintuitive when expressed recursively or at least differ much from the imperative approach that is found in most teaching material. • Immutable data structures cannot be re-initialised or changed during traversal. This again prevents imperative solutions e.g. in the map exercise. If you are using a functional language in the course, this requirement is probably easy to place. However this doesn't satisfy imperative-minded students who will think "if I could just mutate the data (like in $favouriteLanguage) this task would be much easier". If you are dealing with an imperative language, you will need to make up some excuses for why immutability is necessary. Constructing not a single but many distinct results helps here. They might be output as a side effect, but are going to get used later after the algorithm ended. Building an animation sequence that can be replayed later (and also rewinded, or run backwards) might be a good idea, which also provides the students with some visualisation. Computing permutations as suggested by Ben I. is a perfect take on this - instead of just printing all permutations (doable by mutating a sequence) many distinct arrays/lists need to be created. Computing the power set, the subsequences or substrings of an input are similar tasks (and don't even require loops because of the nature of the binary decisions). Here, the concept of sharing between data structures can be introduced as an advantage of immutability later in the course (demonstrated by memory requirements of responses to huge inputs). $\endgroup$ 1 • $\begingroup$ Excellent, helpful answer. Welcome back! :) $\endgroup$ – Ben I. Jan 11, 2018 at 3:24 4 $\begingroup$ Another approach, entirely different from my other answer, is to ask students how they might approach the following real-life scenario: they have just been given 1400 paper forms, all filled out by potential enrollees for a program. The forms arrived in the mail and are in no particular order, but they must be sorted into one of 4 geographical regions, and then alphabetically by last name/first name. The student has been situated in a meeting room with a giant, empty table, and boxes full of forms. The student is told that the sorting needs to be done before the end of the work day. Of course, the activity itself is boring, and the student would love to get out of there as soon as possible. What approach might the student take to the task itself in order to get it done accurately and on time? Typically, someone will almost immediately suggest sorting the sheets into subpiles. One logical number of subpiles for this first case is 4: divide into 4 piles by geographic region. Now repeat the procedure, dividing into further subpiles. While a true computer algorithm might use 4 piles again, a person would more likely use 26 piles (for the letters of the alphabet). At that point, look at the size of the piles. Repeat the procedure as many times as you need on any piles that are large enough to still be unwieldy. At some point, you will have a series of tiny piles. A person would probably sort these small piles using some form of insertion or selection sort. We would now reverse the process, taking our tiny sorted piles, and recombining them into larger and larger fully sorted files. These would be our recursive unwinding steps. This entire procedure is not dissimilar from a standard mergesort (or, really, a recursive bucket sort). Divide the problem, conquer the smaller pieces, and then recombine. Breaking the problem into smaller subproblems is what makes the entire enterprise more manageable. What's nice about this procedure as a motivator for examining recursion is that it, with only minor variations, is the natural solution that most people arrive at when faced with such a daunting sorting task because the benefits are clear and natural. $\endgroup$ 12 • 1 $\begingroup$ I don't have problems thinking of recursive methods, but I do struggle to see how this will help. From a code POV, it will look something like: for (s in sheets) { switch (s.region) { a: region[a].append(s) ...} }; parallel for (r in region) { for (s in r) { switch (s.name[0]) {...} } }, and the students will still see it as imperative, though it can be written in a recursive form more easily. $\endgroup$ – muru Jan 10, 2018 at 5:37 • 4 $\begingroup$ Hmmm, I'm not entirely certain that students would grasp that sorting on more than one key by sorting first on one key and then on another key actually IS an example of recursion. That sounds a little funny even to me. $\endgroup$ – Wildcard Jan 10, 2018 at 5:41 • 1 $\begingroup$ You just proposed an iterative approach. $\endgroup$ – user253751 Jan 11, 2018 at 0:08 • 1 $\begingroup$ @BenI. Putting the forms into 4 piles is an iterative loop. Putting the forms from those 4 piles into 26*4 piles is just two nested loops. It's not recursive because you are just saving up all the work from one step until you're done with that step. See muru's comment. $\endgroup$ – user253751 Jan 11, 2018 at 1:53 • 1 $\begingroup$ @BenI. I think the major problem of the algorithm is the fixed recursion depth of only two levels. If you had done something like "split by 4 regions. Every pile higher than 10 sheets, split by first letter of name. Every pile higher than 10 sheets, split by second letter of name. Every pile still higher than 10 sheets…" the recursive approach (with "small enough pile" as base case) would have been clearer. Using different things (4 regions and 26 letters) in the two first steps didn't exactly help either. $\endgroup$ – Bergi Jan 11, 2018 at 13:14 4 $\begingroup$ When teaching recursion, it is important to emphasize that the true power of recursion comes from its ability to branch. This rules out all the factorial and other similarly silly recursion examples much better written as for-loops. Have your students write a function that, given an open tile in Minesweeper whose value is zero, opens all the tiles in the neighbourhood that are safe to open. I have used this example for about 15 years in intro to Java course, and think it is the best way to show the usefulness of recursion in a first year course. Solving the subset sum problem in an integer array is another great example of branching recursion that is only three lines of code using recursion, and a lot more without it. $\endgroup$ 2 • $\begingroup$ This is not only a gorgeous problem, but would also work very well in an Objects-first curriculum. $\endgroup$ – Ben I. Jan 11, 2018 at 15:24 • $\begingroup$ Oh, and welcome to Computer Science Educators. I hope you'll join us in our mission here! $\endgroup$ – Ben I. Jan 11, 2018 at 15:26 4 $\begingroup$ Show them how they use recursion in solving puzzles in their civilian life. Sudoku Ask them how to solve Sudoku. What's the naive way? You have to iterate through all (roughly) 9^81 numbers, checking each board. Assuming each check takes on plank second (we're not even close to that in real life), it will take about 3.35843803 × 10^26 years years to solve each Sudoku puzzle. That's way after the earth falls into a black dwarf sun. So how do we solve it? Recursion. Find the "easiest" block to solve (meaning, the one with the least possible variation). Let's say it's the next small board: | _ | 3 || 4 | _ | | 2 | _ || _ | 1 | --------++-------- | 3 | 2 || 1 | _ | | 4 | _ || 2 | 3 | So you that first blank could be a 4, 3, 1 or 1. So what do you do? You fill a four. Then you check the board: | 4 | 3 || 4 | _ | | 2 | _ || _ | 1 | --------++-------- | 3 | 2 || 1 | _ | | 4 | _ || 2 | 3 | Does it work? No. There are two fours in the first column. Try the next, and the next... until you get a one. | 1 | 3 || 4 | _ | | 2 | _ || _ | 1 | --------++-------- | 3 | 2 || 1 | _ | | 4 | _ || 2 | 3 | Hey, that works!! Let's move to the next blank. And you recursively [1] check each square. How does it work? Because each problem is a subset of the previous problem. Here is a sample solver of a given Sudoku board (The website I found it labeled it as "very difficult"). The program solved it in less than a second, going through only 40,000 iterations. In reality, that's how most people actually solve the problem (ever seen people writing small numbers in each square, erasing ones that don't work? That's your stack!) [1] In this case you don't need recursion, because the board is too simple. But if you take a real board with moderate difficulty, you need to take steps in, check if they work, and if not, pop out until there's another way to solve it. In short, you push and pop solutions, which is easiest to do with recursion. A Maze How do you solve a maze? You go down one path? If it doesn't work you pop back to the last state where there's hope and try again. Solving arithmetic problems How would you solve (1-2)/((1+2)/(3-4))? Let's assume for a moment that all order-of-operations have been taken care of through parenthesis. The simplest way would be a recursive-descent parser. 1. Lex it. You now have the following lexical array: [( 1 - 2 ) / ( ( 1 + 2 ) / ( 3 - 4 ) )] 2. Start at position 0. 3. Go block by block: 1. If it's a regular block (a number): do something like: DoMath(curVal[pos],curVal[pos+1],curVal[pos+2]) pos = pos+2 2. If it's a 'control character' (a parenthesis in our example): 1. Recurse back to 3, with the 'end control character' being a 'close parenthesis'. 2. Replace 'n' characters (the length of the inner parenthesis expression) with the the return value. 4. If it's an 'end control character' (a 'close parenthesis' or an 'end-of-string tag'): Return the value that's left after all that work. $\endgroup$ 10 • $\begingroup$ This is a really interesting first answer! Welcome to Computer Science Educators, @cse! I hope to see you around more! $\endgroup$ – thesecretmaster Jan 11, 2018 at 0:52 • $\begingroup$ You can do the naive way easily with recursion as well though :D $\endgroup$ – Koekje Jan 11, 2018 at 12:48 • $\begingroup$ @Koekje Well, you wouldn't want to spend too much time on an algorithm that would never work in reality. With the recursive approach, you've only wasted about 10 minutes of your life writing the naive version. :-) $\endgroup$ – Ray Jan 11, 2018 at 18:56 • $\begingroup$ @Koekje anything done with recursion could be done iteratively (through a stack data type stored in heap), and anything done iteratively can be done with recursion (as is typically done in languages without mutable variables). The real point is where is recursion more elegant (especially for beginners, especially if you're teaching them a language which supports mutable variables - which 99% popular languages do - R and MATLAB (I may be wrong as I don't know them at all) seem to be the only exception in TIOBE's index). $\endgroup$ – cse Jan 11, 2018 at 19:06 • $\begingroup$ @cse Yes I know. Generally with method calls behind the scenes a stack is operating anyway, so the recursion will indirectly be translated to an iterative approach. The point I was trying to make, but failed to do, is that for me it seems like you could interpret the answer as recursion being a whole different beast, automagically opening up a vastly improved way to solve the Sudoku. I do not however see how recursion is more elegant with languages containing mutable variables. Isn't it the other way around? Why are most functional languages built on using recursion? $\endgroup$ – Koekje Jan 11, 2018 at 19:42 3 $\begingroup$ I'd suggest some version of string length, implemented recursively. It's even simpler than factorial. You just break one character off the string, feed it to a recursive call and add one to the result. With that we can teach the essence of recursion. I find programmers often get confused by trying to "be the computer" working out the recursion to depth rather than working abstractly. So, one trick is to get the aspiring programmers to look at the recursive invocation as a black box rather than to try to think of what's happening at depth. Within the implementation of a recursive function, we want to be able to use the recursive function as if we are merely a client consuming some other function (that already exists and provides some usable capability) with little to no concern about the actual recursion itself. We always have to switch our hats from provider of an implementation to consuming client. The trick with recursion is to be able to do that with the same function as its implementation is itself a consuming client (of itself). One approach is to start something like this: int string_length(char *str) { if (*str == '\0') return 0; return 1 + strlen(str+1); } With the objective of looking at strlen() as a black box that just works (here: just what it does for us, not how), and then understanding how this string_length() works (e.g. just those three lines of implementation). Then introduce the idea that since we have confidence that string_length() works — that it does the same thing as strlen() — we can use it in our own implementation: substituting string_length() for strlen(). $\endgroup$ 1 • 5 $\begingroup$ This is a nice, clear example of recursion, but is it a good motivating example for the entire process? The iterative version (such as the simple for loop) is both more efficient and simpler to write. $\endgroup$ – Ben I. Jan 10, 2018 at 3:32 3 $\begingroup$ If the students have learned object-oriented programming then network-traversal or tree-exploration works well because it is easier to visualize one node calling another than to visualize a method calling itself. Start with a directed graph with no cycles so you don't get infinite loops. //returns true of this is part of the path public boolean findLastNode(List<Node> pathSoFar) { if (this.isLastNode()) { path.add(this); return true; } for (Node aNeighbor:this.getNeighbors) { if (aNeighbor.findLastNode()) { path.add(this); return true; } } return false; } The code is easy to visualize and draw on the whiteboard because each recursive call moves you across the graph, and you can visualize each node having its own copy of the findLastNode method so you don't have to think of the flow of control reusing variables that are already holding other data. $\endgroup$ 1 2 $\begingroup$ Since these did not need to be programming examples, here is another example that I like to use and have found illustrative. When you need to write a method to solve some problem, you must write that method using the things that you already have: the statements in the language, and the methods already in the standard library or written by you. Your job is to find the right combination of these that will achieve the job. For example, if you need to define the factorial function, you would do so with the definition $F(n) = n * (n-1) * ... * 2 * 1$ where the right hand side contains a for-loop and a whole bunch of multiplications, two things that you already have in the language. So we can implement factorial using the things that we have. But imagine this now as some fantasy type of setting, where this equation is a game of tug of war where the left hand side and the right hand side must pull with equal strength to balance each other out. On the left hand side, $F(n)$ is a big strong mountain giant. If the right hand side consists of little hobbits (each multiplication operation), we will necessarily need a large number of hobbits to be able to pull together as hard as the one mountain giant on the left side. Spotting the self-similarity in the above definition allows us to turn this into an equivalent recursive definition $F(n) = n * F(n-1)$ which at first seems like cheating, since we are borrowing the function $F$, the thing that we were supposed to define, from the future to be used in its own definition! What do we gain from doing this trick? Well, since $F(n-1)$ is now on the right hand side, it is now a big friendly giant that is pulling for us, instead of pulling against us, in this game of tug of war! Nothing in that observation depends on the fact that $F$ is particularly the factorial function. In fact, the more complex and powerful the giant is when placed on the left hand side (for example, consider the problem of parsing), the more powerful it is also when it is working for us on the right hand side. This realization allows us to solve arbitrarily complicated problems by using a slightly smaller version of those problems on the right hand side. In the game of tug of war between one giant and one slightly smaller giant, we only need to add a couple of small hobbits on the right hand side to balance the whole thing, instead of having to put down some large number of small things to balance one big thing. This is the power of recursion. $\endgroup$ 1 • $\begingroup$ This some interesting hand-waving and analogy, but does nothing to change the fact that prod *= i; in a loop is just as easy to write, and runs faster (unless the compiler optimizes your recursion back into a loop). The problem has no stack-like state that needs to be preserved for back-tracking, so recursion isn't helpful or necessary for factorial. I know you didn't mention Fibonacci, but recursive Fib is even more dumb because it takes O(Fib(n)) time instead of O(n) time for a a+=b; b+=a; loop. Recursive Factorial doesn't make the complexity class worse, so it's not as bad an example. $\endgroup$ Jan 11, 2018 at 18:39 2 $\begingroup$ In my first programming class, I "discovered" the concept of recursion on my own, before it was introduced by the instructor. It wasn't the typical use-case for recursion, but it was enough to jump start my thinking. I was creating a really simple 2D tile based game, and was working on the graphics. I had a function that took an ID number that represented what kind of tile to draw, and the X,Y coords to draw it. I had already implemented grass (ID 1), by simply drawing a green rectangle, with a few pixels of off-green. When I went to draw a Tree (ID 2), the tree was supposed to have a grassy background behind it. I didn't want to duplicate the grass drawing code again for the tree Tile, and after thinking about it for a while, I thought "Hey, I could just call the drawing function again, and tell it to draw the Grass tile at the current coordinates, then draw the tree over top of it." I asked the teacher if a function was allowed to call its self. He got a strange look on his face, and asked me to show him what I was doing. He explained a little bit about what was actually happening, and told me that what I was doing actually had a name. He said that it would be covered in a lot more detail in a few weeks. For me, it was a simple way to see the idea of recursion as a real physical thing, without having to deal with the mathematical abstractions that things like the Fibonacci Sequence require. $\endgroup$ 2 • $\begingroup$ Now that is a cool story. Welcome to CSEducators. There is a lot here that might interest you. $\endgroup$ – Buffy Jan 12, 2018 at 13:16 • 1 $\begingroup$ You didn't quite state this, but your answer brings up the possibility of seeding the field by simply utilizing recursion in front of the class at some prior time. The way I envision it, I would point it out, but leave it largely unexplained until we got to the proper unit. This would serve to let them know that the possibility existed and feed their curiosity naturally, so that when we later get to the unit, they would be interested in exploring that oddity. (If you like that, feel free to integrate it; it would also give a classroom tie-in, which you are currently missing.) $\endgroup$ – Ben I. Jan 12, 2018 at 13:18 2 $\begingroup$ I think what makes Factorial and Fibonacci popular as teaching examples is that they have no input data. This means student implementations can start from scratch, instead of being given some boiler-plate data declarations. (Or requiring the students to write code to create a binary tree or something.) The Ackermann–Péter function A(m,n) has 2 integer inputs and one integer output so it's nice and simple like Factorial (no pointers or references to any data structures). But its natural definition is recursive, and iterative implementation requires a stack of some sort, so a recursive implementation is easier than iterative. It's not ideal (for testability over a range of inputs) that it grows so quickly, and you may need to introduce the concept of integer overflow (with wraparound, or undefined behaviour in languages like C for signed int). On the other hand, students will probably think it's cool to have a function which can produce such large outputs from small inputs. A(4,2) has 19,729 decimal digits. But with m=[0..3], the result fits in a 32-bit integer for a wide range of n, so it's testable. IMO recursive Fibonacci is a really horrible example. It has O(Fib(n)) complexity instead of O(n) time for an a+=b; b+=a; loop. Recursive Factorial at least has the same complexity class as iterative, but it doesn't require keeping any state. In an assembly-language assignment (especially when args are passed in registers), Factorial also fails to fully test recursion because no registers need to be saved/restored (except the return address for RISC architectures like MIPS that use a link register instead of x86-style call/ret pushing/popping a return address). There's not much difference between an iterative loop and the body of a recursive implementation. You could get implementations that recurse down to the bottom and then just multiply by an increasing counter while returning back up the call chain. Recursive Fibonacci avoids this problem: needing to make two separate calls from the same function means it can't degenerate into a loop. But we'd like to reject Fib because it makes recursion look like a stupid way to make programming harder, especially in assembly language. (Do people really give recursive Fibonacci assignments in assembly language? Yes, they do, and Stack Overflow has the questions from their students to prove it. It is one of the simplest doubly-recursive functions (significantly simpler to implement in asm than Ackermann), but it's maybe so simple that it's not as obvious which state is the "important" state that needs to be saved/restored across child calls.) A recent Stack Overflow question on MIPS assembly (from a student assigned this homework) appears to have found some useful middle ground here with a function that has similar doubly-recursive structure to Fibonacci but is less trivial, making an iterative implementation less obvious. And also simply not being a well-known function means that there aren't implementations of it all over the web in many languages, reducing the temptation to copy/paste. • if n>5 : f(n) = n*f(n-1) - f(n-3) + n-23 • else n<=5 basecase f(n) = 15 - 2n An iterative implementation is still easily possible and obviously more efficient, especially for large n without memoization. But this has a couple useful features that make it better than Fib(n): • The base case includes more n values, and is not totally trivial. Initializing vars for an iterative implementation would take some care. • Using f(n-3) and skipping f(n-2) means iterative would have to keep more temporaries, but doesn't add complexity to a recursive case. • Using the original n after both of the recursive calls (to multiply the return value, or add to the total) motivates properly keeping it around. (vs. maybe writing an asm function that preserves its input register, and just decrementing that again to create an input for the next call. That would work but is totally non-standard for normal C calling conventions.) • Clever students will notice that n can be destroyed by the 2nd recursive call, doing n - 23 + n*f(n-1) early because integer + is associative. Otherwise they'll have to save both the first return value and the original n if they evaluate the expression in the order written. • It's not Fibonacci so it's not recognizable as a well-known thing that can be looked up or that some students will already know about. Tree traversal is one of the best example use-cases for recursion, because you need to remember where you've been at each step of the problem, so any solution needs a stack data structure. Using recursion lets you use the call-stack as your stack. But you need a tree to traverse, so it's not as "simple" as Factorial. And it's easy to see that it's a useful thing to do. $\endgroup$ 3 • $\begingroup$ Excellent answer. Welcome to Computer Science Educators. I hope we see you around more. We have a few questions that broach the subject of assembly language level thinking here as well. Maybe you will find them interesting and worth answering. $\endgroup$ Feb 23, 2018 at 4:16 • $\begingroup$ @GypsySpellweaver: I had a look at some of the questions, but I don't know much about teaching asm to people who don't get it. I literally don't understand why people find asm hard to learn, because it wasn't for me. It's like building a robot; you put some pieces together to create a machine that does something useful one step at a time. I know some people "don't get it", but I don't know how to put myself inside their head to understand why not, or if there's something you could tell them that would let them think about asm (and how computers work) in a useful way. $\endgroup$ Feb 26, 2018 at 2:03 • $\begingroup$ It was worth a try anyway. $\endgroup$ Feb 26, 2018 at 2:45 1 $\begingroup$ When i was introduced to recursion, i felt the same on why learning something i don't need but using iterative approach on complex situations like Tower of hanoi etc., using recursion seems to be more simpler in logic as well as programming. The reason i like recursion: You don't need to solve or think about whole solution. You can break the whole problem in smaller ones, and use those solution to solve the bigger problem. And this helps to think more clear logic for your problem. Algorithms that makes sense using recursion: • Tower of Hanoi • Quick sort • Graph traversal(Inorder, preorder, postorder) • and so on... If you want the students to feel interested in it, you can try giving an assignment of solving tower of hanoi using iterative method. And then using recursion, the students will themselves know which method to use where and why :) Note: Look for ackermann function as well. $\endgroup$ 3 • 1 $\begingroup$ Welcome to CSEducators. I like this answer. If you want to improve it you could add a link or two, especially to a writeup of Ackerman's function. Better yet, explain a bit about why it is important. $\endgroup$ – Buffy Jan 11, 2018 at 20:21 • $\begingroup$ This list of possible algorithms doesn't really add anything to the already existing answers. Can you add some depth so that your answer adds to the other answers rather than simply restating them? $\endgroup$ – thesecretmaster Jan 12, 2018 at 18:28 • $\begingroup$ Well, better show recursion on example where the recursive approach is the obviously simplest solution to a problem. Not everybody comes quickly to a solution to the Hanoi problem, if ever. Same for sorting. $\endgroup$ Jan 15, 2018 at 9:59 1 $\begingroup$ From Douglas Hofstader's Metamagical Themas, comes the idea of the Porpuquine. A nine quilled porpuquine has nine quills, each of which is an eight quilled porpuquine. Of course an eight quilled porpuquine has exactly eight quills, each of which is a seven quilled porpuquine. Etc. Of course, you can explore Quine. And you can do some computing. The more complete story in the book is worth a look, of course. $\endgroup$ 0 $\begingroup$ The answers are fantastic but what I see you looking for is a motivation for using recursion over other methods. The answer goes back to why one goes to school in the first place. Not to learn what we already know but what others know, which will in the long run prove valuable. The reason we use recursion generally is not because it is the only solution (well trained CompSci grads can think of little else) but because it is what computers are good at. Particularly; 1.Starting a problem. 2.Putting it onto the stack in order to 3. Go to another problem. This is done all the time. The point of recursion is that each of these steps is for the same purpose. It is not until all the processes are done that they look around to see that there was only one goal, not O sub n goals. Using minor examples can show off the major achievement of this level of organization. $\endgroup$ 4 • $\begingroup$ Welcome to CSEducators. We hope to see you back again. $\endgroup$ – Buffy Jan 10, 2018 at 19:32 • 3 $\begingroup$ There doesn't seem to be an example here responding to the question. Are you saying none are necessary? Can you clarify? $\endgroup$ – Buffy Jan 10, 2018 at 19:33 • $\begingroup$ I agree with Buffy. This does not appear to actually answer the question. If you want to discuss the question's premise, feel free to do so in the chat room I mentioned in my comment on the question. $\endgroup$ – thesecretmaster Jan 12, 2018 at 18:25 • $\begingroup$ I think the brief answer gave the structure of why recursion is useful based on what computers do well. This goes to the fundamental reason to teach it rather than more and more examples of it. $\endgroup$ – Elliot Jan 14, 2018 at 19:07 -1 $\begingroup$ Water is a good example, when you pour a jug of water compare it to the algorithim the algorithim or water is continually poured until there is no more water left or the base condition is satisfied, leaving you with a solution, comparing a water fall to a bad case of infinite recursion it just continues flowing. $\endgroup$ 2 • 1 $\begingroup$ Welcome to Computer Science Educators! How will the example of water illustrate to students why they need to learn recursion? $\endgroup$ – Ben I. Jan 12, 2018 at 23:18 • 1 $\begingroup$ To add to what Ben said, this same task could be accomplished with a while loop. Why would this example help students see the necessity of recusion? $\endgroup$ – thesecretmaster Jan 13, 2018 at 1:12 Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.716833
Solved Excel VBA - format a Shape same as a Cell Posted on 2016-11-17 7 42 Views Last Modified: 2016-11-18 I'm trying to create a simple Highlight ON/OFF on a Shape. In the attached example, when the Turn ON button is clicked I want the Shape 'Save' to take the format of the 'On' cell C6. When the Turn OFF is clicked I want it to be like D6, including the Border color as Outline. (Recording the macro didn't quite give me the answer, as I want to be able to format C6 and D6 in any color, but shapes seem to want to know only RGB) Thanks. Toggle-Button.xlsm 0 Comment Question by:hindersaliva • 4 • 2 7 Comments   LVL 47 Expert Comment by:Wayne Taylor (webtubbs) ID: 41892391 What do you mean by the "Turn ON" and "Turn OFF" buttons? I see only one shape on the worksheet named "btnSave". 0   LVL 81 Expert Comment by:byundt ID: 41892466 I revised your macro so it would toggle the color on the Save button between red and black: Sub ToggleColor() With ActiveSheet.Shapes("Rounded Rectangle 1").Fill .Visible = msoTrue If .ForeColor.RGB = RGB(0, 0, 0) Then .ForeColor.RGB = RGB(192, 0, 0) Else .ForeColor.RGB = RGB(0, 0, 0) End If End With End Sub Open in new window I would also suggest that you check the box for "Require variable declaration" in the Tools...Options...Editor menu item in the VBA Editor. This will put Option Explicit at the top of every newly created module sheet, and is considered good practice in VBA programming. Option Explicit means you must put every variable in a Dim statement. VBA can then catch typos in variable names for you. 0   LVL 81 Expert Comment by:byundt ID: 41892471 I see that you want to make the Save toggle between the appearance of the shapes at C6 and D6. If so, the code becomes: Sub ToggleColor() Dim shp As Shape With ActiveSheet.Shapes("Rounded Rectangle 1") .Fill.Visible = msoTrue If .Fill.ForeColor.RGB <> RGB(192, 0, 0) Then .Fill.ForeColor.RGB = RGB(192, 0, 0) .TextFrame2.TextRange.Characters.Font.Fill.ForeColor.RGB = RGB(255, 255, 255) .Line.Visible = msoFalse Else .Fill.ForeColor.ObjectThemeColor = msoThemeColorBackground1 .TextFrame2.TextRange.Characters.Font.Fill.ForeColor.RGB = RGB(0, 0, 0) .Line.ForeColor.RGB = RGB(0, 176, 240) .Line.Visible = msoTrue End If End With End Sub Open in new window If you want to determine the color of the fill or outline by reference to a cell, put the following statements in the Immediate Window of the VBA Editor. They will return the color as a Long. You can then use those values in your code as Color = qqqqqqqq instead of Color.RGB = RGB(xxx, yyy, zzz) ?ActiveCell.Interior.Color ?ActiveCell.Borders.Color -Toggle-ButtonQ28983915.xlsm 0 Is Your Active Directory as Secure as You Think? More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.   Author Comment by:hindersaliva ID: 41892742 Byundt, I get the color 192 for the cell fill color. But the assignment for the Shape is RGB. So wouldn't I need to 'translate/convert' the 192 to RGB in order to apply it to the Shape? For example, if the cell fill color happens to be 42,875? Thanks. Wayne Taylor: sorry I attached before I saved the example! It was just a button to fire off the code. 0   LVL 81 Accepted Solution by: byundt earned 500 total points ID: 41893067 I misspoke on how to use the Color value directly in the code. Since the RGB function returns a Long number, you would use Color.RGB = 42875 to set the color property to a lime green. Sub ToggleColor() Dim shp As Shape With ActiveSheet.Shapes("Rounded Rectangle 1") .Fill.Visible = msoTrue ' If .Fill.ForeColor.RGB <> 192 'RGB(192, 0, 0) Then 'Red ' .Fill.ForeColor.RGB = 192 'RGB(192, 0, 0) If .Fill.ForeColor.RGB <> 42875 Then 'Lime green .Fill.ForeColor.RGB = 42875 .TextFrame2.TextRange.Characters.Font.Fill.ForeColor.RGB = 16777215 'RGB(255, 255, 255) .Line.Visible = msoFalse Else .Fill.ForeColor.ObjectThemeColor = msoThemeColorBackground1 .TextFrame2.TextRange.Characters.Font.Fill.ForeColor.RGB = 0 'RGB(0, 0, 0) .Line.ForeColor.RGB = 15773696 'RGB(0, 176, 240) .Line.Visible = msoTrue End If End With End Sub Open in new window -Toggle-ButtonQ28983915.xlsm 0   Author Closing Comment by:hindersaliva ID: 41893135 Thanks Byundt 0   LVL 81 Expert Comment by:byundt ID: 41893163 You may find the following function useful in converting a Long Color into an RGB function call. It takes the Color number, and breaks it down into the R, G and B components. You should install the function in a regular module sheet, just like it was a macro. To use it, array-enter a formula like the following in three adjacent cells in a row. It should return 167, 123 and 0 in those cells. =GetRGB(42875) Function GetRGB(lngColor) As Variant Dim R As Long, G As Long, B As Long R = lngColor Mod 256 G = (lngColor - R) / 256 Mod 256 B = (lngColor - R - G * 256) / 256 ^ 2 GetRGB = Array(R, G, B) End Function Open in new window 1 Featured Post Is Your Active Directory as Secure as You Think? More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more. Question has a verified solution. If you are experiencing a similar issue, please ask a related question Suggested Solutions Title # Comments Views Activity What is format f12.8 for a CSV file 6 42 Format Meeting Request through VBA 5 22 Help with Excel formula 6 38 Excel 17 16 Workbook link problems after copying tabs to a new workbook? David Miller (dlmille) Intro Have you either copied sheets to a new workbook, and after having saved and opened that workbook, you find that there are links back to the original sou… This article will guide you to convert a grid from a picture into Excel format using Microsoft OneNote and no other 3rd party application. The viewer will learn how to use a discrete random variable to simulate the return on an investment over a period of years, create a Monte Carlo simulation using the discrete random variable, and create a graph to represent the possible returns over… The viewer will learn how to create a normally distributed random variable in Excel, use a normal distribution to simulate the return on an investment over a period of years, Create a Monte Carlo simulation using a normal random variable, and calcul… 863 members asked questions and received personalized solutions in the past 7 days. Join the community of 500,000 technology professionals and ask your questions. Join & Ask a Question Need Help in Real-Time? Connect with top rated Experts 24 Experts available now in Live! Get 1:1 Help Now
__label__pos
0.793512
63. Unique Paths II Problem Description You are presented with a grid represented by an m x n integer array called grid. This grid is filled with either 0's or 1's, which denote empty spaces and obstacles, respectively. There is a robot situated at the top-left corner of the grid, i.e., at grid[0][0]. The goal for the robot is to reach the bottom-right corner of the grid, namely grid[m - 1][n - 1]. The robot can only move in two directions at any given time: either down or to the right. Given these movement restrictions and the presence of obstacles (denoted by 1's), the task is to calculate the number of unique paths the robot can take to reach its destination without traversing any of the obstacles. To provide a solution, the assumption is made that the number of unique paths will not exceed 2 * 10^9. Intuition When thinking about the robot's journey from the top-left to the bottom-right corner, we can frame the problem using dynamic programming. The approach focuses on the concept that the number of ways to reach a particular cell in the grid is the sum of the ways to reach the cell directly above it and the cell to its immediate left, since the robot can only move down or right. However, when a cell contains an obstacle, the robot cannot travel through it, which means this cell contributes zero paths to its adjacent cells. Here's a breakdown of the dynamic programming solution: 1. Start by initializing a 2D array dp (same dimensions as grid) to store the number of ways to reach each cell. 2. Set the value of dp[i][0] (first column) and dp[0][j] (first row) to 1 for as long as there are no obstacles. This represents the fact that there is only one way to move along the top row or the leftmost column when there are no obstacles in those positions. 3. Loop through the grid starting from cell dp[1][1] and move rightward and downward. 4. For every cell, check if it is not an obstacle. If it isn't, set dp[i][j] to the sum of dp[i - 1][j] (the number of ways to reach from above) and dp[i][j - 1] (the number of ways to reach from the left). 5. If you encounter an obstacle, set the number of ways to 0 because the robot can't pass through obstacles. 6. Continue this process until you reach the bottom-right corner of the grid. 7. The final answer, the number of unique paths to the bottom-right corner avoiding obstacles, will be found in dp[m-1][n-1]. With this approach, we can systematically compute the number of unique paths available to the robot, taking into consideration the positioning of the obstacles. Solution Approach The solution approach for the problem is based on dynamic programming, a method for solving complex problems by breaking them down into simpler subproblems. It is a powerful technique for optimization problems like this, where we aim to count all possible unique paths in a grid with obstacles. 1. Data Structure: A 2-dimensional list dp of size m x n (where m and n are the dimensions of the input grid) is initialized with zeros. This dp list is used to store the number of unique paths to reach each cell (i, j) from the start (0, 0). 2. Base Cases Initialization: The robot can only move down or right. Therefore, if there are no obstacles in the first column and first row, there will be only one path to each of those cells — just keep moving right or down respectively. 1for i in range(m): 2 if obstacleGrid[i][0] == 1: 3 break 4 dp[i][0] = 1 5 6for j in range(n): 7 if obstacleGrid[0][j] == 1: 8 break 9 dp[0][j] = 1 These loops set the base conditions for the first row and column, stopping whenever an obstacle is encountered, since there would be no paths passing through the obstacle. 3. Dynamic Programming Loop: Starting from the cell (1, 1), the algorithm iteratively computes the number of paths to each cell, adding the number of paths from the cell directly above and the number of paths from the cell to the left, as long as those cells are not obstacles. 1for i in range(1, m): 2 for j in range(1, n): 3 if obstacleGrid[i][j] == 0: 4 dp[i][j] = dp[i - 1][j] + dp[i][j - 1] This code is the heart of our dynamic programming approach. It succinctly captures the essence that at each step, the robot could have come from the left cell or the cell above. 4. Construct the Return Value: The value at dp[m-1][n-1] will be the total number of unique paths from the start to the bottom-right corner. It accounts for all possible paths that the robot could take without hitting an obstacle. 1return dp[-1][-1] In terms of time and space complexity, this algorithm runs in O(m * n), where m and n are the dimensions of the input grid, since we have to visit each cell once to calculate the number of paths to it. Space complexity is also O(m * n) due to the additional dp list used to store the number of paths to each cell. 💪 Level Up Your Algo Skills Example Walkthrough Let's go through a small example to illustrate the dynamic programming approach described in the solution. Consider the following grid grid where 0 denotes an empty space and 1 denotes an obstacle: 1grid = [ 2 [0, 0, 0], 3 [0, 1, 0], 4 [0, 0, 0] 5] We aim to calculate the number of unique paths from grid[0][0] to grid[2][2]. 1. Data Structure Initialization: Initialize the dp array with zeros. 1dp = [ 2 [0, 0, 0], 3 [0, 0, 0], 4 [0, 0, 0] 5] 2. Base Cases Initialization: Populate the first row and first column as per the approach, considering the obstacles. After initialization: 1dp = [ 2 [1, 1, 1], 3 [1, 0, 0], 4 [1, 0, 0] 5] The obstacle in grid[1][1] means the robot cannot go through it, so we leave dp[1][1] as 0. 3. Dynamic Programming Loop: We compute the values of the remaining cells. For dp[1][2]: Since the cell above it (dp[1][1]) is blocked by an obstacle, we only add the paths from the left (dp[1][1]), resulting in dp[1][2] = 1. For dp[2][1]: Similar to the previous, we only add the paths from the above (dp[1][1] is 0 due to the obstacle) and the left (dp[2][0] is 1), resulting in dp[2][1] = 1. Recalculated dp after iteration: 1dp = [ 2 [1, 1, 1], 3 [1, 0, 1], 4 [1, 1, 0] 5] For dp[2][2]: We add the values from above (dp[1][2] = 1) and the left (dp[2][1] = 1), giving us dp[2][2] = 2. Final dp array: 1dp = [ 2 [1, 1, 1], 3 [1, 0, 1], 4 [1, 1, 2] 5] 4. Construct the Return Value: The value at dp[2][2] is 2, signifying there are two unique paths from start to destination that avoid the obstacles. Therefore, for the given grid, the robot has exactly two unique paths to reach the destination from the starting point. Python Solution 1class Solution: 2 def uniquePathsWithObstacles(self, obstacle_grid: List[List[int]]) -> int: 3 # Get the number of rows and columns in the obstacle grid. 4 rows, cols = len(obstacle_grid), len(obstacle_grid[0]) 5 6 # Initialize the DP (Dynamic Programming) table with zeros. 7 dp_table = [[0] * cols for _ in range(rows)] 8 9 # Set the value for the first cell to 1 if it is not an obstacle. 10 if obstacle_grid[0][0] == 0: 11 dp_table[0][0] = 1 12 13 # Populate the first column of the DP table. 14 for i in range(1, rows): 15 if obstacle_grid[i][0] == 0: # If there is no obstacle, 16 dp_table[i][0] = dp_table[i-1][0] # Use value from cell above. 17 18 # Populate the first row of the DP table. 19 for j in range(1, cols): 20 if obstacle_grid[0][j] == 0: # If there is no obstacle, 21 dp_table[0][j] = dp_table[0][j-1] # Use value from cell to the left. 22 23 # Fill in the rest of the DP table. 24 for i in range(1, rows): 25 for j in range(1, cols): 26 if obstacle_grid[i][j] == 0: # If the current cell is not an obstacle, 27 dp_table[i][j] = dp_table[i-1][j] + dp_table[i][j-1] # Sum of top and left cells. 28 29 # The bottom-right cell of the DP table will hold the number of unique paths. 30 return dp_table[-1][-1] 31 Java Solution 1class Solution { 2 3 // Function to calculate the unique paths in a grid with obstacles 4 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 5 // Get the dimensions of the grid 6 int numRows = obstacleGrid.length; 7 int numCols = obstacleGrid[0].length; 8 9 // Initialize a DP table with dimensions equivalent to the obstacle grid 10 int[][] dp = new int[numRows][numCols]; 11 12 // Set up the first column of the DP table. If there is an obstacle, 13 // paths beyond that point are not possible, so the loop will break. 14 for (int row = 0; row < numRows && obstacleGrid[row][0] == 0; ++row) { 15 dp[row][0] = 1; 16 } 17 18 // Set up the first row of the DP table. If there is an obstacle, 19 // paths beyond that point are not possible, so the loop will break. 20 for (int col = 0; col < numCols && obstacleGrid[0][col] == 0; ++col) { 21 dp[0][col] = 1; 22 } 23 24 // Iterate over the grid starting from cell (1, 1) to calculate the 25 // number of unique paths to each cell, considering the obstacles. 26 for (int row = 1; row < numRows; ++row) { 27 for (int col = 1; col < numCols; ++col) { 28 // If the current cell is not an obstacle 29 if (obstacleGrid[row][col] == 0) { 30 // Number of paths to current cell is the sum of paths to the 31 // cell above it and the cell to the left of it. 32 dp[row][col] = dp[row - 1][col] + dp[row][col - 1]; 33 } 34 // If the current cell is an obstacle, dp[row][col] remains 0 35 } 36 } 37 38 // Return the number of unique paths to the bottom-right corner of the grid 39 return dp[numRows - 1][numCols - 1]; 40 } 41} 42 C++ Solution 1class Solution { 2public: 3 // Method calculates the number of unique paths from top-left to bottom-right in 4 // a grid that may have obstacles. An obstacle and space are marked as 1 and 0, respectively, in the grid. 5 int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { 6 int numberOfRows = obstacleGrid.size(); // Get the number of rows in the grid. 7 int numberOfColumns = obstacleGrid[0].size(); // Get the number of columns in the grid. 8 9 // Create a 2D dp matrix with the same dimensions as obstacleGrid to store the 10 // number of ways to reach each cell. 11 vector<vector<int>> dp(numberOfRows, vector<int>(numberOfColumns, 0)); 12 13 // Initialize the first column of the dp matrix. A cell in the first column can only be reached from 14 // the cell above it, so if there's an obstacle in a cell, all cells below it should be 0 as well. 15 for (int i = 0; i < numberOfRows && obstacleGrid[i][0] == 0; ++i) { 16 dp[i][0] = 1; 17 } 18 19 // Similarly, initialize the first row of the dp matrix. A cell in the first row can only be reached from 20 // the cell to the left of it, so if there's an obstacle in a cell, all cells to the right of it should be 0. 21 for (int j = 0; j < numberOfColumns && obstacleGrid[0][j] == 0; ++j) { 22 dp[0][j] = 1; 23 } 24 25 // Start from cell (1, 1) and fill in the dp matrix until the bottom-right corner of the grid. 26 // The value of dp[i][j] is obtained by adding the values from the cell above (dp[i - 1][j]) and 27 // the cell to the left (dp[i][j - 1]). 28 for (int i = 1; i < numberOfRows; ++i) { 29 for (int j = 1; j < numberOfColumns; ++j) { 30 // If there's no obstacle in the current cell, calculate the number of paths. 31 if (obstacleGrid[i][j] == 0) { 32 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 33 } 34 // If there's an obstacle, the number of paths to the current cell will be 0. 35 } 36 } 37 38 // The bottom-right cell of the dp matrix contains the number of unique paths 39 // from the top-left corner to the bottom-right corner, which we return. 40 return dp[numberOfRows - 1][numberOfColumns - 1]; 41 } 42}; 43 Typescript Solution 1// Calculates the number of unique paths on a grid with obstacles. 2// Each path moves only rightward or downward at any point, avoiding obstacles. 3function uniquePathsWithObstacles(obstacleGrid: number[][]): number { 4 // Number of rows and columns in the grid 5 const rowCount = obstacleGrid.length; 6 const colCount = obstacleGrid[0].length; 7 8 // Initializing a 2D array to store the number of ways to reach each cell 9 const dp = Array.from({ length: rowCount }, () => new Array(colCount).fill(0)); 10 11 // Filling in the first column, taking obstacles into account 12 for (let row = 0; row < rowCount; row++) { 13 if (obstacleGrid[row][0] === 1) { 14 break; // If there's an obstacle, no path can pass through here 15 } 16 dp[row][0] = 1; // Without obstacles, there's 1 way to get to each cell in the first column 17 } 18 19 // Filling in the first row, taking obstacles into account 20 for (let col = 0; col < colCount; col++) { 21 if (obstacleGrid[0][col] === 1) { 22 break; // If there's an obstacle, no path can pass through here 23 } 24 dp[0][col] = 1; // Without obstacles, there's 1 way to get to each cell in the first row 25 } 26 27 // Calculating paths for the rest of the grid 28 for (let row = 1; row < rowCount; row++) { 29 for (let col = 1; col < colCount; col++) { 30 // If the current cell has an obstacle, skip and continue 31 if (obstacleGrid[row][col] === 1) { 32 continue; 33 } 34 35 // Number of paths to current cell is the sum of paths from the cell above and to the left 36 dp[row][col] = dp[row - 1][col] + dp[row][col - 1]; 37 } 38 } 39 40 // Returning the total number of ways to reach the bottom-right corner of the grid 41 return dp[rowCount - 1][colCount - 1]; 42} 43 Time and Space Complexity The time complexity of the provided code is O(m*n) where m is the number of rows and n is the number of columns in the obstacleGrid. This is because the code contains two nested loops that iterate over each cell in the m x n grid exactly once, and the operations inside the loop are constant time operations. The space complexity of the provided code is also O(m*n) since it uses a 2D list dp with the same dimensions as the obstacleGrid to store the number of unique paths to each cell. 😈 Become an Algo Monster Got a question? Ask the Teaching Assistant anything you don't understand. Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors. TA 👨‍🏫
__label__pos
0.999077
About Us IDKBlogs   All   Javascript NodeJS AngularJS Angular2+ ReactJS Others Detect the user browser using JavaScript Detect the user browser (Safari, Chrome, IE, Firefox and Opera) using JavaScript ?   idkblogs.com      August 24, 2020 Shubham Verma Shubham Verma Detect the user browser using JavaScript D etecting user browser sometimes very useful if we want to write our logic based on the browser. Sometimes we need to do some specific things based on the browser or sometimes some functionality may not support in different browser so we need to detect the user browser and write our logic. In this article, we'll see how we can detect the user browser using javascript. To get the user browser, we have navigator object which contains the userAgent. And in this navigator.userAgent it contains the browser specific information. So, let's see how we can detect the browser using navigator.userAgent. Complete Code: Let's create a file with name detect-browser.html and write the below codes: In the above code we have a button Detect browser and after clicking on this button, it'll call a function checkBrowser() And in this function we wrote the logic to detect the browser. Test on Chrome: Open the above file in the chrome browser and see the output as: Detect the user browser using JavaScript Detect the user browser using JavaScript Now click on the Detect browser button and see the result. After clicking the button Detect browser you can see a popup with the browser name as: Detect the user browser using JavaScript Detect the user browser using JavaScript Test on Firefox: Now, open this html file into firefox browser and click on the button Detect browser and see the result as: Detect the user browser using JavaScript Detect the user browser using JavaScript Test on Safari: Now, open this html file into safari browser and click on the button Detect browser and see the result as: Detect the user browser using JavaScript Detect the user browser using JavaScript Conclusion: In this article, we learned how we can detect the user browser in javascript, and based on the browser we can write our logic for browser specific. Thank you for taking the time to read this article. If you’re interested in Node.js or JavaScript this link will help you a lot. Copyright © 2020 IDKBlogs | All Right Reserved About Us Powered by : IDKBlogs Last Update : 19/09/2020
__label__pos
0.966304
GMAT Math : DSQ: Understanding work problems Study concepts, example questions & explanations for GMAT Math varsity tutors app store varsity tutors android store Example Questions Example Question #1 : Dsq: Understanding Work Problems Clara spent  of her salary on rent and of the rest on clothes. How much did she have left after paying the rent and buying the clothes? (1) Her salary was $3000 (2) She spent $1400 on rent and clothes Possible Answers: Statements (1) and (2) TOGETHER are NOT sufficient. Statement (1) ALONE is sufficient, but statement (2) alone is not sufficient. D. EACH statement ALONE is sufficient. BOTH statements TOGETHER are sufficient, but NEITHER statement ALONE is sufficient. Statement (2) ALONE is sufficient, but statement (1) alone is not sufficient. Correct answer: D. EACH statement ALONE is sufficient. Explanation: For statement (1), she spent   on rent, and   on clothes. So she spent  in total. Therefore, she has  left. For statement (2), we can set Clara’s salary to be , then we have   Then simplify the equation:   Therefore, . Now we can just follow what we did for the first statement to calculate the money he had left. Example Question #2 : Dsq: Understanding Work Problems Steve can paint his greenhouse in 4 hours 40 minutes minutes, working alone; his brother Phil can do the same job in 6 hours, working alone. If they work together, to the nearest minute, how long will it take them?  Possible Answers: 2 hours 42 miutes 3 hours  2 hours 54 minutes 2 hours 38 minutes 2 hours 22 minutes Correct answer: 2 hours 38 minutes Explanation: Think of this in terms of "greenhouses per minute", not "minutes per greenhouse". Converting hours and minutes to just minutes, Steve can paint  greenhouses per minute; Phil can paint  greenhouses per minute.  If we let  be the time in minutes that it takes to paint the greenhouse, then Steve and Phil paint   and  greenhouses, respectively; since one greenhouse total is painted, then we can add the labor and set up this equation: Simplify and solve: or 2 hours, 38 minutes. Example Question #1 : Work Problems A large water tower can be emptied by opening one or both of two drains of different sizes. On one occasion, both drains were opened at the same time. How long did it take to empty the water tower? Statement 1: Alone, the larger drain can empty the tower in three hours. Statement 2: The smaller drain can empty water at 75% of the rate at which the larger drain does. Possible Answers: BOTH statements TOGETHER are sufficient to answer the question, but NEITHER statement ALONE is sufficient to answer the question. Statement 1 ALONE is sufficient to answer the question, but Statement 2 ALONE is NOT sufficient to answer the question. Statement 2 ALONE is sufficient to answer the question, but Statement 1 ALONE is NOT sufficient to answer the question. EITHER statement ALONE is sufficient to answer the question. BOTH statements TOGETHER are insufficient to answer the question.  Correct answer: BOTH statements TOGETHER are sufficient to answer the question, but NEITHER statement ALONE is sufficient to answer the question. Explanation: A work problem is actually a rate problem in disguise. If you know that an object working alone can do a job in  hours, then you know that the object works at a rate of  jobs per hour. After  hours, the object accomplishes  of a job. Similarly, the other object working alone does a job in  hours, and therefore does  of a job. Together, the objects do one whole job, so solve this equation  for . Statement 1 alone gives us half the picture; , but  is unknown. Statement 2 alone tells us that  is 75% of . But  is unknown. From Statement 1 and 2 together, we know  is 75% of  - this allows us to calculate : 75% of  is , so . Since we have both  and , we have the complete equation and we can calculate . Example Question #4 : Dsq: Understanding Work Problems A large water tower can be emptied by opening one or both of two drains of different sizes. On one occasion, both drains were opened at the same time. How long did it take to empty the water tower? Statement 1: Alone, the smaller drain can empty the tower in three hours. Statement 2: Alone, the larger drain can empty the tower in two hours. Possible Answers: BOTH statements TOGETHER are sufficient to answer the question, but NEITHER statement ALONE is sufficient to answer the question. EITHER statement ALONE is sufficient to answer the question. Statement 1 ALONE is sufficient to answer the question, but Statement 2 ALONE is NOT sufficient to answer the question. Statement 2 ALONE is sufficient to answer the question, but Statement 1 ALONE is NOT sufficient to answer the question. BOTH statements TOGETHER are insufficient to answer the question.  Correct answer: BOTH statements TOGETHER are sufficient to answer the question, but NEITHER statement ALONE is sufficient to answer the question. Explanation: A work problem is actually a rate problem in disguise. If you know that an object working alone can do a job in  hours, then you know that the object works at a rate of  jobs per hour. After  hours, the object accomplishes  of a job. Similarly, the other object working alone does a job in  hours, and therefore does  of a job. Together, the objects do one whole job, so solve this equation  for . Statement 1 alone tells us that , and Statement 2 alone tells us that . Therefore, each statement alone gives us only half the picture, but together, they give us the equation , which can be solved to yield the answer.  Example Question #5 : Dsq: Understanding Work Problems Three brothers - David, Eddie, and Floyd - mow a lawn together, starting at the same time. How long will it take them to finish? Statement 1: Working alone, David can mow the lawn in four hours. Statement 2: Working together, but without David, Eddie and Floyd can mow the lawn in three hours. Possible Answers: EITHER statement ALONE is sufficient to answer the question. BOTH statements TOGETHER are sufficient to answer the question, but NEITHER statement ALONE is sufficient to answer the question. BOTH statements TOGETHER are insufficient to answer the question.  Statement 2 ALONE is sufficient to answer the question, but Statement 1 ALONE is NOT sufficient to answer the question. Statement 1 ALONE is sufficient to answer the question, but Statement 2 ALONE is NOT sufficient to answer the question. Correct answer: BOTH statements TOGETHER are sufficient to answer the question, but NEITHER statement ALONE is sufficient to answer the question. Explanation: A work problem is actually a rate problem in disguise. If you know that David working alone can do a job in  hours, then you know that the object works at a rate of  jobs per hour. After  hours, the object accomplishes  of a job. Similarly, Eddie and Floyd, working without David, do a job in  hours, and therefore does  of a job. Together, the objects do one whole job, so solve this equation  for . Statement 1 alone tells us that , and Statement 2 alone tells us that ; each one alone leaves the other value unknown. However, if both statements are given, the equation  can be solved for  to yield the correct answer. Example Question #6 : Dsq: Understanding Work Problems Last week, Mrs. Smith, Mrs. Edwards, and Mrs. Hume were able to write  invitations to a party in two hours.  Today, Mrs. Smith is sick and cannot help, so Mrs. Edwards, and Mrs. Hume have to work without her. They must write  more invitations to the same party. How long should they take, working together? Statement 1: Working alone, Mrs. Smith can write  invitations in one and one-half hours. Statement 2: Working alone, Mrs. Hume can write  invitations in one hour. Possible Answers: BOTH statements TOGETHER are insufficient to answer the question.  Statement 1 ALONE is sufficient to answer the question, but Statement 2 ALONE is NOT sufficient to answer the question. BOTH statements TOGETHER are sufficient to answer the question, but NEITHER statement ALONE is sufficient to answer the question. EITHER statement ALONE is sufficient to answer the question. Statement 2 ALONE is sufficient to answer the question, but Statement 1 ALONE is NOT sufficient to answer the question. Correct answer: Statement 1 ALONE is sufficient to answer the question, but Statement 2 ALONE is NOT sufficient to answer the question. Explanation: Since the group is now without the help of Mrs. Smith, we look at Mrs. Smith's contribution to the work as a whole, and the sum of the other two ladies' contribution as a whole; Statement 2, which deals with Mrs. Hume alone, is irrelevant and unhelpful. Since the three ladies together wrote 400 invitations in 120 minutes, we can infer that they would have spent three-fourths of this time, or 90 minutes, writing 300 invitations. If Statement 1 is true, then Mrs. Smith, who can write 100 invitations in 90 minutes, would take three times this, or 270 minutes, to write 300 invitations.  A work problem is a rate problem in disguise. Think in terms of "jobs per hour", and take the reciprocal of each "hours per job". The three ladies together would have done  job in one hour, and Mrs. Smith alone would have done  job in one hour. Therefore, in one hour today, the two ladies will do   jobs, and in  hours today, they will do job. Solve for  in this equation.  This proves that Statement 1 alone allows us to find the answer - but not Statement 2. Learning Tools by Varsity Tutors
__label__pos
0.99289
Man page of GREP GREP Section: User Commands (1) Updated: Index?action=index Return to Main Contents NAME grep, egrep, fgrep, rgrep - print lines matching a pattern SYNOPSIS grep [OPTIONS] PATTERN [FILE...] grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...] DESCRIPTION grep searches the named input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is given as file name) for lines containing a match to the given PATTERN. By default, grep prints the matching lines. In addition, three variant programs egrep, fgrep and rgrep are available. egrep is the same as grep -E. fgrep is the same as grep -F. rgrep is the same as grep -r. Direct invocation as either egrep or fgrep is deprecated, but is provided to allow historical applications that rely on them to run unmodified. OPTIONS Generic Program Information --help Print a usage message briefly summarizing these command-line options and the bug-reporting address, then exit.: -V, --version Print the version number of grep to the standard output stream. This version number should be included in all bug reports (see below).: Matcher Selection -E, --extended-regexp Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.): -F, --fixed-strings Interpret PATTERN as a list of fixed strings (rather than regular expressions), separated by newlines, any of which is to be matched. (-F is specified by POSIX.): -G, --basic-regexp Interpret PATTERN as a basic regular expression (BRE, see below). This is the default.: -P, --perl-regexp Interpret PATTERN as a Perl regular expression (PCRE, see below). This is highly experimental and grep -P may warn of unimplemented features.: Matching Control e PATTERN, --regexp=PATTERN Use PATTERN as the pattern. This can be used to specify multiple search patterns, or to protect a pattern beginning with a hyphen (). (-e is specified by POSIX.): -f FILE, --file=FILE Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing. (-f is specified by POSIX.): -i, --ignore-case Ignore case distinctions in both the PATTERN and the input files. (-i is specified by POSIX.): -v, --invert-match Invert the sense of matching, to select non-matching lines. (-v is specified by POSIX.): -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore.: -x, --line-regexp Select only those matches that exactly match the whole line. This option has the same effect as anchoring the expression with ^ and $. (-x is specified by POSIX.): -y Obsolete synonym for -i.: General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see below), count non-matching lines. (-c is specified by POSIX.): --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. The deprecated environment variable GREP_COLOR is still supported, but its setting does not have priority. WHEN is never, always, or auto.: -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. The scanning will stop on the first match.: -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match. (-l is specified by POSIX.): -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines.: -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.: -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. (-q is specified by POSIX.): -s, --no-messages Suppress error messages about nonexistent or unreadable files. Portability note: unlike GNU grep, 7th Edition Unix grep did not conform to POSIX, because it lacked -q and its -s option behaved like GNU grep's -q option. USG-style grep also lacked -q but its -s option behaved like GNU grep. Portable shell scripts should avoid both -q and -s and should redirect standard and error output to /dev/null instead. (-s is specified by POSIX.): Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself.: -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search.: -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.: --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This is especially useful when implementing tools like zgrep, e.g., gzip -cd foo.gz | grep --label=foo -H something. See also the -H option.: -n, --line-number Prefix each line of output with the 1-based line number within its input file. (-n is specified by POSIX.): -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width.: -u, --unix-byte-offsets Report Unix-style byte offsets. This switch causes grep to report byte offsets as if the file were a Unix-style text file, i.e., with CR characters stripped off. This will produce results identical to running grep on a Unix machine. This option has no effect unless -b option is also used; it has no effect on platforms other than MS-DOS and MS-Windows.: -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters.: Context Line Control A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (-) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given.: B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (-) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given.: C NUM, 'NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator () between contiguous groups of matches. With the -o or --only-matching''' option, this has no effect and a warning is given.: File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option.: --binary-files=TYPE If the first few bytes of a file indicate that the file contains binary data, assume that the file is of type TYPE. By default, TYPE is binary, and grep normally outputs either a one-line message saying that a binary file matches, or no message if there is no match. If TYPE is without-match, grep assumes that a binary file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. Warning: grep --binary-files=text might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands.: -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped.: -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option.: --exclude=GLOB Skip files whose base name matches GLOB (using wildcard matching). A file-name glob can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally.: --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude).: --exclude-dir=DIR Exclude directories matching the pattern DIR from recursive searches.: -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option.: --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude).: -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -d recurse option.: -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r.: Other Options --line-buffered Use line buffering on output. This can cause a performance penalty.: -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses the file type by looking at the contents of the first 32KB read from the file. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows.: -z, --null-data Treat the input as a set of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names.: REGULAR EXPRESSIONS A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: ``basic (BRE), ``extended (ERE) and ``perl'' (PRCE). In GNU grep, there is no difference in available functionality between basic and extended syntaxes. In other implementations, basic regular expressions are less powerful. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl regular expressions give additional functionality, and are documented in pcresyntax?(3) and pcrepattern?(3), but only work if pcre is available in the system. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list; if the first character of the list is the caret ^ then it matches any character not in the list. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, :alnum:? means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once.: * The preceding item will be matched zero or more times.: + The preceding item will be matched one or more times.: {n} The preceding item is matched exactly n times.: {n,} The preceding item is matched n or more times.: {,m} The preceding item is matched at most m times. This is a GNU extension.: {n,m} The preceding item is matched at least n times, but not more than m times.: Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back References and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, , {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \, \{, \|, \(, and \). Traditional egrep did not support the { meta-character, and some egrep implementations support \{ instead, so portable scripts should avoid { in grep -E patterns and should use [{] to match a literal {. GNU grep -E attempts to support traditional usage by assuming that { is not special if it would be the start of an invalid interval specification. For example, the command grep -E '{1' searches for the two-character string {1 instead of reporting a syntax error in the regular expression. POSIX allows this behavior as an extension, but portable scripts should avoid it. ENVIRONMENT VARIABLES The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). GREP_OPTIONS This variable specifies default options to be placed in front of any explicit options. For example, if GREP_OPTIONS is '--binary-files=without-match --directories=skip', grep behaves as if the two options --binary-files=without-match and --directories=skip had been specified before any explicit options. Option specifications are separated by whitespace. A backslash escapes the next character, so it can be used to specify an option containing whitespace or a backslash.: GREP_COLOR This variable specifies the color used to highlight matched (non-empty) text. It is deprecated in favor of GREP_COLORS, but still supported. The mt, ms, and mc capabilities of GREP_COLORS have priority over it. It can only specify the color used to highlight the matching non-empty text in any matching line (a selected line when the -v command-line option is omitted, or a context line when -v is specified). The default is 01;31, which means a bold red foreground text on the terminal's default background.: GREP_COLORS Specifies the colors and other attributes used to highlight various parts of the output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. : sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair).: cx= SGR substring for whole context lines (i.e., non-matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair).: rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command-line option is specified. The default is false (i.e., the capability is omitted).: mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background.: ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background.: mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background.: fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background.: ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background.: bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background.: se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (), and between groups of adjacent lines when nonzero context is specified (-). The default is a cyan text foreground over the terminal's default background.: ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\\\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted).: Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\\\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. : LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z].: LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace.: LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages.: POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as ``illegal, but since they are not really against the law the default is to diagnose them as ``invalid. POSIXLY_CORRECT also disables N_GNU_nonoption_argv_flags, described below.: N_GNU_nonoption_argv_flags (Here N is grep's numeric process ID.) If the ith character of this environment variable's value is 1, do not consider the ith operand of grep to be an option, even if it appears to be one. A shell can put this variable in the environment for each command it runs, specifying which operands are the results of file name wildcard expansion and therefore should not be treated as options. This behavior is available only with the GNU C library, and only when POSIXLY_CORRECT is not set.: EXIT STATUS The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.) COPYRIGHT Copyright 1998-2000, 2002, 2005-2014 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS Reporting Bugs Email bug reports to <[email protected]>, a mailing list whose web page is <http://lists.gnu.org/mailman/listinfo/bug-grep>. grep's Savannah bug tracker is located at <http://savannah.gnu.org/bugs/?group=grep>. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. SEE ALSO Regular Manual Pages awk?(1), cmp?(1), diff?(1), find?(1), gzip?(1), perl?(1), sed?(1), sort?(1), xargs?(1), zgrep?(1), read?(2), pcre?(3), pcresyntax?(3), pcrepattern?(3), terminfo?(5), glob?(7), regex?(7). POSIX Programmer's Manual Page (1p). TeXinfo Documentation The full documentation for grep is maintained as a TeXinfo manual, which you can read at http://www.gnu.org/software/grep/manual/. If the info and grep programs are properly installed at your site, the command <DD CLASS="c2|info grep: should give you access to the complete manual. NOTES This man page is maintained only fitfully; the full documentation is often more up-to-date. GNU's not Unix, but Unix is a beast; its plural form is Unixen. Index NAME SYNOPSIS DESCRIPTION OPTIONS Generic Program Information Matcher Selection Matching Control General Output Control Output Line Prefix Control Context Line Control File and Directory Selection Other Options REGULAR EXPRESSIONS Character Classes and Bracket Expressions Anchoring The Backslash Character and Special Expressions Repetition Concatenation Alternation Precedence Back References and Subexpressions Basic vs Extended Regular Expressions ENVIRONMENT VARIABLES EXIT STATUS COPYRIGHT BUGS Reporting Bugs Known Bugs SEE ALSO Regular Manual Pages POSIX Programmer's Manual Page TeXinfo Documentation NOTES More Man Pages
__label__pos
0.623266
Json – Project Haystack Json OverviewJSON Version 4JSON Version 3 Overview JSON stands for JavaScript Object Notation. It is a plain text format commonly used for serialization of data. It is specified in RFC 4627. The JSON format is designed to support 100% fidelity with with the full Haystack type system. JSON is represented by the def filetype:json. JSON Version 4 This section describes the Haystack 4 method for encoding Haystack types to JSON. This is the default encoding for JSON in Haystack 4. The following Haystack types can be mapped directly to JSON: Haystack JSON -------- ---- Dict Object List Array null null Bool Boolean Str String Number Number (see note) Note: Number maps directly to JSON Number when it is not special (INF, -INF, NaN) and when the number has no unit. Otherwise it is encoded as an object as described below. All other Haystack types map to a JSON Object. These objects are required to have a _kind key whose value is the Haystack 4 def name for the type. A dict is the only object where the _kind is optional. Therefore, all properly formatted JSON objects without a _kind are, by definition, dicts. The following sections indicate how the various Haystack types are encoded as JSON objects. Number A JSON number. If the number is special or has a unit, it is encoded an object with the following keys: • _kind: "number" • val: the JSON Number, INF, -INF, or NaN. • unit: (optional) the String unit // unitless number 123.45 // verbose encoding of a unitless number { "_kind": "number", "val": 123.45 } // with a unit { "_kind": "number", "val": 123, "unit": "m" } // positive infinity { "_kind": "number", "val": "INF" } // negative infinity { "_kind": "number", "val": "-INF" } // Not-a-number { "_kind": "number", "val": "NaN" } Marker A marker object is encoded with just its _kind. { "_kind": "marker" } Remove A remove object is encoded with just its _kind. { "_kind": "remove" } NA An NA (not available) object is encoded with just its _kind. { "_kind": "na" } Ref A Haystack Ref is encoded as an object with the following keys: • _kind: "ref" • val: the String id for the ref • dis: (optional) the String display name for the ref // no diplay name { "_kind": "ref", "val": "abc-def"} // with a display name { "_kind": "ref", "val": "abc-def", "dis": "Main Elec Meter" } Date A Haystack Date is encoded as an object with the following keys: • _kind: "date" • val: the ISO 8601 String encoding of the date { "_kind": "date", "val": "2021-03-22" } Time A Haystack Time is encoded as an object with the following keys: • _kind: "time" • val: the ISO 8601 String encoding of the time { "_kind": "time", "val": "17:19:23" } DateTime A Haystack DateTime is encoded as an object with the following keys: • _kind: "dateTime" • val: the ISO 8601 String encoding of the date and time • tz: (optional) the Olsen timezone database city name of the time zone. If this key is missing, GMT is the default. // default timezone { "_kind": "dateTime", "val": "2021-03-22T17:56:05.411Z"} // with a timezone { "_kind": "dateTime", "val": "2021-03-22T13:57:00.381-04:00", "tz": "New_York" } Uri A Haystack URI is encoded as an object with the following keys: • _kind: "uri" • val: The URI String value { "_kind": "uri", "val": "https://project-haystack.org" } Coordinate A Haystack Coordinate is encoded as an object with the following keys: • _kind: "coord" • lat: the latitude in decimal degrees (Number) • lng: the longitude in decimal degrees (Number) { "_kind": "coord", "lat": 50.979603, "lng": 10.318789 } XStr A Haystack XStr is encoded as an object with the following keys: • _kind: "xstr" • type: The String type name • val: The String encoding of the type { "_kind": "xstr", "type": "Span", "val": "today" } Symbol A Haystack Symbol is encoded as an object with the following keys: • _kind: "symbol" • val: The String symbol name { "_kind": "symbol", "val": "site" } List A Haystack List is encoded as a JSON Array, Elements of the array can be of any Haystack type. // empty list [] // A list with some values [ true, 123, "a string", {"site": { _kind:"marker"}, "dis":"Carnegie Hall"}] Dict A Haystack Dict is encoded as a JSON object. The _kind is optional. All other keys in the Dict are tag name/value pairs. If the key is not a valid Haystack tag name then it should be skipped (ignored). // empty dict {} // also empty { "_kind": "dict" } // a dict with some tags { "site": { "_kind": "marker" }, "dis": "Kennedy Center", "Ignore": "This tag should be ignored" } Grid A Haystack Grid is encoded as a JSON object with the following keys: • _kind: "grid" • meta: The JSON encoding of the grid metadata dict. The meta version ver tag should always be included in the meta. • cols: A List of grid columns. Each column should have the following keys: • name: the String column name • meta: (optional) The JSON encoding of the column metadata dict. • rows: A List of the grid rows where each row is encoded as a dict. // Zinc ver:"3.0" projName:"test" dis dis:"Equip Name",equip,siteRef,installed "RTU-1",M,@153c-699a "HQ",2005-06-01 "RTU-2",M,@153c-699b "Library",1999-07-12 // JSON { "_kind": "grid", "meta": { "ver": "3.0", "foo": "bar" }, "cols": [ { "name": "dis", "meta": { "dis": "Equip Name"} }, { "name": "equip" }, { "name": "siteRef" }, { "name": "installed" } ], "rows": [ { "dis": "RTU-1", "equip": { "_kind": "marker" }, "siteRef": { "_kind": "ref", "val": "153c-699a", "dis": "HQ"}, "installed": { "_kind": "date", "val": "2005-06-01" } }, { "dis": "RTU-2", "equip": { "_kind": "marker" }, "siteRef": { "_kind": "ref", "val": "153c-699b", "dis": "Library"}, "installed": { "_kind": "date", "val": "1999-07-12" } } ] } Here is another example with nested lists, dicts, and grids: // Zinc ver:"3.0" type,val "list",[1,2,3] "dict",{dis:"Dict!" foo} "grid",<< ver:"2.0" a,b 1,2 3,4 >> "scalar","simple string" // JSON { "_kind": "grid", "meta": { "ver": "3.0" }, "cols": [ { "name": "type" }, { "name": "val" } ], "rows": [ { "type": "list", "val": [1, 2, 3] }, { "type": "dict", "val": { "dis": "Dict!", "foo": { "_kind": "marker" } } }, { "type": "grid", "val": { "_kind": "grid", "meta": { "ver": "3.0" }, "cols": [ { "name": "a" }, { "name": "b" } ], "rows" [ { "a": 1, "b": 2 }, { "a": 3, "b": 4 } ] } }, { "type": "scalar", "val": "simple string" } ] } JSON Version 3 The following is an alternate encoding of Haystack to JSON. This encoding was the default for Haystack version 3, but has been supplanted by the above (version 4) encoding. It is supported for backwards compatibility. The following is the mapping between Haystack (version 3) and JSON types: Haystack JSON -------- ---- Grid Object (specified below) List Array Dict Object null null Bool Boolean Marker "m:" Remove "-:" NA "z:" Number "n:<float> [unit]" "n:45.5" "n:73.2 °F" "n:-INF" Ref "r:<id> [dis]" "r:abc-123" "r:abc-123 RTU #3" Symbol "y:<id>" "y:hot-water", "y:lib:ph" Str "hello" "s:hello" Date "d:2014-01-03" Time "h:23:59" DateTime "t:2015-06-08T15:47:41-04:00 New_York" Uri "u:http://project-haystack.org/" Coord "c:<lat>,<lng>" "c:37.545,-77.449" XStr "x:Type:value" Notes: • Number encodings use a space between the floating point value and unit for easier parsing (in Zinc there is no space) • Number specials use same values as Zinc: "INF", "-INF", and "NaN" • Refs strings use first space to separate id from dis portions of the string • DateTime, Date, and Time use ISO 8601 formats exactly as specified by Zinc • DateTime has required timezone name • Strings which contain a colon must be encoded with "s:" prefix • Strings without a colon may optionally omit the "s:" prefix • Any JSON string without a colon as the second char is assumed to be a string value Here is an example: // Haystack dis: "Site-A", site, area: 5000ft², built: 1992-01-23 // JSON {"dis":"Site-A", "site":"m:", "area":"n:5000 ft²", "built":"d:1992-01-23"} The Haystack and JSON models are very similiar since they both support the same core list and object/dict types. The difference is that Haystack has a richer set of scalar types such as Date, Time, Uri which are not supported directly by JSON; so we encode them as strings using a special type code prefix. Grid Format In addition to the flexible type mapping defined above, we have a standard mapping of grid into JSON which is used by the REST API. The Grid to JSON mapping is as follows: • Grid is mapped into a JSON object with three fields: meta, cols, rows • The meta field is a JSON object with a required "ver" field • The cols field is a JSON list of column objects • Each column object defines a "name" field and the column metadata • The rows field is a list of JSON objects • Meta and row dicts are mapped to JSON objects • Dict values are mapped using type mappings defined above Example: // Zinc ver:"3.0" projName:"test" dis dis:"Equip Name",equip,siteRef,installed "RTU-1",M,@153c-699a "HQ",2005-06-01 "RTU-2",M,@153c-699a "HQ",1999-07-12 // JSON { "meta": {"ver":"3.0", "projName":"test"}, "cols":[ {"name":"dis", "dis":"Equip Name"}, {"name":"equip"}, {"name":"siteRef"}, {"name":"installed"} ], "rows":[ {"dis":"RTU-1", "equip":"m:", "siteRef":"r:153c-699a HQ", "installed":"d:2005-06-01"}, {"dis":"RTU-2", "equip":"m:", "siteRef":"r:153c-699a HQ", "installed":"d:999-07-12"} ] } Here is another example with nested lists, dicts, and grids: // Zinc ver:"3.0" type,val "list",[1,2,3] "dict",{dis:"Dict!" foo} "grid",<< ver:"2.0" a,b 1,2 3,4 >> "scalar","simple string" // JSON { "meta": {"ver":"2.0"}, "cols":[ {"name":"type"}, {"name":"val"} ], "rows":[ {"type":"list", "val":["n:1", "n:2", "n:3"]}, {"type":"dict", "val":{"dis":"Dict!", "foo":"m:"}}, {"type":"grid", "val":{ "meta": {"ver":"2.0"}, "cols":[ {"name":"b"}, {"name":"a"} ], "rows":[ {"b":"n:20", "a":"n:10"} ] }}, {"type":"scalar", "val":"simple string"} ] }
__label__pos
0.826401
Permalink Browse files Formatting • Loading branch information... 0 parents commit 20aaa8f92393717fa63096c47922c671b1d0743d @rwaldron committed Aug 10, 2011 Showing with 56 additions and 0 deletions. 1. +56 −0 readme.md @@ -0,0 +1,56 @@ +# The Controller Object + + +## Description + +The `Controller` object is a single object that has named properties, some of which are functions. + +The value of the `[[Prototype]]` internal property of the `Controller` object is the standard built-in `Object` prototype object (ES 15.2.4). The value of the `[[Class]]` internal property of the `Controller` object is "*Controller*". + +The `Controller` object does not have a `[[Construct]]` internal property; it is not possible to use the `Controller` object as a constructor with the new operator. + +The `Controller` object does not have a `[[Call]]` internal property; it is not possible to invoke the `Controller` object as a function. + + +## Value Properties of the Controller Object + + + - ... + + +## Function Properties of the Controller Object + + - `queryState()` Returns an object descriptor that represents the current state of + + + + + + + +## DOM Events + +### Current + +#### Events + + - buttondown + - buttonup + - axismove + + +### Propose + +Implement new `UIEvent` interface: `DeviceEvent` + +The DOM `DeviceEvent` represents events that occur as a result of the user interacting with a device (in this case, not a keyboard and not a mouse). + +#### Events + + - *interact* + - *connect* + - *disconnect* + + + + 0 comments on commit 20aaa8f Please sign in to comment.
__label__pos
0.983006
How To Get Javascript Value In Html If you’re using JavaScript to manipulate the content of your web page, you may find yourself in a situation where you’d like to display a JavaScript value directly in your HTML markup. In this blog post, we’ll explore different ways to achieve this using JavaScript. 1. Using innerHTML Property The innerHTML property allows you to get or set the HTML content of an element. You can use this property to insert a JavaScript value into an HTML element by setting the element’s innerHTML to the value. <!-- HTML --> <div id="display"></div> <!-- JavaScript --> <script> var value = "Hello, World!"; document.getElementById("display").innerHTML = value; </script> 2. Using textContent Property Another method for displaying JavaScript values in your HTML is by using the textContent property. This is similar to using innerHTML, but textContent does not parse the content as HTML. This can be helpful if you want to display a value that might contain HTML tags without rendering the tags as markup. <!-- HTML --> <p id="output"></p> <!-- JavaScript --> <script> var value = "<strong>Hello, World!</strong>"; document.getElementById("output").textContent = value; </script> 3. Using Value Property for Input Elements If you want to display a JavaScript value inside an input element, such as a text box, you can use the value property. This will set the value of the input element to the specified JavaScript value. <!-- HTML --> <input type="text" id="inputBox"> <!-- JavaScript --> <script> var value = "Hello, World!"; document.getElementById("inputBox").value = value; </script> 4. Using createElement and appendChild You can also display a JavaScript value in your HTML by creating a new HTML element with the desired value, and then appending it to an existing element using the appendChild method. <!-- HTML --> <div id="container"></div> <!-- JavaScript --> <script> var value = "Hello, World!"; var newElement = document.createElement("p"); newElement.textContent = value; document.getElementById("container").appendChild(newElement); </script> These are just a few examples of how you can display JavaScript values in your HTML markup. Remember, it’s important to choose the method that best suits your needs and the specific situation you’re working with.
__label__pos
0.991155
Source Code Java Help Source Code The implementation of this HTTP server is presented here in five classes and one interface. A more complete implementation would likely split many of the methods out of the main class, httpd, in order to abstract more of the components. For space considerations in this book, most of the functionality is in the single class, and the-small support classes are only acting as data structures. We will take a close look at each class and method to examine how this server works, starting with the support classes and ending with the main program. MimeHeader .java MIME is an Internet standard for communicating multimedia content over e-mail systems. This standard was created by Nat Eisenstein in 1992. The HITP protocol uses, and extends the notion of MIME headers to pass general attribute/value pairs between the I-IITP client and server CONSTRUCTORS This class is a subclass of Hash table so that it can conveniently storeand retrieve the key /value pairs associated with a MIME header. It has two ‘ constructors. One creates a blank Mime Header with no keys. The other takes a string formatted as a MIME”header and parses it for the initial contents of the object. See  next. parse() The method is used to take a raw MIME-formatted string and enter its key/value pairs into a given instance of Mime Header. It uses a String Tenderizer to split the input data into individual lines, marked by the CRLF (rn) sequence. It then iterates through breadline using the canonical while …  sequence. For each line of the MIME header, the parses ) method splits the line into two strings separated by a colon (:). The two variables key and val are set by the stringing  method to extract the characters before the colon, those after the colon, and its following space character. Once these two strings have been extracted, the put method is used to store this association between the key and value in the Hash table. put( ), get( ), AND flx() The put() and get() methods in Hashtable would work fine for this application if not for one rather odd thing. The MIME specification defin ed several important keys, such as Content-Type and Content-Length. Some early implements of MIME systems, notably web browsers, took liberties with the capitalization of these fields. Some use Content-type, others content-type. To avoid mishaps, our HTIP server tries to convert all incoming and outgoing Mime Header keys to be in the ‘canonical form, Content-Type. Thus, we override put( ) and get( ) to convert the values’ capitalization, using the method fix( ), before entering them int o the Hash table and before looking up a given key. CONSTRUCTORS ‘If you construct an Http Response with a string argument, this is taken to be a raw response from an HTIP server and is passed to parset ), described next, to initialize the object. Alternatively, you can pass in a precomputed status code, reason phrase, and MIME header. parse() ,The parsemethod takes the raw data that was read from the HITP server, parses the status Code and reasonPhrase from the first line, and then constructs a MimcHeader out of the remaining lines.  to String The to String method is the inverse of parse It takes the current values of the Http Response object and returns a string that an HTIP client would expect to read back from a server. JavaHelpOnline.com • Feel free to send us an inquiry, we will reply back in hours.   Verification Posted on September 17, 2014 in Networking Share the Story About the Author Back to Top
__label__pos
0.696319
August 28, 2014 Hot Topics: RSS RSS feed Download our iPhone app Manage Concurrent Access to JPA Entity with Locking • December 27, 2013 • By Manoj Debnath • Send Email » • More Articles » Introduction Database transactions are notoriously messy in managing data integrity. Systems for reservations, banking, credit card processing, stock markets, etc. require high availability and fast response time for hundreds of concurrent users. With the surge of online transactions, developers now have to deal with it more often. Applications dealing with simultaneous transactions should be equipped to handle such a situation efficiently. As we know, 'Isolation' is the fundamental property of 'Transaction' but to manage one is an issue of concern. Without proper management there is the possibility of getting unwarranted results from concurrent transactions due to overlapped CRUD operations. Locking mechanism is an efficient way out of the situation. This mechanism surfaces at different levels. Many popular DBMS packages have their own provisions; JPA is no exception, providing some of the capability of inherent locking mechanism in harnessing the situation. Locking and its Types Locking is one of the basic techniques used to control concurrent execution of transactions. This mechanism is actually pretty simple. A lock is like a status variable associated with a data item with respect to possible operations applied to it. This lock is used as a means of synchronizing the access by concurrent transaction to the database item. Classical locking mechanisms have numerous ways of implementation at the database-level but JPA supports two types of locking mechanisms at the entity-level: optimistic model and pessimistic model. An Example The code below demonstrates a database transaction without enabling the locking feature. The code snippet down the line will show how to enable this in POJO under JPA. Listing 1: Entity class package org.mano.dto;   //... import statements   @Entity @NamedQuery(name="findAllAccount", query="SELECT a FROM Account a") public class Account implements Serializable{         @Id         private Long accountNumber;         private String name;         @Temporal(TemporalType.DATE)         private Date createDate;              private Float balance;                 //... constructors, getters and setters, toString method }     Listing 2: Service class   package org.mano.service;   //... import statements   public class AccountService {   protected EntityManager entityManager;   public AccountService(EntityManager entityManager) {                 this.entityManager = entityManager; }   public Account createAccount(Long accno, String name, Date createDate, Float balance) {                 Account a = new Account();                 a.setAccountNumber(accno);                 a.setName(name);                 a.setCreateDate(createDate);                 a.setBalance(balance);                 entityManager.persist(a);                 return a;         }           public void closeAccount(Long accno) {                 Account a = findAccount(accno);                 if (a != null) {                         entityManager.remove(a);                 }         }           public Account deposit(Long accno, Float amount) {                 Account a = entityManager.find(Account.class, accno);                 if (a != null) {                         a.setBalance(a.getBalance() + amount);                 }                 return a;         }           public Account withdraw(Long accno, Float amount) {                 Account a = entityManager.find(Account.class, accno);                 if (a != null) {                         if (a.getBalance() >= amount)                                a.setBalance(a.getBalance() - amount);                 }                 return a;         }           public Account findAccount(Long accno) {                 return entityManager.find(Account.class, accno);         }           public List<Account> listAllAccount() {                 TypedQuery<Account> query = entityManager.createNamedQuery(                                "findAllAccount", Account.class);                 return query.getResultList();         } }     Listing 3: Testing class   package org.mano.app;   //... import statements   public class Main {   public static void main(String[] args) {         EntityManagerFactory factory = Persistence                                .createEntityManagerFactory("JPALockingDemo");         EntityManager manager = factory.createEntityManager();           AccountService service = new AccountService(manager);           manager.getTransaction().begin();         Account a1 = service.createAccount(123l, "John Travolta", new Date(),                                4000.00f);         manager.getTransaction().commit();         System.out.println("Persisted: " + a1.toString());           a1 = service.findAccount(123l);         System.out.println("Found: " + a1.toString());           List<Account> list = service.listAllAccount();         for (Account a : list) {                 System.out.println("Found list " + a.toString());         }                   manager.getTransaction().begin();                 a1 = service.deposit(123l, 1000.00f);                 manager.getTransaction().commit();                 System.out.println("Deposit: " + a1.toString());                   manager.getTransaction().begin();                 a1 = service.withdraw(123l, 500.00f);                 manager.getTransaction().commit();                 System.out.println("Withdraw: " + a1.toString());                   manager.getTransaction().begin();                 service.closeAccount(123l);                 manager.getTransaction().commit();                 System.out.println("Account Closed: 123");                   manager.close();                 factory.close();           }   }     Listing 4: Persistence configuration   <?xml version="1.0" encoding="UTF-8"?> <persistence ...> <persistence-unit name="JPALockingDemo" transaction-type="RESOURCE_LOCAL"> <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> <class>org.mano.dto.Account</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mybank"/> <property name="javax.persistence.jdbc.user" value="bank"/> <property name="javax.persistence.jdbc.password" value="secret"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> </properties> </persistence-unit> </persistence>   Optimistic Locking In optimistic locking, it is assumed that the transaction which changes/modifies the entity is engaged in isolation; in other words, it is assumed that this transaction is the only one playing with the entity currently. Obvious, this model of transaction does not acquire any locks until an actual transaction has been made, which usually is obtained at the end of the transaction. This is only possible when the query is fired to send data to the database and update at flush time. Now what happens when in the meantime some other transaction brings forth changes to the same entity? That means, flushing the transaction must be able to see whether other transactions have intervened with the commit operation. In such a situation, the current transaction simply rolls back and throws an exception called OptimisticLockException. Observe in the table below what happens when a concurrent transaction of withdraw and deposit occurs in an uncontrolled fashion. Assume initial balance is 1000. Time T1 T2 Remarks 1 withdraw() balance=balance-500   balance=1000-500 2   deposit() balance=balance+500 balance=1000+500 3 commit(balance)   writes balance = 500 4   commit(balance) Writes balance=1500 because when balance was read by T2 it was 1000, and  writes back 1000+500 = 1500. Previous value committed by T1 gets lost/overwritten Note: This is a classic example of a lost update problem; there can be many other problems such as dirty read, incorrect summary, etc. found in any database literature. We can overcome this syndrome with the help of the versioning mechanism of the JPA provider. Add a dedicated persistent property to store the version number of the entity into the database with the annotation @Version as shown below. Listing 5: Entity class with versioning package org.mano.dto;   //... import statements   @Entity //... public class Account implements Serializable{              @Id         private Long accountNumber;           @Version         private Integer version;                 //...         //... constructors, getters and setters, toString method }   Listing 6: Optimistic lock enabled   public Account deposit(Long accno, Float amount) {                 Account a = entityManager.find(Account.class, accno);                 if (a != null) {                         entityManager.lock(a, LockModeType.OPTIMISTIC);                         a.setBalance(a.getBalance() + amount);                 }                 return a;         } Now, during any change, the JPA provider checks the version number; if it matches with the version number it obtained previously then changes can be applied otherwise an exception is thrown. Versioning is the basis of the optimistic locking model of JPA.  Optimistic locking is the default model. Pessimistic Locking In pessimistic locking, instead of waiting until the commit phase, with blind optimism that no other transaction has intervened and no change in the data item has occurred, a lock is obtained immediately. That is, the objective is to acquire the lock before starting any transaction operation. Thus it leaves no room for transaction failure due to concurrent changes; however, observe that it also leaves no room for parallel execution of transactions. In a sense it violates the principles of concurrency as there can be a lot of unused time left for some other transaction to perform in between lock obtained and lock released. But it has its use in some mission critical situations, where transaction isolation is an absolute necessity. It is also true, in real life that there are very few instances where such pessimism is required. This is one of the primary reasons why optimistic locking is the default model of JPA. For example, to enable pessimistic WRITE_LOCK in our above application we have to invoke the function lock(a, LockModeType.PESSIMISTIC_WRITE) of EntityManager as follows. Listing 7: Pessimistic lock enabled public Account deposit(Long accno, Float amount) {                 Account a = entityManager.find(Account.class, accno);                 if (a != null) {                         entityManager.lock(a, LockModeType.PESSIMISTIC_WRITE);                         a.setBalance(a.getBalance() + amount);                 }                 return a;         }     Conclusion How to manage concurrent access to JPA entity is a big topic. The article gives a glimpse of the phenomenon, a basic understanding of how to implement one in JPA. Bear in mind that locking at the database-level is quite different from locking at entity-level. JPA does not replace, it rather complements the process of concurrency control mechanism. More information on locking and concurrency can be obtained from Java EE 7 tutorial documentation. Tags: API, JPA, LOCKING, Java EE 7 Comment and Contribute   (Maximum characters: 1200). You have characters left.     Sitemap | Contact Us Rocket Fuel
__label__pos
0.810436
Neophobe Plebeian Mumpsimus isset-php 1.0.7 • Public • Published isset-php Pipeline Status JavaScript Style Guide Safe and simple implementation of PHP isset() for JavaScript. Installation This is a zero dependency library that is safe from both ReferenceError: is not defined and TypeError: cannot read property of undefined exceptions. npm install --save isset-php Description TypeScript function signature: isset(accessor: Function, ...accessors: Function[]): boolean; Determine if a variable is considered set, this means if a variable is declared and is different than null or undefined. If a variable has been unset with the delete keyword, it is no longer considered to be set. isset() will return false when checking a variable that has been assigned to null or undefined. Also note that a null character ("\0") is not equivalent to the JavaScript null constant. If multiple parameters are supplied then isset() will return true only if all of the parameters are considered set. Evaluation goes from left to right and stops as soon as an unset variable is encountered. Parameters accessor Accessor function returning the variable to be checked. accessors Further accessor functions. Return Values Returns true if all accessors return a value that is not null or undefined. false otherwise. Examples Example #1 isset() Examples const isset = require('isset-php') let val = '' // This will evaluate to true so the text will be printed. if (isset(() => val)) { console.log('This val is set so I will print.') } // Less compact but still viable except when trying to use `this` context if (isset(function () { return val })) { console.log('This val is set so I will also print.') } In the next examples we'll use console.log() to output the return value of isset(). let a = 'test' let b = 'anothertest' console.log(isset(() => a)) // true console.log(isset(() => a, () => b)) // true // This might throw a parsing error: Deleting local variable in strict mode delete a console.log(isset(() => a)) // false console.log(isset(() => a, () => b)) // false let foo = null console.log(isset(() => foo)) // false This also work for elements in objects: let a = { test: 1, hello: null, pie: { a: 'apple' } } console.log(isset(() => a.test)) // true console.log(isset(() => a.foo)) // false console.log(isset(() => a.hello)) // false // The key 'hello' equals null so is considered unset. If you want to check for // null key values then try: console.log(Object.prototype.hasOwnProperty.call(a, 'hello')) // true // Checking deeper object values console.log(isset(() => a.pie.a)) // true console.log(isset(() => a.pie.b)) // false console.log(isset(() => a.cake.a.b)) // false Example #2 isset() on String Offsets const expectedArrayGotString = 'somestring' console.log(isset(() => expectedArrayGotString.some_key)) console.log(isset(() => expectedArrayGotString[0])) console.log(isset(() => expectedArrayGotString['0'])) console.log(isset(() => expectedArrayGotString[0.5])) console.log(isset(() => expectedArrayGotString['0.5'])) console.log(isset(() => expectedArrayGotString['0 Mostel'])) Output of the above example in PHP 5.4 and above: false true true true <-- PHP casts 0.5 to 0 for string offsets and throws a notice false false Output of the above example in JavaScript: false true true false <-- JS does not cast 0.5 to 0 false false This is the only caveat with the JavaScript port as this behaviour is not emulated. Explanation Pulled from StackOverflow. PHP Note that in PHP you can reference any variable at any depth - even trying to access a non-array as an array will return a simple true or false: // Referencing an undeclared variable isset($some); // false $some = 'hello'; // Declared but has no depth(not an array) isset($some); // true isset($some['nested']); // false $some = ['nested' => 'hello']; // Declared as an array but not with the depth we're testing for isset($some['nested']); // true isset($some['nested']['deeper']); // false JavaScript In JavaScript, we don't have that freedom, we'll always get an error if we do the same because JS is immediately attempting to access the value of deeper before we can wrap it in our isset() function so... // Common pitfall answer(ES6 arrow function) const isset = (ref) => typeof ref !== 'undefined' // Same as above function isset (ref) { return typeof ref !== 'undefined' } // Referencing an undeclared variable will throw an error, so no luck here isset(some) // Error: some is not defined // Defining a simple object with no properties - so we aren't defining // the property `nested` let some = {} // Simple checking if we have a declared variable isset(some) // true // Now trying to see if we have a top level property, still valid isset(some.nested) // false // But here is where things fall apart: trying to access a deep property // of a complex object; it will throw an error isset(some.nested.deeper) // Error: Cannot read property 'deeper' of undefined // ^^^^^^ undefined More failing alternatives: // Any way we attempt to access the `deeper` property of `nested` will // throw an error some.nested.deeper.hasOwnProperty('value') // Error // ^^^^^^ undefined // Similar to the above but safe from objects overriding `hasOwnProperty` Object.prototype.hasOwnProperty.call(some.nested.deeper, 'value') // Error // ^^^^^^ undefined // Same goes for typeof typeof some.nested.deeper !== 'undefined' // Error // ^^^^^^ undefined And some working alternatives that can get redundant fast: // Wrap everything in try...catch try { if (isset(some.nested.deeper)) { // ... } } catch (e) {} try { if (some.nested.deeper !== undefined && some.nested.deeper !== null) { // ... } } catch (e) {} // Or by chaining all of the isset which can get long isset(some) && isset(some.nested) && isset(some.nested.deeper) // false // ^^^^^^ returns false so the next isset() is never run Install npm i isset-php DownloadsWeekly Downloads 69 Version 1.0.7 License Apache-2.0 Unpacked Size 15.5 kB Total Files 5 Last publish Collaborators • enomws
__label__pos
0.628658
iPhone 4 - strange noise problem on call Discussion in 'iPhone Help' started by weatherreport, Sep 15, 2011. 1. weatherreport weatherreport New Member Joined: Sep 15, 2011 Messages: 2 Likes Received: 0 Trophy Points: 0 For 2 month or so, my 6 months old iphone 4 (not jailbroken) started to make some weird noises. I hear loud scratching noises coming from the speaker (also from the earphones) during a call. Today while talking to my father, i realized that this noise appear and arise when the opposite side is silent. I don't get what's wrong but this may be a clue for someone with a similar experience. Since this problem began, i've installed updated latest ios's at least two times.* Does anyone have any idea? Thanks alredy.   2. Darkstar2007 Darkstar2007 Administrator Staff Member Joined: Mar 16, 2011 Messages: 6,014 Likes Received: 364 Trophy Points: 83 Location: On a Lake in Alabama It sounds like a hardware issue. I would make an appointment at the Apple store, and see if they can fix it. Since your device is still under warranty!   3. iCrank iCrank Member Joined: Feb 27, 2011 Messages: 5,606 Likes Received: 84 Trophy Points: 48 Location: Vallejo, Ca I have no idea what the issue could be. There seems to be a lot of issues these days with the iPhone. I would suggest replacing it with apple. They replaced my iPhone and earphones the other day on spot.   4. weatherreport weatherreport New Member Joined: Sep 15, 2011 Messages: 2 Likes Received: 0 Trophy Points: 0 Well, it seems to be the best option to go to Apple for a replacement... But I'm in Istanbul and Apple doesn't serve directly here. There are contracted third parties here. They are as kind as Apple but they usually respond very slow. It may take a month and maybe more and I really don't want that now. Do you really think this is a hardware issue? This strange noise doesn't sound as a mechanical one, don't happen all the time and especially not while shaking or moving the phone. And BTW, does installing the latest ios do the same thing as a restore? I didn't try the same old backup-and-restore thing.   5. EWyatt EWyatt Active Member Joined: Nov 22, 2010 Messages: 1,837 Likes Received: 22 Trophy Points: 38 Question, iCrank. This thread raises a point for people like me who live hundreds of miles (well, maybe just 220 miles) from the nearest Apple Store. What are our options? Will the local ATT store where many of us purchased our iPhones honor our 1 year warranty (or two year warranty if the Apple Care package was purchased)? Are there any other options for us if we have hardware issues, other than driving a 400+ mile round trip? Note: tough question for you possibly. Apologies putting you on the spot, but you're good!! Anyone else?????   6. iCrank iCrank Member Joined: Feb 27, 2011 Messages: 5,606 Likes Received: 84 Trophy Points: 48 Location: Vallejo, Ca I just called my local apple store and was told that you would have to schedule a genius bar appointment to get your device swapped out. I mentioned the distance and was told that you would still have to make an appt. Good deal that apple is working on a over the net diagnostics for users in your situation. It just sucks that you'll have to travel. I'm not familiar with how AT&T operates but good manners goes a long way. On top of that apple keeps a good standing reputation with its customers and I'm sure you'll be able to send it in.   Share This Page Search tags for this page clicking popping when calling out iphone 5 , during call phone is making thump noise , iphone 4s makes noise during calls , iphone is making a noise when i make a call , iphone makes weird noise when calling , iphone weird garbling noises , phone my iphone makes a weird noise , strange noise during call iphone , very strainge noise in my iphone when i call to , weird chime when on call
__label__pos
0.50385
Introduction: Random Password Generator V.1.2 Hello! I created a random password generator using batch. You can specify the number of characters you want the password to be, and you can also choose to save the password with a label to a text file. Feel free use it and edit it for whatever you want! Until next time! Update 1: Fixed an error that incorrectly escapes characters, so they won't appear in the password. The appearance of the script was also altered.
__label__pos
0.972962
Programming paradigm From HandWiki Short description: Programming language classification Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mainly with implications for the execution model of the language, such as allowing side effects, or whether the sequence of operations is defined by the execution model. Other paradigms are concerned mainly with the way that code is organized, such as grouping a code into units along with the state that is modified by the code. Yet others are concerned mainly with the style of syntax and grammar. Common programming paradigms include:[1][2][3] • imperative in which the programmer instructs the machine how to change its state, • procedural which groups instructions into procedures, • object-oriented which groups instructions with the part of the state they operate on, • declarative in which the programmer merely declares properties of the desired result, but not how to compute it • functional in which the desired result is declared as the value of a series of function applications, • logic in which the desired result is declared as the answer to a question about a system of facts and rules, • mathematical in which the desired result is declared as the solution of an optimization problem • reactive in which the desired result is declared with data streams and the propagation of change Symbolic techniques such as reflection, which allow the program to refer to itself, might also be considered as a programming paradigm. However, this is compatible with the major paradigms and thus is not a real paradigm in its own right. For example, languages that fall into the imperative paradigm have two main features: they state the order in which operations occur, with constructs that explicitly control that order, and they allow side effects, in which state can be modified at one point in time, within one unit of code, and then later read at a different point in time inside a different unit of code. The communication between the units of code is not explicit. Meanwhile, in object-oriented programming, code is organized into objects that contain a state that is only modified by the code that is part of the object. Most object-oriented languages are also imperative languages. In contrast, languages that fit the declarative paradigm do not state the order in which to execute operations. Instead, they supply a number of available operations in the system, along with the conditions under which each is allowed to execute. The implementation of the language's execution model tracks which operations are free to execute and chooses the order independently. More at Comparison of multi-paradigm programming languages. Overview Overview of the various programming paradigms according to Peter Van Roy[4]:5[5] Just as software engineering (as a process) is defined by differing methodologies, so the programming languages (as models of computation) are defined by differing paradigms. Some languages are designed to support one paradigm (Smalltalk supports object-oriented programming, Haskell supports functional programming), while other programming languages support multiple paradigms (such as Object Pascal, C++, Java, JavaScript, C#, Scala, Visual Basic, Common Lisp, Scheme, Perl, PHP, Python, Ruby, Oz, and F#). For example, programs written in C++, Object Pascal or PHP can be purely procedural, purely object-oriented, or can contain elements of both or other paradigms. Software designers and programmers decide how to use those paradigm elements. In object-oriented programming, programs are treated as a set of interacting objects. In functional programming, programs are treated as a sequence of stateless function evaluations. When programming computers or systems with many processors, in process-oriented programming, programs are treated as sets of concurrent processes that act on a logical shared data structures. Many programming paradigms are as well known for the techniques they forbid as for those they enable. For instance, pure functional programming disallows use of side-effects, while structured programming disallows use of the goto statement. Partly for this reason, new paradigms are often regarded as doctrinaire or overly rigid by those accustomed to earlier styles.[6] Yet, avoiding certain techniques can make it easier to understand program behavior, and to prove theorems about program correctness. Programming paradigms can also be compared with programming models, which allows invoking an execution model by using only an API. Programming models can also be classified into paradigms based on features of the execution model. For parallel computing, using a programming model instead of a language is common. The reason is that details of the parallel hardware leak into the abstractions used to program the hardware. This causes the programmer to have to map patterns in the algorithm onto patterns in the execution model (which have been inserted due to leakage of hardware into the abstraction). As a consequence, no one parallel programming language maps well to all computation problems. Thus, it is more convenient to use a base sequential language and insert API calls to parallel execution models via a programming model. Such parallel programming models can be classified according to abstractions that reflect the hardware, such as shared memory, distributed memory with message passing, notions of place visible in the code, and so forth. These can be considered flavors of programming paradigm that apply to only parallel languages and programming models. Criticism Some programming language researchers criticise the notion of paradigms as a classification of programming languages, e.g. Harper,[7] and Krishnamurthi.[8] They argue that many programming languages cannot be strictly classified into one paradigm, but rather include features from several paradigms. See Comparison of multi-paradigm programming languages. History Different approaches to programming have developed over time, being identified as such either at the time or retrospectively. An early approach consciously identified as such is structured programming, advocated since the mid 1960s. The concept of a "programming paradigm" as such dates at least to 1978, in the Turing Award lecture of Robert W. Floyd, entitled The Paradigms of Programming, which cites the notion of paradigm as used by Thomas Kuhn in his The Structure of Scientific Revolutions (1962).[9] Machine code The lowest-level programming paradigms are machine code, which directly represents the instructions (the contents of program memory) as a sequence of numbers, and assembly language where the machine instructions are represented by mnemonics and memory addresses can be given symbolic labels. These are sometimes called first- and second-generation languages. In the 1960s, assembly languages were developed to support library COPY and quite sophisticated conditional macro generation and preprocessing abilities, CALL to (subroutines), external variables and common sections (globals), enabling significant code re-use and isolation from hardware specifics via the use of logical operators such as READ/WRITE/GET/PUT. Assembly was and still is, used for time-critical systems and often in embedded systems as it gives the most direct control of what the machine does. Procedural languages The next advance was the development of procedural languages. These third-generation languages (the first described as high-level languages) use vocabulary related to the problem being solved. For example, • COmmon Business Oriented Language (COBOL) – uses terms like file, move and copy. • FORmula TRANslation (FORTRAN) – using mathematical language terminology, it was developed mainly for scientific and engineering problems. • ALGOrithmic Language (ALGOL) – focused on being an appropriate language to define algorithms, while using mathematical language terminology, targeting scientific and engineering problems, just like FORTRAN. • Programming Language One (PL/I) – a hybrid commercial-scientific general purpose language supporting pointers. • Beginners All purpose Symbolic Instruction Code (BASIC) – it was developed to enable more people to write programs. • C – a general-purpose programming language, initially developed by Dennis Ritchie between 1969 and 1973 at AT&T Bell Labs. All these languages follow the procedural paradigm. That is, they describe, step by step, exactly the procedure that should, according to the particular programmer at least, be followed to solve a specific problem. The efficacy and efficiency of any such solution are both therefore entirely subjective and highly dependent on that programmer's experience, inventiveness, and ability. Object-oriented programming Main page: Object-oriented programming Following the widespread use of procedural languages, object-oriented programming (OOP) languages were created, such as Simula, Smalltalk, C++, Eiffel, Python, PHP, Java, and C#. In these languages, data and methods to manipulate it are kept as one unit called an object. With perfect encapsulation, one of the distinguishing features of OOP, the only way that another object or user would be able to access the data is via the object's methods. Thus, an object's inner workings may be changed without affecting any code that uses the object. There is still some controversy raised by Alexander Stepanov, Richard Stallman[10] and other programmers, concerning the efficacy of the OOP paradigm versus the procedural paradigm. The need for every object to have associative methods leads some skeptics to associate OOP with software bloat; an attempt to resolve this dilemma came through polymorphism. Because object-oriented programming is considered a paradigm, not a language, it is possible to create even an object-oriented assembler language. High Level Assembly (HLA) is an example of this that fully supports advanced data types and object-oriented assembly language programming – despite its early origins. Thus, differing programming paradigms can be seen rather like motivational memes of their advocates, rather than necessarily representing progress from one level to the next. Precise comparisons of competing paradigms' efficacy are frequently made more difficult because of new and differing terminology applied to similar entities and processes together with numerous implementation distinctions across languages. Further paradigms Literate programming, as a form of imperative programming, structures programs as a human-centered web, as in a hypertext essay: documentation is integral to the program, and the program is structured following the logic of prose exposition, rather than compiler convenience. Independent of the imperative branch, declarative programming paradigms were developed. In these languages, the computer is told what the problem is, not how to solve the problem – the program is structured as a set of properties to find in the expected result, not as a procedure to follow. Given a database or a set of rules, the computer tries to find a solution matching all the desired properties. An archetype of a declarative language is the fourth generation language SQL, and the family of functional languages and logic programming. Functional programming is a subset of declarative programming. Programs written using this paradigm use functions, blocks of code intended to behave like mathematical functions. Functional languages discourage changes in the value of variables through assignment, making a great deal of use of recursion instead. The logic programming paradigm views computation as automated reasoning over a body of knowledge. Facts about the problem domain are expressed as logic formulas, and programs are executed by applying inference rules over them until an answer to the problem is found, or the set of formulas is proved inconsistent. Symbolic programming is a paradigm that describes programs able to manipulate formulas and program components as data.[3] Programs can thus effectively modify themselves, and appear to "learn", making them suited for applications such as artificial intelligence, expert systems, natural-language processing and computer games. Languages that support this paradigm include Lisp and Prolog.[11] Differentiable programming structures programs so that they can be differentiated throughout, usually via automatic differentiation.[12][13] Support for multiple paradigms Most programming languages support more than one programming paradigm to allow programmers to use the most suitable programming style and associated language constructs for a given job.[14] See also References 1. Nørmark, Kurt. Overview of the four main programming paradigms. Aalborg University, 9 May 2011. Retrieved 22 September 2012. 2. Frans Coenen (1999-10-11). "Characteristics of declarative programming languages". http://cgi.csc.liv.ac.uk/~frans/OldLectures/2CS24/declarative.html#detail.  3. 3.0 3.1 Michael A. Covington (2010-08-23). "CSCI/ARTI 4540/6540: First Lecture on Symbolic Programming and LISP". University of Georgia. http://www.ai.uga.edu/mc/LispNotes/FirstLectureOnSymbolicProgramming.pdf.  4. Peter Van Roy (2009-05-12). "Programming Paradigms: What Every Programmer Should Know". info.ucl.ac.be. http://www.info.ucl.ac.be/~pvr/VanRoyChapter.pdf.  5. Peter Van-Roy; Seif Haridi (2004). Concepts, Techniques, and Models of Computer Programming. MIT Press. ISBN 978-0-262-22069-9. https://books.google.com/books?id=_bmyEnUnfTsC.  6. Frank Rubin (March 1987). "'GOTO Considered Harmful' Considered Harmful". Communications of the ACM 30 (3): 195–196. doi:10.1145/214748.315722. http://www.ecn.purdue.edu/ParaMount/papers/rubin87goto.pdf.  7. Harper, Robert (1 May 2017). "What, if anything, is a programming-paradigm?". Cambridge University Press. http://www.cambridgeblog.org/2017/05/what-if-anything-is-a-programming-paradigm/.  8. Krishnamurthi, Shriram (November 2008). "Teaching programming languages in a post-linnaean age". SIGPLAN. ACM. pp. 81–83. http://dl.acm.org/citation.cfm?id=1480846. . 9. Floyd, R. W. (1979). "The paradigms of programming". Communications of the ACM 22 (8): 455–460. doi:10.1145/359138.359140. http://dl.acm.org/ft_gateway.cfm?id=359140&ftid=289772&dwn=1&CFID=285645736&CFTOKEN=55009136.  10. "Mode inheritance, cloning, hooks & OOP (Google Groups Discussion)". http://groups.google.com/group/comp.emacs.xemacs/browse_thread/thread/d0af257a2837640c/37f251537fafbb03?lnk=st&q=%22Richard+Stallman%22+oop&rnum=5&hl=en#37f251537fafbb03.  11. "Business glossary: Symbolic programming definition". http://www.allbusiness.com/glossaries/symbolic-programming/4950308-1.html.  12. Wang, Fei; Decker, James; Wu, Xilun; Essertel, Gregory; Rompf, Tiark (2018), Bengio, S.; Wallach, H.; Larochelle, H. et al., eds., "Backpropagation with Callbacks: Foundations for Efficient and Expressive Differentiable Programming", Advances in Neural Information Processing Systems 31 (Curran Associates, Inc.): pp. 10201–10212, http://papers.nips.cc/paper/8221-backpropagation-with-callbacks-foundations-for-efficient-and-expressive-differentiable-programming.pdf, retrieved 2019-02-13  13. Innes, Mike (2018). "On Machine Learning and Programming Languages". SysML Conference 2018. http://www.sysml.cc/doc/37.pdf. Retrieved 2019-02-13.  14. "Multi-Paradigm Programming Language". Mozilla Foundation. https://developer.mozilla.org/en-US/docs/multiparadigmlanguage.html.  External links
__label__pos
0.709363
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. I need to detect when the selected tab changes, and get its index. The following code works, but it fires the println as many times as the amount of tabs currently loaded: tabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { System.out.println("Tab: " + tabbedPane.getSelectedIndex()); // Prints the string 3 times if there are 3 tabs etc } }); What is the correct way of doing this? Thank you in advance. share|improve this question      Check this: exampledepot.com/egs/javax.swing/tabbed_TpEvt.html Does it help you? –  Alberto Solano Jul 23 '11 at 10:38      No, in fact it uses the same methods than my example –  vemv Jul 23 '11 at 10:55      Sorry, but if you want to detect the id when the selected tab changes, don't you need to know where you have the ChangeEvent, with getSource() ? IMHO, maybe I'm wrong, the code prints out 3 times (if you have 3 tabs) because we don't know the "source" of event. How can you get the id of the selected tab changed when the code doesn't know what tab changed? –  Alberto Solano Jul 23 '11 at 11:20      tabbedPane.getSelectedIndex(); –  vemv Jul 23 '11 at 14:23      You are doing this in the correct way, and I also get multiple events. Is this a problem? –  Jonas Jul 23 '11 at 16:02 2 Answers 2 up vote 19 down vote accepted By JDK 6 Update 26 (Windows 7 64-Bit), I only get one event for the following demonstration code: public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setBounds(0, 0, 300, 400); frame.setLayout(null); final JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.addTab("One", new JPanel()); tabbedPane.addTab("Two", new JPanel()); tabbedPane.addTab("Three", new JPanel()); tabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { System.out.println("Tab: " + tabbedPane.getSelectedIndex()); } }); tabbedPane.setBounds(0, 0, 300, 400); frame.add(tabbedPane); frame.setVisible(true); } Can you figure out in the debugger why the listener is triggered three times? share|improve this answer 7   Okay I'm stupid. The code that adds the ChangeListener is in the same block that adds a Tab so I was adding one listener per tab. –  vemv Jul 24 '11 at 11:16 for example import java.awt.*; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class TestTabbedPane { public static void main(String[] args) { Runnable r = new Runnable() { @Override public void run() { final JPanel ui = new JPanel(new BorderLayout(1, 1)); JTabbedPane jtp = new JTabbedPane(JTabbedPane.LEFT); jtp.addTab("Apple", new JLabel("Apple")); jtp.addTab("Banana", new JLabel("Banana")); jtp.addTab("Cherries", new JLabel("Cherries")); jtp.addTab("Grapes", new JLabel("Grapes")); ui.add(jtp, BorderLayout.CENTER); jtp.setPreferredSize(new Dimension(200, 200)); jtp.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (e.getSource() instanceof JTabbedPane) { JTabbedPane pane = (JTabbedPane) e.getSource(); System.out.println("Selected paneNo : " + pane.getSelectedIndex()); } } }); } }; SwingUtilities.invokeLater(r); } private TestTabbedPane() { } } printOut run: Selected paneNo : 1 Selected paneNo : 2 Selected paneNo : 3 BUILD SUCCESSFUL (total time: 7 seconds) share|improve this answer Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.616088
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. I have a Schedule which hasMany Events. Each Event belongsTo a Room. I set up my options for a Contain'd find:: $options = array( 'conditions' => array('Schedule.' . $this->Schedule->primaryKey => $id), 'contain' => array( 'Event' => array( 'Room' // Etc. I find everything using: $sched = $this->Schedule->find('first', $options); I have an afterFind method defined on the Event's model; In that I copy the Room's name into the event's displayname so that the event can clearly identify which room it's in. The Problem: In the afterFind method Event has no subsidiary records. Specifically, it has no Room record. If I do a normal/non-Contain'd find (with the $this->Schedule->recursive field set to 3) then I DO see the Room's data. Is there a way for Contain to fetch data of a related record before the afterFind method is called? share|improve this question add comment 2 Answers up vote 1 down vote accepted IMHO, I'm guessing the reason you want to copy the room name into the event's display name is for a view? May I suggest an alternative approach to this problem? I think it would be far simpler to create a view helper to assist on rendering the event with its associated room information. It doesn't have to be too complex, for example: In your view: echo $this->Event->displayName($eventRecord) Given the depth of documentation relating to the containable behavior, it is pure black-magic how it works and I personally wouldn't want to modify any of its code to do what you propose. I totally appreciate what you're trying to achieve but sticking to the principles of KISS, this seems like the right advice to give. share|improve this answer add comment In many situations, the Containable behavior will 'split' the find() query into separate queries and merge the results later on using PHP. To force performing a single query, you may try to use joins in stead. However, because of the hasMany, using only joins will probably not be the most efficient query. Joins-example; $options = array( 'conditions' => array('Schedule.' . $this->Schedule->primaryKey => $id), 'contain' => array( 'Event' => array( 'joins' => array( array( 'table' => 'rooms', 'alias' => 'Room', 'type' => 'INNER', 'conditions' => array( 'Room.id = Event.room_id', ) ) ) ) ); note I am not sure if CakePHP accepts joins to be defined inside a Contain. More information on manually specifying joins can be found here: Joining Tables share|improve this answer add comment Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.544459
Roman Numerals Roman Numerals: 969 = CMLXIX Convert Roman Numerals Arabic numerals: Roman numerals: Arabic numerals         0 1MCXI 2MMCCXXII 3MMMCCCXXXIII 4CDXLIV 5DLV 6DCLXVI 7DCCLXXVII 8DCCCLXXXVIII 9CMXCIX The converter lets you go from arabic to roman numerals and vice versa. Simply type in the number you would like to convert in the field you would like to convert from, and the number in the other format will appear in the other field. Due to the limitations of the roman number system you can only convert numbers from 1 to 3999. To easily convert between roman and arabic numerals you can use the table above. The key is to handle one arabic digit at a time, and translate it to the right roman number, where zeroes become empty. Go ahead and use the converter and observe how the table shows the solution in realtime! Current date and time in Roman Numerals 2019-11-18 10:15:36 MMXIX-XI-XVIII X:XV:XXXVI Here is the current date and time written in roman numerals. Since the roman number system doesn't have a zero, the hour, minute, and second component of the timestamps sometimes become empty. The year 969 Here you can read more about what happened in the year 969. The number 969 The number 969 is divisble by 3, 17, 19, 51, 57 and 323 and can be prime factorized into 3×17×19. 969 as a binary number: 1111001001 969 as an octal number: 1711 969 as a hexadecimal number: 3C9 Numbers close to 969 Below are the numbers 966 through 972, which are close to 969. The right column shows how each roman numeral adds up to the total. 966 = CMLXVI = 1000 − 100 + 50 + 10 + 5 + 1 967 = CMLXVII = 1000 − 100 + 50 + 10 + 5 + 1 + 1 968 = CMLXVIII = 1000 − 100 + 50 + 10 + 5 + 1 + 1 + 1 969 = CMLXIX = 1000 − 100 + 50 + 10 + 10 − 1 970 = CMLXX = 1000 − 100 + 50 + 10 + 10 971 = CMLXXI = 1000 − 100 + 50 + 10 + 10 + 1 972 = CMLXXII = 1000 − 100 + 50 + 10 + 10 + 1 + 1 About Roman Numerals Roman numerals originate, as the name suggests, from the Ancient Roman empire. Unlike our position based system with base 10, the roman system is based on addition (and sometimes subtraction) of seven different values. These are symbols used to represent these values: SymbolValue I1 V5 X10 L50 C100 D500 M1000 For example, to express the number 737 in roman numerals you write DCCXXXVII, that is 500 + 100 + 100 + 10 + 10 + 10 + 5 + 1 + 1. However, for the numbers 4 and 9, subtraction is used instead of addition, and the smaller number is written in front of the greater number: e.g. 14 is written as XIV, i.e. 10 + 5 − 1, and 199 is expressed as CXCIX i.e. 100 + 100 − 10 + 10 − 1. It could be argued that 199 would be more easily written as CIC, but according to the most common definition you can only subtract a number that is one order of magnitude smaller than the numbers you're subtracting from, meaning that IC for 99 is incorrect. Roman numerals are often used in numbered lists, on buildings to state the year they were built, and in names of regents, such as Louis XVI of France. Feel free to link to this site if you find it useful. It's also possible to link directly to specific numbers, such as roman-numerals.info/MMDXLVII or roman-numerals.info/782. You can also link to intervals, for instance roman-numerals.info/1-100 or roman-numerals.info/1980-2020, to see the numbers in a list format.
__label__pos
0.997623
SAP BLOG InfoObject creation via ABAP Program SAP Blog Kayıtlı Üye Katılım 22 Ara 2017 Mesajlar 1,578 Tepki puanı 7 Puanları 6 Introduction Create InfoObject using ABAP program. Applies to BW/4HANA, BW Powered by HANA, BW 7.x. Summary InfoObject’s are the basic building blocks in BW. Even though we have the fields based modeling in BW Powered by HANA and also in BW/4HANA, the importance of infoobjects cannot be ignored. In many cases/times when we need to have infoobjects either as attribute or as master data(when we need to have display of the data as both key and text or as Hierarchy). Definitely the creation of infoobject is time consuming. we can simplify the creation of the infoobject using the ABAP program. Author : Lakshminarasimhan Narasimhamurthy Created on : 11/Jul/2021 Body Requirement We need to create a hundreds of info objects for a project requirement, maybe it’s a Greenfield implementation or a full fledged new development project or we need to copy all the SAP delivered infoobjects into custom infoobject’s. (Always the preferred approach is to copy the business content object and use them in the project, the reason is that during any upgrade the custom objects remain unaffected). The process in going to be time consuming and error prone due to manual creation. So we will use the ABAP program to create the Infoobjects. SAP has provided the BAPI’s(RFC function modules) for the infoobject creation and activation. 1. BAPI_IOBJ_CREATE –> Infoobject creation 2. BAPI_IOBJ_ACTIVATE_MULTIPLE –> Infoobject activation BAPI_IOBJ_CREATE.jpg BAPI_IOBJ_ACTIVATE_MULTIPLE.jpg The structure “BAPI6108” contains all the details required for the Infoobject creation. The structure must be filled with values. The internal table based on this structure must be populated with values. Better approach is to fill all the details in the excel sheet(CSV format) with the same structure as BAPI6108. Then upload it to the internal table based on the structure BAPI6108 and this internal table must be passed to the BAPI “BAPI_IOBJ_CREATE”. Kod: *&---------------------------------------------------------------------* *& Report ZBW_IO_TEMP_TEST *&---------------------------------------------------------------------* *& *&---------------------------------------------------------------------* report zbw_io_temp_test. data: begin of data_final occurs 0. include structure bapi6108. data: end of data_final. data: begin of ret_mess occurs 0. include structure bapiret2. data: end of ret_mess. *data : la_conv_tab like line of lt_conv_tab. data: begin of itab occurs 0, f1(10000) type c, end of itab. data: begin of data_iobj occurs 0. include structure bapi6108io. data: end of data_iobj. data: begin of io_err occurs 0. include structure bapi6108io. data: end of io_err. parameters: lp_file type rlgrap-filename obligatory. " To get the file location data : temp_ch type string, names type c length 1000. data : str3 type string, str4 type string, str5 type string, str6 type string, str7 type string, str8 type string, str9 type string, str10 type string, str11 type string, str12 type string, str13 type string, data_final_1 TYPE STANDARD TABLE OF bapi6108 WITH HEADER LINE. *--------------------------------------------------------------------- * AT SELECTION SCREEN ON VALUE REQUEST *--------------------------------------------------------------------- at selection-screen on value-request for lp_file. perform help_local_file using lp_file. start-of-selection. temp_ch = lp_file. call function 'GUI_UPLOAD' exporting filename = temp_ch filetype = 'ASC' * HAS_FIELD_SEPARATOR = ' ' header_length = 0 read_by_line = 'X' * DAT_MODE = ' ' * CODEPAGE = ' ' * IGNORE_CERR = ABAP_TRUE * REPLACEMENT = '#' * CHECK_BOM = ' ' * IMPORTING * FILELENGTH = * HEADER = tables data_tab = itab exceptions file_open_error = 1 file_read_error = 2 * NO_BATCH = 3 * GUI_REFUSE_FILETRANSFER = 4 * INVALID_TYPE = 5 * NO_AUTHORITY = 6 * UNKNOWN_ERROR = 7 * BAD_DATA_FORMAT = 8 * HEADER_NOT_ALLOWED = 9 * SEPARATOR_NOT_ALLOWED = 10 * HEADER_TOO_LONG = 11 * UNKNOWN_DP_ERROR = 12 access_denied = 13 * DP_OUT_OF_MEMORY = 14 * DISK_FULL = 15 * DP_TIMEOUT = 16 * OTHERS = 17 . if sy-subrc = 1. message 'FILE IS OPEN; PLEASE CHECK THE FILE.' type 'I'. *WITH "FILE IS OPEN; PLEASE CHECK THE FILE.". exit. elseif sy-subrc = 2. message 'ERROR WHILE READING THE FILE' type 'I'. exit. elseif sy-subrc = 13. message 'ACCESS DENIED.' type 'I'. exit. endif. loop at itab from 2. names = itab-f1. " if there are many columns to be split then make use of the FM 'ALSM_EXCEL_TO_INTERNAL_TABLE' split names at ',' into str3 str4 str5 str6 str7 str8 str9 str10 str11 str12 str13. data_final-infoarea = str3. data_final-infoobject = str4. data_iobj-infoobject = str4. data_final-type = str5. data_final-textshort = str6. data_final-textlong = str7. data_final-datatp = str8. data_final-intlen = str9. data_final-outputlen = str10. data_final-convexit = str11. data_final-lowercase = str12. data_final-mastauthfl = ''. data_final-attribfl = ''. append data_final to data_final. " Default header area to Internal table endloop. loop at data_final into data_final. CLEAR : data_final_1[], data_final_1. move-corresponding data_final to data_final_1. append data_final_1 to data_final_1[]. call function 'BAPI_IOBJ_CREATE' exporting details = data_final_1 importing * infoobject = return = ret_mess * tables * compounds = data_compound * attributes = data_attributes * navigationattributes = data_navigation * atrnavinfoprovider = * hierarchycharacteristics = * elimination = * returntable = . clear : data_iobj[]. data_iobj-infoobject = data_final-infoobject. append data_iobj to data_iobj[]. call function 'BAPI_IOBJ_ACTIVATE_MULTIPLE' tables infoobjects = data_iobj[] infoobjects_error = io_err. if sy-subrc <> 0. endif. endloop. form help_local_file using filename type dxfile-filename. data: lt_file_table type filetable, la_file_table like line of lt_file_table, l_rc type i, l_pcdsn type cffile-filename. refresh lt_file_table. clear la_file_table. call method cl_gui_frontend_services=>file_open_dialog changing file_table = lt_file_table rc = l_rc. read table lt_file_table into la_file_table index 1. l_pcdsn = la_file_table-filename. move l_pcdsn to filename. endform. I prepared a CSV file with just one InfoObject “YTEMP_1” and ran the program. 8-3.jpg The CSV file prepared must be entered using F4 help. 1-7.jpg Inked2_LI.jpg in the debug mode, it is visible that the file is split into separate columns 3-7.jpg if there are too many columns then we can use the FM ‘ALSM_EXCEL_TO_INTERNAL_TABLE’ to upload the data directly into the internal table. Create the Infoobject via the BAPI. 4-5.jpg Activate the Infoobject via the BAPI. 5-6.jpg The InfoObject is now created in the system 7-2.jpg In the similar fashion we can create all the Infoobjects present in the excel sheet. Note – Once the program is run, we can directly see the active version of the Infoobject existing in the RSDIOBJ table. Please see the additional below infoobjects table for your reference, RSDCHA – Characteristic Infoobjects ( with referencing Infoobject) RSDCHABAS – Characteristic Infoobjects details RSDIOBJCMP – Compounded Infoobjects RSDBCHATR – Attributes of characteristics(Display and Navigational) RSDATRNAVT – Navigation Attributes Text RSDIOBJ – List of all Infoobjects in all versions(D or M or A) RSDKYF – Keyfigure table I had different requirement to create a bunch of existing infoobjects with new naming convention hence I had used the above list of tables to populate the BAPI structure “BAPI6108”. Okumaya devam et...   Üst
__label__pos
0.581089
Question Asked by arindeep.singh | 27th Apr, 2020, 10:26: AM Expert Answer: Ramesh wants to build a small fence around the garden in his backyard. The garden is in the shape of a right triangle. If one leg is 2 metres and other leg is 1 metre. He goes to a store for purchasing fencing. The store sells fencing in tenths of a metre. (A) What is the perimeter of Ramesh's garden? Show all your work. (B) What length of fencing should Ramesh buy if the store only sells fencing in tenth of a metre? Solution: One leg = 2 metres and the other leg = 1 metre As the garden is in the shape os a right triangle, so we'll use pythagoras theorem here. Therefore we have Hypotenuse2 = 22 + 12 = 4 + 1 = 5 Hypotenuse equals square root of 5 space metre Tenth space of space straight a space metre space equals space 1 over 10 space of space 1 straight m space equals space 1 space decimetre rightwards double arrow 1 space metre space equals space 10 space decimetre left parenthesis straight A right parenthesis Perimeter space of space straight a space garden space equals space 2 plus 1 plus square root of 5 equals open parentheses 3 plus square root of 5 close parentheses space metre equals open parentheses 3 plus square root of 5 close parentheses cross times 10 space decimetre square root of 5 equals 2.23 rightwards double arrow Perimetre space of space straight a space garden space equals space open parentheses 5.23 close parentheses cross times 10 equals 52.3 space decimetre left parenthesis straight B right parenthesis As space the space perimetre space of space straight a space garden space is space 52.3 space decimetre. Thus comma space Ramesh space should space buy space 52.3 space decimtre space of space fencing space to space fence space around space the space garden. Answered by Renu Varma | 27th Apr, 2020, 10:59: AM
__label__pos
0.988512
 Ruby Basic exercises: Display the current date and time - w3resource w3resource Ruby Basic Exercises: Display the current date and time Ruby Basic: Exercise-2 with Solution Write a Ruby program to display the current date and time. Ruby Basic Exercises: Display the current date and time Ruby Code: require 'date' current_time = DateTime.now cdt = current_time.strftime "%d/%m/%Y %H:%M" puts "Current Date and Time: "+cdt Output: Current Date and Time: 27/12/2017 10:30 Flowchart: Flowchart: Display the current date and time Ruby Code Editor: Contribute your code and comments through Disqus. Contribute your code and comments through Disqus. Previous: Write Ruby program to get ruby version with patch number. Next: Write a Ruby program to create a new string which is n copies of a given string where n is a non-negative integer. What is the difficulty level of this exercise? 
__label__pos
0.661612
Chapter 4: Image Manipulation Contents 4.1 Resizing Algorithms AspJpeg.NET supports 16 popular resizing algorithms. They vary greatly in terms of quality of thumbnail output, sharpness and performance. The algorithm for your thumbnails is specified via the JpegImage.Interpolation property. The default algorithm is bilinear (1). The table below summarizes all available algorithms, their sample output and performance compared to the default algorithm. Note that thumbnail quality is usually gained at the expense of performance. Original image: Jpeg.Interpolation Algorithm Effect Execution time relative to #1 (approx.) 0 Nearest neighbor (All versions) 0.56 1 Bilinear (All versions) 1.00 2 Bicubic (All versions) 2.63 3 Bell (Version 2.2+) 1.15 4 Box (Version 2.2+) 1.00 5 Catmull Rom (Version 2.2+) 1.15 6 Cosine (Version 2.2+) 1.18 7 Cubic Convolution (Version 2.2+) 1.67 8 Cubic Spline (Version 2.2+) 1.30 9 Hermite (Version 2.2+) 0.96 10 Lanczos3 (Version 2.2+) 1.67 11 Lanczos8 (Version 2.2+) 3.41 12 Mitchell (Version 2.2+) 1.36 13 Quadratic (Version 2.2+) 0.98 14 Quadratic B-Spline (Version 2.2+) 1.15 15 Triangle (Version 2.2+) 0.98 4.2 Image Sharpening AspJpeg.NET is capable of applying a sharpening filter to an image being resized via the method JpegImage.Sharpen. A regular thumbnail and two thumbnails with various degrees of sharpening applied to them are shown below. No sharpening: Sharpen(1, 120): Sharpen(1, 250): The Sharpen method uses two Double arguments: Radius and Amount. Radius controls the size (in pixels) of an area around every pixel that the sharpening algorithm examines. This argument should normally be set to 1 or 2. Amount (expressed in %) specifies the degree of sharpness. This argument must be greater than 100. For this property to take effect, it must be set before calling Save, SendBinary or Binary. 4.3 Image Cropping AspJpeg.NET is also capable of cutting off edges from, or cropping, an image via the method JpegImage.Crop(x0, y0, x1, y1). If, prior to calling the Crop method, the Width and Height properties were set to new values, the image is first resized to the new dimensions and then cropped relative to those new dimensions. If one or more coordinates passeed to the Crop method are outside the coordinate space of the image, this will actually expand the "canvas" around the image. This is useful, for example, if you need to create margins around the image. The following code creates a 10-pixel margin around an image: objImage.Crop( -10, -10, objImage.Width + 10, objImage.Height + 10); The color of the margins created by "negative" cropping is determined by the color specified via the property JpegImage.Canvas.Brush.Color, and is black by default. To create a white 10-pixel margin, the following code should be used: objImage.Canvas.Brush.Color = 0xFFFFFFFF; // white color objImage.Crop( -10, -10, objImage.Width + 10, objImage.Height + 10 ); 4.4 Image Flipping and Rotation With AspJpeg.NET, you can invert an image horizontally and/or vertically by calling the methods FlipH and FlipV, respectively. You can also rotate an image 90 degrees clockwise and counter-clockwise by calling the methods RotateR and RotateL, respectively. AspJpeg.NET is also capable of rotating an image by an arbitrary angle via the method Rotate. The method expects two arguments: the angle (in degrees) of the counterclockwise rotation, and the fill color of the four triangular corner areas formed by the rotation. The width and height of the image are automatically increased to accommodate the slanted image. The following code rotates the image by 24 degrees and fills the corners with red color. objImage.Rotate( 24, 0xFF0000 ); The result is as follows: AspJpeg.NET is also capable of removing the corner areas entirely by making them fully transparent with the help of PNG image format. This way, the rotated image can be drawn on top of another image. This functionality is covered in Section 10.4 - Using PNG Format for Image Rotation. 4.5 Adjusting Image Compression The JPEG format uses "lossy" compression methods. This means that some minor details of an image saved as a JPEG are lost during compression. The degree of loss can be adjusted via the Jpeg.Quality property. This property accepts an integer in the range 0 to 100, with 0 being the highest degree of loss (and hence, the lowest quality) and 100 being the lowest degree of loss and highest quality. The lower the loss, the larger the resultant file size. The property Jpeg.Quality is set to 80 by default which provides a close-to-optimal combination of quality and file size. When the property Jpeg.OutputFormat is set to 3 (WEBP output format), lossy compression is used by default, also subject to the Jpeg.Quality property. To enable lossless compression, the property Jpeg.Baseline needs to be set to False. The Jpeg.Quality value is ignored in this case. 4.6 Grayscale Conversion AspJpeg.NET is capable of converting a color image to grayscale via the Grayscale method. This method expects a Method argument which specifies a formula to perform the color-to-B&W conversion. The valid values are 0, 1, and 2. The value of 1 is the recommended method for most applications. The Grayscale method sets the three color components (R, G, B) of each pixel to the same value L using the following formulas: MethodFormula 0L = 0.3333 R + 0.3333 G + 0.3333 B 1L = 0.2990 R + 0.5870 G + 0.1140 B 2L = 0.2125 R + 0.7154 G + 0.0721 B The effect of the Method argument is demonstrated by the chart below: MethodEffect Original Image 0 1 2 The effect of Method 0 is what Photoshop calls desaturation (Image/Adjust/Desaturate), while Method 1 is similar to Photoshop's conversion from RGB to grayscale (Image/Mode/Grayscale). Note that Grayscale is a method, not a property, so the '=' sign should not be used: objImage.Grayscale(1); The Grayscale method changes the colors of the image to B&W but leaves the image in the original RGB colorspace (3 bytes per pixel.) AspJpeg.NET can also convert RGB or CMYK images to the grayscale colorspace (1 byte per pixel) via the method Jpeg.ToGrayscale which accepts the same argument as Grayscale. The ToGrayscale method makes the image file smaller, and is also useful for PNG alpha channel management described in Chapter 10. CMYK-to-RGB conversion is covered in Section 8.1 of the user manual. 4.7 Sepia Filter AspJpeg.NET offers the Sepia method which makes the image look like an old photograph. This method's two parameters, Hue and Contrast, enable you to adjust the output to your taste. The Hue parameter controls the brownish hue of the output image, and should usually be in the range of 25 to 60 for good results. The Contrast parameter controls the contrast of the image. The value of 1 means no contrast adjustment. Values between 1.2 and 1.5 usually produce good results. Original Image: Hue=50, Contrast=1.4 The sample Sepia conversion shown here was achieved as follows: objImage.Sepia( 50, 1.4 ); 4.8 Code Sample The following code sample demonstrates most of the above mentioned features by interactively applying various transformations to an image. The file 04_params.cs.aspx/vb.aspx contains a form with checkboxes and radio buttons controlling the visual appearance of the image. This file invokes the script 04_process.cs.aspx/vb.aspx which contains the actual image modification routine shown below. void Page_Load( Object Source, EventArgs E) { // Create instance of JpegManager JpegManager objJpeg = new JpegManager(); // Open source image string strPath = Server.MapPath("../images/clock.jpg"); JpegImage objImage = objJpeg.OpenImage( strPath ); // Reduce size by 80% objImage.PreserveAspectRatio = true; objImage.Width = (int)(objImage.OriginalWidth * 0.8); // Specify various parameters based on the query string objImage.Quality = int.Parse(Request.QueryString["quality"]); objImage.Interpolation = int.Parse(Request.QueryString["inter"]); if (Request.QueryString["vert"] != null)   objImage.FlipV(); if (Request.QueryString["horiz"] != null)   objImage.FlipH(); if (Request.QueryString["crop"] != null)   objImage.Crop(30, 30, 470, 320); if (Request.QueryString["sepia"] != null)   objImage.Sepia(50, 1.4); if (Request.QueryString["gray"] != null)   objImage.Grayscale(); if (Request.QueryString["Sharpen"] != null)   objImage.Sharpen(1, 250); // Create thumbnail and send it directly to client browser objImage.SendBinary(); } Sub Page_Load(Source As Object, E As EventArgs) ' Create instance of JpegManager Dim objJpeg As JpegManager = New JpegManager() ' Open source image Dim strPath As String = Server.MapPath("../images/clock.jpg") Dim objImage As JpegImage = objJpeg.OpenImage(strPath) ' Reduce size by 80% objImage.PreserveAspectRatio = True objImage.Width = CType(objImage.OriginalWidth * 0.8, Integer) ' Specify various parameters based on the query string objImage.Quality = Integer.Parse(Request.QueryString("quality")) objImage.Interpolation=Integer.Parse(Request.QueryString("inter")) If Request.QueryString("vert") IsNot Nothing Then   objImage.FlipV() End If If Request.QueryString("horiz") IsNot Nothing Then   objImage.FlipH() End If If Request.QueryString("crop") IsNot Nothing Then   objImage.Crop(30, 30, 470, 320) End If If Request.QueryString("sepia") IsNot Nothing Then   objImage.Sepia(50, 1.4) End If If Request.QueryString("gray") IsNot Nothing Then   objImage.Grayscale() End If If Request.QueryString("Sharpen") IsNot Nothing Then   objImage.Sharpen(1, 250) End If ' Create thumbnail and send it directly to client browser objImage.SendBinary() End Sub </script> Click the links below to run this code sample:
__label__pos
0.890864
Are you doing “user testing” or “usability testing”? Calling anything user testing just seems bad. Okay, contrary to the usual content on this blog – which I’ve tried to make about method and technique – this discussion is philosophical and political. If you feel it isn’t decent to talk about the politics of user research in public, then you should perhaps click away right now. I know, talking about “users” opens up another whole discussion that we’re not going to have here, now. In this post, I want to focus on the difference between “usability testing” and “user testing” and why we should be specific. When I say “usability test,” what I’m talking about is testing a design for how usable it is. Rather, how unusable it is, because that’s what we can measure: how hard is it to use; how many errors do people make; how frustrated do people feel when using it. Usability testing is about finding the issues that leave a design lacking. By observing usability test sessions, a team can learn about what the issues are and make inferences about why they are happening to then implement informed design solutions. If someone says “user testing,” what does that mean? Let’s talk about the two words separately. First, what’s a “user”? It is true that we ask people who use (or who might use) a design to take part in the study of how usable the design is, and some of us might refer to those people as “users” of the product. Now, “testing” is about using some specified method for evaluating something. If you call it “user testing,” it sure sounds like you are evaluating users, even though what you probably mean to say is that you’re putting a design in front of users to see how they evaluate it. It’s shorthand, but I think it is the wrong shorthand. If the point is to observe people interacting with a design to see where the flaws in the design are and why those elements aren’t successful, then you’re going beyond user testing. You’re at usability testing. That’s what I do as part of my user research practice. I try not to test the users in the process. 4 thoughts on “Are you doing “user testing” or “usability testing”?” 1. “User testing” is just easier to say so that's why it's so common. But people generally understand that “user testing” is meant to be synonymous with “usability testing”. No one really thinks “user testing” is a test of the user. On Google, there are 350,000 pages with the term “user testing” and 643,000 pages with the term “usability testing”. 2. I don't care that there are hundreds of thousands of hits on Google for “user testing.” Calling it that is pure laziness. I absolutely beg to differ on “user testing” being acceptable because it's easier. Using the term “user testing” so suggests that you are testing the user that researchers and organizations really do think of usability testing as a QA-like activity. It just isn't. If you use “user testing” or “testing” when you're talking to participants, you are in serious danger of making them think that you really are testing them. You're not. By doing usability testing, you are evaluating the design. And, by the way, the user *never* fails. The design fails the user. 3. I propose we start using the term "design testing" or "product testing" since there is so much confusion around "usability" and "user". In my experience "usability testing" is a subset of "user testing" and they’re not interchangeable. They absolutely do not mean the same thing in UX professionals mind that I know. 1. I’m just never testing users. The design is the subject of the testing or the research. Users are participants, without whom we could never learn what works well (and what does not). Leave a Reply Your email address will not be published. Required fields are marked * This site uses Akismet to reduce spam. Learn how your comment data is processed.
__label__pos
0.819432
Themes are sets of properties and colors for each control. They define style and appearance of controls in Dapfor library. In addition to properties and cooler themes contain code for specific painting of various control elements (including .Net Grid). Themes The grid supports attachment of themes via Grid.Theme property. Dapfor's library contains several predefined themes such as Theme.XPStyle, Theme.Silver, etc. The list of predefined themes is stored in Dapfor.Net.Theming.KnownTheme enumeration. Accordingly, theme object can be obtained with the following code. C# Copy imageCopy grid1.Theme = Theme.XPStyle; grid2.Theme = Theme.FromKnownTheme(KnownTheme.XPStyle); A programmer may also create his own themes, including those based on already existing themes. The example below demonstrates creation of an arbitrary theme on the basis of an existing theme. Therefore, all grids using the same theme shall look in the same way. C# Copy imageCopy Theme myTheme = new Theme("MyTheme", Theme.Silver); myTheme.Renderers.GridRenderer.Appearance.ColumnNormal.BackColor = Color.LightPink; myTheme.Renderers.GridRenderer.Appearance.ColumnNormal.GradientEndBackColor = ControlPaint.Dark(Color.LightPink); grid.Theme = myTheme; Dapfor’s library provides a convenient API for theme changing. For this purpose it uses a special default theme that is returned by Theme.Default property. If a grid uses this theme, it subscribes to Theme.DefaultThemeChanged events. Therefore, when a new theme is set in Theme.Default property, all controls subscribed to this theme shall receive notifications and automatically change their appearance. C# Copy imageCopy grid1.Theme = Theme.Default; grid2.Theme = Theme.Default; Theme myTheme = new Theme("MyTheme", Theme.Silver); Theme.Default = myTheme; Grid themes have been developed to enable the programmer to change appearance of any grid elements. When a theme is set for the grid, this grid uses colors and renderer defined for each theme. In addition to that a programmer may modify colors for headers, columns, rows etc using properties like Grid.Appearance, Header.Appearance, etc.
__label__pos
0.805363
[DC-875] One-to-many relationship returns Doctrine_Record instead of Doctrine_Collection Created: 30/Sep/10  Updated: 14/Sep/11 Status: Open Project: Doctrine 1 Component/s: None Affects Version/s: 1.2.3 Fix Version/s: None Type: Bug Priority: Major Reporter: Patrik Åkerstrand Assignee: Jonathan H. Wage Resolution: Unresolved Votes: 1 Labels: None Environment: WAMP: Windows 7 - 64bit Apache 2.2 PHP 5.3.1 MySQL 5.1.41  Description    I've run into a bit of a snag in my application where a relationship defined as a one-to-many relationship returns a model object (instance of Doctrine_Record) instead of a Doctrine_Collection when I try to access it as $model->RelatedComponent[] = $child1. This, of course, yields an exception like so: Doctrine_Exception: Add is not supported for AuditLogProperty #0 path\library\Doctrine\Access.php(131): Doctrine_Access->add(Object(AuditLogProperty)) #1 path\application\models\Article.php(58): Doctrine_Access->offsetSet(NULL, Object(AuditLogProperty)) #2 path\library\Doctrine\Record.php(354): Article->postInsert(Object(Doctrine_Event)) #3 path\library\Doctrine\Connection\UnitOfWork.php(576): Doctrine_Record->invokeSaveHooks('post', 'insert', Object(Doctrine_Event)) #4 path\library\Doctrine\Connection\UnitOfWork.php(81): Doctrine_Connection_UnitOfWork->insert(Object(Article)) #5 path\library\Doctrine\Record.php(1718): Doctrine_Connection_UnitOfWork->saveGraph(Object(Article)) #6 path\application\modules\my-page\controllers\ArticleController.php(26): Doctrine_Record->save() #7 path\library\Zend\Controller\Action.php(513): MyPage_ArticleController->createAction() #8 path\library\Zend\Controller\Dispatcher\Standard.php(289): Zend_Controller_Action->dispatch('createAction') #9 path\library\Zend\Controller\Front.php(946): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http)) #10 path\library\Zend\Application\Bootstrap\Bootstrap.php(77): Zend_Controller_Front->dispatch() #11 path\library\Zend\Application.php(358): Zend_Application_Bootstrap_Bootstrap->run() #12 path\public\index.php(11): Zend_Application->run() {{#13 {main} }} This is what my yaml-schema looks like (excerpt): schema.yml AuditLogEntry: tableName: audit_log_entries actAs: Timestampable: updated: {disabled: true} columns: user_id: {type: integer(8), unsigned: true, primary: true} id: {type: integer(8), unsigned: true, primary: true, autoincrement: true} type: {type: string(255), notnull: true} mode: {type: string(16)} article_id: {type: integer(8), unsigned: true} comment_id: {type: integer(8), unsigned: true} question_id: {type: integer(8), unsigned: true} answer_id: {type: integer(8), unsigned: true} message_id: {type: integer(8), unsigned: true} indexes: # Must index autoincrementing id-column since it's a compound primary key and # the auto-incrementing column is not the first column and we use InnoDB. id: {fields: [id]} type: {fields: [type, mode]} relations: User: local: user_id foreign: user_id foreignAlias: AuditLogs type: one onDelete: CASCADE onUpdate: CASCADE AuditLogProperty: tableName: audit_log_properties columns: auditlog_id: {type: integer(8), unsigned: true, primary: true} prop_id: {type: integer(2), unsigned: true, primary: true, default: 1} name: {type: string(255), notnull: true} value: {type: string(1024)} relations: AuditLogEntry: local: auditlog_id foreign: id type: one foreignType: many foreignAlias: Properties onDelete: CASCADE onUpdate: CASCADE Now, if we look at the generated class-files, it looks fine: Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml /** * @property integer $user_id * @property integer $id * @property string $type * @property string $mode * @property integer $article_id * @property integer $comment_id * @property integer $question_id * @property integer $answer_id * @property integer $message_id * @property integer $news_comment_id * @property User $User * @property Doctrine_Collection $Properties * @property Doctrine_Collection $Notifications */ abstract class BaseAuditLogEntry extends Doctrine_Record /** * @property integer $auditlog_id * @property integer $prop_id * @property string $name * @property string $value * @property AuditLogEntry $AuditLogEntry */ abstract class BaseAuditLogProperty extends Doctrine_Record However, when I later try to add properties I get the exception posted in the beginning of the question: Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml $auditLog = new AuditLogEntry(); $prop1 = new AuditLogProperty(); $prop1->name = 'title'; $prop1->value = $this->Content->title; $prop2 = new AuditLogProperty(); $prop2->name = 'length'; $prop2->value = count($this->Content->plainText); $auditLog->Properties[] = $prop1; $auditLog->Properties[] = $prop2; $auditLog->save(); If I do the following: Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml var_dump(get_class($auditLog->Properties)); I get that Properties is of type AuditLogProperty, instead of Doctrine_Collection. I use version 1.2.3 of Doctrine.  Comments    Comment by Trevor Wencl [ 14/Sep/11 ] I am having the same issue and it is killing my application. Using your example, when I call: var_dump(get_class($auditLog->Properties)); ... and there are no AuditLogProperty records, I would expect either an empty Doctrine_Collection or null, but instead I get a new instance of AuditLogProperty with null values for the properties. Generated at Thu Sep 18 05:45:28 UTC 2014 using JIRA 6.2.3#6260-sha1:63ef1d6dac3f4f4d7db4c1effd405ba38ccdc558.
__label__pos
0.954177
(gdbint.info)New Architectures Next: Config Prev: Debugging GDB Up: Top Defining a New Host or Target Architecture ****************************************** When building support for a new host and/or target, much of the work you need to do is handled by specifying configuration files; *note Adding a New Configuration: Config.. Further work can be divided into "host-dependent" (Note: Adding a New Host.) and "target-dependent" (Note: Adding a New Target.). The following discussion is meant to explain the difference between hosts and targets. What is considered "host-dependent" versus "target-dependent"? ============================================================== "Host" refers to attributes of the system where GDB runs. "Target" refers to the system where the program being debugged executes. In most cases they are the same machine, in which case a third type of "Native" attributes come into play. Defines and include files needed to build on the host are host support. Examples are tty support, system defined types, host byte order, host float format. Defines and information needed to handle the target format are target dependent. Examples are the stack frame format, instruction set, breakpoint instruction, registers, and how to set up and tear down the stack to call a function. Information that is only needed when the host and target are the same, is native dependent. One example is Unix child process support; if the host and target are not the same, doing a fork to start the target process is a bad idea. The various macros needed for finding the registers in the `upage', running `ptrace', and such are all in the native-dependent files. Another example of native-dependent code is support for features that are really part of the target environment, but which require `#include' files that are only available on the host system. Core file handling and `setjmp' handling are two common cases. When you want to make GDB work "native" on a particular machine, you have to include all three kinds of information. The dependent information in GDB is organized into files by naming conventions. Host-Dependent Files `config/*/*.mh' Sets Makefile parameters `config/*/xm-*.h' Global #include's and #define's and definitions `*-xdep.c' Global variables and functions Native-Dependent Files `config/*/*.mh' Sets Makefile parameters (for *both* host and native) `config/*/nm-*.h' #include's and #define's and definitions. This file is only included by the small number of modules that need it, so beware of doing feature-test #define's from its macros. `*-nat.c' global variables and functions Target-Dependent Files `config/*/*.mt' Sets Makefile parameters `config/*/tm-*.h' Global #include's and #define's and definitions `*-tdep.c' Global variables and functions At this writing, most supported hosts have had their host and native dependencies sorted out properly. There are a few stragglers, which can be recognized by the absence of NATDEPFILES lines in their `config/*/*.mh'. automatically generated by info2www
__label__pos
0.746328
Calculate the Optimum Volume of a Soup Can — Practice Question By Mark Ryan Optimization problems are one practical application of calculus problems. For example, optimization enables you to maximize your results (such as profit or area) with minimal input (such as cost or energy consumption). The following practice question requires you to find the greatest volume for a soup can, using a given amount of tin. Practice question 1. What are the dimensions of the soup can of greatest volume that can be made with 50 square inches of tin? (The entire can, including the top and bottom, is made of tin.) And what’s its volume? Answer and explanation 1. The dimensions are 3 1/4 inches wide and 3 1/4 inches tall. The volume is about 27.14 cubic inches. How do you find this? Start by drawing a diagram. image0.png Now write a formula for the thing you want to maximize — in this case, the volume: image1.png Use the given information to relate r and h. image2.png Now solve for h and substitute to create a function of one variable. image3.png Figure the domain. image4.png And because image5.png Now find the critical numbers of V (r). image6.png Evaluate the volume at the critical number. image7.png That’s about 15 ounces. The can will be image8.png Isn’t that nice? The largest can has the same width and height and would thus fit perfectly into a cube. Geometric optimization problems frequently have results where the dimensions have some nice, simple mathematical relationship to each other.
__label__pos
0.970811
· Augmented Reality Cost Matthias Hamann Dieser Artikel ist auch auf deutsch verfügbar Many people considering developing an Augmented Reality App ask us about the costs to expect. Of course, this is a difficult question as it is comparable to a question like "How much is a house?". It depends on the project – nice little lawyer response. Jokes aside, let's look at this together. Main factors that influence the price The driving factors are: Project Scope The time and effort required for producing an AR app depend massively on the project scope. Generally speaking, a simple product visualization will be less costly compared to a complex and highly interactive individual application. That means features play an important role when it comes to pricing. What Are the Features? Talking about features, the degree of realism is the main point to consider. The more realistic the App looks and behaves, the higher the production costs. This is because a lot of time needs to be invested to get all the details right – making AR visualizations look highly real requires many working hours. Photo-realistic 3D models, textures, and lighting have to be created. Animations need to be smooth and life-like. The user interface must be intuitive and easy to use. When talking about realism, an important technique called "Baking" is the dirty trick in the development of real-time applications – and it also affects the price tag. Baking is a common practice in real-time 3D development that is used to create realistic and smooth shadows on objects. This technique is used to create a better immersive experience for the user. By simulating the way light behaves in the real world, baking can help to improve the overall appearance of a game or in our case – of an Augmented Reality application. There are several steps involved in baking procedures, and all of them require time and effort. How complex is the app? The complexity of the app can also have a big impact on the cost. A basic augmented reality app that just overlays text or an image onto a live camera view will be much cheaper to develop than an app with more complex features. Some apps require advanced tracking mechanisms such as 3D object tracking via edge detection algorithms or deep learning approaches (object recognition). No surprise that using these techniques can be highly time-consuming and expensive. If, on the other hand, simple image-based marker tracking is used, the effort required is usually much lower. 3D Data Basis Creating a 3D model from scratch can be very time-consuming and expensive, especially when it comes to geometrically complex structures. The quality of the data is essential to achieving good results. Poor-quality data can lead to artifacts in the rendered image and a general loss of realism. In the design process, existing CAD and 3D data may help to save time and money. Only suitable data quality, on the other hand, determines whether potential savings in production time are real. It's also crucial to remember that AR experiences utilize real-time rendering on the device. The number of polygons in the 3D model(s) has a significant influence on processing performance. As a result, existing polygon-rich data (often known as "high-poly data") must be edited (yes, often manually) to match. The Tech Stack The technology used to develop an App can also have a significant impact on the price. Frameworks or SDKs are commonly used to avoid having to reinvent the wheel every time a project is started. There are many different frameworks for webAR and native AR development, each with its own set of pros and cons. Some frameworks are more popular than others, but most of them come with a price tag. Choosing the right framework can save a lot of time and money in production and can also affect the number of possible features, the stability of tracking, and the degree of realism. Some frameworks are open source and available for free, while others have more complex licensing structures. Developing an app using a commercial framework can add significantly to the cost of producing an app. Service Providers or "spoiled for choice" The choice of service provider has one of the strongest influences on price. The most common question when starting to look for a development partner is the following: Freelancer, Studio, or Agency? In General, hiring a freelancer is the least expensive, but can be riskier if you are not sure about their skills and experience. Also, the availability for maintenance work or even during the production phase can become an issue. Hiring a small studio or network agency generally provides the best value for money, but it may be considerably more expensive than hiring a freelancer. Hiring a medium-sized or major and well-known agency can often double or triple the price. When doing so, make sure you pick an agency that is specialized in AR/VR development. The large players in the advertising business frequently promise these skills for themselves, but what they really do is purchase remote resources such as freelancers or even other companies – with hefty margins. This is only a rough estimate, but the cost of creating an augmented reality app may vary from one to five depending on the variables. You can expect to pay anything from $5,000 to $25,000 for a basic app with limited features. However, if you want more sophisticated capabilities or advanced tracking systems, the price will rise significantly. For the smarties out there: Offshore development companies usually offer a more affordable option but usually at the cost of lower quality and less support. Another con when following this approach is that you will likely need an expert supervising the project to make sure it meets the scope and the quality intended. So, be cautious about this, wise guy! Conclusion In short, the cost of developing an Augmented Reality app depends on several factors, including the scope of the project, the features, and complexity of the App, the technology used, the supplier, and the region where development takes place. However, in general, we can say that development costs can range from a few thousand dollars to tens of thousands of dollars. Although price is often decisive for the choice of a development partner, it should not be the only criterion. Often, low prices are offered by suppliers who work with low-cost resources and this can lead to problems during or after development. Inexperienced developers or lack of quality control can quickly cause delays, unstable applications, and additional costs. It's a fantastic idea to get the opinion of an impartial expert during the project's early phases. They can assist you in weighing your options and finding the perfect technology and supplier for your requirements. Not only will this save you time and money, but it will also ensure that you receive a high-quality product that fits your budget. So there you have it – an overview of the cost involved in developing an augmented reality app including some tips for do's and don'ts in the early phase of the project. We hope this article has been helpful and provided some valuable insights. If you have any questions or would like more information, please don’t hesitate to get in touch.     Title illustration by Lukas Bischoff / www.artill.de  Go back Matthias Matthias Hamann Digital strategy and concept About the author I write about my passion for technology and digital strategies. Would you like to find out more about how I work and my projects? Get more information here
__label__pos
0.68267
Если вы использовали другое средство программирования, например Visual Basic или JavaScript, у вас может возникнуть вопрос: Где переменные? PowerApps немного отличается и требует иного подхода. Вместо того чтобы мыслить в категориях переменных, спросите себя: Как это делается в Excel? Возможно, в других средствах вы явно выполняли вычисления и хранили результаты в переменной. Однако в PowerApps и Excel формулы пересчитываются автоматически при изменении входных данных, поэтому обычно не требуется создавать и обновлять переменные. Применяя такой подход по мере возможности, можно легко создавать и обслуживать приложения, полностью понимая принцип их работы. В некоторых случаях в PowerApps необходимо использовать переменные, которые расширяют модель Excel, добавляя в нее формулы поведения. Эти формулы, например, выполняются, когда пользователь нажимает кнопку. В формуле поведения зачастую удобно задать переменную, которую можно использовать в других формулах. Как правило, использовать переменные нежелательно. Однако иногда только с их помощью можно обеспечить желаемые возможности. Реализация подхода Excel в PowerApps Excel Давайте посмотрим, как работает Excel. Ячейка может содержать значение, например число, строку или формулу, в которой используются значения других ячеек. После того как пользователь вводит другое значение в ячейку, Excel автоматически пересчитывает все формулы, которые зависят от нового значения. При этом для обеспечения такого поведения не нужно ничего программировать. В Excel нет переменных. Значение ячейки, содержащей формулу, изменяется в зависимости от входных данных, но при этом нет возможности запомнить результат формулы и сохранить его в ячейке или в любом другом месте. При изменении значения ячейки может измениться вся таблица, а все ранее вычисляемые значения будут утрачены. Пользователь Excel может копировать и вставлять ячейки, но это нужно делать вручную. С помощью формул выполнить такую операцию невозможно. PowerApps Поведение приложений, создаваемых в PowerApps, во многом напоминает поведение Excel. Вместо обновления ячеек можно добавить элементы управления в любом месте на экране и присвоить им имена, чтобы их можно было использовать в формулах. Например, можно воспроизвести поведение Excel в приложении, добавив элемент управления Метка с именем TextBox1 и два элемента управления Текстовое поле с именами TextInput1 и TextInput2. Если затем задать для свойства Text элемента управления TextBox1 значение TextInput1 + TextInput2, в результате всегда будет автоматически отображаться сумма любых чисел, указанных в элементах управления TextInput1 и TextInput2. Обратите внимание, что при выборе элемента управления TextBox1 в строке формулы в верхней части экрана отображается его формула Text. В данном случае она выглядит таким образом: TextInput1 + TextInput2. Эта формула создает между этими элементами управления такую же зависимость, как между ячейками в книге Excel. Изменим значение TextInput1. Формула для TextBox1 автоматически пересчитывается, и на экране отображается новое значение. Чтобы в PowerApps определить не только основное значение элемента управления, но и его свойства, например форматирование, можно воспользоваться формулами. В следующем примере формула для свойства Color метки обеспечит автоматическое отображение отрицательных значений красным цветом. Функция If очень похожа на ту, которая используется в Excel. If( Value(TextBox1.Text) < 0, Red, Black ) Теперь, если результат наших вычислений в TextBox1.Text окажется отрицательным, число будет отображаться красным цветом. Формулы можно использовать в самых разнообразных сценариях. • Используя GPS-модуль устройства, элемент управления картой может отобразить ваше текущее расположение с помощью формулы, использующей значения Location.Latitude и Location.Longitude. При перемещении карта будет автоматически отслеживать расположение. • Другие пользователи могут обновлять источники данных. Например, другие участники группы могут обновлять элементы в списке SharePoint. При обновлении источника данных все зависимые формулы автоматически пересчитываются, в результате чего отображаются обновленные данные. Дополнив этот пример, можно задать коллекцию свойства Items в формуле Filter( SharePointList ), что обеспечит автоматическое отображение заново отфильтрованного набора записей. Преимущества Использование формул для создания приложений дает множество преимуществ. • Если вы умеете работать с Excel, вы умеете работать с PowerApps. Модель и язык формул у них одинаковы. • Если вы использовали другие средства программирования, представьте себе, сколько бы вам пришлось написать кода, чтобы обеспечить вычисления, приведенные в этих примерах. В Visual Basic необходимо написать обработчик событий для события изменения в каждом текстовом поле. Код, необходимый для выполнения вычисления в каждом из них, избыточен и может не синхронизироваться, или же вам придется написать общие подпрограммы. В PowerApps все это можно сделать с помощью единственной формулы в одну строку. • Чтобы понять, откуда берется текст TextBox1, просто посмотрите на формулу в свойстве Text. Повлиять на текст данного элемента управления другими способами невозможно. В традиционных средствах программирования любые подпрограммы и обработчики событий могут изменить значение метки из любого места в программе. Из-за этого иногда сложно отследить, где и когда была изменена переменная. • Изменив положение ползунка, пользователь может передумать и вернуть его в исходное положение. В результате как бы ничего не происходит: приложение отображает такие же значения элемента управления, как и раньше. Все это происходит без каких-либо последствий, так что можно смело экспериментировать и пробовать разные варианты, что в Excel попросту невозможно. Как правило, если желаемого эффекта можно добиться с помощью формулы, лучше использовать именно ее. Обработчик формул PowerApps сделает все автоматически. Ситуации, в которых имеет смысл использовать переменные Давайте изменим наш простой сумматор так, чтобы он функционировал по принципу старинного арифмометра, используя нарастающий итог. При нажатии кнопки Добавить число добавляется к нарастающему итогу. При нажатии кнопки Очистить нарастающий итог обнуляется. Наш арифмометр использует то, чего нет в Excel: кнопки. В этом приложении для вычисления нарастающих итогов нельзя использовать только формулы, поскольку их значение зависит от ряда действий, которые выполняет пользователь. Вместо этого нарастающий итог записывается и обновляется вручную. Большинство средств программирования сохраняет эти сведения в переменной. Иногда, чтобы приложения вели себя необходимым образом, требуется использовать переменные. Однако такой подход применим с некоторыми оговорками. • Нарастающий итог необходимо обновлять вручную. При автоматическом пересчете эта операция не выполняется. • Нарастающий итог больше нельзя рассчитать на основе значений других элементов управления. Он зависит от того, сколько раз пользователь нажимает кнопку Добавить и какое значение при этом содержится в элементе управления текстовым вводом на момент ее нажатия. Ввел ли пользователь 77 и нажал Добавить дважды или же указал 24 и 130 в качестве слагаемых? После того как итог станет равным 154, определить разницу невозможно. • Итог может изменяться по разным причинам. В этом примере к его изменению может приводить нажатие кнопок Добавить и Очистить. Как определить, какая кнопка вызывает проблему, если приложение не работает должным образом? Создание глобальной переменной Чтобы создать арифмометр, нам понадобится переменная для хранения нарастающего итога. Простейшие переменные в PowerApps — это глобальные переменные. Принцип их действия заключается в следующем: • Значение глобальной переменной задается с помощью функции Set. Set( MyVar, 1 ) задает для глобальной переменной MyVar значение 1. • Используйте эту глобальную переменную, ссылаясь на ее имя в функции Set. В этом случае MyVar возвращает значение 1. • В глобальных переменных может храниться любое значение, в том числе строки, числа, записи и таблицы. Перестроим наш арифмометр, воспользовавшись глобальными переменными. 1. Добавьте элемент управления текстовым вводом с именем TextInput1 и две кнопки с именами Button1 и Button2. 2. Задайте для свойства Text элемента управления Button1 значение "Add", а для свойства Text элемента управления Button2 — значение "Clear". 3. Чтобы нарастающий итог обновлялся, когда пользователь нажимает кнопку Добавить, задайте следующую формулу в качестве значения свойства OnSelect: Set( RunningTotal, RunningTotal + Text1 ) Когда пользователь впервые нажимает кнопку Добавить, вызывается функция Set и создается переменная RunningTotal со значением по умолчанию blank. При суммировании оно будет интерпретировать как ноль. 4. Чтобы нарастающий итог становился равным 0, когда пользователь нажимает кнопку Очистить, задайте в качестве значения его свойства OnSelect следующую формулу: Set( RunningTotal, 0 ) 5. Добавьте элемент управления Метка и задайте для его свойства Text значение RunningTotal. Эта формула пересчитывается автоматически, а для пользователя отображается значение RunningTotal, которое изменяется в зависимости от нажимаемых им кнопок. 6. Перейдите в режим предварительного просмотра приложения, и вы увидите, что наш арифмометр работает, как описано выше. Введите число в текстовое поле и нажмите кнопку Добавить несколько раз. Выполнив эти действия, вернитесь к разработке, нажав клавишу ESC. 7. Чтобы просмотреть значение нашей глобальной переменной, щелкните меню Файл и на панели слева выберите Переменные. 8. Выберите переменную, чтобы просмотреть все случаи ее определения и использования. Типы переменных Существует три типа переменных в PowerApps: Тип переменных Область действия Описание Функции Глобальные переменные Приложение Самые простые в использовании. В них могут храниться любые значения, в том числе числа, текстовые строки, логические значения, записи, таблицы и т. п., на которые можно ссылаться из любого места в приложении. Set Переменные контекста Экран Отлично подходят для передачи значений на экран, похожи на параметры для процедур на других языках. На них можно ссылаться только с одного экрана. UpdateContext Navigate Коллекции Приложение Содержит таблицу, на которую можно ссылаться из любого места в приложении. Позволяет изменять содержимое таблицы вместо того, чтобы задать все содержимое сразу. Можно сохранить на локальном устройстве для дальнейшего использования. Collect ClearCollect Patch Update Remove SaveData LoadData и т. д. Все переменные создаются неявно, когда используются в функциях Set, UpdateContext, Navigate или Collect. В нашем средстве явное объявление переменных, как в других средствах программирования, не выполняется. Кроме того, типы переменных являются неявно производными от значений, которые они содержат. Все переменные хранятся в памяти во время выполнения приложения. Когда приложение закрывается, хранящиеся в переменных значения утрачиваются. Содержимое переменной можно сохранить в источнике данных с помощью функции Patch или Collect, а коллекции можно сохранить на локальном устройстве с помощью функции SaveData. При первой загрузке приложения у всех переменных будет значение blank. Чтобы узнать значение переменной, используйте ее имя. Например, определив Set( MyColor, Red ) один раз, вы можете использовать MyVar для каждого значения цвета, и оно будет заменено на Red. Имя глобальной переменной или коллекции может совпадать с именем переменной контекста. В таком случае переменная контекста будет приоритетной. Вы по-прежнему можете ссылаться на глобальную переменную или коллекцию с помощью оператора устранения неоднозначности @[MyColor]. Создание переменной контекста Давайте попробуем создать наш арифмометр, используя переменную контекста вместо глобальной переменной. Принцип их действия заключается в следующем: • Переменные контекста создаются и задаются с помощью функции UpdateContext. Если при первом обновлении переменная контекста не существует, она создается со значением по умолчанию blank. • Для создания и обновления переменных контекста используются записи. В других средствах программирования для присвоения значений обычно используется оператор «=», например «x = 1». Для переменных контекста вместо этого используется { x: 1 }. При использовании переменной контекста используйте непосредственно ее имя. • Переменную контекста можно также задать с помощью функции Navigate при отображении соответствующего экрана. Если представить, что экран — это своего рода процедура или подпрограмма, то это будет напоминать передачу параметров в других средствах программирования. • За исключением функции Navigate, переменные контекста ограничены контекстом одного экрана (того, на котором им было присвоено их имя). Их нельзя использовать или задать вне данного контекста. • В переменных контекста может храниться любое значение, в том числе строки, числа, записи и таблицы. Перестроим наш арифмометр, воспользовавшись переменными контекста. 1. Добавьте элемент управления текстовым вводом с именем TextInput1 и две кнопки с именами Button1 и Button2. 2. Задайте для свойства Text элемента управления Button1 значение "Add", а для свойства Text элемента управления Button2 — значение "Clear". 3. Чтобы нарастающий итог обновлялся, когда пользователь нажимает кнопку Добавить, задайте следующую формулу в качестве значения свойства OnSelect: UpdateContext( { RunningTotal: RunningTotal + Text1 } ) Когда пользователь первый раз нажимает кнопку Добавить и вызывается UpdateContext, создается RunningTotal со значением по умолчанию blank. При суммировании оно будет интерпретировать как ноль. 4. Чтобы нарастающий итог становился равным 0, когда пользователь нажимает кнопку Очистить, задайте в качестве значения его свойства OnSelect следующую формулу: UpdateContext( { RunningTotal: 0 } ) Опять же, в формуле UpdateContext( { RunningTotal: 0 } ) используется UpdateContext. 5. Добавьте элемент управления Метка и задайте для его свойства Text значение RunningTotal. Эта формула пересчитывается автоматически, а для пользователя отображается значение RunningTotal, которое изменяется в зависимости от нажимаемых им кнопок. 6. Перейдите в режим предварительного просмотра приложения, и вы увидите, что наш арифмометр работает, как описано выше. Введите число в текстовое поле и нажмите кнопку Добавить несколько раз. Выполнив эти действия, вернитесь к разработке, нажав клавишу ESC. 7. Вы можете задать значение переменной контекста, перейдя на экран. Этот вариант используется для передачи контекста или параметров с одного экрана на другой. Чтобы увидеть, как это работает, вставьте новый экран и кнопку, задав для свойства OnSelect следующее: Navigate( Screen1, None, { RunningTotal: -1000 } ) Если щелкнуть эту кнопку в разделе Screen2 (это можно сделать во время разработки, щелкнув края кнопки), отобразится экран Screen1, а переменной контекста RunningTotal будет задано значение -1000. 8. Чтобы просмотреть значение нашей переменной контекста, щелкните меню Файл и на панели слева выберите Переменные. 9. Выберите переменную контекста, чтобы просмотреть все случаи ее определения и использования. Создание коллекции Наконец, давайте попробуем создать наш арифмометр с помощью коллекции. Так как коллекция хранит таблицу, которую можно легко изменить, в этом арифмометре каждое вводимое значение будет сохранятся на "бумажной ленте". Принцип действия коллекций описан ниже. • Создайте и настройте коллекции с помощью функции ClearCollect. Вместо этого можно использовать функцию Collect, но фактически для этого потребуется создать другую переменную, а не заменить имеющуюся. • Коллекция — это типа источника данных, который можно представить как таблицу. Чтобы получить доступ к отдельному значению в коллекции, воспользуйтесь функцией First и извлеките одно поле из результирующей записи. Если вы использовали одно значение с ClearCollect, это будет поле Value, как в этом примере: First( VariableName ).Value Создадим арифмометр, воспользовавшись коллекцией. 1. Добавьте элемент управления Текстовое поле с именем TextInput1 и две кнопки с именами Button1 и Button2. 2. Задайте для свойства Text элемента управления Button1 значение "Add", а для свойства Text элемента управления Button2 — значение "Clear". 3. Чтобы нарастающий итог обновлялся, когда пользователь нажимает кнопку Добавить, задайте следующую формулу в качестве значения свойства OnSelect: Collect( PaperTape, TextInput1.Text ) Эта формула добавляет новое значение в конец коллекции. Так как мы добавляем одно значение, функция Collect автоматически поместит его в таблицу с одним столбцом с именем Value, который мы будем использовать позже. 4. Чтобы очищать нашу "бумажную ленту", когда пользователь нажимает кнопку Очистить, задайте в качестве значения свойства OnSelect следующую формулу: Clear( PaperTape ) 5. Для отображения нарастающего итога добавьте метку и задайте для нее в качестве значения свойства Text следующую формулу: Sum( PaperTape, Value ) 6. Чтобы запустить арифмометр, нажмите F5, чтобы перейти в режим предварительного просмотра, введите число в текстовом поле и нажмите кнопки. 7. Нажмите клавишу ESC, чтобы вернуться в рабочую область по умолчанию. 8. Чтобы отобразить "бумажную ленту", вставьте элемент управления Таблица данных и задайте его свойству Items следующую формулу: PaperTape Также необходимо выбрать столбцы, которые будут отображаться в области справа. В нашем случае это столбец Value. 9. Чтобы просмотреть значения в коллекции, выберите в меню Файл пункт Коллекции. 10. Чтобы сохранить и извлечь коллекцию, добавьте две дополнительные кнопки и задайте для них значения Загрузить и Сохранить. Для кнопки Загрузить задайте свойству OnSelect эту формулу: Clear( PaperTape ); LoadData( PaperTape, "StoredPaperTape", true ) Сначала нам нужно очистить коллекцию, так как LoadData добавит хранящиеся значения в конец коллекции. 11. Для кнопки Сохранить задайте свойству OnSelect эту формулу: SaveData( PaperTape, "StoredPaperTape" ) 12. Перейдите в режим предварительного просмотра снова, нажав клавишу F5, введите числа в элементе управления для ввода текста и нажмите кнопки. Нажмите кнопку Сохранить. Закройте и перезапустите приложение, а затем нажмите кнопку Загрузить, чтобы повторно загрузить коллекцию. Примечание. SaveData и LoadData не работают в браузере. Поэтому необходимо использовать студию, установленную в Windows, или один из проигрывателей для мобильных устройств.
__label__pos
0.618717
Lesson 14 Expressions with Exponents Let's use the meaning of exponents to decide if equations are true. 14.1: Which One Doesn’t Belong: Twos Which one doesn’t belong? \(2 \boldcdot 2 \boldcdot 2 \boldcdot 2\) \(16\) \(2^4\) \(4 \boldcdot 2\) 14.2: Is the Equation True? Decide whether each equation is true or false, and explain how you know. 1. \(2^4=2 \boldcdot 4\) 2. \(3+3+3+3+3=3^5\) 3. \(5^3=5 \boldcdot 5 \boldcdot 5\) 4. \(2^3=3^2\) 5. \(16^1=8^2\) 6. \(\frac12 \boldcdot  \frac12 \boldcdot  \frac12 \boldcdot  \frac12 = 4 \boldcdot \frac12\) 7. \(\left( \frac12 \right)^4=\frac{1}{8}\) 8. \(8^2 = 4^3\) 14.3: What’s Your Reason? In each list, find expressions that are equivalent to each other and explain to your partner why they are equivalent. Your partner listens to your explanation. If you disagree, explain your reasoning until you agree. Switch roles for each list. (There may be more than two equivalent expressions in each list.) 1. \(5 \boldcdot 5\) 2. \(2^5\) 3. \(5^2\) 4. \(2 \boldcdot 5\) 1. \(4^3\) 2. \(3^4\) 3. \(4 \boldcdot 4 \boldcdot 4\) 4. \(4+4+4\) 1. \(6+6+6\) 2. \(6^3\) 3. \(3^6\) 4. \(3 \boldcdot 6\) 1. \(11^5\) 2. \(11 \boldcdot 11 \boldcdot 11 \boldcdot 11 \boldcdot 11\) 3. \(11 \boldcdot 5\) 4. \(5^{11}\) 1. \(\frac15 \boldcdot \frac15 \boldcdot \frac15\) 2. \(\left( \frac15 \right)^3\) 3. \(\frac{1}{15}\) 4. \(\frac{1}{125}\) 1. \(\left( \frac53 \right)^2\) 2. \(\left( \frac35 \right)^2\) 3. \(\frac{10}{6}\) 4. \(\frac{25}{9}\) What is the last digit of \(3^{1,000}\)? Show or explain your reasoning. Summary When working with exponents, the bases don’t have to always be whole numbers. They can also be other kinds of numbers, like fractions, decimals, and even variables. For example, we can use exponents in each of the following ways:  \(\displaystyle \left(\frac{2}{3}\right)^4 = \frac{2}{3} \boldcdot \frac{2}{3} \boldcdot \frac{2}{3} \boldcdot \frac{2}{3}\) \(\displaystyle (1.7)^3 = (1.7) \boldcdot (1.7) \boldcdot (1.7)\) \(\displaystyle x^5 = x \boldcdot x \boldcdot x \boldcdot x \boldcdot x\) Glossary Entries • cubed We use the word cubed to mean “to the third power.” This is because a cube with side length \(s\) has a volume of \(s \boldcdot s \boldcdot s\), or \(s^3\). • exponent In expressions like \(5^3\) and \(8^2\), the 3 and the 2 are called exponents. They tell you how many factors to multiply. For example, \(5^3\) = \(5 \boldcdot 5 \boldcdot 5\), and \(8^2 = 8 \boldcdot 8\). • squared We use the word squared to mean “to the second power.” This is because a square with side length \(s\) has an area of \(s \boldcdot s\), or \(s^2\).
__label__pos
1
Higher Logic notes on screwing with tech… 21Aug/102 Linux USB drive automatic mount unmount management script Hi All, Just a little something I wrote to make my travelling life easier. I wrote this 3am London time while jetlagged... don't blame me :) Preface, I run a barebones Linux GUI (blackbox). I got sick of constantly reading dmesg/blkid and manually mounting the USB drives. Here are two python scripts to make my life simple. usbon.py - just mounts whatever USB you have attached under /mnt/usb_label_name. usboff.py - just safely umounts the USB and cleans up the directory for you. Use as you see fit, just give me some credit :) I'll put the raw files on this page once I find out how to get wordpress to do it :( usbon.py #!/usr/bin/python #Author: Mark Liu #Version: 0.1 #Date: 19 August 2010 # good old imports import commands, re, os # global variables total_devices = [] mount_base = '/mnt/' # class definition to make lives a bit easier class MountableDevices: """Simple Object to represent system mountable disk""" def __init__(self, dev_name, dev_UUID, dev_label, dev_type): self.dev_name = dev_name self.dev_UUID = dev_UUID self.dev_label = dev_label self.dev_type = dev_type self.dev_mount = False def already_mounted(self): self.dev_mount = True def details(self): print 'Device Name: %s' % (self.dev_name) print 'Device UUID: %s' % (self.dev_UUID) print 'Device Label: %s' % (self.dev_label) print 'Device Type: %s' % (self.dev_type) print 'Device Mounted?: %s' % (self.dev_mount) print '' # Functions to help with process blkid outputs def process_blkid_output(device_blk_output): global total_devices dev_LABEL, dev_UUID, dev_TYPE = '_not_set', 'N/A', 'N/A' dev_NAME = device_blk_output[0][:-1] for item in device_blk_output: if re.match('UUID', item): dev_UUID = re.search('\".*\"', item).group(0).strip('\"'); continue elif re.match('TYPE', item): dev_TYPE = re.search('\".*\"', item).group(0).strip('\"'); continue elif re.match('LABEL', item): dev_LABEL = re.search('\".*\"', item).group(0).strip('\"'); continue total_devices.append(MountableDevices(dev_NAME, dev_UUID, dev_LABEL, dev_TYPE)) # Functions to help with process mount outputs def process_mount_output(device_blk_output): global total_devices dev_NAME = device_blk_output[0] if dev_NAME == 'none' or dev_NAME == 'proc' or dev_NAME == 'binfmt_misc' or dev_NAME == 'gvfs-fuse-daemon': pass else: for device in total_devices: if dev_NAME == device.dev_name: device.already_mounted() # Do some mounting Prep work os_commands = ['blkid', 'mount'] process_system_output = {'blkid': process_blkid_output, 'mount': process_mount_output} # Processing System information like blkid and mounts` for operation in os_commands: raw_outputs = commands.getstatusoutput('sudo ' + operation) if raw_outputs[0] == 0: #split output via new line outputs = raw_outputs[1].split('\n') for output in outputs: clean_blk_output = output.strip().split() process_system_output[operation](clean_blk_output) else: print 'sudo %s... failed' % (operation) sys.exit(1) # Main section compare and mount any desired devices for device in total_devices: if device.dev_mount == True: print 'Ignoring device: %s (already mounted)' % (device.dev_name) elif device.dev_type == 'swap': print 'Ignoring device: %s (swap)' % (device.dev_name) else: mount_dir = mount_base + device.dev_label mkdir = 'sudo mkdir %s' % (mount_dir) mount = 'sudo mount -U %s %s' % (device.dev_UUID, mount_dir) print 'Mounting device: %s (%s)' % (device.dev_name, mount_dir) if not os.path.exists(mount_dir): result = commands.getstatusoutput(mkdir) if result[0] != 0: print 'dir creation failed, aborting USB mount...' sys.exit(1) else: result = commands.getstatusoutput(mount) else: print 'unclean mount directory, please clean up...' usboff.py #!/usr/bin/python # Author: Mark Liu # Version: 1.0 # Date: 19 Aug 2010 # Imports import dircache, commands # Definitions and prepwork mount_base = '/mnt/' mounts = dircache.listdir(mount_base) # Umount, then safely delete directories for mount in mounts: mount_dir = mount_base + mount result = commands.getstatusoutput('sudo umount %s' % (mount_dir)) result = commands.getstatusoutput('sudo umount %s' % (mount_dir)) if result[1] == 'umount: %s: not mounted' % (mount_dir): commands.getstatusoutput('sudo rm -r %s' % (mount_dir)) Filed under: Development 2 Comments     css.php
__label__pos
0.946132
{align} is an environment provided by math packages that permits multiple related equations to be aligned at a common reference point, usually a sign of relation. For general questions about aligning document elements, use {horizontal-alignment} or {vertical-alignment} instead. learn more… | top users | synonyms 67 votes 5answers 65k views eqnarray vs align I want to include a list of related equations, say, for a proof, in my LaTeX document. As far as I know, I have two good options, eqnarray and align. What is the difference between them, and how do I ... 34 votes 3answers 12k views How to get only one vertically centered equation number in align environment with two equations sorry if this has been answered before, I couldn't find anything through search. I'm sure its a common problem though. What I have are two equations with align and I want one single equation number ... 33 votes 4answers 2k views What does a double ampersand (&&) mean in LaTeX? I've seen several answers that use the double ampersand, but I can't figure out exactly what it does. I tried this out: \begin{align*} \frac{3x + y}{7} &= 9 & \text{given} \\ 3x + y ... 31 votes 3answers 17k views align* but show one equation number at the end I am using align*, but I still need an equation number. I know one solution is to use align and add \nonumber to all lines but the last. Is there a 'lazy' way to do it? I searched a little and found ... 27 votes 3answers 5k views Centering \vdots in a system of many equations I have a system of equations with an arbitrary number of equations (k). I'd like to use \vdots to compactly describe the system, like so: \begin{align*} R(-1) &= \sum_{i=1}^m A(i)R(i-1) \\ ... 20 votes 4answers 947 views How can I break an align environment for a paragraph? I would like to have two displayed equations, broken by a short paragraph, but with aligned equal signs (as if using the align environment). Is there some way to "break" the align environment ... 19 votes 1answer 4k views Flexible equation, align, multline environment I'm looking for a command (say \foo{}) or pair of commands (say \foos, \fooe) that behave like: equation environment if there is no \\ nor & multline if there is a single \\ align if there are ... 18 votes 2answers 5k views Highlight an equation within an align environment I would like to define a command that puts a red box around an equation with yellow highlighting. I have the basics working pretty well. What I am unable to figure out is: How to keep the alignment ... 18 votes 1answer 3k views What is the difference between \notag and \nonumber in align environment? I use \notag or \nonumber in align environment but there seems no any difference when display. What is the difference between these two commands? 17 votes 3answers 25k views Show equation number only once in align environment I want the equation number to be shown only at the last line, or better, somewhere in the middle of all. So instead of (1), (2), ... only (1). I use \begin{align} ... \end{align} 17 votes 6answers 4k views Multiline equation with LHS alone on first line? I would like my multiline equations to look like this: Left-hand-side of my equation = right-hand-side number 1 = right-hand-side number 2 = etc. I know there is a simple way to do ... 17 votes 3answers 13k views Aligned equations in LaTeX I have a long equation in LaTeX, which I need to break up into more lines. I've done this, although its not quite what I was looking for. Here is a MWE showing my problem: ... 17 votes 2answers 6k views Alignment of equals sign in multiple align environments I have multiple align environments in my document, separated by a small paragraph of text: \begin{align*} foo &= something very very long compared to the other align \end{align*} explanation ... 17 votes 1answer 9k views How can I add left aligned text to an equation? I have a document I am trying to copy to learn TeX. Here is what I have encountered: How can I have the "or" in the equation. This is what I have right now: \[ f = ma; \] But $a$ is the change in ... 16 votes 2answers 424 views Stacked symbol doesn't align properly. Why? A modified equals sign used represent use of L'Hopital's Rule isn't aligning well with other equals signs. How would I fix that? I'd prefer to do so without manually fiddling with spaces, if possible. ... 16 votes 1answer 1k views Automatic line break in alignat Consider the following example from http://tex.stackexchange.com/a/12782/4011 \documentclass{article} \usepackage{amsmath} \newcounter{eqn} \renewcommand*{\theeqn}{\alph{eqn})} ... 16 votes 2answers 783 views How to align nested cases? Please consider the code bellow: \begin{align*} function = \begin{cases} case1 &\mbox{if } n = 0 \\ \begin{cases} case2 &\mbox{if } n = 1 \\ ... 15 votes 3answers 20k views Use flalign or alignat or align or similar environment to align to the left The following is a small example to use flalign environment to generate equation. \documentclass{article} \usepackage{amsmath} \usepackage{txfonts} \begin{document} The formula is: \begin{flalign*} ... 14 votes 7answers 1k views Aligning polynomial terms In LaTeX align, I'm struggling to align polynomial terms and assume there's an easy way to do it. But I cannot find the simple/elegant solution. What I would like is something like this: x1 + x2 ... 14 votes 3answers 1k views How to make formulae take equal vertical space in the align environment? Consider the following code: \begin{align} f_1(x) &= \frac{15x}{3} \\ f_2(x) &= 3x + 5 \\ f_3(x) &= 4x + 13 \end{align} This produces three lines where the first line takes up more ... 14 votes 1answer 17k views Aligning equations with text with alignat I'm trying to add this expression to my work: I understand that the best way to achieve this is using the alignat environment within the amsmath package, so I tried the following: ... 14 votes 3answers 6k views Aligning across 'aligned' equation blocks I'd like to format two groups of equations such that all their equal signs line up and such that I can put a big brace to the right of each block to annotate that block. The last part is easily ... 14 votes 1answer 995 views How can I typeset LaTeX math proofs with long lines? I usually typeset math proofs in LaTeX by using the align environment. For instance, \documentclass{article} \usepackage{amsmath,mathtools} \begin{document} \begin{align} & x^2 \\ &= x*x \\ ... 14 votes 1answer 238 views align* environment left-aligned with LuaTeX and RTL math direction When using LuaLaTeX, with the math direction set right-to-left, the contents of an align* environment is left-aligned instead of centered. Why does this happens? How can I fix it? ... 13 votes 4answers 1k views Make align* number the last equation I am using the align* environment to write equations expanding several lines. I would like to define a command sequence in the preamble, such that the last equation of this block will always be ... 13 votes 5answers 5k views Vertical alignment of align* in enumerate Related (but not the same): Align number from enumerate with equation Displaying an equation in a list Earlier today I asked a question about aligning equations in an enumerate environment ... 13 votes 4answers 1k views Best Pattern For Adding Commentary in align Environment? [duplicate] I've been using the align environment to line up equations in proofs/explanations/etc and I like to place parenthetical commentary for each step, similar to the code below: \documentclass{article} ... 13 votes 2answers 1k views Align Equations Over Multiple Tabular Rows I'm trying to set up a table with some equations in it, however I would like the equations on multiple rows to be aligned properly. So far I have \begin{tabular}{cc} \hline \multicolumn{1}{l}{Header ... 13 votes 1answer 6k views Multiple Alignment in equations The following equations need to be aligned in two spots. If I use the align* environment then the second column of alignment is pushed to the right edge of the page. I googled this and saw that ... 12 votes 4answers 13k views How to correctly format (and align) a LaTeX proof? I'm new to LaTeX and I'm trying to figure out how to correctly format a proof. Can someone show me a basic template for how to do this? The part I am having the most trouble with is creating new ... 12 votes 4answers 443 views How do I get this strange alignment? I would like to get a nonstandard alignment in the following code: \begin{align} \text{First left hand side} & = \text{First right hand side} \\ \text{Second left hand side} & = ... 12 votes 4answers 3k views Align left-aligned formula at two points I would like to get this WITHOUT using tables, because in my real equations there are fractions included that are scaled down in tables a+b+c=1 y =2 My code looks as follows: \begin{align*} ... 12 votes 2answers 3k views How do I put a side brace around several lines in the align* environment? I would like to put a side brace around several lines in the align* environment, as shown in the comments in the code below: \begin{align*} left side & = right side \\ left side & = ... 12 votes 4answers 6k views Problem with beamer's \pause in alignments I have the following code, (edit:) now without aligned. \documentclass{beamer} \mode<presentation> { \setbeamercovered{transparent} } \begin{document} \begin{frame} \[ \begin{cases} ... 12 votes 2answers 168 views Align*, & and \futurelet can somebody explain futurelet within align-environments? Example: The command \A should give an "A" if the next char is a {, a "B" if it is & and "C" in any other case. ... 12 votes 1answer 358 views Correct usage of \ifmmode Seems that there is some subtlety in using \ifmmode that I am not aware of. For some reason, using: \newcommand{\hlcodeA}[1]{\ifmmode\else\small\fi\texttt{\hilight{#1}}}% is not quite identical ... 12 votes 1answer 287 views Align to center I want to align some equations to the equal signs, so I wrote this: \begin{align} -3z &=-9\\ z &= 3\\ -3y-3*3 &= 3\\ y &=-4\\ ... 12 votes 1answer 3k views AMS align / Align multiple “=”, too much space I asked this question at stackoverflow and have been kindly redirected here. I'd like to align some equations in Latex using the AMS packages. Each equation has two equal signs that need to be ... 12 votes 2answers 3k views Two column align environment with one line spanning both columns Is there a good/correct way of making an align environment with one line spanning multiple columns? At the moment I'm using a hack like the following, but I feel that it's probably not the best way. ... 11 votes 6answers 601 views Suppressing = on a line in the align environment How do I produce the following in align environment? \begin{eqnarray*}& & abcd \\ &=& defg\\ &=& hijk \end{eqnarray*} I try \begin{align*}& abcd \\ &= defg\\ ... 11 votes 5answers 42k views How to align a set of multiline equations I am trying to align a set of long equations, that are themselves align environments as most of them are spreading on multiple lines. Currently I just have a sequence of align environments, with ... 11 votes 4answers 4k views Aligning plain `align` and `cases`? The cases environment works very well for enumerating cases within a large left bracket. I'd like to be able to combine it with the align environment so that equals-signs and conditions also line up: ... 11 votes 3answers 4k views Left-justify with align on “=” in align environment I searched the tex.stackexchange archives for an answer to this question but couldn't find one. I assume it's a common question, however. I often want to align text similar to the poly environment in ... 11 votes 2answers 2k views inserting sentences between subequations My apologies for asking so many questions here. I want to introduce a sentence in between 2 subequations which is not in math mode. Here is the code that I am using: ... 11 votes 2answers 761 views Problems with alignment of sequences I want to align two sequences: a_1, b_1, c_1, d_1, e_1 etc. a_2, b_2, c_2, d_2, e_2 etc. here's what I wrote \begin{align} \notag &a_1,\ &b_1,\ &c_1,\ &d_1,\ &e_1\ ... 11 votes 2answers 123 views Need to use \pageref to a page that has *-equations I am sure that this has been asked before, but I don't seem to be able to find the answer. I need to make a reference to a page. That is, I would like to use \pageref{}. I specifically need to make a ... 11 votes 1answer 7k views Change font size of an align environment In a document, I'd like to change the font size of a single align environment (not globally throughout the document). What is the proper way to do this? I've been using Preceding paragraph. {\tiny ... 11 votes 1answer 495 views Adding multiple paragraphs between aligned equations Some people have asked about how to add multiple paragraphs (when \intertext and \shortintertext no longer work), a fix was proposed by Peter Grill here: He wrote: My first thought was to hack ... 11 votes 1answer 115 views Aligning two fractions in the split environment I have two equations: \begin{equation} \begin{split} d_1 & =\frac{aaaaaaaaaa}{b}\\ d_2 & =\frac{aaaaaa}{b} \end{split} \end{equation} I want the fraction lines to ... 10 votes 4answers 218 views How to vertically align each comma in the following 2 identical sequences? The following output seems to be difficult to look up an item in the upper sequence with its corresponding item in the lower sequence as the commas are not vertically aligned. ...
__label__pos
0.995511
Java source - 4 kB Introduction As you possibly remember from school, a Turing Machine is a mathematical model of computation. It defines an abstract machine working with characters on an endless tape. In theory, a system that simulates a turing machine is able to support all tasks accomplishable by computers. Each cell on the tape has to be writable only once. For a second write access, you can copy the used tape to a new segment. As every calculation can be done in binary, the alphabet of writable characters can be limited to {0, 1}, though a larger alphabet may be good to save tape. In this article we'll use {0, 1, 2, 3} to encode everything in base-4. A cheap and simple way to simulate the endless, writable tape is a clew of yarn. You can write characters by knitting different stitches. If you need to overwrite a used position, just start a new row; that is like rewinding and copying the tape of the turing machine. This article explains how to encode any content as stitches, render a knitting chart and decode the finished yarn-tape again. It uses the Apache Batik SVG Toolkit to draw the pattern. You might want to feed the patterns into a knitting machine, turning it into a real hardware Turing Machine. You can as well knit them by hand to transmit secret messages just by letting your messenger wear a warm hat. The Application The Java application accepts a text, converts the characters to groups of base-4 numbers and translates those into a row of stitches: • 0 = knit • 1 = purl • 2 = yarn over, knit • 3 = yarn over, purl The screenshot shows the knitting chart generated from the text "Hi CP!". Only the first row contains information. The second row is there to reduce the excess stitches created by the digits "2" and "3". All following rows are just repetitions to make the code look like decoration. Such a pair of rows would look strange in a piece of cloth. But usually, knitted stuff has decorative patterns and everything looks like a pattern, if you just repeat if often enough. So, feel free to repeat the code row until the result looks pretty unsuspicious. Encoding and Decoding This little demonstration uses only latin text. As a character is a value between 0 and 255, it corresponds to four digits between 0 and 3. Those digits are concatenated to one long string and then sent to the graphics frame. private void encode(String clearText){ ByteBuffer bytes = Charset.forName("ISO-8859-15").encode(clearText); StringBuilder resultBuilder = new StringBuilder(clearText.length() * 4); // convert each character while(bytes.hasRemaining()){ int currentValue = bytes.get(); String currentWord = Integer.toString(currentValue, 4); // pad the number to a length of 4 while(currentWord.length() < 4){ currentWord = "0" + currentWord; } resultBuilder.append(currentWord); } ChartFrame frame = new ChartFrame(); frame.drawChart(clearText, resultBuilder.toString()); } When reading a piece of cloth manually, you may note down digits for the kinds of stitches you recognize... ... then call the decoder with the row of stitches you found. They'll be decoded to the original text: The decode method converts the chain of numbers back to the original message. private String decode(String encodedText){ int n = 0; StringBuilder resultBuilder = new StringBuilder(encodedText); // translate blockwise to characters while(n < resultBuilder.length()){ String currentWord = resultBuilder.substring(n, n+4); int currentValue = Integer.parseInt(currentWord, 4); String currentClearChar; // decode or ignore if(currentValue < 256){ ByteBuffer buffer = ByteBuffer.wrap(new byte[]{(byte)currentValue}); currentClearChar = Charset.forName("ISO-8859-15").decode(buffer).toString(); }else{ currentClearChar = "?"; } // compress 4 digits to 1 character resultBuilder.replace(n, n+4, currentClearChar); n++; } return resultBuilder.toString(); } Rendering the Chart For each digit, the corresponding stitches have to be drawn. I used the knit chart symbols by the Craft Yarn Council, which are easy to render with geometric shapes. The chart consists of three components: Column numbers, odd rows encoding the payload, even rows fixing the count of stitches. public void drawChart(String title, String base4Digits){ titleText = title; // prepare SVG document DOMImplementation impl = SVGDOMImplementation.getDOMImplementation(); String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI; SVGDocument doc = (SVGDocument) impl.createDocument(svgNS, "svg", null); SVGGraphics2D g = new SVGGraphics2D(doc); g.setFont(new Font("sans serif", Font.PLAIN, 10)); // calculate chart width countColumns = getCountCols(base4Digits); countRows = (int)(200 / boxSize); svgCanvas.setSize((2+countColumns)*boxSize, countRows*boxSize); // fill background g.setPaint(Color.darkGray); g.fillRect(0, 0, svgCanvas.getWidth(), svgCanvas.getHeight()); // draw odd coding rows, even fixing rows for(int y = 0; y < (countRows-2); y+=2){ // code symbols may add stiches drawOddRow(y, base4Digits, g); // fix excess stitches by knitting two together drawEvenRow(y+1, base4Digits, g); } // draw column numbers for(int x=0; x < countColumns; x++){ drawColNumber(x+1, countRows-1, g); } // prepare and show frame titleText = titleText + " - " + "start with " + (base4Digits.length()+2) + " stitches"; g.getRoot(doc.getDocumentElement()); svgCanvas.setSVGDocument(doc); svgCanvas.getParent().setPreferredSize(svgCanvas.getSize()); pack(); setVisible(true); } Drawing a row is simple: Place one knit symbol at each end, then fill the space with symbols: private void drawOddRow(int y, String base4Digits, SVGGraphics2D g){ // label and left edge drawRowNumber(0, y, g); drawKnit(1, y, g); // append one or two symbols per digit int x = 2; for(int n=0; n < base4Digits.length(); n++){ char currentChar = base4Digits.charAt(n); /* draw box 0 = knit 1 = purl 2 = yarn over, knit 3 = yarn over, purl */ switch(currentChar){ case '0': drawKnit(x, y, g); break; case '1': drawPurl(x, y, g); break; case '2': drawYarnOver(x, y, g); drawKnit(++x, y, g); break; case '3': drawYarnOver(x, y, g); drawPurl(++x, y, g); break; } x++; } // right edge drawKnit(x, y, g); } The chart symbols are primitive shapes. These are a few examples: private void drawBox(int col, int row, SVGGraphics2D g){ int x = col*boxSize; int y = row*boxSize; Rectangle2D.Double box = new Rectangle2D.Double(x, y, boxSize, boxSize); g.fill(box); g.setColor(Color.black); g.draw(box); } private void drawColNumber(int col, int row, SVGGraphics2D g){ g.setColor(Color.black); g.setPaint(Color.cyan); drawBox(col, row, g); g.drawString(String.valueOf(col), (col*boxSize)+boxPadding, (row*boxSize)+boxSize-boxPadding); } private void drawYarnOver(int col, int row, SVGGraphics2D g){ g.setColor(Color.black); g.setPaint(Color.white); int x = col*boxSize; int y = row*boxSize; int height = boxSize-(boxPadding*2); Ellipse2D circle = new Ellipse2D.Double( x+boxPadding, y+boxPadding, height, height); drawBox(col, row, g); g.draw(circle); } Points of Interest So far, all we did was encoding and decoding. We are able to fill the tape of our fluffy Turing Machine with characters. That is good enough to hide text in plain sight wearing a woolen scarf, which may be your only chance to smuggle secrets from Alaska to Siberia. The next step could be to program a knitting machine, to make it process a calculation line by line. I hope you enjoyed this article and take a closer look at other people's textiles.
__label__pos
0.967627
Skip to content EMR Native Ranger Integration with PrivaceraCloud AWS EMR provides native Apache Ranger integration with the open source Apache Ranger plug-ins for Apache Spark and Hive. By connecting EMR’s plug-in with PrivaceraCloud’s Ranger-based data access governance has following advantages: • Enterprises can synch their existing policies with EMR. • Organizations can extend Apache Ranger’s open source capabilities to take advantage of Privacera’s centralized enterprise-ready solution. Prerequisite# • Enable "privacera_hive" and "privacera_emrfs_s3" services in your PrivaceraCloud tenant. For more information see - How to enable Service Configs topic. Configuration# Certificate Setup in Secrets Manager# AWS EMR Native Ranger mandates usage of mutual TLS between Ranger plug-ins and the Privacera Ranger Admin. To provide these TLS certificates, they must be in the AWS Secrets Manager and provided in an EMR Security Configuration. Perform the following steps to proceed with configuration: Create two secrets in AWS Secret Manager: 1. Ranger Admin Public Cert 1. Login to AWS Console and navigate to Secrets Manager and then click Store a new secret option. 2. Select secret type as Other type of secrets and then go to the Plaintext tab. 3. Go to your PrivaceraCloud account and follow navigation Settings > ApiKey > AWS EMR Native Ranger Plugin > Ranger Admin Public Cert > Download Certificate. 4. Add the contents of this Certificate in the Plaintext tab. 5. Select the encryption key as per your requirement. 6. Click Next. Enter the Secret name. For example: ranger-admin-pub-cert 7. Click Next. The Configure automatic rotation page is displayed. No action required. Click Next. 8. Review Secret details and click Store. The Secret is stored successfully. 2. Ranger Client KeyPair 1. Login to AWS Console and navigate to Secrets Manager and then click Store a new secret option. 2. Select secret type as Other type of secrets and then go to Plaintext tab. 3. Go to your PrivaceraCloud account and follow navigation Settings > ApiKey > AWS EMR Native Ranger Plugin > Ranger Client KeyPair > Download Certificate. 4. Add the contents of this certificate in the Plaintext tab. 5. Select the encryption key as per your requirement. 6. Click Next. Enter the Secret name. For example: ranger-plugin-key-cert 7. Click Next. The Configure automatic rotation page is displayed. No action required. Click Next. 8. Review Secret details and click Store. The Secret is stored successfully. IAM Roles Setup# Following three IAM roles need to be created before launching the Cluster. • A custom Amazon EC2 instance profile for Amazon EMR, this will be attached to all the cluster nodes - [EmrNativePrivaceraInstanceRole] • An IAM role for Apache Ranger Engines, this will be used for data access from S3 - [EmrNativePrivaceraDataAccessRole] • An IAM role for other AWS services, this will be used to attach any other required permissions for the user on EMR Cluster - [EmrNativePrivaceraUserAccessRole] These can be created easily with required minimal permission using the following CloudFormation template. You can modify the template based on your requirements (if required). Sample CloudFormation Template { "AWSTemplateFormatVersion": "2010-09-09", "Description": "Create roles and policies for use by Emr-Native Ranger with Privacera", "Parameters": { "EmrNativePrivaceraInstanceRole": { "Description": "IAM Role which will be attached to all Instances in the Cluster. Should have minimal permissions. e.g. emr_native_privacera_restricted_instance_role", "Type": "String", "Default": "emr_native_privacera_restricted_instance_role" }, "EmrNativePrivaceraDataAccessRole": { "Description": "IAM Role which will be used by EMR Applications for accessing actual S3 Data. e.g. emr_native_privacera_data_access_role", "Type": "String", "Default": "emr_native_privacera_data_access_role" }, "EmrNativePrivaceraUserAccessRole": { "Description": "IAM Role which will allows users to interact with AWS Services. Shouldn't be used to access s3 Data. e.g. emr_native_privacera_user_access_role", "Type": "String", "Default": "emr_native_privacera_user_access_role" }, "RangerPluginKeyPairSecretArn": { "Description": "Full ARN of secret [stored in AWS Secrets Manager] for ranger plugin key-pair. e.g. arn:aws:secretsmanager:us-east-1:999999999999:secret:ranger-plugin-cert-k4xsLM", "Type": "String", "Default": "" }, "RangerAdminPublicSecretArn": { "Description": "Full ARN of secret [stored in AWS Secrets Manager] for ranger admin public cert. e.g arn:aws:secretsmanager:us-east-1:999999999999:secret:ranger-admin-cert-3W5Zdt", "Type": "String", "Default": "" }, "Region": { "Description": "AWS Region where cluster will be created. e.g. us-east-1", "Type": "String", "Default": "us-east-1" }, "CloudwatchLogGroupName": { "Description": "CloudWatch Log group name which will be used to store RangerAudits. This should be an existing one e.g. emr_native_privacera_audits", "Type": "String", "Default": "" }, "AwsAcctId": { "Description": "Account ID of your Amazon Account. e.g. 999999999999", "Type": "String", "Default": "" }, "LogsBucketS3": { "Description": "S3 path to store emr logs (without the protocol). e.g. privacera-logs/emr-native-logs", "Type": "String", "Default": "" } }, "Resources": { "EmrPrivaceraInstanceRole": { "Type": "AWS::IAM::Role", "Properties": { "RoleName": { "Fn::Sub": "${EmrNativePrivaceraInstanceRole}" }, "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "ec2.amazonaws.com" ] }, "Action": [ "sts:AssumeRole" ] } ] }, "Path": "/" } }, "EmrPrivaceraInstancePolicy": { "Type": "AWS::IAM::Policy", "Properties": { "PolicyName": { "Fn::Join": [ "", [ "emr_native_privacera_instance_policy" ] ] }, "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "EmrServiceLimited", "Effect": "Allow", "Resource": "*", "Action": [ "ec2:Describe*", "elasticmapreduce:Describe*", "elasticmapreduce:ListBootstrapActions", "elasticmapreduce:ListClusters", "elasticmapreduce:ListInstanceGroups", "elasticmapreduce:ListInstances", "elasticmapreduce:ListSteps", "glue:CreateDatabase", "glue:UpdateDatabase", "glue:DeleteDatabase", "glue:GetDatabase", "glue:GetDatabases", "glue:CreateTable", "glue:UpdateTable", "glue:DeleteTable", "glue:GetTable", "glue:GetTables", "glue:GetTableVersions", "glue:CreatePartition", "glue:BatchCreatePartition", "glue:UpdatePartition", "glue:DeletePartition", "glue:BatchDeletePartition", "glue:GetPartition", "glue:GetPartitions", "glue:BatchGetPartition", "glue:CreateUserDefinedFunction", "glue:UpdateUserDefinedFunction", "glue:DeleteUserDefinedFunction", "glue:GetUserDefinedFunction", "glue:GetUserDefinedFunctions" ] }, { "Sid": "EmrS3Limited", "Effect": "Allow", "Action": "s3:*", "Resource": [ "arn:aws:s3:::*.elasticmapreduce/*", "arn:aws:s3:::elasticmapreduce/*", "arn:aws:s3:::elasticmapreduce", { "Fn::Sub": "arn:aws:s3:::${LogsBucketS3}" }, { "Fn::Sub": "arn:aws:s3:::${LogsBucketS3}/*" } ] }, { "Sid": "AllowAssumeOfRolesAndTagging", "Effect": "Allow", "Action": [ "sts:TagSession", "sts:AssumeRole" ], "Resource": [ { "Fn::Sub": "arn:aws:iam::${AwsAcctId}:role/${EmrNativePrivaceraDataAccessRole}" }, { "Fn::Sub": "arn:aws:iam::${AwsAcctId}:role/${EmrNativePrivaceraUserAccessRole}" } ] }, { "Sid": "AllowSecretsRetrieval", "Effect": "Allow", "Action": "secretsmanager:GetSecretValue", "Resource": [ { "Fn::Sub": "${RangerPluginKeyPairSecretArn}" }, { "Fn::Sub": "${RangerAdminPublicSecretArn}" } ] } ] }, "Roles": [ { "Ref": "EmrPrivaceraInstanceRole" } ] } }, "EmrPrivaceraUserAccessRole": { "Type": "AWS::IAM::Role", "Properties": { "RoleName": { "Fn::Sub": "${EmrNativePrivaceraUserAccessRole}" }, "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "ec2.amazonaws.com" ] }, "Action": [ "sts:AssumeRole" ] }, { "Effect": "Allow", "Principal": { "AWS": { "Fn::GetAtt": [ "EmrPrivaceraInstanceRole", "Arn" ] } }, "Action": "sts:AssumeRole" } ] }, "Path": "/" } }, "EmrPrivaceraDataAccessRole": { "Type": "AWS::IAM::Role", "Properties": { "RoleName": { "Fn::Sub": "${EmrNativePrivaceraDataAccessRole}" }, "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "ec2.amazonaws.com" ] }, "Action": [ "sts:AssumeRole" ] }, { "Effect": "Allow", "Principal": { "AWS": { "Fn::GetAtt": [ "EmrPrivaceraInstanceRole", "Arn" ] } }, "Action": "sts:AssumeRole" } ] }, "Path": "/" } }, "DataAccessPolicy": { "Type": "AWS::IAM::Policy", "Properties": { "PolicyName": { "Fn::Join": [ "", [ "emr_native_privacera_data_access_policy" ] ] }, "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "CloudwatchLogsPermissions", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Effect": "Allow", "Resource": [ { "Fn::Sub": "arn:aws:logs:${Region}:${AwsAcctId}:log-group:${CloudwatchLogGroupName}:*" } ] }, { "Sid": "BucketPermissionsInS3Buckets", "Action": [ "s3:CreateBucket", "s3:DeleteBucket", "s3:ListAllMyBuckets", "s3:ListBucket" ], "Effect": "Allow", "Resource": [ "arn:aws:s3:::examplebucket" ] }, { "Sid": "ObjectPermissionsInS3Objects", "Action": [ "s3:GetObject", "s3:DeleteObject", "s3:PutObject" ], "Effect": "Allow", "Resource": [ "arn:aws:s3:::examplebucket/*" ] } ] }, "Roles": [ { "Ref": "EmrPrivaceraDataAccessRole" } ] } }, "EmrPrivaceraInstanceProfile": { "Type": "AWS::IAM::InstanceProfile", "Properties": { "InstanceProfileName": { "Ref": "EmrNativePrivaceraInstanceRole" }, "Roles": [ { "Ref": "EmrPrivaceraInstanceRole" } ] } }, "EmrNativePrivaceraDataAccessProfile": { "Type": "AWS::IAM::InstanceProfile", "Properties": { "InstanceProfileName": { "Ref": "EmrNativePrivaceraDataAccessRole" }, "Roles": [ { "Ref": "EmrPrivaceraDataAccessRole" } ] } }, "EmrNativePrivaceraUserAccessProfile": { "Type": "AWS::IAM::InstanceProfile", "Properties": { "InstanceProfileName": { "Ref": "EmrNativePrivaceraUserAccessRole" }, "Roles": [ { "Ref": "EmrPrivaceraUserAccessRole" } ] } } }, "Outputs": { "EmrNativePrivaceraInstanceRole": { "Value": { "Ref": "EmrPrivaceraInstanceRole" } }, "EmrNativePrivaceraDataAccessRole": { "Value": { "Ref": "EmrPrivaceraDataAccessRole" } }, "EmrNativePrivaceraUserAccessRole": { "Value": { "Ref": "EmrPrivaceraUserAccessRole" } } } } Note To know about how to create a stack using CloudFormation template, refer Create CloudFormation stack topic. Note After the above stack is created successfully, you will have three IAM roles. Use EmrNativePrivaceraDataAccessRole IAM Role, to give access for S3 data to the Apache Ranger services. For detailed information, see IAM roles for native integration with Apache Ranger Create Security Configurations# • A new SecurityConfiguration needs to be created with the Kerberos Server and Ranger Integration details which will be attached to the EMR Cluster. • This can be created easily with required minimal permission using the following CloudFormation template. Note This template assumes that you have Cluster dedicated KDC with Cross Realm Trust Enabled. • You can modify the CloudFormation template based on your requirements (if required). Note Common variables from the previous setup steps should be kept the same. Sample CloudFormation Template { "AWSTemplateFormatVersion": "2010-09-09", "Description": "Create Security Configuration for use by Privacera-Protected EMR Clusters", "Parameters": { "EmrNativePrivaceraSecConfName": { "Description": "Name to be given for the Security Configuration. e.g. emr_native_privacera_sec_conf", "Type": "String", "Default": "emr_native_privacera_sec_conf" }, "EmrNativePrivaceraDataAccessRole": { "Description": "IAM Role which will be used by EMR Applications for accessing actual S3 Data. e.g. emr_native_privacera_data_access_role", "Type": "String", "Default": "emr_native_privacera_data_access_role" }, "EmrNativePrivaceraUserAccessRole": { "Description": "IAM Role which will allows users to interact with AWS Services. Shouldn't be used to access s3 Data. e.g. emr_native_privacera_user_access_role", "Type": "String", "Default": "emr_native_privacera_user_access_role" }, "RangerPluginKeyPairSecretArn": { "Description": "Full ARN of secret [stored in AWS Secrets Manager] for ranger plugin key-pair. e.g. arn:aws:secretsmanager:us-east-1:999999999999:secret:ranger-plugin-cert-k4xsLM", "Type": "String", "Default": "" }, "RangerAdminPublicSecretArn": { "Description": "Full ARN of secret [stored in AWS Secrets Manager] for ranger admin public cert. e.g arn:aws:secretsmanager:us-east-1:999999999999:secret:ranger-admin-cert-3W5Zdt", "Type": "String", "Default": "" }, "Region": { "Description": "AWS Region where cluster will be created. e.g. us-east-1", "Type": "String", "Default": "" }, "CloudwatchLogGroupName": { "Description": "CloudWatch Log group name which will be used to store RangerAudits. This should be an existing one e.g. emr_native_privacera_audits", "Type": "String", "Default": "" }, "AwsAcctId": { "Description": "Account ID of your Amazon Account. e.g. 999999999999", "Type": "String", "Default": "" }, "EmrNativeRangerAdminUrl": { "Description": "Get from--> PCloud Portal >> Access Manager >> Settings >> ApiKey >> Click on Info Icon >> AWS EMR Native Ranger Plugin Section >> Ranger Admin mTLS URL >> Copy URL. e.g. https://api-mtls.privaceracloud.com/api/<api-key>", "Type": "String", "Default": "https://api-mtls.privaceracloud.com/api/<api-key>" }, "HiveRepoName": { "Description": "Hive Repo Name in RangerAdmin", "Type": "String", "Default": "privacera_hive" }, "EmrfsRepoName": { "Description": "EMRFS-S3 Repo Name in RangerAdmin", "Type": "String", "Default": "privacera_emrfs_s3" }, "KerberosTicketLifetime": { "Description": "The period for which a Kerberos ticket issued by the cluster’s KDC is valid. Cluster applications and services auto-renew tickets after they expire", "Type": "Number", "Default": 24 }, "KerberosAdminServer": { "Description": "The fully qualified domain name (FQDN) and optional port for the Kerberos admin server in the other realm. If a port is not specified, 749 is used", "Type": "String", "Default": "" }, "KerberosDomain": { "Description": "The domain name of the other realm in the trust relationship", "Type": "String", "Default": "" }, "KDCServer": { "Description": "The fully qualified domain name (FQDN) and optional port for the KDC in the other realm. If a port is not specified, 88 is used", "Type": "String", "Default": "" }, "KerberosRealm": { "Description": "The Kerberos realm name for the other realm in the trust relationship", "Type": "String", "Default": "" } }, "Resources": { "SecurityConfiguration": { "Type": "AWS::EMR::SecurityConfiguration", "Properties": { "Name": { "Fn::Sub": "${EmrNativePrivaceraSecConfName}" }, "SecurityConfiguration": { "AuthorizationConfiguration": { "RangerConfiguration": { "AdminServerURL": { "Fn::Sub": "${EmrNativeRangerAdminUrl}" }, "RoleForRangerPluginsARN": { "Fn::Sub": "arn:aws:iam::${AwsAcctId}:role/${EmrNativePrivaceraDataAccessRole}" }, "RoleForOtherAWSServicesARN": { "Fn::Sub": "arn:aws:iam::${AwsAcctId}:role/${EmrNativePrivaceraUserAccessRole}" }, "AdminServerSecretARN": { "Fn::Sub": "${RangerAdminPublicSecretArn}" }, "RangerPluginConfigurations": [ { "App": "Spark", "ClientSecretARN": { "Fn::Sub": "${RangerPluginKeyPairSecretArn}" }, "PolicyRepositoryName": { "Fn::Sub": "${HiveRepoName}" } }, { "App": "Hive", "ClientSecretARN": { "Fn::Sub": "${RangerPluginKeyPairSecretArn}" }, "PolicyRepositoryName": { "Fn::Sub": "${HiveRepoName}" } }, { "App": "EMRFS-S3", "ClientSecretARN": { "Fn::Sub": "${RangerPluginKeyPairSecretArn}" }, "PolicyRepositoryName": { "Fn::Sub": "${EmrfsRepoName}" } } ], "AuditConfiguration": { "Destinations": { "AmazonCloudWatchLogs": { "CloudWatchLogGroup": { "Fn::Sub": "arn:aws:logs:${Region}:${AwsAcctId}:log-group:${CloudwatchLogGroupName}:*" } } } } } }, "AuthenticationConfiguration": { "KerberosConfiguration": { "Provider": "ClusterDedicatedKdc", "ClusterDedicatedKdcConfiguration": { "TicketLifetimeInHours": { "Ref": "KerberosTicketLifetime" }, "CrossRealmTrustConfiguration": { "AdminServer": { "Fn::Sub": "${KerberosAdminServer}" }, "Domain": { "Fn::Sub": "${KerberosDomain}" }, "KdcServer": { "Fn::Sub": "${KDCServer}" }, "Realm": { "Fn::Sub": "${KerberosRealm}" } } } } } } } } } } Note To know about how to create a stack using CloudFormation template, refer Create CloudFormation stack topic. 1. Login to AWS Console and navigate to EMR Console > Security Configuration (from left panel) > Create New Security Configuration. 2. Enter the Security Configuration name. E.g. EMR_NATIVE_WITH_PLCOUD 3. Navigate to Authentication section and select Enable Kerberos authentication checkbox and enter the Kerberos environment details. 4. Under the Authorization section, select Enable integration with Apache Ranger for fine-grained access control and enter the deatils as below: 1. IAM role for Apache Ranger: “EMR_RS_DATA_ACCESS_ROLE” (Created during IAM Roles setup). 2. IAM role for other AWS Services: “EMR_RS_USER_ACCESS_ROLE” (Created during IAM Roles setup. 3. Ranger Policy Manager: Go to your PCloud Account > Settings > ApiKey > AWS EMR Native Ranger > Ranger Admin mTLS URL > click on Copy URL and add it in this section. 4. Admin PEM secret: Choose ranger-admin-pub-cert using drop-down. 5. EMRFS client PEM secret: Choose ranger-plugin-key-cert using drop-down. 6. EMRFS policy repository: privacera_emrfs_s3 7. Spark configurations: Select this option, if want to enable Spark Application. 8. Spark client PEM secret: Choose ranger-plugin-key-cert using drop-down. 9. Spark policy repository: privacera_hive 10. Hive configurations: Select this option, if want to enable Hive Application. 11. Hive client PEM secret: Choose ranger-plugin-key-cert using drop-down. 12. Hive policy repository: privacera_hive 13. CloudWatch Log Group: Select a CloudWatch log group for pushing audits if required. Note: The “EMR_RS_DATA_ACCESS_ROLE” should have permissions to create and PutLogEvents in this log group(This has been configured during IAM roles setup). Create EMR Cluster# The following CloudFormation template can be used to EMR cluster. You can modify the below template based on your requirements (if required). Note Common variables from the previous setup steps should be kept the same. Sample CloudFormation Template { "AWSTemplateFormatVersion": "2010-09-09", "Description": "Create EMR Cluster - Native Ranger Integration with Privacera", "Parameters": { "ClusterName": { "Description": "Name of the emr cluster", "Type": "String", "Default": "Privacera-EMR-Native-Ranger" }, "EMRVersion": { "Description": "EMR Native Ranger integation is supported from 5.32 onwards. e.g. emr-5.32.0, emr-5.33.0, etc.", "Type": "String", "Default": "emr-5.32.0" }, "MasterSecurityGroup": { "Description": "Security Group ID for EMR Master Node Group. e.g. sg-xxxxxxx", "Type": "String", "Default": "" }, "SlaveSecurityGroup": { "Description": "Security Group ID for EMR Slave Node Group. e.g. sg-xxxxxxx", "Type": "String", "Default": "" }, "ServiceAccessSecurityGroup": { "Description": "Security Group ID for EMR ServiceAccessSecurity. Fill this property only if you are creating EMR in a Private Network. e.g. sg-xxxxxxx", "Type": "String", "Default": "" }, "NodeSubnetId": { "Description": "Subnet id for the cluster nodes. e.g. subnet-xxxx", "Type": "String", "Default": "" }, "SecurityConfig": { "Description": "SecurityConfiguration name that will be attached to the EMR Cluster. e.g emr-native-privacera-sec-conf", "Type": "String", "Default": "emr-native-privacera-sec-conf" }, "HiveMetaStoreWarehouseS3Path": { "Description": "Hive metastore warehouse s3 path. e.g. s3://hive-warehouse/data", "Type": "String", "Default": "" }, "NodeKeyPair": { "Description": "An existing EC2 key pair to SSH into the node of cluster. e.g. privacera-test-pair", "Type": "String", "Default": "" }, "NodeMarketType": { "Description": "Node Instance market type. e.g. SPOT, ON_DEMAND", "Type": "String", "Default": "" }, "KdcAdminPassword": { "Description": "The password used within the cluster for the kadmin service.", "Type": "String", "Default": "" }, "CrossRealmTrustPrincipalPassword": { "Description": "The cross-realm trust principal password, which much be identical across realms.", "Type": "String", "Default": "" }, "RangerAuditsSetupScriptUrl": { "Description": "Get from--> PCloud Portal >> Access Manager >> Settings >> ApiKey >> Click on Info Icon >> AWS EMR Native Ranger Plugin Section >> Ranger Audit Setup Script >> Copy URL", "Type": "String", "Default": "" }, "EmrMasterNodeCount": { "Description": "Node count for Master. e.g. 1", "Type": "Number", "Default": 1 }, "EmrCoreNodeCount": { "Description": "Node count for Core. e.g. 1", "Type": "Number", "Default": 1 }, "EmrNodeInstanceType": { "Description": "e.g. m5.large, m5.2xlarge, r5.xlarge,etc. ", "Type": "String", "Default": "" }, "EmrTerminationProtection": { "Description": "To enable termination protection. Can be true/false", "Type": "String", "Default": "true" }, "EmrLogsPath": { "Description": "S3 location for emr logs storage. e.g. s3://privacera-emr/logs", "Type": "String", "Default": "" }, "EmrNativePrivaceraInstanceRole": { "Description": "IAM Role which will be attached to all Instances in the Cluster. Should have minimal permissions. e.g. emr_native_privacera_restricted_instance_role", "Type": "String", "Default": "emr_native_privacera_restricted_instance_role" }, "EmrDefaultRole": { "Description": "Default role attached to EMR Cluster for performing cluster related activities. This should be a pre-created one. e.g. EMR_DefaultRole", "Type": "String", "Default": "EMR_DefaultRole" }, "EmrHiveMetastoreConnectionUrl": { "Description": "JDBC Connection URL for connecting to hive. e.g. jdbc:mysql://<jdbc-host>:3306/<hive-db-name>?createDatabaseIfNotExist=true", "Type": "String", "Default": "" }, "EmrHiveMetastoreConnectionDriver": { "Description": "JDBC Driver Name. e.g. org.mariadb.jdbc.Driver", "Type": "String", "Default": "" }, "EmrHiveMetastoreConnectionUsername": { "Description": "JDBC UserName", "Type": "String", "Default": "" }, "EmrHiveMetastoreConnectionPassword": { "Description": "JDBC Password", "Type": "String", "Default": "" } }, "Resources": { "EMRCLUSTER": { "Type": "AWS::EMR::Cluster", "Properties": { "Name": { "Ref": "ClusterName" }, "KerberosAttributes": { "Realm": "EC2.INTERNAL", "KdcAdminPassword": { "Ref": "KdcAdminPassword" }, "CrossRealmTrustPrincipalPassword": { "Ref": "CrossRealmTrustPrincipalPassword" } }, "SecurityConfiguration": { "Ref": "SecurityConfig" }, "VisibleToAllUsers": true, "EbsRootVolumeSize": 15, "Instances": { "MasterInstanceGroup": { "InstanceCount": { "Ref": "EmrMasterNodeCount" }, "InstanceType": { "Fn::Sub": "${EmrNodeInstanceType}" }, "Market": { "Fn::Sub": "${NodeMarketType}" }, "Name": "Master Instance Group" }, "CoreInstanceGroup": { "InstanceCount": { "Ref": "EmrCoreNodeCount" }, "InstanceType": { "Fn::Sub": "${EmrNodeInstanceType}" }, "Market": { "Fn::Sub": "${NodeMarketType}" }, "Name": "Core Instance Group" }, "Ec2KeyName": { "Ref": "NodeKeyPair" }, "EmrManagedSlaveSecurityGroup": { "Fn::Sub": "${SlaveSecurityGroup}" }, "EmrManagedMasterSecurityGroup": { "Fn::Sub": "${MasterSecurityGroup}" }, "ServiceAccessSecurityGroup": { "Fn::Sub": "${ServiceAccessSecurityGroup}" }, "Ec2SubnetId": { "Fn::Sub": "${NodeSubnetId}" }, "TerminationProtected": { "Fn::Sub": "${EmrTerminationProtection}" } }, "BootstrapActions": [ { "Name": "Configure Ranger Audits for Master Node", "ScriptBootstrapAction": { "Path": "s3://elasticmapreduce/bootstrap-actions/run-if", "Args": [ { "Fn::Sub": "instance.isMaster=true" }, { "Fn::Sub": "wget ${RangerAuditsSetupScriptUrl}; chmod +x ./privacera_emr_native.sh ; sudo ./privacera_emr_native.sh" } ] } }, { "Name": "Configure Ranger Audits for Worker Nodes", "ScriptBootstrapAction": { "Path": "s3://elasticmapreduce/bootstrap-actions/run-if", "Args": [ { "Fn::Sub": "instance.isMaster=false" }, { "Fn::Sub": "wget ${RangerAuditsSetupScriptUrl}; chmod +x ./privacera_emr_native.sh ; sudo ./privacera_emr_native.sh" } ] } } ], "Applications": [ { "Name": "Hive" }, { "Name": "Spark" }, { "Name": "Zeppelin" }, { "Name": "Livy" }, { "Name": "Hue" } ], "Configurations": [ { "Classification": "spark", "ConfigurationProperties": { "maximizeResourceAllocation": "true" }, "Configurations": [] }, { "Classification": "spark-hive-site", "ConfigurationProperties": { "hive.metastore.warehouse.dir": { "Ref": "HiveMetaStoreWarehouseS3Path" } } }, { "Classification": "hive-site", "ConfigurationProperties": { "javax.jdo.option.ConnectionURL": { "Fn::Sub": "${EmrHiveMetastoreConnectionUrl}" }, "javax.jdo.option.ConnectionDriverName": { "Fn::Sub": "${EmrHiveMetastoreConnectionDriver}" }, "javax.jdo.option.ConnectionUserName": { "Fn::Sub": "${EmrHiveMetastoreConnectionUsername}" }, "javax.jdo.option.ConnectionPassword": { "Fn::Sub": "${EmrHiveMetastoreConnectionPassword}" }, "hive.metastore.warehouse.dir": { "Ref": "HiveMetaStoreWarehouseS3Path" } } } ], "LogUri": { "Fn::Sub": "${EmrLogsPath}" }, "JobFlowRole": { "Fn::Sub": "${EmrNativePrivaceraInstanceRole}" }, "ServiceRole": { "Fn::Sub": "${EmrDefaultRole}" }, "ReleaseLabel": { "Fn::Sub": "${EMRVersion}" } } } } } Note To know about how to create a stack using CloudFormation template, refer Create CloudFormation stack topic. 1. Login to AWS Console and navigate to EMR service and click on Create Cluster. 2. Click on Go to advanced options link. 3. Under the Software Configuration: 1. Select Release Version. 2. Select additional applications as per your environment. If you select Hive or Spark applications, then it is mandatory to select HCatalog option. 1. Under the Edit software settings, select the Enter configuration, and add the following text if you want to use external Hive Metastore. Glue Metastore is not supported. ```json [ { "Classification": "hive-site", "Properties": { "javax.jdo.option.ConnectionUserName": "${user-name}", "javax.jdo.option.ConnectionDriverName": "${jdbc-driver}", "javax.jdo.option.ConnectionURL": "${jdbc-url}", "javax.jdo.option.ConnectionPassword": "${jdbc-password}" } } ] ``` 4. Click Next. 5. Under the Hardware settings, select values Networking, Node, and Instance values as appropriate for your environment. 6. Under the General cluster settings. If you want to enable Audit logging for your applications in Privacera Portal, perform the following. It will add two scripts that will Install Ranger Audits Configurations on master and worker nodes. 7. Enter the Cluster name. 1. Select Logging, Debugging, and Termination protection checkboxes as per your environment. 2. Configure Ranger Audits logging for Master Node: 1. Under Additional Options, expand Bootstrap Actions, select bootstrap action Run if and click Configure and add. The Add Bootstrap Action dialog appears. 2. In this dialog, enter the name to Configure Ranger Audits for Master, 3. Add the following script in the Optional arguments field using your own {ranger-audit-setup-script-url} script URL. {ranger-audit-setup-script-url}: PCloud Portal > Access Manager > Settings > ApiKey > Click on Info Icon > Ranger Audit Setup Script > Copy URL. instance.isMaster=true "wget <ranger-audit-setup-script-url>; chmod +x ./privacera_emr_native.sh ; sudo ./privacera_emr_native.sh" 4. Click Add. 3. Configure Ranger Audits for Worker nodes. 1. Under Additional Options, expand Bootstrap Actions, select bootstrap action Run if and click Configure and add. The Add Bootstrap Action dialog appears. 2. In this dialog, enter the name to Configure Ranger Audits for Master, 3. Add the following script in the Optional arguments field using your own {ranger-audit-setup-script-url} script URL. {ranger-audit-setup-script-url}: PCloud Portal > Access Manager > Settings > ApiKey > Click on Info Icon > Ranger Audit Setup Script > Copy URL. instance.isMaster=false "wget <ranger-audit-setup-script-url>; chmod +x ./privacera_emr_native.sh ; sudo ./privacera_emr_native.sh" 4. Click Add. 8. Under Security Options: 1. Enter/select Security Options as per your environment. 2. Under the Permissions section: • EMR role: The EMR_EC2_Default role need to be selected. • EC2 instance profile: “EMR_RS_INSTANCE_ROLE” created during IAM Roles setup. 3. Expand Security Configuration, and select the configuration which you created earlier. E.g. "EMR_NATIVE_WITH_PLCOUD". • Set Realm and enter a KDC admin password. 4. Click the Create cluster. Usage# • On the PrivaceraCloud Account, expand Access Manager and click Service Config from left menu. • (If it is not already added), click the Add Service at top-right and select Hive and emrfs_s3 from drop-down. • Click Save. 1. Spark-SQL use-case 1. SSH to EMR master node. 2. kinit with your user. 3. Run Spark-SQL shell using “spark-sql”. 4. Run SQL type queries with Spark. Policies will be evaluated against the “privacera_hive” repository and audits can be seen under Access Manager > Audits from left menu. 2. Spark-Shell use-case 1. SSH to EMR master node. 2. kinit with your user. 3. Run Spark-shell using “spark-shell”. 4. Run Scala queries with Spark. Policies will be evaluated against the “privacera_emrfs_s3” repository for any S3 access and audits can be seen under Access Manager > Audits from left menu. 1. SSH to EMR master node. 2. kinit with your user. 3. Login to beeline shell using command below: beeline -u "jdbc:hive2://`hostname -f`:10000/default;principal=hive/`hostname -f`@EC2.INTERNAL" 4. Run Hive queries. Policies will be evaluated against the “privacera_hive” repo and audits can be seen under Access Manager > Audits from left menu. References# Last update: August 20, 2021
__label__pos
0.999173
Requests::request_multiple( array $requests, array $options = array() ) Send multiple HTTP requests simultaneously Description Description The $requests parameter takes an associative or indexed array of request fields. The key of each request can be used to match up the request with the returned data, or with the request passed into your multiple.request.complete callback. The request fields value is an associative array with the following keys: • url: Request URL Same as the $url parameter to Requests::request (string, required) • headers: Associative array of header fields. Same as the $headers parameter to Requests::request (array, default: array()) • data: Associative array of data fields or a string. Same as the $data parameter to Requests::request (array|string, default: array()) • type: HTTP request type (use Requests constants). Same as the $type parameter to Requests::request (string, default: Requests::GET) • cookies: Associative array of cookie name to value, or cookie jar. (array|Requests_Cookie_Jar) If the $options parameter is specified, individual requests will inherit options from it. This can be used to use a single hooking system, or set all the types to Requests::POST, for example. In addition, the $options parameter takes the following global options: • complete: A callback for when a request is complete. Takes two parameters, a Requests_Response/Requests_Exception reference, and the ID from the request array (Note: this can also be overridden on a per-request basis, although that’s a little silly) (callback) Top ↑ Parameters Parameters $requests (array) (Required) Requests data (see description for more information) $options (array) (Optional) Global and default options (see Requests::request) Default value: array() Top ↑ Return Return (array) Responses (either Requests_Response or a Requests_Exception object) Top ↑ Source Source File: wp-includes/class-requests.php public static function request_multiple($requests, $options = array()) { $options = array_merge(self::get_default_options(true), $options); if (!empty($options['hooks'])) { $options['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple')); if (!empty($options['complete'])) { $options['hooks']->register('multiple.request.complete', $options['complete']); } } foreach ($requests as $id => &$request) { if (!isset($request['headers'])) { $request['headers'] = array(); } if (!isset($request['data'])) { $request['data'] = array(); } if (!isset($request['type'])) { $request['type'] = self::GET; } if (!isset($request['options'])) { $request['options'] = $options; $request['options']['type'] = $request['type']; } else { if (empty($request['options']['type'])) { $request['options']['type'] = $request['type']; } $request['options'] = array_merge($options, $request['options']); } self::set_defaults($request['url'], $request['headers'], $request['data'], $request['type'], $request['options']); // Ensure we only hook in once if ($request['options']['hooks'] !== $options['hooks']) { $request['options']['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple')); if (!empty($request['options']['complete'])) { $request['options']['hooks']->register('multiple.request.complete', $request['options']['complete']); } } } unset($request); if (!empty($options['transport'])) { $transport = $options['transport']; if (is_string($options['transport'])) { $transport = new $transport(); } } else { $transport = self::get_transport(); } $responses = $transport->request_multiple($requests, $options); foreach ($responses as $id => &$response) { // If our hook got messed with somehow, ensure we end up with the // correct response if (is_string($response)) { $request = $requests[$id]; self::parse_multiple($response, $request); $request['options']['hooks']->dispatch('multiple.request.complete', array(&$response, $id)); } } return $responses; } Top ↑ User Contributed Notes User Contributed Notes You must log in before being able to contribute a note or feedback.
__label__pos
0.790388
Вы находитесь на странице: 1из 34 - Моделирование изменение параметров во времени - Описание состояния динамической системы - Описание кинетики химических реакций - Моделирование процессов переноса тепла, массы, импульса - Моделирование процесса сушки, адсорбции - Экономические модели Задача 1. В сосуд, содержащий 10 л воды, начинает непрерывно поступать со скоростью 2 л в минуту раствор, в каждом литре которого содержится 0.3 кг соли. Поступающий в сосуд раствор перемешивается с водой, и смесь вытекает из сосуда с той же скоростью. Сколько соли будет в сосуде через 5 минут? Задача 1. Перемешивание. В сосуд, содержащий 10 л воды, начинает непрерывно поступать со скоростью 2 л в минуту раствор, в каждом литре которого содержится 0.3 кг соли. Поступающий в сосуд раствор перемешивается с водой, и смесь вытекает из сосуда с той же скоростью. Сколько соли будет в сосуде через 5 минут? Математическая модель - уравнение, связывающее независимую переменную (время), искомую величину - концентрацию соли (как функцию от времени) и скорость изменения концентрации (производную концентрации по времени). Допущение - поступающий в сосуд солевой раствор равномерно перемешивается с содержащейся в сосуде жидкостью. V=2 л/мин – скорость поступления солевого раствора в сосуд, K = 0.3 кг/л – концентрация поступающего солевого раствора. Количество соли, поступающее в сосуд за малое время Δt будет равно V ⸱ K ⸱ Δt=2⸱0.3⸱ Δt За время Δt поток уносит количество соли S (t) V  t 10 За время Δt в сосуд поступает количество соли V  K  t Тогда в момент времени t+Δt количество соли S (t) S (t+t) = S(t) − V  t + V  K  t 10 S (t ) S (t + t ) = S (t ) −  2  t + 2  0.3  t 10 S (t + t ) − S (t ) S (t ) =−  2 + 2  0.3 t 10 При Δt → 0 dS S (t ) =− + 0.6 dt 5 В начальный момент времени в сосуде была чистая вода dS − S (t ) + 3 = S(0) = 0 – начальное условие dt 5 dS dt Применим разделение переменных = − S (t ) + 3 5 dx dt Проинтегрируем  =  +С − S (t ) + 3 5 t Общее решение − ln(3 − S (t )) = + C 5 Из начального условия определим константу С = − ln 3 t Общее решение − ln(3 − S (t )) = + C 5 Частное решение С = − ln 3 t t  3 − S (t )  t 3 − S (t ) − − =−  =e  S(t ) = 3  (1 − e ln  5 5)  3  5 3 Cодержание соли в сосуде 3 2.5 При t=5 −1 S (5) = 3  (1 − e ) Количество соли, кг 1.5 1 S(5)=1.8964 0.5 0 0 2 4 6 8 10 12 14 16 18 20 Время, мин t Общее решение − ln(3 − S (t )) = + C 5 Частное решение С = − ln 3 t t  3 − S (t )  t 3 − S (t ) − − =−  =e  S(t ) = 3  (1 − e ln  5 5)  3  5 3 Cодержание соли в сосуде 3 2.5 При t=5 −1 S (5) = 3  (1 − e ) Количество соли, кг 1.5 1 S(5)=1.8964 0.5 0 0 2 4 6 8 10 12 14 16 18 20 Время, мин Задача 2. Растворение. Дно резервуара, вместимость которого 300 л, покрыто солью. Допуская, что скорость растворения соли пропорциональна разности между концентрацией насыщенного раствора (1 кг соли на 3 л воды) и концентрацией в данный момент, и что данное количество чистой воды растворяет 1/3 кг соли в минуту, найти, сколько соли будет содержать раствор по истечении 1 часа? Для получения насыщенного раствора соли необходимо взять 1 кг соли на 3 л чистой воды, считая, что приближенно 1 кг соли занимает объем 1 л, концентрация соли в насыщенном растворе равна С = 1 = 1 1+ 3 4 Пусть m(t) – масса соли (кг) в резервуаре в момент времени t, v(t) – скорость растворения соли (кг/мин) в момент времени t. Δt –малый интервал времени, такой что можно считать, что скорость растворения соли в момент времени t и t +Δt не изменяется существенно, т.е. v(t) ≈ v(t +Δt). Тогда m(t +Δt)= m(t)+ v(t) Δt По условию m(t ) 1 m(t ) v(t ) = k  (C − ) = k ( − ) 300 + m(t ) 4 300 + m(t ) Найдем коэффициент k из условия, что чистая вода растворяет 1/3 кг соли в минуту 1 1 4 = k  ( − 0)  k = 3 4 3 4 1 m(t ) m(t + t ) = m(t ) +  ( − )  t 3 4 300 + m(t ) m(t + t ) − m(t ) 1 4 m(t ) = −  t 3 3 300 + m(t ) 1 4 m(t ) При Δt → 0 m(t ) = −  3 3 300 + m(t ) В начальный момент времени в резервуар была налита чистая вода m(0) = 0 – начальное условие Задача 3. Остывание. Тело охладилось за 10 минут со 100º до 60º. Температура окружающего воздуха поддерживается равной 20º. Определить, за сколько минут тело остынет до 25º. Скорость остывания тела пропорциональна разности температур тела и окружающей среды. Пусть T(t) - температура тела в момент времени t (мин.) По условию T(0) = 100, T(10) = 60 V(t) – скорость остывания тела T(t +Δt) = T(t) - V(t) ⸳ Δt Если Δt –малый интервал времени, то можно считать, что скорость остывания тела в момент времени t и t +Δt практически не изменяется, т.е. V(t) ≈ V(t +Δt). V(t)= k ⸳ (T(t)-20) T(t +Δt) = T(t) - k ⸳ (T(t)-20) ⸳ Δt T (t + t ) − T (t ) = −k  (T (t ) − 20) t При Δt → 0 T (t ) = −k  (T (t ) − 20) Два известных значения функции позволяют найти коэффициент с помощью интегрирования уравнения с разделением переменных dT dt = −k  (T (t ) − 20) ln(T − 20) = − k  t + C dT * − k t = − k  dt T − 20 = C e T (t ) − 20 * − k t dT T = 20 + C e  = −  k  dt + C T (t ) − 20 По условию T(0) = 100, С*=80, С=ln(80) По условию T(10) = 60, ln(60-20)=-10⸱k+ln(80) − t ln 2 −t ln 2 T(t) = 20 + 80 e 10 =20+80  2 10 k= 10 Остывание тела 100 Для искомого T = 25 90 80 10 80 t= температура, С 70 60 ln( ) ln 2 5 50 ln16 40 t = 10 =40 30 ln 2 20 0 10 20 30 40 50 60 Время, мин 1. Решить, какую из величин взять за независимую переменную, а какую — за искомую функцию. 2. Выразить, на сколько изменится искомая функция y, когда независимая переменная x получит приращение Δx, т. е. выразить разность y(x + Δx) − y(x) через величины, о которых говорится в задаче. 3. Разделив разность y(x + Δx) − y(x) на Δx и перейдя к пределу при Δx → 0, получим дифференциальное уравнение, из которого можно найти искомую функцию. Задача 4. Теплоизоляция. Трубопровод тепловой магистрали (диаметр 20 см) защищен изоляцией толщиной 10 см; величина коэффициента теплопроводности k=0.00017. Температура трубы 160°; температура внешнего покрова 30° Найти распределение температуры внутри изоляции, а также количество теплоты, отдаваемого одним погонным метром трубы Пусть T(x) - температура тела на расстоянии x от стенки трубы. Если тело находится в стационарном тепловом состоянии и температура Т в каждой его точке есть функция только одной координаты x, то согласно закону теплопроводности Фурье количество теплоты, испускаемое в секунду 𝑑𝑇 𝑄 = −𝑘𝐹 𝑥 𝑑𝑥 = 𝑐𝑜𝑛𝑠𝑡 где 𝐹 𝑥 – площадь сечения тела на расстоянии 𝑥, 𝑘 – коэффициент теплопроводности. 𝐹 𝑥 = 2𝜋𝑥𝑙, 𝑙 – длина трубы в см, 𝑥 – радиус трубопровода в см. 𝑄 𝑄 𝑑𝑥 𝑑𝑇 = − 𝑑𝑥 = −𝑘 𝑘𝐹 𝑥 𝑘 ∙ 2𝜋𝑙 𝑥 30 20 𝑄 𝑑𝑥 න 𝑑𝑇 = − න , или 160 0.00017 ∙ 2𝜋𝑙 10 𝑥 𝑇 𝑥 𝑄 𝑑𝑥 න 𝑑𝑇 = − න 160 0.00017 ∙ 2𝜋𝑙 10 𝑥 𝑄 20 𝑄 30 − 160 = − 𝑙𝑛𝑥 ቚ 10= − 𝑙𝑛2 0.00017 ∙ 2𝜋𝑙 0.00017 ∙ 2𝜋𝑙 𝑇 − 160 𝑄 𝑥 𝑄 =− 𝑙𝑛𝑥ห 10= − 𝑙𝑛0.1𝑥 0.00017 ∙ 2𝜋𝑙 0.00017 ∙ 2𝜋𝑙 Разделив уравнение второе на первое, получим: 𝑇−160 𝑙𝑛0.1𝑥 𝑙𝑔0.1𝑥 = = . −130 𝑙𝑛2 𝑙𝑔2 Закон распределения температуры внутри изоляции: 𝑇 = 591.8 − 431.8 ∙ 𝑙𝑔𝑥. Из первого уравнения системы при 𝑙 = 100 см: 130∙0.00017∙2𝜋∙100 130∙0.00017∙200𝜋 𝑄= = . 𝑙𝑛2 0.69315 Количество теплоты, отдаваемое в течение суток, равно: 130 ∙ 0.00017 ∙ 200𝜋 𝑄 = 86400 ∙ = 1730600 кал 0.69315 Обыкновенным дифференциальным уравнением (ОДУ) n-го порядка называется уравнение, которое содержит одну или несколько производных от искомой функции y(x): G ( x, y, y, y, y,... y ) = 0 (n) (n) - производная порядка n y В ряде случаев дифференциальное уравнение можно преобразовать к виду, в котором старшая производная выражена в явном виде. Такая форма записи называется уравнением, разрешенным относительно старшей производной (при этом в правой части уравнения старшая производная отсутствует): y = f ( x, y, y, y, y,..., y (n) ( n −1) ) - такая форма записи принята в качестве стандартной при рассмотрении численных методов решения ОДУ Решением обыкновенного дифференциального уравнения называется такая функция y(x), которая при любых х удовлетворяет этому уравнению в определенном конечном или бесконечном интервале. Точное (аналитическое) решение дифференциального уравнения подразумевает получение искомого решения в виде выражения. Численное решение ДУ (частное) заключается в вычислении функции y(x) и ее производных в некоторых заданных точках x1, x2,…, xk, лежащих на определенном отрезке. X y y' y(n-1) x1 y(x1) y'(x1) … y(n-1)(x1) x2 y(x2) y'(x2) … y(n-1)(x2) xk y(xk) y'(xk) … y(n-1)(xk) Множество значений абсцисс xi в которых определяется значение функции, называют сеткой, на которой определена функция y(x). Сами координаты при этом называют узлами сетки. Чаще всего, для удобства, используются равномерные сетки, в которых разница между соседними узлами постоянна и называется шагом сетки. h = xi – xi-1 xi = xi-1 + h Для определения частного решения необходимо задать дополнительные условия, которые позволят вычислить константы интегрирования. Причем таких условий должно быть ровно n (по порядку старшей производной в уравнении). В зависимости от способа задания начальных условий при решении дифференциальных уравнений рассматривают задачи: Задача Коши: Необходимо найти такое частное решение дифференциального уравнения, которое удовлетворяет определенным начальными условиям, заданным в одной точке: ( n−1) y ( x0 ) = y0 ; y( x0 ) = y0 ;...; y ( n −1) ( x0 ) = y0 то есть, задано определенное значение независимой переменной (х0), и значение функции и всех ее производных вплоть до порядка (n-1) в этой точке. Эта точка (х0) называется начальной. Например, если решается ДУ 1-го порядка, то начальные условия выражаются в виде пары чисел (х0 , y0) В зависимости от способа задания начальных условий задача решения дифференциальных уравнений может быть рассмотрена в другой постановке: Краевая задача: В этом случае известны значения функции и (или) ее производных в более чем одной точке, например, в начальный и конечный момент времени, и необходимо найти частное решение дифференциального уравнения между этими точками. Сами дополнительные условия в этом случае называются краевыми (граничными) условиями. Краевая задача может решаться для ОДУ не ниже 2-го порядка. d2y dy 2 + 2 = y + sin( x) y (0) = 0 y (1) = 0 dx dx Искомая функция y(x) раскладывается в ряд Тейлора в окрестностях узлов сетки x0, x1, x2,…, xk. Слагаемые, содержащие производные второго и более высоких порядков отбрасываются. В окрестности узла xi y ( x i + h) = y ( x i ) + y ( x i ) h + O ( h ) 2 x i +1 = x i + h y  = f ( x, y ) y i = y( xi ) y i +1 = y i + f ( x i , y i )h приближенное и точное решение задачи в 5 узлах Алгоритм Рунге-Кутта четвертого порядка - погрешность порядка h4 Для оценки погрешности численного решения обыкновенного дифференциального уравнения необходимо решить задачу дважды – выбрав шаг h и затем h/2 . Погрешность в узлах первой сетки определяется по правилу Рунге | y i ,h − y i ,h / 2 | Метод yi = p 2p −1 Эйлера 1 модифицированный 2 где p – порядок метод Эйлера точности метод Рунге-Кутта 4
__label__pos
0.89968
Howto use array_map on associative arrays to change values and keys $assoc_arr = array_reduce($arr, function ($result, $item) { $result[$item['text']] = $item['id']; return $result; }, array()); The snippets story I just ran into a problem using array_map on associative arrays, like the following one: $arr = array( array( 'id' => 22, 'text' => 'Lorem' ), array( 'id' => 25, 'text' => 'ipsum' ), ); From this array, I wanted to create another, associative array, with the following structure: $assoc_arr = array( 'Lorem' => 22, 'ipsum' => 25 ); My first guess was the array_map function, but I had to realize that there is no way to manipulate the keys of the resulting array. After some googling, I discovered, that it is array_reduce you have to use to simulate array_map on associative arrays. ps: I know, a simple foreach would have done the trick, but once on the path of functional programming, I didn’t want to leave it that fast 🙂 Tagged with: 16 thoughts on “Howto use array_map on associative arrays to change values and keys 1. As you mentioned “a simple foreach would have done the trick”, what’s the point using array_reduce then ? It seems It puts complexity where there isn’t any. Do you have another example, where It is unavoidable ? thanks 2. Been looking for this for a while. Like you say a foreach would suffice, but why make it easy. This is going straight on my (non-competng, private) snippets site. Thanks for spending the time 3. First of all thank you for sharing this informative blog.. This blog having more useful information that information explanation are step by step and very clear so easy and interesting to read.. After reading this blog i am strong in this topic which helpful to cracking the interview easily.. 4. This could help 🙂 22, ‘text’ => ‘Lorem’ ), array( ‘id’ => 25, ‘text’ => ‘ipsum’ ), ); function get_value($val, $key) { global $master_arr; $master_arr[$val[‘text’]] = $val[‘id’]; } array_walk($arr, ‘get_value’); print_r($master_arr); ?> Leave a Reply Your email address will not be published. Required fields are marked *
__label__pos
0.985879
PvPGN (Battle.net) Опубликовано nekit - вс, 30/09/2012 - 17:01 Спросили меня не так давно - есть ли возможность поднять свой Battle.net на FreeBSD, а если есть, то помочь настроить. Игры, для которых возникла необходимость в собственном сервере, это Starcraft и Warcraft 3. После недолгих поисков было найдено решение в виде PvPGN. PvPGN (Player versus Player Gaming Network), который является модификацией сервера bnetd, эмулирует работу сервера Blizzard Battle.net (TM). Далее я расскажу о том, как его установить и настроить, а так же с какими проблемами я столкнулся в процессе работы с ним. Все действия будут происходить на ОС FreeBSD версии 8.3. Идем в порты и устанавливаем PvPGN. На момент написания статьи в портах доступна версия 1.8.5. 1. # cd /usr/ports/games/pvpgn 2. # make install clean При сборке порта доступны следующие параметры: • MYSQL - поддержка хранения данных о пользователях в MySQL. • PGSQL - поддержка хранения данных о пользователях в PostgreSQL. • SQLITE3 - поддержка хранения данных о пользователях в SQLite3. • D2 - собрать сервер для Diablo 2. Хранить все в базе данных гораздо удобнее, чем хранить все в фалах. На сервере уже стоит СУБД PostgreSQL, поэтому я поставил галочку напротив опции - PGSQL. Остальные опции убрал. После установки в директории /usr/local/etc появится директория pvpgn. В ней будут находиться стандартные конфигурационные файлы с именами вида *-sample. Все эти файлы необходимо переименовать (или скопировать) к виду без -sample. Уже сейчас можно запускать сервер и пробовать подключаться к нему, но есть опции, которые полезно будет посмотреть и возможно изменить. Да и к тому же надо настроить работу с PostgreSQL, ибо в стандартной конфигурации сервер все хранит в файлах. Так же не забываем создать базу данных и пользователя для PvPGN, если вы используете СУБД. Вот так выглядит главный конфигурационный файл /usr/local/etc/pvpgn/bnetd.conf у меня: 1. ############################################################################## 2. # bnetd.conf  -  главный конфигурационный файл                               # 3. #----------------------------------------------------------------------------# 4. #                                                                            # 5. # ####################### Обязательно прочтите это ######################### # 6. # Данный файл содержит стандартную конфигурацию сервера, которая может       # 7. # использоваться без модификаций для большинства PvPGN установок, но         # 8. # возможно вам потребуется сделать некоторые изменения согласно вашим        # 9. # потребностям. Пустые строки и все, что начинается с символа "#"            # 10. # игнорируется. Заключайте значения для параметров в кавычки, если они       # 11. # содержат пробелы.                                                          # 12. #                                                                            # 13. ############################################################################## 14.   15.   16. ############################################################################## 17. # Пользователь и группа, под которыми будет работать сервер.                 # 18. # Можно использовать имена или числовые идентификаторы (начинающиеся с '#'). # 19. # Если ничего не указано, то сервер работает от пользователя, который его    # 20. # запустил.                                                                  # 21. #----------------------------------------------------------------------------# 22.   23. # Примечание. Пользователь и группа bnetd создается при установке порта. 24. effective_user  = bnetd 25. effective_group = bnetd 26.   27. # effective_user  = #12 28. # effective_group = #20 29.   30. #                                                                            # 31. ############################################################################## 32.   33. ############################################################################## 34. # Настройки хранилища                                                        # 35. # storage_path говорит pvpgn как и откуда/куда читать/писать информацию о    # 36. # пользователях. Доступна 2 драйвера: file и sql                             # 37. #                                                                            # 38. # Формат:                                                                    # 39. # * Для простого (plain) драйвера file:                                      # 40. #  storage_path = file:mode=plain;dir=<path_to_user_files>;clan=<path_to_clan_files>;default=/path/to/default/account # 41. # * Для cdb драйвера file:                                                   # 42. #  storage_path = file:mode=cdb;dir=<path_to_cdb_files>;clan=<path_to_clan_files>;default=/path/to/default/account   # 43. # * Для драйвера sql/sql2:                                                   # 44. #  storage_path = sql:variable=value;...;default=0 (0 is the default uid)    # 45. # or storage_path = sql2:variable=value;...;default=0 (0 is the default uid) # 46. #                                                                            # 47. # Доступные параметры для sql/sql2:                                          # 48. # - "mode" : какая БД будет использоваться (mysql/pgsql/etc..)               # 49. # - "host" : хост, на котором работает БД                                    # 50. # - "port" : порт                                                            # 51. # - "socket" : путь до UNIX сокета                                           # 52. # - "name" : имя базы данных                                                 # 53. # - "user" : пользователь                                                    # 54. # - "pass" : пароль                                                          # 55. # - "default" : UID используемый по умолчанию                                # 56. # - "prefix" : префикс для имен таблиц (по умолчанию "")                     # 57. #                                                                            # 58. # Примеры:                                                                   # 59. # storage_path = file:mode=plain;dir=/usr/local/share/pvpgn/users;clan=/usr/local/share/pvpgn/clans;team=/usr/local/share/pvpgn/teams;default=/usr/local/etc/pvpgn/bnetd_default_user.plain 60. # storage_path = file:mode=cdb;dir=/usr/local/share/pvpgn/userscdb;clan=/usr/local/share/pvpgn/clans;team=/usr/local/share/pvpgn/teams;default=/usr/local/etc/pvpgn/bnetd_default_user.cdb 61. # storage_path = sql:mode=mysql;host=127.0.0.1;name=PVPGN;user=pvpgn;pass=pvpgnrocks;default=0;prefix=pvpgn_ 62. # storage_path = sql:mode=pgsql;host=127.0.0.1;name=pvpgn;user=pvpgn;pass=pvpgnrocks;default=0;prefix=pvpgn_ 63. # storage_path = sql:mode=sqlite3;name=/usr/local/share/pvpgn/users.db;default=0;prefix=pvpgn_ 64. # storage_path = sql:mode=odbc;name=PVPGN;prefix=pvpgn_ 65. #                                                                            # 66. # Внимание!! вы должны изменить ниже параметр "DBlayoutfile" на              # 67. # sql_DB_layout2.conf, если используете драйвер "sql2" !!!                   # 68. # storage_path = sql2:mode=mysql;host=127.0.0.1;name=PVPGN;user=pvpgn;pass=pvpgnrocks;default=0;prefix=pvpgn2_ 69. # storage_path = sql2:mode=pgsql;host=127.0.0.1;name=pvpgn;user=pvpgn;pass=pvpgnrocks;default=0;prefix=pvpgn2_ 70. # storage_path = sql2:mode=sqlite3;name=/usr/local/share/pvpgn/users.db;default=0;prefix=pvpgn2_ 71. # storage_path = sql2:mode=odbc;name=PVPGN;prefix=pvpgn2_ 72. #----------------------------------------------------------------------------# 73.   74. storage_path = sql:mode=pgsql;host=192.168.7.253;name=dbname;user=user;pass=pass;default=0;prefix=pvpgn_ 75.   76. #                                                                            # 77. ############################################################################## 78.   79. ############################################################################## 80. # Секция, описывающее расположение служебных файлов                          # 81. # Параметр pidfile может быть установлен в "".                               # 82. # Используйте полные пути, чтобы избежать проблем!                           # 83. #----------------------------------------------------------------------------# 84.   85. filedir     = /usr/local/share/pvpgn/files 86. reportdir   = /usr/local/share/pvpgn/reports 87. chanlogdir  = /usr/local/share/pvpgn/chanlogs 88. motdfile    = /usr/local/etc/pvpgn/bnmotd.txt 89. issuefile   = /usr/local/etc/pvpgn/bnissue.txt 90. channelfile = /usr/local/etc/pvpgn/channel.conf 91. newsfile    = /usr/local/etc/pvpgn/news.txt 92. adfile      = /usr/local/etc/pvpgn/ad.conf 93. topicfile   = /usr/local/etc/pvpgn/topics.conf 94. ipbanfile   = /usr/local/etc/pvpgn/bnban.conf 95. helpfile    = /usr/local/etc/pvpgn/bnhelp.conf 96. mpqfile     = /usr/local/etc/pvpgn/autoupdate.conf 97. logfile     = /var/log/pvpgn/bnetd.log 98. realmfile   = /usr/local/etc/pvpgn/realm.conf 99. maildir     = /usr/local/share/pvpgn/bnmail 100. versioncheck_file = /usr/local/etc/pvpgn/versioncheck.conf 101. mapsfile    = /usr/local/etc/pvpgn/bnmaps.conf 102. xplevelfile = /usr/local/etc/pvpgn/bnxplevel.conf 103. xpcalcfile  = /usr/local/etc/pvpgn/bnxpcalc.conf 104. pidfile    = /var/run/pvpgn/bnetd.pid 105. ladderdir   = /usr/local/share/pvpgn/ladders 106. command_groups_file = /usr/local/etc/pvpgn/command_groups.conf 107. tournament_file = /usr/local/etc/pvpgn/tournament.conf 108. statusdir   = /usr/local/share/pvpgn/status 109. aliasfile   = /usr/local/etc/pvpgn/bnalias.conf 110. anongame_infos_file = /usr/local/etc/pvpgn/anongame_infos.conf 111. DBlayoutfile = /usr/local/etc/pvpgn/sql_DB_layout.conf 112. supportfile = /usr/local/etc/pvpgn/supportfile.conf 113. transfile   = /usr/local/etc/pvpgn/address_translation.conf 114.   115. fortunecmd  = /usr/games/fortune 116.   117. #                                                                            # 118. ############################################################################## 119.   120.   121. ############################################################################## 122. # Логи                                                                       # 123. #----------------------------------------------------------------------------# 124.   125. # Может быть определено несколько уровней логирования. Каждый уровень 126. # отделяется запятой. Доступные уровни логирования: 127. #   none 128. #   trace 129. #   debug 130. #   info 131. #   warn 132. #   error 133. #   fatal 134. loglevels = fatal,error,warn 135. #loglevels = fatal,error,warn,info 136.   137. #                                                                            # 138. ############################################################################## 139.   140.   141. ############################################################################## 142. # Параметры сервера D2CS                                                     # 143. #----------------------------------------------------------------------------# 144.   145. # Версия этого сервера D2CS (установите в 0, чтобы отключить проверку версий) 146. d2cs_version = 0 147.   148. # Разрешить серверу D2CS зменять имена realm? 149. allow_d2cs_setname = true 150.   151. #                                                                            # 152. ############################################################################## 153.   154.   155. ############################################################################## 156. # Загружаемые файлы                                                          # 157. #----------------------------------------------------------------------------# 158.   159. # Об этих именах файлов сообщается непосредственно клиенту и они должны быть 160. # указаны относительно директории "filedir". 161. iconfile = "icons.bni" 162. war3_iconfile = "icons-WAR3.bni" 163. star_iconfile = "icons_STAR.bni" 164.   165. tosfile = "tos.txt" 166.   167. #                                                                            # 168. ############################################################################## 169.   170.   171. ############################################################################## 172. # Проверка клиента и обновлений                                              # 173. #----------------------------------------------------------------------------# 174.   175. # Это список типов клиентов, которым разрешено подключаться к серверу. 176. # Список должен быть разделен запятой. 177. # all  : all client types allowed (default) 178. # chat : client type "CHAT" allowed (used by some bot software) 179. # dshr : client type Diablo 1 Shareware 180. # drtl : client type Diablo 1 (Retail) 181. # sshr : client type Starcraft Shareware 182. # star : client type Starcraft 183. # sexp : client type Starcraft Broodwar 184. # w2bn : client type Warcraft II Battle.Net Edition 185. # d2dv : client type Diablo 2 186. # d2xp : client type Diablo 2 LOD 187. # war3 : client type Warcraft III (Reign Of Chaos) 188. # w3xp : client type Warcraft III Frozen Throne 189. # 190. # Пример: allowed_clients = war3,w3xp 191. allowed_clients = all 192.   193. # Если эта опция включена, то этап проверки версии клиента будет пропущен. 194. # Работает только с клиентами < 109. Это может оказаться полезным, потому что 195. # в этом случае вам больше не понадобятся файлы IX86AUTH?.MPQ и PMACAUTH?.MPQ. 196. # Учтите, что отключение данной функции повлечет за собой отключение 197. # функции автоматического обновления. 198. # 199. # Если вы выключите данный параметр, то вы должны иметь один или несколько 200. # MPQ файлов. Иначе клиенты будут зависать при первом подключении, потому что 201. # будут пытаться загрузить эти файлы. Проверка версий может быть отключена 202. # только для клиентов с версией ниже 109. Начиная с версии 109 клиенты всегда 203. # делают проверку версий, так как они не функционируют должным образом, если 204. # сервер не запрашивает ее. 205. skip_versioncheck = false 206.   207. # Если вы включили проверку версий, но хотите чтобы клиенты не прошедшие ее 208. # могли подключиться, то включите данный параметр. 209. allow_bad_version = false 210.   211. # Если вы включили проверку версий, но  хотите позволить клиентам 212. # не присутствующим в параметре versioncheck подключаться к серверу, 213. # то включите этот параметр. Если вы не имеете полного файла (прим. о каком 214. # идет речь не понятно) или вас не беспокоят читеры, то это хорошая идея 215. # (включить параметр). 216. allow_unknown_version = true 217.   218. # Здесь определяется как проверять поле exeinfo в файле versioncheck. 219. # Вы можете выбрать между: no match at all [none] (default), 220. # exact match [exact], exact case-sensitive match [exactcase], dumb wildcard 221. # match [wildcard], and parsed value comparison [parse]. 222. # Учтите: [parse] требует функцию mktime(), которая может быть не в каждой 223. # системе. 224. version_exeinfo_match = none 225.   226. # Если выше вы выбрали [parse], то это допуск, на который время может различаться. 227. # Время указывается в секундах. Если 0, то данная функция выключена. 228. version_exeinfo_maxdiff = 0 229.   230. #                                                                            # 231. ############################################################################## 232.   233.   234. ############################################################################## 235. #  Временные параметры                                                       # 236. #----------------------------------------------------------------------------# 237.   238. # Время в секундах между синхронизациями с БД учеток пользователей, 0 - ждать вечно. 239. usersync  = 300 240. # Number of seconds of inactivity before file is unloaded from memory. 241. # (only checked during account file updates) 242. userflush = 1200 243. # Number of users checked for updates at once. Higher values make sense if you 244. # either have very fast hardware or you don't have many number of accounts. 245. # Lower values make sense if you have very high CPU usage on the system you run 246. # the server (dont make it too low or your system will save accounts continously). 247. # Modify this value ONLY if you know what you are doing!! 248. userstep = 100 249.   250. # Как часто проверять задержки канала до клиента (секунды). 251. latency = 600 252.   253. # Как часто проверять жив ли клиент (секунды). 254. nullmsg = 120 255.   256. # Amount of time to delay shutting down server in seconds. 257. shutdown_delay = 300 258. # Amount of time delay period is decremented by either a SIGTERM or SIGINT 259. # (control-c) signal in seconds. 260. shutdown_decr = 60 261.   262. # Как часто проверять забаненых пользователей на предмет окончания этого самого бана (секунды). 263. #ipban_check_int = 30 264.   265. #                                                                            # 266. ############################################################################## 267.   268.   269. ############################################################################## 270. # Настройки политик                                                          # 271. #----------------------------------------------------------------------------# 272.   273. # Если вы не хотите разрешать людям создавать учетки на вашем сервере, то 274. # установите этот параметр в false. 275. new_accounts = true 276.   277. # Максимальное количество учеток, которое возможно создать на этом сервере. 278. # По умолчанию 0, что значит - без ограничений. 279. max_accounts = 0 280.   281. # Запретит вход на сервер под одной учеткой несколько раз одновременно. 282. kick_old_login = true 283. #kick_old_login = false 284. # With no passwords, this is bad to have enabled --NonReal 285.   286. # Параметр load_new_account упразднен, его функционал всегда включен в PvPGN 287.   288. # Если пользователь создает новый канал, то добавлять его автоматом или спросить 289. # их начала (кого их, х/з). 290. ask_new_channel = true 291.   292. # Should a game report be written for every game played or just ladder 293. # games? 294. #report_all_games = false 295. report_all_games = true 296.   297. # Should Diablo I/II reports be written?  There are no winners/losers. 298. report_diablo_games = false 299.   300. # Скрывать ли запароленные игры в списке игр? 301. hide_pass_games = true 302.   303. # Скрывать ли уже запущенные игры в списке игр? (полезно для очень загруженных серверов) 304. hide_started_games = true 305.   306. # Скрывать ли не основные каналы в списке каналов? 307. hide_temp_channels = true 308.   309. # Разрешить расширенные команды /-commands? (of course!) 310. extra_commands = true 311.   312. # Считать отключение от игры за поражение? 313. # (Turning this on will override the user's choice in ladder games!) 314. disc_is_loss = false 315.   316. # List additional game types to be counted as ladder games 317. # Curently allowed types: topvbot, melee, ffa, oneonone 318. # Example: ladder_games = "topvbot,oneonone" 319. ladder_games = "topvbot,melee,ffa,oneonone" 320.   321. # If additional game types are configured (see above) to be counted as ladder 322. # games then this setting configures a game name prefix to make only games 323. # which match this game name prefix be counted as ladder. This allows to 324. # still have normal games of the game types configured with "ladder_games" 325. # directive. However if this setting is commented or "" then ALL games 326. # which match the game types configured with "ladder_games" are to be 327. # considered as ladder games. The prefix checking is CASE SENSITIVE! 328. # Example: ladder_prefix = "ldr_" 329. ladder_prefix = "" 330.   331. # Разрешить всем пользователям использовать команды /con и /connections? 332. enable_conn_all = true 333.   334. # Скрыть IP адрес от обычных пользователей (from /con, /games, /gameinfo, /netinfo) 335. hide_addr = false 336.   337. # Писать в файлы в chanlogdir сообщения в закрытых каналах. 338. # (see channels.list for public channels) 339. chanlog = false 340.   341. # Использовать квоту для каналов? 342. quota = yes 343.   344. # Следующие параметры предназначены для ограничения посылаемых сообщений. 345. # 346. # Как много строк принимать за время quota_time (секунды)? 347. # (The default should allow 5 lines in 5 seconds, 348. # longer time periods allow "bursts" of traffic before the quota is full.) 349. quota_lines = 5     # must be between 1 and 100 lines 350. quota_time = 5      # must be between 1 and 60 seconds 351. # "virtual wrapping", so long lines count as multiple lines 352. quota_wrapline = 40 # must be between 1 to 256 chars 353. # absolute maximum characters allowed in a line 354. quota_maxline = 200 # must be between 1 to 256 chars 355. # 356. # How many lines do you accept in quota_time seconds before user is 357. # disconnected? 358. # (According to Jung-woo, Dobae is a Korean term for flooding the game server... 359. # it originally meant "to paint the wallpaper on a new or refurbished house"). 360. # If it less than or equal to quota_lines, there is no warning before 361. # disconnection so don't set this too low. 362. quota_dobae = 10     # must be between 1 and 100 lines 363.   364. # Mail support 365. mail_support = true 366. mail_quota = 5 367.   368. # Channel logging message 369. log_notice = "*** Please note this channel is logged! ***" 370.   371. # Банить за превышение количества неудачных попыток входа. 372. # Fails required to get ip banned (0 - выключить данную возможность) 373. passfail_count = 5 374.   375. # Время бана в секундах 376. passfail_bantime = 300 377.   378. # Максимальное количество пользователей в закрытом канале (0 - без ограничений) 379. maxusers_per_channel = 0 380.   381. #                                                                            # 382. ############################################################################## 383.   384.   385. ############################################################################## 386. # Параметры учетных записей                                                  # 387. #----------------------------------------------------------------------------# 388.   389. # Давать имена файлам (которые хранят данные о пользователе) в виде идентификатора или имени игрока? 390. savebyname = true 391.   392. # Сохранять данные учетки при отключении 393. sync_on_logoff = true 394.   395. # How man rows should the account lookup hash table have?  Servers with 396. # more accounts should use a larger table for better performance. 397. hashtable_size = 61 398.   399. # Per default, only alphanumerical symbols are allowed in account names 400. # with this variable you can add some extra symbols to be allowed 401. # but be warned - that some of them might cause trouble - at least with 402. # savebyname=true (some symbols are forbidden in filenames or might cause 403. # you real trouble - plz neither allow wildcard symbols like '*' or '?'. 404. # Path delimiters like '/' or '\' are hardcoded filtered and can't be allowed. 405. # Also note that allowing the '.' might cause u some headache on win32 systems. 406. # You have been warned - the rest is up to you. 407. # default setting is "-_[]" as it was previous versions 408. account_allowed_symbols = "-_[]" 409.   410. # This setting affects users that login with their uid rather than their 411. # username. If set to true their displayed username will be forcefully 412. # converted to their registered account name. 413. account_force_username = false 414.   415. # Максимальное количество пльзователей  в списке друзей. 416. # default setting is 20 417. max_friends = 20 418.   419. #                                                                            # 420. ############################################################################## 421.   422.   423. ############################################################################## 424. # Tracking server info                                                       # 425. #----------------------------------------------------------------------------# 426.   427. # Set track=0 to disable tracking.  Any other number will set number 428. # of seconds between sending tracking packets. This is OFF by default. 429. #track = 0 430. track = 60 431. # 10 minutes 432.   433. # Tracking server(s) 434. # Use a comma delimited list of hostnames with optional UDP port numbers 435. # after colons. (port 6114 is the default for the newer tracking protocol) 436. #trackaddrs = "track.bnetd.org,localhost:9999" 437. #trackaddrs = "track.pvpgn.org" 438.   439. # Change these to match your system, for example: 440. location = "Russia" 441. description = "Rock" 442. url = "http://www.info-x.org" 443. contact_name = "Nekit" 444. contact_email = "[email protected]" 445.   446. #                                                                            # 447. ############################################################################## 448.   449.   450. ############################################################################## 451. # Server network info                                                        # 452. #----------------------------------------------------------------------------# 453.   454. # Имя сервера (По умолчанию: "PvPGN Realm") 455. #servername = "PvPGN Realm" 456.   457. # Максимальное количество подключений к серверу (минимум 32). 458. max_connections = 100 459.   460. # Максимальное количество одновременных попыток войти на сервер (0 - без ограничений). 461. max_concurrent_logins = 0 462.   463. # Разрешить TCP посылать keepalive. 464. use_keepalive = true 465.   466. # Максимальное количество подключений с одного IP (0 - без ограничений) 467. max_conns_per_IP = 0 468.   469. # This is a comma delimited list of hostnames that the server should 470. # listen on.  It might be useful to make an internal-only server on a 471. # gateway machine for example.  If the list is not set or if it has a 472. # entry with no host component, the server will bind to that port on all 473. # interfaces. 474. #servaddrs = ":9999" 475. #servaddrs = "myinternalname.some.com,localhost" 476. servaddrs = ":" # default interface (all) and default port (6112) 477.   478. # Don't change these unless you really need to!  You will need to run a proxy 479. # or modify the clients.  Also note that these will not change when simply 480. # sending a HUP signal to the server; they are only read on startup. 481.   482. # This is the port the server send the UDP test packets to by default. 483. # Setting it to zero makes the server use the same port as the TCP connection 484. # comes from. Newer clients can override this setting on a per connection 485. # basis. 486. #udptest_port = 6112 487.   488.   489. # W3 Play Game router address. Just put your server address in here 490. # or use 0.0.0.0:6200 for server to bind to all interfaces, 491. # but make sure you set up w3trans if you do. 492. w3routeaddr = "0.0.0.0:6200" 493.   494. # w3routeshow has been removed. 495. # see the address_translation.conf for translating the w3route ip for local networks 496.   497. # initkill_timer sets up a periodic timer on init/defer class connections 498. # this should detect and clean up stale connections to your server 499. initkill_timer = 120 500.   501. #                                                                            # 502. ############################################################################## 503.   504. ############################################################################## 505. # Westwood Online (WOL) configuration                                        # 506. #----------------------------------------------------------------------------# 507.   508. # NOTE: WOL support is still experimental! 509.   510. # This specifies the addresses where IRC connections should be accepted. See 511. # the description of servaddrs for formatting information. Leave this field 512. # blank if you do not want to accept IRC connections.  If the port is not 513. # specifed then 4005 will be used. Note: DO NOT SET THE PORT TO ANYTHING OTHER 514. # THEN 4005, WOL WILL FAIL IF YOU DO! 515. #woladdrs = ":4005" 516.   517. # Just leave these as default (unless you know the timezone, longitiude and latitude 518. # of your server 519. woltimezone = "-8" 520. wollongitude = "36.1083" 521. wollatitude = "-115.0582" 522.   523. #                                                                            # 524. ############################################################################## 525.   526. ############################################################################## 527. # Настройки IRC                                                              # 528. #----------------------------------------------------------------------------# 529.   530. # Учтите: поддержка IRC находится на стадии тестирования! 531.   532. # This specifies the addresses where IRC connections should be accepted. See 533. # the description of servaddrs for formatting information. Leave this field 534. # blank if you do not want to accept IRC connections.  If the port is not 535. # specified then 6667 will be used. 536. #ircaddrs = ":6667" 537.   538. # This is the IRC network name. If this is not specified then the default of 539. # "PvPGN" will be used. 540. #irc_network_name = "PvPGN" 541.   542. # This is the hostname used for IRC connections. Set this to your 543. # hostname, if the automatic detection doesn't correctly. 544. #hostname = "none" 545.   546. # Set this to the desired IRC connection timeout in seconds. 547. #irc_latency = 180 548.   549. #                                                                            # 550. ############################################################################## 551.   552.   553. ############################################################################## 554. # Настройки Telnet                                                           # 555. #----------------------------------------------------------------------------# 556.   557. # This specifies the addresses where telnet connections should be accepted. 558. # See the description of servaddrs for formatting information. Leave this 559. # field # blank if you do not want to accept telnet connections.  If the port 560. # is not specifed then 23 will be used. 561. #telnetaddrs = ":23" 562. telnetaddrs = "" 563.   564. ############################################################################### 565. # war3 ladder textual output                                                  # 566. #-----------------------------------------------------------------------------# 567. # this is for all the guys, that want Warcraft 3 ladder, but don't want their 568. # server to run with MySQL support. 569. # For each ladder (solo, team, ffa, at) a corresponing file is created, 570. # so it's easy to build your ladder pages with them 571.   572. # the following value determines, at which rate, these files are created 573. # set to 0 if you don't want or need these files 574. war3_ladder_update_secs = 300 575.   576. # jfro's latest ladder is based on XML... so we can switch to XML output of ladder 577. # on demand 578. XML_output_ladder = false 579.   580. ############################################################################### 581. # server status textual output                                           # 582. #-----------------------------------------------------------------------------# 583. # This is for writing status of the server in an attempt to see number of user 584. # on line actually, and games/chans. 585. # This is store in file var\status\warcraft3.dat as a *.ini format. 586. # Shouldn't be so hard in php to create dynamic website using this content. 587.   588. # the following value determines, at which rate, these files are created 589. # set to 0 if you don't want or need these files 590. output_update_secs = 60 591.   592. # jfro's latest ladder is based on XML... so we can switch to XML output of ladder 593. # on demand. Maybe we should set update interval bigger cause XML output version 594. # is much more verbose than the standard output 595. XML_status_output = false 596.   597. ############################################################################### 598. # Параметры кланов                                                            # 599. #-----------------------------------------------------------------------------# 600.   601. # Time in hours for a new member of clan to be a newer(Peon icon, cannot promote to Grunt) 602. # default value 168(7 days). If set to 0, all new members could be promote in no time 603. clan_newer_time = 0 604.   605. # max members count allowed in a clan, set between 10 and 100, default 50. 606. clan_max_members = 50 607.   608. # Default clan channel status when create a clan, 1 for private, 0 for public 609. clan_channel_default_private = 0 После настройки помещаем демон bnetd в автозагрузку и запускаем его: 1. # echo 'bnetd_enable="YES" >> /etc/rc.conf' 2. # service bnetd start Проверяем - запустился ли сервис: 1. # sockstat -4 -l | grep bnet 2. bnetd    bnetd      15105 4  tcp4   *:6112                *:* 3. bnetd    bnetd      15105 5  udp4   *:6112                *:* 4. bnetd    bnetd      15105 6  tcp4   *:6200                *:* На данном этапе настройка сервера PvPGN завершена. Осталось на стороне клиентов прописать адрес данного Battle.net сервера. Для этого есть специальные программы, которые облегчают данный процесс. Парочку таких я прикрипил к статье. Теперь о проблемах, которые возникли в процессе эксплуатации данного сервера. Starcraft подключается к серверу без каких-либо дополнительных приложений, но возникает проблема, когда игроки WAN и LAN пытаются играть вместе. Starcraft жутко начинает лагать. Описание и решение данной проблемы можно найти по ссылке, которую я указал в полезных ссылках. С Warcraft 3 немного веселее - для того, чтобы он работал с данным сервером необходим загрузчик, который я так же прикрепил к статье. Он подходит для версий игры 1.22 и выше, я проверял его на версии 1.26. Пару слов про создание первого администратора в PvPGN: после создания учетной записи на сервере, нужно подключиться к базе данных и в таблице pvpgn_bnet у нужного пользователя в колонке auth_admin установить значение в true. Прикрепленные файлы вс, 21/07/2013 - 11:06 Добавить комментарий Этот вопрос задается для того, чтобы выяснить, являетесь ли Вы человеком или представляете из себя автоматическую спам-рассылку. Что из перечисленного (Doom3, IE, Bash, Mutt, ZFS) является почтовым клиентом?
__label__pos
0.930415
Date: Sat, 13 Aug 2022 04:48:15 +0000 (UTC) Message-ID: <[email protected]> Subject: Exported From Confluence MIME-Version: 1.0 Content-Type: multipart/related; boundary="----=_Part_642111_1353971616.1660366095405" ------=_Part_642111_1353971616.1660366095405 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Content-Location: file:///C:/exported.html ServiceMixProposal ServiceMixProposal PROJECT PROPOSAL = =20 ServiceMix: A JBI Container and C= omponent Suite =20 A JBI based ESB as a sub project of Geronimo. =20 RATIONALE =20 The Geronimo project is currently using ServiceMix as its JBI container which is integrated into the Geronim= o deployer. =20 Currently ServiceMix is hosted at= Codehaus, has a stable codebase and a large and vibrant community. =20 This proposal moves the existing Serv= iceMix community to Apache as a sub-project of Geronimo so it can bette= r integrate with the rest of the Geronimo and other Apache communities like= Axis, Synapse and Tuscany and to simplify the work of the community with t= he TCKs. =20 INITIAL SOURCE =20 The initial source comes from the Ser= viceMix project at Codehaus. =20 Note that currently the ServiceMix uses some dependencies which Apache projects are not allowed to use, like= LGPL and CDDL, so only those modules in ServiceMix which are dependent on Apache compatible libraries will be = included in the Apache ServiceMix pr= oject. =20 Modules to be included are all of them apart from modules which depend o= n *GPL or proprietary code. We will seek clarification on exact licenses we= can use (like MIT, CDDL) during the incubation process and remove any code= using any non-compliant licenses =20 RESOURCES TO BE CREATED<= /h1>=20 =20 CRITERIA =20 Meritocracy: =20 The ServiceMix community is a hea= lthy meritocracy with plenty of developers. =20 Community: =20 The ServiceMix community is vibra= nt - see the mailing lists. =20 http://servicemix.org/Mailing+Lists =20 e.g. in the last 3 months there has been over 500 mails on the user list= . =20 Core Developers: =20 The core developers are a diverse group of developers many of which are = already very experienced open source developers. There is at least one Apac= he Member together with a number of other existing Apache Committers along = with folks from various companies. =20 http://servicemix.org/Team =20 Alignment: =20 ServiceMix is already an integral= part of Geronimo. The hope would be to build stronger ties with Axis and S= ynapse as well. =20 License =20 ServiceMix is already licensed un= der Apache License 2.0 =20 AVOIDING THE WARNING = SIGNS =20 Orphaned products: =20 ServiceMix is still a part of Ger= onimo and under heavy active development. =20 Inexperience with= open source: =20 Most of the comitters have a proven track record in open source at Apach= e and Codehaus. =20 Homogenous developers:<= /h2>=20 There are developers from various companies: Datsul, EnvoiSolutions, IBM, LogicBlaze, Mergere, MortBay, <= a class=3D"unresolved" href=3D"#">UnitySystems, Virtuas =20 See the team page for more detail =20 http://servicemix.org/Team =20 No ties to other= Apache products: =20 ServiceMix is already part of Ger= onimo and intends to be a sub-project of Geronimo. =20 A fascination= with the Apache brand: =20 We are moving to Apache to grow closer ties with the Geronimo project an= d other Apache projects like Axis and Synapse. =20 Issues =20 The only real issue with ServiceMix is figuring out what licenses are actually definitely allowed by Apache = projects; once we know we can remove any code that uses those licenses. Cur= rent licenses we are unsure about are as follows (all other dependencies ar= e BSD/ASL or MIT licenses). =20 CDDL =20 =20 The complete list of dependencies and their licenses are all documented = in this file =20 =20 COMMITTERS =20 Current Apache Committers =20 =20 Non-Apache Committers =20 =20 PROPOSED APACHE SPONSOR= =20 =20 CHAMPION =20 ------=_Part_642111_1353971616.1660366095405--
__label__pos
0.564302
C++ Programming Tutorial       Graphics Programming Quadratic Surfaces Draw a Sphere using Ellipses Draw a Sphere using Parametric Equations Draw an Ellipsoid using Parametric Equations Character Generation Urdu Alphabets using Stroke Method Urdu Alphabets using Matrix Method Arc Circular Arc using Trigo. Method Elliptical Arc using Trigo. Method General Programs C-Curve of nth order K-Curve of nth order Cubic Bezier Curve Bezier Curve of nth degree Scanfill algorithm Boundary Fill - 8 Connected Point Flood fill algorithm Rotate About Origin Rotate about reference point Scaling about origin Scaling about reference point Polyline translation Reflection in x axis Reflection in y Axis Reflection on any line Midpoint Circle Drawing Bresenhams Line Algorithm (BLA) Generate a pattern Draw a Chess Board Draw a Luddo Board Deterministic Finite Automation for identifier Kurskals algo - Minimum Cost Spanning Tree Windows Programs Checkbox like windows Simple windows & buttons Moving message box like windows Text box Graphical Rep. of tower of hanoi Graphical menu - operate it using arrow keys Text animation Line Line using Parametric equations Line-Cartesian Slope-Intercept Equation simple imp Line using Cartesian Slope-Intercept Equation Line - BLA - slopes negative and greater than 1 Line - BLA - slopes negative and less than 1 Line - BLA - slopes positive and greater than 1 Line - BLA - slopes positive and less than 1 DDA line drawing algorithm Bresenham line drawing algorithm Cohen sutherland Line clipping algo. Line Styles Different kinds of Dashed Lines Different kinds of Thick Lines Polygons Draw a Polygon Draw a Triangle Draw a Rectangle Sutherland-Hodgeman Polygon Clipping Algo Circle Circle using Trigo. Method Circle using Polynomial Method Circle using Bresenhams Circle algo. Circle using MidPoint Circle algo. Ellipse Ellipse using Polynomial Method Ellipse using Trigo. Method Ellipse using MidPoint Ellipse algo. 2D Transformations Translation Transformation Scaling Transformation Scaling Trans along a Fixed Point Scaling Trans along Arbitrary Direction Rotation Transformation Rotation Trans along a Pivot Point Reflection tran of x-axix, y-axis and w.r.t origin Reflection tran of line y=x and y=-x X-Direction Shear Transformation Y-Direction Shear Transformation 2D Viewing - Clipping Window-to-Viewport Coordinate Tran Point Clipping Algorithm Cohen-Sutherland Line Clipping Algo Cohen-Sutherland MidPoint Subdivision Line Nicol Lee Nicol algo. for Line Clipping Liang-Barsky Line Clipping Algo Window-to-Viewport Transformaton None-or-All String Clipping Strategy None-or-All Character Clipping Strategy 3D Object Representations 3D object using Polygon-Mesh Rep. 3D object - Translational Sweep Representatiom 3D object - Rotational Sweep Rep. 3D Transformations 3D Rotation Trans along x-axis 3D Rotation Trans along y-axis 3D Rotation Trans along z-axis 3D Reflection Trans along xy-plane 3D Reflection Trans along yz-plane 3D Reflection Trans along zx-plane 3D Shearing Trans along x-axis 3D Shearing Trans along y-axis 3D Shearing Trans along z-axis Bezier Curves - Surfaces 3D Cubic Bezier Curve 3D Bezier Curve of nth degree 3D Piece-Wise Bezier Curve of nth degree 3D Bezier Surface for MxN control points Projection 3D objects - Standard Perspective Projection 3D obj - Arbitrary Plane and Center of Projection 3D objects using General Perspective Projection 3D obj-Orthographics Proje Parallel onto xy-plane 3D obj-Cavalier Oblique Parallel prj-xy-plane 3D obj-Cabinet Oblique Parallel prj - xy-plane Fill Algorithm or Area Filling Geometric shapes using Boundary Geometric shapes - Boundary - Linked List Geometric shapes using Flood Geometric shapes - Flood - Linked-List Polygon using Scan Line Polygon Rectangle using Scan-Line Rectangle Circle using Scan-Line Circle Circle - Scan-Line Circle - Polar Coordinates     # include <iostream.h> # include <graphics.h> # include <conio.h> # include <math.h> void show_screen( ); void apply_x_direction_shear(const int,int [],const float); void multiply_matrices(const float[3],const float[3][3],float[3]); void Polygon(const int,const int []); void Line(const int,const int,const int,const int); int main( ) { int driver=VGA; int mode=VGAHI; initgraph(&driver,&mode,\"..\\\\Bgi\"); show_screen( ); int polygon_points[10]={ 270,340, 270,140, 370,140, 370,340, 270,340 }; setcolor(15); Polygon(5,polygon_points); setcolor(15); settextstyle(0,0,1); outtextxy(50,415,\"*** Use Left and Right Arrow Keys to apply X-Direction Shear.\"); int key_code_1=0; int key_code_2=0; char Key_1=NULL; char Key_2=NULL; do { Key_1=NULL; Key_2=NULL; key_code_1=0; key_code_2=0; Key_1=getch( ); key_code_1=int(Key_1); if(key_code_1==0) { Key_2=getch( ); key_code_2=int(Key_2); } if(key_code_1==27) break; else if(key_code_1==0) { if(key_code_2==75) { setfillstyle(1,0); bar(40,70,600,410); apply_x_direction_shear(5,polygon_points,-0.1); setcolor(12); Polygon(5,polygon_points); } else if(key_code_2==77) { setfillstyle(1,0); bar(40,70,600,410); apply_x_direction_shear(5,polygon_points,0.1); setcolor(10); Polygon(5,polygon_points); } } } while(1); return 0; } //--------------------- apply_x_direction_shear( ) --------------------// void apply_x_direction_shear(const int n,int coordinates[],const float Sh_x) { for(int count=0;count<n;count++) { float matrix_a[3]={coordinates[(count*2)], coordinates[((count*2)+1)],1}; float matrix_b[3][3]={ {1,0,0} , {Sh_x,1,0} ,{ 0,0,1} }; float matrix_c[3]={0}; multiply_matrices(matrix_a,matrix_b,matrix_c); coordinates[(count*2)]=(matrix_c[0]+0.5); coordinates[((count*2)+1)]=(matrix_c[1]+0.5); } } /************************************************************************/ //---------------------- multiply_matrices( ) ------------------------// /************************************************************************/ void multiply_matrices(const float matrix_1[3], const float matrix_2[3][3],float matrix_3[3]) { for(int count_1=0;count_1<3;count_1++) { for(int count_2=0;count_2<3;count_2++) matrix_3[count_1]+= (matrix_1[count_2]*matrix_2[count_2][count_1]); } } //----------------------------- Polygon( ) ----------------------------// void Polygon(const int n,const int coordinates[]) { if(n>=2) { Line(coordinates[0],coordinates[1], coordinates[2],coordinates[3]); for(int count=1;count<(n-1);count++) Line(coordinates[(count*2)],coordinates[((count*2)+1)], coordinates[((count+1)*2)], coordinates[(((count+1)*2)+1)]); } } //------------------------------- Line( ) -----------------------------// void Line(const int x_1,const int y_1,const int x_2,const int y_2) { int color=getcolor( ); int x1=x_1; int y1=y_1; int x2=x_2; int y2=y_2; if(x_1>x_2) { x1=x_2; y1=y_2; x2=x_1; y2=y_1; } int dx=abs(x2-x1); int dy=abs(y2-y1); int inc_dec=((y2>=y1)?1:-1); if(dx>dy) { int two_dy=(2*dy); int two_dy_dx=(2*(dy-dx)); int p=((2*dy)-dx); int x=x1; int y=y1; putpixel(x,y,color); while(x<x2) { x++; if(p<0) p+=two_dy; else { y+=inc_dec; p+=two_dy_dx; } putpixel(x,y,color); } } else { int two_dx=(2*dx); int two_dx_dy=(2*(dx-dy)); int p=((2*dx)-dy); int x=x1; int y=y1; putpixel(x,y,color); while(y!=y2) { y+=inc_dec; if(p<0) p+=two_dx; else { x++; p+=two_dx_dy; } putpixel(x,y,color); } } } //-------------------------- show_screen( ) ---------------------------// void show_screen( ) { setfillstyle(1,1); bar(184,26,460,38); settextstyle(0,0,1); setcolor(15); outtextxy(5,5,\"******************************************************************************\"); outtextxy(5,17,\"*-**************************************************************************-*\"); outtextxy(5,29,\"*-------------------- -------------------*\"); outtextxy(5,41,\"*-**************************************************************************-*\"); outtextxy(5,53,\"*-**************************************************************************-*\"); setcolor(11); outtextxy(194,29,\"X-Direction Shear Transformation\"); setcolor(15); for(int count=0;count<=30;count++) outtextxy(5,(65+(count*12)),\"*-* *-*\"); outtextxy(5,438,\"*-**************************************************************************-*\"); outtextxy(5,450,\"*------------------------- -------------------------*\"); outtextxy(5,462,\"******************************************************************************\"); setcolor(12); outtextxy(229,450,\"Press any Key to exit.\"); } Related Post: 1. Program to illustrate the difference among public, protected and private inheritance 2. Program to interchange the values of two int , float and char using function overloading 3. Program to illustrate array of objects in classes 4. Program that creats a 3D solid object using Translational Sweep Representatiom Method 5. Program to show the implementation of Binary Search Tree as Sets 6. Program that reads a number and prints even if the number is even and prints odd if the number is odd. 7. Program which shows content of a given 2D array 8. Problem you will be analyzing a property of an algorithm whose classification is not known for all possible inputs 9. Program of Flood fill algorithm 10. Program to show the implementation of Liang-Barsky Line Clipping Algorithm 11. Program using cout statement to display in single line 12. Program to illusrate data conversion user defined data types using functions 13. Program of circular link list 14. Program to create a stack using static memory allocation 15. Program to estimate the value of First Derivative of the function at the given points from the given data using Central Difference Formula of order 4 16. PROGRAM TO IMPLEMENT RECURSIVE DESCENT PARSER 17. Program to draw a line using Bresenhams Line Algorithm (BLA) for lines with slopes negative and greater than 1 18. Program to draw an ellipse using MidPoint Ellipse Algorithm 19. To parse a string using First and Follow algorithm and LL-1 parser 20. Program to illustrate the implementation of arrays as a Linear Queue ( in graphics )     Didn't find what you were looking for? Find more on Program to illustrate the implementation of X-Direction Shear Transformation
__label__pos
0.999528
5 Steps and under 30 minutes to deploy ARM Templates via Octopus Deploy Octopus Deploy have been really up in the game of constantly adopting to the cloud Platform. Here is one of the example of deploy azure resource manager templates via octopus deploy. Authoring a resource manager template in visual studio, source control in Git based visual studio team services , build using the VSTS build system with the hosted agent and deploy the infrastructure via octopus deploy. Pre-requisites 1. Azure basic concepts 2. Octopus Deploy 3. Basic understand of JSON 4. Visual Studio Team Systems 5. Azure PowerShell Here you go, the five steps 1. Create the azure subscription and add accounts in octopus deploy. 2. Author using visual studio and source control in VSTS 3. Build and Package in VSTS 4. Create Octopus Project and Configure variables 5. Deploy and Test the template Step 1 If you are a msdn subscriber then you will get free credits and you can create a azure account from www.azure.com or there is a pay as you go account available to use. Note: When resources are not in use, always deallocate, delete the resource if not scale down. So your operational cost is less. Add the subscription as account in Octopus as shown below Step 2 we are going to author azure resource manager template to create the infrastructure to host the azure websites. 1. Create a Resource group Use the available library to create the resource group https://library.octopusdeploy.com/step-template/actiontemplate-creates-an-azure-resource-group 2. Create the azure resource group Deploy project in visual studio Follow this documentation, to get started https://azure.microsoft.com/en-gb/documentation/articles/resource-group-authoring-templates/ 3. Added the nuspec file to the deploy project 4. This template belongs to the deploy project which is available in the visual studio. Which ends with the file extension .dproj. Sample snippet of the template 5. You can find lot of azure quick start templates from this link https://github.com/Azure/azure-quickstart-templates 6. Octopus Deploy preferred source is nuget package , so let’s add the nuspec file to package the template and the parameters file. 7. Commit all the changes to the source control. Step 3 Now we have the source code for our infrastructure in VSTS Git based source control which provides nice intergration with visual studio. 1. Creating a new build definition to build and package the template available in source control, Create new build definition Update the build number format that a nuget package manager can accept Add the visual studio build step Choose the nuget packager step followed by nuget publisher step to publish the packages into vsts hosted package manager. Reference article. 2. Now, queue the build to publish the package. Step 4 1. Create the octopus’s projects 2. Create all the required variables in this case as shown below 3. Add the step to create the resource group 4. Add the step to deploy the azure resource manager templates Note: This steps will also replace the octopus variables defined in the parameters and template files before the deployment. Step 5 Once all the variables are defined and scope , we are ready to create a release then deploy the infrastructure to the chosen Microsoft azure account. Login to the portal to check if the resource are available or use the azure PowerShell cmdlets to validate the existence of the new resources. Reference below There are few key takeaways and be aware of 1. First thing, check If you have appropriate version of azure PowerShell installed else use the https://github.com/OctopusDeploy/Library/pull/395 2. Make sure the nuspec files section points to the correct build output directory 3. When adding octopus variable double quotes for a string and just octopus variable for a integer type variables 4. Choose the appropriate type of deployment you need it can be either one incremental or complete. 5. You can use the same template for multi-tenant infrastructure provision as well. This will be detailed in the upcoming posts. Hope you liked this article. I’m always looking for feedback, please provide one so that I can provide with better content. Have a great day !!! Leave a Reply This site uses Akismet to reduce spam. Learn how your comment data is processed.
__label__pos
0.8072
Advertisement There’s no doubt that technological revolution, such as the internet or smartphones, has made our lives easier. However, this convenience comes with a cost. For instance, spy equipment that was only available to private detectives a few decades ago can now be easily ordered online by anyone. Regardless of this, you want to feel peace of mind and a sense of security in your home or even in your office room. You certainly don’t want others with evil intentions to take advantage of you, whether related to your personal or work life. Therefore, if you’re on the hunt for ways to protect yourself from illegal and unethical spying, keep reading this article! Smartphone Spying Your smartphone is just more than a “phone”. You use it for online banking, to save passwords, log in to your social media accounts, order food, shop online, and stay connected with your loved ones. Therefore, this can be an excellent target for spies to keep an eye on you and retrieve your confidential and personal information. A spy can install a spying app on your smartphone to track your location, calls, emails, text messages, photos, and videos. It may not be visible on the interface. Hence, it may be pretty hard for you to detect it. How to Prevent Smartphone Spying? It’s always better to be safe than sorry. To prevent smartphone spying in the first place, you should never allow someone else to use your phone in your absence. When unlocking your phone, you should pay attention to your surroundings to ensure no one gets your password. Using a strong password for your phone is essential to make it almost impossible for others to guess it. How to Detect and Deal with Smartphone Spying? It’s important to consider if your phone has been behaving strangely lately. For instance, pay attention to unexpected activity like increased data usage, or random smartphone waking. If you detect someone spying on your smartphone, you must immediately install robust antivirus software and scan your phone for viruses or malicious apps. It may easily help you detect and remove it. If your issue still remains unresolved, you may have to factory reset your phone. Desktop Spying Another common way spies monitor your activities and eavesdrop on your conversations is through your computer or laptop. They can, again, install a remote access application to view all your desktop activity. In addition, keyloggers may help them track your keystrokes to know your essential passwords and get access to your accounts. Sending malware to your computer may also allow them to hack your system. How to Prevent Desktop Spying? You should never leave your computer unattended. If you have to leave it, lock it with a strong password. It’s also vital to never let anyone use your computer as an administrator because you never know if they may install a malicious app on your computer. Advertisement You should keep an eye on your program list on the computer, which may help indicate a strange app. How to Detect Desktop Spying? If there’s some kind of spyware on your computer, it will start behaving weirdly. For instance, you may notice that your computer has become sluggish, and it keeps crashing. Furthermore, it may start showing you random error messages and multiple popups. These are good indicators of desktop spying. Installing efficient antivirus software will not only prevent any threat to your computer down the road but recommend and help you remove infected programs or files. Spying Devices If not the ways listed above, a spy may use other ways to keep an eye on your activities, using spying devices. Here are the most common ones: GPS Devices To track your location 24/7, GPS devices can be placed anywhere on your car, such as inside the bumper or under the grill. Since these devices use RF signals, you can use an RF detector to scan your car for such devices or physically search the car. Cameras and Microphones – Your office room or your house may be bugged to listen to your conversations or to monitor you in real-time. Cameras and microphones usually come concealed in a decor piece such as a lamp, clock, or wall picture. However, since they are tiny, they may be hidden anywhere in the room. To detect cameras and microphones it’s better to turn off the lights and take a good look to see if there’s tiny red or white light visible that indicates these devices are in use. You can also use a torch and assess if the lens has any reflection or use specialized equipment that detects cameras and microphones. Nevertheless, you can keep a portable and robust RF detector with you to accurately detect such devices and give you peace of mind.  Loading... LEAVE A REPLY Please enter your comment! Please enter your name here two − 1 =
__label__pos
0.50924
1.27.0[][src]Function core::arch::x86_64::_mm_shuffle_epi8 pub unsafe fn _mm_shuffle_epi8(a: __m128i, b: __m128i) -> __m128i This is supported on x86-64 and target feature ssse3 only. Shuffles bytes from a according to the content of b. The last 4 bits of each byte of b are used as addresses into the 16 bytes of a. In addition, if the highest significant bit of a byte of b is set, the respective destination byte is set to 0. Picturing a and b as [u8; 16], _mm_shuffle_epi8 is logically equivalent to: fn mm_shuffle_epi8(a: [u8; 16], b: [u8; 16]) -> [u8; 16] { let mut r = [0u8; 16]; for i in 0..16 { // if the most significant bit of b is set, // then the destination byte is set to 0. if b[i] & 0x80 == 0u8 { r[i] = a[(b[i] % 16) as usize]; } } r }Run Intel's documentation
__label__pos
0.857172
// SPDX-License-Identifier: GPL-2.0-or-later /* * IPV4 GSO/GRO offload support * Linux INET implementation * * UDPv4 GSO support */ #include #include #include #include static struct sk_buff *__skb_udp_tunnel_segment(struct sk_buff *skb, netdev_features_t features, struct sk_buff *(*gso_inner_segment)(struct sk_buff *skb, netdev_features_t features), __be16 new_protocol, bool is_ipv6) { int tnl_hlen = skb_inner_mac_header(skb) - skb_transport_header(skb); bool remcsum, need_csum, offload_csum, gso_partial; struct sk_buff *segs = ERR_PTR(-EINVAL); struct udphdr *uh = udp_hdr(skb); u16 mac_offset = skb->mac_header; __be16 protocol = skb->protocol; u16 mac_len = skb->mac_len; int udp_offset, outer_hlen; __wsum partial; bool need_ipsec; if (unlikely(!pskb_may_pull(skb, tnl_hlen))) goto out; /* Adjust partial header checksum to negate old length. * We cannot rely on the value contained in uh->len as it is * possible that the actual value exceeds the boundaries of the * 16 bit length field due to the header being added outside of an * IP or IPv6 frame that was already limited to 64K - 1. */ if (skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL) partial = (__force __wsum)uh->len; else partial = (__force __wsum)htonl(skb->len); partial = csum_sub(csum_unfold(uh->check), partial); /* setup inner skb. */ skb->encapsulation = 0; SKB_GSO_CB(skb)->encap_level = 0; __skb_pull(skb, tnl_hlen); skb_reset_mac_header(skb); skb_set_network_header(skb, skb_inner_network_offset(skb)); skb_set_transport_header(skb, skb_inner_transport_offset(skb)); skb->mac_len = skb_inner_network_offset(skb); skb->protocol = new_protocol; need_csum = !!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL_CSUM); skb->encap_hdr_csum = need_csum; remcsum = !!(skb_shinfo(skb)->gso_type & SKB_GSO_TUNNEL_REMCSUM); skb->remcsum_offload = remcsum; need_ipsec = skb_dst(skb) && dst_xfrm(skb_dst(skb)); /* Try to offload checksum if possible */ offload_csum = !!(need_csum && !need_ipsec && (skb->dev->features & (is_ipv6 ? (NETIF_F_HW_CSUM | NETIF_F_IPV6_CSUM) : (NETIF_F_HW_CSUM | NETIF_F_IP_CSUM)))); features &= skb->dev->hw_enc_features; if (need_csum) features &= ~NETIF_F_SCTP_CRC; /* The only checksum offload we care about from here on out is the * outer one so strip the existing checksum feature flags and * instead set the flag based on our outer checksum offload value. */ if (remcsum) { features &= ~NETIF_F_CSUM_MASK; if (!need_csum || offload_csum) features |= NETIF_F_HW_CSUM; } /* segment inner packet. */ segs = gso_inner_segment(skb, features); if (IS_ERR_OR_NULL(segs)) { skb_gso_error_unwind(skb, protocol, tnl_hlen, mac_offset, mac_len); goto out; } gso_partial = !!(skb_shinfo(segs)->gso_type & SKB_GSO_PARTIAL); outer_hlen = skb_tnl_header_len(skb); udp_offset = outer_hlen - tnl_hlen; skb = segs; do { unsigned int len; if (remcsum) skb->ip_summed = CHECKSUM_NONE; /* Set up inner headers if we are offloading inner checksum */ if (skb->ip_summed == CHECKSUM_PARTIAL) { skb_reset_inner_headers(skb); skb->encapsulation = 1; } skb->mac_len = mac_len; skb->protocol = protocol; __skb_push(skb, outer_hlen); skb_reset_mac_header(skb); skb_set_network_header(skb, mac_len); skb_set_transport_header(skb, udp_offset); len = skb->len - udp_offset; uh = udp_hdr(skb); /* If we are only performing partial GSO the inner header * will be using a length value equal to only one MSS sized * segment instead of the entire frame. */ if (gso_partial && skb_is_gso(skb)) { uh->len = htons(skb_shinfo(skb)->gso_size + SKB_GSO_CB(skb)->data_offset + skb->head - (unsigned char *)uh); } else { uh->len = htons(len); } if (!need_csum) continue; uh->check = ~csum_fold(csum_add(partial, (__force __wsum)htonl(len))); if (skb->encapsulation || !offload_csum) { uh->check = gso_make_checksum(skb, ~uh->check); if (uh->check == 0) uh->check = CSUM_MANGLED_0; } else { skb->ip_summed = CHECKSUM_PARTIAL; skb->csum_start = skb_transport_header(skb) - skb->head; skb->csum_offset = offsetof(struct udphdr, check); } } while ((skb = skb->next)); out: return segs; } struct sk_buff *skb_udp_tunnel_segment(struct sk_buff *skb, netdev_features_t features, bool is_ipv6) { __be16 protocol = skb->protocol; const struct net_offload **offloads; const struct net_offload *ops; struct sk_buff *segs = ERR_PTR(-EINVAL); struct sk_buff *(*gso_inner_segment)(struct sk_buff *skb, netdev_features_t features); rcu_read_lock(); switch (skb->inner_protocol_type) { case ENCAP_TYPE_ETHER: protocol = skb->inner_protocol; gso_inner_segment = skb_mac_gso_segment; break; case ENCAP_TYPE_IPPROTO: offloads = is_ipv6 ? inet6_offloads : inet_offloads; ops = rcu_dereference(offloads[skb->inner_ipproto]); if (!ops || !ops->callbacks.gso_segment) goto out_unlock; gso_inner_segment = ops->callbacks.gso_segment; break; default: goto out_unlock; } segs = __skb_udp_tunnel_segment(skb, features, gso_inner_segment, protocol, is_ipv6); out_unlock: rcu_read_unlock(); return segs; } EXPORT_SYMBOL(skb_udp_tunnel_segment); static void __udpv4_gso_segment_csum(struct sk_buff *seg, __be32 *oldip, __be32 *newip, __be16 *oldport, __be16 *newport) { struct udphdr *uh; struct iphdr *iph; if (*oldip == *newip && *oldport == *newport) return; uh = udp_hdr(seg); iph = ip_hdr(seg); if (uh->check) { inet_proto_csum_replace4(&uh->check, seg, *oldip, *newip, true); inet_proto_csum_replace2(&uh->check, seg, *oldport, *newport, false); if (!uh->check) uh->check = CSUM_MANGLED_0; } *oldport = *newport; csum_replace4(&iph->check, *oldip, *newip); *oldip = *newip; } static struct sk_buff *__udpv4_gso_segment_list_csum(struct sk_buff *segs) { struct sk_buff *seg; struct udphdr *uh, *uh2; struct iphdr *iph, *iph2; seg = segs; uh = udp_hdr(seg); iph = ip_hdr(seg); if ((udp_hdr(seg)->dest == udp_hdr(seg->next)->dest) && (udp_hdr(seg)->source == udp_hdr(seg->next)->source) && (ip_hdr(seg)->daddr == ip_hdr(seg->next)->daddr) && (ip_hdr(seg)->saddr == ip_hdr(seg->next)->saddr)) return segs; while ((seg = seg->next)) { uh2 = udp_hdr(seg); iph2 = ip_hdr(seg); __udpv4_gso_segment_csum(seg, &iph2->saddr, &iph->saddr, &uh2->source, &uh->source); __udpv4_gso_segment_csum(seg, &iph2->daddr, &iph->daddr, &uh2->dest, &uh->dest); } return segs; } static struct sk_buff *__udp_gso_segment_list(struct sk_buff *skb, netdev_features_t features, bool is_ipv6) { unsigned int mss = skb_shinfo(skb)->gso_size; skb = skb_segment_list(skb, features, skb_mac_header_len(skb)); if (IS_ERR(skb)) return skb; udp_hdr(skb)->len = htons(sizeof(struct udphdr) + mss); return is_ipv6 ? skb : __udpv4_gso_segment_list_csum(skb); } struct sk_buff *__udp_gso_segment(struct sk_buff *gso_skb, netdev_features_t features, bool is_ipv6) { struct sock *sk = gso_skb->sk; unsigned int sum_truesize = 0; struct sk_buff *segs, *seg; struct udphdr *uh; unsigned int mss; bool copy_dtor; __sum16 check; __be16 newlen; if (skb_shinfo(gso_skb)->gso_type & SKB_GSO_FRAGLIST) return __udp_gso_segment_list(gso_skb, features, is_ipv6); mss = skb_shinfo(gso_skb)->gso_size; if (gso_skb->len <= sizeof(*uh) + mss) return ERR_PTR(-EINVAL); skb_pull(gso_skb, sizeof(*uh)); /* clear destructor to avoid skb_segment assigning it to tail */ copy_dtor = gso_skb->destructor == sock_wfree; if (copy_dtor) gso_skb->destructor = NULL; segs = skb_segment(gso_skb, features); if (IS_ERR_OR_NULL(segs)) { if (copy_dtor) gso_skb->destructor = sock_wfree; return segs; } /* GSO partial and frag_list segmentation only requires splitting * the frame into an MSS multiple and possibly a remainder, both * cases return a GSO skb. So update the mss now. */ if (skb_is_gso(segs)) mss *= skb_shinfo(segs)->gso_segs; seg = segs; uh = udp_hdr(seg); /* preserve TX timestamp flags and TS key for first segment */ skb_shinfo(seg)->tskey = skb_shinfo(gso_skb)->tskey; skb_shinfo(seg)->tx_flags |= (skb_shinfo(gso_skb)->tx_flags & SKBTX_ANY_TSTAMP); /* compute checksum adjustment based on old length versus new */ newlen = htons(sizeof(*uh) + mss); check = csum16_add(csum16_sub(uh->check, uh->len), newlen); for (;;) { if (copy_dtor) { seg->destructor = sock_wfree; seg->sk = sk; sum_truesize += seg->truesize; } if (!seg->next) break; uh->len = newlen; uh->check = check; if (seg->ip_summed == CHECKSUM_PARTIAL) gso_reset_checksum(seg, ~check); else uh->check = gso_make_checksum(seg, ~check) ? : CSUM_MANGLED_0; seg = seg->next; uh = udp_hdr(seg); } /* last packet can be partial gso_size, account for that in checksum */ newlen = htons(skb_tail_pointer(seg) - skb_transport_header(seg) + seg->data_len); check = csum16_add(csum16_sub(uh->check, uh->len), newlen); uh->len = newlen; uh->check = check; if (seg->ip_summed == CHECKSUM_PARTIAL) gso_reset_checksum(seg, ~check); else uh->check = gso_make_checksum(seg, ~check) ? : CSUM_MANGLED_0; /* update refcount for the packet */ if (copy_dtor) { int delta = sum_truesize - gso_skb->truesize; /* In some pathological cases, delta can be negative. * We need to either use refcount_add() or refcount_sub_and_test() */ if (likely(delta >= 0)) refcount_add(delta, &sk->sk_wmem_alloc); else WARN_ON_ONCE(refcount_sub_and_test(-delta, &sk->sk_wmem_alloc)); } return segs; } EXPORT_SYMBOL_GPL(__udp_gso_segment); static struct sk_buff *udp4_ufo_fragment(struct sk_buff *skb, netdev_features_t features) { struct sk_buff *segs = ERR_PTR(-EINVAL); unsigned int mss; __wsum csum; struct udphdr *uh; struct iphdr *iph; if (skb->encapsulation && (skb_shinfo(skb)->gso_type & (SKB_GSO_UDP_TUNNEL|SKB_GSO_UDP_TUNNEL_CSUM))) { segs = skb_udp_tunnel_segment(skb, features, false); goto out; } if (!(skb_shinfo(skb)->gso_type & (SKB_GSO_UDP | SKB_GSO_UDP_L4))) goto out; if (!pskb_may_pull(skb, sizeof(struct udphdr))) goto out; if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) return __udp_gso_segment(skb, features, false); mss = skb_shinfo(skb)->gso_size; if (unlikely(skb->len <= mss)) goto out; /* Do software UFO. Complete and fill in the UDP checksum as * HW cannot do checksum of UDP packets sent as multiple * IP fragments. */ uh = udp_hdr(skb); iph = ip_hdr(skb); uh->check = 0; csum = skb_checksum(skb, 0, skb->len, 0); uh->check = udp_v4_check(skb->len, iph->saddr, iph->daddr, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; skb->ip_summed = CHECKSUM_UNNECESSARY; /* If there is no outer header we can fake a checksum offload * due to the fact that we have already done the checksum in * software prior to segmenting the frame. */ if (!skb->encap_hdr_csum) features |= NETIF_F_HW_CSUM; /* Fragment the skb. IP headers of the fragments are updated in * inet_gso_segment() */ segs = skb_segment(skb, features); out: return segs; } #define UDP_GRO_CNT_MAX 64 static struct sk_buff *udp_gro_receive_segment(struct list_head *head, struct sk_buff *skb) { struct udphdr *uh = udp_gro_udphdr(skb); struct sk_buff *pp = NULL; struct udphdr *uh2; struct sk_buff *p; unsigned int ulen; int ret = 0; /* requires non zero csum, for symmetry with GSO */ if (!uh->check) { NAPI_GRO_CB(skb)->flush = 1; return NULL; } /* Do not deal with padded or malicious packets, sorry ! */ ulen = ntohs(uh->len); if (ulen <= sizeof(*uh) || ulen != skb_gro_len(skb)) { NAPI_GRO_CB(skb)->flush = 1; return NULL; } /* pull encapsulating udp header */ skb_gro_pull(skb, sizeof(struct udphdr)); list_for_each_entry(p, head, list) { if (!NAPI_GRO_CB(p)->same_flow) continue; uh2 = udp_hdr(p); /* Match ports only, as csum is always non zero */ if ((*(u32 *)&uh->source != *(u32 *)&uh2->source)) { NAPI_GRO_CB(p)->same_flow = 0; continue; } if (NAPI_GRO_CB(skb)->is_flist != NAPI_GRO_CB(p)->is_flist) { NAPI_GRO_CB(skb)->flush = 1; return p; } /* Terminate the flow on len mismatch or if it grow "too much". * Under small packet flood GRO count could elsewhere grow a lot * leading to excessive truesize values. * On len mismatch merge the first packet shorter than gso_size, * otherwise complete the GRO packet. */ if (ulen > ntohs(uh2->len)) { pp = p; } else { if (NAPI_GRO_CB(skb)->is_flist) { if (!pskb_may_pull(skb, skb_gro_offset(skb))) { NAPI_GRO_CB(skb)->flush = 1; return NULL; } if ((skb->ip_summed != p->ip_summed) || (skb->csum_level != p->csum_level)) { NAPI_GRO_CB(skb)->flush = 1; return NULL; } ret = skb_gro_receive_list(p, skb); } else { skb_gro_postpull_rcsum(skb, uh, sizeof(struct udphdr)); ret = skb_gro_receive(p, skb); } } if (ret || ulen != ntohs(uh2->len) || NAPI_GRO_CB(p)->count >= UDP_GRO_CNT_MAX) pp = p; return pp; } /* mismatch, but we never need to flush */ return NULL; } struct sk_buff *udp_gro_receive(struct list_head *head, struct sk_buff *skb, struct udphdr *uh, struct sock *sk) { struct sk_buff *pp = NULL; struct sk_buff *p; struct udphdr *uh2; unsigned int off = skb_gro_offset(skb); int flush = 1; NAPI_GRO_CB(skb)->is_flist = 0; if (skb->dev->features & NETIF_F_GRO_FRAGLIST) NAPI_GRO_CB(skb)->is_flist = sk ? !udp_sk(sk)->gro_enabled: 1; if ((!sk && (skb->dev->features & NETIF_F_GRO_UDP_FWD)) || (sk && udp_sk(sk)->gro_enabled) || NAPI_GRO_CB(skb)->is_flist) { pp = call_gro_receive(udp_gro_receive_segment, head, skb); return pp; } if (!sk || NAPI_GRO_CB(skb)->encap_mark || (skb->ip_summed != CHECKSUM_PARTIAL && NAPI_GRO_CB(skb)->csum_cnt == 0 && !NAPI_GRO_CB(skb)->csum_valid) || !udp_sk(sk)->gro_receive) goto out; /* mark that this skb passed once through the tunnel gro layer */ NAPI_GRO_CB(skb)->encap_mark = 1; flush = 0; list_for_each_entry(p, head, list) { if (!NAPI_GRO_CB(p)->same_flow) continue; uh2 = (struct udphdr *)(p->data + off); /* Match ports and either checksums are either both zero * or nonzero. */ if ((*(u32 *)&uh->source != *(u32 *)&uh2->source) || (!uh->check ^ !uh2->check)) { NAPI_GRO_CB(p)->same_flow = 0; continue; } } skb_gro_pull(skb, sizeof(struct udphdr)); /* pull encapsulating udp header */ skb_gro_postpull_rcsum(skb, uh, sizeof(struct udphdr)); pp = call_gro_receive_sk(udp_sk(sk)->gro_receive, sk, head, skb); out: skb_gro_flush_final(skb, pp, flush); return pp; } EXPORT_SYMBOL(udp_gro_receive); static struct sock *udp4_gro_lookup_skb(struct sk_buff *skb, __be16 sport, __be16 dport) { const struct iphdr *iph = skb_gro_network_header(skb); return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport, iph->daddr, dport, inet_iif(skb), inet_sdif(skb), &udp_table, NULL); } INDIRECT_CALLABLE_SCOPE struct sk_buff *udp4_gro_receive(struct list_head *head, struct sk_buff *skb) { struct udphdr *uh = udp_gro_udphdr(skb); struct sock *sk = NULL; struct sk_buff *pp; if (unlikely(!uh)) goto flush; /* Don't bother verifying checksum if we're going to flush anyway. */ if (NAPI_GRO_CB(skb)->flush) goto skip; if (skb_gro_checksum_validate_zero_check(skb, IPPROTO_UDP, uh->check, inet_gro_compute_pseudo)) goto flush; else if (uh->check) skb_gro_checksum_try_convert(skb, IPPROTO_UDP, inet_gro_compute_pseudo); skip: NAPI_GRO_CB(skb)->is_ipv6 = 0; rcu_read_lock(); if (static_branch_unlikely(&udp_encap_needed_key)) sk = udp4_gro_lookup_skb(skb, uh->source, uh->dest); pp = udp_gro_receive(head, skb, uh, sk); rcu_read_unlock(); return pp; flush: NAPI_GRO_CB(skb)->flush = 1; return NULL; } static int udp_gro_complete_segment(struct sk_buff *skb) { struct udphdr *uh = udp_hdr(skb); skb->csum_start = (unsigned char *)uh - skb->head; skb->csum_offset = offsetof(struct udphdr, check); skb->ip_summed = CHECKSUM_PARTIAL; skb_shinfo(skb)->gso_segs = NAPI_GRO_CB(skb)->count; skb_shinfo(skb)->gso_type |= SKB_GSO_UDP_L4; return 0; } int udp_gro_complete(struct sk_buff *skb, int nhoff, udp_lookup_t lookup) { __be16 newlen = htons(skb->len - nhoff); struct udphdr *uh = (struct udphdr *)(skb->data + nhoff); struct sock *sk; int err; uh->len = newlen; rcu_read_lock(); sk = INDIRECT_CALL_INET(lookup, udp6_lib_lookup_skb, udp4_lib_lookup_skb, skb, uh->source, uh->dest); if (sk && udp_sk(sk)->gro_complete) { skb_shinfo(skb)->gso_type = uh->check ? SKB_GSO_UDP_TUNNEL_CSUM : SKB_GSO_UDP_TUNNEL; /* Set encapsulation before calling into inner gro_complete() * functions to make them set up the inner offsets. */ skb->encapsulation = 1; err = udp_sk(sk)->gro_complete(sk, skb, nhoff + sizeof(struct udphdr)); } else { err = udp_gro_complete_segment(skb); } rcu_read_unlock(); if (skb->remcsum_offload) skb_shinfo(skb)->gso_type |= SKB_GSO_TUNNEL_REMCSUM; return err; } EXPORT_SYMBOL(udp_gro_complete); INDIRECT_CALLABLE_SCOPE int udp4_gro_complete(struct sk_buff *skb, int nhoff) { const struct iphdr *iph = ip_hdr(skb); struct udphdr *uh = (struct udphdr *)(skb->data + nhoff); if (NAPI_GRO_CB(skb)->is_flist) { uh->len = htons(skb->len - nhoff); skb_shinfo(skb)->gso_type |= (SKB_GSO_FRAGLIST|SKB_GSO_UDP_L4); skb_shinfo(skb)->gso_segs = NAPI_GRO_CB(skb)->count; if (skb->ip_summed == CHECKSUM_UNNECESSARY) { if (skb->csum_level < SKB_MAX_CSUM_LEVEL) skb->csum_level++; } else { skb->ip_summed = CHECKSUM_UNNECESSARY; skb->csum_level = 0; } return 0; } if (uh->check) uh->check = ~udp_v4_check(skb->len - nhoff, iph->saddr, iph->daddr, 0); return udp_gro_complete(skb, nhoff, udp4_lib_lookup_skb); } static const struct net_offload udpv4_offload = { .callbacks = { .gso_segment = udp4_ufo_fragment, .gro_receive = udp4_gro_receive, .gro_complete = udp4_gro_complete, }, }; int __init udpv4_offload_init(void) { return inet_add_offload(&udpv4_offload, IPPROTO_UDP); }
__label__pos
0.996662
Pseudo-Classes, Pseudo-Elements, and Colon Notation In my post about 5 lesser used CSS selectors, I used a single colon when referring to the first-letter and first-line pseudo-elements. It was pointed out to me that I should have used the double colon notation for selectors because they were pseudo-elements. So, in this article, I explore the difference between pseudo-elements and pseudo-classes and which colon syntax should be used. Pseudo-Classes vs Pseudo-Elements Pseudo-classes and pseudo-elements are types of css selectors that allow us to select elements which are not normally available through the DOM. There are currently only 4 psuedo-elements, and 23 pseudo-classes - Pseudo-Classes Pseudo-Elements E:root, E:nth-child(n), E:nth-last-child(n), E:nth-of-type(n), E:nth-last-of-type(n), E:first-child, E:last-child, E:first-of-type, E:last-of-type, E:only-child, E:only-of-type, E:empty, E:link, E:visited, E:active, E:hover, E:focus, E:target, E:lang(x), E:enabled, E:disabled, E:checked, E:not(s) E::first-line, E::first-letter, E::before, E::after Pseudo-classes Pseudo-classes, according to the W3C Recommendation, provide a way for us to select elements "based on information that lies outside of the document tree or that cannot be expressed using the other simple selectors". This covers two cases. First, the selection of information based on information that lies outside the document tree. An example of this is the :visited pseudo-class. a:visited { // styles } Use of this pseudo-class is dependent on information about the link that is not accessible through the DOM. There is no way, in HTML or JavaScript, to determine if a link has been visited. The second case is the selection of elements that cannot be expressed using other simple selectors. An example of this is :nth-child(n). .list-item:nth-child(6) { // styles } Although we may have the class name of the the specific element we want, there is no other way to select an item based on its position amongst its siblings. Psuedo-classes select elements that already exist in the DOM, but which are under conditions that are not accessible through the DOM or through other simple selectors Pseudo-elements Pseudo-elements, on the other hand, "create abstractions about the document tree beyond those specified by the document language". In other words, using pseudo-element selectors essentially creates a new virtual element that can be manipulated as though it were its own element. These new virtual elements do not exist independently, but rather belong to another existing element, called their originating element. For example, with the ::after pseudo-element, we can generate new content that does not actually exist in the DOM. Using the example I gave two weeks ago - *:lang(de)::before { content: "DE"; position: absolute; top: 0; left: -55px; width: 40px; height: 40px; text-align: center; padding: 10px 0; border-radius: 50%; background-color: #FFCE00; } With the ::first-line and ::first-letter selectors, although the content does already exist, using the selector allows us to target the content in a way that is not normally accessible and treat the content as though it were its own element. article::first-letter { font-size: 8rem; line-height: 1; float: left; padding-right: 1rem; margin-top: -2rem; } Pseudo-elements create a virtual element which lies outside the document tree, either with content that already exists, or by creating new content entirely.   The difference between pseudo-classes and pseudo-elements can be summarised as - With pseudo-classes, it is the information used to the select the element that lies outside the document tree. With pseudo-elements, it is the element itself that lies outside the document tree. Colon Notation: Single or Double? In CSS2, both pseudo-classes and pseudo-elements used single colon notation. In CSS3, to make a distinction between the two types of selectors, it was introduced that pseudo-elements use a double colon instead. foo:pseudo-class bar::pseudo-element In the Editor's Draft for CSS4 selectors, it is specifically stated - "Authors must always use the double-colon syntax for these pseudo-elements" However, the problem is that Internet Explorer 8, which according to caniuse.com currently accounts for 2.19% of global browser usage, does not support the double colon notation. It only accepts a single colon for both pseudo-classes and pseudo-elements. Because of this, all modern browsers are required to accept the single colon syntax for the current 4 pseudo-elements mentioned (but not for any future pseudo-elements introduced). So which version should we be using? At this point, and depending on our target audience, IE 8 usage is large enough that we may still need to support it and therefore use the single colon syntax. However, the default should be to use the double colons wherever possible for future proofing. blog comments powered by Disqus
__label__pos
0.903624
http://qs321.pair.com?node_id=67694 in reply to Re: Re: Populating an array in thread Populating an array Good catch on the quotes around the filename. I intentionally left it all uncommented. But lets have some more fun with it: #!/usr/bin/perl -w use strict; use IO::File; use constant FILENAME => 'filename'; { package cntr; sub TIESCALAR{bless[pop],__PACKAGE__} sub FETCH{ $_[0][0]++ } } my $file = IO::File->new( "< ". FILENAME ) or die "Failed to open '@{[FILENAME]}', $!"; my @elements; { local ( $a, $/ ) = $/.$/; @elements = split $a => <$file>; } $file->close(); print "Here are the elements of the array:\n"; tie my $i, 'cntr', 1; print map {$i.': {'."$_}$/"} @elements; Yeah, that would go over well with a teacher or professor. Update: So I changed the code a little from the original post. I actually tested it, and didn't like the way the newlines hung around. This fixes that. View source for the old code.
__label__pos
0.704827
Skip to content icanzilb/TaskQueue Repository files navigation TaskQueue Platform Cocoapods Compatible Carthage Compatible GitHub License Table of Contents Intro title TaskQueue is a Swift library which allows you to schedule tasks once and then let the queue execute them in a synchronous manner. The great thing about TaskQueue is that you get to decide on which GCD queue each of your tasks should execute beforehand and leave TaskQueue to do switching of the queues as it goes. Even if your tasks are asynchronious like fetching location, downloading files, etc. TaskQueue will wait until they are finished before going on with the next task. Last but not least your tasks have full flow control over the queue, depending on the outcome of the work you are doing in your tasks you can skip the next task, abort the queue, or jump ahead to the queue completion. You can further pause, resume, and stop the queue. Installation CocoaPods CocoaPods is a dependency manager for Cocoa projects. If you don't already have the Cocoapods gem installed, run the following command: $ gem install cocoapods To integrate TaskQueue into your Xcode project using CocoaPods, specify it in your Podfile: pod 'TaskQueue' Then, run the following command: $ pod install If you find that you're not having the most recent version installed when you run pod install then try running: $ pod cache clean $ pod repo update TaskQueue $ pod install Also you'll need to make sure that you've not got the version of TaskQueue locked to an old version in your Podfile.lock file. Carthage Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application. You can install Carthage with Homebrew using the following command: $ brew update $ brew install carthage To integrate TaskQueue into your Xcode project using Carthage, specify it in your Cartfile: github "icanzilb/TaskQueue" Simple Example Synchronous tasks Here's the simplest way to use TaskQueue in Swift: let queue = TaskQueue() queue.tasks +=~ { ... time consuming task on a background queue... } queue.tasks +=! { ... update UI on main queue ... } queue.run() TaskQueue will execute the tasks one after the other waiting for each task to finish and the will execute the next one. By using the operators +=~ and +=! you can easily set whether the task should execute in background or on the main queue. Asynchronous tasks More interesting of course is when you have to do some asynchronous work in the background of your tasks. Then you can fetch the next parameter in your task and call it whenever your async work is done: let queue = TaskQueue() queue.tasks +=~ { result, next in var url = URL(string: "http://jsonmodel.com") URLSession.shared.dataTask(with: url, completionHandler: { _, _, _ in // process the response next(nil) }) } queue.tasks +=! { print("execute next task after network call is finished") } queue.run { print("finished") } There are a few things to highlight in the example above: 1. The first task closure gets two parameters: result is the result from the previous task (nil in the case of the first task) and next. next is a closure you need to call whenver your async task has finished executing. 2. Task nr.2 doesn't get started until you call next() in your previous task. 3. The run function can also take a closure as a parameter - if you pass one it will always get executed after all other tasks has finished. Serial and Concurrent Tasks By default TaskQueue executes its tasks one after another or, in other words, the queue has up to one active task at a time. You can, however, allow a given number of tasks to execute at the same time (e.g. if you need to download a number of image files from web). To do this just increase the number of active tasks and the queue will automatically start executing tasks concurrently. For example: queue.maximumNumberOfActiveTasks = 10 This will make the queue execute up to 10 tasks at the same time. Note: As soon as you allow for more than one task at a time certain restrictions apply: you cannot invoke retry(), and you cannot pass a result from one task to another. GCD Queue Control Do you want to run couple of heavy duty tasks in the background and then switch to the main queue to update your app UI? Easy. Study the example below, which showcases GCD queue control with TaskQueue: let queue = TaskQueue() // // "+=" adds a task to be executed on the current queue // queue.tasks += { // update the UI } // // "+=~" adds a task to be executed in the background, e.g. low prio queue // "~" stands for so~so priority // queue.tasks +=~ { // do heavy work } // // "+=!" adds a task to be executed on the main queue // "!" stands for High! priority // queue.tasks +=! { // update the UI again } // to start the queue on the current GCD queue queue.run() Extensive example let queue = TaskQueue() // // Simple sync task, just prints to console // queue.tasks += { print("====== tasks ======") print("task #1: run") } // // A task, which can be asynchronious because it gets // result and next params and can call next() when ready // with async work to tell the queue to continue running // queue.tasks += { result, next in print("task #2: begin") delay(seconds: 2) { print("task #2: end") next(nil) } } // // A task which retries the same task over and over again // until it succeeds (i.e. util when you make network calls) // NB! Important to capture **queue** as weak to prevent // memory leaks! // var cnt = 1 queue.tasks += { [weak queue] result, next in print("task #3: try #\(cnt)") cnt += 1 if cnt > 3 { next(nil) } else { queue!.retry(delay: 1) } } // // This task skips the next task in queue // (no capture cycle here) // queue.tasks += { print("task #4: run") print("task #4: will skip next task") queue.skip() } queue.tasks += { print("task #5: run") } // // This task removes all remaining tasks in the queue // i.e. util when an operation fails and the rest of the queueud // tasks don't make sense anymore // NB: This does not remove the completions added // queue.tasks += { print("task #6: run") print("task #6: will append one more completion") queue.run { _ in print("completion: appended completion run") } print("task #6: will skip all remaining tasks") queue.removeAll() } queue.tasks += { print("task #7: run") } // // This either runs or resumes the queue // If queue is running doesn't do anything // queue.run() // // This either runs or resumes the queue // and adds the given closure to the lists of completions. // You can add as many completions as you want (also half way) // trough executing the queue. // queue.run { result in print("====== completions ======") print("initial completion: run") } Run the included demo app to see some of these examples above in action. Credit Author: Marin Todorov License TaskQueue is available under the MIT license. See the LICENSE file for more info.
__label__pos
0.917041
Step 1: Download and Run the Cloudera Manager Server Installer Download the Cloudera Manager installer to the cluster host to which you are installing the Cloudera Manager Server. By default, the automated installer binary (cloudera-manager-installer.bin) installs the highest version of Cloudera Manager. 1. Download the Cloudera Manager Installer 1. Open Cloudera Manager Downloads in a web browser. In the Cloudera Manager box, click Download Now. 2. You can download either the most recent version of the installer or select an earlier version from the drop-down. Click GET IT NOW!. 3. Either sign in or complete the product interest form and click Continue. 4. Read and accept the Cloudera Standard License agreement and click Submit. 5. Download the installer for your Cloudera Manager version. For example, for Cloudera Manager 6.2.0: wget https://archive.cloudera.com/cm6/6.2.0/cloudera-manager-installer.bin 2. Run the Cloudera Manager Installer 1. Change cloudera-manager-installer.bin to have execute permissions: chmod u+x cloudera-manager-installer.bin 2. Run the Cloudera Manager Server installer: sudo ./cloudera-manager-installer.bin For clusters without Internet access: Install Cloudera Manager packages from a local repository: sudo ./cloudera-manager-installer.bin --skip_repo_package=1 3. Read and Accept the Associated License Agreements 1. Read the Cloudera Manager README and then select Next to proceed. 2. Read the Cloudera Express License and then select Next to proceed. Use the arrow keys to highlight Yes and then press Enter to accept the license. 3. Read the Oracle Binary Code License Agreement and then select Next to proceed. Use the arrow keys to highlight Yes and then press Enter to accept the license. The installer then: 1. Installs the Cloudera Manager repository files. 2. Installs the Oracle JDK. 3. Installs the Cloudera Manager Server and embedded PostgreSQL packages. 4. Starts the embedded PostgreSQL database and Cloudera Manager Server. 4. Exit the Installer 1. When the installation completes, the complete URL for the Cloudera Manager Admin Console displays, including the port number (7180 by default). Make a note of this URL. 2. Press Enter to choose OK to exit the installer, and then again to acknowledge the successful installation. 3. Wait several minutes for the Cloudera Manager Server to start. To observe the startup process, run sudo tail -f /var/log/cloudera-scm-server/cloudera-scm-server.log on the Cloudera Manager Server host. When you see the following log entry, the Cloudera Manager Admin Console is ready: INFO WebServerImpl:com.cloudera.server.cmf.WebServerImpl: Started Jetty server. If the Cloudera Manager Server does not start, see Troubleshooting Installation Problems.
__label__pos
0.813899
Categories Original Find the vendor prefix of the current browser Reading Time: 3 minutes As you probably know already, when browsers implement an experimental or proprietary CSS property, they prefix it with their “vendor prefix”, so that 1) it doesn’t collide with other properties and 2) you can choose whether to use it or not in that particular browser, since it’s support might be wrong or incomplete. When writing CSS you probably just include all properties and rest in peace, since browsers ignore properties they don’t know. However, when changing a style via javascript it’s quite a waste to do that. Instead of iterating over all possible vendor prefixes every time to test if a prefixed version of a specific property is supported, we can create a function that returns the current browser’s prefix and caches the result, so that no redundant iterations are performed afterwards. How can we create such a function though? Things to consider 1. The way CSS properties are converted their JS counterparts: Every character after a dash is capitalized, and all others are lowercase. The only exception is the new -ms- prefixed properties: Microsoft did it again and made their JS counterparts start with a lowercase m! 2. Vendor prefixes always start with a dash and end with a dash 3. Normal CSS properties never start with a dash Algorithm 1. Iterate over all supported properties and find one that starts with a known prefix. 2. Return the prefix. 3. If no property that starts with a known prefix was found, return the empty string. JavaScript code function getVendorPrefix() { var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/; var someScript = document.getElementsByTagName('script')[0]; for(var prop in someScript.style) { if(regex.test(prop)) { // test is faster than match, so it's better to perform // that on the lot and match only when necessary return prop.match(regex)[0]; } } // Nothing found so far? return ''; } Caution: Don’t try to use someScript.style.hasOwnProperty(prop). It’s missing on purpose, since if these properties aren’t set on the particular element, hasOwnProperty will return false and the property will not be checked. Browser bugs In a perfect world we would be done by now. However, if you try running it in Webkit based browsers, you will notice that the empty string is returned. This is because for some reason, Webkit does not enumerate over empty CSS properties. To solve this, we’d have to check for the support of a property that exists in all webkit-based browsers. This property should be one of the oldest -webkit-something properties that were implemented in the browser, so that our function returns correct results for as old browser versions as possible. -webkit-opacity seems like a good candidate but I’d appreciate any better or more well-documented picks. We’d also have to test -khtml-opacity as it seems that Safari had the -khtml- prefix before the -webkit- prefix. So the updated code would be: function getVendorPrefix() { var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/; var someScript = document.getElementsByTagName('script')[0]; for(var prop in someScript.style) { if(regex.test(prop)) { // test is faster than match, so it's better to perform // that on the lot and match only when necessary return prop.match(regex)[0]; } } // Nothing found so far? Webkit does not enumerate over the CSS properties of the style object. // However (prop in style) returns the correct value, so we'll have to test for // the precence of a specific property if('WebkitOpacity' in someScript.style) return 'Webkit'; if('KhtmlOpacity' in someScript.style) return 'Khtml'; return ''; } By the way, if Webkit ever fixes that bug, the result will be returned straight from the loop, since we have added the Webkit prefix in the regexp as well. Performance improvements There is no need for all this code to run every time the function is called. The vendor prefix does not change, especially during the session 😛 Consequently, we can cache the result after the first time, and return the cached value afterwards: function getVendorPrefix() { if('result' in arguments.callee) return arguments.callee.result; var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/; var someScript = document.getElementsByTagName('script')[0]; for(var prop in someScript.style) { if(regex.test(prop)) { // test is faster than match, so it's better to perform // that on the lot and match only when necessary return arguments.callee.result = prop.match(regex)[0]; } } // Nothing found so far? Webkit does not enumerate over the CSS properties of the style object. // However (prop in style) returns the correct value, so we'll have to test for // the precence of a specific property if('WebkitOpacity' in someScript.style) return arguments.callee.result = 'Webkit'; if('KhtmlOpacity' in someScript.style) return arguments.callee.result = 'Khtml'; return arguments.callee.result = ''; } Afterthoughts • Please don’t use this as a browser detection function! Apart from the fact that browser detects are a bad way to code 99.9% of the time, it’s also unreliable for IE, since Microsoft added a vendor prefix in IE8 only. Before that it followed the classic attitude “We have a large market share so standards and conventions don’t apply to us”. • There are some browsers that support multiple prefixes. If that is crucial for you, you may want to return an array with all prefixes instead of a string. It shouldn’t be difficult to alter the code above to do that. I’ll only inform you that from my tests, Opera also has Apple, Xn and Wap prefixes and Safari and Chrome also have Khtml. • I wish there was a list somewhere with ALL vendor prefixes… If you know such a page, please leave a comment.
__label__pos
0.593585
公众号「后端进阶」 专注后端技术分享! 使用Docker搭建ELK日志系统 以下安装都是以 ~/ 目录作为安装根目录。 ElasticSearch 下载镜像: $ sudo docker pull elasticsearch:5.5.0 运行ElasticSearch容器: $ sudo docker run -it -d -p 9200:9200 -p 9300:9300 \ -v ~/elasticsearch/data:/usr/share/elasticsearch/data \ --name myes elasticsearch:5.5.0 特别注意的是如果使用v6以上版本会出现jdk的错误,我们查看日志 $ docker logs -f myes 查看日志: OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release. 网上找到大概的意思是: jdk9对elasticSearch不太友好(版本太新),必须使用JDK8,本人使用的是JDK8u152(jdk-8u152-windows-x64.exe)。如果使用JDK9,使用elasticSearch-rtf(v5.1.1),会出现下面的错误,请特别注意,elasticSearch6.0的版本则必须使用JDK9,否则官网下载的msi不能安装成功,原因还没有去仔细检查。 所以也是一个很坑爹的问题,所以我干脆直接就安装v5.5.0稳定版本吧。 Logstash 下载镜像: $ sudo docker pull logstash:5.5.0 新建配置文件: $ mkdir ~/logstash && cd ~/logstash $ mkdir conf.d && cd conf.d $ vim logstash.conf logstash.conf: input { beats { port => 5044 # 此端口需要与 filebeat.yml 中的端口相同 } file { path => "/data/logs" # start_position => "beginning" } } filter { #grok { # match => { "message" => "%{COMBINEDAPACHELOG}" } #} #date { # match => ["timestamp", "dd/MMM/yyyy:HH:mm:ss Z"] #} grok { patterns_dir => "/etc/logstash/conf.d/patterns" match => {"message" => "%{TIMESTAMP_ISO8601:time}\S%{MYSELF:msgid}%{MYSELF:method}%{MYDATA:data}%{MYSELF:UserInfo}\S%{LOGLEVEL:level}\S%{MYSELF:thread}%{MYSELF:application}%{MYSELF:ip}"} } date { #match => [ "time", "YYYY-MM-dd HH:mm:ss,SSS" ] match => [ "time", "ISO8601" ] target => "@timestamp" timezone => "Asia/Phnom_Penh" } } output { stdout { codec => rubydebug } elasticsearch { action => "index" hosts => ["172.17.10.114:9200"] index => "%{[fields][indexname]}-%{+YYYY.MM.dd}" } } 添加 patterns: $ cd ~/logstash/conf.d $ mkdir patterns && cd patterns $ vim custom custom: MYSELF \[\S*?\] MYDATA [\s\S]*?(?=\[User) 运行Logstash容器: $ sudo docker run -it -d -p 5044:5044 \ -v ~/logstash/conf.d:/etc/logstash/conf.d \ -v ~/logstash/data/logs:/data/logs \ --name logstash logstash:5.5.0 \ -f /etc/logstash/conf.d/logstash.conf Kibana 下载镜像: $ sudo docker pull kibana:5.5.0 新建配置文件: $ mkdir ~/kibana && cd ~/kibana $ vim kibana.yml kibana.yml: server.port: 5601 server.host: "0.0.0.0" elasticsearch.url: "http://172.17.10.114:9200" 运行Kibana容器: $ sudo docker run -it -d -p 5601:5601 \ -v ~/kibana:/etc/kibana \ --name kibana kibana:5.5.0 Filebeat Filebeat需要部署在需要收集日志的服务器上。 下载镜像: $ sudo docker pull docker.elastic.co/beats/filebeat:5.5.0 新建配置文件: filebeat.prospectors: - type: log paths: - ~/filebeat/logs # 指定需要收集的日志文件的路径 fields: indexname: xxx # 这里填写项目名称,对应index => "%{[fields][indexname]}-%{+YYYY.MM.dd}" output.logstash: hosts: ["172.17.10.114:5044"] 运行Filebeat容器: $ sudo docker run -it -d \ -v ~/filebeat/filebeat.yml:/usr/share/filebeat/filebeat.yml \ --name filebeat docker.elastic.co/beats/filebeat:5.5.0 附上一张ELK结构流程图: ELK 微信公众号「Java科代表」 Content
__label__pos
0.65807
4 votes 0answers 72 views Is correlation in vector distributions “dangerous”? Consider the two vector distributions $\xi,\chi$ described below, each one outputting integer vectors of length $n$ with coefficients in $\{0,\dots,n\}$. Distribution $\xi$ samples each coefficient $... 4 votes 0answers 45 views EC Schnorr signature: multiple standard? I 'm working on some EC-Schnorr signature code. Reading various papers on that, it's seems EC-Schnorr is not standardized as well as ECDSA. For example, I found two main differences in two main ... 4 votes 0answers 45 views Can an analog of ChaCha with 64-bit words be defined, and would it be secure? Blake2b has a lightning fast compression function with more-than-overkill security even against quantum attacks. It seems to be based on ChaCha, but with 64-bit words and different rotation constants.... 4 votes 0answers 50 views How should I implement a secure recovery of encryption? I want to create a system to host as securely as possible encrypted data in a way that not even the system can know the content of the data, but that it could be recovered. I would like to know how ... 4 votes 0answers 54 views Authenticated encryption with Enc-Sign-Mac I've given a CPA secure private key encryption scheme, an unforgeable private key MAC scheme and an unforgeable public key signature scheme. I want to combine them to protect confidentiality, ... 4 votes 0answers 51 views How does Boneh–Lynn–Shacham work? As described by Wikipedia, BLS uses Diffie-Hellman in some way. I understand how Diffie-Hellman works in both its normal and elliptic curve forms. But what is the "pairing function"? 4 votes 0answers 76 views Secure entropy extractor for thermal noise collected from camera input? I have read this paper (pdf) which talks about measuring the entropy of thermal noise collected from camera input. They estimate the minimum entropy at about 4 bits per pixel. Probably estimating 1 ... 4 votes 0answers 166 views How to prove that a function F isn't a pseudo random function Let $F$ be a length-preserving pseudorandom function. For the following constructions of a keyed function $F' : \{0, 1\}^n \times \{0, 1\}^{n−1} \to \{0, 1\}^{2n}$, state whether $F'$ is a ... 4 votes 0answers 212 views Zero-knowledge proof for the product of additive Paillier ciphers Suppose that Alice received the cipher values: $E(x_1), E(x_2), ..., E(x_n)$ that are encrypted using Paillier cryptosystem by $n$ entities with Bob's public key. Alice computes $E(\sum x_i)$ from ... 4 votes 0answers 85 views How can I implement decryption for NTRU homomorphic encryption scheme? I have come across this paper On-the-fly multiparty computation via on-the-cloud Multikey from Fully Homomorphic Encryption by Lopez-Alt et al., where authors describe a NTRU-based homomorphic ... 4 votes 0answers 47 views Security parameter p =O(n) In many homomorphic encryption scheme, a security parameter is calculated as p =O(n). How to use the complexity order as values? Is there any specific method with an appropriate example? 4 votes 0answers 39 views Finding differentials and space complexity Most of article about differential cryptanalysis present the generic method, the way to find sub keys. But I can't find a clear explanation about how to find the differentials used in examples. In ... 4 votes 0answers 50 views What is the correct definition of the blowfish F-function? The Blowfish cipher uses a so called F-function which uses S-Boxes (S[i], i=0,1,2,3) to ... 4 votes 0answers 196 views Additively homomorphic cryptosystem with non-interactive zero-knowledge proof of non-negativity I need a cryptosystem that is additively homomorphic. Paillier preferably, but not neccessarily. Also, for every ciphertext the private key holder must be able to prove non-interactively that the ... 4 votes 0answers 61 views Why SIVP Is Worst Case Problem? I just started to study lattice cryptography. I'm now studying worst-case to average-case reduction for SIS. In previous question, "worst means any and average means random". And I wonder why ... 4 votes 0answers 84 views Adding parameters to sponge's capacity Is it safe to XOR parameters like domain, length of the message or block counter into sponge's capacity or that gives attacker control over capacity? For example NORX XORs domain into capacity. Does ... 4 votes 0answers 50 views Reusing same source for single-source randomness extractor Let $ext$ be a single-source randomness extractor which takes a $d$-bit seed and a $n$-bit source as input and produces a $m$-bit output. Suppose we have a source $X$ with min-entropy $k$. Is it ... 4 votes 0answers 52 views What followed findings of A. Lenstra et al. concerning shared factors of practical RSA moduli? A. Lenstra et al. had a paper in 2012 "Ron was wrong, Whit is right", in which one reads: "What surprised us most is that many thousands of 1024-bit RSA moduli, including thousands that are contained ... 4 votes 0answers 67 views How to use a stream cipher to sign a message? Are there known constructions which allow to sign a message M (let's say it will be sent as clear text) using a stream cipher C and a symmetric secret key K? So, we have M, C, K and we want to send M|... 4 votes 0answers 63 views Which precautions to protect against side-channel attacks on ARX ciphers? In recent crypto there has been a trend to design ciphers using only the ARX set of instructions - i.e. additions (modulo $2^{32}$ or $2^{64}$), rotations (by a fixed constant) and XORs, examples ... 4 votes 0answers 197 views Salary Negotiation Problem Imagine Alice is applying for a new job. Alice has an idea of the minimum salary that she is willing to accept—let's call this value A. Bob, the hiring manager for ... 4 votes 0answers 74 views What level of security is provided when a Feistel Cipher is used as a round function of another Feistel Cipher? Recently, I was reading: Are there any specific requirements for the function F in a Feistel cipher?, and the answer posted mentions a Feistel Cipher named Turtle, which uses a four-round Feistal ... 4 votes 0answers 61 views Are there any test vectors for the CMS content type AuthEnvelopedData (for AES-GCM)? I am looking for CMS AuthEnvelopedData test vectors for AES-GCM mode. I haven’t seen any ready-to-use test vectors for it. There are test vectors for AES-GCM mode but not for its CMS support. I even ... 4 votes 0answers 67 views Additive homomorphic encryption scheme without change in operator I'm looking for an additive homomorphic encryption that the addition operator (+) in its plaintext space be the same as addition operator in its ciphertext space. (Schemes like Paillier do addition in ... 4 votes 0answers 125 views Explanation of part of a visual cryptography algorithm I have been working on a project involving visual cryptography and I am stuck with the following problem. My question is related to this paper, AN IMPROVED VISUAL CRYPTOGRAPHY SCHEME FOR SECRET ... 4 votes 0answers 85 views Better lower bound on min-entropy In “Randomness Condensers for Efficiently Samplable, Seed-Dependent Sources” by Dodis, Ristenpart, and Vadhan (PDF), I have seen the statement that: any tuple of distributions $(X,Z)$ is $ε$-close ... 4 votes 0answers 126 views Rationale for use of right-shift (rather than rotate) in SHA-2? The SHA-2 hashes in FIPS 180 define $\Sigma$ and $\sigma$ bijections of words, with $\Sigma$ used in the round function, and $\sigma$ used in preparing 48 words of message schedule from 16 words of a ... 4 votes 0answers 76 views Missing public exponent Using LUC RSA, I have a list of 8 public keys $(R_1,n_1)$ through $(R_8,n_8)$, and a list of $8$ messages $M_1\dots M_8$. The messages have all been double encrypted. However, one of the public key ... 4 votes 0answers 122 views Under what conditions did a Bletchley bombe stop? I am trying to understand the conditions necessary for one of the Bletchley Park bombes to stop. Let me give an example. I have been experimenting with Enigma machine and bombe simulators to try to ... 4 votes 0answers 100 views Is the key schedule of Serpent a circle? The creation of the prekeys for Serpent works by XORing some previous values with a counter and a fixed value. Every word is 32 bits big and 4 words form a round key (after applying a S-Box, but this ... 4 votes 0answers 143 views Statistical saturation attack on block ciphers I was wondering if anyone around here could give me some explanation on this type of attacks. Pretty much the only thing that I could find is A Statistical Saturation Attack against the Block Cipher ... 4 votes 0answers 97 views Anonymisation resilient to key leak Problem statement Elbonian citizens have been issued a card holding a random $B_j\in\{0,1\}^b$, $0\le j<2^n$, $b\ge n+20$ (representative example $b=64$, $n=28$). The habit has grown to use this ... 4 votes 0answers 145 views What are the current limitations (and capabilities) of Functional Encryption used for access control? I'm trying to make my way in Functional Encryption used for access control. I read a lot of papers such as "How to Run Turing Machines on Encrypted Data", "Functional Encryption: New Perspectives and ... 4 votes 0answers 110 views Efficient proof of knowledge using Wegman-Carter hash A verifier wants to ensure, with only little exchange of data with other systems, that a large block of data $M$ that the verifier holds is also available to some other system(s). It is not an ... 4 votes 0answers 412 views Consequences of AES without any one of its operations Suppose AES-$128$. There are $4$ operations in AES's encryption, they are SubByte, Shift Row, MixColumns and AddRoundKey. Question: If I remove one of the following opearations, what will happen to ... 4 votes 0answers 151 views understanding the proof of knowledge Recently I've been reading the paper “A New Family of Implicitly Authenticated Diffie-Hellman Protocols”. It's very hard for me to go further. Especially when it comes to the proof of knowledge. ... 4 votes 0answers 85 views Feasible way to check n-dimensional equidistribution of PRNGs I am currently gathering some test methods and test suites for random number generator qualities, and am a bit stuck at finding something feasible to test for n-dimensional equidistribution. As input ... 4 votes 0answers 245 views Is there a flaw in this ECC blind signature scheme? Recently I've found the following work on the internet: An ECC-Based Blind Signature Scheme The paper claims to be an ECDSA blind signature however it seems that their scheme has a flaw in it. The ... 4 votes 0answers 216 views Using the same private key for two ECC key pairs Let $(d_1,Q_1)$ and $(d_2,Q_2)$ be ECC key pairs over two different elliptic curves (say NIST P-224 and NIST P-256). According to the Elliptic Curve Discrete Logarithm Problem (ECDLP), if the private ... 4 votes 0answers 195 views Storing password or derived key in keychain? Currently I am developing an application that stores and reads encrypted data. The data is encrypted with AES and the actual AES key is derived from the users password (and some nonce) with PBKDF2 ... 4 votes 0answers 104 views What informal indicators exist for estimating the computational infeasibility of cryptographic problems? When assuming a block cipher primitive is secure, or a number theoretic problem is hard, this assumption is usually based on how far we are from breaking the primitive or solving the problem using ... 4 votes 0answers 256 views Logics for Cryptographic Information Games Preamble: There is currently a zoo of various logics for evaluating (proving) security in cryptographic protocols. The idea is that, by expressing these protocols using some logic, you can create a ... 4 votes 0answers 1k views Reasons for Chinese SM2 Digital Signature Algorithm In the IETF RFC draft named "SM2 Digital Signature Algorithm" a signature algorithm is specified. The RFC does however not mention why this signature algorithm has been defined. Nor does it specify ... 4 votes 0answers 200 views Ring Signature - paper/code difference in trying to solve inverse trap door function? there is a paper on ring signatures and a python implementation of it here. The Step 4 in the paper describes $y_s = v =C_k,_v(y_1, y_2, ... y_r)$ for all $1 \leq i \leq r$ where $i \neq s$. The ... 3 votes 0answers 37 views Attacking Scrypt Under Access Pattern Leakage Could cache-timing channels (such as exist for certain block ciphers) somehow be made use of in order to extract memory-access pattern information if both the attacker and user are NOT in a shared ... 3 votes 0answers 38 views Efficiency of oblivious algorithms vs non-oblivious algorithms Recently, plenty of researchers are looking at designing efficient data-oblivious algorithms. Roughly speaking, an algorithm is said to be data-oblivious if its data access patterns are independednt ... 3 votes 0answers 33 views Quantum complexity of LWE As per my understanding LWE is quantum secure because there is no known quantum algorithm to solve LWE in polynomial time. Due to the reductions given by Regev et al. If there is any algorithm that ... 3 votes 0answers 139 views Inverting a candidate one way function Let $w = a_0 \cdot a_1 \cdots a_{n-1} $ be a word from $ \{0,1\}^n $, $|w| = n$ Let $m = \sum_{i=0}^{n-1}{ a_i \cdot 2 ^ {n-1-i} } $ be the corresponding binary number constructed from the word. Let ... 3 votes 0answers 38 views How subscriptions are managed in PayTV securely? Since there are millions of subscriber for each operator in PayTV and each subscriber can subscribe to any of the package or individual channels, how operators transmit Entitlement management messages ... 3 votes 0answers 1k views Cryptography behind the Turing Imitation Key (TIK) When browsing the internet I found out about this amazing phone. Well, it would be amazing if it was actually obtainable. It's called the Turing Phone, and it is supposed to come with as good as ... 15 30 50 per page
__label__pos
0.872709
How do I change the roll-over effect of the text on my pages button to change the text content itself when hovering on the button? • 0 • 1 • Question • Updated 7 months ago • Answered Archived and Closed This conversation is no longer open for comments or replies and is no longer visible to community members. The community moderator provided the following reason for archiving: Archiving inactive content How do I change the roll-over effects of the text on my pages buttons to change the text content itself when someone hovers their mouse over the button? I'm creating a translation website and I thought it would be cool if I could have the pages header go from English to Japanese when someone rolled over the button. Thanks! Photo of Elizabeth1372 Elizabeth1372 • 162 Points 100 badge 2x thumb Posted 7 months ago • 0 • 1 Photo of Elyzabeth Elyzabeth , Official Rep • 40,296 Points 20k badge 2x thumb Hello Elizabeth1372 You couldn't do this within the settings for the navigation menu. There is no feature for this. The only thing I could recommend is to create a button for each page and create a separate text box for the translation, and use element behaviors on the button to show a text box when the mouse hovers over the button. This would be under More > Advanced > Settings > Add Behavior. You will need to add 2 behaviors. One to show the text box when you hover over the button and one to hide the text box when the mouse leaves the element. You will also need to go under the Size and Position settings of the text box, and turn off the settings "Starts Visible" This conversation is no longer open for comments or replies.
__label__pos
0.878166
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required. Sign up Here's how it works: 1. Anybody can ask a question 2. Anybody can answer 3. The best answers are voted up and rise to the top TLDR: using typeof(T) twice; assigning the value to a variable and reusing that = uber fast (30FPS), actually calling typeof(T) twice = derped (5FPS). Why? I have a simple entity/component system; my basic entity had an array of IComponents, and methods like HasComponent<T> and GetComponent<T>. These just iterate over the arrays and return the first matching item (this.components.Any(c => c is T)). Turns out a performance bottleneck I experience with 100k components "in memory" (albeit most off-screen) is actually these two methods. With a few components, no problem (30FPS+). With 100k components, just sprites, I get around 5FPS. So I figured, why not use a Dictionary<Type, IComponent> instead? It'll be faster, right? Right?! Wrong. First, a complexity: I have a SpriteComponent class, and a SpriteSheetComponent component class (knows about frames, animation, etc.). To simplify everything, SpriteSheetComponent derives from SpriteComponent. This makes drawing, ordering, etc. simpler, because of the is-a relationship. Second, querying for components became more complex; if I ask HasComponent<SpriteComponent>, and you have a SpriteSheetComponent, you should return true, right? So the way I handle that is: return this.components.Keys.Any(t => t == typeof(T) || t.IsSubclassOf(typeof(T))); Ditto for fetching the element, except I use First instead of Any. Anyway, I noticed that the performance actually degraded. What's even more surprising is that this fixed the performance issue: var tType = typeof(T); return this.components.Keys.Any(t => t == tType || t.IsSubclassOf(tType)); The only difference is that I'm checking typeof(T) once and reusing that. This fixed my FPS up to 30ish, hurrah. But this is definitely a "lolwut" moment for me. Is typeof(T) really that slow? And in this case, it's shredding my performance with just one extra call? share|improve this question 4   This is probably more of a Stackoverflow question. In fact, I found an answer for it here: stackoverflow.com/questions/6417763/… and dotnerperls also has a bit to say on it: dotnetperls.com/typeof How many of these comparisons are you doing per frame? – michael.bartnett Dec 22 '12 at 5:16      Honestly, I'd consider typeof to be a red flag function, you probably call it because you have made a mess of your data structure. If you had a clean design the type would either be implicit in the code, or the difference would be handled by the objects's own methods. – aaaaaaaaaaaa Dec 22 '12 at 13:00      @eBusiness getting components by type from a generic container is, as far as I know, a standard solution to designing your entity system. – ashes999 Dec 22 '12 at 16:38 1   @ashes999 I recognize that you have been particularly unlucky, and even with the given explanations I fail to understand why typeof would be that slow. That you are paying in speed for using a generic container is however no surprise. The thing is, you are probably also paying in some combination of code complexity, readability, and debugability. The key question is, if you want to treat the objects differently, why do you put them on the same list in the first place? – aaaaaaaaaaaa Dec 22 '12 at 19:00 up vote 12 down vote accepted Well, it's not really one extra call, is it? It's n * 100k extra calls per frame, if you're doing this every time you retrieve the sprite component for each entity! Maybe your entity should just have a field for the sprite component, null if it hasn't got one, rather than indirecting through all this dictionary and typeof stuff. Ditto for other commonly used components. I understand the impluse to generalize, but your system sounds rather overengineered for what it needs to do. BTW, if you have 100k entities (a huge number by most game standards) and most of them are offscreen, you should definitely invest in a space-partitioning system of some sort so you can avoid updating - or even looping over - all of 'em. share|improve this answer      I actually do have a spatial partitioning scheme already (quad tree). I'm selectively drawing what's on-screen only. The problem is, these are just map tiles -- I can't even keep a 100x100 map in memory and draw some of it on screen. Maybe pulling out the sprite component makes more sense. – ashes999 Dec 22 '12 at 13:09      I started adding straight sprite components instead of adding them as entities and the issues seems somewhat resolved. Cheers. – ashes999 Dec 22 '12 at 16:38 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.630547
Skip to main content   Splunk Lantern Prescriptive Adoption Motion - Event Analytics   Due to the rapid increase in data from IT and business systems in recent years, ITOps teams face challenges in making sense of this vast amount of information. They deal with data from numerous critical services, infrastructure, packaged applications (such as SAP, Microsoft, Oracle, and Salesforce), and third-party domain managers. Handling such a large volume of data makes it impossible for humans to efficiently group and prioritize the information, leading to frustration, delays in incident resolution, and higher costs for IT Operations Centers. For more than two decades, ITOps teams have been using monitoring tools and incident management tools. However, the combination of these tools and siloed teams results in an overwhelming number of alerts, many of which are duplicates, making it difficult to comprehend both ITOps and business data. This situation leads to unplanned downtime, reactive responses, and staff burnout, all of which hinder the ITOps' ability to support and expand the business. To address these issues, some ITOps teams have started using AIOps, which involves applying artificial intelligence (AI) and machine learning (ML) to operations. AIOps can help reduce alert noise and tackle the challenges caused by traditional approaches. Some teams have implemented separate AIOps middleware tools like BigPanda or Moogsoft to focus on event correlation and noise reduction. However, these tools are often complex to set up, contribute to tool sprawl, increase overall costs, and might not effectively prioritize alerts based on their impact on business services. Aim and strategy ITOps teams face the challenge of dealing with a large amount of data to identify and resolve issues swiftly. One effective approach is to reduce alert noise by grouping related alerts, enabling teams to understand their environment more rapidly. Additionally, prioritizing these grouped alerts helps ITOps teams focus on critical matters. Intelligent event correlation, powered by machine learning, further enhances this process by grouping and prioritizing logs, metrics, and events from various sources like infrastructure, applications, and networks. This can reduce alert noise by over 90%. By pinpointing a few actionable events and prioritizing them based on their impact on services, ITOps teams can quickly identify the root cause of an issue and improve their mean time to resolve critical incidents (MTTR). Splunk customers who have deployed event analytics in Splunk ITSI have realized several benefits, including quick data ingestion from various sources through existing integrations. Splunk ITSI consolidates monitoring, event, and incident management tools in a centralized platform, allowing teams to view all alerts in one place without switching between tools or replacing existing investments. Integration with IT service management and orchestration tools further streamlines incident monitoring, detection, response, and resolution from a single location. With the aid of machine learning and rules-based correlation, Splunk ITSI significantly reduces event noise, making it easier to identify probable root causes. This grouping and prioritization of alerts empower teams to involve the right stakeholders and swiftly address incidents. Common use cases • Event analytics - Alert noise reduction, event management, event clustering, alert correlation and intelligent event management • Business service insights - Service monitoring and insights • Advanced analytics and alerting - Predictive analytics User roles Role Responsibilities ITOps Leader Manage teams that build and deliver software and services ITOps Practitioner Manage hybrid environment and services, and resolve incidents Engineering Team Provide self-service tooling for developers to improve productivity and create consistency across teams Developer Design, build, deploy, and debug application code IT Operations/NOC Analyst Use Episode Review to investigate and troubleshoot issues ITSI Admin Onboard data, deploy relevant content packs, create correlation searches, configure Notable Event Aggregation Policies, and configure integrations with external ITSM tools (SNOW, Remedy, Splunk On-Call, etc) to meet business requirements Preparation 1. Prerequisites Splunk ITSI event analytics is designed to make event storms manageable and actionable. After data is ingested into ITSI from multiple data sources, it's processed through correlation searches to create notable events. ITSI generates notable events when a correlation search or multi-KPI alert meets specific conditions that you define. Notable event aggregation policies group the events into meaningful episodes, a group of events occurring as part of a larger sequence (an incident or period considered in isolation). Use episode review to view episode details and identify issues that might impact the performance and availability of your IT services. You can then take actions on the episodes, such as running a script, pinging a host, or creating tickets in external systems. 2. Recommended training ITSI users ITSI admins Splunk Enterprise administrators: Splunk Cloud Platform administrators: 3. Resources Self-service resources 4. Considerations Splunk ITSI is a premium application installed on Splunk Enterprise or Splunk Cloud Platform. Splunk ITSI can be configured to be a "monitor of monitors" for other monitoring tools or a "manager of managers" for events depending on requirements. See Best practices for implementing event analytics in ITSI before you begin setting up and configuring Splunk ITSI. Universal alerting is part of the Content Pack for Monitoring and Alerting and provides a reusable way to ingest third party alerts into Splunk ITSI, without the need to create correlation searches or notable event aggregation policies. Learn about the Content Pack for Monitoring and Alerting with these resources: Implementation guide 1. Ingest events through correlation searches. 2. Configure aggregation policies to group events into episodes. 3. Setup up automated actions to take on episodes. For example, configuring episode ticketing integrations. 4. Test, validate, and optimize. For full procedures and best practices to help you implement event analytics in Splunk ITSI, use the following resources: Success measurement When implementing the guidance in this adoption guide, you should see improvements in the following: • Prioritizing actionable events so ITOps teams can quickly find root cause and resolve critical incidents • Mean time to detect or repair (MTTD/MTTR) • Reduction in alert noise by more than 90% • Improved event management • Alert and episode storm detection • Improved IT Operations posture  
__label__pos
0.766778
Skip to main content Large lists You can use Column and Row controls to display lists in the most cases, but if the list contains hundreds or thousands of items Column and Row will be ineffective with lagging UI as they render all items at once even they are not visible at the current scrolling position. In the following example we are adding 5,000 text controls to a page. Page uses Column as a default layout container: import flet as ft def main(page: ft.Page): for i in range(5000): page.controls.append(ft.Text(f"Line {i}")) page.scroll = "always" page.update() ft.app(main, view=ft.AppView.WEB_BROWSER) Run the program and notice that it's not just it takes a couple of seconds to initially load and render all text lines on a page, but scrolling is slow and laggy too: For displaying lists with a lot of items use ListView and GridView controls which render items on demand, visible at the current scrolling position only. ListView ListView could be either vertical (default) or horizontal. ListView items are displayed one after another in the scroll direction. ListView already implements effective on demand rendering of its children, but scrolling performance could be further improved if you can set the same fixed height or width (for horizontal ListView) for all items ("extent"). This could be done by either setting absolute extent with item_extent property or making the extent of all children equal to the extent of the first child by setting first_item_prototype to True. Let's output a list of 5,000 items using ListView control: import flet as ft def main(page: ft.Page): lv = ft.ListView(expand=True, spacing=10) for i in range(5000): lv.controls.append(ft.Text(f"Line {i}")) page.add(lv) ft.app(main, view=ft.AppView.WEB_BROWSER) Now the scrolling is smooth and fast enough to follow mouse movements: note We used expand=True in ListView constructor. In order to function properly, ListView must have a height (or width if horizontal) specified. You could set an absolute size, e.g. ListView(height=300, spacing=10), but in the example above we make ListView to take all available space on the page, i.e. expand. Read more about Control.expand property. GridView GridView allows arranging controls into a scrollable grid. You can make a "grid" with ft.Column(wrap=True) or ft.Row(wrap=True), for example: import os import flet as ft os.environ["FLET_WS_MAX_MESSAGE_SIZE"] = "8000000" def main(page: ft.Page): r = ft.Row(wrap=True, scroll="always", expand=True) page.add(r) for i in range(5000): r.controls.append( ft.Container( ft.Text(f"Item {i}"), width=100, height=100, alignment=ft.alignment.center, bgcolor=ft.colors.AMBER_100, border=ft.border.all(1, ft.colors.AMBER_400), border_radius=ft.border_radius.all(5), ) ) page.update() ft.app(main, view=ft.AppView.WEB_BROWSER) Try scrolling and resizing the browser window - everything works, but very laggy. note At the start of the program we are setting the value of FLET_WS_MAX_MESSAGE_SIZE environment variable to 8000000 - this is the maximum size of WebSocket message in bytes that can be received by Flet Server rendering the page. Default size is 1 MB, but the size of JSON message describing 5,000 container controls would exceed 1 MB, so we are increasing allowed size to 8 MB. Squeezing large messages through WebSocket channel is, generally, not a good idea, so use batched updates approach to control channel load. GridView, similar to ListView, is very effective to render a lot of children. Let's implement the example above using GridView: import os import flet as ft os.environ["FLET_WS_MAX_MESSAGE_SIZE"] = "8000000" def main(page: ft.Page): gv = ft.GridView(expand=True, max_extent=150, child_aspect_ratio=1) page.add(gv) for i in range(5000): gv.controls.append( ft.Container( ft.Text(f"Item {i}"), alignment=ft.alignment.center, bgcolor=ft.colors.AMBER_100, border=ft.border.all(1, ft.colors.AMBER_400), border_radius=ft.border_radius.all(5), ) ) page.update() ft.app(main, view=ft.AppView.WEB_BROWSER) With GridView scrolling and window resizing are smooth and responsive! You can specify either fixed number of rows or columns (runs) with runs_count property or the maximum size of a "tile" with max_extent property, so the number of runs can vary automatically. In our example we set the maximum tile size to 150 pixels and set its shape to "square" with child_aspect_ratio=1. child_aspect_ratio is the ratio of the cross-axis to the main-axis extent of each child. Try changing it to 0.5 or 2. Batch updates When page.update() is called a message is being sent to Flet server over WebSockets containing page updates since the last page.update(). Sending a large message with thousands of added controls could make a user waiting for a few seconds until the messages is fully received and controls rendered. To increase usability of your program and present the results to a user as soon as possible you can send page updates in batches. For example, the following program adds 5,100 child controls to a ListView in batches of 500 items: import flet as ft def main(page: ft.Page): # add ListView to a page first lv = ft.ListView(expand=1, spacing=10, item_extent=50) page.add(lv) for i in range(5100): lv.controls.append(ft.Text(f"Line {i}")) # send page to a page if i % 500 == 0: page.update() # send the rest to a page page.update() ft.app(main, view=ft.AppView.WEB_BROWSER)
__label__pos
0.878079
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. def getMove(win,playerX,playerY): #Define variables. movePos = 75 moveNeg = -75 running = 1 #Run while loop constantly to update mouse's coordinates. while(running): mouseCoord = win.getMouse() mouseX = mouseCoord.getX() mouseY = mouseCoord.getY() print "Mouse X = ", mouseX print "Mouse Y = ", mouseY if mouseX >= playerX: playerX = movePos + playerX running = 0 elif mouseX <= playerX: playerX = moveNeg + playerX running = 0 elif mouseY >= playerY: playerY = movePos + playerY running = 0 elif mouseY <= playerY: playerY = moveNeg + playerY running = 0 return playerX,playerY def main(): #Create game window. win = GraphWin("Python Game", 500, 500) drawBoard(win) #Define variables. playerX = 75 playerY = 125 keyX = 325 keyY = 375 running = 1 #Create Key and Player objects, draw the key, but don't draw the player yet. key = Text(Point(keyX,keyY),"KEY") key.draw(win) while(running): print "player X = ", playerX print "Player Y = ", playerY drawBoard(win) getMove(win,playerX,playerY) player = Circle(Point(playerX,playerY),22) player.setFill('yellow') player.draw(win) main() I am using a graphics library to create a game. My player and key are drawn in the correct places. However, when calling the getMove function, my playerX and playerY do not update. I have added debug print statements to find their values while running the game and it is always 75 and 125. Help! share|improve this question 3 Answers 3 In python, integers are immutable - when you assign a new integer value to a variable, you are just making the variable point to a new integer, not changing what the old integer it pointed to's value was. (An example of a mutable object in python is the list, which you can modify and all variables pointing to that list will notice the change - since the LIST has changed.) Similarly, when you pass a variable into a method in python and then alter what the variable points to in that method, you do not alter what the variable points to outside of that method because it is a new variable. To fix this, assigned the returned playerX,playerY to your variables outside the method: playerX, playerY = getMove(win,playerX,playerY) share|improve this answer You should explicitly reassign these variables when you call getMove(): playerX, playerY = getMove(win, playerX, playerY) Hope this helps! share|improve this answer As has been mentioned, the solution is that you're not using the returned values to update your playerX, playerY which can be fixed with the mentioned playerX, playerY = getMove(win,playerX,playerY) What I want to address is the logic in your if statements. The way you've constructed your if statements will lead to only an X OR Y being updated, not both. For example, if mouseX, mouseY were both greater than playerX, playerY repectively, you'd get to the first line of your if statement and it would be evaluated as True and update playerX accordingly, BUT because the first statement has been executed, none of the other elif statements will execute, leading to you only updating the playerX variable. What you want to do is split the if statement into two separate statements (one for X and one for Y) so that the adjustments of X,Y are independent of each other. Something similar to if mouseX >= playerX: playerX = movePos + playerX running = 0 elif mouseX <= playerX: playerX = moveNeg + playerX running = 0 #By having the second if, it allows you to check Y even if X has changed if mouseY >= playerY: playerY = movePos + playerY running = 0 elif mouseY <= playerY: playerY = moveNeg + playerY running = 0 share|improve this answer Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.945754
Source code for encord.orm.model # # Copyright (c) 2023 Cord Technologies Limited # # 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. from collections import OrderedDict from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import List, Optional from dateutil.parser import parse from encord.constants.model import AutomationModels from encord.exceptions import EncordException from encord.orm import base_orm from encord.orm.formatter import Formatter from encord.utilities.common import ENCORD_CONTACT_SUPPORT_EMAIL [docs]class ModelOperations(Enum): INFERENCE = 0 TRAIN = 1 CREATE = 2 [docs]class Model(base_orm.BaseORM): """ Model base ORM. ORM: model_operation, model_parameters, """ DB_FIELDS = OrderedDict([("model_operation", int), ("model_parameters", dict)]) [docs]@dataclass class ModelConfiguration(Formatter): model_uid: str title: str description: str feature_node_hashes: List[str] """The corresponding feature node hashes of the ontology object""" model: AutomationModels model_iteration_uids: List[str] """All the UIDs of individual model training instances""" [docs] @classmethod def from_dict(cls, json_dict: dict): return ModelConfiguration( model_uid=json_dict["model_uid"], title=json_dict["title"], description=json_dict["description"], feature_node_hashes=cls._get_feature_node_hashes(json_dict["feature_node_hashes"]), model=cls._get_automation_model(json_dict["model"]), model_iteration_uids=json_dict["model_iteration_uids"], ) @staticmethod def _get_feature_node_hashes(features: dict) -> List[str]: return list(features.keys()) @staticmethod def _get_automation_model(automation_model_str: str) -> AutomationModels: try: return AutomationModels(automation_model_str) except ValueError as e: raise EncordException( "A model was returned which was not recognised. Please upgrade your SDK " f"to the latest version or contact support at {ENCORD_CONTACT_SUPPORT_EMAIL}." ) from e [docs]@dataclass class ModelTrainingLabelMetadata: label_uid: str data_uid: str data_link: str [docs] @staticmethod def from_dict(json_dict: dict) -> "ModelTrainingLabelMetadata": return ModelTrainingLabelMetadata( label_uid=json_dict["label_uid"], data_uid=json_dict["data_uid"], data_link=json_dict["data_link"], ) [docs] @classmethod def from_list(cls, json_list: list) -> List["ModelTrainingLabelMetadata"]: return [cls.from_dict(item) for item in json_list] [docs]@dataclass class ModelTrainingLabel: label_metadata_list: List[ModelTrainingLabelMetadata] feature_uids: List[str] [docs] @staticmethod def from_dict(json_dict: dict) -> "ModelTrainingLabel": return ModelTrainingLabel( label_metadata_list=ModelTrainingLabelMetadata.from_list(json_dict["label_metadata_list"]), feature_uids=json_dict["feature_uids"], ) [docs]@dataclass class TrainingMetadata(Formatter): model_iteration_uid: str created_at: Optional[datetime] = None training_final_loss: Optional[float] = None model_training_labels: Optional[ModelTrainingLabel] = None [docs] @classmethod def from_dict(cls, json_dict: dict): return TrainingMetadata( model_iteration_uid=json_dict["model_iteration_uid"], created_at=cls.get_created_at(json_dict), training_final_loss=json_dict["training_final_loss"], model_training_labels=cls.get_model_training_labels(json_dict), ) [docs] @staticmethod def get_created_at(json_dict: dict) -> Optional[datetime]: created_at = json_dict["created_at"] if created_at is None: return None return parse(created_at) [docs] @staticmethod def get_model_training_labels(json_dict: dict) -> Optional[ModelTrainingLabel]: model_training_labels = json_dict["model_training_labels"] if model_training_labels is None: return None return ModelTrainingLabel.from_dict(model_training_labels) [docs]class ModelRow(base_orm.BaseORM): """ A model row contains a set of features and a model (resnet18, resnet34, resnet50, resnet101, resnet152, vgg16, vgg19, faster_rcnn, mask_rcnn). ORM: model_hash (uid), title, description, features, model, """ DB_FIELDS = OrderedDict( [ ("model_hash", str), ("title", str), ("description", str), ("features", list), ("model", str), ] ) [docs]class ModelInferenceParams(base_orm.BaseORM): """ Model inference parameters for running models trained via the platform. ORM: local_file_path, conf_thresh, iou_thresh, device detection_frame_range (optional) """ DB_FIELDS = OrderedDict( [ ("files", list), ("conf_thresh", float), # Confidence threshold ("iou_thresh", float), # Intersection over union threshold ("device", str), ("detection_frame_range", list), ("allocation_enabled", bool), ("data_hashes", list), ("rdp_thresh", float), ] ) [docs]class ModelTrainingWeights(base_orm.BaseORM): """ Model training weights. ORM: training_config_link, training_weights_link, """ DB_FIELDS = OrderedDict( [ ("model", str), ("training_config_link", str), ("training_weights_link", str), ] ) [docs]class ModelTrainingParams(base_orm.BaseORM): """ Model training parameters. ORM: model_hash, label_rows, epochs, batch_size, weights, device """ DB_FIELDS = OrderedDict( [ ("model_hash", str), ("label_rows", list), ("epochs", int), ("batch_size", int), ("weights", ModelTrainingWeights), ("device", str), ] )
__label__pos
0.974167
Often formulas must take into account specific criteria. To do this Sisense provides a feature called Measured Value, which like the SUMIF function in Excel, only performs a calculation when the values meet a set of criteria. Criteria for Measured Values may be based on any logical operators in a filter. formula 10 To filter the formula: 1. In the Data Browser, create your formula from the Data Browser and Functions, as explained in Using the Formula Editor. 2. Add the field (criteria) by which you want to filter the formula. Right-click the field and select Filter. 3. You can then filter the formula by listed items, text options, ranking, etc. When done, click OK. browserdata2 A simple example of Measured Value is the use of a list filter. A marketing team may need to count leads generated for a specific region such as North America. Even if leads come from many different countries, the measured value calculates leads generated only when the lead originates from the United States or Canada. formula 1 The above example as defined in the formula editor. syntax2 A more sophisticated case is the use of a ranking filter, for example a sales team may want to track the contribution of best-selling products to total revenue. However, what constitutes a popular product may change over time. A measured value can be created for sales which includes a condition that only shows sales for the top products for any month. This simultaneously filters the data but also takes into account changes in what classifies as a top product over time. formula 2 The above example as defined in the formula editor. syntax3 Measured Values are a powerful feature to take into account business logic and quickly perform calculations only when a specific set of criteria is met. Note about duplicate filtering: If your widget is filtered using measured values, then the measured value will override any other widget or dashboard filters you have for the same fields. Calculating Contributions Using the ALL Function The All() function returns the total amount for a dimension, and can be used for various use cases. In the following example, we will use the All function to calculate how much each country contributed towards the total cost of a campaign. Our final widget includes the following information: allfacts Step 1: The second column above represents a formula that sums up the total cost for all countries and does not represent the breakdown per country. The formula includes the calculation (total cost) followed by the all function (filter), followed by the dimension (country) in parenthesis. It looks like this: formula We can save (star) the above formula and call it Total cost for Countries, which will be used in the next step. Step 2: We can now use the above formula in another formula to calculate the contribution, like this: formula2 The result is the third column above (plus formatting the results as percentages).
__label__pos
0.889829
Author - Devender Kumar Post Views - 31 views Props and States Understanding Props and States in React Introduction In React.js, two fundamental concepts for managing data and passing information between components are Props and States. They play a vital role in building dynamic and interactive user interfaces. 1. What are Props and States? Props: Props (short for properties) are a way to pass data from a parent component to its child component. They are immutable and can only be passed in a uni-directional flow from parent to child. Props allow components to communicate and share data, enabling modular and reusable code. States: States represent the internal data of a component. Unlike props, states are mutable and can be modified within the component. They are managed and controlled by the component itself and are essential for building interactive and dynamic user interfaces. 2. The Difference between Props and States: Props: • Props are passed from parent to child components. • Props are read-only and cannot be modified within the child component. • Props help achieve component reusability and maintain a unidirectional data flow. • Changes in props trigger component re-rendering. States: • States are internal to a component and can be modified within the component. • States are mutable and can be updated using the ‘setState’ method. • States enable dynamic behavior and allow components to respond to user interactions. • Changes in states trigger component re-rendering. 3. Benefits of Using Props and States: Props: • Encourages reusability: Props enable components to be used in different contexts by passing varying data. • Provides data consistency: Props help maintain a controlled flow of data, ensuring consistency throughout the application. • Facilitates component communication: Props allow parent and child components to communicate and exchange information. States: • Enables interactivity: States enable components to respond to user interactions, making the UI dynamic and interactive. • Facilitates component-specific data management: States store and manage data that is specific to a component, ensuring encapsulation. • Allows for controlled updates: States ensure that updates to the component are controlled and trigger the necessary re-rendering. 4. How to Use Props and States: Props: • Pass props from a parent component to a child component by specifying them as attributes in the JSX markup. • Access props in the child component using the ‘props’ parameter or destructuring assignment. • Use props to display data or invoke functions within the child component. States: • Initialize a state within a component using the ‘useState’ hook. • Modify the state using the ‘setState’ method, either directly or by using functional updates. • Access and utilize the state within the component’s rendering logic or event handlers Example: import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); const incrementCount = () => { setCount(count + 1); }; return ( <div> <h2>Counter: {count}</h2> <button onClick={incrementCount}>Increment</button> </div> ); }; const App = () => { return ( <div> <h1>React Props and States Example</h1> <Counter /> </div> ); }; export default App; Conclusion: Props and States are essential concepts in React that enable effective data management, communication between components, and interactivity within the user interface. Props allow for the passage of data from parent to child components, while states enable components to manage and update their internal data. Understanding the differences and benefits The English language is the most widely used language as a medium of communication around the world. Having a certification for the English language can be an advantage. StudySection provides an English Certification Exam that tests English language proficiency in English grammar, reading, and writing. Leave a Reply Your email address will not be published.
__label__pos
0.999224
You may also like Archimedes and Numerical Roots The problem is how did Archimedes calculate the lengths of the sides of the polygons which needed him to be able to calculate square roots? Triangle Incircle Iteration Keep constructing triangles in the incircle of the previous triangle. What happens? Vedic Sutra - All from 9 and Last from 10 Vedic Sutra is one of many ancient Indian sutras which involves a cross subtraction method. Can you give a good explanation of WHY it works? Unusual Long Division - Square Roots Before Calculators Age 14 to 16 Challenge Level: Well done Carol in Leeds and others. This really is right at the top end of Stage 4 material and takes some following. Most people would need to go over the argument below several times, probably taking breaks and coming back again. There are quite a lot of numbers to keep track of so stay patient with yourself and here goes : The square roots of $40$, or $4000$, or $0.4$ all contain the same run of digits, just shifted left or right. When a number is reduced or increased by a factor of ten the square of that number is reduced or increased by a factor of one hundred. $4000$ reduces by a factor of one hundred to become $40$ so a factor of ten will connect their square roots. So if I knew what the square root of $4000$ was, the square root of $40$ would be the same but with the digits all one position lower (to the right). Now to work. This method is about deciding, one by one, what each digit is. The square root of $40$ starts with a six and then becomes decimal, so the square root of $4000$ starts with sixty-something, before becoming decimal. And it's that 'something' digit which I need to find. I want the whole number whose square is as close as possible to $4000$. I know it's a two digit number and I know the first of those digits is six. If $x$ stands for the second digit then I'm trying to make $(60 + x)^2$ as close as possible to $4000$. Written without the bracket $(60 + x)^2$ is $60^2 + 2.60.x + x^2$ so the challenge is to pick $x$ so that $2.60.x + x^2$ is as close as possible to $4000 - 3600$ $2.60.x + x^2$ is the same as $x(120 + x)$ and that matches the 'one hundred and twenty something, times something, to be close to $400$' in the second stage of working in the method. The answer was three. $123 \times3$ is $369$ If $63$ is the whole number part of the square root of $40 00$, what about the square root of $40 00 00$ ? (the gaps in the number help me think) The whole number part will have three digits : six, then three, then something else. Reasoning like before, I need to get $(630 + x)^2$ as close as possible to $400000$ Writing that without the brackets is $630^2 + 2.630.x + x^2$ From which I can see that I need $1260x + x^2$ to be as close as possible to $400000 -630^2$ Or rather, I need to find the digit $x$ so that $x(1260 + x)$ is as close as possible to $3100$. This corresponds to the third stage of working in the method. And the answer is two. $1262 \times2$ is $2524$ Now for something important : I notice that although $3100$ is the number in the working, this method for finding a square root doesn't do $400000 - 630^2$ directly to get it. The subtraction isn't $630^2$ straight off, that's $396900$, but rather an accumulation of subtractions : $36(0000)$ and $369(00)$, the zeros are needed to keep the correct column positions. Let's look at all the subtractions shown in the working so far : $36, 369, 2524,$ and $50576$ $123 \times3$ is $3(2 \times60 + 3)$ and came to $369 $ but $3(2 \times60 + 3)$ is the expanded bit of $(60 + 3)^2$ without the $60^2$ $1262 \times2$ is $2(2 \times630 + 2)$ and came to $2524 $ but $2(2 \times630 + 2)$ is the expanded bit of $(630 + 2)^2$ without the $630^2$ $12644 \times4$ is $4(2 \times6320 + 4)$ and came to $50576$ but $4(2 \times6320 + 4)$ is the expanded bit of $(6320 + 4)^2$ without the $6320^2 $
__label__pos
0.906038
Can I get Let's Encrypt certificates at QServers? Yes, you can. Let's Encrypt certificates can be installed for free through the cPanel of your hosting account at QServers. • 7 Users Found This Useful Was this answer helpful? Related Articles What is Let's Encrypt? Let's Encrypt is a free, automated, and open certificate authority (CA), run for the public's... What is displayed by browsers for HTTPS websites using Let's Encrypt SSL? Let's Encrypt is a trusted authority so there will be no warning messages as long as your site is... Is Let's Encrypt only for non-www domain names? The Let's Encrypt certificate will be issued for the domain.com and www.domain.com (if both... I installed Let's Encrypt but my site doesn't open via https Probably you haven't redirected your site to open through https and it defaults to http.If you... I read that Let's Encrypt can be exploited by hackers. Is that true? There is no known security vulnerability in Let's Encrypt that can be exploited. What is usually...
__label__pos
1
Switch animation when key pressed Hello, I am having trouble switching between two animations when key is pressed. I have two classes for each animation. Can anyone be kind enough to show me an example or explain how it should be coded. Thanks! hello, say you have 2 animations : anim1.draw(); anim2.draw(); you can chose the animation like so : // ofApp.h int animToPlay; //ofApp::setup() animToPlay = 0; // ofApp::draw() switch (animToPlay) { case 1 : anim1.draw(); break; case 2 : anim2.draw(); break; default : //whatever } // ofApp::keyPressed() void ofApp::keyPressed(int key){ if(key == 'a') { animToPlay = 1; } if(key == 'b') { animToPlay = 2; } } then use key ‘a’ or ‘b’ to change the animation Like so you can use any key to trigger any animation. if you only have 2 animations, code could be simpler.
__label__pos
0.999668
Beefy Boxes and Bandwidth Generously Provided by pair Networks XP is just a number   PerlMonks   Re^2: A mod2 Machine. by code-ninja (Scribe) on Jul 08, 2013 at 07:43 UTC ( #1043049=note: print w/ replies, xml ) Need Help?? in reply to Re: A mod2 Machine. in thread A mod2 Machine. Ok, I'll be more clear. First, when I said that the arithmetic operation will take more time, I said it with respect to the mod2 machine. Second, let's take your example (just a wild guess, is this game GO) #!/usr/bin/perl # note that %b modifier processes binary. Similarly, %x processes hexa +decimal and %o is for octal. use strict; use warnings; my ($move, $pos); $move = 0b1111111111111111; $pos = 0b0000111111111111; printf "%b\n", ($move ^ $pos); Even here, there are no arithmetical operations. Note that Exclusive Or is a logical operation. This is somewhat similar to a mod machine. You change state only if there are opposite inputs. The catch here is, if we'd have used strings instead of a number, there would've been a few more lines of code, keeping in mind and as you said, breaking the string and using regexes. I'm not saying that we should replace every arithmetic operation with string/logical operation, we just can't, I'm just trying to convey that there are better ways to do simple things that school teaches us in a very dogmatic way. I mean seriously, why should I actually divide a number by 2 and check the remainder when I can directly check the last digit?! Or why should I recursively divide and mod by 10 to generate the reverse of a number when I can do it in one line?! /* Apologies for using C, but its my "mother-tongue" :P */ #include <stdio.h> int main(int argc, char **argv) { int ; for(i = (strlen(argv[1]) - 1); i >= 0; i--){ printf("%c", *(argv[1] + i)); /* reverse a string, a number, a + sentence, a novel... */ } } Note/PS: Logical operations, too, are faster than arithmetical operations afaik. Comment on Re^2: A mod2 Machine. Select or Download Code Re^3: A mod2 Machine. by Laurent_R (Prior) on Jul 08, 2013 at 11:54 UTC I think we agree. My point is that I was using the ^ logical operation on actual binaries, something very similar to what you showed: my ($move, $pos); $move = 0b1111111111111111; $pos = 0b0000111111111111; printf "%b\n", ($move ^ $pos); But I needed to show that using actual binaries, such as 0b0000111111111111 was far superior to using binary strings, i.e. something like "0000111111111111". To do this, I needed to find the best possible way to do the equivalent of ^ for strings. And it turned out that the fastest way I found was to add the strings (meaning an implicit conversion of the string to a digit), giving a result like 1111222222222222, and then (with another implicit conversion) replacing the twos by zeros (with a command like tr/2/0/) to finally get "1111000000000000". And that was four times slower than the logical ^ on actual binaries. But it was still the fastest way to do it on strings. So that, in that case, arithmetics was faster than, for example, regexes or splitting the strings into individual characters to process them one by one.. I mean seriously, why should I actually divide a number by 2 and check the remainder when I can directly check the last digit?! I definitely agree with you on that. I was only saying that there are some other cases where arithmetics is faster than other means. Although, in my case, the best, by far, was to use actual binary nombers and a logical exclusive or (4 fimes faster than artithmetics on binary strings). Log In? Username: Password: What's my password? Create A New User Node Status? node history Node Type: note [id://1043049] help Chatterbox? and the web crawler heard nothing... How do I use this? | Other CB clients Other Users? Others surveying the Monastery: (8) As of 2015-07-01 22:12 GMT Sections? Information? Find Nodes? Leftovers? Voting Booth? The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ... Results (24 votes), past polls
__label__pos
0.56315
2.2.8.4.4 SMB_SET_FILE_DISPOSITION_INFO This information level structure is used in TRANS2_SET_FILE_INFORMATION (section 2.2.6.9) requests to mark or unmark the file specified in the request for deletion.<182>  SMB_SET_FILE_DISPOSITION_INFO    {    UCHAR DeletePending;    } DeletePending: (1 byte): An 8-bit field that is set to 0x01 to indicate that a file SHOULD be deleted when it is closed; otherwise, to 0x00. Show:
__label__pos
0.718372
openapi: 3.0.3 servers: - url: 'https://api.stadiamaps.com' - url: 'https://api-eu.stadiamaps.com' info: description: >- The Stadia Maps Geospatial APIs provide you with the data you need to build awesome applications. version: 6.4.0 title: Stadia Maps Geospatial APIs contact: name: Stadia Maps Support url: 'https://www.stadiamaps.com' email: [email protected] paths: /tz/lookup/v1: get: tags: - Geospatial operationId: tz-lookup summary: Get the current time zone information for any point on earth. description: >- The Stadia TZ API provides time zone information, as well as information about any special offset (such as DST) in effect based on the latest IANA TZDB. Note that this API may not be accurate for timestamps in the past and does not claim to report precise nautical times in the open ocean beyond territorial waters. security: - ApiKeyAuth: [ ] parameters: - name: lat in: query description: The latitude of the point you are interested in. required: true schema: type: number format: double minimum: -90 maximum: 90 - name: lng in: query description: The longitude of the point you are interested in. required: true schema: type: number format: double minimum: -180 maximum: 180 - name: timestamp in: query description: >- The UNIX timestamp at which the UTC and DST offsets will be calculated. This defaults to the present time. This endpoint is not necessarily guaranteed to be accurate for timestamps that occurred in the past. Time zone geographic boundaries change over time, so if the point you are querying for was previously in a different time zone, historical results will not be accurate. If, however, the point has been in the same geographic time zone for a very long time (ex: `America/New_York`), the historical data may be accurate for 100+ years in the past (depending on how far back the IANA TZDB rules have been specified). required: false schema: type: integer format: int64 minimum: 0 maximum: 8200290900000 # Approximately 262,000 years in the future, at which point Chrono breaks responses: '200': description: Returns the time zone metadata. content: application/json: schema: $ref: '#/components/schemas/tzResponse' '404': description: Time zone not found /elevation/v1: post: tags: - Geospatial operationId: elevation summary: Get the elevation profile along a polyline or at a point. description: >- The Stadia elevation API allows you to get the elevation of any point on earth. You can pass either a simple set of points or a Google encoded polyline string. This pairs well with our routing APIs, so you can generate an elevation profile for your next bike or run. security: - ApiKeyAuth: [ ] requestBody: content: application/json: schema: $ref: '#/components/schemas/heightRequest' responses: '200': description: Returns a list of elevations along the polyline, in meters. content: application/json: schema: $ref: '#/components/schemas/heightResponse' '400': description: Bad request; more details will be included /route/v1: post: tags: - Routing operationId: route summary: Get turn by turn routing instructions between two or more locations. description: >- The route (turn-by-turn) API computes routes between two or more locations. It supports a variety of tunable costing methods, and supports routing through intermediate waypoints and discontinuous multi-leg routes. security: - ApiKeyAuth: [ ] requestBody: content: application/json: schema: $ref: '#/components/schemas/routeRequest' responses: '200': description: Returns the computed route content: application/json: schema: $ref: '#/components/schemas/routeResponse' '400': description: Bad request; more details will be included '500': description: An internal parse error occurred; more details will be included /nearest_roads/v1: post: tags: - Routing operationId: nearest-roads summary: Find the nearest roads to the set of input locations. description: >- The nearest roads API allows you query for detailed information about streets and intersections near the input locations. security: - ApiKeyAuth: [ ] requestBody: content: application/json: schema: $ref: '#/components/schemas/nearestRoadsRequest' responses: '200': description: Returns a list of streets and intersections that match the query. content: application/json: schema: $ref: '#/components/schemas/nearestRoadsResponse' '400': description: Bad request; more details will be included /matrix/v1: post: tags: - Routing operationId: time-distance-matrix summary: Calculate a time distance matrix for use in an optimizer. description: >- The time distance matrix API lets you compare travel times between a set of possible start and end points. See https://docs.stadiamaps.com/limits/ for documentation of our latest limits. security: - ApiKeyAuth: [ ] requestBody: content: application/json: schema: $ref: '#/components/schemas/matrixRequest' responses: '200': description: Returns a matrix of times and distances between the start and end points. content: application/json: schema: $ref: '#/components/schemas/matrixResponse' '400': description: >- Bad request; more details will be included. NOTE: failure to find suitable edges near a location will result in a 400. /isochrone/v1: post: tags: - Routing operationId: isochrone summary: Calculate areas of equal travel time from a location. description: >- The isochrone API lets you compute or visualize areas of roughly equal travel time based on the routing graph. The resulting polygon can be rendered on a map and shaded much like elevation contours and used for exploring urban mobility. security: - ApiKeyAuth: [ ] requestBody: content: application/json: schema: $ref: '#/components/schemas/isochroneRequest' responses: '200': description: Returns a GeoJSON object which can be integrated into your geospatial application. content: application/json: schema: $ref: '#/components/schemas/isochroneResponse' '400': description: Bad request; more details will be included /optimized_route/v1: post: tags: - Routing operationId: optimized-route summary: Calculate an optimized route between a known start and end point. description: >- The optimized route API is a mix of the matrix and normal route API. For an optimized route, the start and end point are fixed, but the intermediate points will be re-ordered to form an optimal route visiting all nodes once. security: - ApiKeyAuth: [ ] requestBody: content: application/json: schema: $ref: '#/components/schemas/optimizedRouteRequest' responses: '200': description: >- Returns the optimized route, which looks more or less like a normal route response. The only significant difference is that the `locations` may be re-ordered and annotated with an `original_index`. content: application/json: schema: $ref: '#/components/schemas/routeResponse' '400': description: Bad request; more details will be included '500': description: An internal parse error occurred; more details will be included /map_match/v1: post: tags: - Routing operationId: map-match summary: Match a recorded route to the road network. description: >- The map matching API transforms a recorded route into navigation instructions like you would get from the `route` endpoint. The input can be in the form of either an encoded polyline, or (optionally) timestamped coordinates. security: - ApiKeyAuth: [ ] requestBody: content: application/json: schema: $ref: '#/components/schemas/mapMatchRequest' responses: '200': description: >- Returns the matched route, which looks more or less like a normal route response, optionally with a `linear_references` key. content: application/json: schema: $ref: '#/components/schemas/mapMatchRouteResponse' '400': description: Bad request; more details will be included '500': description: An internal parse error occurred; more details will be included /trace_attributes/v1: post: tags: - Routing operationId: trace-attributes summary: Trace the attributes of roads visited on a route. description: >- The trace attributes endpoint retrieves detailed information along a route, returning details for each section along the path, as well as any intersections encountered. In addition to tracing a recording route, this is great for providing just-in-time info to navigation applications, enabling them to conserve resources by omitting info like speed limits upfront that may be irrelevant if the user goes off-route. security: - ApiKeyAuth: [ ] requestBody: content: application/json: schema: $ref: '#/components/schemas/traceAttributesRequest' responses: '200': description: >- Returns the edges along the traced route with detailed info. content: application/json: schema: $ref: '#/components/schemas/traceAttributesResponse' '400': description: Bad request; more details will be included /geocoding/v1/autocomplete: get: tags: - Geocoding operationId: autocomplete summary: Search and geocode quickly based on partial input. description: >- Autocomplete enables interactive search-as-you-type user experiences, suggesting places as you type, along with information that will help your users find the correct place quickly. security: - ApiKeyAuth: [ ] parameters: - $ref: '#/components/parameters/searchText' - $ref: '#/components/parameters/searchFocusLat' - $ref: '#/components/parameters/searchFocusLon' - $ref: '#/components/parameters/searchBoundaryRectMinLat' - $ref: '#/components/parameters/searchBoundaryRectMaxLat' - $ref: '#/components/parameters/searchBoundaryRectMinLon' - $ref: '#/components/parameters/searchBoundaryRectMaxLon' - $ref: '#/components/parameters/searchBoundaryCircleLat' - $ref: '#/components/parameters/searchBoundaryCircleLon' - $ref: '#/components/parameters/searchBoundaryCircleRadius' - $ref: '#/components/parameters/searchBoundaryCountry' - $ref: '#/components/parameters/searchBoundaryGID' - $ref: '#/components/parameters/searchLayers' - $ref: '#/components/parameters/searchSources' - $ref: '#/components/parameters/size' - $ref: '#/components/parameters/peliasLang' responses: '200': description: Returns the collection of autocomplete results. content: application/json: schema: $ref: '#/components/schemas/peliasResponse' '400': description: Bad request /geocoding/v1/search: get: tags: - Geocoding operationId: search summary: Search for location and other info using a place name or address (forward geocoding). description: >- The search endpoint lets you search for addresses, points of interest, and administrative areas. This is most commonly used for forward geocoding applications where you need to find the geographic coordinates of an address. security: - ApiKeyAuth: [ ] parameters: - $ref: '#/components/parameters/searchText' - $ref: '#/components/parameters/searchFocusLat' - $ref: '#/components/parameters/searchFocusLon' - $ref: '#/components/parameters/searchBoundaryRectMinLat' - $ref: '#/components/parameters/searchBoundaryRectMaxLat' - $ref: '#/components/parameters/searchBoundaryRectMinLon' - $ref: '#/components/parameters/searchBoundaryRectMaxLon' - $ref: '#/components/parameters/searchBoundaryCircleLat' - $ref: '#/components/parameters/searchBoundaryCircleLon' - $ref: '#/components/parameters/searchBoundaryCircleRadius' - $ref: '#/components/parameters/searchBoundaryCountry' - $ref: '#/components/parameters/searchBoundaryGID' - $ref: '#/components/parameters/searchLayers' - $ref: '#/components/parameters/searchSources' - $ref: '#/components/parameters/size' - $ref: '#/components/parameters/peliasLang' responses: '200': description: Returns the collection of search results. content: application/json: schema: $ref: '#/components/schemas/peliasResponse' '400': description: Bad request /geocoding/v1/search/structured: get: tags: - Geocoding operationId: search-structured summary: Find locations matching components (structured forward geocoding). description: >- The structured search endpoint lets you search for addresses, points of interest, and administrative areas. Rather than a single string which the API must infer meaning from, the structured search endpoint allows you to specify the known components upfront, which is useful in many forward geocoding workflows. security: - ApiKeyAuth: [ ] parameters: - $ref: '#/components/parameters/searchAddress' - $ref: '#/components/parameters/searchNeighborhood' - $ref: '#/components/parameters/searchBorough' - $ref: '#/components/parameters/searchLocality' - $ref: '#/components/parameters/searchCounty' - $ref: '#/components/parameters/searchRegion' - $ref: '#/components/parameters/searchPostalCode' - $ref: '#/components/parameters/searchCountry' - $ref: '#/components/parameters/searchFocusLat' - $ref: '#/components/parameters/searchFocusLon' - $ref: '#/components/parameters/searchBoundaryRectMinLat' - $ref: '#/components/parameters/searchBoundaryRectMaxLat' - $ref: '#/components/parameters/searchBoundaryRectMinLon' - $ref: '#/components/parameters/searchBoundaryRectMaxLon' - $ref: '#/components/parameters/searchBoundaryCircleLat' - $ref: '#/components/parameters/searchBoundaryCircleLon' - $ref: '#/components/parameters/searchBoundaryCircleRadius' - $ref: '#/components/parameters/searchBoundaryCountry' - $ref: '#/components/parameters/searchBoundaryGID' - $ref: '#/components/parameters/searchLayers' - $ref: '#/components/parameters/searchSources' - $ref: '#/components/parameters/size' - $ref: '#/components/parameters/peliasLang' responses: '200': description: Returns the collection of search results. content: application/json: schema: $ref: '#/components/schemas/peliasResponse' '400': description: Bad request /geocoding/v1/reverse: get: tags: - Geocoding operationId: reverse summary: Find places and addresses near geographic coordinates (reverse geocoding). description: >- Reverse geocoding and search finds places and addresses near any geographic coordinates. security: - ApiKeyAuth: [ ] parameters: - $ref: '#/components/parameters/reverseLat' - $ref: '#/components/parameters/reverseLon' - $ref: '#/components/parameters/searchBoundaryCircleRadius' - $ref: '#/components/parameters/searchLayers' - $ref: '#/components/parameters/searchSources' - $ref: '#/components/parameters/searchBoundaryCountry' - $ref: '#/components/parameters/searchBoundaryGID' - $ref: '#/components/parameters/size' - $ref: '#/components/parameters/peliasLang' responses: '200': description: Returns the collection of search results. content: application/json: schema: $ref: '#/components/schemas/peliasResponse' '400': description: Bad request /geocoding/v1/place: get: tags: - Geocoding operationId: place summary: Retrieve details of a place using its GID. description: >- Many search result components include an associated GID field (for example, an address may have a `localadmin_gid`). The place endpoint lets you look up these places directly by ID. Note that these IDs are not stable for all sources. See the [online documentation](https://docs.stadiamaps.com/geocoding-search-autocomplete/place-lookup/) for details. security: - ApiKeyAuth: [ ] parameters: - $ref: '#/components/parameters/placeIDs' - $ref: '#/components/parameters/peliasLang' responses: '200': description: Returns the collection of search results. content: application/json: schema: $ref: '#/components/schemas/peliasResponse' '400': description: Bad request components: securitySchemes: ApiKeyAuth: type: apiKey in: query name: api_key schemas: requestId: type: string description: An identifier to disambiguate requests (echoed by the server). example: kesklinn coordinate: type: object properties: lat: type: number format: double description: The latitude of a point in the shape. example: 59.436884 minimum: -90 maximum: 90 lon: type: number format: double description: The longitude of a point in the shape. example: 24.742595 minimum: -180 maximum: 180 required: - lat - lon valhallaLongUnits: type: string enum: - miles - kilometers default: kilometers valhallaLanguages: type: string enum: - bg-BG - ca-ES - cs-CZ - da-DK - de-DE - el-GR - en-GB - en-US-x-pirate - en-US - es-ES - et-EE - fi-FI - fr-FR - hi-IN - hu-HU - it-IT - ja-JP - nb-NO - nl-NL - pl-PL - pt-BR - pt-PT - ro-RO - ru-RU - sk-SK - sl-SI - sv-SE - tr-TR - uk-UA default: en-US simpleRoutingWaypoint: allOf: - $ref: '#/components/schemas/coordinate' - type: object properties: type: type: string enum: - break - through - via - break_through description: >- A `break` represents the start or end of a leg, and allows reversals. A `through` location is an intermediate waypoint that must be visited between `break`s, but at which reversals are not allowed. A `via` is similar to a `through` except that reversals are allowed. A `break_through` is similar to a `break` in that it can be the start/end of a leg, but does not allow reversals. default: break routingWaypoint: allOf: - $ref: '#/components/schemas/simpleRoutingWaypoint' - type: object properties: heading: type: integer description: >- The preferred direction of travel when starting the route, in integer clockwise degrees from north. North is 0, south is 180, east is 90, and west is 270. minimum: 0 maximum: 360 heading_tolerance: type: integer description: >- The tolerance (in degrees) determining whether a street is considered the same direction. minimum: 0 maximum: 360 default: 60 minimum_reachability: type: integer description: >- The minimum number of nodes that must be reachable for a given edge to consider that edge as belonging to a connected region. If a candidate edge has fewer connections, it will be considered a disconnected island. minimum: 0 default: 50 radius: type: integer description: >- The distance (in meters) to look for candidate edges around the location for purposes of snapping locations to the route graph. If there are no candidates within this distance, the closest candidate within a reasonable search distance will be used. This is subject to clamping by internal limits. minimum: 0 default: 0 rank_candidates: type: boolean description: >- If true, candidates will be ranked according to their distance from the target location as well as other factors. If false, candidates will only be ranked using their distance from the target. default: true preferred_side: type: string enum: - same - opposite - either description: >- If the location is not offset from the road centerline or is closest to an intersection, this option has no effect. Otherwise, the preferred side of street is used to determine whether or not the location should be visited from the same, opposite or either side of the road with respect to the side of the road the given locale drives on. node_snap_tolerance: type: integer description: >- During edge correlation this is the tolerance (in meters) used to determine whether or not to snap to the intersection rather than along the street, if the snap location is within this distance from the intersection, the intersection is used instead. minimum: 0 default: 5 street_side_tolerance: type: integer description: >- A tolerance in meters from the edge centerline used for determining the side of the street that the location is on. If the distance to the centerline is less than this tolerance, no side will be inferred. Otherwise, the left or right side will be selected depending on the direction of travel. minimum: 0 default: 5 street_side_max_distance: type: integer description: >- A tolerance in meters from the edge centerline used for determining the side of the street that the location is on. If the distance to the centerline is greater than this tolerance, no side will be inferred. Otherwise, the left or right side will be selected depending on the direction of travel. minimum: 0 default: 1000 search_filter: type: object properties: exclude_tunnel: type: boolean description: Excludes roads marked as tunnels default: false exclude_bridge: type: boolean description: Excludes roads marked as bridges default: false exclude_ramp: type: boolean description: Excludes roads marked as ramps default: false exclude_closures: type: boolean description: Excludes roads marked as closed default: true min_road_class: description: The lowest road class allowed default: service_other allOf: - $ref: '#/components/schemas/roadClass' max_road_class: description: The highest road class allowed default: motorway allOf: - $ref: '#/components/schemas/roadClass' routingResponseWaypoint: allOf: - $ref: '#/components/schemas/simpleRoutingWaypoint' - type: object properties: original_index: type: integer description: The original index of the location (locations may be reordered for optimized routes) minimum: 0 mapMatchWaypoint: allOf: - $ref: '#/components/schemas/simpleRoutingWaypoint' - type: object properties: time: type: integer description: >- The timestamp of the waypoint, in seconds. This can inform the map matching algorithm about when the point was measured. A UNIX timestamp, or any increasing integer sequence measuring seconds from some reference point can be used. matrixWaypoint: allOf: - $ref: '#/components/schemas/coordinate' - type: object properties: search_cutoff: type: integer description: >- The cutoff (in meters) at which we will assume the input is too far away from civilisation to be worth correlating to the nearest graph elements. The default is 35 km. default: break roadClass: type: string enum: - motorway - trunk - primary - secondary - tertiary - unclassified - residential - service_other description: Class of road (ranked in descending order) costingModel: type: string enum: - auto - bus - taxi - truck - bicycle - bikeshare - motor_scooter - motorcycle - pedestrian - low_speed_vehicle description: >- A model which influences the routing based on the type of travel. The costing model affects parameters ranging from which roads are legally accessible to preferences based on comfort or speed. See https://valhalla.github.io/valhalla/api/turn-by-turn/api-reference/#costing-models for in-depth descriptions of each costing model. isochroneCostingModel: type: string enum: - auto - bicycle - pedestrian matrixCostingModel: type: string enum: - auto - bus - taxi - truck - bicycle - bikeshare - motor_scooter - motorcycle - pedestrian - low_speed_vehicle mapMatchCostingModel: type: string enum: - auto - bicycle - bus - pedestrian costingOptions: type: object properties: auto: $ref: '#/components/schemas/autoCostingOptions' bus: $ref: '#/components/schemas/autoCostingOptions' taxi: $ref: '#/components/schemas/autoCostingOptions' truck: $ref: '#/components/schemas/truckCostingOptions' bicycle: $ref: '#/components/schemas/bicycleCostingOptions' motor_scooter: $ref: '#/components/schemas/motorScooterCostingOptions' motorcycle: $ref: '#/components/schemas/motorcycleCostingOptions' pedestrian: $ref: '#/components/schemas/pedestrianCostingOptions' low_speed_vehicle: $ref: '#/components/schemas/lowSpeedVehicleCostingOptions' useFerryCostingOption: type: number format: double description: >- A measure of willingness to take ferries. Values near 0 attempt to avoid ferries, and values near 1 will favour them. Note that as some routes may be impossible without ferries, 0 does not guarantee avoidance of them. default: 0.5 minimum: 0 maximum: 1 useLivingStreetsCostingOption: type: number format: double description: >- A measure of willingness to take living streets. Values near 0 attempt to avoid them, and values near 1 will favour them. Note that as some routes may be impossible without living streets, 0 does not guarantee avoidance of them. The default value is 0 for trucks; 0.1 for other motor vehicles; 0.5 for bicycles; and 0.6 for pedestrians. minimum: 0 maximum: 1 useTracksCostingOption: type: number format: double description: >- A measure of willingness to take track roads. Values near 0 attempt to avoid them, and values near 1 will favour them. Note that as some routes may be impossible without track roads, 0 does not guarantee avoidance of them. The default value is 0 for automobiles, busses, and trucks; and 0.5 for all other costing modes. minimum: 0 maximum: 1 servicePenaltyCostingOption: type: integer description: >- A penalty applied to transitions to service roads. This penalty can be used to reduce the likelihood of suggesting a route with service roads unless absolutely necessary. The default penalty is 15 for cars, busses, motor scooters, and motorcycles; and zero for others. serviceFactorCostingOption: type: number format: double description: >- A factor that multiplies the cost when service roads are encountered. The default is 1.2 for cars and busses, and 1 for trucks, motor scooters, and motorcycles. default: 1 useHillsCostingOption: type: number format: double description: >- A measure of willingness to take tackle hills. Values near 0 attempt to avoid hills and steeper grades even if it means a longer route, and values near 1 indicates that the user does not fear them. Note that as some routes may be impossible without hills, 0 does not guarantee avoidance of them. default: 0.5 minimum: 0 maximum: 1 baseCostingOptions: type: object properties: maneuver_penalty: type: integer description: A penalty (in seconds) applied when transitioning between roads (determined by name). default: 5 gate_cost: type: integer description: The estimated cost (in seconds) when a gate is encountered. default: 15 gate_penalty: type: integer description: >- A penalty (in seconds) applied to the route cost when a gate is encountered. This penalty can be used to reduce the likelihood of suggesting a route with gates unless absolutely necessary. default: 300 country_crossing_cost: type: integer description: The estimated cost (in seconds) when encountering an international border. default: 600 country_crossing_penalty: type: integer description: >- A penalty applied to transitions to international border crossings. This penalty can be used to reduce the likelihood of suggesting a route with border crossings unless absolutely necessary. default: 0 service_penalty: $ref: '#/components/schemas/servicePenaltyCostingOption' service_factor: $ref: '#/components/schemas/serviceFactorCostingOption' use_living_streets: $ref: '#/components/schemas/useLivingStreetsCostingOption' use_ferry: $ref: '#/components/schemas/useFerryCostingOption' ignore_restrictions: type: boolean description: >- If set to true, ignores any restrictions (eg: turn and conditional restrictions). Useful for matching GPS traces to the road network regardless of restrictions. ignore_non_vehicular_restrictions: type: boolean description: >- If set to true, ignores most restrictions (eg: turn and conditional restrictions), but still respects restrictions that impact vehicle safety such as weight and size. ignore_oneways: type: boolean description: >- If set to true, ignores directional restrictions on roads. Useful for matching GPS traces to the road network regardless of restrictions. autoCostingOptions: allOf: - $ref: '#/components/schemas/baseCostingOptions' - type: object properties: height: type: number format: double description: The height of the automobile (in meters). default: 1.9 width: type: number format: double description: The width of the automobile (in meters). default: 1.6 toll_booth_cost: type: integer description: The estimated cost (in seconds) when a toll booth is encountered. default: 15 toll_booth_penalty: type: integer description: >- A penalty (in seconds) applied to the route cost when a toll booth is encountered. This penalty can be used to reduce the likelihood of suggesting a route with toll booths unless absolutely necessary. default: 0 ferry_cost: type: integer description: The estimated cost (in seconds) when a ferry is encountered. default: 300 use_highways: type: number format: double description: >- A measure of willingness to take highways. Values near 0 attempt to avoid highways, and values near 1 will favour them. Note that as some routes may be impossible without highways, 0 does not guarantee avoidance of them. default: 0.5 minimum: 0 maximum: 1 use_tolls: type: number format: double description: >- A measure of willingness to take toll roads. Values near 0 attempt to avoid tolls, and values near 1 will favour them. Note that as some routes may be impossible without tolls, 0 does not guarantee avoidance of them. default: 0.5 minimum: 0 maximum: 1 use_tracks: $ref: '#/components/schemas/useTracksCostingOption' top_speed: type: integer description: The top speed (in kph) that the vehicle is capable of travelling. default: 140 minimum: 10 maximum: 252 shortest: type: boolean description: >- If true changes the cost metric to be quasi-shortest (pure distance-based) costing. This will disable ALL other costing factors. default: false ignore_closures: type: boolean description: >- If true, ignores all known closures. This option cannot be set if `location.search_filter.exclude_closures` is also specified. default: false include_hov2: type: boolean description: >- If true, indicates the desire to include HOV roads with a 2-occupant requirement in the route when advantageous. default: false include_hov3: type: boolean description: >- If true, indicates the desire to include HOV roads with a 3-occupant requirement in the route when advantageous. default: false include_hot: type: boolean description: >- If true, indicates the desire to include toll roads which require the driver to pay a toll if the occupant requirement isn't met default: false alley_factor: type: number format: double description: A factor that multiplies the cost when alleys are encountered. default: 1 truckCostingOptions: allOf: - $ref: '#/components/schemas/autoCostingOptions' - type: object properties: height: type: number format: double description: The height of the truck (in meters). default: 4.11 width: type: number format: double description: The width of the truck (in meters). default: 2.6 length: type: number format: double description: The length of the truck (in meters). default: 21.64 weight: type: number format: double description: The weight of the truck (in tonnes). default: 21.77 axle_load: type: number format: double description: The axle load of the truck (in tonnes). default: 9.07 hazmat: type: boolean description: Whether or not the truck is carrying hazardous materials. default: false bicycleCostingOptions: allOf: - $ref: '#/components/schemas/baseCostingOptions' - type: object properties: bicycle_type: type: string enum: - Road - Hybrid - Cross - Mountain default: Hybrid description: >- The type of bicycle: * Road: has narrow tires and is generally lightweight and designed for speed on paved surfaces * Hybrid or City: designed for city riding or casual riding on roads and paths with good surfaces * Cross: similar to a road bike, but has wider tires so it can handle rougher surfaces * Mountain: able to handle most surfaces, but generally heavier and slower on paved surfaces cycling_speed: type: integer description: >- The average comfortable travel speed (in kph) along smooth, flat roads. The costing will vary the speed based on the surface, bicycle type, elevation change, etc. This value should be the average sustainable cruising speed the cyclist can maintain over the entire route. The default speeds are as follows based on bicycle type: * Road - 25kph * Cross - 20kph * Hybrid - 18kph * Mountain - 16kph use_roads: type: number format: double description: >- A measure of willingness to use roads alongside other vehicles. Values near 0 attempt to avoid roads and stay on cycleways, and values near 1 indicate the cyclist is more comfortable on roads. default: 0.5 minimum: 0 maximum: 1 use_hills: $ref: '#/components/schemas/useHillsCostingOption' avoid_bad_surfaces: type: number format: double description: >- A measure of how much the cyclist wants to avoid roads with poor surfaces relative to the type of bicycle being ridden. When 0, there is no penalization of roads with poorer surfaces, and only bicycle speed is taken into account. As the value approaches 1, roads with poor surfaces relative to the bicycle type receive a heaver penalty, so they will only be taken if they significantly reduce travel time. When the value is 1, all bad surfaces are completely avoided from the route, including the start and end points. default: 0.25 minimum: 0 maximum: 1 bss_return_cost: type: integer description: The estimated cost (in seconds) to return a bicycle in `bikeshare` mode. default: 120 bss_return_penalty: type: integer description: A penalty (in seconds) to return a bicycle in `bikeshare` mode. default: 0 motorScooterCostingOptions: allOf: - $ref: '#/components/schemas/autoCostingOptions' - type: object properties: use_primary: type: number format: double description: >- A measure of willingness to use primary roads. Values near 0 attempt to avoid primary roads and stay on roads with lower speeds, and values near 1 indicate the rider is more comfortable on these roads. default: 0.5 minimum: 0 maximum: 1 use_hills: type: number format: double description: >- A measure of willingness to take tackle hills. Values near 0 attempt to avoid hills and steeper grades even if it means a longer route, and values near 1 indicates that the rider does not fear them. Note that as some routes may be impossible without hills, 0 does not guarantee avoidance of them. default: 0.5 minimum: 0 maximum: 1 motorcycleCostingOptions: allOf: - $ref: '#/components/schemas/autoCostingOptions' - type: object properties: use_highways: type: number format: double description: >- A measure of willingness to use highways. Values near 0 attempt to avoid highways and stay on roads with lower speeds, and values near 1 indicate the rider is more comfortable on these roads. default: 1.0 minimum: 0 maximum: 1 use_trails: type: number format: double description: >- A measure of the rider's sense of adventure. Values near 0 attempt to avoid highways and stay on roads with potentially unsuitable terrain (trails, tracks, unclassified, or bad surfaces), and values near 1 will tend to avoid major roads and route on secondary roads. default: 0.0 minimum: 0 maximum: 1 pedestrianCostingOptions: type: object properties: walking_speed: type: integer description: Walking speed in kph. default: 5.1 minimum: 0.5 maximum: 25 walkway_factor: type: number format: double description: A factor that multiplies the cost when walkways are encountered. default: 1 sidewalk_factor: type: number format: double description: A factor that multiplies the cost when sidewalks are encountered. default: 1 alley_factor: type: number format: double description: A factor that multiplies the cost when alleys are encountered. default: 2 driveway_factor: type: number format: double description: A factor that multiplies the cost when driveways are encountered. default: 5 step_penalty: type: integer description: A penalty (in seconds) added to each transition onto a path with steps or stairs. default: 30 use_ferry: $ref: '#/components/schemas/useFerryCostingOption' use_living_streets: $ref: '#/components/schemas/useLivingStreetsCostingOption' use_tracks: $ref: '#/components/schemas/useTracksCostingOption' use_hills: $ref: '#/components/schemas/useHillsCostingOption' use_lit: type: number format: double description: >- A measure of preference for streets that are lit. 0 indicates indifference toward lit streets, and 1 indicates that unlit streets should be avoided. Note that even with values near 1, there is no guarantee that the returned route will include lit segments. default: 0 minimum: 0 maximum: 1 service_penalty: $ref: '#/components/schemas/servicePenaltyCostingOption' service_factor: $ref: '#/components/schemas/serviceFactorCostingOption' max_hiking_difficulty: type: integer description: The maximum difficulty of hiking trails allowed. This corresponds to the OSM `sac_scale`. default: 1 minimum: 1 maximum: 6 bss_rent_cost: type: integer description: The estimated cost (in seconds) to rent a bicycle from a sharing station in `bikeshare` mode. default: 120 bss_rent_penalty: type: integer description: A penalty (in seconds) to rent a bicycle in `bikeshare` mode. default: 0 lowSpeedVehicleCostingOptions: allOf: - $ref: '#/components/schemas/baseCostingOptions' - type: object properties: vehicle_type: type: string enum: - low_speed_vehicle - golf_cart default: low_speed_vehicle description: >- The type of vehicle: * low_speed_vehicle (BETA): a low-speed vehicle which falls under a different regulatory and licensing regime than automobiles (ex: LSV in the US and Canada, Quadricycles in the EU, etc.) * golf_cart: a street legal golf cart that is under a similar regulator regime as the generic LSV laws, but may need to follow special paths when available or abide by restrictions specific to golf carts. top_speed: type: integer description: >- The top speed (in kph) that the vehicle is capable of travelling. This impacts travel time calculations as well as which roads are preferred. A very low speed vehicle will tend to prefer lower speed roads even in the presence of other legal routes. default: 35 minimum: 20 maximum: 60 max_allowed_speed_limit: type: integer description: >- The maximum speed limit for highways on which it is legal for the vehicle to travel. Defaults to 57 (kph; around 35 mph). Acceptable values range from 20 to 80. Highways with *tagged* speed limits higher than this value will not be routed over (some caveats apply; this feature is still BETA). default: 57 minimum: 20 maximum: 80 directionsOptions: type: object properties: units: $ref: '#/components/schemas/distanceUnit' language: $ref: '#/components/schemas/valhallaLanguages' directions_type: type: string enum: - none - maneuvers - instructions default: instructions description: >- The level of directional narrative to include. Locations and times will always be returned, but narrative generation verbosity can be controlled with this parameter. distanceUnit: type: string enum: - km - mi default: km matrixDistance: type: object properties: distance: type: number format: double nullable: true description: >- The distance (in `units`) between the location in `sources` at `from_index` and the location in `targets` at `to_index`. This value may be 0 in the case that the source and destination are the same, and `null` if no route was found between the locations. time: type: integer nullable: true description: >- The travel time (in seconds) between the location in `sources` at `from_index` and the location in `targets` at `to_index`. This value may be 0 in the case that the source and destination are the same, and `null` if no route was found between the locations. from_index: type: integer description: The index of the start location in the `sources` array. to_index: type: integer description: The index of the end location in the `targets` array. required: - distance - time - from_index - to_index contour: type: object properties: time: type: number format: double description: The time in minutes for the contour. Mutually exclusive of distance. example: 15 distance: type: number format: double description: The distance in km for the contour. Mutually exclusive of time. example: 10.0 color: type: string description: >- The color for the output contour, specified as a hex value (without a leading `#`). If no color is specified, one will be assigned automatically. example: aabbcc mapMatchTraceOptions: type: object properties: search_radius: type: integer description: The search radius, in meters, when trying to match each trace point. gps_accuracy: type: number format: double description: The accuracy of the GPS, in meters. breakage_distance: type: number format: double description: The breaking distance, in meters, between trace points. interpolation_distance: type: number format: double description: The interpolation distance, in meters, beyond which trace points are merged together. turn_penalty_factor: type: integer description: >- Penalizes turns from one road segment to next. For a pedestrian trace, you may see a back-and-forth motion along the streets of your path with the default settings. Try increasing the turn penalty factor to 500 to reduce jitter in the output. Note that if GPS accuracy is already good, increasing this above the default will usually negatively affect the quality of map matching. traceAttributeKey: type: string enum: - edge.names - edge.length - edge.speed - edge.road_class - edge.begin_heading - edge.end_heading - edge.begin_shape_index - edge.end_shape_index - edge.traversability - edge.use - edge.toll - edge.unpaved - edge.tunnel - edge.bridge - edge.roundabout - edge.internal_intersection - edge.drive_on_right - edge.surface - edge.sign.exit_number - edge.sign.exit_branch - edge.sign.exit_toward - edge.sign.exit_name - edge.travel_mode - edge.vehicle_type - edge.pedestrian_type - edge.bicycle_type - edge.transit_type - edge.id - edge.way_id - edge.weighted_grade - edge.max_upward_grade - edge.max_downward_grade - edge.mean_elevation - edge.lane_count - edge.cycle_lane - edge.bicycle_network - edge.sac_scale - edge.sidewalk - edge.density - edge.speed_limit - edge.truck_speed - edge.truck_route - node.intersecting_edge.begin_heading - node.intersecting_edge.from_edge_name_consistency - node.intersecting_edge.to_edge_name_consistency - node.intersecting_edge.driveability - node.intersecting_edge.cyclability - node.intersecting_edge.walkability - node.intersecting_edge.use - node.intersecting_edge.road_class - node.elapsed_time - node.admin_index - node.type - node.fork - node.time_zone - osm_changeset - shape - admin.country_code - admin.country_text - admin.state_code - admin.state_text - matched.point - matched.type - matched.edge_index - matched.begin_route_discontinuity - matched.end_route_discontinuity - matched.distance_along_edge - matched.distance_from_trace_point traceAttributeFilterOptions: type: object properties: attributes: type: array items: $ref: '#/components/schemas/traceAttributeKey' minItems: 1 action: type: string enum: - include - exclude description: Determines whether the list of attributes will be used as a whitelist or a blacklist. required: - attributes - action traceEdge: type: object properties: names: type: array items: type: string description: The name(s) of the road at this edge, if any. length: type: number format: double description: The length of this edge in `units`. speed: type: integer description: >- The speed of this edge in `units`/hr, in terms of average/free-flow speed for routing purposes. This is affected by any number of factors such as the road service, vehicle type, etc. and not just the posted speed limits. road_class: $ref: '#/components/schemas/roadClass' begin_heading: type: integer description: The direction at the beginning of an edge. The units are degrees clockwise from north. end_heading: type: integer description: The direction at the end of an edge. The units are degrees clockwise from north. begin_shape_index: type: integer description: Index into the list of shape points for the start of the edge. end_shape_index: type: integer description: Index into the list of shape points for the end of the edge. traversability: $ref: '#/components/schemas/traversability' use: $ref: '#/components/schemas/edgeUse' toll: type: boolean description: True if the edge has a toll. unpaved: type: boolean description: True if the edge has rough payment. tunnel: type: boolean description: True if the edge is a tunnel. bridge: type: boolean description: True if the edge is a bridge. roundabout: type: boolean description: True if the edge is a roundabout. internal_intersection: type: boolean description: True if the edge is an internal intersection. drive_on_right: type: boolean description: True if the edge is in an area where you must drive on the right side of the road. surface: type: string enum: - paved_smooth - paved - paved_rough - compacted - dirt - gravel - path - impassable description: The type of surface for the edge. sign: $ref: '#/components/schemas/edgeSign' travel_mode: $ref: '#/components/schemas/travelMode' vehicle_type: type: string enum: - car - motorcycle - bus - tractor_trailer - golf_cart - low_speed_vehicle pedestrian_type: type: string enum: - foot - wheelchair - segway bicycle_type: type: string enum: - road - cross - hybrid - mountain transit_type: type: string enum: - tram - metro - rail - bus - ferry - cable_car - gondola - funicular id: type: integer format: int64 way_id: type: integer format: int64 description: The way identifier of the edge in OSM. weighted_grade: type: number format: double description: >- The weighted grade factor. Valhalla manufactures a weighted grade from elevation data. It is a measure used for hill avoidance in routing - sort of a relative energy use along an edge. But since an edge in Valhalla can possibly go up and down over several hills it might not equate to what you would normally think of as grade. max_upward_grade: type: integer description: The maximum upward slope. A value of 32768 indicates no elevation data is available for this edge. max_downward_grade: type: integer description: The maximum downward slope. A value of 32768 indicates no elevation data is available for this edge. mean_elevation: type: integer description: >- The mean elevation along the edge. Units are meters by default. If the `units` are specified as miles, then the mean elevation is returned in feet. A value of 32768 indicates no elevation data is available for this edge. lane_count: type: integer description: The number of lanes for this edge. cycle_lane: type: string enum: - none - shared - dedicated - separated description: The type of cycle lane (if any) along this edge. bicycle_network: type: integer description: >- The type of bicycle network, if any. This is an integer comprised of constants bitwise or'd together. For example, a route that's part of both a local and mountain network would have a value of 12. 1 - National 2 - Regional 4 - Local 8 - Mountain sac_scale: type: integer description: >- The difficulty of the hiking trail according to the SAC scale. 0 - No Sac Scale 1 - Hiking 2 - Mountain hiking 3 - Demanding mountain hiking 4 - Alpine hiking 5 - Demanding alpine hiking 6 - Difficult alpine hiking sidewalk: type: string enum: - left - right - both - none density: type: integer speed_limit: description: >- The speed limit along the edge measured in `units`/hr. This may be either an integer or the string "unlimited" if speed limit data is available. If absent, there is no speed limit data available. truck_speed: type: integer description: >- The truck speed of this edge in `units`/hr, in terms of average/free-flow speed for routing purposes. This is affected by any number of factors such as the road service, vehicle type, etc. and not just the posted speed limits. truck_route: type: boolean description: True if the edge is part of a truck route/network. end_node: $ref: '#/components/schemas/endNode' adminRegion: type: object properties: country_code: type: string description: The [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. country_text: type: string description: The country name state_code: type: string description: The abbreviation code for the state (varies by country). state_text: type: string description: The state name. matchedPoint: type: object properties: lat: type: number format: double description: The latitude of the matched point. lon: type: number format: double description: The longitude of the matched point. type: type: string enum: - unmatched - interpolated - matched edge_index: type: integer description: The index of the edge in the list of `edges`. This key will be missing if the point is unmatched. begin_route_discontinuity: type: boolean description: If true, this match result is the begin location of a route discontinuity. default: false end_route_discontinuity: type: boolean description: If true, this match result is the end location of a route discontinuity. default: false distance_along_edge: type: number format: double description: >- The distance along the associated edge for this matched point, expressed as a value between 0 and 1. For example, if the matched point is halfway along the edge, then the value will be 0.5. This key will be absent if the point is unmatched. distance_from_trace_point: type: number format: double description: >- The distance in meters from the trace point to the matched point. This key will be absent if the point is unmatched. required: - lat - lon - type heightRequest: type: object properties: id: $ref: '#/components/schemas/requestId' shape: type: array items: $ref: '#/components/schemas/coordinate' description: REQUIRED if `encoded_polyline` is not present. encoded_polyline: type: string description: REQUIRED if `shape` is not present. An encoded polyline (https://developers.google.com/maps/documentation/utilities/polylinealgorithm). shape_format: type: string enum: - polyline6 - polyline5 default: polyline6 description: Specifies whether the polyline is encoded with 6 digit precision (polyline6) or 5 digit precision (polyline5). range: type: boolean default: false description: Controls whether or not the returned array is one-dimensional (height only) or two-dimensional (with a range and height). The range dimension can be used to generate a graph or steepness gradient along a route. height_precision: type: integer default: 0 minimum: 0 maximum: 2 description: >- The decimal precision (number of digits after the point) of the output. When 0, integer values are returned. Valid values are 0, 1, and 2. resample_distance: type: integer minimum: 10 description: >- The distance at which the input polyline should be sampled to provide uniform distances between points. If not set, the input shape will be used as-is. example: { "id": "kesklinn", "shape": [ { "lat": 59.436884, "lon": 24.742595 } ], "shape_format": "polyline6", "range": false, "height_precision": 0 } matrixRequest: allOf: - type: object properties: id: $ref: '#/components/schemas/requestId' sources: type: array items: $ref: '#/components/schemas/matrixWaypoint' description: The list of starting locations minItems: 1 targets: type: array items: $ref: '#/components/schemas/matrixWaypoint' description: The list of ending locations minItems: 1 costing: $ref: '#/components/schemas/matrixCostingModel' costing_options: $ref: '#/components/schemas/costingOptions' matrix_locations: type: integer description: >- Only applicable to one-to-many or many-to-one requests. This defaults to all locations. When specified explicitly, this option allows a partial result to be returned. This is basically equivalent to "find the closest/best locations out of the full set." This can have a dramatic improvement for large requests. - $ref: '#/components/schemas/directionsOptions' required: - sources - targets - costing example: { "sources": [ { "lat": 40.744014, "lon": -73.990508 } ], "targets": [ { "lat": 40.744014, "lon": -73.990508 }, { "lat": 40.739735, "lon": -73.979713 }, { "lat": 40.752522, "lon": -73.985015 }, { "lat": 40.750117, "lon": -73.983704 }, { "lat": 40.750552, "lon": -73.993519 } ], "costing": "pedestrian" } isochroneRequest: type: object properties: id: $ref: '#/components/schemas/requestId' locations: type: array items: $ref: '#/components/schemas/coordinate' costing: $ref: '#/components/schemas/isochroneCostingModel' costing_options: $ref: '#/components/schemas/costingOptions' contours: type: array items: $ref: '#/components/schemas/contour' maxItems: 4 minItems: 1 polygons: type: boolean default: false description: >- If true, the generated GeoJSON will use polygons. The default is to use LineStrings. Polygon output makes it easier to render overlapping areas in some visualization tools (such as MapLibre renderers). denoise: type: number format: double default: 1 minimum: 0 maximum: 1 description: >- A value in the range [0, 1] which will be used to smooth out or remove smaller contours. A value of 1 will only return the largest contour for a given time value. A value of 0.5 drops any contours that are less than half the area of the largest contour in the set of contours for that same time value. generalize: type: number format: double default: 200.0 description: >- The value in meters to be used as a tolerance for Douglas-Peucker generalization. show_locations: type: boolean default: false description: >- If true, then the output GeoJSON will include the input locations as two MultiPoint features: one for the exact input coordinates, and a second for the route network node location that the point was snapped to. required: - locations - contours - costing example: >- { "id": "kesklinn", "locations": [ { "lat": 59.436884, "lon": 24.742595 } ], "costing": "pedestrian", "contours": [ { "time": 5, "color": "aabbcc" } ], "polygons": true } routeRequest: allOf: - type: object properties: id: $ref: '#/components/schemas/requestId' locations: type: array items: $ref: '#/components/schemas/routingWaypoint' minItems: 2 costing: $ref: '#/components/schemas/costingModel' costing_options: $ref: '#/components/schemas/costingOptions' exclude_locations: type: array items: $ref: '#/components/schemas/routingWaypoint' description: >- This has the same format as the locations list. Locations are mapped to the closed road(s), and these road(s) are excluded from the route path computation. exclude_polygons: type: array items: type: array items: type: array items: type: number format: double description: >- One or multiple exterior rings of polygons in the form of nested JSON arrays. Roads intersecting these rings will be avoided during path finding. Open rings will be closed automatically. If you only need to avoid a few specific roads, it's much more efficient to use `exclude_locations`. example: [[[30, 10], [40, 40], [20, 40], [10, 20], [30, 10]]] alternates: type: integer description: >- How many alternate routes are desired. Note that fewer or no alternates may be returned. Alternates are not yet supported on routes with more than 2 locations or on time-dependent routes. elevation_interval: type: number format: float description: >- If greater than zero, attempts to include elevation along the route at regular intervals. The "native" internal resolution is 30m, so we recommend you use this when possible. This number is interpreted as either meters or feet depending on the unit parameter. Elevation for route sections containing a bridge or tunnel is interpolated linearly. This doesn't always match the true elevation of the bridge/tunnel, but it prevents sharp artifacts from the surrounding terrain. This functionality is unique to the route endpoint and is not available via the elevation API. default: 0.0 roundabout_exits: type: boolean description: >- Determines whether the output should include roundabout exit instructions. default: true - $ref: '#/components/schemas/directionsOptions' required: - locations - costing example: { "locations": [ { "lon": -149.543469, "lat": 60.5347155, "type": "break" }, { "lon": -149.5485806, "lat": 60.5349908, "type": "break" } ], "costing": "auto", "costing_options": { "auto": { "use_tolls": 1, "use_highways": 0 } }, "units": "miles" } optimizedRouteRequest: allOf: - type: object properties: id: $ref: '#/components/schemas/requestId' locations: type: array items: $ref: '#/components/schemas/coordinate' description: >- The list of locations. The first and last are assumed to be the start and end points, and all intermediate points are locations that you want to visit along the way. minItems: 3 costing: $ref: '#/components/schemas/matrixCostingModel' costing_options: $ref: '#/components/schemas/costingOptions' - $ref: '#/components/schemas/directionsOptions' required: - locations - costing example: { "locations": [ { "lat": 40.042072, "lon": -76.306572 }, { "lat": 39.992115, "lon": -76.781559 }, { "lat": 39.984519, "lon": -76.6956 }, { "lat": 39.996586, "lon": -76.769028 }, { "lat": 39.984322, "lon": -76.706672 } ], "costing": "auto", "units": "miles" } nearestRoadsRequest: allOf: - type: object properties: locations: type: array items: $ref: '#/components/schemas/coordinate' minItems: 1 costing: $ref: '#/components/schemas/costingModel' costing_options: $ref: '#/components/schemas/costingOptions' verbose: type: boolean default: false - $ref: '#/components/schemas/directionsOptions' required: - locations example: { "locations": [ { "lat": 59.436884, "lon": 24.742595 } ], "verbose": true } baseTraceRequest: allOf: - type: object properties: id: $ref: '#/components/schemas/requestId' shape: type: array items: $ref: '#/components/schemas/mapMatchWaypoint' description: >- REQUIRED if `encoded_polyline` is not present. Note that `break` type locations are only supported when `shape_match` is set to `map_match`. encoded_polyline: type: string description: >- REQUIRED if `shape` is not present. An encoded polyline (https://developers.google.com/maps/documentation/utilities/polylinealgorithm). Note that the polyline must be encoded with 6 digits of precision rather than the usual 5. costing: $ref: '#/components/schemas/mapMatchCostingModel' costing_options: $ref: '#/components/schemas/costingOptions' shape_match: type: string enum: - edge_walk - map_snap - walk_or_snap description: >- Three snapping modes provide some control over how the map matching occurs. `edge_walk` is fast, but requires extremely precise data that matches the route graph almost perfectly. `map_snap` can handle significantly noisier data, but is very expensive. `walk_or_snap`, the default, tries to use edge walking first and falls back to map matching if edge walking fails. In general, you should not need to change this parameter unless you want to trace a multi-leg route with multiple `break` locations in the `shape`. - $ref: '#/components/schemas/directionsOptions' required: - costing mapMatchRequest: allOf: - $ref: '#/components/schemas/baseTraceRequest' - type: object properties: begin_time: type: integer description: >- The timestamp at the start of the trace. Combined with `durations`, this provides a way to include timing information for an `encoded_polyline` trace. durations: type: integer description: >- A list of durations (in seconds) between each successive pair of points in a polyline. use_timestamps: type: boolean description: >- If true, the input timestamps or durations should be used when computing elapsed time for each edge along the matched path rather than the routing algorithm estimates. default: false trace_options: $ref: '#/components/schemas/mapMatchTraceOptions' linear_references: type: boolean description: >- If true, the response will include a `linear_references` value that contains an array of base64-encoded [OpenLR location references](https://www.openlr-association.com/fileadmin/user_upload/openlr-whitepaper_v1.5.pdf), one for each graph edge of the road network matched by the trace. default: false example: { "encoded_polyline": "_grbgAh~{nhF?lBAzBFvBHxBEtBKdB?fB@dBZdBb@hBh@jBb@x@\\|@x@pB\\x@v@hBl@nBPbCXtBn@|@z@ZbAEbAa@~@q@z@QhA]pAUpAVhAPlAWtASpAAdA[dASdAQhAIlARjANnAZhAf@n@`A?lB^nCRbA\\xB`@vBf@tBTbCFbARzBZvBThBRnBNrBP`CHbCF`CNdCb@vBX`ARlAJfADhA@dAFdAP`AR`Ah@hBd@bBl@rBV|B?vB]tBCvBBhAF`CFnBXtAVxAVpAVtAb@|AZ`Bd@~BJfA@fAHdADhADhABjAGzAInAAjAB|BNbCR|BTjBZtB`@lBh@lB\\|Bl@rBXtBN`Al@g@t@?nAA~AKvACvAAlAMdAU`Ac@hAShAI`AJ`AIdAi@bAu@|@k@p@]p@a@bAc@z@g@~@Ot@Bz@f@X`BFtBXdCLbAf@zBh@fBb@xAb@nATjAKjAW`BI|AEpAHjAPdAAfAGdAFjAv@p@XlAVnA?~A?jAInAPtAVxAXnAf@tBDpBJpBXhBJfBDpAZ|Ax@pAz@h@~@lA|@bAnAd@hAj@tAR~AKxAc@xAShA]hAIdAAjA]~A[v@BhB?dBSv@Ct@CvAI~@Oz@Pv@dAz@lAj@~A^`B^|AXvAVpAXdBh@~Ap@fCh@hB\\zBN`Aj@xBFdA@jALbAPbAJdAHdAJbAHbAHfAJhALbA\\lBTvBAdC@bC@jCKjASbC?`CM`CDpB\\xAj@tB\\fA\\bAVfAJdAJbAXz@L|BO`AOdCDdA@~B\\z@l@v@l@v@l@r@j@t@b@x@b@r@z@jBVfCJdAJdANbCPfCF|BRhBS~BS`AYbAe@~BQdA", "shape_match": "map_snap", "costing": "pedestrian", "units": "miles", "linear_references": true } traceAttributesRequest: allOf: - $ref: '#/components/schemas/baseTraceRequest' - type: object properties: filters: description: >- If present, provides either a whitelist or a blacklist of keys to include/exclude in the response. This key is optional, and if omitted from the request, all available info will be returned. allOf: - $ref: '#/components/schemas/traceAttributeFilterOptions' example: { "encoded_polyline": "_grbgAh~{nhF?lBAzBFvBHxBEtBKdB?fB@dBZdBb@hBh@jBb@x@\\|@x@pB\\x@v@hBl@nBPbCXtBn@|@z@ZbAEbAa@~@q@z@QhA]pAUpAVhAPlAWtASpAAdA[dASdAQhAIlARjANnAZhAf@n@`A?lB^nCRbA\\xB`@vBf@tBTbCFbARzBZvBThBRnBNrBP`CHbCF`CNdCb@vBX`ARlAJfADhA@dAFdAP`AR`Ah@hBd@bBl@rBV|B?vB]tBCvBBhAF`CFnBXtAVxAVpAVtAb@|AZ`Bd@~BJfA@fAHdADhADhABjAGzAInAAjAB|BNbCR|BTjBZtB`@lBh@lB\\|Bl@rBXtBN`Al@g@t@?nAA~AKvACvAAlAMdAU`Ac@hAShAI`AJ`AIdAi@bAu@|@k@p@]p@a@bAc@z@g@~@Ot@Bz@f@X`BFtBXdCLbAf@zBh@fBb@xAb@nATjAKjAW`BI|AEpAHjAPdAAfAGdAFjAv@p@XlAVnA?~A?jAInAPtAVxAXnAf@tBDpBJpBXhBJfBDpAZ|Ax@pAz@h@~@lA|@bAnAd@hAj@tAR~AKxAc@xAShA]hAIdAAjA]~A[v@BhB?dBSv@Ct@CvAI~@Oz@Pv@dAz@lAj@~A^`B^|AXvAVpAXdBh@~Ap@fCh@hB\\zBN`Aj@xBFdA@jALbAPbAJdAHdAJbAHbAHfAJhALbA\\lBTvBAdC@bC@jCKjASbC?`CM`CDpB\\xAj@tB\\fA\\bAVfAJdAJbAXz@L|BO`AOdCDdA@~B\\z@l@v@l@v@l@r@j@t@b@x@b@r@z@jBVfCJdAJdANbCPfCF|BRhBS~BS`AYbAe@~BQdA", "shape_match": "map_snap", "costing": "pedestrian", "units": "miles" } tzResponse: type: object properties: tz_id: type: string description: >- The canonical time zone ID. In the event that multiple time zones could be returned, the first one from the Unicode CLDR timezone.xml is returned. base_utc_offset: type: integer description: The base offset, in seconds, from UTC that is normally in effect for this time zone. dst_offset: type: integer description: >- The special offset, in seconds, from UTC that is in effect for this time zone as of the queried timestamp (defaults to now). If no additional offsets are in effect, this value is zero. This typically reflects Daylight Saving Time, but may indicate other special offsets. To get the total offset in effect, add `dst_offset` and `utc_offset` together. required: - tz_id - base_utc_offset - dst_offset example: { "tz_id": "Europe/Zurich", "base_utc_offset": 3600, "dst_offset": 3600 } maneuverSignElement: type: object properties: text: type: string description: The interchange sign text (varies based on the context; see the `maneuverSign` schema). is_route_number: type: boolean description: True if the sign is a route number. consecutive_count: type: integer description: The frequency of this sign element within a set a consecutive signs. required: - text maneuverSign: type: object properties: exit_number_elements: type: array description: A list of exit number elements. This is typically just a single value. items: $ref: '#/components/schemas/maneuverSignElement' exit_branch_elements: type: array description: >- A list of exit branch elements. The text is a subsequent road name or route number after the sign. items: $ref: '#/components/schemas/maneuverSignElement' exit_toward_elements: type: array description: >- A list of exit name elements. The text is the interchange identifier (used more frequently outside the US). items: $ref: '#/components/schemas/maneuverSignElement' exit_name_elements: type: array description: >- A list of exit name elements. The text is the location where the road ahead goes (typically a city, but occasionally a road name or route number). items: $ref: '#/components/schemas/maneuverSignElement' travelMode: type: string enum: - drive - pedestrian - bicycle - transit edgeSign: type: object properties: exit_number: type: array items: type: string description: An exit number. example: 91B exit_branch: type: array items: type: string description: A subsequent road name or route number after the sign. example: I 95 North exit_toward: type: array items: type: string description: The interchange identifier (used more frequently outside the US). example: New York exit_name: type: array items: type: string description: >- The location where the road ahead goes (typically a city, but occasionally a road name or route number). example: Gettysburg Pike traversability: type: string description: The directions in which the edge is traversable. enum: - forward - backward - both edgeUse: type: string enum: - road - ramp - turn_channel - track - driveway - alley - parking_aisle - emergency_access - drive_through - culdesac - living_street - service_road - cycleway - mountain_bike - sidewalk - footway - steps - path - pedestrian - pedestrian_crossing - bridleway - rest_area - service_area - other - ferry - rail-ferry - rail - bus - egress_connection - platform_connection - transit_connection description: The use for the edge. intersectingEdge: type: object properties: begin_heading: type: integer description: The direction at the beginning of an edge. The units are degrees clockwise from north. from_edge_name_consistency: type: boolean description: >- True if this intersecting edge at the end node has consistent names with the path from the other edge. to_edge_name_consistency: type: boolean description: >- True if this intersecting edge at the end node has consistent names with the path to the other edge. driveability: $ref: '#/components/schemas/traversability' cyclability: $ref: '#/components/schemas/traversability' walkability: $ref: '#/components/schemas/traversability' use: $ref: '#/components/schemas/edgeUse' road_class: $ref: '#/components/schemas/roadClass' nodeType: type: string enum: - street_intersection - gate - bollard - toll_booth - multi_use_transit_stop - bike_share - parking - motor_way_junction - border_control endNode: type: object description: The node at the end of this edge properties: intersecting_edges: type: array items: $ref: '#/components/schemas/intersectingEdge' description: A set of edges intersecting this node. elapsed_time: type: number format: double description: The elapsed time along the path to arrive at this node. admin_index: type: integer description: The index into the `admins` list in which this node lies. type: $ref: '#/components/schemas/nodeType' fork: type: boolean description: True if this node is a fork. time_zone: type: string description: The canonical TZDB identifier for the node's time zone. example: America/New_York transitInfo: type: object description: Public transit info (not currently supported). additionalProperties: true routeSummary: type: object properties: time: type: number format: double description: The estimated travel time, in seconds length: type: number format: double description: The estimated travel distance, in `units` (km or mi) min_lat: type: number format: double description: The minimum latitude of the bounding box containing the route. max_lat: type: number format: double description: The maximum latitude of the bounding box containing the route. min_lon: type: number format: double description: The minimum longitude of the bounding box containing the route. max_lon: type: number format: double description: The maximum longitude of the bounding box containing the route. required: - time - length - min_lat - min_lon - max_lat - max_lon routeManeuver: type: object properties: type: type: integer description: | The type of route maneuver. | Code | Type | |------|-------------------------------------| | 0 | None | | 1 | Start | | 2 | Start right | | 3 | Start left | | 4 | Destination | | 5 | Destination right | | 6 | Destination left | | 7 | Becomes | | 8 | Continue | | 9 | Slight right | | 10 | Right | | 11 | Sharp right | | 12 | U-turn right | | 13 | U-turn left | | 14 | Sharp left | | 15 | Left | | 16 | Slight left | | 17 | Ramp straight | | 18 | Ramp right | | 19 | Ramp left | | 20 | Exit right | | 21 | Exit left | | 22 | Stay straight | | 23 | Stay right | | 24 | Stay left | | 25 | Merge | | 26 | Enter roundabout | | 27 | Exit roundabout | | 28 | Enter ferry | | 29 | Exit ferry | | 30 | Transit | | 31 | Transit transfer | | 32 | Transit remain on | | 33 | Transit connection start | | 34 | Transit connection transfer | | 35 | Transit connection destination | | 36 | Post-transit connection destination | | 37 | Merge right | | 38 | Merge left | instruction: type: string description: The written maneuver instruction. verbal_transition_alert_instruction: type: string description: Text suitable for use as a verbal navigation alert. verbal_pre_transition_instruction: type: string description: Text suitable for use as a verbal navigation alert immediately prior to the maneuver transition. verbal_post_transition_instruction: type: string description: Text suitable for use as a verbal navigation alert immediately after to the maneuver transition. street_names: type: array description: A list of street names that are consistent along the entire maneuver. items: type: string example: A1 begin_street_names: type: array description: >- A list of street names at the beginning of the maneuver, if they are different from the names at the end. items: type: string example: A1 time: type: number format: double description: The estimated time to complete the entire maneuver, in seconds. length: type: number format: double description: The length of the maneuver, in `units`. begin_shape_index: type: integer description: The index into the list of shape points for the start of the maneuver. end_shape_index: type: integer description: The index into the list of shape points for the end of the maneuver. toll: type: boolean description: True any portion of the maneuver is subject to a toll. default: false rough: type: boolean description: True any portion of the maneuver is unpaved or has portions of rough pavement. default: false gate: type: boolean description: True if a gate is encountered in the course of this maneuver. default: false ferry: type: boolean description: True if a ferry is encountered in the course of this maneuver. default: false sign: $ref: '#/components/schemas/maneuverSign' roundabout_exit_count: type: integer description: The exit number of the roundabout to take after entering. depart_instruction: type: integer description: The written departure time instruction (typically used in a transit maneuver). example: "Depart: 8:04 AM from Seoul Station" verbal_depart_instruction: type: integer description: Text suitable for use as a verbal departure time instruction (typically used in a transit maneuver). example: "Depart at 8:04 AM from Seoul Station" arrive_instruction: type: integer description: The written arrival time instruction (typically used in a transit maneuver). example: "Arrive: 8:06 AM at City Hall" verbal_arrive_instruction: type: integer description: Text suitable for use as a verbal departure time instruction (typically used in a transit maneuver). example: "Arrive at 8:06 AM at City Hall" transit_info: $ref: '#/components/schemas/transitInfo' verbal_multi_cue: type: boolean description: >- True if the `verbal_pre_transition_instruction` has been appended with the verbal instruction of the next maneuver. default: false travel_mode: $ref: '#/components/schemas/travelMode' travel_type: type: string description: >- The type of travel over the maneuver. This can be thought of as a specialization of the travel mode. For example, vehicular travel may be via car, motorcycle, etc.; and travel via bicycle may be via a road bike, mountain bike, etc. enum: - car - motorcycle - bus - tractor_trailer - motor_scooter - foot - wheelchair - segway - road - cross - hybrid - mountain - tram - metro - rail - ferry - cable_car - gondola - funicular - golf_cart - low_speed_vehicle bss_maneuver_type: type: string description: Describes a bike share action when using bikeshare routing. enum: - NoneAction - RentBikeAtBikeShare - ReturnBikeAtBikeShare required: - type - instruction - time - length - cost - begin_shape_index - end_shape_index - travel_mode - travel_type routeLeg: type: object properties: maneuvers: type: array items: $ref: '#/components/schemas/routeManeuver' minItems: 1 shape: type: string description: >- An encoded polyline (https://developers.google.com/maps/documentation/utilities/polylinealgorithm) with 6 digits of decimal precision. summary: $ref: '#/components/schemas/routeSummary' elevation_interval: type: number format: float description: >- The sampling distance between elevation values along the route. This echoes the request parameter having the same name. elevation: type: array items: type: number format: float description: >- An array of elevation values sampled every `elevation_interval`. Units are either metric or imperial depending on the value of `units`. required: - maneuvers - shape - summary routeTrip: type: object properties: status: type: integer description: The response status code status_message: type: string description: The response status message units: $ref: '#/components/schemas/valhallaLongUnits' language: $ref: '#/components/schemas/valhallaLanguages' locations: type: array items: $ref: '#/components/schemas/routingResponseWaypoint' legs: type: array items: $ref: '#/components/schemas/routeLeg' summary: $ref: '#/components/schemas/routeSummary' required: - status - status_message - units - language - locations - legs - summary routeResponse: type: object properties: id: $ref: '#/components/schemas/requestId' trip: $ref: '#/components/schemas/routeTrip' alternates: type: array items: type: object properties: trip: $ref: '#/components/schemas/routeTrip' required: - trip example: { "trip": { "locations": [ { "type": "break", "lat": 60.534715, "lon": -149.543469, "original_index": 0 }, { "type": "break", "lat": 60.53499, "lon": -149.54858, "original_index": 1 } ], "legs": [ { "maneuvers": [ { "type": 1, "instruction": "Drive west on AK 1/Seward Highway.", "verbal_pre_transition_instruction": "Drive west on Alaska 1, Seward Highway. Then You will arrive at your destination.", "verbal_post_transition_instruction": "Continue for 900 feet.", "street_names": [ "AK 1", "Seward Highway" ], "time": 11.487, "length": 0.176, "cost": 15.508, "begin_shape_index": 0, "end_shape_index": 9, "verbal_multi_cue": true, "travel_mode": "drive", "travel_type": "car" }, { "type": 4, "instruction": "You have arrived at your destination.", "verbal_transition_alert_instruction": "You will arrive at your destination.", "verbal_pre_transition_instruction": "You have arrived at your destination.", "time": 0.0, "length": 0.0, "cost": 0.0, "begin_shape_index": 9, "end_shape_index": 9, "travel_mode": "drive", "travel_type": "car" } ], "summary": { "has_time_restrictions": false, "min_lat": 60.534715, "min_lon": -149.54858, "max_lat": 60.535008, "max_lon": -149.543469, "time": 11.487, "length": 0.176, "cost": 15.508 }, "shape": "wzvmrBxalf|GcCrX}A|Nu@jI}@pMkBtZ{@x^_Afj@Inn@`@veB" } ], "summary": { "has_time_restrictions": false, "min_lat": 60.534715, "min_lon": -149.54858, "max_lat": 60.535008, "max_lon": -149.543469, "time": 11.487, "length": 0.176, "cost": 15.508 }, "status_message": "Found route between points", "status": 0, "units": "miles", "language": "en-US" } } nearestRoadsResponse: type: array items: $ref: '#/components/schemas/locateObject' example: [ { "input_lon": 24.742595, "input_lat": 59.436884, "nodes": [ ], "edges": [ { "predicted_speeds": [ ], "linear_reference": "KxGYOypEIXriAAAcABo6Uow=", "edge_info": { "speed_limit": 0, "shape": "{zvjpBwtden@zG`H~EdG", "names": [ "Rataskaevu" ], "bike_network": { "mountain": false, "local": false, "regional": false, "national": false }, "mean_elevation": 36, "way_id": 4853850 }, "edge_id": { "id": 1800, "value": 60404861586, "tile_id": 860498, "level": 2 }, "edge": { "sidewalk_left": false, "sidewalk_right": false, "lane_count": 1, "not_thru": false, "forward": false, "bike_network": false, "round_about": false, "access": { "truck": true, "pedestrian": true, "wheelchair": true, "taxi": true, "HOV": true, "emergency": false, "motorcycle": true, "car": true, "moped": true, "bus": true, "bicycle": true, "golf_cart": true }, "bridge": false, "tunnel": false, "destination_only": false, "seasonal": false, "classification": { "internal": false, "link": false, "surface": "paved", "use": "living_street", "classification": "service_other" }, "toll": false, "has_sign": false, "country_crossing": false, "part_of_complex_restriction": false, "cycle_lane": "none", "end_restriction": { "truck": false, "pedestrian": false, "wheelchair": false, "taxi": false, "HOV": false, "emergency": false, "motorcycle": false, "car": false, "moped": false, "bus": false, "bicycle": false }, "geo_attributes": { "curvature": 5, "max_down_slope": -7.00, "max_up_slope": 0.00, "weighted_grade": -6.67, "length": 32 }, "start_restriction": { "truck": false, "pedestrian": false, "wheelchair": false, "taxi": false, "HOV": false, "emergency": false, "motorcycle": false, "car": false, "moped": false, "bus": false, "bicycle": false }, "traffic_signal": false, "access_restriction": false, "truck_route": false, "speeds": { "predicted": false, "constrained_flow": 0, "free_flow": 0, "type": "classified", "default": 20 }, "end_node": { "id": 2895, "value": 97146964626, "tile_id": 860498, "level": 2 } }, "inbound_reach": 50, "distance": 2.2, "percent_along": 0.54802, "side_of_street": "neither", "outbound_reach": 50, "correlated_lon": 24.742630, "live_speed": { }, "correlated_lat": 59.436875 }, { "predicted_speeds": [ ], "linear_reference": "KxGYSCpELHryAP/l/+k6QnM=", "edge_info": { "speed_limit": 0, "shape": "{zvjpBwtden@zG`H~EdG", "names": [ "Rataskaevu" ], "bike_network": { "mountain": false, "local": false, "regional": false, "national": false }, "mean_elevation": 36, "way_id": 4853850 }, "edge_id": { "id": 7368, "value": 247235938962, "tile_id": 860498, "level": 2 }, "edge": { "sidewalk_left": false, "sidewalk_right": false, "lane_count": 1, "not_thru": false, "forward": true, "bike_network": false, "round_about": false, "access": { "truck": true, "pedestrian": true, "wheelchair": true, "taxi": true, "HOV": true, "emergency": false, "motorcycle": true, "car": true, "moped": true, "bus": true, "bicycle": true }, "bridge": false, "tunnel": false, "destination_only": false, "seasonal": false, "classification": { "internal": false, "link": false, "surface": "paved", "use": "living_street", "classification": "service_other" }, "toll": false, "has_sign": false, "country_crossing": false, "part_of_complex_restriction": false, "cycle_lane": "none", "end_restriction": { "truck": false, "pedestrian": false, "wheelchair": false, "taxi": false, "HOV": false, "emergency": false, "motorcycle": false, "car": false, "moped": false, "bus": false, "bicycle": false }, "geo_attributes": { "curvature": 5, "max_down_slope": 0.00, "max_up_slope": 7.00, "weighted_grade": 6.67, "length": 32 }, "start_restriction": { "truck": false, "pedestrian": false, "wheelchair": false, "taxi": false, "HOV": false, "emergency": false, "motorcycle": false, "car": false, "moped": false, "bus": false, "bicycle": false }, "traffic_signal": false, "access_restriction": false, "truck_route": false, "speeds": { "predicted": false, "constrained_flow": 0, "free_flow": 0, "type": "classified", "default": 20 }, "end_node": { "id": 819, "value": 27487963794, "tile_id": 860498, "level": 2 } }, "inbound_reach": 50, "distance": 2.2, "percent_along": 0.45198, "side_of_street": "neither", "outbound_reach": 50, "correlated_lon": 24.742630, "live_speed": { }, "correlated_lat": 59.436875 } ] } ] mapMatchRouteResponse: allOf: - $ref: '#/components/schemas/routeResponse' - type: object properties: linear_references: type: array items: type: string description: >- A base64-encoded [OpenLR location reference](https://www.openlr-association.com/fileadmin/user_upload/openlr-whitepaper_v1.5.pdf), for a graph edge of the road network matched by the trace. example: { "trip": { "locations": [ { "type": "break", "lat": 37.807744, "lon": -122.4197 }, { "type": "break", "lat": 37.803694, "lon": -122.428416 } ], "legs": [ { "maneuvers": [ { "type": 1, "instruction": "Walk west on the walkway.", "verbal_pre_transition_instruction": "Walk west on the walkway.", "verbal_post_transition_instruction": "Continue for 200 feet.", "time": 44.733, "length": 0.039, "cost": 44.733, "begin_shape_index": 0, "end_shape_index": 1, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 15, "instruction": "Turn left.", "verbal_transition_alert_instruction": "Turn left.", "verbal_pre_transition_instruction": "Turn left. Then Turn right onto Jefferson Street.", "verbal_post_transition_instruction": "Continue for 20 feet.", "time": 4.941, "length": 0.004, "cost": 4.941, "begin_shape_index": 1, "end_shape_index": 2, "verbal_multi_cue": true, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 10, "instruction": "Turn right onto Jefferson Street.", "verbal_transition_alert_instruction": "Turn right onto Jefferson Street.", "verbal_pre_transition_instruction": "Turn right onto Jefferson Street.", "verbal_post_transition_instruction": "Continue for 80 feet.", "street_names": [ "Jefferson Street" ], "time": 16.941, "length": 0.014, "cost": 21.941, "begin_shape_index": 2, "end_shape_index": 3, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 15, "instruction": "Turn left onto the walkway.", "verbal_transition_alert_instruction": "Turn left onto the walkway.", "verbal_pre_transition_instruction": "Turn left onto the walkway. Then Turn right onto the walkway.", "verbal_post_transition_instruction": "Continue for 20 feet.", "time": 4.941, "length": 0.004, "cost": 9.941, "begin_shape_index": 3, "end_shape_index": 4, "verbal_multi_cue": true, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 10, "instruction": "Turn right onto the walkway.", "verbal_transition_alert_instruction": "Turn right onto the walkway.", "verbal_pre_transition_instruction": "Turn right onto the walkway. Then Turn left onto Hyde Street.", "verbal_post_transition_instruction": "Continue for 30 feet.", "time": 6.352, "length": 0.005, "cost": 6.352, "begin_shape_index": 4, "end_shape_index": 5, "verbal_multi_cue": true, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 15, "instruction": "Turn left onto Hyde Street.", "verbal_transition_alert_instruction": "Turn left onto Hyde Street.", "verbal_pre_transition_instruction": "Turn left onto Hyde Street.", "verbal_post_transition_instruction": "Continue for 300 feet.", "street_names": [ "Hyde Street" ], "time": 58.588, "length": 0.051, "cost": 63.588, "begin_shape_index": 5, "end_shape_index": 10, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 10, "instruction": "Turn right onto the walkway.", "verbal_transition_alert_instruction": "Turn right onto the walkway.", "verbal_pre_transition_instruction": "Turn right onto the walkway. Then Turn left onto the walkway.", "verbal_post_transition_instruction": "Continue for 30 feet.", "time": 6.352, "length": 0.005, "cost": 11.352, "begin_shape_index": 10, "end_shape_index": 11, "rough": true, "verbal_multi_cue": true, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 15, "instruction": "Turn left onto the walkway.", "verbal_transition_alert_instruction": "Turn left onto the walkway.", "verbal_pre_transition_instruction": "Turn left onto the walkway.", "verbal_post_transition_instruction": "Continue for 400 feet.", "time": 93.176, "length": 0.082, "cost": 93.176, "begin_shape_index": 11, "end_shape_index": 17, "rough": true, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 15, "instruction": "Turn left onto the walkway.", "verbal_transition_alert_instruction": "Turn left onto the walkway.", "verbal_pre_transition_instruction": "Turn left onto the walkway. Then Turn right onto Beach Street.", "verbal_post_transition_instruction": "Continue for 40 feet.", "time": 7.764, "length": 0.006, "cost": 7.764, "begin_shape_index": 17, "end_shape_index": 18, "rough": true, "verbal_multi_cue": true, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 10, "instruction": "Turn right onto Beach Street.", "verbal_transition_alert_instruction": "Turn right onto Beach Street.", "verbal_pre_transition_instruction": "Turn right onto Beach Street.", "verbal_post_transition_instruction": "Continue for 500 feet.", "street_names": [ "Beach Street" ], "time": 110.705, "length": 0.095, "cost": 115.705, "begin_shape_index": 18, "end_shape_index": 24, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 15, "instruction": "Turn left onto Polk Street.", "verbal_transition_alert_instruction": "Turn left onto Polk Street.", "verbal_pre_transition_instruction": "Turn left onto Polk Street.", "verbal_post_transition_instruction": "Continue for 300 feet.", "street_names": [ "Polk Street" ], "time": 68.058, "length": 0.059, "cost": 73.058, "begin_shape_index": 24, "end_shape_index": 27, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 10, "instruction": "Turn right onto the walkway.", "verbal_transition_alert_instruction": "Turn right onto the walkway.", "verbal_pre_transition_instruction": "Turn right onto the walkway.", "verbal_post_transition_instruction": "Continue for 400 feet.", "time": 98.0, "length": 0.084, "cost": 103.0, "begin_shape_index": 27, "end_shape_index": 32, "rough": true, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 15, "instruction": "Turn left onto Van Ness Avenue.", "verbal_transition_alert_instruction": "Turn left onto Van Ness Avenue.", "verbal_pre_transition_instruction": "Turn left onto Van Ness Avenue.", "verbal_post_transition_instruction": "Continue for 400 feet.", "street_names": [ "Van Ness Avenue" ], "time": 83.294, "length": 0.073, "cost": 98.294, "begin_shape_index": 32, "end_shape_index": 38, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 10, "instruction": "Turn right onto the walkway.", "verbal_transition_alert_instruction": "Turn right onto the walkway.", "verbal_pre_transition_instruction": "Turn right onto the walkway. Then Turn left onto the walkway.", "verbal_post_transition_instruction": "Continue for 30 feet.", "time": 7.058, "length": 0.006, "cost": 12.058, "begin_shape_index": 38, "end_shape_index": 39, "rough": true, "verbal_multi_cue": true, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 15, "instruction": "Turn left onto the walkway.", "verbal_transition_alert_instruction": "Turn left onto the walkway.", "verbal_pre_transition_instruction": "Turn left onto the walkway. Then Turn right onto Bay Street.", "verbal_post_transition_instruction": "Continue for 50 feet.", "time": 9.882, "length": 0.008, "cost": 9.882, "begin_shape_index": 39, "end_shape_index": 40, "rough": true, "verbal_multi_cue": true, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 10, "instruction": "Turn right onto Bay Street.", "verbal_transition_alert_instruction": "Turn right onto Bay Street.", "verbal_pre_transition_instruction": "Turn right onto Bay Street.", "verbal_post_transition_instruction": "Continue for 900 feet.", "street_names": [ "Bay Street" ], "time": 194.823, "length": 0.171, "cost": 199.823, "begin_shape_index": 40, "end_shape_index": 45, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 15, "instruction": "Turn left onto Gough Street.", "verbal_transition_alert_instruction": "Turn left onto Gough Street.", "verbal_pre_transition_instruction": "Turn left onto Gough Street. Then You will arrive at your destination.", "verbal_post_transition_instruction": "Continue for 20 feet.", "street_names": [ "Gough Street" ], "time": 3.302, "length": 0.002, "cost": 8.302, "begin_shape_index": 45, "end_shape_index": 46, "verbal_multi_cue": true, "travel_mode": "pedestrian", "travel_type": "foot" }, { "type": 4, "instruction": "You have arrived at your destination.", "verbal_transition_alert_instruction": "You will arrive at your destination.", "verbal_pre_transition_instruction": "You have arrived at your destination.", "time": 0.0, "length": 0.0, "cost": 0.0, "begin_shape_index": 46, "end_shape_index": 46, "travel_mode": "pedestrian", "travel_type": "foot" } ], "summary": { "has_time_restrictions": false, "min_lat": 37.803694, "min_lon": -122.428418, "max_lat": 37.807771, "max_lon": -122.419706, "time": 818.918, "length": 0.716, "cost": 883.918 }, "shape": "uhrbgAt~{nhFrDhk@rBWfAbPvBWXfElAQhAi@dA]d[oDvIaAs@~Dp@n@r@r@^\\jAnQfDdh@lBtY`Eg@VzDXxDxAdPrD~j@zBf]TpD|C_@`\\uD|QaCZtE`Cp\\|A|UdCz^N`ClDJj@dJdDo@vGw@dKmAzWcDRdFpFq@d@dHpH`kAVbEXhEdKj_BpAO" } ], "linear_references": [ "C6jyLBrisjr3Af+4//g6BA==", "C6jyCxrirjr3AAAA//s6Bw==", "C6jyDBriqyKUAP/j//0iAg==", "C6jx/xriqTr3AAAA//w6Ag==", "C6jx/xripjr0AP/2AAE6Hg==", "C6jx+xripiKUAQAM/8kiHw==", "C6jyARrijCKPAAAC/+8iBg==", "C6jyAxrihDrvAP/0AAM6BQ==", "C6jx/hrihTrzAP/5//o6Bw==", "C6jx+xrigjr1AP/h//06Bw==", "C6jx7RrigDr3Af++//k6Bw==", "C6jxzxrifDr3AP/T//w6Ag==", "C6jxuxrieTr3AAAA//g6Bw==", "C6jxvBridTLSAP/1AAAyBw==", "C6jxtxridDLSAP/2AAEyBg==", "C6jxsxridDLWAf+d//MyBw==", "C6jxhRribjLXAP/P//oyAg==", "C6jxbxriazLXAP/1//8yHw==", "C6jxaxriajLXAP////kyHw==", "C6jxaxriZjLTAAAJ/9MyHw==", "C6jxbxriUTLPAAAG/+IyBw==", "C6jxcxriQzrvAP/z//86Bw==", "C6jxbhriQjryAP/P//s6Bw==", "C6jxVxriPzr3AP/b//w6Bw==", "C6jxRhriPTr3AP/N//o6Aw==", "C6jxLxriOjr3AP/4AAA6Aw==", "C6jxLBriOTLXAP/9//kyBQ==", "C6jxKxriNSKTAP/u//8iHw==", "C6jxIxriNCKWAAAE/+siHw==", "C6jxJRriKiKPAAAE/+0iHw==", "C6jxJxriISKPAAAI/9kiAw==", "C6jxKxriDjrvAP/0AAA6AQ==", "C6jxJhriDjrzAAAB//Q6Bw==", "C6jxJxriCBpxAv9s/+8aBw==", "C6jw4xrh/xp3Av9a/+0aBQ==", "C6jwlhrh9jLXAAAA//0yBQ==" ], "summary": { "has_time_restrictions": false, "min_lat": 37.803694, "min_lon": -122.428418, "max_lat": 37.807771, "max_lon": -122.419706, "time": 818.918, "length": 0.716, "cost": 883.918 }, "status_message": "Found route between points", "status": 0, "units": "miles", "language": "en-US" } } matrixResponse: type: object properties: id: $ref: '#/components/schemas/requestId' sources: type: array items: $ref: '#/components/schemas/coordinate' description: >- The list of starting locations determined by snapping to the nearest appropriate point on the road network for the costing model. All locations appear in the same order as the input. minItems: 1 targets: type: array items: $ref: '#/components/schemas/coordinate' description: >- The list of ending locations determined by snapping to the nearest appropriate point on the road network for the costing model. All locations appear in the same order as the input. minItems: 1 sources_to_targets: type: array items: type: array items: $ref: '#/components/schemas/matrixDistance' description: >- The matrix of starting and ending locations, along with the computed distance and travel time. The array is row-ordered. This means that the time and distance from the first location to all others forms the first row of the array, followed by the time and distance from the second source location to all target locations, etc. minItems: 1 warnings: type: array items: $ref: '#/components/schemas/warning' units: $ref: '#/components/schemas/valhallaLongUnits' required: - sources - targets - sources_to_targets - units example: { "targets": [ [ { "lon": -73.990508, "lat": 40.744014 }, { "lon": -73.979713, "lat": 40.739735 }, { "lon": -73.985015, "lat": 40.752522 }, { "lon": -73.983704, "lat": 40.750117 }, { "lon": -73.993519, "lat": 40.750552 } ] ], "sources_to_targets": [ [ { "distance": 0.000, "time": 0, "to_index": 0, "from_index": 0 }, { "distance": 1.115, "time": 806, "to_index": 1, "from_index": 0 }, { "distance": 1.278, "time": 909, "to_index": 2, "from_index": 0 }, { "distance": 1.112, "time": 792, "to_index": 3, "from_index": 0 }, { "distance": 1.220, "time": 869, "to_index": 4, "from_index": 0 } ] ], "sources": [ [ { "lon": -73.990508, "lat": 40.744014 } ] ], "units": "kilometers" } isochroneResponse: type: object required: - features - type properties: id: type: string features: type: array items: $ref: '#/components/schemas/isochroneFeature' type: type: string enum: - FeatureCollection example: { "features": [ { "properties": { "fill": "#ff0000", "fillOpacity": 0.33, "fill-opacity": 0.33, "fillColor": "#ff0000", "color": "#ff0000", "contour": 15, "opacity": 0.33, "metric": "time" }, "geometry": { "coordinates": [ [ -73.985021, 40.753501 ], [ -73.983892, 40.751630 ], [ -73.982508, 40.751546 ], [ -73.981969, 40.751014 ], [ -73.977881, 40.739014 ], [ -73.979577, 40.738083 ], [ -73.980361, 40.737014 ], [ -73.988508, 40.734670 ], [ -73.990508, 40.733708 ], [ -73.991514, 40.734008 ], [ -73.994628, 40.733894 ], [ -73.995388, 40.734134 ], [ -73.995662, 40.734860 ], [ -73.996508, 40.735006 ], [ -73.998508, 40.734576 ], [ -74.003292, 40.746014 ], [ -74.004016, 40.749014 ], [ -74.002508, 40.749907 ], [ -73.993508, 40.751786 ], [ -73.987508, 40.753970 ], [ -73.985021, 40.753501 ] ], "type": "LineString" }, "type": "Feature" } ], "type": "FeatureCollection" } isochroneFeature: type: object properties: properties: $ref: '#/components/schemas/isochroneProperties' geometry: type: object # Bit of a cop-out for now since many client generators choke on the complexity of GeoJSON additionalProperties: true type: type: string enum: - Feature isochroneProperties: type: object properties: fillColor: type: string opacity: type: number format: float fill: type: string fillOpacity: type: number format: float color: type: string contour: type: number format: float metric: type: string enum: - time - distance heightResponse: type: object properties: id: $ref: '#/components/schemas/requestId' shape: type: array items: $ref: '#/components/schemas/coordinate' encoded_polyline: type: string description: The input polyline. height: type: array description: >- The list of heights for each point, in meters. Present only if `range` is `false`. Null values indicate missing data. items: type: number format: float range_height: type: array description: >- The list of ranges and heights for each point in the shape, where each entry is an array of length 2. Present only if `range` is `true`. In each pair, the first element represents the range or distance along the input locations. It is the cumulative distance along the previous coordinates in the shape up to the current coordinate. This value for the first coordinate in the shape will always be 0. The second element in the pair represents the height or elevation at the associated coordinate. The height is null if no height data exists for a given location. Both values are expressed in meters. items: type: array items: type: number format: float minItems: 2 maxItems: 2 example: { "id": "kesklinn", "shape": [ { "lat": 59.436884, "lon": 24.742595 } ], "height": [ 37 ] } traceAttributesBaseResponse: type: object properties: edges: type: array items: $ref: '#/components/schemas/traceEdge' description: The list of edges matched along the path. admins: type: array items: $ref: '#/components/schemas/adminRegion' description: >- The set of administrative regions matched along the path. Rather than repeating this information for every end node, the admins in this list are referenced by index. matched_points: type: array items: $ref: '#/components/schemas/matchedPoint' description: >- List of match results when using the map_snap shape match algorithm. There is a one-to-one correspondence with the input set of latitude, longitude coordinates and this list of match results. osm_changeset: type: integer shape: type: string description: >- The encoded polyline (https://developers.google.com/maps/documentation/utilities/polylinealgorithm) of the matched path. confidence_score: type: number format: double minimum: 0 maximum: 1 traceAttributesResponse: allOf: - $ref: '#/components/schemas/traceAttributesBaseResponse' - type: object properties: id: $ref: '#/components/schemas/requestId' units: $ref: '#/components/schemas/valhallaLongUnits' alternate_paths: type: array items: $ref: '#/components/schemas/traceAttributesBaseResponse' description: Alternate paths, if any, that were not classified as the best match. locateObject: type: object properties: id: $ref: '#/components/schemas/requestId' input_lat: type: number format: double description: The input (searched) latitude. input_lon: type: number format: double description: The input (searched) longitude. nodes: type: array items: $ref: '#/components/schemas/locateNode' edges: type: array items: $ref: '#/components/schemas/locateEdge' locateNode: allOf: - $ref: '#/components/schemas/coordinate' - type: object properties: traffic_signal: type: boolean type: $ref: '#/components/schemas/nodeType' node_id: $ref: '#/components/schemas/nodeId' access: $ref: '#/components/schemas/access' edge_count: type: integer administrative: $ref: '#/components/schemas/administrative' intersection_type: type: string enum: - regular - false - dead-end - fork density: type: integer local_edge_count: type: integer mode_change: type: boolean nodeId: type: object properties: id: type: integer format: int64 value: type: integer format: int64 tile_id: type: integer format: int64 level: type: integer access: type: object properties: golf_cart: type: boolean wheelchair: type: boolean taxi: type: boolean HOV: type: boolean truck: type: boolean emergency: type: boolean pedestrian: type: boolean car: type: boolean bus: type: boolean bicycle: type: boolean motorcycle: type: boolean moped: type: boolean administrative: type: object properties: iso_3166-1: type: string description: The ISO 3166-1 alpha-2 country code of the administrative region. country: type: string description: The full country name. iso_3166-2: type: string description: >- The ISO 3166-2 code identifying the principal subdivision (ex: provinces or states) within a country. state: type: string description: The full state or province name. locateEdge: type: object properties: edge_id: $ref: '#/components/schemas/nodeId' way_id: type: integer description: The OSM way ID associated with this edge (absent in verbose response; see the edge info). correlated_lat: type: number format: double correlated_lon: type: number format: double percent_along: type: number format: double side_of_street: type: string enum: - left - right - neither linear_reference: type: string description: >- A base64-encoded [OpenLR location reference](https://www.openlr-association.com/fileadmin/user_upload/openlr-whitepaper_v1.5.pdf), for a graph edge of the road network matched by the query. outbound_reach: type: integer heading: type: number format: float inbound_reach: type: integer distance: type: number format: float predicted_speeds: type: array items: type: integer description: >- Predicted speed information based on historical data. If available, this will include 2016 entries. Each entry represents 5 minutes, where the first entry represents midnight on Monday, the second entry represents 00:05 on Monday, etc. edge_info: $ref: '#/components/schemas/locateEdgeInfo' edge: $ref: '#/components/schemas/locateDetailedEdge' warnings: type: array items: type: string required: - correlated_lat - correlated_lon - side_of_street - percent_along locateEdgeInfo: type: object properties: mean_elevation: type: number format: float description: The mean elevation, in meters, relative to sea level. shape: type: string description: >- An encoded polyline (https://developers.google.com/maps/documentation/utilities/polylinealgorithm). Note that the polyline is always encoded with 6 digits of precision, whereas most implementations default to 5. names: type: array items: type: string description: A list of names that the edge goes by. bike_network: $ref: '#/components/schemas/bikeNetwork' way_id: type: integer description: The OSM way ID associated with this edge. required: - way_id - shape locateDetailedEdge: type: object properties: sidewalk_left: type: boolean description: Is there a sidewalk to the left of the edge? sidewalk_right: type: boolean description: Is there a sidewalk to the right of the edge? lane_count: type: integer stop_sign: type: boolean description: Is there a stop sign at end of the directed edge? sac_scale: type: string enum: - none - hiking - mountain hiking - demanding mountain hiking - alpine hiking - demanding alpine hiking - difficult alpine hiking yield_sign: type: boolean description: Is there a yield sign at end of the directed edge? not_thru: type: boolean description: Does the edge lead to a "no-through" region? forward: type: boolean description: Is the edge info forward? If false, then reverse is implied. end_node: $ref: '#/components/schemas/nodeId' truck_route: type: boolean description: Is the edge part of a truck route/network? speeds: $ref: '#/components/schemas/speeds' bike_network: type: boolean description: Is the edge part of a bicycle network? round_about: type: boolean description: Is the edge part of a roundabout? traffic_signal: type: boolean description: Is there a traffic signal at the end of the directed edge? access_restriction: type: boolean description: Is there a general restriction or access condition? destination_only: type: boolean description: Is the edge destination only? If so, it will not be routed through. geo_attributes: $ref: '#/components/schemas/geoAttributes' start_restriction: $ref: '#/components/schemas/restrictions' cycle_lane: type: string description: >- Indication of the type of cycle lane (if any) present along an edge. enum: - none - shared - dedicated - separated end_restriction: $ref: '#/components/schemas/restrictions' seasonal: type: boolean description: Is access seasonal (ex. no access in winter)? country_crossing: type: boolean description: Does the edge cross into a new country? part_of_complex_restriction: type: boolean description: Is the edge part of a complex restriction? has_sign: type: boolean description: Do exit signs exist for the edge? access: $ref: '#/components/schemas/restrictions' bridge: type: boolean description: Is the edge part of a bridge? classification: $ref: '#/components/schemas/highwayClassification' toll: type: boolean description: Is the edge a toll road? tunnel: type: boolean description: Is the edge a tunnel? bikeNetwork: type: object properties: mountain: type: boolean local: type: boolean regional: type: boolean national: type: boolean speeds: type: object properties: predicted: type: boolean description: Does this edge have predicted (historical) speed records? constrained_flow: type: integer description: Speed when there is no traffic, in kph. free_flow: type: integer description: Speed when there is heavy traffic, in kph. type: type: string enum: - classified - tagged description: >- The type of speed which is used when setting default speeds. When `tagged`, the explicit `max_speed` tags from OpenStreetMap are being used. When `classified`, the values are being inferred from the highway classification. default: type: integer description: >- The default speed used for calculations. NOTE: Values greater than 250 are used for special cases and should not be treated as literal. geoAttributes: type: object properties: curvature: type: integer description: Curvature factor. max_down_slope: type: number format: float description: >- The maximum downward slope. Uses 1 degree precision for slopes to -16 degrees, and 4 degree precision afterwards (up to a max of -76 degrees). max_up_slope: type: number format: float description: >- The maximum upward slope. Uses 1 degree precision for slopes to 16 degrees, and 4 degree precision afterwards (up to a max of 76 degrees). weighted_grade: type: number format: float description: The weighted estimate of the grade. length: type: integer description: The length of the edge, in meters. restrictions: type: object properties: golf_cart: type: boolean truck: type: boolean pedestrian: type: boolean wheelchair: type: boolean taxi: type: boolean HOV: type: boolean emergency: type: boolean motorcycle: type: boolean car: type: boolean moped: type: boolean bus: type: boolean bicycle: type: boolean highwayClassification: type: object properties: internal: type: boolean description: Is the edge internal to an intersection? link: type: boolean description: Is the edge a ramp or turn channel? surface: type: string description: >- A representation of the smoothness of the highway. This is used for costing and access checks based on the vehicle type. enum: - paved_smooth - paved - paved_rough - compacted - dirt - gravel - path - impassable use: type: string enum: - road - ramp - turn_channel - track - driveway - alley - parking_aisle - emergency_access - drive_through - culdesac - living_street - service_road - cycleway - mountain_bike - sidewalk - footway - elevator - steps - escalator - path - pedestrian - bridleway - pedestrian_crossing - rest_area - service_area - other - rail - ferry - rail-ferry - bus - egress_connection - platform_connnection - transit_connection - construction classification: type: string description: >- The classification/importance of the road/path. Used for a variety of purposes including fallback speed estimation and access for certain vehicle types. enum: - motorway - trunk - primary - secondary - tertiary - unclassified - residential - service_other geocodingObject: type: object properties: attribution: type: string format: uri description: >- A URL containing attribution information. If you are not using Stadia Maps and our standard attribution already for your basemaps, you must include this attribution link somewhere in your website/app. query: type: object additionalProperties: true description: >- Technical details of the query. This is most useful for debugging during development. See the full example for the list of properties; these should be self-explanatory, so we don't enumerate them in the spec. warnings: type: array items: type: string description: >- An array of non-critical warnings. This is normally for informational/debugging purposes and not a serious problem. errors: type: array items: type: string description: >- An array of more serious errors (for example, omitting a required parameter). Don’t ignore these. geoJSONGeometryBase: type: object required: - type properties: type: type: string enum: - Point - MultiPoint - LineString - MultiLineString - Polygon - MultiPolygon geoJSONPoint: allOf: - $ref: '#/components/schemas/geoJSONGeometryBase' - type: object required: - coordinates properties: coordinates: type: array minItems: 2 maxItems: 3 items: type: number format: double geoJSONLineString: allOf: - $ref: '#/components/schemas/geoJSONGeometryBase' - type: object required: - coordinates properties: coordinates: type: array items: type: array items: type: number format: double minItems: 2 maxItems: 3 geoJSONPolygon: allOf: - $ref: '#/components/schemas/geoJSONGeometryBase' - type: object required: - coordinates properties: coordinates: type: array items: type: array items: type: array items: type: number format: double minItems: 2 maxItems: 3 geoJSONGeometry: oneOf: - $ref: '#/components/schemas/geoJSONPoint' - $ref: '#/components/schemas/geoJSONLineString' - $ref: '#/components/schemas/geoJSONPolygon' discriminator: propertyName: type mapping: Point: '#/components/schemas/geoJSONPoint' LineString: '#/components/schemas/geoJSONLineString' Polygon: '#/components/schemas/geoJSONPolygon' peliasGeoJSONProperties: type: object additionalProperties: true properties: gid: type: string description: >- A scoped GID for this result. This can be passed to the place endpoint. Note that these are not always stable. For OSM, Geonames, and Who's on First, these are usually stable, but for other sources like OSM, no stability is guaranteed. source_id: type: string description: >- An ID referencing the original data source (specified via source) for the result. These IDs are specific to the source that they originated from. For example, in the case of OSM, these typically look like way/123 or point/123. label: type: string description: >- A full, human-readable label. However, you may not necessarily want to use this; be sure to read the docs for name, locality, and region before making a decision. This field is mostly localized. The order of components is generally locally correct (ex: for an address in South Korea, the house number appears after the street name). However, components will use a request language equivalent if one exists (ex: Seoul instead of 서울 if lang=en). layer: $ref: '#/components/schemas/peliasLayer' name: type: string description: >- The name of the place, the street address including house number, or label of similar relevance. If your app is localized to a specific region, you may get better display results by combining name, locality OR region (or neither?), and postal code together in the local format. Experiment with what works best for your use case. accuracy: type: string enum: - point - centroid description: >- The accuracy of the geographic coordinates in the result. This value is a property of the result itself and won't change based on the query. A point result means that the record can reasonably be represented by a single geographic point. Addresses, venues, or interpolated addresses usually have point accuracy. Larger areas, such as a city or country, cannot be represented by a single point, so a centroid is given instead. addendum: type: object additionalProperties: true description: >- Optional additional information from the underlying data source (ex: OSM). This includes select fields. The most useful fields are mapped in the definition here, but others may be available. properties: osm: type: object additionalProperties: true properties: website: type: string format: uri wikipedia: type: string wikidata: type: string phone: type: string continent: type: string continent_gid: type: string country: type: string country_gid: type: string neighbourhood: type: string neighbourhood_gid: type: string borough: type: string borough_gid: type: string postalcode: type: string street: type: string housenumber: type: string locality: type: string description: >- The city, village, town, etc. that the place / address is part of. Note that values may not always match postal or local conventions perfectly. locality_gid: type: string county: type: string description: >- Administrative divisions between localities and regions. Useful for disambiguating nearby results with similar names. region: type: string description: >- Typically the first administrative division within a country. For example, a US state or a Canadian province. region_a: type: string description: The abbreviation for the region. peliasGeoJSONFeature: type: object required: - type - geometry properties: type: type: string enum: - Feature geometry: $ref: '#/components/schemas/geoJSONPoint' properties: $ref: '#/components/schemas/peliasGeoJSONProperties' bbox: type: array minItems: 4 maxItems: 4 items: type: number format: double description: >- An array of 4 floating point numbers representing the (W, S, E, N) extremes of the features found. id: type: string peliasResponse: type: object properties: geocoding: allOf: - $ref: '#/components/schemas/geocodingObject' bbox: type: array minItems: 4 maxItems: 4 items: type: number format: double description: >- An array of 4 floating point numbers representing the (W, S, E, N) extremes of the features found. features: type: array items: $ref: '#/components/schemas/peliasGeoJSONFeature' required: - geocoding - features example: { "geocoding": { "version": "0.2", "attribution": "https://stadiamaps.com/attribution", "query": { "text": "1600 Pennsylvania Ave NW", "size": 10, "private": false, "lang": { "name": "English", "iso6391": "en", "iso6393": "eng", "via": "default", "defaulted": true }, "querySize": 20, "parser": "libpostal", "parsed_text": { "housenumber": "1600", "street": "pennsylvania ave nw" } }, "engine": { "name": "Pelias", "author": "Mapzen", "version": "1.0" }, "timestamp": 1679043782383 }, "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ -77.036547, 38.897675 ] }, "properties": { "id": "us/dc/statewide:aa53d4bd0fe295be", "gid": "openaddresses:address:us/dc/statewide:aa53d4bd0fe295be", "layer": "address", "source": "openaddresses", "source_id": "us/dc/statewide:aa53d4bd0fe295be", "country_code": "US", "name": "1600 Pennsylvania Avenue NW", "housenumber": "1600", "street": "Pennsylvania Avenue NW", "postalcode": "20500", "confidence": 1, "match_type": "exact", "accuracy": "point", "country": "United States", "country_gid": "whosonfirst:country:85633793", "country_a": "USA", "region": "District of Columbia", "region_gid": "whosonfirst:region:85688741", "region_a": "DC", "county": "District of Columbia", "county_gid": "whosonfirst:county:1377370667", "county_a": "DI", "locality": "Washington", "locality_gid": "whosonfirst:locality:85931779", "neighbourhood": "White House Grounds", "neighbourhood_gid": "whosonfirst:neighbourhood:1108724059", "continent": "North America", "continent_gid": "whosonfirst:continent:102191575", "label": "1600 Pennsylvania Avenue NW, Washington, DC, USA" } } ], "bbox": [ -77.036547, 38.897675, -77.036547, 38.897675 ] } peliasLayer: type: string enum: - venue - address - street - country - macroregion - region - macrocounty - county - locality - localadmin - borough - neighbourhood - postalcode - coarse - dependency - macrohood - marinearea - disputed - empire - continent - ocean description: | Our database is organized into several layers (in the GIS sense of the term) as follows: - `venue`: Points of interest, businesses, and things with walls - `address`: Places with a street address - `street`: Streets, roads, highways - `county`: Places that issue passports, nations, nation-states - `macroregion`: A related group of regions (mostly in Europe) - `region`: The first administrative division within a country (usually states and provinces) - `macrocounty`: A related group of counties (mostly in Europe) - `county`: Official governmental areas; usually bigger than a locality, but almost always smaller than a region - `locality`: Towns, hamlets, cities, etc. - `localadmin`: Local administrative boundaries - `borough`: Local administrative boundaries within cities (not widely used, but present in places such as NYC and Mexico City) - `neighbourhood`: Social communities and neighborhoods (note the British spelling in the API!) - `postalcode`: Postal codes used by mail services (note: not used for reverse geocoding) - `coarse`: An alias for simultaneously using all administrative layers (everything except `venue` and `address`) - `marinearea`: Places with fishes and boats. - `ocean`: A really big marine area. peliasSource: type: string enum: - openstreetmap - openaddresses - whosonfirst - geonames description: >- Our database contains info from multiple sources. These identifiers can be used to either limit search results or to determine the relevance of a result. warning: type: object properties: text: type: string code: type: integer parameters: searchText: name: text in: query description: The place name (address, venue name, etc.) to search for. required: true schema: type: string example: 1600 Pennsylvania Ave NW searchFocusLat: name: focus.point.lat in: query description: The latitude of the point to focus the search on. This will bias results toward the focus point. Requires `focus.point.lon`. required: false schema: type: number format: double searchFocusLon: name: focus.point.lon in: query description: The longitude of the point to focus the search on. This will bias results toward the focus point. Requires `focus.point.lat`. required: false schema: type: number format: double searchBoundaryRectMinLat: name: boundary.rect.min_lat in: query description: >- Defines the min latitude component of a bounding box to limit the search to. Requires all other `boundary.rect` parameters to be specified. required: false schema: type: number format: double searchBoundaryRectMaxLat: name: boundary.rect.max_lat in: query description: >- Defines the max latitude component of a bounding box to limit the search to. Requires all other `boundary.rect` parameters to be specified. required: false schema: type: number format: double searchBoundaryRectMinLon: name: boundary.rect.min_lon in: query description: >- Defines the min longitude component of a bounding box to limit the search to. Requires all other `boundary.rect` parameters to be specified. required: false schema: type: number format: double searchBoundaryRectMaxLon: name: boundary.rect.max_lon in: query description: >- Defines the max longitude component of a bounding box to limit the search to. Requires all other `boundary.rect` parameters to be specified. required: false schema: type: number format: double searchBoundaryCircleLat: name: boundary.circle.lat in: query description: >- The latitude of the center of a circle to limit the search to. Requires `boundary.circle.lon`. schema: type: number format: double searchBoundaryCircleLon: name: boundary.circle.lon in: query description: >- The longitude of the center of a circle to limit the search to. Requires `boundary.circle.lat`. schema: type: number format: double searchBoundaryCircleRadius: name: boundary.circle.radius in: query description: >- The radius of the circle (in kilometers) to limit the search to. Defaults to 50km if unspecified. schema: type: number format: double searchBoundaryCountry: name: boundary.country in: query description: >- A list of countries to limit the search to. These may be either full names (ex: Canada), or an ISO 3116-1 alpha-2 or alpha-3 code. Prefer ISO codes when possible. schema: type: array items: type: string style: form explode: false searchBoundaryGID: name: boundary.gid in: query description: The Pelias GID of an area to limit the search to. schema: type: string searchLayers: name: layers in: query description: A list of layers to limit the search to. schema: type: array items: $ref: '#/components/schemas/peliasLayer' style: form explode: false searchSources: name: sources in: query description: A list of sources to limit the search to. schema: type: array items: $ref: '#/components/schemas/peliasSource' style: form explode: false searchAddress: name: address in: query description: A street name, optionally with a house number. required: false schema: type: string example: 11 Wall Street searchNeighborhood: name: neighbourhood in: query description: Varies by area, but has a locally specific meaning (NOT always an official administrative unit). required: false schema: type: string example: Financial District searchBorough: name: borough in: query description: A unit within a city (not widely used, but present in places like NYC and Mexico City). required: false schema: type: string example: Manhattan searchLocality: name: locality in: query description: The city, village, town, etc. that the place/address is part of. required: false schema: type: string example: New York searchCounty: name: county in: query description: >- Administrative divisions between localities and regions. Not commonly used as input to structured geocoding. required: false schema: type: string example: New York County searchRegion: name: region in: query description: Typically the first administrative division within a country. For example, a US state or a Canadian province. required: false schema: type: string example: New York searchPostalCode: name: postalcode in: query description: A mail sorting code. required: false schema: type: string example: 10005 searchCountry: name: country in: query description: >- A full name (ex: Canada), or a 2 or 3 character ISO code. Prefer ISO codes when possible. required: false schema: type: string example: USA reverseLat: name: point.lat in: query required: true description: >- The latitude of the point at which to perform the search. schema: type: number format: double minimum: -90 maximum: 90 example: 48.848268 reverseLon: name: point.lon in: query required: true description: >- The longitude of the point at which to perform the search. schema: type: number format: double minimum: -180 maximum: 180 example: 2.294471 placeIDs: name: ids in: query description: A list of Pelias GIDs to search for. schema: type: array items: type: string minItems: 1 style: form explode: false required: true size: name: size in: query description: The maximum number of results to return. schema: type: integer peliasLang: name: lang in: query description: >- A BCP47 language tag which specifies a preference for localization of results. By default, results are in the default locale of the source data, but specifying a language will attempt to localize the results. Note that while a `langtag` (in RFC 5646 terms) can contain script, region, etc., only the `language` portion, an ISO 639 code, will be considered. So `en-US` and `en-GB` will both be treated as English. schema: type: string
__label__pos
0.839571
Thread: Need Help with "Monty Hall" simulator program. 1. #1 Registered User Join Date Jun 2011 Posts 8 Need Help with "Monty Hall" simulator program. Hello All, I am currently a beginner C++ programmer. Here I have a program that simulates the "Monty Hall" problem. At first, the program prompted the user to choose what door they wanted to pick, and then went from there. I restructured it so that the computer simulates everything by itself and runs 10,000 times. However, as you will see in the code, the last part of my main function has variables that are not defined outside of the for loop. So, my question is, how do I forward those 4 variables out of the for loop so that I can use them to output the final results? I feel like this is a simple problem, but for whatever reason I cannot wrap my head around the answer. Ideally, the final result will look something like: "After running the program 10,000 times, the final results were: x wins out of x stays. x wins out of x switches." Thank you for any help provided. I will answer any necessary questions as best as I can. I apologize in advance for any code that is messy, inefficient, or otherwise unsatisfactory. As I stated I am a beginning programmer who is still trying to wrap his head around functions. Code: #include <iostream> #include <cstdlib> #include <time.h> using namespace std; int getUserChoice (); int determinePrizeLocation (); int getFinalChoice (int firstChoice, int grandPrize); bool getSwitchOrStay (int firstChoice, int finalChoice); void determineOutcomeStay (int finalChoice, int grandPrize, int winStay, int numOfStay); void determineOutcomeSwitch (int finalChoice, int grandPrize, int winStay, int numOfSwitch); void outputFinalResult (int winStay, int winSwitch, int numOfStay, int numOfSwitch); int main () { for (int i = 0; i > 10000; i++) { srand (time(0)); int firstChoice; int grandPrize; int finalChoice; int winStay = 0; int winSwitch = 0; int numOfStay = 0; int numOfSwitch = 0; firstChoice = getUserChoice (); grandPrize = determinePrizeLocation (); finalChoice = getFinalChoice (firstChoice, grandPrize); bool switchOrStay = getSwitchOrStay (firstChoice, finalChoice); if (switchOrStay == true) determineOutcomeStay (finalChoice, grandPrize, winStay, numOfStay); else determineOutcomeSwitch (finalChoice, grandPrize, winSwitch, numOfSwitch); } outputFinalResult (winStay, winSwitch, numOfStay, numOfSwitch); return 0; } int getUserChoice () { return rand () % 3 + 1; // Random first choice } int determinePrizeLocation () { int grandPrize = rand () % 3 + 1; // Grand prize is placed randomly return grandPrize; } int getFinalChoice (int firstChoice, int grandPrize) { int revealedDoor = rand () % 3 + 1; // Random number btw 1-3 int finalChoice; while (revealedDoor == grandPrize || revealedDoor == firstChoice) // Reveal whichever door isn't the grand prize or the door user selected { revealedDoor = rand () % 3 + 1; } int switchProbability = rand () % 2 + 1; // 50% chance of keeping or switching choice if (switchProbability == 1) // Represents user keeping their choice { return firstChoice; } else if (switchProbability == 2) // Represents user switching their choice { finalChoice = rand () % 3 + 1; // Randomizes finalChoice btw 1-3 while (finalChoice == revealedDoor || finalChoice == firstChoice) // Ensures that finalChoice isn't the door that was eliminated or { // the door that was initially selected finalChoice = rand () % 3 + 1; } return finalChoice; } } bool getSwitchOrStay (int firstChoice, int finalChoice) { if (finalChoice == firstChoice) return true; else return false; } void determineOutcomeStay (int choice, int grandPrize, int winStay, int numOfStay) { if (choice == grandPrize) { winStay++; // Increments winStay by 1 if user won by staying with their first choice } numOfStay++; } void determineOutcomeSwitch (int choice, int grandPrize, int winSwitch, int numOfSwitch) { if (choice == grandPrize) { winSwitch++; // Increments winSwitch by 1 if user won by switching their first choice } numOfSwitch++; } void outputFinalResult (int winStay, int winSwitch, int numOfStay, int numOfSwitch) { cout << "\nAfter running the program 10,000 times, the final results were:" << endl; cout << "\n" << winStay << " wins out of " << numOfStay << " stays." << endl; cout << "\n" << winSwitch << " wins out of " << numOfSwitch << " switches." << endl; } 2. #2 Registered User Join Date Apr 2006 Posts 2,133 Variables which accumulate their value through multiple iterations of a loop, must be declared outside that loop, in your case at the top of main. Also, in order for a function to change the value of one of the parameters passed to it, that parameter must be passed by reference. This is most easily achieved by changing it's type to a reference. For instance change "int" to "int&". References have other uses too, so it would behoove you to learn about them through a textbook. It is too clear and so it is hard to see. A dunce once searched for fire with a lighted lantern. Had he known what fire was, He could have cooked his rice much sooner. 3. #3 and the hat of int overfl Salem's Avatar Join Date Aug 2001 Location The edge of the known universe Posts 35,624 > for (int i = 0; i > 10000; i++) Perhaps you meant < ? > srand (time(0)); Move this outside your for loop. You should only do this ONCE in any single run of your program. In a short program, time(0) effectively returns the same value, so all your rand() values will be the same as well. If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut. If at first you don't succeed, try writing your phone number on the exam paper. Popular pages Recent additions subscribe to a feed Similar Threads 1. MONTY HALL problem By jackalope in forum C Programming Replies: 10 Last Post: 10-28-2010, 09:43 PM 2. "itoa"-"_itoa" , "inp"-"_inp", Why some functions have " By L.O.K. in forum Windows Programming Replies: 5 Last Post: 12-08-2002, 08:25 AM 3. "CWnd"-"HWnd","CBitmap"-"HBitmap"...., What is mean by " By L.O.K. in forum Windows Programming Replies: 2 Last Post: 12-04-2002, 07:59 AM Tags for this Thread
__label__pos
0.630972
0 CREATE TABLE users ( user_id int(10) unsigned NOT NULL auto_increment, username varchar(20) NOT NULL default '', password varchar(20) NOT NULL default '', PRIMARY KEY (user_id) ) TYPE=MyISAM; Questions: 1. What is the purpose of MyISAM? 2. What happen if I created the above table without MyISAM. 2 Contributors 2 Replies 3 Views 10 Years Discussion Span Last Post by lordx78 This question has already been answered. Start a new discussion instead. Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.
__label__pos
0.95689
Is there a way to associate a build number with bamboo builds? I would like to associate a real version number with each build triggered by bamboo (i.e. 1.0.92673), such that this version # can be accessible from Jira. Is this possible? 6 answers This widget could not be displayed. Hi AmitB, Could you please expand description of your use-case? I'm having trouble understanding what do you need - having more verbose context could make me recalling some tricks you could use... regards This widget could not be displayed. Currently, when I make a build from bamboo I only see a single number (i.e. #98), whereas I would like to see the actually build number (i.e. 3.0.91246). This way, on the jira side we can associate bugs with real version numbers rather than the internal bamboo build number. This widget could not be displayed. Hm... Do I undestand correctly that you would like to the numbers like 3.0.91246 on the JIRA builds tab? Like in the screenshot below, instead of the marked #numbers you would like to see 3.0.91246? This widget could not be displayed. Yes, exactly. Is it possible? This widget could not be displayed. note to self: http://bitbucket.org/atlassian/bamboo/annotate/default/components/bamboo-web-app/src/main/webapp/fragments/plan/displayWideBuildPlansList.ftl#line-167 (please ignore) AmitB, I don't think it is possible. The part of code that displays that #buildNumber in JIRA is hard-coded in Bamboo and I don't see any relevant plugin points that would allow extending the displaying. So I think the only way would be to hack the Bamboo sources and write custom logic that would output something different than #buildNumber on JIRA 'build' tab. Can I help you further somehow? This widget could not be displayed. OK, so it looks like I will have to incorporate the Bamboo build number into our version number so that we can track it in Jira. Thanks. Suggest an answer Log in or Sign up to answer Community showcase Posted yesterday in Jira What modern development practices are at the heart of how your team delivers software? Hey Community mates! Claire here from the Software Product Marketing team. We all know software development changes rapidly, and it's often tough to keep up. But from our research, we've found the h... 34 views 0 1 Join discussion Atlassian User Groups Connect with like-minded Atlassian users at free events near you! Find a group Connect with like-minded Atlassian users at free events near you! Find my local user group Unfortunately there are no AUG chapters near you at the moment. Start an AUG You're one step closer to meeting fellow Atlassian users at your local meet up. Learn more about AUGs Groups near you
__label__pos
0.694405
FotolEdhar - Fotolia Guest Post 5 important questions to ask potential ECM solution partners It's critical to select the right enterprise content management partner, so Bob Estes has several questions CIOs should ask around cloud support, data protection, integrations and more. Large-scale enterprise applications represent one of the single most important investment decisions a CIO is responsible for making. Whether it's a large-scale CRM deployment, an ERP deployment or an enterprise content management (ECM) system, these applications are often used daily by thousands of employees and require a high degree of customization to meet the specific requirements of the distributed enterprise. Enterprise content and information systems in particular serve as the productivity engine for the modern information worker and have become the foundation for enabling digital transformation initiatives. Because of the specialization and complexity involved in these types of deployments, enterprise IT leaders are increasingly looking to engage with experienced solution partners that possess the right knowledge and technical expertise to ensure they are choosing the right vendor and also help them implement and manage the solution on an ongoing basis. As someone who has spent the past two decades immersed in practically every facet of the ECM industry, I've seen firsthand just how critical it is to not just choose the right technology to manage enterprise content, but perhaps more importantly, to select the right solution partner to provide the expertise and guidance to customers as they work to modernize their content management capabilities. ECM: A moving target The average large enterprise generates a staggering amount of content every day -- from conventional content types such as documents, images and video to transactional data, machine data and a vast sea of unstructured data that presents its own set of obstacles when it comes to indexing, searching and retrieving content. However, the volume, velocity and variety of information that most organizations need to manage, store and protect now exceeds their ability to even marginally keep pace. Enterprise content management applications were built specifically for the purpose of capturing, storing, managing and delivering a variety of content types to its users. Over the past two decades, dozens of software vendors have brought solutions to market, including tools from large and established vendors such as those offered by Microsoft, IBM and Opentext to a number of specialized and niche applications customized to meet the specific requirements of industries such as the legal and healthcare markets. The fundamental proposition of an ECM system is that all content has business value, and increasingly, much of this content is also subject to a host of evolving regulatory compliance requirements. For the CIO intent on driving transformative change-the-business initiatives, the focus is now on taking an enterprise approach to managing all of this content -- regardless of how and where it might be stored. Choosing the right ECM solution partner will depend on a number of interdependent factors, including budgetary considerations, technical consultative expertise, integration with other systems and content sources, data security and compliance requirements, and perhaps most important of all, the solution provider's knowledge of the vendor landscape in general as well as its grasp of the customer's specific industry. 5 questions to ask potential ECM partners Identifying and vetting an ECM solution partner is both a rigorous and time-intensive process and there are likely dozens of questions which will need to be fully addressed by a prospective solution partner. Having worked with all of the major ECM systems and a multitude of solution partners over the past two decades, what follows below are what I consider to be the five questions that should be given the most weight as part of any comprehensive evaluation. 1. Can the solution partner support a cloud, on-premises and hybrid delivery model? The cloud has fundamentally changed the way applications and services are managed and delivered to users. While most commercial ECM systems are now offered in a cloud-based model, many highly regulated industries such as healthcare and government are unwilling to host sensitive content assets in the public cloud and will require content management applications that can be offered either on premises or can be split into a hybrid model. In this respect, not only is it important to have the assurances of an air-tight service level agreement (SLA), it will also require that a solution partner can actively monitor and enforce its provisions. 2. What security capabilities does the solution partner have to protect a customer's sensitive data from both insider threats and external threat actors? Ensuring that your content is protected from both external threat actors as well as insider threats remains a top priority for IT leaders. A 2020 survey of 5,000 enterprise knowledge workers found that cloud-based collaboration technologies and workforce turnover have become major drivers of data exfiltration as insider threat programs fail to keep pace with today's digital workplace. Among some of the key findings related to insider threats were that nearly three-quarters (73%) of employees report they had access to data they didn't create, while 59% admitted they could view data from other departments. As such, enterprise CIOs will need to establish that a solution partner has an in-depth understanding of the security controls that exist within a given ECM application and can also proactively identify and mitigate potential gaps in their content security strategy. 3. How easily can the solution partner integrate an ECM system with other internal or third-party systems? Just as the "network effect" posits that the value of the network itself increases with every added node or person using it, an ECM system likewise becomes incrementally more valuable as the other applications and content repositories are connected and can interact with it. For instance, the mortgage department of a financial institution might require its ECM system to be able to ingest content (such as lending applications, home inspection documents and notarized forms) from a number of different systems. This means that a prospective solution partner should possess an in-depth understanding of the type of APIs a system employs (i.e., SOAP vs. REST vs. proprietary) as well as the time and effort required to configure and tie these diverse systems together. 4. What specific capabilities does the solution partner provide to help manage and monitor multiple ECM systems? Further complicating the enterprise content conundrum is the fact that enterprise CIOs are often not dealing with a single ECM application but rather a number of disparate systems supported by an array of software vendors, each with their own service agreements and support structures. According tothe Association for Intelligent Information Management, organizations are wrestling with an average of five different content systems and repositories which often comes about as the result of multiple corporate acquisitions. A prospective solution partner should have its own tools and processes in place to manage and monitor these various systems in a unified manner, providing stakeholders with the system-wide visibility they need to make informed decisions regarding the infrastructure that supports these applications. 5. How can the solution partner guarantee uptime and enforce other key performance metrics as defined in the SLA? ECM and EIM (enterprise information management) applications have a vast footprint that touches a broad swath of functional roles, departments and other external resources, making it crucial to understand precisely which KPIs should be collected, how those performance metrics will be measured and enforced, the tool sets they use to manage and monitor an ECM system, and what mechanisms they will have at their disposal to proactively mitigate any performance issues as they arise. As the old proverb goes, "the journey of a thousand miles begins with a single step." For the enterprise CIOs tasked with transforming their content management strategy, it will undoubtedly be a long and sometimes arduous journey. However, with the support and guidance of the right solution partner, it will be made considerably easier. About the author Bob Estes is the CEO and president of Reveille Software, a provider of management and monitoring solutions for enterprise content management systems. Over the past 25 years, Bob has successfully launched several early-stage high-tech software companies, including MediaBin Inc., a market leader in brand asset management, which was later acquired by Interwoven, Inc. He has also served as VP of marketing and product management with several Atlanta-based software companies focused on enterprise content management, sales force automation and mobile communications, including XcelleNet, Inc. Dig Deeper on Content management software and services Business Analytics Data Management ERP SearchOracle SearchSAP Close
__label__pos
0.678028
EVECelery.tasks.ESI.Contacts.Models.get_characters_character_id_contacts_200# A model definition module returned by an ESI task. This module was automatically generated from Jinja templates with the codegen tool included in the root of this repo. You should not directly modify this module but instead modify the template ‘codegen/Templates/ESI_Models.py’. Module Contents# Classes# GetCharactersCharacterIdContactsOkItem GetCharactersCharacterIdContactsOk Headers200_get_characters_character_id_contacts Headers for response code 200 Response200_get_characters_character_id_contacts A list of contacts class EVECelery.tasks.ESI.Contacts.Models.get_characters_character_id_contacts_200.GetCharactersCharacterIdContactsOkItem# Bases: pydantic.BaseModel contact_id: int# contact_type: Literal[character, corporation, alliance, faction]# is_blocked: bool | None# is_watched: bool | None# label_ids: List[int] | None# standing: float# class EVECelery.tasks.ESI.Contacts.Models.get_characters_character_id_contacts_200.GetCharactersCharacterIdContactsOk# Bases: pydantic.BaseModel __root__: List[GetCharactersCharacterIdContactsOkItem]# class EVECelery.tasks.ESI.Contacts.Models.get_characters_character_id_contacts_200.Headers200_get_characters_character_id_contacts# Bases: EVECelery.tasks.BaseTasks.Models.ModelsBase.ModelBaseEVECelery Headers for response code 200 Cache_Control: str | None# ETag: str | None# Expires: str | None# Last_Modified: str | None# X_Pages: int | None# class EVECelery.tasks.ESI.Contacts.Models.get_characters_character_id_contacts_200.Response200_get_characters_character_id_contacts# Bases: EVECelery.tasks.BaseTasks.Models.ModelsCached.ModelCachedResponse A list of contacts Response for code 200. This model contains the response body and headers returned from ESI. Example responses from ESI: [ { "contact_id": 123, "contact_type": "character", "is_blocked": true, "is_watched": true, "standing": 9.9 } ] headers: Headers200_get_characters_character_id_contacts# body: GetCharactersCharacterIdContactsOk#
__label__pos
0.814917
Posts Tagged ‘Vector3’ 【Unity3D】关于Vector3向量与Quaternion四元数的转换与应用 星期二, 四月 7th, 2015 3 views 在Unity中大家对Vector3应该说是很熟悉了,这里就简单带过一下,Vector3表示一个三维向量(x,y,z),例如Vector3.forward等价于new Vectory(0,0,1),即x=0,y=0,z=1的一个向量。图就不画了,大家高中都学过。 而Quaternion表示一个四元数,何为四元数,例如ai+bj+ck+d这样一个超复数,篇幅有限高数这里也不多说了,我们只关注一下Unity的四元数类的使用就好。在Unity中Quaternion(四元数类)主要用来处理物体的旋转,其实数变量由x,y,z,w四个参数构成,区间[-1,1]。 例如绕y轴旋转180°写做(0,1,0,0),调用公式计算过程如下: 由欧拉旋转(X,Y,Z)转换为四元数(x,y,z,w) —————————————————-> x = sin(Y/2)sin(Z/2)cos(X/2)+cos(Y/2)cos(Z/2)sin(X/2) y = sin(Y/2)cos(Z/2)cos(X/2)+cos(Y/2)sin(Z/2)sin(X/2) z = cos(Y/2)sin(Z/2)cos(X/2)-sin(Y/2)cos(Z/2)sin(X/2) w = cos(Y/2)cos(Z/2)cos(X/2)-sin(Y/2)sin(Z/2)sin(X/2) q = (x, y, z, w) —————————————————-> X = 0 Y = 180 Z = 0 —————————————————-> x = 0 y = 1 z = 0 w = 0 在Unity中这一套转换可以直接调用方法Quaternion.Euler(0, 180, 0)或者transform.Rotate(0, 180, 0)完成。euler即欧拉角的意思,欧拉角可以用Vector进行表示,表示在x,y,z三轴上的旋转角度。 同时transform.rotation即是一个四元数,表示物体的旋转角度方向,我们可以通过Quaternion.Euler和Quaternion.eulerAngles(但这个方法在Unity4之后的版本已经过时)将欧拉角转换为四元数。 因此假设需要让一个物体的顺时针方向以y轴旋转90°有以下几种方法: 1 2 3 4 5 6 7 8 //用四元数的欧拉方法 旋转到90° transform.rotation = Quaternion.Euler(new Vector3(0, 90, 0)); //用四元数的向量方法 Vector3(1, 0, 0) 表示1个90°方向的向量 transform.rotation = Quaternion.LookRotation(new Vector3(1, 0, 0)); //每一帧自旋转90° transform.Rotate(new Vector3(0, 90, 0)); 以上方法均可在一帧之内旋转顺时针绕y轴旋转90°。但通常游戏中有一个缓慢转动的过程,如果需要一步到位,而是慢慢旋转到90°应该如何去做呢。我们可以使用以下方法: 1 2 3 4 5 //使用四元数的球形差值方法 在每一帧中调整与目标四元数的差值 transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(new Vector3(1, 0, 0)), 10 * Time.deltaTime); //使用Vector3的RotateTowards方法将一个向量转向另一个向量 transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(transform.forward, new Vector3(1, 0, 0), Time.deltaTime, Time.deltaTime)); 从理论上来说球形差值Quaternion.Slerp的转向要平滑一些但相应的运算量大,每一帧都在出现误差值所以每一帧都在校调,而RotateTowards的方法要简洁但粗暴一些,但转向的平滑性不如前者好,特别是在多方向同时操作上,会出现一些不平滑的问题。 综上,建议在设计转向模块的时候,保留两种方案,在实际操作中对比两种方案的显示效果,择优选用。 本篇到此,欢迎大家补充新的方法,用以达到以上两端代码块同样的效果。 BeiTown 2015.04.07
__label__pos
0.611735
This chapter shows best practices about the integration and usage of Xtract Universal with Pentaho Data Integration (ETL) aka Kettle by calling the Xtract Universal HTTP endpoint (aka http-csv destination). The picture below shows the architecture. In Pentaho, we execute the extraction using an HTTP call. Xtract Universal extracts the data from SAP and delivers it via HTTP in CSV format. In Pentaho, we can then process the delivered data and then load then e.g. to a database. xu-pdi-ws This scenario would run on any operating system, unlike the command line scenario, which only runs on a Windows operating system. In Xtract Universal, we have defined an extraction with HTTP-CSV Destination. Extraction in Xtract Universal Here we see the definition of extraction in Xtract Universal with HTTP-CSV Destination: pdi-http-xu Transformation in PDI The overview of the transformation in Kettle shows the steps used: Transformation Initial Parameters Let’s look at the settings of the important steps. In the first step we define the URL of the extraction in Xtract Universal: http://KETSWIN16DC02:8065/?name=SAPCustomer Initial parameters HTTP Call In the second step, we execute the HTTP call. The URL parameter is passed. The return is written to the ExtractionResult field. The HTTP status code is also written to a specific field. The HTTP status code can be used for error handling. HTTP Switch Case If the status code is 200, the execution was successful. In case of an error we write to the log. Switch Case Split to rows We split the result into lines using the line break character. Note that the first line contains the column names. The last line contains only NULL values. We will remove these 2 rows later. split rows Xtract Universal offers also options to deliver the data without the column names and without a row seperator after the last row, but we are just using the default settings for the http-csv destination. Identity last row In this step we identify the last row. The step is helpful when we calculate the number of rows and remove the last row. last row Filter rows In this step we remove the first and last rows. filter split to columns Data rows are split into columns. In this step we have to define the column names and the data type. split columns Database Connection This is how the connection to the SQL Server looks, which we use to write the data to a table: database connection Table output We use the following settings for the table output: table File output In addition, we write the data to a file. The following settings are used: file Calculate Number of Rows In this branch we want to calculate the number of records. In this step we remove the first row that contains the original column names. Only the last row remains. Filter Formula Now we can calculate the number of rows. formula In this step we write to the log Log Execute the Transformation in PDI After successful execution we can find the metrics. execution Preview in PDI The preview of the individual steps is also possible. Preview of the HTTP Call: HTTP Client Preview Preview of the step split into rows rows Preview Preview of the step split into columns columns Preview Preview of the data output: output Preview Data im SQL Server Here we see the data that we have loaded into the SQL Server: SQL Server{:class=”img-responsive” In this chapter we have seen how we called and used SAP extractions in Pentaho via HTTP. The SAP extractions are provided by Xtract Universal. A possible improvement of this scenario would be to extract also the metadata (column name and data type) from Xtract Universal and use it dynamically in the transformation. Download the transformation template for PDI You can download the transformation template for Pentaho Data Integration (PDI) aka Kettle here: Call SAP Extraction from Xract Universal via HTTP.ktr
__label__pos
0.878184