text
stringlengths
1
1.04M
language
stringclasses
25 values
Financial services platform KFin Technologies on today said it has fixed a price band of Rs 347-366 a share for its Rs 1,500-crore initial share sale, which will open for public subscription on December 19. The three-day initial public offering will conclude on December 21, and the bidding for anchor investors will take place on December 16, the company said in a statement. The IPO will be a pure offer-for-sale (OFS) of up to Rs 1,500 crore by its existing promoter General Atlantic Singapore Fund Pte Ltd. The company will not receive any proceeds from the offer, as all of it will go to the promoter. At present, the promoter and promoter group hold a 74. 37 per cent stake in the company. KFin Technologies is majority-owned by funds managed by private equity investor General Atlantic. Kotak Mahindra Bank Limited also owns a 9. 98 per cent stake in KFintech which it acquired in 2021. The company said that 75 per cent of the issue size has been reserved for qualified institutional investors, 15 per cent for non-institutional investors and the remaining 10 per cent for retail investors. Investors can bid for a minimum of 40 shares and in multiples thereof. KFintech is an investor and issuer solutions provider, serving asset managers such as mutual funds, alternative investment funds (AIFs), wealth managers, pension funds and corporate issuers, as well as international clients in Southeast Asia and Hong Kong. It is the country's largest investor solutions provider to Indian mutual funds based on the number of asset management company (AMC) clients serviced as of September 2022. The firm provides services to 24 out of 41 AMCs in India, representing 59 per cent market share. ICICI Securities, Kotak Mahindra Capital Company, JP Morgan India, IIFL Securities and Jefferies India are the book-running lead managers to the issue. The equity shares of the company will be listed on the stock exchanges on December 29. (Except for the headline, this story has not been edited by NDTV staff and is published from a syndicated feed. )
english
<filename>docs/api/rules/greaterThan.md --- id: greaterThan title: .greaterThan --- The `.greaterThan` rule is used to ensure that the value of a given `number` property is strictly greater than a given value. ## Example ```typescript import { Validator } from 'fluentvalidation-ts'; type FormModel = { quantity: number; }; class FormValidator extends Validator<FormModel> { constructor() { super(); this.ruleFor('quantity').greaterThan(0); } } const formValidator = new FormValidator(); formValidator.validate({ quantity: 2 }); // ✔ {} formValidator.validate({ quantity: 0 }); // ❌ { quantity: 'Value must be greater than 0' } ``` ## Reference ### `.greaterThan(threshold: number)` A number validation rule which takes in a threshold and ensures that the given property is strictly greater than it. ## Example Message > Value must be greater than `[threshold]`
markdown
<filename>commands/new.tsx import React from 'react' import {Box} from 'ink' import PropTypes from 'prop-types' import {SessionInfo} from '../components/SessionInfo' import FileTree from '../components/FileTree' import Errors from '../components/Errors' import useLocalRegistry from '../hooks/useLocalRegistry' import useDriveSync from '../hooks/useDriveSync' import Hotkeys from '../components/Hotkeys' import Stats from '../components/Stats' import DisplayComponent from '../components/DisplayComponent' import {AppContextProvider} from '../contexts/App' import useHyper from '../hooks/useHyper' interface IHostProps { dir: string; includeGitFiles: boolean; verbose: boolean; tree: boolean; } /// Creates a new portal from the given directory const Host = ({dir, includeGitFiles, verbose, tree}: IHostProps) => { const hyper = useHyper() const { errors, loading, localRegistry, registryRenderableArray, stats } = useLocalRegistry(dir, hyper.hyperObj?.eventLog, !includeGitFiles, verbose) useDriveSync(dir, localRegistry, hyper.hyperObj?.drive) return ( <AppContextProvider hyper={hyper}> <Box flexDirection="column"> <SessionInfo numConnected={hyper.numConnected} sessionId={hyper?.hyperObj?.eventLog?.key?.toString('hex')}/> <DisplayComponent loading={loading} loadingMessage={`Scanning directory... ${registryRenderableArray.length} files found`}> <FileTree registry={registryRenderableArray} full={tree}/> <Stats registry={registryRenderableArray} totalBytes={stats.totalBytes} bytesPerSecond={stats.bytesPerSecond}/> </DisplayComponent> <Hotkeys/> <Errors errors={errors}/> </Box> </AppContextProvider> ) } Host.propTypes = { /// Directory to create portal from. Defaults to current working directory dir: PropTypes.string, /// Include git dotfiles includeGitFiles: PropTypes.bool, /// Verbose mode verbose: PropTypes.bool, /// Show full folder file tree tree: PropTypes.bool } Host.shortFlags = { dir: 'd', verbose: 'v', tree: 't' } Host.defaultProps = { dir: '.', includeGitFiles: false, verbose: false, tree: false } export default Host
typescript
Identifying the young goalies with the talent and opportunity to take their game to the next level. Levi has succeeded at every level, including a great college career at Northeastern University, where he became the first goalie to ever win the Mike Richter Award as the NCAA’s best goalie two years in a row. He performed for Canada in the 2021 World Junior Championship, posting a ridiculous .964 save percentage in seven games. The Sabres let Levi get his first taste of the NHL in March and April, and he fit right in. He’s not the biggest goalie, but his positioning is great thanks to his quick reads and strong skating.Read more: Strictly the Facts: James Jordan on Strictly's return show - and who he thinks will be first outJoin us as we break down week one of Strictly Come Dancing 2023! Detroit Red Wings 2023-24 season previewThe Red Wings should improve from last season, but in a highly competitive East, the odds are stacked against them. Arizona Coyotes 2023-24 season previewAfter years of blatant tanking that led to the addition of good talent, Arizona once again looks like a team that wants to win hockey games. Max Verstappen’s faultless, dominant Japanese GP sums up F1 in 2023In a race where just 15 cars finished, Verstappen never stumbled, and Red Bull cruised to its second consecutive constructors' championship. The best lightweight laptops in September 2023Super-portable yet still surprisingly powerful, these are the best lightweight laptops available today. No goalie enters the 2023-24 season with a higher expectation of a breakout than Sabres rookie Devon Levi. The 21-year-old made his NHL debut late last season and impressed with a 5-2-0 record and .905 save percentage. Levi has succeeded at every level, including a great college career at Northeastern University, where he became the first goalie to ever win the Mike Richter Award as the NCAA’s best goalie two years in a row. He performed for Canada in the 2021 World Junior Championship, posting a ridiculous .964 save percentage in seven games. The Sabres let Levi get his first taste of the NHL in March and April, and he fit right in. He’s not the biggest goalie, but his positioning is great thanks to his quick reads and strong skating. What elevates Levi above other talented young goalies heading into this season is his clear path to a No. 1 job. The Sabres declined to bring in goalie help this summer, and with onlyas competition, Levi could cement himself as the workhorse goalie quickly. Considering the high overall expectations for the Sabres, it’s a lot to ask from a goalie in his first full season as a pro, but Levi’s talent is obvious so it will be a fascinating storyline to watch unfold.
english
{"packages":{"wpackagist-plugin\/undo-publish":{"0.1":{"name":"wpackagist-plugin\/undo-publish","version":"0.1","version_normalized":"0.1.0.0","uid":368241,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/undo-publish.0.1.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/undo-publish\/","reference":"tags\/0.1"},"homepage":"https:\/\/wordpress.org\/plugins\/undo-publish\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"0.2":{"name":"wpackagist-plugin\/undo-publish","version":"0.2","version_normalized":"0.2.0.0","uid":368242,"dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/undo-publish.0.2.zip"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/undo-publish\/","reference":"tags\/0.2"},"homepage":"https:\/\/wordpress.org\/plugins\/undo-publish\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"},"dev-trunk":{"name":"wpackagist-plugin\/undo-publish","version":"dev-trunk","version_normalized":"9999999-dev","uid":368243,"time":"2010-07-30 04:00:02","dist":{"type":"zip","url":"https:\/\/downloads.wordpress.org\/plugin\/undo-publish.zip?timestamp=1280462402"},"source":{"type":"svn","url":"https:\/\/plugins.svn.wordpress.org\/undo-publish\/","reference":"trunk"},"homepage":"https:\/\/wordpress.org\/plugins\/undo-publish\/","require":{"composer\/installers":"~1.0"},"type":"wordpress-plugin"}}}}
json
{"firebase-analytics.js":"<KEY>,"firebase-analytics.min.js":"<KEY>,"firebase-app.js":"<KEY>,"firebase-app.min.js":"<KEY>,"firebase-auth.js":"<KEY>,"firebase-auth.min.js":"<KEY>,"firebase-database.js":"sha512-uZ89v8C0V3fLZmtgqC/7e0fiFNGXiIYcLfEwgOor/vBk77ohgdkTQnuLsX+AEoVZYMDHH216lIgtmzW2KkMmaw==","firebase-database.min.js":"<KEY>,"firebase-firestore.js":"<KEY>,"firebase-firestore.memory.js":"<KEY>,"firebase-firestore.memory.min.js":"<KEY>,"firebase-firestore.min.js":"<KEY>,"firebase-functions.js":"<KEY>,"firebase-functions.min.js":"sha512-6dW+kDeBWxU89S/oKR0vOFfNcnX6V/3wQkplDETdkCGnTtLiGO11fSlD7mdQ+w/MmrVkBvZCwdqdWatFub5P5w==","firebase-installations.js":"sha512-XwnKOztRq9zCY32FD4Wmf9ul+pL2oKolT1+iqZKhFHtdg+/0qGVTS1TFr8r0RAJtlAfgaqhG4CVi5LaPUTfcug==","firebase-installations.min.js":"sha512-K9LLZn6p2E75GWJDm/BFtPt1F4jvmoFWr02MfOUOx2dV5/Get6kMBby/u4xJMSORnidlowh59rRfMTkhCUtyhQ==","firebase-messaging.js":"<KEY>,"firebase-messaging.min.js":"<KEY>,"firebase-performance-standalone.es2017.js":"sha512-MLtqvZcla1G7p2WG716F2wAASQkvY4/cOhA2pQriy96sfJw2ZINrMcI3okMDF5RhMGrMud6GRf+6aB+3LaIXJw==","firebase-performance-standalone.es2017.min.js":"sha512-reTsnE1kZx7HogW9iNP6bj+yTU5Uhe3z7jSxppTCSaYmU2bi/wDtSay7kpILV3rBj5+lP+8r6ics15aKy2YRaw==","firebase-performance-standalone.js":"sha512-lmVrjUeWE+d+PwH7RwtNx1YO3OkGGUzX3MN8VtFfMEyMYW<KEY>ZXur3X89FlSIkLrHTwYR<KEY>,"firebase-performance-standalone.min.js":"sha512-sON/5KolGSTW8O8NoBVzXjI5pCacgVU9hW5MPyVoGP89yONCEQRrZIJaJhb3R7oT5N3wpRvu/uaB+pGU7PAz3Q==","firebase-performance.js":"sha512-mYDiduQZIFbwVT+dZK3mPd0yiL6rAYSuyHPRQHk2xLEw9mwnQf90MEwO9xUG7xOhgRehITYwH03X5HByFDz5vA==","firebase-performance.min.js":"<KEY>,"firebase-remote-config.js":"<KEY>,"firebase-remote-config.min.js":"<KEY>,"firebase-storage.js":"<KEY>,"firebase-storage.min.js":"sha512-iBKVMEOoY76w2N0W6WwJ1i+cfgjSE6Sfhtw3zNsybpPm0SL4yITlHaTPilcyEdakduRaQDK2EoyBxK89ePMBdQ==","firebase.js":"<KEY>,"firebase.min.js":"<KEY>}
json
<filename>data/usercss/66511.user.css /* ==UserStyle== @name Tumblr logo - Harry Potter font {white} @namespace USO Archive @author heytherelexa @description `Tumblr logo in Harry Potter font. White, with a black outer glow. Requested by osolhosdeasuamae.` @version 20120530.21.11 @license NO-REDISTRIBUTION @preprocessor uso ==/UserStyle== */ @namespace url(http://www.w3.org/1999/xhtml); @-moz-document url-prefix('http://www.tumblr.com/'), url-prefix('https://www.tumblr.com/') { #logo {height: 0 !important; width: 0 !important; padding-left: 230px !important; padding-top: 120px !important; background: url(http://i226.photobucket.com/albums/dd64/atxdivagal/tumblrlogowhite.png) no-repeat !important;}}
css
{ "_args": [ [ "split2@https://registry.npmjs.org/split2/-/split2-2.1.1.tgz", "/home/amit/repos/github_page/node_modules/csv-parser/node_modules/ndjson" ] ], "_from": "split2@>=2.1.0 <3.0.0", "_id": "split2@2.1.1", "_inCache": true, "_location": "/csv-parser/ndjson/split2", "_phantomChildren": {}, "_requested": { "name": "split2", "raw": "split2@https://registry.npmjs.org/split2/-/split2-2.1.1.tgz", "rawSpec": "https://registry.npmjs.org/split2/-/split2-2.1.1.tgz", "scope": null, "spec": "https://registry.npmjs.org/split2/-/split2-2.1.1.tgz", "type": "remote" }, "_requiredBy": [ "/csv-parser/ndjson" ], "_resolved": "https://registry.npmjs.org/split2/-/split2-2.1.1.tgz", "_shasum": "7a1f551e176a90ecd3345f7246a0cfe175ef4fd0", "_shrinkwrap": null, "_spec": "split2@https://registry.npmjs.org/split2/-/split2-2.1.1.tgz", "_where": "/home/amit/repos/github_page/node_modules/csv-parser/node_modules/ndjson", "author": { "email": "<EMAIL>", "name": "<NAME>" }, "bugs": { "url": "http://github.com/mcollina/split2/issues" }, "dependencies": { "through2": "^2.0.2" }, "description": "split a Text Stream into a Line Stream, using Stream 3", "devDependencies": { "callback-stream": "^1.1.0", "fastbench": "^1.0.0", "pre-commit": "^1.1.2", "standard": "^8.6.0", "tap": "^8.0.1" }, "homepage": "https://github.com/mcollina/split2#readme", "license": "ISC", "main": "index.js", "name": "split2", "optionalDependencies": {}, "pre-commit": [ "test" ], "readme": "# Split2(matcher, mapper, options)\n\n[![build status](https://secure.travis-ci.org/mcollina/split2.svg)](http://travis-ci.org/mcollina/split2)\n\nBreak up a stream and reassemble it so that each line is a chunk.\n`split2` is inspired by [@dominictarr](https://github.com/dominictarr) [`split`](https://github.com/dominictarr/split) module,\nand it is totally API compatible with it.\nHowever, it is based on [`through2`](https://github.com/rvagg/through2) by [@rvagg](https://github.com/rvagg) and it is fully based on Stream3.\n\n`matcher` may be a `String`, or a `RegExp`. Example, read every line in a file ...\n\n``` js\n fs.createReadStream(file)\n .pipe(split2())\n .on('data', function (line) {\n //each chunk now is a seperate line!\n })\n\n```\n\n`split` takes the same arguments as `string.split` except it defaults to '/\\r?\\n/' instead of ',', and the optional `limit` paremeter is ignored.\n[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split)\n\n`split` takes an optional options object on it's third argument, which\nis directly passed as a\n[Transform](http://nodejs.org/api/stream.html#stream_class_stream_transform_1)\noption.\n\nAdditionally, the `.maxLength` option is implemented, which will make the split stream throw an error\nif the buffer size exceeds `.maxLength`.\n\nCalling `.destroy` will make the stream emit `close`. Use this to perform cleanup logic\n\n``` js\nvar splitFile = function(filename) {\n var file = fs.createReadStream(filename)\n\n return file\n .pipe(split2())\n .on('close', function() {\n // destroy the file stream in case the split stream was destroyed\n file.destroy()\n })\n}\n\nvar stream = splitFile('my-file.txt')\n\nstream.destroy() // will destroy the input file stream\n```\n\n# NDJ - Newline Delimited Json\n\n`split2` accepts a function which transforms each line.\n\n``` js\nfs.createReadStream(file)\n .pipe(split2(JSON.parse))\n .on('data', function (obj) {\n //each chunk now is a a js object\n })\n```\n\nHowever, in [@dominictarr](https://github.com/dominictarr) [`split`](https://github.com/dominictarr/split) the mapper\nis wrapped in a try-catch, while here it is not: if your parsing logic can throw, wrap it yourself.\n\n# License\n\nCopyright (c) 2014-2017, <NAME> <<EMAIL>>\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR\nIN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n", "readmeFilename": "README.md", "repository": { "type": "git", "url": "git+https://github.com/mcollina/split2.git" }, "scripts": { "test": "standard && tap -b test.js" }, "version": "2.1.1", "website": "https://github.com/mcollina/split2" }
json
<filename>sds-biz-suite/bizcore/WEB-INF/caf_core_src/com/terapico/utils/RestUtil.java package com.terapico.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class RestUtil { private static CloseableHttpClient httpclient = null; private static String getResponseAsString(CloseableHttpResponse response) throws IOException { HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity, StandardCharsets.UTF_8); return content; } private static byte[] getResponseAsByteArray(CloseableHttpResponse response) throws IOException { HttpEntity entity = response.getEntity(); return EntityUtils.toByteArray(entity); } public static Object remoteGetObject(String sessionId, String url, Class<?> clazz) throws ClientProtocolException, IOException { CloseableHttpClient httpClient = getHttpClient(); HttpGet getRequest = new HttpGet(url); getRequest.addHeader("Accept", "application/json"); getRequest.addHeader("Cookie", sessionId); getRequest.addHeader("X-Auth", sessionId); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Object responseObj = mapper.readValue(br, clazz); return responseObj; } private static CloseableHttpClient getHttpClient() { if (httpclient != null) { return httpclient; } httpclient = HttpClients.createDefault(); return httpclient; } public static Map<String, Object> getAsByteArray(URI uri) throws URISyntaxException, IOException { CloseableHttpClient client = getHttpClient(); HttpGet httpget = new HttpGet(uri); CloseableHttpResponse response = client.execute(httpget); StatusLine resLine = response.getStatusLine(); byte[] content = getResponseAsByteArray(response); System.out.println(new Date() + " http-get got: " + content.length + " bytes"); return MapUtil.put("code", resLine.getStatusCode()).put("reason", resLine.getReasonPhrase()) .put("body", content).into_map(); } public static Map<String, Object> getForJson(URI uri) throws URISyntaxException, IOException { CloseableHttpClient client = getHttpClient(); HttpGet httpget = new HttpGet(uri); CloseableHttpResponse response = client.execute(httpget); StatusLine resLine = response.getStatusLine(); String content = getResponseAsString(response); System.out.println(new Date() + " http-get got: " + content); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> responseObj = mapper.readValue(content, Map.class); responseObj.put("__response", MapUtil.newMap(MapUtil.$("code", resLine.getStatusCode()), MapUtil.$("reason", resLine.getReasonPhrase()))); return responseObj; } public static URI buildUri(String requestSchema, String requestHost, int requestPort, String requestPath, List<NameValuePair> requestParameters) throws URISyntaxException { URIBuilder builder = new URIBuilder(); builder.setScheme(requestSchema); builder.setHost(requestHost); if (requestPort > 0) { builder.setPort(requestPort); } if (requestPath != null) { builder.setPath(requestPath); } if (requestParameters != null) { builder.setParameters(requestParameters); } URI uri = builder.build(); return uri; } public static String postXml(String url, String xml, String encoding) throws IOException { String body = ""; CloseableHttpClient client = getHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8"); StringEntity entityParams = new StringEntity(xml, encoding); httpPost.setEntity(entityParams); CloseableHttpResponse response = client.execute(httpPost); HttpEntity entity = response.getEntity(); if (entity != null) { body = EntityUtils.toString(entity, encoding); } EntityUtils.consume(entity); response.close(); return body; } public static String postForm(String url, List<NameValuePair> params) throws Exception { HttpClient client = getHttpClient(); HttpPost httpPost = new HttpPost(url); String s = ""; httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); HttpResponse response = client.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); s = EntityUtils.toString(entity); return s; } else { throw new Exception("Request not success: " + statusCode); } } public static String postJson(String url, String json) throws Exception { String body = ""; CloseableHttpClient client = getHttpClient(); HttpPost httpPost = new HttpPost(url); StringEntity entityParams = null; CloseableHttpResponse response = null; HttpEntity entity = null; try { entityParams = new StringEntity(json); httpPost.setEntity(entityParams); response = client.execute(httpPost); entity = response.getEntity(); if (entity != null) { body = EntityUtils.toString(entity); } } catch (Exception e) { } finally { EntityUtils.consume(entity); if (response != null) { response.close(); } } return body; } public static Map<String, Object> getForJsonWithHeader(URI uri, Map<String, String> headers) throws URISyntaxException, IOException { CloseableHttpClient client = getHttpClient(); HttpGet httpget = new HttpGet(uri); if (headers != null && !headers.isEmpty()) { for (Entry<String, String> entry : headers.entrySet()) { httpget.addHeader(entry.getKey(), entry.getValue()); } } CloseableHttpResponse response = client.execute(httpget); StatusLine resLine = response.getStatusLine(); String content = getResponseAsString(response); System.out.println(new Date() + " http-get got: " + content); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> responseObj = mapper.readValue(content, Map.class); responseObj.put("__response", MapUtil.put("code", resLine.getStatusCode()) .put("reason", resLine.getReasonPhrase()).into_map()); return responseObj; } }
java
<filename>samples/demos/irb/experimenter/worker/server_api.py # Copyright 2021 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 import attestation import keys import protos.irb_pb2 as irb import storage_client import diagnose import base64 def HandleAttestation(): attestation_bytes = attestation.GetAttestation() print(attestation_bytes) #build identity bytes id = irb.Identity() id.public_key = keys.GetSerializedVerifyingKey() id.public_encryption_key = keys.GetSerializedEncryptionKey() id_bytes = id.SerializeToString() #build worker credentials wc = irb.WorkerCredentials() wc.identity_bytes = id_bytes wc.attestation = attestation_bytes.encode('utf_8') return wc.SerializeToString() def HandleExecuteEvaluationPack(evaluation_pack): eep = irb.EncryptedEvaluationPack() eep.ParseFromString(evaluation_pack) #decrypt encrypted evalution pack res = keys.PkDecrypt(eep.encrypted_encryption_key) if res[1] != None: return "Error decrypting eval encryption key: " + res[1] key = bytearray(res[0]) res = keys.Decrypt(key, eep.encrypted_evaluationpack) if res[1] != None: return "Error decrypting eval pack: " + res[1] evaluationpack = bytearray(res[0]) epm = irb.EvaluationPackMessage() epm.ParseFromString(evaluationpack) sc = storage_client.StorageClient() return_string = "" first = True for r in epm.registered_data: if first: first = False else: return_string += ", " print("Data handler: {0}".format(r.data_handler)) val = sc.get(r.data_handler) if val[1] == False: return "Error: Cannot retrieve value of key: " + r.data_handler print("Encoded data: {0}".format(val[0])) encrypted_data = base64.b64decode(val[0]) res = keys.Decrypt(r.decryption_key, encrypted_data) if res[1] != None: return "Error decrypting data item: " + res[1] data = bytearray(res[0]) result = diagnose.diagnose(data) if result[1] != "" : return "Error running diagnosis: " + result[1] return_string += result[0] print("Final result: {0}".format(return_string)) return return_string
python
ET Now: This announcement or this statement one of the highest outlays 1.35 lakh crores for FY18 to upgrade existing infra, invest in freight corridor so on so forth...all through the last three or four years the quantums may vary but we have heard of planned outlays somehow it does not quite result in the order books of railway companies and the results of the railway companies really showing the same performance. Why is that disconnect and can it get corrected this time around? V Kalyana Rama: It should get connected but I am not connected with that space of working see our company our capex is completely different from the capex which you are talking of. But hopefully this time because I am little bit connected with these things I hope things will definitely workout. ET Now: I know and we will come to something that essentially about your company as well because I do remember that there was earlier conversations that the racks could be doubled in terms of railway transportation and that itself will add a lot of value to Con Cor. We will come to Con Cor specific things but right now I am asking you to where more of an industry had and tell whether this disconnect it gets connected for the sector at large? V Kalyana Rama: Out of the capital outlay what has given by the railway ministry it is not only the wagons it is also the infrastructure development and the sectional capacity works and also so many other works in this like safety related works. So I think the capital outlay given by the Railway Ministry should be able to come through and definitely it should get connected with the industry also. The industry also should get benefitted of course this is more or less dependent on the economy also, the economy everybody is expecting to pick up in the FY17-FY18 so whether there is a pick up in the economy the things should work out. ET Now: Exactly the point as to how much would be the benefit of this capex outlay what kind of increment in volumes are you anticipating for the second half of the fiscal? V Kalyana Rama: As I mentioned earlier we are maintaining our growth rate of around 8% to 10% and I am not seeing any downward trend in that, I am hopeful of achieving the 8% to 10% growth in the volumes. In this FY definitely things are going on as per the plan and really the demonetisation did not affect much on the volumes which we are handling as on date also. V Kalyana Rama: I am just concluding that makes us comfortable achieving the growth plan whatever we are maintaining the guidance (6:49) of 8% to 10% in the volumes of this FY. ET Now: So where is your current total order book and if you could give us a segment division as well for the same? V Kalyana Rama: About our order book? ET Now: Yes, that is right. V Kalyana Rama: Yes, we are doing an EXIM as last first six months results we achieve around roughly 5% growth in EXIM sector and around 1.5 to 1.6% growth in our domestic sector. It will be in the same scenario that EXIM will be more pronounced because out of the total the volumes handle EXIM gives us around 80% of our volumes and 20% is through the domestic segment. So the same thing will continue as far as the volume is concerned. ET Now: So do not think demonetisation is likely to impact the EXIM segment at all? V Kalyana Rama: As of now it is not there so I am hopeful because now already it is from November 8th onwards almost we are reaching that 50 days period and even though if it continues but because in the last 45 days not much effect on our volumes, things are moving on. ET Now: After that Q2 disappointment because of that land licence fees or otherwise which are difficult to pass on everybody is hoping for better volumes number one and I think everybody is also betting on the fact that if double stacking starts then with volumes of 7.5 that you have guided for your margins will improve incrementally in Q3 and Q4 are those assumptions correct and will we see evidence of that in this quarter? V Kalyana Rama: You see we are now because we are almost breaching our third quarter and we will be coming out with our results. I will not be talking about the figures right now but regarding the double stack which you have mentioned this double stack is going on very good. In fact we started our double stack not only in imports but in exports also and the most positive sign is when we are running time table trains in EXIM sector between Delhi and Mundra via Katua. The response of the market is very good. The product is large and right from the first day it is a hit. Till now we are doing two trains between Delhi, Dadri into Katua’s. Now we increase it to four trains adding Ludhiana also into their circuit so this is an encouraging sign that the people are opting to the railways definitely back from road into the into the railway where we are assuring them a transit time and these are giving our double stack trains in export sector. The number of double stack trains is moving out of Katua’s are coming into Katua’s are increasing month on month so I am also hopeful that once I see the figures, my financial figures will be crunching my people must be crunching the figures very soon for the third quarter and we are hopeful that we should be able to come out with some better results because the things worked out well in this quarter.
english
import * as LSP from "vscode-languageserver-protocol"; import { merlin } from "../../../lib"; import Session from "../session"; export default class Merlin implements LSP.Disposable { private readonly session; private readonly queue; private readonly readline; private process; constructor(session: Session); dispose(): void; initialize(): Promise<void>; query<I, O>({ query }: merlin.Query<I, O>, token: LSP.CancellationToken | null, id?: LSP.TextDocumentIdentifier, priority?: number): merlin.Response<O>; restart(): Promise<void>; sync<I, O>({ sync: query }: merlin.Sync<I, O>, id?: LSP.TextDocumentIdentifier): merlin.Response<O>; private establishProtocol; private logMessage; }
typescript
<reponame>ntnhan2266/helper_admin_web<gh_stars>0 import { Component, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { BookingsService } from 'app/bookings/bookings.service'; export interface DialogData { id: string; } @Component({ selector: 'app-booking-cancel-dialog', templateUrl: './booking-cancel-dialog.component.html', styleUrls: ['./booking-cancel-dialog.component.scss'] }) export class BookingCancelDialogComponent { content: string; constructor( private bookingService: BookingsService, public dialogRef: MatDialogRef<BookingCancelDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: DialogData) { } onNoClick(): void { this.dialogRef.close(); } close(): void { this.dialogRef.close(); } cancelBooking() { this.bookingService.cancel(this.data.id, this.content).subscribe((res) => { this.dialogRef.close('OK'); }) } }
typescript
<filename>system/p2p/dht/protocol/p2pstore/handler.go package p2pstore import ( "encoding/hex" "sync/atomic" "time" "github.com/33cn/chain33/queue" "github.com/33cn/chain33/system/p2p/dht/protocol" types2 "github.com/33cn/chain33/system/p2p/dht/types" "github.com/33cn/chain33/types" "github.com/libp2p/go-libp2p-core/network" kb "github.com/libp2p/go-libp2p-kbucket" ) func (p *Protocol) handleStreamFetchChunk(stream network.Stream) { var req types.P2PRequest if err := protocol.ReadStreamAndAuthenticate(&req, stream); err != nil { return } param := req.Request.(*types.P2PRequest_ChunkInfoMsg).ChunkInfoMsg var res types.P2PResponse var bodys *types.BlockBodys var err error defer func() { t := time.Now() writeBodys(bodys, stream) _ = protocol.WriteStream(&res, stream) log.Info("handleStreamFetchChunk", "chunk hash", hex.EncodeToString(param.ChunkHash), "start", param.Start, "remote peer", stream.Conn().RemoteMultiaddr(), "time cost", time.Since(t)) }() // 全节点模式,只有网络中出现数据丢失时才提供数据 if p.SubConfig.IsFullNode { hexHash := hex.EncodeToString(param.ChunkHash) if _, ok := p.chunkWhiteList.Load(hexHash); !ok { //该chunk不在白名单里 if pid, ok := p.checkChunkInNetwork(param); ok { //网络中可以查到数据,不应该到全节点来要数据 var addrs [][]byte for _, addr := range p.Host.Peerstore().Addrs(pid) { addrs = append(addrs, addr.Bytes()) } res.CloserPeers = []*types.PeerInfo{{ID: []byte(pid), MultiAddr: addrs}} return } //该chunk添加到白名单,10分钟内无条件提供数据 p.chunkWhiteList.Store(hexHash, time.Now()) //分片网络中出现数据丢失,备份该chunk到分片网络中 go func() { chunkInfo, ok := p.getChunkInfoByHash(param.ChunkHash) if !ok { log.Error("HandleStreamFetchChunk chunkInfo not found", "chunk hash", hexHash) return } p.notifyStoreChunk(chunkInfo.ChunkInfoMsg) }() } bodys, err = p.getChunkBlock(param) if err != nil { res.Error = err.Error() return } return } closerPeers := p.healthyRoutingTable.NearestPeers(genDHTID(param.ChunkHash), AlphaValue) if len(closerPeers) != 0 && kb.Closer(p.Host.ID(), closerPeers[0], genChunkNameSpaceKey(param.ChunkHash)) { closerPeers = p.healthyRoutingTable.NearestPeers(genDHTID(param.ChunkHash), Backup-1) } for _, pid := range closerPeers { if pid == p.Host.ID() { continue } var addrs [][]byte for _, addr := range p.Host.Peerstore().Addrs(pid) { addrs = append(addrs, addr.Bytes()) } res.CloserPeers = append(res.CloserPeers, &types.PeerInfo{ ID: []byte(pid), MultiAddr: addrs, }) } if atomic.LoadInt64(&p.concurrency) > maxConcurrency { return } atomic.AddInt64(&p.concurrency, 1) defer atomic.AddInt64(&p.concurrency, -1) //分片节点模式,检查本地是否存在 bodys, err = p.getChunkBlock(param) if err != nil { res.Error = err.Error() return } } // 对端节点通知本节点保存数据 /* 检查点p2pStore是否保存了数据, 1)若已保存则只更新时间即可 2)若未保存则从网络中请求chunk数据 */ func (p *Protocol) handleStreamStoreChunks(req *types.P2PRequest) { log.Info("into handleStreamStoreChunks......") param := req.Request.(*types.P2PRequest_ChunkInfoList).ChunkInfoList.Items log.Info("handleStreamStoreChunks", "items len", len(param)) for _, info := range param { chunkHash := hex.EncodeToString(info.ChunkHash) //已有其他节点通知该节点保存该chunk,避免接收到多个节点的通知后重复查询数据 if _, ok := p.notifying.LoadOrStore(chunkHash, nil); ok { continue } //检查本地 p2pStore,如果已存在数据则直接更新 if err := p.updateChunk(info); err == nil { p.notifying.Delete(chunkHash) continue } //send message to notifying queue to process select { case p.notifyingQueue <- info: //drop the notify message if queue is full default: p.notifying.Delete(chunkHash) } } } func (p *Protocol) handleStreamGetHeader(req *types.P2PRequest, res *types.P2PResponse) error { param := req.Request.(*types.P2PRequest_ReqBlocks) msg := p.QueueClient.NewMessage("blockchain", types.EventGetHeaders, param.ReqBlocks) err := p.QueueClient.Send(msg, true) if err != nil { return err } resp, err := p.QueueClient.Wait(msg) if err != nil { return err } if headers, ok := resp.GetData().(*types.Headers); ok { res.Response = &types.P2PResponse_BlockHeaders{BlockHeaders: headers} return nil } return types.ErrNotFound } func (p *Protocol) handleStreamGetChunkRecord(req *types.P2PRequest, res *types.P2PResponse) error { param := req.Request.(*types.P2PRequest_ReqChunkRecords).ReqChunkRecords records, err := p.getChunkRecordFromBlockchain(param) if err != nil { return err } res.Response = &types.P2PResponse_ChunkRecords{ChunkRecords: records} return nil } //handleEventNotifyStoreChunk handles notification of blockchain, // store chunk if this node is the nearest *count* node in the local routing table. func (p *Protocol) handleEventNotifyStoreChunk(m *queue.Message) { req := m.GetData().(*types.ChunkInfoMsg) var err error defer func() { m.Reply(p.QueueClient.NewMessage("blockchain", 0, &types.Reply{ IsOk: err == nil, })) }() if p.SubConfig.IsFullNode { //全节点保存所有chunk, blockchain模块通知保存chunk时直接保存到本地 if err = p.storeChunk(req); err != nil { log.Error("HandleEventNotifyStoreChunk", "storeChunk error", err) } return } //如果本节点是本地路由表中距离该chunk最近的节点,则保存数据;否则不需要保存数据 pid := p.healthyRoutingTable.NearestPeer(genDHTID(req.ChunkHash)) if pid != "" && kb.Closer(pid, p.Host.ID(), genChunkNameSpaceKey(req.ChunkHash)) { return } err = p.checkNetworkAndStoreChunk(req) if err != nil { log.Error("StoreChunk", "chunk hash", hex.EncodeToString(req.ChunkHash), "start", req.Start, "end", req.End, "error", err) return } log.Info("StoreChunk", "local pid", p.Host.ID(), "chunk hash", hex.EncodeToString(req.ChunkHash)) } func (p *Protocol) handleEventGetChunkBlock(m *queue.Message) { req := m.GetData().(*types.ChunkInfoMsg) bodys, _, err := p.getChunk(req) if err != nil { log.Error("GetChunkBlock", "chunk hash", hex.EncodeToString(req.ChunkHash), "start", req.Start, "end", req.End, "error", err) return } headers := p.getHeaders(&types.ReqBlocks{Start: req.Start, End: req.End}) if len(headers.Items) != len(bodys.Items) { log.Error("GetBlockHeader", "error", types2.ErrLength, "header length", len(headers.Items), "body length", len(bodys.Items), "start", req.Start, "end", req.End) return } var blockList []*types.Block for index := range bodys.Items { body := bodys.Items[index] header := headers.Items[index] block := &types.Block{ Version: header.Version, ParentHash: header.ParentHash, TxHash: header.TxHash, StateHash: header.StateHash, Height: header.Height, BlockTime: header.BlockTime, Difficulty: header.Difficulty, MainHash: body.MainHash, MainHeight: body.MainHeight, Signature: header.Signature, Txs: body.Txs, } blockList = append(blockList, block) } msg := p.QueueClient.NewMessage("blockchain", types.EventAddChunkBlock, &types.Blocks{Items: blockList}) err = p.QueueClient.Send(msg, false) if err != nil { log.Error("EventGetChunkBlock", "reply message error", err) } } func (p *Protocol) handleEventGetChunkBlockBody(m *queue.Message) { req := m.GetData().(*types.ChunkInfoMsg) blockBodys, _, err := p.getChunk(req) if err != nil { log.Error("GetChunkBlockBody", "chunk hash", hex.EncodeToString(req.ChunkHash), "start", req.Start, "end", req.End, "error", err) m.ReplyErr("", err) return } m.Reply(&queue.Message{Data: blockBodys}) } func (p *Protocol) handleEventGetChunkRecord(m *queue.Message) { req := m.GetData().(*types.ReqChunkRecords) records := p.getChunkRecords(req) if records == nil { log.Error("handleEventGetChunkRecord", "getChunkRecords error", types2.ErrNotFound) return } msg := p.QueueClient.NewMessage("blockchain", types.EventAddChunkRecord, records) err := p.QueueClient.Send(msg, false) if err != nil { log.Error("handleEventGetChunkRecord", "reply message error", err) } } func writeBodys(bodys *types.BlockBodys, stream network.Stream) { if bodys == nil { return } var data types.P2PResponse for _, body := range bodys.Items { data.Response = &types.P2PResponse_BlockBody{ BlockBody: body, } if err := protocol.WriteStream(&data, stream); err != nil { return } } }
go
// Package handlers provides HTTP request handlers. package handlers import ( "net/http" "github.com/zew/urlshort/storages" ) // EncodeHandler returns a HandlerFunc for encoding urls // encapsulating the storage in a closure. func EncodeHandler(st storages.IStore) http.Handler { handleFunc := func(w http.ResponseWriter, r *http.Request) { if url := r.FormValue("url"); url != "" { enc, err := st.Save(url) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Write([]byte(enc)) } } return http.HandlerFunc(handleFunc) } // DecodeHandler returns a HandlerFunc for retrieving urls by code // encapsulating the storage in a closure. func DecodeHandler(st storages.IStore) http.Handler { handleFunc := func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") code := r.URL.Path[len("/dec/"):] url, err := st.Load(code) if err != nil { w.WriteHeader(http.StatusNotFound) w.Write([]byte("URL Not Found. Error: " + err.Error() + "\n")) return } w.Write([]byte(url)) w.Write([]byte("<br>\n")) str, err := st.Dump(0, 100) if err != nil { w.Write([]byte(err.Error())) w.Write([]byte("<br>\n")) } w.Write([]byte(str)) } return http.HandlerFunc(handleFunc) } // RedirectHandler returns a HandlerFunc for redirecting to the encoded URL, // encapsulating the storage in a closure. func RedirectHandler(st storages.IStore) http.Handler { handleFunc := func(w http.ResponseWriter, r *http.Request) { code := r.URL.Path[len("/r/"):] url, err := st.Load(code) if err != nil { w.WriteHeader(http.StatusNotFound) w.Write([]byte("URL Not Found. Error: " + err.Error() + "\n")) return } http.Redirect(w, r, string(url), 301) } return http.HandlerFunc(handleFunc) } // DumpHandler dumps func DumpHandler(st storages.IStore) http.Handler { handleFunc := func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") str, err := st.Dump(0, 100) if err != nil { w.Write([]byte(err.Error())) w.Write([]byte("<br>\n")) } w.Write([]byte(str)) } return http.HandlerFunc(handleFunc) }
go
package com.ctrip.zeus.service; public class ArgsSplitException extends Exception { public ArgsSplitException(String msg) { super(msg); } }
java
{"date":20201230,"states":56,"positive":19638128,"negative":58381318,"pending":14200,"hospitalizedCurrently":125220,"hospitalizedCumulative":579515,"inIcuCurrently":23069,"inIcuCumulative":36855,"onVentilatorCurrently":7930,"onVentilatorCumulative":3653,"dateChecked":"2020-12-30T24:00:00Z","death":333505,"hospitalized":579515,"totalTestResults":252452699,"lastModified":"2020-12-30T24:00:00Z","recovered":null,"total":0,"posNeg":0,"deathIncrease":3900,"hospitalizedIncrease":5514,"negativeIncrease":215107,"positiveIncrease":229496,"totalTestResultsIncrease":1583713,"hash":"d55afa7354a34a5d7351cd334c201b1329c5d753"}
json
Our editors will review what you’ve submitted and determine whether to revise the article. Mount Washington, mountain in the Presidential Range, the highest (6,288 feet [1,917 metres]) peak of the White Mountains, New Hampshire, U.S. The peak is 23 miles (37 km) north-northwest of Conway. It is noted for its extreme weather conditions, one of the world’s highest wind velocities (231 miles [372 km] per hour) having been recorded there in 1934. The treeless summit, the state’s highest point, is accessible by road from Pinkham Notch, by a cog railway (1869) northeast of Crawford Notch, and by marked hiking trails. Summit buildings, anchored against high winds, include Tip Top House and Summit House, open to the public in summer, and Mount Washington Weather Observatory. The area is included in the White Mountain National Forest. Mount Washington is the watershed of the Androscoggin, Connecticut, and Saco rivers.
english
23 And they put forward two, Joseph called (A)Barsabbas, who was also called (B)Justus, and (C)Matthias. 7 And he left there and went to the house of a man named Titius (A)Justus, (B)a worshiper of God. His house was next door to the synagogue. The Holy Bible, English Standard Version. ESV® Text Edition: 2016. Copyright © 2001 by Crossway Bibles, a publishing ministry of Good News Publishers.
english
A day after Nationalist Congress Party president and Union Agriculture Minister Sharad Pawar met Shiv Sena leader Bal Thackeray — purportedly to ensure the safety of Australian cricketers on the IPL teams — the Congress said the issue of food inflation fell squarely within the realm of his Ministry. This is the first time the Congress has so clearly fixed the responsibility for the spiralling prices on Mr. Pawar. As recently as Friday — when Mr. Pawar came in for veiled attack within the Congress Working Committee (CWC) for not addressing the price rise issue — the Congress was careful to insist that no Minister was singled out for criticism. However, on Mr. Pawar’s meeting with Mr. Thackeray, the Congress maintained that the Minister went to ‘Matoshree’ (Mr. Thackeray’s residence) in his private capacity and not as a representative of the government. Refusing to subscribe to the analysis that this meeting had caused the Congress great embarrassment, Mr. Tewari said that as far as his party was concerned, the position was clearly spelt out by AICC general secretary Rahul Gandhi with his visit to Mumbai on Friday last.
english
{"title":"プールで楽しく裏表ラバーズ!18歳以上!","author":"<NAME>","description":"ご視聴ありがとうございました!","thumb":"//i.iwara.tv/sites/default/files/styles/thumbnail/public/videos/thumbnails/986328/thumbnail-986328_0012.jpg?itok=_f0Go7Vw","download":"https://ecchi.iwara.tv/api/video/7orjncvj0gfmd79lv","origin":"https://ecchi.iwara.tv/videos/7orjncvj0gfmd79lv"}
json
import ToDo from '../models/todo'; /** * The main HTML constructor service, all methods are static */ export default class Renderer { /** * Create a new list of todo items to be inserted into the dom * @param title The text to appear above the todo list * @param list The items to render in the todo list * @param removeCallback The function to call when the x button is clicked * @param changeCallback The function to call when the checkbox is clicked */ static todoList(title: string, list: ToDo[], removeCallback: (id: number) => void, changeCallback: (id: number, newState: boolean) => void) { let ret = document.createElement('div'); ret.setAttribute('class', `todo-list ${title.toLowerCase()}`); let header = document.createElement('h2'); header.setAttribute('class', 'list-title'); header.appendChild(document.createTextNode(title)); ret.appendChild(header); if (!list || list.length < 1) { ret.appendChild(Renderer.dummy(`Nothing here!`)); } else { list.forEach(todo => { ret.appendChild(Renderer.todo(todo, removeCallback, changeCallback)) }); } return ret; } /** * Generate a single todo item to be inserted into the dom * @param todo The todo item that will be rendered * @param removeCallback The function to be called when the X button is clicked * @param changeCallback The function to be called with the checkbox is clicked */ static todo(todo: ToDo, removeCallback: (id: number) => void, changeCallback: (id: number, newState: boolean) => void): HTMLDivElement { let ret = document.createElement('div'); ret.setAttribute('class', 'todo-item'); let chk = Renderer.todoCheckbox(todo.id, todo.complete, changeCallback); ret.appendChild(chk); let sp = Renderer.todoAction(todo.action); ret.appendChild(sp); let btn = Renderer.todoRemove(todo.id) btn.addEventListener('click', () => removeCallback(todo.id)); ret.appendChild(btn); return ret; } /** * Generate the checkbox for a todo item * @param id The id of the todo item (this will be passed to the callbacks) * @param complete The current state of the todo item (the inverse of this will be passed to the changeCallback) * @param changeCallback The function to call when the checkbox is clicked */ static todoCheckbox(id: number, complete: boolean, changeCallback: (id: number, newState: boolean) => void): HTMLDivElement { let chk = document.createElement('div'); chk.setAttribute('type', 'checkbox'); chk.setAttribute('class', 'todo-complete'); chk.setAttribute('id', `chk-${id}`) chk.addEventListener('click', () => changeCallback(id, !complete)); let symbol = complete ? '✓' : ''; chk.appendChild(document.createTextNode(symbol)); return chk; } /** * Generate the span element for a todo item * @param action The text that should appear for the todo item */ static todoAction(action: string): HTMLSpanElement { let sp = document.createElement('span'); sp.setAttribute('class', 'todo-action'); sp.appendChild(document.createTextNode(action)); return sp; } /** * Generate the delete button for a todo item * @param id the id of the todo item */ static todoRemove(id: number): HTMLButtonElement { let btn = document.createElement('button'); btn.setAttribute('type', 'button'); btn.setAttribute('class', 'remove-button'); btn.setAttribute('id', `btn-${id}`); btn.appendChild(document.createTextNode('✘')); return btn; } static dummy(text: string): HTMLDivElement { let ret = document.createElement('div'); ret.setAttribute('class', 'todo-item dummy'); ret.appendChild(Renderer.todoAction(text)); return ret; } /** * Display an error message to the user * @param text The message you want to display * @param isError If the message should be styled as an error */ static showMessage(text: string, isError: boolean = false) { let msg = document.createElement('div'); let cls = `message ${isError ? 'error' : ''}`.trim(); msg.setAttribute('class', cls); msg.appendChild(document.createTextNode(text)); document.body.appendChild(msg); setTimeout(() => document.body.removeChild(msg), 3000); } }
typescript
When politicians die, especially an untimely death in tragic circumstances, obituaries tend to go overboard. A sense of perspectives is lost when obituaries become eulogies. But you can’t falsify history. And in the final analysis, it is the forces of history that write the course of politics rather than individuals, and the fact is Japan has a gory past, a blood-soaked and brutal imperial past. Almost all of Japan’s neighbours paid a high price for its hegemonist ambitions and thirst for territorial conquests. Shinzo Abe’s grandfather who founded Japan’s ruling party was himself a war criminal. Japan perpetrated unspeakable crimes on conquered peoples even by the standards of colonialism, especially the Korean and Chinese peoples. Therefore, when Abe’s legacy gets evaluated dispassionately some day, as it surely will, what may well stand out as his single most outstanding contribution is that he summarily turned around ‘pacifist’ Japan and dragged it back unwillingly to its ‘militaristic’ past. There is no question about it. But how this will pan out in Asian politics and Japan’s political economy in a medium and long term leaves troubling question marks.The point is, Abe did not even ascertain his countrymen’s wishes to change the country’s constitution but was uneasy that the nation might not endorse his agenda. What moved the young assassin to commit such an abominable crime we do not know, but his abject surrender owning the crime suggests that he was a man of strong convictions and the murder was far from an impulsive act. What it reminds us is that Abe was a controversial figure within Japan. Abe’s reform programme widened the gap between the rich and the poor and fuelled social discontent while Abe’s abandonment of Japan’s ‘pacifism’ did not enjoy a national consensus. Abe’s populism obfuscated his real agenda, and his use of baser instincts such as racial and ethnic prejudices and his manipulation of the media and suppression of free press damaged Japan’s democratic foundations. Therefore, a big question mark needs to be put on his ‘vision,’ as his admirers tend to put it. Frankly, Abe has become a polariser in the world opinion — simply put, one-dimensional Sinophobes warm up to him like nobody’s business and in the process overlook his flawed legacy in an outpouring of emotions. The Quad’s troika itself used a catching expression in its curious obituary for Abe. It praised Abe as a “transformative leader for Japan” and discreetly left it at that. The Quad’s troika is right in estimating that Abe “played a formative role in the founding of the Quad partnership and worked tirelessly to advance a shared vision for a free and open Indo-Pacific.” He was indeed an ardent votary of the containment strategy against China. But Abe was also a master of doublespeak and once made significant contributions to improving Japan’s ties with China and even publicly expressed willingness to cooperate with the Belt and Road Initiative! Quad was almost entirely built on the strength of the relationship Abe worked out with Prime Minister Modi, with whom he shared a deep distrust of China. However, Japan’s Indo-Pacific policy has since morphed into robust support for accelerating the pace of NATO’s entry into Asia. That said, the fact remains that throughout its history, Japan always tenaciously sought to maintain its autonomy in the international system. How this contradiction gets resolved remains to be seen. Clearly, Japan finds it difficult to get accustomed to its status behind China in Asia’s power dynamic and needs NATO support to level with China. Abe, without doubt, was a close friend of India. His regards for India harks back to the Manmohan Singh government. Yet, how far India subscribes to this new dimension to Japan’s Indo-Pacific strategy in the direction of pioneering an “Asian NATO” is unclear. Traditionally, India never had a bloc mentality. Besides, Quad or Indo-Pacific strategy is not to be equated with India’s Act East policy, either. Abe’s place as the longest serving Japanese prime minister (9 years) is largely due to his charisma, the force of his personality, and his formidable political talent. But his legacy for Japan’s future in terms of his ambitious domestic reform agenda — “Abenomics” or the surge in state spending and super-easy monetary policy aimed at kickstarting Japan’s stagnant economy — is rather patchy. Japan’s debt increased dramatically and Abe’s reforms indeed weakened the yen. The reforms’ promise to reshape an economy hobbled by low productivity, a rapidly ageing population and a rigid labour market, proved elusive. On top of it, COVID-19 wiped out the short-term benefits brought by Abenomics, such as an inbound tourism boom, reflated growth and rising job availability. Looking ahead, Abe’s death could stimulate the extreme Japanese right wing to promote populist, xenophobic and even extreme political goals. Japan’s two giant neighbours China and Russia are increasingly coordinating their security presence in the Far East. These two big powers will counter Japan’s partnership with the NATO, no matter what it takes, and that may become the salience of the geopolitics of Asia-Pacific in the period ahead. Moscow has openly accused Japan of revanchist tendencies vis-a-vis Kuril Islands, which pose threat to regional security and stability. If the US and NATO’s prestige suffers a lethal blow in Ukraine, which seems likely, Japan’s political and policy goals would lose traction. But Prime Minister Kishida is firing all cylinders to inject swagger into Japan’s ties with major European powers — especially, with Germany, with which it once had an alliance known as the Anti-Commintern Pact (1936) built on the common concerns of Nazi Germany and Imperial Japan over the steady rise of Soviet power under Josef Stalin. Chancellor Olaf Scholz and Kishida recently visited each other’s capitals in quick succession to renew the historical bonding in the current circumstances. To be sure, Abe’s departure comes at a time when Japan may find itself at the crossroads of Asian politics and world order.
english
<gh_stars>0 { "name": "eslint-config-jude", "version": "1.1.1", "main": "index.js", "repository": "https://github.com/judehunter/eslint-config-jude", "author": "judehunter <<EMAIL>>", "license": "The UNLICENSE", "files": [ "index.js", "LICENSE" ], "peerDependencies": { "@typescript-eslint/eslint-plugin": "4.2.0", "eslint": "7.9.0" }, "dependencies": { "@typescript-eslint/parser": "^4.2.0" } }
json
<filename>src/unittest/resources/service_templates_test/pylib/cookiecutter.json { "project_name": "Name of the project", "description": "A short description of the project", "owner": "owner", "role": "role", "application": "application", "service_type": "service-type", "repository_url": "Full https url for repo", "project_slug": "{{ cookiecutter.project_name.lower().replace(' ', '-') }}", "release_date": "{% now 'local' %}", "version": "0.1.0", "_extensions": ["jinja2_time.TimeExtension"] }
json
<filename>src/app/admin/quiz/quiz-routing.module.ts import { NgModule } from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; import {HomeQuizComponent} from './home-quiz/home-quiz.component'; import {CreateQuizComponent} from './create-quiz/create-quiz.component'; import {ListQuestionComponent} from '../questions/list-question/list-question.component'; import {DetailQuizComponent} from './detail-quiz/detail-quiz.component'; import {ListQuizComponent} from './list-quiz/list-quiz.component'; const routes: Routes = [ { path: '', component: HomeQuizComponent, children: [ { path: 'list', component: ListQuizComponent }, { path: 'create', component: CreateQuizComponent }, { path: ':id', component: DetailQuizComponent }, { path: '**', redirectTo: 'list' } ] } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class QuizRoutingModule { }
typescript
{"Name":"C2_50_L_9","Objects":[{"Length":100,"Height":100,"Stock":null,"Cost":10000}],"Items":[{"Length":74,"Height":51,"Demand":1,"DemandMax":null,"Value":3774},{"Length":30,"Height":55,"Demand":4,"DemandMax":null,"Value":1650},{"Length":71,"Height":33,"Demand":1,"DemandMax":null,"Value":2343},{"Length":52,"Height":44,"Demand":4,"DemandMax":null,"Value":2288},{"Length":41,"Height":67,"Demand":4,"DemandMax":null,"Value":2747},{"Length":32,"Height":26,"Demand":3,"DemandMax":null,"Value":832},{"Length":31,"Height":41,"Demand":4,"DemandMax":null,"Value":1271},{"Length":68,"Height":36,"Demand":2,"DemandMax":null,"Value":2448},{"Length":66,"Height":61,"Demand":1,"DemandMax":null,"Value":4026},{"Length":31,"Height":64,"Demand":2,"DemandMax":null,"Value":1984},{"Length":62,"Height":67,"Demand":4,"DemandMax":null,"Value":4154},{"Length":65,"Height":67,"Demand":4,"DemandMax":null,"Value":4355},{"Length":73,"Height":50,"Demand":2,"DemandMax":null,"Value":3650},{"Length":45,"Height":27,"Demand":3,"DemandMax":null,"Value":1215},{"Length":51,"Height":55,"Demand":1,"DemandMax":null,"Value":2805},{"Length":58,"Height":27,"Demand":1,"DemandMax":null,"Value":1566},{"Length":68,"Height":27,"Demand":2,"DemandMax":null,"Value":1836},{"Length":33,"Height":73,"Demand":1,"DemandMax":null,"Value":2409},{"Length":28,"Height":57,"Demand":3,"DemandMax":null,"Value":1596},{"Length":68,"Height":42,"Demand":3,"DemandMax":null,"Value":2856},{"Length":64,"Height":29,"Demand":2,"DemandMax":null,"Value":1856},{"Length":70,"Height":64,"Demand":3,"DemandMax":null,"Value":4480},{"Length":58,"Height":48,"Demand":4,"DemandMax":null,"Value":2784},{"Length":36,"Height":59,"Demand":2,"DemandMax":null,"Value":2124},{"Length":67,"Height":43,"Demand":1,"DemandMax":null,"Value":2881},{"Length":55,"Height":62,"Demand":1,"DemandMax":null,"Value":3410},{"Length":49,"Height":46,"Demand":4,"DemandMax":null,"Value":2254},{"Length":44,"Height":74,"Demand":2,"DemandMax":null,"Value":3256},{"Length":38,"Height":26,"Demand":1,"DemandMax":null,"Value":988},{"Length":25,"Height":36,"Demand":4,"DemandMax":null,"Value":900},{"Length":35,"Height":33,"Demand":4,"DemandMax":null,"Value":1155},{"Length":61,"Height":59,"Demand":4,"DemandMax":null,"Value":3599},{"Length":28,"Height":51,"Demand":2,"DemandMax":null,"Value":1428},{"Length":70,"Height":43,"Demand":2,"DemandMax":null,"Value":3010},{"Length":51,"Height":42,"Demand":3,"DemandMax":null,"Value":2142},{"Length":44,"Height":28,"Demand":2,"DemandMax":null,"Value":1232},{"Length":73,"Height":40,"Demand":2,"DemandMax":null,"Value":2920},{"Length":27,"Height":31,"Demand":1,"DemandMax":null,"Value":837},{"Length":68,"Height":59,"Demand":4,"DemandMax":null,"Value":4012},{"Length":29,"Height":63,"Demand":3,"DemandMax":null,"Value":1827},{"Length":67,"Height":52,"Demand":4,"DemandMax":null,"Value":3484},{"Length":38,"Height":36,"Demand":1,"DemandMax":null,"Value":1368},{"Length":46,"Height":42,"Demand":2,"DemandMax":null,"Value":1932},{"Length":54,"Height":39,"Demand":2,"DemandMax":null,"Value":2106},{"Length":29,"Height":25,"Demand":4,"DemandMax":null,"Value":725},{"Length":35,"Height":72,"Demand":3,"DemandMax":null,"Value":2520},{"Length":42,"Height":48,"Demand":2,"DemandMax":null,"Value":2016},{"Length":48,"Height":66,"Demand":1,"DemandMax":null,"Value":3168},{"Length":54,"Height":65,"Demand":2,"DemandMax":null,"Value":3510},{"Length":74,"Height":50,"Demand":1,"DemandMax":null,"Value":3700}]}
json
import { Eq } from 'fp-ts/lib/Eq' import { flow } from 'fp-ts/lib/function' import * as S from 'fp-ts/Set' export const filterUnique = <T>(eq: Eq<T>): ((array: T[]) => T[]) => flow(S.fromArray(eq), (set) => [...set]) export const uniqueBy = <T>(compareFn: (a: T, b: T) => boolean) => (element: T, index: number, self: T[]) => self.findIndex((item) => compareFn(element, item)) === index export const atIndices = <T>(array: T[], indexes: number[]) => indexes.map((index) => array[index]) export const partition = <T>(predicate: (item: T) => boolean) => (array: T[]): [T[], T[]] => array.reduce<[T[], T[]]>( ([passing, failing], item) => predicate(item) ? [[...passing, item], failing] : [passing, [...failing, item]], [[], []] )
typescript
Tiruchirappalli: A young man was arrested by the police in Trichy rural on Monday on various charges. The charges included kidnapping, marrying and sexually assaulting a minor girl, recording nude photos of her and threatening to release the photos. The complaint has been filed by a 16-year-old girl and her mother at the all-woman police station in Thiruverumbur. The accused has been identified as Gokul, a resident of Virinjipuram in Vellore district. He has been booked under relevant sections of the Indian Penal Code, the Prohibition of Child Marriage Act, the Protection of Children from Sexual Offences (POCSO) Act and the Information Technology (IT) Act, reported The Times Of India. Gokul then planned to meet her, he told her that his parents have fixed his marriage with another woman and convinced her to meet him. He told her to visit a room in a dormitory near the Trichy railway junction on January 5. The girl believed his words and went to meet him. Upon meeting her, he married the girl and committed penetrative sexual assault on her. He also recorded a video of them on his phone that day, the girl told the police in her complaint. After the incident both went to their respective homes. Gokul continued talking to the girl over the phone via chats and video calls. He even made her show him her private parts on video call. Upon learning about it, the girl’s mother reprimanded him over the phone. He then started verbally abusing her and threatened them that will release the girl’s photos online if they didn’t give him Rs. 10,000. The girl and her mother then approached the police.
english
# ApplyBQSR v4.1.8.1 ## Version of tools in [docker image ](https://hub.docker.com/r/broadinstitute/gatk) | Tool | Version | Location | | :--- | :--- | :--- | | GATK | 4.1.8.1 | [https://github.com/broadinstitute/gatk/releases/tag/4.1.8.1](https://github.com/broadinstitute/gatk/releases/tag/4.1.8.1) | [![](https://img.shields.io/badge/version-4.1.8.1-blue)](https://github.com/broadinstitute/gatk/releases/tag/4.1.8.1) ## CWL * CWL specification 1.0 * Use example\_inputs.yml to see the inputs to the cwl * Example Command using [toil](https://toil.readthedocs.io): ```bash > toil-cwl-runner gatk_downsamplesam_4.1.8.1.cwl example_inputs.yml ``` **If at MSK, using the JUNO cluster you can use the following command** ```bash #Using CWLTOOL > cwltool --singularity --non-strict gatk_downsamplesam_4.1.8.1.cwl inputs.yaml #Using toil-cwl-runner > mkdir run_directory > toil-cwl-runner --singularity --logFile path/to/run_directory/cwltoil.log --jobStore path/to/jobStore --batchSystem lsf --workDir /path/to/run_directory --outdir /path/to/run_directory --writeLogs /path/to/run_directory --logLevel DEBUG --stats --retryCount 2 --disableCaching --maxLogFileSize 20000000000 gatk_downsamplesam_4.1.8.1.cwl inputs.yaml > file.stdout 2> file.stderr & ``` ## Usage \`\`\`bash > toil-cwl-runner gatk_downsamplesam_4.1.8.1.cwl --help usage: gatk_downsamplesam_4.1.8.1.cwl [-h] --input INPUT --reference REFERENCE [--output_file_name OUTPUT_FILE_NAME] [--output_file_name_metrics OUTPUT_FILE_NAME_METRICS] [--probability PROBABILITY] [--random_seed RANDOM_SEED] [--strategy STRATEGY] [--arguments_file ARGUMENTS_FILE] [--cloud-index-prefetch-buffer CLOUD_INDEX_PREFETCH_BUFFER] [--cloud_prefetch_buffer CLOUD_PREFETCH_BUFFER] [--create_output_bam_index] [--create_output_bam_md5] [--disable_bam_index_caching] [--disable_read_filter DISABLE_READ_FILTER] [--disable_sequence_dictionary_validation] [--exclude_intervals EXCLUDE_INTERVALS] [--gatk_config_file GATK_CONFIG_FILE] [--gcs_max_retries GCS_MAX_RETRIES] [--gcs_project_for_requester_pays GCS_PROJECT_FOR_REQUESTER_PAYS] [--QUIET] [--read_filter READ_FILTER] [--read_index READ_INDEX] [--seconds_between_progress_updates SECONDS_BETWEEN_PROGRESS_UPDATES] [--lenient] [--number_of_threads NUMBER_OF_THREADS] [--memory_per_job MEMORY_PER_JOB] [--memory_overhead MEMORY_OVERHEAD] [--temporary_directory TEMPORARY_DIRECTORY] [job_order] positional arguments: job_order Job input json file optional arguments: -h, --help show this help message and exit --input INPUT BAM/SAM file containing reads --reference REFERENCE Reference sequence file --output_file_name OUTPUT_FILE_NAME Output file name. Not Required --output_file_name_metrics OUTPUT_FILE_NAME_METRICS Output file name for metrics file. Not Required --probability PROBABILITY The probability of keeping any individual read, between 0 and 1. --random_seed RANDOM_SEED Random seed used for deterministic results. Setting to null will cause multiple invocations to produce different results. --strategy STRATEGY The --STRATEGY argument is an enumerated type (Strategy), which can have one of the following values: HighAccuracy ConstantMemory Chained default Strategy ConstantMemory --arguments_file ARGUMENTS_FILE --cloud-index-prefetch-buffer CLOUD_INDEX_PREFETCH_BUFFER --cloud_prefetch_buffer CLOUD_PREFETCH_BUFFER --create_output_bam_index --create_output_bam_md5 --disable_bam_index_caching --disable_read_filter DISABLE_READ_FILTER Read filters to be disabled before analysis --disable_sequence_dictionary_validation --exclude_intervals EXCLUDE_INTERVALS --gatk_config_file GATK_CONFIG_FILE --gcs_max_retries GCS_MAX_RETRIES --gcs_project_for_requester_pays GCS_PROJECT_FOR_REQUESTER_PAYS --QUIET --read_filter READ_FILTER --read_index READ_INDEX --seconds_between_progress_updates SECONDS_BETWEEN_PROGRESS_UPDATES --lenient --number_of_threads NUMBER_OF_THREADS --memory_per_job MEMORY_PER_JOB --memory_overhead MEMORY_OVERHEAD --temporary_directory TEMPORARY_DIRECTORY Default value: null.
markdown
Former New York Yankees prospect Raimfer Salinas has been suspended for 80 games. Under baseball's minor league drug program, the former prospect was hit with a lengthy ban following a positive test. Salinas was using the performing-enhancing substance known as Nandrolone, an anabolic steroid. The young outfield prospect was released by the Yankees' Class A affiliate, the Tampa Tarpons, last week. He hasn't played all that well this season, going just 0-for-4 with an RBI groundout in his only game this season in April. He hit . 225 with five homers and 25 RBIs in 64 appearances for the same team last year. Salinas signed with the Yankees in December 2017 and earned a $1. 85 million bonus. He spent time in 2018 with both the Dominican Summer League Yankees and the Gulf Coast Yankees. He spent 2019 with the GCL team and 2021 with the Florida Complex League Yankees before his recent stints. Salinas is the sixth player to have been disciplined under the minor league program this year. Will Raimfer Salinas make it back to the league? Following his positive test and subsequent ban, Raimfer Salinas was out of a job. The Tampa Tarpons released him and he's not currently with a team. That doesn't bode well for his future. He wasn't a highly-rated prospect, so a team may not even bother to pick him up since he wasn't playing well even on steroids.
english
- Four mysterious Google phones just passed through the FCC, likely the Google Pixel 6 series. - Each model should have a mmWave version and a version with just Sub6 5G. - FCC certifications such as these usually signal an imminent launch. Google has told us a lot about its upcoming pair of flagship phones. However, one thing it hasn’t divulged is when we’ll actually see them launch. Thankfully, we now know we are quite close to that date, whenever it might be. Traditionally, the FCC is one of the last steps in the release of a smartphone. Although these certification listings don’t tell us much, they prove that we should see Google launch the devices very soon. The two phones have the following model numbers: - GLU0G and G8VOU (likely Pixel 6 Pro) - GB7N6 and GB7N6 (likely Pixel 6) It’s not easy to tell which model number matches up to which phone. The reason each variant has two models, though, is due to one having Sub6 5G support only and the other supporting mmWave as well. We’ll need to wait and see if these theories match up, but you can go ahead and start getting pumped for the Pixel 6 release, as they are almost certainly right around the corner.
english
Hyderabad: A madrasa teacher was booked on Friday for allegedly misbehaving with a seven-year-old girl student, police said. The teacher, Irfan Ahmed Siddiqi, 37, taught Arabic at the religious school. Siddiqi, who also used to give tuitions on the school premises, allegedly misbehaved with the minor girl two days back, said Maddanapet Police Station Additional Inspector K Chandrasekhar. Action against Siddiqi was taken after the parents of the alleged victim, who used to attend his tuition class, filed a police complaint. Siddiqi has not been arrested. Following the complaint, a case was registered against the teacher under relevant sections of IPC as also the Protection of Children from Sexual Offences Act (POCSO Act), police said, adding that inquiries are on in the case.
english
When Apple launched the 12-inch MacBook back in 2015, there were rumors of MacBook Air biting the dust and disappearing from the MacBook lineup. Apple did bring an uninspiring upgrade in 2017, but there were a lot of people hoping and praying Apple would provide a real upgrade to the MacBook Air. And Apple has done just that. The new MacBook Air is here and comes with most of the 2018 goodness. Retina display? Check. USB Type-C? Check. Touch ID? Check. Slimmed out bezels? Check. The design is mash-up of the new MacBook Pros and the good-old MacBook Air with a tapered base. It’s a full retina display which is a HUGE markup to the old MacBook Air, but not True tone like the new MBP. Glossy LCD with sRGB color spectrum can be a disappointment for some. It’s still 13.3-inch screen, but cutting down of bezels and some ports (more on that later) has led to a smaller footprint, and it is now 17% lesser volume than before and a quarter pound lighter. In a lot of ways, it reminds you of the original 12-inch MacBook, but the unmistakable taper confirms it’s a MacBook Air. Apple has managed to build the MacBook Air with 100 percent recycled aluminum which is a commendable thing. The device feels as sturdy as any Apple laptop. Apple has removed all the older ports and has replaced them with Thunderbolt 3 ports. It’s disappointing that there are just two of them, but that’s what we have come to expect from Apple these days (Yay! #DongleLife). The other big highlight of the new MacBook Air is the presence of Touch ID. Alongside that, there is the new T2 security chip which handles encryption, does encoding etc. The new “latest-gen” Butterfly keyboard is actually the same one we saw on the newer MacBook Pros. With my limited testing, typing on that keyboard felt good. There is also a Force touch trackpad that is 20 percent bigger than previous Air. It wasn’t an ideal environment to test the new stereo speakers, but Apple claims they are 25% louder with 2x more bass and wide stereo sound. In a lot of ways, the new MacBook Air is a lot like the 13-inch MacBook Pro minus the TouchBar and on a tapered slab. It comes in three colors – Gold, Slate gray and Silver. I particularly liked the Gold one which is more like the gold on the iPhones than 12-inch MacBook gold. At a starting price of $1199 (Rs 1,14,900 in India), the new MacBook Air offers 8GB of RAM, 128GB SSD and the latest 8th-gen Intel i5 processor. It’s sad that Apple is still keeping 128 GB as the storage in the base variant, but it can be specced-up to 16GB of RAM and 1.5TB of SSD. The MacBook Air has got the much delayed and much-deserved upgrade but it’s no more the ‘affordable MacBook’ like it once was. At a starting price of over a lakh in India, it competes with the likes of Dell XPS 13 and Microsoft Surface Book 2, and not mention, Apple’s very own 12-inch MacBook. There’s a lot to test and compare, so stay tuned for our detailed review coming up soon.
english
There are 1 used Mahindra cars are available for sale in osmanabad. The cheapest model in Mahindra is Mahindra Scorpio with price 400000 in osmanabad. You can see other similar brands such as second hand Mahindra Scorpio (Rs. 4 Lakh - 4 Lakh) in osmanabad. Check used car valuation online, also we can help you to sell car at best prices at CarDekho. You can also explore 1 second hand cars with prices, images and reviews and select your desired car models from the list. Q 1.How many used Mahindra cars are available in osmanabad? 1 second hand Mahindra cars are available for sale in osmanabad at starting price of 4 Lakh. Q 2.Which is the inexpensive model of used Mahindra car in osmanabad? The Mahindra Scorpio is the cheapest model available for sale in osmanabad with price of Rs 4 Lakh. Q 3.What are the most popular 2nd hand Mahindra cars available in osmanabad?
english
The Bombay High Court has rejected the plea of actor Shilpa Shetty's husband Raj Kundra, an accused in the porn racket case, where he sought immediate release from judicial custody. By Mustafa Shaikh: Businessman Raj Kundra's plea seeking an immediate release from police custody in the porn racket case was turned down by the Bombay High Court on Saturday. In his plea, Raj Kundra, who is the husband of actor Shilpa Shetty, had alleged that the Mumbai Police did not issue him summons under Section 41A of CrPC before his arrest. He also challenged the extension of his police remand for 14 days by a Metropolitan Magistrate on July 28. However, the police had stated that after the search at Raj Kundra's Viaan Industries office on July 19, a summon under Section 41A of CrPC was issued on the spot. Raj Kundra refused to accept it and sign, following which the cops arrested him, the police said. On July 28, a Sessions Court in Mumbai also rejected Raj Kundra's bail application while stating that the investigation in the case was still underway. The court had sent Raj Kundra to judicial custody for 14 days. The police had opposed Raj Kundra's bail, stating that tampering of evidence could take place if he is granted bail. The police also said that since Raj Kundra is a British national, he could flee the country to avoid prosecution.
english
import { Context, DduItem, DduOptions, FilterOptions, SourceOptions, } from "../types.ts"; import { Denops } from "../deps.ts"; export type OnInitArguments<Params extends Record<string, unknown>> = { denops: Denops; filterOptions: FilterOptions; filterParams: Params; }; export type FilterArguments<Params extends Record<string, unknown>> = { denops: Denops; context: Context; options: DduOptions; sourceOptions: SourceOptions; filterOptions: FilterOptions; filterParams: Params; input: string; items: DduItem[]; }; export abstract class BaseFilter<Params extends Record<string, unknown>> { name = ""; isInitialized = false; apiVersion = 1; async onInit(_args: OnInitArguments<Params>): Promise<void> {} abstract filter({}: FilterArguments<Params>): Promise<DduItem[]>; abstract params(): Params; } export function defaultFilterOptions(): FilterOptions { return { placeholder: undefined, }; } export function defaultFilterParams(): Record<string, unknown> { return {}; }
typescript
// Copyright (c) Aptos // SPDX-License-Identifier: Apache-2.0 use crate::tests::{assert_json, find_value, new_test_context, pretty, TestContext}; use aptos_api_types::{HashValue, HexEncodedBytes}; use aptos_crypto::{ hash::CryptoHash, multi_ed25519::{MultiEd25519PrivateKey, MultiEd25519PublicKey}, SigningKey, Uniform, }; use aptos_sdk::{transaction_builder::Currency, types::LocalAccount}; use aptos_types::{ access_path::{AccessPath, Path}, account_address::AccountAddress, account_config::{from_currency_code_string, xus_tag, XUS_NAME}, transaction::{ authenticator::{AuthenticationKey, TransactionAuthenticator}, ChangeSet, Script, ScriptFunction, SignedTransaction, Transaction, }, write_set::{WriteOp, WriteSetMut}, }; use move_core_types::{ identifier::Identifier, language_storage::{ModuleId, StructTag, TypeTag, CORE_CODE_ADDRESS}, }; use rand::{distributions::Alphanumeric, thread_rng, Rng}; use serde_json::json; #[tokio::test] async fn test_deserialize_genesis_transaction() { let context = new_test_context(); let resp = context.get("/transactions/0").await; serde_json::from_value::<aptos_api_types::Transaction>(resp).unwrap(); } #[tokio::test] async fn test_get_transactions_output_genesis_transaction() { let context = new_test_context(); let ledger_info = context.get_latest_ledger_info(); let txns = context .context .get_transactions(0, 1, ledger_info.version()) .unwrap(); let resp = context.get("/transactions").await; assert_eq!(1, resp.as_array().unwrap().len()); let txn = &resp[0]; assert_eq!(txn["type"], "genesis_transaction"); assert_eq!(txn["version"], "0"); let info = txns[0].info.clone(); assert_eq!(txn["hash"], info.transaction_hash().to_hex_literal()); assert_eq!( txn["state_root_hash"], info.state_change_hash().to_hex_literal() ); assert_eq!( txn["event_root_hash"], info.event_root_hash().to_hex_literal() ); let chain_id = find_value(&txn["payload"]["write_set"]["changes"], |val| { val["type"] == "write_module" && val["data"]["abi"]["name"] == "ChainId" }); let bytecode = chain_id["data"]["bytecode"].clone(); assert!(bytecode.as_str().unwrap().starts_with("0x")); assert_json( chain_id, json!({ "type": "write_module", "address": "0x1", "data": { "bytecode": bytecode.as_str().unwrap(), "abi": { "address": "0x1", "name": "ChainId", "friends": [], "exposed_functions": [ { "name": "get", "visibility": "public", "generic_type_params": [], "params": [], "return": ["u8"] }, { "name": "initialize", "visibility": "public", "generic_type_params": [], "params": [ "&signer", "u8" ], "return": [] } ], "structs": [ { "name": "ChainId", "is_native": false, "abilities": [ "key" ], "generic_type_params": [], "fields": [ { "name": "id", "type": "u8" } ] } ] } } }), ); let chain_id = find_value(&txn["payload"]["write_set"]["changes"], |val| { val["type"] == "write_resource" && val["address"] == "0xdd" && val["data"]["type"] == "0x1::Roles::RoleId" }); assert_json( chain_id, json!({ "type": "write_resource", "address": "0xdd", "data": { "type": "0x1::Roles::RoleId", "data": { "role_id": "2" } } }), ); let first_event = txn["events"][0].clone(); // transaction events are same with events from payload assert_json( first_event.clone(), txn["payload"]["write_set"]["events"][0].clone(), ); assert_json( first_event, json!({ "key": "0x00000000000000000000000000000000000000000a550c18", "sequence_number": "0", "type": "0x1::DiemAccount::CreateAccountEvent", "data": { "created": "0xa550c18", "role_id": "0" } }), ); } #[tokio::test] async fn test_get_transactions_returns_last_page_when_start_version_is_not_specified() { let mut context = new_test_context(); let mut tc = context.tc_account(); for _i in 0..20 { let account = context.gen_account(); let txn = context.create_parent_vasp_by_account(&mut tc, &account); context.commit_block(&vec![txn.clone()]).await; } let resp = context.get("/transactions").await; let txns = resp.as_array().unwrap(); assert_eq!(25, txns.len()); assert_eq!("15", txns[0]["version"]); assert_eq!("39", txns[24]["version"]); } #[tokio::test] async fn test_get_transactions_with_start_version_is_too_large() { let context = new_test_context(); let ledger_version = context.get_latest_ledger_info().version(); let resp = context .expect_status_code(404) .get("/transactions?start=1000000&limit=10") .await; assert_json( resp, json!({ "code": 404, "message": "transaction not found by version(1000000)", "aptos_ledger_version": ledger_version.to_string() }), ); } #[tokio::test] async fn test_get_transactions_with_invalid_start_version_param() { let context = new_test_context(); let resp = context .expect_status_code(400) .get("/transactions?start=hello") .await; assert_json( resp, json!({ "code": 400, "message": "invalid parameter start: hello" }), ); } #[tokio::test] async fn test_get_transactions_with_invalid_limit_param() { let context = new_test_context(); let resp = context .expect_status_code(400) .get("/transactions?limit=hello") .await; assert_json( resp, json!({ "code": 400, "message": "invalid parameter limit: hello" }), ); } #[tokio::test] async fn test_get_transactions_with_zero_limit() { let context = new_test_context(); let resp = context .expect_status_code(400) .get("/transactions?limit=0") .await; assert_json( resp, json!({ "code": 400, "message": "invalid parameter limit: 0" }), ); } #[tokio::test] async fn test_get_transactions_param_limit_exceeds_limit() { let context = new_test_context(); let resp = context .expect_status_code(400) .get("/transactions?limit=2000") .await; assert_json( resp, json!({ "code": 400, "message": "invalid parameter limit: 2000, exceed limit 1000" }), ); } #[tokio::test] async fn test_get_transactions_output_user_transaction_with_script_function_payload() { let mut context = new_test_context(); let account = context.gen_account(); let txn = context.create_parent_vasp(&account); context.commit_block(&vec![txn.clone()]).await; let txns = context.get("/transactions?start=1").await; assert_eq!(2, txns.as_array().unwrap().len()); let expected_txns = context.get_transactions(1, 2); assert_eq!(2, expected_txns.len()); let metadata = expected_txns[0].info.clone(); let metadata_txn = match &expected_txns[0].transaction { Transaction::BlockMetadata(txn) => txn.clone(), _ => panic!("unexpected transaction: {:?}", expected_txns[0].transaction), }; assert_json( txns[0].clone(), json!( { "type": "block_metadata_transaction", "version": "1", "hash": metadata.transaction_hash().to_hex_literal(), "state_root_hash": metadata.state_change_hash().to_hex_literal(), "event_root_hash": metadata.event_root_hash().to_hex_literal(), "gas_used": metadata.gas_used().to_string(), "success": true, "vm_status": "Executed successfully", "id": metadata_txn.id().to_hex_literal(), "round": "1", "previous_block_votes": [], "proposer": context.validator_owner.to_hex_literal(), "timestamp": metadata_txn.timestamp_usec().to_string(), "accumulator_root_hash": HashValue::from(context.context.get_accumulator_root_hash(1).unwrap()).to_string(), }), ); let user_txn_info = expected_txns[1].info.clone(); let (public_key, sig) = match txn.authenticator() { TransactionAuthenticator::Ed25519 { public_key, signature, } => (public_key, signature), _ => panic!( "expecting TransactionAuthenticator::Ed25519, but got: {:?}", txn.authenticator() ), }; assert_json( txns[1].clone(), json!({ "type": "user_transaction", "version": "2", "hash": user_txn_info.transaction_hash().to_hex_literal(), "state_root_hash": user_txn_info.state_change_hash().to_hex_literal(), "event_root_hash": user_txn_info.event_root_hash().to_hex_literal(), "gas_used": user_txn_info.gas_used().to_string(), "success": true, "vm_status": "Executed successfully", "sender": "0xb1e55ed", "sequence_number": "0", "max_gas_amount": "1000000", "gas_unit_price": "0", "gas_currency_code": "XUS", "expiration_timestamp_secs": txn.expiration_timestamp_secs().to_string(), "events": [ { "key": "0x00000000000000000000000000000000000000000a550c18", "sequence_number": "5", "type": "0x1::DiemAccount::CreateAccountEvent", "data": { "created": account.address().to_hex_literal(), "role_id": "5" } } ], "payload": { "type": "script_function_payload", "function": "0x1::AccountCreationScripts::create_parent_vasp_account", "type_arguments": [ "0x1::XUS::XUS" ], "arguments": [ "0", account.address().to_hex_literal(), format!("0x{}", hex::encode(account.authentication_key().prefix())), format!("0x{}", hex::encode("vasp".as_bytes())), true ] }, "signature": { "type": "ed25519_signature", "public_key": format!("0x{}", hex::encode(public_key.unvalidated().to_bytes())), "signature": format!("0x{}", hex::encode(sig.to_bytes())), }, "timestamp": metadata_txn.timestamp_usec().to_string(), "accumulator_root_hash": HashValue::from(context.context.get_accumulator_root_hash(2).unwrap()).to_string(), }), ) } #[tokio::test] async fn test_get_transactions_output_user_transaction_with_script_payload() { let context = new_test_context(); let new_key = "717d1d400311ff8797c2441ea9c2d2da1120ce38f66afb079c2bad0919d93a09" .parse() .unwrap(); let mut tc_account = context.tc_account(); let txn = tc_account.sign_with_transaction_builder( context .transaction_factory() .rotate_authentication_key_by_script(new_key), ); context.commit_block(&vec![txn.clone()]).await; let txns = context.get("/transactions?start=2").await; assert_eq!(1, txns.as_array().unwrap().len()); let expected_txns = context.get_transactions(2, 1); assert_eq!(1, expected_txns.len()); assert_json( txns[0]["payload"].clone(), json!({ "type": "script_payload", "code": { "bytecode": "0xa11ceb0b010000000601000202020403060f05151207277c08a3011000000001010000020001000003010200000403020001060c01080000020608000a0202060c0a020b4469656d4163636f756e74154b6579526f746174696f6e4361706162696c6974791f657874726163745f6b65795f726f746174696f6e5f6361706162696c6974791f726573746f72655f6b65795f726f746174696f6e5f6361706162696c69747919726f746174655f61757468656e7469636174696f6e5f6b657900000000000000000000000000000001000401090b0011000c020e020b0111020b02110102", "abi": { "name": "main", "visibility": "script", "generic_type_params": [], "params": [ "&signer", "vector<u8>" ], "return": [] } }, "type_arguments": [], "arguments": [ "0x717d1d400311ff8797c2441ea9c2d2da1120ce38f66afb079c2bad0919d93a09" ] }), ) } #[tokio::test] async fn test_get_transactions_output_user_transaction_with_module_payload() { let context = new_test_context(); let code = "a11ceb0b0300000006010002030205050703070a0c0816100c260900000001000100000102084d794d6f64756c650269640000000000000000000000000b1e55ed00010000000231010200"; let mut tc_account = context.tc_account(); let txn = tc_account.sign_with_transaction_builder( context .transaction_factory() .module(hex::decode(code).unwrap()), ); context.commit_block(&vec![txn.clone()]).await; let txns = context.get("/transactions?start=2").await; assert_eq!(1, txns.as_array().unwrap().len()); let expected_txns = context.get_transactions(2, 1); assert_eq!(1, expected_txns.len()); assert_json( txns[0]["payload"].clone(), json!({ "type": "module_bundle_payload", "modules": [ { "bytecode": format!("0x{}", code), "abi": { "address": "0xb1e55ed", "name": "MyModule", "friends": [], "exposed_functions": [ { "name": "id", "visibility": "public", "generic_type_params": [], "params": [], "return": ["u8"] } ], "structs": [] } }, ] }), ) } #[tokio::test] async fn test_get_transactions_output_user_transaction_with_write_set_payload() { let context = new_test_context(); let mut root_account = context.root_account(); let code_address = AccountAddress::from_hex_literal("0x1").unwrap(); let txn = root_account.sign_with_transaction_builder( context.transaction_factory().change_set(ChangeSet::new( WriteSetMut::new(vec![ ( AccessPath::new( code_address, bcs::to_bytes(&Path::Code(ModuleId::new( code_address, Identifier::new("AccountAdministrationScripts").unwrap(), ))) .unwrap(), ), WriteOp::Deletion, ), ( AccessPath::new( context.tc_account().address(), bcs::to_bytes(&Path::Resource(StructTag { address: code_address, module: Identifier::new("AccountFreezing").unwrap(), name: Identifier::new("FreezingBit").unwrap(), type_params: vec![], })) .unwrap(), ), WriteOp::Deletion, ), ]) .freeze() .unwrap(), vec![], )), ); context.commit_block(&vec![txn.clone()]).await; let txns = context.get("/transactions?start=2").await; assert_eq!(1, txns.as_array().unwrap().len()); assert_json( txns[0]["payload"].clone(), json!({ "type": "write_set_payload", "write_set": { "type": "direct_write_set", "changes": [ { "type": "delete_module", "address": "0x1", "module": "0x1::AccountAdministrationScripts" }, { "type": "delete_resource", "address": "0xb1e55ed", "resource": "0x1::AccountFreezing::FreezingBit" } ], "events": [] } }), ) } #[tokio::test] async fn test_post_bcs_format_transaction() { let mut context = new_test_context(); let account = context.gen_account(); let txn = context.create_parent_vasp(&account); let body = bcs::to_bytes(&txn).unwrap(); let resp = context .expect_status_code(202) .post_bcs_txn("/transactions", body) .await; let expiration_timestamp = txn.expiration_timestamp_secs(); let (public_key, sig) = match txn.authenticator() { TransactionAuthenticator::Ed25519 { public_key, signature, } => (public_key, signature), _ => panic!( "expecting TransactionAuthenticator::Ed25519, but got: {:?}", txn.authenticator() ), }; let hash = Transaction::UserTransaction(txn).hash(); assert_json( resp.clone(), json!({ "type": "pending_transaction", "hash": hash.to_hex_literal(), "sender": "0xb1e55ed", "sequence_number": "0", "max_gas_amount": "1000000", "gas_unit_price": "0", "gas_currency_code": "XUS", "expiration_timestamp_secs": expiration_timestamp.to_string(), "payload": { "type": "script_function_payload", "function": "0x1::AccountCreationScripts::create_parent_vasp_account", "type_arguments": [ "0x1::XUS::XUS" ], "arguments": [ "0", account.address().to_hex_literal(), format!("0x{}", hex::encode(account.authentication_key().prefix())), format!("0x{}", hex::encode("vasp".as_bytes())), true ] }, "signature": { "type": "ed25519_signature", "public_key": format!("0x{}", hex::encode(public_key.unvalidated().to_bytes())), "signature": format!("0x{}", hex::encode(sig.to_bytes())), }, }), ); // ensure ed25519 sig txn can be submitted into mempool by JSON format context .expect_status_code(202) .post("/transactions", resp) .await; } #[tokio::test] async fn test_post_invalid_bcs_format_transaction() { let context = new_test_context(); let resp = context .expect_status_code(400) .post_bcs_txn("/transactions", bcs::to_bytes("invalid data").unwrap()) .await; assert_json( resp, json!({ "code": 400, "message": "invalid request body: deserialize error: unexpected end of input" }), ); } #[tokio::test] async fn test_post_invalid_signature_transaction() { let mut context = new_test_context(); let txn = context.create_invalid_signature_transaction(); let body = bcs::to_bytes(&txn).unwrap(); let resp = context .expect_status_code(400) .post_bcs_txn("/transactions", &body) .await; assert_json( resp, json!({ "code": 400, "message": "invalid transaction: INVALID_SIGNATURE" }), ); } #[tokio::test] async fn test_post_transaction_rejected_by_mempool() { let mut context = new_test_context(); let account1 = context.gen_account(); let account2 = context.gen_account(); let txn1 = context.create_parent_vasp(&account1); let txn2 = context.create_parent_vasp(&account2); context .expect_status_code(202) .post_bcs_txn("/transactions", &bcs::to_bytes(&txn1).unwrap()) .await; let resp = context .expect_status_code(400) .post_bcs_txn("/transactions", &bcs::to_bytes(&txn2).unwrap()) .await; assert_json( resp, json!({ "code": 400, "message": "transaction is rejected: InvalidUpdate - Transaction already in mempool" }), ); } #[tokio::test] async fn test_multi_agent_signed_transaction() { let mut context = new_test_context(); let account = context.gen_account(); let factory = context.transaction_factory(); let mut tc_account = context.tc_account(); let secondary = context.root_account(); let txn = tc_account.sign_multi_agent_with_transaction_builder( vec![&secondary], factory.create_parent_vasp_account( Currency::XUS, 0, account.authentication_key(), "vasp", true, ), ); let body = bcs::to_bytes(&txn).unwrap(); let resp = context .expect_status_code(202) .post_bcs_txn("/transactions", body) .await; let (sender, secondary_signers) = match txn.authenticator() { TransactionAuthenticator::MultiAgent { sender, secondary_signer_addresses: _, secondary_signers, } => (sender, secondary_signers), _ => panic!( "expecting TransactionAuthenticator::MultiAgent, but got: {:?}", txn.authenticator() ), }; assert_json( resp["signature"].clone(), json!({ "type": "multi_agent_signature", "sender": { "type": "ed25519_signature", "public_key": format!("0x{}", hex::encode(sender.public_key_bytes())), "signature": format!("0x{}", hex::encode(sender.signature_bytes())), }, "secondary_signer_addresses": [ secondary.address().to_hex_literal(), ], "secondary_signers": [ { "type": "ed25519_signature", "public_key": format!("0x{}",hex::encode(secondary_signers[0].public_key_bytes())), "signature": format!("0x{}", hex::encode(secondary_signers[0].signature_bytes())), } ] }), ); // ensure multi agent txns can be submitted into mempool by JSON format context .expect_status_code(202) .post("/transactions", resp) .await; } #[tokio::test] async fn test_multi_ed25519_signed_transaction() { let context = new_test_context(); let private_key = MultiEd25519PrivateKey::generate_for_testing(); let public_key = MultiEd25519PublicKey::from(&private_key); let auth_key = AuthenticationKey::multi_ed25519(&public_key); let factory = context.transaction_factory(); let mut tc_account = context.tc_account(); let create_account_txn = tc_account.sign_with_transaction_builder( factory.create_parent_vasp_account(Currency::XUS, 0, auth_key, "vasp", true), ); context.commit_block(&vec![create_account_txn]).await; let raw_txn = factory .create_recovery_address() .sender(auth_key.derived_address()) .sequence_number(0) .expiration_timestamp_secs(u64::MAX) // set timestamp to max to ensure static raw transaction .build(); let signature = private_key.sign(&raw_txn); let txn = SignedTransaction::new_multisig(raw_txn, public_key, signature.clone()); let body = bcs::to_bytes(&txn).unwrap(); let resp = context .expect_status_code(202) .post_bcs_txn("/transactions", body) .await; assert_json( resp["signature"].clone(), json!({ "type": "multi_ed25519_signature", "public_keys": [ "<KEY>", "<KEY>", "0x852b13cd7a89b0c223d74504705e84c745d32261244ed233ef0285637a1dece0", "0x77e7fe2a510e4f14e15071fc420469ee287b64f2c8f8c0221b946a3fd9cbfef3", "0xd0c66cfef88b999f027347726bd54eda4675ae312af9146bfdc9e9fa702cc90a", "0xd316059933e0dd6415f00ce350962c8e94b46373b7fb5fb49687f3d6b9e3cb30", "0xf20e973e6dfeda74ca8e15f1a7aed9c87d67bd12e071fd3de4240368422712c9", "0xead82d6e9e3f3baeaa557bd7a431a1c6fe9f35a82c10fed123f362615ee7c2cd", "0x5c048c8c456ff9dd2810343bbd630fb45bf064317efae22c65a1535cf392c5d5", "0x861546d0818178f2b5f37af0fa712fe8ce3cceeda894b553ee274f3fbcb4b32f", "0xfe047a766a47719591348a4601afb3f38b0c77fa3f820e0298c064e7cde6763f" ], "signatures": [ "0xab0ffa0926dd765979c422572b4429d11161a2df6975e223ad4d75c87a117e6c790558e8286caf95550ab97515d2cfa8654365f54524688df91b3b4e91b69d0e", "0x300774b6dd50658d4b693ad5cc1842944465a92b31f1652b445d36b911d4ca625260c451ab7d998534b61253f3bfcdd6bcb03adf4c048b03bd18678d56cd5a03", "0x4bac0f0d9dde41196efae43849f8e4427ee142e04e57e7291ecdfb225528b0fe31eff8e17461a220430daea94a14f750a37b5e0360aa1c72cb956c402743c202" ], "threshold": 3, "bitmap": "0xe0000000" }), ); // ensure multi sig txns can be submitted into mempool by JSON format context .expect_status_code(202) .post("/transactions", resp) .await; } #[tokio::test] async fn test_get_transaction_by_hash() { let mut context = new_test_context(); let account = context.gen_account(); let txn = context.create_parent_vasp(&account); context.commit_block(&vec![txn.clone()]).await; let txns = context.get("/transactions?start=2").await; assert_eq!(1, txns.as_array().unwrap().len()); let resp = context .get(&format!( "/transactions/{}", txns[0]["hash"].as_str().unwrap() )) .await; assert_json(resp, txns[0].clone()) } #[tokio::test] async fn test_get_transaction_by_hash_not_found() { let context = new_test_context(); let resp = context .expect_status_code(404) .get("/transactions/0xdadfeddcca7cb6396c735e9094c76c6e4e9cb3e3ef814730693aed59bd87b31d") .await; assert_json( resp, json!({ "code": 404, "message": "transaction not found by hash(0xdadfeddcca7cb6396c735e9094c76c6e4e9cb3e3ef814730693aed59bd87b31d)", "aptos_ledger_version": "0" }), ) } #[tokio::test] async fn test_get_transaction_by_invalid_hash() { let context = new_test_context(); let resp = context .expect_status_code(400) .get("/transactions/0x1") .await; assert_json( resp, json!({ "code": 400, "message": "invalid parameter transaction hash or version: 0x1" }), ) } #[tokio::test] async fn test_get_transaction_by_version_not_found() { let context = new_test_context(); let resp = context .expect_status_code(404) .get("/transactions/10000") .await; assert_json( resp, json!({ "code": 404, "message": "transaction not found by version(10000)", "aptos_ledger_version": "0" }), ) } #[tokio::test] async fn test_get_transaction_by_version() { let mut context = new_test_context(); let account = context.gen_account(); let txn = context.create_parent_vasp(&account); context.commit_block(&vec![txn.clone()]).await; let txns = context.get("/transactions?start=2").await; assert_eq!(1, txns.as_array().unwrap().len()); let resp = context.get("/transactions/2").await; assert_json(resp, txns[0].clone()) } #[tokio::test] async fn test_get_pending_transaction_by_hash() { let mut context = new_test_context(); let account = context.gen_account(); let txn = context.create_parent_vasp(&account); let body = bcs::to_bytes(&txn).unwrap(); let pending_txn = context .expect_status_code(202) .post_bcs_txn("/transactions", body) .await; let txn_hash = pending_txn["hash"].as_str().unwrap(); let txn = context.get(&format!("/transactions/{}", txn_hash)).await; assert_json(txn, pending_txn); let not_found = context .expect_status_code(404) .get("/transactions/0xdadfeddcca7cb6396c735e9094c76c6e4e9cb3e3ef814730693aed59bd87b31d") .await; assert_json( not_found, json!({ "code": 404, "message": "transaction not found by hash(0xdadfeddcca7cb6396c735e9094c76c6e4e9cb3e3ef814730693aed59bd87b31d)", "aptos_ledger_version": "0" }), ) } #[tokio::test] async fn test_signing_message_with_script_function_payload() { let mut context = new_test_context(); let account = context.gen_account(); let txn = context.create_parent_vasp(&account); let payload = json!({ "type": "script_function_payload", "function": "0x1::AccountCreationScripts::create_parent_vasp_account", "type_arguments": [ "0x1::XUS::XUS" ], "arguments": [ "0", // sliding_nonce account.address().to_hex_literal(), // new_account_address format!("0x{}", hex::encode(account.authentication_key().prefix())), // auth_key_prefix format!("0x{}", hex::encode("vasp".as_bytes())), // human_name true, // add_all_currencies ] }); test_signing_message_with_payload(context, txn, payload).await; } #[tokio::test] async fn test_signing_message_with_module_payload() { let context = new_test_context(); let code = "a11ceb0b0300000006010002030205050703070a0c0816100c260900000001000100000102084d794d6f64756c650269640000000000000000000000000b1e55ed00010000000231010200"; let mut tc_account = context.tc_account(); let txn = tc_account.sign_with_transaction_builder( context .transaction_factory() .module(hex::decode(code).unwrap()), ); let payload = json!({ "type": "module_bundle_payload", "modules" : [ {"bytecode": format!("0x{}", code)}, ], }); test_signing_message_with_payload(context, txn, payload).await; } #[tokio::test] async fn test_signing_message_with_script_payload() { let context = new_test_context(); let new_key = "717d1d400311ff8797c2441ea9c2d2da1120ce38f66afb079c2bad0919d93a09" .parse() .unwrap(); let mut tc_account = context.tc_account(); let txn = tc_account.sign_with_transaction_builder( context .transaction_factory() .rotate_authentication_key_by_script(new_key), ); let code = "a11ceb0b010000000601000202020403060f05151207277c08a3011000000001010000020001000003010200000403020001060c01080000020608000a0202060c0a020b4469656d4163636f756e74154b6579526f746174696f6e4361706162696c6974791f657874726163745f6b65795f726f746174696f6e5f6361706162696c6974791f726573746f72655f6b65795f726f746174696f6e5f6361706162696c69747919726f746174655f61757468656e7469636174696f6e5f6b657900000000000000000000000000000001000401090b0011000c020e020b0111020b02110102"; let payload = json!({ "type": "script_payload", "code": { "bytecode": format!("0x{}", code) }, "type_arguments": [], "arguments": [ "0x717d1d400311ff8797c2441ea9c2d2da1120ce38f66afb079c2bad0919d93a09" ] }); test_signing_message_with_payload(context, txn, payload).await; } #[tokio::test] async fn test_signing_message_with_write_set_payload() { // This test is created for testing error message for now. // Update test when write_set_payload is supported let context = new_test_context(); let mut root_account = context.root_account(); let code_address = AccountAddress::from_hex_literal("0x1").unwrap(); let txn = root_account.sign_with_transaction_builder( context.transaction_factory().change_set(ChangeSet::new( WriteSetMut::new(vec![ ( AccessPath::new( code_address, bcs::to_bytes(&Path::Code(ModuleId::new( code_address, Identifier::new("AccountAdministrationScripts").unwrap(), ))) .unwrap(), ), WriteOp::Deletion, ), ( AccessPath::new( context.tc_account().address(), bcs::to_bytes(&Path::Resource(StructTag { address: code_address, module: Identifier::new("AccountFreezing").unwrap(), name: Identifier::new("FreezingBit").unwrap(), type_params: vec![], })) .unwrap(), ), WriteOp::Deletion, ), ]) .freeze() .unwrap(), vec![], )), ); let payload = json!({ "type": "write_set_payload", "write_set": { "type": "direct_write_set", "changes": [ { "type": "delete_module", "address": "0x1", "module": "0x1::AccountAdministrationScripts" }, { "type": "delete_resource", "address": "0xb1e55ed", "resource": "0x1::AccountFreezing::FreezingBit" } ], "events": [] } }); let sender = context.tc_account(); let body = json!({ "sender": sender.address().to_hex_literal(), "sequence_number": sender.sequence_number().to_string(), "gas_unit_price": txn.gas_unit_price().to_string(), "max_gas_amount": txn.max_gas_amount().to_string(), "gas_currency_code": txn.gas_currency_code(), "expiration_timestamp_secs": txn.expiration_timestamp_secs().to_string(), "payload": payload, }); context .expect_status_code(400) .post("/transactions/signing_message", body) .await; } async fn test_signing_message_with_payload( context: TestContext, txn: SignedTransaction, payload: serde_json::Value, ) { let sender = context.tc_account(); let mut body = json!({ "sender": sender.address().to_hex_literal(), "sequence_number": sender.sequence_number().to_string(), "gas_unit_price": txn.gas_unit_price().to_string(), "max_gas_amount": txn.max_gas_amount().to_string(), "gas_currency_code": txn.gas_currency_code(), "expiration_timestamp_secs": txn.expiration_timestamp_secs().to_string(), "payload": payload, }); let resp = context .post("/transactions/signing_message", body.clone()) .await; let signing_msg = resp["message"].as_str().unwrap(); assert_eq!( signing_msg, format!( "0x{}", hex::encode(&txn.clone().into_raw_transaction().signing_message()) ) ); let hex_bytes: HexEncodedBytes = signing_msg.parse().unwrap(); let sig = context .tc_account() .private_key() .sign_arbitrary_message(hex_bytes.inner()); let expected_sig = match txn.authenticator() { TransactionAuthenticator::Ed25519 { public_key: _, signature, } => signature, _ => panic!("expect TransactionAuthenticator::Ed25519"), }; assert_eq!(sig, expected_sig); // assert transaction can be submitted into mempool and execute. body["signature"] = json!({ "type": "ed25519_signature", "public_key": format!("0x{}", hex::encode(sender.public_key().to_bytes())), "signature": format!("0x{}", hex::encode(sig.to_bytes())), }); context .expect_status_code(202) .post("/transactions", body) .await; context.commit_mempool_txns(10).await; let ledger = context.get("/").await; assert_eq!(ledger["ledger_version"].as_str().unwrap(), "2"); // one metadata + one txn } #[tokio::test] async fn test_get_account_transactions() { let mut context = new_test_context(); let account = context.gen_account(); let txn = context.create_parent_vasp(&account); context.commit_block(&vec![txn]).await; let txns = context .get(format!("/accounts/{}/transactions", context.tc_account().address()).as_str()) .await; assert_eq!(1, txns.as_array().unwrap().len()); let expected_txns = context.get("/transactions?start=2&limit=1").await; assert_json(txns, expected_txns); } #[tokio::test] async fn test_get_account_transactions_filter_transactions_by_start_sequence_number() { let mut context = new_test_context(); let account = context.gen_account(); let txn = context.create_parent_vasp(&account); context.commit_block(&vec![txn]).await; let txns = context .get( format!( "/accounts/{}/transactions?start=1", context.tc_account().address() ) .as_str(), ) .await; assert_json(txns, json!([])); } #[tokio::test] async fn test_get_account_transactions_filter_transactions_by_start_sequence_number_is_too_large() { let mut context = new_test_context(); let account = context.gen_account(); let txn = context.create_parent_vasp(&account); context.commit_block(&vec![txn]).await; let txns = context .get( format!( "/accounts/{}/transactions?start=1000", context.tc_account().address() ) .as_str(), ) .await; assert_json(txns, json!([])); } #[tokio::test] async fn test_get_account_transactions_filter_transactions_by_limit() { let mut context = new_test_context(); let mut tc_account = context.tc_account(); let account1 = context.gen_account(); let txn1 = context.create_parent_vasp_by_account(&mut tc_account, &account1); let account2 = context.gen_account(); let txn2 = context.create_parent_vasp_by_account(&mut tc_account, &account2); context.commit_block(&vec![txn1, txn2]).await; let txns = context .get( format!( "/accounts/{}/transactions?start=0&limit=1", context.tc_account().address() ) .as_str(), ) .await; assert_eq!(txns.as_array().unwrap().len(), 1); let txns = context .get( format!( "/accounts/{}/transactions?start=0&limit=2", context.tc_account().address() ) .as_str(), ) .await; assert_eq!(txns.as_array().unwrap().len(), 2); } const MISC_ERROR: &str = "Move bytecode deserialization / verification failed, including script function not found or invalid arguments"; #[tokio::test] async fn test_get_txn_execute_failed_by_invalid_module_payload_bytecode() { let context = new_test_context(); let invalid_bytecode = hex::decode("a11ceb0b030000").unwrap(); let mut tc_account = context.tc_account(); let txn = tc_account .sign_with_transaction_builder(context.transaction_factory().module(invalid_bytecode)); test_transaction_vm_status(context, txn, false, MISC_ERROR).await } #[tokio::test] async fn test_get_txn_execute_failed_by_invalid_script_payload_bytecode() { let context = new_test_context(); let mut tc_account = context.tc_account(); let invalid_bytecode = hex::decode("a11ceb0b030000").unwrap(); let txn = tc_account.sign_with_transaction_builder( context .transaction_factory() .script(Script::new(invalid_bytecode, vec![], vec![])), ); test_transaction_vm_status(context, txn, false, MISC_ERROR).await } #[tokio::test] async fn test_get_txn_execute_failed_by_invalid_write_set_payload() { let context = new_test_context(); let invalid_bytecode = hex::decode("a11ceb0b030000").unwrap(); let mut root_account = context.root_account(); let code_address = AccountAddress::from_hex_literal("0x1").unwrap(); let txn = root_account.sign_with_transaction_builder( context.transaction_factory().change_set(ChangeSet::new( WriteSetMut::new(vec![( AccessPath::new( code_address, bcs::to_bytes(&Path::Code(ModuleId::new( code_address, Identifier::new("AccountAdministrationScripts").unwrap(), ))) .unwrap(), ), WriteOp::Value(invalid_bytecode), )]) .freeze() .unwrap(), vec![], )), ); // should fail, but VM executed successfully, need investigate, but out of API scope test_transaction_vm_status(context, txn, true, "Executed successfully").await } #[tokio::test] async fn test_get_txn_execute_failed_by_invalid_script_function_address() { let context = new_test_context(); let account = context.dd_account(); test_get_txn_execute_failed_by_invalid_script_function( context, account, "0x1222", "PaymentScripts", "peer_to_peer_with_metadata", vec![xus_tag()], vec![ bcs::to_bytes(&AccountAddress::from_hex_literal("0xdd").unwrap()).unwrap(), bcs::to_bytes(&1u64).unwrap(), bcs::to_bytes(&Vec::<u8>::new()).unwrap(), bcs::to_bytes(&Vec::<u8>::new()).unwrap(), ], MISC_ERROR, ) .await } #[tokio::test] async fn test_get_txn_execute_failed_by_invalid_script_function_module_name() { let context = new_test_context(); let account = context.dd_account(); test_get_txn_execute_failed_by_invalid_script_function( context, account, "0x1", "PaymentScriptsInvalid", "peer_to_peer_with_metadata", vec![xus_tag()], vec![ bcs::to_bytes(&AccountAddress::from_hex_literal("0xdd").unwrap()).unwrap(), bcs::to_bytes(&1u64).unwrap(), bcs::to_bytes(&Vec::<u8>::new()).unwrap(), bcs::to_bytes(&Vec::<u8>::new()).unwrap(), ], MISC_ERROR, ) .await } #[tokio::test] async fn test_get_txn_execute_failed_by_invalid_script_function_name() { let context = new_test_context(); let account = context.dd_account(); test_get_txn_execute_failed_by_invalid_script_function( context, account, "0x1", "PaymentScripts", "peer_to_peer_with_metadata_invalid", vec![xus_tag()], vec![ bcs::to_bytes(&AccountAddress::from_hex_literal("0xdd").unwrap()).unwrap(), bcs::to_bytes(&1u64).unwrap(), bcs::to_bytes(&Vec::<u8>::new()).unwrap(), bcs::to_bytes(&Vec::<u8>::new()).unwrap(), ], MISC_ERROR, ) .await } #[tokio::test] async fn test_get_txn_execute_failed_by_invalid_script_function_type_arguments() { let context = new_test_context(); let account = context.dd_account(); test_get_txn_execute_failed_by_invalid_script_function( context, account, "0x1", "PaymentScripts", "peer_to_peer_with_metadata_invalid", vec![TypeTag::Struct(StructTag { address: CORE_CODE_ADDRESS, module: from_currency_code_string(XUS_NAME).unwrap(), name: Identifier::new("invalid").unwrap(), type_params: vec![], })], vec![ bcs::to_bytes(&AccountAddress::from_hex_literal("0xdd").unwrap()).unwrap(), bcs::to_bytes(&1u64).unwrap(), bcs::to_bytes(&Vec::<u8>::new()).unwrap(), bcs::to_bytes(&Vec::<u8>::new()).unwrap(), ], MISC_ERROR, ) .await } #[tokio::test] async fn test_get_txn_execute_failed_by_invalid_script_function_arguments() { let context = new_test_context(); let account = context.dd_account(); test_get_txn_execute_failed_by_invalid_script_function( context, account, "0x1", "PaymentScripts", "peer_to_peer_with_metadata", vec![xus_tag()], vec![ bcs::to_bytes(&AccountAddress::from_hex_literal("0xdd").unwrap()).unwrap(), bcs::to_bytes(&1u8).unwrap(), // invalid type bcs::to_bytes(&Vec::<u8>::new()).unwrap(), bcs::to_bytes(&Vec::<u8>::new()).unwrap(), ], MISC_ERROR, ) .await } #[tokio::test] async fn test_get_txn_execute_failed_by_missing_script_function_arguments() { let context = new_test_context(); let account = context.dd_account(); test_get_txn_execute_failed_by_invalid_script_function( context, account, "0x1", "PaymentScripts", "peer_to_peer_with_metadata", vec![xus_tag()], vec![ bcs::to_bytes(&AccountAddress::from_hex_literal("0xdd").unwrap()).unwrap(), // missing 3 arguments ], MISC_ERROR, ) .await } #[tokio::test] async fn test_get_txn_execute_failed_by_script_function_validation() { let mut context = new_test_context(); let account = context.gen_account(); context .commit_block(&vec![context.create_parent_vasp(&account)]) .await; test_get_txn_execute_failed_by_invalid_script_function( context, account, "0x1", "PaymentScripts", "peer_to_peer_with_metadata", vec![xus_tag()], vec![ bcs::to_bytes(&AccountAddress::from_hex_literal("0xdd").unwrap()).unwrap(), bcs::to_bytes(&123u64).unwrap(), // exceed limit, account balance is 0. bcs::to_bytes(&Vec::<u8>::new()).unwrap(), bcs::to_bytes(&Vec::<u8>::new()).unwrap(), ], r#"Move abort by LIMIT_EXCEEDED - EINSUFFICIENT_BALANCE A limit on an amount, e.g. a currency, is exceeded. Example: withdrawal of money after account limits window is exhausted. The account does not hold a large enough balance in the specified currency"#, ) .await } #[tokio::test] async fn test_get_txn_execute_failed_by_script_function_execution_failure() { let context = new_test_context(); // address 0xA550C18 { // module Hello { // fun world() { // 1/0; // } // public(script) fun hello() { // world(); // } // } // } let hello_script_fun = hex::decode("a11ceb0b030000000601000203020a050c01070d12081f100c2f24000000010000000002000000000548656c6c6f0568656c6c6f05776f726c640000000000000000000000000a550c180002000000021101020100000000050601000000000000000600000000000000001a010200").unwrap(); let mut root_account = context.root_account(); let module_txn = root_account .sign_with_transaction_builder(context.transaction_factory().module(hello_script_fun)); context.commit_block(&vec![module_txn]).await; test_get_txn_execute_failed_by_invalid_script_function( context, root_account, "0xA550C18", "Hello", "hello", vec![], vec![], "Execution failed in 0000000000000000000000000A550C18::Hello::world at code offset 2", ) .await } #[tokio::test] async fn test_get_txn_execute_failed_by_script_execution_failure() { let context = new_test_context(); // script { // fun main() { // 1/0; // } // } let script = hex::decode("a11ceb0b030000000105000100000000050601000000000000000600000000000000001a0102") .unwrap(); let mut root_account = context.root_account(); let txn = root_account.sign_with_transaction_builder( context .transaction_factory() .script(Script::new(script, vec![], vec![])), ); test_transaction_vm_status( context, txn, false, "Execution failed in script at code offset 2", ) .await } async fn test_get_txn_execute_failed_by_invalid_script_function( context: TestContext, mut account: LocalAccount, address: &str, module_id: &str, func: &str, ty_args: Vec<TypeTag>, args: Vec<Vec<u8>>, vm_status: &str, ) { let txn = account.sign_with_transaction_builder(context.transaction_factory().script_function( ScriptFunction::new( ModuleId::new( AccountAddress::from_hex_literal(address).unwrap(), Identifier::new(module_id).unwrap(), ), Identifier::new(func).unwrap(), ty_args, args, ), )); test_transaction_vm_status(context, txn, false, vm_status).await } async fn test_transaction_vm_status( context: TestContext, txn: SignedTransaction, success: bool, vm_status: &str, ) { let body = bcs::to_bytes(&txn).unwrap(); // we don't validate transaction payload when submit txn into mempool. context .expect_status_code(202) .post_bcs_txn("/transactions", body) .await; context.commit_mempool_txns(1).await; let resp = context .get(format!("/transactions/{}", txn.committed_hash().to_hex_literal()).as_str()) .await; assert_eq!( resp["success"].as_bool().unwrap(), success, "{}", pretty(&resp) ); assert_eq!(resp["vm_status"].as_str().unwrap(), vm_status); } #[tokio::test] async fn test_submit_transaction_rejects_payload_too_large_bcs_txn_body() { let context = new_test_context(); let resp = context .expect_status_code(413) .post_bcs_txn( "/transactions", gen_string(context.context.content_length_limit() + 1).as_bytes(), ) .await; assert_json( resp, json!({ "code": 413, "message": "The request payload is too large" }), ); } #[tokio::test] async fn test_submit_transaction_rejects_payload_too_large_json_body() { let context = new_test_context(); let resp = context .expect_status_code(413) .post( "/transactions", json!({ "data": gen_string(context.context.content_length_limit()+1).as_bytes(), }), ) .await; assert_json( resp, json!({ "code": 413, "message": "The request payload is too large" }), ); } #[tokio::test] async fn test_submit_transaction_rejects_invalid_content_type() { let context = new_test_context(); let req = warp::test::request() .header("content-type", "invalid") .method("POST") .body("text") .path("/transactions"); let resp = context.expect_status_code(415).execute(req).await; assert_json( resp, json!({ "code": 415, "message": "The request's content-type is not supported" }), ); } #[tokio::test] async fn test_submit_transaction_rejects_invalid_json() { let context = new_test_context(); let req = warp::test::request() .header("content-type", "application/json") .method("POST") .body("invalid json") .path("/transactions"); let resp = context.expect_status_code(400).execute(req).await; assert_json( resp, json!({ "code": 400, "message": "Request body deserialize error: expected value at line 1 column 1" }), ); } #[tokio::test] async fn test_create_signing_message_rejects_payload_too_large_json_body() { let context = new_test_context(); let resp = context .expect_status_code(413) .post( "/transactions/signing_message", json!({ "data": gen_string(context.context.content_length_limit()+1).as_bytes(), }), ) .await; assert_json( resp, json!({ "code": 413, "message": "The request payload is too large" }), ); } #[tokio::test] async fn test_create_signing_message_rejects_invalid_content_type() { let context = new_test_context(); let req = warp::test::request() .header("content-type", "invalid") .method("POST") .body("text") .path("/transactions/signing_message"); let resp = context.expect_status_code(415).execute(req).await; assert_json( resp, json!({ "code": 415, "message": "The request's content-type is not supported" }), ); } #[tokio::test] async fn test_create_signing_message_rejects_invalid_json() { let context = new_test_context(); let req = warp::test::request() .header("content-type", "application/json") .method("POST") .body("invalid json") .path("/transactions/signing_message"); let resp = context.expect_status_code(400).execute(req).await; assert_json( resp, json!({ "code": 400, "message": "Request body deserialize error: expected value at line 1 column 1" }), ); } #[tokio::test] async fn test_create_signing_message_rejects_no_content_length_request() { let context = new_test_context(); let req = warp::test::request() .header("content-type", "application/json") .method("POST") .path("/transactions/signing_message"); let resp = context.expect_status_code(411).execute(req).await; assert_json( resp, json!({ "code": 411, "message": "A content-length header is required" }), ); } fn gen_string(len: u64) -> String { let mut rng = thread_rng(); std::iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .take(len as usize) .map(char::from) .collect() }
rust
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). """Core rules for Pants to operate correctly. These are always activated and cannot be disabled. """ from pants.core.goals import fmt, lint, package, repl, run, test, typecheck from pants.core.target_types import ArchiveTarget, Files, GenericTarget, RelocatedFiles, Resources from pants.core.target_types import rules as target_type_rules from pants.core.util_rules import ( archive, distdir, external_tool, filter_empty_sources, pants_bin, pants_environment, source_files, stripped_source_files, subprocess_environment, ) from pants.source import source_root def rules(): return [ # goals *fmt.rules(), *lint.rules(), *package.rules(), *repl.rules(), *run.rules(), *test.rules(), *typecheck.rules(), # util_rules *distdir.rules(), *filter_empty_sources.rules(), *pants_bin.rules(), *source_files.rules(), *stripped_source_files.rules(), *archive.rules(), *external_tool.rules(), *pants_environment.rules(), *subprocess_environment.rules(), *source_root.rules(), *target_type_rules(), ] def target_types(): return [ArchiveTarget, Files, GenericTarget, Resources, RelocatedFiles]
python
#pragma once #include "Instance.cpp" #include "Global.cpp" #include "Permutation.cpp" class Solution : public Permutation { private: double *Fitness; int LastSwap[2]; public: double *LastSwapCost; const Instance& Problem; Solution(const Instance& instance) : Permutation(instance.Size), Problem(instance), LastSwapCost(NULL), Fitness(NULL) { LastSwap[0] = -1; LastSwap[1] = -1; } Solution(const Solution& solution) : Permutation(solution.Problem.Size), Problem(solution.Problem), LastSwapCost(NULL), Fitness(NULL) { operator=(solution); } Solution& operator=(const Solution &solution) { assert(&solution.Problem == &Problem); for (int i=0; i<Problem.Size; ++i) Values[i] = solution.Values[i]; ClearFitness(); Fitness = solution.Fitness != NULL ? new double(*solution.Fitness) : NULL; LastSwapCost = solution.LastSwapCost != NULL ? new double(*solution.LastSwapCost) : NULL; LastSwap[0] = solution.LastSwap[0]; LastSwap[1] = solution.LastSwap[1]; return *this; } inline double GetDeviation() { return (GetFitness() - Problem.OptimalFitness)/Problem.OptimalFitness * 100; } inline double GetFitness() { if (Fitness != NULL) return *Fitness; double sum = 0; for (int i=0; i<Problem.Size; ++i) for (int j=0; j<Problem.Size; ++j) sum += Problem.Distance[i][j] * Problem.Flow[Values[i]][Values[j]]; Fitness = new double(sum); return sum; } inline void Swap(int i, int j, double* swapCost) { if (i==j) return; Permutation::Swap(i,j); LastSwap[0] = i; LastSwap[1] = j; if (swapCost != NULL) { delete LastSwapCost; LastSwapCost = new double(*swapCost); if (Fitness != NULL) *Fitness += *swapCost; } else ClearFitness(); } inline int Size() { return Problem.Size; } inline int& operator[](int index) { return Values[index]; } inline void SwapCostMatrix(double** matrix) { for (int i=0; i<Size(); ++i) for (int j=i; j<Size(); ++j) // set j=i to zero out the diagonal. matrix[j][i] = matrix[i][j] = SwapCost(i,j); } inline void UpdateSwapCostMatrix(double** matrix) { for (int i=0; i<Size(); ++i) for (int j=i+1; j<Size(); ++j) matrix[j][i] = matrix[i][j] = FastSwapCost(matrix[i][j], i, j); } inline double FastSwapCost(double lastSwapCostUV, int u, int v) { int r = LastSwap[0], s = LastSwap[1]; if (r != u && r != v && s != u && s != v) // Condition: {r,s} intersect {u,v} == NULL { double **a = Problem.Distance, **b = Problem.Flow; int pu = Values[u], pv = Values[v], pr = Values[r], ps = Values[s]; return lastSwapCostUV + (a[r][u]-a[r][v]+a[s][v]-a[s][u]) * (b[ps][pu]-b[ps][pv]+b[pr][pv]-b[pr][pu]) + (a[u][r]-a[v][r]+a[v][s]-a[u][s]) * (b[pu][ps]-b[pv][ps]+b[pv][pr]-b[pu][pr]); } return SwapCost(u,v); } inline double SwapCost(int r, int s) { if (r == s) return 0; double **a = Problem.Distance, **b = Problem.Flow; int pr = Values[r], ps = Values[s]; double sum = a[r][r]*(b[ps][ps]-b[pr][pr]) + a[r][s]*(b[ps][pr]-b[pr][ps]) + a[s][r]*(b[pr][ps]-b[ps][pr]) + a[s][s]*(b[pr][pr]-b[ps][ps]); for (int k=0; k<Problem.Size; ++k) { if (k == r || k == s) continue; int pk = Values[k]; sum += a[k][r]*(b[pk][ps]-b[pk][pr]) + a[k][s]*(b[pk][pr]-b[pk][ps]) + a[r][k]*(b[ps][pk]-b[pr][pk]) + a[s][k]*(b[pr][pk]-b[ps][pk]); } return sum; } inline void ClearFitness() { delete LastSwapCost; LastSwapCost = NULL; delete Fitness; Fitness = NULL; } ~Solution() { ClearFitness(); } };
cpp
/*ハンバーグメニュー*/ nav { text-align: center; display: block; position: fixed; top: 0; right: 100%; bottom: 0; width: 100%; overflow-x: hidden; overflow-y: auto; -webkit-overflow-scrolling: touch; transition: all 1.0s; z-index: 3; opacity: 0; } .open nav { left: 0; opacity: 1; } nav .inner { padding: 15px; } nav .inner ul { list-style: none; margin: 0; padding: 0; } nav .inner ul li { position: relative; margin: 0; border-bottom: 1px solid #fff; /*区切り線*/ } nav .inner ul li a { display: block; color: #fff; font-size: 20px; padding: 1.5em; text-decoration: none; transition-duration: 0.4s; } nav .inner ul li a:hover { background: #80808099; } .inner p{ font-size: 25px; text-shadow: 0px 0px 15px #00fffd; color:#ffffff; padding:25px; } @media screen and (max-width: 767px) { nav { right: 100%; width: 100%; } } /*============ .toggle_btn =============*/ .toggle_btn { display: block; position: fixed; top: 30px; right: 30px; width: 30px; height: 30px; transition: all .5s; cursor: pointer; z-index: 3; } .toggle_btn span { display: block; position: absolute; left: 0; width: 30px; height: 2px; background-color: #fff; /*3本線いろ*/ border-radius: 4px; transition: all .4s; } .toggle_btn span:nth-child(1) { top: 4px; } .toggle_btn span:nth-child(2) { top: 14px; } .toggle_btn span:nth-child(3) { bottom: 4px; } .open .toggle_btn span { background-color: #fff; } .open .toggle_btn span:nth-child(1) { -webkit-transform: translateY(10px) rotate(-315deg); transform: translateY(10px) rotate(-315deg); } .open .toggle_btn span:nth-child(2) { opacity: 0; } .open .toggle_btn span:nth-child(3) { -webkit-transform: translateY(-10px) rotate(315deg); transform: translateY(-10px) rotate(315deg); } /*============ #mask =============*/ #mask { display: none; transition: all .5s; } .open #mask { display: block; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: #000; opacity: .9; z-index: 2; cursor: pointer; }
css
<reponame>cavalrytactics/juniper<gh_stars>0 use crate::{ result::{GraphQLScope, UnsupportedAttribute}, util::{self, span_container::SpanContainer}, }; use proc_macro2::TokenStream; use quote::quote; use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields}; pub fn build_derive_union( ast: syn::DeriveInput, is_internal: bool, error: GraphQLScope, ) -> syn::Result<TokenStream> { let ast_span = ast.span(); let enum_fields = match ast.data { Data::Enum(data) => data.variants, _ => return Err(error.custom_error(ast_span, "can only be applied to enums")), }; // Parse attributes. let attrs = util::ObjectAttributes::from_attrs(&ast.attrs)?; let ident = &ast.ident; let name = attrs .name .clone() .map(SpanContainer::into_inner) .unwrap_or_else(|| ident.unraw().to_string()); let fields = enum_fields .into_iter() .filter_map(|field| { let span = field.span(); let field_attrs = match util::FieldAttributes::from_attrs( &field.attrs, util::FieldAttributeParseMode::Object, ) { Ok(attrs) => attrs, Err(e) => { proc_macro_error::emit_error!(e); return None; } }; if let Some(ident) = field_attrs.skip { error.unsupported_attribute_within(ident.span(), UnsupportedAttribute::Skip); return None; } let variant_name = field.ident; let name = field_attrs .name .clone() .map(SpanContainer::into_inner) .unwrap_or_else(|| util::to_camel_case(&variant_name.unraw().to_string())); let resolver_code = quote!( #ident :: #variant_name ); let _type = match field.fields { Fields::Unnamed(inner) => { let mut iter = inner.unnamed.iter(); let first = match iter.next() { Some(val) => val, None => unreachable!(), }; if iter.next().is_some() { error.custom( inner.span(), "all members must be unnamed with a single element e.g. Some(T)", ); } first.ty.clone() } _ => { error.custom( variant_name.span(), "only unnamed fields with a single element are allowed, e.g., Some(T)", ); return None; } }; if let Some(description) = field_attrs.description { error.unsupported_attribute_within( description.span_ident(), UnsupportedAttribute::Description, ); } if let Some(default) = field_attrs.default { error.unsupported_attribute_within( default.span_ident(), UnsupportedAttribute::Default, ); } if name.starts_with("__") { error.no_double_underscore(if let Some(name) = field_attrs.name { name.span_ident() } else { variant_name.span() }); } Some(util::GraphQLTypeDefinitionField { name, _type, args: Vec::new(), description: None, deprecation: field_attrs.deprecation.map(SpanContainer::into_inner), resolver_code, is_type_inferred: true, is_async: false, default: None, span, }) }) .collect::<Vec<_>>(); // Early abort after checking all fields proc_macro_error::abort_if_dirty(); if !attrs.interfaces.is_empty() { attrs.interfaces.iter().for_each(|elm| { error.unsupported_attribute(elm.span(), UnsupportedAttribute::Interface) }); } if fields.is_empty() { error.not_empty(ast_span); } if name.starts_with("__") && !is_internal { error.no_double_underscore(if let Some(name) = attrs.name { name.span_ident() } else { ident.span() }); } // NOTICE: This is not an optimal implementation. It is possible // to bypass this check by using a full qualified path instead // (crate::Test vs Test). Since this requirement is mandatory, the // `std::convert::Into<T>` implementation is used to enforce this // requirement. However, due to the bad error message this // implementation should stay and provide guidance. let all_variants_different = { let mut all_types: Vec<_> = fields.iter().map(|field| &field._type).collect(); let before = all_types.len(); all_types.dedup(); before == all_types.len() }; if !all_variants_different { error.custom(ident.span(), "each variant must have a different type"); } // Early abort after GraphQL properties proc_macro_error::abort_if_dirty(); let definition = util::GraphQLTypeDefiniton { name, _type: syn::parse_str(&ast.ident.to_string()).unwrap(), context: attrs.context.map(SpanContainer::into_inner), scalar: attrs.scalar.map(SpanContainer::into_inner), description: attrs.description.map(SpanContainer::into_inner), fields, generics: ast.generics, interfaces: None, include_type_generics: true, generic_scalar: true, no_async: attrs.no_async.is_some(), }; let juniper_crate_name = if is_internal { "crate" } else { "juniper" }; Ok(definition.into_union_tokens(juniper_crate_name)) }
rust
Chelsea were unable to sell tickets after the government imposed sanctions on its Russian owner Roman Abramovich in response to Moscow’s invasion of Ukraine. However, the Department for Digital, Culture, Media and Sport last week tweaked its license to let the club sell tickets, with all proceeds set to go to relevant competition organisers and not Chelsea. Off later, sanctioned Russian billionaire Roman Abramovich and Ukrainian peace negotiators suffered symptoms of suspected poisoning earlier this month after a meeting in Kyiv, the Wall Street Journal reported on Monday, citing people familiar with the matter. Chelsea Sale Live: In other news, John Terry who has won five Premier League titles and two Champions League crowns has confirmed that he is at the forefront of a consortium that is looking to purchase a 10% stake in Chelsea for £250million. The Chelsea legend along with former women’s star Claire Rafferty are heading up the consortium called True Blue. A report claims the bid will also allow supporters, players and ex-staff to buy fan tokens for more than £100, with voting rights coming in return. Check John Terry’s official statement. Terry has been extremely active in promoting his ‘Ape Kids Football Club’ non-fungible tokens (NFT) collection in recent months, though its value is said to have plummeted in value by 90 per cent. However, the ex-Blues captain cannot fund a full bid to try and compete for total ownership of the club.
english
Begin typing your search above and press return to search. BONGAIGAON: A Bol Bom devotee drowned on Monday in Bongaigaon. The incident took place in the Srijangram area of Bongaigaon district where a devotee named Rajib Ray (17) drowned in the Aie River. Rajib was a student of Laksminath Academy of Abhayapuri. Also watch: #NewsMakers: Being LGBTQ+ A Curse?
english
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageBrightness5 = (props) => ( <SvgIcon {...props}> <path d="M20 15.31L23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z"/> </SvgIcon> ); ImageBrightness5.displayName = 'ImageBrightness5'; ImageBrightness5.muiName = 'SvgIcon'; export default ImageBrightness5;
javascript
<gh_stars>0 import React,{useState} from 'react' import { connect } from 'react-redux'; import openSocket from 'socket.io-client'; import { motion,AnimatePresence } from 'framer-motion'; import ringtone from '../assets/incoming.mp3' import '../scss/components/helpers/notification.scss'; const nextVariants = { hidden: { y: '-100vw' }, visible: { y: "0vw", x:"-7vw", transition: { type: 'spring', stiffness: 80 } }, exit: { x: "-100vh", transition: { ease: 'easeInOut',delay:0.5 } }, } const { REACT_APP_SOCKET } = process.env; const socket = openSocket(REACT_APP_SOCKET); const Notify = ({ authInfo,AddOrder }) => { const [ message,setMessage ] = useState(); const [ socketId, setSocketId ] = useState(); const [ showToast, setShowToast ] = useState(false); socket.on('ping',(id)=>{ if(id !== undefined) setSocketId(id); if(authInfo.token !== null && socketId !== undefined) socket.emit('auth',{ socketId: id, authInfo }) }) socket.on('new_order',order =>{ if(authInfo.role !== "WAITER" && authInfo.role !== "ADMIN"){ if(order.processor === authInfo.role){ AddOrder(order); setMessage(order.owner); setShowToast(true); } } }) socket.on('updated_order',order=>{ if(order.creator_id === authInfo.id){ AddOrder(order); setMessage('Pick up'); setShowToast(true); } }) if (showToast&&authInfo.role !== 'GUEST'){ setTimeout(()=> { setShowToast(false) setMessage(); } ,5000) return ( <AnimatePresence> <audio src={ringtone} autoPlay loop></audio> <section className="cover"> <motion.div className="notification" variants={nextVariants} initial="hidden" animate="visible" exit="exit" > <div> <i className="fas fa-utensils"></i> </div> <div> <span> { message }</span> </div> </motion.div> </section> </AnimatePresence> ) }else{ return <></> } } const mapStateToProp = (state) =>({ authInfo: state.auth.userInfo }) const mapDispatchToProps = (dispatch) => ({ AddOrder: (order) => dispatch({type:'AddOrder',action:order}) }) export default connect(mapStateToProp,mapDispatchToProps)(Notify);
javascript
Rating: ( Not yet rated ) Egypt\'s top army generals have cleared the way for army chief Abdel Fattah el-Sisi to run for president. Military commanders claim the people\'s trust in Sisi is a call that must be heeded. Sisi has not said has not said whether he will seek the country\'s highest office. Send PTV a Message!
english
[ { "pkh": "tz1KfCukgwoU32Z4or88467mMM3in5smtv8k", "rolls": 5 }, { "pkh": "tz1KfEsrtDaA1sX7vdM4qmEPWuSytuqCDp5j", "rolls": 307 } ]
json
<reponame>mnebuerquo/virtuous-python # virtuous-python This is a tool for writing python virtuously. Support linting, testing, deploying and good maintenance. ## What is this? This is a script to help you be virtuous when writing and running Python programs. I had just come back to python after not using it for a while, and I was annoyed wiith having to set up a virtualenv and activate it for each project. So I wrote a script to make that easier. Mostly because I didn't want to have to remember the steps and commands, and I didn't want to have to remember to pip install or freeze my requirements. This script is like a cross between a wrapper and a makefile. It runs your program, but it also creates, activates and cleans up a virtualenv around it. It can run a linter, test suite, and auto-format your code as well. And it can be used to run things in production. ## How to use it (in a hurry): 1. Copy the `run` script to your project directory. 2. Edit your requirements.txt and add your dependencies. 3. Call `run` with your main file as the first argument: ```bash ./run my-app.py arg1 arg2 arg3 ``` 4. Profit! ## Options The `run` script has some options which help you write clean code. * `--lint` - Run a linter and output warnings about your code. This uses [flake8](http://flake8.pycqa.org/en/latest/) to give warnings for code not following PEP8 conventions. * `--test` - Run [pytest](https://docs.pytest.org/en/latest/) to evaluate all your tests. * `--format <path>` - Auto-format your code with [autopep8](https://github.com/hhatto/autopep8) to fix all your annoying little whitespace inconsistencies. * `--clean` - removes virtualenv directories so you can re-install all your dependencies. * Without the above options, it runs any python program you tell it. ## Features * Simplifies your development workflow. * Manages your virtualenv directories for the project so you don't have to. * Provides built-in configuration for flake8 (lint) and pytest. * Creates a `.gitignore` for python if you don't already have one. * Automatically installs and freezes your requirements. ## How I use it: First I copy `run` to my project, either a legacy project or a new one. Then I follow these steps: 1. `./run my-project-main.py with command line args` - When I run, it sets up my virtualenv, activates it for me, and pip installs my requirements. I don't have to think about that stuff. I see my code is working or I find a bug which I need to fix. 2. Write code to fix a bug or add a feature. 3. Add tests to the code. 4. `./run --test` - Run all my tests, and see if they pass or fail. Fix and repeat. 5. `./run --format . && ./run --lint` - Then I fix any lint warnings. Repeat until there are no more warnings. 6. Repeat until happy. 7. Commmit code, requirements.txt, and requirements.freeze to git.
markdown
Telugu superstar Mahesh Babu was last seen in action and romantic drama Sarileru Neekevvaru, which released in theatres in 2020. After the release of Anil Ravipudi’ directorial venture, Mahesh Babu took a break from work for three months and then signed Sarkaru Vaari Paata with director Parasuram Petla which has National award winning actress Keerthy Suresh as the leading lady. Now according to the latest report, Malayalam actress Sowmyaa Menon has been roped in Mahesh Babu and Keerthy Suresh starrer upcoming film Sarkaru Vaari Paata, to play the crucial role. Sowmyaa Menon herself confirmed the same by sharing a post on her Instagram where she said: Hola Fam, Super excited to be a part of this huge team. “Sarkaru Vaari Patta“. I am feeling truly blessed to have this opportunity to work with such incredibly talented, wonderful & legendary team. An amazing new beginning Looking forward for all your prayers and support.” She also shared a pic on Insta where she is seen holding a clap board. Currently the team of Sarkaru Vaari Paata is in Spain and the makers are canning the crucial scenes on Keerthy Suresh, Mahesh Babu and the other casts of the film. Sarkaru Vaari Paata is slated to hit the theaters on 13th January 2022.
english
/* * Copyright 2001-2008, pinc Software. All Rights Reserved. */ //! handles the BFS block bitmap #include "Bitmap.h" #include "Disk.h" #include "Inode.h" #include <stdlib.h> #include <stdio.h> #include <string.h> Bitmap::Bitmap(Disk *disk) : fBitmap(NULL), fBackupBitmap(NULL) { SetTo(disk); } Bitmap::Bitmap() : fDisk(NULL), fBitmap(NULL), fBackupBitmap(NULL), fSize(0L), fByteSize(0L), fUsedBlocks(0LL) { } Bitmap::~Bitmap() { free(fBitmap); free(fBackupBitmap); } status_t Bitmap::SetTo(Disk *disk) { free(fBitmap); fDisk = disk; fSize = divide_roundup(disk->NumBlocks(),disk->BlockSize() * 8); fByteSize = disk->BlockSize() * disk->SuperBlock()->num_ags * disk->SuperBlock()->blocks_per_ag; fBitmap = (uint32 *)malloc(fByteSize); if (!fBitmap) return B_NO_MEMORY; fBackupBitmap = (uint32 *)malloc(fByteSize); if (fBackupBitmap == NULL) return B_NO_MEMORY; memset(fBackupBitmap, 0, fByteSize); // set root block, block bitmap, log as used off_t end = disk->ToBlock(disk->Log()) + disk->Log().length; for (off_t block = 0; block < end; block++) { if (!BackupSetAt(block, true)) break; } ssize_t size; if ((size = disk->ReadAt(disk->BlockSize(), fBitmap, fByteSize)) < B_OK) { free(fBitmap); fBitmap = NULL; free(fBackupBitmap); fBackupBitmap = NULL; return size; } // calculate used blocks fUsedBlocks = 0LL; for (uint32 i = fByteSize >> 2;i-- > 0;) { uint32 compare = 1; for (int16 j = 0;j < 32;j++,compare <<= 1) { if (compare & fBitmap[i]) fUsedBlocks++; } } return B_OK; } status_t Bitmap::InitCheck() { return fBitmap ? B_OK : B_ERROR; } off_t Bitmap::FreeBlocks() const { if (fDisk == NULL) return 0; return fDisk->NumBlocks() - fUsedBlocks; } bool Bitmap::UsedAt(off_t block) const { uint32 index = block / 32; // 32bit resolution, (beginning with block 1?) if (index > fByteSize / 4) return false; return fBitmap[index] & (1L << (block & 0x1f)); } bool Bitmap::BackupUsedAt(off_t block) const { uint32 index = block / 32; // 32bit resolution, (beginning with block 1?) if (index > fByteSize / 4) return false; return fBackupBitmap[index] & (1L << (block & 0x1f)); } bool Bitmap::BackupSetAt(off_t block, bool used) { uint32 index = block / 32; if (index > fByteSize / 4) { fprintf(stderr, "Bitmap::BackupSetAt(): Block %" B_PRIdOFF " outside " "bitmap!\n", block); return false; } int32 mask = 1L << (block & 0x1f); bool oldUsed = fBackupBitmap[index] & mask; if (used) fBackupBitmap[index] |= mask; else fBackupBitmap[index] &= ~mask; return oldUsed; } void Bitmap::BackupSet(Inode *inode, bool used) { // set inode and its data-stream // the attributes are ignored for now, because they will // be added anyway since all inodes from disk are collected. // printf("a: %Ld\n",inode->Block()); BackupSetAt(inode->Block(),used); // the data stream of symlinks is no real data stream if (inode->IsSymlink() && (inode->Flags() & INODE_LONG_SYMLINK) == 0) return; // direct blocks const bfs_inode *node = inode->InodeBuffer(); for (int32 i = 0; i < NUM_DIRECT_BLOCKS; i++) { if (node->data.direct[i].IsZero()) break; off_t start = fDisk->ToBlock(node->data.direct[i]); off_t end = start + node->data.direct[i].length; for (off_t block = start; block < end; block++) { if (!BackupSetAt(block, used)) { //dump_inode(node); break; } } } // indirect blocks if (node->data.max_indirect_range == 0 || node->data.indirect.IsZero()) return; // printf("c: %Ld\n",fDisk->ToBlock(node->data.indirect)); BackupSetAt(fDisk->ToBlock(node->data.indirect), used); DataStream *stream = dynamic_cast<DataStream *>(inode); if (stream == NULL) return; // load indirect blocks int32 bytes = node->data.indirect.length << fDisk->BlockShift(); block_run *indirect = (block_run *)malloc(bytes); if (indirect == NULL) return; if (fDisk->ReadAt(fDisk->ToOffset(node->data.indirect), indirect, bytes) <= 0) return; int32 runs = bytes / sizeof(block_run); for (int32 i = 0; i < runs; i++) { if (indirect[i].IsZero()) break; off_t start = fDisk->ToBlock(indirect[i]); off_t end = start + indirect[i].length; for (off_t block = start; block < end; block++) { // printf("d: %Ld\n", block); if (!BackupSetAt(block, used)) break; } } free(indirect); // double indirect blocks if (node->data.max_double_indirect_range == 0 || node->data.double_indirect.IsZero()) return; // printf("e: %Ld\n",fDisk->ToBlock(node->data.double_indirect)); BackupSetAt(fDisk->ToBlock(node->data.double_indirect), used); // FIXME: to be implemented... puts("double indirect blocks to block bitmap requested..."); } status_t Bitmap::Validate() { return B_OK; } status_t Bitmap::CompareWithBackup() { for (int32 i = fByteSize / 4;i-- > 0;) { if (fBitmap[i] != fBackupBitmap[i]) { printf("differ at %" B_PRId32 " (block %" B_PRId32 ") -> bitmap = " "%08" B_PRIx32 ", backup = %08" B_PRIx32 "\n", i, i * 32, fBitmap[i], fBackupBitmap[i]); } } return B_OK; } bool Bitmap::TrustBlockContaining(off_t /*block*/) const { return true; }
cpp
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include <map> #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/model/BasicTypes.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/IFC4/include/IfcMeasureValue.h" #include "ifcpp/IFC4/include/IfcSizeSelect.h" #include "ifcpp/IFC4/include/IfcPositiveRatioMeasure.h" // TYPE IfcPositiveRatioMeasure = IfcRatioMeasure; shared_ptr<BuildingObject> IfcPositiveRatioMeasure::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcPositiveRatioMeasure> copy_self( new IfcPositiveRatioMeasure() ); copy_self->m_value = m_value; return copy_self; } void IfcPositiveRatioMeasure::getStepParameter( std::stringstream& stream, bool is_select_type ) const { if( is_select_type ) { stream << "IFCPOSITIVERATIOMEASURE("; } stream << m_value; if( is_select_type ) { stream << ")"; } } const std::wstring IfcPositiveRatioMeasure::toString() const { std::wstringstream strs; strs << m_value; return strs.str(); } shared_ptr<IfcPositiveRatioMeasure> IfcPositiveRatioMeasure::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map ) { if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcPositiveRatioMeasure>(); } if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcPositiveRatioMeasure>(); } shared_ptr<IfcPositiveRatioMeasure> type_object( new IfcPositiveRatioMeasure() ); readReal( arg, type_object->m_value ); return type_object; }
cpp
<reponame>sguzman/book-repo<gh_stars>1-10 {"categories":["Programming","Scripting","Web Development"],"desc":"\n","details":{"authors":"<NAME>","format":"pdf","isbn-10":"1484226550","isbn-13":"978-1484226551","pages":"164 pages","publication date":"March 10, 2017","publisher":"Apress","size":"3.00Mb"},"img":"http://2192.168.3.11/covers/07/0719eb6425fc99bfce752051e5e2b39b.jpg","link":"https://rapidhosting.info/files/bl4","title":"Beginning Functional JavaScript: Functional Programming with JavaScript Using EcmaScript 6"}
json
Raqesh Vashisht: Worried Qubool Hai Fans May Not Accept Me As Asad! Raqesh Vashisht met the press for the first time after starting his work as Asad Ahmad Khan in Zee TV's popular show Qubool Hai replacing Karan Singh Grover. Here is what he had to tell everyone regarding his new challenge. - I am looking forward to this role and want to work hard to take this show to new heights. - I have accepted this role as a challenge and want to bring a freshness to the character of Asad. - If you have passion you will be happy doing films or TV shows. Everyone gets a chance to make a mark in television industry. - I totally believe in destiny. I follow God's plans. He has been kind to me. - Looking to take the show to a new level especially because all the people who work so hard behind the scenes. - When I first visited set I got great positivity especially from Surabhi. - The character is same but I will bring my own style to Asad. - Was worried that fans may not accept me in this role but this was a challenge and I am glad to be here. - I am a bit anxious and excited about fans reaction. I hope fans will give me a chance to prove myself in the role of Asad. - Qubool Hai is a path breaking show and the real hero of the show is the script. I am glad Indian audience likes new kind of shows. Here are some of the tweets posts by Qubool Hai fans regarding Karan Singh Grover getting replaces by Raqesh Vashisht. Was worried that fans may not accept me in this role but this was a challenge and I am glad to be here. quвσσl hαι. ♥ says, "Stop all this drama, and jus end #QuboolHai. Not that it is going to happen, but they seriously should. Stop doing this! " ZahraKSG says, "Gul Khan - #QuboolHai is a story about 2 brothers ! Me - But both brothers r not even on screen. " KaranSinghGroverFCTM - Enough of Trending Guys KSG is no more Part of #QuboolHai and all we can do is ignore d show don't spoil your and KSG name by Overreacting! KaranSinghGroverFCTM - We're no more Viewer of #QuboolHai! ;) RT & Spread this Ppl! ! ! ! quвσσl hαι. - THEY WILL NEVER FIND A BETTER #ASADAHMEDKHAN THEN KARAN SINGH GROVER! NO ONE CAN REPLACE HIM! WIll Raqesh Vashisht Get Accepted? The question every one wants to know is whether Raqesh will get accepted as Asad Ahmad Khan. Karan Singh Grover on the other hand is apparently in talks regarding his next show already. Let's now wait and watch if the new Asad and Zoya succeed in overcoming this obstacle or not.
english
<reponame>aghontpi/mirror-xkcd-api {"month": "8", "num": 1411, "link": "", "year": "2014", "news": "", "safe_title": "Loop", "transcript": "[[A figure sits at a desk with a monitor and a laptop on it. The figure is holding a tablet and a smartphone.]]\n((The following caption is laid out as a circle))\nStare blankly at screen \u00e2\u0086\u0092 open news site \u00e2\u0086\u0092 start reading \u00e2\u0086\u0092 get bored \u00e2\u0086\u0092 absently check smaller device \u00e2\u0086\u0092 stare blankly at screen\n\n{{Title text: Ugh, today's kids are forgetting the old-fashioned art of absentmindedly reading the same half-page of a book over and over and then letting your attention wander and picking up another book.}}", "alt": "Ugh, today's kids are forgetting the old-fashioned art of absentmindedly reading the same half-page of a book over and over and then letting your attention wander and picking up another book.", "img": "https://imgs.xkcd.com/comics/loop.png", "title": "Loop", "day": "22", "mirror_img": "https://raw.githubusercontent.com/aghontpi/mirror-xkcd-api/main/api/1411/loop.png"}
json
<filename>src/main/gen/io/github/stefansjs/flatbuffersplugin/parser/FlatbuffersParser.java // This is a generated file. Not intended for manual editing. package io.github.stefansjs.flatbuffersplugin.parser; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiBuilder.Marker; import static io.github.stefansjs.flatbuffersplugin.psi.FlatbuffersTypes.*; import static com.intellij.lang.parser.GeneratedParserUtilBase.*; import com.intellij.psi.tree.IElementType; import com.intellij.lang.ASTNode; import com.intellij.psi.tree.TokenSet; import com.intellij.lang.PsiParser; import com.intellij.lang.LightPsiParser; @SuppressWarnings({"SimplifiableIfStatement", "UnusedAssignment"}) public class FlatbuffersParser implements PsiParser, LightPsiParser { public ASTNode parse(IElementType t, PsiBuilder b) { parseLight(t, b); return b.getTreeBuilt(); } public void parseLight(IElementType t, PsiBuilder b) { boolean r; b = adapt_builder_(t, b, this, null); Marker m = enter_section_(b, 0, _COLLAPSE_, null); r = parse_root_(t, b); exit_section_(b, 0, m, t, r, true, TRUE_CONDITION); } protected boolean parse_root_(IElementType t, PsiBuilder b) { return parse_root_(t, b, 0); } static boolean parse_root_(IElementType t, PsiBuilder b, int l) { return schema(b, l + 1); } /* ********************************************************** */ // LBRACK (primitive | declared_type) RBRACK public static boolean array_type(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "array_type")) return false; if (!nextTokenIs(b, LBRACK)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, ARRAY_TYPE, null); r = consumeToken(b, LBRACK); p = r; // pin = 1 r = r && report_error_(b, array_type_1(b, l + 1)); r = p && consumeToken(b, RBRACK) && r; exit_section_(b, l, m, r, p, null); return r || p; } // primitive | declared_type private static boolean array_type_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "array_type_1")) return false; boolean r; r = primitive(b, l + 1); if (!r) r = declared_type(b, l + 1); return r; } /* ********************************************************** */ // ATTRIBUTE ( ident | string_constant ) SEMICOLON public static boolean attribute_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "attribute_decl")) return false; if (!nextTokenIs(b, ATTRIBUTE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, ATTRIBUTE_DECL, null); r = consumeToken(b, ATTRIBUTE); r = r && attribute_decl_1(b, l + 1); p = r; // pin = 2 r = r && consumeToken(b, SEMICOLON); exit_section_(b, l, m, r, p, null); return r || p; } // ident | string_constant private static boolean attribute_decl_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "attribute_decl_1")) return false; boolean r; r = ident(b, l + 1); if (!r) r = string_constant(b, l + 1); return r; } /* ********************************************************** */ // (TRUE|FALSE) | (integer_constant QUESTION_MARK TRUE COLON FALSE) public static boolean boolean_constant(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "boolean_constant")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, BOOLEAN_CONSTANT, "<boolean constant>"); r = boolean_constant_0(b, l + 1); if (!r) r = boolean_constant_1(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // TRUE|FALSE private static boolean boolean_constant_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "boolean_constant_0")) return false; boolean r; r = consumeToken(b, TRUE); if (!r) r = consumeToken(b, FALSE); return r; } // integer_constant QUESTION_MARK TRUE COLON FALSE private static boolean boolean_constant_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "boolean_constant_1")) return false; boolean r; Marker m = enter_section_(b); r = integer_constant(b, l + 1); r = r && consumeTokens(b, 0, QUESTION_MARK, TRUE, COLON, FALSE); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // enumval_decl ( COMMA enumval_decl )* COMMA? static boolean commasep_enumval_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "commasep_enumval_decl")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = enumval_decl(b, l + 1); r = r && commasep_enumval_decl_1(b, l + 1); r = r && commasep_enumval_decl_2(b, l + 1); exit_section_(b, m, null, r); return r; } // ( COMMA enumval_decl )* private static boolean commasep_enumval_decl_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "commasep_enumval_decl_1")) return false; while (true) { int c = current_position_(b); if (!commasep_enumval_decl_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "commasep_enumval_decl_1", c)) break; } return true; } // COMMA enumval_decl private static boolean commasep_enumval_decl_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "commasep_enumval_decl_1_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COMMA); r = r && enumval_decl(b, l + 1); exit_section_(b, m, null, r); return r; } // COMMA? private static boolean commasep_enumval_decl_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "commasep_enumval_decl_2")) return false; consumeToken(b, COMMA); return true; } /* ********************************************************** */ // unionval_decl ( COMMA unionval_decl )* COMMA? static boolean commasep_unionval_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "commasep_unionval_decl")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = unionval_decl(b, l + 1); r = r && commasep_unionval_decl_1(b, l + 1); r = r && commasep_unionval_decl_2(b, l + 1); exit_section_(b, m, null, r); return r; } // ( COMMA unionval_decl )* private static boolean commasep_unionval_decl_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "commasep_unionval_decl_1")) return false; while (true) { int c = current_position_(b); if (!commasep_unionval_decl_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "commasep_unionval_decl_1", c)) break; } return true; } // COMMA unionval_decl private static boolean commasep_unionval_decl_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "commasep_unionval_decl_1_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COMMA); r = r && unionval_decl(b, l + 1); exit_section_(b, m, null, r); return r; } // COMMA? private static boolean commasep_unionval_decl_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "commasep_unionval_decl_2")) return false; consumeToken(b, COMMA); return true; } /* ********************************************************** */ // ( value ( COMMA value )* )? static boolean commasep_value(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "commasep_value")) return false; commasep_value_0(b, l + 1); return true; } // value ( COMMA value )* private static boolean commasep_value_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "commasep_value_0")) return false; boolean r; Marker m = enter_section_(b); r = value(b, l + 1); r = r && commasep_value_0_1(b, l + 1); exit_section_(b, m, null, r); return r; } // ( COMMA value )* private static boolean commasep_value_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "commasep_value_0_1")) return false; while (true) { int c = current_position_(b); if (!commasep_value_0_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "commasep_value_0_1", c)) break; } return true; } // COMMA value private static boolean commasep_value_0_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "commasep_value_0_1_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COMMA); r = r && value(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // DEC_INTEGER public static boolean dec_integer_constant(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "dec_integer_constant")) return false; if (!nextTokenIs(b, DEC_INTEGER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, DEC_INTEGER); exit_section_(b, m, DEC_INTEGER_CONSTANT, r); return r; } /* ********************************************************** */ // DEC_FLOAT public static boolean decimal_float_constant(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "decimal_float_constant")) return false; if (!nextTokenIs(b, DEC_FLOAT)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, DEC_FLOAT); exit_section_(b, m, DECIMAL_FLOAT_CONSTANT, r); return r; } /* ********************************************************** */ // !decl_start static boolean decl_recover(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "decl_recover")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !decl_start(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // NAMESPACE // | TABLE // | STRUCT // | ENUM // | UNION // | ROOT_TYPE // | FILE_EXTENSION // | FILE_IDENTIFIER // | ATTRIBUTE // | RPC_SERVICE static boolean decl_start(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "decl_start")) return false; boolean r; r = consumeToken(b, NAMESPACE); if (!r) r = consumeToken(b, TABLE); if (!r) r = consumeToken(b, STRUCT); if (!r) r = consumeToken(b, ENUM); if (!r) r = consumeToken(b, UNION); if (!r) r = consumeToken(b, ROOT_TYPE); if (!r) r = consumeToken(b, FILE_EXTENSION); if (!r) r = consumeToken(b, FILE_IDENTIFIER); if (!r) r = consumeToken(b, ATTRIBUTE); if (!r) r = consumeToken(b, RPC_SERVICE); return r; } /* ********************************************************** */ // namespace_decl // | type_decl // | enum_decl // | union_decl // | root_decl // | file_extension_decl // | file_identifier_decl // | attribute_decl // | rpc_decl // | object public static boolean declaration(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "declaration")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, DECLARATION, "<declaration>"); r = namespace_decl(b, l + 1); if (!r) r = type_decl(b, l + 1); if (!r) r = enum_decl(b, l + 1); if (!r) r = union_decl(b, l + 1); if (!r) r = root_decl(b, l + 1); if (!r) r = file_extension_decl(b, l + 1); if (!r) r = file_identifier_decl(b, l + 1); if (!r) r = attribute_decl(b, l + 1); if (!r) r = rpc_decl(b, l + 1); if (!r) r = object(b, l + 1); exit_section_(b, l, m, r, false, FlatbuffersParser::decl_recover); return r; } /* ********************************************************** */ // ident public static boolean declared_name(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "declared_name")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = ident(b, l + 1); exit_section_(b, m, DECLARED_NAME, r); return r; } /* ********************************************************** */ // (ident DOT)* public static boolean declared_namespace(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "declared_namespace")) return false; Marker m = enter_section_(b, l, _NONE_, DECLARED_NAMESPACE, "<declared namespace>"); while (true) { int c = current_position_(b); if (!declared_namespace_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "declared_namespace", c)) break; } exit_section_(b, l, m, true, false, null); return true; } // ident DOT private static boolean declared_namespace_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "declared_namespace_0")) return false; boolean r; Marker m = enter_section_(b); r = ident(b, l + 1); r = r && consumeToken(b, DOT); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // declared_namespace declared_name public static boolean declared_type(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "declared_type")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, DECLARED_TYPE, "<declared type>"); r = declared_namespace(b, l + 1); p = r; // pin = 1 r = r && declared_name(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // DOCLINE* public static boolean documentation(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "documentation")) return false; Marker m = enter_section_(b, l, _NONE_, DOCUMENTATION, "<documentation>"); while (true) { int c = current_position_(b); if (!consumeToken(b, DOCLINE)) break; if (!empty_element_parsed_guard_(b, "documentation", c)) break; } exit_section_(b, l, m, true, false, null); return true; } /* ********************************************************** */ // documentation? ENUM type_name ( COLON primitive )? metadata? LCURLY commasep_enumval_decl? RCURLY public static boolean enum_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "enum_decl")) return false; if (!nextTokenIs(b, "<enum decl>", DOCLINE, ENUM)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, ENUM_DECL, "<enum decl>"); r = enum_decl_0(b, l + 1); r = r && consumeToken(b, ENUM); r = r && type_name(b, l + 1); p = r; // pin = type_name r = r && report_error_(b, enum_decl_3(b, l + 1)); r = p && report_error_(b, enum_decl_4(b, l + 1)) && r; r = p && report_error_(b, consumeToken(b, LCURLY)) && r; r = p && report_error_(b, enum_decl_6(b, l + 1)) && r; r = p && consumeToken(b, RCURLY) && r; exit_section_(b, l, m, r, p, null); return r || p; } // documentation? private static boolean enum_decl_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "enum_decl_0")) return false; documentation(b, l + 1); return true; } // ( COLON primitive )? private static boolean enum_decl_3(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "enum_decl_3")) return false; enum_decl_3_0(b, l + 1); return true; } // COLON primitive private static boolean enum_decl_3_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "enum_decl_3_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COLON); r = r && primitive(b, l + 1); exit_section_(b, m, null, r); return r; } // metadata? private static boolean enum_decl_4(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "enum_decl_4")) return false; metadata(b, l + 1); return true; } // commasep_enumval_decl? private static boolean enum_decl_6(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "enum_decl_6")) return false; commasep_enumval_decl(b, l + 1); return true; } /* ********************************************************** */ // ident ( EQUALS integer_constant )? public static boolean enumval_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "enumval_decl")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = ident(b, l + 1); r = r && enumval_decl_1(b, l + 1); exit_section_(b, m, ENUMVAL_DECL, r); return r; } // ( EQUALS integer_constant )? private static boolean enumval_decl_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "enumval_decl_1")) return false; enumval_decl_1_0(b, l + 1); return true; } // EQUALS integer_constant private static boolean enumval_decl_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "enumval_decl_1_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, EQUALS); r = r && integer_constant(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // field_ident COLON field_type ( EQUALS field_value )? metadata? SEMICOLON public static boolean field_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "field_decl")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, FIELD_DECL, "<field decl>"); r = field_ident(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, consumeToken(b, COLON)); r = p && report_error_(b, field_type(b, l + 1)) && r; r = p && report_error_(b, field_decl_3(b, l + 1)) && r; r = p && report_error_(b, field_decl_4(b, l + 1)) && r; r = p && consumeToken(b, SEMICOLON) && r; exit_section_(b, l, m, r, p, null); return r || p; } // ( EQUALS field_value )? private static boolean field_decl_3(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "field_decl_3")) return false; field_decl_3_0(b, l + 1); return true; } // EQUALS field_value private static boolean field_decl_3_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "field_decl_3_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, EQUALS); r = r && field_value(b, l + 1); exit_section_(b, m, null, r); return r; } // metadata? private static boolean field_decl_4(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "field_decl_4")) return false; metadata(b, l + 1); return true; } /* ********************************************************** */ // ident | keyword public static boolean field_ident(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "field_ident")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, FIELD_IDENT, "<field ident>"); r = ident(b, l + 1); if (!r) r = keyword(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // primitive // | array_type // | declared_type public static boolean field_type(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "field_type")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, FIELD_TYPE, "<field type>"); r = primitive(b, l + 1); if (!r) r = array_type(b, l + 1); if (!r) r = declared_type(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // ident | scalar public static boolean field_value(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "field_value")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, FIELD_VALUE, "<field value>"); r = ident(b, l + 1); if (!r) r = scalar(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // FILE_EXTENSION string_constant SEMICOLON public static boolean file_extension_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "file_extension_decl")) return false; if (!nextTokenIs(b, FILE_EXTENSION)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, FILE_EXTENSION); r = r && string_constant(b, l + 1); r = r && consumeToken(b, SEMICOLON); exit_section_(b, m, FILE_EXTENSION_DECL, r); return r; } /* ********************************************************** */ // FILE_IDENTIFIER string_constant SEMICOLON public static boolean file_identifier_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "file_identifier_decl")) return false; if (!nextTokenIs(b, FILE_IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, FILE_IDENTIFIER); r = r && string_constant(b, l + 1); r = r && consumeToken(b, SEMICOLON); exit_section_(b, m, FILE_IDENTIFIER_DECL, r); return r; } /* ********************************************************** */ // decimal_float_constant | hexadecimal_float_constant | special_float_constant public static boolean float_constant(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "float_constant")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, FLOAT_CONSTANT, "<float constant>"); r = decimal_float_constant(b, l + 1); if (!r) r = hexadecimal_float_constant(b, l + 1); if (!r) r = special_float_constant(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // float // | double // | float32 // | float64 static boolean float_type(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "float_type")) return false; boolean r; r = consumeToken(b, FLOAT); if (!r) r = consumeToken(b, DOUBLE); if (!r) r = consumeToken(b, FLOAT32); if (!r) r = consumeToken(b, FLOAT64); return r; } /* ********************************************************** */ // HEX_INTEGER public static boolean hex_integer_constant(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "hex_integer_constant")) return false; if (!nextTokenIs(b, HEX_INTEGER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, HEX_INTEGER); exit_section_(b, m, HEX_INTEGER_CONSTANT, r); return r; } /* ********************************************************** */ // HEX_FLOAT public static boolean hexadecimal_float_constant(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "hexadecimal_float_constant")) return false; if (!nextTokenIs(b, HEX_FLOAT)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, HEX_FLOAT); exit_section_(b, m, HEXADECIMAL_FLOAT_CONSTANT, r); return r; } /* ********************************************************** */ // IDENTIFIER public static boolean ident(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ident")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, IDENTIFIER); exit_section_(b, m, IDENT, r); return r; } /* ********************************************************** */ // (INCLUDE | IMPORT) string_constant SEMICOLON public static boolean incl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "incl")) return false; if (!nextTokenIs(b, "<incl>", IMPORT, INCLUDE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, INCL, "<incl>"); r = incl_0(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, string_constant(b, l + 1)); r = p && consumeToken(b, SEMICOLON) && r; exit_section_(b, l, m, r, p, null); return r || p; } // INCLUDE | IMPORT private static boolean incl_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "incl_0")) return false; boolean r; r = consumeToken(b, INCLUDE); if (!r) r = consumeToken(b, IMPORT); return r; } /* ********************************************************** */ // bool // | byte // | ubyte // | short // | ushort // | int // | uint // | long // | ulong // | int8 // | uint8 // | int16 // | uint16 // | int32 // | uint32 // | int64 // | uint64 static boolean int_type(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "int_type")) return false; boolean r; r = consumeToken(b, BOOL); if (!r) r = consumeToken(b, BYTE); if (!r) r = consumeToken(b, UBYTE); if (!r) r = consumeToken(b, SHORT); if (!r) r = consumeToken(b, USHORT); if (!r) r = consumeToken(b, INT); if (!r) r = consumeToken(b, UINT); if (!r) r = consumeToken(b, LONG); if (!r) r = consumeToken(b, ULONG); if (!r) r = consumeToken(b, INT8); if (!r) r = consumeToken(b, UINT8); if (!r) r = consumeToken(b, INT16); if (!r) r = consumeToken(b, UINT16); if (!r) r = consumeToken(b, INT32); if (!r) r = consumeToken(b, UINT32); if (!r) r = consumeToken(b, INT64); if (!r) r = consumeToken(b, UINT64); return r; } /* ********************************************************** */ // dec_integer_constant | hex_integer_constant public static boolean integer_constant(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "integer_constant")) return false; if (!nextTokenIs(b, "<integer constant>", DEC_INTEGER, HEX_INTEGER)) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, INTEGER_CONSTANT, "<integer constant>"); r = dec_integer_constant(b, l + 1); if (!r) r = hex_integer_constant(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // primitive // | TABLE // | STRUCT static boolean keyword(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "keyword")) return false; boolean r; r = primitive(b, l + 1); if (!r) r = consumeToken(b, TABLE); if (!r) r = consumeToken(b, STRUCT); return r; } /* ********************************************************** */ // LPAREN metadata_value ( COMMA metadata_value )* RPAREN public static boolean metadata(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "metadata")) return false; if (!nextTokenIs(b, LPAREN)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, LPAREN); r = r && metadata_value(b, l + 1); r = r && metadata_2(b, l + 1); r = r && consumeToken(b, RPAREN); exit_section_(b, m, METADATA, r); return r; } // ( COMMA metadata_value )* private static boolean metadata_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "metadata_2")) return false; while (true) { int c = current_position_(b); if (!metadata_2_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "metadata_2", c)) break; } return true; } // COMMA metadata_value private static boolean metadata_2_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "metadata_2_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COMMA); r = r && metadata_value(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // ident ( COLON single_value )? static boolean metadata_value(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "metadata_value")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = ident(b, l + 1); r = r && metadata_value_1(b, l + 1); exit_section_(b, m, null, r); return r; } // ( COLON single_value )? private static boolean metadata_value_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "metadata_value_1")) return false; metadata_value_1_0(b, l + 1); return true; } // COLON single_value private static boolean metadata_value_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "metadata_value_1_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COLON); r = r && single_value(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // NAMESPACE ident ( DOT ident )* SEMICOLON public static boolean namespace_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "namespace_decl")) return false; if (!nextTokenIs(b, NAMESPACE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, NAMESPACE_DECL, null); r = consumeToken(b, NAMESPACE); r = r && ident(b, l + 1); p = r; // pin = 2 r = r && report_error_(b, namespace_decl_2(b, l + 1)); r = p && consumeToken(b, SEMICOLON) && r; exit_section_(b, l, m, r, p, null); return r || p; } // ( DOT ident )* private static boolean namespace_decl_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "namespace_decl_2")) return false; while (true) { int c = current_position_(b); if (!namespace_decl_2_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "namespace_decl_2", c)) break; } return true; } // DOT ident private static boolean namespace_decl_2_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "namespace_decl_2_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, DOT); r = r && ident(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // NATIVE_INCLUDE string_constant SEMICOLON public static boolean native_incl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "native_incl")) return false; if (!nextTokenIs(b, NATIVE_INCLUDE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, NATIVE_INCL, null); r = consumeToken(b, NATIVE_INCLUDE); p = r; // pin = NATIVE_INCLUDE r = r && report_error_(b, string_constant(b, l + 1)); r = p && consumeToken(b, SEMICOLON) && r; exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // object_value ( COMMA object_value )* public static boolean object(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "object")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = object_value(b, l + 1); r = r && object_1(b, l + 1); exit_section_(b, m, OBJECT, r); return r; } // ( COMMA object_value )* private static boolean object_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "object_1")) return false; while (true) { int c = current_position_(b); if (!object_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "object_1", c)) break; } return true; } // COMMA object_value private static boolean object_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "object_1_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COMMA); r = r && object_value(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // ident COLON value static boolean object_value(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "object_value")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = ident(b, l + 1); r = r && consumeToken(b, COLON); r = r && value(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // incl // | native_incl static boolean pre_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "pre_decl")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_); r = incl(b, l + 1); if (!r) r = native_incl(b, l + 1); exit_section_(b, l, m, r, false, FlatbuffersParser::pre_decl_recover); return r; } /* ********************************************************** */ static boolean pre_decl_error(PsiBuilder b, int l) { Marker m = enter_section_(b, l, _NONE_); exit_section_(b, l, m, true, false, FlatbuffersParser::pre_decl_recover); return true; } /* ********************************************************** */ // !(pre_decl_start | decl_start) static boolean pre_decl_recover(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "pre_decl_recover")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !pre_decl_recover_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // pre_decl_start | decl_start private static boolean pre_decl_recover_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "pre_decl_recover_0")) return false; boolean r; r = pre_decl_start(b, l + 1); if (!r) r = decl_start(b, l + 1); return r; } /* ********************************************************** */ // INCLUDE | IMPORT | NATIVE_INCLUDE static boolean pre_decl_start(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "pre_decl_start")) return false; boolean r; r = consumeToken(b, INCLUDE); if (!r) r = consumeToken(b, IMPORT); if (!r) r = consumeToken(b, NATIVE_INCLUDE); return r; } /* ********************************************************** */ // int_type | float_type | string public static boolean primitive(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "primitive")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, PRIMITIVE, "<primitive>"); r = int_type(b, l + 1); if (!r) r = float_type(b, l + 1); if (!r) r = consumeToken(b, STRING); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // ROOT_TYPE declared_type SEMICOLON public static boolean root_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "root_decl")) return false; if (!nextTokenIs(b, ROOT_TYPE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, ROOT_DECL, null); r = consumeToken(b, ROOT_TYPE); r = r && declared_type(b, l + 1); p = r; // pin = declared_type r = r && consumeToken(b, SEMICOLON); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // RPC_SERVICE ident LCURLY rpc_method+ RCURLY public static boolean rpc_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "rpc_decl")) return false; if (!nextTokenIs(b, RPC_SERVICE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, RPC_DECL, null); r = consumeToken(b, RPC_SERVICE); r = r && ident(b, l + 1); p = r; // pin = ident r = r && report_error_(b, consumeToken(b, LCURLY)); r = p && report_error_(b, rpc_decl_3(b, l + 1)) && r; r = p && consumeToken(b, RCURLY) && r; exit_section_(b, l, m, r, p, null); return r || p; } // rpc_method+ private static boolean rpc_decl_3(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "rpc_decl_3")) return false; boolean r; Marker m = enter_section_(b); r = rpc_method(b, l + 1); while (r) { int c = current_position_(b); if (!rpc_method(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "rpc_decl_3", c)) break; } exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // ident LPAREN ident RPAREN COLON ident metadata? SEMICOLON public static boolean rpc_method(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "rpc_method")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = ident(b, l + 1); r = r && consumeToken(b, LPAREN); r = r && ident(b, l + 1); r = r && consumeTokens(b, 0, RPAREN, COLON); r = r && ident(b, l + 1); r = r && rpc_method_6(b, l + 1); r = r && consumeToken(b, SEMICOLON); exit_section_(b, m, RPC_METHOD, r); return r; } // metadata? private static boolean rpc_method_6(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "rpc_method_6")) return false; metadata(b, l + 1); return true; } /* ********************************************************** */ // integer_constant | float_constant | boolean_constant public static boolean scalar(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "scalar")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, SCALAR, "<scalar>"); r = integer_constant(b, l + 1); if (!r) r = float_constant(b, l + 1); if (!r) r = boolean_constant(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // pre_decl_error? pre_decl* declaration* static boolean schema(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "schema")) return false; boolean r; Marker m = enter_section_(b); r = schema_0(b, l + 1); r = r && schema_1(b, l + 1); r = r && schema_2(b, l + 1); exit_section_(b, m, null, r); return r; } // pre_decl_error? private static boolean schema_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "schema_0")) return false; pre_decl_error(b, l + 1); return true; } // pre_decl* private static boolean schema_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "schema_1")) return false; while (true) { int c = current_position_(b); if (!pre_decl(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "schema_1", c)) break; } return true; } // declaration* private static boolean schema_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "schema_2")) return false; while (true) { int c = current_position_(b); if (!declaration(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "schema_2", c)) break; } return true; } /* ********************************************************** */ // scalar | string_constant public static boolean single_value(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "single_value")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, SINGLE_VALUE, "<single value>"); r = scalar(b, l + 1); if (!r) r = string_constant(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // SPECIAL_FLOAT public static boolean special_float_constant(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "special_float_constant")) return false; if (!nextTokenIs(b, SPECIAL_FLOAT)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, SPECIAL_FLOAT); exit_section_(b, m, SPECIAL_FLOAT_CONSTANT, r); return r; } /* ********************************************************** */ // STRING_LITERAL public static boolean string_constant(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "string_constant")) return false; if (!nextTokenIs(b, STRING_LITERAL)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, STRING_LITERAL); exit_section_(b, m, STRING_CONSTANT, r); return r; } /* ********************************************************** */ // ( TABLE | STRUCT ) type_name metadata? LCURLY field_decl* RCURLY public static boolean type_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "type_decl")) return false; if (!nextTokenIs(b, "<type decl>", STRUCT, TABLE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, TYPE_DECL, "<type decl>"); r = type_decl_0(b, l + 1); r = r && type_name(b, l + 1); p = r; // pin = type_name r = r && report_error_(b, type_decl_2(b, l + 1)); r = p && report_error_(b, consumeToken(b, LCURLY)) && r; r = p && report_error_(b, type_decl_4(b, l + 1)) && r; r = p && consumeToken(b, RCURLY) && r; exit_section_(b, l, m, r, p, null); return r || p; } // TABLE | STRUCT private static boolean type_decl_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "type_decl_0")) return false; boolean r; r = consumeToken(b, TABLE); if (!r) r = consumeToken(b, STRUCT); return r; } // metadata? private static boolean type_decl_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "type_decl_2")) return false; metadata(b, l + 1); return true; } // field_decl* private static boolean type_decl_4(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "type_decl_4")) return false; while (true) { int c = current_position_(b); if (!field_decl(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "type_decl_4", c)) break; } return true; } /* ********************************************************** */ // ident public static boolean type_name(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "type_name")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = ident(b, l + 1); exit_section_(b, m, TYPE_NAME, r); return r; } /* ********************************************************** */ // documentation? union type_name LCURLY commasep_unionval_decl? RCURLY public static boolean union_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "union_decl")) return false; if (!nextTokenIs(b, "<union decl>", DOCLINE, UNION)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, UNION_DECL, "<union decl>"); r = union_decl_0(b, l + 1); r = r && consumeToken(b, UNION); r = r && type_name(b, l + 1); p = r; // pin = type_name r = r && report_error_(b, consumeToken(b, LCURLY)); r = p && report_error_(b, union_decl_4(b, l + 1)) && r; r = p && consumeToken(b, RCURLY) && r; exit_section_(b, l, m, r, p, null); return r || p; } // documentation? private static boolean union_decl_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "union_decl_0")) return false; documentation(b, l + 1); return true; } // commasep_unionval_decl? private static boolean union_decl_4(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "union_decl_4")) return false; commasep_unionval_decl(b, l + 1); return true; } /* ********************************************************** */ // ( ident COLON )? declared_namespace declared_name public static boolean unionval_decl(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "unionval_decl")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = unionval_decl_0(b, l + 1); r = r && declared_namespace(b, l + 1); r = r && declared_name(b, l + 1); exit_section_(b, m, UNIONVAL_DECL, r); return r; } // ( ident COLON )? private static boolean unionval_decl_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "unionval_decl_0")) return false; unionval_decl_0_0(b, l + 1); return true; } // ident COLON private static boolean unionval_decl_0_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "unionval_decl_0_0")) return false; boolean r; Marker m = enter_section_(b); r = ident(b, l + 1); r = r && consumeToken(b, COLON); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // single_value | object | LBRACK commasep_value RBRACK public static boolean value(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "value")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, VALUE, "<value>"); r = single_value(b, l + 1); if (!r) r = object(b, l + 1); if (!r) r = value_2(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // LBRACK commasep_value RBRACK private static boolean value_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "value_2")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, LBRACK); r = r && commasep_value(b, l + 1); r = r && consumeToken(b, RBRACK); exit_section_(b, m, null, r); return r; } }
java
[TOC] ## Redis ### 一、介绍 ### 二、常用命令 1、获取最大允许连接数 ```shell config get maxclients ``` 2、获取当前连接情况 ```shell info clients ``` 3、杀死指定连接 ```shell CLIENT KILL ip:port ``` 4、从服务器变为主服务器 ```shell SLAVEOF NO ONE ``` 5、scan实现模糊查询 > - SCAN相关命令包括SSCAN 命令、HSCAN 命令和 ZSCAN 命令,分别用于集合、哈希键及有续集等 > 命令格式: ```shell SCAN cursor [MATCH pattern] [COUNT count] ``` 命令解释:scan 游标 MATCH <返回和给定模式相匹配的元素> count 每次迭代所返回的元素数量 > SCAN命令是增量的循环,每次调用只会返回一小部分的元素。所以不会有KEYS命令的坑(key的数量比较多,一次KEYS查询会block其他操作)。 > SCAN命令返回的是一个游标,从0开始遍历,到0结束遍历。 > 通过scan中的MATCH <pattern> 参数,可以让命令只返回和给定模式相匹配的元素,实现模糊查询的效果 例如: ```shell 示例: scan 0 match DL* count 5 sscan myset 0 match f* ``` 注意:游标的值,其实就是查出来结果的number号 ### 三、使用 - **1、哨兵模式下,如果通过哨兵查询主从服务器?** 使用 sentinel masters 命令列出主服务器信息 > 备注:以下列出的是 Sentinel 接受的命令: > > - PING :返回 PONG 。 > - sentinel masters :列出所有被监视的主服务器,以及这些主服务器的当前状态。 > - sentinel slaves :列出给定主服务器的所有从服务器,以及这些从服务器的当前状态。 > - sentinel get-master-addr-by-name : 返回给定名字的主服务器的 IP 地址和端口号。 如果这个主服务器正在执行故障转移操作, 或者针对这个主服务器的故障转移操作已经完成, 那么这个命令返回新的主服务器的 IP 地址和端口号。 > - sentinel reset : 重置所有名字和给定模式 pattern 相匹配的主服务器。 pattern 参数是一个 Glob 风格的模式。 重置操作清楚主服务器目前的所有状态, 包括正在执行中的故障转移, 并移除目前已经发现和关联的, 主服务器的所有从服务器和 Sentinel 。 > - sentinel failover : 当主服务器失效时, 在不询问其他 Sentinel 意见的情况下, 强制开始一次自动故障迁移 (不过发起故障转移的 Sentinel 会向其他 Sentinel 发送一个新的配置,其他 Sentinel 会根据这个配置进行相应的更新)。 ## Redis的Java客户端 Jedis、Lettuce 和 Redisson **1. Jedis** Jedis 是老牌的 Redis 的 Java 实现客户端,提供了比较全面的 Redis 命令的支持,其官方网址是:http://tool.oschina.net/uploads/apidocs/redis/clients/jedis/Jedis.html。 优点: - 支持全面的 Redis 操作特性(可以理解为API比较全面)。 缺点: - 使用阻塞的 I/O,且其方法调用都是同步的,程序流需要等到 sockets 处理完 I/O 才能执行,不支持异步; - Jedis 客户端实例不是线程安全的,所以需要通过连接池来使用 Jedis。 **2. lettuce** lettuce ([ˈletɪs]),是一种可扩展的线程安全的 Redis 客户端,支持异步模式。如果避免阻塞和事务操作,如BLPOP和MULTI/EXEC,多个线程就可以共享一个连接。lettuce 底层基于 Netty,支持高级的 Redis 特性,比如哨兵,集群,管道,自动重新连接和Redis数据模型。lettuce 的官网地址是:https://lettuce.io/ 优点: - 支持同步异步通信模式; - Lettuce 的 API 是线程安全的,如果不是执行阻塞和事务操作,如BLPOP和MULTI/EXEC,多个线程就可以共享一个连接。 **3. Redisson** Redisson 是一个在 Redis 的基础上实现的 Java 驻内存数据网格(In-Memory Data Grid)。它不仅提供了一系列的分布式的 Java 常用对象,还提供了许多分布式服务。其中包括( BitSet, Set, Multimap, SortedSet, Map, List, Queue, BlockingQueue, Deque, BlockingDeque, Semaphore, Lock, AtomicLong, CountDownLatch, Publish / Subscribe, Bloom filter, Remote service, Spring cache, Executor service, Live Object service, Scheduler service) Redisson 提供了使用Redis 的最简单和最便捷的方法。Redisson 的宗旨是促进使用者对Redis的关注分离(Separation of Concern),从而让使用者能够将精力更集中地放在处理业务逻辑上。Redisson的官方网址是:https://redisson.org/ 优点: - 使用者对 Redis 的关注分离,可以类比 Spring 框架,这些框架搭建了应用程序的基础框架和功能,提升开发效率,让开发者有更多的时间来关注业务逻辑; - 提供很多分布式相关操作服务,例如,分布式锁,分布式集合,可通过Redis支持延迟队列等。 缺点: - Redisson 对字符串的操作支持比较差。 **4. 使用建议** 结论:lettuce + Redisson Jedis 和 lettuce 是比较纯粹的 Redis 客户端,几乎没提供什么高级功能。Jedis 的性能比较差,所以如果你不需要使用 Redis 的高级功能的话,优先推荐使用 lettuce。 Redisson 的优势是提供了很多开箱即用的 Redis 高级功能,如果你的应用中需要使用到 Redis 的高级功能,建议使用 Redisson。具体 Redisson 的高级功能可以参考:https://redisson.org/
markdown
<filename>cmd/goplumber/main.go /* Apache v2 license * Copyright (C) <2019> Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ package main import ( "context" "encoding/json" "flag" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "github.com/intel/rsp-sw-toolkit-im-suite-goplumber" "io/ioutil" "os" "os/signal" "time" ) func main() { conf := flag.String("config", "plumber.json", "configuration file") flag.Parse() data, err := ioutil.ReadFile(*conf) if err != nil { log.Fatal(err) } pc := PlumberConfig{} if err := json.Unmarshal(data, &pc); err != nil { log.Fatal(err) } ctx, cncl := context.WithCancel(context.Background()) defer cncl() if err := loadPipelines(ctx, pc); err != nil { log.Fatal(err) } stop := make(chan os.Signal, 1) signal.Notify(stop, os.Interrupt) <-stop log.Debug("Received shutdown; canceling pipelines.") } type PlumberConfig struct { ConfigDir string MQTTConfigFile string CustomTasks []string PipelineNames []string } func loadPipelines(ctx context.Context, config PlumberConfig) error { log.Debug("Starting pipelines.") plumber := goplumber.NewPlumber() loader := goplumber.NewFileSystem(config.ConfigDir) plumber.SetTemplateSource("template", loader) plumber.SetSource("secret", loader) plumber.SetSink("saveFile", loader) kvData := goplumber.NewMemoryStore() plumber.SetSource("get", kvData) plumber.SetSink("put", kvData) mqttData, err := loader.GetFile(config.MQTTConfigFile) if err != nil { return err } mqc := goplumber.MQTTClient{} if err := json.Unmarshal(mqttData, &mqc); err != nil { return errors.Wrap(err, "failed to unmarshal MQTT client") } plumber.SetSink("mqtt", &mqc) log.Debug("Loading custom task types from pipelines.") for _, name := range config.CustomTasks { data, err := loader.GetFile(name) if err != nil { return err } var pConf goplumber.PipelineConfig if err := json.Unmarshal(data, &pConf); err != nil { return errors.Wrapf(err, "failed to unmarshal %s", name) } taskType, err := plumber.NewPipeline(&pConf) if err != nil { return errors.Wrapf(err, "failed to load %s", name) } client, err := goplumber.NewTaskType(taskType) if err != nil { return errors.Wrapf(err, "failed to create client for %s", name) } plumber.SetClient(pConf.Name, client) } // only load the configured names log.Debug("Loading pipelines.") pipelines := map[*goplumber.Pipeline]time.Duration{} for _, name := range config.PipelineNames { data, err := loader.GetFile(name) if err != nil { return errors.Wrapf(err, "failed to pipeline %s", name) } var pipelineConf goplumber.PipelineConfig if err := json.Unmarshal(data, &pipelineConf); err != nil { return errors.Wrapf(err, "failed to unmarshal %s", name) } p, err := plumber.NewPipeline(&pipelineConf) if err != nil { return errors.Wrapf(err, "failed to load %s", name) } pipelines[p] = pipelineConf.Trigger.Interval.Duration() } log.Debug("Running pipelines.") for p, d := range pipelines { if d > 0 { goplumber.RunPipelineForever(ctx, p, d) } else { go goplumber.RunNow(ctx, p) } } return nil }
go
east India, including the regions of eastern Uttar Pradesh and northern and southern Bihar, has about 100 cm of rainfall, Before those areas came to be colonized on a large scale, they were thickly forested. The thick jungles could not be cleared without the aid of iron axes. Although some people lived in this area before 600 B.C, they used implements of stone and copper, and they led a precarious life on river banks and confluences, where land was opened to settlement through the PUNCIL MARKEDE SILVER 9.1 Punch-marked Coins TI IL A process of erosion and flooding In the middle Gangetic basın large-scale habitations began from about 600 B.C, when iron came to be used in this area. On account of the moist nature of the soil in this area too many iron tools of earliest times have not survived, but quite a few axes have been recovered from the layers belonging to circa 600-500 B.C The use of iron tools made possible clearance, agriculture and large settlements. The agricultural economy based on the iron ploughshare required the use of bullocks, and it could not flourish without animal husbandry. But the Vedic practice of killing cattle indiscriminately in sacrifices stood in the way of the progress of new agriculture. The cattle wealth slowly decimated because the cows and bullocks were killed in numerous Vedic sacrifices. The tribal people living on the southern and eastern fringes of Magadha also killed battle for food. But if the new agrarian economy had to be stable this killing had to be stopped. The period saw the rise of a large number of cities in north-eastern India. We may refer, for example, to Kausambı near Allahabad, Kusinagar (in the Deoria district of Uttar Pradesh), Banaras, Vaisalı (in the newly created district of the same name in north Bihar), Chirand (in the Chapra district) and Rajgır (situated at a distance of about 100 km from Patna). Besides others these cities had many artisans and traders, who began to use coins for the first time. The earliest coins belonged to the fifth century B.C., and they are called punch-marked coins. They circulated for the first time in eastern Uttar Pradesh and Bihat. The use of coins naturally facilitated trade and commerce, which added to the importance of the vaisyas. In the brahmanical society the vaisyas ranked third, the first two being brahmanas and kshatriyas Naturally they looked for some religion which would improve their position. The vaisyas extended generous support to both Mahavira and Gautama Buddha. The merchants, called the setthis, made handsome gifts to Gautama Buddha and his disciples. There were several reasons for it First, Jainism and Buddhism in the initial stage did not attach any importance to the existing varna system Second, they preached the gospel of non-violence, which would put an end to wars between different kingdoms and consequently promote trade and commerce. Third, the brahmanical law-books, called the Dharmasutras, decried lending money on interest. A person who lived on interest was condemned by them Therefore the vaisyas, who lent money on account of growing trade and commerce, were not held investeem and were eager to improve their social status. On the other hand we also notice a strong reaction against various forms of private property Old-fashioned people did not like the use and accumulation coins made certainly of silver and copper and possibly of gold. They' detested new dwellings and dresses, new systems of transport which amounted to luxury, and they hated war and violence The new forms of property created social inequalities, and caused misery and suffering to the masses of the people So the common people yearned to return to primitive life. They wanted to get back to the ascetic ideal which dispensed with the new forms of property and the new style of life. Both Jainism and Buddhism preferred simple, puritan, ascetic living. The Buddhist and Jaina monks were asked to forgo the good things of life. They were not allowed to touch gold and silver. They were to accept only as much from their patrons as was sufficient to keep body and soul together. They therefore rebelled against the material advantages stemming from the new life in the Gangetic basin. In other words we find the same kind of reaction against the changes in material life in north-eastern India in the sixth century B.C. as we notice against the changes introduced by the Industrial Revolution in modern times. Just as the advent of Industrial Revolution made many people think of return to the pre-machine age life, similarly people in the past wanted to return to the preiron age life. Vardhamana Mahavira and Jainism Vardhamana Mahavira was born in 540 B.C. in a village near Vaısali, which is identical with Basarh in the district of Vaisalı in north Bihar. His father was the head of a famous kshatriya clan, and his mother a Lichchhavi princess. They were also connected with the royal family of Magadha. High connections made it easy for Mahavira to approach princes and nobles in the course of his mission. In the beginning Mahavira led the life of a householder, but in the search for truth he abandõned the world at the age of 30 and became an ascetic He kept on wandering for 12 years from place to place He would not stay for more than a day in a village and for more than five days in a town. During the course of his long journey, it is said, he never changed his clothes for, 12 years, and abandoned them altogether when he attained perfect knowledge or kaivalya at the age of 42. Through kaivalya he conquered misery and happiness Because of this conquest he is known as Mahavira or the great hero or jina, i e., the conqueror, and his followers are known as Jainas He propagated his religion for 30 years, and his mission took him to Kosala, Magadha, Mithila, Champa, etc. He passed away at the age of 72 in 468 B C at a place called Pavapuri near modern Rajgir. Doctrines of Jainism Jainism taught five doctrines (1) do not commit violence, (2) do not speak a lie, (3) do not steal, (4) do not acquire property and (5) observe continence (brahmacharya). It is said that only the fifth doctrine was added by Mahavira, the other four being taken over by him from previous teachers Although Parsva, the predecessor of Mahavira, had asked his followJAINISM AND BUDDHISM ers to cover the upper and lower portions of their body, Mahavira asked them to discard clothes completely. This implies that Mahavira asked his followers to lead a more austere life On account of this in later times Jainism was divided into two sects: svetambaras or those who put on white dress, and digambaras or those who keep themselves naked Jainism recognized the existence of the gods but placed them lower than the jina It did not condemn the vaina system, as Buddhism did. According to Mahavira, a person is born in a high or in a lower varna in consequence of the sins or the virtues acquired by him in the previous birth Mahavira looks for human values even in a chandala. In his opinion through pure and meritorious life members of the lower castes can attain liberation. Jainism mainly aims at the attainment of freedom from worldly bonds. It is not necessary to use any ritual for acquiring such liberation. It can be obtained through full knowledge and action. Full knowledge, action and liberation are considered to be the three gems or ratnas of Jainism Spread of Jainism In order to spread the teachings of Jainism, Mahavira organized an order of his followers which admitted both men and women It is said that his followers counted 14,000, which is not a large number Since Jainism did not very clearly mark itself out from the brahmanical religion, it failed to attract the masses. Despite this Jainism gradually spread into south and west India According to a late tradition, the spread of Jainism in Karnataka is attributed to Chandragupta Maurya (322-298 B.C.). The emperor became a Jaina, gave up his throne and spent the last years of his life in Karnataka as a Jaina ascetic. But this tradition is not corroborated by any other source. The second cause of the spread of Jainism in south India is said to be the great famine that took place in Magadha 200 years after the death of Mahavira. The famine lasted for 12 years, and so in order to protect themselves many a Jaina went to the south under the leadership of Bhadrabahu, but the rest of them stayed back in Magadha under the leadership of Sthalabahu. The immigrant Jainas spread Jainism in south India At the end of the famine they came back to Magadha, where they developed differences with the local Jainas. Those who came back from the south claimed that even during the famine they strictly observed the religious rules, on the other hand, they alleged, the Jaina ascetics living in Magadha had violated those rules and become lax. In order to sort out these differences and to compile the main teachings of Jainism a council was convened in Pataliputra, modern Patna, but the, southern Jainas boycotted the council and refused to accept its decisions. From now onwards the southerners began to be called digambaras, and the Magadhans svetambaras. However, epigraphic evidence for the spread of Jainism in Karnataka is not earlier than the third century A.D. In subsequent centuries, especially from the sixth century, numerous Jaina monastic establishments called basadis sprang up in Karnataka and were granted land by the kings for their support Jainism spread to Kalınga in Orissa in the fourth century B.C., and in the first century B Ç. it enjoyed the patronage of the Kalinga king Kharavela who had defeated the princes of Andhra and Magadha. In the second and first centuries B.C it also seems to have reached the southern districts of Tamil Nadu. In later centuries Jainism penetrated Malwa, Gujarat and Rajasthan, and even now these areas have a good number of Jainas, mainly engaged in trade and commerce. Although Jainism did not win as much state patronage as Buddhism did and did not spread very fast in early times, it still retains its hold in the areas where it spread. On the other hand Buddhism has practically disappeared from the Indian subcontinent, Contribution of Jainism Jainism made the first serious attempt to mitigate the evils of the varna oider and the ritualistic Vedic religion The early Jainas discarded Sanskrit language mainly patronized by the brahmanas. They adopted Prakrit language of the common people to preach their doctrines Their religious literature was written in Ardhamagadhi, and the texts were finally compiled in the sixth century A.D in Gujarat at a place called Valabhi, a great centre of education. The adoption of Prakrit by the Jainas helped the growth of this language and its literature Many regional languages developed out of Prakrit languages, particulaily Sauraseni, out of which grew the Marathi language The Jainas composed the earliest important works in Apabhramsa and its first grammai. The Jauna literature contains epics, Puranas, novels and drama. A large portion of the Jaina writing is still in the form of manuscripts, which have not been published and which are found in the Jaina shrines of Gujarat and Rajasthan In . carly medieval times the Jatnas also made good use of Sanskrit and wrote many texts in this language Last but not the least, they contributed to the growth of Kannada, in which they wrote extensively. Gautama Buddha and Buddhism Gautama Buddha or Siddhartha was a contemporary of Mahavira. He was born in 563 B,C in a Sakya kshatriya family ın Kapılavastu, which is situated in the foothills of Nepal. Gautama's father seems to have been the elected ruler of Kapilavastu, and headed the republican clan of the Sakyas. His mother was a princess from the Kosalan dynasty. Thus, like Mahavira, Gautama also belonged to a noble family. Born in a republic, he also inherited some republican sentiments. From his early childhood Gautama showed a meditative bent of mind. He was married early, but married life did not interest him. He was moved by the misery which people suffered in the world, and looked for solution. At the age of 29, lıke Mahavira again, he left home. He kept on wandering for about seven years and then attained knowledge at the age of 35 at Bodh Gaya under a pipal tree. From this time onwards he began to be called the Buddha or the enlightened. Gautama Buddha delivered his first sermons at Sarnath in Banaras. He undertook long Journeys and took his message far and wide. He had a very strong physique. which enabled him to walk 20 to 30 km a day He kept on wandering, preaching and meditating continuously for 40 years, resting only in the rainy season every year During this long period he encountered many staunch supporters of rival sects including the brahmanas, but defeated them in debates. His missionary activities did not discriminate between the rich and the poor, the high and the low, and man and woman. Gautama Buddha passed away at the age of 80 in 483 B.C. at a place called Kusinagar, identical with the village called Kasia in the district of Deoria in eastern Uttar Pradesh. Doctrines of Buddhism The Buddha proved to be a practical reformer who took note of the realities of the day. He did not involve himself in fruitless controversies regarding the soul (atman) and the Brahma which raged strongly in his time; he addressed himself to the worldly problems He said that the world is full of sorrows and people suffer on account of desires. If desires are conquered, nirvana will be attained, that is, man will be free from the cycle of birth and death. Gautama Buddha recommended an eightfold path (astangika marga) for the elimination of human misery. This path is attributed to him in a text of about the third century B.C. It comprised right observation, right determination, right speech. right action, right livelihood, right exercise, right memory and right medita-, tion. If a person follows this eightfold path he would not depend on the machinations of the priests, and yet he will be able to reach his destination Gautama taught that a person should avoid the excess of both luxury and austerity. He prescribed the middle path. The Buddha also laid down a code of conduct for his followers on the same lines as was done by the Jaina teachers. The main items in this social conduct are (1) do not covet the property of others, (2) do not commit violence, (3) do not use intoxicants, (4) do not speak a lie, and (5) do not indulge in corrupt practices. These teachings are common to the social conduct ordained by almost all religions. Special Features of Buddhism and the Causes of its Spread Buddhism does not recognize the existence of god and soul (atman). This can be taken as a kind of revolution in the history of Indian religions. Since early Buddhism was not enmeshed in the clap-trap of philosophical discussion, it appealed to the common people. It particularly won the support of the lower orders as it attacked the varna system People were taken into the Buddhist order without any consideration of caste. Women also were admitted to the sangha and thus brought on a par with men. In comparison with brahmanism, Buddhism was liberal and democratic Buddhism made a special appeal to the people of the non-Vedic areas where it found a virgin soil for conversion. The people of Magadha responded readily to Buddhism because they were looked down upon by the orthodox brahmanas. Magadha was placed outside the pale of the holy Aryavarata, the land of the Aryas, covering modern Uttar Pradesh The old tradition persists, and the people of north Bihar would not like to be cremated south of the Ganga in Magadha. The personality of the Buddha and the method adopted by him to preach his religion helped the spread of Buddhism. He tried to fight evil by goodness and hatred by love He refused to be provoked by slander and abuse. He maintained poise and calm under difficult conditions, and tackled his opponents with wit and presence of mind. It is said that on one occasion an ignorant person abused him The Buddha listened on silently, and when the purson had stopped abusing, the Buddha asked: "My son, if a person does not accept a present what will happen to it?" His adversary replied. "It remains with the person who has offered it." The Buddha then said "My son, I do not accept your abuse " The use of Pali, the language of the people, also contributed to the spread of Buddhism. It facilitated the spread of Buddhist docti ines among the common people. Gautama Buddha also organized the sangha or the religious order, whose doors were kept open to everybody, irrespective of caste and sex. The only condition required of the monks was that they would faithfully observe the rules and regulations of the sangha Once they were enrolled as members of the Buddhist Church they had to take the vow of continence, poverty and faith. So there are three main elements in Buddhism. Buddha, sangha and dhamma As a result of organized preaching under the auspices of the sangha Buddhism made rapid strides even in the lifetime of the Buddha The monarchies of Magadha, Kosala and Kausambi and several republican states and their people adopted this religion. Two hundred years after the death of the Buddha the famous Maurya king Asoka embraced Buddhism. This was an epoch-making event. Through his agents Asoka spread Buddhism into Central Asia, West Asia and Sri Lanka, and thus transformed it into a world religion. Even today Sri Lanka, Burma, Tibet and parts of China and Japan profess Buddhism. Although Buddhism disappeared from the land of its birth, it continues to hold ground in the coun66 tries of South Asia, South-East Asia and East Asia. Causes of the Decline of Buddhism By the twelfth century A.D., Buddhism became practically extinct in India. It continued to exist in a changed form in Bengal and Bihar till the twelfth century, but after that this religion almost completely vanished from the country. What were its causes? We find that in the beginning every religion is inspired by the spirit of reform, but eventually it succumbs to rituals and ceremonies it originally denounced. Buddhism underwent a similar metamorphosis. It became a victim to the evils of brahmaniısm against which it had fought in the beginning. To meet the Buddhist challenge the brahmanas reformed their religion. They stressed the need for preserving the cattle wealth and assured women and sudras of admission to heaven Buddhism, on the other hand, changed for the worse. Gradually the Buddhist monks were cut off from the mainstream of people's life; they gave up Pali, the language of the people, and took to Sanskrit, the language of intellectuals. From the first century A.D. they practised idol worship on a large scale and received numerous offerings from devotees. The rich offerings supplemented by generous royal grants to the Buddhist monasteries made the life of monks easy. Some of the monasteries such as Nalanda collected revenue from as many as 200 villages. By the seventh century A.D. the Buddhist monasterias had come to be dominated by ease-loving p ople and became centres of corrupt practices which Gautama Buddha had strictly prohibited. The new form, of Buddhism was known as Vajrayana The enormous wealth of the monasteries with women living in them led to further degeneration. Buddhists came to look upon women as objects of lust. The Buddha is reported to have said to his favourite disciple Ananda "If women were not admitted into the monasteries Buddhism would have continued for thousands of years, but because this admission has been granted it would last only five hundred years." For their riches the monasteries came to be coveted by the Turkish invaders. They became special targets of the invaders' greed The Turks killed a large number of Buddhist monks in Nalanda, although some of the monks managed to escape to Nepal and Tibet In any case by the twelfth century A.D. Buddhism had practically disappeared from the land of its birth. Importance and Influence of Buddhism Despite its ultimate disappearance as an organized religion Buddhism left its abiding mark on the history of India The Buddhists showed a keen awareness of the problems that faced the people of north-east India in the sixth century B C. The new iron ploughshare agriculture, trade, and the use of coins enabled the traders and nobles to accumulate wealth, and we hear of people possessing eighty kotis of wealth All this naturally created sharp social and economic inequalities. So Buddhism asked people not to accumulate wealth According to it poverty breeds hatred, cruelty and violence. To eradicate these evils the Buddha advised that farmers should be provided with grain and other facilities, the traders with wealth, and the labourers with wages These measures were recommended to remove poverty in this world. Buddhism further taught that if the poor gave alms to the monks they would be born wealthy in the next world The code of conduct prescribed for the monks represents a reaction against the material conditions of north-east India in the sixth and fifth centuries B.C. It imposes restrictions on the food, dress and sexual behaviour of the monks They cannot accept gold and silver and they cannot take to sale and purchase. These rules were relaxed after the death of the Buddha, but the early rules suggest a return to a kind of primitive communism, a characteristic of the tribal society in which people did not practise trade and plough agriculture. The code of conduct prescribed for monks partially reflects a revolt against the use of money, private property and luxurious living, which appeared in the sixth century BC. in north-east India In those days property and money were regarded as luxuries. Although Buddhism tried to mitigate the evils resulting from the new material life in the sixth century BC, it also tried to consolidate the changes in the social and economic life of the people. The rule that debtors were not permitted to be members of the sangha naturally helped the moneylenders and richer sections of society from whose clutches the debtors could not be saved. Similarly the rule that slaves could not join the sangha helped the slaveowners Thus the rules and teachings of Gautama Buddha took full account of the new changes in the material life and strengthened them ideologically. Although the Buddhist monkş had renounced the world and repeatedly criticised the greedy brahmanas, in several ways they resembled the brahmanas. Both of them did no participate directly in production, and lived on the alms or gifts given by society. Both of them emphasised the virtues of carrying out family obligations, protecting private property and respecting political authority. Both of them supported the social order based on classes; for the monks however the varna was based on action and attributes but for the brahmanas it was based on birth. Undoubtedly the objective of the Buddhist teaching was to secure the salvation of the individual or nirvana. Those who found it difficult to adjust themselves to the break-up of the old tribal society and the rise of gross social inequalities on account of private property were provided with some way of escape, but it was confined to the monks. 'No escape was provided for the lay followers, who were taught to come to terms with the existing situation. Buddhism made an important impact on society by keeping its doors open to women and sudras. Since both women and sudras were placed in the same category by brahmanism, they were neither given sacred thread nor allowed to read the Vedas. Their conversion to Buddhism freed them from such mark of inferiority. With its emphasis on non-violence and the sanctity of animal Life, Buddhism boosted the cattle wealth of the country The earliest Buddhist text Suttanipata declares the cattle to be givers of food, beauty and happiness (annada vannada sukhada), and thus pleads for their protection. This teaching came significantly at a time when the non-Aryans slaughtered animals for food, and the Aryans in the name of religion. The brahmanical insistence on the sacredness of the cow and non-violence was apparently derived from Buddhist teachings Buddhism created and developed a new awareness in the field of intellect and culture. It taught the people not to take things for granted but to argue and judge them on merits. To a certain extent the place of superstition was taken by logic. This promoted rationalism among people. In order to preach the doctrines of the new religion the Buddhists compiled a new type of literature. They enormously enriched Pali by their writings. The early Pali literature can be divided into three categories. The first contains the sayings and teachings of the Buddha, the second deals with the rules to be observed by members of the sangha, and the third presents the philosophical exposition of the dhamma. The literary activities of the Buddhist monks continued even in the Middle Ages, and some famous Apabhramsa writings in east India were composed by them. The Buddhist monasteries developed as great centres of learning, and can be called residential universities. Mention may be made of Nalanda and Vikramasila in Bihar, and Valabhi in Gujarat, Buddhism left its mark on the art of ancient India The first human statues worshipped in India were probably those of the Buddha. The faithful devotees portrayed the various events in the life of the Buddha in stone. The panels found at Gaya in Bihar and at Sanchi and Bharhut in Madhya Pradesh are illuminating examples of artistic activity. From the first century AD the panel images of Gautama Buddha began to be made. The Greek and the Indian sculptors worked together to create a new kind of art on the north-west frontier of India, which is known as the Gandhara art. The images made in this region betray Indian as well as foreign influence. For the residence of the monks rooms were hewn out of the rocks, and thus began the cave architecture in the Barabar hills in Gaya and in western India around Nasik. Under the impetus of Roman trade Buddhist art flourished in the Kushna delta, and under that of Central Asian contacts it thi ove in Mathura and Gandhara. Explain the causes of the origin of the religious sects in north-east India in the sixth century BC. "The sixth century B.C. is remarkable for the origin of numerous religious sects in north-east India." Explain Who was Vardhamana Mahavira and what were his teachings? Trace the origin and development of Jainism in India. 5 Give an account of Jainism. What did it contribute to Indian society? Who was Gautama Buddha? State his teachings Explain the social aspects of Buddhism. 8 Why did Buddhism spread in India and abroad? Account for the decline of Buddhism. Discuss the importance and influence of Buddhism. CHAPTER 10 Territorial States and the First Magadhan Empire century BC. Eventually the kingdom of Anga was swallowed by its powerful neighbour Magadha. From the sixth century B.C. the widespread use of iron in eastern Uttar Pradesh and western Bihar facilitated the formation of large territorial states. Because of iron weapons the warrior class now played an important part. The new agricultural tools and implements enabled the peasants to produce far more foodgrains than they required for consumption The extra product could be collected by the princes to meet their military and administrative needs. The surplus could also be made available to the towns which had sprung up in the sixth century B.C These material advantages naturally enabled the people to stick to their land, and also to expand at the cost of the neighbouring areas. The rise of large states with towns as their base of operations strengthened the territorial idea People owed strong allegiance to the janapada or the territory to which they belonged and not to the jana or the tribe to which they belonged. The Mahajanapadas In the age of the Buddha we find 16 large states called mahajanapadas. They were mostly situated north of the Vindhyas and extended from the north-west frontier to Bihar. Of these, Magadha, Kosala, Vatsa and Avanti seem to have been considerably powerful. Baginning from the east we hear of the kingdom of Anga which covered the modern districts. of Monghyr and Bhagalpur. It had its capital at Champa, which shows signs of habitation from the sixth Magadha embraced the modern districts of Patna, Gaya and parts of Shahabad, and grow to be the leading state of the time. North of the Ganga in the division of Tirhut was the state of the Vajjis which included eight clans, But the most powerful were the Lichchhavis with their capital at Vaisali which is identical with the village of Basarh in the district of Vaisali, The Puranas push the antiquity of Vaisalı to a much earlier period, but archaeologically Basarh was not settled earlier than the sixth century B.C. Further west we find the kingdom of Kasi with its capital at Varanası Excavations at Rajghat show that the earliest habitation started around 700 BC, and the city was enclosed by mud-walls in the sixth century B.C. In the beginning Kasi appears to be the most powerful of the states, but eventually it had to submit to the power of K.osala. Kosala embraced the area occupied by eastern Uttar Pradesh and had its capital at Sravasti, which is identical with Sahet-Mahet on the borders of Gondla and Bahraich districts in Uttar Pradesh. Diggings indicate that Sahet-Mahet did not possess any large settlement in the sixth century B.C. Kosala. contained an important city called Ayodhya, which is associated with the story in the Ramayana. But excavations, show that it was not settled on any scale before the sixth
english
Directors on boards have two distinct roles: A “map” role and a “compass” role. The former is the traditional role. It is about overseeing the short-term goals, with a horizon of a few years. The latter is about the long term, securing the future over decades. The overseeing role is most often written about. There is a shift in focus from the short term to the long term. This article is about the long term. Management needs new ways of thinking to make companies survive and grow for the long term, and to be sustainable companies in every sense of the word. Sustainability is about conducting business in a manner that the business can flourish for many decades by being of, by and for the communities around the business. TO READ THE FULL STORY, SUBSCRIBE NOW NOW AT JUST RS 249 A MONTH. What you get on Business Standard Premium? - Unlock 30+ premium stories daily hand-picked by our editors, across devices on browser and app. - Pick your 5 favourite companies, get a daily email with all news updates on them. - Full access to our intuitive epaper - clip, save, share articles from any device; newspaper archives from 2006. - Preferential invites to Business Standard events. - Curated newsletters on markets, personal finance, policy & politics, start-ups, technology, and more.
english
<reponame>fluxxu/rust-async-dnssd<gh_stars>10-100 use futures_channel::oneshot; use futures_util::FutureExt; use std::{ future::Future, io, os::raw::c_void, pin::Pin, task::{ Context, Poll, }, }; use crate::{ error::Error, ffi, inner::EventedService, }; #[allow(clippy::borrowed_box)] fn box_raw<T>(ptr: &mut Box<T>) -> *mut c_void { ptr.as_mut() as *mut T as *mut c_void } type CallbackContext<T> = Option<oneshot::Sender<io::Result<T>>>; struct Inner<S: EventedService, T> { service: S, _sender: Box<CallbackContext<T>>, receiver: oneshot::Receiver<io::Result<T>>, } #[must_use = "futures do nothing unless polled"] pub(crate) struct ServiceFuture<S: EventedService, T>(Option<Inner<S, T>>); impl<S: EventedService, T> ServiceFuture<S, T> { pub(crate) unsafe fn run_callback<F>( context: *mut c_void, error_code: ffi::DNSServiceErrorType, f: F, ) where F: FnOnce() -> io::Result<T>, T: ::std::fmt::Debug, { let sender = context as *mut CallbackContext<T>; let sender: &mut CallbackContext<T> = &mut *sender; let sender = sender.take().expect("callback must be run only once"); let data = Error::from(error_code) .map_err(io::Error::from) .and_then(|()| f()); sender.send(data).expect("receiver must still be alive"); } pub(crate) fn new<F>(f: F) -> io::Result<Self> where F: FnOnce(*mut c_void) -> Result<S, Error>, { let (sender, receiver) = oneshot::channel::<io::Result<T>>(); let mut sender = Box::new(Some(sender)); let service = f(box_raw(&mut sender))?; Ok(Self(Some(Inner { service, _sender: sender, receiver, }))) } pub(crate) fn new_with<R, F>(service: S, f: F) -> io::Result<(Self, R)> where F: FnOnce(*mut c_void) -> Result<R, Error>, { let (sender, receiver) = oneshot::channel::<io::Result<T>>(); let mut sender = Box::new(Some(sender)); let res = f(box_raw(&mut sender))?; Ok(( Self(Some(Inner { service, _sender: sender, receiver, })), res, )) } fn inner(&self) -> &Inner<S, T> { self.0.as_ref().expect("can only get ready once") } fn inner_mut(&mut self) -> &mut Inner<S, T> { self.0.as_mut().expect("can only get ready once") } pub(crate) fn service(&self) -> &S { &self.inner().service } } impl<S: EventedService, T> Future for ServiceFuture<S, T> { type Output = io::Result<(S, T)>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { if self.0.is_none() { // can only get ready once. return Poll::Pending; } self.inner_mut().service.poll_service(cx)?; let item = futures_core::ready!(self.inner_mut().receiver.poll_unpin(cx)) .expect("send can't die")?; Poll::Ready(Ok((self.0.take().unwrap().service, item))) } }
rust
import { Site } from 'hn'; import site from './site'; test('site util', () => { expect(site).toBeInstanceOf(Site); });
typescript
A $330 million national broadband network deal between the Philippine government and ZTE firm from China. Critics describe the contract as overpriced, unnecessary and disadvantageous to the Philippines. Tales of bribery, corruption and harassment have surfaced which could implicate the First Family. Pinoyblogero has highlights from last week's posting on Philippines blogsphere. The topics include the trail of former president Joseph Estrada and how a blogger stirred up controversy by baiting them on his blog. Mike Abundo wonders why Yahoo is looking to base it's online Community Manager for Philippines in Singapore. After six years of trial, former Philippine president Joseph Estrada was found guilty of plunder by a special anti-graft court. This was the first time a former president was convicted of such crime in the Philippines. BISEAN is today looking at the origin of the names of South East Asian capital cities. Since 1968, the Communist Party of Philippines is fighting to create a Maoist society in Philippines. Mong Palatino blogs about this longest running insurgency in South East Asia. The letsgophilippines blog features the top dive sites in the Philippines. Lauren blogs about her close encounter with the Church of Scientology. The Perpetual Malcontent disputes the statement of the officer-in-charge of the Philippines National Economic and Development Authority that Indians are better English speakers compared to the Filipinos.
english
One person was killed and nearly 300 people were injured, 15 of them seriously, during the annual "Gotmar" (stone-throwing) festival at Pandhurna in Madhya Pradesh's Chhindwara district Monday. During the annual Gotmar festival, people of Sawargaon and Pandhurna gather on either side of Jaam River and, while throwing stones, race to snatch a flag hoisted on top of a dead tree situated in the middle of the river. The tradition is said to have started around 300 years ago when a boy from Pandhurna abducted a girl from Sawargaon. The couple, facing a volley of stones while crossing the river, reached Pandhurna safely due to help from the villagers, according to folklore in the region. Collector Ved Prakash Sharma and Superintendent of Police Atul Singh told reporters Monday that one person, identified as Shankar Bhalavi, 28, died on the spot after being hit in the stomach by stones. He was a resident of Belgaon village, the officials added. Earlier, one person had died during this festival in 2011, officials said.
english
package com.easemob.server.example.comm.body; import org.apache.commons.lang3.StringUtils; import com.easemob.server.example.comm.wrapper.BodyWrapper; import com.fasterxml.jackson.databind.node.ContainerNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; public class IMUserBody implements BodyWrapper { private String userName; private String password; private String nickName; public IMUserBody(String userName, String password, String nickName) { super(); this.userName = userName; this.password = password; this.nickName = nickName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } @Override public ContainerNode<?> getBody() { return JsonNodeFactory.instance.objectNode().put("username", userName).put("password", password).put("nickname", nickName); } @Override public Boolean validate() { return StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(password); } }
java
[{"__symbolic":"module","version":4,"metadata":{"IonicImageZoomer":{"__symbolic":"class","decorators":[{"__symbolic":"call","expression":{"__symbolic":"reference","module":"@angular/core","name":"NgModule","line":4,"character":1},"arguments":[{"declarations":[{"__symbolic":"reference","module":"./components/img-zoomer","name":"ImgZoomerComponent","line":6,"character":4}],"imports":[{"__symbolic":"reference","module":"ionic-angular","name":"IonicModule","line":9,"character":4}],"exports":[{"__symbolic":"reference","module":"./components/img-zoomer","name":"ImgZoomerComponent","line":12,"character":4}]}]}],"statics":{"forRoot":{"__symbolic":"function","parameters":[],"value":{"ngModule":{"__symbolic":"reference","name":"IonicImageZoomer"},"providers":[]}}}}}}]
json
{ "version": 1, "tags": [ { "name": "vtm-5e-tools", "description": "Unofficial Vampire the Masquerade 5e Tools including Character Builder and Dice Roller by <NAME> (aka FuzzieChikun). Written in Google's Lit JS.", "properties": [ { "name": "Unofficial VtM 5e Tools", "type": "String", "description": "Unofficial Vampire the Masquerade 5e Tools including Character Builder and Dice Roller by <NAME> (aka FuzzieChikun). Written in Google's Lit JS.", "default": "Hey there" }, { "name": "page", "type": "String", "description": "Which page to show", "default": "main" } ], "events": [], "slots": [], "cssProperties": [] } ] }
json
@import views.html.layout.main @import play.api.i18n.Messages @import org.ada.server.models.DataSpaceMetaInfo @import views.html.elements._ @import views.html.layout @import views.html.dataset.{datasetMenu, datasetSubNavWithJs} @import org.incal.spark_ml.models.VectorScalerType @import org.incal.play.controllers.WebContext @import org.incal.play.controllers.WebContext._ @import org.ada.server.models.RCPredictionSettings @import com.bnd.network.domain.ActivationFunctionType @import org.ada.web.util.enumToValueString @( form: Form[RCPredictionSettings], dataSpaceMetaInfos: Traversable[DataSpaceMetaInfo] )( implicit context: WebContext ) @inputTextAux(fieldName: String, defaultValue: Option[Any] = None) = @{ defining(form(fieldName)) { field => inputFieldText( "rcPredictionSettings", if (field.value.isEmpty && defaultValue.isDefined) field.copy(value = Some(defaultValue.get.toString)) else field, Nil, 3 ) } } @selectEnumAux(fieldName: String, enum: Enumeration) = { @select("rcPredictionSettings", fieldName, form, enumToValueString(enum), true, Nil, 3) } @selectJavaEnumAux(fieldName: String, clazz: Class[_]) = { @select("rcPredictionSettings", fieldName, form, clazz.getEnumConstants.map( x => (x.toString, x.toString)), true, Nil, 3) } @main("RC Prediction", Some(datasetMenu(dataSpaceMetaInfos))) { <div class="page-header"> <h3> RC Prediction </h3> </div> <div class="row"> <div class="col-md-12"> @helper.form(action = controllers.ml.routes.RCPredictionController.runRCPrediction()) { <fieldset> @inputTextAux("reservoirNodeNums", Some(50)) @inputTextAux("reservoirInDegrees", Some(50)) @inputTextAux("reservoirCircularInEdges") @selectJavaEnumAux("reservoirFunctionType", classOf[ActivationFunctionType]) @inputTextAux("reservoirFunctionParams") @inputTextAux("inputReservoirConnectivities", Some(0.5)) @inputTextAux("reservoirSpectralRadiuses", Some(1)) <hr/> @inputTextAux("inScales", Some(1)) @inputTextAux("predictAheads", Some(1)) @inputTextAux("washoutPeriod", Some(500)) @inputTextAux("dropLeftLength") @inputTextAux("dropRightLength", Some(200)) @inputTextAux("seriesLength") @inputTextAux("inputSeriesFieldPaths", Some("accel_walking_outboundu002ejsonu002eitems.x, accel_walking_outboundu002ejsonu002eitems.y, accel_walking_outboundu002ejsonu002eitems.z")) @inputTextAux("outputSeriesFieldPaths", Some("accel_walking_outboundu002ejsonu002eitems.x")) @inputTextAux("sourceDataSetId", Some("mpower_challenge.walking_activity_training_w_demographics")) @inputTextAux("resultDataSetId", Some("mpower_challenge.walking_activity_training_rc_weights")) @inputTextAux("resultDataSetName", Some("Walking Activity Training (RC) Weights")) @inputTextAux("resultDataSetIndex", Some(1)) @selectEnumAux("seriesPreprocessingType", VectorScalerType) @inputTextAux("batchSize", Some(20)) @inputTextAux("preserveWeightFieldNames", Some("recordId, medTimepoint, healthCode")) </fieldset> <div class="actions pull-right"> <input type="submit" value="Submit" class="btn btn-primary"> </div> } </div> </div> }
html
{ "git": { "delete": "rmdir \"{{{workspace}}}{{{pathseparator}}}{{{name}}}\" /s /q", "init": "git clone {{{url}}} \"{{{workspace}}}{{{pathseparator}}}{{{name}}}\"", "get": "cd \"{{{workspace}}}{{{pathseparator}}}{{{name}}}\" && git pull --rebase", "changes": "cd \"{{{workspace}}}{{{pathseparator}}}{{{name}}}\" && git status -s && git log --branches --not --remotes --oneline", "report": { "getBranchName": "git symbolic-ref --short --quiet HEAD", "hasUncommitted": "(git diff-index --quiet HEAD -- && echo Clean) || echo Dirty", "hasUnpushed": "git log --branches --not --remotes --oneline | wc -l" }, "save": "cd \"{{{workspace}}}{{{pathseparator}}}{{{name}}}\" && git push origin master", "undo": "cd \"{{{workspace}}}{{{pathseparator}}}{{{name}}}\" && git reset --hard" }, "svn": { "delete": "rmdir \"{{{workspace}}}{{{pathseparator}}}{{{name}}}\" /s /q", "init": "svn checkout {{{url}}} \"{{{workspace}}}{{{pathseparator}}}{{{name}}}\"", "get": "cd \"{{{workspace}}}{{{pathseparator}}}{{{name}}}\" && svn up", "changes": "cd \"{{{workspace}}}{{{pathseparator}}}{{{name}}}\" && svn stat", "report": { "getBranchName": "svn info | grep '^URL:' | egrep -o '(tags|branches)/[^/]+|trunk' | egrep -o '[^/]+$'", "hasUncommitted": "((svn status -q | grep --quiet [AMCDG]) && echo Dirty) || echo Clean", "hasUnpushed": "echo \"N. A.\"" }, "save": "cd \"{{{workspace}}}{{{pathseparator}}}{{{name}}}\" && svn commit -m \"Commited by Repoman\"", "undo": "cd \"{{{workspace}}}{{{pathseparator}}}{{{name}}}\" && svn revert -R ." } }
json
[{"skyblock_id":"JACOBS_TICKET","quantity":"16","item_name":"Jacobs ticket","estimated_price":"Coming Soon","estimated_total_price":"Coming Soon"},{"skyblock_id":"ENCHANTED_SUGAR","quantity":"64","item_name":"Enchanted sugar","estimated_price":"Coming Soon","estimated_total_price":"Coming Soon"},{"skyblock_id":"JACOBS_TICKET","quantity":"16","item_name":"Jacobs ticket","estimated_price":"Coming Soon","estimated_total_price":"Coming Soon"},{"skyblock_id":"ENCHANTED_SUGAR","quantity":"64","item_name":"Enchanted sugar","estimated_price":"Coming Soon","estimated_total_price":"Coming Soon"},{"skyblock_id":"THEORETICAL_HOE_CANE_1","quantity":"1","item_name":"Theoretical hoe cane 1","estimated_price":"Coming Soon","estimated_total_price":"Coming Soon"},{"skyblock_id":"ENCHANTED_SUGAR","quantity":"64","item_name":"Enchanted sugar","estimated_price":"Coming Soon","estimated_total_price":"Coming Soon"},{"skyblock_id":"JACOBS_TICKET","quantity":"16","item_name":"Jacobs ticket","estimated_price":"Coming Soon","estimated_total_price":"Coming Soon"},{"skyblock_id":"ENCHANTED_SUGAR","quantity":"64","item_name":"Enchanted sugar","estimated_price":"Coming Soon","estimated_total_price":"Coming Soon"},{"skyblock_id":"JACOBS_TICKET","quantity":"16","item_name":"Jacobs ticket","estimated_price":"Coming Soon","estimated_total_price":"Coming Soon"}]
json
{ "variants": { "axis=x,type=bottom": { "model": "betterslabs:block/test_slab_side", "y": 270 }, "axis=x,type=top": { "model": "betterslabs:block/test_slab_side", "y": 90 }, "axis=x,type=double": { "model": "betterslabs:block/test_slab_double_horizontal", "x": 90, "y": 90 }, "axis=y,type=bottom": { "model": "betterslabs:block/test_slab" }, "axis=y,type=top": { "model": "betterslabs:block/test_slab_top" }, "axis=y,type=double": { "model": "betterslabs:block/test_slab_double" }, "axis=z,type=bottom": { "model": "betterslabs:block/test_slab_side" }, "axis=z,type=top": { "model": "betterslabs:block/test_slab_side", "y": 180 }, "axis=z,type=double": { "model": "betterslabs:block/test_slab_double_horizontal", "x": 90 } } }
json
The Russian stock market resumed limited trading Thursday under heavy restrictions almost one month after prices plunged and the market was shut down following Moscow’s invasion of Ukraine. Trading of a limited number of stocks including energy giants Gazprom and Rosneft took place under curbs that are meant to prevent a repeat of the massive selloff that took place Feb. 24 in anticipation of Western economic sanctions. Foreigners cannot sell and traders are barred from short selling, or betting prices will fall. Also Read: Russia sanctions the West: Who all are in Moscow’s crosshairs? The benchmark MOEX index gained 8% in the first minutes of trading. The reopening of stock trading on the Moscow Exchange has little impact on investors outside Russia. Its market capitalization is a fraction of that of major Western or Asian markets. Foreign investment managers lost one reason to buy Russian stocks after MSCI Inc. declared the market to be “uninvestable” following the Feb. 24 invasion and removed it from global indexes. Hundreds of U. S. , European and Japanese companies have pulled out of Russia. There have been bank runs and panic buying of sugar and other staples. The exchange rate of Russia’s ruble has tumbled. Foreigners are barred from selling shares under rules imposed to counter Western sanctions against Russia’s weakening financial system and currency. Trading will be allowed in 33 of the 50 companies that are part of the country’s benchmark MOEX index, including air carrier Aeroflot, state-owned gas producer Gazprom and the oil company Rosneft, according to a central bank announcement. Stocks last traded in Moscow on Feb. 25. A day earlier the MOEX sank 33% after Russian forces invaded Ukraine. Moscow’s stock exchange had a market capitalization of about $773 billion at the end of last year, according to the World Federation of Exchanges. That is dwarfed by the New York Stock Exchange, where the total of all equities is roughly $28 trillion. Russia’s central bank relaunched trading in ruble-denominated government bonds this week. The central bank estimates that roughly 7. 7 trillion rubles, equal to $79 billion, of Russia’s stock was owned by retail investors as of late 2021. Russia’s government may intervene to support its companies and investors. Prime Minister Mikhail Mishustin said March 1 that the country’s National Wealth Fund would purchase up to 1 trillion rubles ($10. 2 billion) in Russian shares by the end of the year. Before the war, foreign investors were showing growing interest in Russian stocks as an emerging markets opportunity. But roughly a week into the war, Russia was removed from emerging markets indexes compiled by MSCI, a division of Morgan Stanley. MCSI said that after consultation with a large number of asset managers it determined the Russian stock market to be “uninvestable. ” That took away a primary incentive for fund managers to invest there. On March 3, the London Stock Exchange suspended trading in shares of 27 companies with links to Russia, including some of the biggest in energy and finance. The shares lost most of their value prior to the suspension. Rosneft shares dropped from $7. 91 on Feb. 16 to 60 cents on March 2. Sberbank plunged from $14. 90 to 5 cents.
english
Sunset Serenade Movie Streaming Watch Online. Bad guys plot to trick a newly arrived Eastern girl out of a ranch which belongs to her infant ward. Roy, of course, saves the ranch for the girl. Songs include "I'm Headin's for the Home Corral," "He's a No Good Son of a Gun," "Sandman Lullaby," "Song of the San Joaquin," and "I'm a Cowboy Rockefeller."
english
<filename>src/observation_wrappers.py import gym import numpy as np class CorridorObservationWrapper(gym.ObservationWrapper): def observation(self, obs): return obs, class FSWObservationWrapper(gym.ObservationWrapper): def observation(self, observation): return observation, class WoodsBinaryAdapter(gym.ObservationWrapper): def observation(self, observation): result = [] for el in observation: if el == 'F': result.extend(['1', '1', '0']) if el == 'G': result.extend(['1', '1', '1']) if el == 'O': result.extend(['0', '1', '0']) if el == 'Q': result.extend(['0', '1', '1']) if el == '.': result.extend(['0', '0', '0']) return result class BinnedObservationWrapper(gym.ObservationWrapper): """ Divide observation using environment's observation space into `num_bins` equal bins. """ def __init__(self, env, num_bins): super().__init__(env) self._range, self._low = (env.observation_space.high - env.observation_space.low, env.observation_space.low) self.num_bins = num_bins def observation(self, obs): r = (obs + np.abs(self._low)) / self._range b = (r * self.num_bins).astype(int) return b.astype(str).tolist()
python
package com.rabc.fangkuai.entity; import com.yyfly.common.entity.BaseEntity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Table; /** * @创建人 lin * @创建时间 2020/1/20 * @描述 */ @Data @Entity @Table(name = "imms_resource") public class Resource extends BaseEntity { /** * serialVersionUID */ private static final long serialVersionUID = -4091125312802177946L; /** * 无 */ public static final String TYPE_NONE = "0"; /** * 菜单 */ public static final String TYPE_MENU = "1"; /** * 功能 */ public static final String TYPE_FUNCTION = "2"; /** * 资源名称 */ private String resourceName; /** * path */ private String path; /** * 资源类型 * <ul> * <li> 0 - 无</li> * <li> 1 - 菜单</li> * <li> 2 - 功能</li> * </ul> */ private String type; /** * 权限标识 */ private String permission; /** * 上级 */ private String pid; /** * 备注 */ private String remark; }
java
<p>Id = 67</p> <p>Nombre Capitulo = Blips and Chitz</p> <p>Tipo = Arcade</p> <p>Dimension = Replacement Dimension</p> <p>Personaje = ['https://rickandmortyapi.com/api/character/242']</p> <p>Numero Personaje = ['242']</p> <p>URL Locacion = https://rickandmortyapi.com/api/location/67</p>
html
{ "name": "homebridge-harmony-hub", "version": "1.0.0", "author": "AirBorne04, original authored by KraigM", "description": "Logitech Harmony Hub plugin for HomeBridge", "homepage": "https://github.com/AirBorne04/harmonyhub/tree/master/packages/homebridge", "keywords": [ "homebridge-plugin", "logitech", "harmony", "home automation", "remote" ], "license": "MIT", "repository": { "type": "git", "url": "git://github.com/AirBorne04/harmonyhub.git" }, "bugs": { "url": "https://github.com/AirBorne04/harmonyhub/issues" }, "main": "./dist/index.js", "types": "./dist/index.d.ts", "engines": { "node": ">=4.0.0", "homebridge": ">=0.3.1" }, "preferGlobal": true, "dependencies": { "@harmonyhub/client": "^1.0.5", "@harmonyhub/discover": "^1.0.5", "autobind-decorator": "^2.1.0", "debug": "^3.1.0", "lodash": "^4.6" }, "devDependencies": { "@types/debug": "0.0.30", "@types/node": "^10.5.7" } }
json
i = 1 while i <= 9: j = 1 while j <= i: print("{}x{}={}\t".format(j, i, i * j), end='') j += 1 print() i += 1
python
from libs.threading import Threads from school.content import courseinfo from school.content.coursemanager import CourseManager from school.ui.userinterface import UserInterface from . import notifications class Starter: @staticmethod def check_changes(): courses = courseinfo.get_courses() coursemanagers = [ CourseManager(c, part) for c in courses for part in c.to_check ] content_threads = Threads([c.check for c in coursemanagers]).start() if notifications.check_notifications(): extra_coursemanagers = [CourseManager(c, "news/") for c in courses] coursemanagers += extra_coursemanagers extra_content_threads = Threads( [c.check for c in extra_coursemanagers] ).start() UserInterface.show_progres(len(coursemanagers)) content_threads.join() if len(coursemanagers) > len(content_threads.threads): extra_content_threads.join() new_sections = [ s for c in coursemanagers if c.contentmanager for s in c.contentmanager.new_topic_sections ] if new_sections: from school.content import outputwriter # noqa: autoimport outputwriter.write_output_to_html(new_sections)
python
{"solution_size":51,"ok":true,"resemblance":0.292517,"problem_id":2819,"solution_spec_hash":"4e92482c7cae95e7cad188bd061d54fd2792da30"}
json
<gh_stars>10-100 # windows-cpu History Changes to `windows-cpu` will be recorded in this file. ## 1.1.0 (7/5/2018) * **NEW:** Moved `wmic` constant to class property `cpu.wmic` to allow overriding the location of `wmic.exe` and to handle certain issues when testing on non-Windows systems. * **FIX:** The default `wmic` path now contains a default `/` if `process.env.SystemRoot` is `undefined`. (#14) * Removed `command-join` dependency which was used for escaping shell input in `findLoad()`. This has been replaced with a more simple solution which makes this module dependency-free again. * Added `_shellEscape()` method that is a simple way to escape possible malicious input to the `findLoad()` method. * Added tests for `_shellEscape()`. * Misc. cleanup. ## 1.0.1 (5/28/2018) * Removed OS limitation from package.json to prevent issues with installation when windows-cpu is used as an optional dependency (#13). ## 1.0.0 (5/24/2018) * **BREAKING:** `checkPlatform()` has been renamed to `isSupported()` and is no longer called in the constructor. * **BREAKING:** `processLoad()` has been renamed to `thisLoad()`. * **BREAKING:** Minimum supported Node version 8.x+ * **BREAKING:** All methods that originally used callbacks now returns Promises. * **NEW:** Now checks if `wmic.exe` exists when checking for support * **NEW:** `findLoad()` will now return all processes and their load if no argument is provided. * Fix command line injection vulnerability (thanks <NAME>) * Refactor to ES6 * Added dependency `command-join` to assist with escaping malicious input to `findLoad()`. * Added CI for testing new releases. ## 0.1.6 (5/28/2018) * Removed OS limitation from package.json to prevent issues with installation when windows-cpu is used as an optional dependency (#13). ## 0.1.5 (5/24/2018) * Added `command-join` dependency. * Fix command line injection vulnerability - CWE-94 (thanks <NAME>). ## 0.1.4 (4/8/2015) * `totalLoad` crashing when no results returned (@driedger - #6) * Updated README to reflect Windows 8 support ## 0.1.3 (2/3/2015) * Performance improvements for functions that call `wmic.exe` (thanks @SkyLined - #3) * Updated `totalLoad` function to call `wmic.exe` directly * Updated `cpuInfo` function to call `wmic.exe` directly * Updated `totalMemoryUsage` function to improve performance * Misc. clean up * Added HISTORY.md ## 0.1.2 (10/27/2014) * Added `totalMemoryUsage` function (@scriptnull) * Added tests and updated Readme ## 0.1.1 (12/16/2013) * Minor cleanup of unused variables ## 0.1.0 (12/16/2013) * Initial commit of windows-cpu
markdown
Inner Mongolia - desert area – December - below freezing point. It was with this hype, I started dreaming of feeling snow falling on my head or even make a snow man. Though upon reaching, the pilot did say that temperature was -3, but it hardly felt like a sub-zero weather. With Sun shimmering and sans chilly wind even at -8 degrees, all my dreams went kaput!! Decent vegetarian meal remained a distant dream and I had to be content with fruits and vegetables. It was under these conditions that I fell in love with Broccoli. Getting fried rice was the other good meal that I chanced upon during these 2 days. Potato juice was exceptionally bad though pure corn juice was awesome. The only other new thing that I tried in Hohhot was the Hot-Pot. Boiling soup kinda thing, wherein u put the raw vegetables and let it boil. After some time u take it out and mix with sauce and eat. Not knowing how to handle chop-sticks can be a nightmare. Thankfully, I got knife and fork, so I was atleast able to eat my vegetables and fruits without much discomfort. Fast-forwarding to Beijing. I hoped to the see the Great Wall and I had 2 days to see it. But call it bad timing or laziness, it didn’t work out. Till the time I reached Beijing, I had no idea where I am going to stay. I only knew a guy, who lived behind our house and was now working in an Indian restaurant – Ganges in Beijing. Thankfully, he picked up my call and I went straight to meet him. In comparison to other compatriots who just ignore you, this guy was extremely polite and welcoming. So after having first decent meal (that too, Indian meal) in days, I kept the luggage in the restaurant itself and went about exploring the city. Not knowing the city at all and English map not helping much, I took a cab to the Forbidden City. It was a Saturday, so more crowd than usual. I visited the annex to the forbidden city, which also looked quite good. Seeing the huge ticket line for main enclosure of Forbidden City, I chucked the idea and instead went to the opposite side to Tiananmen Square. In China, its easy to find out who is a thug and who is trying to fool you. In China, normally people hardly speak in English and its even rare to see them take the initiative and offer help..that too in English. So, when few people started approaching me after every 10 minutes with big friendly smile and offering a drink, I knew something was fishy. Best way to explore an unknown city is by walking. I too walked and wandered. Walking was indeed a pleasure albeit the nuisance thugs as the roads were super clean and motorists behaving at signals. As I walked, I stumbled upon the big market street – Wangjuming Street. It was a lovely shopping street with all the big brands lighting up the dark evening with flea market tucked inbetween somewhere. Also at the end of market was the wonderful night food street - a street full of snack items. Before you start thinking of finger fries and burgers, let me clarify that we are talking about China and snacks could only refer to fried creatures. So from snakes to worms, scorpions to cockroaches, all were dangling by the stick taken out from fire ready to be consumed. Going home was a bit of an issue. Taxi drivers in China, like their Indian counterpart, try to loot away the tourists. Since I came by taxi with a meter, I had a fair idea as to how much to pay. Thus, after saying no to several taxis, finally one agreed and I reached back to Ganges to have my Indian meal. Final day in China started at well past 10 am with awesome Paranthas for breakfast. After that it was back to Beijing exploration. With only half day to spend, I chose nearby places and instead of taxi, I decided to take metro. But with no English signboards, I had to just walk with the hope of stumbling upon a metro station. Assuming Chinese may not be of much help, I presumed a foreigner would be more aware and more approachable. I did ask a foreigner. However, to my luck, he himself was looking for a metro station. Thereafter we together searched for metro and eventually found also. At RMB 2 per ride, it was a very good option compared to the taxis. Though that foreign guy was heading for some other spot, but when he heard of Confucius Temple and Lama Temple, he changed his plan and joined me. So, the trip was not lonely thereafter. Both the temples were opposite to each other and both were extremely quiet and serene, far away from the usual rush of Beijing spots. While Confucius Temple was a simple affair, which was more about the life and times of Confucius, Lama Temple on the contrary was one of the very few religious places in Beijing. It was a usual Buddhist Temple, which adorned Buddhas of various shapes and sizes. As we went in deeper into the temple, the size of the Buddha kept on increasing with the main statue of Buddha measuring 28 meters carved out of single Sandalwood tree. It is astonishing that this towering figure is still unknown to many.
english
Dhenkanal: A major fire broke out since this morning in the OPTCL power grid station situated at Kantabania in the district here. Reports said that the mishap occurred at around 7 am this morning and till the filing of the report over 10 fire tending vehicles from local Tata Steel, GMR, Navbharat, MGM companies as well as from the fire stations of Banarpal, Hindol Road, Angul and Khajuriakata were pressed into action for dousing the raging flames. Reports further said that the intensity of the inferno was increasing and spreading fast due to the oil of the transformers. It is suspected that property worth crores of rupees will get gutted. As the operation was still on, the exact cause behind the fire mishap could not be ascertained while short circuit was attributed at the preliminary stage.
english
<reponame>sluyters/Gester {"name":"curve_downRight","subject":1009,"date":"1212010-022321","paths":{"Pen":{"strokes":[{"x":-637,"y":-662,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":0,"stroke_id":0},{"x":-614,"y":-658,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":1,"stroke_id":0},{"x":-579,"y":-652,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":2,"stroke_id":0},{"x":-534,"y":-645,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":3,"stroke_id":0},{"x":-478,"y":-648,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":4,"stroke_id":0},{"x":-404,"y":-634,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":5,"stroke_id":0},{"x":-334,"y":-627,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":6,"stroke_id":0},{"x":-246,"y":-606,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":7,"stroke_id":0},{"x":-157,"y":-584,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":8,"stroke_id":0},{"x":-63,"y":-549,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":9,"stroke_id":0},{"x":25,"y":-507,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":10,"stroke_id":0},{"x":111,"y":-454,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":11,"stroke_id":0},{"x":186,"y":-396,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":12,"stroke_id":0},{"x":254,"y":-328,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":13,"stroke_id":0},{"x":306,"y":-249,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":14,"stroke_id":0},{"x":342,"y":-162,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":15,"stroke_id":0},{"x":357,"y":-66,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":16,"stroke_id":0},{"x":349,"y":35,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":17,"stroke_id":0},{"x":318,"y":140,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":18,"stroke_id":0},{"x":268,"y":252,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":19,"stroke_id":0},{"x":199,"y":362,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":20,"stroke_id":0},{"x":116,"y":473,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":21,"stroke_id":0},{"x":20,"y":579,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":22,"stroke_id":0},{"x":-84,"y":680,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":23,"stroke_id":0},{"x":-196,"y":773,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":24,"stroke_id":0},{"x":-307,"y":856,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":25,"stroke_id":0},{"x":-410,"y":924,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":26,"stroke_id":0},{"x":-502,"y":979,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":27,"stroke_id":0},{"x":-579,"y":1022,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":28,"stroke_id":0},{"x":-643,"y":1041,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":29,"stroke_id":0},{"x":-682,"y":1054,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":30,"stroke_id":0},{"x":-710,"y":1042,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":31,"stroke_id":0},{"x":-714,"y":1023,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":32,"stroke_id":0},{"x":-706,"y":989,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":33,"stroke_id":0},{"x":-687,"y":957,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":34,"stroke_id":0},{"x":-660,"y":922,"w":null,"z":null,"alpha":null,"beta":null,"gamma":null,"t":35,"stroke_id":0}]}},"device":{"osBrowserInfo":"Fujitsu-Siemens Lenovo X61 Tablet PC","resolutionHeight":null,"resolutionWidth":null,"windowHeight":null,"windowWidth":null,"pixelRatio":null,"mouse":false,"pen":true,"finger":false,"acceleration":false,"webcam":false}}
json
<reponame>Viniciusalopes/mzphp { "repo_name": "oficial", "repo_url": "http://mazonos.com/packages/", "repo_dirlib": "/var/lib/mzphp/", "folder": "net/", "name": "netcat", "version": "0.7.1-1", "maintainer": "<NAME>", "license": "", "url": "http://netcat.sourceforge.net/", "deps": "", "file_mz": "netcat-0.7.1-1.mz", "file_desc": "netcat-0.7.1-1.mz.desc", "file_sha256": "netcat-0.7.1-1.mz.sha256", "file_json": "netcat-0.7.1-1.mz.json", "desc": "Netcat is a featured networking utility which reads and writes \ndata across network connections, using the TCP/IP protocol.\nIt is designed to be a reliable back-end tool that can be used \ndirectly or easily driven by other programs and scripts. At the same \ntime, it is a feature-rich network debugging and exploration tool, \nsince it can create almost any kind of connection you would need and \nhas several interesting built-in capabilities.\nAlthough the project development is marked as beta, GNU Netcat is \nalready enough stable for everyday use.\nGoals of this project are full compatibility with the original nc 1.10 \nthat is widely used, and portability." }
json
<gh_stars>10-100 { "vorgangId": "69689", "VORGANG": { "WAHLPERIODE": "18", "VORGANGSTYP": "Kleine Anfrage", "TITEL": "Möglichkeit der Entkriminalisierung von Flüchtlingen durch Änderung des Aufenthaltsgesetzes", "INITIATIVE": "<NAME>", "AKTUELLER_STAND": "Beantwortet", "SIGNATUR": "", "GESTA_ORDNUNGSNUMMER": "", "WICHTIGE_DRUCKSACHE": [ { "DRS_HERAUSGEBER": "BT", "DRS_NUMMER": "18/6262", "DRS_TYP": "Kleine Anfrage", "DRS_LINK": "http://dipbt.bundestag.de:80/dip21/btd/18/062/1806262.pdf" }, { "DRS_HERAUSGEBER": "BT", "DRS_NUMMER": "18/6467", "DRS_TYP": "Antwort", "DRS_LINK": "http://dipbt.bundestag.de:80/dip21/btd/18/064/1806467.pdf" } ], "EU_DOK_NR": "", "SACHGEBIET": [ "Ausländerpolitik, Zuwanderung", "Innere Sicherheit" ], "SCHLAGWORT": [ "Aufenthaltsgesetz", "Aufenthaltsrecht", "Bundespolizei", "Erkennungsdienstliche Maßnahme", "Ermittlungsverfahren", "Flüchtling", "Freizügigkeit", "Grenzkontrolle", { "_fundstelle": "true", "__cdata": "Illegale Einwanderung" }, "Österreich", "Personalbeschaffung", "Strafverfolgung" ], "ABSTRAKT": "Unerlaubte Einreisen 2014 und 2015: Anzahl, Straf- und Ermittlungsverfahren, Verfahrenseinstellungen bzw. Verurteilungen, Gründe, erkennungsdienstliche Maßnahmen, Zeit-, Personal- und Technikaufwand, Kosten; Notwendigkeit strafrechtlicher Verfolgung; personelle Mehrbelastung durch Grenzkontrollen an der deutsch-österreichischen Grenze; Einsatz von Dokumenten- und Visumberatern im Ausland, Neueinstellung von Bundespolizisten; Verletzung der Residenzpflicht: Strafverfahren und Einstellungen, Bearbeitungsaufwand, Notwendigkeit strafrechtlicher Verfolgung \r\n(insgesamt 19 Einzelfragen)" }, "VORGANGSABLAUF": { "VORGANGSPOSITION": [ { "ZUORDNUNG": "BT", "URHEBER": "Kleine Anfrage, Urheber : Fraktion DIE LINKE ", "FUNDSTELLE": "30.09.2015 - BT-Drucksache 18/6262", "FUNDSTELLE_LINK": "http://dipbt.bundestag.de:80/dip21/btd/18/062/1806262.pdf", "PERSOENLICHER_URHEBER": [ { "VORNAME": "Ulla", "NACHNAME": "Jelpke", "FUNKTION": "MdB", "FRAKTION": "DIE LINKE", "AKTIVITAETSART": "Kleine Anfrage" }, { "VORNAME": "Jan", "NACHNAME": "Korte", "FUNKTION": "MdB", "FRAKTION": "DIE LINKE", "AKTIVITAETSART": "Kleine Anfrage" } ] }, { "ZUORDNUNG": "BT", "URHEBER": "Antwort, Urheber : Bundesregierung, Bundesministerium des Innern (federführend)", "FUNDSTELLE": "23.10.2015 - BT-Drucksache 18/6467", "FUNDSTELLE_LINK": "http://dipbt.bundestag.de:80/dip21/btd/18/064/1806467.pdf" } ] } }
json
<filename>src/main/resources/assets/armorless/models/item/unseen_armor_legs.json { "parent": "item/generated", "textures": { "layer0": "armorless:items/unseen_leggings" } }
json
<reponame>jfgrissom/xrpl-hooks-api-assembly-script { "name": "xrpl-hooks-api-assembly-script", "version": "0.2.9", "description": "XRPL hooks API exports that you can import into your XRPL hooks project written in AssemblyScript.", "main": "dist/index.ts", "repository": { "type": "git", "url": "git+https://github.com/jfgrissom/xrpl-hooks-api-assembly-script.git" }, "keywords": ["xrpl", "hooks", "assemblyscript"], "author": "<NAME>", "license": "MIT", "bugs": { "url": "https://github.com/jfgrissom/xrpl-hooks-api-assembly-script/issues" }, "homepage": "https://github.com/jfgrissom/xrpl-hooks-api-assembly-script#readme" }
json
Shaw fell one run short of becoming the youngest Indian T20 League centurion during Delhi’s thrilling Super Over win against Kolkata. Prithvi Shaw fell one run short of becoming the youngest Indian T20 League centurion during Delhi’s thrilling Super Over win against Kolkata on Saturday. Chasing a challenging 186-run target, Delhi rode on the young Mumbai batsman’s 55-ball 99 as the match ended in a tie. (Watch: Rabada leads Delhi to Super-Over win against Kolkata after Shaw’s 99) The hosts went on to win the Super Over after South Africa pacer Kagiso Rabada underlined his greatness firing toe crushers one after another as they defended 10 runs that triggered wild celebrations at the Feroz Shah Kotla. Former India opener Gautam Gambhir reckons Shaw’s role in the side should not be altered. “Delhi should thank Kagiso Rabada for some old-fashioned death bowling in the super over. Prithvi Shaw is carrying his high backlift riding on an even higher confidence quotient,” Gambhir, who led Kolkata to two titles, wrote in his column for the Times of India. (ALSO READ: Injury setback behind him, Prithvi Shaw ready to take IPL by storm) Delhi next face Punjab at the latter’s fortress in Mohali on Monday in what will be an exciting contest. Punjab won all their four games at the IS Bindra Stadium last year before the Ravichandran Ashwin-led side shifted base to Indore. Gambhir advised the Delhi think-tank not to alter Shaw’s role. “When they take on Kings XI Punjab on Monday, Prithvi’s role should not be altered. Mohali is an even better wicket and it should suit his style of play,” he explained.
english
import os import sys import numpy as np import pandas as pd import tensorflow as tf from losses import focal_loss,weighted_binary_crossentropy from utils import Dataset class DeepFM(object): def __init__(self, params): self.feature_size = params['feature_size'] self.field_size = params['field_size'] self.embedding_size = params['embedding_size'] self.deep_layers = params['deep_layers'] self.l2_reg_coef = params['l2_reg'] self.learning_rate = params['learning_rate'] self.pos_ratio = params['pos_ratio'] self.keep_prob_v = params['keep_prob'] self.activate = tf.nn.relu self.weight = {} self.saver=None self.checkpoint_dir = params['checkpoint_dir'] self.build() def build(self): """ feature_size: N field_size: F embedding_size: K batch_size: None """ self.feat_index = tf.placeholder(tf.int32, shape=[None, None], name='feature_index') self.feat_value = tf.placeholder(tf.float32, shape=[None, None], name='feature_value') self.label = tf.placeholder(tf.float32, shape=[None,1], name='label') self.keep_prob = tf.placeholder(tf.float32, shape=[], name='keep_prob') # scaler self.is_training= tf.placeholder(tf.bool, shape=[],name='is_training') #1、-------------------------定义权值----------------------------------------- # FM部分中一次项的权值定义 self.weight['first_order'] = tf.Variable(tf.random_normal([self.feature_size, 1], 0.0, 0.05), # N * 1 name='first_order') # One-hot编码后的输入层与Dense embeddings层的权值定义,即DNN的输入embedding。 self.weight['embedding_weight'] = tf.Variable(tf.random_normal([self.feature_size, self.embedding_size], 0.0, 0.05), # N*K name='embedding_weight') # deep网络部分的weight和bias, deep网络初始输入维度:input_size = F*K num_layer = len(self.deep_layers) input_size = self.field_size * self.embedding_size # glorot_normal = np.sqrt(2.0 / (input_size + self.deep_layers[0])) # for sigmoid he_normal = np.sqrt(2.0 /input_size) # for relu self.weight['layer_0'] = tf.Variable(np.random.normal(loc=0, scale=he_normal, size=(input_size, self.deep_layers[0])), dtype=np.float32) self.weight['bias_0'] = tf.Variable(np.random.normal(loc=0, scale=he_normal, size=(1, self.deep_layers[0])), dtype=np.float32) # 生成deep network里面每层的weight 和 bias for i in range(1, num_layer): he_normal = np.sqrt(2.0 / (self.deep_layers[i - 1])) self.weight['layer_' + str(i)] = tf.Variable(np.random.normal(loc=0, scale=he_normal, size=(self.deep_layers[i - 1], self.deep_layers[i])), dtype=np.float32) self.weight['bias_' + str(i)] = tf.Variable(np.random.normal(loc=0, scale=he_normal, size=(1, self.deep_layers[i])),dtype=np.float32) # deep部分output_size + 一次项output_size + 二次项output_size last_layer_size = self.deep_layers[-1] + self.field_size + self.embedding_size glorot_normal = np.sqrt(2.0 / (last_layer_size + 1)) # 生成最后一层的weight和bias self.weight['last_layer'] = tf.Variable(np.random.normal(loc=0, scale=glorot_normal, size=(last_layer_size, 1)), dtype=np.float32) self.weight['last_bias'] = tf.Variable(tf.constant(0.0), dtype=np.float32) #2、----------------------前向传播------------------------------------ # None*F*K self.embedding_index = tf.nn.embedding_lookup(self.weight['embedding_weight'],self.feat_index) # [None*F*K] .*[None*F*1] = None*F*K self.embedding_part = tf.multiply(self.embedding_index, tf.reshape(self.feat_value, [-1, self.field_size, 1])) # FM部分一阶特征 # None * F*1 self.embedding_first = tf.nn.embedding_lookup(self.weight['first_order'], self.feat_index) #[None*F*1].*[None*F*1] = None*F*1 self.embedding_first = tf.multiply(self.embedding_first, tf.reshape(self.feat_value, [-1, self.field_size, 1])) # None*F self.first_order = tf.reduce_sum(self.embedding_first, 2) # 二阶特征 None*K self.sum_second_order = tf.reduce_sum(self.embedding_part, 1) self.sum_second_order_square = tf.square(self.sum_second_order) self.square_second_order = tf.square(self.embedding_part) self.square_second_order_sum = tf.reduce_sum(self.square_second_order, 1) # 1/2*((a+b)^2 - a^2 - b^2)=ab # None*K self.second_order = 0.5 * tf.subtract(self.sum_second_order_square, self.square_second_order_sum) # FM部分的输出 None*(F+K) self.fm_part = tf.concat([self.first_order, self.second_order], axis=1) # DNN部分 # None*(F*K) self.deep_embedding = tf.reshape(self.embedding_part, [-1, self.field_size * self.embedding_size]) # 全连接部分 for i in range(0, len(self.deep_layers)): self.deep_embedding = tf.add(tf.matmul(self.deep_embedding, self.weight["layer_%d" % i]), self.weight["bias_%d" % i]) # self.deep_embedding =tf.matmul(self.deep_embedding, self.weight["layer_%d" % i]) self.bn_out = tf.layers.batch_normalization(self.deep_embedding, training=self.is_training) # self.bn_out = tf.layers.dropout(self.deep_embedding, rate=self.keep_prob,training=self.is_training) self.deep_embedding = self.activate(self.bn_out) self.deep_embedding = tf.layers.dropout(self.deep_embedding, rate =1.0-self.keep_prob, training= self.is_training) # FM输出与DNN输出拼接 None*(F+K+layer[-1]]) din_all = tf.concat([self.fm_part, self.deep_embedding], axis=1) #None*1 self.out = tf.add(tf.matmul(din_all, self.weight['last_layer']), self.weight['last_bias']) #3. ------------------确定损失--------------------------------------- # loss部分 None*1 self.prob = tf.nn.sigmoid(self.out) # self.entropy_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels= self.label, logits= self.out)) # self.entropy_loss = -tf.reduce_mean( # self.label * tf.log(tf.clip_by_value(self.prob, 1e-10, 1.0))+ (1 - self.label)* tf.log(tf.clip_by_value(1-self.prob,1e-10,1.0))) self.entropy_loss = focal_loss(self.prob, self.label, alpha=0.5, gamma=2) # self.entropy_loss = weighted_binary_crossentropy(self.prob, self.label, pos_ratio=self.pos_ratio) # 正则:sum(w^2)/2*l2_reg_coef self.reg_loss = tf.contrib.layers.l2_regularizer(self.l2_reg_coef)(self.weight["last_layer"]) for i in range(len(self.deep_layers)): self.reg_loss += tf.contrib.layers.l2_regularizer(self.l2_reg_coef)(self.weight["layer_%d" % i]) # tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(self.l2_reg_coef)(self.weight['layer_1'])) # print(self.entropy_loss.shape.as_list(), self.reg_loss.shape.as_list()) self.loss = self.entropy_loss + self.reg_loss self.global_step = tf.Variable(0, trainable=False, name='global_step') self.learning_rate = tf.train.exponential_decay(self.learning_rate, self.global_step,3000, 0.99,staircase=False) opt = tf.train.AdamOptimizer(self.learning_rate) # opt = tf.train.GradientDescentOptimizer(self.learning_rate) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) trainable_params = tf.trainable_variables() gradients = tf.gradients(self.loss, trainable_params) clip_gradients, _ = tf.clip_by_global_norm(gradients, 5) with tf.control_dependencies(update_ops): # self.train_op = opt.minimize(self.loss, global_step = self.global_step) self.train_op = opt.apply_gradients(zip(clip_gradients, trainable_params), global_step=self.global_step) self.saver = tf.train.Saver(max_to_keep=3) def train(self, sess, feat_index, feat_value, label): _, step = sess.run([self.train_op, self.global_step], feed_dict={ self.feat_index: feat_index, self.feat_value: feat_value, self.label: label, self.keep_prob: self.keep_prob_v, self.is_training:True}) return step def predict(self, sess, feat_index, feat_value, batch_size=None): if batch_size is None: prob = sess.run([self.prob], feed_dict={ self.feat_index: feat_index, self.feat_value: feat_value, self.keep_prob: 1, self.is_training:False})[0] else: data =Dataset(feat_value, feat_index, [None]*len(feat_index), batch_size, shuffle=False) probs =[] for feat_index, feat_value, _ in data: prob = sess.run([self.prob], feed_dict={ self.feat_index: feat_index, self.feat_value: feat_value, self.keep_prob: 1, self.is_training:False})[0] probs.append(prob.ravel()) prob = np.concatenate(probs) return prob.ravel() def evaluate(self, sess, feat_index, feat_value, label, batch_size=None): tloss, entloss,regloss = 0,0,0 if batch_size is None: tloss, entloss,regloss = sess.run([self.loss, self.entropy_loss, self.reg_loss],feed_dict={ self.feat_index: feat_index, self.feat_value: feat_value, self.label: label, self.keep_prob: 1, self.is_training:False}) else: data = Dataset(feat_value,feat_index,label, batch_size, shuffle=False) for i, (feat_index, feat_value, label) in enumerate(data,1): _tloss, _entloss, _regloss = sess.run([self.loss, self.entropy_loss, self.reg_loss],feed_dict={ self.feat_index: feat_index, self.feat_value: feat_value, self.label: label, self.keep_prob: 1, self.is_training:False}) tloss = tloss+ (_tloss-tloss)/i entloss = entloss + (_entloss-entloss)/i regloss = regloss + (_regloss-regloss)/i return tloss, entloss, regloss def save(self, sess, path, global_step): if self.saver is not None: self.saver.save(sess, save_path=path, global_step= global_step) def restore(self, sess, path): model_file = tf.train.latest_checkpoint(path) if model_file is not None: print('restore model:', model_file) self.saver.restore(sess, save_path=model_file) if __name__ == '__main__': BASE_PATH = os.path.dirname(os.path.abspath(__file__)) params ={'feature_size':None, 'field_size':None, 'embedding_size':4, 'deep_layers':[32,32,32], 'epoch':200, 'batch_size':128, 'learning_rate':0.001, 'l2_reg': 0.001, 'keep_prob':0.7, 'checkpoint_dir':os.path.join(BASE_PATH,'data/deepfm'), 'training_model':True} with tf.Session() as sess: model = DeepFM(params) sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) # global_step counter etc. sys.stdout.flush() if params['training_model']: #---------------training--------------------------------- for i in range(params['epoch']): print('epoch ={}'.format(i).center(50,'-')) for j, (xi, xv, y) in enumerate(train_data): loss,_, step = model.train(sess, xi, xv, y) if j %1000 ==0: train_loss,train_entropy,train_reg = model.evaluate(sess, Xi,Xv, Y) val_loss,val_entropy, val_reg = model.evaluate(sess, val_Xi, val_Xv, val_y) print('---batch= %d--- \n train_loss=%f,\t train_entropy=%f,\t train_reg=%f \n val_loss=%f,\t val_entropy=%f,\t val_reg=%f' % ( j,train_loss,train_entropy,train_reg, val_loss,val_entropy,val_reg)) if i%10 ==0 or i == params['epoch']-1: model.save(sess, model.checkpoint_dir, i) prob = model.predict(sess, Xi, Xv) hit_rate, top_k = top_ratio_hit_rate(np.array(Y).ravel(), np.array(prob[0]).ravel(), top_ratio=0.001) # ravel return view, flatten return copy print('top-k={}, train-hit-rate={}'.format(top_k ,hit_rate)) #-----------------test----------------------------------- probs =[] test_y=[] for xi, xv, y in test_data: prob = model.predict(sess, xi, xv) # list of np.ndarry probs.extend(prob[0].ravel().tolist()) test_y.extend(y.tolist()) hit_rate, top_k = top_ratio_hit_rate(np.array(test_y).ravel(), np.array(probs).ravel(), top_ratio=0.001) print('top-k={}, test-hit-rate={}'.format(top_k ,hit_rate)) calc_threshold_vs_depth(np.asarray(test_y).ravel(), np.asarray(probs).ravel()) else: model.restore(sess, os.path.split(model.checkpoint_dir)[0]) probs=[] Y =[] for xi, xv, y in train_data: prob = model.predict(sess, xi, xv) # np.ndarry probs.extend(prob[0].ravel().tolist()) Y.extend(y.tolist()) hit_rate, top_k = top_ratio_hit_rate(np.array(Y).ravel(), np.array(probs).ravel(), top_ratio=0.001) print('train-top-k={}, train-hit-rate={}'.format(top_k ,hit_rate)) probs=[] test_y=[] for xi, xv, y in test_data: prob = model.predict(sess, xi, xv) # np.ndarry probs.extend(prob[0].ravel().tolist()) test_y.extend(y.tolist()) hit_rate, top_k = top_ratio_hit_rate(np.array(test_y).ravel(), np.array(probs).ravel(), top_ratio=0.001) print('test-top-k={}, test-hit-rate={}'.format(top_k ,hit_rate))
python
Sarah Jessica Parker says 'Sex and the City' was ‘suffocating’: 'It felt like somebody was holding me hostage' "Sex and the City" with Sarah Jessica Parker almost never happened. The 53-year-old actress who starred as famed columnist Carrie Bradshaw recently revealed that she was reluctant to sign on for "Sex and the City. " After working herself into viable roles as a film and Broadway actress, the series mainstay admitted she was apprehensive to sign on to play the iconic Bradshaw out of fear that the show would consume her life. “I panicked and I was like, ‘I want to maintain my life. I like doing a few plays a year and a movie, and maybe a TV movie of the week,’" she told James Andrew Miller in the latest episode of his "Origins" podcast released on Thursday. Bradshaw explained that she really began freaking out once the show had emerged as a hit and that she had a difficult time adjusting to the grueling schedule that comes with working in television. "All of a sudden it felt like somebody was holding me hostage or something or there just were these limitations which felt very suffocating," she said. Parker is still recognized as the fabulous New York City columnist who has a love affair with Manolos and told Fox News she already knows what's next for Bradshaw, but maintained that fans probably won't get the opportunity to follow her journey anytime soon. Parker's admission comes just days after she opened up about her reported feud with former co-star Kim Cattrall. Parker stressed to Extra that while the other actresses from the series signed up for a possible “Sex and the City 3” movie, except for the 62-year-old, there is no catfight occurring between the women. As for Parker, she is moving on. In fact, she’s currently starring in “Here and Now” as Vivienne, a renowned jazz vocalist preparing to release a new album only to receive a grim health diagnosis. She appears in the drama alongside veteran star Jacqueline Bisset who plays her meddling mother Jeanne. The 74-year-old told Fox News she was pleased to see Parker as the actress and the woman, not just the celebrated fashion icon. Fox News' Stephanie Nolasco contributed to this report.
english
<reponame>JS-VeryHappy/react-taro-app<filename>src/components/LoadMoreCustom/demo/index.tsx import React, { useEffect, useState } from 'react'; import { View, Text } from '@tarojs/components'; import TabbarCustom from '@/components/TabbarCustom'; import NavBarCustom from '@/components/NavBarCustom'; import useLoadMore from '@/hooks/useLoadMore'; import Taro, { useReachBottom } from '@tarojs/taro'; import { lists } from '@/services/api/user'; import styles from './index.module.scss'; /** * 分页使用加载更多使用 * @returns */ const LoadMoreCustomDemo1 = () => { const [optionState, LoadMoreNode, showLoading, hideLoading, isCheckLoading, loadHandle] = useLoadMore(); const [Info, setInfo] = useState<any>([]); const InfoHttp = (page?: any) => { if (!isCheckLoading()) { return false; } showLoading(); lists({ page: page || optionState.page, limit: 30, }) .then((res: any) => { const datas = [...Info, ...res.data.data]; setInfo(datas); loadHandle(res.data); }) .finally(() => { hideLoading(); }); }; useEffect(() => { InfoHttp(1); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useReachBottom(() => { InfoHttp(); }); return ( <> <NavBarCustom title="首页" /> <View className={styles.wrapper}> {Info.map((item, key) => { return ( <View key={item.id} className={styles.title}> <View> 为Taro而设计的Hooks Library</View> <View> asdasdasdasdas Library</View> </View> ); })} <LoadMoreNode optionState={optionState} data={Info} /> </View> <TabbarCustom /> </> ); }; export default LoadMoreCustomDemo1;
typescript
The Sahil Hotel is a beautifully designed hotel with a number of amenities for a luxurious stay. The hotel, located in Mumbai has earned a lot of popularity due to its facilities and services. The location of the hotel makes it more important since it is in close proximity to a few corporate house, shopping malls and bus terminus. The Sahil Hotel has two restaurants, one the Riyaz restaurant, known especially for its traditional Awadhi cuisine and the other Bluet, an all day dining place. The business facilities are also very good, as there are 4 banquet rooms to organize meetings or seminars, with all sorts of useful facilities. The staffs are well behaved and friendly, and therefore are favored by the guests. The hotel is disabled people friendly as it offers special facilities for them. Here are some of the main facilities of the Sahil Hotel. The rooms are categorized as Delux room, suite room and superior room with state of art amenities. In the hotel free private parking facility is available. There are special facilities for disabled people. Business centers are available for people taking a business trip. Other services in the hotel include laundry, dry cleaning, shoe shine etc. There are concierge service and locker facilities available in the Sahil Hotel. There are different categories of rooms in this hotel, but some of the basic facilities which are mentioned below are available in all the categories of room. The Santa Cruz domestic airport and the Chatrapati Shivaji International airport are within 20 km of this hotel. The Chatrapati Shivaji Terminus Railway station is about 3.3 Km away, while Mumbai Central is only about 0.5 km away from this hotel. Some of the nearby tourist attractions of this place are the Gateway of India, the Colaba Causeaway, the Nehru Science Centre among others.
english
import { CrossBrowserCompatibilityPage } from './CrossBrowserCompatibilityPage' import { AsyncCrossBrowserCompatibilityPage } from './AsyncCrossBrowserCompatibilityPage' export { AsyncCrossBrowserCompatibilityPage, CrossBrowserCompatibilityPage }
javascript
<reponame>kisbox/browserslist-config<filename>package.json { "name": "@kisbox/browserslist-config", "version": "1.0.0-beta.21", "description": "A well-balanced browserslist configuration", "author": "MisterTicot <<EMAIL>>", "repository": "github:kisbox/browserslist-config", "license": "MIT", "main": "src/index.js", "keywords": [], "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "prettier": "prettier --write --no-semi --trailing-comma none 'src/**/*.{js,json,md}' '*.{json,md}'", "eslint": "eslint --fix 'src/**/*.js'", "lint": "npm run prettier && npm run eslint", "commit-release": "[ \"$version\" ] && git ci -am \"Release $version\"", "tag-release": "[ \"$version\" ] && git tag -s \"$version\" -m \"Release $version\"", "push-release": "git push --follow-tags", "make-release": "npm run commit-release", "publish-release": "npm run tag-release && npm run push-release && npm publish" }, "devDependencies": { "eslint": "^7.32.0", "prettier": "^2.4.0" } }
json
<reponame>yakuizhao/intel-vaapi-driver # VM Configuration libraries This package supplies library that supports VM configuration by: * creating, initializing and verifying images used to create a VM, * creating configuration file that can be used with `libvirt` directly. ## Details ### `FilePartition` `FilePartition` class offers means to create (both persistent and ephemeral), initialize and access image files. ### `GuestConfig` `GuestConfig` class builds XML configuration string based on supplied details that is used to initialize `libvirt` domain.
markdown
[ { "docstatus": 0, "doctype": "Workflow Action Master", "modified": "2016-08-22 18:25:02.124065", "name": "Approve", "parent": null, "parentfield": null, "parenttype": null, "workflow_action_name": "Approve" }, { "docstatus": 0, "doctype": "Workflow Action Master", "modified": "2016-08-22 18:25:02.126024", "name": "Reject", "parent": null, "parentfield": null, "parenttype": null, "workflow_action_name": "Reject" }, { "docstatus": 0, "doctype": "Workflow Action Master", "modified": "2016-08-22 18:25:02.127240", "name": "Review", "parent": null, "parentfield": null, "parenttype": null, "workflow_action_name": "Review" }, { "docstatus": 0, "doctype": "Workflow Action Master", "modified": "2018-12-18 10:40:22.508330", "name": "Cancel", "parent": null, "parentfield": null, "parenttype": null, "workflow_action_name": "Cancel" }, { "docstatus": 0, "doctype": "Workflow Action Master", "modified": "2019-09-04 00:16:17.689870", "name": "Enviar", "parent": null, "parentfield": null, "parenttype": null, "workflow_action_name": "Enviar" }, { "docstatus": 0, "doctype": "Workflow Action Master", "modified": "2019-09-04 00:16:23.076454", "name": "Aprovar", "parent": null, "parentfield": null, "parenttype": null, "workflow_action_name": "Aprovar" }, { "docstatus": 0, "doctype": "Workflow Action Master", "modified": "2019-09-04 00:16:28.842997", "name": "Reprovar", "parent": null, "parentfield": null, "parenttype": null, "workflow_action_name": "Reprovar" }, { "docstatus": 0, "doctype": "Workflow Action Master", "modified": "2019-09-04 00:16:33.313962", "name": "Cancelar", "parent": null, "parentfield": null, "parenttype": null, "workflow_action_name": "Cancelar" } ]
json
var dir_bce4fe468017adc58bf81882531ea016 = [ [ "Serial.cpp", "_serial_8cpp.html", null ], [ "Serial.hpp", "_serial_8hpp.html", "_serial_8hpp" ] ];
javascript
$("#loginform").on("submit", function(event) { event.preventDefault(); var formData = { 'email': $('input[name=email]').val(), //for get email 'password': $('input[name=password]').val(), //for get email 'secrate_key' : 'demokey' }; $.ajax({ url: "Api/Admin/Login", method: 'POST', data: formData, }) .done(function(data) { let response = JSON.parse(data); if (response.status == 200){ top.location.href = "Dashboard"; swal({ title: "Success", text: response.message, icon: "success", button: false, timer: "1500", }); } else if(response.status == 404) { swal({ title: "Oops!", text: response.message, icon: "error", button: false, timer: "1500", }); } else if(response.status == 400) { swal({ title: "Oops!", text: response.message, icon: "error", button: false, timer: "1500", }); } }); }); var modal = document.getElementById('myModal'); var btn = document.getElementById("popup"); var span = document.getElementsByClassName("close")[0]; btn.onclick = function() { modal.style.display = "block"; } span.onclick = function() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }
javascript
<filename>modules/messenger/notify/notify.service.go // Copyright (c) 2021 Terminus, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package notify import ( "context" "encoding/json" "strconv" "strings" "time" "google.golang.org/protobuf/types/known/timestamppb" "github.com/erda-project/erda-infra/base/logs" "github.com/erda-project/erda-proto-go/core/messenger/notify/pb" monitor "github.com/erda-project/erda-proto-go/core/monitor/alert/pb" "github.com/erda-project/erda/bundle" "github.com/erda-project/erda/modules/messenger/common" "github.com/erda-project/erda/modules/messenger/notify/db" "github.com/erda-project/erda/modules/messenger/notify/model" "github.com/erda-project/erda/pkg/common/apis" "github.com/erda-project/erda/pkg/common/errors" ) type notifyService struct { DB *db.DB L logs.Logger bdl *bundle.Bundle Monitor monitor.AlertServiceServer `autowired:"erda.core.monitor.alert.AlertService" optional:"true"` } func (n notifyService) CreateNotifyHistory(ctx context.Context, request *pb.CreateNotifyHistoryRequest) (*pb.CreateNotifyHistoryResponse, error) { result := &pb.CreateNotifyHistoryResponse{} var historyId int64 var err error if request.NotifyTags != nil { historyId, err = n.CreateHistoryAndIndex(request) if err != nil { return result, errors.NewInternalServerError(err) } } else { dbReq, err := ToDBNotifyHistory(request) if err != nil { return result, errors.NewInternalServerError(err) } history, err := n.DB.NotifyHistoryDB.CreateNotifyHistory(dbReq) if err != nil { return result, errors.NewInternalServerError(err) } historyId = history.ID } result.Data = historyId return result, nil } func ToDBNotifyHistory(request *pb.CreateNotifyHistoryRequest) (*db.NotifyHistory, error) { targetData, err := json.Marshal(request.NotifyTargets) if err != nil { return nil, err } sourceData, err := json.Marshal(request.NotifySource) if err != nil { return nil, err } history := &db.NotifyHistory{ NotifyName: request.NotifyName, NotifyItemDisplayName: request.NotifyItemDisplayName, Channel: request.Channel, TargetData: string(targetData), SourceData: string(sourceData), Status: request.Status, OrgID: request.OrgID, Label: request.Label, ClusterName: request.ClusterName, SourceType: request.NotifySource.SourceType, SourceID: request.NotifySource.SourceID, ErrorMsg: request.ErrorMsg, } return history, nil } func (n notifyService) CreateHistoryAndIndex(request *pb.CreateNotifyHistoryRequest) (historyId int64, err error) { tx := n.DB.Begin() defer func() { if err != nil { tx.Rollback() } else if err := recover(); err != nil { n.L.Errorf("panic: %s", err) tx.Rollback() } else { tx.Commit() } }() dbReq, err := ToDBNotifyHistory(request) if err != nil { return 0, errors.NewInternalServerError(err) } history, err := tx.NotifyHistoryDB.CreateNotifyHistory(dbReq) if err != nil { return 0, err } attributes, err := json.Marshal(request.NotifyTags) if err != nil { return 0, err } alertId := int64(request.NotifyTags["alertId"].GetNumberValue()) alertNotifyIndex := &db.AlertNotifyIndex{ NotifyID: history.ID, NotifyName: request.NotifyItemDisplayName, Status: request.Status, Channel: request.Channel, Attributes: string(attributes), CreatedAt: time.Now(), SendTime: history.CreatedAt, ScopeType: request.NotifySource.SourceType, ScopeID: request.NotifySource.SourceID, OrgID: request.OrgID, AlertId: alertId, } _, err = tx.AlertNotifyIndexDB.CreateAlertNotifyIndex(alertNotifyIndex) if err != nil { return 0, err } return history.ID, nil } func (n notifyService) QueryNotifyHistories(ctx context.Context, request *pb.QueryNotifyHistoriesRequest) (*pb.QueryNotifyHistoriesResponse, error) { orgIdStr := apis.GetOrgID(ctx) orgId, err := strconv.Atoi(orgIdStr) if err != nil { return nil, errors.NewInternalServerError(err) } request.OrgID = int64(orgId) queryReq := &model.QueryNotifyHistoriesRequest{} data, err := json.Marshal(request) if err != nil { return nil, errors.NewInternalServerError(err) } err = json.Unmarshal(data, queryReq) if err != nil { return nil, errors.NewInternalServerError(err) } list, count, err := n.DB.NotifyHistoryDB.QueryNotifyHistories(queryReq) if err != nil { return &pb.QueryNotifyHistoriesResponse{}, nil } result := &pb.QueryNotifyHistoriesResponse{ Data: &pb.QueryNotifyHistoryData{ List: []*pb.NotifyHistory{}, }, } for _, notifyHistory := range list { notify, err := notifyHistory.ToApiData() if err != nil { return result, nil } result.Data.List = append(result.Data.List, notify) } result.Data.Total = count return result, nil } func (n notifyService) GetNotifyStatus(ctx context.Context, request *pb.GetNotifyStatusRequest) (*pb.GetNotifyStatusResponse, error) { orgIdStr := apis.GetOrgID(ctx) result := &pb.GetNotifyStatusResponse{ Data: make(map[string]int64), } orgId, err := strconv.Atoi(orgIdStr) if err != nil { return result, errors.NewInternalServerError(err) } filterStatus := &model.FilterStatusRequest{ OrgId: orgId, ScopeType: request.ScopeType, ScopeId: request.ScopeId, StartTime: request.StartTime, EndTime: request.EndTime, } filterStatusResult, err := n.DB.NotifyHistoryDB.FilterStatus(filterStatus) if err != nil { return result, errors.NewInternalServerError(err) } for _, v := range filterStatusResult { result.Data[v.Status] = v.Count } return result, nil } func (n notifyService) GetNotifyHistogram(ctx context.Context, request *pb.GetNotifyHistogramRequest) (*pb.GetNotifyHistogramResponse, error) { orgIdStr := apis.GetOrgID(ctx) orgId, err := strconv.Atoi(orgIdStr) result := &pb.GetNotifyHistogramResponse{ Data: &pb.NotifyHistogramData{ Timestamp: make([]int64, 0), Value: make(map[string]*pb.StatisticValue), }, } if err != nil { return result, errors.NewInternalServerError(err) } //(endTime-startTime)/points算出interval startTime, err := strconv.ParseInt(request.StartTime, 10, 64) if err != nil { return result, errors.NewInternalServerError(err) } endTime, err := strconv.ParseInt(request.EndTime, 10, 64) if err != nil { return result, errors.NewInternalServerError(err) } interval := (endTime - startTime) / request.Points //和最小的interval进行比较 if interval < common.Interval { interval = common.Interval request.Points = (endTime - startTime) / interval } valueMap := map[string]*pb.StatisticValue{} rs, err := n.DB.NotifyHistoryDB.QueryNotifyValue(request.Statistic, orgId, request.ScopeId, request.ScopeType, interval, startTime, endTime) if err != nil { return nil, errors.NewInternalServerError(err) } for i := 0; int64(i) < request.Points; i++ { result.Data.Timestamp = append(result.Data.Timestamp, startTime) startTime = startTime + interval } for _, v := range rs { _, ok := valueMap[v.Field] if !ok { valueMap[v.Field] = &pb.StatisticValue{ Value: make([]int64, request.Points), } } var i int64 timeUnix := v.RoundTime.UnixNano() / 1e6 for i < request.Points { if timeUnix <= result.Data.Timestamp[i] { valueMap[v.Field].Value[i] = v.Count break } i++ } } result.Data.Value = valueMap return result, nil } func (n notifyService) QueryAlertNotifyHistories(ctx context.Context, request *pb.QueryAlertNotifyHistoriesRequest) (*pb.QueryAlertNotifyHistoriesResponse, error) { result := &pb.QueryAlertNotifyHistoriesResponse{ Data: &pb.AlertNotifyHistories{}, } orgIdStr := apis.GetOrgID(ctx) orgId, err := strconv.Atoi(orgIdStr) if err != nil { return result, errors.NewInternalServerError(err) } queryRequest := &model.QueryAlertNotifyIndexRequest{} data, err := json.Marshal(request) if err != nil { return result, errors.NewInternalServerError(err) } err = json.Unmarshal(data, queryRequest) if err != nil { return result, errors.NewInternalServerError(err) } queryRequest.OrgID = int64(orgId) list, count, err := n.DB.AlertNotifyIndexDB.QueryAlertNotifyHistories(queryRequest) if err != nil { return result, errors.NewInternalServerError(err) } result.Data.Total = count result.Data.List = make([]*pb.AlertNotifyIndex, 0) data, err = json.Marshal(list) if err != nil { return nil, errors.NewInternalServerError(err) } err = json.Unmarshal(data, &result.Data.List) if err != nil { return result, errors.NewInternalServerError(err) } return result, nil } func (n notifyService) GetAlertNotifyDetail(ctx context.Context, request *pb.GetAlertNotifyDetailRequest) (*pb.GetAlertNotifyDetailResponse, error) { result := &pb.GetAlertNotifyDetailResponse{ Data: &pb.AlertNotifyDetail{}, } alertNotifyIndex, err := n.DB.AlertNotifyIndexDB.GetAlertNotifyIndex(request.Id) if err != nil { return result, errors.NewInternalServerError(err) } attributes := model.AlertIndexAttribute{} err = json.Unmarshal([]byte(alertNotifyIndex.Attributes), &attributes) if err != nil { return result, errors.NewInternalServerError(err) } result.Data.Channel = alertNotifyIndex.Channel result.Data.SendTime = timestamppb.New(alertNotifyIndex.SendTime) result.Data.Status = alertNotifyIndex.Status result.Data.NotifyRule = attributes.AlertName result.Data.NotifyGroup = strconv.Itoa(int(attributes.GroupID)) alertNotifyHistory, err := n.DB.NotifyHistoryDB.GetAlertNotifyHistory(alertNotifyIndex.NotifyID) if err != nil { return result, errors.NewInternalServerError(err) } str := strings.TrimLeft(alertNotifyHistory.NotifyName, "【") str = strings.TrimRight(str, "】\n") result.Data.AlertName = str sourceDataParam := model.NotifySourceData{} err = json.Unmarshal([]byte(alertNotifyHistory.SourceData), &sourceDataParam) if err != nil { return result, errors.NewInternalServerError(err) } result.Data.NotifyContent = sourceDataParam.Params.Content return result, nil } func (n notifyService) GetTypeNotifyHistogram(ctx context.Context, request *pb.GetTypeNotifyHistogramRequest) (*pb.GetTypeNotifyHistogramResponse, error) { result := &pb.GetTypeNotifyHistogramResponse{ Data: &pb.TypeNotifyHistogram{ Value: make(map[string]*pb.StatisticValue), }, } orgIdStr := apis.GetOrgID(ctx) orgId, err := strconv.Atoi(orgIdStr) if err != nil { return result, errors.NewInternalServerError(err) } startTime, err := strconv.ParseInt(request.StartTime, 10, 64) if err != nil { return result, errors.NewInternalServerError(err) } endTime, err := strconv.ParseInt(request.EndTime, 10, 64) if err != nil { return result, errors.NewInternalServerError(err) } rs, err := n.DB.NotifyHistoryDB.NotifyHistoryType(request.Statistic, orgId, request.ScopeId, request.ScopeType, startTime, endTime) if err != nil { return result, errors.NewInternalServerError(err) } for _, item := range rs { result.Data.Value[item.Field] = &pb.StatisticValue{Value: []int64{item.Count}} } return result, nil }
go