text stringlengths 1 1.04M | language stringclasses 25 values |
|---|---|
<reponame>micurley/prn
{
"header": {
"category": "leid-stories",
"image": {
"type": "",
"url": ""
},
"layout": "podcast",
"link": "http://leidstories.podbean.com/e/leid-stories-081914/",
"podcast": {
"developer-note": "",
"length": "57:37",
"note": "",
"size": 20745072,
"type": "audio/mpeg",
"url": "http://leidstories.podbean.com/mf/feed/7e8sgp/LeidStories_081914.mp3"
},
"show": {
"category": [
"Society & Culture"
],
"image": {
"height": 144,
"url": "http://imglogo.podbean.com/image-logo/547423/Utrice-Leid-Album-Art.jpg",
"width": 144
},
"owner": {
"email": "<EMAIL>",
"name": "Progressive Radio Network"
},
"published": {
"string": "Thu, 12 Mar 2015 21:05:57 +0000",
"timestamp": "1426212357"
},
"subtitle": "Stories and news that affect us all",
"title": "Leid Stories"
},
"tags": [
"Society & Culture",
"leid-stories"
],
"title": "Leid Stories"
},
"title": "Leid Stories",
"date": "2014-08-19 00:00:00 -0400",
"categories": [
"leid-stories"
],
"content": "<p>‘Attorney at War’ Alton Maddox Warns of Problems in Garner, Brown Cases\nApocalypse Soon?\n<!--more-->\n The Middle East’s Present As Apocalyptic Prologue\nAttorney <NAME>. <br />\nMaddox Jr.<br />\n, who has litigated or played a major role in several high-profile cases involving excessive force by police, discusses major legal issues in two current cases – the July 17 chokehold death of <NAME> in Staten Island, NY, and the shooting death on Aug. <br />\n9 of <NAME> in Ferguson, Missouri.\n<br />\nThe “people’s attorney general,” as he is called, says these legal issues can compromise the integrity of both cases, and, thus, their outcomes. <br />\nMoreover, they can affect the prosecution of other current and future cases of police killings of civilians, Maddox says.\n<br />\nCould the Islamist insurgency in the entire Middle East and North Africa, and repeated military interventions by Europe and the West, be setting the stage for an apocalypse of global proportions?\n<br />\nIt’s quite possible, says our guest, Dr <NAME>, renowned investigative journalist and international security scholar, who posits the theory in a chilling sci-fi thriller, Zero Point, released this week. <br /></p>\n"
}
| json |
/* Global Styles */
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }
* {
box-sizing: border-box;
}
#MyAgenda {
color: var(--primary-color);
}
/* Variables */
:root {
--primary-color: #EA5455;
--secondary-color: #3F51B5;
--secondary-color-hover: #1d32a7;
--white: #FFF;
--black: #222;
--dark-gray: #323232;
--success: #ADFF2F;
}
.msg-success {
background-color: var(--dark-gray);
color: var(--success);
}
.msg-error {
color: var(--primary-color);
} | css |
All eyes are on the preparations for the 13th edition of the Indian Premier League (IPL), which will begin on September 19 in the United Arab Emirates. In the build-up to the much awaited league, players and franchises have been engaging in online banter.
Most recently, Twitter saw a hilarious interaction between the Rajasthan Royals and Kings XI Punjab.
On World Lion Day, Rajasthan Royals shared a photo of Ben Stokes in which the all-rounder has a lion family engraved on his back.
“Name a better tattoo in cricket, we'll wait,” RR had captioned the post. Kings XI Punjab soon responded to the tweet by sharing a picture of their opener Chris Gayle, who has a tattoo of a lion engraved on his chest.
Both Chris Gayle and Ben Stokes will be seen in action in the forthcoming IPL. Chris Gayle will be opening the batting for Kings XI Punjab, and has scored 868 runs in 24 matches for the Punjab outfit.
England and Rajasthan Royals all-rounder Ben Stokes returned to international cricket in the Test series against West Indies in July, followed by the series against Pakistan. He opted out of the last two Tests to visit his family in New Zealand.
England will also be hosting Australia for a white-ball series next month, and Ben Stokes has made himself available for that series. Hence, his arrival in the UAE might be delayed by more than two weeks. In 34 IPL games that Ben Stokes has played so far, he has 635 runs and 26 wickets.
The performances of Chris Gayle and Ben Stokes in the UAE will decide who the real lion is!
| english |
<gh_stars>100-1000
from raspberryturk import is_running_on_raspberryturk, RaspberryTurkError
if not is_running_on_raspberryturk():
raise RaspberryTurkError("Must be running on Raspberry Turk to use {} module.".format(__name__))
| python |
/* latin-ext */
@font-face {
font-family: 'Bungee Inline';
font-style: normal;
font-weight: 400;
src: local('Bungee Inline'), local('BungeeInline-Regular'), url(https://fonts.gstatic.com/s/bungeeinline/v2/Tb-1914q4rFpjT-F66PLCX1PgMwFt2V-WJ2uOZ4WXLU.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Bungee Inline';
font-style: normal;
font-weight: 400;
src: local('Bungee Inline'), local('BungeeInline-Regular'), url(https://fonts.gstatic.com/s/bungeeinline/v2/Tb-1914q4rFpjT-F66PLCTxObtw73-qQgbr7Be51v5c.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* thai */
@font-face {
font-family: 'Kanit';
font-style: normal;
font-weight: 400;
src: local('Kanit'), local('Kanit-Regular'), url(https://fonts.gstatic.com/s/kanit/v1/RPQGAQk3DD66RypwKRnBKQ.woff2) format('woff2');
unicode-range: U+0E01-0E5B, U+200B-200D, U+25CC;
}
/* latin-ext */
@font-face {
font-family: 'Kanit';
font-style: normal;
font-weight: 400;
src: local('Kanit'), local('Kanit-Regular'), url(https://fonts.gstatic.com/s/kanit/v1/2fzaAAzWW07YitDl-NekHg.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Kanit';
font-style: normal;
font-weight: 400;
src: local('Kanit'), local('Kanit-Regular'), url(https://fonts.gstatic.com/s/kanit/v1/5NAKUBdE3Nb95aTaJlZOXQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
html,
body {
font-family: 'Kanit', sans-serif !important;;
}
h1,
h2,
h3,
h4,
h5 {
font-family: 'Bungee Inline', cursive;
}
| css |
{
"type": "Production Trading Tasks",
"paragraphs": [
{
"style": "Block",
"text": "Content",
"updated": 1610106726574
},
{
"style": "Text",
"text": "Superalgos aims to provide a flexible and robust trading bots deployment toolbox."
},
{
"style": "Text",
"text": "With Superalgos, you may deploy as many trading bots as you wish and have them running on a single computer or in as many machines as you wish, in a Trading Farm type of setup. To help with the management of large numbers of live trading sessions, the system helps you with sorting tasks by exchange, market, and trading mine.",
"updated": 1609666769136
},
{
"style": "Text",
"text": "The production environment works pretty much in the same way as the testing environment, save for two important differences:"
},
{
"style": "List",
"text": "The production environment runs forward testing and live trading sessions, instead of backtesting and paper trading sessions."
},
{
"style": "List",
"text": "These two types of sessions involve monetary transactions at the exchange, thus require the set up of a key reference to authenticate your account with the exchange."
},
{
"style": "Note",
"text": "If you are familiar with Testing Trading Tasks, there isn’t much more to learn to understand Production Trading Tasks. If you are not familiar with either, please refer to the Testing Trading Tasks Section page for the details.",
"updated": 1610111338574
},
{
"style": "Include",
"text": "Superalgos->Concept->Reusable Snippets->Deleting Node Warning",
"updated": 1610122740064
}
],
"definition": {
"text": "The Production Trading Tasks node organizes trading sessions involving live trading.",
"updated": 1609666696048
}
} | json |
<reponame>healeycodes/calorie-king<filename>db.js
const fs = require('fs');
const setup = () => {
const dbFile =
process.env.NODE_ENV === 'test' ? './data/test.db' : './data/sqlite.db';
const exists = fs.existsSync(dbFile);
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(dbFile);
db.serialize(() => {
if (!exists) {
db.run(
'CREATE TABLE Users (user TEXT, goal INTEGER, points, INTEGER, visited TEXT, activity TEXT)'
);
console.log('New table Users created!');
db.run(
'CREATE TABLE Meals (id INTEGER PRIMARY KEY, user TEXT, name TEXT, cals INTEGER, date INTEGER)'
);
console.log('New table Meals created!');
}
});
return db;
};
module.exports = setup;
| javascript |
<gh_stars>100-1000
{
"id": 111468,
"info": {
"name": "Scroll Details Card on Google Contacts",
"description": "I wasn't able to scroll the details card on Google Contacts. This vexed me. So I fixed it and trimmed a little bit of the padding.",
"additionalInfo": "The new Google Contacts layout is pretty darn cool - and a lot more is statically declared - so I'm not going to compact it like I had before.",
"format": "uso",
"category": "google",
"createdAt": "2015-03-13T21:44:04.000Z",
"updatedAt": "2015-03-13T21:44:04.000Z",
"license": "NO-REDISTRIBUTION",
"author": {
"id": 150421,
"name": "<NAME>",
"homepage": "http://stevensaus.com"
}
},
"stats": {
"installs": {
"total": 181,
"weekly": 0
}
},
"screenshots": {
"main": {
"name": "111468_after.png",
"archived": false
},
"additional": [
{
"name": "111468_additional_14293.png",
"archived": false
},
{
"name": "111468_additional_14294.png",
"archived": false
}
]
},
"discussions": {
"stats": {
"discussionsCount": 0,
"commentsCount": 0
},
"data": []
},
"style": {
"css": "@namespace url(http://www.w3.org/1999/xhtml);\r\n\r\n@-moz-document domain(\"contacts.google.com\") {\r\n/* There are a lot more static elements now; the main thing I wanted to\r\n * do was to be able to scroll the contact card and make it a tiny bit\r\n * more compact */\r\n\r\n.nCCa6e.G-q {\r\nposition: relative !important; }\r\n\r\n.G2RIEb {\r\nposition: relative !important; }\r\n\r\n.gAGAfb \r\n{\r\nmargin-bottom: 5px !important;\r\npadding-bottom: 5px !important; }\r\n\r\n.G-q-B {\r\nline-height: 1em !important;}\r\n}"
}
} | json |
/**
* Model list with their configuration
* @type {Object}
*/
export var models = {};
/**
* Singulars/plural correspondences
* @type {Object}
*
* @property {Object} singulars - Singular -> plural correspondences
* @property {Object} plurals - Plural -> Singular correspondences
*/
export var names = {
singulars: {},
plurals: {}
/**
* NOT YET INTERNATIONALIZABLE, it's only a prototype.
* @type {{ofOne: string, ofMany: string}}
*/
};export var locale = {
ofOne: {},
ofMany: {}
/**
* Generates a model
* @param singular
* @param plural
* @param fields
* @param relations
*/
};export var generate = function generate(singular, plural) {
var fields = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var relations = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var localeTerms = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
names.singulars[plural] = singular;
names.plurals[singular] = plural;
locale.ofMany[plural] = localeTerms.ofMany || plural;
locale.ofOne[singular] = localeTerms.ofOne || "a " + singular;
models[singular] = {
fields: fields,
relations: {
many: relations.many || [],
one: relations.one || [],
habtm: relations.habtm || []
}
};
};
/**
* Returns complete relations from model definition.
*
* @param {string} name - Singular model name
*
* @return {Object}
*/
export var relations = function relations(name) {
return models[name].relations;
};
/**
* Returns the plural form of a singular name from `names` var, or adds an 's'...
*
* @param {string} name - Singular model name
*
* @return {string}
*/
export var plural = function plural(name) {
if (names.plurals[name]) {
// console.log(`Plural found for ${name}`);
return names.plurals[name];
}
console.error("Plural not found for " + name + ", falling back");
return name + "s";
};
/**
* Returns the singular form of a plural name from `names` var or removes the last char.
*
* @param {string} name - Plural model name
*
* @return {string}
*/
export var singular = function singular(name) {
if (names.singulars[name]) {
// console.log(`Singular found for ${name}`);
return names.singulars[name];
}
console.error("Singular not found for " + name + ", falling back.");
return name.slice(0, name.length - 1);
};
export var fields = function fields(model) {
return models[model].fields;
};
export default { models: models, names: names, locale: locale, generate: generate, fields: fields, relations: relations, plural: plural, singular: singular }; | javascript |
import { dayjsInstance } from '../../services/date';
const sanitizeString = (value) => {
if (!value) return null;
if (typeof value === 'string') return value;
if (typeof `${value}` === 'string') return `${value}`;
return null;
};
const sanitizeNumber = (value) => {
if (!isNaN(value)) return value;
if (!isNaN(parseInt(value, 10))) return parseInt(value, 10);
return null;
};
const sanitizeDate = (value) => {
// https://stackoverflow.com/a/643827/5225096
if (typeof value?.getMonth === 'function' || value instanceof dayjsInstance) return value;
if (!isNaN(new Date(value).getMonth())) return new Date(value);
return null;
};
const sanitizeYesNo = (value) => {
value = sanitizeString(value);
if (!value) return null;
if (['Oui', 'Non'].includes(value)) return value;
if (value === 'No') return 'Non';
if (value === 'Yes') return 'Oui';
return null;
};
const sanitizeEnum = (value, possibleValues = []) => {
value = sanitizeString(value);
if (!value) return null;
if (possibleValues.includes(value)) return value;
return null;
};
const sanitizeMultiChoice = (value, possibleValues = []) => {
// value is either string or array
if (!Array.isArray(value)) {
value = sanitizeString(value);
if (!value) return null;
value = value.split(',');
}
value = value.filter((value) => possibleValues.includes(value));
if (value.length) return value;
return null;
};
const sanitizeBoolean = (value) => {
if (typeof value === 'undefined') return null;
// We have to handle the case where value is a string (cf: import XLSX users).
if (typeof value === 'string') {
if (['true', 'oui', 'yes'].includes(value.toLowerCase())) return true;
if (['false', 'non', 'no'].includes(value.toLowerCase())) return false;
}
return Boolean(value);
};
export function sanitizeFieldValue(field, { v: rawValue, w: formattedText }) {
if (field.type === 'text') return sanitizeString(rawValue);
if (field.type === 'textarea') return sanitizeString(rawValue);
if (field.type === 'number') return sanitizeNumber(rawValue);
if (field.type === 'date') return sanitizeDate(formattedText);
if (field.type === 'date-with-time') return sanitizeDate(formattedText);
if (field.type === 'yes-no') return sanitizeYesNo(rawValue);
if (field.type === 'enum') return sanitizeEnum(rawValue, field.options);
if (field.type === 'multi-choice') return sanitizeMultiChoice(rawValue, field.options);
if (field.type === 'boolean') return sanitizeBoolean(rawValue);
return rawValue;
}
| javascript |
Lyon, June 7 (IANS) FC Lyon striker Alexandre Lacazette has asserted that he is interested in a move to the English Premier League (EPL).
Speaking on Facebook Live, the star striker, who has scored 100 goals in 203 matches for Lyon, said he will take a decision on his future following the current round of international matches with France.
“That could be an interesting option, it is a great league with interesting teams,” he said during the interview on Tuesday.
This development will surely delight EPL clubs like Arsenal, Manchester United and Chelsea, all of whom have been linked with the 26-year-old who scored 37 goals for Lyon this season.
Arsenal boss Arsene Wenger has stepped up efforts to buy the striker as he met the French club’s president Jean-Michael Aulas in order to thrash out the details of the transfer.
The transfer will reportedly cost the former EPL champions 50 million pounds ($64.6 million) and Lacazette will earn 200,000 pounds ($258,000) a week while playing for the current FA Cup champions.
The France international’s proposed transfer to Atletico Madrid fell through because of a transfer ban imposed upon the Spanish club by the Court of Arbitration for Sport for the current transfer window.
But Lacazette is reportedly keen on a playing for Atletico Madrid and had not ruled out a possible move in the future.
| english |
We have been ready to share our knowledge of internet marketing worldwide and recommend you suitable merchandise at most aggressive rates. So Profi Tools present you very best price of money and we are ready to develop alongside one another with Led Cabinet Light, A5 Display Stand, Retail Store Shelves And Displays, Department Store Display,Shop Display. As we are moving forward, we keep an eye on our ever-expanding product range and make improvement to our services. The product will supply to all over the world, such as Europe, America, Australia,Japan, Somalia,Bandung, Brisbane.Now, we are trying to enter new markets where we do not have a presence and developing the markets we have now the already penetrated. On account of superior quality and competitive price , we'll be the market leader, be sure to don??¥t hesitate to contact us by phone or email, if you are interested in any of our solutions.
| english |
At least 29 people were killed and several others were injured when a Delhi-bound Uttar Pradesh State Roadways Transport Corporation (UPSRTC) Janrath bus fell off Yamuna Expressway in Uttar Pradesh’s Agra, early on Monday morning.
According to the reports the bus fell into a nullah.
The bus, carrying at least 44 people from Lucknow to Delhi met with an accident today morning, reports said.
Senior officials were rushed to the spot and the rescue operation is underway.
The injured were immediately taken to the hospital for further treatment.
“DGP UP OP Singh has directed to carry out relief & rescue work in full swing and is supervising it personally. All senior officers present at the spot,” UP Police said.
Our condolences to the bereaved family members & prayers for the departed soul. We also wish a speedy recovery to the injured,” UP Police added.
Chief Minister Yogi Adityanath paid his condolences on the death of the people and directed officials to provide all possible help to the injured and the families of those killed in the accident, sources said. | english |
From Microsoft Bob to Edubuntu there have been a number of attempts at making computers of various sorts easier and more useful for young people. Another participant in this space is Kiddix, “a complete operating system and software environment for children, built from the ground up with your family’s needs and safety in mind.” Kiddix is built upon Linux, and aims to present things in a very “kid friendly” way. Through the end of June, Kiddix is running a “Pay What You Want” promotion, allowing you to pay any amount to buy their OS.
I admit I’d never heard of Kiddix before. From the Kiddix FAQ:
Q: I’ve used Edubuntu, Qimo, or another “kids” Linux distribution. How is Kiddix different?
A: Simply put, we don’t aim to be a “Linux for kids”. Instead, we utilize Linux and Open Source Software as a base for providing children with a full operating system designed just for them. As far as we know, Kiddix is, and has been, the the only OS on the market exclusively designed from the ground up for children.
Inside Kiddix we offer a fully customized desktop environment for children that has been designed with the help of parents, teachers, and development psychologists. Children have access to a wide variety of software which has all been customized to be used by children ages 4-11. Also included are many acclaimed open source applications, games, and educational material.
Simplicity and ease of use for both children and parents is a primary focus of our software design. On the backend parents have access to a variety of comprehensive and easy-to-use parental controls.
I’m a Linux user, so the value proposition of paying for Kiddix is not clear to me: when something like Edubuntu is free (as in beer), why would I pay for something similar? The Kiddix World magazine concept seems like a good idea, and might have been worth paying for, but it’s been discontinued. Maybe I’m being overly critical, but it doesn’t seem to me that Kiddix has sufficiently explained why I should pay anything for their OS.
Of course, not all parents are familiar with Linux, or the Free Software mentality, so perhaps Kiddix is sufficiently turnkey to make this a good choice for them. And the “Pay What You Want” promotion makes it a low-risk decision.
If you’ve used Kiddix, sound off in the comments about your experience.
| english |
For those who don’t already know, Thaman is composing the music for Mahesh Babu’s upcoming film Sarkaru Vaari Paata.
In his latest interaction, Thaman opened up about the film and made an interesting statement.
“Sarkaru Vaari Paata is a high octane actioner. The film is loaded with commercial elements. It will be on the lines of Dookudu,” he revealed.
When asked about Mahesh’s next with Trivikram, Thaman said this film is on a different dimension. “Mahesh Babu and Trivikram are collaborating after a long gap and they are planning to go big,” he said.
Thaman had already competed composing three songs for Sarkaru Vaari Paata. | english |
Rafael Nadal said on Friday that without the media “we will not be the athletes that we are today” as Naomi Osaka became increasingly isolated over her decision to boycott all French Open press commitments.
Japanese star Osaka caused a stir at Roland Garros by announcing that she will refuse to carry out any press activity at the tournament, claiming she fears the effect of them on her mental health.
The four-time major winner believes the traditional post-match inquests are akin to “kicking people when they are down”.
Nadal, the 13-time French Open champion, said that even though he respected Osaka’s decision, media coverage has driven the success of the sport.
“I understand her, but for me without the press, without the people who are writing the news and achievements that we are having around the world probably we will not be the athletes that we are today,” said Nadal, a 20-time major winner.
Osaka, the world number two, risks fines of up to $20,000 for skipping news conferences at the French Open which starts on Sunday.
The 23-year-old’s closest rival and 2019 French Open winner Ashleigh Barty said carrying out media duties is part and parcel of the job.
“We know what we sign up for as professional tennis players,” the 25-year-old Australian said.
French Tennis Federation president Gilles Moretton lambasted Osaka.
Defending champion Iga Swiatek, who is close to Osaka, said she is happy to speak to the press.
“It’s important because not everybody is a professional athlete and not everybody knows what we are dealing with on court. It’s good to speak about that,” said the Pole who turns 20 on Monday.
However, she also believes it’s crucial to have a support system to “separate you from hate or something”.
World No 2 Daniil Medvedev could be forgiven for having a rocky relationship with the media thanks to a French Open record for four matches played, four matches lost.
| english |
On this week's episode of RAW, it was announced that Rhea Ripley will defend her Women's World Championship at WWE Day 1 in two weeks.
The Eradicator is one of the most dominant female superstars in the entire company, and she's been champion since WrestleMania 39. Her latest title defense was at Survivor Series: WarGames, where she faced Zoey Starks.
On the latest episode of Monday Night RAW, Damian Priest and Finn Balor defended their Undisputed WWE Tag Team Championship against The Creed Brothers. Rhea Ripley and Ivy Nile got physical during the bout, and they stood face-to-face last week after The Judgment Day member defeated Maxxine Dupri.
During a backstage segment, Mami said she wanted to teach Ivy a lesson, and she was so confident that she put her title on the line. It was later confirmed that on the Day 1 episode of RAW, Rhea Ripley and Ivy Nile will collide for the Women's World Championship.
This will be the latter's first time competing in a championship match since arriving on the red brand, and it's undoubtedly the biggest match of her career. If she defeats Ripley, it'll be a huge upset.
Do you think Ivy Nile can dethrone Rhea? Sound off in the comments below!
| english |
<gh_stars>1-10
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { UpdateUseAvatarUseCase } from './UpdateUseAvatarUseCase';
class UpdateUseAvatarController {
async handle(request: Request, response: Response): Promise<Response> {
const { id } = request.user;
const avatar_File = request.file.filename;
const updateUseAvatarUseCase = container.resolve(UpdateUseAvatarUseCase);
await updateUseAvatarUseCase.execute({ user_id: id, avatar_File });
return response.status(204).send();
}
}
export { UpdateUseAvatarController };
| typescript |
<reponame>Bloombox/Java<gh_stars>1-10
/*
* Copyright 2019, Momentum Ideas, Co. All rights reserved.
*
* Source and object computer code contained herein is the private intellectual
* property of Momentum Ideas Co., a Delaware Corporation. Use of this
* code in source form requires permission in writing before use or the
* assembly, distribution, or publishing of derivative works, for commercial
* purposes or any other purpose, from a duly authorized officer of Momentum
* Ideas Co.
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: identity/industry/StaffSettings.proto
package io.bloombox.schema.identity.industry;
public final class UserStaffSettings {
private UserStaffSettings() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
public interface StaffSettingsOrBuilder extends
// @@protoc_insertion_point(interface_extends:bloombox.identity.industry.StaffSettings)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
boolean hasPos();
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings getPos();
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettingsOrBuilder getPosOrBuilder();
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
boolean hasDashboard();
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings getDashboard();
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettingsOrBuilder getDashboardOrBuilder();
}
/**
* <pre>
* Settings for staff users, attached to a user's overall industry profile. Applies in any context where the user is
* authorized for industry-side use of Bloombox products.
* </pre>
*
* Protobuf type {@code bloombox.identity.industry.StaffSettings}
*/
public static final class StaffSettings extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:bloombox.identity.industry.StaffSettings)
StaffSettingsOrBuilder {
private static final long serialVersionUID = 0L;
// Use StaffSettings.newBuilder() to construct.
private StaffSettings(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private StaffSettings() {
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private StaffSettings(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings.Builder subBuilder = null;
if (pos_ != null) {
subBuilder = pos_.toBuilder();
}
pos_ = input.readMessage(io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(pos_);
pos_ = subBuilder.buildPartial();
}
break;
}
case 18: {
io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings.Builder subBuilder = null;
if (dashboard_ != null) {
subBuilder = dashboard_.toBuilder();
}
dashboard_ = input.readMessage(io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(dashboard_);
dashboard_ = subBuilder.buildPartial();
}
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.bloombox.schema.identity.industry.UserStaffSettings.internal_static_bloombox_identity_industry_StaffSettings_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.bloombox.schema.identity.industry.UserStaffSettings.internal_static_bloombox_identity_industry_StaffSettings_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings.class, io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings.Builder.class);
}
public static final int POS_FIELD_NUMBER = 1;
private io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings pos_;
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
public boolean hasPos() {
return pos_ != null;
}
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
public io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings getPos() {
return pos_ == null ? io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings.getDefaultInstance() : pos_;
}
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
public io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettingsOrBuilder getPosOrBuilder() {
return getPos();
}
public static final int DASHBOARD_FIELD_NUMBER = 2;
private io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings dashboard_;
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
public boolean hasDashboard() {
return dashboard_ != null;
}
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
public io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings getDashboard() {
return dashboard_ == null ? io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings.getDefaultInstance() : dashboard_;
}
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
public io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettingsOrBuilder getDashboardOrBuilder() {
return getDashboard();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (pos_ != null) {
output.writeMessage(1, getPos());
}
if (dashboard_ != null) {
output.writeMessage(2, getDashboard());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (pos_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, getPos());
}
if (dashboard_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getDashboard());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings)) {
return super.equals(obj);
}
io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings other = (io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings) obj;
if (hasPos() != other.hasPos()) return false;
if (hasPos()) {
if (!getPos()
.equals(other.getPos())) return false;
}
if (hasDashboard() != other.hasDashboard()) return false;
if (hasDashboard()) {
if (!getDashboard()
.equals(other.getDashboard())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasPos()) {
hash = (37 * hash) + POS_FIELD_NUMBER;
hash = (53 * hash) + getPos().hashCode();
}
if (hasDashboard()) {
hash = (37 * hash) + DASHBOARD_FIELD_NUMBER;
hash = (53 * hash) + getDashboard().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Settings for staff users, attached to a user's overall industry profile. Applies in any context where the user is
* authorized for industry-side use of Bloombox products.
* </pre>
*
* Protobuf type {@code bloombox.identity.industry.StaffSettings}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:bloombox.identity.industry.StaffSettings)
io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettingsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.bloombox.schema.identity.industry.UserStaffSettings.internal_static_bloombox_identity_industry_StaffSettings_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.bloombox.schema.identity.industry.UserStaffSettings.internal_static_bloombox_identity_industry_StaffSettings_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings.class, io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings.Builder.class);
}
// Construct using io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (posBuilder_ == null) {
pos_ = null;
} else {
pos_ = null;
posBuilder_ = null;
}
if (dashboardBuilder_ == null) {
dashboard_ = null;
} else {
dashboard_ = null;
dashboardBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.bloombox.schema.identity.industry.UserStaffSettings.internal_static_bloombox_identity_industry_StaffSettings_descriptor;
}
@java.lang.Override
public io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings getDefaultInstanceForType() {
return io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings.getDefaultInstance();
}
@java.lang.Override
public io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings build() {
io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings buildPartial() {
io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings result = new io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings(this);
if (posBuilder_ == null) {
result.pos_ = pos_;
} else {
result.pos_ = posBuilder_.build();
}
if (dashboardBuilder_ == null) {
result.dashboard_ = dashboard_;
} else {
result.dashboard_ = dashboardBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings) {
return mergeFrom((io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings other) {
if (other == io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings.getDefaultInstance()) return this;
if (other.hasPos()) {
mergePos(other.getPos());
}
if (other.hasDashboard()) {
mergeDashboard(other.getDashboard());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings pos_;
private com.google.protobuf.SingleFieldBuilderV3<
io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings, io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings.Builder, io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettingsOrBuilder> posBuilder_;
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
public boolean hasPos() {
return posBuilder_ != null || pos_ != null;
}
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
public io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings getPos() {
if (posBuilder_ == null) {
return pos_ == null ? io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings.getDefaultInstance() : pos_;
} else {
return posBuilder_.getMessage();
}
}
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
public Builder setPos(io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings value) {
if (posBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
pos_ = value;
onChanged();
} else {
posBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
public Builder setPos(
io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings.Builder builderForValue) {
if (posBuilder_ == null) {
pos_ = builderForValue.build();
onChanged();
} else {
posBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
public Builder mergePos(io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings value) {
if (posBuilder_ == null) {
if (pos_ != null) {
pos_ =
io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings.newBuilder(pos_).mergeFrom(value).buildPartial();
} else {
pos_ = value;
}
onChanged();
} else {
posBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
public Builder clearPos() {
if (posBuilder_ == null) {
pos_ = null;
onChanged();
} else {
pos_ = null;
posBuilder_ = null;
}
return this;
}
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
public io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings.Builder getPosBuilder() {
onChanged();
return getPosFieldBuilder().getBuilder();
}
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
public io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettingsOrBuilder getPosOrBuilder() {
if (posBuilder_ != null) {
return posBuilder_.getMessageOrBuilder();
} else {
return pos_ == null ?
io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings.getDefaultInstance() : pos_;
}
}
/**
* <pre>
* Point-of-sale device settings. Includes the user's authorization code hash, public key hash, and other settings or
* security details. User preferences on the point-of-sale device are also stored here.
* </pre>
*
* <code>.bloombox.identity.industry.POSStaffSettings pos = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings, io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings.Builder, io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettingsOrBuilder>
getPosFieldBuilder() {
if (posBuilder_ == null) {
posBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings, io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettings.Builder, io.bloombox.schema.identity.industry.StaffPOSSettings.POSStaffSettingsOrBuilder>(
getPos(),
getParentForChildren(),
isClean());
pos_ = null;
}
return posBuilder_;
}
private io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings dashboard_;
private com.google.protobuf.SingleFieldBuilderV3<
io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings, io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings.Builder, io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettingsOrBuilder> dashboardBuilder_;
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
public boolean hasDashboard() {
return dashboardBuilder_ != null || dashboard_ != null;
}
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
public io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings getDashboard() {
if (dashboardBuilder_ == null) {
return dashboard_ == null ? io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings.getDefaultInstance() : dashboard_;
} else {
return dashboardBuilder_.getMessage();
}
}
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
public Builder setDashboard(io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings value) {
if (dashboardBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
dashboard_ = value;
onChanged();
} else {
dashboardBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
public Builder setDashboard(
io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings.Builder builderForValue) {
if (dashboardBuilder_ == null) {
dashboard_ = builderForValue.build();
onChanged();
} else {
dashboardBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
public Builder mergeDashboard(io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings value) {
if (dashboardBuilder_ == null) {
if (dashboard_ != null) {
dashboard_ =
io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings.newBuilder(dashboard_).mergeFrom(value).buildPartial();
} else {
dashboard_ = value;
}
onChanged();
} else {
dashboardBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
public Builder clearDashboard() {
if (dashboardBuilder_ == null) {
dashboard_ = null;
onChanged();
} else {
dashboard_ = null;
dashboardBuilder_ = null;
}
return this;
}
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
public io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings.Builder getDashboardBuilder() {
onChanged();
return getDashboardFieldBuilder().getBuilder();
}
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
public io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettingsOrBuilder getDashboardOrBuilder() {
if (dashboardBuilder_ != null) {
return dashboardBuilder_.getMessageOrBuilder();
} else {
return dashboard_ == null ?
io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings.getDefaultInstance() : dashboard_;
}
}
/**
* <pre>
* Settings specific to the web dashboard when this user signs in. Personalization and preference options expressed
* for update by the user in the dashboard are stored here. These are distinguished from organization settings in that
* they are not shared between users and generally only apply cosmetically.
* </pre>
*
* <code>.bloombox.identity.industry.DashboardStaffSettings dashboard = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings, io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings.Builder, io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettingsOrBuilder>
getDashboardFieldBuilder() {
if (dashboardBuilder_ == null) {
dashboardBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings, io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettings.Builder, io.bloombox.schema.identity.industry.StaffDashboardSettings.DashboardStaffSettingsOrBuilder>(
getDashboard(),
getParentForChildren(),
isClean());
dashboard_ = null;
}
return dashboardBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:bloombox.identity.industry.StaffSettings)
}
// @@protoc_insertion_point(class_scope:bloombox.identity.industry.StaffSettings)
private static final io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings();
}
public static io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<StaffSettings>
PARSER = new com.google.protobuf.AbstractParser<StaffSettings>() {
@java.lang.Override
public StaffSettings parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new StaffSettings(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<StaffSettings> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<StaffSettings> getParserForType() {
return PARSER;
}
@java.lang.Override
public io.bloombox.schema.identity.industry.UserStaffSettings.StaffSettings getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_bloombox_identity_industry_StaffSettings_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_bloombox_identity_industry_StaffSettings_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n%identity/industry/StaffSettings.proto\022" +
"\032bloombox.identity.industry\032(identity/in" +
"dustry/POSStaffSettings.proto\032.identity/" +
"industry/DashboardStaffSettings.proto\"\221\001" +
"\n\rStaffSettings\0229\n\003pos\030\001 \001(\0132,.bloombox." +
"identity.industry.POSStaffSettings\022E\n\tda" +
"shboard\030\002 \001(\01322.bloombox.identity.indust" +
"ry.DashboardStaffSettingsBC\n$io.bloombox" +
".schema.identity.industryB\021UserStaffSett" +
"ingsH\001P\000\242\002\003BBSb\006proto3"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
io.bloombox.schema.identity.industry.StaffPOSSettings.getDescriptor(),
io.bloombox.schema.identity.industry.StaffDashboardSettings.getDescriptor(),
}, assigner);
internal_static_bloombox_identity_industry_StaffSettings_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_bloombox_identity_industry_StaffSettings_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_bloombox_identity_industry_StaffSettings_descriptor,
new java.lang.String[] { "Pos", "Dashboard", });
io.bloombox.schema.identity.industry.StaffPOSSettings.getDescriptor();
io.bloombox.schema.identity.industry.StaffDashboardSettings.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| java |
"""
Profile the time needed for retrieval.
We consider retrieval in a corpus of 1M videos, 1K videos are added, 10K queries are retrieved.
Calculate the time needed for adding 1K videos, and performing retrieval for 10K queries.
1, Data Loading time is ignored, consider it is hidden by computation time.
2, Sort time is ignored, since it is the similar among the methods.
"""
import os
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import pprint
from tqdm import tqdm, trange
from baselines.crossmodal_moment_localization.model_xml import XML, xml_base_config
from baselines.mixture_embedding_experts.model import MEE, mee_base_cfg
from baselines.clip_alignment_with_language.model import CALWithSub, cal_base_cfg
from baselines.excl.model import EXCL, excl_base_cfg
from utils.basic_utils import save_json
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(format="%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=logging.INFO)
def mask_logits(target, mask):
return target * mask + (1 - mask) * (-1e10)
class ProfileBase(object):
N_NewQuery = 1e4
N_NewVideo = 1e3
N_Videos = 1e6
AvgVideoLength = 100
ClipLength = 5
AvgClipPerVideo = int(AvgVideoLength / ClipLength) # max_ctx_l
AvgWordInQuery = 15
# estimated by
# scales=[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], => max_proposal = 14
AvgProposalPerVideo = 170
MaxClipPerProposal = 14 # pad to this length
AvgClipPerProposal = 7 # 6.88
VideoFeatureDim = 3074 # 1024 + 2048 + 2 (TEF)
SubFeatureDim = 770
QueryFeatureDim = 768
HiddenSize = 256
N_Runs = 5 # Get the average time
def __init__(self, device=torch.device("cuda:0"), ctx_batch_size=400, query_batch_size=100):
self.device = device
self.ctx_batch_size = ctx_batch_size
self.query_batch_size = query_batch_size
self.model_config = self.get_model_config()
print(self.model_config)
self.model = self.get_model()
def get_model(self):
return None
def get_model_config(self):
return None
def set_ctx_batch_size(self, batch_size):
self.ctx_batch_size = batch_size
def set_query_batch_size(self, batch_size):
self.query_batch_size = batch_size
def cast_dict_inputs_to_device(self, dict_inputs, device):
return {k: v.to(device) for k, v in dict_inputs.items()}
def get_fake_ctx_raw_input_st_ed(self, no_tef=False):
return dict(
video_feat=torch.FloatTensor(self.ctx_batch_size, self.model_config.max_ctx_l,
self.VideoFeatureDim - 2*no_tef),
sub_feat=torch.FloatTensor(self.ctx_batch_size, self.model_config.max_ctx_l, self.SubFeatureDim - 2*no_tef),
ctx_mask=torch.FloatTensor(self.ctx_batch_size, self.model_config.max_ctx_l),
)
def get_fake_raw_query(self):
return dict(
query_feat=torch.FloatTensor(self.query_batch_size, self.AvgWordInQuery, self.QueryFeatureDim),
query_mask=torch.ones(self.query_batch_size, self.AvgWordInQuery)
)
"""
from baselines.profiling.profile_main import ProfileXML
profile_xml = ProfileXML(ctx_batch_size=400, query_batch_size=100)
profile_xml.get_ctx_encoding_time()
"""
class ProfileXML(ProfileBase):
def get_model_config(self):
xml_base_config["ctx_mode"] = "video_sub_tef"
xml_base_config["merge_two_stream"] = True
xml_base_config["cross_att"] = True
xml_base_config["max_ctx_l"] = self.AvgClipPerVideo
xml_base_config["visual_input_size"] = self.VideoFeatureDim
xml_base_config["query_input_size"] = self.QueryFeatureDim
xml_base_config["sub_input_size"] = self.SubFeatureDim
xml_base_config["hidden_size"] = self.HiddenSize
return xml_base_config
def get_model(self):
model = XML(self.model_config)
model.to(self.device)
model.eval()
return model
def get_fake_encoded_ctx(self):
return dict(
ctx_feat=torch.FloatTensor(self.ctx_batch_size, self.model_config.max_ctx_l, self.HiddenSize),
ctx_mask=torch.FloatTensor(self.ctx_batch_size, self.model_config.max_ctx_l),
)
def get_fake_encoded_query(self):
return dict(query_feat=torch.FloatTensor(self.ctx_batch_size, self.HiddenSize))
def _get_ctx_encoding_time(self, video_feat, sub_feat, ctx_mask):
"""Considered two modalities"""
torch.cuda.synchronize()
st_time = time.time()
self.model.cross_encode_context(video_feat, ctx_mask, sub_feat, ctx_mask)
torch.cuda.synchronize()
return time.time() - st_time
def get_ctx_encoding_time(self):
with torch.no_grad():
fake_ctx_inputs = self.cast_dict_inputs_to_device(self.get_fake_ctx_raw_input_st_ed(), self.device)
raw_video = fake_ctx_inputs["video_feat"]
raw_sub = fake_ctx_inputs["sub_feat"]
ctx_mask = fake_ctx_inputs["ctx_mask"]
times = []
for _ in trange(self.N_Runs):
times += [self._get_ctx_encoding_time(raw_video, raw_sub, ctx_mask)]
times = torch.FloatTensor(times)
return dict(avg=float(times.mean()), std=float(times.std()))
def _get_query_encoding_time(self, raw_query, query_mask):
"""Considered two modalities"""
torch.cuda.synchronize()
st_time = time.time()
encoded_query = self.model.encode_input(raw_query, query_mask,
self.model.query_input_proj,
self.model.query_encoder,
self.model.query_pos_embed) # (N, Lq, D)
# video level
video_query, sub_query = \
self.model.get_modularized_queries(encoded_query, query_mask, return_modular_att=False)
# st ed
video_query = self.model.video_query_linear(video_query)
sub_query = self.model.sub_query_linear(sub_query)
torch.cuda.synchronize()
return time.time() - st_time
def get_query_encoding_time(self):
with torch.no_grad():
query_inputs = self.cast_dict_inputs_to_device(self.get_fake_raw_query(), self.device)
raw_query = query_inputs["query_feat"]
query_mask = query_inputs["query_mask"]
times = []
for _ in trange(self.N_Runs):
times += [self._get_query_encoding_time(raw_query, query_mask)]
times = torch.FloatTensor(times)
return dict(avg=float(times.mean()), std=float(times.std()))
def _get_retrieval_time(self, encoded_video_query, encoded_video, ctx_mask):
"""Consider the queries are encoded, Calculate in a single modality then multiply by 2."""
torch.cuda.synchronize()
st_time = time.time()
self.model.get_video_level_scores(encoded_video_query, encoded_video, ctx_mask)
torch.cuda.synchronize()
return (time.time() - st_time) * 2
def get_retrieval_time(self):
with torch.no_grad():
encoded_query = self.cast_dict_inputs_to_device(self.get_fake_encoded_query(), self.device)["query_feat"]
fake_ctx_inputs = self.cast_dict_inputs_to_device(self.get_fake_encoded_ctx(), self.device)
encoded_ctx = fake_ctx_inputs["ctx_feat"]
ctx_mask = fake_ctx_inputs["ctx_mask"]
times = []
for _ in trange(self.N_Runs):
times += [self._get_retrieval_time(encoded_query, encoded_ctx, ctx_mask)]
times = torch.FloatTensor(times) # since we have two modalities
return dict(avg=float(times.mean()), std=float(times.std()))
def _get_span_prediction_time(self, query_feat, ctx_feat, ctx_mask):
"""Considered two modalities"""
torch.cuda.synchronize()
st_time = time.time()
similarity = torch.einsum("md,nld->mnl", query_feat, ctx_feat)
similarity = (similarity + similarity) / 2 # (Nq, Nv, L) from query to all videos.
n_q, n_c, l = similarity.shape
similarity = similarity.view(n_q * n_c, 1, l)
st_prob = self.model.merged_st_predictor(similarity).view(n_q, n_c, l) # (Nq, Nv, L)
ed_prob = self.model.merged_ed_predictor(similarity).view(n_q, n_c, l) # (Nq, Nv, L)
st_prob = mask_logits(st_prob, ctx_mask) # (N, L)
ed_prob = mask_logits(ed_prob, ctx_mask)
torch.cuda.synchronize()
return time.time() - st_time
def get_span_prediction_time(self):
with torch.no_grad():
encoded_query = self.cast_dict_inputs_to_device(self.get_fake_encoded_query(), self.device)["query_feat"]
fake_ctx_inputs = self.cast_dict_inputs_to_device(self.get_fake_encoded_ctx(), self.device)
encoded_ctx = fake_ctx_inputs["ctx_feat"]
ctx_mask = fake_ctx_inputs["ctx_mask"]
times = []
for _ in trange(self.N_Runs):
times += [self._get_span_prediction_time(encoded_query, encoded_ctx, ctx_mask)]
times = torch.FloatTensor(times)
return dict(avg=float(times.mean()), std=float(times.std()))
"""
from baselines.profiling.profile_main import ProfileMEE
profile_mee = ProfileMEE(ctx_batch_size=400, query_batch_size=100)
profile_mee.get_ctx_encoding_time()
"""
class ProfileMEE(ProfileBase):
def get_model_config(self):
mee_base_cfg["ctx_mode"] = "video_sub"
mee_base_cfg["text_input_size"] = self.QueryFeatureDim
mee_base_cfg["vid_input_size"] = self.VideoFeatureDim
mee_base_cfg["output_size"] = self.HiddenSize
return mee_base_cfg
def get_model(self):
model = MEE(self.model_config)
model.to(self.device)
model.eval()
return model
def get_fake_raw_ctx(self):
return dict(
vid_feat=torch.FloatTensor(self.ctx_batch_size, self.VideoFeatureDim),
sub_feat=torch.FloatTensor(self.ctx_batch_size, self.QueryFeatureDim)
)
def get_fake_encoded_ctx_query(self):
return dict(
ctx_feat=torch.FloatTensor(self.ctx_batch_size, self.HiddenSize),
query_feat=torch.FloatTensor(self.ctx_batch_size, self.HiddenSize)
)
def _get_ctx_encoding_time(self, vid_feat, sub_feat):
torch.cuda.synchronize()
st_time = time.time()
self.model.video_gu(vid_feat)
self.model.sub_gu(sub_feat)
torch.cuda.synchronize()
return time.time() - st_time
def get_ctx_encoding_time(self):
feat_dict = self.cast_dict_inputs_to_device(self.get_fake_raw_ctx(), self.device)
with torch.no_grad():
times = []
for _ in trange(self.N_Runs):
times += [self._get_ctx_encoding_time(**feat_dict)]
times = torch.FloatTensor(times)
return dict(avg=float(times.mean()), std=float(times.std()))
def _get_query_encoding_time(self, query_feat):
"""Considered 2 modalities"""
torch.cuda.synchronize()
st_time = time.time()
pooled_query = self.model.query_pooling(query_feat) # (N, Dt)
video_query = self.model.video_query_gu(pooled_query)
sub_query = self.model.sub_query_gu(pooled_query)
stream_weights = self.model.moe_fc(pooled_query) # (N, 2)
torch.cuda.synchronize()
return time.time() - st_time
def get_query_encoding_time(self):
raw_query = self.cast_dict_inputs_to_device(self.get_fake_raw_query(), self.device)["query_feat"]
with torch.no_grad():
times = []
for _ in trange(self.N_Runs):
times += [self._get_query_encoding_time(raw_query)]
times = torch.FloatTensor(times)
return dict(avg=float(times.mean()), std=float(times.std()))
def _get_retrieval_time(self, encoded_query, encoded_ctx):
"""Considered 2 modalities"""
torch.cuda.synchronize()
st_time = time.time()
torch.einsum("md,nd->mn", encoded_query, encoded_ctx) # (N, N)
torch.cuda.synchronize()
return (time.time() - st_time) * 2
def get_retrieval_time(self):
model_inputs = self.cast_dict_inputs_to_device(self.get_fake_encoded_ctx_query(), self.device)
encoded_query = model_inputs["ctx_feat"]
encoded_ctx = model_inputs["query_feat"]
with torch.no_grad():
times = []
for _ in trange(self.N_Runs):
times += [self._get_retrieval_time(encoded_query, encoded_ctx)]
times = torch.FloatTensor(times)
return dict(avg=float(times.mean()), std=float(times.std()))
class ProfileCAL(ProfileBase):
def get_model_config(self):
cal_base_cfg["ctx_mode"] = "video_sub"
cal_base_cfg["embedding_size"] = self.QueryFeatureDim
cal_base_cfg["visual_input_size"] = self.VideoFeatureDim * 2
cal_base_cfg["textual_input_size"] = self.SubFeatureDim * 2
cal_base_cfg["output_size"] = self.HiddenSize
return cal_base_cfg
def get_model(self):
model = CALWithSub(self.model_config)
model.to(self.device)
model.eval()
return model
def get_fake_raw_ctx(self, model_name="cal"):
"""The features are `*2` since they use both global and local features"""
return dict(
sub_feat=torch.FloatTensor(self.ctx_batch_size, self.AvgProposalPerVideo,
self.AvgClipPerProposal, self.SubFeatureDim * 2),
vid_feat=torch.FloatTensor(self.ctx_batch_size, self.AvgProposalPerVideo,
self.AvgClipPerProposal, self.VideoFeatureDim * 2))
def _get_ctx_encoding_time(self, sub_feat, vid_feat, model_name="cal"):
if model_name == "mcn":
sub_feat = sub_feat.sum(2)
vid_feat = vid_feat.sum(2)
torch.cuda.synchronize()
st_time = time.time()
self.model.moment_encoder(vid_feat, module_name="video")
self.model.moment_encoder(sub_feat, module_name="sub")
torch.cuda.synchronize()
return time.time() - st_time
def get_ctx_encoding_time(self, model_name="cal"):
"""model_name: str, `cal` or `mcn`"""
feat_dict = self.cast_dict_inputs_to_device(
self.get_fake_raw_ctx(model_name=model_name), self.device)
feat_dict["model_name"] = model_name
with torch.no_grad():
times = []
for _ in trange(self.N_Runs):
times += [self._get_ctx_encoding_time(**feat_dict)]
times = torch.FloatTensor(times)
return dict(avg=float(times.mean()), std=float(times.std()))
def _get_query_encoding_time(self, query_feat, query_mask):
torch.cuda.synchronize()
st_time = time.time()
self.model.query_encoder(query_feat, query_mask)
torch.cuda.synchronize()
return time.time() - st_time
def get_query_encoding_time(self):
feat_dict = self.cast_dict_inputs_to_device(self.get_fake_raw_query(), self.device)
with torch.no_grad():
times = []
for _ in trange(self.N_Runs):
times += [self._get_query_encoding_time(**feat_dict)]
times = torch.FloatTensor(times)
return dict(avg=float(times.mean()), std=float(times.std()))
class ProfileExCL(ProfileBase):
def get_model_config(self):
excl_base_cfg["ctx_mode"] = "video_sub"
excl_base_cfg["query_input_size"] = self.QueryFeatureDim
excl_base_cfg["visual_input_size"] = self.VideoFeatureDim
excl_base_cfg["sub_input_size"] = self.SubFeatureDim
excl_base_cfg["output_size"] = self.HiddenSize
return excl_base_cfg
def get_model(self):
model = EXCL(self.model_config)
model.to(self.device)
model.eval()
return model
def get_fake_raw_input(self):
"""The features are `*2` since they use both global and local features"""
return dict(
query_feat=torch.FloatTensor(self.ctx_batch_size, self.AvgWordInQuery, self.QueryFeatureDim),
query_mask=torch.ones((self.ctx_batch_size, self.AvgWordInQuery)),
sub_feat=torch.FloatTensor(self.ctx_batch_size, self.AvgClipPerVideo, self.SubFeatureDim),
sub_mask=torch.ones(self.ctx_batch_size, self.AvgClipPerVideo),
video_feat=torch.FloatTensor(self.ctx_batch_size, self.AvgClipPerVideo, self.VideoFeatureDim),
video_mask=torch.ones(self.ctx_batch_size, self.AvgClipPerVideo),
tef_feat=torch.FloatTensor(self.ctx_batch_size, self.AvgClipPerVideo, 2),
tef_mask=torch.ones(self.ctx_batch_size, self.AvgClipPerVideo),
st_ed_indices=torch.ones(2, 2), # not used.
)
def _get_prediction_time(self, input_dict):
torch.cuda.synchronize()
st_time = time.time()
self.model(**input_dict)
torch.cuda.synchronize()
return time.time() - st_time
def get_prediction_time(self):
"""model_name: str, `cal` or `mcn`"""
feat_dict = self.cast_dict_inputs_to_device(
self.get_fake_raw_input(), self.device)
feat_dict["is_training"] = False
with torch.no_grad():
times = []
for _ in trange(self.N_Runs):
times += [self._get_prediction_time(feat_dict)]
times = torch.FloatTensor(times)
return dict(avg=float(times.mean()), std=float(times.std()))
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--model", type=str, help="")
parser.add_argument("--ctx_batch_size", type=int, default=400)
parser.add_argument("--query_batch_size", type=int, default=100)
parser.add_argument("--save_dir", type=str, default="baselines/profiling/cache")
args = parser.parse_args()
model = args.model
query_batch_size = args.query_batch_size
ctx_batch_size = args.ctx_batch_size
if model == "mee":
profile_mee = ProfileMEE(ctx_batch_size=ctx_batch_size, query_batch_size=query_batch_size)
# use the 2nd one to report time
profile_mee.get_ctx_encoding_time()
ctx_enc_time = profile_mee.get_ctx_encoding_time()
query_enc_time = profile_mee.get_query_encoding_time()
elif model == "cal":
profile_cal = ProfileCAL(ctx_batch_size=ctx_batch_size, query_batch_size=query_batch_size)
# use the 2nd one to report time
profile_cal.get_ctx_encoding_time()
ctx_enc_time = profile_cal.get_ctx_encoding_time(model_name="cal")
query_enc_time = profile_cal.get_query_encoding_time()
elif model == "mcn":
profile_cal = ProfileCAL(ctx_batch_size=ctx_batch_size, query_batch_size=query_batch_size)
# use the 2nd one to report time
profile_cal.get_ctx_encoding_time()
ctx_enc_time = profile_cal.get_ctx_encoding_time(model_name="mcn")
query_enc_time = profile_cal.get_query_encoding_time()
elif model == "xml":
profile_xml = ProfileXML(ctx_batch_size=ctx_batch_size, query_batch_size=query_batch_size)
# use the 2nd one to report time
profile_xml.get_ctx_encoding_time()
ctx_enc_time = profile_xml.get_ctx_encoding_time()
query_enc_time = profile_xml.get_query_encoding_time()
elif model == "excl":
profile_excl = ProfileExCL(ctx_batch_size=ctx_batch_size, query_batch_size=ctx_batch_size)
# use the 2nd one to report time
profile_excl.get_prediction_time()
ctx_enc_time = profile_excl.get_prediction_time()
query_enc_time = 0
# Calculate the total time as ctx_enc_time * (100 * 1M / ctx_batch_size)
else:
raise NotImplementedError
# ctx_enc_time = ctx_enc_time
save_path = os.path.join(args.save_dir, "{}_profile_main.json".format(model))
n_videos = ProfileBase.N_Videos
res = dict(
ctx_enc_time=ctx_enc_time,
ctx_enc_avg_time_all_videos=ctx_enc_time["avg"] * n_videos / ctx_batch_size,
query_enc_time=query_enc_time,
n_videos=n_videos,
ctx_batch_size=ctx_batch_size,
query_batch_size=query_batch_size,
model=model
)
save_json(res, save_path, save_pretty=True)
pprint.pprint(res)
| python |
<filename>public/src/jobs/beatmap.js<gh_stars>1-10
const path = require('path')
const log = require('electron-log')
const fileType = require('file-type')
const fse = require('../utils/file.js')
const { JobError } = require('./job.js')
const { findPath } = require('../logic/pathFinder.js')
const { saveBeatmap } = require('../logic/beatmap.js')
const { safeDownload } = require('../remote/remote.js')
const { inputType, fromHash, fromID } = require('../remote/beatsaver.js')
const { getActiveWindow } = require('../utils/window.js')
const { ERRORS } = require('../constants.js')
class BeatmapError extends JobError {
constructor (message, status, title) {
super(message, status, title)
this.title = title || 'Beatmap Install Error'
}
}
/**
* @param {string} input BeatSaver Key
* @returns {Promise.<void>}
*/
const beatSaverBeatmap = async input => {
// Window Details
const { sender } = getActiveWindow()
// Find install path
const install = await findPath()
if (install.platform === 'unknown') throw new BeatmapError(ERRORS.INVALID_INSTALL_DIR)
// Validate input type
const type = inputType(input)
if (type === 'invalid') throw new BeatmapError('Invalid Song ID / Hash!')
// Download song info
sender.send('set-status', { text: 'Downloading song info...' })
const { error, song } = await (type === 'hash' ? fromHash(input) : fromID(input))
if (error) throw new BeatmapError(`Song Not Found!\nFailed to find "${input}"`)
// Download song zip
sender.send('set-status', { text: 'Downloading song zip...' })
const zip = await safeDownload(song.downloadUrl, true)
if (zip.error) {
log.error(zip.error)
throw new BeatmapError('Song Download Failed!')
}
try {
await saveBeatmap(zip.body, song.key, install.path)
return undefined
} catch (err) {
log.error(err)
throw new BeatmapError('Extraction Failure!')
}
}
/**
* @param {string} filePath File Path
* @returns {Promise.<void>}
*/
const fileBeatmap = async filePath => {
// Find install path
const install = await findPath()
if (install.platform === 'unknown') throw new BeatmapError(ERRORS.INVALID_INSTALL_DIR)
// Parse file info
const { base, name } = path.parse(filePath)
// Validate file exists
const fileExists = await fse.exists(filePath)
if (!fileExists) throw new BeatmapError(`Could not find file ${base}!`)
// Read and validate file
const zip = await fse.readFile(filePath)
const { mime } = fileType(zip)
if (mime !== 'application/zip') throw new BeatmapError('File is not a Beatmap zip!')
// Delete and install
await fse.remove(filePath)
await saveBeatmap(zip, name, install.path)
return undefined
}
module.exports = { beatSaverBeatmap, fileBeatmap }
| javascript |
Micro-blogging site Twitter has started rolling out a new feature for all iOS users that will now let them pin five lists to their timeline and also allow a quicker swipe between different groups of accounts directly from home screen.
Twitter announced the new update in a tweet, saying, "Make lists even better for you! Now on iOS, you can pin up to five lists, rearrange them, and swipe to access from home."
With this new feature, Twitter users can do things like group co-workers, friends along with family into different lists, and then with a swipe, view just tweets from each individual list, MacRumors reported on Monday.
"Customizable timelines that are easy to access? We are thinking about ways to do this! One idea we had is for you to be able to swipe to your lists from home. If you are in the test tell us what you think," the company had originally tweeted in June when it had previously tested the feature among some users. In July, it added, "Ready for more customisation? Now you can pick which lists will appear and pin them. Just don't let your lists know you're playing favourites."
As per the report, Twitter has also changed the design of list pages, introducing header images and making it easier to see list of members and who is subscribed to the given list.
| english |
<gh_stars>1-10
var searchData=
[
['uibarbuttonitem_28initwithimage_29',['UIBarButtonItem(initwithimage)',['../category_u_i_bar_button_item_07initwithimage_08.html',1,'']]],
['uicustomalertview',['UICustomAlertView',['../interface_u_i_custom_alert_view.html',1,'']]],
['uidevice_28platformname_29',['UIDevice(platformName)',['../category_u_i_device_07platform_name_08.html',1,'']]],
['uiimage_28custom_29',['UIImage(custom)',['../category_u_i_image_07custom_08.html',1,'']]],
['uiimage_28hnk_5futils_29',['UIImage(hnk_utils)',['../category_u_i_image_07hnk__utils_08.html',1,'']]],
['uiimageview_28haneke_29',['UIImageView(Haneke)',['../category_u_i_image_view_07_haneke_08.html',1,'']]],
['uiscreen_28property_29',['UIScreen(property)',['../category_u_i_screen_07property_08.html',1,'']]],
['uistatictableviewcontrollerbase',['UIStaticTableViewControllerBase',['../interface_u_i_static_table_view_controller_base.html',1,'']]],
['uistatictableviewcontrollerbase_28_29',['UIStaticTableViewControllerBase()',['../category_u_i_static_table_view_controller_base_07_08.html',1,'']]],
['uitableviewcontrollerbase',['UITableViewControllerBase',['../interface_u_i_table_view_controller_base.html',1,'']]],
['uitableviewcontrollerbase_28_29',['UITableViewControllerBase()',['../category_u_i_table_view_controller_base_07_08.html',1,'']]],
['uiview_28position_29',['UIView(position)',['../category_u_i_view_07position_08.html',1,'']]],
['uiview_28property_29',['UIView(property)',['../category_u_i_view_07property_08.html',1,'']]],
['uiviewcontrollerbase',['UIViewControllerBase',['../interface_u_i_view_controller_base.html',1,'']]],
['uiviewcontrollerbase_28_29',['UIViewControllerBase()',['../category_u_i_view_controller_base_07_08.html',1,'']]],
['usermodel',['UserModel',['../interface_user_model.html',1,'']]],
['usermodelbase',['UserModelBase',['../interface_user_model_base.html',1,'']]],
['usernotice_5fst',['USERNOTICE_st',['../struct_u_s_e_r_n_o_t_i_c_e__st.html',1,'']]]
];
| javascript |
Cyberabad Police on Friday picked up four suspects in connection with a gang rape and murder of a 22-year-old veterinarian in the outskirts here on Wednesday.
Those detained include a truck driver and a cleaner. The police suspect the girl was gang raped by the accused, who later strangulated her to death and burnt the body.
The Cyberabad Police officials are likely to announce the arrests and reveal the details of the case later in the day.
While the victim was gang raped and murdered near the Tondupally toll plaza in Shamshabad on the outskirts here, her body was dumped and burnt 25 km away at the Chatanpally Bridge in the Ranga Reddy district.
The incident sent shockwaves across the state, drew all round condemnation besides bringing people from all walks of life out on streets in protest against the heinous crime. They also raised the issue of law and order in the particular district.
Telangana Minister K. T. Rama Rao on Friday condemned the incidentand promised to personally monitor the case.
Rama Rao, son of Chief Minister K. Chandrashekhar Rao, said the government would ensure that the victim gets justice at the earliest.
Police suspect the victim was raped and murdered by those who offered to help her in rectifying a punctured two-wheeler.
The victim's clothes, footwear and a liquor bottle were recovered by the police near the toll plaza, where she had parked her scooty.
Ten police teams were directed immediately after the crime broke, to crack the case.
According to the police, the victim had called her sister around 9. 45 p. m. that her vehicle was punctured and somebody has offered to help her. They had promised to take her vehicle for repair.
The sister, however, did mention to the police that she felt the victim was feeling threatened by some truck drivers standing nearby.
The victim's sister had advised her to leave the vehicle, go to the toll plaza and return home by a cab. However, when the sister later called her back, her mobile phone was switched off.
The family lodged a missing complaint with the police around 11 p. m.
The police on Thursday morning found the charred body of the victim near Shadnagar.
Investigations revealed that the victim had left her house in Shamshabad for Kolluru village to attend duty at the veterinary hospital. She returned in the evening at the toll plaza, parked her scooty nearby and took a cab to go to Gachibowli to visit a dermatologist.
When she returned at the same place around 9 p. m. , she found the two-wheeler punctured.
Police suspect the vehicle was deliberately punctured by the culprits to trap the victim. | english |
State Bank of India Shoranur Regional Manager Anu Raghurajan, Indian Oil Corporation Chief General Manager Rajendran and Vaniyamkulam Gram Panchayat members spoke on the occasion, an official statement said. Beneficiaries of various central government schemes, including Ujjwala Yojana, NULM (National Urban Livelihoods Mission), and PM SVANidhi, shared their experience on the occasion.
In its letter the Delhi government's Director of Vigilance wrote "It also needs to be investigated whether the same drugs which have been procured by the Central Procurement Agency (CPA) are also being distributed to the patients through the 'Mohalla Clinics' or not". The letter further said that any action for supplying 'Not of Standard Quality' drugs should not be confined to the CPA and there is need to investigate the entire supply chain -- the role of the suppliers who procured from manufacturers and provided supply to the end users, that is, hospitals (patients).
Kiyosaki's approach centers around the concept of "good debt," which involves using loans to build wealth through income-generating assets such as real estate and investments. He advocates for leveraging debt in investments, particularly in the real estate market, as a proactive strategy to navigate market fluctuations effectively. Kiyosaki's investment portfolio extends beyond traditional avenues and encompasses gold, silver, real estate, and even Wagyu cattle, reflecting his belief in diversification and non-conventional assets.
Renowned author Robert Kiyosaki shocks by admitting $1.2 billion debt, defending it as a strategic move. He views luxury vehicles as liabilities, challenges conventional savings, and advocates leveraging good debt in investments, particularly in real estate.
The Central Drugs Standard Control Organisation (CDSCO), along with state drug inspectors, has been carrying out inspections as part of a nationwide crackdown on spurious and substandard drugs. At present, phase IV of risk-based inspections is on.
More than 75% of the firms have also been issued show cause notices, the people said. Out of the total samples drawn from these manufacturing units, 15.1% have so far been declared to be of not of standard quality (NSQ). The regulator is currently conducting Phase IV of these inspections.
This disregard is all-pervasive. Right from the individual level, when one does not bother to wear a helmet while riding a two-wheeler, to the organisational level, when there is poor regard towards environment, health and safety (EHS) norms, to the government level, where adequate deterrence is not built into the system to make safety of the citizenry a priority.
"The general level of awareness and compliance related to EHS (Environment Health & Safety) norms in case of manufacturing companies requires drastic improvement and urgent attention" said Nagaraj Krishnan, managing director, Aparajitha Corporate Services, a tech firm providing compliance solutions to over 2000 companies in India.
Experts have indicated that the current impact of stubble burning on Delhi's air quality is minimal, but this may change as wind conditions are expected to calm down. Punjab recorded 656 paddy-residue burning incidents, while Haryana saw 166, and Uttar Pradesh reported 74 cases between September 15 and October 4. The daily count of fires in these states surpasses 6,000 at its peak.
Sanjeev Sanyal, a Member of the Economic Advisory Council to the Prime Minister, spoke at the Africa Partnership Conference in Mauritius about the need for clear Environmental, Social & Governance (ESG) norms. He emphasized the importance of globally recognized ESG norms and effective monitoring of their implementation. Sanyal also discussed India's economic growth, infrastructure development, and its aim to become the world's 3rd largest economy.
The U.S. military, employers and economic development specialists have been raising alarms about the implications of American students' low math scores for the country's competitiveness and national security.
The G20 leaders have emphasized the importance of implementing well-calibrated policies to promote growth, reduce inequalities, and maintain macroeconomic and financial stability. They have also stressed the commitment of central banks to achieving price stability and ensuring that inflation expectations remain anchored. The leaders have welcomed steps taken by the Financial Stability Board and Standard Setting Bodies to examine lessons from recent banking turbulence.
The Union home ministry has framed guidelines to decongest prisons and has asked states and Union Territories to release economically weaker prisoners who are in jails due to non-payment of fine or unable to secure bail due to financial constraints.
Naturally, questions will arise over the timing of the rating action. Expectations of monetary tightening bringing the US economy to a standstill are receding. Doomsayers are in retreat, and Fitch finds itself under attack — from the administration and from independent observers. Standard & Poor’s, Moody’s and Fitch had warned the US its AAA credit rating was at risk. But only one has acted on it.
There is an important subtext, though. This emerging cohort of the middle class is not homogenous. Measured in terms of household incomes, the middle class is stratified. The annual household income of the middle class varies between ₹5 lakh and ₹30 lakh. This intra-middle-class inequality gets amplified when this segment is compared with two other cohorts - destitute (less than ₹1.25 lakh) and wealthy households (more than ₹30 lakh).
About 135 million Indians have moved out of multidimensional poverty in the past five years, according to India's NITI Aayog. The proportion of poor in the country fell from 24.8% to 14.9% between 2015-16 and 2019-21. Uttar Pradesh saw the highest number of people exiting poverty, followed by Bihar, Madhya Pradesh, Rajasthan, and West Bengal.
India witnessed an achievement in poverty reduction as 415 million people moved out of poverty within 15 years, from 2005/2006 to 2019/2021, according to the United Nations. The Multidimensional Poverty Index update also highlighted that 25 countries, including China, Cambodia, and Vietnam, managed to halve their global MPI values within the same timeframe, demonstrating the possibility of rapid progress, but acknowledged the negative effects of the COVID-19 pandemic on poverty reduction.
"We will be shortly notifying the quality control orders. All aluminium, copper and nickel that is sold in the country will need to follow the minimum quality standards," said a senior mines ministry official, who did not wish to be identified. In March, the ministry had issued draft quality control orders and sought public comments. The final notification is being issued after stakeholder consultations.
"Sabse jyada culprit koi hai toh DPR banane wala (The biggest culprit is the entity which makes DPR). DPR quality is a big issue," he said, adding that the preference should be given to international companies as such reports made by Indian companies are not good.
The blanket use of the global benchmark overstates India's child malnutrition problem. This is not to suggest that malnutrition is not a serious issue. The percentage of malnourished children is high even using the local standard. But effective policymaking requires accurate measurement.
Such a person, with no tax savings options like home loan repayment or Sec 80C investments like insurance policies or PPF beyond PF deduction would have been paying Rs 39k tax under the new regime. She would now pay nothing.
The decision not to increase exposure to the dollar and other foreign currencies in relation to Bangladesh stemmed from the current economic situation and the neighbouring nation's shortage of foreign currency, the bank said in its circular.
SBI, India’s largest bank by assets, jumped two spots to be ranked 22nd in the list with $695 billion in assets. HDFC Bank, the country’s private sector bank also improved its position to 44th from 46th last year. ICICI just about made it to the list at number 50 with $226 billion in assets.
| english |
vetor = []
i = 1
while(i <= 100):
valor = int(input())
vetor.append(valor)
i = i + 1
print(max(vetor))
print(vetor.index(max(vetor)) + 1) | python |
<reponame>DavidSongzw/RN-Gank
export function getFullPath ({path, w, h}) {
let fullPath = path
fullPath += `?imageView2/1/w/${w}/h/${h}/interlace/1`
return fullPath
}
| javascript |
package org.jeecg.modules.pd.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.io.Serializable;
/**
* 实体的公共父类
*/
@Data
public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
public static final String DEL_FLAG_NORMAL = "0";
public static final String DEL_FLAG_DELETE = "1";
public BaseEntity() {
this.delFlag = DEL_FLAG_NORMAL;
}
/**删除标志*/
@TableLogic
private String delFlag;
}
| java |
TAGS: EAGR, EAID, ECIN, EFIN, EINT, EINV, ENRG, ETRD, ETTC,
(B, D)
1. (SBU) Madame Secretary: Mission India warmly welcomes you to India. This is an opportune moment in the relationship between the world's largest democracies. The Congress Party's strong showing in the April elections allowed formation of a new and strong Indian government--freed from the constraints of anti-American coalition partners or a precarious political position---with a commitment to elevate the bilateral relationship.
2. (SBU) As the Obama Administration's first cabinet Secretary to visit India and meet the new Indian government, you are well-positioned to launch our partnership to the next level. Both the Indian government and public eagerly await your visit. The speech you gave at the USIBC event received much favorable press here.
3. (C) During your visit we plan to announce the formal establishment of a new architecture for our bilateral relationship. You will sign the Science and Technology (S&T) Endowment Agreement, which creates a $30 million endowment to fund joint projects. We will also highlight an agreement on technology safeguards (TSA) that will boost what we hope will be expedited negotiations for a Commercial Space Launch Agreement (CSLA) and expand opportunities for satellite services. In addition, we hope to announce resolution of a long-standing roadblock to an expanded defense relationship if agreement is reached on End Use Monitoring (EUM) language. We also hope to announce the opening of talks on a Bilateral Investment Treaty. We have encouraged the Indian government to announce publicly during your visit the designation of two nuclear reactor sites for U. S. companies.
4. (SBU) The strong performance by the Congress Party and its United Progressive Alliance allies in India's national elections in April provided the Congress Party with a mandate to govern, after years of battling communists and regional coalition ""partners"" over both domestic and foreign policy issues, including a closer relationship with the United States. This has allowed the Prime Minister to assemble a cabinet that some in the media have referred to as ""Manmohan's dream team,"" including the new External Affairs Minister, SM Krishna. Krishna is the first Indian foreign minister to have received a degree from a U. S. university (Southern Methodist University, along with a Fulbright term at George Washington University). In his first press interaction, he promised to consolidate India's partnership with the United States, along with other major powers. With the return to the Cabinet of key players such as Pranab Mukherjee as Finance Minister, P Chidambaram as Home Minister, and AK Antony as Defense Minister, we anticipate stability in our bilateral relationship and a continuation of the positive, if sometimes bumpy, trajectory that has marked our ties for the past decade.
5. (C) Your visit will be crucial in reassuring India that the relationship is as important to the current administration as it was to the previous one. Some Indian pundits fear that Washington is no longer looking at India through the Asian geopolitical prism but rather through the regional--i. e. , Afghanistan-Pakistan lens. In contrast, they believe the new administration has focused on China as the key player on Asian issues. These observers feel threatened by discussion of trilateral security talks between the U. S. , China, and Japan.
6. (SBU) India's goal is to become a regional power and global player. The ambition at the top echelons of the government is readily apparent, as India vigorously pursues its number one foreign policy goal -- a permanent UNSC seat. India uses its voice in the G-20 and active engagement in multilateral fora like the East Asia Summit and Brazil-Russia-India-China (BRIC) Summit to raise its profile. The same ambition drives military modernization efforts and spurs India to take on greater security responsibilities, not only in longstanding UN peacekeeping operations, but also in joint security efforts such as anti-piracy operations off Somalia.
7. (SBU) Although the Congress Party's victory set the stage for bolder moves on its foreign policy agenda, serious challenges remain. India's bureaucracy remains stove piped and slow-moving, and in many instances populated by senior officials who came of age during the Cold War, steeped in the ""non-aligned"" rhetoric of the 60s and 70s, and perhaps afraid to take forward leaning stances. There is a lack of capacity in every sector of the Indian bureaucracy.
8. (SBU) The extreme level of domestic poverty also stands in stark contrast to India's global ambitions. While India's poverty levels have fallen in the past decade as the economy has grown, hundreds of millions of Indians continue to subsist on less than two U. S. dollars a day. India is home to the third largest number of people living with HIV/AIDS and one-fourth of the world's tuberculosis cases. It is one of four nations in which polio still exists. PM Singh has signaled that improved governance and service delivery toward poverty reduction are top priorities in his second term.
9. (SBU) Congress Party leaders attribute its strong showing in the April elections to the close attention it paid to the rural sector during the previous government. Despite expectations that the current coalition's strong base would allow it to pursue ""big bang"" economic reforms, the more likely approach is gradual reform with a close watch at each step on political and social effects of policy changes. The UPA's July 6 budget proposal focuses most new spending on a rural employment program and rural infrastructure.
10. (C) India's efforts to be the regional power in South Asia and act as a global player face their greatest challenge from India's troubled relationship with Pakistan. Indian leaders you meet will all point to growing signs that the Pakistani state no longer exercises effective control over its territory, but at the same time these genuine expressions of concern will not be accompanied by any solid ideas about how India can help arrest Pakistan's decline. The small steps toward dialogue in the aftermath of the Mumbai attacks, such as the June meeting between PM Singh and President Zardari and the planned meeting between PM Singh and PM Gilani at the NAM summit in Sharm-al-Sheikh, are likely to produce limited results at best. Your Indian interlocutors will argue that India has relaunched dialogue each time after a major terrorist attack, but that Pakistan has taken no effective steps to rein in extremist elements that launch the attacks. After the Mumbai attacks, India's willingness to begin talks again is quite limited; on multiple occasions, Indian leaders have made it clear that progress against Pakistan-based terrorist groups (including the alleged perpetrators of the Mumbai attacks) is a prerequisite for NEW DELHI 00001464 003 OF 006 resumption of the formal dialogue process.
11. (C) Despite early concerns, the GOI now appreciates Special Representative Holbrooke's active outreach to India on Afghanistan-Pakistan policy, and has agreed to contribute more toward Afghan reconstruction. GOI officials will be very interested in hearing from you how President Obama views South Asia. Hypersensitivity remains in the government and the general Indian public over whether the U. S. intends to interfere in Kashmir and/or sacrifice Indian securty interests to U. S. objectives in Afghanistan. Indian officials emphatically reject suggestions of a link between the problems on the Afghanistan-Pakistan border region and the India-Pakistan relationship, especially the dispute over Kashmir.
12. (C) Elsewhere in the region, the U. S. and India generally share similar goals for stability and democratic governance in Nepal, Bangladesh, and Sri Lanka, and have coordinated better than in the past. Policies toward Burma and Iran remain exceptions, largely because India's proximity, historical ties, and strategic and economic interests leave it with a policy perspective that more often than not differs from ours. The good news for the United States is that the same leaders who have a vision for India's ascendancy generally recognize that healthy relations with the U. S. are essential for India to get to where it wants to be.
13. (SBU) The major thrust of your visit will be to conclude an agreement on the architecture for dialogues that will form the pillars for our partnership in the coming years. The five pillars are Science, Technology, Health, and Innovation; Strategic Cooperation; Energy and Climate Change; Education and Development; and Economics, Trade, and Agriculture.
14. (SBU) Technology and science are common strengths and priorities of our two knowledge-based democracies. The U. S. and India have a close and long-standing relationship in Science and Technology (S&T) led by academic, commercial and official institutions and encompassing a wide range of topics including health, agriculture, biotechnology, nanotechnology, space, nuclear technology, defense/security research and development, and environmental sciences. Despite India's recent economic growth, hundreds of millions of Indians live without adequate access to food, healthcare, education, and water. Together, our open societies can generate ideas and initiatives to help close the technological and health divide between various segments of India's huge population. The Science, Technology, Health and Innovation pillar will include a three-part S&T Dialogue, and the first bilateral ministerial-level dialogue dedicated to health and biomedical sciences.
15. (SBU) We seek a closer partnership with India on defense, counterterrorism, homeland security, and non-proliferation issues. This pillar covers strategic security talks, the high technology cooperation group, the defense policy group, a forum on global issues, the joint working group on counterterrorism, and an expanded discussion of security challenges in South Asia and beyond, including the Middle East, Africa, and East Asia.
16. (S) In general, the defense relationship is on a strong growth curve despite a variety of frustrations. While the Indian uniformed leadership of all three Services, and in particular the Indian Navy, appreciate their improving ties with the United States military, bureaucratic inertia and recalcitrant officials in the Ministries of External Affairs and Defense continue to complicate attempts to improve the partnership. Despite these challenges, military-to-military contacts continue to be a strong foundation of our strategic partnership. We conducted the largest ground forces/counterterrorism centric combined exercise to date in February 2009 and are poised to conduct air and army exercises in the fall. India has already hosted visits this year from the Chairman of the Joint Chiefs of Staff, the Commander of United States Pacific Command, and the Commandant of the United States Coast Guard. We continue to seek opportunities for capacity-building, greater access and improved partnering through more focused combined exercises, better-tailored subject matter exchange events, and additional high-level visitor exchanges.
17. (C) Defense sales have risen from near zero in 2004 to over $2. 2 billion already in 2009, with prospects for further expansion. Despite this potential, the sale of military equipment and training through the Foreign Military Sales (FMS) process has been halted pending agreement on End Use Monitoring (EUM). At a time when our defense relationship is otherwise beginning to flourish, the lack of an EUM agreement has become an irritant. If EUM has not been resolved at the time of your visit, you will be positioned to stress at the highest levels that EUM is a requirement of U. S. law, has been accepted by over eighty other countries, and will have to be accepted by India if it desires to procure the state-of-the-art technology we would like to share.
18. (SBU) India continues to rank among the world's most terror-afflicted countries. We have seen increased willingness to accept U. S. offers of training and other assistance, particularly from the FBI and on intelligence sharing, in the wake of the November 2008 attacks in Mumbai. In general, however, progress on increased tangible programs reains slow, and as in the defense relationship, India often foregoes opportunities through failing to respond to offers within needed time frames. The June 2009 bilateral counterterrorism talks, chaired by CT Coordinator Benjamin in Washington, were positive and provided some suggested avenues for expanding cooperation. We are hopeful the Minister of Home Affairs will visit the National Counterterrorism Center (NCTC) in early 2010. We also continue to encourage India to play a positive role in sub-regional cooperation efforts, particularly on border issues with Bangladesh and Nepal.
19. (SBU) The Civil Nuclear Cooperation Agreement was a landmark in the bilateral relationship, both for its non-proliferation consequences as well as for our energy relationship. The Indian government is likely to announce two reactor park sites for U. S. companies. There are other remaining implementation issues we face; most immediately India needs to file a declaration of its nuclear facilities with the IAEA in order for U. S. companies to start moving forward. India is eager to increase engagement with the U. S. on research and development of technologies for clean, renewable energy, and on energy efficiency. Indian leaders do not believe, however, that these other energy forms will be able to replace existing capacities or substitute for large scale expansion of coal-fired thermal power. (Coal-fired thermal power accounts for 53 percent of India's total power generating capacity and over 66 percent of India's electricity production. ) India has pledged to host an International Renewable Energy Conference in October 2010, building on the successful one held in Washington in 2008.
20. (SBU) In spite of the synergies, our views on climate change differ. Indian officials reject any greenhouse gas emission monitoring or reduction commitments. They argue that primary responsibility for global warming lies with developed countries, and that it is entitled to an equal per capita share of the ""global carbon space,"" particularly in light of its need for economic development. (India's per capita electricity consumption and per capita carbon dioxide emissions are five to six percent of U. S. levels; 55 percent of the population has no access to electricity. ) India's total electricity generated from coal is now a fifth that of China and a fourth of the U. S. , so India is unlikely to be motivated by Chinese commitments to emissions reductions. Nevertheless, a high-level bilateral dialogue will give us the opportunity to find common ground since we share an overall concern for the impact on climate change.
21. (SBU) We wish to combine U. S. and Indian expertise and knowledge to foster new joint partnerships in education, development, and women's empowerment. The GOI is considering long-overdue reforms in its education system. The Education Dialogue would focus on the following areas: challenges of funding and scaling up large educational institutions, identifying funds to support programs for research and teaching, promotion of the study of the U. S. in India and vice versa, and enhancing improvements in basic education.
22. (SBU) Women's Empowerment: The Women's Empowerment Forum (WEF) will provide opportunities to share best practices and partner on relevant initiatives. The indicators regarding the status of women in India are startling: Female feticide, trafficking for commercial sex work, domestic violence (approximately 30% of married women), and dowry deaths (one death every 90 minutes) affect countless women throughout India. The new government has focused on women's empowerment initiatives, promising to pass the long-pending Women's Reservation Bill that sets aside one-third of elected seats in the Lok Sabha (lower house of the Indian Parliament) and state legislatures for women. The government has also pledged to re-brand the ""National Literacy Mission"" as the ""National Mission for Female Literacy"" which would strive for 100 percent female literacy over the next five years; to boost the number of women working for the central government; and to establish the National Mission on the Empowerment of Women to coordinate the implementation of these initiatives. The WEF will draw on USAID's long experience in education, reproductive health, and legal access programs.
23. (SBU) Under this pillar we hope to remove barriers to greater trade and investment between our countries and harness the power of our public and private sectors to help India achieve a sustainable agriculture sector and food security. Agriculture and rural development are inextricably linked with poverty reduction, but India's chief crop yields are still lower than other major nations. Trade and investment have long been an important source of private sector ties between our two countries and the growth is only accelerating, as India's economy matures and our respective companies discover each other. U. S. exports to India have tripled since 2004 and while U. S. investment to India continues to climb, Indian companies are increasingly finding strategic investments in the U. S. , with $3 billion in 2008 alone. This has led to mutual support within the CEO Forum for a bilateral investment treaty. (Note: The GOI has accepted our proposed dates for negotiations to start in mid-August, which we look forward to your announcing during your visit. End Note. )
24. (SBU) The senior leaders we have requested look forward to meeting with you: Prime Minister Singh, External Affairs Minister Krishna, Congress Party President Sonia Gandhi, and Leader of the Opposition LK Advani.
BURLEIGH " | english |
Your immune system is made up of your white blood cells plus the organs and tissues of your lymph system, like your bone marrow. Its main job is to help your body fight off disease and stay healthy.
Immunotherapy drugs help your immune system work harder or make it easier for it to find and get rid of cancer cells.
Several immunotherapy drugs have been approved to fight cancer, and hundreds more are being tested in clinical trials (research studies that use volunteers to test new medicines). If immunotherapy seems like the best way to fight your cancer, your doctor may know of a clinical trial you can join.
If your doctor suggests immunotherapy to fight your cancer, there’s a lot to talk to them about before you decide if it’s right for you.
What Are the Benefits?
There are many reasons your doctor might think immunotherapy is a good choice for you:
Immunotherapy may work when other treatments don’t. Some cancers (like skin cancer) don’t respond well to radiation or chemotherapy but start to go away after immunotherapy.
It can help other cancer treatments work better. Other therapies you have, like chemotherapy, may work better if you also have immunotherapy.
It causes fewer side effects than other treatments. This is because it targets just your immune system and not all the cells in your body.
Your cancer may be less likely to return. When you have immunotherapy, your immune system learns to go after cancer cells if they ever come back. This is called immunomemory, and it could help you stay cancer-free for a longer time.
What Are the Risks?
Immunotherapy holds a lot of promise as a cancer treatment. Still, it can cause some problems.
You might have a bad reaction. The area where the medication goes into your body could hurt, itch, swell, turn red, or get sore.
There are side effects. Some types of immunotherapy rev up your immune system and make you feel like you have the flu, complete with fever, chills, and fatigue. Others could cause problems like swelling, weight gain from extra fluids, heart palpitations, a stuffy head, and diarrhea. Most of the time, these ease up after your first treatment.
It can harm organs and systems. Some of these drugs can cause your immune system to attack organs like your heart, liver, lungs, kidneys, or intestines.
It isn’t a quick fix. In some cases, immunotherapy takes longer to work than other treatments. Your cancer may not go away quickly.
It doesn’t work for everyone. Right now, immunotherapy works for less than half the people who try it. Many people only have a partial response. This means your tumor could stop growing or get smaller, but it doesn’t go away. Doctors aren’t sure yet why immunotherapy helps only some people.
Your body could get used to it. Over time, immunotherapy may stop having an effect on your cancer cells. This means that even if it works at first, your tumor could start to grow again.
| english |
<reponame>seinlin/actix-net<gh_stars>100-1000
//! Simple "poll function" future and factory.
use core::{
fmt,
future::Future,
pin::Pin,
task::{Context, Poll},
};
/// Creates a future driven by the provided function that receives a task context.
#[inline]
pub fn poll_fn<F, T>(f: F) -> PollFn<F>
where
F: FnMut(&mut Context<'_>) -> Poll<T>,
{
PollFn { f }
}
/// A Future driven by the inner function.
pub struct PollFn<F> {
f: F,
}
impl<F> Unpin for PollFn<F> {}
impl<F> fmt::Debug for PollFn<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PollFn").finish()
}
}
impl<F, T> Future for PollFn<F>
where
F: FnMut(&mut Context<'_>) -> Poll<T>,
{
type Output = T;
#[inline]
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
(self.f)(cx)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[actix_rt::test]
async fn test_poll_fn() {
let res = poll_fn(|_| Poll::Ready(42)).await;
assert_eq!(res, 42);
let mut i = 5;
let res = poll_fn(|cx| {
i -= 1;
if i > 0 {
cx.waker().wake_by_ref();
Poll::Pending
} else {
Poll::Ready(42)
}
})
.await;
assert_eq!(res, 42);
}
}
| rust |
Loads of startups have signed up for The Next Web Rising Sun Startup Rally already. This makes a lot of sense since it is a great opportunity to present your startup (at no costs) to the most influential European Internet crowd out there. This will boost buzz around your company, you’ll meet very interesting people (bloggers, journalists, peers, investors, decisions makers of big companies).
Joining the rally means that we (the jury) will review your submission and 50 – 60 startups will be interviewed (via phone and skype) to end up with the 24 best and most promising startups that will present on main stage during The Next Web Conference. Even if you don’t make it to the final, we’ll show our appreciation to you for taking the time and energy to sign up. It takes only 10 minutes of your time and did I already mention that it is free....
Submit your startup now. Today it is the last day we take on submissions.
If you’ve a cool twitter app / company, make sure you check the special Twitter ecosystem session.
Get the most important tech news in your inbox each week.
| english |
<filename>src/main/java/sql/sand/detector/UnparamerizedDetector.java
package sql.sand.detector;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import sql.sand.abstraction.Silica;
import sql.sand.analysis.helper.Pair;
import sql.sand.function.Analyzer;
import sql.sand.function.SilicaFinder;
public class UnparamerizedDetector {
/**
* Check if (1) a query contains a dynamic value at its data value position
* and (2) if the query is issued in a loop
*/
//25 lines of code
public static Set<Silica> detect(Set<String> classFilter)
{
Set<Silica> targetSilicas = new HashSet<>();
Set<Silica> relevantSilicas = SilicaFinder.find("^(select|insert|update|delete).*", classFilter);
for(Silica silica : relevantSilicas)
{
boolean containDynamic = false;
if(silica.getQueryToDataValues() != null)
{
for(List<String> dataValues : silica.getQueryToDataValues().values())
{
for(String dataValue : dataValues)
{
if(dataValue.equals("$$$"))
{
containDynamic = true;
break;
}
}
}
}
if(containDynamic)
targetSilicas.add(silica);
}
return targetSilicas;
}
}
| java |
#ifndef CPP_WEB_SERVER_HTTP_REPLY_HPP
#define CPP_WEB_SERVER_HTTP_REPLY_HPP
#include <vector>
#include <string>
#include <boost/asio.hpp>
#include "async_web_server_cpp/http_header.hpp"
#include "async_web_server_cpp/http_connection.hpp"
#include "async_web_server_cpp/http_request_handler.hpp"
#include <boost/filesystem.hpp>
namespace async_web_server_cpp
{
class ReplyBuilder;
/**
* Utility methods for constructing replys
*/
struct HttpReply
{
enum status_type
{
switching_protocols = 101,
ok = 200,
created = 201,
accepted = 202,
no_content = 204,
multiple_choices = 300,
moved_permanently = 301,
moved_temporarily = 302,
not_modified = 304,
bad_request = 400,
unauthorized = 401,
forbidden = 403,
not_found = 404,
internal_server_error = 500,
not_implemented = 501,
bad_gateway = 502,
service_unavailable = 503
} status;
static std::vector<boost::asio::const_buffer> to_buffers(const std::vector<HttpHeader> &headers);
/**
* Create a request handler that sends a stock reply based on the stats code
*/
static HttpServerRequestHandler stock_reply(status_type status);
/**
* Create a request handler that sends the contents of a file
*/
static HttpServerRequestHandler from_file(HttpReply::status_type status,
const std::string& content_type,
const std::string& filename,
const std::vector<HttpHeader>& additional_headers = std::vector<HttpHeader>());
/**
* Create a request handler that reads files from the filesystem
* No content type is served and it is left to the browser to determine the content type
* @param path_root the prefix in the request path that should be ignored
* @param filesystem_root the path to search for the requested file
*/
static HttpServerRequestHandler from_filesystem(HttpReply::status_type status,
const std::string& path_root,
const std::string& filesystem_root,
bool list_directories,
const std::vector<HttpHeader>& additional_headers = std::vector<HttpHeader>());
/**
* Create a request handler that sends a static response
*/
static HttpServerRequestHandler static_reply(status_type status,
const std::string& content_type,
const std::string& content,
const std::vector<HttpHeader>& additional_headers = std::vector<HttpHeader>());
/**
* Create a builder to create and send reply headers
*/
static ReplyBuilder builder(status_type status);
};
/**
* Object to build and send reply headers
*/
class ReplyBuilder
{
public:
ReplyBuilder(HttpReply::status_type status);
/**
* Add a header to the reply
*/
ReplyBuilder &header(const std::string &name, const std::string &value);
/**
* Add a header to the reply
*/
ReplyBuilder &header(const HttpHeader &header);
/**
* Add a group of headers to the reply
*/
ReplyBuilder &headers(const std::vector<HttpHeader> &headers);
/**
* Send the headers over the connection
*/
void write(HttpConnectionPtr connection);
private:
HttpReply::status_type status_;
boost::shared_ptr<std::vector<HttpHeader> > headers_;
};
/**
* Request Handler that serves a predefined response
*/
class StaticHttpRequestHandler
{
public:
StaticHttpRequestHandler(HttpReply::status_type status,
const std::vector<HttpHeader> &headers,
const std::string &content);
bool operator()(const HttpRequest &, boost::shared_ptr<HttpConnection>, const char* begin, const char* end);
private:
ReplyBuilder reply_builder_;
const std::string content_string_;
};
/**
* Request Handler that serves a response from a file
*/
class FileHttpRequestHandler
{
public:
FileHttpRequestHandler(HttpReply::status_type status,
const std::string& filename,
const std::vector<HttpHeader>& headers);
bool operator()(const HttpRequest &, boost::shared_ptr<HttpConnection>, const char* begin, const char* end);
private:
HttpReply::status_type status_;
std::vector<HttpHeader> headers_;
std::string filename_;
};
/**
* Request Handler that serves a responses from the filesystem from a base path
*/
class FilesystemHttpRequestHandler
{
public:
FilesystemHttpRequestHandler(HttpReply::status_type status,
const std::string& path_root,
const std::string& filesystem_root,
bool list_directories,
const std::vector<HttpHeader>& headers);
bool operator()(const HttpRequest &, boost::shared_ptr<HttpConnection>, const char* begin, const char* end);
private:
HttpReply::status_type status_;
std::vector<HttpHeader> headers_;
std::string path_root_;
boost::filesystem::path filesystem_root_;
bool list_directories_;
};
}
#endif
| cpp |
<reponame>xUndero/noc
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# inv.platform application
# ----------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# NOC modules
from noc.lib.app.extdocapplication import ExtDocApplication
from noc.inv.models.platform import Platform
from noc.core.translation import ugettext as _
class PlatformApplication(ExtDocApplication):
"""
Platform application
"""
title = "Platform"
menu = [_("Setup"), _("Platforms")]
model = Platform
query_fields = ["full_name__icontains", "name__icontains", "description__icontains"]
default_ordering = ["full_name"]
| python |
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IsDivisibleBy = exports.isDivisibleBy = exports.IS_DIVISIBLE_BY = void 0;
const ValidateBy_1 = require("../common/ValidateBy");
const isDivisibleBy_1 = __importDefault(require("validator/lib/isDivisibleBy"));
exports.IS_DIVISIBLE_BY = 'isDivisibleBy';
/**
* Checks if value is a number that's divisible by another.
*/
function isDivisibleBy(value, num) {
return typeof value === 'number' && typeof num === 'number' && isDivisibleBy_1.default(String(value), num);
}
exports.isDivisibleBy = isDivisibleBy;
/**
* Checks if value is a number that's divisible by another.
*/
function IsDivisibleBy(num, validationOptions) {
return ValidateBy_1.ValidateBy({
name: exports.IS_DIVISIBLE_BY,
constraints: [num],
validator: {
validate: (value, args) => isDivisibleBy(value, args.constraints[0]),
defaultMessage: ValidateBy_1.buildMessage(eachPrefix => eachPrefix + '$property must be divisible by $constraint1', validationOptions),
},
}, validationOptions);
}
exports.IsDivisibleBy = IsDivisibleBy;
//# sourceMappingURL=IsDivisibleBy.js.map | javascript |
New Delhi: Congress today took a dig at Prime Minister Narendra Modi over the issue of his educational qualification saying his government was a "habitual offender" on the matter.
"If the Prime Minister himself is seeking to hide his educational qualifications, then how could common man have the confidence to use the RTI as a tool to fight corruption," party's chief spokesman Randeep Singh Surjewala said when asked about the CIC's direction to universities in Delhi and Gujarat to provide proper responses to RTI applications seeking details of education qualification of the Prime Minister.
Recalling the degree row in which Education Minister Smriti Irani was involved, he noted that a court case is also on in the matter. He said there is also controversy over the degree of Minister of State of Education Ram Shankar Katheria.
Insisting that the Congress respected the Prime Minister despite being his opponent, Mr Surjewala, however, said if the Prime Minister "himself hides his degrees, then how could be the Right to Information be defended".
He said that not only should the Prime Minister make public his educational qualifications, but he should also "act against those in the PMO who attempted to malign him by not giving the information".
He alleged that other BJP leaders too have "misled" on their educational qualifications and that they were "habitual offenders".
Mr Surjewala's remarks came close on the heels of the Central Information Commission giving direction to the universities of Delhi and Gujarat to provide proper responses to RTI applications seeking details of education qualification of the Prime Minister.
The CIC's order came a day after Delhi Chief Minister Arvind Kejriwal wrote a letter to CIC saying he does not object to government records about him being made public and wondered why the Commission wants to "hide" information on Modi's educational qualification. | english |
<filename>packages/fast-components-react-base/src/slider-track-item/slider-track-item.spec.tsx
import React from "react";
import Adapter from "enzyme-adapter-react-16";
import { configure, mount, shallow } from "enzyme";
import SliderTrackItem, {
SliderTrackItemAnchor,
SliderTrackItemHandledProps,
SliderTrackItemProps,
SliderTrackItemUnhandledProps,
} from "./slider-track-item";
import {
SliderContext,
SliderMode,
SliderOrientation,
SliderRange,
SliderThumb,
} from "../slider";
import { DisplayNamePrefix } from "../utilities";
import { SliderState } from "../slider/slider";
import { Direction } from "@microsoft/fast-web-utilities";
/*
* Configure Enzyme
*/
configure({ adapter: new Adapter() });
/* tslint:disable:no-string-literal */
describe("slider track item", (): void => {
const defaultSliderState: SliderState = {
dragValue: -1,
upperValue: 100,
lowerValue: 0,
activeThumb: null,
isMouseDragging: false,
isTouchDragging: false,
isIncrementing: false,
incrementDirection: 1,
usePageStep: false,
};
test("should have a displayName that matches the component name", () => {
expect(`${DisplayNamePrefix}${(SliderTrackItem as any).name}`).toBe(
SliderTrackItem.displayName
);
});
test("should not throw if managedClasses are not provided", () => {
expect(() => {
shallow(<SliderTrackItem />);
}).not.toThrow();
});
test("should implement unhandledProps", (): void => {
const unhandledProps: SliderTrackItemUnhandledProps = {
"aria-label": "label",
};
const rendered: any = shallow(<SliderTrackItem {...unhandledProps} />);
expect(rendered.first().prop("aria-label")).toEqual("label");
});
test("totalRangeMax and totalRangeMin bindings don't call getValueAsPercent", (): void => {
const container: HTMLDivElement = document.createElement("div");
document.body.appendChild(container);
const getValueAsPercent: any = jest.fn();
const rendered: any = mount(
<SliderContext.Provider
value={{
sliderOrientation: SliderOrientation.horizontal,
sliderMode: SliderMode.singleValue,
sliderState: defaultSliderState,
sliderConstrainedRange: undefined,
sliderValueAsPercent: getValueAsPercent,
sliderDirection: Direction.ltr,
}}
>
<SliderTrackItem
maxValuePositionBinding={SliderTrackItemAnchor.totalRangeMax}
minValuePositionBinding={SliderTrackItemAnchor.totalRangeMin}
/>
</SliderContext.Provider>,
{ attachTo: container }
);
expect(getValueAsPercent).toHaveBeenCalledTimes(0);
document.body.removeChild(container);
});
test("numeric bindings call getValueAsPercent", (): void => {
const container: HTMLDivElement = document.createElement("div");
document.body.appendChild(container);
const getValueAsPercent: any = jest.fn();
getValueAsPercent.mockReturnValueOnce(90);
getValueAsPercent.mockReturnValueOnce(10);
const rendered: any = mount(
<SliderContext.Provider
value={{
sliderOrientation: SliderOrientation.horizontal,
sliderMode: SliderMode.singleValue,
sliderState: defaultSliderState,
sliderConstrainedRange: undefined,
sliderValueAsPercent: getValueAsPercent,
sliderDirection: Direction.ltr,
}}
>
<SliderTrackItem
id="trackItem"
maxValuePositionBinding={90}
minValuePositionBinding={10}
/>
</SliderContext.Provider>,
{ attachTo: container }
);
expect(getValueAsPercent).toHaveBeenCalledTimes(2);
document.body.removeChild(container);
});
test("selectedRangeMax and selectedRangeMin bindings don't call getValueAsPercent", (): void => {
const container: HTMLDivElement = document.createElement("div");
document.body.appendChild(container);
const getValueAsPercent: any = jest.fn();
const rendered: any = mount(
<SliderContext.Provider
value={{
sliderOrientation: SliderOrientation.horizontal,
sliderMode: SliderMode.singleValue,
sliderState: defaultSliderState,
sliderConstrainedRange: undefined,
sliderValueAsPercent: getValueAsPercent,
sliderDirection: Direction.ltr,
}}
>
<SliderTrackItem
maxValuePositionBinding={SliderTrackItemAnchor.selectedRangeMax}
minValuePositionBinding={SliderTrackItemAnchor.selectedRangeMin}
/>
</SliderContext.Provider>,
{ attachTo: container }
);
expect(getValueAsPercent).toHaveBeenCalledTimes(2);
document.body.removeChild(container);
});
test("getPositonAsPercent() returns correct values for anchors", (): void => {
const container: HTMLDivElement = document.createElement("div");
document.body.appendChild(container);
const getValueAsPercent: any = jest.fn();
getValueAsPercent.mockReturnValueOnce(20);
getValueAsPercent.mockReturnValueOnce(80);
getValueAsPercent.mockReturnValueOnce(20);
getValueAsPercent.mockReturnValueOnce(80);
getValueAsPercent.mockReturnValueOnce(10);
getValueAsPercent.mockReturnValueOnce(90);
const rendered: any = mount(
<SliderContext.Provider
value={{
sliderOrientation: SliderOrientation.horizontal,
sliderMode: SliderMode.singleValue,
sliderState: defaultSliderState,
sliderConstrainedRange: { minValue: 20, maxValue: 80 },
sliderValueAsPercent: getValueAsPercent,
sliderDirection: Direction.ltr,
}}
>
<SliderTrackItem
maxValuePositionBinding={SliderTrackItemAnchor.selectedRangeMax}
minValuePositionBinding={SliderTrackItemAnchor.selectedRangeMin}
/>
</SliderContext.Provider>,
{ attachTo: container }
);
const trackItem: any = rendered.find("BaseSliderTrackItem");
expect(
trackItem
.instance()
["getPositionAsPercent"](SliderTrackItemAnchor.totalRangeMin)
).toBe(0);
expect(
trackItem
.instance()
["getPositionAsPercent"](SliderTrackItemAnchor.totalRangeMax)
).toBe(100);
expect(
trackItem
.instance()
["getPositionAsPercent"](SliderTrackItemAnchor.constrainedRangeMin)
).toBe(20);
expect(
trackItem
.instance()
["getPositionAsPercent"](SliderTrackItemAnchor.constrainedRangeMax)
).toBe(80);
expect(
trackItem
.instance()
["getPositionAsPercent"](SliderTrackItemAnchor.selectedRangeMin)
).toBe(10);
expect(
trackItem
.instance()
["getPositionAsPercent"](SliderTrackItemAnchor.selectedRangeMax)
).toBe(90);
document.body.removeChild(container);
});
});
| typescript |
import asyncio
import gc
import time
import uuid
import elasticsearch
import pytest
from aiohttp.test_utils import unused_port
from docker import from_env as docker_from_env
import aioelasticsearch
@pytest.fixture
def loop(request):
asyncio.set_event_loop(None)
loop = asyncio.new_event_loop()
yield loop
if not loop._closed:
loop.call_soon(loop.stop)
loop.run_forever()
loop.close()
gc.collect()
asyncio.set_event_loop(None)
@pytest.fixture(scope='session')
def session_id():
'''Unique session identifier, random string.'''
return str(uuid.uuid4())
@pytest.fixture(scope='session')
def docker():
client = docker_from_env(version='auto')
return client
def pytest_addoption(parser):
parser.addoption("--es_tag", action="append", default=[],
help=("Elasticsearch server versions. "
"May be used several times. "
"6.0.0 by default"))
parser.addoption("--no-pull", action="store_true", default=False,
help="Don't perform docker images pulling")
parser.addoption("--local-docker", action="store_true", default=False,
help="Use 0.0.0.0 as docker host, useful for MacOs X")
def pytest_generate_tests(metafunc):
if 'es_tag' in metafunc.fixturenames:
tags = set(metafunc.config.option.es_tag)
if not tags:
tags = ['6.0.0']
else:
tags = list(tags)
metafunc.parametrize("es_tag", tags, scope='session')
@pytest.fixture(scope='session')
def es_container(docker, session_id, es_tag, request):
image = 'docker.elastic.co/elasticsearch/elasticsearch:{}'.format(es_tag)
if not request.config.option.no_pull:
docker.images.pull(image)
es_auth = ('elastic', 'changeme')
if request.config.option.local_docker:
es_port_9200 = es_access_port = unused_port()
es_port_9300 = unused_port()
else:
es_port_9200 = es_port_9300 = None
es_access_port = 9200
container = docker.containers.run(
image=image,
detach=True,
name='aioelasticsearch-' + session_id,
ports={
'9200/tcp': es_port_9200,
'9300/tcp': es_port_9300,
},
environment={
'http.host': '0.0.0.0',
'transport.host': '127.0.0.1',
},
)
if request.config.option.local_docker:
docker_host = '0.0.0.0'
else:
inspection = docker.api.inspect_container(container.id)
docker_host = inspection['NetworkSettings']['IPAddress']
delay = 0.1
for i in range(20):
es = elasticsearch.Elasticsearch(
[{
'host': docker_host,
'port': es_access_port,
}],
http_auth=es_auth,
)
try:
es.transport.perform_request('GET', '/_nodes/_all/http')
except elasticsearch.TransportError:
time.sleep(delay)
delay *= 2
else:
break
finally:
es.transport.close()
else:
pytest.fail("Cannot start elastic server")
yield {
'host': docker_host,
'port': es_access_port,
'auth': es_auth,
}
container.kill(signal=9)
container.remove(force=True)
@pytest.fixture
def es_clean(es_container):
def do():
es = elasticsearch.Elasticsearch(
hosts=[{
'host': es_container['host'],
'port': es_container['port'],
}],
http_auth=es_container['auth'],
)
try:
es.transport.perform_request('DELETE', '/_template/*')
es.transport.perform_request('DELETE', '/_all')
finally:
es.transport.close()
return do
@pytest.fixture
def es_server(es_clean, es_container):
es_clean()
return es_container
@pytest.fixture
def es(es_server, auto_close, loop):
es = aioelasticsearch.Elasticsearch(
hosts=[{
'host': es_server['host'],
'port': es_server['port'],
}],
http_auth=es_server['auth'],
loop=loop,
)
return auto_close(es)
@pytest.fixture
def auto_close(loop):
close_list = []
def f(arg):
close_list.append(arg)
return arg
yield f
for arg in close_list:
loop.run_until_complete(arg.close())
@pytest.mark.tryfirst
def pytest_pycollect_makeitem(collector, name, obj):
if collector.funcnamefilter(name):
item = pytest.Function(name, parent=collector)
if 'run_loop' in item.keywords:
return list(collector._genfunctions(name, obj))
@pytest.mark.tryfirst
def pytest_pyfunc_call(pyfuncitem):
if 'run_loop' in pyfuncitem.keywords:
funcargs = pyfuncitem.funcargs
loop = funcargs['loop']
testargs = {
arg: funcargs[arg]
for arg in pyfuncitem._fixtureinfo.argnames
}
assert asyncio.iscoroutinefunction(pyfuncitem.obj)
loop.run_until_complete(pyfuncitem.obj(**testargs))
return True
@pytest.fixture
def populate(es, loop):
async def do(index, doc_type, n, body):
coros = []
await es.indices.create(index)
for i in range(n):
coros.append(
es.index(
index=index,
doc_type=doc_type,
id=str(i),
body=body,
),
)
await asyncio.gather(*coros, loop=loop)
await es.indices.refresh()
return do
| python |
package templateignition
import (
"context"
"github.com/giantswarm/apiextensions/v3/pkg/apis/core/v1alpha1"
"github.com/giantswarm/microerror"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/giantswarm/ignition-operator/pkg/label"
"github.com/giantswarm/ignition-operator/pkg/project"
"github.com/giantswarm/ignition-operator/service/controller/controllercontext"
"github.com/giantswarm/ignition-operator/service/controller/key"
)
func (r *Resource) EnsureCreated(ctx context.Context, obj interface{}) error {
cr, err := key.ToIgnition(obj)
if err != nil {
return microerror.Mask(err)
}
cc, err := controllercontext.FromContext(ctx)
if err != nil {
return microerror.Mask(err)
}
var template map[string]string
{
if cr.Spec.IsMaster {
template, err = key.Render(cc, key.MasterTemplatePath, false)
} else {
template, err = key.Render(cc, key.WorkerTemplatePath, false)
}
if err != nil {
return microerror.Mask(err)
}
}
s := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: key.StatusSecretName(cr.Spec.ClusterID, cr.GetName()),
Labels: map[string]string{
"cluster.x-k8s.io/cluster-name": cr.Spec.ClusterID,
label.ManagedBy: project.Name(),
},
OwnerReferences: []metav1.OwnerReference{
*metav1.NewControllerRef(&cr, cr.GroupVersionKind()),
},
},
StringData: map[string]string{
"value": template["."],
},
}
actualSecret, err := r.k8sClient.K8sClient().CoreV1().Secrets(cr.GetNamespace()).Update(ctx, s, metav1.UpdateOptions{})
if apierrors.IsNotFound(err) {
actualSecret, err = r.k8sClient.K8sClient().CoreV1().Secrets(cr.GetNamespace()).Create(ctx, s, metav1.CreateOptions{})
if err != nil {
return microerror.Mask(err)
}
} else if err != nil {
return microerror.Mask(err)
}
cr.Status.DataSecret = v1alpha1.IgnitionStatusSecret{
Name: actualSecret.Name,
Namespace: actualSecret.Namespace,
ResourceVersion: actualSecret.ResourceVersion,
}
_, err = r.k8sClient.G8sClient().CoreV1alpha1().Ignitions(cr.Namespace).UpdateStatus(ctx, &cr, metav1.UpdateOptions{})
if err != nil {
return microerror.Mask(err)
}
return nil
}
| go |
Posted On:
Union Ministry of Health has finalised arrangements with Hyderabad based vaccine manufacturer Biological-E to reserve 30 crore of COVID-19 vaccine doses. These vaccine doses will be manufactured and stockpiled by M/s Biological-E from August-December 2021. For this purpose, the Union Ministry of Health would be making an advance payment of Rs. 1500 crore to M/s Biological-E.
The COVID-19 vaccine of Biological-E is currently undergoing Phase-3 clinical trial after showing promising results in Phase 1 and 2 clinical trials. The vaccine being developed by Biological-E is a RBD protein sub-unit vaccine and is likely to be available in the next few months.
The proposal of M/s Biological-E was examined and recommended for approval after due diligence by National Expert Group on Vaccine Administration for COVID-19 (NEGVAC).
The arrangement with M/s Biological-E is part of the wider endeavour of Government of India to encourage indigenous vaccine manufacturers by providing them support in Research & Development (R&D) and also financial support.
Biological-E COVID Vaccine candidate has been supported by Government of India from Preclinical stage to Phase-3 studies. Department of Biotechnology has not only provided financial assistance in terms of grant-in-aid of over Rs 100 cr but has also partnered with Biological-E to conduct all animal challenge and assay studies through its Research Institute Translational Health Science Technology Institute (THSTI), Faridabad.
This has been undertaken as part of Government of India's ‘Mission COVID Suraksha- the Indian COVID-19 Vaccine Development Mission’ which was launched to reinforce and accelerate COVID-19 vaccine development efforts as part of the third stimulus package, Atmanirbhar 3.0.
The Mission aims to bring to the citizens a safe, efficacious, affordable and accessible COVID-19 Vaccine. The Mission is supporting development of 5-6 COVID-19 vaccine candidates. Some of these are now closer to licensure and introduction in public health systems. It has not just accelerated COVID-19 Vaccine development efforts, but also fostered a robust end-to-end vaccine development ecosystem in the country that will be available for other on-going and future research and developmental activities for other vaccines.
| english |
"use strict";
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
require('./Info.less');
var React = require('react');
var QRCode = require('qrcode.react');
module.exports = React.createClass({
displayName: "exports",
getInitialState: function getInitialState() {
return {
event: null,
fields: [],
formItems: [{
title: '标题',
name: 'title',
type: 'Input',
required: true,
error: '必填项!'
}, {
title: '是否必填字段',
name: 'required',
type: 'Radio',
value: 0,
data: [{
text: '否',
value: 0
}, {
text: '是',
value: 1
}]
}, {
title: '类型',
name: 'type',
type: 'Select',
data: [{
text: '组标题',
value: 'FormTitle'
}, {
text: '单行输入框',
value: 'Input'
}, {
text: '数字框',
value: 'Input_number'
}, {
text: '日期框',
value: 'Input_date'
}, {
text: '时间框',
value: 'DateTime'
}, {
text: '组合框',
value: 'MultiInput'
}, {
text: '选择框',
value: 'Select'
}, {
text: '单图片',
value: 'ImageUploader'
}, {
text: '多文件',
value: 'FileUploader'
}, {
text: '是否框',
value: 'Checkbox'
}, {
text: '多选框',
value: 'CheckboxGroup'
}, {
text: '单选框',
value: 'Radio'
}, {
text: '多行输入框',
value: 'Textarea'
}],
onChange: function onChange(data, item, select) {
if (data) {
if (data.value.indexOf('Input_') != -1) {
select.props.form.state.hiddens.attrs = JSON.stringify({
type: data.value.split('_')[1]
});
}
}
}
}, {
title: '数据源',
name: 'data',
type: 'Textarea'
}, {
title: '字段说明',
name: 'zn_note',
type: 'Textarea'
}],
toolbarItems: [{
text: '添加字段',
name: 'add',
icon: 'fa-plus',
style: {
marginRight: 5
}
}]
};
},
componentDidMount: function componentDidMount() {
this.__loadMeta();
},
__loadMeta: function __loadMeta() {
zn.preloader.open({
content: '加载中...'
});
zn.http.post('/zn.plugin.survey/event/getEventFields', {
event_uuid: this.props.request.search.znid
}).then(function (data) {
if (data.status == 200) {
this.setState(data.result);
} else {
zn.notification.error(data.result);
}
zn.preloader.close();
}.bind(this), function (error) {
zn.notification.error('请求网络失败');
zn.preloader.close();
});
},
__onAddSubmitBefore: function __onAddSubmitBefore(data) {
for (var key in data) {
if (key.indexOf('.') != -1) {
var _value = data[key],
_keys = key.split('.');
if (!data[_keys[0]]) {
data[_keys[0]] = {};
}
data[_keys[0]][_keys[1]] = _value;
data[key] = null;
delete data[key];
}
}
zn.http.post('/zn.plugin.survey/event/createEventField', data).then(function (data) {
if (data.status == 200) {
this.__loadMeta();
} else {
zn.notification.error(data.result);
}
}.bind(this), function (err) {
zn.notification.error('网络请求失败');
}.bind(this));
return false;
},
__addItem: function __addItem() {
zn.dialog({
title: '添加字段',
content: /*#__PURE__*/React.createElement(zn.react.Form, {
hiddens: {
zn_id: zn.uuid(),
event_id: this.state.event.id,
field_order: this.state.fields.length + 1
},
onSubmitBefore: this.__onAddSubmitBefore,
items: this.state.formItems
})
});
},
__updateItem: function __updateItem(data) {
zn.dialog({
title: '更新字段',
content: /*#__PURE__*/React.createElement(zn.react.Form, {
merge: "updates",
action: "/zn.plugin.admin/model/update",
exts: {
model: 'ZNPluginSurveyEventField',
where: {
id: data.id
}
},
value: zn.store.post('/zn.plugin.admin/model/selectOne', {
model: 'ZNPluginSurveyEventField',
where: {
id: data.id
}
}),
onSubmitSuccess: this.__loadMeta,
items: this.state.formItems
})
});
},
__removeItem: function __removeItem(item) {
zn.confirm('确认删除这个字段吗?', '提示', function () {
zn.preloader.open({
title: '删除中...'
});
zn.http.post('/zn.plugin.admin/model/delete', {
model: 'ZNPluginSurveyEventField',
where: {
id: item.id
}
}).then(function (data) {
if (data.status == 200) {
zn.notification.success('删除成功');
this.__loadMeta();
} else {
zn.notification.error(data.result);
}
zn.preloader.close();
}.bind(this), function (data) {
zn.notification.error("网络请求失败");
zn.preloader.close();
});
}.bind(this));
},
__upItem: function __upItem(item) {
zn.preloader.open({
title: '升序中...'
});
zn.http.post('/zn.plugin.survey/event/orderField', {
field_id: item.id,
order: 'up'
}).then(function (data) {
if (data.status == 200) {
zn.notification.success('升序成功');
this.__loadMeta();
} else {
zn.notification.error(data.result);
}
zn.preloader.close();
}.bind(this), function (data) {
zn.notification.error("网络请求失败");
zn.preloader.close();
});
},
__downItem: function __downItem(item) {
zn.preloader.open({
title: '降序中...'
});
zn.http.post('/zn.plugin.survey/event/orderField', {
field_id: item.id,
order: 'down'
}).then(function (data) {
if (data.status == 200) {
zn.notification.success('降序成功');
this.__loadMeta();
} else {
zn.notification.error(data.result);
}
zn.preloader.close();
}.bind(this), function (data) {
zn.notification.error("网络请求失败");
zn.preloader.close();
});
},
__itemRender: function __itemRender(item, index) {
var _this = this;
if (item.data) {
try {
if (item.data[0] == '[' && item.data[item.data.length - 1] == ']') {
item.data = JSON.parse(item.data);
} else if (item.data.indexOf(' ') != -1) {
item.data = item.data.split(' ');
}
} catch (e) {
console.error(e);
}
}
if (item.attrs) {
item.attrs = JSON.parse(item.attrs);
}
if (item.props) {
zn.extend(item, JSON.parse(item.props));
}
item.type = item.type.split('_')[0];
return /*#__PURE__*/React.createElement("li", {
className: "field"
}, /*#__PURE__*/React.createElement(zn.react.FormItem, _extends({}, item, {
className: "column"
})), /*#__PURE__*/React.createElement("div", {
className: "action"
}, index != 0 && /*#__PURE__*/React.createElement("i", {
onClick: function onClick() {
return _this.__upItem(item);
},
"data-tooltip": "\u4E0A\u79FB",
className: "fa fa-angle-up"
}), index != this.state.fields.length - 1 && /*#__PURE__*/React.createElement("i", {
onClick: function onClick() {
return _this.__downItem(item);
},
"data-tooltip": "\u4E0B\u79FB",
className: "fa fa-angle-down"
}), /*#__PURE__*/React.createElement("i", {
onClick: function onClick() {
return _this.__updateItem(item);
},
"data-tooltip": "\u4FEE\u6539\u5B57\u6BB5",
className: "fa fa-edit"
}), /*#__PURE__*/React.createElement("i", {
onClick: function onClick() {
return _this.__removeItem(item);
},
"data-tooltip": "\u5220\u9664\u5B57\u6BB5",
className: "fa fa-remove",
style: {
color: 'red'
}
})));
},
render: function render() {
var _this2 = this;
return /*#__PURE__*/React.createElement(zn.react.Page, {
className: "zn-plugin-survey-event-info",
title: "\u6D3B\u52A8\u8BE6\u60C5"
}, this.state.event && /*#__PURE__*/React.createElement("div", {
className: "inner info"
}, !!this.state.event.status && /*#__PURE__*/React.createElement("div", {
className: "inner-left qr-code",
style: {
width: 138
}
}, /*#__PURE__*/React.createElement(QRCode, {
value: window.location.origin + window.location.pathname.replace('admin.html', 'index.html') + "#/znpluginsurvey.event.submit?znid=" + this.state.event.zn_id
}), /*#__PURE__*/React.createElement("a", {
className: "btn",
onClick: function onClick() {
return zn.react.copyToClipboard(window.location.origin + window.location.pathname.replace('admin.html', 'index.html') + "#/znpluginsurvey.event.submit?znid=" + _this2.state.event.zn_id);
}
}, /*#__PURE__*/React.createElement("i", {
className: "fa fa-copy"
}), "\u590D\u5236\u94FE\u63A5")), /*#__PURE__*/React.createElement("div", {
className: "inner-right base-items"
}, /*#__PURE__*/React.createElement("div", {
className: "r-header"
}, /*#__PURE__*/React.createElement("span", {
className: "name"
}, this.state.event.zn_title), /*#__PURE__*/React.createElement("span", {
className: "h-tag zr-fr"
}, "\u6700\u8FD1\u4E00\u6B21\u62A5\u540D\u65F6\u95F4\uFF1A", this.state.event.zn_modify_time)), /*#__PURE__*/React.createElement("div", {
className: "r-item"
}, /*#__PURE__*/React.createElement("span", {
className: "_key"
}, "\u5F53\u524D\u8FDB\u5EA6"), /*#__PURE__*/React.createElement("span", {
className: "h-tag"
}, this.state.event.count, " / ", this.state.event.max_count)), /*#__PURE__*/React.createElement("div", {
className: "r-item"
}, /*#__PURE__*/React.createElement("span", {
className: "_key"
}, "\u9884\u8BA1\u5468\u671F\uFF1A"), /*#__PURE__*/React.createElement("span", {
className: "_value"
}, (this.state.event.start_time || '').toString().split(' ')[0], " ~ ", (this.state.event.end_time || '').toString().split(' ')[0])), /*#__PURE__*/React.createElement("div", {
className: "r-item"
}, /*#__PURE__*/React.createElement("span", {
className: "_key"
}, "\u521B\u5EFA\u65F6\u95F4\uFF1A"), /*#__PURE__*/React.createElement("span", {
className: "_value"
}, this.state.event.zn_create_time)), /*#__PURE__*/React.createElement("div", {
className: "r-item"
}, /*#__PURE__*/React.createElement("span", {
className: "_key"
}, "\u5907\u6CE8\uFF1A"), /*#__PURE__*/React.createElement("span", {
className: "_value"
}, this.state.event.comment)))), this.state.event && /*#__PURE__*/React.createElement("div", {
className: "event-fields",
style: {
color: this.state.event.text_color,
width: 414,
margin: '0 auto'
}
}, this.state.event.background_image && /*#__PURE__*/React.createElement("img", {
className: "background-image",
src: this.state.event.background_image
}), /*#__PURE__*/React.createElement("div", {
className: "content"
}, /*#__PURE__*/React.createElement(zn.react.Button, {
onClick: this.__addItem,
text: "\u6DFB\u52A0\u5B57\u6BB5",
status: "warning",
icon: "fa-plus"
}), !!this.state.fields.length ? /*#__PURE__*/React.createElement("ul", {
className: "fields"
}, this.state.fields.map(this.__itemRender)) : /*#__PURE__*/React.createElement("span", {
className: "zr-tip"
}, "\u6682\u65F6\u6CA1\u6709\u5B57\u6BB5"))));
}
}); | javascript |
<filename>src/main/java/cn/haohaoli/book/headfirst/strategy/version6/impl/quack/MuteQuack.java
package cn.haohaoli.book.headfirst.strategy.version6.impl.quack;
import cn.haohaoli.book.headfirst.strategy.version6.QuackBehavior;
/**
* @author liWenHao
* @date 2019/1/8 20:48
*/
public class MuteQuack implements QuackBehavior {
@Override
public void quack() {
//什么都不做 不会叫
}
}
| java |
<reponame>fuersten/csvsqldb
//
// csvsqldb test
//
// BSD 3-Clause License
// Copyright (c) 2015, <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include "test.h"
#include "test/test_util.h"
#include "libcsvsqldb/base/exception.h"
#include "libcsvsqldb/base/default_configuration.h"
#include "libcsvsqldb/base/lua_configuration.h"
#include "libcsvsqldb/base/global_configuration.h"
#include <set>
class MyGlobalConfiguration : public csvsqldb::GlobalConfiguration
{
public:
struct Test {
int32_t wtf;
};
virtual void doConfigure(const csvsqldb::Configuration::Ptr& configuration)
{
test.wtf = configuration->get("test.wtf", 4711);
}
Test test;
};
class ConfigurationTestCase
{
public:
void setUp()
{
}
void tearDown()
{
}
void configTest()
{
csvsqldb::Configuration::Ptr config(
std::make_shared<csvsqldb::LuaConfiguration>(CSVSQLDB_TEST_PATH + std::string("/testdata/luaengine/test.lua")));
MPF_TEST_ASSERTEQUAL(10474, config->get("port", 9999));
MPF_TEST_ASSERT(std::fabs(47.11 - config->get("factor", 8.15)) < 0.0001);
MPF_TEST_ASSERTEQUAL("Thor", config->get("hostname", "horst"));
MPF_TEST_ASSERTEQUAL(100, config->get("server.threads", 10));
MPF_TEST_ASSERTEQUAL("LUA", config->get("server.api.code", "php"));
MPF_TEST_ASSERT(std::fabs(47.11 - config->get<double>("factor")) < 0.0001);
MPF_TEST_ASSERTEQUAL(true, config->get<bool>("daemonize"));
MPF_TEST_ASSERTEQUAL(2, config->get<int32_t>("debug.level.tcp_server"));
MPF_TEST_EXPECTS(csvsqldb::LuaConfiguration("not existent configuration"), csvsqldb::FilesystemException);
}
void configCheck()
{
csvsqldb::Configuration::Ptr config(
std::make_shared<csvsqldb::LuaConfiguration>(CSVSQLDB_TEST_PATH + std::string("/testdata/luaengine/test.lua")));
MPF_TEST_ASSERTEQUAL(true, config->hasProperty("daemonize"));
MPF_TEST_ASSERTEQUAL(true, config->hasProperty("server.api.code"));
MPF_TEST_ASSERTEQUAL(false, config->hasProperty("not_available_entry"));
MPF_TEST_ASSERTEQUAL(1, config->get<int32_t>("debug.global_level"));
csvsqldb::StringVector properties;
MPF_TEST_ASSERTEQUAL(3u, config->getProperties("debug.level", properties));
std::set<std::string> props(properties.begin(), properties.end());
MPF_TEST_ASSERT(props.find("tcp_server") != props.end());
MPF_TEST_ASSERT(props.find("connection") != props.end());
MPF_TEST_ASSERT(props.find("filesystem") != props.end());
}
void defaultConfigTest()
{
csvsqldb::Configuration::Ptr config(std::make_shared<csvsqldb::DefaultConfiguration>());
MPF_TEST_ASSERTEQUAL(false, config->hasProperty("application.daemonize"));
MPF_TEST_ASSERTEQUAL(false, config->hasProperty("not_available_entry"));
MPF_TEST_ASSERTEQUAL(false, config->hasProperty("logging.device"));
MPF_TEST_ASSERTEQUAL(false, config->hasProperty("debug.global_level"));
csvsqldb::StringVector properties;
MPF_TEST_ASSERTEQUAL(0u, config->getProperties("debug.level", properties));
MPF_TEST_EXPECTS(config->get<int32_t>("debug.global_level"), csvsqldb::ConfigurationException);
}
void globalConfigTest()
{
csvsqldb::Configuration::Ptr config(
std::make_shared<csvsqldb::LuaConfiguration>(CSVSQLDB_TEST_PATH + std::string("/testdata/luaengine/test.lua")));
csvsqldb::GlobalConfiguration::create<MyGlobalConfiguration>();
csvsqldb::GlobalConfiguration::instance<MyGlobalConfiguration>()->configure(config);
MPF_TEST_ASSERTEQUAL(1, csvsqldb::GlobalConfiguration::instance<MyGlobalConfiguration>()->debug.global_level);
MPF_TEST_ASSERTEQUAL(3, csvsqldb::GlobalConfiguration::instance<MyGlobalConfiguration>()->debug.level["connection"]);
MPF_TEST_ASSERTEQUAL(815, csvsqldb::config<MyGlobalConfiguration>()->test.wtf);
}
};
MPF_REGISTER_TEST_START("ApplicationTestSuite", ConfigurationTestCase);
MPF_REGISTER_TEST(ConfigurationTestCase::configTest);
MPF_REGISTER_TEST(ConfigurationTestCase::configCheck);
MPF_REGISTER_TEST(ConfigurationTestCase::defaultConfigTest);
MPF_REGISTER_TEST(ConfigurationTestCase::globalConfigTest);
MPF_REGISTER_TEST_END();
| cpp |
Former WWE manager Jim Cornette shared his thoughts on why the company brought back Brock Lesnar to face Roman Reigns at SummerSlam.
On this week's SmackDown, Lesnar made his surprising return to WWE and assaulted long-term rival Roman Reigns. He came out after The Tribal Chief's match against Riddle to plant The Bloodline with F5s. It was later announced by WWE that the two men will face each other at SummerSlam in a Last Man Standing Match.
Speaking on the Jim Cornette Experience, the wrestling veteran said that WWE decided to use the "Brock signal" in the absence of two of their marquee stars, Cody Rhodes and Randy Orton. The two men are currently sidelined with their respective injuries.
Cornette also pointed out how WWE moved the upcoming Money in the Bank Premium Live Event from the Allegiant Stadium to the MGM Grand Garden Arena. For this reason, the company will probably hope to avoid a similar shift for SummerSlam.
Watch Jim Cornette's comments on Brock Lesnar's return on SmackDown:
At WrestleMania 38, Roman Reigns became the Undisputed WWE Universal Champion by defeating Brock Lesnar and unifying the two world titles. Since then, The Tribal Chief has defended both his world titles at live events, but the latest edition of SmackDown marked his first televised defense of the championships.
Moving forward, Reigns will face Lesnar in a Last Man Standing Match at the SummerSlam premium live event.
The Head of the Table successfully defended the Universal Championship against John Cena at SummerSlam last year. After the match, he was confronted by a returning Lesnar, who also attacked Cena after the cameras stopped rolling.
The looming clash between the powerhouses won't be the first time Reigns and Lesnar have shared the ring. Over the years, they have faced each other at numerous WrestleMania main events and on other shows as well.
If you use any quotes from this article, please credit Jim Cornette Experience and add a H/T to Sportskeeda Wrestling for the transcription.
| english |
NewZNew (Chandigarh) : Punjabi film Vaisakhi List who has already taken place in the audience heart Film is going to be release on 22nd April, 2016 worldwide. The film has already released its trailer and first track and here they goes for another track launch.
This film is presented by Amolak Singh Gakhal and produced by Palwinder Singh Gakhal, Gurvinder Singh Gakhal and Iqbal Singh Gakhal(GAKHAL BROS. ENT.) and is directed by Smeep Kang. The lead role is being played by the very famous and versatile actor Jimmy Sheirgill and also is the debut entry of Actor and Comedian Sunil Grover in Pollywood. The star cast also includes Shruti Sodhi, Binnu Dhillon, Nisha Bano, Jaswinder Bhalla, and Karamjit Anmol.
Where the viewers have enjoyed the trailer and first track ‘Jatt Mele Aa Gya’ largely, they will also feel the emotions of freshly released song ‘Tu Dur Gayi.’ Labeled by Gakhal Brothers, The song is sung by Rahat Fateh Ali Khan, the lyrics are penned by the renowned lyricist Kumaar and the music is directed by Jaidev Kumar.
The audience will have a different experience watching this film as unlike other movies the audience would witness prisoners not trying to run from the jail yet getting back into the jail. This humorous and entertaining journey is what differentiates the film from the rest.
You can listen to the track of Punjabi Film Vaisakhi List on Youtube.
| english |
(861 results found for profile picture face)
Illustration Of A Woman Profile Face.Illustration Of A Woman Profile Face.Illustration Of A Profile Man Face.Illustration Of A Profile Man Face.Illustration Of A Woman Profile Face.Illustration Of A Woman Profile Face.Illustration Of A Woman Profile Face.Illustration Of A Profile Man Face.Illustration Of A Woman Profile Face.Illustration Of A Woman Profile Face.Illustration Of A Woman Profile Face.Happy man taking selfie. Focus on smartphoneIllustration Of A Profile Man.Illustration Of A Reindeer.Stylish person capturing selfie. Focus on smartphone.Lovely profile of a brunette womanLovely profile of a brunette womanLovely profile of a brunette womanLovely profile of a brunette womanA closeup of a young woman's side profileFriends Taking Pictures While Making FacesAthletic man in profile. isolated dark backgroundFloral Girl SilhouetteNewspaper - Vector IllustrationFull length portrait of couple cuddling and kiss. in profile. eyes to eyesTHAILAND - SEPTEMBER 2, 2014: Pinterest page first landing page view on web browser.Taking Picture - Office Character - Vector IllustrationValentine Abstract Frame IllustrationTalented bearded food designer in production studio, reviewing photos on computer monitorNewspaper And Media - Vector IllustrationNewspaper - Vector IllustrationTHAILAND - SEPTEMBER 2, 2014: Magnifying glass of Pinterest page first landing page view on web browser.CHIANG MAI, THAILAND - OCTOBER 03, 2014: Pinterest and all of popular social media icons on tablet device screen.THAILAND - SEPTEMBER 2, 2014: Pinterest page first landing page view on web browser.THAILAND - SEPTEMBER 2, 2014: Magnifying glass of Pinterest page first landing page view on web browser.Digital Camera - Office Character - Vector IllustrationClicking A Picture - Office Character - Vector IllustrationDirector Taking Shot - Vector Character Cartoon IllustrationCHIANG MAI, THAILAND - OCTOBER 21, 2014: Pinterest page first landing page view on web browser using Apple macbook pro.Newspaper And Media - Vector IllustrationAsian man in kitchen. looking away. with cereal, tablet and juice. sitting by the tableMan Taking Picture - Office Character - Vector IllustrationTaking Shot With Digital Camera - Business Cartoons CharacterPortrait of a stunning young woman in a white shirt, gazing to the side with a gentle touchCheerful young artist with oil paints on face in workshop, holding palette.Lanner Falcon, rare bird of prey with orange leaves branch in autumn forest, SpainSmiley Vector Illustration - Eye BlinkingA beautiful woman gazing upwards.
| english |
New Delhi: The fisheries sector in the country is grappling with mounting losses for the second consecutive year, as business continues to remain sluggish due to the Covid lockdowns in the key summer months.
The demand and price drop due to the lockdown has been further aggravated by cyclone damage on either coast of the country, coupled with a rise in input prices such as fuel and transportation.
“Each trip into the seas costs one boat about Rs 30,000-40,000 due to fuel, net and ice costs,” said Kiran Koli, secretary of the Maharashtra Machhimar Kruti Samiti (MMKS), a fisherman’s collective.
Stakeholders say that the lockdowns in the states have severely affected business.
In Maharashtra for instance, under new Covid lockdown rules, business in wholesale fish markets has been restricted to until 11 am. This leads to an early shutdown of business in the market with a decline in trade.
According to the fishermen, the restriction has disrupted the seafood supply from coastal areas of Mumbai and the Konkan region, leading to a fall in demand and prices. They now want Maharashtra to increase trading hours in wholesale markets to be extended to 2 pm each day.
Other fish traders in non-seaside cities echo the same concern, adding that to make matters worse, freight rates have increased.
Mahesh added that people are also staying away from popular fish markets due to fear of crowds.
The lockdown has diminished the possibility of profitable business in the fisheries sector on the east coast and other states as well.
Dr. Kumaravelu, vice-chairperson of the National Fishworkers’ Forum (NFF) in Tamil Nadu, told ThePrint that commercial establishments remaining shut in the lockdown has severely affected their business.
“Fishermen are not able to sell to the major source of income, which are restaurants and markets that are shut due to lockdown,” he said.
He said that the annual ban on deep sea fishing has further hurt the sector. India imposes an annual ban from April 15 until 14 June on the east coast, and 1 June and 31 July on the west coast every year. This year, however, the fisheries ministry has reduced the ban period on the east coast from 15 April to 31 May, and on the west coast from 15 June to 31 July.
“Popular produce in local markets also witnessed sudden and massive price drops. The prawn rate dropped to Rs 150/kg from the usual cost of Rs 600-650/kg,” he added.
Similar sentiments are echoed by fishermen in neighbouring Andhra Pradesh.
Usman Seragai, the NFF secretary in Gujarat and owner of a seafood company, said it was a similar situation in the state.
“Though fishing was allowed as an essential service during lockdown, vital infrastructures related to it such as transport and markets were heavily curtailed leading to less price recovery on the catch for fishermen even after paying increased input and transportation cost,” he said.
Frequent cyclones have also wreaked havoc on the already battered fisheries sector on either coast of the country.
While Cyclone Tauktae affected the west coast throughout the latter half of May, Cyclone Yass rampaged through the east coast around the same time.
According to the fishermen in Odisha, Cyclone Yaas, which made landfall in the state on 26 May, and the resultant floods have shattered the hopes of thousands of inland shrimp and fish farmers in districts such as Bhadrak, Balasore and Kendrapara among other coastal areas.
Allaya of the Odisha Marine Fish Producers’ Association told ThePrint that the government should provide the shrimp farmers with interest-free loans.
Usman Seragai said Cyclone Tauktae did similar damage in Gujarat.
According to experts, the damage in the inland fisheries sector has been twice as much as the marine fisheries sector.
The inland sector plays a vital role in providing dry fish, fish oil, and fish as well poultry meal for domestic consumption as well as exporting products like Norwegian Salmon to other countries such as Chile and Norway.
“Even after lockdown, companies that buy material for fish oil or poultry meals are missing due to a dip in demand in their export and other domestic ends,” he added.
To add more woes, the monsoon fishing ban has also kicked in. This period is normally utilised by fishermen to repair their boats but most say they have no capital for it.
Even women workers in fisheries who are also a part of the sector in fish vending and other businesses have been adversely affected.
(Edited by Arun Prashanth) | english |
As the yearly tradition goes, Madden released edge rusher ratings. In this article, we look at three surprises in the top-notch video game.
The Madden release lacks a 99-rated edge rusher. But, ratings may change during the NFL season. Bosa and Garrett reached 98 ratings, with Bosa deserving a 99, as he plays a key role in the 49ers' defense.
Despite Miller's potential HOF status, his 94 rating in Madden seems undeserved due to an injury-plagued 2022 season with Bills. The worst thing is that he ranks higher than the Raiders' Crosby on the list.
Crosby's lack of recognition from EA Sports is possibly due to his team, but he deserves greater respect. Miller's sacks are impactful, yet Crosby should be rated at least 95.
Bosa's 91 rating and top 10 spot in Madden's edge rushers list are debatable. He's still a defensive threat but may have lost speed. Rating seems reputation-based rather than recent performance.
Joey Bosa could be amused, eagerly anticipating the chance to silence critics by delivering a season worthy of Defensive Player of the Year honors. | english |
KGS vs PAT Dream11 Team Prediction and Suggestions for today’s Pondicherry T10 Tournament 2022 match between Kings and Patriots: It will be a battle of the toppers in the Pondicherry T10 tournament 2022 on Wednesday as the Patriots will lock horns with the Kings.
Kings are second in the standings with two wins and one loss from four league matches. Their unbeaten ride in the tournament came to an end in their last match as they endured a 30-run loss against Titans. Kings’ batting line-up witnessed a rare collapse as none of their batters were successful in scoring even 30 runs. As a result, the team posted only 78 runs while following a target of 109.
Patriots, on the other hand, are yet to lose a game. They have all four league matches to sit at the top of the table. The patriots outclassed the Eagles in their last game by restricting them to a below-average score of 60 runs in ten overs.
Ahead of the match between Kings and Patriots, here is everything you need to know:
The Pondicherry T10 Tournament 2022 will be streamed live on the FanCode app and website.
KGS vs PAT match will be played at the CAP Siechem Ground in Pondicherry at 08:30 AM IST on May 25, Wednesday. | english |
import string
from .network import g2p_network
graphemes = ["<pad>", "<unk>", "</s>"] + list(string.ascii_lowercase)
grapheme_to_index = {x: i for i, x in enumerate(graphemes)}
UNKNOWN_GRAPHEME = grapheme_to_index["<unk>"]
END_OF_WORD = grapheme_to_index["</s>"]
phonemes = [
"<pad>",
"<unk>",
"<s>",
"</s>",
"AA0",
"AA1",
"AA2",
"AE0",
"AE1",
"AE2",
"AH0",
"AH1",
"AH2",
"AO0",
"AO1",
"AO2",
"AW0",
"AW1",
"AW2",
"AY0",
"AY1",
"AY2",
"B",
"CH",
"D",
"DH",
"EH0",
"EH1",
"EH2",
"ER0",
"ER1",
"ER2",
"EY0",
"EY1",
"EY2",
"F",
"G",
"HH",
"IH0",
"IH1",
"IH2",
"IY0",
"IY1",
"IY2",
"JH",
"K",
"L",
"M",
"N",
"NG",
"OW0",
"OW1",
"OW2",
"OY0",
"OY1",
"OY2",
"P",
"R",
"S",
"SH",
"T",
"TH",
"UH0",
"UH1",
"UH2",
"UW",
"UW0",
"UW1",
"UW2",
"V",
"W",
"Y",
"Z",
"ZH",
]
def predict(graphemes):
indices = [grapheme_to_index.get(x, UNKNOWN_GRAPHEME) for x in graphemes]
indices.append(END_OF_WORD)
preds = g2p_network.predict(indices)
preds = [phonemes[i] for i in preds]
return preds
| python |
<filename>node_modules/.cache/vue-loader/6a83f526cd99e9fd438669e2fe6d538e.json
{"remainingRequest":"E:\\VUE\\vue-element-admin\\node_modules\\vue-loader\\lib\\index.js??vue-loader-options!E:\\VUE\\vue-element-admin\\src\\views\\example\\components\\ArticleDetail.vue?vue&type=style&index=0&id=53a465a6&lang=scss&scoped=true&","dependencies":[{"path":"E:\\VUE\\vue-element-admin\\src\\views\\example\\components\\ArticleDetail.vue","mtime":1568391861221},{"path":"E:\\VUE\\vue-element-admin\\node_modules\\css-loader\\index.js","mtime":499162500000},{"path":"E:\\VUE\\vue-element-admin\\node_modules\\vue-loader\\lib\\loaders\\stylePostLoader.js","mtime":499162500000},{"path":"E:\\VUE\\vue-element-admin\\node_modules\\postcss-loader\\src\\index.js","mtime":499162500000},{"path":"E:\\VUE\\vue-element-admin\\node_modules\\sass-loader\\dist\\cjs.js","mtime":499162500000},{"path":"E:\\VUE\\vue-element-admin\\node_modules\\cache-loader\\dist\\cjs.js","mtime":499162500000},{"path":"E:\\VUE\\vue-element-admin\\node_modules\\vue-loader\\lib\\index.js","mtime":499162500000}],"contextDependencies":[],"result":["\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n@import \"~@/styles/mixin.scss\";\n\n.createPost-container {\n position: relative;\n\n .createPost-main-container {\n padding: 40px 45px 20px 50px;\n\n .postInfo-container {\n position: relative;\n @include clearfix;\n margin-bottom: 10px;\n\n .postInfo-container-item {\n float: left;\n }\n }\n }\n\n .word-counter {\n width: 40px;\n position: absolute;\n right: 10px;\n top: 0px;\n }\n}\n\n.article-textarea /deep/ {\n textarea {\n padding-right: 40px;\n resize: none;\n border: none;\n border-radius: 0px;\n border-bottom: 1px solid #bfcbd9;\n }\n}\n",null]} | json |
<gh_stars>0
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package it.stealth.sql;
import it.stealth.sql.connection.DbConnectionProvider;
import it.stealth.sql.connection.StickyConnectionProvider;
import it.stealth.sql.connection.UnclosableConnectionProvider;
import it.stealth.sql.readers.SQLQueryReader;
import it.stealth.sql.readers.SQLQueryReaders;
import it.stealth.sql.wrappers.PreparedStatementWrapper;
import java.io.InputStream;
import java.io.Reader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;
import org.apache.commons.lang3.Validate;
import it.stealth.sql.util.SQLUtils;
/**
* Defines an object responsible for executing SQL commands.
*
* @author <NAME>
* @version 1.0
*/
public class SQLEngine
{
/**
* Reference to the internal connection provider.
*/
private final StickyConnectionProvider mProvider;
/**
* Defines the parameter name for the JDBC connection.
*/
protected static final String DbConnParam = "dbConn";
/**
* Defines the parameter name for an SQL command.
*/
private static final String SqlCommandParam = "sqlCommand";
/**
* Defines the parameter name for the query result reader.
*/
private static final String QueryReaderParam = "queryReader";
/**
* Defines the name of the parameter related to the database connection provider.
*/
private static final String DbConnProviderParam = "dbConnectionProvider";
/**
* Exception message raised when the supplied SQL
* command string is {@code null} or an blank string.
*/
private static final String ExBlankSqlCmd = "Unable to generate a "
+ "SQL statement starting from a null or blank string.";
/**
* Initializes an instance of {@link SQLEngine}
* class specifying the database connection provider.
*
* @param dbConnectionProvider database connection provider.
* @throws NullPointerException if {@code dbConnectionProvider} is {@code null}.
*/
public SQLEngine(final DbConnectionProvider dbConnectionProvider) {
// Invokes the overloaded constructor
this(dbConnectionProvider, false);
}
/**
* Initializes an instance of {@link SQLEngine} class
* specifying the database connection provider and whether to
* keep the database connection alive for multiple requests.
*
* @param dbConnectionProvider database connection provider.
* @param keepAlive {@code true} to keep alive the connection provided.
* @throws NullPointerException if {@code dbConnectionProvider} is {@code null}.
*/
public SQLEngine(final DbConnectionProvider dbConnectionProvider, final boolean keepAlive) {
// Check that the database connection provider is not null and install it within an object
// that implements the functionality to keep the database connection alive on demand
this.mProvider = new StickyConnectionProvider(SQLEngine.unwrap(
Objects.requireNonNull(dbConnectionProvider, SQLEngine.
DbConnProviderParam)), keepAlive);
}
//<editor-fold defaultstate="collapsed" desc="PreparedStatement wrapper that closes all associated resources">
/**
* Implements a {@link PreparedStatement} wrapper tasked with closing all
* resources associated with that statement during the closing phase.
*/
private static final class RHPS extends PreparedStatementWrapper
{
/**
* Reference to the object queue to be closed.
*/
private final Queue<AutoCloseable> mQueue;
/**
* Class constructor.
*
* @param inner statement to wrap.
*/
public RHPS(final PreparedStatement inner) {
// Invokes the superclass builder
super(inner);
// Instantiate the queue of associated resources
this.mQueue = new LinkedList<>();
}
/**
* {@inheritDoc}
*/
@Override
public void setClob(final int parameterIndex,
final Reader reader) throws SQLException {
// Invokes the superclass method
super.setClob(parameterIndex, reader);
// Add the parameter to the queue
this.mQueue.add(reader);
}
/**
* {@inheritDoc}
*/
@Override
public void setNClob(final int parameterIndex,
final Reader reader) throws SQLException {
// Invokes the superclass method
super.setNClob(parameterIndex, reader);
// Add the parameter to the queue
this.mQueue.add(reader);
}
/**
* {@inheritDoc}
*/
@Override
public void setAsciiStream(final int parameterIndex,
final InputStream x) throws SQLException {
// Invokes the superclass method
super.setAsciiStream(parameterIndex, x);
// Add the parameter to the queue
this.mQueue.add(x);
}
/**
* {@inheritDoc}
*/
@Override
public void setBinaryStream(final int parameterIndex,
final InputStream x) throws SQLException {
// Invokes the superclass method
super.setBinaryStream(parameterIndex, x);
// Add the parameter to the queue
this.mQueue.add(x);
}
/**
* {@inheritDoc}
*/
@Override
public void setBlob(final int parameterIndex, final
InputStream inputStream) throws SQLException {
// Invokes the superclass method
super.setBlob(parameterIndex, inputStream);
// Add the parameter to the queue
this.mQueue.add(inputStream);
}
/**
* {@inheritDoc}
*/
@Override
public void setCharacterStream(final int parameterIndex,
final Reader reader) throws SQLException {
// Invokes the superclass method
super.setCharacterStream(parameterIndex, reader);
// Add the parameter to the queue
this.mQueue.add(reader);
}
/**
* {@inheritDoc}
*/
@Override
public void setNCharacterStream(final int parameterIndex,
final Reader value) throws SQLException {
// Invokes the superclass method
super.setNCharacterStream(parameterIndex, value);
// Add the parameter to the queue
this.mQueue.add(value);
}
/**
* {@inheritDoc}
*/
@Override
public void setClob(final int parameterIndex, final Reader
reader, final long length) throws SQLException {
// Invokes the superclass method
super.setClob(parameterIndex, reader, length);
// Add the parameter to the queue
this.mQueue.add(reader);
}
/**
* {@inheritDoc}
*/
@Override
public void setNClob(final int parameterIndex, final Reader
reader, final long length) throws SQLException {
// Invokes the superclass method
super.setNClob(parameterIndex, reader, length);
// Add the parameter to the queue
this.mQueue.add(reader);
}
/**
* {@inheritDoc}
*/
@Override
public void setAsciiStream(final int parameterIndex, final
InputStream x, final int length) throws SQLException {
// Invokes the superclass method
super.setAsciiStream(parameterIndex, x, length);
// Add the parameter to the queue
this.mQueue.add(x);
}
/**
* {@inheritDoc}
*/
@Override
public void setBinaryStream(final int parameterIndex, final
InputStream x, final int length) throws SQLException {
// Invokes the superclass method
super.setBinaryStream(parameterIndex, x, length);
// Add the parameter to the queue
this.mQueue.add(x);
}
/**
* {@inheritDoc}
*/
@Override
public void setAsciiStream(final int parameterIndex, final
InputStream x, final long length) throws SQLException {
// Invokes the superclass method
super.setAsciiStream(parameterIndex, x, length);
// Add the parameter to the queue
this.mQueue.add(x);
}
/**
* {@inheritDoc}
*/
@Override
public void setBinaryStream(final int parameterIndex, final
InputStream x, final long length) throws SQLException {
// Invokes the superclass method
super.setAsciiStream(parameterIndex, x, length);
// Add the parameter to the queue
this.mQueue.add(x);
}
/**
* {@inheritDoc}
*/
@Override
public void setUnicodeStream(final int parameterIndex, final
InputStream x, final int length) throws SQLException {
// Invokes the superclass method
super.setUnicodeStream(parameterIndex, x, length);
// Add the parameter to the queue
this.mQueue.add(x);
}
/**
* {@inheritDoc}
*/
@Override
public void setBlob(final int parameterIndex, final InputStream
inputStream, final long length) throws SQLException {
// Invokes the superclass method
super.setBlob(parameterIndex, inputStream, length);
// Add the parameter to the queue
this.mQueue.add(inputStream);
}
/**
* {@inheritDoc}
*/
@Override
public void setCharacterStream(final int parameterIndex, final
Reader reader, final int length) throws SQLException {
// Invokes the superclass method
super.setCharacterStream(parameterIndex, reader, length);
// Add the parameter to the queue
this.mQueue.add(reader);
}
/**
* {@inheritDoc}
*/
@Override
public void setCharacterStream(final int parameterIndex, final
Reader reader, final long length) throws SQLException {
// Invokes the superclass method
super.setCharacterStream(parameterIndex, reader, length);
// Add the parameter to the queue
this.mQueue.add(reader);
}
/**
* {@inheritDoc}
*/
@Override
public void setNCharacterStream(final int parameterIndex, final
Reader value, final long length) throws SQLException {
// Invokes the superclass method
super.setNCharacterStream(parameterIndex, value, length);
// Add the parameter to the queue
this.mQueue.add(value);
}
/**
* Closes all resources associated with the statement.
*
* @throws SQLException if an error occurs while closing a resource.
*/
private void closeResources() throws SQLException {
// Declare a support reference
AutoCloseable res;
// Itera until the queue is empty
while (!this.mQueue.isEmpty()) {
// Dequeue a resource from queue
res = this.mQueue.poll();
// Check that this resource is not null
if (res != null) {
// Starts a try-catch block
try {
// Closes this resource
res.close();
}
// Capture any exception
// raised when closing a resource
catch (final Exception ex) {
// Wrap this exception in a SQLException
throw new SQLException(ex);
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void clearParameters() throws SQLException {
// Invokes the superclass method
super.clearParameters();
// Close all associated resources
this.closeResources();
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws SQLException {
// Invokes the superclass method
super.close();
// Close all associated resources
this.closeResources();
}
}//</editor-fold>
/**
* Envelops the statement in an instance that closes all resources in closing.
* <p>By wrapping a {@link PreparedStatement} through this method it is ensured
* that all the resources associated with it (each object implements the
* {@link AutoCloseable} interface, such as {@link InputStream} and
* {@link Reader}) are released when the statement is closed.</p>
*
* @param stmt a {@link PreparedStatement} to wrap.
* @return an instance of {@link PreparedStatement} that closes all resources being closed.
*/
public static final PreparedStatement asResourceHolder(final PreparedStatement stmt) {
// Envelops the statement in an instance that closes all resources in closing
return stmt instanceof SQLEngine.RHPS ? stmt : new SQLEngine.RHPS(stmt);
}
/**
* Internal procedure that attempts to recover the original
* {@link DbConnectionProvider}, freeing it from external layers.
* <p>Among the known external layers are the classes: {@link
* SQLEngine}, {@link StickyConnectionProvider} and {@link
* UnclosableConnectionProvider}.</p>
*
* @param dcp {@link DbConnectionProvider} reference to unwrap.
* @return internal instance managed by the classes listed in
* the description, or the instance itself.
*/
private static DbConnectionProvider unwrap(final DbConnectionProvider dcp) {
// Check if a StickyConnectionProvider has been provided
if (dcp instanceof StickyConnectionProvider) {
// Retrieves the original connection provider reference
return ((StickyConnectionProvider) dcp).getOriginalProvider();
}
// Check if a UnclosableConnectionProvider has been provided
if (dcp instanceof UnclosableConnectionProvider) {
// Retrieves the original connection provider reference
return ((UnclosableConnectionProvider) dcp).getInnerProvider();
}
// Return the instance provided
return dcp;
}
/**
* Executes an SQL query by storing the results in a {@link QueryResults}.
* <p>This procedure is designed to perform simple (non-parametric) queries.</p>
* <p>The query results are stored and returned into a {@link QueryResults}. It
* can be considered the disconnected version of a {@link ResultSet}, since it
* does not hold any connection resource to the data source with which it was
* populated.</p>
*
* @param sqlQuery SQL query that must be sent to the database.
* @return {@link QueryResults} that encapsulates the query results.
* @throws SQLException if an error occurs while querying the database.
* @see QueryResults
*/
public final QueryResults query(final String sqlQuery) throws SQLException {
// Executes the query provided by storing the results in a QueryResults
return this.query(sqlQuery, SQLQueryReaders.DefaultReader);
}
/**
* Executes an SQL query whose results are read by a certain reader.
* <p>This procedure is designed to perform simple (non-parametric) queries.</p>
* <p>The control of the {@link ResultSet} is passed directly to the reader,
* who has the task of scrolling through the records provided by it.</p>
*
* @param <T> type of the object returned by the query.
* @param sqlQuery SQL query that must be sent to the database.
* @param queryReader reader of the query results.
* @return object that encapsulates the query results.
* @throws SQLException if an error occurs while querying the database.
*/
public final <T> T query(final String sqlQuery, final
SQLQueryReader<T> queryReader) throws SQLException {
// Check that the query reader reference is not null
Objects.requireNonNull(queryReader, SQLEngine.QueryReaderParam);
// Make sure the SQL query string is not a null or blank string
Validate.notBlank(sqlQuery, SQLEngine.ExBlankSqlCmd);
// Opens a connection to the database in which to perform the query
try (final Connection dbConn = this.mProvider.getDbConnection()) {
// Create an empty statement to send commands to the database
try (final Statement stmt = dbConn.createStatement()) {
// Execute the query and return the results
try (final ResultSet rs = stmt.executeQuery(sqlQuery)) {
// Invokes the callback to read the query results
return queryReader.read(rs);
}
}
}
}
/**
* Executes an SQL query verifying if it returns at least one record.
* <p>This procedure is designed to perform simple (non-parametric) queries.</p>
* <p>This procedure does nothing more than execute the query provided, limiting
* itself to determining whether the product {@link ResultSet} is not empty.</p>
*
* @param sqlQuery SQL query that must be sent to the database.
* @return {@code true} if the query produced at least one result.
* @throws SQLException if an error occurs while querying the database.
* @since 1.3
*/
public final boolean hasRecord(final String sqlQuery) throws SQLException {
// Executes the SQL query checking that at least one result is provided
return this.query(sqlQuery, SQLUtils.HasQueryResults);
}
// /**
// * Executes an SQL query whose results are read by a certain reader.
// * <p>This procedure is designed to perform simple (non-parametric) queries.</p>
// * <p>The control of the {@link ResultSet} is passed directly to the reader,
// * who has the task of scrolling through the records provided by it.</p>
// *
// * @param <T> type of the object returned by the query.
// * @param sqlQuery SQL query that must be sent to the database.
// * @param queryReader reader of the query results.
// * @param args ####################################.
// * @return object that encapsulates the query results.
// * @throws SQLException if an error occurs while querying the database.
// */
// public final <T> T query(final String sqlQuery, final SQLQueryReader<T>
// queryReader, final Object... args) throws SQLException {
// // Check that the query reader reference is not null
// Objects.requireNonNull(queryReader, SQLEngine.QueryReaderParam);
// // Make sure the SQL query string is not a null or blank string
// Validate.notBlank(sqlQuery, SQLEngine.ExBlankSqlCmd);
// // Opens a connection to the database in which to perform the query
// try (final Connection dbConn = this.mProvider.getDbConnection()) {
// // Create an empty statement to send commands to the database
// try (final PreparedStatement stmt = dbConn.prepareStatement(sqlQuery)) {
// // ##################################
// SQLEngine.writeParams(stmt, args);
// // Execute the query and return the results
// try (final ResultSet rs = stmt.executeQuery()) {
// // Invokes the callback to read the query results
// return queryReader.read(rs);
// }
// }
// }
// }
//
// private static void writeParams(final PreparedStatement
// stmt, final Object[] args) throws SQLException {
// int i;
// if (args != null) {
// for (i = 1; i < args.length; i++) {
// stmt.setObject(i, args[i]);
// }
// }
// }
/**
* Executes an SQL query by storing the results in a {@link QueryResults}.
* <p>This procedure is designed to perform simple (non-parametric) queries.</p>
* <p>The query results are stored and returned into a {@link QueryResults}. It
* can be considered the disconnected version of a {@link ResultSet}, since it
* does not hold any connection resource to the data source with which it was
* populated.</p><p>This version uses the connection provided by the outside
* to execute the query.</p>
*
* @param dbConn open connection with the database.
* @param sqlQuery SQL query that must be sent to the database.
* @return {@link QueryResults} that encapsulates the query results.
* @throws SQLException if an error occurs while querying the database.
*/
public static final QueryResults query(final Connection
dbConn, final String sqlQuery) throws SQLException {
// Executes the query provided by storing the results in a QueryResults
return SQLEngine.query(dbConn, sqlQuery, SQLQueryReaders.DefaultReader);
}
/**
* Executes an SQL query whose results are read by a certain reader.
* <p>This procedure is designed to perform simple (non-parametric) queries.</p>
* <p>The control of the {@link ResultSet} is passed directly to the reader,
* who has the task of scrolling through the records provided by it.</p>
* <p>This version uses the connection provided by the outside to
* execute the query.</p>
*
* @param <T> type of the object returned by the query.
* @param dbConn open connection with the database.
* @param sqlQuery SQL query that must be sent to the database.
* @param queryReader reader of the query results.
* @return object that encapsulates the query results.
* @throws SQLException if an error occurs while querying the database.
*/
public static final <T> T query(final Connection dbConn, final String
sqlQuery, final SQLQueryReader<T> queryReader) throws SQLException {
// Check that the connection reference is not null
Objects.requireNonNull(dbConn, SQLEngine.DbConnParam);
// Check that the query reader reference is not null
Objects.requireNonNull(queryReader, SQLEngine.QueryReaderParam);
// Make sure the SQL query string is not a null or blank string
Validate.notBlank(sqlQuery, SQLEngine.ExBlankSqlCmd);
// Create an empty statement to send commands to the database
try (final Statement stmt = dbConn.createStatement()) {
// Execute the query and return the results
try (final ResultSet rs = stmt.executeQuery(sqlQuery)) {
// Invokes the callback to read the query results
return queryReader.read(rs);
}
}
}
/**
* Executes an SQL query verifying if it returns at least one record.
* <p>This procedure is designed to perform simple (non-parametric) queries.</p>
* <p>This procedure does nothing more than execute the query provided, limiting
* itself to determining whether the product {@link ResultSet} is not empty.</p>
* <p>This version uses the connection provided by the outside to
* execute the query.</p>
*
* @param dbConn open connection with the database.
* @param sqlQuery SQL query that must be sent to the database.
* @return {@code true} if the query produced at least one result.
* @throws SQLException if an error occurs while querying the database.
* @since 1.3
*/
public static final boolean hasRecord(final Connection
dbConn, final String sqlQuery) throws SQLException {
// Executes the SQL query checking that at least one result is provided
return SQLEngine.query(dbConn, sqlQuery, SQLUtils.HasQueryResults);
}
/**
* Execute an SQL Data Manipulation Language command (ie INSERT,
* UPDATE, REPLACE or DELETE) through the default connection
* provided by the underlying {@link DbConnectionProvider}.
* <p>It's also possible to request that the operation be
* performed within an SQL transaction, through the
* {@code transactional} parameter.</p>
*
* @param sqlCommand SQL DML command to execute.
* @param transactional indicates whether the command should
* be executed within an SQL transaction.
* @return either (1) the row count for SQL Data Manipulation Language
* statements or (2) 0 for SQL statements that return nothing
* @throws SQLException if a database access error occurs.
*/
public final int execute(final String sqlCommand, final
boolean transactional) throws SQLException {
// Check whether to perform a transaction
if (transactional) {
// Execute the command within an SQL transaction
return this.executeTran(sqlCommand);
} else {
// Execute the command with a normal connection
return this.execute(sqlCommand);
}
}
/**
* Execute an SQL Data Manipulation Language command (ie INSERT,
* UPDATE, REPLACE or DELETE) using a certain database connection.
*
* @param dbConn open connection with the database.
* @param sqlCommand SQL DML command to execute.
* @return either (1) the row count for SQL Data Manipulation Language
* statements or (2) 0 for SQL statements that return nothing
* @throws SQLException if a database access error occurs.
*/
public final static int execute(final Connection dbConn,
final String sqlCommand) throws SQLException {
// Make sure the SQL command string is not a null or blank string
Validate.notBlank(sqlCommand, SQLEngine.ExBlankSqlCmd);
// Create an empty statement to send commands to the database
try (final Statement stmt = dbConn.createStatement()) {
// Executes the SQL command provided
return stmt.executeUpdate(sqlCommand);
}
}
/**
* Execute an SQL Data Manipulation Language command (ie INSERT,
* UPDATE, REPLACE or DELETE) through the default connection
* provided by the underlying {@link DbConnectionProvider}.
*
* @param sqlCommand SQL DML command to execute.
* @return either (1) the row count for SQL Data Manipulation Language
* statements or (2) 0 for SQL statements that return nothing
* @throws SQLException if a database access error occurs.
*/
public final int execute(final String sqlCommand) throws SQLException {
// Make sure the SQL command string is not a null or blank string
Validate.notBlank(sqlCommand, SQLEngine.ExBlankSqlCmd);
// Open a connection to the database on which to execute the command
try (final Connection dbConn = this.getDbConnection()) {
// Create an empty statement to send commands to the database
try (final Statement stmt = dbConn.createStatement()) {
// Executes the SQL command provided
return stmt.executeUpdate(sqlCommand);
}
}
}
/**
* Execute an SQL Data Manipulation Language command (ie
* INSERT, UPDATE, REPLACE or DELETE) through a transaction
* with the database that uses the connection provided by the
* underlying {@link DbConnectionProvider}.
*
* @param sqlCommand SQL DML command to execute.
* @return either (1) the row count for SQL Data Manipulation Language
* statements or (2) 0 for SQL statements that return nothing
* @throws SQLException if a database access error occurs.
*/
public final int executeTran(final String sqlCommand) throws SQLException {
// Declares a support int
final int rowCount;
// Make sure the SQL command string is not a null or blank string
Validate.notBlank(sqlCommand, SQLEngine.ExBlankSqlCmd);
// Opens a transaction to the database to execute the command
try (final Transaction dbTran = this.getDbTransaction()) {
// Create an empty statement to send commands to the database
try (final Statement stmt = dbTran.createStatement()) {
// Executes the SQL command provided
rowCount = stmt.executeUpdate(sqlCommand);
// Mark this transaction as completed
if (rowCount >= 0) dbTran.complete();
}
}
// Returns the number of rows
// affected by this command
return rowCount;
}
/**
* Execute a sequence of SQL Data Manipulation Language command
* (ie INSERT, UPDATE, REPLACE or DELETE) through a transaction
* with the database that uses the connection provided by the
* underlying {@link DbConnectionProvider}.
*
* @param sqlCommands array of SQL DML commands to execute.
* @return either (1) the row count for SQL Data Manipulation Language
* statements or (2) 0 for SQL statements that return nothing.
* @throws SQLException if a database access error occurs.
*/
public final int executeTran(final String... sqlCommands) throws SQLException {
// Declares three support integers
int i, rowCount, totCount = 0;
// Make sure that every SQL command is not null or blank
SQLEngine.checkSqlCommandArray(sqlCommands);
// Opens a transaction to the database to execute the command
try (final Transaction dbTran = this.getDbTransaction()) {
// Create an empty statement to send commands to the database
try (final Statement stmt = dbTran.createStatement()) {
// Iterate on all the SQL commands provided
for (i = 0; i < sqlCommands.length; i++) {
// Executes each SQL command provided
rowCount = stmt.executeUpdate(sqlCommands[i]);
// Returns the counter value if negative
if (rowCount < 0) return rowCount;
// Adds this value to the total counter
totCount += rowCount;
}
// Check that at least one rows has been involved
if (totCount > 0) {
// Mark this transaction as completed
dbTran.complete();
}
}
}
// Returns the total number of
// rows involved by the commands
return totCount;
}
/**
* Executes a sequence of SQL Data Manipulation Language command (ie
* INSERT, UPDATE, REPLACE or DELETE) through the default connection
* provided by the underlying {@link DbConnectionProvider}.
*
* @param sqlCommands array of SQL DML commands to execute.
* @return sum of all the rows involved by the commands provided.
* @throws SQLException if a database access error occurs.
*/
public final int execute(final String... sqlCommands) throws SQLException {
// Declares three support integers
int i, rowCount, totCount = 0;
// Make sure that every SQL command is not null or blank
SQLEngine.checkSqlCommandArray(sqlCommands);
// Open a connection to the database on which to execute the command
try (final Connection dbConn = this.getDbConnection()) {
// Create an empty statement to send commands to the database
try (final Statement stmt = dbConn.createStatement()) {
// Iterate on all the SQL commands provided
for (i = 0; i < sqlCommands.length; i++) {
// Executes each SQL command provided
rowCount = stmt.executeUpdate(sqlCommands[i]);
// Returns the counter value if negative
if (rowCount < 0) return rowCount;
// Adds this value to the total counter
totCount += rowCount;
}
}
}
// Returns the total number of
// rows involved by the commands
return totCount;
}
/**
* Executes a sequence of SQL Data Manipulation Language command (ie
* INSERT, UPDATE, REPLACE or DELETE) using a certain database connection.
*
* @param dbConn open connection with the database.
* @param sqlCommands array of SQL DML commands to execute.
* @return sum of all the rows involved by the commands provided.
* @throws SQLException if a database access error occurs.
*/
public final static int execute(final Connection dbConn,
final String... sqlCommands) throws SQLException {
// Declares three support integers
int i, rowCount, totCount = 0;
// Make sure that every SQL command is not null or blank
SQLEngine.checkSqlCommandArray(sqlCommands);
// Check that the connection reference is not null
Objects.requireNonNull(dbConn, SQLEngine.DbConnParam);
// Create an empty statement to send commands to the database
try (final Statement stmt = dbConn.createStatement()) {
// Iterate on all the SQL commands provided
for (i = 0; i < sqlCommands.length; i++) {
// Executes each SQL command provided
rowCount = stmt.executeUpdate(sqlCommands[i]);
// Returns the counter value if negative
if (rowCount < 0) return rowCount;
// Adds this value to the total counter
totCount += rowCount;
}
}
// Returns the total number of
// rows involved by the commands
return totCount;
}
/**
* Internal utility method that checks
* that no SQL command is null or blank.
*
* @param sqlCommands array of SQL commands to check.
*/
private static void checkSqlCommandArray(final String[] sqlCommands) {
// Check that the array is not null or empty
Validate.notEmpty(sqlCommands, SQLEngine.SqlCommandParam);
// Iterate over all SQL commands held by the array
for (final String sqlCommand : sqlCommands) {
// Check that none of them is null or blank
Validate.notBlank(sqlCommand, SQLEngine.SqlCommandParam);
}
}
/**
* Set a value that indicates whether the database
* connection provided by this engine should be kept alive.
* <p>Keeping a connection alive means inhibiting the closing operation,
* which normally allows terminating communication with the database.</p>
* <p>If for some reason it is necessary to reuse the same connection on
* several occasions (that is, multiple calls of the {@link #getDbConnection()}
* method) and you want to inhibit the closing operation for all the duration
* of this period, you can set the retention for the connection provided by
* this engine.</p>
*
* @param keepAlive {@code true} to keep alive the connection provided by this engine.
* @throws SQLWarning if errors occur during the resetting of the closing operation.
* @see #isConnectionKeptAlive()
*/
public final void setConnectionKeepAlive(final boolean keepAlive) throws SQLWarning {
// Invokes the internal connection provider method
this.mProvider.setDbConnectionKeepAlive(keepAlive);
}
/**
* Attempts to establish a connection to
* the database by starting a new transaction.
*
* @return a connection to the database in the form of a transaction.
* @throws SQLException if a database access error occurs.
* @see it.stealth.sql.connection.DbConnectionProvider#getDbConnection()
*/
public final Transaction getDbTransaction() throws SQLException {
// Wraps the new connection within a transaction
return new Transaction(this.mProvider.getDbConnection());
}
/**
* Gets the database connection provider currently in use.
*
* @return database connection provider currently used.
*/
public final DbConnectionProvider getConnectionProvider() {
// Return the database connection provider
return this.mProvider.getOriginalProvider();
}
/**
* Attempts to establish a connection to the database.
* <p>By default, the generated connection has autocommit enabled.</p>
*
* @return a connection to the database.
* @throws SQLException if a database access error occurs.
* @see it.next.sql.connection.DbConnectionProvider#getDbConnection()
*/
private Connection getDbConnection() throws SQLException {
// Try to get an open connection to the database
return this.mProvider.getDbConnection();
}
/**
* Indicates if the connection used by this engine is kept alive.
* <p>Keeping a connection alive means inhibiting the closing operation,
* which normally allows terminating communication with the database.</p>
*
* @return {@code true} if the connection provided is kept alive.
* @see #setConnectionKeepAlive(boolean)
*/
public final boolean isConnectionKeptAlive() {
// Invokes the internal connection provider method
return this.mProvider.isDbConnectionKeptAlive();
}
}
| java |
"""Shelving Filter Cascade with Adjustable Transition Slope and Bandwidth
<NAME>, <NAME>, <NAME>
In: Proc. of 148th AES Convention, Virtual Vienna, May 2020, Paper 10339
http://www.aes.org/e-lib/browse.cfm?elib=20756
"""
import numpy as np
from scipy.signal import tf2sos, freqs
from matplotlib import rcParams
def halfpadloss_shelving_filter_num_den_coeff(G):
"""Half-pad-loss polynomial coefficients for 1st/2nd order shelving filter.
- see type III in
long-url: https://github.com/spatialaudio/digital-signal-processing-lecture/blob/master/filter_desig/audiofilter.ipynb # noqa
- see Sec. 3.2 in https://doi.org/10.3390/app6050129
"""
sign = np.sign(G) # amplify/boost (1) or attenuate/cut (-1)
g = 10**(np.abs(G) / 20) # linear gain
n1, n2 = g**(sign / 4), g**(sign / 2) # numerator coeff
d1, d2 = 1 / n1, 1 / n2 # denominator coeff
return n1, n2, d1, d2
def normalized_low_shelving_1st_coeff(G=-10*np.log10(2)):
"""See low_shelving_1st_coeff() for omega=1."""
n1, n2, d1, d2 = halfpadloss_shelving_filter_num_den_coeff(G)
b, a = np.array([0, 1, n2]), np.array([0, 1, d2])
return b, a
def low_shelving_1st_coeff(omega=1, G=-10*np.log10(2)):
"""Half-pad-loss/mid-level low shelving filter 1st order.
Parameters
----------
omega : angular frequency in rad/s at half-pad-loss/mid-level
G : level in dB (G/2 at omega)
Returns
-------
b[0] s^2 + b[1] s^1 + b[2] s^0
b,a : coefficients for Laplace H(s) = ------------------------------
a[0] s^2 + a[1] s^1 + a[2] s^0
with s = j omega, note: b[0]=a[0]=0 here for 1st order filter
see halfpadloss_shelving_filter_num_den_coeff() for references
"""
b, a = normalized_low_shelving_1st_coeff(G=G)
scale = omega**np.arange(-2., 1.) # powers in the Laplace domain
return b * scale, a * scale
def normalized_high_shelving_1st_coeff(G=-10*np.log10(2)):
"""See high_shelving_1st_coeff() for omega=1."""
n1, n2, d1, d2 = halfpadloss_shelving_filter_num_den_coeff(G)
b, a = np.array([0, n2, 1]), np.array([0, d2, 1])
return b, a
def high_shelving_1st_coeff(omega=1, G=-10*np.log10(2)):
"""Half-pad-loss/mid-level high shelving filter 1st order.
Parameters
----------
omega : angular frequency in rad/s at half-pad-loss/mid-level
G : level in dB (G/2 at omega)
Returns
-------
b[0] s^2 + b[1] s^1 + b[2] s^0
b,a : coefficients for Laplace H(s) = ------------------------------
a[0] s^2 + a[1] s^1 + a[2] s^0
with s = j omega, note: b[0]=a[0]=0 here for 1st order filter
see halfpadloss_shelving_filter_num_den_coeff() for references
"""
b, a = normalized_high_shelving_1st_coeff(G=G)
scale = omega**np.arange(-2., 1.) # powers in the Laplace domain
return b * scale, a * scale
def normalized_low_shelving_2nd_coeff(G=-10*np.log10(2), Q=1/np.sqrt(2)):
"""See low_shelving_2nd_coeff() for omega=1."""
n1, n2, d1, d2 = halfpadloss_shelving_filter_num_den_coeff(G)
b, a = np.array([1, n1 / Q, n2]), np.array([1, d1 / Q, d2])
return b, a
def low_shelving_2nd_coeff(omega=1, G=-10*np.log10(2), Q=1/np.sqrt(2)):
"""Half-pad-loss/mid-level low shelving filter 2nd order.
Parameters
----------
omega : angular frequency in rad/s at half-pad-loss/mid-level
G : level in dB (G/2 at omega)
Q : pole/zero quality, Q>0.5
Returns
-------
b[0] s^2 + b[1] s^1 + b[2] s^0
b,a : coefficients for Laplace H(s) = ------------------------------
a[0] s^2 + a[1] s^1 + a[2] s^0
with s = j omega
see halfpadloss_shelving_filter_num_den_coeff() for references
"""
b, a = normalized_low_shelving_2nd_coeff(G=G, Q=Q)
scale = omega**np.arange(-2., 1.) # powers in the Laplace domain
return b * scale, a * scale
def normalized_high_shelving_2nd_coeff(G=-10*np.log10(2), Q=1/np.sqrt(2)):
"""See high_shelving_2nd_coeff() for omega=1."""
n1, n2, d1, d2 = halfpadloss_shelving_filter_num_den_coeff(G)
b, a = np.array([n2, n1 / Q, 1]), np.array([d2, d1 / Q, 1])
return b, a
def high_shelving_2nd_coeff(omega=1, G=-10*np.log10(2), Q=1/np.sqrt(2)):
"""Half-pad-loss/mid-level high shelving filter 2nd order.
Parameters
----------
omega : angular frequency in rad/s at half-pad-loss/mid-level
G : level in dB (G/2 at omega)
Q : pole/zero quality, Q>0.5
Returns
-------
b[0] s^2 + b[1] s^1 + b[2] s^0
b,a : coefficients for Laplace H(s) = ------------------------------
a[0] s^2 + a[1] s^1 + a[2] s^0
with s = j omega
see halfpadloss_shelving_filter_num_den_coeff() for references
"""
b, a = normalized_high_shelving_2nd_coeff(G=G, Q=Q)
scale = omega**np.arange(-2., 1.) # powers in the Laplace domain
return b * scale, a * scale
def db(x, *, power=False):
"""Convert *x* to decibel.
Parameters
----------
x : array_like
Input data. Values of 0 lead to negative infinity.
power : bool, optional
If ``power=False`` (the default), *x* is squared before
conversion.
"""
with np.errstate(divide='ignore'):
return (10 if power else 20) * np.log10(np.abs(x))
def db2lin(x):
return 10**(x / 20)
def shelving_slope_parameters(slope=None, BWd=None, Gd=None):
"""Compute the third parameter from the given two.
Parameters
----------
slope : float, optional
Desired shelving slope in decibel per octave.
BW : float, optional
Desired bandwidth of the slope in octave.
G : float, optional
Desired gain of the stop band in decibel.
"""
if slope == 0:
raise ValueError("`slope` should be nonzero.")
if slope and BWd is not None:
Gd = -BWd * slope
elif BWd and Gd is not None:
slope = -Gd / BWd
elif Gd and slope is not None:
if Gd * slope > 1:
raise ValueError("`Gd` and `slope` cannot have the same sign.")
else:
BWd = np.abs(Gd / slope)
else:
print('At lest two parameters need to be specified.')
return slope, BWd, Gd
def shelving_filter_parameters(biquad_per_octave, **kwargs):
"""Parameters for shelving filter design.
Parameters
----------
biquad_per_octave : float
Number of biquad filters per octave.
Returns
-------
num_biquad : int
Number of biquad filters.
Gb : float
Gain of each biquad filter in decibel.
G : float
Gain of overall (concatenated) filters in decibel. This might differ
from what is returned by `shelving_parameters`.
"""
slope, BWd, Gd = shelving_slope_parameters(**kwargs)
num_biquad = int(np.ceil(BWd * biquad_per_octave))
Gb = -slope / biquad_per_octave
G = Gb * num_biquad
return num_biquad, Gb, G
def check_shelving_filter_validity(biquad_per_octave, **kwargs):
"""Level, slope, bandwidth validity for shelving filter cascade.
Parameters
----------
biquad_per_octave : float
Number of biquad filters per octave.
see shelving_slope_parameters(), shelving_filter_parameters()
Returns
-------
flag = [Boolean, Boolean, Boolean]
if all True then intended parameter triplet holds, if not all True
deviations from desired response occur
"""
flag = [True, True, True]
slope, BWd, Gd = shelving_slope_parameters(**kwargs)
num_biquad, Gb, G = shelving_filter_parameters(biquad_per_octave, **kwargs)
# BWd < 1 octave generally fails
if BWd <= 1:
flag[0] = False
# BWd * biquad_per_octave needs to be integer
flag[1] = float(BWd * biquad_per_octave).is_integer()
# biquad_per_octave must be large enough
# for slope < 12.04 dB at least one biquad per ocatve is required
tmp = slope / (20*np.log10(4))
if tmp > 1.:
if biquad_per_octave < tmp:
flag[2] = False
else:
if biquad_per_octave < 1:
flag[2] = False
return flag
def low_shelving_1st_cascade(w0, Gb, num_biquad, biquad_per_octave):
"""Low shelving filter design using cascaded biquad filters.
- see low_shelving_2nd_cascade()
- under construction for code improvement
"""
sos = np.zeros((num_biquad, 6))
for m in range(num_biquad):
wm = w0 * 2**(-(m + 0.5) / biquad_per_octave)
b, a = low_shelving_1st_coeff(omega=wm, G=Gb)
sos[m] = tf2sos(b, a)
return sos
def high_shelving_1st_cascade(w0, Gb, num_biquad, biquad_per_octave):
"""High shelving filter design using cascaded biquad filters.
- see low_shelving_2nd_cascade()
- under construction for code improvement
"""
sos = np.zeros((num_biquad, 6))
for m in range(num_biquad):
wm = w0 * 2**(-(m + 0.5) / biquad_per_octave)
b, a = high_shelving_1st_coeff(omega=wm, G=Gb)
sos[m] = tf2sos(b, a)
return sos
def low_shelving_2nd_cascade(w0, Gb, num_biquad, biquad_per_octave,
Q=1/np.sqrt(2)):
"""Low shelving filter design using cascaded biquad filters.
Parameters
----------
w0 : float
Cut-off frequency in radian per second.
Gb : float
Gain of each biquad filter in decibel.
num_biquad : int
Number of biquad filters.
Q : float, optional
Quality factor of each biquad filter.
Returns
-------
sos : array_like
Array of second-order filter coefficients, must have shape
``(n_sections, 6)``. Each row corresponds to a second-order
section, with the first three columns providing the numerator
coefficients and the last three providing the denominator
coefficients.
"""
sos = np.zeros((num_biquad, 6))
for m in range(num_biquad):
wm = w0 * 2**(-(m + 0.5) / biquad_per_octave)
b, a = low_shelving_2nd_coeff(omega=wm, G=Gb, Q=Q)
sos[m] = tf2sos(b, a)
return sos
def high_shelving_2nd_cascade(w0, Gb, num_biquad, biquad_per_octave,
Q=1/np.sqrt(2)):
"""High shelving filter design using cascaded biquad filters.
- see low_shelving_2nd_cascade()
- under construction for code improvement
"""
sos = np.zeros((num_biquad, 6))
for m in range(num_biquad):
wm = w0 * 2**(-(m + 0.5) / biquad_per_octave)
b, a = high_shelving_2nd_coeff(omega=wm, G=Gb, Q=Q)
sos[m] = tf2sos(b, a)
return sos
def sosfreqs(sos, worN=200, plot=None):
"""Compute the frequency response of an analog filter in SOS format.
Parameters
----------
sos : array_like
Array of second-order filter coefficients, must have shape
``(n_sections, 6)``. Each row corresponds to a second-order
section, with the first three columns providing the numerator
coefficients and the last three providing the denominator
coefficients.
worN : {None, int, array_like}, optional
If None, then compute at 200 frequencies around the interesting parts
of the response curve (determined by pole-zero locations). If a single
integer, then compute at that many frequencies. Otherwise, compute the
response at the angular frequencies (e.g. rad/s) given in `worN`.
plot : callable, optional
A callable that takes two arguments. If given, the return parameters
`w` and `h` are passed to plot. Useful for plotting the frequency
response inside `freqs`.
Returns
-------
w : ndarray
The angular frequencies at which `h` was computed.
h : ndarray
The frequency response.
"""
h = 1.
for row in sos:
w, rowh = freqs(row[:3], row[3:], worN=worN, plot=plot)
h *= rowh
return w, h
def matchedz_zpk(s_zeros, s_poles, s_gain, fs):
"""Matched-z transform of poles and zeros.
Parameters
----------
s_zeros : array_like
Zeros in the Laplace domain.
s_poles : array_like
Poles in the Laplace domain.
s_gain : float
System gain in the Laplace domain.
fs : int
Sampling frequency in Hertz.
Returns
-------
z_zeros : numpy.ndarray
Zeros in the z-domain.
z_poles : numpy.ndarray
Poles in the z-domain.
z_gain : float
System gain in the z-domain.
See Also
--------
:func:`scipy.signal.bilinear_zpk`
"""
z_zeros = np.exp(s_zeros / fs)
z_poles = np.exp(s_poles / fs)
omega = 1j * np.pi * fs
s_gain *= np.prod((omega - s_zeros) / (omega - s_poles)
* (-1 - z_poles) / (-1 - z_zeros))
return z_zeros, z_poles, np.abs(s_gain)
def nearest_value(x0, x, f):
"""Plot helping."""
return f[np.abs(x - x0).argmin()]
def set_rcparams():
"""Plot helping."""
rcParams['axes.linewidth'] = 0.5
rcParams['axes.edgecolor'] = 'black'
rcParams['axes.facecolor'] = 'None'
rcParams['axes.labelcolor'] = 'black'
rcParams['xtick.color'] = 'black'
rcParams['ytick.color'] = 'black'
rcParams['font.family'] = 'serif'
rcParams['font.size'] = 13
rcParams['text.usetex'] = True
rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
rcParams['text.latex.preamble'] = r'\usepackage{gensymb}'
rcParams['legend.title_fontsize'] = 10
def set_outdir():
"""Plot helping."""
return '../graphics/'
def interaction_matrix_sge(G_proto, gain_factor, w_command, w_control,
bandwidth):
"""
Parameters
----------
G_proto: array_like
Prototype gain in decibel.
gain_factor: float
Gain factor.
w_command: array_like
Normalized command frequencies.
w_control: array_like
Normalized control frequencies.
bandwidth: array_like
Bandwidth.
"""
num_command = len(w_command)
num_control = len(w_control)
leak = np.zeros((num_command, num_control))
G_bandwidth = gain_factor * G_proto
g_proto = db2lin(G_proto)
g_bandwidth = db2lin(G_bandwidth)
z1 = np.exp(-1j * w_control)
z2 = z1**2
poly = np.zeros((num_command, 3))
poly[6] = 0.000321, 0.00474, 0.00544
poly[7] = 0.00108, 0.0221, 0.0169
poly[8] = 0.00184, 0.125, 0.0212
poly[9] = -0.00751, 0.730, -0.0672
for m, (Gp, gp, p, gb, wc, bw) in enumerate(
zip(G_proto, g_proto, poly, g_bandwidth, w_command, bandwidth)):
G_nyquist = np.sign(Gp) * np.polyval(p, np.abs(Gp))
gn = db2lin(G_nyquist)
gp2 = gp**2
gb2 = gb**2
gn2 = gn**2
F = np.abs(gp2 - gb2)
G00 = np.abs(gp2 - 1)
F00 = np.abs(gb2 - 1)
G01 = np.abs(gp2 - gn)
G11 = np.abs(gp2 - gn2)
F01 = np.abs(gb2 - gn)
F11 = np.abs(gb2 - gn2)
W2 = np.sqrt(G11 / G00) * np.tan(wc / 2)**2
DW = (1 + np.sqrt(F00 / F11) * W2) * np.tan(bw / 2)
C = F11 * DW**2 - 2 * W2 * (F01 - np.sqrt(F00 * F11))
D = 2 * W2 * (G01 - np.sqrt(G00 * G11))
A = np.sqrt((C + D) / F)
B = np.sqrt((gp2 * C + gb2 * D) / F)
num = np.array([gn+W2+B, -2*(gn-W2), (gn-B+W2)]) / (1+W2+A)
den = np.array([1, -2*(1-W2)/(1+W2+A), (1+W2-A)/(1+W2+A)])
H = (num[0] + num[1]*z1 + num[2]*z2)\
/ (den[0] + den[1]*z1 + den[2]*z2)
G = db(H) / Gp
leak[m] = np.abs(G)
return leak
def peq_seg(g_ref, g_nyquist, g, g_bandwidth, w_command, bandwidth):
"""
Parameters
----------
g_ref: float
Reference linear gain.
g_nyquist: float
Nyquist linear gain.
g_bandwidth: float
(Optimized) linear gain.
w_command: float
Normalized command frequencies.
bandwidth: float
Bandwidth.
"""
g2 = g**2
gb2 = g_bandwidth**2
gr2 = g_ref**2
gn2 = g_nyquist**2
grn = g_ref * g_nyquist
F = np.abs(g2 - gb2)
G00 = np.abs(g2 - gr2)
F00 = np.abs(gb2 - gr2)
G01 = np.abs(g2 - grn)
G11 = np.abs(g2 - gn2)
F01 = np.abs(gb2 - grn)
F11 = np.abs(gb2 - gn2)
W2 = np.sqrt(G11 / G00) * np.tan(w_command / 2)**2
DW = (1 + np.sqrt(F00 / F11) * W2) * np.tan(bandwidth / 2)
C = F11 * DW**2 - 2 * W2 * (F01 - np.sqrt(F00 * F11))
D = 2 * W2 * (G01 - np.sqrt(G00 * G11))
A = np.sqrt((C + D) / F)
B = np.sqrt((g**2 * C + g_bandwidth**2 * D) / F)
b = np.array([(g_nyquist + g_ref * W2 + B),
-2*(g_nyquist - g_ref * W2),
(g_nyquist - B + g_ref * W2)]) / (1 + W2 + A)
a = np.array([1, -2*(1 - W2) / (1 + W2 + A), (1 + W2 - A) / (1 + W2 + A)])
return b, a
def optimized_peq_seg(gain_command, gain_proto, gain_factor, w_command,
w_control, bandwidth):
"""
Parameters
----------
gain_command: array_like
Command gain in decibel.
gain_proto: array_like
Prototype gain in decibel.
gain_factor: float
Gain factor.
w_command: array_like
Normalized command frequencies.
w_control: array_like
Normalized control frequencies.
bandwidth: array_like
Bandwidths.
Returns
-------
b_opt: array_like (N, 3)
Moving average coefficients.
a_opt: array_like (N, 3)
Autoregressive (recursive) coefficients.
"""
num_command = len(gain_command)
# symmetric GEG design
gain_control = np.zeros(2 * num_command - 1)
gain_control[::2] = gain_command
gain_control[1::2] = 0.5 * (gain_command[:-1] + gain_command[1:])
# interaction matrix "B"
B = interaction_matrix_sge(gain_proto, gain_factor,
w_command, w_control, bandwidth)
gain2 = np.zeros((2 * num_command - 1, 1))
gain2[::2, 0] = gain_command
gain2[1::2, 0] = 0.5 * (gain_command[:-1] + gain_command[1:])
# band weights
weights = np.ones(2 * num_command - 1)
weights[1::2] *= 0.5
W = np.diag(weights)
gain_opt =\
np.matmul(np.linalg.inv(np.linalg.multi_dot([B, W, np.transpose(B)])),
np.linalg.multi_dot([B, W, gain2]))
gain_opt_bandwidth = gain_factor * gain_opt
gain_opt = np.squeeze(gain_opt)
gain_opt_bandwidth = np.squeeze(gain_opt_bandwidth)
g_opt = db2lin(gain_opt)
g_opt_bandwidth = db2lin(gain_opt_bandwidth)
poly = np.zeros((num_command, 3))
poly[6] = 0.000321, 0.00474, 0.00544
poly[7] = 0.00108, 0.0221, 0.0169
poly[8] = 0.00184, 0.125, 0.0212
poly[9] = -0.00751, 0.730, -0.0672
b_opt = np.zeros((3, num_command))
a_opt = np.zeros((3, num_command))
for m, (Go, go, gob, wc, bw, p) in enumerate(
zip(gain_opt, g_opt, g_opt_bandwidth, w_command, bandwidth, poly)):
gain_nyquist = np.sign(Go) * np.polyval(p, np.abs(Go))
b, a = peq_seg(1, db2lin(gain_nyquist), go, gob, wc, bw)
b_opt[:, m] = b
a_opt[:, m] = a
return b_opt, a_opt
def fracorder_lowshelving_eastty(w1, w2, G1, G2, rB=None):
"""
Parameters
----------
w1: float
Lower corner frequency.
w2: float
Upper corner frequency.
G1: float
Target level at lower corner frequency in dB.
G2: float
Target level at upper corner frequency in dB.
rB: float
Gain per octave.
Returns
-------
z: array_like
Complex zeros in the Laplace domain.
p: array_like
Complex poles in the Laplace domain.
k: float
Gain.
"""
Gd = G1 - G2
n_eff = effective_order(w1, w2, Gd, rB)
n_int, n_frac = np.divmod(n_eff, 1)
n_int = int(n_int)
z = np.array([])
p = np.array([])
# Second-order sections (complex conjugate pole/zero pairs)
if n_int > 0:
alpha = complex_zp_angles(n_int, n_frac)
alpha = np.concatenate((alpha, -alpha))
z = w1 * np.exp(1j * alpha)
p = w2 * np.exp(1j * alpha)
# First-order section (real pole/zero)
if n_eff % 2 != 0:
s_lower, s_upper = real_zp(n_int, n_frac, w1, w2)
if n_int % 2 == 0:
z_real = s_lower
p_real = s_upper
elif n_int % 2 == 1:
z_real = s_upper
p_real = s_lower
z = np.append(z, z_real)
p = np.append(p, p_real)
return z, p, 1
def effective_order(w1, w2, Gd, rB=None):
"""Effective order of shelving filter.
Parameters
----------
w1: float
Lower corner frequency.
w2: float
Upper corner frequency.
Gd: float
Target level difference in dB.
rB: float
Gain per octave.
"""
if rB is None:
rB = db(2) * np.sign(Gd) # Butterworth
return Gd / rB / np.log2(w2/w1)
def complex_zp_angles(n_int, n_frac):
"""Polar angles of the complex conjugate zeros/poles.
These correspond to the second-order section filters.
Parameters
----------
n_int: int
Interger order.
n_frac: float
Fractional order [0, 1).
"""
# linear interpolation of angles
num_zp_pair = int(n_int+1) // 2
return np.pi/2 * np.stack([
(1-n_frac) * (1 + (2*m+1)/n_int)
+ n_frac * (1 + (2*m+1)/(n_int+1))
for m in range(num_zp_pair)])
def real_zp(n_int, n_frac, w_lower, w_upper):
"""Real-valued zero and pole.
These correspond to the first-order section filters.
Parameters
----------
n_int: int
Integer order
n_frac: float
Fractional order [0, 1).
w_lower: float
Lower corner frequency.
w_upper: float
Upper corner frequency.
Returns
-------
s_lower: float
Smaller real-valued zero or pole.
s_upper: float
Larger real-valued zero or pole.
"""
w_mean = np.sqrt(w_lower * w_upper)
ratio = (w_upper / w_lower)
# logarithmic interpolation of zero/pole radius
if n_int % 2 == 0: # even
s_lower = -w_mean * ratio**(-n_frac/2)
s_upper = -w_mean * ratio**(n_frac/2)
elif n_int % 2 == 1: # odd
s_lower = -w_lower * ratio**(n_frac/2)
s_upper = -w_upper * ratio**(-n_frac/2)
return s_lower, s_upper
| python |
Mirpur (Bangladesh), July 29 (IANS) After a disappointing performance in the first Test match against Bangladesh, South African fast bowler Morne Morkel is confident that the Proteas can return to their best form in the second Test which starts at the Sher-e-Bangla stadium here on Thursday.
"It's time for us now to step it up a bit and show why we are the No. 1 team in the world," said Morne Morkel, according to bdnews24. com.
The Chittagong Test was called off after rain washed out the last two days. But the Proteas were under pressure in the first three days after they were restricted to just 248 in the first innings and then the hosts took a 78-run lead, scoring 326. Bangladesh still had a 17-run lead when the match was drawn.
"We just need to get 20 wickets, whether a stumping down the leg side or a yorker. We have had a look at their batting line-up again and we are going to go with different plans. Hopefully, that will work for us in the second Test," said Morkel, who has 217 wickets from 63 Tests.
He said they were happy with the weather change as South Africa trained under a scorching sun here. After drawing the curtains in the first Test, the rain had kept the players inside the hotel for the past four days forcing the players to practice indoors.
"We're very happy. We have got a bit of cabin fever sitting in the hotel. Really excited to go and get this Test underway and there are 11 hungry Proteas in the change room," said Morkel.
The lanky pacer thanked the Bangladeshi people for their hospitality but expressed frustration at grid locks on the city streets. He said: "Fantastic! Coming to Bangladesh is always special. People go out of their way to make us feel at home. It's just one thing, the traffic sometimes is not fun. "
This is the fourth time Morkel has travelled to Bangladesh. He came in 2008 for the first time to play in a bilateral series, the second was in 2011 during the World Cup and the third last year to play in the World Twenty20.
Fellow pacer Dale Steyn will begin the last match in the series with the chance of taking his record 400th Test wicket. Steyn, who will play his 80th Test on Thursday, had taken 3/78 in the first innings of the first Test to take his tally to 399.
Until now, Shaun Pollock is the only Proteas seamer to have achieved the feat of 400 Test wickets. Morkel and Steyn have spearheaded the Proteas pace attack in 59 Tests in the past nine years and the former is delighted for his fellow paceman.
"Dale's been unbelievable. He has led this attack for years now and he has been the No. 1 Test bowler for many years. I am happy for him," Morkel said.
"He is a guy who really works hard and is always looking to improve, always looking to shape the ball from different angles. He is like a good red wine, he is going to get better with age. It's going to be special when he gets his 400th, but there is plenty more in the tank for him," added the fast bowler. | english |
<reponame>mateuspalacio/solid
package isp;
/**
*
* @author mateu
*/
public interface PassearCao {
void passearOCao();
}
| java |
package io.opensaber.registry.util;
import io.opensaber.registry.dao.RegistryDaoImpl;
import io.opensaber.registry.model.DBConnectionInfo;
import io.opensaber.registry.model.DBConnectionInfoMgr;
import io.opensaber.registry.sink.DBProviderFactory;
import io.opensaber.registry.sink.DatabaseProvider;
import io.opensaber.registry.sink.OSGraph;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
@Component("entityParenter")
public class EntityParenter {
private static Logger logger = LoggerFactory.getLogger(EntityParenter.class);
@Autowired
private DBProviderFactory dbProviderFactory;
@Autowired
private RegistryDaoImpl tpGraphMain;
private DefinitionsManager definitionsManager;
private DBConnectionInfoMgr dbConnectionInfoMgr;
private Set<String> defintionNames;
private List<DBConnectionInfo> dbConnectionInfoList;
/**
* Holds information about a shard and a list of definitionParents
*/
private HashMap<String, ShardParentInfoList> shardParentMap = new HashMap<>();
@Autowired
public EntityParenter(DefinitionsManager definitionsManager, DBConnectionInfoMgr dbConnectionInfoMgr) {
this.definitionsManager = definitionsManager;
this.dbConnectionInfoMgr = dbConnectionInfoMgr;
defintionNames = this.definitionsManager.getAllKnownDefinitions();
dbConnectionInfoList = this.dbConnectionInfoMgr.getConnectionInfo();
}
/**
* Creates the parent vertex in all the shards for all default definitions
*
* @return
*/
public Optional<String> ensureKnownParenters() {
logger.info("Start - ensure parent node for defined schema");
Optional<String> result;
dbConnectionInfoList.forEach(dbConnectionInfo -> {
logger.info("Starting to parents for {} definitions in shard {}", defintionNames.size(), dbConnectionInfo.getShardId());
DatabaseProvider dbProvider = dbProviderFactory.getInstance(dbConnectionInfo);
try {
try (OSGraph osGraph = dbProvider.getOSGraph()) {
Graph graph = osGraph.getGraphStore();
List<ShardParentInfo> shardParentInfoList = new ArrayList<>();
try (Transaction tx = dbProvider.startTransaction(graph)) {
List<String> parentLabels = new ArrayList<>();
defintionNames.forEach(defintionName -> {
String parentLabel = ParentLabelGenerator.getLabel(defintionName);
parentLabels.add(parentLabel);
Vertex v = tpGraphMain.ensureParentVertex(graph, parentLabel);
ShardParentInfo shardParentInfo = new ShardParentInfo(defintionName, v);
shardParentInfo.setUuid(v.id().toString());
shardParentInfoList.add(shardParentInfo);
});
ShardParentInfoList valList = new ShardParentInfoList();
valList.setParentInfos(shardParentInfoList);
shardParentMap.put(dbConnectionInfo.getShardId(), valList);
dbProvider.commitTransaction(graph, tx);
}
logger.info("Ensured parents for {} definitions in shard {}", defintionNames.size(), dbConnectionInfo.getShardId());
}
} catch (Exception e) {
logger.error("Can't ensure parents for definitions " + e);
}
});
logger.info("End - ensure parent node for defined schema");
result = Optional.empty();
return result;
}
/**
* Gets a known parent id
*
* @return
*/
public String getKnownParentId(String definition, String shardId) {
String id = "";
ShardParentInfoList shardParentInfoList = shardParentMap.get(shardId);
for (ShardParentInfo shardParentInfo : shardParentInfoList.getParentInfos()) {
if (shardParentInfo.getName().compareToIgnoreCase(definition) == 0) {
id = shardParentInfo.getUuid();
break;
}
}
return id;
}
/**
* Gets a known parent vertex
*
* @return
*/
public Vertex getKnownParentVertex(String definition, String shardId) {
Vertex vertex = null;
ShardParentInfoList shardParentInfoList = shardParentMap.get(shardId);
for (ShardParentInfo shardParentInfo : shardParentInfoList.getParentInfos()) {
if (shardParentInfo.getName().compareToIgnoreCase(definition) == 0) {
vertex = shardParentInfo.getVertex();
break;
}
}
return vertex;
}
}
| java |
<gh_stars>0
<!DOCTYPE html>
<html class="writer-html5" lang="en" >
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>progressbar — utils4 - v1.1.0 Documentation</title>
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="../_static/copybutton.css" type="text/css" />
<link rel="stylesheet" href="../_static/css/s5defs-rules.css" type="text/css" />
<!--[if lt IE 9]>
<script src="../_static/js/html5shiv.min.js"></script>
<![endif]-->
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/clipboard.min.js"></script>
<script src="../_static/copybutton.js"></script>
<script src="../_static/js/theme.js"></script>
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
</head>
<body class="wy-body-for-nav">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search" >
<a href="../index.html" class="icon icon-home"> utils4
<img src="../_static/s3dev_tri_white_sm.png" class="logo" alt="Logo"/>
</a>
<div class="version">
1.1.0
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div><div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
<ul>
<li class="toctree-l1"><a class="reference internal" href="../library.html">Libary API Documentation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../changelog.html">Change Log</a></li>
<li class="toctree-l1"><a class="reference internal" href="../contact.html">Contact Us</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"><nav class="wy-nav-top" aria-label="Mobile navigation menu" >
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../index.html">utils4</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="Page navigation">
<ul class="wy-breadcrumbs">
<li><a href="../index.html" class="icon icon-home"></a> »</li>
<li><a href="index.html">Module code</a> »</li>
<li>progressbar</li>
<li class="wy-breadcrumbs-aside">
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<h1>Source code for progressbar</h1><div class="highlight"><pre>
<span></span><span class="c1"># -*- coding: utf-8 -*-</span>
<span class="sd">"""</span>
<span class="sd">:Purpose: This is a small class module which provides access to a</span>
<span class="sd"> simple console progress bar.</span>
<span class="sd">:Platform: Linux/Windows | Python 3.6+</span>
<span class="sd">:Developer: <NAME></span>
<span class="sd">:Email: <EMAIL></span>
<span class="sd">:Comments: n/a</span>
<span class="sd">:Example: For a simple usage example, refer to the :class:`~ProgressBar`</span>
<span class="sd"> class docstring.</span>
<span class="sd">"""</span>
<span class="kn">import</span> <span class="nn">sys</span>
<div class="viewcode-block" id="ProgressBar"><a class="viewcode-back" href="../progressbar.html#progressbar.ProgressBar">[docs]</a><span class="k">class</span> <span class="nc">ProgressBar</span><span class="p">:</span>
<span class="sd">"""Implement a console progress bar into a processing loop.</span>
<span class="sd"> Args:</span>
<span class="sd"> total_values (int, optional): Total number of iterations.</span>
<span class="sd"> Defaults to 25.</span>
<span class="sd"> bar_len (int, optional): Complete length of the progress bar, in chars.</span>
<span class="sd"> Defaults to 25</span>
<span class="sd"> symbol (str, optional): The symbol which is used to track progress.</span>
<span class="sd"> Defaults to ``'.'``.</span>
<span class="sd"> color (str, optional): Colour of the progress bar; where only the first</span>
<span class="sd"> letter of the colour is required.</span>
<span class="sd"> Options are: red, green, yellow, blue, magenta, cyan, white.</span>
<span class="sd"> Defaults to 'w' (white).</span>
<span class="sd"> :Design:</span>
<span class="sd"> This is a simple console progress bar which should be called</span>
<span class="sd"> **inside** a processing loop.</span>
<span class="sd"> On instantiation, you can pass in the bar colour, length and</span>
<span class="sd"> symbol parameters if you want to configure the appearance a</span>
<span class="sd"> little bit.</span>
<span class="sd"> :Colour Options:</span>
<span class="sd"> red, green, yellow, blue, magenta, cyan, white</span>
<span class="sd"> :Example:</span>
<span class="sd"> You might implement the progress bar in a loop like this::</span>
<span class="sd"> >>> import time</span>
<span class="sd"> >>> from utils4.progressbar import ProgressBar</span>
<span class="sd"> >>> pb = ProgressBar(total_values=25,</span>
<span class="sd"> bar_len=25,</span>
<span class="sd"> symbol='#',</span>
<span class="sd"> color='red')</span>
<span class="sd"> >>> for i range(26):</span>
<span class="sd"> >>> # < some processing ></span>
<span class="sd"> >>> pb.update_progress(current=i)</span>
<span class="sd"> >>> # Optional pause to see updates.</span>
<span class="sd"> >>> time.sleep(.1)</span>
<span class="sd"> Processing 25 of 25 [ ......................... ] 100% Complete</span>
<span class="sd"> """</span>
<div class="viewcode-block" id="ProgressBar.__init__"><a class="viewcode-back" href="../progressbar.html#progressbar.ProgressBar.__init__">[docs]</a> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">total_values</span><span class="p">:</span> <span class="nb">int</span><span class="o">=</span><span class="mi">25</span><span class="p">,</span> <span class="n">bar_len</span><span class="p">:</span> <span class="nb">int</span><span class="o">=</span><span class="mi">25</span><span class="p">,</span> <span class="n">symbol</span><span class="p">:</span> <span class="nb">str</span><span class="o">=</span><span class="s1">'.'</span><span class="p">,</span> <span class="n">color</span><span class="p">:</span> <span class="nb">str</span><span class="o">=</span><span class="s1">'w'</span><span class="p">):</span>
<span class="sd">"""Progress bar class initialiser."""</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_total</span> <span class="o">=</span> <span class="n">total_values</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_bar_len</span> <span class="o">=</span> <span class="n">bar_len</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_symbol</span> <span class="o">=</span> <span class="n">symbol</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_color</span> <span class="o">=</span> <span class="n">color</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_len</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_total</span><span class="p">))</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_rst</span> <span class="o">=</span> <span class="s1">'</span><span class="se">\x1b</span><span class="s1">[0m'</span>
<span class="bp">self</span><span class="o">.</span><span class="n">_clr</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_getcolor</span><span class="p">()</span></div>
<div class="viewcode-block" id="ProgressBar.update_progress"><a class="viewcode-back" href="../progressbar.html#progressbar.ProgressBar.update_progress">[docs]</a> <span class="k">def</span> <span class="nf">update_progress</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">current</span><span class="p">:</span> <span class="nb">int</span><span class="p">):</span> <span class="c1"># pragma: nocover</span>
<span class="sd">"""Incrementally update the progress bar.</span>
<span class="sd"> Args:</span>
<span class="sd"> current (int): Index value for the current iteration.</span>
<span class="sd"> This value is compared against the initialised ``total_values``</span>
<span class="sd"> parameter to determine the current position in the overall</span>
<span class="sd"> progress.</span>
<span class="sd"> :Example:</span>
<span class="sd"> Refer to the :class:`~ProgressBar` class docstring.</span>
<span class="sd"> """</span>
<span class="c1"># Calculate percent complete.</span>
<span class="n">percent</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">current</span><span class="p">)</span> <span class="o">/</span> <span class="bp">self</span><span class="o">.</span><span class="n">_total</span>
<span class="c1"># Number of ticks.</span>
<span class="n">ticks</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_symbol</span> <span class="o">*</span> <span class="nb">int</span><span class="p">(</span><span class="nb">round</span><span class="p">(</span><span class="n">percent</span> <span class="o">*</span> <span class="bp">self</span><span class="o">.</span><span class="n">_bar_len</span><span class="p">))</span>
<span class="c1"># Number of space placeholders.</span>
<span class="n">spaces</span> <span class="o">=</span> <span class="s1">' '</span> <span class="o">*</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_bar_len</span> <span class="o">-</span> <span class="nb">len</span><span class="p">(</span><span class="n">ticks</span><span class="p">))</span>
<span class="n">msg</span> <span class="o">=</span> <span class="p">(</span><span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="n">_clr</span><span class="si">}</span><span class="s1">'</span>
<span class="sa">f</span><span class="s1">'</span><span class="se">\r</span><span class="s1">Processing </span><span class="si">{</span><span class="nb">str</span><span class="p">(</span><span class="n">current</span><span class="p">)</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_len</span><span class="p">)</span><span class="si">}</span><span class="s1"> of </span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="n">_total</span><span class="si">}</span><span class="s1"> [ </span><span class="si">{</span><span class="n">ticks</span><span class="o">+</span><span class="n">spaces</span><span class="si">}</span><span class="s1"> ] '</span>
<span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">percent</span><span class="o">*</span><span class="mi">100</span><span class="si">:</span><span class="s1">.0f</span><span class="si">}</span><span class="s1">% Complete</span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="n">_rst</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>
<span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
<span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span></div>
<span class="k">def</span> <span class="nf">_getcolor</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-></span> <span class="nb">str</span><span class="p">:</span>
<span class="sd">"""Create ANSI colour escape sequence to user's colour.</span>
<span class="sd"> Returns:</span>
<span class="sd"> str: ANSI escape sequence string for the user's colour.</span>
<span class="sd"> """</span>
<span class="n">clrs</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'r'</span><span class="p">:</span> <span class="mi">31</span><span class="p">,</span> <span class="s1">'g'</span><span class="p">:</span> <span class="mi">32</span><span class="p">,</span> <span class="s1">'y'</span><span class="p">:</span> <span class="mi">33</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">:</span> <span class="mi">34</span><span class="p">,</span> <span class="s1">'m'</span><span class="p">:</span> <span class="mi">35</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">:</span> <span class="mi">36</span><span class="p">,</span> <span class="s1">'w'</span><span class="p">:</span> <span class="mi">37</span><span class="p">}</span>
<span class="n">seq</span> <span class="o">=</span> <span class="sa">f</span><span class="s1">'</span><span class="se">\033</span><span class="s1">[</span><span class="si">{</span><span class="n">clrs</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_color</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span><span class="si">}</span><span class="s1">;40m'</span>
<span class="k">return</span> <span class="n">seq</span></div>
</pre></div>
</div>
</div>
<footer>
<hr/>
<div role="contentinfo">
<p>© Copyright 2016-2022 | S3DEV | version 1.1.0.</p>
</div>
</footer>
</div>
</div>
</section>
</div>
<script>
jQuery(function () {
SphinxRtdTheme.Navigation.enable(true);
});
</script>
</body>
</html> | html |
<gh_stars>1-10
{
"name": "jquery-layout",
"filename": "jquery.layout.min.js",
"version": "1.4.3",
"description": "jQuery plugin for layout management (jQuery version of extJS border-layout).",
"homepage": "http://layout.jquery-dev.net/",
"keywords": [
"jquery",
"layout",
"ui"
],
"repositories": [
{
"type": "git",
"url": "git://github.com/allpro/layout.git"
}
],
"autoupdate": {
"source": "git",
"target": "git://github.com/allpro/layout.git",
"basePath": "source/stable",
"files": [
"*.min.js",
"*.css"
]
}
}
| json |
<filename>src/action/scripts/record/data/crop_rosbag.py
#!/usr/bin/env python
# Copyright (c) 2016, <NAME>, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
# OF SUCH DAMAGE.
import os
import logging
import numpy as np
import rosbag
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from optparse import OptionParser
from bagutils import getAllTopicsMetadata, getDropsTimeDistribution, findBestDataWindow, plotDropsTimeDistribution
logger = logging.getLogger(__name__)
def getCropTimes(topicTimestamps, dropThreshold=1.0, windowSize=600, ignoreBorder=15, windowConv=10):
drops, startRefTime, recordDuration = getDropsTimeDistribution(topicTimestamps, dropThreshold, windowWidth=windowConv, ignoreBorder=ignoreBorder)
centerPos, centerPosAbs = findBestDataWindow(drops, startRefTime, recordDuration, T=windowSize)
startTime = centerPosAbs - windowSize/2
endTime = centerPosAbs + windowSize/2
return startTime, endTime, drops, centerPos
def cropRosbag(inbagFile, outbagFile, startTime, endTime, useRosbagTime=False):
with rosbag.Bag(outbagFile, 'w') as outbag:
for topic, msg, timestamp in rosbag.Bag(inbagFile).read_messages():
if not useRosbagTime:
# Get timestamp from header
timestamp = msg.header.stamp
t = float(timestamp.to_sec())
if t >= startTime and t <= endTime:
outbag.write(topic, msg, timestamp)
def main(args=None):
parser = OptionParser()
parser.add_option("-i", "--input", dest="input", default=False,
help="Location of Rosbag to analyse")
parser.add_option("-o", "--output", dest="output", default="",
help="Output rosbag file")
parser.add_option("-r", "--ignore-topics", dest="topicRemove", default="",
help="Comma separated list of topics to ignore")
parser.add_option("-c", "--use-rosbag-time",
action="store_true", dest="useRosbagTime", default=False,
help="Use rosbag time instead of capture time")
parser.add_option("-m", "--simulate",
action="store_true", dest="simulate", default=False,
help="Simulate the cropping, without actually writing the output rosbag")
parser.add_option("-t", "--drop-threshold", dest="dropThreshold", type='float', default=1.0,
help='Specify the threshold to use for detecting dropped messages')
parser.add_option("-e", "--crop-window", dest="cropWindow", type='int', default=600, help="Specify in seconds the windows of best quality data to extract")
parser.add_option("-p", "--ignore-border", dest="ignoreBorder", type='int', default=15, help="Specify in seconds the time to ignore at the start and end of rosbag")
parser.add_option("-w", "--window-size-conv", dest="windowSizeConv", type='int', default=10, help="Specify in seconds the window to use for convolution")
parser.add_option("-s", "--save-drop-distribution", dest="saveDropDistribution", default="", help="Specify to save the drop time distribution figure to file")
(options, args) = parser.parse_args()
if not options.input:
parser.error("Please specify input rosbag file with -i ")
inputRosbagPath = os.path.abspath(options.input)
logger.info('Using input rosbag file: %s' % (inputRosbagPath))
if not options.output:
parser.error("Please specify output rosbag file with -o ")
outputRosbagFilePath = os.path.abspath(options.output)
logger.info('Using output rosbag file: %s' % (outputRosbagFilePath))
ignoreList = []
if options.topicRemove:
ignoreList = options.topicRemove.split(',')
logger.info('Ignored topics: %s' % (options.topicRemove))
# Get timestamps and sequence ids from the rosbag
topicTimestamps, topicSequenceIds = getAllTopicsMetadata(inputRosbagPath, ignoreList, options.useRosbagTime)
if options.cropWindow <= 0:
raise Exception('Specified crop window size must be greater than zero')
startTime, endTime, drops, centerPos = getCropTimes(topicTimestamps,
options.dropThreshold, options.cropWindow,
options.ignoreBorder, options.windowSizeConv)
logger.info('Using calculated crop times: start = %f, end = %f' % (startTime, endTime))
if options.saveDropDistribution:
outputFigureFilePath = os.path.abspath(options.saveDropDistribution)
fig = plotDropsTimeDistribution(drops,
centerPos=centerPos,
cropWindow=options.cropWindow,
windowSizeConv=options.windowSizeConv)
logger.info('Saving drop time distribution figure to file: %s' % (outputFigureFilePath))
plt.savefig(outputFigureFilePath, dpi=100)
plt.close(fig)
if not options.simulate:
cropRosbag(inputRosbagPath, outputRosbagFilePath, startTime, endTime)
else:
logger.info('Skipping cropping because simulation mode is activated')
logger.info('All done.')
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
main()
| python |
/**
* Angular ORM for HTTP REST APIs
* @version angular-rest-orm - v0.4.5 - 2014-11-11
* @link https://github.com/panta/angular-rest-orm
* @author <NAME> <<EMAIL>>
*
* Copyright (c) 2014 <NAME> <<EMAIL>>
* Licensed under the MIT License, http://opensource.org/licenses/MIT
*/
var __hasProp = {}.hasOwnProperty,
__slice = [].slice,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
angular.module("restOrm", []).factory("Resource", ['$http', '$q', '$rootScope', function($http, $q, $rootScope) {
var Resource, endsWith, isEmpty, isKeyLike, startsWith, urljoin, _urljoin;
isEmpty = function(obj) {
var key;
if (obj == null) {
return true;
}
if (obj.length > 0) {
return false;
}
if (obj.length === 0) {
return true;
}
for (key in obj) {
if (!__hasProp.call(obj, key)) continue;
return false;
}
return true;
};
startsWith = function(s, sub) {
return s.slice(0, sub.length) === sub;
};
endsWith = function(s, sub) {
return sub === '' || s.slice(-sub.length) === sub;
};
isKeyLike = function(value) {
if (value == null) {
return false;
}
if (angular.isUndefined(value) || (value === null)) {
return false;
}
if (angular.isObject(value) || angular.isArray(value)) {
return false;
}
return true;
};
_urljoin = function() {
var c_url, component, components, i, last_comp, normalize, r, skip, url_result, _i, _j, _len, _ref;
components = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
normalize = function(str) {
return str.replace(/[\/]+/g, "/").replace(/\/\?/g, "?").replace(/\/\#/g, "#").replace(/\:\//g, "://");
};
url_result = [];
if (components && (components.length > 0)) {
skip = 0;
while (skip < components.length) {
if (components[skip]) {
break;
}
++skip;
}
if (skip) {
components = components.slice(skip);
}
}
last_comp = null;
for (_i = 0, _len = components.length; _i < _len; _i++) {
component = components[_i];
if (!((component != null) && component)) {
continue;
}
last_comp = component;
c_url = ("" + component).split("/");
for (i = _j = 0, _ref = c_url.length; 0 <= _ref ? _j < _ref : _j > _ref; i = 0 <= _ref ? ++_j : --_j) {
if (c_url[i] === "..") {
url_result.pop();
} else if ((c_url[i] === ".") || (c_url[i] === "")) {
continue;
} else {
url_result.push(c_url[i]);
}
}
}
r = normalize(url_result.join("/"));
if (components && (components.length >= 1)) {
component = "" + components[0];
if (startsWith(component, "//")) {
r = "//" + r;
} else if (startsWith(component, "/")) {
r = "/" + r;
}
last_comp = "" + last_comp;
if (endsWith(last_comp, "/") && (!endsWith(r, "/"))) {
r = r + "/";
}
}
return r;
};
urljoin = function() {
return encodeURI(_urljoin.apply(null, arguments));
};
/**
* @ngdoc service
* @name restOrm.Resource
*
* @description
* # Resource
* Is the base class for RESTful resource models.
*
* Derive from `Resource` providing proper values for class properties
* as described below to define models for your resources.
*
* A very minimal example in JavaScript:
*
* ```javascript
* var Book = Resource.Subclass({}, {
* urlEndpoint: '/api/books/',
* idField: '_id'
* });
* ```
*
* of in CoffeeScript:
*
* ```coffeescript
* class Book extends Resource
* @.urlEndpoint: '/api/books/'
* @.idField: '_id'
* ```
* (the `.` has been added to circumvent an `ngdoc` bug regarding parsing of `@` in blockquotes...)
*
* @returns {object} Resource class
*/
Resource = (function() {
/**
* @ngdoc property {String}
* @name .#urlPrefix
* @propertyOf restOrm.Resource
*
* @description
* # urlPrefix
* **class property** - prefix that will be prepended to all URLs
* for this resource.
* Defaults to the empty string (in this case, nothing will be prepended).
*
* The final base URL will have the form
*
* `urlPrefix` / `urlEndpoint`
*
* (Note that slashes will be added only where necessary)
*
* This property is intended to be specified on subclasses of `Resource`.
*/
Resource.urlPrefix = '';
/**
* @ngdoc property {String}
* @name .#urlEndpoint
* @propertyOf restOrm.Resource
*
* @description
* # urlEndpoint
* **class property** - the base URL for the resource.
*
* The final base URL will have the form
*
* `urlPrefix` / `urlEndpoint`
*
* (Note that slashes will be added only where necessary)
*
* This property is intended to be specified on subclasses of `Resource`.
*/
Resource.urlEndpoint = '';
/**
* @ngdoc property {String}
* @name .#idField
* @propertyOf restOrm.Resource
*
* @description
* # idField
* **class property** - (optional) the name of the field containing the ID of the resource in
* remote endpoint responses.
*
* Defaults to `id`.
*
* This property is intended to be specified on subclasses of `Resource`.
*/
Resource.idField = 'id';
/**
* @ngdoc property {Object}
* @name .#fields
* @propertyOf restOrm.Resource
*
* @description
* # fields
* **class property** - (optional) object specifying names and kinds of resource fields.
*
* It's possible to specify an entry for each field, with this form:
*
* ```javascript
* {
* ...
* NAME: {
* default: DEFAULT_VALUE,
* remote: REMOTE_FIELD_NAME,
* type: FIELD_TYPE,
* model: RELATED_MODEL
* },
* ...
* }
* ```
*
* where:
*
* - *NAME* is the field name as used on the resource (model instance). This can be
* different from the remote endpoint field name.
* - *DEFAULT_VALUE* is the default value for the field, used if the remote doesn't
* provide a value or when creating a resource without specifying all fields
* - *REMOTE_FIELD_NAME* is the (optional) field name on the remote endpoint. If not
* specified, it's assumed to be the same as *NAME*
* - *FIELD_TYPE* at this time is used only to specify relations. If specified can
* be `Resource.Reference` or `Resource.ManyToMany`
* - *RELATED_MODEL* used only for relations, specifies the related model (must be a
* `Resource` subclass)
*
* All of the entry object fields are optional.
*
*
* If `fields` is not specified, fields will be fetched and copied between
* responses and resource models as-is.
*
* This property is intended to be specified on subclasses of `Resource`.
*/
Resource.fields = {};
/**
* @ngdoc property {Object}
* @name .#defaults
* @propertyOf restOrm.Resource
*
* @description
* # defaults
* **class property** - (optional) object specifying default values for resource fields.
* It is meant to be an easy shortcut for those cases where the `fields` complexity is
* not needed.
*
* This property is intended to be specified on subclasses of `Resource`.
*/
Resource.defaults = {};
Resource.headers = {};
Resource.prepareRequest = null;
Resource.transformResponse = null;
Resource.postResponse = null;
Resource.Reference = 'reference';
Resource.ManyToMany = 'many2many';
Resource.include = function(obj) {
var key, value, _ref;
if (!obj) {
throw new Error('include(obj) requires obj');
}
for (key in obj) {
value = obj[key];
if (key !== 'included' && key !== 'extended') {
this.prototype[key] = value;
}
}
if ((_ref = obj.included) != null) {
_ref.apply(this);
}
return this;
};
Resource.extend = function(obj) {
var key, value, _ref;
if (!obj) {
throw new Error('extend(obj) requires obj');
}
for (key in obj) {
value = obj[key];
if (key !== 'included' && key !== 'extended') {
this[key] = value;
}
}
if ((_ref = obj.extended) != null) {
_ref.apply(this);
}
return this;
};
/**
* @ngdoc method
* @name Resource#Subclass
* @methodOf restOrm.Resource
*
* @description
* # Resource.Subclass()
* **class method** that returns a new subclass derived from `Resource`
* extended with the specified instance and class properties.
*
* This method is intended to be used from plain *JavaScript*.
*
* *CoffeeScript* users should rely on the native `class ... extends ...` syntax
* to create `Resource` subclasses.
*
* @param {object} instances Properties to add to instances of the newly created class
*
* @param {object} statics Class properties of the newly created class
*
* @returns {function} the new class (a constructor function)
*/
Resource.Subclass = function(instances, statics) {
var Result;
Result = (function(_super) {
__extends(Result, _super);
function Result() {
return Result.__super__.constructor.apply(this, arguments);
}
return Result;
})(this);
if (instances) {
Result.include(instances);
}
if (statics) {
Result.extend(statics);
}
Result.prototype.$super = function(method) {
return this.constructor.__super__[method];
};
return Result;
};
/**
* @ngdoc method
* @name Resource
* @methodOf restOrm.Resource
*
* @description
* # Resource()
* **constructor** for `Resource`
*
* Usually one would never call this constructor direcly, but always through subclasses.
*
* @param {object|null=} data Object that will be used to initialize the resource (model instance)
*
* @param {object=} opts Options
*/
function Resource(data, opts) {
if (data == null) {
data = null;
}
if (opts == null) {
opts = {};
}
this.$meta = {
persisted: false,
async: {
direct: {
deferred: null,
resolved: true
},
m2o: {
deferred: null,
resolved: true
},
m2m: {
deferred: null,
resolved: true
}
}
};
angular.extend(this.$meta, opts);
this.$error = null;
this.$id = null;
this._fromObject(data || {});
this.$promise = null;
this.$promiseDirect = null;
this._setupPromises();
this._fetchRelations();
if (typeof this.$initialize === "function") {
this.$initialize.apply(this, arguments);
}
}
/**
* @ngdoc method
* @name Resource#Create
* @methodOf restOrm.Resource
*
* @description
* # Resource.Create()
* **class method ** - creates a model resource (instance) and persists it on the remote side.
*
* Usually this method will be called on a `Resource` subclass.
*
* @param {data|null=} data Object used to initialize the new model instance properties
*
* @param {object=} opts Options passed to `$save()`
*
* @returns {object} newly created resource (model instance)
*/
Resource.Create = function(data, opts) {
var item;
if (data == null) {
data = null;
}
if (opts == null) {
opts = {};
}
data = data || this.defaults;
item = new this(data, {
persisted: false
});
item.$save(opts);
return item;
};
/**
* @ngdoc method
* @name Resource#Get
* @methodOf restOrm.Resource
*
* @description
* # Resource.Get
* **class method ** - fetches and returns a resource with the given id.
*
* A model instance for the resource is constructed and returned, and it
* will be populated with the contents fetched from the remote endpoint
* for the resource with the specified `id`.
*
* The HTTP fetch will be performed asynchronously, so the model instance,
* even if returned immediately, will be populated in an
* incremental fashion.
*
* To allow the user to be notified on the completion of the fetch process,
* the model instance contains as special properties a couple of promises that
* will be fulfilled when the fetch completes.
*
* The first one is named `$promise`. This will be fulfilled when
* the resource will have been fetched **along with all its relations**
* (and the relations of the relations... down to the deepest nesting levels).
*
* The other one is named `$promiseDirect`. This will be fulfilled when the
* resource will have been fetched, but ignoring relations.
*
* The method will cause an http request of the form:
*
* `GET` *RESOURCE_URL* / *id*
*
* Usually this method will be called on a `Resource` subclass.
*
* @param {Number|String} id Remote endpoint id of the resource to fetch
*
* @param {object=} opts Options object containing optional `params` and `data`
* fields passed to the respective counterparts of the `$http` call
*
* @returns {object} fetched resource (model instance)
*/
Resource.Get = function(id, opts) {
var item, req, url;
if (opts == null) {
opts = {};
}
item = new this();
url = urljoin(this._GetURLBase(), id);
item._setupPromises();
req = this._PrepareRequest({
id: id,
opts: opts,
what: 'Get',
method: 'GET',
url: url,
headers: this._BuildHeaders('Get', 'GET', null),
params: opts.params || {},
data: opts.data || {},
item: item
});
$http({
method: req.method,
url: req.url,
headers: req.headers,
params: req.params,
data: req.data
}).then(((function(_this) {
return function(response) {
var res;
res = _this._TransformResponse(req, response);
item._fromRemote(res.data);
return _this._PostResponse(res);
};
})(this)), function(response) {
item.$error = response;
item.resolvePromise(item.$meta.async.direct.deferred, false);
item.resolvePromise(item.$meta.async.m2o.deferred, false);
return item.resolvePromise(item.$meta.async.m2m.deferred, false);
});
return item;
};
/**
* @ngdoc method
* @name Resource#All
* @methodOf restOrm.Resource
*
* @description
* # Resource.All
* **class method ** - fetches and returns all the remote resources.
*
* This method returns a *collection*, an Array augmented with some
* additional properties, as detailed below.
*
* The HTTP fetch will be performed asynchronously, so the collection,
* even if returned immediately, will be filled with results in an
* incremental fashion.
*
* To allow the user to be notified on the completion of the fetch process,
* the collection contains as special properties a couple of promises that
* will be fulfilled when the fetch completes.
*
* The first one is named `$promise`. This will be fulfilled when all
* collection items will have been fetched **along with all their relations**
* (and the relations of the relations... down to the deepest nesting levels).
*
* The other one is named `$promiseDirect`. This will be fulfilled when all
* collection items will have been fetched, but ignoring relations.
*
* The method will cause an http request of the form:
*
* `GET` *RESOURCE_URL* /
*
* Usually this method will be called on a `Resource` subclass.
*
* @param {object=} opts Options object containing optional `params` and `data`
* fields passed to the respective counterparts of the `$http` call
*
* @returns {object} fetched collection (augmented array of model instances)
*/
Resource.All = function(opts) {
var collection, req, url;
if (opts == null) {
opts = {};
}
collection = this._MakeCollection();
url = urljoin(this._GetURLBase());
req = this._PrepareRequest({
opts: opts,
what: 'All',
method: 'GET',
url: url,
headers: this._BuildHeaders('All', 'GET', null),
params: opts.params || {},
data: opts.data || {},
collection: collection
});
$http({
method: req.method,
url: req.url,
headers: req.headers,
params: req.params,
data: req.data
}).then(((function(_this) {
return function(response) {
var res, values, _i, _len, _ref;
res = _this._TransformResponse(req, response);
_ref = res.data;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
values = _ref[_i];
collection.push(_this._MakeInstanceFromRemote(values));
}
_this._PostResponse(res);
return collection.$finalize();
};
})(this)), (function(_this) {
return function(response) {
var res;
res = _this._TransformResponse(req, response);
_this._PostResponse(res);
return collection.$finalize(false, response);
};
})(this));
return collection;
};
Resource.Search = function(field, value, opts) {
var collection, req, url;
if (opts == null) {
opts = {};
}
collection = this._MakeCollection();
url = urljoin(this._GetURLBase(), "search", field, value);
req = this._PrepareRequest({
field: field,
value: value,
opts: opts,
what: 'Search',
method: 'GET',
url: url,
headers: this._BuildHeaders('Search', 'GET', null),
params: opts.params || {},
data: opts.data || {},
collection: collection
});
$http({
method: req.method,
url: req.url,
headers: req.headers,
params: req.params,
data: req.data
}).then(((function(_this) {
return function(response) {
var res, values, _i, _len, _ref;
res = _this._TransformResponse(req, response);
_ref = res.data;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
values = _ref[_i];
collection.push(_this._MakeInstanceFromRemote(values));
}
_this._PostResponse(res);
return collection.$finalize();
};
})(this)), (function(_this) {
return function(response) {
var res;
res = _this._TransformResponse(req, response);
_this._PostResponse(res);
return collection.$finalize(false, response);
};
})(this));
return collection;
};
/**
* @ngdoc method
* @name Resource#$save
* @methodOf restOrm.Resource
*
* @description
* Saves the resource represented by this model instance.
*
* If the model instance represents a resource obtained from the
* remote endpoint (thus having an ID), than the method will update
* the remote resource (using an HTTP `PUT`), otherwise it will create
* the resource on the remote endpoint (using an HTTP `POST`).
*
* The operation will update the model representation with the data
* obtained from the remote endpoint.
*
* The HTTP operation will be performed asynchronously, so the `$promise`
* and `$promiseDirect` promises will be re-generated to inform of the
* completion.
*
* For a new resource, the method will cause an http request of the form:
*
* `POST` *RESOURCE_URL* /
*
* otherwise for an existing resource:
*
* `PUT` *RESOURCE_URL* / *id*
*
* Usually this method will be called on a `Resource` subclass.
*
* @param {object=} opts Options object containing optional `params` and `data`
* fields passed to the respective counterparts of the `$http` call
*
* @returns {object} the model instance itself
*/
Resource.prototype.$save = function(opts) {
var data, method, req, url;
if (opts == null) {
opts = {};
}
data = this._toRemoteObject();
if (this.$meta.persisted && (this.$id != null)) {
method = 'PUT';
url = urljoin(this._getURLBase(), this.$id);
} else {
method = 'POST';
if (this.constructor.idField in data) {
delete data[this.constructor.idField];
}
url = urljoin(this._getURLBase());
}
this._setupPromises();
req = this._prepareRequest({
opts: opts,
what: '$save',
method: method,
url: url,
headers: this._buildHeaders('$save', method),
params: opts.params || {},
data: data,
cache: false,
item: this
});
$http({
method: req.method,
url: req.url,
data: req.data,
cache: req.cache,
headers: req.headers,
params: req.params
}).then(((function(_this) {
return function(response) {
var res;
res = _this._transformResponse(req, response);
_this._fromRemote(res.data);
return _this._postResponse(res);
};
})(this)), (function(_this) {
return function(response) {
_this.$error = response;
_this.resolvePromise(_this.$meta.async.direct.deferred, false);
_this.resolvePromise(_this.$meta.async.m2o.deferred, false);
return _this.resolvePromise(_this.$meta.async.m2m.deferred, false);
};
})(this));
return this;
};
Resource._MakeCollection = function() {
var collection;
collection = [];
collection.$useApplyAsync = false;
collection.$meta = {
model: this,
async: {
direct: {
deferred: $q.defer(),
resolved: false
},
complete: {
deferred: $q.defer(),
resolved: false
}
}
};
collection.$error = false;
collection.$promise = collection.$meta.async.complete.deferred.promise;
collection.$promiseDirect = collection.$meta.async.direct.deferred.promise;
collection.$getItemsPromises = function() {
var instance, _i, _len, _results;
_results = [];
for (_i = 0, _len = collection.length; _i < _len; _i++) {
instance = collection[_i];
_results.push(instance.$promise);
}
return _results;
};
collection.$getItemsPromiseDirects = function() {
var instance, _i, _len, _results;
_results = [];
for (_i = 0, _len = collection.length; _i < _len; _i++) {
instance = collection[_i];
_results.push(instance.$promiseDirect);
}
return _results;
};
collection.$_getPromiseForItems = function() {
return $q.all(collection.$getItemsPromises());
};
collection.$_getPromiseDirectForItems = function() {
return $q.all(collection.$getItemsPromiseDirects());
};
collection._resolvePromise = function(deferred, success) {
if (success == null) {
success = true;
}
if (success) {
return deferred.resolve(collection);
}
return deferred.reject(collection);
};
collection.resolvePromise = function(deferred, success) {
if (success == null) {
success = true;
}
if (collection.$useApplyAsync) {
$rootScope.$applyAsync(function() {
return collection._resolvePromise(deferred, success);
});
} else {
collection._resolvePromise(deferred, success);
if (!$rootScope.$$phase) {
$rootScope.$apply();
}
}
return collection;
};
collection.$finalize = function(success, response) {
var items_success;
if (success == null) {
success = true;
}
if (response == null) {
response = null;
}
items_success = success;
collection.$_getPromiseForItems().then((function() {
collection.resolvePromise(collection.$meta.async.complete.deferred, success);
return collection.$meta.async.complete.resolved = true;
}), function() {
items_success = false;
collection.resolvePromise(collection.$meta.async.complete.deferred, items_success);
collection.$meta.async.complete.resolved = true;
return collection.$error = true;
});
collection.resolvePromise(collection.$meta.async.direct.deferred, success);
collection.$meta.async.direct.resolved = true;
if ((!success) && response) {
collection.$error = response;
} else {
collection.$error = !(success && items_success);
}
return collection;
};
return collection;
};
Resource._MakeInstanceFromRemote = function(data) {
var instance;
instance = new this();
instance._setupPromises();
instance._fromRemote(data);
return instance;
};
Resource._GetURLBase = function() {
return _urljoin(this.urlPrefix, this.urlEndpoint);
};
Resource._BuildHeaders = function(what, method, instance) {
var dst_headers, processHeaderSource;
if (what == null) {
what = null;
}
if (method == null) {
method = null;
}
if (instance == null) {
instance = null;
}
if (this.headers == null) {
return {};
}
if (angular.isFunction(this.headers)) {
return this.headers.call(this, {
klass: this,
what: what,
method: method,
instance: instance
});
} else if (angular.isObject(this.headers)) {
processHeaderSource = (function(_this) {
return function(dst, src) {
var dst_value, name, value;
for (name in src) {
value = src[name];
if (angular.isFunction(value)) {
dst_value = value.call(_this, {
klass: _this,
what: what,
method: method,
instance: instance
});
} else {
dst_value = value;
}
if (dst_value !== null) {
dst[name] = dst_value;
}
}
return dst;
};
})(this);
dst_headers = {};
if (('common' in this.headers) || ((what != null) && (what in this.headers)) || ((method != null) && (method in this.headers))) {
if ('common' in this.headers) {
processHeaderSource(dst_headers, this.headers.common);
}
if ((what != null) && (what in this.headers)) {
processHeaderSource(dst_headers, this.headers[what]);
}
if ((method != null) && (method in this.headers)) {
processHeaderSource(dst_headers, this.headers[method]);
}
} else {
processHeaderSource(dst_headers, this.headers);
}
return dst_headers;
}
return {};
};
Resource._PrepareRequest = function(req) {
req.klass = this;
if ((this.prepareRequest != null) && angular.isFunction(this.prepareRequest)) {
return this.prepareRequest.call(this, req);
}
return req;
};
Resource.prototype._prepareRequest = function(req) {
req.instance = this;
return this.constructor._PrepareRequest(req);
};
Resource._TransformResponse = function(req, http_response, instance) {
var res;
if (instance == null) {
instance = null;
}
res = angular.extend({}, req, {
request: req,
response: http_response,
data: http_response.data
});
res.klass = this;
res.instance = instance;
res.data = res.response.data;
res.status = res.response.status;
res.headers = res.response.headers;
res.config = res.response.config;
res.statusText = res.response.statusText;
if ((this.transformResponse != null) && angular.isFunction(this.transformResponse)) {
return this.transformResponse.call(this, res);
}
return res;
};
Resource.prototype._transformResponse = function(req, http_response) {
return this.constructor._TransformResponse(req, http_response, this);
};
Resource._PostResponse = function(res) {
res.klass = this;
if ((this.postResponse != null) && angular.isFunction(this.postResponse)) {
return this.postResponse.call(this, res);
}
return res;
};
Resource.prototype._postResponse = function(res) {
res.instance = this;
return this.constructor._PostResponse(res);
};
Resource.prototype._buildHeaders = function(what, method) {
if (what == null) {
what = null;
}
if (method == null) {
method = null;
}
return this.constructor._BuildHeaders(what, method, this);
};
Resource.prototype._setupPromises = function() {
var changed;
changed = false;
if (this.$meta.async.direct.resolved || (this.$meta.async.direct.deferred == null)) {
this.$meta.async.direct.deferred = $q.defer();
this.$meta.async.direct.resolved = false;
changed = true;
this.$promiseDirect = this.$meta.async.direct.deferred.promise.then((function(_this) {
return function() {
_this.$meta.async.direct.resolved = true;
return _this;
};
})(this));
}
if (this.$meta.async.m2o.resolved || (this.$meta.async.m2o.deferred == null)) {
this.$meta.async.m2o.deferred = $q.defer();
this.$meta.async.m2o.resolved = false;
changed = true;
this.$meta.async.m2o.deferred.promise.then((function(_this) {
return function() {
_this.$meta.async.m2o.resolved = true;
return _this;
};
})(this));
}
if (this.$meta.async.m2m.resolved || (this.$meta.async.m2m.deferred == null)) {
this.$meta.async.m2m.deferred = $q.defer();
this.$meta.async.m2m.resolved = false;
changed = true;
this.$meta.async.m2m.deferred.promise.then((function(_this) {
return function() {
_this.$meta.async.m2m.resolved = true;
return _this;
};
})(this));
}
if (changed) {
this.$promise = $q.all([this.$meta.async.direct.deferred.promise, this.$meta.async.m2o.deferred.promise, this.$meta.async.m2m.deferred.promise]).then((function(_this) {
return function() {
_this.$meta.async.direct.resolved = true;
_this.$meta.async.m2o.resolved = true;
_this.$meta.async.m2m.resolved = true;
return _this;
};
})(this));
}
return this;
};
Resource.prototype._getURLBase = function() {
return _urljoin(this.constructor.urlPrefix, this.constructor.urlEndpoint);
};
Resource.prototype._fetchRelations = function() {
if (this.$id != null) {
this._fetchReferences();
this._fetchM2M();
}
return this;
};
Resource.prototype._fetchReferences = function() {
var def, fetchReference, name, promises;
fetchReference = function(instance, reference, promises) {
var fieldName, record, ref_id;
fieldName = reference.name;
if ((fieldName in instance) && (instance[fieldName] != null) && isKeyLike(instance[fieldName])) {
ref_id = instance[fieldName];
record = reference.model.Get(ref_id);
instance[fieldName] = record;
return promises.push(record.$promise);
}
};
promises = [];
for (name in this.constructor.fields) {
def = this._getField(name);
if (def.type === this.constructor.Reference) {
fetchReference(this, def, promises);
}
}
$q.all(promises).then(((function(_this) {
return function() {
return _this.resolvePromise(_this.$meta.async.m2o.deferred);
};
})(this)), (function(_this) {
return function() {
return _this.resolvePromise(_this.$meta.async.m2o.deferred, false);
};
})(this));
return this;
};
Resource.prototype._fetchM2M = function() {
var collections, def, fetchM2M, name, promises, refs_collection, _i, _len;
fetchM2M = function(instance, m2m, promises, collections) {
var fieldName, record, ref_id, refs_collection, refs_promises, _i, _len, _ref;
fieldName = m2m.name;
if ((fieldName in instance) && (instance[fieldName] != null) && angular.isArray(instance[fieldName])) {
refs_promises = [];
refs_collection = m2m.model._MakeCollection();
_ref = instance[fieldName];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
ref_id = _ref[_i];
record = m2m.model.Get(ref_id);
refs_collection.push(record);
refs_promises.push(record.$promise);
}
instance[fieldName] = refs_collection;
promises.push(refs_collection.$promise);
return collections.push(refs_collection);
} else {
return instance[fieldName] = [];
}
};
promises = [];
collections = [];
for (name in this.constructor.fields) {
def = this._getField(name);
if (def.type === this.constructor.ManyToMany) {
fetchM2M(this, def, promises, collections);
}
}
$q.all(promises).then(((function(_this) {
return function() {
return _this.resolvePromise(_this.$meta.async.m2m.deferred);
};
})(this)), (function(_this) {
return function() {
return _this.resolvePromise(_this.$meta.async.m2m.deferred, false);
};
})(this));
for (_i = 0, _len = collections.length; _i < _len; _i++) {
refs_collection = collections[_i];
refs_collection.$finalize();
}
return this;
};
Resource.prototype._fromRemote = function(data) {
this._fromRemoteObject(data);
this.$meta.persisted = true;
this.resolvePromise(this.$meta.async.direct.deferred);
this._fetchRelations();
return this;
};
Resource.prototype._resolvePromise = function(deferred, success) {
if (success == null) {
success = true;
}
if (success) {
return deferred.resolve(this);
}
return deferred.reject(this);
};
Resource.prototype.resolvePromise = function(deferred, success) {
if (success == null) {
success = true;
}
if (this.$useApplyAsync) {
$rootScope.$applyAsync((function(_this) {
return function() {
return _this._resolvePromise(deferred, success);
};
})(this));
} else {
this._resolvePromise(deferred, success);
if (!$rootScope.$$phase) {
$rootScope.$apply();
}
}
return this;
};
Resource.prototype._getFields = function() {
var fieldsSpec, name, value, _ref;
fieldsSpec = {};
_ref = this.constructor.defaults;
for (name in _ref) {
value = _ref[name];
fieldsSpec[name] = {
"default": value
};
}
if (!(this.constructor.idField in fieldsSpec)) {
fieldsSpec[this.constructor.idField] = {
"default": null
};
}
angular.extend(fieldsSpec, this.constructor.fields);
return fieldsSpec;
};
Resource.prototype._getField = function(name) {
var def;
def = {
name: name,
remote: name,
type: null,
model: null
};
if (name in this.constructor.fields) {
return angular.extend(def, this.constructor.fields[name] || {});
}
return def;
};
Resource.prototype._toObject = function() {
var def, name, obj, result_values, value, values, _i, _len;
obj = {};
for (name in this) {
if (!__hasProp.call(this, name)) continue;
value = this[name];
if (name === '$id' || name === '$meta' || name === 'constructor' || name === '__proto__') {
continue;
}
def = this._getField(name);
obj[name] = value;
if (!value) {
continue;
}
if (def.type === this.constructor.Reference) {
if (angular.isObject(value) || (value instanceof Resource)) {
obj[name] = value.$id != null ? value.$id : null;
}
} else if (def.type === this.constructor.ManyToMany) {
values = angular.isArray(value) ? value : [value];
result_values = [];
for (_i = 0, _len = values.length; _i < _len; _i++) {
value = values[_i];
if (angular.isObject(value) || (value instanceof Resource)) {
result_values.push(value.$id != null ? value.$id : null);
} else {
result_values.push(value);
}
}
obj[name] = result_values;
}
}
return obj;
};
Resource.prototype._fromObject = function(obj) {
var data, def, name, value;
data = angular.extend({}, this.constructor.defaults, obj || {});
for (name in data) {
value = data[name];
if (name === '$id' || name === '$meta' || name === 'constructor' || name === '__proto__') {
continue;
}
this[name] = value;
}
for (name in this.constructor.fields) {
def = this._getField(name);
if (name === '$id' || name === '$meta' || name === 'constructor' || name === '__proto__') {
continue;
}
if (!(name in data) && ('default' in def)) {
this[name] = def["default"];
}
}
return this;
};
Resource.prototype._toRemoteObject = function() {
var def, name, obj, result_values, value, values, _i, _len;
obj = {};
for (name in this) {
if (!__hasProp.call(this, name)) continue;
value = this[name];
if (name === '$id' || name === '$meta' || name === 'constructor' || name === '__proto__') {
continue;
}
def = this._getField(name);
obj[def.remote] = value;
if (!value) {
continue;
}
if (def.type === this.constructor.Reference) {
if (angular.isObject(value) || (value instanceof Resource)) {
obj[def.remote] = value.$id != null ? value.$id : null;
}
} else if (def.type === this.constructor.ManyToMany) {
values = angular.isArray(value) ? value : [value];
result_values = [];
for (_i = 0, _len = values.length; _i < _len; _i++) {
value = values[_i];
if (angular.isObject(value) || (value instanceof Resource)) {
result_values.push(value.$id != null ? value.$id : null);
} else {
result_values.push(value);
}
}
obj[def.remote] = result_values;
}
}
return obj;
};
Resource.prototype._fromRemoteObject = function(obj) {
var data, def, fieldsSpec, name, value, _ref;
if (isEmpty(this.constructor.fields)) {
data = angular.extend({}, this.constructor.defaults, obj || {});
for (name in data) {
value = data[name];
if (name === '$id' || name === '$meta' || name === 'constructor' || name === '__proto__') {
continue;
}
this[name] = value;
}
} else {
data = angular.extend({}, obj || {});
fieldsSpec = this._getFields();
for (name in fieldsSpec) {
def = this._getField(name);
if (name === '$id' || name === '$meta' || name === 'constructor' || name === '__proto__') {
continue;
}
if (def.remote in data) {
this[name] = data[def.remote];
} else if ('default' in def) {
this[name] = def["default"];
}
}
_ref = this.constructor.defaults;
for (name in _ref) {
value = _ref[name];
if (!(name in this)) {
this[name] = value;
}
}
}
if (this.constructor.idField in data) {
this.$id = obj[this.constructor.idField];
}
return this;
};
return Resource;
})();
return Resource;
}]);
| javascript |
(b) Amongst the steps taken to curb terrorist activities in the Capital are formation of an Anti-Terrorist Cellmneach Police Distt., deployment of armed pickets at vulnerable/strategic points, intensive mobile patrolling; distribution of educative literature amongst the people to make them more vigilant, deployment of spotters, displaying of photos of known terrorists at public places, stationing of PCR vehicles at stratagicplaces, coordination meetings with the adjoining States, etc
Direct Coal Linkage with Private Sector Steel Plants
7221 SHRIDHARMANNA MONDAYYA SADUL Will the Minister of COAL be pleased to state
(a) whether some of the leading Steel Plants in private sector have demanded coal linkage directs from the mines in order to avoid delay in supply of coal and also to improve their economy,
(c) the action taken by the Union Govern ment thereon?
THE MINISTER OF STATE OF THE MINISTRY COAL (SHRI AJIT PANJA) (a) to (c) Specific coal linkages for prospective entrepreneurs/units for setting up of pig iron, Steel, coke manufacturing projects have been considered by the Linkage Committee set up by the Ministry of Steel which is the nodal Ministry in respect of 14 such proposals raw low volatile medium cooking coal linkages direct from the collienes have been agreed to. For one more proposal non-cooking coal linkage has been agreed to
Supply of Medicines of Bihar
7222. SHAIKHELAN RAM JANGDE:
Written Answers 436
SHRI RAM TAHAL COUDHARY
Will the Minister of HEALTH AND FAMILY WELFARE be pleased to refer to the reply given on December 1, 1992 to starred Question No 106 and state
(a) whether 60 items out of the 229 items which were not supplied have since been supplied,
(b) if so, the quantity of each item supplied,
(c) the quantum of supply sought by the Government of Bihar, and
(d) the reasons for partial supply of these items?
THE DEPUTY MINISTER IN THE MINISTRY OF HEALTH AND FAMILY WELFARE (SHRI PABAN SINGH GHATOWAR) (a)to(d) Information is being collected and will be laid on the Table of the House
Grievance Redressal System
7223 SHRI MANORANJAN BHAKTA Will the Minister of HOME AFFAIRSbepleased to state
(a) whether the Government propose to introduce contact point system in Delhiinvolving the local populace in providing information and the Grievance Redressal system for solving the problems of the people of the spot and
(b) if so, the details thereof?
THE MINISTER OF STATE IN THE MINISTRY OF HOME AFFAIRS (SHRI P.M.SAYEED):(a) There is no such proposal under consideration at present.
(b) Does not arise in view of (a) above
VAISAKHA 9, 1915' (SAKA)
Ferrous protection Policy
7224DA P.R GANGWAR Will the Minister of MINES be pleased to state
(a) the salient features of the trade policy of the Government regarding non-ferrous metals,
(b) whether the Government propose to revise the ferrous protection policy, and
(c) if so, the details thereof?
THE MINISTER OF STATE OF THE MINISTRY OF MINES (SHRI BALRAM SINGH YADAV)(a) to (c) The trade of ferrous and nonterrous metals is governed by the Export Import policy announced by the Government from time to time
illegal Mining in Bhatti mines
7225 SHRIRAM KAPSE' Will the Minister of MINES be pleased to state
(a) whether the Government are aware about illegal mining done in Buetti mines on Delhi side of the Haryana Border; and
(b) if so, the steps taken to check it
THE MINISTER OF STATE OF THE MINISTRY OF MINES (SHRI BALRAM SINGH YADAV). (a) and (b) Delhi Administration has informed that reports about illegal mining in Bhatti mines area are received by it from time to time and that the police patrolling has been intensified and static picket post has also been set up. Forest Department has deployed field officials to curb Legal mining Field staff of the collectorate of Mines & Quarries, Delhi Administration also conduct periodic inspections.
Cases of Viscera Examination in Delhi
7226. SHRI GURUDAS KAMAT: Will the Minister of HOME AFFAIRS be pleased to
Written Answers 438
(a) whether the Forensic Laboratory has recently asked the Delhi Police to cut down the number of cases sent to it for viscera Examination,
(c) the alternative steps being contemnplated by the Government in this regard?
THE MINISTER OF STATE IN THE MINISTRY OF HOME AFFAIRS (SHRI P M SAYEED) (a) and (b) Central Bureau of Investigation, New Delhi has written to the Commissioner of Police, Delhi that there was heavy cendency in Chemistry, Biology and Documents Divisions of Central Forensic Science Laboratory C B.I requested him to examine whether in all these cases examination by a Forensic Expert was necessary
(c) The Delhi police has reported that a meeting was held with Director, C F S.L, Chandigarh and it was decided to send limited number of exhibits to C.F S.L.. Chandigarh for examination till Delhi police sets up its own Forensic Science Laboratory
Supply of Coal to Electricity Boards
7227,SHRIPRAKASHV PATIL Will the Minister of COAL be pleased to state“
(a) the total amount for which coal was supplied to the different Electricity Boards during 1992-93;
(b) the total amount due on the various State Electricity Boards as on March 1, 1993;
(c) whether interest is being charged on the dues; and
(d) the steps being taken to recover the
THE MINISTEROFSTATE OF THE MIN ISTRY OF COAL (SHRI AJIT PANJA):(a) Ac
| english |
#include <ncine/common_macros.h>
#include <nctl/ProxyAllocator.h>
namespace nctl {
///////////////////////////////////////////////////////////
// CONSTRUCTORS and DESTRUCTOR
///////////////////////////////////////////////////////////
ProxyAllocator::ProxyAllocator(const char *name, IAllocator &allocator)
: IAllocator(name, allocateImpl, reallocateImpl, deallocateImpl, 0, nullptr),
allocator_(allocator)
{
}
ProxyAllocator::~ProxyAllocator()
{
FATAL_ASSERT(usedMemory_ == 0 && numAllocations_ == 0);
}
///////////////////////////////////////////////////////////
// PRIVATE FUNCTIONS
///////////////////////////////////////////////////////////
void *ProxyAllocator::allocateImpl(IAllocator *allocator, size_t bytes, uint8_t alignment)
{
FATAL_ASSERT(allocator);
ProxyAllocator *allocatorImpl = static_cast<ProxyAllocator *>(allocator);
IAllocator &subject = allocatorImpl->allocator_;
const size_t memoryUsedBefore = subject.usedMemory();
void *ptr = subject.allocateFunc_(&subject, bytes, alignment);
if (ptr)
{
allocatorImpl->usedMemory_ += subject.usedMemory() - memoryUsedBefore;
allocatorImpl->numAllocations_++;
}
return ptr;
}
void *ProxyAllocator::reallocateImpl(IAllocator *allocator, void *ptr, size_t bytes, uint8_t alignment, size_t &oldSize)
{
FATAL_ASSERT(allocator);
ProxyAllocator *allocatorImpl = static_cast<ProxyAllocator *>(allocator);
IAllocator &subject = allocatorImpl->allocator_;
const size_t memoryUsedBefore = subject.usedMemory();
void *newPtr = subject.reallocateFunc_(&subject, ptr, bytes, alignment, oldSize);
if (newPtr)
allocatorImpl->usedMemory_ += subject.usedMemory() - memoryUsedBefore;
return newPtr;
}
void ProxyAllocator::deallocateImpl(IAllocator *allocator, void *ptr)
{
if (ptr == nullptr)
return;
FATAL_ASSERT(allocator);
ProxyAllocator *allocatorImpl = static_cast<ProxyAllocator *>(allocator);
IAllocator &subject = allocatorImpl->allocator_;
const size_t memoryUsedBefore = subject.usedMemory();
subject.deallocateFunc_(&subject, ptr);
allocatorImpl->usedMemory_ -= memoryUsedBefore - subject.usedMemory();
FATAL_ASSERT(allocatorImpl->numAllocations_ > 0);
allocatorImpl->numAllocations_--;
}
}
| cpp |
26 (A)“Do not eat any meat with blood still in it. Do not practice any kind of magic.
18 (A)“Put to death any woman who practices magic.
Good News Translation® (Today’s English Version, Second Edition)
© 1992 American Bible Society. All rights reserved.
For more information about GNT, visit www.bibles.com and www.gnt.bible.
| english |
<gh_stars>0
import makeStyles from '@material-ui/core/styles/makeStyles';
import { boxShadows } from '../../services/theme/boxShadows';
export const useAvatarStyles = makeStyles({
avatar: {
width: "100%",
height: "100%",
borderRadius: "50%",
},
avatarContainer: {
width: 160,
height: 160,
backgroundColor: "#fff",
borderRadius: "50%",
padding: 5,
boxShadow: boxShadows.boxShadowCookies,
},
avatarButton: {
"& span": {
margin: 0,
},
borderRadius: "50%",
},
}); | typescript |
<gh_stars>0
{
"sidebar": {
"title": "MiroBot",
"shortTitle": "MB",
"dashboard": "Dashboard",
"navigation": "Navigation",
"teleop": "Teleop",
"debug": "Debug",
"config": "Configuration"
}
}
| json |
Los Angeles Chargers running back Austin Ekeler is not happy in LA. The seventh-year running back is requesting permission to speak with other teams about a potential trade, according to ESPN NFL reporter Adam Schefter.
Ekeler is in the final year of his contract and is due only $6.25 million this season. He signed a four-year $24.5 million contract extension with the Chargers on March 16, 2020.
The request comes after the two sides didn't have good talks on a contract extension.
Ekeler is coming off one of his most productive seasons in the NFL. He set career-highs in rushing yards (915) rushing touchdowns (13) and receptions (107), while amassing over 1,600 total yards and scoring 18 total touchdowns.
At age 27, Ekeler knows he will likely get one more big contract before he starts to wear as a running back, resulting in less value for the future.
As of right now, Ekeler has the 14th-highest cap hit among RBs in 2023 ($7.75 million) which is a bargain for the Chargers.
Where can Austin Ekeler land in 2023?
While Ekeler has requested a trade at the time, no deal or move is quite imminent. There is still time for the two sides to reach a long-term deal, but there is a chance the Chargers can move the star running back.
Here are three potential landing spots for Ekeler in 2023:
The Dolphins haven't had a running back rush for over 1,000 yards in a single season since 2016. As a team, they rushed for 1,686 yards last season and 12 rushing touchdowns.
Ekeler scored 13 rushing touchdowns of his own last season. The offense would also be more balanced as they're a pass-heavy team. Ekeler will also help out in their passing game as he's caught over 389 passes, including a career-high 107 last season.
Last season, the Dolphins were aggressive in acquiring Tyreek Hill from the Chiefs and should be again if they want one of the most versatile running backs in the NFL to help out their offense.
The Eagles are one of the most aggressive teams in the NFL as far as making off-season moves.
Running back Miles Sanders is a free agent and is expected to leave in free agency after having the best season of his career.
Ekeler would be an amazing replacement for Sanders. Joining a group that features Jalen Hurts, AJ Brown, and DeVonta Smith would make this offense even better than with Sanders, as Ekeler is a better pass-catching running back.
Since Ekeler only accounts for $6.25 million this season, the Eagles can afford to make the move and extend him to a long-term deal as they're expected to lose many key free agents this off-season.
The Chicago Bears are going to be one of the busiest teams this off-season.
The Bears have the most cap space in the league with $75 million. Chicago has already started to improve their offense this off-season as they acquired Panthers wideout DJ Moore in a blockbuster trade where they traded the first-overall pick.
Last season, quarterback Justin Fields led the team with 1,143 rushing yards and eight touchdowns.
They have two quality running backs in David Montgomery and Khalil Hebert, who both rushed for over 700 yards last season.
Adding Ekeler would give the Bears a true number one back with a deeper committee, relieving Fields from using his legs as much as he does.
Rumors are just rumors, but for now, Ekeler wants out of LA. He could be moved soon or it could take awhile for a trade to process.
| english |
<filename>bee-crypto/src/ternary/bigint/i384/constants.rs
// Copyright 2020 <NAME>
// SPDX-License-Identifier: Apache-2.0
use crate::ternary::bigint::{
binary_representation::{U32Repr, U8Repr},
endianness::{BigEndian, LittleEndian},
I384,
};
/// I384 big-endian `u8` represented 0.
pub const BE_U8_0: I384<BigEndian, U8Repr> = I384::<BigEndian, U8Repr>::from_array([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
/// I384 big-endian `u8` represented 1.
pub const BE_U8_1: I384<BigEndian, U8Repr> = I384::<BigEndian, U8Repr>::from_array([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
]);
/// I384 big-endian `u8` represented -1.
pub const BE_U8_NEG_1: I384<BigEndian, U8Repr> = I384::<BigEndian, U8Repr>::from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
]);
/// I384 big-endian `u8` represented 2.
pub const BE_U8_2: I384<BigEndian, U8Repr> = I384::<BigEndian, U8Repr>::from_array([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
]);
/// I384 big-endian `u8` represented -2.
pub const BE_U8_NEG_2: I384<BigEndian, U8Repr> = I384::<BigEndian, U8Repr>::from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
]);
/// I384 big-endian `u8` represented maximum value.
pub const BE_U8_MAX: I384<BigEndian, U8Repr> = I384::<BigEndian, U8Repr>::from_array([
0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
]);
/// I384 big-endian `u8` represented minimum value.
pub const BE_U8_MIN: I384<BigEndian, U8Repr> = I384::<BigEndian, U8Repr>::from_array([
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
/// I384 big-endian `u32` represented 0.
pub const BE_U32_0: I384<BigEndian, U32Repr> = I384::<BigEndian, U32Repr>::from_array([
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
]);
/// I384 big-endian `u32` represented 1.
pub const BE_U32_1: I384<BigEndian, U32Repr> = I384::<BigEndian, U32Repr>::from_array([
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0001,
]);
/// I384 big-endian `u32` represented -1.
pub const BE_U32_NEG_1: I384<BigEndian, U32Repr> = I384::<BigEndian, U32Repr>::from_array([
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
]);
/// I384 big-endian `u32` represented 2.
pub const BE_U32_2: I384<BigEndian, U32Repr> = I384::<BigEndian, U32Repr>::from_array([
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0002,
]);
/// I384 big-endian `u32` represented -2.
pub const BE_U32_NEG_2: I384<BigEndian, U32Repr> = I384::<BigEndian, U32Repr>::from_array([
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_fffe,
]);
/// I384 big-endian `u32` represented maximum value.
pub const BE_U32_MAX: I384<BigEndian, U32Repr> = I384::<BigEndian, U32Repr>::from_array([
0x7fff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
]);
/// I384 big-endian `u32` represented mminimum value.
pub const BE_U32_MIN: I384<BigEndian, U32Repr> = I384::<BigEndian, U32Repr>::from_array([
0x8000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
]);
/// I384 little-endian `u8` represented 0.
pub const LE_U8_0: I384<LittleEndian, U8Repr> = I384::<LittleEndian, U8Repr>::from_array(BE_U8_0.inner);
/// I384 little-endian `u8` represented 1.
pub const LE_U8_1: I384<LittleEndian, U8Repr> = I384::<LittleEndian, U8Repr>::from_array([
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
/// I384 little-endian `u8` represented -1.
pub const LE_U8_NEG_1: I384<LittleEndian, U8Repr> = I384::<LittleEndian, U8Repr>::from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
]);
/// I384 little-endian `u8` represented 2.
pub const LE_U8_2: I384<LittleEndian, U8Repr> = I384::<LittleEndian, U8Repr>::from_array([
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
/// I384 little-endian `u8` represented 2.
pub const LE_U8_NEG_2: I384<LittleEndian, U8Repr> = I384::<LittleEndian, U8Repr>::from_array([
0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
]);
/// I384 little-endian `u8` represented maximum value.
pub const LE_U8_MAX: I384<LittleEndian, U8Repr> = I384::<LittleEndian, U8Repr>::from_array([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
]);
/// I384 little-endian `u8` represented minimum value.
pub const LE_U8_MIN: I384<LittleEndian, U8Repr> = I384::<LittleEndian, U8Repr>::from_array([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
]);
/// I384 little-endian `u32` represented 0.
pub const LE_U32_0: I384<LittleEndian, U32Repr> = I384::<LittleEndian, U32Repr>::from_array(BE_U32_0.inner);
/// I384 little-endian `u32` represented 1.
pub const LE_U32_1: I384<LittleEndian, U32Repr> = I384::<LittleEndian, U32Repr>::from_array([
0x0000_0001,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
]);
/// I384 little-endian `u32` represented -1.
pub const LE_U32_NEG_1: I384<LittleEndian, U32Repr> = I384::<LittleEndian, U32Repr>::from_array([
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
]);
/// I384 little-endian `u32` represented 2.
pub const LE_U32_2: I384<LittleEndian, U32Repr> = I384::<LittleEndian, U32Repr>::from_array([
0x0000_0002,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
]);
/// I384 little-endian `u32` represented -2.
pub const LE_U32_NEG_2: I384<LittleEndian, U32Repr> = I384::<LittleEndian, U32Repr>::from_array([
0xffff_fffe,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
]);
/// I384 little-endian `u32` represented maximum value.
pub const LE_U32_MAX: I384<LittleEndian, U32Repr> = I384::<LittleEndian, U32Repr>::from_array([
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0xffff_ffff,
0x7fff_ffff,
]);
/// I384 little-endian `u32` represented minimum value.
pub const LE_U32_MIN: I384<LittleEndian, U32Repr> = I384::<LittleEndian, U32Repr>::from_array([
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x0000_0000,
0x8000_0000,
]);
| rust |
<filename>ext/templates-openscienceASAP/openscienceASAP.org/project-overview_de.html
<strong>KURZBESCHREIBUNG</strong>
<h2>Idee</h2>
Was soll mit dem Projekt erreicht werden. Warum?
<h2>Umsetzung</h2>
Wie soll die Idee umgesetzt werden?
<h2>Openness</h2>
SIEHE UNTEN
<h2>Mitmachen</h2>
Wie kann man mitmachen?
<strong>Kontakt</strong>
NAME, EMAIL, TWITTER, URL
<h2>Details</h2>
Start Datum: DATE
Status: [Konzeptionierung, Umsetzung, Finalisiert]
<h3>TeilnehmerInnen</h3>
AUFLISTEN DER TEILNEHMERINNEN ODER AUF PROJEKTSEITE VERWEISEN
<ul>
<li>NAME (<a href="BLOGURL">Blog</a>, <a href="LINKTWITTER" title="ACCOUNTNAME Twitter">@ACCOUNT</a>)</li>
</ul>
<h2>Links</h2>
<ul>
<li><a href="https://github.com/REPOSITORY" title="PROJEKTNAME GitHub Repository">GitHub Repository</a></li>
<li><a href="http://openscience.alpine-geckos.at/category/CATEGORY" title="Blog PROJEKTNAME">Blog</a></li>
<li><a href="http://openscience.alpine-geckos.at/category/CATEGORY/feed" title="RSS Feed PROJEKTNAME">RSS Feed</a></li>
<li><a title="PROJEKTNAME Open Science Wiki Page" href="http://wiki.alpine-geckos.at/wiki/WIKIPAGE">Wiki Page</a></li> [WIKI PAGE NOT NECESSARILY]
<li><a href="http://okfnpad.org/openscience-course-SHORTTITLE" title="OKFNPad PROJEKTNAME">OKFNPad</a></li> [NUR WENN ES KEIN ANDERES PAD GIBT!]
</ul>
<!--
<h3>Dokumentation</h3>
LINK ZUR DOKUMENTATION
Weiters wird über das Projekt wie üblich im <a href="http://openscience.alpine-geckos.at/category/CATEGORY" title="Blog PROJEKTNAME">Blog</a> geschrieben.
<h3>Source</h3>
<h4>verwendete Software</h4>
<ul>
<li></li>
</ul>
<h4>erzeugte Software</h4>
Der Quellcode wird unter der [FreeBSD License](http://opensource.org/licenses/BSD-2-Clause) im <a href="https://github.com/skasberger/REPOSITORY" title="COURSENAME GitHub Repository">GitHub Repository</a> frei zur Verfügung gestellt.
<h3>Data</h3>
LIZENZ; GITHUB
<h3>Sozio-kulturel</h3>
IST DAS PROJEKT OFFEN FÜR TEILNEHMERINNEN?
<a href="http://okfnpad.org/openscience-course-KURZBEZEICHNUNG" title="OKFNPad PROJEKTNAME">OKFNPad</a> [NUR WENN ES KEIN ANDERES PAD GIBT / ODER LINK ZU ANDEREM PAD]
-->
| html |
### Project Overview
For this project I have the publicly available data from LendingClub.com. Lending Club connects people who need money (borrowers) with people who have money (investors). As an investor one would want to invest in people who showed a profile of having a high probability of paying the amount back. The data that we have is from 2007-2010
### Learnings from the project
After completing this project, you will have a better understanding of how to build a decision tree model. In this project, you will apply the following concepts:
1.Train-test split
2.Correlation between the features
3.Decision Tree Modeling
4.Evaluation Metrics
5.Graphviz plotting
### Approach taken to solve the problem
A decision tree was employed to find the number of people who have paid back the loan and those who have not.
| markdown |
{"id_10661":{"title":"Prose Edda (Brodeur Translation)","language":"English","totaltime":"06:20:59","url_librivox":"http://librivox.org/the-prose-edda-by-snorri-sturleson/","url_iarchive":"http://archive.org/details/prose_edda_brodeur_1604_librivox","readers":["8713"],"authors":"11622","genres":"Myths, Legends & Fairy Tales"}} | json |
- 2 hrs ago 5 Best Microwave Ovens For Your Kitchen: Deals To Consider As Amazon Sale 2023 Is Nearing!
- Technology Samsung Galaxy Z Fold 5, Galaxy Z Flip 5 Price Leaks Ahead Of Launch: Premium Foldable Smartphones Start At?
- Travel Have you been to Vishveshwaraya Falls in Mandya yet? If not, this is the best time!
One thing is for sure, Ranveer Singh and Deepika Padukone cannot get enough of their movie Bajirao Mastani. We have spotted them almost everywhere, promoting the upcoming flick.
While earlier their wardrobe was highly inspired by Maratha era. The splendid Indian gowns of Deepika and long tunics of Ranveer were something we admired. But now they have switched their wardrobe back to western ensembles.
Last when we checked, Deepika was sporting a white dress and Ranveer a blue blazer. And this time, we again spotted them at a radio studio talking out loud about their movie. Before we start talking about their wardrobe, let's make this clear that this time Ranveer won over Deepika in wardrobe category.
Ranveer wore a long grey tunic paired with black cigarette pants and a beanie. Deepika was flaunting her long satin sleeveless coat paired with a pencil skirt and a black sandal.
- bollywood wardrobePriyanka Chopra Jonas Wows In Gorgeous Outfits In Her Latest Photoshoot And It’s Quite Impressive! | english |
{
"name": "boilerplate",
"main": "lib/index.d.ts",
"author": "<NAME>",
"description": "A description",
"ambientDevDependencies": {
"chai": "github:DefinitelyTyped/DefinitelyTyped/chai/chai.d.ts#91989d35b892f1526c35fb1e55219ba05bc5065e",
"mocha": "github:DefinitelyTyped/DefinitelyTyped/mocha/mocha.d.ts#d6dd320291705694ba8e1a79497a908e9f5e6617"
}
}
| json |
You have asked your dream girl/boy out on a date, you have picked out the chicest joint in town for the night and have made all the arrangements possible to make this evening one of the most romantic and memorable ones of the year. But how to tell if your date is actually into you or not! Well, we tell you how…read on!
You have asked your dream girl/boy out on a date, you have picked out the chicest joint in town for the night and have made all the arrangements possible to make this evening one of the most romantic and memorable ones of the year. But how to tell if your date is actually into you or not! Well, we tell you how…read on!
She fiddles with her hair. A lot!
Well, if the girl you’re with fiddles with her hair a lot, she is totally into you. Women do this unknowingly, because a) they love their hair, b) they want you to notice it, c) they are imagining how your hand will feel against their hair. But if she is fiddling with it without making eye contact with you, drop her like a hot potato. Because she is only bidding time till she can fake an emergency and scoot off from there!
He Looks into your eyes:
Not creepily staring at you like a potential stalker, but looking into your eyes without making your uncomfortable (or blush) then there is going to be another date for sure. Guys do give their girls all the attention at a romantic set up, but if he is gazing into your eyes with a slight twinkle, he is probably thanking his stars for bringing you to him. You should gaze back too, smile and nod a little and continue the conversation without breaking the flow.
Touchy feely:
This applies to both the genders. If he touches your arm, hand, back or shoulder (all in a friendly manner, of course), he is definitely thinking of you as someone worth spending his money and time on. And if she takes your hand to walk to her seat, touches your shoulder lightly or pats your back while laughing at your jokes, she is sending out signals in all directions. She is enjoying being with you and wouldn’t mind going on another date.
Phone is off the hook:
Once again, this applies to both of you. If his/her phone is off the hook and he/she is ONLY concentrating on you , it’s sure shot sign that he/she is interested…and more! In this day and age of tagging, checking-in and Instagram, you have to be someone pretty special to make your date not obsess over his/her phone.
Engaging conversation:
Fiddling with hair can be faked, looking into the eyes can be faked. But an engaging conversation, peppered with laughter and punctuated with animated shrieks JUST can’t be forced. If you like his/her company, you’re bound to indulge in fun talks and stare at each other with awkward smiles. So, if this is how your date turns out to be, you’re in for some great loving!
We do hope your V-Day celebrations turn out to be smashing! But don’t read too much into these signs as some people are pretty reserved. And that doesn’t mean that they are not into you. Instead of losing sleep over it, ask them point blank how they liked the evening with you. If they hesitate or don’t call you the morning-after, you have got your answer!
| english |
Tuesday February 16, 2016,
Learning, reinventing, and pivoting are the realities of being a part of a startup.
Living in such a reality are Farooq Adam (32), Harsh Shah (27), and Sreeraman M.G. (28). In November 2015, they pivoted from Shopsense, a B2B retail and inventory management solution, to Fynd, a B2C e-commerce marketplace.
Harsh tells us that when it came to downloads, targeted marketing did the trick. By the end of December last year, the firm was struggling with a mere 10,000 downloads of the app. In January, they started on-ground activations, social media marketing followed by ad push from mobile ad networks like InMobi and STG Media.
Co-founder Harsh tells us that the activations were apparel based, with graphic tees finding marketing done in colleges and startups while office apparels saw the team going to bigger offices in Lower Parel.
Today, Fynd has 97,000 downloads on Play Store with 8,000 on iOS. Obviously, Harsh and the other co-founders do not deny the massive experience that they carried from their previous business model.
But here’s the twist: Fynd is not like its other contemporaries in the market, rather it focuses more on helping the existing offline stores come online without changing any dynamics. Harsh explains,
Fynd aims to partner with offline brand stores near your vicinity, giving you the latest in-season fashion at the store price, while applying discounts only when there is a discount in the store.
How is that customer-friendly? Harsh replies by saying that the following model reduces the delivery time from days to a mere four to six hours. The customers also get fitting option ‘Fynd a Fit’, where if a certain consumer has asked for a size M, a size L will also be carried by the delivery personnel to be sure of the fitting. In case the size is right, then customers can take one of the offered options or return the product altogether.
Harsh rebuttals further by saying the basics of e-commerce remains the same. Instant gratification and best customer experience is what will get customer loyalty, while discount is just an added layer to the offering. He also doesn’t deny the importance of current in-season fashions, which according to him, his contemporaries are not showcasing.
Harsh says for brands, fashion comes of equal importance as selling. However, the co-founders don’t deny the fact that Fynd has partner stores for sourcing products in places like Guwahati, just to be on the safer side.
In November last year, Shopsense raised an undisclosed amount of pre-series A funding from Kae Capital, Kunal Bahl, and Rohit Bansal as investors to go bullish on their B2C platform, Fynd.
Fynd-ing ground?
Presently, the firm claims to have above 103 live brands on the platform while having 12,000 stores and stockpoints across the country. On an average, Fynd handles about 80–100 transactions daily with an average ticket size of above INR 2,000.
The firm also claims that the current traction is growing at 30 per cent week-on-week, with December witnessing a mere 10–15 orders daily. In December last year, the application had only 10,000 downloads, with as many as 29 brands live on the portal.
Following an app-only strategy, 65–70 per cent of their orders are from unique customers, with men’s T-shirts and women’s tops being the highest sold categories. Nike, Being Human, and Fab India are the most purchased brands.
On a revenue front, the firm charges a commission of 20 per cent from brands for every transaction made or product sold. The firm also plans to expand their presence to Delhi and Bengaluru by the end of next month, with Pune also being in the radar of expansion. With the valentine fervor getting over, according to Harsh customers can also expect newer collections and fashions from this week followed by super-fast delivery and campaign partnerships around the T20 world cup.
Although these metrics seem impressive, one has to realise that these figures is from a newer player which is finding ground. With the business taking its course, we’ll have to watch out whether Fynd keeps up with its conversions and is well received in markets like Bengaluru and Delhi.
Moreover, looking at the e-commerce pie, Fynd’s contemporaries like Jabong have not really been able to fire all cylinders with their backers, Rocket Internet trying to sell away the business. The game is also getting fiercer with Snapdeal trying to strengthen its fashion focus through acquiring Exclusively.com. Amazon is also trying to ramp its popularity on their fashion offerings by providing high discounts. Their direct competition Myntra says that they are on a high road to clock $1 billion in GMV in 2016, with their app-only strategy still being on a testing plate.
With such strong established players in the market, we will have to see how Fynd will register its uniqueness into the hearts of customers through fitting and same-day deliveries.
| english |
Adorable buttercups garden are growing around the globe, live near the ponds. Such variability of the plant appeared due to the work of breeders, the flower differs from its wild relative by the variety of colors and the size of the rosette.
Grass perennial garden buttercup or a culture of Ranunculus is a small shrub in size 40-100 cm. It has an erect stem with dissected leaves and a tuberous root. His flowers are similar to roses or poppies in miniature, they have rosettes 5-10 cm in diameter. Corollas are fluffy, semi-fluffy or simple, the palette of tones is diverse. Excludes cornflower blue and bluish tones, which have not yet been selected. The culture blossoms in the middle of summer for a month. Isolated raunch with juicy juice, which fills the poison with all the segments of the buttercup.
The bush keeps its charming characteristics for 3-4 years, then it is necessary to update its varieties. Flowers of buttercup garden according to the configuration of the outlet are divided into four types:
- Chalmoid or African - strongly-marbled, the flower is similar in shape to the sphere.
- French - half-fluffy, has two rows of petals.
- Persian or Asian - low, represented by ordinary half-fluffy rosettes.
- Pion shaped - corolla prominent, fluffy.
The most popular varieties of garden buttercups:
- Buttercup Rose Bicolor. The specimen is snow-white, fluffy, the tips are painted in a pinkish color, similar to a mini rose. The bush is compact, 20-25 cm in size.
- Buttercup Purple Pikoti. It has white petals with purple pollination. Corolla - fluffy, bush - compact.
- Buttercup Double Pink Buttercup. Gustomahrovy brand with pinkish petals. The average bush is up to 40 cm high.
Picturesque garden buttercups prefer sunny areas with scattered sun or shading hidden from the wind. The ideal site - near a bush or a tree with a very loose branch. Garden buttercups in the flowerbed are planted with tubers or seeds. It is better to immediately plant them on the street without growing seedlings - they do not like transplanting such a flower. Successfully it is cultivated and houses in pots.
Purchase planting stock is in February-March. Prior to sealing the bulbs should be stored at + 17 ° C in a ventilated place. In the street soil flowers are planted in mid-May, after the onset of real heat. Garden Buttercup - competent cultivation from tubers:
- Tubers before planting soak for 10-12 hours, so they are saturated with moisture. In the liquid, you can add the growth biostimulant Epin and a little potassium permanganate or Fundazol. This will allow the plant to quickly take root and accelerate its growth, saturate the rhizomes with moisture and protect them from diseases.
- Ready to germinate tubers in the water are much more - then they are alive. Those bulbs that do not change their size - are spoiled and should not be rooted.
- For planting, prepare holes, to the bottom of which drainage is laid.
- Plant tubers need to 5 cm deep, with an interval of 15-20 cm, they are closed down with "fingers. "
- If after planting there is a threat of frost, then the flowers should be covered with agrofiber or straw.
- The first shoots will be carried out 10-14 days later.
When deciding to cultivate the buttercups, garden seeds are best to buy them in the store. Collecting your personal material for planting is difficult, and its vitality is not high. Buttercups garden - an unmistakable planting of seeds:
- Sow seeds in late February-early March in the soil, consisting of a dose of peat soil, a dose of leaf soil and a half-sand.
- At the top, the crops are covered with soil and irrigated from the spray gun.
- The container is covered with glass and kept at + 10 ° C - 12 ° C, regularly ventilating and removing condensation.
- Seedlings squeezed after 2-3 weeks, then the vessel can be put in place with + 20 ° С.
- In the phase of 4-5 young leaves, the seedlings are transferred to pots of peat.
- In the second part of May, buttercups with a pot of peat are transferred to a hole 15-20 cm deep on the street.
- Saplings condense and moisturize. In the current year, they are unlikely to give color, and in the future - certainly.
When growing the buttercup garden planting and nursing in the pots is not more difficult than in the garden. For this purpose, low species with a height of no more than 40 cm are selected. The reserve is made in a neutral light substrate on the basis of peat (one copy - 1 liter of soil). On the eve of the nodule, they are soaked for half a day in water with potassium permanganate. At the bottom of the box you need to pour a layer of drainage , then - the substrate and plant the Ranunculus. The bulb is poured so that its top is visible.
Buttercup in the pot in the initial period should be kept warm + 12 ° C, periodically moistening the soil and not allowing strong sputum. When the shoots reach a few centimeters, the temperature is raised to + 20 ° C (in cooler circumstances it quickly fades). It is important to care for the buttercup indoors, so that light falls on it. In the summer, the pot can be carried to the balcony.
How to care for the garden buttercup?
Picturesque buttercups in the garden are unpretentious in their care. When they are cultivated, it is important to carry out the main activities:
- Watering should be systematic and moderate without sputum. At the end of the season, watering is gradually reduced, with the appearance of fading leaves - stop.
- For generous flowering, the roots need excellent air exchange, so you need to constantly loosen the soil, especially after the rains.
- For regular flowering, makeup every two weeks is important. At the initial stage of development, nitrogen-containing compounds are used, while in the flowering period they are complex with calcium and phosphorus content.
- In order for the budding period to be longer, it is necessary to systematically rid shoots from wilted flowers.
- The tubers are dug at the end of September, cleaned of soil and dried. Each bulb is placed in a pot with dry peat or wrapped in natural matter. Keep it at + 20 ° C until the next season. | english |
////////////////////////////////
//
// Copyright 2019 Battelle Energy Alliance, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
////////////////////////////////
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AnalyticsService } from '../../../services/analytics.service';
import { Navigation2Service } from '../../../services/navigation2.service';
import { NavigationService } from '../../../services/navigation.service';
@Component({
selector: 'app-analytics',
templateUrl: './analytics.component.html',
styleUrls: ['./analytics.component.scss']
})
export class AnalyticsComponent implements OnInit {
demographics:any = null;
questionAnswers:any = null;
constructor(private router: Router,
public navSvc2: Navigation2Service,
public navSvc: NavigationService,
public analyticsSvc: AnalyticsService,
private route: ActivatedRoute
) { }
ngOnInit() {
this.loadAnalytics();
this.navSvc.itemSelected.asObservable().subscribe((value: string) => {
this.router.navigate([value], { relativeTo: this.route.parent });
});
}
loadAnalytics() {
this.getDemographics();
this.getQuestionAnswers();
}
getDemographics(){
this.analyticsSvc.getDemographics().subscribe(
(data: any) => {
this.demographics = data;
},
error => {
console.log('Error getting all documents: ' + (<Error>error).name + (<Error>error).message);
console.log('Error getting all documents: ' + (<Error>error).stack);
});
}
getQuestionAnswers(){
this.analyticsSvc.getQuestionsAnswers().subscribe(
(data: any) => {
this.questionAnswers = data;
},
error => {
console.log('Error getting all documents: ' + (<Error>error).name + (<Error>error).message);
console.log('Error getting all documents: ' + (<Error>error).stack);
});
}
getRawData(){
return JSON.stringify(this.questionAnswers);
}
syntaxHighlight() {
var json = this.getRawData();
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
}
| typescript |
import React from 'react';
import PropTypes from 'prop-types';
import BoxShadow from '../Shared/BoxShadow/BoxShadow';
import css from './TestQuestion.module.css';
const TestQuestion = ({ question }) => {
return (
<BoxShadow boxShadow={14} className={css.paper}>
<p className={css.text} dangerouslySetInnerHTML={{ __html: question }} />
</BoxShadow>
);
};
TestQuestion.propTypes = {
question: PropTypes.string,
};
TestQuestion.defaultProps = {
question: '',
};
export default TestQuestion;
| javascript |
iQOO 9T was launched with a price tag of Rs 49,999 for 8GB RAM and 128GB storage.
iQOO 9T was launched with a price tag of Rs 49,999 for 8GB RAM and 128GB storage.
Redmi 10A Sport flaunts a 6.53-inch HD+ IPS display with an aspect ratio of 20:9.
Google has announced the release of official Android 10 for its Pixel range of smartphones.
Vivo is all set to bring the V25 Pro handset to India.
The corporation said that it removed 528,846 accounts nationwide as part of its automatic identification processes.
Director Amol Gupte has seen the comments on the ‘Saina’ poster and has responded to the criticism with a puzzling breakdown.
Parineeti Chopra took to social media to share the poster of the film that is based on ace badminton player Saina Nehwal and her life.
BTS would once more endorse Samsung devices.
A 12-megapixel selfie camera is said to be included on the S23 and S23+.
The incident happened in Kerala and the two-wheeler ride is fined by Kerala MVD.
Some users are also claiming that the e-commerce giant Flipkart is not placing their replacement requests.
If you are also among the ones who are looking to buy a phone but are confused with so many options then you are at the right place.
In the latest report, it has been revealed that the watch will not offer any new sensor.
Samsung Galaxy Z Flip 3 has survived 4,18,000 folds and unfolds. Let’s have a closer look at the latest durability test.
Oppo is rolling out a stable ColorOS12 update based on Android 12 for the Oppo Reno 3 and Oppo Reno 3 Pro smartphones.
| english |
package com.afollestad.sectionedrecyclerview;
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.Assert.fail;
import org.junit.Before;
import org.junit.Test;
public class PositionManagerTest {
private PositionManager positionManager;
private boolean showFooters;
@Before
public void before() {
showFooters = false;
positionManager = new PositionManager();
assertThat(positionManager.hasInvalidated()).isFalse();
invalidate();
}
private int invalidate() {
return positionManager.invalidate(
new ItemProvider() {
@Override
public int getSectionCount() {
return 2;
}
@Override
public int getItemCount(int sectionIndex) {
return 5;
}
@Override
public boolean showHeadersForEmptySections() {
return true;
}
@Override
public boolean showFooters() {
return showFooters;
}
});
}
@Test
public void test_is_header_true() {
assertThat(positionManager.isHeader(0)).isTrue();
assertThat(positionManager.isHeader(6)).isTrue();
}
@Test
public void test_is_header_false() {
assertThat(positionManager.isHeader(1)).isFalse();
assertThat(positionManager.isHeader(2)).isFalse();
assertThat(positionManager.isHeader(3)).isFalse();
assertThat(positionManager.isHeader(4)).isFalse();
assertThat(positionManager.isHeader(5)).isFalse();
assertThat(positionManager.isHeader(7)).isFalse();
assertThat(positionManager.isHeader(8)).isFalse();
assertThat(positionManager.isHeader(9)).isFalse();
assertThat(positionManager.isHeader(10)).isFalse();
assertThat(positionManager.isHeader(11)).isFalse();
}
@Test
public void test_section_id_no_footers() {
// Header 0
// 1
// 2
// 3
// 4
// 5
// Header 6
// 7
// 8
// 9
// 10
// 11
assertThat(positionManager.sectionId(-1)).isEqualTo(-1);
assertThat(positionManager.sectionId(0)).isEqualTo(0);
assertThat(positionManager.sectionId(1)).isEqualTo(-1);
assertThat(positionManager.sectionId(5)).isEqualTo(-1);
assertThat(positionManager.sectionId(6)).isEqualTo(1);
assertThat(positionManager.sectionId(7)).isEqualTo(-1);
assertThat(positionManager.sectionId(20)).isEqualTo(-1);
}
@Test
public void test_section_id_with_footers() {
// Header 0
// 1
// 2
// 3
// 4
// 5
// Footer 6
// Header 7
// 8
// 9
// 10
// 11
// 12
// Footer 13
showFooters = true;
invalidate();
assertThat(positionManager.sectionId(-1)).isEqualTo(-1);
assertThat(positionManager.sectionId(0)).isEqualTo(0);
assertThat(positionManager.sectionId(1)).isEqualTo(-1);
assertThat(positionManager.sectionId(6)).isEqualTo(-1);
assertThat(positionManager.sectionId(7)).isEqualTo(1);
assertThat(positionManager.sectionId(8)).isEqualTo(-1);
assertThat(positionManager.sectionId(20)).isEqualTo(-1);
}
@Test
public void test_footer_id() {
showFooters = true;
invalidate();
assertThat(positionManager.footerId(5)).isEqualTo(-1);
assertThat(positionManager.footerId(6)).isEqualTo(0);
assertThat(positionManager.footerId(7)).isEqualTo(-1);
assertThat(positionManager.footerId(12)).isEqualTo(-1);
assertThat(positionManager.footerId(13)).isEqualTo(1);
assertThat(positionManager.footerId(14)).isEqualTo(-1);
assertThat(positionManager.footerId(20)).isEqualTo(-1);
}
@Test
public void test_header_index_no_footers() {
assertThat(positionManager.sectionHeaderIndex(-1)).isEqualTo(-1);
assertThat(positionManager.sectionHeaderIndex(0)).isEqualTo(0);
assertThat(positionManager.sectionHeaderIndex(1)).isEqualTo(6);
assertThat(positionManager.sectionHeaderIndex(2)).isEqualTo(-1);
}
@Test
public void test_header_index_with_footers() {
showFooters = true;
invalidate();
assertThat(positionManager.sectionHeaderIndex(-1)).isEqualTo(-1);
assertThat(positionManager.sectionHeaderIndex(0)).isEqualTo(0);
assertThat(positionManager.sectionHeaderIndex(1)).isEqualTo(7);
assertThat(positionManager.sectionHeaderIndex(2)).isEqualTo(-1);
}
@Test
public void test_relative_pos_no_footers() {
assertThat(positionManager.relativePosition(0)).isEqualTo(new ItemCoord(0, -1));
assertThat(positionManager.relativePosition(1)).isEqualTo(new ItemCoord(0, 0));
assertThat(positionManager.relativePosition(3)).isEqualTo(new ItemCoord(0, 2));
assertThat(positionManager.relativePosition(6)).isEqualTo(new ItemCoord(1, -1));
assertThat(positionManager.relativePosition(7)).isEqualTo(new ItemCoord(1, 0));
assertThat(positionManager.relativePosition(11)).isEqualTo(new ItemCoord(1, 4));
}
@Test
public void test_relative_pos_with_footers() {
showFooters = true;
invalidate();
assertThat(positionManager.relativePosition(0)).isEqualTo(new ItemCoord(0, -1));
assertThat(positionManager.relativePosition(1)).isEqualTo(new ItemCoord(0, 0));
assertThat(positionManager.relativePosition(3)).isEqualTo(new ItemCoord(0, 2));
assertThat(positionManager.relativePosition(7)).isEqualTo(new ItemCoord(1, -1));
assertThat(positionManager.relativePosition(8)).isEqualTo(new ItemCoord(1, 0));
assertThat(positionManager.relativePosition(12)).isEqualTo(new ItemCoord(1, 4));
}
@Test
public void test_absolute_pos_no_footers() {
assertThat(positionManager.absolutePosition(new ItemCoord(0, 0))).isEqualTo(1);
assertThat(positionManager.absolutePosition(new ItemCoord(0, 1))).isEqualTo(2);
assertThat(positionManager.absolutePosition(new ItemCoord(0, 2))).isEqualTo(3);
assertThat(positionManager.absolutePosition(new ItemCoord(0, 3))).isEqualTo(4);
assertThat(positionManager.absolutePosition(new ItemCoord(0, 4))).isEqualTo(5);
assertThat(positionManager.absolutePosition(new ItemCoord(0, 5))).isEqualTo(-1);
assertThat(positionManager.absolutePosition(new ItemCoord(0, 6))).isEqualTo(-1);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 0))).isEqualTo(7);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 1))).isEqualTo(8);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 2))).isEqualTo(9);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 3))).isEqualTo(10);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 4))).isEqualTo(11);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 5))).isEqualTo(-1);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 6))).isEqualTo(-1);
assertThat(positionManager.absolutePosition(new ItemCoord(2, 6))).isEqualTo(-1);
assertThat(positionManager.absolutePosition(new ItemCoord(3, 3))).isEqualTo(-1);
assertThat(positionManager.absolutePosition(new ItemCoord(-5, 3))).isEqualTo(-1);
}
@Test
public void test_absolute_pos_with_footers() {
showFooters = true;
invalidate();
assertThat(positionManager.absolutePosition(new ItemCoord(0, 0))).isEqualTo(1);
assertThat(positionManager.absolutePosition(new ItemCoord(0, 1))).isEqualTo(2);
assertThat(positionManager.absolutePosition(new ItemCoord(0, 2))).isEqualTo(3);
assertThat(positionManager.absolutePosition(new ItemCoord(0, 3))).isEqualTo(4);
assertThat(positionManager.absolutePosition(new ItemCoord(0, 4))).isEqualTo(5);
assertThat(positionManager.absolutePosition(new ItemCoord(0, 5))).isEqualTo(-1);
assertThat(positionManager.absolutePosition(new ItemCoord(0, 6))).isEqualTo(-1);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 0))).isEqualTo(8);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 1))).isEqualTo(9);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 2))).isEqualTo(10);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 3))).isEqualTo(11);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 4))).isEqualTo(12);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 5))).isEqualTo(-1);
assertThat(positionManager.absolutePosition(new ItemCoord(1, 6))).isEqualTo(-1);
assertThat(positionManager.absolutePosition(new ItemCoord(2, 6))).isEqualTo(-1);
assertThat(positionManager.absolutePosition(new ItemCoord(3, 3))).isEqualTo(-1);
assertThat(positionManager.absolutePosition(new ItemCoord(-5, 3))).isEqualTo(-1);
}
@Test
public void test_is_section_expanded_true() {
assertThat(positionManager.isSectionExpanded(0)).isTrue();
assertThat(positionManager.isSectionExpanded(1)).isTrue();
}
@Test
public void test_is_section_expanded_false() {
positionManager.collapseSection(0);
assertThat(positionManager.isSectionExpanded(0)).isFalse();
positionManager.collapseSection(1);
assertThat(positionManager.isSectionExpanded(1)).isFalse();
}
@Test
public void test_collapse_expand_out_of_bounds() {
try {
positionManager.collapseSection(-1);
fail("No exception thrown for out of range section!");
} catch (IllegalArgumentException ignored) {
}
try {
positionManager.collapseSection(3);
fail("No exception thrown for out of range section!");
} catch (IllegalArgumentException ignored) {
}
try {
positionManager.expandSection(-1);
fail("No exception thrown for out of range section!");
} catch (IllegalArgumentException ignored) {
}
try {
positionManager.expandSection(3);
fail("No exception thrown for out of range section!");
} catch (IllegalArgumentException ignored) {
}
try {
positionManager.isSectionExpanded(-1);
fail("No exception thrown for out of range section!");
} catch (IllegalArgumentException ignored) {
}
try {
positionManager.isSectionExpanded(3);
fail("No exception thrown for out of range section!");
} catch (IllegalArgumentException ignored) {
}
}
@Test
public void test_collapse_section() {
assertThat(invalidate()).isEqualTo(12);
positionManager.collapseSection(0);
assertThat(invalidate()).isEqualTo(7);
}
@Test
public void test_collapse_all_sections() {
assertThat(invalidate()).isEqualTo(12);
positionManager.collapseAllSections();
assertThat(invalidate()).isEqualTo(2);
}
@Test
public void test_expand_section() {
positionManager.collapseSection(1);
assertThat(invalidate()).isEqualTo(7);
positionManager.expandSection(1);
assertThat(invalidate()).isEqualTo(12);
}
@Test
public void test_expand_all_sections() {
positionManager.collapseAllSections();
assertThat(invalidate()).isEqualTo(2);
positionManager.expandAllSections();
assertThat(invalidate()).isEqualTo(12);
}
@Test
public void test_toggle_expanded() {
positionManager.collapseSection(1);
assertThat(invalidate()).isEqualTo(7);
positionManager.toggleSectionExpanded(1);
assertThat(invalidate()).isEqualTo(12);
positionManager.toggleSectionExpanded(1);
assertThat(invalidate()).isEqualTo(7);
}
@Test
public void test_has_invalidated() {
assertThat(positionManager.hasInvalidated()).isTrue();
}
@Test
public void test_item_coord_toString() {
assertThat(new ItemCoord(8, 16).toString()).isEqualTo("8:16");
}
}
| java |
عن أبي هريرة رضي الله عنه قال: قال رسول الله صلى الله عليه وسلم : «إنكم لا تسعون الناس بأموالكم وَلْيَسَعُهُمْ منكم بَسْطُ الوجه وحسن الخلق».
Abu Hurayrah (may Allah be pleased with him) reported that the Prophet (may Allah's peace and blessings be upon him) said: "Verily you cannot embrace and suffice all people with your money, but you can embrace and suffice them all with a cheerful face and good manners."
This Hadīth is proof of the virtue of having a smiling, cheerful face when meeting others, as well as the virtue of having good manners and good social relations, and of being kind to people in word and deed to all people. This is indeed within the capacity of each human being. Good manners create mutual love and nurture amicability and friendliness among the members of a society.
| english |
..so the summer is back with bang!!!!! In Gujarat and Ahmedabad, the sun is more “focused” to dry the minds of biz oriented Gujarati people…I think the temperature will rise upto 43-45 C this time..what you say?
so the summer is on your door step and you just require to face it….and nothing!!!! Some wise man has truly said that,if you want to have a real experience of Seasons in nature..then do go to tropical countries( here read India) to have it clearly distinguished in all flavors…..
So, enjoy mango -ras, thin chapaties, Subji of moong dal,rice, mango-curry …and so…much…so salivating…….
But dont forget to enjoy yourselves…..
| english |
Between Bitcoin-themed superspreader events and cringey branded NFT’s, those within the crypto community have set a high bar for devising the worst ways to hawk their currency of choice. But this week, the creators of an Elon Musk-themed cryptocurrency dubbed the “Elon Goat Token” (yes, that’s actually what it’s called) came up with a promotional campaign that might have just blown those other ideas out of the water. It’s a statue featuring Elon Musk’s expressionless face on a goat’s body, and it looks... exactly like you’d think it would.
“At every crucial point in human history, a magnum opus, or masterpiece, has captured the essence of that period. Think of the Great Pyramids of Giza. The Statue of David. Picasso’s Guernica,” reads a 12-page whitepaper explaining the conception of the new currency.
“The world now stands upon the brink of the greatest transfer of wealth in its entire history,” the manifesto continued. “What better way to enshrine the beginning of this new blazing era, than to do so by celebrating the degenerates involved, alongside the most innovative man of the 21st Century, Elon Musk?” Behold:
Regardless of your feelings on Elon Musk, goats, or the word “innovation,” you can’t deny that the statue is unsettling, to say the least. Maybe it’s the goat horns. Maybe it’s the fact he’s riding a rocket that seems to be actively electrocuting him. Maybe it’s because—as the brief describes—the Elon Goat team has plans to hook up the over 30-foot long statue to a Tesla and drive the thing to the automaker’s HQ in Austin, Texas, “for Musk and the globe to admire.” You can watch the promo clip below and come to your own conclusions:
Apparently, making “a huge goat” (his words) just made more sense. And after researching logistics, Sansalone came to the conclusion that the easiest way to build that huge goat would be indoors, and on a trailer—a tactic that would let his team skirt the regulations and zoning laws he’d need to comply with otherwise. This, in turn, sparked the idea to hitch that huge goat to the back of a Tesla, take it on a tour around the country, and drop it on Elon Musk’s doorstep where he’ll, presumably... tweet about it, since that’s kind of his specialty.
Sansalone noted in the interview that he’s already dropped a solid $20,000 on an outside designer to start work on the project, and that designer, in turn, has been chronicling his goatventures on Instagram. Sansalone said he expected the statue to be complete in “under four months,” and will cost him about $500,000 after all’s said and done. But if this debacle somehow lands Elon Goat on its namesake’s Twitter feed—which has been seen singlehandedly spiking the prices of other cryptos in the past—then maybe that price is worth it.
| english |
<filename>apexplugin.json<gh_stars>1-10
{
"name" : "Pretius Enhanced Notifications",
"version" : "1.0",
"description" : "The plugin is dynamic action plugin providing notifications for Oracle APEX 5 and Universal Theme. Due to highly configurable attributes, the plugin can be used as presentation layer for AJAX callbacks. Translated messages from the database can be easly presented in two types of notification.",
"keywords" : ["notification", "ajax", "inline", "floating"],
"homepage" : "https://github.com/Pretius/apex-enhanced-notifications",
"bugs" : {
"url" : "https://github.com/Pretius/apex-enhanced-notifications/issues",
"email" : "<EMAIL>"
},
"license" : "MIT",
"commercial" : "No",
"commercially_supported":"No",
"author" : {
"name" : "Pretius",
"email" : "<EMAIL>",
"url" : "http://www.pretius.com",
"twitter": "PretiusSoftware"
},
"repository" : {
"type" : "git",
"url" : "https://github.com/Pretius/apex-enhanced-notifications.git"
},
"oracle" : {
"versions" : ["172.16.17.32", "172.16.31.10"],
"apex" : {
"versions" : ["5.0.0"],
"plugin" : {
"internalName" : "apex.ehnanced.notifications",
"type" : "dynamic action",
"demo" : "http://apex.pretius.com/apex/f?p=105:NOTIFICATIONS",
"previewImage" : "https://raw.githubusercontent.com/Pretius/apex-enhanced-notifications/master/preview.gif"
}
}
}
} | json |
const ProceedingsController = (req, res) => {
return (routeInstance, methods) => {
const controller = new Promise(resolve => {
let proceedingsOptions = []
const childrenNames = methods.getMultipleValues('children', 'child_used-name_')
const otherChildrenNames = methods.getMultipleValues('other-children', 'other-children_full-name_')
if (childrenNames.length + otherChildrenNames.length > 1) {
const childrenOptions = childrenNames.map((name, index) => {
return {
name: `children_${index + 1}`,
xvalue: 'yes',
label: name
}
})
const otherChildrenOptions = otherChildrenNames.map((name, index) => {
return {
name: `other_children_${index + 1}`,
xvalue: 'yes',
label: name
}
})
proceedingsOptions = [].concat(childrenOptions, otherChildrenOptions)
// routeInstance.blocks.push({
// _id: 'kazaam',
// _blockType: 'Section',
// heading: 'Oh My Word',
// content: 'Tish-alish'
// }, 'proceedings-children')
routeInstance.proceedingsOptions = proceedingsOptions
routeInstance.proceedingsName = 'proceedings-children-options'
}
resolve(routeInstance)
})
return controller
}
}
module.exports = ProceedingsController | javascript |
<filename>common-parent/edu-service/src/main/java/com/zl/edu/service/IUserService.java<gh_stars>0
package com.zl.edu.service;
import com.zl.edu.model.User;
import com.zl.edu.service.base.IBaseService;
import javax.jnlp.BasicService;
/**
* @author zhanglong0314
* @date 2019/5/20 - 22:38
*/
public interface IUserService<User> extends IBaseService<User>{
}
| java |
/*
* Copyright (c) 2021 Works Applications Co., Ltd.
*
* 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.
*/
use super::*;
use serde_json::{Map, Value};
use crate::config::Config;
use crate::dic::grammar::Grammar;
use crate::test::zero_grammar;
#[test]
fn combine_continuous_prolonged_sound_mark() {
let original = "ゴーール";
let normalized = "ゴール";
let (_, plugin) = setup();
let mut text = InputBuffer::from(original);
plugin.rewrite(&mut text).expect("succeeds");
assert_eq!(original, text.original());
assert_eq!(normalized, text.current());
assert_eq!(9, text.current().len());
let expected = b"\xe3\x82\xb4\xe3\x83\xbc\xe3\x83\xab";
assert_eq!(expected, text.current().as_bytes());
assert_eq!(0, text.get_original_index(0));
assert_eq!(3, text.get_original_index(3));
assert_eq!(9, text.get_original_index(6));
assert_eq!(12, text.get_original_index(9));
}
#[test]
fn combined_continuous_prolonged_sound_marks_at_end() {
let original = "スーパーー";
let normalized = "スーパー";
let (_, plugin) = setup();
let mut text = InputBuffer::from(original);
plugin.rewrite(&mut text).expect("succeeds");
assert_eq!(original, text.original());
assert_eq!(normalized, text.current());
assert_eq!(12, text.current().as_bytes().len());
let expected = b"\xe3\x82\xb9\xe3\x83\xbc\xe3\x83\x91\xe3\x83\xbc";
assert_eq!(expected, text.current().as_bytes());
assert_eq!(0, text.get_original_index(0));
assert_eq!(3, text.get_original_index(3));
assert_eq!(6, text.get_original_index(6));
assert_eq!(9, text.get_original_index(9));
assert_eq!(15, text.get_original_index(12));
}
#[test]
fn combine_continuous_prolonged_sound_marks_multi_times() {
let original = "エーービーーーシーーーー";
let normalized = "エービーシー";
let (_, plugin) = setup();
let mut text = InputBuffer::from(original);
plugin.rewrite(&mut text).expect("succeeds");
assert_eq!(original, text.original());
assert_eq!(normalized, text.current());
assert_eq!(18, text.current().as_bytes().len());
let expected = b"\xe3\x82\xa8\xe3\x83\xbc\xe3\x83\x93\xe3\x83\xbc\xe3\x82\xb7\xe3\x83\xbc";
assert_eq!(expected, text.current().as_bytes());
assert_eq!(0, text.get_original_index(0));
assert_eq!(3, text.get_original_index(3));
assert_eq!(9, text.get_original_index(6));
assert_eq!(12, text.get_original_index(9));
assert_eq!(21, text.get_original_index(12));
assert_eq!(24, text.get_original_index(15));
assert_eq!(36, text.get_original_index(18));
}
#[test]
fn combine_continuous_prolonged_sound_marks_multi_symbol_types() {
let original = "エーービ〜〜〜シ〰〰〰〰";
let normalized = "エービーシー";
let (_, plugin) = setup();
let mut text = InputBuffer::from(original);
plugin.rewrite(&mut text).expect("succeeds");
assert_eq!(original, text.original());
assert_eq!(normalized, text.current());
assert_eq!(18, text.current().as_bytes().len());
let expected = b"\xe3\x82\xa8\xe3\x83\xbc\xe3\x83\x93\xe3\x83\xbc\xe3\x82\xb7\xe3\x83\xbc";
assert_eq!(expected, text.current().as_bytes());
assert_eq!(0, text.get_original_index(0));
assert_eq!(3, text.get_original_index(3));
assert_eq!(9, text.get_original_index(6));
assert_eq!(12, text.get_original_index(9));
assert_eq!(21, text.get_original_index(12));
assert_eq!(24, text.get_original_index(15));
assert_eq!(36, text.get_original_index(18));
}
#[test]
fn combine_continuous_prolonged_sound_marks_multi_mixed_symbol_types() {
let original = "エー〜ビ〜〰ーシ〰ー〰〜";
let normalized = "エービーシー";
let (_, plugin) = setup();
let mut text = InputBuffer::from(original);
plugin.rewrite(&mut text).expect("succeeds");
assert_eq!(original, text.original());
assert_eq!(normalized, text.current());
assert_eq!(18, text.current().as_bytes().len());
let expected = b"\xe3\x82\xa8\xe3\x83\xbc\xe3\x83\x93\xe3\x83\xbc\xe3\x82\xb7\xe3\x83\xbc";
assert_eq!(expected, text.current().as_bytes());
assert_eq!(0, text.get_original_index(0));
assert_eq!(3, text.get_original_index(3));
assert_eq!(9, text.get_original_index(6));
assert_eq!(12, text.get_original_index(9));
assert_eq!(21, text.get_original_index(12));
assert_eq!(24, text.get_original_index(15));
assert_eq!(36, text.get_original_index(18));
}
fn setup<'a>() -> (Grammar<'a>, ProlongedSoundMarkPlugin) {
let settings = build_mock_setting();
let config = Config::default();
let grammar = zero_grammar();
let mut plugin = ProlongedSoundMarkPlugin::default();
plugin
.set_up(&settings, &config, &grammar)
.expect("Failed to setup plugin");
(grammar, plugin)
}
fn build_mock_setting() -> Value {
let mut map = Map::default();
map.insert(
"prolongedSoundMarks".to_string(),
Value::Array(vec![
Value::String("ー".to_string()),
Value::String("〜".to_string()),
Value::String("〰".to_string()),
]),
);
Value::Object(map)
}
| rust |
<reponame>getkloudi/integration-wrapper-generator
# Jira.JqlQueryFieldEntityProperty
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**entity** | **String** | The object on which the property is set. |
**key** | **String** | The key of the property. |
**path** | **String** | The path in the property value to query. |
**type** | **String** | The type of the property value extraction. Not available if the extraction for the property is not registered on the instance with the [Entity property](https://developer.atlassian.com/cloud/jira/platform/modules/entity-property/) module. | [optional]
## Enum: TypeEnum
* `number` (value: `"number"`)
* `string` (value: `"string"`)
* `text` (value: `"text"`)
* `date` (value: `"date"`)
* `user` (value: `"user"`)
| markdown |
import { TokenInterceptor } from './auth/token.interceptor';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomeComponent } from './home/home.component';
import { CatalogComponent } from './catalog/catalog.component';
import { OrdersComponent } from './orders/orders.component';
import { CatalogClient, OrdersClient,CustomersClient, EmployeesClient, ShippersClient ,DashboardClient} from './clients';
import { ProductsComponent } from './products/products.component';
import { ReactiveFormsModule } from '@angular/forms';
import { ToastrModule } from 'ngx-toastr';
import { BlockUIModule } from 'ng-block-ui';
import { ModalModule } from 'ngx-bootstrap/modal';
import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
import { NgSelectModule } from '@ng-select/ng-select';
import { TabsModule } from 'ngx-bootstrap/tabs';
import { PaginationModule } from 'ngx-bootstrap/pagination';
import { ExportService } from './services/export.service';
import { FilterPipe } from './pipes/filter.pipe';
import { DateService } from './services/date.service';
import { PaginationService } from './services/pagination.service';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ChartsModule } from 'ng2-charts';
@NgModule({
declarations: [
AppComponent,
NavMenuComponent,
HomeComponent,
CatalogComponent,
OrdersComponent,
ProductsComponent,
FilterPipe,
DashboardComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
HttpClientModule,
FormsModule,
RouterModule.forRoot([
{ path: '', component: DashboardComponent, pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent, pathMatch: 'full' },
{ path: 'catalog', component: CatalogComponent },
{ path: 'orders', component: OrdersComponent },
{ path: 'products', component: ProductsComponent }
]),
ReactiveFormsModule,
BrowserAnimationsModule,
ToastrModule.forRoot(),
BlockUIModule.forRoot(),
ModalModule.forRoot(),
BsDatepickerModule.forRoot(),
NgSelectModule,
TabsModule.forRoot(),
PaginationModule.forRoot(),
ChartsModule
],
exports: [
FilterPipe
],
providers: [
CatalogClient,
OrdersClient,
EmployeesClient,
CustomersClient,
ShippersClient,
DashboardClient,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
},
ExportService,
DateService,
PaginationService
],
bootstrap: [AppComponent]
})
export class AppModule { }
| typescript |
This article was written during the SAG and WGA strikes. The work talked about here would not be possible without all of their talent and hard work!
Happy And Just Like That season finale day! I can say “season” with confidence, because this absolutely delightful trainwreck of a show has already been renewed for season 3. Despite that, the writers gave an absolute masterclass on how to end a series in a way that feels good if it gets canceled but still keeps the door open for renewal. Nobody relapsed and got into a car accident or threw a vial of sperm on the floor. Instead, we ended with an incredibly hot sex montage and the promise of friendship.
But before we get there, back to the beginning.
The episode opens with Carrie on the phone with Aidan. She double checks to make sure that Wyatt is doing okay, but it’s clear even from this short interlude that Aidan is eager to be off the phone with his long distance wifey.
Then Carrie gets another phone call, and it’s from Samantha! She answers it with the ease of old friends, saying “hello London, what’s shakin’ lady!” and I’m confused. Did we somehow settle the Carrie/Samantha feud far more than I thought we did? Either way, I’m happy because KIM CATTRALL AKA SAMANTHA MOTHER FUCKING JONES IS BACK ON OUR SCRENES. Yes, that did require all caps. Samantha was the heart and soul of Sex and the City, and while bad working conditions (especially her relationship with Sarah Jessica Parker) prevented Cattrall from returning to the reboot, I miss her dearly.
Unfortunately, her time on the show is all too short. Samantha says she was planning on surprising Carrie for the Last Supper, but her flight was delayed three hours, and as she was only planning on coming for the night she won’t see her at all. This was such a clever way of talking to Carrie without ever actually having to see SJP! Samantha has a British accent now and she’s delightfully fashionable. I love her.
Then her scene ends, and we’re back in New York.
It’s the day after Charlotte’s drunken bender, and she’s struggling to get up. Harry comes in to wake her up because Anthony arrived. He has plans to discuss losing his “ass virginity”, but Charlotte can’t deal right then and tells Harry to go away.
Harry’s still having trouble adjusting to his larger parenting role. He tells Charlotte that he got the kids all ready for the day and out the door that morning, but that he “can’t do it all!”. This causes even a very hungover Charlotte to break, and I have to quote nearly her entire rant here because it’s so good.
“I can’t talk loud, so please just listen. You are not doing it all. I know, because you made a few breakfasts and you ran a few errands that it feels like you are. But in fact, you are doing the bare minimum of what I, and other women, have been asked—no, expected, to do around the house for years and years and years. And now I am asking—no, expecting, you to help out with part of it, not all of it”.
A couple years ago, I started writing an article about why I thought Charlotte was a lesbian on Sex and the City. Despite the fact that most people considered Miranda the queer one (especially given she’s played by queer actress Cynthia Nixon), something about Charlotte’s attitude felt queer to me, and the way she hated blow jobs felt like it may even be lesbian.
In reality, she just embodied choice feminism in a way that so deeply defied the way her friend’s practiced feminism that she was set apart. She made the decision to be a wife and mother because that was the life she craved in spite of what other people wanted for her. While that’s not queerness, it resonated with me in a way that Miranda’s work-hard-and-win mindset never did. And now, she’s once again making an active choice, and fighting for her right to choose work if that’s what she wants. As an adult it’s so clear that Charlotte is the coolest.
But speaking of Miranda! She finally took the trip out to Coney Island to visit Steve at his new place. They have a good talk about being friends in the present, not just the past, and Steve seems happy that Miranda brought it up. He engages in some light bisexual erasure by confirming she won’t “loop back around to straight”, and Miranda affirms how right Steve always was about their life.
It’s adorable, and they put their arms around each other in casual comfort. Brady is arriving at that moment, and when he sees his parents together he grins. This scene truly made me cry! I am soft! There is nothing that makes me cry quicker than true love, even if that love is a friendship. And Miranda and Steve are soulmates, even if they aren’t meant to date forever.
There’s good news at work for Nya. She was elected to the American Law Institute! It was supposed to be a long process, but Nya is so impressive that the board unanimously voted her in just a few days after she submitted her application.
I’m delighted for her, but upon hearing the news all Nya wanted to do was call Andre. She returns home to Miranda pouting about not having a man to share her life with. She’s so sad that she wants to skip Carrie’s party that night, but Miranda talks her out of it with the mention of a Michelin chef.
Carrie plates the table in And Just Like That theme colors, and then everyone starts to arrive!
Everyone is dressed to impress, and while I expect that from the show I can’t help but think that if my friends were to host a Michelin chef in our home, we’d all be wearing pajamas.
Charlotte notices Lisa drinking and points it out in surprise. Lisa tells her she miscarried, and when Charlotte’s eyes fill with sympathy, Lisa tells her not to do it there.
Harry shows up with a new iPhone that he bought just for Charlotte, boasting of how proud he is of her.
Giuseppe and Anthony arrive still bickering about Anthony’s walls. They’re so high that Giuseppe is considering moving back to Rome just to escape them. Giuseppe states that NYC publishing is “impenetrable”, and Charlotte’s face is comical. When Anthony hears this, it prompts a deep discussion about all the ways Anthony is holding back, and Anthony admits that he loves Giuseppe, which he’s never done before. The two get on better terms and I’m happy for them and their May/December romance.
Lisette and Che also have a cute conversation. Lisette was a huge fan of Che’s podcast, and when she hears that Che might be taking a break from comedy, she takes it in stride. She also went through a transitional period when she first moved from LA to NYC, and it’s okay for Che to be doing the same thing. This seems to have a positive impact on Che, who’s happy to meet Lisette.
Nya and Miranda arrive and run into the chef on their way upstairs. The chef happens to be Toussaint, the man Nya ran into at Bar T’s a few episodes ago. They hit it off once again, and Nya sends Miranda upstairs alone so that she can flirt.
Without her wingwoman by her side, Miranda decides to go chat with Che right away. She tells them that they can’t ruin Carrie’s party, and they decide to hash out what happened the weekend before. I must say, Miranda looks hot tonight. Lately, she’s been dressing for revenge.
Che apologizes to Miranda for their jokes, and promises they’ll never make a joke about their relationship again. Miranda brings up that she thought they left on good terms, and Che says they did too and then Miranda ghosted them, so they’re a bit confused. That being said, they just made the jokes because they thought they were funny!
The two agree that their relationship, while a trainwreck, was the “good” kind of train wreck where nobody dies and everyone gets where they want to go. It’s cute, and I’m glad Miranda is getting closure on all of her relationships this episode.
Seema and Ravi arrive and then Seema proceeds to promptly ignore him. She tells Carrie that she’s stopped putting energy in because ever since she said “I love you”, Ravi has been on his phone all the time again. Carrie points out that maybe Seema is the one putting up walls because she’s scared and Seema looks stressed, which is a sign Carrie is right.
Before dinner begins, Carrie introduces everyone to her cat and then announces that she has to put her “baby to bed”. This is out of character for Carrie and was put in the show just to get a reaction out of Lisa. It works, and Lisa runs into the bathroom, brushing past a very-much-reconciled Anthony and Giuseppe to do so.
Herbert follows her, and is the best husband in the world as he comforts her. She’s worried she wished the baby away, and he assures her she didn’t. I want to give Lisa a hug!
The appetizer is served, and Nya and Toussaint flirt as it’s rolled out. Before they can even finish eating the three bites of food, Egypt calls and Ravi darts off. As the main course rolls around, Seema goes out to find him. He’s pissed at him for always being on his phone and implies that he’s flirting with Instagram and TikTok models.
“I have not Tik’d or Tok’d since we met!” Ravi announces. He tells Seema that they need him to switch the dates he’s filming in New York and Egypt which means he’d leave the next day and be gone for six months. He loves Seema, and he wants her to know that, but he has to go to Egypt. Seema pouts a bit, but it seems like him saying the word “love” settled some of her worst fears.
Carrie makes a speech before the food is served and demands that everyone say something they want to let go of, in one word with no repeats. Rather than meme-ing Carrie and this extremely bizarre short notice request, they make it as serious as possible.
Miranda wanted to say that as well, so she changes it to “regret”, and then “guilt” in quick succession.
Lisa was planning on saying guilt, but she can’t find another word so she sticks with it.
Herbert passes, too choked up about his wife, and then we continue.
Harry says “possessiveness” and Charlotte says “limits”.
Carrie says “expectations” and launches into a speech. She doesn’t want to assume things will go a certain way, and she acknowledges that tomorrow will be better than she ever expected.
Che calls her out on saying more than one word, and they all laugh and then dive into dinner.
As people begin to leave, Miranda gets a call asking her to do a live interview on BBC that very night. She scurries off in excitement! Once there she meets Joy, a hot woman who suggests going out for a drink after, and then delivers a great on-air speech.
Toussaint asks to give Nya a ride home even though he lives in Harlem and she lives in Brooklyn! They’re going to fall in love, I just know it.
Ravi and Seema get ready for bed lightly bickering. He wants her to come to Cairo, but she refuses to give up her career or personhood for a man, full stop. I’m happy she put her foot down, because I can’t imagine there would be much to do in Egypt when Ravi would most certainly be incredibly busy. She does, however, acknowledge how real the relationship is to her, and Ravi promises that he’ll be back.
Carrie is talking to her little cat when she hears rocks hitting the window. It’s Aidan! He comes up the stairs to the apartment, and I’m more in shock that he left his incredibly injured son than I am that he got over his deep fear of the past. The reason he came, though, is essentially to break up with Carrie.
He needs to be there for his kids, especially Wyatt (who was on shrooms and drunk when he crashed). Carrie says she understands and offers to go back to Virginia with him every once in a while, but Aidan refuses. He can’t multitask, and he needs all of his energy to go towards his boys. I understand why he can’t go to New York, but it seems a bit extreme that Carrie can’t come visit on the weeks where Aidan’s ex has the kids!
Carrie says “I can’t believe we’re back here again” and puts her head in her hands, but Aidan says they’re not. He loves Carrie, and he just wants her to wait five years for him. That’s insane. Who’s sitting around waiting for five years!
They kiss, but all I can think is how crazy of a request that is.
To wrap up everyone’s storylines for the season, we get an incredibly hot couples montage set to a song I’m going to have to look up later. Charlotte and Harry hang out in bed giggling and trying to set up Charlotte’s new phone. Miranda gets (non-alcoholic, flirty) drinks with Joy. Giuseppe finally fucks Anthony and we get some lube representation. Che makes out with Tony. Nya welcomes Toussaint into her home. Carrie and Aidan have sex and the camera somehow shows us so much nakedness and simultaneously none at all. Seema and Ravi have sex and then spend time just talking in bed afterwards. Lisa and Herbert cuddle each other to sleep.
The next morning, Aidan and Carrie say their goodbyes. Carrie waves goodbye from the doorway of her new home, holding her cat in her hand, and Aidan gives what looks like a finger heart but is in fact a snap so quick nobody can see it.
Seema calls and tells Carrie she booked a getaway, and the two head to oceanside Greece to drink and reminisce about the too-good-to-be-true relationships they both just put on hold. They’re sad, but they’re also happy to be together.
And just like that… Carrie ordered two more cosmopolitans. Friendship endures. And so does this show. See you all next year (or 3 years from now, depending on whether the studios actually meet worker’s demands) for another round of recaps!
| english |
<reponame>ooasis/zipkin
/*
* Copyright 2015-2018 The OpenZipkin Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package zipkin2.storage.snowflake;
import org.jooq.DSLContext;
import org.jooq.InsertSetMoreStep;
import org.jooq.Query;
import org.jooq.Record;
import zipkin2.Annotation;
import zipkin2.Call;
import zipkin2.Span;
import zipkin2.storage.SpanConsumer;
import zipkin2.storage.snowflake.internal.generated.tables.SpanAnnotations;
import zipkin2.storage.snowflake.internal.generated.tables.SpanTags;
import zipkin2.storage.snowflake.internal.generated.tables.Spans;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
class SnowflakeSpanConsumer implements SpanConsumer {
DataSourceCall.Factory dataSourceCallFactory;
public SnowflakeSpanConsumer(SnowflakeStorage snowflakeStorage) {
dataSourceCallFactory = new DataSourceCall.Factory(
snowflakeStorage.datasource(),
new DSLContexts(snowflakeStorage.settings(), snowflakeStorage.listenerProvider()),
snowflakeStorage.executor());
}
@Override
public Call<Void> accept(List<Span> spans) {
if (spans.isEmpty()) return Call.create(null);
return dataSourceCallFactory.create(new BatchInsertSpans(spans));
}
@SuppressWarnings("Duplicates")
static final class BatchInsertSpans implements Function<DSLContext, Void> {
final List<Span> spans;
BatchInsertSpans(List<Span> spans) {
this.spans = spans;
}
@Override
public Void apply(DSLContext create) {
List<Query> inserts = new ArrayList<>();
for (Span v2 : spans) {
InsertSetMoreStep<Record> insertSpan = create
.insertInto(Spans.SPANS)
.set(Spans.SPANS.TRACE_ID, v2.traceId())
.set(Spans.SPANS.NAME, v2.traceId())
.set(Spans.SPANS.PARENT_ID, v2.traceId())
.set(Spans.SPANS.ID, v2.traceId())
.set(Spans.SPANS.KIND, v2.kind().name())
.set(Spans.SPANS.TIMESTAMP, v2.timestampAsLong())
.set(Spans.SPANS.DURATION, v2.durationAsLong())
.set(Spans.SPANS.DEBUG, v2.debug())
.set(Spans.SPANS.SHARE, v2.shared())
.set(Spans.SPANS.LOCAL_SERVICE_NAME, v2.localServiceName())
.set(Spans.SPANS.LOCAL_IPV4, v2.localEndpoint().ipv4())
.set(Spans.SPANS.LOCAL_IPV6, v2.localEndpoint().ipv6())
.set(Spans.SPANS.LOCAL_PORT, v2.localEndpoint().port())
.set(Spans.SPANS.REMOTE_SERVICE_NAME, v2.remoteServiceName())
.set(Spans.SPANS.REMOTE_IPV4, v2.remoteEndpoint().ipv4())
.set(Spans.SPANS.REMOTE_IPV6, v2.remoteEndpoint().ipv6())
.set(Spans.SPANS.REMOTE_PORT, v2.remoteEndpoint().port());
inserts.add(insertSpan);
for (Annotation anno : v2.annotations()) {
InsertSetMoreStep<Record> insertSpanAnnotation = create
.insertInto(SpanAnnotations.SPAN_ANNOTATIONS)
.set(SpanAnnotations.SPAN_ANNOTATIONS.TRACE_ID, v2.traceId())
.set(SpanAnnotations.SPAN_ANNOTATIONS.ID, v2.traceId())
.set(SpanAnnotations.SPAN_ANNOTATIONS.A_TIMESTAMP, anno.timestamp())
.set(SpanAnnotations.SPAN_ANNOTATIONS.A_VALUE, anno.value());
inserts.add(insertSpanAnnotation);
}
for (Map.Entry<String, String> tag : v2.tags().entrySet()) {
InsertSetMoreStep<Record> insertSpanTag = create
.insertInto(SpanTags.SPAN_TAGS)
.set(SpanTags.SPAN_TAGS.TRACE_ID, v2.traceId())
.set(SpanTags.SPAN_TAGS.ID, v2.traceId())
.set(SpanTags.SPAN_TAGS.T_KEY, tag.getKey())
.set(SpanTags.SPAN_TAGS.T_VALUE, tag.getValue());
inserts.add(insertSpanTag);
}
}
create.batch(inserts).execute();
return null;
}
}
}
| java |
<gh_stars>0
package com.logginghub.logging.frontend.charting;
import com.logginghub.logging.frontend.analysis.ChunkedResult;
import com.logginghub.logging.frontend.charting.model.Stream;
import com.logginghub.logging.frontend.charting.model.StreamListener;
import com.logginghub.logging.frontend.charting.model.StreamResultItem;
import com.logginghub.logging.messages.AggregationType;
import com.logginghub.utils.Statistics;
import com.logginghub.utils.TimeUtils;
import com.logginghub.utils.logging.Logger;
import java.util.EnumSet;
public class NewAggregator implements StreamListener<StreamResultItem> {
private static final Logger logger = Logger.getLoggerFor(NewAggregator.class);
private long chunkInterval = 1000;
private long startOfCurrentChunk = -1;
private boolean generateMissingChunks = false;
// private Mode mode = Mode.Count;
private Statistics statistics = new Statistics();
private Stream<ChunkedResult> outputStream = new Stream<ChunkedResult>();
// private double value;
private double totalSum;
private double totalCount;
// private double count;
private EnumSet<AggregationType> publishingModes = EnumSet.allOf(AggregationType.class);
private String source;
private long lastData;
private double lastValue = Double.NaN;
private String label;
private String groupBy;
private String aggregationName;
public NewAggregator() {
}
public String getAggregationName() {
return aggregationName;
}
public String getGroupBy() {
return groupBy;
}
public String getLabel() {
return label;
}
public void setAggregationName(String aggregationName) {
this.aggregationName = aggregationName;
}
public void setGroupBy(String groupBy) {
this.groupBy = groupBy;
}
public void setLabel(String label) {
this.label = label;
}
public void setOutputStream(Stream<ChunkedResult> outputStream) {
this.outputStream = outputStream;
}
public Stream<ChunkedResult> getOutputStream() {
return outputStream;
}
// public void setMode(Mode mode)
// {
// this.mode = mode;
// }
public void update(long time, double value, String source) {
lastData = System.currentTimeMillis();
logger.fine("Updating chunk source {} with value {} at time {}", source, value, Logger.toDateString(time));
long chunkedTime = chunk(time);
if (startOfCurrentChunk == -1) {
startOfCurrentChunk = chunkedTime;
}
else {
if (chunkedTime > startOfCurrentChunk) {
flush();
if (generateMissingChunks) {
generateMissingChunks(time, label, source, groupBy);
}
startOfCurrentChunk = chunk(time);
}
else if (time < startOfCurrentChunk) {
// TODO : this might be bad, but most of the data goes back and
// forwards a bit...
// logger.warn(String.format("Time [%s] is before current chunk start [%s], is your source sequence out of order?",
// new Date(time).toLocaleString(),
// new Date(startOfCurrentChunk).toLocaleString()));
}
}
// Don't count NaNs as they represent chart gaps and should not be counted!
if (!Double.isNaN(value)) {
this.statistics.addValue(value);
this.lastValue = value;
this.totalSum += value;
this.totalCount++;
}
}
private void fireResult(ChunkedResult result) {
outputStream.send(result);
}
private void generateMissingChunks(long time, String label, String source, String groupBy) {
long startOfNextChunk = chunk(time);
long missingPeriods = ((startOfNextChunk - startOfCurrentChunk) / chunkInterval) - 1;
for (int i = 0; i < missingPeriods; i++) {
long chunkStart = startOfCurrentChunk + ((i + 1) * chunkInterval);
ChunkedResult gapResult = new ChunkedResult(chunkStart, chunkInterval, 0, "gap", label, groupBy, source);
fireResult(gapResult);
}
}
public long chunk(long time) {
return chunk(time, chunkInterval);
}
public static long chunk(long time, long chunkInterval) {
return TimeUtils.chunk(time, chunkInterval);
}
public void setChunkInterval(long chunkInterval) {
this.chunkInterval = chunkInterval;
}
public void setGenerateMissingChunks(boolean generateMissingChunks) {
this.generateMissingChunks = generateMissingChunks;
}
public double getValue(AggregationType mode) {
switch (mode) {
case Mean:
return statistics.calculateMean();
case Count:
return statistics.getCount();
case Sum:
return statistics.calculateSum();
case Median:
return statistics.calculateMedian();
case Mode:
return statistics.calculateMode();
case StandardDeviation:
return statistics.calculateStandardDeviationFast();
case Percentile90:
return statistics.calculatePercentile(90);
case TotalCount:
return totalCount;
case TotalSum:
return totalSum;
case LastValue:
return lastValue;
default:
throw new RuntimeException(String.format("Unsupported mode : " + mode));
}
}
public void reset() {
statistics = new Statistics();
// jshaw - we definitely dont want to reset the last value here!
// lastValue = Double.NaN;
}
public void complete() {
// TODO : maybe put other methods on the stream class?
// for (ChunkedResultHandler chunkedResultHandler : resultHandlers) {
// chunkedResultHandler.complete();
// }
}
public void setSource(String source) {
this.source = source;
}
public void tick() {
if (System.currentTimeMillis() - lastData > 1010) {
logger.fine("Generating empty tick for series");
update(System.currentTimeMillis(), Double.NaN, "");
}
}
public void flush() {
for (AggregationType mode : publishingModes) {
ChunkedResult result = new ChunkedResult(startOfCurrentChunk, chunkInterval, getValue(mode),mode.name(), label, groupBy, source /*
* +
* "/"
* +
* mode
*/);
result.setAggregationName(aggregationName);
logger.fine("Flushing time chunk result {}", result);
fireResult(result);
}
reset();
}
/**
* Similar to reset but this one sets us back to our completely empty state
*/
public void clear() {
reset();
startOfCurrentChunk = -1;
totalCount = 0;
totalSum = 0;
lastValue = Double.NaN;
}
public void setPublishingModes(EnumSet<AggregationType> publishingModes) {
this.publishingModes = publishingModes;
}
public void setPublishingModes(AggregationType... modes) {
EnumSet<AggregationType> set = EnumSet.noneOf(AggregationType.class);
for (AggregationType mode : modes) {
set.add(mode);
}
setPublishingModes(set);
}
public void parseInterval(String newValue) {}
@Override public void onNewItem(StreamResultItem t) {
update(t.getTime(), Double.parseDouble(t.getResult()), t.getPath());
}
}
| java |
<filename>flags/BQ-SA.js
import l from '../svg/l/BQ-SA.svg'
import m from '../svg/m/BQ-SA.svg'
import s from '../svg/s/BQ-SA.svg'
export default {l,m,s} | javascript |
<gh_stars>0
{
"caseDeterminationInstanceRecord" : {
"customerAgreement" : "customerAgreement",
"interestedPartyAgreement" : "interestedPartyAgreement",
"fraudCaseDeterminationRecord" : {},
"merchantAgreementReference" : "715221",
"interestedPartyAgreementReference" : "743054",
"customerAgreementReference" : "710856",
"merchantAgreement" : "merchantAgreement"
},
"caseDeterminationRetrieveActionTaskRecord" : {},
"caseDeterminationInstanceReport" : {
"caseDeterminationInstanceReport" : {},
"caseDeterminationInstanceReportRecord" : {},
"caseDeterminationInstanceReportType" : "caseDeterminationInstanceReportType",
"caseDeterminationInstanceReportParameters" : "caseDeterminationInstanceReportParameters"
},
"fraudResolutionInstanceRecord" : {
"date" : "09-22-2018",
"transactionRecord" : {},
"transactionReference" : "764045",
"contactReference" : "725202",
"caseLocation" : "caseLocation",
"fraudCaseType" : "fraudCaseType",
"interstedPartyReference" : "758612",
"productInstanceReference" : "724071",
"employeeBusinessUnitReference" : "750318",
"fraudCaseWorkProducts" : "fraudCaseWorkProducts",
"customerReference" : "784318",
"fraudCaseResolutionSchedule" : "fraudCaseResolutionSchedule",
"fraudCaseStatus" : "fraudCaseStatus",
"merchantReference" : "798993"
},
"caseDeterminationRetrieveActionTaskReference" : "CDRATR749568",
"caseDeterminationInstanceAnalysis" : {
"caseDeterminationInstanceAnalysisReportType" : "caseDeterminationInstanceAnalysisReportType",
"caseDeterminationInstanceAnalysisParameters" : "caseDeterminationInstanceAnalysisParameters",
"caseDeterminationInstanceAnalysisReport" : {},
"caseDeterminationInstanceAnalysisRecord" : {}
},
"caseDeterminationRetrieveActionResponse" : "caseDeterminationRetrieveActionResponse",
"caseAnalysisInstanceRecord" : {
"fraudCaseRootCause" : "fraudCaseRootCause"
}
} | json |
<filename>src/s2mTau.cpp<gh_stars>0
#define BIORBD_API_EXPORTS
#include "../include/s2mTau.h"
s2mTau::s2mTau(const s2mJoints &j) :
s2mVector(j.nbTau()){
}
s2mTau s2mTau::timeDerivativeActivation(const s2mTau &act){
// Implémentation de la fonction da/dt = (u-a)/tau(u,a)
// ou tau(u,a) = t_act(0.5+1.5*a) is u>a et tau(u,a)=t_deact(0.5+1.5*a) sinon
//double tauAct = .05;
double tauDeact = 0.01;
s2mTau actDot(this->rows());
//std::cout << "This = " << (*this).transpose() << std::endl;
//std::cout << "act = " << act.transpose() << std::endl;
for (unsigned int i=0; i<this->rows(); ++i){
if ((*this)(i) == 0)
actDot(i) = 0;
else{
double num = act(i) - (*this)(i) ;
// std::cout << "num = " << num << std::endl;
double denom;
// if (true || num>0 && act(i) > 0 || num<0 && act(i)<0 )
// denom = tauAct*(0.5+1.5* abs(act(i)));
// else
denom = tauDeact/(0.5+1.5* abs(act(i)));
// std::cout << "denom = " << denom << std::endl;
actDot(i) = num/denom;
// std::cout << actDot(i) << std::endl;
}
}
// std::cout << "actDot = " << actDot.transpose() << std::endl << std::endl ;
return actDot;
}
| cpp |
Unlike us, these Bollywood celebs do not need to go online to see cute cat or therapeutic dog videos every day. For they get their daily dose of cute and goofy from their beloved pets. Here are 10 pics of our favourite actors with their darling pooches and feline friends. But before you scroll down, can you guess who is a cat lover and who has an affinity for dogs? Hint: cat lovers are perceived to be introverts who keep things to themselves with a graceful demeanour whereas dog people tend to border on the extrovert with more agreeable personality traits.
| english |
<filename>schemaDocuments/core/applicationCommon/foundationCommon/crmCommon/sales/_allImports.1.4.cdm.json
{
"documentVersion": "1.3.2",
"jsonSchemaSemanticVersion": "1.0.0",
"imports": [
{
"corpusPath": "/core/cdsConcepts.1.0.1.cdm.json"
},
{
"corpusPath": "/core/wellKnownCDSAttributeGroups.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/PropertyInstance.1.3.cdm.json",
"moniker": "base_PropertyInstance"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/PriceListItem.1.3.cdm.json",
"moniker": "base_PriceListItem"
},
{
"corpusPath": "/core/applicationCommon/Currency.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/SLA.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/KnowledgeBaseRecord.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/Owner.1.1.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/Team.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/BusinessUnit.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/BookableResourceBookingHeader.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/ProductAssociation.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/Unit.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/PriceList.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/Organization.1.2.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/KnowledgeArticle.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/BookableResourceBooking.1.4.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/Product.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/crmCommon/Account.1.4.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/crmCommon/QuickCampaign.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/crmCommon/Lead.1.4.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/crmCommon/Activity.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/crmCommon/CampaignActivity.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/crmCommon/Contact.1.4.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/crmCommon/Campaign.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/crmCommon/service/Site.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/crmCommon/service/Case.1.4.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/crmCommon/service/Entitlement.1.4.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/crmCommon/service/User.1.3.cdm.json"
},
{
"corpusPath": "/core/applicationCommon/foundationCommon/crmCommon/service/Service.1.3.cdm.json"
},
{
"corpusPath": "Competitor.1.3.cdm.json"
},
{
"corpusPath": "DiscountList.1.3.cdm.json"
},
{
"corpusPath": "Invoice.1.4.cdm.json"
},
{
"corpusPath": "InvoiceProduct.1.4.cdm.json"
},
{
"corpusPath": "Opportunity.1.4.cdm.json"
},
{
"corpusPath": "OpportunityProduct.1.4.cdm.json"
},
{
"corpusPath": "Order.1.4.cdm.json"
},
{
"corpusPath": "OrderProduct.1.4.cdm.json"
},
{
"corpusPath": "Quote.1.4.cdm.json"
},
{
"corpusPath": "QuoteProduct.1.4.cdm.json"
},
{
"corpusPath": "SalesLiterature.1.3.cdm.json"
}
]
} | json |
{"relation": [["", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], ["Name", "Batman (Theme)", "How Do I Live Without You", "<NAME> (Theme)", "Chicken Dance (The Birdie Song)", "Lullaby", "How Do I Live Without You", "Moonlight Sonata, 1st Movement", "Be Thou My Vision", "Jesus, Remember Me", "Do They Know It's Christmas Time"], ["Album", "Party Music - The Ultimate Birthday Party Album!", "My Valentine - Great Love Songs", "Party Music - The Ultimate Birthday Party Album!", "Party Music - The Ultimate Birthday Party Album!", "Classical Dreams", "Great Love Songs", "Classical Dreams", "50 Golden Hymns, Vol. 3 - Great Is Thy Faithfulness (Instrumental)", "Jesus Remember Me - Taize Songs", "Christmas Party"], ["Time", "1:38", "4:02", "2:49", "2:19", "1:46", "4:02", "5:51", "4:40", "3:04", "3:36"], ["Price", "$0.99", "$0.99", "$0.99", "$0.99", "$0.99", "$0.99", "$0.99", "$0.99", "$0.99", "$0.99"], ["", "View In iTunes", "View In iTunes", "View In iTunes", "View In iTunes", "View In iTunes", "View In iTunes", "View In iTunes", "View In iTunes", "View In iTunes", "View In iTunes"]], "pageTitle": "iTunes - Music - Creations Praise Classics (Favourite Classical Music Accompanied by the Sounds of Nature) by The London Fox Players & The London Fox Orchestra", "title": "", "url": "https://itunes.apple.com/us/album/traumerei-springtime-birds/id494263388?i=494263479", "hasHeader": true, "headerPosition": "FIRST_ROW", "tableType": "RELATION", "tableNum": 2, "s3Link": "common-crawl/crawl-data/CC-MAIN-2015-32/segments/1438042988458.74/warc/CC-MAIN-20150728002308-00049-ip-10-236-191-2.ec2.internal.warc.gz", "recordEndOffset": 879768467, "recordOffset": 879744293, "tableOrientation": "HORIZONTAL", "TableContextTimeStampAfterTable": "{106817=Copyright \u00a9 2014 Apple Inc. All rights reserved.}", "lastModified": "Sat, 01 Aug 2015 03:59:30 GMT", "textBeforeTable": "View In iTunes Smart Baby - The Music of Bach (from The Mother & Child Collection) 5. View In iTunes Hymn Styles: Cello Hymns 4. View In iTunes Kids Sing Christmas - 39 Popular Carols and Songs (Split Track) + 13 Christmas Stories", "textAfterTable": "Listeners Also Bought Blessings Laura Story View In iTunes \u00a0 Name Album Artist Time Price \u00a0 1 Oceans (Where Feet May Fail)", "hasKeyColumn": true, "keyColumnIndex": 1, "headerRowIndex": 0} | json |
<reponame>object1037/blog
export interface anchorProps {
href: string
children: string
}
export default function Anchor(props: anchorProps) {
return (
<a target="_blank" rel="noopener noreferrer" className="text-ppink-300 dark:text-ppink-200 hover:underline" href={props.href}>
{props.children}
</a>
)
} | typescript |
For his extraordinary work in manufacturing and distributing vaccinations, Cyrus Poonawalla is known as one of the 'seven vaccine heroes of the world.'
The University of Massachusetts recently awarded Cyrus Poonawalla, the business tycoon from Pune an honorary degree. A big name in the medical industry, Poonawalla became the first Indian to be conferred the ‘Doctor of Humane Letters’ by the academic institution for his outstanding work in the field of vaccination.
Here are seven things you must know about the Pune businessman.
1. He is the chairman of the Poonawalla group, and the Serum Institute of India and the Indian Biotech Company (manufacturers of paediatric vaccines) come under the Poonawalla group umbrella.
3. In a speech after being conferred the degree, Poonawalla said, “Ever since the Serum Institute was established, our primary goal has been to make life-saving vaccinations available at the most affordable costs to the masses.” The list of vaccines supplied by the Serum Institute of India includes vaccines for Diptheria, H1N1 (Swine flu), measles, anti-rabies, Hepatitis, Tetanus etc.
So, some of the most common diseases, as well as the uncommon ones are treated with the help of vaccinations manufactured by Poonawalla’s institutes.
4. The institute, in collaboration with the US-based MassBiologics of the University of Massachusetts Medical School, has co-developed a fast-acting anti-rabies agent called the Rabies Human Monoclonal Antibody (RMAb).
You may also like: AIIMS Doctors To Visit Old-Age Homes For Free Cancer Check-Ups & Vaccinations!
5. The Serum Institute is the largest vaccine manufacturer in the world, in accordance to the number of vaccines produced and sold. Accredited with the World Health Organisation, the institute sells vaccines in about 170 countries.
(Edited by Gayatri Mishra)
Like this story? Or have something to share?
Connect with us on Facebook and Twitter.
We bring stories straight from the heart of India, to inspire millions and create a wave of impact. Our positive movement is growing bigger everyday, and we would love for you to join it.
Please contribute whatever you can, every little penny helps our team in bringing you more stories that support dreams and spread hope.
| english |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.