content
stringlengths
10
4.9M
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import { SeverityLevel } from './Contracts/Generated/SeverityLevel' import { IPartC } from './IPartC'; export interface ITraceTelemetry extends IPartC { /** * @description A message string * @type {string} * @memberof ITraceTelemetry */ message: string; /** * @description Severity level of the logging message used for filtering in the portal * @type {SeverityLevel} * @memberof ITraceTelemetry */ severityLevel?: SeverityLevel; }
#include "raw.h" #include <signal.h> #include <stdio.h> #include "util.h" volatile sig_atomic_t terminate; static void on_signal(int s) { terminate = 1; } static void dump(uint8_t *frame, size_t len, void *arg) { fprintf(stderr, "%s: receive %zu octets\n", (char *)arg, len); hexdump(stderr, frame, len); } int main(int argc, char const *argv[]) { char *name = "tap1"; struct rawdev *dev; uint8_t addr[6]; signal(SIGINT, on_signal); dev = rawdev_alloc(RAWDEV_TYPE_AUTO, name); if (dev == NULL) { fprintf(stderr, "rawdev_alloc(): error\n"); return -1; } if (dev->ops->open(dev) == -1) { fprintf(stderr, "dev->ops->open(): failure - (%s)\n", dev->name); return -1; } dev->ops->addr(dev, addr, sizeof(addr)); fprintf(stderr, "[%s] %02x:%02x:%02x:%02x:%02x:%02x\n", name, addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); while (!terminate) { dev->ops->rx(dev, dump, dev, 1000); } dev->ops->close(dev); printf("closed"); return 0; }
<filename>ml_proj_init/config.py """ A module for defining the config parameters globally """ import os import string current_abs_path = os.path.split(os.path.realpath(__file__))[0] #print(current_abs_path) configs = {} configs["run_name_choices"] = ["c", "a", "A", "C"] configs["valid_proj_type"] = ["ml", "dl", "ML", "DL"] configs["data_loader_types"] = ["img", "text", "csv", "IMG", "TEXT", "CSV"] configs["nn_architecture_types"] = ["cnn", "lstm", "nn", "CNN", "LSTM", "NN"] configs["proj_name_first_char"] = string.ascii_lowercase configs["proj_name_allowed_char"] = string.ascii_lowercase + string.digits + "_" + "-" configs["proj_name_length"] = 80 configs["ml_template_path"] = os.path.join(current_abs_path, "data/ml") configs["dl_template_path"] = os.path.join(current_abs_path, "data/dl") configs["data_loader_path"] = os.path.join(current_abs_path, "data/loader") configs["network_template_path"] = os.path.join(current_abs_path, "data/network") if __name__ == "__main__": print(configs["proj_name_first_char"]) print(configs["proj_name_allowed_char"])
<reponame>ca0v/react-lab<filename>components/packets/common.ts declare var requirejs; import * as geom from "@ol/geom"; import * as extent from "@ol/extent"; import type { Polygon } from "@ol/geom"; type Continents = any; const ol = { geom, extent, }; import { BingImagerySet, OtherImagerySet } from "../openlayers"; export interface IGeoJsonFeature<T> { type: string; properties: T; geometry: { type: string; coordinates: any; }; } export interface IPacket<T> { type: string; url: string | string[]; name: string; // primaryFieldName style?: (score: number) => BingImagerySet | OtherImagerySet; weight?: (d: IGeoJsonFeature<T>) => number; filter?: (Promise<(d: IGeoJsonFeature<T>, score: number) => boolean>) | ((d: IGeoJsonFeature<T>, score: number) => boolean); score?: number; } export interface IGeoJson<T> { type: "FeatureCollection"; features: Array<IGeoJsonFeature<T>>; } function asGeom(geometry: { type: string; coordinates: any }) { let hack: any = ol.geom; let geom = new hack[geometry.type](geometry.coordinates, "XY"); return geom; } export async function filterByContinent(name: string) { let continents: Continents | null = null; return new Promise<(g: IGeoJsonFeature<any>) => boolean>( async (good, bad) => { const data = await fetch("./data/continents.json"); continents = await data.json(); let europe = continents.features.filter( (f) => f.properties.CONTINENT === name )[0]; if (!europe) return bad("unknown continent"); const continent: Polygon = asGeom(europe.geometry); const filter = (f: IGeoJsonFeature<any>) => { const country: Polygon = asGeom(f.geometry); const points = country.getFlatCoordinates(); let count = 0; for (let i = 0; i < points.length; i += 2) { const [x, y] = [points[i], points[i + 1]]; count += continent.containsXY(x, y) ? 1 : 0; } // at least half are within continent return count > points.length / 2 / 4; }; good(filter); } ); }
Elon Musk is being targeted by the conservative political action committee, Citizens for the Republic. The group's so-called Sunlight Project is behind an incendiary lobbying campaign and website called, "Stop Elon Musk from Failing Again," with a mission of divesting the Tesla/SpaceX/SolarCity boss from federal clean energy subsidies. Musk himself has tweeted about the recent rash of attacks. According to the Washington Examiner, the campaign was launched a few days before Tesla's recently approved merger with sister company SolarCity. "The Musk empire appears to be nothing more than a collection of failing startups and plummeting stock options," Citizens for the Republic said in a statement to the Washington Examiner. "Even the once-touted SolarCity had to be bought out by Tesla" to survive. "Following the victory of President-elect Donald Trump and a majority of Republicans in the House and Senate, government corruption and spending abuse at all levels must end," the group added in reference to Musk's subsidies. The "Stop Elon" website is a giant hit piece on Musk's several companies and his endeavors. Its about page states: "Elon Musk has defrauded the American Taxpayer out of over $4.9 Billion in the form of subsidies, grants, and other favors. We are challenging not just Elon, but the entire culture of corporations making billions of dollars off of the American people for almost zero return to the consumer. CEO's like Musk are taking advantage of Americans, and it is our intention to end their free ride." The $4.9 billion figure stems from a debunked Los Angeles Times story. While Musk said that government subsidies are "helpful" they are also "not necessary" for his company to run. He pointed out that $4.9 billion is from "adding up everything that's ever happened and including things that will take the next 20 years." Musk suggested that the Times report was planted after the International Monetary Fund's staggering report that the fossil fuel industry receives more than $5 trillion in subsidies a year. During a talk in May, the sustainable transport/clean energy advocate urged a revolt against Big Energy for allegedly feeding negative stories about his work to the press. "We need to appeal to the people—educate people to sort of revolt against this and to fight the propaganda of the fossil fuel industry which is unrelenting and enormous," Musk said. On its website, the misleadingly titled Sunlight Project considers the solar industry "Big Energy," calling it a pet project of "the Obama Administration and those who claim to care about the environment." It accuses Washington of funneling millions in tax credits to solar companies "despite posting losses year after year." (Actually, the solar industry has reported record-breaking growth in recent years). Several new reports have determined that the anti-solar/anti-Musk campaign has dubious ties with conservative interests and Big Energy lobbyists. Electrek writer Fred Lambert reported that Citizens for the Republic, which was first launched by Ronald Reagan in the 1970s and later dismantled, is now spearheaded by none other than conservative radio host and climate change denier Laura Ingraham. Ingraham, a top Donald Trump surrogate, happens to be in the running for press secretary under the Trump administration. The Drive's Liane Yvkoff also reported that Citizens for the Republic's board members Craig Shirley and Diane Banister are partners of the right-wing public relations firm Shirley and Banister Public Affairs, that has represented the National Rifle Association, commentator Ann Coulter and the Tea Party Patriots. Posts on "Stop Elon Musk From Failing" are authored by someone called "stopelon," the same user name on Alt Left Watch, which also happens to be managed by the PR company. Not only that, Yvkoff noted that Shirley has previously lobbied for Citizens for State Power that "actively fought deregulation of utilities—in the years 1999, 2000, and 2001." The Washington Post revealed that utility companies secretly funded millions to Citizens for State Power to lobby Congress for energy deregulation. Shirley served on the board of the United Seniors Association that lobbied on behalf of the Republican party for energy deregulation in 2000, according to Public Citizen. According to Yvkoff, Citizens for State Power and Stop Elon Musk From Failing "probably isn't a personal project of Craig Shirley or Diane Banister, and is more likely to be supported by energy companies that want to end the tax credits that help Tesla and other renewable energy companies build infrastructure." However, when Bloomberg asked Banister if oil companies are contributing to the campaign, she responded, "We reached out to them [for donations], but they haven't responded.'" The Sunlight Project produced a video that delves into their overall mission and touts the tagline, "We believe sunlight is the best disinfectant." The clip features Shirley as well as Heartland Institute-approved Greg E. Walcher, the president of the Natural Resources Group and the former executive director of the Colorado Department of Natural Resources. In 2004, The League of Conservation Voters added Walcher to their "Dirty Dozen" list of anti-environmental candidates during his run for Congress in Colorado's 3rd District. Walcher boasts on his resume that he "helped forge a compromise and approval that allowed new technology to access oil shale in the Piceance Basin, leading to the first practical oil shale production in 30 years."
package group // Values clause. type Values struct { elementReindenter } func NewValues(element []Reindenter, opts ...Option) *Values { return &Values{ elementReindenter: newElementReindenter(element, opts...), } }
/** * Method for building trie in-memory structure, and writing it out * using given output stream. * * @param out Output stream to write trie structure to */ @Override public void buildAndWrite(OutputStream out, boolean writeHeader) throws IOException { TrieNode<T> root = build(); byte[] tmpBuffer = new byte[ClosedTrieNode.MINIMUM_TEMP_BUFFER_LENGTH]; if (writeHeader) { System.out.println("Payload length: "+root.length()); int headerLen = TrieHeader.fillHeaderInfo(tmpBuffer, TrieHeader.ValueType.VINT, root.length()); out.write(tmpBuffer, 0, headerLen); } root.serializeTo(out, tmpBuffer); out.flush(); }
"""Implements the FilePositionMarker class. This class is a construct to keep track of positions within a file. """ from collections import namedtuple protoFilePositionMarker = namedtuple('FilePositionMarker', ['statement_index', 'line_no', 'line_pos', 'char_pos']) class FilePositionMarker(protoFilePositionMarker): """This class is a construct to keep track of positions within a file.""" def advance_by(self, raw="", idx=0): """Construct a new `FilePositionMarker` at a point ahead of this one. Args: raw (:obj:`str`): The string to indicate how we should advance the position. idx (:obj:`int`, optional): The statement index to advance by. """ stmt = self.statement_index line = self.line_no pos = self.line_pos char_pos = self.char_pos for elem in raw: char_pos += 1 if elem == '\n': line += 1 pos = 1 else: pos += 1 return FilePositionMarker(stmt + idx, line, pos, char_pos) @classmethod def from_fresh(cls): """Construct a fresh position marker. This should be the default way of creating a new postion marker, and is where we define what the `start` of a file looks like. """ return cls(1, 1, 1, 0) def __str__(self): return "[{0}]({1}, {2}, {3})".format( self.char_pos, self.statement_index, self.line_no, self.line_pos) def __gt__(self, other): return self.char_pos > other.char_pos def __lt__(self, other): return self.char_pos < other.char_pos def __eq__(self, other): return ((self.statement_index == other.statement_index) and (self.line_no == other.line_no) and (self.line_pos == other.line_pos) and (self.char_pos == other.char_pos))
/** * Tells if the option requires more arguments to be valid. * * @return false if the option doesn't require more arguments * @since 1.3 */ boolean requiresArg() { if (optionalArg) { return false; } if (argCount == UNLIMITED_VALUES) { return values.isEmpty(); } return acceptsArg(); }
/** * This class was generated by Ali-Generator * @author bang */ public class ActionExample { /** * * @mbg.generated */ protected String orderByClause; /** * * @mbg.generated */ @Deprecated protected boolean distinct; /** * * @mbg.generated */ protected boolean page; /** * * @mbg.generated */ protected int pageIndex; /** * * @mbg.generated */ protected int pageSize; /** * * @mbg.generated */ protected int pageStart; /** * * @mbg.generated */ protected String distinctSql; /** * * @mbg.generated */ protected List<Criteria> oredCriteria; /** * * @mbg.generated */ public ActionExample() { oredCriteria = new ArrayList<Criteria>(); } /** * @param orderCondition * @param sortType * @return * * @mbg.generated */ public ActionExample appendOrderByClause(OrderCondition orderCondition, SortType sortType) { if (null != orderByClause) { orderByClause = orderByClause + ", " + orderCondition.getColumnName() + " " + sortType.getValue(); } else { orderByClause = orderCondition.getColumnName() + " " + sortType.getValue(); } return this; } /** * @return * * @mbg.generated */ public String getOrderByClause() { return orderByClause; } /** * @param distinct * * @mbg.generated */ @Deprecated public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * @return * * @mbg.generated */ @Deprecated public boolean isDistinct() { return distinct; } /** * @param page * @return * * @mbg.generated */ public ActionExample setPage(boolean page) { this.page = page; return this; } /** * @return * * @mbg.generated */ public boolean isPage() { return page; } /** * @return * * @mbg.generated */ public int getPageIndex() { return pageIndex; } /** * @param pageSize * @return * * @mbg.generated */ public ActionExample setPageSize(int pageSize) { this.pageSize = pageSize < 1 ? 10 : pageSize; this.pageIndex = pageStart < 1 ? 0 : (pageStart - 1) * this.pageSize; return this; } /** * @return * * @mbg.generated */ public int getPageSize() { return pageSize; } /** * @param pageStart * @return * * @mbg.generated */ public ActionExample setPageStart(int pageStart) { this.pageStart = pageStart < 1 ? 1 : pageStart; this.pageIndex = (this.pageStart - 1) * this.pageSize; return this; } /** * @return * * @mbg.generated */ public int getPageStart() { return pageStart; } /** * @param pageStart * @param pageSize * * @mbg.generated */ public void setPagination(int pageStart, int pageSize) { this.page = true; this.pageSize = pageSize < 1 ? 10 : pageSize; this.pageIndex = pageStart < 1 ? 0 : (pageStart - 1) * this.pageSize; } /** * @param condition * @return * * @mbg.generated */ public ActionExample appendDistinct(OrderCondition condition) { if (null != distinctSql){ distinctSql = distinctSql + ", " + condition.getColumnName(); } else { distinctSql = condition.getColumnName(); } return this; } /** * @return * * @mbg.generated */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * @param criteria * * @mbg.generated */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * @return * * @mbg.generated */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * @return * * @mbg.generated */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * @return * * @mbg.generated */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * * @mbg.generated */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * * @mbg.generated */ protected abstract static class AbstractGeneratedCriteria { protected List<Criterion> criteria; protected AbstractGeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Long> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Long> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andAppCodeIsNull() { addCriterion("app_code is null"); return (Criteria) this; } public Criteria andAppCodeIsNotNull() { addCriterion("app_code is not null"); return (Criteria) this; } public Criteria andAppCodeEqualTo(String value) { addCriterion("app_code =", value, "appCode"); return (Criteria) this; } public Criteria andAppCodeNotEqualTo(String value) { addCriterion("app_code <>", value, "appCode"); return (Criteria) this; } public Criteria andAppCodeGreaterThan(String value) { addCriterion("app_code >", value, "appCode"); return (Criteria) this; } public Criteria andAppCodeGreaterThanOrEqualTo(String value) { addCriterion("app_code >=", value, "appCode"); return (Criteria) this; } public Criteria andAppCodeLessThan(String value) { addCriterion("app_code <", value, "appCode"); return (Criteria) this; } public Criteria andAppCodeLessThanOrEqualTo(String value) { addCriterion("app_code <=", value, "appCode"); return (Criteria) this; } public Criteria andAppCodeLike(String value) { addCriterion("app_code like", value, "appCode"); return (Criteria) this; } public Criteria andAppCodeNotLike(String value) { addCriterion("app_code not like", value, "appCode"); return (Criteria) this; } public Criteria andAppCodeIn(List<String> values) { addCriterion("app_code in", values, "appCode"); return (Criteria) this; } public Criteria andAppCodeNotIn(List<String> values) { addCriterion("app_code not in", values, "appCode"); return (Criteria) this; } public Criteria andAppCodeBetween(String value1, String value2) { addCriterion("app_code between", value1, value2, "appCode"); return (Criteria) this; } public Criteria andAppCodeNotBetween(String value1, String value2) { addCriterion("app_code not between", value1, value2, "appCode"); return (Criteria) this; } public Criteria andActionIdIsNull() { addCriterion("action_id is null"); return (Criteria) this; } public Criteria andActionIdIsNotNull() { addCriterion("action_id is not null"); return (Criteria) this; } public Criteria andActionIdEqualTo(Long value) { addCriterion("action_id =", value, "actionId"); return (Criteria) this; } public Criteria andActionIdNotEqualTo(Long value) { addCriterion("action_id <>", value, "actionId"); return (Criteria) this; } public Criteria andActionIdGreaterThan(Long value) { addCriterion("action_id >", value, "actionId"); return (Criteria) this; } public Criteria andActionIdGreaterThanOrEqualTo(Long value) { addCriterion("action_id >=", value, "actionId"); return (Criteria) this; } public Criteria andActionIdLessThan(Long value) { addCriterion("action_id <", value, "actionId"); return (Criteria) this; } public Criteria andActionIdLessThanOrEqualTo(Long value) { addCriterion("action_id <=", value, "actionId"); return (Criteria) this; } public Criteria andActionIdIn(List<Long> values) { addCriterion("action_id in", values, "actionId"); return (Criteria) this; } public Criteria andActionIdNotIn(List<Long> values) { addCriterion("action_id not in", values, "actionId"); return (Criteria) this; } public Criteria andActionIdBetween(Long value1, Long value2) { addCriterion("action_id between", value1, value2, "actionId"); return (Criteria) this; } public Criteria andActionIdNotBetween(Long value1, Long value2) { addCriterion("action_id not between", value1, value2, "actionId"); return (Criteria) this; } public Criteria andElementIdIsNull() { addCriterion("element_id is null"); return (Criteria) this; } public Criteria andElementIdIsNotNull() { addCriterion("element_id is not null"); return (Criteria) this; } public Criteria andElementIdEqualTo(String value) { addCriterion("element_id =", value, "elementId"); return (Criteria) this; } public Criteria andElementIdNotEqualTo(String value) { addCriterion("element_id <>", value, "elementId"); return (Criteria) this; } public Criteria andElementIdGreaterThan(String value) { addCriterion("element_id >", value, "elementId"); return (Criteria) this; } public Criteria andElementIdGreaterThanOrEqualTo(String value) { addCriterion("element_id >=", value, "elementId"); return (Criteria) this; } public Criteria andElementIdLessThan(String value) { addCriterion("element_id <", value, "elementId"); return (Criteria) this; } public Criteria andElementIdLessThanOrEqualTo(String value) { addCriterion("element_id <=", value, "elementId"); return (Criteria) this; } public Criteria andElementIdLike(String value) { addCriterion("element_id like", value, "elementId"); return (Criteria) this; } public Criteria andElementIdNotLike(String value) { addCriterion("element_id not like", value, "elementId"); return (Criteria) this; } public Criteria andElementIdIn(List<String> values) { addCriterion("element_id in", values, "elementId"); return (Criteria) this; } public Criteria andElementIdNotIn(List<String> values) { addCriterion("element_id not in", values, "elementId"); return (Criteria) this; } public Criteria andElementIdBetween(String value1, String value2) { addCriterion("element_id between", value1, value2, "elementId"); return (Criteria) this; } public Criteria andElementIdNotBetween(String value1, String value2) { addCriterion("element_id not between", value1, value2, "elementId"); return (Criteria) this; } public Criteria andActionTypeIsNull() { addCriterion("action_type is null"); return (Criteria) this; } public Criteria andActionTypeIsNotNull() { addCriterion("action_type is not null"); return (Criteria) this; } public Criteria andActionTypeEqualTo(String value) { addCriterion("action_type =", value, "actionType"); return (Criteria) this; } public Criteria andActionTypeNotEqualTo(String value) { addCriterion("action_type <>", value, "actionType"); return (Criteria) this; } public Criteria andActionTypeGreaterThan(String value) { addCriterion("action_type >", value, "actionType"); return (Criteria) this; } public Criteria andActionTypeGreaterThanOrEqualTo(String value) { addCriterion("action_type >=", value, "actionType"); return (Criteria) this; } public Criteria andActionTypeLessThan(String value) { addCriterion("action_type <", value, "actionType"); return (Criteria) this; } public Criteria andActionTypeLessThanOrEqualTo(String value) { addCriterion("action_type <=", value, "actionType"); return (Criteria) this; } public Criteria andActionTypeLike(String value) { addCriterion("action_type like", value, "actionType"); return (Criteria) this; } public Criteria andActionTypeNotLike(String value) { addCriterion("action_type not like", value, "actionType"); return (Criteria) this; } public Criteria andActionTypeIn(List<String> values) { addCriterion("action_type in", values, "actionType"); return (Criteria) this; } public Criteria andActionTypeNotIn(List<String> values) { addCriterion("action_type not in", values, "actionType"); return (Criteria) this; } public Criteria andActionTypeBetween(String value1, String value2) { addCriterion("action_type between", value1, value2, "actionType"); return (Criteria) this; } public Criteria andActionTypeNotBetween(String value1, String value2) { addCriterion("action_type not between", value1, value2, "actionType"); return (Criteria) this; } public Criteria andActionNameIsNull() { addCriterion("action_name is null"); return (Criteria) this; } public Criteria andActionNameIsNotNull() { addCriterion("action_name is not null"); return (Criteria) this; } public Criteria andActionNameEqualTo(String value) { addCriterion("action_name =", value, "actionName"); return (Criteria) this; } public Criteria andActionNameNotEqualTo(String value) { addCriterion("action_name <>", value, "actionName"); return (Criteria) this; } public Criteria andActionNameGreaterThan(String value) { addCriterion("action_name >", value, "actionName"); return (Criteria) this; } public Criteria andActionNameGreaterThanOrEqualTo(String value) { addCriterion("action_name >=", value, "actionName"); return (Criteria) this; } public Criteria andActionNameLessThan(String value) { addCriterion("action_name <", value, "actionName"); return (Criteria) this; } public Criteria andActionNameLessThanOrEqualTo(String value) { addCriterion("action_name <=", value, "actionName"); return (Criteria) this; } public Criteria andActionNameLike(String value) { addCriterion("action_name like", value, "actionName"); return (Criteria) this; } public Criteria andActionNameNotLike(String value) { addCriterion("action_name not like", value, "actionName"); return (Criteria) this; } public Criteria andActionNameIn(List<String> values) { addCriterion("action_name in", values, "actionName"); return (Criteria) this; } public Criteria andActionNameNotIn(List<String> values) { addCriterion("action_name not in", values, "actionName"); return (Criteria) this; } public Criteria andActionNameBetween(String value1, String value2) { addCriterion("action_name between", value1, value2, "actionName"); return (Criteria) this; } public Criteria andActionNameNotBetween(String value1, String value2) { addCriterion("action_name not between", value1, value2, "actionName"); return (Criteria) this; } public Criteria andActionLabelIsNull() { addCriterion("action_label is null"); return (Criteria) this; } public Criteria andActionLabelIsNotNull() { addCriterion("action_label is not null"); return (Criteria) this; } public Criteria andActionLabelEqualTo(String value) { addCriterion("action_label =", value, "actionLabel"); return (Criteria) this; } public Criteria andActionLabelNotEqualTo(String value) { addCriterion("action_label <>", value, "actionLabel"); return (Criteria) this; } public Criteria andActionLabelGreaterThan(String value) { addCriterion("action_label >", value, "actionLabel"); return (Criteria) this; } public Criteria andActionLabelGreaterThanOrEqualTo(String value) { addCriterion("action_label >=", value, "actionLabel"); return (Criteria) this; } public Criteria andActionLabelLessThan(String value) { addCriterion("action_label <", value, "actionLabel"); return (Criteria) this; } public Criteria andActionLabelLessThanOrEqualTo(String value) { addCriterion("action_label <=", value, "actionLabel"); return (Criteria) this; } public Criteria andActionLabelLike(String value) { addCriterion("action_label like", value, "actionLabel"); return (Criteria) this; } public Criteria andActionLabelNotLike(String value) { addCriterion("action_label not like", value, "actionLabel"); return (Criteria) this; } public Criteria andActionLabelIn(List<String> values) { addCriterion("action_label in", values, "actionLabel"); return (Criteria) this; } public Criteria andActionLabelNotIn(List<String> values) { addCriterion("action_label not in", values, "actionLabel"); return (Criteria) this; } public Criteria andActionLabelBetween(String value1, String value2) { addCriterion("action_label between", value1, value2, "actionLabel"); return (Criteria) this; } public Criteria andActionLabelNotBetween(String value1, String value2) { addCriterion("action_label not between", value1, value2, "actionLabel"); return (Criteria) this; } public Criteria andNodeIsNull() { addCriterion("node is null"); return (Criteria) this; } public Criteria andNodeIsNotNull() { addCriterion("node is not null"); return (Criteria) this; } public Criteria andNodeEqualTo(String value) { addCriterion("node =", value, "node"); return (Criteria) this; } public Criteria andNodeNotEqualTo(String value) { addCriterion("node <>", value, "node"); return (Criteria) this; } public Criteria andNodeGreaterThan(String value) { addCriterion("node >", value, "node"); return (Criteria) this; } public Criteria andNodeGreaterThanOrEqualTo(String value) { addCriterion("node >=", value, "node"); return (Criteria) this; } public Criteria andNodeLessThan(String value) { addCriterion("node <", value, "node"); return (Criteria) this; } public Criteria andNodeLessThanOrEqualTo(String value) { addCriterion("node <=", value, "node"); return (Criteria) this; } public Criteria andNodeLike(String value) { addCriterion("node like", value, "node"); return (Criteria) this; } public Criteria andNodeNotLike(String value) { addCriterion("node not like", value, "node"); return (Criteria) this; } public Criteria andNodeIn(List<String> values) { addCriterion("node in", values, "node"); return (Criteria) this; } public Criteria andNodeNotIn(List<String> values) { addCriterion("node not in", values, "node"); return (Criteria) this; } public Criteria andNodeBetween(String value1, String value2) { addCriterion("node between", value1, value2, "node"); return (Criteria) this; } public Criteria andNodeNotBetween(String value1, String value2) { addCriterion("node not between", value1, value2, "node"); return (Criteria) this; } public Criteria andEntityTypeIsNull() { addCriterion("entity_type is null"); return (Criteria) this; } public Criteria andEntityTypeIsNotNull() { addCriterion("entity_type is not null"); return (Criteria) this; } public Criteria andEntityTypeEqualTo(String value) { addCriterion("entity_type =", value, "entityType"); return (Criteria) this; } public Criteria andEntityTypeNotEqualTo(String value) { addCriterion("entity_type <>", value, "entityType"); return (Criteria) this; } public Criteria andEntityTypeGreaterThan(String value) { addCriterion("entity_type >", value, "entityType"); return (Criteria) this; } public Criteria andEntityTypeGreaterThanOrEqualTo(String value) { addCriterion("entity_type >=", value, "entityType"); return (Criteria) this; } public Criteria andEntityTypeLessThan(String value) { addCriterion("entity_type <", value, "entityType"); return (Criteria) this; } public Criteria andEntityTypeLessThanOrEqualTo(String value) { addCriterion("entity_type <=", value, "entityType"); return (Criteria) this; } public Criteria andEntityTypeLike(String value) { addCriterion("entity_type like", value, "entityType"); return (Criteria) this; } public Criteria andEntityTypeNotLike(String value) { addCriterion("entity_type not like", value, "entityType"); return (Criteria) this; } public Criteria andEntityTypeIn(List<String> values) { addCriterion("entity_type in", values, "entityType"); return (Criteria) this; } public Criteria andEntityTypeNotIn(List<String> values) { addCriterion("entity_type not in", values, "entityType"); return (Criteria) this; } public Criteria andEntityTypeBetween(String value1, String value2) { addCriterion("entity_type between", value1, value2, "entityType"); return (Criteria) this; } public Criteria andEntityTypeNotBetween(String value1, String value2) { addCriterion("entity_type not between", value1, value2, "entityType"); return (Criteria) this; } public Criteria andEntityValueIsNull() { addCriterion("entity_value is null"); return (Criteria) this; } public Criteria andEntityValueIsNotNull() { addCriterion("entity_value is not null"); return (Criteria) this; } public Criteria andEntityValueEqualTo(String value) { addCriterion("entity_value =", value, "entityValue"); return (Criteria) this; } public Criteria andEntityValueNotEqualTo(String value) { addCriterion("entity_value <>", value, "entityValue"); return (Criteria) this; } public Criteria andEntityValueGreaterThan(String value) { addCriterion("entity_value >", value, "entityValue"); return (Criteria) this; } public Criteria andEntityValueGreaterThanOrEqualTo(String value) { addCriterion("entity_value >=", value, "entityValue"); return (Criteria) this; } public Criteria andEntityValueLessThan(String value) { addCriterion("entity_value <", value, "entityValue"); return (Criteria) this; } public Criteria andEntityValueLessThanOrEqualTo(String value) { addCriterion("entity_value <=", value, "entityValue"); return (Criteria) this; } public Criteria andEntityValueLike(String value) { addCriterion("entity_value like", value, "entityValue"); return (Criteria) this; } public Criteria andEntityValueNotLike(String value) { addCriterion("entity_value not like", value, "entityValue"); return (Criteria) this; } public Criteria andEntityValueIn(List<String> values) { addCriterion("entity_value in", values, "entityValue"); return (Criteria) this; } public Criteria andEntityValueNotIn(List<String> values) { addCriterion("entity_value not in", values, "entityValue"); return (Criteria) this; } public Criteria andEntityValueBetween(String value1, String value2) { addCriterion("entity_value between", value1, value2, "entityValue"); return (Criteria) this; } public Criteria andEntityValueNotBetween(String value1, String value2) { addCriterion("entity_value not between", value1, value2, "entityValue"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(String value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(String value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(String value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(String value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(String value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(String value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusLike(String value) { addCriterion("status like", value, "status"); return (Criteria) this; } public Criteria andStatusNotLike(String value) { addCriterion("status not like", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<String> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<String> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(String value1, String value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(String value1, String value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Long value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Long value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Long value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Long value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Long value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Long value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Long> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Long> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Long value1, Long value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Long value1, Long value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andStartTimeIsNull() { addCriterion("start_time is null"); return (Criteria) this; } public Criteria andStartTimeIsNotNull() { addCriterion("start_time is not null"); return (Criteria) this; } public Criteria andStartTimeEqualTo(Long value) { addCriterion("start_time =", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeNotEqualTo(Long value) { addCriterion("start_time <>", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeGreaterThan(Long value) { addCriterion("start_time >", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeGreaterThanOrEqualTo(Long value) { addCriterion("start_time >=", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeLessThan(Long value) { addCriterion("start_time <", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeLessThanOrEqualTo(Long value) { addCriterion("start_time <=", value, "startTime"); return (Criteria) this; } public Criteria andStartTimeIn(List<Long> values) { addCriterion("start_time in", values, "startTime"); return (Criteria) this; } public Criteria andStartTimeNotIn(List<Long> values) { addCriterion("start_time not in", values, "startTime"); return (Criteria) this; } public Criteria andStartTimeBetween(Long value1, Long value2) { addCriterion("start_time between", value1, value2, "startTime"); return (Criteria) this; } public Criteria andStartTimeNotBetween(Long value1, Long value2) { addCriterion("start_time not between", value1, value2, "startTime"); return (Criteria) this; } public Criteria andEmpIdIsNull() { addCriterion("emp_id is null"); return (Criteria) this; } public Criteria andEmpIdIsNotNull() { addCriterion("emp_id is not null"); return (Criteria) this; } public Criteria andEmpIdEqualTo(String value) { addCriterion("emp_id =", value, "empId"); return (Criteria) this; } public Criteria andEmpIdNotEqualTo(String value) { addCriterion("emp_id <>", value, "empId"); return (Criteria) this; } public Criteria andEmpIdGreaterThan(String value) { addCriterion("emp_id >", value, "empId"); return (Criteria) this; } public Criteria andEmpIdGreaterThanOrEqualTo(String value) { addCriterion("emp_id >=", value, "empId"); return (Criteria) this; } public Criteria andEmpIdLessThan(String value) { addCriterion("emp_id <", value, "empId"); return (Criteria) this; } public Criteria andEmpIdLessThanOrEqualTo(String value) { addCriterion("emp_id <=", value, "empId"); return (Criteria) this; } public Criteria andEmpIdLike(String value) { addCriterion("emp_id like", value, "empId"); return (Criteria) this; } public Criteria andEmpIdNotLike(String value) { addCriterion("emp_id not like", value, "empId"); return (Criteria) this; } public Criteria andEmpIdIn(List<String> values) { addCriterion("emp_id in", values, "empId"); return (Criteria) this; } public Criteria andEmpIdNotIn(List<String> values) { addCriterion("emp_id not in", values, "empId"); return (Criteria) this; } public Criteria andEmpIdBetween(String value1, String value2) { addCriterion("emp_id between", value1, value2, "empId"); return (Criteria) this; } public Criteria andEmpIdNotBetween(String value1, String value2) { addCriterion("emp_id not between", value1, value2, "empId"); return (Criteria) this; } public Criteria andEndTimeIsNull() { addCriterion("end_time is null"); return (Criteria) this; } public Criteria andEndTimeIsNotNull() { addCriterion("end_time is not null"); return (Criteria) this; } public Criteria andEndTimeEqualTo(Long value) { addCriterion("end_time =", value, "endTime"); return (Criteria) this; } public Criteria andEndTimeNotEqualTo(Long value) { addCriterion("end_time <>", value, "endTime"); return (Criteria) this; } public Criteria andEndTimeGreaterThan(Long value) { addCriterion("end_time >", value, "endTime"); return (Criteria) this; } public Criteria andEndTimeGreaterThanOrEqualTo(Long value) { addCriterion("end_time >=", value, "endTime"); return (Criteria) this; } public Criteria andEndTimeLessThan(Long value) { addCriterion("end_time <", value, "endTime"); return (Criteria) this; } public Criteria andEndTimeLessThanOrEqualTo(Long value) { addCriterion("end_time <=", value, "endTime"); return (Criteria) this; } public Criteria andEndTimeIn(List<Long> values) { addCriterion("end_time in", values, "endTime"); return (Criteria) this; } public Criteria andEndTimeNotIn(List<Long> values) { addCriterion("end_time not in", values, "endTime"); return (Criteria) this; } public Criteria andEndTimeBetween(Long value1, Long value2) { addCriterion("end_time between", value1, value2, "endTime"); return (Criteria) this; } public Criteria andEndTimeNotBetween(Long value1, Long value2) { addCriterion("end_time not between", value1, value2, "endTime"); return (Criteria) this; } public Criteria andOrderIdIsNull() { addCriterion("order_id is null"); return (Criteria) this; } public Criteria andOrderIdIsNotNull() { addCriterion("order_id is not null"); return (Criteria) this; } public Criteria andOrderIdEqualTo(String value) { addCriterion("order_id =", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdNotEqualTo(String value) { addCriterion("order_id <>", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdGreaterThan(String value) { addCriterion("order_id >", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdGreaterThanOrEqualTo(String value) { addCriterion("order_id >=", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdLessThan(String value) { addCriterion("order_id <", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdLessThanOrEqualTo(String value) { addCriterion("order_id <=", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdLike(String value) { addCriterion("order_id like", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdNotLike(String value) { addCriterion("order_id not like", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdIn(List<String> values) { addCriterion("order_id in", values, "orderId"); return (Criteria) this; } public Criteria andOrderIdNotIn(List<String> values) { addCriterion("order_id not in", values, "orderId"); return (Criteria) this; } public Criteria andOrderIdBetween(String value1, String value2) { addCriterion("order_id between", value1, value2, "orderId"); return (Criteria) this; } public Criteria andOrderIdNotBetween(String value1, String value2) { addCriterion("order_id not between", value1, value2, "orderId"); return (Criteria) this; } public Criteria andSyncResultIsNull() { addCriterion("sync_result is null"); return (Criteria) this; } public Criteria andSyncResultIsNotNull() { addCriterion("sync_result is not null"); return (Criteria) this; } public Criteria andSyncResultEqualTo(Byte value) { addCriterion("sync_result =", value, "syncResult"); return (Criteria) this; } public Criteria andSyncResultNotEqualTo(Byte value) { addCriterion("sync_result <>", value, "syncResult"); return (Criteria) this; } public Criteria andSyncResultGreaterThan(Byte value) { addCriterion("sync_result >", value, "syncResult"); return (Criteria) this; } public Criteria andSyncResultGreaterThanOrEqualTo(Byte value) { addCriterion("sync_result >=", value, "syncResult"); return (Criteria) this; } public Criteria andSyncResultLessThan(Byte value) { addCriterion("sync_result <", value, "syncResult"); return (Criteria) this; } public Criteria andSyncResultLessThanOrEqualTo(Byte value) { addCriterion("sync_result <=", value, "syncResult"); return (Criteria) this; } public Criteria andSyncResultIn(List<Byte> values) { addCriterion("sync_result in", values, "syncResult"); return (Criteria) this; } public Criteria andSyncResultNotIn(List<Byte> values) { addCriterion("sync_result not in", values, "syncResult"); return (Criteria) this; } public Criteria andSyncResultBetween(Byte value1, Byte value2) { addCriterion("sync_result between", value1, value2, "syncResult"); return (Criteria) this; } public Criteria andSyncResultNotBetween(Byte value1, Byte value2) { addCriterion("sync_result not between", value1, value2, "syncResult"); return (Criteria) this; } public Criteria andUuidIsNull() { addCriterion("uuid is null"); return (Criteria) this; } public Criteria andUuidIsNotNull() { addCriterion("uuid is not null"); return (Criteria) this; } public Criteria andUuidEqualTo(String value) { addCriterion("uuid =", value, "uuid"); return (Criteria) this; } public Criteria andUuidNotEqualTo(String value) { addCriterion("uuid <>", value, "uuid"); return (Criteria) this; } public Criteria andUuidGreaterThan(String value) { addCriterion("uuid >", value, "uuid"); return (Criteria) this; } public Criteria andUuidGreaterThanOrEqualTo(String value) { addCriterion("uuid >=", value, "uuid"); return (Criteria) this; } public Criteria andUuidLessThan(String value) { addCriterion("uuid <", value, "uuid"); return (Criteria) this; } public Criteria andUuidLessThanOrEqualTo(String value) { addCriterion("uuid <=", value, "uuid"); return (Criteria) this; } public Criteria andUuidLike(String value) { addCriterion("uuid like", value, "uuid"); return (Criteria) this; } public Criteria andUuidNotLike(String value) { addCriterion("uuid not like", value, "uuid"); return (Criteria) this; } public Criteria andUuidIn(List<String> values) { addCriterion("uuid in", values, "uuid"); return (Criteria) this; } public Criteria andUuidNotIn(List<String> values) { addCriterion("uuid not in", values, "uuid"); return (Criteria) this; } public Criteria andUuidBetween(String value1, String value2) { addCriterion("uuid between", value1, value2, "uuid"); return (Criteria) this; } public Criteria andUuidNotBetween(String value1, String value2) { addCriterion("uuid not between", value1, value2, "uuid"); return (Criteria) this; } public Criteria andTeslaOrderIdIsNull() { addCriterion("tesla_order_id is null"); return (Criteria) this; } public Criteria andTeslaOrderIdIsNotNull() { addCriterion("tesla_order_id is not null"); return (Criteria) this; } public Criteria andTeslaOrderIdEqualTo(Long value) { addCriterion("tesla_order_id =", value, "teslaOrderId"); return (Criteria) this; } public Criteria andTeslaOrderIdNotEqualTo(Long value) { addCriterion("tesla_order_id <>", value, "teslaOrderId"); return (Criteria) this; } public Criteria andTeslaOrderIdGreaterThan(Long value) { addCriterion("tesla_order_id >", value, "teslaOrderId"); return (Criteria) this; } public Criteria andTeslaOrderIdGreaterThanOrEqualTo(Long value) { addCriterion("tesla_order_id >=", value, "teslaOrderId"); return (Criteria) this; } public Criteria andTeslaOrderIdLessThan(Long value) { addCriterion("tesla_order_id <", value, "teslaOrderId"); return (Criteria) this; } public Criteria andTeslaOrderIdLessThanOrEqualTo(Long value) { addCriterion("tesla_order_id <=", value, "teslaOrderId"); return (Criteria) this; } public Criteria andTeslaOrderIdIn(List<Long> values) { addCriterion("tesla_order_id in", values, "teslaOrderId"); return (Criteria) this; } public Criteria andTeslaOrderIdNotIn(List<Long> values) { addCriterion("tesla_order_id not in", values, "teslaOrderId"); return (Criteria) this; } public Criteria andTeslaOrderIdBetween(Long value1, Long value2) { addCriterion("tesla_order_id between", value1, value2, "teslaOrderId"); return (Criteria) this; } public Criteria andTeslaOrderIdNotBetween(Long value1, Long value2) { addCriterion("tesla_order_id not between", value1, value2, "teslaOrderId"); return (Criteria) this; } public Criteria andTeslaOrderSyncResultIsNull() { addCriterion("tesla_order_sync_result is null"); return (Criteria) this; } public Criteria andTeslaOrderSyncResultIsNotNull() { addCriterion("tesla_order_sync_result is not null"); return (Criteria) this; } public Criteria andTeslaOrderSyncResultEqualTo(Byte value) { addCriterion("tesla_order_sync_result =", value, "teslaOrderSyncResult"); return (Criteria) this; } public Criteria andTeslaOrderSyncResultNotEqualTo(Byte value) { addCriterion("tesla_order_sync_result <>", value, "teslaOrderSyncResult"); return (Criteria) this; } public Criteria andTeslaOrderSyncResultGreaterThan(Byte value) { addCriterion("tesla_order_sync_result >", value, "teslaOrderSyncResult"); return (Criteria) this; } public Criteria andTeslaOrderSyncResultGreaterThanOrEqualTo(Byte value) { addCriterion("tesla_order_sync_result >=", value, "teslaOrderSyncResult"); return (Criteria) this; } public Criteria andTeslaOrderSyncResultLessThan(Byte value) { addCriterion("tesla_order_sync_result <", value, "teslaOrderSyncResult"); return (Criteria) this; } public Criteria andTeslaOrderSyncResultLessThanOrEqualTo(Byte value) { addCriterion("tesla_order_sync_result <=", value, "teslaOrderSyncResult"); return (Criteria) this; } public Criteria andTeslaOrderSyncResultIn(List<Byte> values) { addCriterion("tesla_order_sync_result in", values, "teslaOrderSyncResult"); return (Criteria) this; } public Criteria andTeslaOrderSyncResultNotIn(List<Byte> values) { addCriterion("tesla_order_sync_result not in", values, "teslaOrderSyncResult"); return (Criteria) this; } public Criteria andTeslaOrderSyncResultBetween(Byte value1, Byte value2) { addCriterion("tesla_order_sync_result between", value1, value2, "teslaOrderSyncResult"); return (Criteria) this; } public Criteria andTeslaOrderSyncResultNotBetween(Byte value1, Byte value2) { addCriterion("tesla_order_sync_result not between", value1, value2, "teslaOrderSyncResult"); return (Criteria) this; } public Criteria andSyncTeslaOrderIsNull() { addCriterion("sync_tesla_order is null"); return (Criteria) this; } public Criteria andSyncTeslaOrderIsNotNull() { addCriterion("sync_tesla_order is not null"); return (Criteria) this; } public Criteria andSyncTeslaOrderEqualTo(Byte value) { addCriterion("sync_tesla_order =", value, "syncTeslaOrder"); return (Criteria) this; } public Criteria andSyncTeslaOrderNotEqualTo(Byte value) { addCriterion("sync_tesla_order <>", value, "syncTeslaOrder"); return (Criteria) this; } public Criteria andSyncTeslaOrderGreaterThan(Byte value) { addCriterion("sync_tesla_order >", value, "syncTeslaOrder"); return (Criteria) this; } public Criteria andSyncTeslaOrderGreaterThanOrEqualTo(Byte value) { addCriterion("sync_tesla_order >=", value, "syncTeslaOrder"); return (Criteria) this; } public Criteria andSyncTeslaOrderLessThan(Byte value) { addCriterion("sync_tesla_order <", value, "syncTeslaOrder"); return (Criteria) this; } public Criteria andSyncTeslaOrderLessThanOrEqualTo(Byte value) { addCriterion("sync_tesla_order <=", value, "syncTeslaOrder"); return (Criteria) this; } public Criteria andSyncTeslaOrderIn(List<Byte> values) { addCriterion("sync_tesla_order in", values, "syncTeslaOrder"); return (Criteria) this; } public Criteria andSyncTeslaOrderNotIn(List<Byte> values) { addCriterion("sync_tesla_order not in", values, "syncTeslaOrder"); return (Criteria) this; } public Criteria andSyncTeslaOrderBetween(Byte value1, Byte value2) { addCriterion("sync_tesla_order between", value1, value2, "syncTeslaOrder"); return (Criteria) this; } public Criteria andSyncTeslaOrderNotBetween(Byte value1, Byte value2) { addCriterion("sync_tesla_order not between", value1, value2, "syncTeslaOrder"); return (Criteria) this; } public Criteria andOrderTypeIsNull() { addCriterion("order_type is null"); return (Criteria) this; } public Criteria andOrderTypeIsNotNull() { addCriterion("order_type is not null"); return (Criteria) this; } public Criteria andOrderTypeEqualTo(String value) { addCriterion("order_type =", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeNotEqualTo(String value) { addCriterion("order_type <>", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeGreaterThan(String value) { addCriterion("order_type >", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeGreaterThanOrEqualTo(String value) { addCriterion("order_type >=", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeLessThan(String value) { addCriterion("order_type <", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeLessThanOrEqualTo(String value) { addCriterion("order_type <=", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeLike(String value) { addCriterion("order_type like", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeNotLike(String value) { addCriterion("order_type not like", value, "orderType"); return (Criteria) this; } public Criteria andOrderTypeIn(List<String> values) { addCriterion("order_type in", values, "orderType"); return (Criteria) this; } public Criteria andOrderTypeNotIn(List<String> values) { addCriterion("order_type not in", values, "orderType"); return (Criteria) this; } public Criteria andOrderTypeBetween(String value1, String value2) { addCriterion("order_type between", value1, value2, "orderType"); return (Criteria) this; } public Criteria andOrderTypeNotBetween(String value1, String value2) { addCriterion("order_type not between", value1, value2, "orderType"); return (Criteria) this; } } /** * * @mbg.generated do_not_delete_during_merge */ public static class Criteria extends AbstractGeneratedCriteria { protected Criteria() { super(); } } /** * * @mbg.generated */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } /** * * @mbg.generated */ public enum OrderCondition { /** *主键 */ ID("id"), /** *所属产品线 */ APPCODE("app_code"), /** *操作唯一ID */ ACTIONID("action_id"), /** *操作elementId */ ELEMENTID("element_id"), /** *操作类型 */ ACTIONTYPE("action_type"), /** *操作名称 */ ACTIONNAME("action_name"), /** *操作label */ ACTIONLABEL("action_label"), /** *执行操作上层的node信息 */ NODE("node"), /** *对象实体类型 */ ENTITYTYPE("entity_type"), /** *对象实体值 */ ENTITYVALUE("entity_value"), /** *执行状态 */ STATUS("status"), /** *创建时间 */ CREATETIME("create_time"), /** *开始时间 */ STARTTIME("start_time"), /** *执行人工号 */ EMPID("emp_id"), /** *结束时间 */ ENDTIME("end_time"), /** *changfree orderId */ ORDERID("order_id"), /** *是否同步结束 */ SYNCRESULT("sync_result"), /** *action uuid */ UUID("uuid"), /** *tesla工单ID */ TESLAORDERID("tesla_order_id"), /** *tesla工单是否同步结束 */ TESLAORDERSYNCRESULT("tesla_order_sync_result"), /** *是否同步到tesla工单系统 */ SYNCTESLAORDER("sync_tesla_order"), /** *同步工单类型 */ ORDERTYPE("order_type"); private String columnName; OrderCondition(String columnName) { this.columnName = columnName; } public String getColumnName() { return columnName; } public static OrderCondition getEnumByName(String name) { OrderCondition[] orderConditions = OrderCondition.values(); for (OrderCondition orderCondition : orderConditions) { if (orderCondition.name().equalsIgnoreCase(name)) { return orderCondition; } } throw new RuntimeException("OrderCondition of " + name + " enum not exist"); } @Override public String toString() { return columnName; } } /** * * @mbg.generated */ public enum SortType { /** * 升序 */ ASC("asc"), /** * 降序 */ DESC("desc"); private String value; SortType(String value) { this.value = value; } public String getValue() { return value; } public static SortType getEnumByName(String name) { SortType[] sortTypes = SortType.values(); for (SortType sortType : sortTypes) { if (sortType.name().equalsIgnoreCase(name)) { return sortType; } } throw new RuntimeException("SortType of " + name + " enum not exist"); } @Override public String toString() { return value; } } }
<reponame>komura-c/universal<gh_stars>1000+ /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // eslint-disable-next-line import/no-unassigned-import import 'zone.js'; // eslint-disable-next-line import/no-unassigned-import import '@angular/compiler'; import { ngAspnetCoreEngine } from '@nguniversal/aspnetcore-engine'; import { MockServerModule } from './mock.server.module'; describe('ASPNETCore Engine', () => { it('should render a basic template', async () => { const { html } = await ngAspnetCoreEngine({ appSelector: '<root></root>', request: { data: { request: 'localhost', }, } as any, ngModule: MockServerModule, }); expect(html).toContain('some template'); }); });
/* main executable function */ func main() { fmt.Println("\n\n\033[31m~~~~~Dragon\033[32mFruit~~~~~\033[0m") cnf := parseFlags() fmt.Print("\033[1mVersion ", VERSION, " \033[0m\n\n\n") if cnf.version { return } d := backend_couchdb.Db_backend_couch{} d.Connect("http://" + cnf.config.DbServer + ":" + cnf.config.DbPort) if (cnf.resourcefile != "" && cnf.resourcetype == "") || (cnf.resourcefile == "" && cnf.resourcetype != "") { fmt.Println("\033[31;1mYou must enter both a resource file and a resource type if you pass a resource from the command line.\033[0m") return } if cnf.addInteractive { addResouce(&d, cnf.config) } else if cnf.resourcefile != "" { addResourceFromFile(&d, cnf.config, cnf.resourcetype, cnf.resourcefile) } if cnf.serve { launchServer(&d, cnf.config) } }
 #include "si_base/gpu/dx12/dx12_command_queue.h" #include "si_base/gpu/gfx_fence.h" #include "si_base/gpu/gfx_command_list.h" #include "si_base/gpu/gfx_command_queue.h" namespace SI { GfxCommandQueue::GfxCommandQueue(BaseCommandQueue* base) : m_base(base) { } GfxCommandQueue::~GfxCommandQueue() { } void GfxCommandQueue::ExecuteCommandList(GfxCommandList& list) { m_base->ExecuteCommandList(*list.GetBaseCommandList()); } void GfxCommandQueue::ExecuteCommandLists(uint32_t count, GfxCommandList** lists) { m_base->ExecuteCommandLists(count, lists); } int GfxCommandQueue::Signal(GfxFence& fence, uint64_t fenceValue) { return m_base->Signal(*fence.GetBaseFence(), fenceValue); } } // namespace SI
<gh_stars>1-10 package com.example.random.service.business; import java.security.SecureRandom; import com.example.random.service.QualityLevel; import com.example.random.service.RandomNumberGenerator; import com.example.random.service.ServiceQuality; @ServiceQuality(QualityLevel.SECURE) public class SecureRandomNumberGenerator implements RandomNumberGenerator { private SecureRandom random = new SecureRandom(); @Override public int generate(int min, int max) { return random.nextInt(min, max); } }
#include<bits/stdc++.h> #define mid ((l+r)>>1) typedef long long ll; using namespace std; set<int>edge[100010]; double ans[100010]; int children[100010]; void dfs1(int st) { for(set<int>::iterator it=edge[st].begin();it!=edge[st].end();it++) { dfs1(*it); children[st]+=children[*it]+1; } } void dfs2(int st) { for(set<int>::iterator it=edge[st].begin();it!=edge[st].end();it++) { ans[*it]=ans[st]+1.0+0.5*(children[st]-children[*it]-1); dfs2(*it); } } int main() { int n; cin>>n; for(int i=2;i<=n;i++) { int temp; scanf("%d",&temp); edge[temp].insert(i); } dfs1(1); ans[1]=1; dfs2(1); for(int i=1;i<=n;i++) printf("%.10lf ",ans[i]); return 0; }
def smooth_lightcone_tophat(lightcone, redshifts, dz, verbose=True): output_lightcone = np.zeros(lightcone.shape) for i in tqdm(range(output_lightcone.shape[2]), disable=False if verbose else True): z_out_low = redshifts[i]-dz[i]/2 z_out_high = redshifts[i]+dz[i]/2 idx_low = int(np.ceil(find_idx(redshifts, z_out_low))) idx_high = int(np.ceil(find_idx(redshifts, z_out_high))) output_lightcone[:,:,i] = np.mean(lightcone[:,:,idx_low:idx_high+1], axis=2) return output_lightcone
// NewClient returns a new staketab service client func NewClient(httpClient *http.Client, endpoint string) *Client { return &Client{ endpoint: endpoint, client: httpClient, } }
Every pompous television pundit and untrustworthy intelligence agency wants you, the vulnerable news consumer, to believe that Putin hacked the DNC from the Kremlin’s basement, directly resulting in Hillary Clinton’s defeat — even though it was clearly “her turn”. And we must admit — although it pains us to do so — that all the unverifiable accusations and rumors point to direct Kremlin meddling in our beloved American democracy. It’s a simple fact: You cannot find an anonymous source from an anonymous intelligence agency who will say that Russian didn’t steal Hillary Clinton’s emails. Damning. Which is why we were so shocked to learn that a government that doesn’t speak Russian attempted to break into Georgia’s voter registration database. Instant Access to Current Spot Prices & Interactive Charts As IT World reports: Georgia’s secretary of state says the state was hit with an attempted hack of its voter registration database from an IP address linked to the federal Department of Homeland Security. Of course, it could have just been a routine test to make sure states had secure voter registration databases. The problem, of course, is that Georgia Secretary of State Brian Kemp was not informed — not even after the attempted hack — that the DHS planned on conducted such a test: “This morning I sent a letter to DHS Secretary Jeh Johnson demanding to know why,” he said in the post. The DHS said it had received the letter. “We are looking into the matter. DHS takes the trust of our public and private sector partners seriously, and we will respond to Secretary Kemp directly,” the department said in a statement. The hacking attempt reportedly took place on Nov. 15, after the presidential election, according to the Wall Street Journal, which saw a copy of the letter. “At no time has my office agreed to or permitted DHS to conduct penetration testing or security scans of our network,” Kemp wrote in his letter. “Moreover, your department has not contacted my office since this unsuccessful incident to alert us of any security event that would require testing or scanning of our network.” We’re sure this lack of communication is an innocent bureaucratic slip-up. No reason to suspect any foul play. After all, there is zero evidence that the U.S. government attempted to break into voter registration databases. To report something like that would be irresponsible fake news. The most likely explanation is that Russian hackers took control of DHS systems and then attempted to break into Georgia’s voter rolls. Very sneaky. And very, very Russian. Reprinted from Russia Insider.
<gh_stars>10-100 package locals_in; public class A_test567 { public void foo() { String args[] = null; /*[*/ args = new String[/*]*/ 4]; args[0] = args[1]; } }
<gh_stars>1-10 package com.huan.common.util; import cn.hutool.core.date.DateUtil; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import lombok.extern.slf4j.Slf4j; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; /** * JWT工具 * * @author <a href="mailto:<EMAIL>">huan</a> * @version 1.0.0 * @date 2021/2/22 */ @Slf4j public class JwtUtil { public static void main(String[] args) throws UnsupportedEncodingException { String s = Jwts.builder() .setSubject("1234567890") .setId("68e46077-5560-4593-a603-df5c5541412b") .setIssuedAt(DateUtil.nextMonth()) .setExpiration(DateUtil.nextMonth()) .claim("password", "<PASSWORD>") .signWith(SignatureAlgorithm.HS256, "secret".getBytes(StandardCharsets.UTF_8)) .compact(); System.out.println(s); } }
LifeWay Christian book stores still carry Dinesh D’Souza’s books. For now. The journalistic scoop belongs to Warren Cole Smith of the very conservative World magazine, so we’ll quote from his report first: About 2,000 people gathered on Sept. 28 at First Baptist North in Spartanburg, S.C., to hear high-profile Christians speak on defending the faith and applying a Christian worldview to their lives. Among the speakers: Eric Metaxas, Josh McDowell, and — keynote speaker for the evening — best-selling author, filmmaker, and Christian college president Dinesh D’Souza. D’Souza’s speech earned him a standing ovation and a long line at the book-signing table immediately afterward. Although D’Souza has been married for 20 years to his wife, Dixie, in South Carolina he was with a young woman, Denise Odie Joseph II,* and introduced her to at least three people as his fiancée. Finally, near 11 p.m., event organizer Tony Beam escorted D’Souza and Joseph to the nearby Comfort Suites. Beam noted that they checked in together and were apparently sharing a room for the night in the sold-out hotel. The next morning, around 6 a.m., Beam arrived back at the hotel and called up to D’Souza’s room. “We’ll be down in 10 minutes,” D’Souza told Beam. D’Souza and Joseph came down together, and Beam took them to the airport. The next day another conference organizer, Alex McFarland, distressed by D’Souza’s behavior, confronted him in a telephone conversation. D’Souza admitted he shared a room with his fiancée but said “nothing happened.” When I called D’Souza, he confirmed that he was indeed engaged to Joseph, but did not explain how he could be engaged to one woman while still married to another. When asked when he had filed for divorce from his wife, Dixie, D’Souza answered, “Recently.” Amy Sullivan describes “The Right-wing Rivalry Behind” that scoop: Needless to say, this sort of thing is frowned upon in the conservative religious circles in which D’Souza is usually celebrated. So it is perhaps unsurprising that the story was broken by Warren C. Smith, a writer and associate publisher for the evangelical World magazine. The publication has a history of covering problems within the evangelical world, and it has not shied away from stories about preacher scandals or church abuse of women. But this particular story may have interested the magazine for a different reason: World’s editor-in-chief is Marvin Olasky, the sometime Bush advisor who is no fan of D’Souza. Olasky served, briefly, as provost of The King’s College. He resigned shortly after D’Souza became the school’s president. Read the whole thing for Sullivan’s take on the nasty history between these two nasty men. Christianity Today’s report notes that “D’Souza has regularly appeared in CT’s pages.” One example of that is CT’s report on D’Souza’s hiring at King’s, which emphasized that the conservative activist’s Roman Catholic faith should not preclude him from membership in the evangelical tribe: D’Souza’s wife, Dixie, is an evangelical, and the family has attended Calvary Chapel, a nondenominational evangelical church in San Diego, for the past 10 years. He has been invited to speak in several churches and colleges, including Rick Warren’s Saddleback Church and Jerry Falwell’s Liberty University. “I do not describe myself as Catholic today. But I don’t want to renounce it either because it’s an important part of my background. I’m an American citizen, but I wouldn’t reject the Indian label because it’s part of my heritage,” D’Souza said. “I say I have a Catholic origin or background. I say I’m a nondenominational Christian, and I’m comfortable with born-again.” He said that his views align with the Apostles’ Creed and C. S. Lewis’s Mere Christianity. That’s the imprimatur — the stamp of approval. But D’Souza wasn’t embraced by the evangelical tribe just because he affirms the creeds and C.S. Lewis. What made CT and King’s College and the rest of mainstream evangelicalism decide that D’Souza was one of us was his political history — a former policy aide in the Reagan White House, D’Souza is fiercely opposed to abortion, gay rights, feminism and progressive taxation. As Sarah Posner said, “D’Souza’s … rise in the evangelical world is due in no small part to his conspiracy-minded claims about President Obama’s ‘Kenyan, anti-colonial behavior.'” Yes, conspiratorial warnings about Africans and anti-colonialism contributed to D’Souza’s legitimacy among evangelicals. Bruce Garrett notes some of D’Souza’s odious political history: How the man who, while editor of the Dartmouth Review, penned a racist parody of African American students titled “This Sho Ain’t No Jive Bro” and later outed a gay student using stolen mail between members of the Dartmouth Gay Student Alliance can in any sense be labeled a Christian is something confederate Christianists can explain I suppose. Those two themes — racism and anti-gay sentiment — have endured as the hallmarks of much of D’Souza’s “scholarship.” Alvin McEwen highlights a 2008 article of D’Souza’s titled, “Gay Rights vs. Democracy,” in which he pulls the man-on-dog nonsense. Here is D’Souza’s idea of scholarship: “Why doesn’t the Fourteenth Amendment protect the fellow who wants to walk down the aisle with his poodle on the grounds that ‘I love my dog and my dog loves me’?” (What is it about the idea of consent that confuses these folks so much?) Grace at Are Women Human? echoes Garrett’s observation, noting — savoring — the irony that D’Souza’s adultery has done what his nasty racism and homophobia never did, diminished his standing amongst evangelicals. The entire post — a Snoopy-dance of schadenfreude — is great fun, but the kernel of it is summed up in this one tweet from Grace: Does it matter than D’souza peddles racist, colonialist lies? Nope. But he shared a hotel room with a woman he’s not married to! OH NOES Or, as she writes in the post itself: Sarah Posner writes for Religion Dispatches that this (presumed) sex scandal may spell the end for D’Souza’s once rising star. Note, not the fact that he’s been peddling racist and colonialist lies to white Christians for fun and profit for the past forever, but because of what’s assumed about his marriage and sex life. PRIORITIES. – – – – – – – – – – – – * Brian Tashman at Right Wing Watch quotes from a post by Odie Joseph II at Smart Girl Politics, which bears the unfortunate title of “Whatever Happened to Good Ole Hypocrisy?” Feminists and liberals … tore the traditional family to shreds until they reduced us to the shining bastion of zoological (but even animals aren’t this bad and do not depend on the state to care for them) cesspool equality that we have now in every American ghetto and which is seeping out into the middle and upper classes in less animated ways. Her bogeymen are just like those of her boyfriend: Black. As women spearhead the demise of the ideal, the alternative to hypocrisy, they spearhead the demise of social order as we know it and love it. Henceforth, all of us will be staring down the barrel of life in a hip hop video or government-funded project. … Buzzfeed snagged a cached copy of Odie Joseph’s blog (which disappeared when the story broke), which reveals her to have been a fan of D’Souza’s books — and of Ayn Rand.
<filename>tests/CompileTests/ElsaTestCases/t0277.cc // t0277.cc // another dependent name problem void bar(); void bar(int *); template <class T> void foo(T t) { typedef T *Ptr; // not a member of a template Ptr p; // will be regarded as non-dependent bar(p); // overload resolution will fail } template void foo(int t);
def encode_null(message: str, word_list: list) -> list: message = ''.join(format_plaintext(message)) cipherlist = [] for letter in message: for word in word_list: if all([len(word) > 2, word not in cipherlist]): if len(cipherlist) % 2 == 0 and \ word[1].lower() == letter: cipherlist.append(word) break elif len(cipherlist) % 2 != 0 and \ word[2].lower() == letter: cipherlist.append(word) break if word == word_list[-1]: if len(cipherlist) % 2 == 0: place = 'second' else: place = 'third' raise ValueError(f'Missing word with {place} letter of: ' f'{letter}') return cipherlist
import logging from sys import stdout logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(stdout) handler.setFormatter(logging.Formatter( fmt='[%(asctime)s][%(levelname)s]%(message)s', datefmt='%Y-%m-%d %H:%M:%S' )) logger.addHandler(handler)
<reponame>viniciusgcardozo/rodrigues-api<gh_stars>0 import event from './event' const routes = (app: any) => { event(app) } export default routes
import React from "react"; import styled from "styled-components"; const Container = styled.div` -webkit-app-region: no-drag; `; type Props = { onChange?: () => void; defaultChecked?: boolean; checked?: boolean; }; const Toggle: React.FC<Props> = (props) => { const { onChange, defaultChecked, checked } = props; return ( <Container data-testid="toggle"> <label className="switch"> <input type="checkbox" checked={checked} defaultChecked={defaultChecked} onChange={onChange} /> <span className="slider round"></span> </label> </Container> ); }; export default Toggle;
def is_optional(self): return self.is_in_function or self.is_in_conditional or self.is_in_tryexcept
/** * Lists all files at the specified path. Will return a {@link Map} that contains a paginated list * of secure file summaries. If Cerberus returns an unexpected response code, a {@link CerberusServerException} * will be thrown with the code and error details. If an unexpected I/O error is * encountered, a {@link CerberusClientException} will be thrown wrapping the underlying exception. * <p> * See https://github.com/Nike-Inc/cerberus/blob/master/API.md for details on what the * list files operation returns. * </p> * * @param path Path to the data * @param limit The max number of results to return * @param offset The number offset of results to return * @return List of metadata for secure files at the specified path */ public CerberusListFilesResponse listFiles(final String path, Integer limit, Integer offset) { final HttpUrl httpUrl = buildUrl("v1/secure-files/", path, limit, offset); logger.debug("list: requestUrl={}, limit={}, offset={}", httpUrl, limit, offset); final Response response = ofSupplier( () -> execute(httpUrl, HttpMethod.GET, null) ) .withRetry(RETRY) .decorate() .get(); if (response.code() != HttpStatus.OK) { parseAndThrowApiErrorResponse(response); } return parseResponseBody(response, CerberusListFilesResponse.class); }
<reponame>developerfromjokela/abitikku<filename>webpack.dev.config.ts import configs from './webpack.config'; import { WebpackOptionsNormalized } from 'webpack'; import * as fs from 'fs'; const [guiConfig, etcherConfig, childWriterConfig] = configs as unknown as WebpackOptionsNormalized[]; configs.forEach((config) => { config.mode = 'development'; // @ts-ignore config.devtool = 'source-map'; }); guiConfig.devServer = { hot: true, port: 3030, }; fs.copyFileSync('./lib/gui/app/index.dev.html', './generated/index.html'); export default [guiConfig, etcherConfig, childWriterConfig];
<filename>src/main.rs<gh_stars>0 extern crate gl; extern crate glutin; extern crate png; use gl::types::*; use glutin::GlContext; use std::ffi::CString; use std::fs::File; use std::process::Command; use std::str; use std::thread; use std::time::{Duration, Instant}; use std::{mem, ptr}; macro_rules! check_error { //($s: expr) => { unsafe { ($s:expr) => {{ let err = gl::GetError(); match err { gl::NO_ERROR => (), gl::INVALID_ENUM => panic!("enum: {}", $s), gl::INVALID_VALUE => panic!("value: {}", $s), gl::INVALID_OPERATION => panic!("operation: {}", $s), gl::INVALID_FRAMEBUFFER_OPERATION => { panic!("framebuffer operation: {}", $s) } gl::OUT_OF_MEMORY => panic!("out of memory: {}", $s), gl::STACK_UNDERFLOW => panic!("stack underflow: {}", $s), gl::STACK_OVERFLOW => panic!("stack overflow: {}", $s), _ => panic!("Unknow: {}", $s), } if err != gl::NO_ERROR { panic!("Error: {}", $s); } }}; } static SCREEN_PATH: &str = "/tmp/screen.png"; fn compile_shader(src: &str, ty: GLenum) -> GLuint { let shader; unsafe { shader = gl::CreateShader(ty); // Attempt to compile the shader let c_str = CString::new(src.as_bytes()).unwrap(); gl::ShaderSource(shader, 1, &c_str.as_ptr(), ptr::null()); gl::CompileShader(shader); // Get the compile status let mut status = gl::FALSE as GLint; gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut status); // Fail on error if status != gl::TRUE as GLint { let mut len = 0; gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len); let mut buf = Vec::with_capacity(len as usize); buf.set_len(len as usize - 1); gl::GetShaderInfoLog( shader, len, ptr::null_mut(), buf.as_mut_ptr() as *mut GLchar, ); panic!("{}", str::from_utf8(&buf).unwrap()); } } shader } fn link_program(vs: GLuint, fs: GLuint) -> GLuint { let program; unsafe { program = gl::CreateProgram(); gl::AttachShader(program, vs); gl::AttachShader(program, fs); gl::LinkProgram(program); // Get the link status let mut status = gl::FALSE as GLint; gl::GetProgramiv(program, gl::LINK_STATUS, &mut status); // Fail on error if status != gl::TRUE as GLint { let mut len = 0; gl::GetProgramiv(program, gl::INFO_LOG_LENGTH, &mut len); let mut buf = Vec::with_capacity(len as usize); buf.set_len(len as usize - 1); gl::GetProgramInfoLog( program, len, ptr::null_mut(), buf.as_mut_ptr() as *mut GLchar, ); panic!("{}", str::from_utf8(&buf).unwrap()); } } program } fn read_shader_files(vertex: &str, fragment: &str) -> (Vec<u8>, Vec<u8>) { use std::fs::File; use std::io::Read; let mut file_vertex = File::open(vertex).unwrap(); let mut file_fragment = File::open(fragment).unwrap(); let mut vec_vertex = Vec::new(); let mut vec_fragment = Vec::new(); file_vertex.read_to_end(&mut vec_vertex).unwrap(); file_fragment.read_to_end(&mut vec_fragment).unwrap(); (vec_vertex, vec_fragment) } fn load_texture(texture: GLuint, texture_path: &str) -> (u32, u32) { unsafe { let (x, y); gl::BindTexture(gl::TEXTURE_2D, texture); if texture_path != "" { let decoder = png::Decoder::new(File::open(texture_path).unwrap()); let (info, mut reader) = decoder.read_info().unwrap(); //(x, y) = (info.width, info.height); x = info.width; y = info.height; let mut buf = vec![0; info.buffer_size()]; //reader.next_frame(&mut buf).unwrap(); reader.next_frame(&mut buf); gl::TexImage2D( gl::TEXTURE_2D, 0, gl::RGBA as _, info.width as _, info.height as _, 0, gl::RGBA, gl::UNSIGNED_BYTE, buf.as_ptr() as _ //mem::transmute(buf.as_ptr()), ); } else { panic!("Can't open file"); } gl::BindTexture(gl::TEXTURE_2D, 0); (x, y) } } fn run_commands() { let _ = Command::new("adb") .arg("shell") .arg("screencap") .arg("-p") .arg("/sdcard/screen.png") //.spawn() .status() .expect("failed to execute process"); let _ = Command::new("adb") .arg("pull") .arg("/sdcard/screen.png") .arg(SCREEN_PATH) //.spawn() //.output() .status() .expect("failed to execute process"); //println!("status: {}", output.status); thread::sleep(Duration::from_millis(100)); } fn tap(x: u32, y: u32) { println!("x {:.0} y {:.0}", x, y); let _ = Command::new("adb") .arg("shell") .arg("input") .arg("tap") .arg(format!("{:.0}", x)) .arg(format!("{:.0}", y)) .status() .expect("failed to execute process"); } fn swipe(x0: u32, y0: u32, x1: u32, y1: u32, ms: u32) { println!( "x0 {:.0} y0 {:.0} x1 {:.0} y1 {:.0} t {}", x0, y0, x1, y1, ms ); let _ = Command::new("adb") .arg("shell") .arg("input") .arg("swipe") .arg(format!("{:.0}", x0)) .arg(format!("{:.0}", y0)) .arg(format!("{:.0}", x1)) .arg(format!("{:.0}", y1)) .arg(format!("{:.0}", ms)) .status() .expect("failed to execute process"); } fn event_code(code: usize) { let _ = Command::new("adb") .arg("shell") .arg("input") .arg("keyevent") .arg(format!("{}", code)) .status() .expect("failed to execute process"); } fn main() { let mut swipe_timer = Instant::now(); let vertices: Vec<f32> = vec![ -1., -1., 1., -1., 1., 1., // first triangle -1., -1., 1., 1., -1., 1., // seconde triangle ]; let (mut width, mut height) = (256, 64); let mut events_loop = glutin::EventsLoop::new(); let (mut mouse_x, mut mouse_y) = (0., 0.); let (mut s_x, mut s_y) = (0., 0.); let mut reload = true; let mut running = true; let mut texture = 0; let mut vao = 0; let mut vbo = 0; let alpha = 0.385; let program; let window = glutin::WindowBuilder::new() .with_title("vadb") .with_dimensions(width, height); let context = glutin::ContextBuilder::new(); //.with_vsync(true); let gl_window = glutin::GlWindow::new(window, context, &events_loop).unwrap(); unsafe { gl_window.make_current() }.unwrap(); gl::load_with(|symbol| gl_window.get_proc_address(symbol) as *const _); unsafe { let (vs_src, fs_src) = read_shader_files("shaders/main.vert", "shaders/main.frag"); let vs = compile_shader(str::from_utf8(&vs_src).unwrap(), gl::VERTEX_SHADER); let fs = compile_shader( str::from_utf8(&fs_src).unwrap(), gl::FRAGMENT_SHADER, ); program = link_program(vs, fs); gl::DeleteShader(vs); gl::DeleteShader(fs); // Create texture gl::GenTextures(1, &mut texture); gl::BindTexture(gl::TEXTURE_2D, texture); gl::TexParameteri( gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_BORDER as _, ); gl::TexParameteri( gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_BORDER as _, ); gl::TexParameteri( gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, // gl::LINEAR as _); gl::NEAREST as _, ); gl::TexParameteri( gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, // gl::LINEAR as _); gl::NEAREST as _, ); gl::GenVertexArrays(1, &mut vao); gl::BindVertexArray(vao); gl::GenBuffers(1, &mut vbo); gl::BindBuffer(gl::ARRAY_BUFFER, vbo); gl::BufferData( gl::ARRAY_BUFFER, (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, vertices.as_ptr() as _, //mem::transmute(vertices.as_ptr()), gl::STATIC_DRAW, ); //gl::BindVertexArray(0); check_error!("vao"); gl::UseProgram(program); let target = CString::new("target").unwrap(); gl::BindFragDataLocation( program, 0, target.as_ptr(), ); //* let str_u_pos = CString::new("u_pos").unwrap(); let u_pos = gl::GetAttribLocation( program, str_u_pos.as_ptr(), ); gl::EnableVertexAttribArray(u_pos as GLuint); gl::VertexAttribPointer( u_pos as GLuint, 2, gl::FLOAT, gl::FALSE as GLboolean, 0, ptr::null(), ); gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, texture); let str_tex0 = CString::new("tex0").unwrap(); let tex0 = gl::GetUniformLocation( program, str_tex0.as_ptr(), ); gl::Uniform1i(tex0, 0); // */ check_error!("end"); gl::BindVertexArray(0); } while running { unsafe { if reload { run_commands(); let (mut w, mut h) = load_texture(texture, SCREEN_PATH); w = (alpha * w as f32) as _; h = (alpha * h as f32) as _; width = w; height = h; gl_window.set_inner_size(w, h); reload = false; } events_loop.poll_events(|event| { //events_loop.run_forever(|event| { use glutin::WindowEvent; use glutin::{ ElementState, KeyboardInput, MouseButton, VirtualKeyCode, }; match event { glutin::Event::WindowEvent { event, .. } => { // use glutin::Event; match event { WindowEvent::Closed => running = false, WindowEvent::MouseMoved { position: (x, y), .. } => { mouse_x = x; mouse_y = y; } WindowEvent::MouseInput { state: ElementState::Pressed, button: MouseButton::Left, .. } => { s_x = mouse_x; s_y = mouse_y; swipe_timer = Instant::now(); } WindowEvent::MouseInput { state: ElementState::Released, button: MouseButton::Left, .. } => { let distance = (s_x - mouse_x).powf(2.) + (s_y - mouse_y).powf(2.); if distance < 1.0 { tap( (mouse_x as f32 / alpha) as u32, (mouse_y as f32 / alpha) as u32, ); } else { let t = (swipe_timer.elapsed().as_secs() * 1000) as u32 + (swipe_timer.elapsed().subsec_nanos() / 1_000_000) as u32; swipe( (s_x as f32 / alpha) as u32, (s_y as f32 / alpha) as u32, (mouse_x as f32 / alpha) as u32, (mouse_y as f32 / alpha) as u32, t, ); } reload = true; } WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::LControl), .. }, .. } => reload = true, WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. }, .. } => { event_code(4); // KEYCODE_BACK reload = true; } WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::F1), .. }, .. } => { event_code(82); // KEYCODE_MENU reload = true; } WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Up), .. }, .. } => { event_code(19); // KEYCODE_DPAD_UP reload = true; } WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Down), .. }, .. } => { event_code(20); // KEYCODE_DPAD_DOWN reload = true; } WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Left), .. }, .. } => { event_code(21); // KEYCODE_DPAD_LEFT reload = true; } WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Right), .. }, .. } => { event_code(22); // KEYCODE_DPAD_RIGHT reload = true; } s => println!("event: {:?}", s), // _ => (), } } _ => (), } //glutin::ControlFlow::Break }); gl::Viewport(0, 0, width as _, height as _); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); gl::ClearColor(0., 0., 0., 1.); gl::UseProgram(program); gl::BindVertexArray(vao); gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, texture); let str_tex0 = CString::new("tex0").unwrap(); let tex0 = gl::GetUniformLocation( program, str_tex0.as_ptr(), ); gl::Uniform1i(tex0, 0); gl::DrawArrays(gl::TRIANGLES, 0, 6); gl::Flush(); gl::Finish(); gl::BindVertexArray(0); gl::UseProgram(0); gl_window.swap_buffers().unwrap(); } } }
<gh_stars>1-10 import pygame, graphics, palette segment_width = 8 class Wire(): def __init__(self): segment = Segment() self.segments = [segment] def set_start(self, (x, y)): old_stop = self.segments[-1].rect.topright self.segments[0].rect.left = x self.segments[0].y = y for segment in self.segments[1:]: segment.rect.left = segment.left.rect.right self.set_stop(old_stop) def set_stop(self, (x, y)): for segment in self.segments[1:]: if segment.rect.right > x: segment.left.right = None segment.kill() self.segments.remove(segment) while self.segments[-1].rect.right < x: segment = Segment() segment.y = y segment.rect.topleft = self.segments[-1].rect.right, y segment.left = self.segments[-1] segment.update_size() self.segments[-1].right = segment self.segments.append(segment) segment.left.rect.width = segment_width self.segments[-1].y = y self.segments[-1].nexty = None self.segments[-1].rect.top = y self.segments[-1].rect.width = max(x - self.segments[-1].rect.left, 1) self.segments[-1].rect.right = x self.segments[-1].update_size() graphics.wirelayer.add(self.segments) class Segment(pygame.sprite.Sprite): images = {} thickness = 4 outline_color = palette.color(0x2a) fill_color = palette.color(0x3f) gravity = 0.1 spring_constant = 0.3 friction =0.5 mass = 0.8 def __init__(self): pygame.sprite.Sprite.__init__(self) self.y = 0 self.speed = 0 self.left = None self.right = None self.nexty = None self.rect = pygame.Rect(0, 0, segment_width, 1) self.update_size() def update(self, frame): if self.nexty: self.y = self.nexty self.update_size() self.left.update_size() if self.left and self.right: force = self.gravity force += self.spring_constant*(self.left.y + self.right.y - 2*self.y) force -= self.friction*self.speed self.speed += force/self.mass self.nexty = self.y + self.speed if not self.right: self.rect.top = self.y if self.left: self.left.update_size() def update_size(self): if self.right: size = int(self.right.y - self.y) else: size = 0 height = abs(size) + self.thickness width = self.rect.width key = (width, size) if not key in self.images: image = pygame.Surface((width, height)) image.set_colorkey(graphics.transparent) image.fill(graphics.transparent) points = (0, 0), (width - 1, height - self.thickness) for shift in range(self.thickness): points1 = tuple((x, y + shift) for x, y in points) if size < 0: points1 = tuple((x, height - 1 - y) for x, y in points1) if shift in (0, self.thickness-1): color = self.outline_color else: color = self.fill_color pygame.draw.lines(image, color, False, points1) self.images[key] = image self.image = self.images[key] self.rect.height = height if self.right: if self.y < self.right.y: self.rect.top = self.y else: self.rect.top = self.right.y
After months of non-denying denials, Ford CEO Alan Mulally has finally said he isn't going to take the open CEO job at Microsoft. In a January 7 interview with the Associated Press, Mulally said he is not planning to leave Ford for Microsoft and that he will stay at Ford at least through 2014. The Associated Press Twitter account tweeted the news around 5:20 p.m. ET. Mulally said he wanted to put an end to the speculation regarding him going to Microsoft and finally decided to speak definitively about rumors that he might be the successor to outgoing Microsoft CEO Steve Ballmer. Mulally declined to comment as to whether he spoken with anyone at Microsoft about the CEO job, according to the AP report. Back in December 2013, Reuters reported that the Ford board of directors, meeting on December 12, planned to pressure CEO Mulally to answer directly whether or not was in the running to replace outgoing Ballmer. Mulally's handlers have been in non-denial denial mode. The reason, as Reuters reported, citing "one source close to Ford's board": "People don't write about Mustang, they don't write about earnings, they write about Mulally." Microsoft still has yet to announce who will be the next CEO at the company. Some had expected the announcement to happen before the end of 2013. Microsoft officials have said that the new CEO will be named in early 2014 . The company is believed to be continuing to consider both internal and external candidates. Internal names that have been bandied about include Cloud & Enterprise chief Satya Nadella and Business Development chief Tony Bates, as well as Nokia CEO Steven Elop. Mulally has been a friend and advisor to Ballmer over the years. Microsoft's "One Microsoft" reorg is believed to have been influenced heavily by the "One Ford" structure. I've asked Microsoft officials for comment on the AP report. No word back so far. Update: "“Out of respect for the process and the potential candidates, we don’t comment on individual names," a Microsoft spokesperson said.
/** * skip whitespace and scan next token */ public Token scan() { while (!eot && currentChar == ' ') skipIt(); currentSpelling = new StringBuilder(); TokenKind kind = scanToken(); String spelling = currentSpelling.toString(); return new Token(kind, spelling); }
The improved ammoxidation catalysts based on mixed metal oxides 1. A catalyst composition comprising a complex metal oxide, wherein the ratio of the elements in the composition represented by the following formula: MoBiFeADEFGCeO, where A represents at least one element selected from the group consisting of sodium, potassium, rubidium and cesium; and D represents at least one element selected from the group consisting of nickel, cobalt, manganese, zinc, magnesium, calcium, strontium, cadmium and barium, E represents at least one element selected from the group consisting of chromium, tungsten, boron, aluminum, gallium, indium, phosphorus, arsenic, antimony, vanadium, and tellurium; F represents at least one element selected from the group consisting of a rare earth element, titanium, zirconium, hafnium, niobium, tantalum, aluminum, gallium, indium , thallium, silicon, germanium and lead; G represents at m D is one element selected from the group consisting of silver, gold, ruthenium, rhodium, palladium, osmium, iridium, platinum, and mercury; ua, b, c, d, e, f, g, h and n, respectively, represent the number of bismuth atoms (Bi), iron (Fe), A, D, E, F, cerium (Ce) and oxygen (O) relating to 12 atoms of molybdenum (Mo), where: a has a value of from 0.05 to 7, b has a value from 0.1 to 7, c has a value of from 0.01 to 5, d is from 0.1 to 12, e is from 0 to 5, f is from 0 to 5, g has a value from 0 to 0,2, h has a value of from 0.01 to 5 and n denotes the number of oxygen atoms required to saturate the valencies of other available elements ; wherein 0,15≤ (a + h) / d≤1 and 0,8≤h / b≤5 and wherein the X-ray diffraction pattern when indicated the catalyst composition comprises diffraction peaks at angle 2θ ± 0,3 28 degrees and the angle 2θ ± 0,3 · 26.5 degrees, and wherein the intensity ratio of the most yn
#include <iostream> #include <bits/stdc++.h> #include <vector> #include <algorithm> using namespace std; #define REP(i,n) FOR(i,0,n) #define FOR(i,a,b) for(long long i=(a),i##Len_=(b);i<i##Len_;i++) typedef long long ll; const ll INF = 1000000007; //くみあわせ ll P [10]={0 ,0 ,0 ,0 ,0 ,0 ,1 ,1 ,1 ,2}; ll Q [10]={1 ,1 ,1 ,2 ,2 ,3 ,2 ,2 ,3 ,3}; ll R [10]={2 ,3 ,4 ,3 ,4 ,4 ,3 ,4 ,4 ,4}; int main() { ll N; string tmp; cin >> N; ll res = 0; vector <ll> cnt(5,0); REP(i,N) { cin >> tmp; if(tmp[0] == 'M')cnt[0]++; if(tmp[0] == 'A')cnt[1]++; if(tmp[0] == 'R')cnt[2]++; if(tmp[0] == 'C')cnt[3]++; if(tmp[0] == 'H')cnt[4]++; } ll wa = 0; //waC3だけど、かぶってる場合はできませんよと REP(i,10) { res += cnt[P[i]]*cnt[Q[i]]*cnt[R[i]]; } cout << res << endl; return 0; }
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "NR-InterNodeDefinitions" * found in "../../../rrc_15.5.1_asn.asn1" * `asn1c -D ./rrc_out_hlal -fcompound-names -fno-include-deps -findirect-choice -gen-PER -no-gen-example` */ #include "ConfigRestrictModReqSCG.h" #include "BandCombinationInfoSN.h" asn_TYPE_member_t asn_MBR_ConfigRestrictModReqSCG_1[] = { { ATF_POINTER, 2, offsetof(struct ConfigRestrictModReqSCG, requestedBC_MRDC), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_BandCombinationInfoSN, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "requestedBC-MRDC" }, { ATF_POINTER, 1, offsetof(struct ConfigRestrictModReqSCG, requestedP_MaxFR1), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_P_Max, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "requestedP-MaxFR1" }, }; static const int asn_MAP_ConfigRestrictModReqSCG_oms_1[] = { 0, 1 }; static const ber_tlv_tag_t asn_DEF_ConfigRestrictModReqSCG_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_ConfigRestrictModReqSCG_tag2el_1[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* requestedBC-MRDC */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* requestedP-MaxFR1 */ }; asn_SEQUENCE_specifics_t asn_SPC_ConfigRestrictModReqSCG_specs_1 = { sizeof(struct ConfigRestrictModReqSCG), offsetof(struct ConfigRestrictModReqSCG, _asn_ctx), asn_MAP_ConfigRestrictModReqSCG_tag2el_1, 2, /* Count of tags in the map */ asn_MAP_ConfigRestrictModReqSCG_oms_1, /* Optional members */ 2, 0, /* Root/Additions */ 2, /* First extension addition */ }; asn_TYPE_descriptor_t asn_DEF_ConfigRestrictModReqSCG = { "ConfigRestrictModReqSCG", "ConfigRestrictModReqSCG", &asn_OP_SEQUENCE, asn_DEF_ConfigRestrictModReqSCG_tags_1, sizeof(asn_DEF_ConfigRestrictModReqSCG_tags_1) /sizeof(asn_DEF_ConfigRestrictModReqSCG_tags_1[0]), /* 1 */ asn_DEF_ConfigRestrictModReqSCG_tags_1, /* Same as above */ sizeof(asn_DEF_ConfigRestrictModReqSCG_tags_1) /sizeof(asn_DEF_ConfigRestrictModReqSCG_tags_1[0]), /* 1 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_ConfigRestrictModReqSCG_1, 2, /* Elements count */ &asn_SPC_ConfigRestrictModReqSCG_specs_1 /* Additional specs */ };
#include <bits/stdc++.h> using namespace std; int main() { cin.sync_with_stdio(0); cin.tie(0); int n; int pointer; cin >> n; pointer = (n - 1) / 2; int xArray[n]; int yArray[n]; int x, y; for (int i = 0; i < n; ++i) { cin >> x >> y; xArray[i] = x; yArray[i] = y; } sort(xArray, xArray + n); sort(yArray, yArray + n); int xMid = xArray[pointer], yMid = yArray[pointer]; long long total = 0; for (int i = 0; i < n; ++i) { total += abs(xMid - xArray[i]) + abs(yMid - yArray[i]); } cout << total << "\n"; }
Excitation of an Electromagnetic Field in a Large Nerve Fiber by an Array of Electric-Dipole Filaments Excitation of an electromagnetic field with the desired spatial structure in a relatively large nerve fiber consisting of tightly packaged axons by an array of filamentary electric-dipole sources is studied. The procedure of finding the dipole moments of the filamentary sources located around the nerve fiber is proposed to ensure the required field pattern inside the nerve. Numerical results demonstrating the possibility of excitation of the desired field in the considered fiber are reported.
Production of hydrogen by ethanol steam reforming over nickel–metal oxide catalysts prepared via urea–nitrate combustion method A series of Ni/MgO catalysts have been prepared by a urea–nitrate combustion method, studied for the ethanol steam reforming, and compared with Ni/ZnO and Ni/Al2O3. The results show that Ni/MgO is superior to the latter two types of catalysts, especially in terms of H2 yield. Influential factors, including Ni loading, temperature, water‐to‐ethanol molar ratio, and liquid hourly space velocity, are investigated with the Ni/MgO catalyst. The conversions are always complete at temperatures above 773 K, regardless of the changes of the other reaction conditions. The hydrogen yield increases with increasing temperature and H2O/C2H5OH molar ratios, with up to 75% being obtained at 873 K, liquid hourly space velocity (LHSV) of 5.0 ml g–1 h–1 and H2O/C2H5OH molar ratio of 10. Copyright © 2010 John Wiley & Sons, Ltd.
import pytest from .data_providers import valid_customers @pytest.mark.parametrize("customer", valid_customers, ids=[repr(x) for x in valid_customers]) def test_can_register_customer(app, customer): old_ids = app.get_customer_ids() app.register_new_customer(customer) new_ids = app.get_customer_ids() assert all([i in new_ids for i in old_ids]) assert len(new_ids) == len(old_ids) + 1
Spatial distancing and social closeness: The work of creative professionals during the pandemic As a complete recovery from the COVID-19 pandemic crisis does not seem possible in the near future, the survival of many creative professions is under threat in Russia and other countries. Strict anti-pandemic measures were introduced in Moscow at the end of March 2020 and lasted for a little more than two months. One of the main requirements was to work from home and go outside as rarely as possible. Most Russian creative professionals such as photographers, makeup artists, actors, musicians, stand-up comedians and television hosts found themselves in very unfamiliar conditions since their work presumes physical contact with other people. However, even artists who usually work alone like jewellers or designers met with came across practical and psychological difficulties as well and had to adapt to the new order. This research focuses on two examples of creative work during the COVID-19 pandemic: Russian jewellery designer Katia Rabey’s project ‘Quarantine Rings’ and the participation of Russian makeup artist Yulia Rada in virtual commercial photo-shoots. I am interested in how the artists perceived the changes introduced as a result of the pandemic and how these changes emphasized the digital side of contemporary creative labour. Despite the differences in the challenges that the two artists met, both of them stressed the importance of social closeness.
// // FCObjectCaseTableViewCell.h // FCObjectCase // // Created by 石富才 on 2020/12/19. // #import <FCBaseKit/FCBaseKit.h> @interface FCObjectCaseTableViewCell : FCTableViewCell @end
/** * set_timing_db() - enable/disable Timing DB register * @ctrl: Pointer to controller host hardware. * @enable: Enable/Disable flag. * * Enable or Disabe the Timing DB register. */ void dsi_ctrl_hw_cmn_set_timing_db(struct dsi_ctrl_hw *ctrl, bool enable) { if (enable) DSI_W32(ctrl, DSI_DSI_TIMING_DB_MODE, 0x1); else DSI_W32(ctrl, DSI_DSI_TIMING_DB_MODE, 0x0); wmb(); pr_debug("[DSI_%d] ctrl timing DB set:%d\n", ctrl->index, enable); SDE_EVT32(ctrl->index, enable); }
<filename>org.xtext.grammars/org.xtext.component/componentParameter/org.xtext.component.componentParameter/src-gen/org/xtext/component/componentParameter/services/ComponentParameterGrammarAccess.java //================================================================ // // Copyright (C) 2017 <NAME>, <NAME>, <NAME> // // <EMAIL> // <EMAIL> // <EMAIL> // // Servicerobotik Ulm // <NAME> // Ulm University of Applied Sciences // Prittwitzstr. 10 // 89075 Ulm // Germany // // This file is part of the SmartMDSD Toolchain V3. // //================================================================ package org.xtext.component.componentParameter.services; import com.google.inject.Inject; import com.google.inject.Singleton; import java.util.List; import org.eclipse.xtext.Action; import org.eclipse.xtext.Alternatives; import org.eclipse.xtext.Assignment; import org.eclipse.xtext.CrossReference; import org.eclipse.xtext.EnumRule; import org.eclipse.xtext.Grammar; import org.eclipse.xtext.GrammarUtil; import org.eclipse.xtext.Group; import org.eclipse.xtext.Keyword; import org.eclipse.xtext.ParserRule; import org.eclipse.xtext.RuleCall; import org.eclipse.xtext.TerminalRule; import org.eclipse.xtext.common.services.TerminalsGrammarAccess; import org.eclipse.xtext.service.AbstractElementFinder.AbstractGrammarElementFinder; import org.eclipse.xtext.service.GrammarProvider; import org.xtext.base.basicAttributes.services.BasicAttributesGrammarAccess; import org.xtext.base.docuterminals.services.DocuTerminalsGrammarAccess; import org.xtext.service.parameterDefinition.services.ParameterDefinitionGrammarAccess; @Singleton public class ComponentParameterGrammarAccess extends AbstractGrammarElementFinder { public class ComponentParamModelElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.xtext.component.componentParameter.ComponentParameter.ComponentParamModel"); private final Group cGroup = (Group)rule.eContents().get(1); private final Action cComponentParamModelAction_0 = (Action)cGroup.eContents().get(0); private final Assignment cImportsAssignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cImportsParamDefRepoImportParserRuleCall_1_0 = (RuleCall)cImportsAssignment_1.eContents().get(0); private final Assignment cParametrizationAssignment_2 = (Assignment)cGroup.eContents().get(2); private final RuleCall cParametrizationComponentParameterParserRuleCall_2_0 = (RuleCall)cParametrizationAssignment_2.eContents().get(0); //ComponentParamModel componentParam::ComponentParamModel: // {componentParam::ComponentParamModel} imports+=super::ParamDefRepoImport* // parametrization=ComponentParameter?; @Override public ParserRule getRule() { return rule; } //{componentParam::ComponentParamModel} imports+=super::ParamDefRepoImport* parametrization=ComponentParameter? public Group getGroup() { return cGroup; } //{componentParam::ComponentParamModel} public Action getComponentParamModelAction_0() { return cComponentParamModelAction_0; } //imports+=super::ParamDefRepoImport* public Assignment getImportsAssignment_1() { return cImportsAssignment_1; } //super::ParamDefRepoImport public RuleCall getImportsParamDefRepoImportParserRuleCall_1_0() { return cImportsParamDefRepoImportParserRuleCall_1_0; } //parametrization=ComponentParameter? public Assignment getParametrizationAssignment_2() { return cParametrizationAssignment_2; } //ComponentParameter public RuleCall getParametrizationComponentParameterParserRuleCall_2_0() { return cParametrizationComponentParameterParserRuleCall_2_0; } } public class ComponentParameterElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.xtext.component.componentParameter.ComponentParameter.ComponentParameter"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cComponentParameterKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cNameAssignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cNameIDTerminalRuleCall_1_0 = (RuleCall)cNameAssignment_1.eContents().get(0); private final Group cGroup_2 = (Group)cGroup.eContents().get(2); private final Keyword cComponentKeyword_2_0 = (Keyword)cGroup_2.eContents().get(0); private final Assignment cComponentAssignment_2_1 = (Assignment)cGroup_2.eContents().get(1); private final CrossReference cComponentComponentDefinitionCrossReference_2_1_0 = (CrossReference)cComponentAssignment_2_1.eContents().get(0); private final RuleCall cComponentComponentDefinitionFQNParserRuleCall_2_1_0_1 = (RuleCall)cComponentComponentDefinitionCrossReference_2_1_0.eContents().get(1); private final Keyword cLeftCurlyBracketKeyword_3 = (Keyword)cGroup.eContents().get(3); private final Assignment cParametersAssignment_4 = (Assignment)cGroup.eContents().get(4); private final RuleCall cParametersAbstractComponentParameterParserRuleCall_4_0 = (RuleCall)cParametersAssignment_4.eContents().get(0); private final Keyword cRightCurlyBracketKeyword_5 = (Keyword)cGroup.eContents().get(5); //ComponentParameter componentParam::ComponentParameter: // 'ComponentParameter' name=ID ('component' component=[componentDefinition::ComponentDefinition|FQN])? // '{' // parameters+=AbstractComponentParameter* // '}'; @Override public ParserRule getRule() { return rule; } //'ComponentParameter' name=ID ('component' component=[componentDefinition::ComponentDefinition|FQN])? '{' //parameters+=AbstractComponentParameter* '}' public Group getGroup() { return cGroup; } //'ComponentParameter' public Keyword getComponentParameterKeyword_0() { return cComponentParameterKeyword_0; } //name=ID public Assignment getNameAssignment_1() { return cNameAssignment_1; } //ID public RuleCall getNameIDTerminalRuleCall_1_0() { return cNameIDTerminalRuleCall_1_0; } //('component' component=[componentDefinition::ComponentDefinition|FQN])? public Group getGroup_2() { return cGroup_2; } //'component' public Keyword getComponentKeyword_2_0() { return cComponentKeyword_2_0; } //component=[componentDefinition::ComponentDefinition|FQN] public Assignment getComponentAssignment_2_1() { return cComponentAssignment_2_1; } //[componentDefinition::ComponentDefinition|FQN] public CrossReference getComponentComponentDefinitionCrossReference_2_1_0() { return cComponentComponentDefinitionCrossReference_2_1_0; } //FQN public RuleCall getComponentComponentDefinitionFQNParserRuleCall_2_1_0_1() { return cComponentComponentDefinitionFQNParserRuleCall_2_1_0_1; } //'{' public Keyword getLeftCurlyBracketKeyword_3() { return cLeftCurlyBracketKeyword_3; } //parameters+=AbstractComponentParameter* public Assignment getParametersAssignment_4() { return cParametersAssignment_4; } //AbstractComponentParameter public RuleCall getParametersAbstractComponentParameterParserRuleCall_4_0() { return cParametersAbstractComponentParameterParserRuleCall_4_0; } //'}' public Keyword getRightCurlyBracketKeyword_5() { return cRightCurlyBracketKeyword_5; } } public class AbstractComponentParameterElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.xtext.component.componentParameter.ComponentParameter.AbstractComponentParameter"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final RuleCall cInternalParameterParserRuleCall_0 = (RuleCall)cAlternatives.eContents().get(0); private final RuleCall cExtendedParameterParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cExtendedTriggerParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cParameterSetInstanceParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); //AbstractComponentParameter componentParam::AbstractComponentParameter: // InternalParameter | ExtendedParameter | ExtendedTrigger | ParameterSetInstance; @Override public ParserRule getRule() { return rule; } //InternalParameter | ExtendedParameter | ExtendedTrigger | ParameterSetInstance public Alternatives getAlternatives() { return cAlternatives; } //InternalParameter public RuleCall getInternalParameterParserRuleCall_0() { return cInternalParameterParserRuleCall_0; } //ExtendedParameter public RuleCall getExtendedParameterParserRuleCall_1() { return cExtendedParameterParserRuleCall_1; } //ExtendedTrigger public RuleCall getExtendedTriggerParserRuleCall_2() { return cExtendedTriggerParserRuleCall_2; } //ParameterSetInstance public RuleCall getParameterSetInstanceParserRuleCall_3() { return cParameterSetInstanceParserRuleCall_3; } } public class InternalParameterElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.xtext.component.componentParameter.ComponentParameter.InternalParameter"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cDocumentationAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cDocumentationDOCU_COMMENTTerminalRuleCall_0_0 = (RuleCall)cDocumentationAssignment_0.eContents().get(0); private final Keyword cInternalParameterKeyword_1 = (Keyword)cGroup.eContents().get(1); private final Assignment cNameAssignment_2 = (Assignment)cGroup.eContents().get(2); private final RuleCall cNameIDTerminalRuleCall_2_0 = (RuleCall)cNameAssignment_2.eContents().get(0); private final Keyword cLeftCurlyBracketKeyword_3 = (Keyword)cGroup.eContents().get(3); private final Assignment cAttributesAssignment_4 = (Assignment)cGroup.eContents().get(4); private final RuleCall cAttributesAttributeDefinitionParserRuleCall_4_0 = (RuleCall)cAttributesAssignment_4.eContents().get(0); private final Keyword cRightCurlyBracketKeyword_5 = (Keyword)cGroup.eContents().get(5); //InternalParameter componentParam::InternalParameter: // documentation=DOCU_COMMENT? // 'InternalParameter' name=ID // '{' // attributes+=BasicAttributes::AttributeDefinition* // '}'; @Override public ParserRule getRule() { return rule; } //documentation=DOCU_COMMENT? 'InternalParameter' name=ID '{' attributes+=BasicAttributes::AttributeDefinition* '}' public Group getGroup() { return cGroup; } //documentation=DOCU_COMMENT? public Assignment getDocumentationAssignment_0() { return cDocumentationAssignment_0; } //DOCU_COMMENT public RuleCall getDocumentationDOCU_COMMENTTerminalRuleCall_0_0() { return cDocumentationDOCU_COMMENTTerminalRuleCall_0_0; } //'InternalParameter' public Keyword getInternalParameterKeyword_1() { return cInternalParameterKeyword_1; } //name=ID public Assignment getNameAssignment_2() { return cNameAssignment_2; } //ID public RuleCall getNameIDTerminalRuleCall_2_0() { return cNameIDTerminalRuleCall_2_0; } //'{' public Keyword getLeftCurlyBracketKeyword_3() { return cLeftCurlyBracketKeyword_3; } //attributes+=BasicAttributes::AttributeDefinition* public Assignment getAttributesAssignment_4() { return cAttributesAssignment_4; } //BasicAttributes::AttributeDefinition public RuleCall getAttributesAttributeDefinitionParserRuleCall_4_0() { return cAttributesAttributeDefinitionParserRuleCall_4_0; } //'}' public Keyword getRightCurlyBracketKeyword_5() { return cRightCurlyBracketKeyword_5; } } public class ExtendedParameterElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.xtext.component.componentParameter.ComponentParameter.ExtendedParameter"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cDocumentationAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cDocumentationDOCU_COMMENTTerminalRuleCall_0_0 = (RuleCall)cDocumentationAssignment_0.eContents().get(0); private final Keyword cExtendedParameterKeyword_1 = (Keyword)cGroup.eContents().get(1); private final Assignment cNameAssignment_2 = (Assignment)cGroup.eContents().get(2); private final RuleCall cNameIDTerminalRuleCall_2_0 = (RuleCall)cNameAssignment_2.eContents().get(0); private final Keyword cLeftCurlyBracketKeyword_3 = (Keyword)cGroup.eContents().get(3); private final Assignment cAttributesAssignment_4 = (Assignment)cGroup.eContents().get(4); private final RuleCall cAttributesAttributeDefinitionParserRuleCall_4_0 = (RuleCall)cAttributesAssignment_4.eContents().get(0); private final Keyword cRightCurlyBracketKeyword_5 = (Keyword)cGroup.eContents().get(5); //ExtendedParameter componentParam::ExtendedParameter: // documentation=DOCU_COMMENT? // 'ExtendedParameter' name=ID // '{' // attributes+=BasicAttributes::AttributeDefinition* // '}'; @Override public ParserRule getRule() { return rule; } //documentation=DOCU_COMMENT? 'ExtendedParameter' name=ID '{' attributes+=BasicAttributes::AttributeDefinition* '}' public Group getGroup() { return cGroup; } //documentation=DOCU_COMMENT? public Assignment getDocumentationAssignment_0() { return cDocumentationAssignment_0; } //DOCU_COMMENT public RuleCall getDocumentationDOCU_COMMENTTerminalRuleCall_0_0() { return cDocumentationDOCU_COMMENTTerminalRuleCall_0_0; } //'ExtendedParameter' public Keyword getExtendedParameterKeyword_1() { return cExtendedParameterKeyword_1; } //name=ID public Assignment getNameAssignment_2() { return cNameAssignment_2; } //ID public RuleCall getNameIDTerminalRuleCall_2_0() { return cNameIDTerminalRuleCall_2_0; } //'{' public Keyword getLeftCurlyBracketKeyword_3() { return cLeftCurlyBracketKeyword_3; } //attributes+=BasicAttributes::AttributeDefinition* public Assignment getAttributesAssignment_4() { return cAttributesAssignment_4; } //BasicAttributes::AttributeDefinition public RuleCall getAttributesAttributeDefinitionParserRuleCall_4_0() { return cAttributesAttributeDefinitionParserRuleCall_4_0; } //'}' public Keyword getRightCurlyBracketKeyword_5() { return cRightCurlyBracketKeyword_5; } } public class ExtendedTriggerElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.xtext.component.componentParameter.ComponentParameter.ExtendedTrigger"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cDocumentationAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cDocumentationDOCU_COMMENTTerminalRuleCall_0_0 = (RuleCall)cDocumentationAssignment_0.eContents().get(0); private final Keyword cExtendedTriggerKeyword_1 = (Keyword)cGroup.eContents().get(1); private final Assignment cNameAssignment_2 = (Assignment)cGroup.eContents().get(2); private final RuleCall cNameIDTerminalRuleCall_2_0 = (RuleCall)cNameAssignment_2.eContents().get(0); private final Alternatives cAlternatives_3 = (Alternatives)cGroup.eContents().get(3); private final Assignment cActiveAssignment_3_0 = (Assignment)cAlternatives_3.eContents().get(0); private final Keyword cActiveActiveKeyword_3_0_0 = (Keyword)cActiveAssignment_3_0.eContents().get(0); private final Keyword cPassiveKeyword_3_1 = (Keyword)cAlternatives_3.eContents().get(1); private final Keyword cLeftCurlyBracketKeyword_4 = (Keyword)cGroup.eContents().get(4); private final Assignment cAttributesAssignment_5 = (Assignment)cGroup.eContents().get(5); private final RuleCall cAttributesAttributeDefinitionParserRuleCall_5_0 = (RuleCall)cAttributesAssignment_5.eContents().get(0); private final Keyword cRightCurlyBracketKeyword_6 = (Keyword)cGroup.eContents().get(6); //ExtendedTrigger componentParam::ExtendedTrigger: // documentation=DOCU_COMMENT? // 'ExtendedTrigger' name=ID (active?='active' | 'passive') // '{' // attributes+=BasicAttributes::AttributeDefinition* // '}'; @Override public ParserRule getRule() { return rule; } //documentation=DOCU_COMMENT? 'ExtendedTrigger' name=ID (active?='active' | 'passive') '{' //attributes+=BasicAttributes::AttributeDefinition* '}' public Group getGroup() { return cGroup; } //documentation=DOCU_COMMENT? public Assignment getDocumentationAssignment_0() { return cDocumentationAssignment_0; } //DOCU_COMMENT public RuleCall getDocumentationDOCU_COMMENTTerminalRuleCall_0_0() { return cDocumentationDOCU_COMMENTTerminalRuleCall_0_0; } //'ExtendedTrigger' public Keyword getExtendedTriggerKeyword_1() { return cExtendedTriggerKeyword_1; } //name=ID public Assignment getNameAssignment_2() { return cNameAssignment_2; } //ID public RuleCall getNameIDTerminalRuleCall_2_0() { return cNameIDTerminalRuleCall_2_0; } //active?='active' | 'passive' public Alternatives getAlternatives_3() { return cAlternatives_3; } //active?='active' public Assignment getActiveAssignment_3_0() { return cActiveAssignment_3_0; } //'active' public Keyword getActiveActiveKeyword_3_0_0() { return cActiveActiveKeyword_3_0_0; } //'passive' public Keyword getPassiveKeyword_3_1() { return cPassiveKeyword_3_1; } //'{' public Keyword getLeftCurlyBracketKeyword_4() { return cLeftCurlyBracketKeyword_4; } //attributes+=BasicAttributes::AttributeDefinition* public Assignment getAttributesAssignment_5() { return cAttributesAssignment_5; } //BasicAttributes::AttributeDefinition public RuleCall getAttributesAttributeDefinitionParserRuleCall_5_0() { return cAttributesAttributeDefinitionParserRuleCall_5_0; } //'}' public Keyword getRightCurlyBracketKeyword_6() { return cRightCurlyBracketKeyword_6; } } public class ParameterSetInstanceElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.xtext.component.componentParameter.ComponentParameter.ParameterSetInstance"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cDocumentationAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cDocumentationDOCU_COMMENTTerminalRuleCall_0_0 = (RuleCall)cDocumentationAssignment_0.eContents().get(0); private final Keyword cParameterSetInstanceKeyword_1 = (Keyword)cGroup.eContents().get(1); private final Assignment cParamSetAssignment_2 = (Assignment)cGroup.eContents().get(2); private final CrossReference cParamSetParameterSetDefinitionCrossReference_2_0 = (CrossReference)cParamSetAssignment_2.eContents().get(0); private final RuleCall cParamSetParameterSetDefinitionFQNParserRuleCall_2_0_1 = (RuleCall)cParamSetParameterSetDefinitionCrossReference_2_0.eContents().get(1); private final Keyword cLeftCurlyBracketKeyword_3 = (Keyword)cGroup.eContents().get(3); private final Assignment cParameterInstancesAssignment_4 = (Assignment)cGroup.eContents().get(4); private final RuleCall cParameterInstancesAbstractParameterInstanceParserRuleCall_4_0 = (RuleCall)cParameterInstancesAssignment_4.eContents().get(0); private final Keyword cRightCurlyBracketKeyword_5 = (Keyword)cGroup.eContents().get(5); //ParameterSetInstance componentParam::ParameterSetInstance: // documentation=DOCU_COMMENT? // 'ParameterSetInstance' paramSet=[parameterDefinition::ParameterSetDefinition|FQN] // '{' // parameterInstances+=AbstractParameterInstance* // '}'; @Override public ParserRule getRule() { return rule; } //documentation=DOCU_COMMENT? 'ParameterSetInstance' paramSet=[parameterDefinition::ParameterSetDefinition|FQN] '{' //parameterInstances+=AbstractParameterInstance* '}' public Group getGroup() { return cGroup; } //documentation=DOCU_COMMENT? public Assignment getDocumentationAssignment_0() { return cDocumentationAssignment_0; } //DOCU_COMMENT public RuleCall getDocumentationDOCU_COMMENTTerminalRuleCall_0_0() { return cDocumentationDOCU_COMMENTTerminalRuleCall_0_0; } //'ParameterSetInstance' public Keyword getParameterSetInstanceKeyword_1() { return cParameterSetInstanceKeyword_1; } //paramSet=[parameterDefinition::ParameterSetDefinition|FQN] public Assignment getParamSetAssignment_2() { return cParamSetAssignment_2; } //[parameterDefinition::ParameterSetDefinition|FQN] public CrossReference getParamSetParameterSetDefinitionCrossReference_2_0() { return cParamSetParameterSetDefinitionCrossReference_2_0; } //FQN public RuleCall getParamSetParameterSetDefinitionFQNParserRuleCall_2_0_1() { return cParamSetParameterSetDefinitionFQNParserRuleCall_2_0_1; } //'{' public Keyword getLeftCurlyBracketKeyword_3() { return cLeftCurlyBracketKeyword_3; } //parameterInstances+=AbstractParameterInstance* public Assignment getParameterInstancesAssignment_4() { return cParameterInstancesAssignment_4; } //AbstractParameterInstance public RuleCall getParameterInstancesAbstractParameterInstanceParserRuleCall_4_0() { return cParameterInstancesAbstractParameterInstanceParserRuleCall_4_0; } //'}' public Keyword getRightCurlyBracketKeyword_5() { return cRightCurlyBracketKeyword_5; } } public class AbstractParameterInstanceElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.xtext.component.componentParameter.ComponentParameter.AbstractParameterInstance"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final RuleCall cTriggerInstanceParserRuleCall_0 = (RuleCall)cAlternatives.eContents().get(0); private final RuleCall cParameterInstanceParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); //AbstractParameterInstance componentParam::AbstractParameterInstance: // TriggerInstance | ParameterInstance; @Override public ParserRule getRule() { return rule; } //TriggerInstance | ParameterInstance public Alternatives getAlternatives() { return cAlternatives; } //TriggerInstance public RuleCall getTriggerInstanceParserRuleCall_0() { return cTriggerInstanceParserRuleCall_0; } //ParameterInstance public RuleCall getParameterInstanceParserRuleCall_1() { return cParameterInstanceParserRuleCall_1; } } public class TriggerInstanceElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.xtext.component.componentParameter.ComponentParameter.TriggerInstance"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cDocumentationAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cDocumentationDOCU_COMMENTTerminalRuleCall_0_0 = (RuleCall)cDocumentationAssignment_0.eContents().get(0); private final Keyword cTriggerInstanceKeyword_1 = (Keyword)cGroup.eContents().get(1); private final Assignment cTriggerDefAssignment_2 = (Assignment)cGroup.eContents().get(2); private final CrossReference cTriggerDefTriggerDefinitionCrossReference_2_0 = (CrossReference)cTriggerDefAssignment_2.eContents().get(0); private final RuleCall cTriggerDefTriggerDefinitionFQNParserRuleCall_2_0_1 = (RuleCall)cTriggerDefTriggerDefinitionCrossReference_2_0.eContents().get(1); private final Alternatives cAlternatives_3 = (Alternatives)cGroup.eContents().get(3); private final Assignment cActiveAssignment_3_0 = (Assignment)cAlternatives_3.eContents().get(0); private final Keyword cActiveActiveKeyword_3_0_0 = (Keyword)cActiveAssignment_3_0.eContents().get(0); private final Keyword cPassiveKeyword_3_1 = (Keyword)cAlternatives_3.eContents().get(1); private final Keyword cSemicolonKeyword_4 = (Keyword)cGroup.eContents().get(4); //TriggerInstance componentParam::TriggerInstance: // documentation=DOCU_COMMENT? // 'TriggerInstance' triggerDef=[parameterDefinition::TriggerDefinition|FQN] (active?='active' | 'passive') ';'?; @Override public ParserRule getRule() { return rule; } //documentation=DOCU_COMMENT? 'TriggerInstance' triggerDef=[parameterDefinition::TriggerDefinition|FQN] (active?='active' //| 'passive') ';'? public Group getGroup() { return cGroup; } //documentation=DOCU_COMMENT? public Assignment getDocumentationAssignment_0() { return cDocumentationAssignment_0; } //DOCU_COMMENT public RuleCall getDocumentationDOCU_COMMENTTerminalRuleCall_0_0() { return cDocumentationDOCU_COMMENTTerminalRuleCall_0_0; } //'TriggerInstance' public Keyword getTriggerInstanceKeyword_1() { return cTriggerInstanceKeyword_1; } //triggerDef=[parameterDefinition::TriggerDefinition|FQN] public Assignment getTriggerDefAssignment_2() { return cTriggerDefAssignment_2; } //[parameterDefinition::TriggerDefinition|FQN] public CrossReference getTriggerDefTriggerDefinitionCrossReference_2_0() { return cTriggerDefTriggerDefinitionCrossReference_2_0; } //FQN public RuleCall getTriggerDefTriggerDefinitionFQNParserRuleCall_2_0_1() { return cTriggerDefTriggerDefinitionFQNParserRuleCall_2_0_1; } //active?='active' | 'passive' public Alternatives getAlternatives_3() { return cAlternatives_3; } //active?='active' public Assignment getActiveAssignment_3_0() { return cActiveAssignment_3_0; } //'active' public Keyword getActiveActiveKeyword_3_0_0() { return cActiveActiveKeyword_3_0_0; } //'passive' public Keyword getPassiveKeyword_3_1() { return cPassiveKeyword_3_1; } //';'? public Keyword getSemicolonKeyword_4() { return cSemicolonKeyword_4; } } public class ParameterInstanceElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.xtext.component.componentParameter.ComponentParameter.ParameterInstance"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cDocumentationAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cDocumentationDOCU_COMMENTTerminalRuleCall_0_0 = (RuleCall)cDocumentationAssignment_0.eContents().get(0); private final Keyword cParameterInstanceKeyword_1 = (Keyword)cGroup.eContents().get(1); private final Assignment cParameterDefAssignment_2 = (Assignment)cGroup.eContents().get(2); private final CrossReference cParameterDefParameterDefinitionCrossReference_2_0 = (CrossReference)cParameterDefAssignment_2.eContents().get(0); private final RuleCall cParameterDefParameterDefinitionFQNParserRuleCall_2_0_1 = (RuleCall)cParameterDefParameterDefinitionCrossReference_2_0.eContents().get(1); private final Keyword cLeftCurlyBracketKeyword_3 = (Keyword)cGroup.eContents().get(3); private final Assignment cAttributesAssignment_4 = (Assignment)cGroup.eContents().get(4); private final RuleCall cAttributesAttributeRefinementParserRuleCall_4_0 = (RuleCall)cAttributesAssignment_4.eContents().get(0); private final Keyword cRightCurlyBracketKeyword_5 = (Keyword)cGroup.eContents().get(5); //ParameterInstance componentParam::ParameterInstance: // documentation=DOCU_COMMENT? // 'ParameterInstance' parameterDef=[parameterDefinition::ParameterDefinition|FQN] // '{' // attributes+=BasicAttributes::AttributeRefinement* // '}'; @Override public ParserRule getRule() { return rule; } //documentation=DOCU_COMMENT? 'ParameterInstance' parameterDef=[parameterDefinition::ParameterDefinition|FQN] '{' //attributes+=BasicAttributes::AttributeRefinement* '}' public Group getGroup() { return cGroup; } //documentation=DOCU_COMMENT? public Assignment getDocumentationAssignment_0() { return cDocumentationAssignment_0; } //DOCU_COMMENT public RuleCall getDocumentationDOCU_COMMENTTerminalRuleCall_0_0() { return cDocumentationDOCU_COMMENTTerminalRuleCall_0_0; } //'ParameterInstance' public Keyword getParameterInstanceKeyword_1() { return cParameterInstanceKeyword_1; } //parameterDef=[parameterDefinition::ParameterDefinition|FQN] public Assignment getParameterDefAssignment_2() { return cParameterDefAssignment_2; } //[parameterDefinition::ParameterDefinition|FQN] public CrossReference getParameterDefParameterDefinitionCrossReference_2_0() { return cParameterDefParameterDefinitionCrossReference_2_0; } //FQN public RuleCall getParameterDefParameterDefinitionFQNParserRuleCall_2_0_1() { return cParameterDefParameterDefinitionFQNParserRuleCall_2_0_1; } //'{' public Keyword getLeftCurlyBracketKeyword_3() { return cLeftCurlyBracketKeyword_3; } //attributes+=BasicAttributes::AttributeRefinement* public Assignment getAttributesAssignment_4() { return cAttributesAssignment_4; } //BasicAttributes::AttributeRefinement public RuleCall getAttributesAttributeRefinementParserRuleCall_4_0() { return cAttributesAttributeRefinementParserRuleCall_4_0; } //'}' public Keyword getRightCurlyBracketKeyword_5() { return cRightCurlyBracketKeyword_5; } } private final ComponentParamModelElements pComponentParamModel; private final ComponentParameterElements pComponentParameter; private final AbstractComponentParameterElements pAbstractComponentParameter; private final InternalParameterElements pInternalParameter; private final ExtendedParameterElements pExtendedParameter; private final ExtendedTriggerElements pExtendedTrigger; private final ParameterSetInstanceElements pParameterSetInstance; private final AbstractParameterInstanceElements pAbstractParameterInstance; private final TriggerInstanceElements pTriggerInstance; private final ParameterInstanceElements pParameterInstance; private final Grammar grammar; private final ParameterDefinitionGrammarAccess gaParameterDefinition; private final BasicAttributesGrammarAccess gaBasicAttributes; private final DocuTerminalsGrammarAccess gaDocuTerminals; private final TerminalsGrammarAccess gaTerminals; @Inject public ComponentParameterGrammarAccess(GrammarProvider grammarProvider, ParameterDefinitionGrammarAccess gaParameterDefinition, BasicAttributesGrammarAccess gaBasicAttributes, DocuTerminalsGrammarAccess gaDocuTerminals, TerminalsGrammarAccess gaTerminals) { this.grammar = internalFindGrammar(grammarProvider); this.gaParameterDefinition = gaParameterDefinition; this.gaBasicAttributes = gaBasicAttributes; this.gaDocuTerminals = gaDocuTerminals; this.gaTerminals = gaTerminals; this.pComponentParamModel = new ComponentParamModelElements(); this.pComponentParameter = new ComponentParameterElements(); this.pAbstractComponentParameter = new AbstractComponentParameterElements(); this.pInternalParameter = new InternalParameterElements(); this.pExtendedParameter = new ExtendedParameterElements(); this.pExtendedTrigger = new ExtendedTriggerElements(); this.pParameterSetInstance = new ParameterSetInstanceElements(); this.pAbstractParameterInstance = new AbstractParameterInstanceElements(); this.pTriggerInstance = new TriggerInstanceElements(); this.pParameterInstance = new ParameterInstanceElements(); } protected Grammar internalFindGrammar(GrammarProvider grammarProvider) { Grammar grammar = grammarProvider.getGrammar(this); while (grammar != null) { if ("org.xtext.component.componentParameter.ComponentParameter".equals(grammar.getName())) { return grammar; } List<Grammar> grammars = grammar.getUsedGrammars(); if (!grammars.isEmpty()) { grammar = grammars.iterator().next(); } else { return null; } } return grammar; } @Override public Grammar getGrammar() { return grammar; } public ParameterDefinitionGrammarAccess getParameterDefinitionGrammarAccess() { return gaParameterDefinition; } public BasicAttributesGrammarAccess getBasicAttributesGrammarAccess() { return gaBasicAttributes; } public DocuTerminalsGrammarAccess getDocuTerminalsGrammarAccess() { return gaDocuTerminals; } public TerminalsGrammarAccess getTerminalsGrammarAccess() { return gaTerminals; } //ComponentParamModel componentParam::ComponentParamModel: // {componentParam::ComponentParamModel} imports+=super::ParamDefRepoImport* // parametrization=ComponentParameter?; public ComponentParamModelElements getComponentParamModelAccess() { return pComponentParamModel; } public ParserRule getComponentParamModelRule() { return getComponentParamModelAccess().getRule(); } //ComponentParameter componentParam::ComponentParameter: // 'ComponentParameter' name=ID ('component' component=[componentDefinition::ComponentDefinition|FQN])? // '{' // parameters+=AbstractComponentParameter* // '}'; public ComponentParameterElements getComponentParameterAccess() { return pComponentParameter; } public ParserRule getComponentParameterRule() { return getComponentParameterAccess().getRule(); } //AbstractComponentParameter componentParam::AbstractComponentParameter: // InternalParameter | ExtendedParameter | ExtendedTrigger | ParameterSetInstance; public AbstractComponentParameterElements getAbstractComponentParameterAccess() { return pAbstractComponentParameter; } public ParserRule getAbstractComponentParameterRule() { return getAbstractComponentParameterAccess().getRule(); } //InternalParameter componentParam::InternalParameter: // documentation=DOCU_COMMENT? // 'InternalParameter' name=ID // '{' // attributes+=BasicAttributes::AttributeDefinition* // '}'; public InternalParameterElements getInternalParameterAccess() { return pInternalParameter; } public ParserRule getInternalParameterRule() { return getInternalParameterAccess().getRule(); } //ExtendedParameter componentParam::ExtendedParameter: // documentation=DOCU_COMMENT? // 'ExtendedParameter' name=ID // '{' // attributes+=BasicAttributes::AttributeDefinition* // '}'; public ExtendedParameterElements getExtendedParameterAccess() { return pExtendedParameter; } public ParserRule getExtendedParameterRule() { return getExtendedParameterAccess().getRule(); } //ExtendedTrigger componentParam::ExtendedTrigger: // documentation=DOCU_COMMENT? // 'ExtendedTrigger' name=ID (active?='active' | 'passive') // '{' // attributes+=BasicAttributes::AttributeDefinition* // '}'; public ExtendedTriggerElements getExtendedTriggerAccess() { return pExtendedTrigger; } public ParserRule getExtendedTriggerRule() { return getExtendedTriggerAccess().getRule(); } //ParameterSetInstance componentParam::ParameterSetInstance: // documentation=DOCU_COMMENT? // 'ParameterSetInstance' paramSet=[parameterDefinition::ParameterSetDefinition|FQN] // '{' // parameterInstances+=AbstractParameterInstance* // '}'; public ParameterSetInstanceElements getParameterSetInstanceAccess() { return pParameterSetInstance; } public ParserRule getParameterSetInstanceRule() { return getParameterSetInstanceAccess().getRule(); } //AbstractParameterInstance componentParam::AbstractParameterInstance: // TriggerInstance | ParameterInstance; public AbstractParameterInstanceElements getAbstractParameterInstanceAccess() { return pAbstractParameterInstance; } public ParserRule getAbstractParameterInstanceRule() { return getAbstractParameterInstanceAccess().getRule(); } //TriggerInstance componentParam::TriggerInstance: // documentation=DOCU_COMMENT? // 'TriggerInstance' triggerDef=[parameterDefinition::TriggerDefinition|FQN] (active?='active' | 'passive') ';'?; public TriggerInstanceElements getTriggerInstanceAccess() { return pTriggerInstance; } public ParserRule getTriggerInstanceRule() { return getTriggerInstanceAccess().getRule(); } //ParameterInstance componentParam::ParameterInstance: // documentation=DOCU_COMMENT? // 'ParameterInstance' parameterDef=[parameterDefinition::ParameterDefinition|FQN] // '{' // attributes+=BasicAttributes::AttributeRefinement* // '}'; public ParameterInstanceElements getParameterInstanceAccess() { return pParameterInstance; } public ParserRule getParameterInstanceRule() { return getParameterInstanceAccess().getRule(); } //ParamDefModel param::ParamDefModel: // {param::ParamDefModel} imports+=ParamDefRepoImport* // repository=ParameterSetRepository?; public ParameterDefinitionGrammarAccess.ParamDefModelElements getParamDefModelAccess() { return gaParameterDefinition.getParamDefModelAccess(); } public ParserRule getParamDefModelRule() { return getParamDefModelAccess().getRule(); } //// parser rules for names //FQNW: // FQN '.*'?; public ParameterDefinitionGrammarAccess.FQNWElements getFQNWAccess() { return gaParameterDefinition.getFQNWAccess(); } public ParserRule getFQNWRule() { return getFQNWAccess().getRule(); } //ParamDefRepoImport param::ParamDefRepoImport: // '#import' importedNamespace=FQNW ';'?; public ParameterDefinitionGrammarAccess.ParamDefRepoImportElements getParamDefRepoImportAccess() { return gaParameterDefinition.getParamDefRepoImportAccess(); } public ParserRule getParamDefRepoImportRule() { return getParamDefRepoImportAccess().getRule(); } //ParameterSetRepository param::ParameterSetRepository: // documentation=DOCU_COMMENT? // 'ParameterSetRepository' name=ID // '{' // sets+=ParameterSetDefinition* // '}'; public ParameterDefinitionGrammarAccess.ParameterSetRepositoryElements getParameterSetRepositoryAccess() { return gaParameterDefinition.getParameterSetRepositoryAccess(); } public ParserRule getParameterSetRepositoryRule() { return getParameterSetRepositoryAccess().getRule(); } //ParameterSetDefinition param::ParameterSetDefinition: // documentation=DOCU_COMMENT? // 'ParameterSet' name=ID ('extends' extends+=[param::ParameterSetDefinition|FQN] ("," // extends+=[param::ParameterSetDefinition|FQN])*)? // '{' // parameters+=AbstractParameter* // '}'; public ParameterDefinitionGrammarAccess.ParameterSetDefinitionElements getParameterSetDefinitionAccess() { return gaParameterDefinition.getParameterSetDefinitionAccess(); } public ParserRule getParameterSetDefinitionRule() { return getParameterSetDefinitionAccess().getRule(); } //AbstractParameter param::AbstractParameter: // ParameterDefinition | TriggerDefinition; public ParameterDefinitionGrammarAccess.AbstractParameterElements getAbstractParameterAccess() { return gaParameterDefinition.getAbstractParameterAccess(); } public ParserRule getAbstractParameterRule() { return getAbstractParameterAccess().getRule(); } //ParameterDefinition param::ParameterDefinition: // documentation=DOCU_COMMENT? // 'Parameter' name=ID // '{' // attributes+=AttributeDefinition* // '}'; public ParameterDefinitionGrammarAccess.ParameterDefinitionElements getParameterDefinitionAccess() { return gaParameterDefinition.getParameterDefinitionAccess(); } public ParserRule getParameterDefinitionRule() { return getParameterDefinitionAccess().getRule(); } //TriggerDefinition param::TriggerDefinition: // documentation=DOCU_COMMENT? // 'Trigger' name=ID // '{' // attributes+=AttributeDefinition* // '}'; public ParameterDefinitionGrammarAccess.TriggerDefinitionElements getTriggerDefinitionAccess() { return gaParameterDefinition.getTriggerDefinitionAccess(); } public ParserRule getTriggerDefinitionRule() { return getTriggerDefinitionAccess().getRule(); } //AttributeDefinition attr::AttributeDefinition: // documentation=DOCU_COMMENT? // name=ID ':' type=AbstractAttributeType ('=' defaultvalue=AbstractValue)? ';'?; public BasicAttributesGrammarAccess.AttributeDefinitionElements getAttributeDefinitionAccess() { return gaBasicAttributes.getAttributeDefinitionAccess(); } public ParserRule getAttributeDefinitionRule() { return getAttributeDefinitionAccess().getRule(); } //AttributeRefinement attr::AttributeRefinement: // documentation=DOCU_COMMENT? // attribute=[attr::AttributeDefinition|FQN] '=' value=AbstractValue ';'?; public BasicAttributesGrammarAccess.AttributeRefinementElements getAttributeRefinementAccess() { return gaBasicAttributes.getAttributeRefinementAccess(); } public ParserRule getAttributeRefinementRule() { return getAttributeRefinementAccess().getRule(); } //// parser rules for names //FQN: // ID ('.' ID)*; public BasicAttributesGrammarAccess.FQNElements getFQNAccess() { return gaBasicAttributes.getFQNAccess(); } public ParserRule getFQNRule() { return getFQNAccess().getRule(); } //EBoolean ecore::EBoolean: // 'true' | 'false'; public BasicAttributesGrammarAccess.EBooleanElements getEBooleanAccess() { return gaBasicAttributes.getEBooleanAccess(); } public ParserRule getEBooleanRule() { return getEBooleanAccess().getRule(); } //EString: // STRING; public BasicAttributesGrammarAccess.EStringElements getEStringAccess() { return gaBasicAttributes.getEStringAccess(); } public ParserRule getEStringRule() { return getEStringAccess().getRule(); } //EInt ecore::EInt: // '-'? INT; public BasicAttributesGrammarAccess.EIntElements getEIntAccess() { return gaBasicAttributes.getEIntAccess(); } public ParserRule getEIntRule() { return getEIntAccess().getRule(); } //EDouble ecore::EDouble: // '-'? INT? '.' INT (('E' | 'e') '-'? INT)?; public BasicAttributesGrammarAccess.EDoubleElements getEDoubleAccess() { return gaBasicAttributes.getEDoubleAccess(); } public ParserRule getEDoubleRule() { return getEDoubleAccess().getRule(); } //EnumerationElement attr::EnumerationElement: // name=ID ('=' value=EInt)? ';'?; public BasicAttributesGrammarAccess.EnumerationElementElements getEnumerationElementAccess() { return gaBasicAttributes.getEnumerationElementAccess(); } public ParserRule getEnumerationElementRule() { return getEnumerationElementAccess().getRule(); } //AbstractAttributeType attr::AbstractAttributeType: // PrimitiveType | InlineEnumerationType; public BasicAttributesGrammarAccess.AbstractAttributeTypeElements getAbstractAttributeTypeAccess() { return gaBasicAttributes.getAbstractAttributeTypeAccess(); } public ParserRule getAbstractAttributeTypeRule() { return getAbstractAttributeTypeAccess().getRule(); } //InlineEnumerationType attr::InlineEnumerationType: // 'InlineEnumeration' array=ArrayType? '{' enums+=EnumerationElement+ '}'; public BasicAttributesGrammarAccess.InlineEnumerationTypeElements getInlineEnumerationTypeAccess() { return gaBasicAttributes.getInlineEnumerationTypeAccess(); } public ParserRule getInlineEnumerationTypeRule() { return getInlineEnumerationTypeAccess().getRule(); } //ArrayType attr::ArrayType: // {attr::ArrayType} // '[' length=Cardinality? ']'; public BasicAttributesGrammarAccess.ArrayTypeElements getArrayTypeAccess() { return gaBasicAttributes.getArrayTypeAccess(); } public ParserRule getArrayTypeRule() { return getArrayTypeAccess().getRule(); } //Cardinality: // INT | '*'; public BasicAttributesGrammarAccess.CardinalityElements getCardinalityAccess() { return gaBasicAttributes.getCardinalityAccess(); } public ParserRule getCardinalityRule() { return getCardinalityAccess().getRule(); } //enum PRIMITIVE_TYPE_NAME returns attr::PRIMITIVE_TYPE_NAME: // Int8 | Int16 | Int32 | Int64 | // UInt8 | UInt16 | UInt32 | UInt64 | // Float | Double | String | Boolean; public BasicAttributesGrammarAccess.PRIMITIVE_TYPE_NAMEElements getPRIMITIVE_TYPE_NAMEAccess() { return gaBasicAttributes.getPRIMITIVE_TYPE_NAMEAccess(); } public EnumRule getPRIMITIVE_TYPE_NAMERule() { return getPRIMITIVE_TYPE_NAMEAccess().getRule(); } //PrimitiveType attr::PrimitiveType: // typeName=PRIMITIVE_TYPE_NAME array=ArrayType?; public BasicAttributesGrammarAccess.PrimitiveTypeElements getPrimitiveTypeAccess() { return gaBasicAttributes.getPrimitiveTypeAccess(); } public ParserRule getPrimitiveTypeRule() { return getPrimitiveTypeAccess().getRule(); } //AbstractValue attr::AbstractValue: // SingleValue | ArrayValue; public BasicAttributesGrammarAccess.AbstractValueElements getAbstractValueAccess() { return gaBasicAttributes.getAbstractValueAccess(); } public ParserRule getAbstractValueRule() { return getAbstractValueAccess().getRule(); } //ArrayValue attr::ArrayValue: // '[' values+=SingleValue (',' values+=SingleValue)* ']'; public BasicAttributesGrammarAccess.ArrayValueElements getArrayValueAccess() { return gaBasicAttributes.getArrayValueAccess(); } public ParserRule getArrayValueRule() { return getArrayValueAccess().getRule(); } //SingleValue attr::SingleValue: // {attr::IntValue} value=EInt | {attr::FloatingPointValue} value=EDouble | {attr::StringValue} value=EString | // {attr::BoolValue} value=EBoolean | {attr::EnumerationValue} value=[attr::EnumerationElement|FQN]; public BasicAttributesGrammarAccess.SingleValueElements getSingleValueAccess() { return gaBasicAttributes.getSingleValueAccess(); } public ParserRule getSingleValueRule() { return getSingleValueAccess().getRule(); } //AbstractDocumentedElement: // {AbstractDocumentedElement} documentation=DOCU_COMMENT?; public DocuTerminalsGrammarAccess.AbstractDocumentedElementElements getAbstractDocumentedElementAccess() { return gaDocuTerminals.getAbstractDocumentedElementAccess(); } public ParserRule getAbstractDocumentedElementRule() { return getAbstractDocumentedElementAccess().getRule(); } //@Override //terminal ML_COMMENT: // '/*' !'*'->'*/'; public TerminalRule getML_COMMENTRule() { return gaDocuTerminals.getML_COMMENTRule(); } //terminal fragment ML_DOCUMENTATION: // '/**'->'*/'; public TerminalRule getML_DOCUMENTATIONRule() { return gaDocuTerminals.getML_DOCUMENTATIONRule(); } //@Override //terminal SL_COMMENT: // '//' !'/' !('\n' | '\r')* ('\r'? '\n')?; public TerminalRule getSL_COMMENTRule() { return gaDocuTerminals.getSL_COMMENTRule(); } //terminal fragment SL_DOCUMENTATION: // '///' !('\n' | '\r')* ('\r'? '\n')?; public TerminalRule getSL_DOCUMENTATIONRule() { return gaDocuTerminals.getSL_DOCUMENTATIONRule(); } //terminal DOCU_COMMENT: // ML_DOCUMENTATION | SL_DOCUMENTATION; public TerminalRule getDOCU_COMMENTRule() { return gaDocuTerminals.getDOCU_COMMENTRule(); } //terminal ID: // '^'? ('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '_' | '0'..'9')*; public TerminalRule getIDRule() { return gaTerminals.getIDRule(); } //terminal INT returns ecore::EInt: // '0'..'9'+; public TerminalRule getINTRule() { return gaTerminals.getINTRule(); } //terminal STRING: // '"' ('\\' . | !('\\' | '"'))* '"' | // "'" ('\\' . | !('\\' | "'"))* "'"; public TerminalRule getSTRINGRule() { return gaTerminals.getSTRINGRule(); } //terminal WS: // ' ' | '\t' | '\r' | '\n'+; public TerminalRule getWSRule() { return gaTerminals.getWSRule(); } //terminal ANY_OTHER: // .; public TerminalRule getANY_OTHERRule() { return gaTerminals.getANY_OTHERRule(); } }
<reponame>maksymko/cortex-demos<filename>tests/nrf52_timer_test.cpp<gh_stars>10-100 /******************************************************************************* Copyright 2018 Google LLC 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 https://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. *******************************************************************************/ #include "third_party/catch2/catch.hpp" #include "mock_memio.hpp" #include "nvic.h" #include "driver/timer.hpp" namespace { const uint32_t timer_base[] = { 0x40008000, 0x40009000, 0x4000a000, 0x4001a000, 0x4001b000, }; const int timer_irq[] = {8, 9, 10, 26, 27}; const driver::Timer::ID timer_id[] = { driver::Timer::ID::TIMER0, driver::Timer::ID::TIMER1, driver::Timer::ID::TIMER2, driver::Timer::ID::TIMER3, driver::Timer::ID::TIMER4, }; } // namespace TEST_CASE("Timer API") { auto& mem = mock::get_global_memory(); mem.reset(); SECTION("Basic API") { for (unsigned timer_index = 0; timer_index < 5; ++timer_index) { auto* timer = driver::Timer::request_by_id(timer_id[timer_index]); REQUIRE(timer != nullptr); CHECK(timer->get_irq_num() == timer_irq[timer_index]); const auto ct_base = timer_base[timer_index]; timer->start(); CHECK(mem.get_value_at(ct_base, 0) == 1); timer->stop(); CHECK(mem.get_value_at(ct_base + 4, 0) == 1); timer->set_prescaler(3); CHECK(mem.get_value_at(ct_base + 0x510) == 3); timer->set_prescaler(9); CHECK(mem.get_value_at(ct_base + 0x510) == 9); timer->set_prescaler(10); CHECK(mem.get_value_at(ct_base + 0x510) == 9); timer->set_prescaler(235); CHECK(mem.get_value_at(ct_base + 0x510) == 9); constexpr unsigned int base_rate = 16'000'000; for (unsigned presc = 0; presc < 10; ++presc) { mem.set_value_at(ct_base + 0x510, presc); auto rate = timer->get_rate(); auto expected_rate = 16 * 1000 * 1000 / (1 << presc); CHECK(rate == expected_rate); CHECK(timer->get_base_rate() == base_rate); } const unsigned int rate_req = 1000'000; auto new_rate = timer->request_rate(rate_req); CHECK(new_rate > 0); CHECK(new_rate == rate_req); CHECK(mem.get_value_at(ct_base + 0x510) == 4); // Request rate smaller than the minimum one new_rate = timer->request_rate(25'000); CHECK(new_rate == 0); CHECK(timer->get_base_rate() == base_rate); // Request largest possible rate new_rate = timer->request_rate(16'000'000); CHECK(new_rate == 16'000'000); // Request even larger rate new_rate = timer->request_rate(23'000'000); CHECK(new_rate == 16'000'000); } } }
def validate_image_names(self, data, udata): for image in data.images(): filename = self.image_path(image, udata) if ' ' in filename: logger.error( 'Image name "{}" contains spaces. ' 'This is not supported by the NVM format. ' 'Please, rename it before running OpenSfM.' .format(filename)) sys.exit(1)
// Will be shot down by a plane static void DisasterTick_4(Vehicle v) { GetNewVehiclePosResult gp = new GetNewVehiclePosResult(); int z; Vehicle w; Town t; TileIndex tile; TileIndex tile_org; v.tick_counter++; if (v.getCurrent_order().station == 1) { int x = v.dest_tile.TileX() * 16 + 8; int y = v.dest_tile.TileY() * 16 + 8; if (Math.abs(v.getX_pos() - x) + Math.abs(v.getY_pos() - y) >= 8) { v.direction = Vehicle.GetDirectionTowards(v, x, y); v.GetNewVehiclePos(gp); SetDisasterVehiclePos(v, gp.x, gp.y, v.z_pos); return; } z = Landscape.GetSlopeZ(v.getX_pos(), v.getY_pos()); if (z < v.z_pos) { SetDisasterVehiclePos(v, v.getX_pos(), v.getY_pos(), v.z_pos - 1); return; } v.getCurrent_order().station = 2; Vehicle.forEach( (u) -> { if (u.type == Vehicle.VEH_Train || u.type == Vehicle.VEH_Road) { if (Math.abs(u.getX_pos() - v.getX_pos()) + Math.abs(u.getY_pos() - v.getY_pos()) <= 12*16) { u.breakdown_ctr = 5; u.breakdown_delay = 0xF0; } } }); t = Town.ClosestTownFromTile(v.dest_tile, -1); Global.SetDParam(0, t.index); NewsItem.AddNewsItem(Str.STR_B004_UFO_LANDS_NEAR, NewsItem.NEWS_FLAGS(NewsItem.NM_THIN, NewsItem.NF_VIEWPORT|NewsItem.NF_TILE, NewsItem.NT_ACCIDENT, 0), v.tile.getTile(), 0); Vehicle u = Vehicle.ForceAllocateSpecialVehicle(); if (u == null) { DeleteDisasterVeh(v); return; } InitializeDisasterVehicle(u, -6*16, v.getY_pos(), 135, 5, 11); u.disaster.unk2 = v.index; w = Vehicle.ForceAllocateSpecialVehicle(); if (w == null) return; u.next = w; InitializeDisasterVehicle(w, -6*16, v.getY_pos(), 0, 5, 12); w.setDisaster(true); } else if (v.getCurrent_order().station < 1) { int x = v.dest_tile.TileX() * 16; int y = v.dest_tile.TileY() * 16; if (Math.abs(x - v.getX_pos()) + Math.abs(y - v.getY_pos()) >= 16) { v.direction = Vehicle.GetDirectionTowards(v, x, y); v.GetNewVehiclePos( gp); SetDisasterVehiclePos(v, gp.x, gp.y, v.z_pos); return; } if (++v.age < 6) { v.dest_tile = Hal.RandomTile(); return; } v.getCurrent_order().station = 1; tile_org = tile = Hal.RandomTile(); do { if (tile.IsTileType( TileTypes.MP_RAILWAY) && (tile.getMap().m5 & ~3) != 0xC0 && tile.GetTileOwner().IS_HUMAN_PLAYER()) break; tile = tile.iadd(1); tile.TILE_MASK(); } while (!tile.equals(tile_org)); v.dest_tile = tile; v.age = 0; } }
/**************************************************************************** * VCGLib o o * * Visual and Computer Graphics Library o o * * _ O _ * * Copyright(C) 2004-2016 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ /**************************************************************************** History $Log: not supported by cvs2svn $ Revision 1.6 2006/05/21 06:58:55 cignoni Added ClampMask function Revision 1.5 2006/01/10 13:20:42 cignoni Changed ply::PlyMask to io::Mask Revision 1.4 2004/10/28 00:52:45 cignoni Better Doxygen documentation Revision 1.3 2004/05/12 10:19:30 ganovelli new line added at the end of file Revision 1.2 2004/03/09 21:26:47 cignoni cr lf mismatch Revision 1.1 2004/03/03 15:00:51 cignoni Initial commit ****************************************************************************/ #ifndef __VCGLIB_IOTRIMESH_IO_MASK #define __VCGLIB_IOTRIMESH_IO_MASK namespace vcg { namespace tri { namespace io { /** @name Input/output data mask */ //@{ class Mask { public: /* Bitmask for specifying what data has to be loaded or saved or it is present in a given plyfile; */ enum { IOM_NONE = 0x00000, IOM_VERTCOORD = 0x00001, IOM_VERTFLAGS = 0x00002, IOM_VERTCOLOR = 0x00004, IOM_VERTQUALITY = 0x00008, IOM_VERTNORMAL = 0x00010, IOM_VERTTEXCOORD = 0x00020, IOM_VERTRADIUS = 0x10000, IOM_EDGEINDEX = 0x80000, IOM_FACEINDEX = 0x00040, IOM_FACEFLAGS = 0x00080, IOM_FACECOLOR = 0x00100, IOM_FACEQUALITY = 0x00200, IOM_FACENORMAL = 0x00400, IOM_WEDGCOLOR = 0x00800, IOM_WEDGTEXCOORD = 0x01000, IOM_WEDGTEXMULTI = 0x02000, // when textrue index is explicit IOM_WEDGNORMAL = 0x04000, IOM_BITPOLYGONAL = 0x20000, // loads explicit polygonal mesh IOM_CAMERA = 0x08000, IOM_FLAGS = IOM_VERTFLAGS + IOM_FACEFLAGS, IOM_ALL = 0xFFFFF }; // // //static void IOMask2String( int mask, char str[] ) //{ // str[0] = 0; // // strcat(str,"V:"); // if( mask & IOM_VERTFLAGS ) strcat(str,"flag,"); // if( mask & IOM_VERTCOLOR ) strcat(str,"color,"); // if( mask & IOM_VERTQUALITY ) strcat(str,"quality,"); // if( mask & IOM_VERTTEXCOORD ) strcat(str,"texcoord,"); // if( mask & IOM_VERTNORMAL ) strcat(str,"normal,"); // // strcat(str," F:"); // if( mask & IOM_FACEFLAGS ) strcat(str,"mask,"); // if( mask & IOM_FACECOLOR ) strcat(str,"color,"); // if( mask & IOM_FACEQUALITY ) strcat(str,"quality,"); // if( mask & IOM_FACENORMAL ) strcat(str,"normal,"); // // strcat(str," W:"); // if( mask & IOM_WEDGCOLOR ) strcat(str,"color,"); // if( mask & IOM_WEDGTEXCOORD ) strcat(str,"texcoord,"); // if( mask & IOM_WEDGNORMAL ) strcat(str,"normal,"); // // if( mask & IOM_CAMERA ) strcat(str," camera"); //} template <class MeshType> static void ClampMask(MeshType &m, int &mask) { if( (mask & IOM_FACECOLOR) && !HasPerFaceColor(m) ) mask = mask & (~IOM_FACECOLOR); if( (mask & IOM_WEDGTEXCOORD) && !HasPerWedgeTexCoord(m) ) mask = mask & (~IOM_WEDGTEXCOORD); if( (mask & IOM_WEDGNORMAL) && !HasPerWedgeNormal(m) ) mask = mask & (~IOM_WEDGNORMAL); if( (mask & IOM_VERTCOLOR) && !HasPerVertexColor(m) ) mask = mask & (~IOM_VERTCOLOR); } }; // end class //@} } // end namespace tri } // end namespace io } // end namespace vcg #endif
{-# LANGUAGE RankNTypes , ScopedTypeVariables #-} module Linear.Grammar ( (.+.) , (.*.) , (.==.) , (.<=.) , (.>=.) , module Linear.Grammar.Types.Inequalities )where import Linear.Grammar.Types.Syntax (LinAst (EAdd, ECoeff)) import Linear.Grammar.Types.Expressions (makeLinExpr) import qualified Linear.Grammar.Types.Inequalities as Ineq import Linear.Grammar.Types.Inequalities (standardForm) -- | Addition operation (.+.) :: LinAst k a -> LinAst k a -> LinAst k a (.+.) = EAdd infixl 6 .+. -- | Multiplication operation (.*.) :: LinAst k a -> a -> LinAst k a (.*.) = ECoeff infixl 5 .*. (.==.) :: Eq a => Num a => Ord k => LinAst k a -> LinAst k a -> Ineq.IneqExpr k a a x .==. y = Ineq.EquExpr (makeLinExpr x) (makeLinExpr y) infixl 7 .==. (.<=.) :: Eq a => Num a => Ord k => LinAst k a -> LinAst k a -> Ineq.IneqExpr k a a x .<=. y = Ineq.LteExpr (makeLinExpr x) (makeLinExpr y) infixl 7 .<=. (.>=.) :: Eq a => Num a => Ord k => LinAst k a -> LinAst k a -> Ineq.IneqExpr k a a (.>=.) = flip (.<=.) infixl 7 .>=.
Effect of dental silane primer activation time on resin–ceramic bonding The purpose of this study was to investigate the effect of activation time for the hydrolysis of dental silane primers on resin bonding to ceramic. Two commercial two-part silane primers (Bis-Silane, BS; Tokuso Ceramic Primer, TCP) were tested. Leucite-reinforced glass-ceramic (IPS Empress CAD) surfaces were used as the bonding substrates. The degree of hydrolysis of each mixed silane was observed at five specified times (immediately, 10 min, 30 min, 1 h, and 2 h after mixing) using Fourier transform infrared (FTIR) spectroscopy. Prior to resin (Duo-Link) bonding, the polished ceramic surfaces were pretreated with silanes that were activated in two different ways: an ‘in-solution’ or ‘on-surface’ activation, at the specified times. All bonded specimens were stored in water at 37 °C for 24 h prior to tensile bond strength (TBS) testing (n = 12). A one-bottle silane (Monobond-S, MS) was also tested. The FTIR analysis showed that the hydrolysis proceeded gradually for 2 h in the BS, but the initial hydrolysis halted in the TCP. When the BS was further hydrolyzed up to 2 h, the TBS values significantly increased up to 30 min (p < 0.001) with no further significant increases (p > 0.05) regardless of the activation method used. For TCP, there were no significant differences in TBS as a function of activation time (p > 0.05). The fractographic analysis of the debonded surfaces was consistent with the TBS data. In conclusion, a lengthened activation time was effective for the BS in enhancing resin bonding efficacy to the ceramic.
// // Whenever we display a modal dialog, we need to let // our embeddings (the WebBrowser OC) know to disable // any modeless dialogs the embedding is displaying. // VOID EnableEmbeddingModelessDlgs(BOOL fEnable) { LPOLEINPLACEACTIVEOBJECT pIPAO = GetIPAObject(); if (pIPAO) pIPAO->EnableModeless(fEnable); }
/************************************************************************/ /* msIO_stripStdoutBufferContentType() */ /* */ /* Strip off content-type header from buffer, and return to */ /* caller. Returned string is the callers responsibility to */ /* call msFree() on to deallocate. This function will return */ /* NULL if there is no content-type header. */ /************************************************************************/ char *msIO_stripStdoutBufferContentType() { msIOContext *ctx = msIO_getHandler( (FILE *) "stdout" ); msIOBuffer *buf; char *content_type = NULL; int end_of_ct, start_of_data; if( ctx == NULL || ctx->write_channel == MS_FALSE || strcmp(ctx->label,"buffer") != 0 ) { msSetError( MS_MISCERR, "Can't identify msIO buffer.", "msIO_stripStdoutBufferContentType" ); return NULL; } buf = (msIOBuffer *) ctx->cbData; if( buf->data_offset < 14 || strncasecmp((const char*) buf->data,"Content-type: ",14) != 0 ) return NULL; end_of_ct = 13; while( end_of_ct+1 < buf->data_offset && buf->data[end_of_ct+1] != 10 ) end_of_ct++; if( end_of_ct+1 == buf->data_offset ) { msSetError( MS_MISCERR, "Corrupt Content-type header.", "msIO_stripStdoutBufferContentType" ); return NULL; } start_of_data = end_of_ct+2; while( start_of_data < buf->data_offset && buf->data[start_of_data] != 10 ) start_of_data++; if( start_of_data == buf->data_offset ) { msSetError( MS_MISCERR, "Corrupt Content-type header.", "msIO_stripStdoutBufferContentType" ); return NULL; } start_of_data++; content_type = (char *) malloc(end_of_ct-14+2); strlcpy( content_type, (const char *) buf->data + 14, end_of_ct - 14 + 2); content_type[end_of_ct-14+1] = '\0'; memmove( buf->data, buf->data+start_of_data, buf->data_offset - start_of_data ); buf->data[buf->data_offset - start_of_data] = '\0'; buf->data_offset -= start_of_data; return content_type; }
// NewModuleImport returns a `*ModuleImport` for the given alias and import path. // The import path is the import path as used in a playbook and is not a valid Go // import path, as it has the module appended as a suffix. func NewModuleImport(alias, importPath string) (*ModuleImport, error) { qi := qualifiedIdentifier(importPath) parts := strings.Split(qi, ".") if len(parts) != 2 { return nil, fmt.Errorf("invalid import path %s", importPath) } parts = strings.Split(importPath, ".") ml := &ModuleImport{ Alias: alias, GoImportPath: strings.Join(parts[0:len(parts)-1], "."), QualifiedIdentifier: qi, } return ml, nil }
// naive growth - just adds a full row or column on a side public synchronized Set<Region> grow(final Regions regions, Direction direction) { Set<Region> growthRegions = new HashSet<>(); int numberOfRegions = calcSideRegions(regions, direction); switch (direction) { case NORTH: { for (int depth = 0; depth < PAD_DEPTH; depth++) { int newLocationY = regions.getMaxValues().getY() + 1; int startingX = regions.getMinValues().getX(); for (int i = 0; i < numberOfRegions; i++) { if (i > 0) { startingX += Regions.REGION_EDGE_SIZE; } Location loc = Location.create(startingX, newLocationY); Region newRegion = regionHelper.generateRegion(loc, Regions.REGION_EDGE_SIZE, Regions.REGION_EDGE_SIZE, false); growthRegions.add(newRegion); } } } break; case SOUTH: { for (int depth = 0; depth < PAD_DEPTH; depth++) { int newLocationY = regions.getMinValues().getY() - Regions.REGION_EDGE_SIZE; int startingX = regions.getMinValues().getX(); for (int i = 0; i < numberOfRegions; i++) { if (i > 0) { startingX += Regions.REGION_EDGE_SIZE; } Location loc = Location.create(startingX, newLocationY); Region newRegion = regionHelper.generateRegion(loc, Regions.REGION_EDGE_SIZE, Regions.REGION_EDGE_SIZE, false); growthRegions.add(newRegion); } } } break; case EAST: { for (int depth = 0; depth < PAD_DEPTH; depth++) { int newLocationX = regions.getMaxValues().getX() + 1; int startingY = regions.getMinValues().getY(); for (int i = 0; i < numberOfRegions; i++) { if (i > 0) { startingY += Regions.REGION_EDGE_SIZE; } Location loc = Location.create(newLocationX, startingY); Region newRegion = regionHelper.generateRegion(loc, Regions.REGION_EDGE_SIZE, Regions.REGION_EDGE_SIZE, false); growthRegions.add(newRegion); } } } break; case WEST: { for (int depth = 0; depth < PAD_DEPTH; depth++) { int newLocationX = regions.getMinValues().getX() - Regions.REGION_EDGE_SIZE; int startingY = regions.getMinValues().getY(); for (int i = 0; i < numberOfRegions; i++) { if (i > 0) { startingY += Regions.REGION_EDGE_SIZE; } Location loc = Location.create(newLocationX, startingY); Region newRegion = regionHelper.generateRegion(loc, Regions.REGION_EDGE_SIZE, Regions.REGION_EDGE_SIZE, false); growthRegions.add(newRegion); } } } break; } return growthRegions; }
def reject(fn: callable, l: iter) -> iter: return func.enum.filter(lambda x: not(fn(x)), l)
/** * Creates a request for location updates, using the location request and locationCallBack objects. * The location call back checks whether or not the user has changed college locations every 500-750ms, and then reloads the TravelActivity page. * To execute the request for location updates, we use the requestLocationUpdates method in fused location provider client. * * @param * @return void * @see <a href = "https://developer.android.com/training/location/retrieve-current">https://developer.android.com/training/location/retrieve-current</> * @see <a href = "https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html">https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html</> */ @SuppressLint("MissingPermission") public void generateLocationReceiverAndNavigateToTravelPage() { /** * Setup a LocationRequest to be passed into the Activity Compat's request location method. */ lR = LocationRequest.create(); lR.setInterval(750); lR.setFastestInterval(500); lR.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); lCB = new LocationCallback() { @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onLocationResult(LocationResult lResult) { if (lResult != null) { computeLocations(lResult.getLastLocation()); if (!whereWasIMap.equals(whereAmINowMap)) { logoutTrigger = 0; synchronizeLocations(whereWasIMap, whereAmINowMap); Intent refresh = new Intent(LoginActivity.super.getApplicationContext(), TravelActivity.class); refresh.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(refresh); } Log.d("Longitude", String.valueOf(lResult.getLastLocation().getLongitude())); longitude = Double.valueOf(lResult.getLastLocation().getLongitude()); Log.d("Latitude", String.valueOf(lResult.getLastLocation().getLatitude())); latitude = Double.valueOf(lResult.getLastLocation().getLatitude()); } else { Log.d("LOCATION", "Location result is null"); } } }; fLC = LocationServices.getFusedLocationProviderClient(LoginActivity.this); fLC.requestLocationUpdates(lR, lCB, null); loginButton.setEnabled(true); loginStatus = true; userInstance.removeAuthStateListener(new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { } }); Intent refresh = new Intent(LoginActivity.super.getApplicationContext(), TravelActivity.class); startActivity(refresh); }
// tests to see if hypocenter can successfully // read json output TEST(HypoTest, ReadsJSON) { rapidjson::Document hypodocument; detectionformats::hypocenter hypoobject( detectionformats::FromJSONString(std::string(HYPOSTRING), hypodocument)); checkdata(hypoobject, ""); }
<gh_stars>0 package com.yelelen.sfish.contract; /** * Created by yelelen on 17-9-12. */ public interface MatrixImageViewListener { interface MatrixImageViewCallback { void onClick(); void onLongClick(int position); } }
def generate_website(): util.buildhelpers.create_content_pages_dir() if not os.path.isdir(site_config.resources_markdown_path): os.mkdir(site_config.resources_markdown_path) util.buildhelpers.move_templates(website_build_config.module_name, website_build_config.website_build_templates_path) generate_javascript_settings() generate_base_html() generate_index_page() generate_static_pages() generate_faq_page() generate_changelog_page() store_pelican_settings() override_colors() pelican_content() reset_override_colors() remove_pelican_settings() remove_unwanted_output()
/** * Happy-path smoke test to validate that OpenBanking environment with Consent UI is in sane state. */ @EnabledIfEnvironmentVariable(named = ENABLE_SMOKE_TESTS, matches = TRUE_BOOL) @ExtendWith({SeleniumExtension.class, WebDriverErrorReportAspectAndWatcher.class}) @SpringBootTest(classes = {JGivenConfig.class, SmokeConfig.class, FintechRequestSigningTestConfig.class, SmokeSandboxServers.class}, webEnvironment = NONE) // Use @ActiveProfiles(profiles = {SMOKE_TEST, "test-smoke-local"}) to run the test on local env. @ActiveProfiles(profiles = {SMOKE_TEST}) class OpbaApiWithHbciConsentUiSmokeE2ETest extends SpringScenarioTest<SmokeSandboxServers, WebDriverBasedAccountInformation<? extends WebDriverBasedAccountInformation<?>>, AccountInformationResult> { private static final String MAX_MUSTERMAN_IBAN = "DE59300000033466865655"; private static final String PUSH_TAN_SCA_NAME = "pushTAN"; private static final String PUSH_TAN_PAGE_NAME = "PUSH_OTP"; private final String opbaLogin = UUID.randomUUID().toString(); private final String opbaPassword = UUID.randomUUID().toString(); @Autowired private SmokeConfig config; @BeforeAll static void setupDriverArch() { WebDriverManager.firefoxdriver().arch64(); } @Test void testAccountsListHbci(FirefoxDriver firefoxDriver) { given() .rest_assured_points_to_opba_server_with_fintech_signer_on_banking_api(config.getOpbaServerUri()); when() .fintech_calls_list_accounts_for_anton_brueckner(HBCI_SANDBOX_BANK_SCA_ID) .and() .user_opens_opba_consent_login_page(firefoxDriver) .and() .user_sees_register_button_clicks_it_navigate_to_register_fills_form_and_registers(firefoxDriver, opbaLogin, opbaPassword) .and() .user_logs_in_to_opba(firefoxDriver, opbaLogin, opbaPassword) .and() .user_provided_to_consent_ui_initial_parameters_to_list_accounts_with_hbci_consent(firefoxDriver, ANTON_BRUECKNER) .and() .user_in_consent_ui_reviews_account_consent_and_accepts(firefoxDriver) .and() .user_in_consent_ui_provides_pin(firefoxDriver) .and() .user_in_consent_ui_sees_thank_you_for_consent_and_clicks_to_tpp(firefoxDriver); then() .fintech_calls_consent_activation_for_current_authorization_id() .open_banking_can_read_anton_brueckner_hbci_account_data_using_consent_bound_to_service_session(HBCI_SANDBOX_BANK_SCA_ID); } @Test void testTransactionListHbci(FirefoxDriver firefoxDriver) { given() .rest_assured_points_to_opba_server_with_fintech_signer_on_banking_api(config.getOpbaServerUri()); when() .fintech_calls_list_transactions_for_max_musterman(MAX_MUSTERMAN_IBAN, HBCI_SANDBOX_BANK_SCA_ID) .and() .user_opens_opba_consent_login_page(firefoxDriver) .and() .user_sees_register_button_clicks_it_navigate_to_register_fills_form_and_registers(firefoxDriver, opbaLogin, opbaPassword) .and() .user_logs_in_to_opba(firefoxDriver, opbaLogin, opbaPassword) .and() .user_provided_to_consent_ui_initial_parameters_to_list_transactions_with_hbci_consent(firefoxDriver, MAX_MUSTERMAN) .and() .user_in_consent_ui_reviews_transaction_consent_and_accepts(firefoxDriver) .and() .user_in_consent_ui_provides_pin(firefoxDriver) .and() .user_in_consent_ui_sees_sca_select_and_selected_type(firefoxDriver, PUSH_TAN_SCA_NAME) .and() .user_in_consent_ui_provides_sca_result_to_embedded_authorization(firefoxDriver, PUSH_TAN_PAGE_NAME) .and() .user_in_consent_ui_sees_thank_you_for_consent_and_clicks_to_tpp(firefoxDriver); then() .fintech_calls_consent_activation_for_current_authorization_id() .open_banking_can_read_max_musterman_hbci_transaction_data_using_consent_bound_to_service_session( MAX_MUSTERMAN_IBAN, HBCI_SANDBOX_BANK_SCA_ID, DATE_FROM, DATE_TO, BOTH_BOOKING ); } }
<gh_stars>0 /* * Copyright (C) 2009 JavaRosa * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.javarosa.core.model.utils; import java.util.Date; import java.util.List; import org.javarosa.core.model.data.DateData; import org.javarosa.core.model.data.DateTimeData; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.StringData; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.core.services.PropertyManager; import org.javarosa.core.util.Map; import org.javarosa.core.util.PropertyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Question Preloader is responsible for maintaining a set of handlers which are capable * of parsing 'preload' elements, and their parameters, and returning IAnswerData objects. * * @author <NAME> * */ public class QuestionPreloader { private static final Logger logger = LoggerFactory.getLogger(QuestionPreloader.class); /* String -> IPreloadHandler */ // NOTE: this is not java.util.Map!!! private Map<String,IPreloadHandler> preloadHandlers; /** * Creates a new Preloader with default handlers */ public QuestionPreloader() { preloadHandlers = new Map<String,IPreloadHandler>(); initPreloadHandlers(); } /** * Initializes the default preload handlers */ private void initPreloadHandlers() { IPreloadHandler date = new IPreloadHandler() { public String preloadHandled() { return "date"; } public IAnswerData handlePreload(String preloadParams) { return preloadDate(preloadParams); } public boolean handlePostProcess(TreeElement node, String params) { //do nothing return false; } }; IPreloadHandler property = new IPreloadHandler() { public String preloadHandled() { return "property"; } public IAnswerData handlePreload(String preloadParams) { return preloadProperty(preloadParams); } public boolean handlePostProcess(TreeElement node, String params) { saveProperty(params, node); return false; } }; IPreloadHandler timestamp = new IPreloadHandler() { public String preloadHandled() { return "timestamp"; } public IAnswerData handlePreload(String preloadParams) { return ("start".equals(preloadParams) ? getTimestamp() : null); } public boolean handlePostProcess(TreeElement node, String params) { if ("end".equals(params)) { node.setAnswer(getTimestamp()); return true; } else { return false; } } }; IPreloadHandler uid = new IPreloadHandler() { public String preloadHandled() { return "uid"; } public IAnswerData handlePreload(String preloadParams) { return new StringData(PropertyUtils.genGUID(25)); } public boolean handlePostProcess(TreeElement node, String params) { return false; } }; /* //TODO: Finish this up. IPreloadHandler meta = new IPreloadHandler() { public String preloadHandled() { return "meta"; } public IAnswerData handlePreload(String preloadParams) { //TODO: Ideally, we want to handle this preloader by taking in the //existing structure. Resultantly, we don't want to mess with this. //We should be enforcing that we don't. return null; } public boolean handlePostProcess(TreeElement node, String params) { List kids = node.getChildren(); Enumeration en = kids.elements(); while(en.hasMoreElements()) { TreeElement kid = (TreeElement)en.nextElement(); if(kid.getName().equals("uid")) { kid.setValue(new StringData(PropertyUtils.genGUID(25))); } } return true; } }; */ addPreloadHandler(date); addPreloadHandler(property); addPreloadHandler(timestamp); addPreloadHandler(uid); } /** * Adds a new preload handler to this preloader. * * @param handler an IPreloadHandler that can handle a preload type */ public void addPreloadHandler(IPreloadHandler handler) { preloadHandlers.put(handler.preloadHandled(), handler); } /** * Returns the IAnswerData preload value for the given preload type and parameters * * @param preloadType The type of the preload to be returned * @param preloadParams Parameters for the preload handler * @return An IAnswerData corresponding to a pre-loaded value for the given * Arguments. null if no preload could successfully be derived due to either * the lack of a handler, or to invalid parameters */ public IAnswerData getQuestionPreload(String preloadType, String preloadParams) { IPreloadHandler handler = preloadHandlers.get(preloadType); if(handler != null) { return handler.handlePreload(preloadParams); } else { logger.error("Do not know how to handle preloader [{}]", preloadType); return null; } } public boolean questionPostProcess (TreeElement node, String preloadType, String params) { IPreloadHandler handler = preloadHandlers.get(preloadType); if(handler != null) { return handler.handlePostProcess(node, params); } else { logger.error("Do not know how to handle preloader [{}]", preloadType); return false; } } /** * Preloads a DateData object for the preload type 'date' * * @param preloadParams The parameters determining the date * @return A preload date value if the parameters can be parsed, * null otherwise */ private IAnswerData preloadDate(String preloadParams) { Date d = null; if (preloadParams.equals("today")) { d = new Date(); } else if (preloadParams.substring(0, 11).equals("prevperiod-")) { List<String> v = DateUtils.split(preloadParams.substring(11), "-", false); String[] params = new String[v.size()]; for (int i = 0; i < params.length; i++) params[i] = (String)v.get(i); try { String type = params[0]; String start = params[1]; boolean beginning; if (params[2].equals("head")) beginning = true; else if (params[2].equals("tail")) beginning = false; else throw new RuntimeException(); boolean includeToday; if (params.length >= 4) { if (params[3].equals("x")) includeToday = true; else if (params[3].equals("")) includeToday = false; else throw new RuntimeException(); } else { includeToday = false; } int nAgo; if (params.length >= 5) { nAgo = Integer.parseInt(params[4]); } else { nAgo = 1; } d = DateUtils.getPastPeriodDate(new Date(), type, start, beginning, includeToday, nAgo); } catch (Exception e) { throw new IllegalArgumentException("invalid preload params for preload mode 'date'"); } } DateData data = new DateData(d); return data; } /** * Preloads a StringData object for the preload type 'property' * * @param preloadParams The parameters determining the property to be retrieved * @return A preload property value if the parameters can be parsed, * null otherwise */ private IAnswerData preloadProperty(String preloadParams) { String propname = preloadParams; String propval = PropertyManager.__().getSingularProperty(propname); StringData data = null; if (propval != null && propval.length() > 0) { data = new StringData(propval); } return data; } private void saveProperty (String propName, TreeElement node) { IAnswerData answer = node.getValue(); String value = (answer == null ? null : answer.getDisplayText()); if (propName != null && propName.length() > 0 && value != null && value.length() > 0) PropertyManager.__().setProperty(propName, value); } private DateTimeData getTimestamp() { return new DateTimeData(new Date()); } }
def Ssrootsinf(theta1inf, theta2inf, q, chi1, chi2): S1, S2 = spinmags(q, chi1, chi2) coscos = np.cos(theta1inf)*np.cos(theta2inf) sinsin = np.sin(theta1inf)*np.sin(theta2inf) Sminussinf = S1**2 + S2**2 + 2*S1*S2*(coscos - sinsin) Splussinf = S1**2 + S2**2 + 2*S1*S2*(coscos + sinsin) S3sinf = -np.inf return np.stack([Sminussinf, Splussinf, S3sinf])
/** * mei_cl_complete - processes completed operation for a client * * @cl: private data of the file object. * @cb: callback block. */ void mei_cl_complete(struct mei_cl *cl, struct mei_cl_cb *cb) { if (cb->fop_type == MEI_FOP_WRITE) { mei_io_cb_free(cb); cb = NULL; cl->writing_state = MEI_WRITE_COMPLETE; if (waitqueue_active(&cl->tx_wait)) wake_up_interruptible(&cl->tx_wait); } else if (cb->fop_type == MEI_FOP_READ && MEI_READING == cl->reading_state) { cl->reading_state = MEI_READ_COMPLETE; if (waitqueue_active(&cl->rx_wait)) wake_up_interruptible(&cl->rx_wait); else mei_cl_bus_rx_event(cl); } }
<gh_stars>0 // Allow zero pointers for lazy_static. Otherwise clippy will complain. #![allow(unknown_lints)] #[macro_use] extern crate clap; #[macro_use] extern crate error_chain; extern crate liquid; #[cfg(feature = "serde_json")] extern crate serde_json; #[cfg(feature = "serde_yaml")] extern crate serde_yaml; use std::ffi; use std::fs; use std::io; use std::io::Write; use std::path; error_chain! { links { } foreign_links { Clap(clap::Error); Io(io::Error); Liquid(liquid::Error); Yaml(serde_yaml::Error) #[cfg(feature = "serde_yaml")]; Json(serde_json::Error) #[cfg(feature = "serde_json")]; } errors { } } fn option<'a>(name: &'a str, value: &'a str) -> clap::Arg<'a, 'a> { clap::Arg::with_name(name).long(name).value_name(value) } #[cfg(feature = "serde_yaml")] fn load_yaml(path: &path::Path) -> Result<liquid::value::Value> { let f = fs::File::open(path)?; serde_yaml::from_reader(f).map_err(|e| e.into()) } #[cfg(not(feature = "serde_yaml"))] fn load_yaml(_path: &path::Path) -> Result<liquid::value::Value> { bail!("yaml is unsupported"); } #[cfg(feature = "serde_json")] fn load_json(path: &path::Path) -> Result<liquid::value::Value> { let f = fs::File::open(path)?; serde_json::from_reader(f).map_err(|e| e.into()) } #[cfg(not(feature = "serde_json"))] fn load_json(_path: &path::Path) -> Result<liquid::value::Value> { bail!("json is unsupported"); } fn build_context(path: &path::Path) -> Result<liquid::value::Object> { let extension = path.extension().unwrap_or_else(|| ffi::OsStr::new("")); let value = if extension == ffi::OsStr::new("yaml") { load_yaml(path) } else if extension == ffi::OsStr::new("yaml") { load_json(path) } else { Err("Unsupported file type".into()) }?; let value = match value { liquid::value::Value::Object(o) => Ok(o), _ => Err("File must be an object"), }?; Ok(value) } fn run() -> Result<()> { let matches = clap::App::new("liquidate") .version(crate_version!()) .author(crate_authors!()) .arg(option("input", "LIQUID").required(true)) .arg(option("output", "TXT")) .arg(option("context", "YAML")) .get_matches_safe()?; let parser = liquid::ParserBuilder::with_liquid() .extra_filters() .jekyll_filters() .build() .expect("should succeed without partials"); let template_path = matches .value_of("input") .map(path::PathBuf::from) .expect("Parameter was required"); let template = parser.parse_file(template_path)?; let data = matches .value_of("context") .map(|s| { let p = path::PathBuf::from(s); build_context(p.as_path()) }) .map_or(Ok(None), |r| r.map(Some))? .unwrap_or_else(liquid::value::Object::new); let output = template.render(&data)?; match matches.value_of("output") { Some(path) => { let mut out = fs::File::create(path::PathBuf::from(path))?; out.write_all(output.as_bytes())?; } None => { println!("{}", output); } } Ok(()) } quick_main!(run);
def build_map(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index): node = layer._inbound_nodes[node_index] if node in nodes_in_progress: raise ValueError('The tensor ' + str(tensor) + ' at layer "' + layer.name + '" is part of a cycle.') if node in finished_nodes: return node_key = _make_node_key(layer.name, node_index) network_nodes.add(node_key) if layer not in layer_indices: layer_indices[layer] = len(layer_indices) nodes_in_progress.add(node) for layer, node_index, tensor_index, tensor in node.iterate_inbound( include_arguments=True): build_map(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index) finished_nodes.add(node) nodes_in_progress.remove(node) nodes_in_decreasing_depth.append(node)
<filename>torigemubot/wordsdb.go<gh_stars>0 package main import ( "database/sql" "fmt" "regexp" "strings" ) const wordsTablename = "words" const customwordsTablename = "customwords" const kanjipointsTablename = "kanjipoints" const addCustomWordSavePoint = "AddCustomWord" const removeCustomWordSavePoint = "RemoveCustomWord" const kanaExp = `(\p{Katakana}|\p{Hiragana}|ー)([ゃャょョゅュ])?` var wordsdb *sql.DB var endKanaExp = regexp.MustCompile(fmt.Sprintf("%s$", kanaExp)) var beginKanaExp = regexp.MustCompile(fmt.Sprintf("^%s", kanaExp)) var endsInNExp = regexp.MustCompile(`(ん|ン)$`) func getWordPts(chatID int64, theWord string, lastEntry *wordEntry) (int, string) { // If points are zero or not found, then return zero. Probably ends in 'n', or not a noun. kana, pts := lookupKana(chatID, theWord) if lastEntry != nil && pts != 0 { // Get kana of last word. lastEntryKana, _ := lookupKana(chatID, lastEntry.word) // If first kana of new word does not match ending kana of last word, then return zero. if !matchKana(lastEntryKana, kana) { return 0, fmt.Sprintf("初めの仮名は終わりのかなと一致しません: %s「%s」-> %s「%s」", lastEntry.word, lastEntryKana, theWord, kana) } } else if pts == 0 { if endsInN(kana) { return pts, fmt.Sprintf("言葉は'ん'が終わることが禁止されています: %s", theWord) } return pts, fmt.Sprintf("無効言葉: %s", theWord) } return pts, "" } func lookupKana(chatID int64, theWord string) (string, int) { found, kana, pts := lookupStandardKana(chatID, theWord) if !found || pts == 0 { var customkana string found, customkana, pts = lookupCustomKana(chatID, theWord) if !found { return kana, 0 } kana = customkana } return kana, pts } func lookupStandardKana(chatID int64, theWord string) (bool, string, int) { var kana string var pts int found := nil == gamedb.SingleQuery(fmt.Sprintf("SELECT kana, points FROM %s WHERE kanji = '%s'", wordsTablename, theWord), &kana, &pts) return found, kana, pts } func lookupCustomKana(chatID int64, theWord string) (bool, string, int) { var kana string var pts int found := nil == gamedb.SingleQuery(fmt.Sprintf("SELECT kana, points FROM %s WHERE chatid = %d AND kanji = '%s'", customwordsTablename, chatID, theWord), &kana, &pts) return found, kana, pts } func matchKana(lastWordKana string, newWordKana string) bool { lastKana := strings.Split(lastWordKana, ",") newKana := strings.Split(newWordKana, ",") for _, lk := range lastKana { endingMatch := endKanaExp.FindStringSubmatch(lk) for _, nk := range newKana { if endAndBeginMatch(endingMatch, beginKanaExp.FindStringSubmatch(nk)) { return true } } } return false } func endAndBeginMatch(endingMatch []string, beginningMatch []string) bool { // If the word ends in a combined phonic (i.e., しゃ), then the // next word must begin with that same combination. // However, if the word ends in just し, then the next word can // optionally start with combined phonic (i.e., しゃ) or just し. if len(beginningMatch) < len(endingMatch) { return false } for index := 1; index < len(endingMatch); index++ { if len(endingMatch[index]) > 0 && endingMatch[index] != beginningMatch[index] { return false } } return true } func endsInN(kana string) bool { // Check for ending in ん. for _, k := range strings.Split(kana, ",") { if endsInNExp.MatchString(k) { return true } } return false } func calcWordPoints(kanji string) int { // Words entirely of hiragana or katakana are worth 1 point. pts := 1 if kanjiExp.MatchString(kanji) { for _, k := range kanji { kpts := getKanjiPoints(string(k)) if kpts > pts { // The word pts is equal to the highest kanji pts in the word. pts = kpts } } } return pts } func getKanjiPoints(kanjiCharacter string) int { var pts int if nil != gamedb.SingleQuery(fmt.Sprintf("SELECT points FROM %s WHERE kanji = '%s'", kanjipointsTablename, kanjiCharacter), &pts) { return 0 } return pts } func addCustomWord(chatID int64, userID int, kanji string, kana string) error { wordpts := calcWordPoints(kanji) // Replace any existing custom word with the updated version of it. return gamedb.ExecWithSavePoint(addCustomWordSavePoint, func() error { if err := removeCustomWord(chatID, kanji); err != nil { return err } if err := gamedb.Exec(fmt.Sprintf("INSERT INTO %s (chatid, userid, kanji, kana, points) VALUES (?, ?, ?, ?, ?)", customwordsTablename), chatID, userID, kanji, kana, wordpts); err != nil { return err } return updatePlayerScore(chatID, userID, addWordPts) }) } func removeCustomWord(chatID int64, kanji string) error { exists, userID := customWordExists(chatID, kanji) if !exists { // Custom word does not exist, so it has been removed. return nil } return gamedb.ExecWithSavePoint(removeCustomWordSavePoint, func() error { if err := gamedb.Exec(fmt.Sprintf("DELETE FROM %s WHERE chatid = %d AND kanji = '%s'", customwordsTablename, chatID, kanji)); err != nil { return err } return updatePlayerScore(chatID, userID, -addWordPts) }) } func customWordExists(chatID int64, kanji string) (bool, int) { // Get userID that submitted the custom word. var userID int err := gamedb.SingleQuery(fmt.Sprintf("SELECT userid from %s where chatid = %d AND kanji = '%s'", customwordsTablename, chatID, kanji), &userID) return err == nil, userID }
Scores of North American cities are expected to bid for Amazon’s second corporate headquarters, or HQ2, but only two — Calgary and Denver — are in a real race to win it, based on the giant Internet retailer’s requirements, said Adam Waterous, a member of the executive advisory committee of Calgary’s bid. “Here’s the punch line: Based on the data, third party analysis shows that it’s a two-horse race between Denver and Calgary … and we are running the faster race,” the chief executive of Waterous Energy Fund and the former global head of investment banking at Scotiabank, said Wednesday. “We think we have a large competitive advantage over Denver. We think we have a very good chance of winning this.” Strengths In an interview, Waterous said Calgary beats the Colorado city in four areas: lower cost of living, less traffic congestion, availability of office space, and opportunity for Amazon to amplify its global nature. Calgary Economic Development announced Wednesday it has established an advisory committee to support the city’s bid. In addition to Waterous, the committee includes Gregg Saretsky, CEO of WestJet Airlines; Gianna Manes, CEO of ENMAX; Alice Reimer, entrepreneur and a member of Calgary Economic Development’s board; Calgary mayor Naheed Nenshi and Mary Moran, the CEO of Calgary Economic Development. Moran has been leading a major civic effort to woo new business to Calgary to fill an abundance of top-drawer office space left vacant by downsizing oil companies. Calgary Economic Development has also formed a business base task team to build out the bid strategy and a campaign team to develop a PR campaign. Seattle-based Amazon announced Sept. 7 it was looking for a North American location to establish a second corporate headquarters, where it would hire as many as 50,000 new full-time employees with an average annual total compensation exceeding $100,000 over the next ten to fifteen years, and spend US$5 billion in construction alone. The announcement stoked a frenzy of interest, with several Canadian cities stepping up to be considered. The deadline to respond to Amazon’s request for proposals is Oct. 19 and a decision is expected in 2018. Waterous said Calgary’s optimism is based on data rather than “rooting for the home team.” On Sept. 9, The New York Times looked at how 50 U.S. cities stacked up against the criteria Amazon listed in its RFP. They include population of more than one million people, a stable and business friendly environment, the ability to retain and attract strong technical talent, big and creative thinking in attracting real estate options. It concluded that Denver led the pack. Analysis A Vancouver-based data firm, MountainMath Software and Analytics, did a similar analysis of major Canadian metropolitan areas, arguing that “the attractiveness of a location in Canada for a company that will undoubtedly want to attract talent from beyond national boundaries can’t be understated in today’s political environment. And recent changes to Canada’s work visa process for tech workers, where work visas are now issued within two weeks of application, stands in stark contrast with developments south of the border.” Of these, six fit the bill of having more than one million in population: Montreal, Calgary, Toronto, Vancouver, Edmonton and Ottawa-Gatineau. But Calgary emerged as the best fit because it has more of the other things Amazon is looking for: the right and a growing labour pool, a high quality of life, the ability for workers to easily get around and out of town, availability of space, willingness to pay to play (that is, offer incentives, which Calgary is prepared to do with help from other levels of government, said Waterous). “Calgary (is) a city frequently ranked near the top of global liveability indices, situated in proximity to beautiful national parks in the Rocky Mountains, with the recent expansion of their light rail system and downtown bike infrastructure …, with an existing and growing pool of tech-related professionals and currently a good amount of office space already built and available,” MountainMath said. Waterous said Amazon would co-exist well with Calgary’s energy-focused economy. Notably, Denver is also a major energy centre near the Rocky Mountains. Calgary has a highly educated workforce and particularly an abundance of engineers, plus plenty of executive and administrative talent, he said. Indeed, a lot of that talent is on the sidelines and motivated to work as a result of large oilpatch layoffs in the past three years. “There is a bit of a perception that Amazon is a software business, but it’s an engineering intensive business in terms of logistics management, distribution and capital spending projects,” Waterous said. “That plays exactly to Calgary’s historic engineering strength.” Financial Post [email protected]
import sys #97 if __name__ == '__main__': s = raw_input() ch = int(raw_input()) Wi = map(int,list(raw_input().split())) Wi_max = max(Wi) s_len = len(s) ans = 0 for i in xrange(s_len): ans += Wi[ord(s[i])-97]*(i+1) for i in xrange(ch): ans += Wi_max*(s_len+i+1) print ans
/** * * 2. Producer thread which can publish messages to subscribers through the EventBus * */ class Producer implements Runnable{ private ThreadSafePub pub; private String tid; public Producer(ThreadSafePub p, String tid){ this.pub = p; this.tid = tid; } @Override public void run() { try{ for (int i=0;i<10;i++){ pub.publishEvent(tid+":event"+i); Thread.sleep(500); } pub.publishEvent("END"); } catch(InterruptedException ex){ System.out.println("Thread interrupted."); } } }
<reponame>Yulyalu/yes-cart /* * Copyright 2009 Inspire-Software.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yes.cart.web.service.rest; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.MediaType; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.yes.cart.constants.AttributeNamesKeys; import org.yes.cart.domain.entity.*; import org.yes.cart.domain.i18n.I18NModel; import org.yes.cart.domain.i18n.impl.FailoverStringI18NModel; import org.yes.cart.domain.misc.Pair; import org.yes.cart.domain.ro.*; import org.yes.cart.service.domain.ShopService; import org.yes.cart.service.misc.LanguageService; import org.yes.cart.service.order.impl.CustomerTypeAdapter; import org.yes.cart.shoppingcart.ShoppingCart; import org.yes.cart.shoppingcart.ShoppingCartCommand; import org.yes.cart.shoppingcart.ShoppingCartCommandFactory; import org.yes.cart.utils.RegExUtils; import org.yes.cart.web.service.rest.impl.CartMixin; import org.yes.cart.web.service.rest.impl.RoMappingMixin; import org.yes.cart.web.support.service.AddressBookFacade; import org.yes.cart.web.support.service.CustomerServiceFacade; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; /** * User: denispavlov * Date: 21/08/2014 * Time: 14:46 */ @Controller @Api(value = "Authentication", description = "Authentication controller", tags = "auth") public class AuthenticationController { private static final String REG_FORM_CODE = "regAddressForm"; @Autowired private CustomerServiceFacade customerServiceFacade; @Autowired private AddressBookFacade addressBookFacade; @Autowired private ShoppingCartCommandFactory shoppingCartCommandFactory; @Autowired private LanguageService languageService; @Autowired private ShopService shopService; @Autowired private CartMixin cartMixin; @Autowired @Qualifier("restRoMappingMixin") private RoMappingMixin mappingMixin; /** * Interface: GET /api/rest/auth/check * <p> * <p> * Check interface that allows to check authentication state of user. The token for the authenticated cart is * returned back as response header and also as a cookie. * <p> * <p> * <h3>Headers for operation</h3><p> * <table border="1"> * <tr><td>Accept</td><td>application/json or application/xml</td></tr> * <tr><td>X-CW-TOKEN</td><td>token uuid</td></tr> * </table> * <p> * <p> * <h3>Parameters for operation</h3><p> * NONE * <p> * <p> * <h3>Output</h3><p> * * <table border="1"> * <tr><td>JSON example</td><td> * <pre><code> * { * "success" : true, * "greeting" : "<NAME>", * "token" : { * "uuid" : "<PASSWORD>" * }, * "error" : null * } * </code></pre> * </td></tr> * <tr><td>XML example</td><td> * <pre><code> * &lt;authentication-result&gt; * &lt;greeting&gt;<NAME>&lt;/greeting&gt; * &lt;success&gt;true&lt;/success&gt; * &lt;token&gt; * &lt;uuid&gt;<PASSWORD>&lt;/uuid&gt; * &lt;/token&gt; * &lt;/authentication-result&gt; * </code></pre> * </td></tr> * </table> * <p> * <p> * <h3>Error codes</h3><p> * <table border="1"> * <tr><td>SESSION_EXPIRED</td><td>user session expired</td></tr> * <tr><td>INACTIVE_FOR_SHOP</td><td>user is inactive for shop</td></tr> * <tr><td>AUTH_FAILED</td><td>user exists but credentials are not valid</td></tr> * </table> * * * @param request request * @param response response * * @return authentication result */ @ApiOperation(value = "Check interface that allows to check authentication state of user. " + "The token for the authenticated cart is returned back as response header and also as a cookie.") @RequestMapping( value = "/auth/check", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE } ) public @ResponseBody AuthenticationResultRO check(final HttpServletRequest request, final HttpServletResponse response) { final ShoppingCart cart = cartMixin.getCurrentCart(); cartMixin.persistShoppingCart(request, response); switch (cart.getLogonState()) { case ShoppingCart.LOGGED_IN: return new AuthenticationResultRO( cart.getCustomerName(), new TokenRO(cart.getGuid())); case ShoppingCart.SESSION_EXPIRED: final AuthenticationResultRO authExpired = new AuthenticationResultRO( cart.getCustomerName(), new TokenRO(cart.getGuid())); authExpired.setAuthenticated(false); authExpired.setCode("SESSION_EXPIRED"); return authExpired; case ShoppingCart.INACTIVE_FOR_SHOP: final AuthenticationResultRO authInactive = new AuthenticationResultRO( cart.getCustomerName(), new TokenRO(cart.getGuid())); authInactive.setAuthenticated(false); authInactive.setCode("INACTIVE_FOR_SHOP"); return authInactive; case ShoppingCart.NOT_LOGGED: default: return new AuthenticationResultRO("AUTH_FAILED"); } } /** * Interface: POST /api/rest/auth/login * <p> * <p> * Login interface that allows to authenticate user cart. The token for the authenticated cart is * returned back as response header and also as a cookie. * <p> * <p> * <h3>Headers for operation</h3><p> * <table border="1"> * <tr><td>Content-Type</td><td>application/json or application/xml</td></tr> * <tr><td>Accept</td><td>application/json or application/xml</td></tr> * <tr><td>X-CW-TOKEN</td><td>token uuid (optional)</td></tr> * </table> * <p> * <p> * <h3>Parameters for login PUT operation</h3><p> * <table border="1"> * <tr><td>JSON example</td><td> * <pre><code> * { * "username": "<EMAIL>", * "password": "<PASSWORD>-", * "activate": true * } * </code></pre> * </td></tr> * <tr><td>XML example</td><td> * <pre><code> * &lt;login&gt; * &lt;username&gt;<EMAIL>&lt;/username&gt; * &lt;password&gt;<PASSWORD>-&lt;/password&gt; * &lt;activate&gt;true&lt;/activate&gt; * &lt;/login&gt; * </code></pre> * </td></tr> * </table> * <p> * <p> * <h3>Output</h3><p> * * <table border="1"> * <tr><td>JSON example</td><td> * <pre><code> * { * "success" : true, * "greeting" : "<NAME>", * "token" : { * "uuid" : "1db8def2-21e0-44d2-aeb0-56baae761129" * }, * "error" : null * } * </code></pre> * </td></tr> * <tr><td>XML example</td><td> * <pre><code> * &lt;authentication-result&gt; * &lt;greeting&gt;<NAME>&lt;/greeting&gt; * &lt;success&gt;true&lt;/success&gt; * &lt;token&gt; * &lt;uuid&gt;1db8def2-21e0-44d2-aeb0-56baae761129&lt;/uuid&gt; * &lt;/token&gt; * &lt;/authentication-result&gt; * </code></pre> * </td></tr> * </table> * <p> * <p> * <h3>Error codes</h3><p> * <table border="1"> * <tr><td>USER_FAILED</td><td>user does not exist</td></tr> * <tr><td>AUTH_FAILED</td><td>user exists but credentials are not valid</td></tr> * <tr><td>INACTIVE_FOR_SHOP</td><td>user exists but profile is active for given shop, use activate=true to force activation on login</td></tr> * </table> * * * @param loginRO login parameters (see examples above) * @param request request * @param response response * * @return authentication result */ @ApiOperation(value = "Login interface that allows to authenticate user cart. " + "The token for the authenticated cart is returned back as response header and also as a cookie.", tags = { "auth", "manager"}) @RequestMapping( value = "/auth/login", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE } ) public @ResponseBody AuthenticationResultRO login(final @ApiParam(value = "Login as customer flag") @RequestParam(value = "customer", required = false) Boolean customer, final @ApiParam(value = "Login data") @RequestBody LoginRO loginRO, final HttpServletRequest request, final HttpServletResponse response) { if (customer != null && customer) { executeLoginOnBehalf(loginRO.getUsername()); } else { executeLoginCommand(loginRO.getUsername(), loginRO.getPassword()); } final TokenRO token = cartMixin.persistShoppingCart(request, response); ShoppingCart cart = cartMixin.getCurrentCart(); final int logOnState = cart.getLogonState(); if (logOnState == ShoppingCart.LOGGED_IN) { return new AuthenticationResultRO(cart.getCustomerName(), token); } return new AuthenticationResultRO("AUTH_FAILED"); } /** * Interface: POST /api/rest/auth/logout * <p> * <p> * Logout interface that allows to de-authenticate user cart. The token for the authenticated cart is * returned back as response header and also as a cookie. * <p> * <p> * <h3>Headers for operation</h3><p> * <table border="1"> * <tr><td>Accept</td><td>application/json or application/xml</td></tr> * <tr><td>X-CW-TOKEN</td><td>token uuid</td></tr> * </table> * <p> * <p> * <h3>Parameters for logout operation</h3><p> * NONE * <p> * <p> * <h3>Output</h3><p> * * <table border="1"> * <tr><td>JSON example</td><td> * <pre><code> * { * "success" : true, * "greeting" : null, * "tokenRO" : null, * "error" : 'LOGOUT_SUCCESS' * } * </code></pre> * </td></tr> * <tr><td>XML example</td><td> * <pre><code> * &lt;authentication-result&gt; * &lt;greeting&gt;<NAME>&lt;/greeting&gt; * &lt;success&gt;true&lt;/success&gt; * &lt;token&gt; * &lt;uuid&gt;1db8def2-21e0-44d2-aeb0-56baae761129&lt;/uuid&gt; * &lt;/token&gt; * &lt;/authentication-result&gt; * </code></pre> * </td></tr> * </table> * <p> * <p> * <h3>Error codes</h3><p> * <table border="1"> * <tr><td>LOGOUT_SUCCESS</td><td>if logout was successful</td></tr> * </table> * * * @param request request * @param response response * * @return authentication result */ @ApiOperation(value = "Logout interface that allows to de-authenticate user cart. " + "The token for the authenticated cart is returned back as response header and also as a cookie.", tags = { "auth", "manager"}) @RequestMapping( value = "/auth/logout", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE } ) public @ResponseBody AuthenticationResultRO logout(final @ApiParam(value = "Logout from customer account flag") @RequestParam(value = "customer", required = false) Boolean customer, final HttpServletRequest request, final HttpServletResponse response) { final ShoppingCart cart = cartMixin.getCurrentCart(); if (cart.getLogonState() == ShoppingCart.LOGGED_IN) { if (customer != null && customer) { executeLogoutCustomerCommand(); final TokenRO token = cartMixin.persistShoppingCart(request, response); ShoppingCart freshCart = cartMixin.getCurrentCart(); final int logOnState = freshCart.getLogonState(); if (logOnState == ShoppingCart.LOGGED_IN) { return new AuthenticationResultRO(freshCart.getCustomerName(), token); } } else { executeLogoutCommand(); cartMixin.persistShoppingCart(request, response); } } return new AuthenticationResultRO("LOGOUT_SUCCESS"); } /** * Interface: GET /api/rest/auth/register * <p> * <p> * Interface to list all attributes required for registration. * <p> * If customerType is not specified returns form with two custom attributes: 1) customerType - containing customer type choices * and 2) guestCheckoutEnabled - containing true/false flag. * <p> * If customerType is specified returns custom attributes that represent form fields. * <p> * <p> * <h3>Headers for operation</h3><p> * <table border="1"> * <tr><td>Content-Type</td><td>application/json or application/xml</td></tr> * <tr><td>Accept</td><td>application/json or application/xml</td></tr> * <tr><td>X-CW-TOKEN</td><td>token uuid (optional)</td></tr> * </table> * <p> * <p> * <h3>Parameters for register GET operation</h3><p> * <p> * <table border="1"> * <tr><td>customerType</td><td>B2B,B2C etc must be configured in SHOP_CUSTOMER_TYPES</td></tr> * </table> * <p> * <h3>Output</h3><p> * <table border="1"> * <tr><td>JSON example</td><td> * <pre><code> * { * "phone" : null, * "custom" : [ * { * "attrvalueId" : 0, * "val" : null, * "displayVals" : null, * "attributeName" : "Marketing Opt in", * "attributeId" : 11051, * "attributeDisplayNames" : {}, * "attributeDisplayChoices" : {}, * "customerId" : 0 * }, * { * "attrvalueId" : 0, * "val" : null, * "displayVals" : null, * "attributeName" : "Customer Type", * "attributeId" : 1611, * "attributeDisplayNames" : { * "uk" : "тип пользователя", * "en" : "Customer Type" * }, * "attributeDisplayChoices" : { * "uk" : "B-Покупатель,S-Продавец", * "ru" : "B-Покупатель,S-Продавец", * "en" : "B-Buyer,S-Seller" * }, * "customerId" : 0 * } * ], * "lastname" : null, * "firstname" : null, * "email" : null * } * </code></pre> * </td></tr> * <tr><td>XML example</td><td> * <pre><code> * &lt;register-form&gt; * &lt;custom&gt; * &lt;attribute attribute-id="11051" attrvalue-id="0" customer-id="0"&gt; * &lt;attribute-display-choices/&gt; * &lt;attribute-display-names/&gt; * &lt;attribute-name&gt;Marketing Opt in&lt;/attribute-name&gt; * &lt;/attribute&gt; * &lt;attribute attribute-id="1611" attrvalue-id="0" customer-id="0"&gt; * &lt;attribute-display-choices&gt; * &lt;entry lang="uk"&gt;B-Покупатель,S-Продавец&lt;/entry&gt; * &lt;entry lang="en"&gt;B-Buyer,S-Seller&lt;/entry&gt; * &lt;entry lang="ru"&gt;B-Покупатель,S-Продавец&lt;/entry&gt; * &lt;/attribute-display-choices&gt; * &lt;attribute-display-names&gt; * &lt;entry lang="uk"&gt;тип пользователя&lt;/entry&gt; * &lt;entry lang="en"&gt;Customer Type&lt;/entry&gt; * &lt;/attribute-display-names&gt; * &lt;attribute-name&gt;Customer Type&lt;/attribute-name&gt; * &lt;/attribute&gt; * &lt;/custom&gt; * &lt;/register-form&gt; * </code></pre> * </td></tr> * </table> * <p> * <p> * * @param request request * @param response response * * @return registration data */ @ApiOperation(value = "Interface to list all attributes required for registration. " + "If customerType is not specified returns form with two custom attributes: " + "1) customerType - containing customer type choices and 2) guestCheckoutEnabled - containing true/false flag. " + "If customerType is specified returns custom attributes that represent form fields.", tags = { "auth", "manager"}) @RequestMapping( value = "/auth/register", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE } ) public @ResponseBody RegisterFormRO register(final @ApiParam(value = "Customer type to retrieve registration attributes for") @RequestParam(value = "customerType", required = false) String customerType, final HttpServletRequest request, final HttpServletResponse response) { cartMixin.persistShoppingCart(request, response); final Shop shop = cartMixin.getCurrentShop(); final List<Pair<String, I18NModel>> allowedTypes = customerServiceFacade.getShopSupportedCustomerTypes(shop); final RegisterFormRO formRO = new RegisterFormRO(); if (StringUtils.isNotBlank(customerType)) { // Retrieve form fields for type formRO.setCustomerType(customerType); if (AttributeNamesKeys.Cart.CUSTOMER_TYPE_GUEST.equals(customerType)) { formRO.setCustomerTypeSupported(customerServiceFacade.isShopGuestCheckoutSupported(shop)); } else { formRO.setCustomerTypeSupported(customerServiceFacade.isShopCustomerTypeSupported(shop, customerType)); } final List<AttrValueWithAttribute> allReg = getAllRegistrationAttributes(customerType, shop); formRO.setCustom(mappingMixin.map(allReg, AttrValueAndAttributeRO.class, AttrValueWithAttribute.class)); } else { // If no type then present form with allowed types. final AttrValueAndAttributeRO avroct = new AttrValueAndAttributeRO(); avroct.setAttributeCode("customerType"); final List<String> supported = languageService.getSupportedLanguages(shop.getCode()); final Map<String, String> displayChoice = new HashMap<>(); for (final Pair<String, I18NModel> allowedType : allowedTypes) { for (final String lang : supported) { final String i18n = allowedType.getSecond().getValue(lang); String existing = displayChoice.get(lang); if (existing != null) { displayChoice.put(lang, existing + "," + allowedType.getFirst() + "-" + i18n); } else { displayChoice.put(lang, allowedType.getFirst() + "-" + i18n); } } } avroct.setAttributeDisplayChoices(displayChoice); final AttrValueAndAttributeRO avrogc = new AttrValueAndAttributeRO(); avrogc.setAttributeCode("guestCheckoutEnabled"); avrogc.setVal(String.valueOf(customerServiceFacade.isShopGuestCheckoutSupported(shop))); formRO.setCustom(new ArrayList<>(Arrays.asList(avrogc, avroct))); } return formRO; } private List<AttrValueWithAttribute> getAllRegistrationAttributes(final String customerType, final Shop shop) { final List<AttrValueWithAttribute> allReg = new ArrayList<>(); final List<AttrValueWithAttribute> avs = customerServiceFacade.getShopRegistrationAttributes(shop, customerType); for (final AttrValueWithAttribute attrValue : avs) { if (REG_FORM_CODE.equals(attrValue.getAttributeCode())) { final List<AttrValueWithAttribute> regAddressForm = addressBookFacade .getShopCustomerAddressAttributes(new CustomerTypeAdapter(customerType), shop, Address.ADDR_TYPE_SHIPPING); if (CollectionUtils.isNotEmpty(regAddressForm)) { for (final AttrValueWithAttribute attrValueAddr : regAddressForm) { // include address form attributes but prefix them with address form code attrValueAddr.setAttributeCode(REG_FORM_CODE.concat(".").concat(attrValueAddr.getAttributeCode())); allReg.add(attrValueAddr); } } } else { allReg.add(attrValue); } } return allReg; } /** * Interface: POST /api/rest/auth/register * <p> * <p> * Register interface that allows to register user. The token for the authenticated cart is * returned back as response header and also as a cookie. * <p> * <p> * <h3>Headers for operation</h3><p> * <table border="1"> * <tr><td>Content-Type</td><td>application/json or application/xml</td></tr> * <tr><td>Accept</td><td>application/json or application/xml</td></tr> * <tr><td>X-CW-TOKEN</td><td>token uuid (optional)</td></tr> * </table> * <p> * <p> * <h3>Parameters for register PUT operation</h3><p> * <p> * <p> * <table border="1"> * <tr><td>JSON example:</td><td> * <pre><code> * { * "email" : "<EMAIL>", * "firstname" : "Bob", * "lastname" : "Doe", * "phone" : "123123123123", * "customerType" : "B2C", * "custom" : { * "attr1": "value1", * "attr2": "value2", * ... * "attrN": "valueN" * } * } * </code></pre> * </td></tr> * <tr><td>XML example:</td><td> * <pre><code> * &lt;login&gt; * &lt;email&gt;<EMAIL>&lt;/email&gt; * &lt;firstname&gt;Bob&lt;/firstname&gt; * &lt;lastname&gt;Doe&lt;/lastname&gt; * &lt;phone&gt;123123123123&lt;/phone&gt; * &lt;custom&gt; * &lt;entry key="attr1"&gt;value1&lt;/entry&gt; * &lt;entry key="attr2"&gt;value2&lt;/entry&gt; * ... * &lt;entry key="attrN"&gt;valueN&lt;/entry&gt; * &lt;/custom&gt; * &lt;/login&gt; * </code></pre> * </td></tr> * </table> * <p> * <p> * <h3>Output</h3><p> * <table border="1"> * <tr><td>JSON example</td><td> * <pre><code> * { * "success" : true, * "greeting" : "<NAME>", * "token" : { * "uuid" : "<PASSWORD>" * }, * "error" : null * } * </code></pre> * </td></tr> * <tr><td>XML example</td><td> * <pre><code> * &lt;authentication-result&gt; * &lt;greeting&gt;<NAME>&lt;/greeting&gt; * &lt;success&gt;true&lt;/success&gt; * &lt;token&gt; * &lt;uuid&gt;<PASSWORD>&lt;/uuid&gt; * &lt;/token&gt; * &lt;/authentication-result&gt; * </code></pre> * </td></tr> * </table> * <p> * <p> * <h3>Error codes</h3><p> * <table border="1"> * <tr><td>USER_EXISTS</td><td>Customer already exists</td></tr> * <tr><td>USER_TYPE_FAILED</td><td>Unsupported customer type</td></tr> * <tr><td>EMAIL_FAILED</td><td>email must be more than 6 and less than 256 chars (^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*((\.[A-Za-z]{2,}){1}$)) </td></tr> * <tr><td>FIRSTNAME_FAILED</td><td>must be not blank</td></tr> * <tr><td>LASTNAME_FAILED</td><td>must be not blank</td></tr> * <tr><td>PHONE_FAILED</td><td>phone must be more than 4 and less than 13 chars</td></tr> * <tr><td>[ATTRIBUTE CODE]:FAILED</td><td> * E.g. CUSTOMERTYPE_FAILED denoting that mandatory value was missing (could also happen if regex fails but there is no * validation message specified on the {@link org.yes.cart.domain.entity.Attribute#getValidationFailedMessage()}) * </td></tr> * <tr><td>[ATTRIBUTE CODE]:FAILED:[Message]</td><td> * E.g. "CUSTOMERTYPE:FAILED:Please choose either Buyer or Seller (UK)" denoting that regex test failed. * RegEx and Message come from {@link org.yes.cart.domain.entity.Attribute#getRegexp()} and * {@link org.yes.cart.domain.entity.Attribute#getValidationFailedMessage()} respectively * </td></tr> * <tr><td>USER_FAILED</td><td>email must not be already registered</td></tr> * </table> * * * @param registerRO register parameters (see examples above) * @param request request * @param response response * * @return authentication result */ @ApiOperation(value = "Register interface that allows to register user. " + "The token for the authenticated cart is returned back as response header and also as a cookie.", tags = { "auth", "manager"}) @RequestMapping( value = "/auth/register", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }, consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE } ) public @ResponseBody AuthenticationResultRO register(final @ApiParam(value = "Registration details") @RequestBody RegisterRO registerRO, final HttpServletRequest request, final HttpServletResponse response) { // non-typed customers or guests are not allowed if (StringUtils.isBlank(registerRO.getCustomerType()) || AttributeNamesKeys.Cart.CUSTOMER_TYPE_GUEST.equals(registerRO.getCustomerType()) || !customerServiceFacade.isShopCustomerTypeSupported(cartMixin.getCurrentShop(), registerRO.getCustomerType())) { return new AuthenticationResultRO("USER_TYPE_FAILED"); } final ShoppingCart cart = cartMixin.getCurrentCart(); final Shop shop = cartMixin.getCurrentShop(); Shop registrationShop = shop; if (StringUtils.isNotBlank(registerRO.getOrganisation())) { registrationShop = shopService.getSubShopByNameAndMaster(registerRO.getOrganisation(), shop.getShopId()); if (registrationShop == null) { return new AuthenticationResultRO("ORGANISATION_FAILED"); } } final Map<String, Object> data = new HashMap<>(); data.put("customerType", registerRO.getCustomerType()); String passwordAttr = null; String confirmPasswordAttr = null; if (registerRO.getCustom() != null) { final List<AttrValueWithAttribute> allReg = getAllRegistrationAttributes(registerRO.getCustomerType(), shop); for (final AttrValueWithAttribute av : allReg) { final Attribute attr = av.getAttribute(); if ("password".equals(av.getAttribute().getVal())) { passwordAttr = av.getAttributeCode(); } else if ("confirmPassword".equals(av.getAttribute().getVal())) { confirmPasswordAttr = av.getAttributeCode(); } final String value = registerRO.getCustom().get(av.getAttributeCode()); final AuthenticationResultRO result = checkValid(attr, value, cart.getCurrentLocale()); if (result != null) { return result; } data.put(av.getAttributeCode(), value); } } final String userPass = (String) data.get(passwordAttr); final String confirmPass = (String) data.get(confirmPasswordAttr); if (StringUtils.isNotBlank(userPass) && !userPass.equals(confirmPass)) { return new AuthenticationResultRO("PASSWORD_MATCH_FAILED"); } final CustomerServiceFacade.RegistrationResult reg = customerServiceFacade.registerCustomer(registrationShop, data); if (reg.isDuplicate()) { // No existing users not allowed return new AuthenticationResultRO("USER_EXISTS"); } else if (!reg.isSuccess()) { return new AuthenticationResultRO("UNABLE_TO_REGISTER"); } final String login = reg.getCustomer().getLogin(); final String passw = reg.getRawPassword(); final LoginRO loginRO = new LoginRO(); loginRO.setUsername(login); loginRO.setPassword(<PASSWORD>); return login(null, loginRO, request, response); } /** * Interface: POST /api/rest/auth/guest * <p> * <p> * Guest interface that allows create guest user. The token for the authenticated cart is * returned back as response header and also as a cookie. * <p> * <p> * <h3>Headers for operation</h3><p> * <table border="1"> * <tr><td>Content-Type</td><td>application/json or application/xml</td></tr> * <tr><td>Accept</td><td>application/json or application/xml</td></tr> * <tr><td>X-CW-TOKEN</td><td>token uuid (optional)</td></tr> * </table> * <p> * <p> * <h3>Parameters for register PUT operation</h3><p> * <p> * <p> * <table border="1"> * <tr><td>JSON example:</td><td> * <pre><code> * { * "email" : "<EMAIL>", * "firstname" : "Bob", * "lastname" : "Doe", * "phone" : "123123123123", * "customerType" : "B2G", * "custom" : { * "attr1": "value1", * "attr2": "value2", * ... * "attrN": "valueN" * } * } * </code></pre> * </td></tr> * <tr><td>XML example:</td><td> * <pre><code> * &lt;login&gt; * &lt;email&gt;<EMAIL>&lt;/email&gt; * &lt;firstname&gt;Bob&lt;/firstname&gt; * &lt;lastname&gt;Doe&lt;/lastname&gt; * &lt;phone&gt;123123123123&lt;/phone&gt; * &lt;custom&gt; * &lt;entry key="attr1"&gt;value1&lt;/entry&gt; * &lt;entry key="attr2"&gt;value2&lt;/entry&gt; * ... * &lt;entry key="attrN"&gt;valueN&lt;/entry&gt; * &lt;/custom&gt; * &lt;/login&gt; * </code></pre> * </td></tr> * </table> * <p> * <p> * <h3>Output</h3><p> * <table border="1"> * <tr><td>JSON example</td><td> * <pre><code> * { * "success" : true, * "greeting" : "<NAME>", * "token" : { * "uuid" : "1db8def2-21e0-44d2-aeb0-56baae761129" * }, * "error" : null * } * </code></pre> * </td></tr> * <tr><td>XML example</td><td> * <pre><code> * &lt;authentication-result&gt; * &lt;greeting&gt;<NAME>&lt;/greeting&gt; * &lt;success&gt;true&lt;/success&gt; * &lt;token&gt; * &lt;uuid&gt;1db8def2-21e0-44d2-aeb0-56baae761129&lt;/uuid&gt; * &lt;/token&gt; * &lt;/authentication-result&gt; * </code></pre> * </td></tr> * </table> * <p> * <p> * <h3>Error codes</h3><p> * <table border="1"> * <tr><td>EMAIL_FAILED</td><td>email must be more than 6 and less than 256 chars (^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*((\.[A-Za-z]{2,}){1}$)) </td></tr> * <tr><td>FIRSTNAME_FAILED</td><td>must be not blank</td></tr> * <tr><td>LASTNAME_FAILED</td><td>must be not blank</td></tr> * <tr><td>PHONE_FAILED</td><td>phone must be more than 4 and less than 13 chars</td></tr> * <tr><td>[ATTRIBUTE CODE]:FAILED</td><td> * E.g. CUSTOMERTYPE_FAILED denoting that mandatory value was missing (could also happen if regex fails but there is no * validation message specified on the {@link org.yes.cart.domain.entity.Attribute#getValidationFailedMessage()}) * </td></tr> * <tr><td>[ATTRIBUTE CODE]:FAILED:[Message]</td><td> * E.g. "CUSTOMERTYPE:FAILED:Please choose either Buyer or Seller (UK)" denoting that regex test failed. * RegEx and Message come from {@link org.yes.cart.domain.entity.Attribute#getRegexp()} and * {@link org.yes.cart.domain.entity.Attribute#getValidationFailedMessage()} respectively * </td></tr> * <tr><td>GUEST_FAILED</td><td>error creating guest account</td></tr> * </table> * * * @param registerRO register parameters (see examples above) * @param request request * @param response response * * @return authentication result */ @ApiOperation(value = "Guest interface that allows create guest user. " + "The token for the authenticated cart is returned back as response header and also as a cookie.") @RequestMapping( value = "/auth/guest", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }, consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE } ) public @ResponseBody AuthenticationResultRO guest(final @ApiParam(value = "Registration details") @RequestBody RegisterRO registerRO, final HttpServletRequest request, final HttpServletResponse response) { // Only guests allowed if (StringUtils.isBlank(registerRO.getCustomerType()) || !AttributeNamesKeys.Cart.CUSTOMER_TYPE_GUEST.equals(registerRO.getCustomerType())) { return new AuthenticationResultRO("GUEST_FAILED"); } final ShoppingCart cart = cartMixin.getCurrentCart(); final Shop shop = cartMixin.getCurrentShop(); if (!customerServiceFacade.isShopGuestCheckoutSupported(shop)) { return new AuthenticationResultRO("GUEST_FAILED"); } for (final AttrValueWithAttribute av : customerServiceFacade.getShopRegistrationAttributes(shop, registerRO.getCustomerType())) { final Attribute attr = av.getAttribute(); if ("email".equals(av.getAttribute().getVal())) { final String value = av.getAttributeCode(); final AuthenticationResultRO result = checkValid(attr, value, cart.getCurrentLocale()); if (result != null) { return result; } else { break; } } } final Map<String, Object> data = new HashMap<>(); data.put("customerType", registerRO.getCustomerType()); data.put("cartGuid", cart.getGuid()); if (registerRO.getCustom() != null) { for (final AttrValueWithAttribute av : customerServiceFacade.getShopRegistrationAttributes(shop, registerRO.getCustomerType())) { final Attribute attr = av.getAttribute(); final String value = registerRO.getCustom().get(attr.getCode()); final AuthenticationResultRO result = checkValid(attr, value, cart.getCurrentLocale()); if (result != null) { return result; } data.put(attr.getCode(), value); } } final CustomerServiceFacade.RegistrationResult guest = customerServiceFacade.registerGuest(shop, data); if (guest.isSuccess()) { final TokenRO token = cartMixin.persistShoppingCart(request, response); return new AuthenticationResultRO(null, token); } return new AuthenticationResultRO("GUEST_FAILED"); } /** * Interface: POST /api/rest/auth/resetpassword * <p> * <p> * Reset password interface that allows to request password to be reset and reset it. * Password reset is a two step process. First step is to provide valid email of registered * customer and generate authToken. Second step is to use authToken in order to confirm password * reset. * <p> * <p> * <h3>Headers for operation</h3><p> * <table border="1"> * <tr><td>Accept</td><td>application/json or application/xml</td></tr> * <tr><td>X-CW-TOKEN</td><td>token uuid (optional)</td></tr> * </table> * <p> * <p> * <h3>Parameters for operation</h3><p> * <table border="1"> * <tr><td>email</td><td> * E-mail of a registered customer. Supplying this parameter will trigger an email * with authToken. * </td></tr> * <tr><td>authToken</td><td> * Authentication token of a registered customer. Supplying this parameter will trigger an * email with new password. * </td></tr> * <tr><td>newPassword</td><td> * New password to accompany authToken for configurations that support customer selectable * passwords. * </td></tr> * </table> * <p> * <p> * <h3>Output</h3><p> * <p> * Output that does not have error code indicates successful processing. * <p> * <table border="1"> * <tr><td>JSON example</td><td> * <pre><code> * { * "success" : false, * "greeting" : null, * "token" : null, * "error" : null * } * </code></pre> * </td></tr> * <tr><td>XML example</td><td> * <pre><code> * &lt;authentication-result&gt; * &lt;greeting/&gt; * &lt;success&gt;false&lt;/success&gt; * &lt;token/&gt; * &lt;/authentication-result&gt; * </code></pre> * </td></tr> * </table> * <p> * <p> * <h3>Error codes</h3><p> * <table border="1"> * <tr><td>INVALID_PARAMETERS</td><td>if either "email" or "authToken" was not sent</td></tr> * <tr><td>INVALID_TOKEN</td><td>Supplied authToken is not valid or expired</td></tr> * <tr><td>INVALID_EMAIL</td><td>Supplied email does not belong to a registered customer</td></tr> * </table> * * * @param request request * @param response response * * @return authentication result */ @ApiOperation(value = "Reset password interface that allows to request password to be reset and reset it. " + "Password reset is a two step process. First step is to provide valid email of registered customer and " + "generate authToken. Second step is to use authToken in order to confirm password reset.", tags = "customer") @RequestMapping( value = "/auth/resetpassword", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE } ) public @ResponseBody CodedResultRO resetPassword(final @ApiParam(value = "Email") @RequestParam(value = "email", required = false) String email, final @ApiParam(value = "Authentication token to authorise new password") @RequestParam(value = "authToken", required = false) String authToken, final @ApiParam(value = "New password") @RequestParam(value = "newPassword", required = false) String newPassword, final HttpServletRequest request, final HttpServletResponse response) { cartMixin.persistShoppingCart(request, response); if (StringUtils.isNotBlank(authToken)) { if (executePasswordResetCommand(authToken, newPassword)) { return new CodedResultRO(); } return new CodedResultRO("INVALID_TOKEN"); } else if (StringUtils.isNotBlank(email)) { final Shop shop = cartMixin.getCurrentShop(); final Customer customer = customerServiceFacade.getCustomerByLogin(cartMixin.getCurrentShop(), email); if (customer == null) { return new CodedResultRO("INVALID_EMAIL"); } customerServiceFacade.resetPassword(shop, customer); return new CodedResultRO(); } return new CodedResultRO("INVALID_PARAMETERS"); } /** * Interface: POST /api/rest/auth/deleteaccount * <p> * <p> * Delete account of currently logged in user. * Delete account is a two step process. First step is to provide valid email of registered * customer and generate authToken. Second step is to use authToken in order to confirm account * deletion. * <p> * <p> * <h3>Headers for operation</h3><p> * <table border="1"> * <tr><td>Accept</td><td>application/json or application/xml</td></tr> * <tr><td>X-CW-TOKEN</td><td>token uuid (optional)</td></tr> * </table> * <p> * <p> * <h3>Parameters for operation</h3><p> * <table border="1"> * <tr><td>authToken</td><td> * Authentication token of a registered customer. Supplying this parameter will trigger an * email with new password. * </td></tr> * <tr><td>password</td><td> * Password to accompany authToken to confirm account deletion. * </td></tr> * </table> * <p> * <p> * <h3>Output</h3><p> * <p> * Output that does not have error code indicates successful processing. * <p> * <table border="1"> * <tr><td>JSON example</td><td> * <pre><code> * { * "success" : false, * "greeting" : null, * "token" : null, * "error" : null * } * </code></pre> * </td></tr> * <tr><td>XML example</td><td> * <pre><code> * &lt;authentication-result&gt; * &lt;greeting/&gt; * &lt;success&gt;false&lt;/success&gt; * &lt;token/&gt; * &lt;/authentication-result&gt; * </code></pre> * </td></tr> * </table> * <p> * <p> * <h3>Error codes</h3><p> * <table border="1"> * <tr><td>INVALID_PARAMETERS</td><td>if either "email" or "authToken" was not sent</td></tr> * <tr><td>INVALID_TOKEN</td><td>Supplied authToken is not valid or expired</td></tr> * <tr><td>INVALID_EMAIL</td><td>Supplied email does not belong to a registered customer</td></tr> * </table> * * * @param request request * @param response response * * @return authentication result */ @ApiOperation(value = "Delete account of currently logged in user. " + "Delete account is a two step process. First step is to provide valid email of registered " + "customer and generate authToken. Second step is to use authToken in order to confirm account deletion.", tags = "customer") @RequestMapping( value = "/auth/deleteaccount", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE } ) public @ResponseBody CodedResultRO deleteAccount(final @ApiParam(value = "Authentication token to authorise account removal") @RequestParam(value = "authToken", required = false) String authToken, final @ApiParam(value = "Current password") @RequestParam(value = "password", required = false) String password, final HttpServletRequest request, final HttpServletResponse response) { cartMixin.persistShoppingCart(request, response); if (StringUtils.isNotBlank(authToken)) { if (executeDeleteAccountCommand(authToken, password)) { return new CodedResultRO(); } return new CodedResultRO("INVALID_TOKEN"); } else if (check(request, response).isAuthenticated()) { final Shop shop = cartMixin.getCurrentShop(); final ShoppingCart cart = cartMixin.getCurrentCart(); final Customer customer = customerServiceFacade.getCustomerByLogin(cartMixin.getCurrentShop(), cart.getCustomerLogin()); if (customer == null) { return new CodedResultRO("INVALID_EMAIL"); } customerServiceFacade.deleteAccount(shop, customer); return new CodedResultRO(); } return new CodedResultRO("INVALID_PARAMETERS"); } /** * Execute login command. * * @param email customer. * @param password password. */ protected void executeLoginCommand(final String email, final String password) { shoppingCartCommandFactory.execute(ShoppingCartCommand.CMD_LOGIN, cartMixin.getCurrentCart(), new HashMap<String, Object>() {{ put(ShoppingCartCommand.CMD_LOGIN_P_LOGIN, email); put(ShoppingCartCommand.CMD_LOGIN_P_PASS, password); put(ShoppingCartCommand.CMD_LOGIN, ShoppingCartCommand.CMD_LOGIN); }} ); } /** * Execute login command. * * @param email customer. */ protected void executeLoginOnBehalf(final String email) { shoppingCartCommandFactory.execute(ShoppingCartCommand.CMD_LOGIN_ON_BEHALF, cartMixin.getCurrentCart(), new HashMap<String, Object>() {{ put(ShoppingCartCommand.CMD_LOGIN_P_LOGIN, email); put(ShoppingCartCommand.CMD_LOGIN_ON_BEHALF, ShoppingCartCommand.CMD_LOGIN_ON_BEHALF); }} ); } /** * Execute logout command. */ protected void executeLogoutCommand() { shoppingCartCommandFactory.execute(ShoppingCartCommand.CMD_LOGOUT, cartMixin.getCurrentCart(), new HashMap<String, Object>() {{ put(ShoppingCartCommand.CMD_LOGOUT, ShoppingCartCommand.CMD_LOGOUT); }} ); } /** * Execute logout command. */ protected void executeLogoutCustomerCommand() { shoppingCartCommandFactory.execute(ShoppingCartCommand.CMD_LOGOUT_ON_BEHALF, cartMixin.getCurrentCart(), new HashMap<String, Object>() {{ put(ShoppingCartCommand.CMD_LOGOUT_ON_BEHALF, ShoppingCartCommand.CMD_LOGOUT_ON_BEHALF); }} ); } /** * Execute password reset command. */ protected boolean executePasswordResetCommand(final String token, final String newPassword) { try { final Map<String, Object> params = new HashMap<>(); params.put(ShoppingCartCommand.CMD_RESET_PASSWORD, token); if (StringUtils.isNotBlank(newPassword)) { params.put(ShoppingCartCommand.CMD_RESET_PASSWORD_PW, newPassword); } shoppingCartCommandFactory.execute(ShoppingCartCommand.CMD_RESET_PASSWORD, cartMixin.getCurrentCart(), params); return true; } catch (BadCredentialsException bce) { return false; } } /** * Execute delete account command. */ protected boolean executeDeleteAccountCommand(final String token, final String password) { try { final Map<String, Object> params = new HashMap<>(); params.put(ShoppingCartCommand.CMD_DELETE_ACCOUNT, token); params.put(ShoppingCartCommand.CMD_DELETE_ACCOUNT_PW, password); shoppingCartCommandFactory.execute(ShoppingCartCommand.CMD_DELETE_ACCOUNT, cartMixin.getCurrentCart(), params); return true; } catch (BadCredentialsException bce) { return false; } } protected AuthenticationResultRO checkValid(final Attribute attr, final String value, final String lang) { if (attr.isMandatory() && StringUtils.isBlank(value)) { return new AuthenticationResultRO(attr.getCode() + ":FAILED"); } else if (StringUtils.isNotBlank(attr.getRegexp()) && !RegExUtils.getInstance(attr.getRegexp()).matches(value)) { final String regexError = new FailoverStringI18NModel( attr.getValidationFailedMessage(), null).getValue(lang); if (StringUtils.isBlank(regexError)) { return new AuthenticationResultRO(attr.getCode() + ":FAILED"); } return new AuthenticationResultRO(attr.getCode() + ":FAILED:" + regexError); } return null; } }
// What happens if malloc returns null? #include "testharness.h" #include <malloc.h> #include <sys/resource.h> #include <unistd.h> struct list { struct list* next; int data[1024*10]; }; int main() { struct list* p = 0; // This test tries to run out of memory. To avoid annoying other users, // put a 10MB limit on the memory that is allocated to this test. const int heapSize = 1024*1024*10; struct rlimit limit = {heapSize, heapSize}; int res = setrlimit(RLIMIT_DATA, &limit); if (res != 0){ printf("***setrlimit didn't work"); } while(1) { //Eventually, malloc returns null. Hopefully, CCured won't try to //dereference it. struct list* newp = malloc(sizeof(struct list)); if (! newp) { break; } newp->next = p; p = newp; } SUCCESS; }
The anti-apoptotic and anti-oxidant effect of eriodictyol on UV-induced apoptosis in keratinocytes. Recently, considerable scientific and therapeutic interest has focused on the structure and functions of the flavonoids. In a previous study, we suggested that hydroxyl (OH) substitutions on specific carbons in the skeleton of the flavonoids might significantly affect their apoptosis-modulating properties. Here, to investigate the effect of various OH substitutions on their diphenylpropane (C6C3C6) skeleton carbons, we selected 10 different flavonoids and assessed their role on UV-induced apoptosis of human keratinocytes, the principal cell type of epidermis. The results showed that 5,7,3',4'-tetrahydroxylflavanone (eriodictyol) and 3,4'-dihydroxy flavone (3,4'-DHF) had a positive effect on cell proliferation of human HaCaT keratinocytes. Treatment with eriodictyol in particular resulted in significant suppression of cell death induced by ultraviolet (UV) light, a major skin-damaging agent. We found that eriodictyol treatment apparently reduced the percentage of apoptotic cells and the cleavage of poly(ADP-ribose) polymerase, concomitant with the repression of caspase-3 activation and reactive oxygen species (ROS) generation. The anti-apoptotic and anti-oxidant effects of eriodictyol were also confirmed in UV-induced cell death of normal human epidermal keratinocyte (NHEK) cells. Taken together, these findings suggest that eriodictyol can be used to protect keratinocytes from UV-induced damage, implying the presence of a complex structure-activity relationship (SAR) in the differential apoptosis-modulating activities of various flavonoids.
def external_recognition(): logger.warning('Recognizing intent using wit.ai') audio = record_audio()
Publishing is a competitive business. Can you recall a writing conference that did not include overcrowded sessions on how to pitch an editor? Neither can I.​ As Stephen King once said... "Talent is cheaper than table salt. What separates the talented individual from the successful one is a lot of hard work." While conference speakers expound on the editor as "champion for your book," they pay scant attention to an editor's process of reading a manuscript. Granted, every editor is different; but, every editor is also responsible for turning a profit on the books they acquire for publication. Successful editors have a process for reading manuscripts with business acumen and efficiency. A major part of the "hard work" King refers to means that you, the writer, must broaden your reading skills in order to think like an editor who acquires manuscripts. In this post, I share my 15-years of experience reading and buying nonfiction books for publishers such as HarperCollins, Van Nostrand Reinhold, Routledge, and McGraw-Hill International. Reading Like a Publisher Secret #1: The writer's voice is obvious in a 90-second cold read​. I love an amazing first sentence as much as the next editor. However, I like to pick a manuscript page at random in order to start reading wherever my eye lands on the text. I do this because I know you've been trained at workshops to make the first page sing like an opera star. But can you sustain your voice throughout the manuscript? That is the question I turnover in my mind while I read on. Secret #2: From reading the manuscript, what other medium could showcase the writer's voice and story? ​In my General Interest Books (trade publishing) course at Pace University, I required the graduate students to read Another Life: A Memoir of Other People by Michael Korda, now retired editor-in-chief at Simon & Schuster. These students represent the future of publishing. One day soon, these new editors will evaluate your manuscripts. When I opened our class discussion by asking about their first impressions of Korda's book, the first student said, "it would be a great book if it had pictures." The rest of the class agreed. This soon-to-be editor knows by instinct that the future of storytelling is visual. And, a good agent knows that the greatest earning potential comes from the myriad of licensing opportunities in multiple mediums for your work. The more licenses sold, the more opportunities for the publisher to sell books. Today's editor reads manuscripts while thinking about tomorrow's new revenue sources. Secret #3: The market for this manuscript is .... A book's category must be clear to the editor, the marketing and sales teams, and, most important, to readers. Editors understand the market dynamics in their list category, including the nuanced differences among authors. While reading a manuscript, even now as a consultant, I jot notes while making comparisons based on the subject, the market, your brand, platform, and how your book compares and contrasts to other titles. To learn more about specific categories, I recommend that you review the BISC codes. Published by the Book Industry Study Group, these codes are used by publishers and booksellers to place your title in the appropriate category on the bookshelf and to appear in reader search queries on Amazon. Like the editor, your job is to be confident where your book fits in its category. Secret​ #4: What is different in this manuscript and what makes this difference significant? Here's where your title and subtitle are critical. The main title represents the book's promise to the reader. The subtitle explains how you deliver the promise to the reader. In marketing parlance, this is your value proposition. To illustrate this point, here are three nonfiction books I'm in the process of reading. 1. ​Silence and Beauty: Hidden Faith Born of Suffering by Makoto Fujimura. The main title marries two evocative concepts: silence and beauty. The subtitle sends me off on a challenging journey. Suffering is a necessary catalyst in order for me to uncover, feel, accept, and transform my personal understanding of faith. 2. Blockchain Revolution: How the Technology Behind Bitcoin Is Changing Money, Business, and the World by Don Tapscott and Alex Tapscott. Revolution is a powerful word. What kind of revolution am I going to learn about? The Blockchain Revolution. What do these authors promise to explain to me? They are going to show me why they believe the technology behind Bitcoin is going to transform how people conduct all business and social financial transactions. 3. Scratch: Writers, Money, and the Art of Making a Living by Manjula Martin​. Love it! The main title is slang for money. The subtitle explains who needs the money (writers) and what writers want most (after readers, of course) to make a living from their writing. Hallelujah. Secret #5: How has the manuscript changed and/or deepened my perspective? It is often said that Joseph Campbell, the preeminent American mythologist and author of Hero with a Thousand Faces, stood on the shoulders of C.G. Jung, father of analytical psychology and author of The Undiscovered Self: The Dilemma of the Individual in Modern Society (a must read now more than ever!). In other words, no writer is an island. We all stand on the shoulders of our teachers, mentors, and the people who inspire us to pursue our passions and to share them. I believe this question of how the proposed manuscript is advancing ideas and conversations is a critical factor for an editor to consider when making a publishing decision. Every editor wants to believe that his or her publishing decision contributes to making the lives of people better. Another way to think of this secret is: why does the world need your book? Secret #6: I would recommend this book to ....​ This is the best part. After I've read the book proposal, sample chapters and/or the manuscript, I make a list of 10 people that I believe will like the book too. Within a publishing context, I consider booksellers, bloggers, reviewers, the sales reps, other authors, friends. Who would enjoy and/or benefit from the book? Enthusiasm is contagious. Publishing is a networking business. If 10 people do not flow easily from my pen in a stream of consciousness, ​I know I have an interesting book, but not necessarily a marketable one. This why I pass on interesting books. The standard is interesting + marketable. Read On and Rock On So, we know you are talented. Now, you have a process for doing the hard work. With this knowledge, you will be able to put yourself in the editor's shoes while reading your manuscript. Raise your game and compete to win in the publishing arena. ​
// Mark the actual stack data. // This is used both for `StackData` and `StackDataLarge`. uintptr_t mark_stack_data(jl_ptls_t ptls, jl_value_t *p) { dynstack_t *stk = (dynstack_t *)p; if (gc_counter_full & 1) { jl_gc_mark_queue_objarray(ptls, p, stk->data, stk->size); return 0; } else { uintptr_t n = 0; for (size_t i = 0; i < stk->size; i++) { if (jl_gc_mark_queue_obj(ptls, stk->data[i])) n++; } return n; } }
//go:generate ../../../tools/readme_config_includer/generator package disque import ( "bufio" _ "embed" "errors" "fmt" "net" "net/url" "strconv" "strings" "sync" "time" "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/plugins/inputs" ) //go:embed sample.conf var sampleConfig string type Disque struct { Servers []string c net.Conn } var defaultTimeout = 5 * time.Second var Tracking = map[string]string{ "uptime_in_seconds": "uptime", "connected_clients": "clients", "blocked_clients": "blocked_clients", "used_memory": "used_memory", "used_memory_rss": "used_memory_rss", "used_memory_peak": "used_memory_peak", "total_connections_received": "total_connections_received", "total_commands_processed": "total_commands_processed", "instantaneous_ops_per_sec": "instantaneous_ops_per_sec", "latest_fork_usec": "latest_fork_usec", "mem_fragmentation_ratio": "mem_fragmentation_ratio", "used_cpu_sys": "used_cpu_sys", "used_cpu_user": "used_cpu_user", "used_cpu_sys_children": "used_cpu_sys_children", "used_cpu_user_children": "used_cpu_user_children", "registered_jobs": "registered_jobs", "registered_queues": "registered_queues", } var ErrProtocolError = errors.New("disque protocol error") func (*Disque) SampleConfig() string { return sampleConfig } // Reads stats from all configured servers accumulates stats. // Returns one of the errors encountered while gather stats (if any). func (d *Disque) Gather(acc telegraf.Accumulator) error { if len(d.Servers) == 0 { address := &url.URL{ Host: ":7711", } return d.gatherServer(address, acc) } var wg sync.WaitGroup for _, serv := range d.Servers { u, err := url.Parse(serv) if err != nil { acc.AddError(fmt.Errorf("unable to parse to address %q: %w", serv, err)) continue } else if u.Scheme == "" { // fallback to simple string based address (i.e. "10.0.0.1:10000") u.Scheme = "tcp" u.Host = serv u.Path = "" } wg.Add(1) go func() { defer wg.Done() acc.AddError(d.gatherServer(u, acc)) }() } wg.Wait() return nil } const defaultPort = "7711" func (d *Disque) gatherServer(addr *url.URL, acc telegraf.Accumulator) error { if d.c == nil { _, _, err := net.SplitHostPort(addr.Host) if err != nil { addr.Host = addr.Host + ":" + defaultPort } c, err := net.DialTimeout("tcp", addr.Host, defaultTimeout) if err != nil { return fmt.Errorf("unable to connect to disque server %q: %w", addr.Host, err) } if addr.User != nil { pwd, set := addr.User.Password() if set && pwd != "" { if _, err := c.Write([]byte(fmt.Sprintf("AUTH %s\r\n", pwd))); err != nil { return err } r := bufio.NewReader(c) line, err := r.ReadString('\n') if err != nil { return err } if line[0] != '+' { return errors.New(strings.TrimSpace(line)[1:]) } } } d.c = c } // Extend connection if err := d.c.SetDeadline(time.Now().Add(defaultTimeout)); err != nil { return err } if _, err := d.c.Write([]byte("info\r\n")); err != nil { return err } r := bufio.NewReader(d.c) line, err := r.ReadString('\n') if err != nil { return err } if line[0] != '$' { return fmt.Errorf("bad line start: %w", ErrProtocolError) } line = strings.TrimSpace(line) szStr := line[1:] sz, err := strconv.Atoi(szStr) if err != nil { return fmt.Errorf("bad size string <<%s>>: %w", szStr, ErrProtocolError) } var read int fields := make(map[string]interface{}) tags := map[string]string{"disque_host": addr.String()} for read < sz { line, err := r.ReadString('\n') if err != nil { return err } read += len(line) if len(line) == 1 || line[0] == '#' { continue } parts := strings.SplitN(line, ":", 2) name := parts[0] metric, ok := Tracking[name] if !ok { continue } val := strings.TrimSpace(parts[1]) ival, err := strconv.ParseUint(val, 10, 64) if err == nil { fields[metric] = ival continue } fval, err := strconv.ParseFloat(val, 64) if err != nil { return err } fields[metric] = fval } acc.AddFields("disque", fields, tags) return nil } func init() { inputs.Add("disque", func() telegraf.Input { return &Disque{} }) }
package validator import ( "fmt" "reflect" "github.com/odoku/validator/ast" "github.com/odoku/validator/lexer" "github.com/odoku/validator/parser" ) type ( Rules map[string]Functions ) func createRulesFromStruct(s interface{}) (Rules, error) { v := getSubstance(s) if v.Kind() != reflect.Struct { return nil, fmt.Errorf("%T Is not struct value.", s) } rules := Rules{} for i := 0; i < v.NumField(); i++ { t := v.Type().Field(i) tag := t.Tag.Get("valid") if tag == "" { continue } field := t.Tag.Get("form") if field == "" { field = t.Name } p := parser.NewParser() s := lexer.NewLexer([]byte(tag)) result, err := p.Parse(s) if err != nil { return nil, fmt.Errorf("Could not parse %s field tag: %v", field, err) } functions := result.([]ast.Function) vfs := make(Functions, len(functions)) for i, function := range functions { f, err := GetFunc(function.Name) if err != nil { return nil, err } vfs[i] = &Function{Func: f, Args: function.Args} } rules[field] = vfs } return rules, nil } func getSubstance(s interface{}) reflect.Value { v := reflect.ValueOf(s) if v.Kind() == reflect.Interface || v.Kind() == reflect.Ptr { v = v.Elem() } return v }
package io.dotanuki.fixtures; public class Starter { public static void main(String[] args) throws InterruptedException { Thread.sleep(Long.valueOf(args[0])); System.out.println("Done"); } }
//------------------------------------------------------------------------------ // Application Run Function contains the Main Loop void WinPCPlatformApplication::Run(IGameLaunchOption *gameLaunchOption) { std::shared_ptr<IGame> game = CreateGame(this, gameLaunchOption); game->Prepare(); game->GraphicPrepare(); while (game->IsRunning() && m_isRunning) { bool isFrameProcessed = game->UpdateFrame(); if (isFrameProcessed) { m_glView->SwapBuffers(); } Sleep(0); } game->GraphicShutdown(); game->Shutdown(); }
#pragma once #include "MacroSet.h" #include "Interface3D.h" #include "EnumSet.h" class MouseRender : public Interface3D { public: MouseRender(); ~MouseRender(); public: void Init(); virtual void Update(); virtual void Render() const; void SetGameCursorPos( int PosX, int PosY ); private: bool m_IsCursorReady = false; int m_CursorHotspotX = 4; int m_CursorHotspotY = 3; };
<reponame>renaudll/omtk<gh_stars>10-100 import pymel.core as pymel from maya import OpenMaya from maya import cmds from omtk.libs import libRigging def create_shape_circle(size=1.0, normal=(1, 0, 0), *args, **kwargs): transform, make = pymel.circle(*args, **kwargs) make.radius.set(size) make.normal.set(normal) # Expose the rotateOrder transform.rotateOrder.setKeyable(True) make.radius.set(size) make.degree.set(1) make.sections.set(8) return transform, make def create_shape_needle(size=1, length=None, radius=None, name=None, normal=(0, 1, 0), *args, **kwargs): # TODO: docstring # Resolve length # Default length is 4x the provided size if length is None: length = size * 1.0 # Resolve radius if radius is None: radius = size * 0.25 radius_mid = radius * 0.75 y_circle_mid_max = length + radius_mid y_circle_mid_min = length - radius_mid y_circle_min = length - radius y_circle_max = length + radius xz_circle_rad = radius xz_circle_mid_rad = xz_circle_rad * 0.75 shape1 = pymel.curve(d=1, p=[ (0.0, 0.0, 0.0), (0.0, y_circle_min, 0.0) ]) shape2 = pymel.curve(d=1, p=[ (0.0, y_circle_max, -0.0), (0.0, y_circle_max, 0.0), (xz_circle_mid_rad, y_circle_mid_max, 0.0), (xz_circle_rad, length, 0.0), (xz_circle_mid_rad, y_circle_mid_min, 0.0), (0.0, y_circle_min, 0), (-xz_circle_mid_rad, y_circle_mid_min, -0.0), (-xz_circle_rad, length, 0.0), (-xz_circle_mid_rad, y_circle_mid_max, 0.0), (0.0, y_circle_max, 0.0), (xz_circle_mid_rad, y_circle_mid_max, 0.0) ]) shape3 = pymel.curve(d=1, p=[ (-xz_circle_mid_rad, length, -xz_circle_mid_rad), (-xz_circle_rad, length, 0.0), (-xz_circle_mid_rad, length, xz_circle_mid_rad), (0.0, length, xz_circle_rad), (xz_circle_mid_rad, length, xz_circle_mid_rad), (xz_circle_rad, length, 0.0), (xz_circle_mid_rad, length, -xz_circle_mid_rad), (0.0, length, -xz_circle_rad), (-xz_circle_mid_rad, length, -xz_circle_mid_rad), (-xz_circle_rad, length, 0.0), (-xz_circle_rad, length, 0.0) ]) shape2.getShape().setParent(shape1, shape=True, relative=True) shape3.getShape().setParent(shape1, shape=True, relative=True) pymel.delete(shape2) pymel.delete(shape3) # Apply normal parameter # TODO: Find a better way need_identity = True normal_x, normal_y, normal_z = normal if normal_x: if normal_x < 0: shape1.rotateZ.set(90) else: shape1.rotateZ.set(-90) elif normal_y: if normal_y < 0: shape1.rotateX.set(180) else: need_identity = False elif normal_z: if normal_z < 0: shape1.rotateX.set(-90) else: shape1.rotateX.set(90) if need_identity: pymel.makeIdentity(shape1, apply=True, rotate=True) if name: shape1.rename(name) # Expose the rotateOrder shape1.rotateOrder.setKeyable(True) return shape1 def create_shape_double_needle(normal=(0, 1, 0), *args, **kwargs): normal_inv = (normal[0] * -1, normal[1] * -1, normal[2] * -1) # TODO: find an eleguant way shape1 = create_shape_needle(normal=normal, *args, **kwargs) shape2 = create_shape_needle(normal=normal_inv, *args, **kwargs) for shape in shape2.getShapes(): shape.setParent(shape1, shape=True, relative=True) pymel.delete(shape2) # Expose the rotateOrder shape1.rotateOrder.setKeyable(True) return shape1 def create_shape_cross(size=1.0, **kwargs): s1 = size * 0.5 s2 = size node = pymel.curve(d=1, p=[ (0,-s1,s1), (0,-s1,s2), (0,s1,s2), (0,s1,s1), (0,s2,s1), (0,s2,-s1), (0,s1,-s1), (0,s1,-s2), (0,-s1,-s2), (0,-s1,-s1), (0,-s2,-s1), (0,-s2,s1), (0,-s1,s1) ], **kwargs) # Expose the rotateOrder node.rotateOrder.setKeyable(True) return node def create_shape_attrholder(size=1.0, **kwargs): s1 = size s2 = s1 * 0.7 node = pymel.curve(d=1, p=[(0,0,s1),(0,s2,s2),(0,s1,0),(0,s2,-s2),(0,0,-s1),(0,-s2,-s2),(0,-s1,0),(0,-s2,s2),(0,0,s1),(-s2,0,s2),(-s1,0,0),(-s2,s2,0),(0,s1,0),(s2,s2,0),(s1,0,0),(s2,0,-s2),(0,0,-s1),(-s2,0,-s2),(-s1,0,0),(-s2,-s2,0),(0,-s1,0),(s2,-s2,0),(s1,0,0),(s2,0,s2),(0,0,s1),(-s2,0,s2)], k=range(26), *kwargs) # Expose the rotateOrder node.rotateOrder.setKeyable(True) return node def create_shape_box(size=1.0, r=None, h=None): if r is None: r = size if h is None: h = size / 5.0 node = pymel.curve(d=1, p=[(-r, -h, r), (-r, h, r), (r, h, r), (r, -h, r), (-r, -h, r), (-r, -h, -r), (-r, h, -r), (-r, h, r), (r, h, r), (r, h, -r), (r, -h, -r), (r, -h, r), (r, -h, -r), (-r, -h, -r), (-r, h, -r), (r, h, -r)] ) # Expose the rotateOrder node.rotateOrder.setKeyable(True) return node def _get_bounds_using_raycast(positions, dirs, geometries, parent_tm=None, filter=None): min_x = max_x = min_y = max_y = min_z = max_z = None parent_tm_inv = parent_tm.inverse() # Ray-cast for pos in positions: #x = pos.x #y = pos.y #z = pos.z # Expand bounds using starting positions. pos_local = pymel.datatypes.Point(pos) * parent_tm_inv if parent_tm is not None else pos x_local = pos_local.x y_local = pos_local.y z_local = pos_local.z if min_x is None or x_local < min_x: min_x = x_local if max_x is None or x_local > max_x: max_x = x_local if min_y is None or y_local < min_y: min_y = y_local if max_y is None or y_local > max_y: max_y = y_local if min_z is None or z_local < min_z: min_z = z_local if max_z is None or z_local > max_z: max_z = z_local for dir in dirs: ray_cast_pos = libRigging.ray_cast_nearest(pos, dir, geometries, debug=False) if ray_cast_pos is None: continue if parent_tm is not None: ray_cast_pos = ray_cast_pos * parent_tm_inv x = ray_cast_pos.x y = ray_cast_pos.y z = ray_cast_pos.z if min_x is None or x < min_x: min_x = x if max_x is None or x > max_x: max_x = x if min_y is None or y < min_y: min_y = y if max_y is None or y > max_y: max_y = y if min_z is None or z < min_z: min_z = z if max_z is None or z > max_z: max_z = z return min_x, max_x, min_y, max_y, min_z, max_z def create_shape_box_arm(refs, geometries, epsilon=0.01, default_size=1.0): # TODO: Prevent crashes when there's no geometries ref = next(iter(refs)) ref_tm = ref.getMatrix(worldSpace=True) positions = [r.getTranslation(space='world') for r in refs] # Resolve raycast directions dir_offset_tm = pymel.datatypes.Matrix( # Remove translation from ref_tm to keep direction normalized. ref_tm.a00, ref_tm.a01, ref_tm.a02, ref_tm.a03, ref_tm.a10, ref_tm.a11, ref_tm.a12, ref_tm.a13, ref_tm.a20, ref_tm.a21, ref_tm.a22, ref_tm.a23, 0, 0, 0, 1 ) x_pos = ref.getTranslation(space='world').x dirs = [ OpenMaya.MPoint(0,-1,0) * dir_offset_tm, OpenMaya.MPoint(0,1,0) * dir_offset_tm, OpenMaya.MPoint(0,0,-1) * dir_offset_tm, OpenMaya.MPoint(0,0,1) * dir_offset_tm ] # HACK : Check the x_position to know in which direction we need to do the raycast if x_pos >= 0.0: dirs.append( OpenMaya.MPoint(1,0,0) * dir_offset_tm, ) else: dirs.append( OpenMaya.MPoint(-1,0,0) * dir_offset_tm, ) min_x, max_x, min_y, max_y, min_z, max_z = _get_bounds_using_raycast(positions, dirs, geometries, parent_tm=ref_tm) # Ensure a minimum size for the ctrl if (max_x - min_x) < epsilon: max_x = default_size if (max_y - min_y) < epsilon: min_y = -default_size * 0.5 max_y = default_size * 0.5 if (max_z - min_z) < epsilon: min_z = -default_size * 0.5 max_z = default_size * 0.5 # Convert our bouding box #min_x = 0 pos1 = pymel.datatypes.Point(min_x, min_y, min_z) pos2 = pymel.datatypes.Point(min_x, min_y, max_z) pos3 = pymel.datatypes.Point(min_x, max_y, min_z) pos4 = pymel.datatypes.Point(min_x, max_y, max_z) pos5 = pymel.datatypes.Point(max_x, min_y, min_z) pos6 = pymel.datatypes.Point(max_x, min_y, max_z) pos7 = pymel.datatypes.Point(max_x, max_y, min_z) pos8 = pymel.datatypes.Point(max_x, max_y, max_z) node = pymel.curve(d=1, p=[pos2, pos4, pos8, pos6, pos2, pos1, pos3, pos4, pos8, pos7, pos5, pos6, pos5, pos1, pos3, pos7] ) # Expose the rotateOrder node.rotateOrder.setKeyable(True) return node def create_shape_box_feet(refs, geometries, *args, **kwargs): ref = next(iter(refs)) ref_pos = ref.getTranslation(space='world') ref_tm = pymel.datatypes.Matrix( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ref_pos.x, ref_pos.y, ref_pos.z, 1 ) positions = [ref.getTranslation(space='world') for ref in refs] dirs = [ OpenMaya.MVector(-1,0,0), OpenMaya.MVector(1,0,0), OpenMaya.MVector(0,0,-1), OpenMaya.MVector(0,0,1) ] # Sanity check, ensure that at least one point is in the bounds of geometries. # This can prevent rays from being fired from outside a geometry. # TODO: Make it more robust. filtered_geometries = [] for geometry in geometries: xmin, ymin, zmin, xmax, ymax, zmax = cmds.exactWorldBoundingBox(geometry.__melobject__()) bound = pymel.datatypes.BoundingBox((xmin, ymin, zmin), (xmax, ymax, zmax)) if any(True for pos in positions if bound.contains(pos)): filtered_geometries.append(geometry) # Using all provided objects min_x, max_x, min_y, max_y, min_z, max_z = _get_bounds_using_raycast(positions, dirs, filtered_geometries, parent_tm=ref_tm) min_y = min(min_y, - ref_pos.y) # If no geometry was provided, there won't be any width in the returned values. if not geometries: length = max_z - min_z desired_width = length * 0.25 min_x = -desired_width max_x = desired_width pos1 = pymel.datatypes.Point(min_x, min_y, min_z) pos2 = pymel.datatypes.Point(min_x, min_y, max_z) pos3 = pymel.datatypes.Point(min_x, max_y, min_z) pos4 = pymel.datatypes.Point(min_x, max_y, max_z) pos5 = pymel.datatypes.Point(max_x, min_y, min_z) pos6 = pymel.datatypes.Point(max_x, min_y, max_z) pos7 = pymel.datatypes.Point(max_x, max_y, min_z) pos8 = pymel.datatypes.Point(max_x, max_y, max_z) # HACK: Convert to local space... ''' ref = next(iter(refs)) pos = ref.getTranslation(space='world') pos1 -= pos pos2 -= pos pos3 -= pos pos4 -= pos pos5 -= pos pos6 -= pos pos7 -= pos pos8 -= pos ''' node = pymel.curve(d=1, p=[pos2, pos4, pos8, pos6, pos2, pos1, pos3, pos4, pos8, pos7, pos5, pos6, pos5, pos1, pos3, pos7] ) # Expose the rotateOrder node.rotateOrder.setKeyable(True) return node def create_square(size=1.0, width=None, height=None, **kwargs): if width is None: width = 1.0 if height is None: height = 1.0 width *= size height *= size pos1 = pymel.datatypes.Point(-height, -width, 0) pos2 = pymel.datatypes.Point(-height, width, 0) pos3 = pymel.datatypes.Point(height, width, 0) pos4 = pymel.datatypes.Point(height, -width, 0) pos5 = pymel.datatypes.Point(-height, -width, 0) node = pymel.curve(d=1, p=[pos1, pos2, pos3, pos4, pos5] ) # Expose the rotateOrder node.rotateOrder.setKeyable(True) return node def create_triangle_upp(): p1 = [0, 0.577, 0] p2 = [-0.5, -0.288, 0] p3 = [0.5, -0.288, 0] node = pymel.curve(d=1, p=[p1, p2, p3, p1] ) # Expose the rotateOrder node.rotateOrder.setKeyable(True) return node def create_triangle_low(): p1 = [0, -0.577, 0] p2 = [-0.5, 0.288, 0] p3 = [0.5, 0.288, 0] node = pymel.curve(d=1, p=[p1, p2, p3, p1] ) # Expose the rotateOrder node.rotateOrder.setKeyable(True) return node def create_triangle_left(): p1 = [0.577, 0, 0] p2 = [-0.288, -0.5, 0] p3 = [-0.288, 0.5, 0] node = pymel.curve(d=1, p=[p1, p2, p3, p1] ) # Expose the rotateOrder node.rotateOrder.setKeyable(True) return node def create_triangle_right(): p1 = [-0.577, 0, 0] p2 = [0.288, -0.5, 0] p3 = [0.288, 0.5, 0] node = pymel.curve(d=1, p=[p1, p2, p3, p1] ) # Expose the rotateOrder node.rotateOrder.setKeyable(True) return node
<gh_stars>100-1000 /** @file Time Zone processing, declarations and macros. Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License that accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license. THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. Derived from the NIH time zone package file, tzfile.h, which contains the following notice: This file is in the public domain, so clarified as of 1996-06-05 by <NAME> (<EMAIL>). This header is for use ONLY with the time conversion code. There is no guarantee that it will remain unchanged, or that it will remain at all. Do NOT copy it to any system include directory. Thank you! NetBSD: tzfile.h,v 1.8 1998/01/22 07:06:59 jtc Exp **/ #ifndef TZFILE_H #define TZFILE_H /* ** Information about time zone files. */ #ifndef TZDIR /* Time zone object file directory */ #define TZDIR "/usr/share/zoneinfo" #endif /* !defined TZDIR */ #ifndef TZDEFAULT #define TZDEFAULT "/etc/localtime" #endif /* !defined TZDEFAULT */ #ifndef TZDEFRULES #define TZDEFRULES "posixrules" #endif /* !defined TZDEFRULES */ /* ** Each file begins with. . . */ #define TZ_MAGIC "TZif" struct tzhead { char tzh_magic[4]; /* TZ_MAGIC */ char tzh_reserved[16]; /* reserved for future use */ char tzh_ttisgmtcnt[4]; /* coded number of trans. time flags */ char tzh_ttisstdcnt[4]; /* coded number of trans. time flags */ char tzh_leapcnt[4]; /* coded number of leap seconds */ char tzh_timecnt[4]; /* coded number of transition times */ char tzh_typecnt[4]; /* coded number of local time types */ char tzh_charcnt[4]; /* coded number of abbr. chars */ }; /* ** . . .followed by. . . ** ** tzh_timecnt (char [4])s coded transition times a la time(2) ** tzh_timecnt (unsigned char)s types of local time starting at above ** tzh_typecnt repetitions of ** one (char [4]) coded UTC offset in seconds ** one (unsigned char) used to set tm_isdst ** one (unsigned char) that's an abbreviation list index ** tzh_charcnt (char)s '\0'-terminated zone abbreviations ** tzh_leapcnt repetitions of ** one (char [4]) coded leap second transition times ** one (char [4]) total correction after above ** tzh_ttisstdcnt (char)s indexed by type; if TRUE, transition ** time is standard time, if FALSE, ** transition time is wall clock time ** if absent, transition times are ** assumed to be wall clock time ** tzh_ttisgmtcnt (char)s indexed by type; if TRUE, transition ** time is UTC, if FALSE, ** transition time is local time ** if absent, transition times are ** assumed to be local time */ /* ** In the current implementation, "tzset()" refuses to deal with files that ** exceed any of the limits below. */ #ifndef TZ_MAX_TIMES /* ** The TZ_MAX_TIMES value below is enough to handle a bit more than a ** year's worth of solar time (corrected daily to the nearest second) or ** 138 years of Pacific Presidential Election time ** (where there are three time zone transitions every fourth year). */ #define TZ_MAX_TIMES 370 #endif /* !defined TZ_MAX_TIMES */ #ifndef TZ_MAX_TYPES #ifndef NOSOLAR #define TZ_MAX_TYPES 256 /* Limited by what (unsigned char)'s can hold */ #endif /* !defined NOSOLAR */ #ifdef NOSOLAR /* ** Must be at least 14 for Europe/Riga as of Jan 12 1995, ** as noted by <NAME> <<EMAIL>>. */ #define TZ_MAX_TYPES 20 /* Maximum number of local time types */ #endif /* !defined NOSOLAR */ #endif /* !defined TZ_MAX_TYPES */ #ifndef TZ_MAX_CHARS #define TZ_MAX_CHARS 50 /* Maximum number of abbreviation characters */ /* (limited by what unsigned chars can hold) */ #endif /* !defined TZ_MAX_CHARS */ #ifndef TZ_MAX_LEAPS #define TZ_MAX_LEAPS 50 /* Maximum number of leap second corrections */ #endif /* !defined TZ_MAX_LEAPS */ #define SECSPERMIN 60 #define MINSPERHOUR 60 #define HOURSPERDAY 24 #define DAYSPERWEEK 7 #define DAYSPERNYEAR 365 #define DAYSPERLYEAR 366 #define SECSPERHOUR (SECSPERMIN * MINSPERHOUR) #define SECSPERDAY ((LONG32)(SECSPERHOUR * HOURSPERDAY)) #define MONSPERYEAR 12 #define EPOCH_YEAR 1970 #define EPOCH_WDAY TM_THURSDAY // Use this for 32-bit time_t //#define EPOCH_WDAY TM_SUNDAY // Use this for 64-bit time_t /* ** Accurate only for the past couple of centuries; ** that will probably do. */ #define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0)) #endif /* !defined TZFILE_H */
/* Called after each test method. */ void testTearDown() { MQTTStatus_t mqttStatus; TransportSocketStatus_t transportStatus; mqttStatus = MQTT_Disconnect( &context ); transportStatus = SecureSocketsTransport_Disconnect( &networkContext ); TEST_ASSERT_EQUAL( MQTTSuccess, mqttStatus ); TEST_ASSERT_EQUAL( TRANSPORT_SOCKET_STATUS_SUCCESS, transportStatus ); }
<reponame>GuyLivni/da-design-system<gh_stars>0 import * as React from 'react'; import { render } from '../../util/testUtils'; import { Button } from './Button'; describe('Button', () => { it('should render the button', () => { const text = 'Heyo'; const { getByRole } = render(<Button>{text}</Button>); expect(getByRole('button')).toHaveTextContent(text); expect(getByRole('button')).toBeInTheDocument(); }); });
After David’s post, I got a few mails asking whether this change has anything to do with the project I started last summer, so I decided to provide a small update. My original plan was to ship a test version of Blade a few months after the project announcement, but that did not happen. The main reason was that there were some higher-priority things in Plasma I needed to work on, so I had to put this on hold a bit. While the project is not yet made public, some important things have happened that moved it forward quite a bit. First, a teaser Before I start, a fancy screenshot is in order. The main UI is as dull as it was, but there is another UI: If you are not sure what this is, this is not a fancy new Plasma theme. This is a screenshot from a phone (more precisely, a phone version of Sailfish OS in a virtual machine) connected and set to search applications on my main system. The design I have significantly simplified the design because the original one induced some communication overhead to allow any two nodes in the system to communicate with each other (regardless whether they are on the same system or not). This was a cool feature, but I’ve realized that it is not needed here, and that it is not needed in most programs that I’d use a similar message-passing mechanism in. The messages now have a strict flow and each node can send messages only to its designated listener(s). The beast below I’ve also replaced the serialization mechanism which used the Qt data stream proocol with the ProtoBuf library, and the Qt networking has been replaced by ZeroMQ (yes, I’ve changed my mind). One great thing about these libraries (and one of the reasons I decided to replace the old stack with them) is that they have fully-functional bindings for any programming language imaginable – from Python and Java, to languages like Haskell, Erlang and Elixir. This means that it will be possible to write any of the components in any language you want. If you want to use Python’s great numeric libraries to implement the calculator runner, or if you want to implement a Web UI in Haskell, you will be able to. No need to be limited only to languages that support Qt. The future I don’t have any plans to propose replacing KRunner’s current implementation with this anytime soon. As David mentioned in his post, this would be problematic because this is a reimplementation with a completely different API and everything. The first milestone will be to create an alternative to KRunner that will have enough cool features for people to start using it instead of KRunner. This is the same approach I took a long time ago with Lancelot. Be a conscious choice instead of being the default.
// authenticate is used to handle connection authentication func (sf *Server) authenticate(conn io.Writer, bufConn io.Reader, userAddr string, methods []byte) (*AuthContext, error) { for _, auth := range sf.authMethods { for _, method := range methods { if auth.GetCode() == method { return auth.Authenticate(bufConn, conn, userAddr) } } } conn.Write([]byte{statute.VersionSocks5, statute.MethodNoAcceptable}) return nil, statute.ErrNoSupportedAuth }
Vacuums – also handy underwater (Image: Brett Seymour/ARGO/EUA) GEMMA SMITH is grinning like a child on Christmas morning. “It could be anything!” she says as our boat speeds past the rugged grey cliffs of Antikythera, a tiny Greek island midway between the Peloponnese and Crete. We are here to explore one of the world’s most famous shipwrecks, where divers once found an ancient computer. The day before, the team discovered part of a large object buried beneath a metre of sand; now they are back to find out what it is. After years of preparation, there’s a feeling that today is going to be big. Advertisement The ship that sank here was a hefty wooden vessel, sailing west from Asia Minor towards Rome when it smashed against the island’s cliffs in the 1st century BC. It was discovered in 1900 by sponge divers, who salvaged the site under the direction of Greek archaeologists: the first scientific investigation of a shipwreck. They found bronze and marble statues, gold jewellery, ornate furniture, and gorgeous ceramics and glassware. Most intriguing was an ancient geared device – the Antikythera mechanism. Now understood to have been a clockwork computer, it was used to predict and display the movements of the sun, moon and planets in the sky (see “The solar system in a box“). “It is a symbolic place,” says Theotokis Theodoulou, an archaeologist at Greece’s Ephorate of Underwater Antiquities. “This is the cradle of underwater archaeology.” In 1976, a scuba team led by marine explorer Jacques Cousteau excavated a small area of the site and brought up hundreds of small items including jewellery, statuettes and coins, suggesting that much of the ship’s cargo still lies buried under the sand. Now, an international team has come to finish the job. They hope to uncover more exquisite statues, or even other examples of advanced technology. It is possible that the ship contained several geared devices, particularly if it was carrying a commercial consignment rather than stolen loot, speculates Michael Wright, a London-based mechanic and curator. “I live in hope!” he says. “It is possible that the ship contained several geared devices like the Antikythera mechanism” The project is led by Theodoulou, his colleague Dimitris Kourkoumelis at the Ephorate of Underwater Antiquities and Brendan Foley, an archaeologist at Woods Hole Oceanographic Institution in Massachusetts. The $1.8 million scheme, funded largely by private and corporate sponsors, is one of biggest underwater archaeology efforts in world, and dwarfs those carried out before in Greece. There are two main challenges. Few archaeologists are qualified to dive to the site’s 55 metres, where the risk of the bends is severe. So to avoid injury, they descend with dive specialists including Smith, and only dive for 45 minutes at a time, taking 90 minutes to decompress. Another problem is finding items hidden in the sand. Cousteau’s 1976 team used a huge suction pipe to hoover up the seabed, dumping sediment and precious artefacts onto the deck of their ship. But the priority now is to record and understand the site, not simply to salvage its treasure. So in June, Foley and a team from the University of Sydney in Australia used stereoscopic cameras and sonar mounted on an underwater drone to make a 3D map of the site (see diagram). Reconstruction site Then, at the end of August, the dive team arrived on this windswept island. Its members surveyed the site with handheld metal detectors, investigating hits by fanning water with their hands to dig shallow trenches, and sucking away the raised sediment with a small dredge. They marked any finds directly onto the 3D map as they worked, using an iPad in a waterproof case. Above and below: The wreck that keeps on giving (Image: Brett Seymour/ARGO/EUA) While underwater, the researchers also took hundreds of photographs from different angles of artefacts and of an excavation trench. Software then crunched these into a 3D virtual reconstruction. Such software is changing the way underwater archaeology is done, says team member Brett Seymour, an underwater photographer for the US National Park Service. It allows researchers to map sites quickly and accurately instead of spending days with tape measures and drawing objects by hand. “This site is inherently remote and difficult to access,” adds Foley. “But through virtual reality and 3D modelling we can make it accessible for any archaeologist anywhere in the world.” The first couple of weeks of the diving expedition yielded a slow stream of finds including ship components such as roof tiles and lead hull sheeting as well as finer items: sections of a bone flute, a blue game pawn and a statuette base. “These are prestige goods,” says Foley, “not the sort of thing you normally find on a wreck.” Everyone was hoping for a headline-grabbing find, however, and on 8 September a shoebox-sized block of black metal, weighing nearly 30 kilograms, caused excitement. It was immediately dubbed the ship’s “black box”. But the metal turned out to be iron, probably a ballast weight dropped by Cousteau’s diving saucer. A couple of days later, diver Alexandros Sotiriou uncovered the square end of a large object buried deep in the sand. He was unable to move it, but believed he saw the green glint of semi-precious bronze. (Image: Brett Seymour/ARGO/EUA) Now, as the team reaches the wreck site to investigate Sotiriou’s find, the excitement is palpable. As the first two divers descend, their colleagues and I crowd round a small screen on the boat, which shows a live video feed of progress underwater. The divers wedge their scooter against a rock and use its propeller to create a water jet that pushes sand away. The pair disappear into a cloud of sediment, and later emerge with two long bars, each with a semicircular hole halfway down its length. The bars turn out to be lead, not bronze; the components of a large anchor. The team is quiet on the way back to harbour – this isn’t what the divers had hoped for. But it’s still a significant find, showing how deep the team must dig for larger items, and pinpointing the position of the ship’s bow. With the stern already located, Foley and Theodoulou calculate the vessel’s midpoint – a flat, featureless area dubbed “the meadow” – as the most likely place for its cargo. Video: Sunken treasures from famous wreck revealed in 3D The next day, Smith and Foley dig two 70-centimetre-deep trenches in the meadow. They surface jubilant. Within half an hour, they have uncovered several items, including a part of an amphora and an elegant wine jug. Smith’s pockets are filled with small bronze pieces – nails, and what might be parts of a cooking pot. “There’s obviously stuff down there,” she says. “We just weren’t digging deep enough before.” It’s the best dive of the project and Foley is convinced the team is about to reach the ship’s cargo. “That’s the way to go,” he says. “Now it’s just a matter of time.” But at this treacherous site, the project is at the mercy of the elements. The unrelenting north wind makes it too dangerous to dive again, and the divers pack for home, where they will collaborate with other teams to run tests on the recovered artefacts. Lead isotope analysis could reveal the ship’s geographic origin, and DNA analysis could shed light on the make-up of ancient products. But to discover if the wreck hides the treasures they dream of, perhaps even another ancient computer, they must wait for next year’s expedition. The solar system in a box From one of the most famous shipwrecks came the most unlikely of finds (see main story). In the 1st century BC, a ship sunk off the coast of the island of Antikythera. Among the treasures salvaged from it in a 1900-1901 expedition was a battered lump of bronze, which cracked open to reveal gearwheels, pointers and inscriptions in ancient Greek. Experts at the time were stumped, but decades of research, including X-ray analyses and CT scans, have revealed that the device was a clockwork computer, with more than 30 gearwheels that modelled the workings of the solar system. This gearing was originally inside a wooden box, about the size of a mantelpiece clock, with a handle that allowed the user to move forwards or backwards in time. Revolving pointers showed the movements of the sun, moon and planets, while a series of smaller dials displayed the timing of eclipses, and even the Olympic games. Nothing close to its complexity appears again in the historical record for well over 1000 years. The device recast our understanding of ancient technology, and indicated that geared mechanisms – which led to the invention of modern clocks and the automated machinery that drove the industrial revolution – began not in Medieval Europe, but more than 2000 years ago in Greece. This article appeared in print under the headline “Diving for pearls of Greek wisdom”
<reponame>cojoj/Codewars<gh_stars>0 module NameCombiner where combineNames :: String -> String -> String combineNames x y = x ++ " " ++ y
# Description: Checks that all EC2 instances are launched as Spot Instances for maximum cost savings # # Trigger Type: Change Triggered # Scope of Changes: EC2:Instance # Required Parameter: desiredLifecycle # Required Value: spot # # See https://aws.amazon.com/ec2/spot/ to learn more about EC2 Spot Instances import boto3 import json def is_applicable(config_item, event): status = config_item['configurationItemStatus'] event_left_scope = event['eventLeftScope'] test = ((status in ['OK', 'ResourceDiscovered']) and event_left_scope == False) return test def evaluate_compliance(config_item, rule_parameters): if (config_item['resourceType'] != 'AWS::EC2::Instance'): return 'NOT_APPLICABLE' elif (config_item['configuration']['instanceLifecycle'] == rule_parameters['desiredLifecycle']): return 'COMPLIANT' else: return 'NON_COMPLIANT' def lambda_handler(event, context): invoking_event = json.loads(event['invokingEvent']) rule_parameters = json.loads(event['ruleParameters']) compliance_value = 'NOT_APPLICABLE' if is_applicable(invoking_event['configurationItem'], event): compliance_value = evaluate_compliance( invoking_event['configurationItem'], rule_parameters) config = boto3.client('config') response = config.put_evaluations( Evaluations=[ { 'ComplianceResourceType': invoking_event['configurationItem']['resourceType'], 'ComplianceResourceId': invoking_event['configurationItem']['resourceId'], 'ComplianceType': compliance_value, 'OrderingTimestamp': invoking_event['configurationItem']['configurationItemCaptureTime'] }, ], ResultToken=event['resultToken'])
// MinPoint returns the smallest voxel coordinate of the given 3d chunk. func (c ChunkPoint3d) MinPoint(size Point) Point { return Point3d{ c[0] * size.Value(0), c[1] * size.Value(1), c[2] * size.Value(2), } }
// NEq returns true iff all given arguments are different. func NEq(args ...jsonutil.JSONToken) (jsonutil.JSONBool, error) { if len(args) < 2 { return true, nil } hashSet := stringset.NewSize(len(args)) for _, a := range args { h, err := Hash(a) if err != nil { return false, err } if !hashSet.Add(string(h)) { return false, nil } } return true, nil }
<gh_stars>1-10 package namespace import ( "context" "fmt" "time" "github.com/appuio/seiso/pkg/util" "github.com/karrick/tparse/v2" log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" core "k8s.io/client-go/kubernetes/typed/core/v1" ) const cleanAnnotation = "syn.tools/clean" var ( resources = []schema.GroupVersionResource{ {Version: "v1", Resource: "pods"}, {Group: "apps", Version: "v1", Resource: "statefulsets"}, {Group: "apps", Version: "v1", Resource: "deployments"}, {Group: "apps", Version: "v1", Resource: "daemonsets"}, {Group: "extensions", Version: "v1beta1", Resource: "daemonsets"}, {Group: "extensions", Version: "v1beta1", Resource: "deployments"}, } ) type ( NamespacesService struct { configuration ServiceConfiguration client core.NamespaceInterface dynamicClient dynamic.Interface checkers []Checker } ServiceConfiguration struct { Batch bool } Checker interface { NonEmptyNamespaces(context.Context, map[string]struct{}) error Name() string } ) // NewNamespacesService creates a new Service instance func NewNamespacesService(client core.NamespaceInterface, dynamicClient dynamic.Interface, configuration ServiceConfiguration) NamespacesService { return NamespacesService{ client: client, configuration: configuration, checkers: []Checker{NewHelmChecker(), NewResourceChecker(dynamicClient)}, } } func (nss NamespacesService) List(ctx context.Context, listOptions metav1.ListOptions) ([]corev1.Namespace, error) { ns, err := nss.client.List(ctx, listOptions) if err != nil { return nil, err } return ns.Items, nil } func (nss NamespacesService) GetEmptyFor(ctx context.Context, namespaces []corev1.Namespace, duration string) ([]corev1.Namespace, error) { now := time.Now() emptyNamespaces := []corev1.Namespace{} nonEmptyNamespaces := make(map[string]struct{}, len(namespaces)) for _, checker := range nss.checkers { err := checker.NonEmptyNamespaces(ctx, nonEmptyNamespaces) if err != nil { return nil, fmt.Errorf("could not get %s resources %w", checker.Name(), err) } } for _, ns := range namespaces { if _, ok := nonEmptyNamespaces[ns.Name]; ok { // Namespace is not empty if _, ok := ns.Annotations[cleanAnnotation]; ok && !nss.configuration.Batch { log.Warnf("Namespace is annotated for deletion, but not empty. Skipping %q", ns.Name) } continue } ts, ok := ns.Annotations[cleanAnnotation] if ok { emptySince, err := time.Parse(util.TimeFormat, ts) if err != nil { return nil, err } deleteAt, err := tparse.AddDuration(emptySince, duration) if err != nil { return nil, err } if now.After(deleteAt) { emptyNamespaces = append(emptyNamespaces, ns) } } else { nsCopy := ns.DeepCopy() if nsCopy.Annotations == nil { nsCopy.Annotations = make(map[string]string, 1) } nsCopy.Annotations[cleanAnnotation] = now.UTC().Format(util.TimeFormat) log.Infof("Annotated Namespace for deletion: %q", nsCopy.Name) if _, err := nss.client.Update(ctx, nsCopy, metav1.UpdateOptions{}); err != nil { return nil, err } } } return emptyNamespaces, nil } func (nss NamespacesService) Delete(ctx context.Context, namespaces []corev1.Namespace) error { for _, ns := range namespaces { err := nss.client.Delete(ctx, ns.Name, metav1.DeleteOptions{}) if err != nil && !apierrors.IsNotFound(err) { return err } if nss.configuration.Batch { fmt.Println(ns.Name) } else { log.Infof("Deleted Namespace %q", ns.Name) } } return nil } func (nss NamespacesService) Print(namespaces []corev1.Namespace) { if len(namespaces) == 0 { log.Info("Nothing found to be deleted.") } for _, ns := range namespaces { if nss.configuration.Batch { fmt.Println(ns.Name) } else { log.Infof("Found candidate: %s", ns.Name) } } }
<filename>examples/reference/swap.cpp #include <iostream> using namespace std; void swap(int& a, int& b) { int temp = a; cout << "Inside the swap() function:\n" << "address of a: " << &a << "\taddress of b: " << &b << "\naddress of temp: " << &temp << endl; a = b; b = temp; } int main() { int n1 = 25; int n2 = 38; int n3 = 71; int n4 = 82; cout << "Initial values:\n" << "address of n1: " << &n1 << "\taddress of n2: " << &n2 << "\nvalue of n1: " << n1 << "\t\t\tvalue of n2: " << n2 << "\naddress of n3: " << &n3 << "\taddress of n4: " << &n4 << "\nvalue of n3: " << n3 << "\t\t\tvalue of n4: " << n4 << "\nMaking the first call to swap()" << endl; swap(n1,n2); cout << "After the first call to swap():\n" << "address of n1: " << &n1 << "\taddress of n2: " << &n2 << "\nvalue of n1: " << n1 << "\t\t\tvalue of n2: " << n2 << "\nMaking the second call to swap()" << endl; swap(n3,n4); cout << "After the second call to swap():\n" << "address of n3: " << &n3 << "\taddress of n4: " << &n4 << "\nvalue of n3: " << n3 << "\tvalue of n4: " << n4 << endl; return 0; }
// Generate methods on the builder for setting a value of each of the struct // fields. // // impl CommandBuilder { // fn executable(&mut self, executable: String) -> &mut Self { // self.executable = Some(executable); // self // } // // ... // } use robma_builder::Builder; #[derive(Builder)] pub struct Command { executable: String, args: Vec<String>, env: Vec<String>, current_dir: String, } fn main() { let mut builder = Command::builder(); builder.executable("cargo".to_owned()); builder.args(vec!["build".to_owned(), "--release".to_owned()]); builder.env(vec![]); builder.current_dir("..".to_owned()); }
import { ApiProperty } from '@nestjs/swagger' import { Column, Entity } from 'typeorm' import { BaseEntity } from '../../common/models/base.entity' import { Exclude } from 'class-transformer' @Entity('key_value') export class KeyValueEntity extends BaseEntity { @Exclude() @Column({ nullable: false, type: 'varchar', length: 32, }) key: string @ApiProperty() @Column({ nullable: true, type: 'text', }) value: string constructor(partial: Partial<KeyValueEntity>) { super() Object.assign(this, partial) } }
package com.mingsoft.people.entity; import com.mingsoft.base.constant.e.BaseEnum; import com.mingsoft.base.entity.BaseEntity; /** * * 用户收货地址实体类 * @author yangxy * @version * 版本号:【100-000-000】 * 创建日期:2015年8月24日 * 历史修订: */ public class PeopleAddressEntity extends BaseEntity{ /** * 用户收货地址自增长Id */ int peopleAddressId; /** * 对应用户基础信息拓展表的id */ int peopleAddressPeopleId; /** * 用户收货人姓名 */ String peopleAddressConsigneeName; /** * 收货人所在的省 */ String peopleAddressProvince; /** * 收货人所在的市 */ String peopleAddressCity; /** * 收货人所在区 */ String peopleAddressDistrict; /** * 收货人的详细收货地址 */ String peopleAddressAddress; /** * 收货人邮箱 */ String peopleAddressMail; /** * 收货人手机 */ String peopleAddressPhone; /** * 是否是收货人最终收货地址。0代表是,1代表不是,默认为0 */ int peopleAddressDefault; /** * 对应的站点id */ int peopleAddressAppId; public int getPeopleAddressId() { return peopleAddressId; } public void setPeopleAddressId(int peopleAddressId) { this.peopleAddressId = peopleAddressId; } public int getPeopleAddressPeopleId() { return peopleAddressPeopleId; } public void setPeopleAddressPeopleId(int peopleAddressPeopleId) { this.peopleAddressPeopleId = peopleAddressPeopleId; } public String getPeopleAddressConsigneeName() { return peopleAddressConsigneeName; } public void setPeopleAddressConsigneeName(String peopleAddressConsigneeName) { this.peopleAddressConsigneeName = peopleAddressConsigneeName; } public String getPeopleAddressProvince() { return peopleAddressProvince; } public void setPeopleAddressProvince(String peopleAddressProvince) { this.peopleAddressProvince = peopleAddressProvince; } public String getPeopleAddressCity() { return peopleAddressCity; } public void setPeopleAddressCity(String peopleAddressCity) { this.peopleAddressCity = peopleAddressCity; } public String getPeopleAddressDistrict() { return peopleAddressDistrict; } public void setPeopleAddressDistrict(String peopleAddressDistrict) { this.peopleAddressDistrict = peopleAddressDistrict; } public String getPeopleAddressAddress() { return peopleAddressAddress; } public void setPeopleAddressAddress(String peopleAddressAddress) { this.peopleAddressAddress = peopleAddressAddress; } public String getPeopleAddressMail() { return peopleAddressMail; } public void setPeopleAddressMail(String peopleAddressMail) { this.peopleAddressMail = peopleAddressMail; } public String getPeopleAddressPhone() { return peopleAddressPhone; } public void setPeopleAddressPhone(String peopleAddressPhone) { this.peopleAddressPhone = peopleAddressPhone; } public int getPeopleAddressDefault() { return peopleAddressDefault; } /** * 推荐使用枚举类形参方法,此方法过时 * @param peopleAddressDefault */ @Deprecated public void setPeopleAddressDefault(int peopleAddressDefault) { this.peopleAddressDefault = peopleAddressDefault; } /** * 枚举类形参方法 * @param peopleAddressDefault */ public void setPeopleAddressDefault(BaseEnum peopleAddressDefault) { this.peopleAddressDefault = peopleAddressDefault.toInt(); } public int getPeopleAddressAppId() { return peopleAddressAppId; } public void setPeopleAddressAppId(int peopleAddressAppId) { this.peopleAddressAppId = peopleAddressAppId; } }
Umavathi Effect of Time-Periodic Boundary Temperature on the Onset of Nanofluid Convection in a Layer of a Saturated Porous Medium T The linear stability of nanofluid convection in a horizontal porous layer is examined theoretically when the walls of the porous layer are subjected to time-periodic temperature modulation. The model used for the nanofluid incorporates the effects of Brownian motion and thermopherosis, while the Darcy model is used for the porous medium. The analysis revels that for a typical nanofluid (with large Lewis number) the prime effect of the nanofluids is via a buoyancy effect coupled with the conservation of nanoparticles. The contribution of nanoparticles to the thermal energy equation being a second-order effect. It is found that the critical thermal Rayleigh number can be found reduced or decreased by a substantial amount, depending on whether the basic nanoparticle distribution is top-heavy or bottom-heavy. Oscillatory instability is possible in the case of a bottom-heavy nanoparticle distribution, phase angle and frequency of modulation. Keywords—Brownian motion and thermophoresis, Porous medium, Nanofluid, Natural convection, Thermal modulation. NOMENCLATURE c nanofluid specific heat at constant pressure p c specific heat of the nanoparticle material ( )m c ρ effective heat capacity of the porous medium g gravitational accelaeration ( 2 m s ) B D Brownian diffusion coefficient ( 2 m s ) T D thermophoretic diffusion coefficient ( 2 m s ) H dimensional layer depth ( m ) k thermal conductivity of the nanofluid m k effective thermal conductivity of the porous medium Le Lewis number A N modified diffusivity ratio B N modified particle-density increment * p pressure p dimensionless pressure, * m p K μα Ra thermal RayleighDarcy number Rm basic-density Rayleigh number Rn concentration Rayleigh number * t time ( s ) t dimensionless time, * 2 m t H α σ * T nanofluid temperature Prof. J.C. Umavathi is with the Department of Mathematics, Gulbarga Univerisity, Gulbarga, Karnataka, India – 585 106 (e-mail: [email protected]) r T reference temperature ( ) , , u v w dimensionless Darcy velocity components ( ) * * * , , m u v w H α v nanofluid velocity D v Darcy velocity v ε D * v dimensionless Darcy velocity ( ) * * * , , u v w ( ) , , x y z dimensionless Cartesian coordinate ( ) * * * , , x y z H ; z is the vertically upward coordinate ( ) * * * , , x y z Cartesian coordinates
<gh_stars>1-10 package main import ( "context" "log" "math/rand" "strconv" "time" "github.com/go-redis/redis/v8" ) var profAttr = [10]string{"professor_name", "quality_score", "difficulty_score", "sentiment_score_discrete", "sentiment_score_continuous", "keywords", "would_take_again", "pid", "school", "department"} var profPIDAttr = [4]string{"professor_name", "department", "school", "pid"} // Check and Try to retrieve query entry from Redis func RedisCheckResultCache(redisClient *redis.Client, input string, ctx context.Context) map[string]string { // check Redis (as a fast RAM-based cache) if the input query exists res, err := redisClient.HGetAll(ctx, input).Result() if err != nil { log.Fatal("CheckCache err:", err) } return res } // Update Redis entry -> {PID: results} in form of HashMap func RedisUpdateResultCache(redisClient *redis.Client, input string, values []string, ctx context.Context) int64 { m := make(map[string]interface{}) // populate the map m with the new values for ind, val := range profAttr { m[val] = values[ind] } // store the query result into Redis ok, err := redisClient.HSet(ctx, input, m).Result() if err != nil { log.Fatal("UpdateCache err:", err) } // set the expiration time of cache --> random in range of 1 to 6 hours rand.Seed(time.Now().Unix()) _, expErr := redisClient.Expire(ctx, input, time.Duration((rand.Intn(6)+1))*60*60*time.Second).Result() if expErr != nil { log.Fatal("SetExpire err:", expErr) } return ok } // Check and Try to retrieve query entry from Redis func RedisCheckNameCache(redisClient *redis.Client, input string, ctx context.Context) map[string]string { // check Redis (as a fast RAM-based cache) if the input query exists res, err := redisClient.HGetAll(ctx, input).Result() if err != nil { log.Fatal("CheckCache err:", err) } return res } // Update Redis entry -> {Prof name: results} in form of Key/Value pair func RedisUpdateNameCache(redisClient *redis.Client, input string, values []string, ctx context.Context) int64 { m := make(map[string]interface{}) // populate the map m with the new values for ind, val := range values { m[strconv.Itoa(ind)] = val } // store the query result into Redis ok, err := redisClient.HSet(ctx, input, m).Result() if err != nil { log.Fatal("UpdateCache err:", err) } // set the expiration time of cache --> random in range of 1 to 6 hours rand.Seed(time.Now().Unix()) _, expErr := redisClient.Expire(ctx, input, time.Duration((rand.Intn(6)+1))*60*60*time.Second).Result() if expErr != nil { log.Fatal("SetExpire err:", expErr) } return ok } // Check and Try to retrieve query entry from Redis func RedisCheckDepartmentList(redisClient *redis.Client, input string, ctx context.Context) map[string]string { // check Redis (as a fast RAM-based cache) if the input query exists res, err := redisClient.HGetAll(ctx, input).Result() if err != nil { log.Fatal("CheckCache err:", err) } return res } // Update Redis entry -> {School name: departments list} in form of Key/Value pair func RedisUpdateDepartmentList(redisClient *redis.Client, input string, values []string, ctx context.Context) int64 { m := make(map[string]interface{}) // populate the map m with the new values for ind, val := range values { m[strconv.Itoa(ind)] = val } // store the query result into Redis ok, err := redisClient.HSet(ctx, input, m).Result() if err != nil { log.Fatal("UpdateCache err:", err) } // no expiration time because there is no way to retrive RMP's department data JIT... /* // set the expiration time of cache --> random in range of 1 to 6 hours rand.Seed(time.Now().Unix()) _, expErr := redisClient.Expire(ctx, input, time.Duration((rand.Intn(6) + 1)) * 60 * 60 * time.Second).Result() if expErr != nil { log.Fatal("SetExpire err:", expErr) } */ return ok }
package pdf import ( "image/color" "github.com/alecthomas/chroma" "github.com/alecthomas/chroma/styles" ) // Style is the struct to capture the styling features for text // Size and Spacing are specified in points. // The sum of Size and Spacing is used as line height value // in the gofpdf API type Style struct { Font Font Size float64 Spacing float64 TextColor color.Color FillColor color.Color // For formatting the text format string } type Styles struct { // Headings H1 *Style H2 *Style H3 *Style H4 *Style H5 *Style H6 *Style // normal text Normal *Style // blockquote text Blockquote *Style // Table styling THeader *Style TBody *Style // code and preformatted text CodeFont Font // Codeblock Chroma Theme CodeBlockTheme *chroma.Style // link text LinkColor color.Color // IndentValue float64 } func DefaultStyles() Styles { c := Styles{} c.Normal = &Style{Font: FontRoboto, Size: 12, Spacing: 3, TextColor: color.RGBA{0, 0, 0, 0}, FillColor: color.RGBA{255, 255, 255, 0}} c.H1 = &Style{Font: FontRoboto, Size: 24, Spacing: 5, TextColor: color.RGBA{0, 0, 0, 0}, FillColor: color.RGBA{255, 255, 255, 0}} c.H2 = &Style{Font: FontRoboto, Size: 22, Spacing: 5, TextColor: color.RGBA{0, 0, 0, 0}, FillColor: color.RGBA{255, 255, 255, 0}} c.H3 = &Style{Font: FontRoboto, Size: 20, Spacing: 5, TextColor: color.RGBA{0, 0, 0, 0}, FillColor: color.RGBA{255, 255, 255, 0}} c.H4 = &Style{Font: FontRoboto, Size: 18, Spacing: 5, TextColor: color.RGBA{0, 0, 0, 0}, FillColor: color.RGBA{255, 255, 255, 0}} c.H5 = &Style{Font: FontRoboto, Size: 16, Spacing: 5, TextColor: color.RGBA{0, 0, 0, 0}, FillColor: color.RGBA{255, 255, 255, 0}} c.H6 = &Style{Font: FontRoboto, Size: 14, Spacing: 5, TextColor: color.RGBA{0, 0, 0, 0}, FillColor: color.RGBA{255, 255, 255, 0}} c.Blockquote = &Style{Font: FontRoboto, Size: 14, Spacing: 1, TextColor: color.RGBA{0, 0, 0, 0}, FillColor: color.RGBA{255, 255, 255, 0}} c.THeader = &Style{Font: FontRoboto, Size: 12, Spacing: 2, TextColor: color.RGBA{0, 0, 0, 0}, FillColor: color.RGBA{180, 180, 180, 0}} c.TBody = &Style{Font: FontRoboto, Size: 12, Spacing: 2, TextColor: color.RGBA{0, 0, 0, 0}, FillColor: color.RGBA{240, 240, 240, 0}} c.CodeFont = FontRobotoMono c.CodeBlockTheme = styles.Monokai return c }
export { XmLabeledViewContainerModule, XmLabeledViewContainerComponent, XmLabeledContainerOptions, } from './xm-labeled-view-container.component';