text
stringlengths
3
1.05M
const router = require("express").Router(); const { Room, Amenities } = require("../models"); router.get("/", (req, res) => { Room.findAll({ attributes: [ "id", "room_name", "room_price", "room_img", "room_description", ], }) .then((dbRoomData) => { const rooms = dbRoomData.map((room) => room.get({ plain: true })); res.render("rooms", { rooms, loggedIn:req.session.loggedIn }); }) .catch((err) => { console.log(err); res.status(500).json(err); }); }); module.exports = router;
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Object2689449295.h" // System.Byte[] struct ByteU5BU5D_t3397334013; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Security.X509.X501 struct X501_t349661535 : public Il2CppObject { public: public: }; struct X501_t349661535_StaticFields { public: // System.Byte[] Mono.Security.X509.X501::countryName ByteU5BU5D_t3397334013* ___countryName_0; // System.Byte[] Mono.Security.X509.X501::organizationName ByteU5BU5D_t3397334013* ___organizationName_1; // System.Byte[] Mono.Security.X509.X501::organizationalUnitName ByteU5BU5D_t3397334013* ___organizationalUnitName_2; // System.Byte[] Mono.Security.X509.X501::commonName ByteU5BU5D_t3397334013* ___commonName_3; // System.Byte[] Mono.Security.X509.X501::localityName ByteU5BU5D_t3397334013* ___localityName_4; // System.Byte[] Mono.Security.X509.X501::stateOrProvinceName ByteU5BU5D_t3397334013* ___stateOrProvinceName_5; // System.Byte[] Mono.Security.X509.X501::streetAddress ByteU5BU5D_t3397334013* ___streetAddress_6; // System.Byte[] Mono.Security.X509.X501::domainComponent ByteU5BU5D_t3397334013* ___domainComponent_7; // System.Byte[] Mono.Security.X509.X501::userid ByteU5BU5D_t3397334013* ___userid_8; // System.Byte[] Mono.Security.X509.X501::email ByteU5BU5D_t3397334013* ___email_9; // System.Byte[] Mono.Security.X509.X501::dnQualifier ByteU5BU5D_t3397334013* ___dnQualifier_10; // System.Byte[] Mono.Security.X509.X501::title ByteU5BU5D_t3397334013* ___title_11; // System.Byte[] Mono.Security.X509.X501::surname ByteU5BU5D_t3397334013* ___surname_12; // System.Byte[] Mono.Security.X509.X501::givenName ByteU5BU5D_t3397334013* ___givenName_13; // System.Byte[] Mono.Security.X509.X501::initial ByteU5BU5D_t3397334013* ___initial_14; public: inline static int32_t get_offset_of_countryName_0() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___countryName_0)); } inline ByteU5BU5D_t3397334013* get_countryName_0() const { return ___countryName_0; } inline ByteU5BU5D_t3397334013** get_address_of_countryName_0() { return &___countryName_0; } inline void set_countryName_0(ByteU5BU5D_t3397334013* value) { ___countryName_0 = value; Il2CppCodeGenWriteBarrier(&___countryName_0, value); } inline static int32_t get_offset_of_organizationName_1() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___organizationName_1)); } inline ByteU5BU5D_t3397334013* get_organizationName_1() const { return ___organizationName_1; } inline ByteU5BU5D_t3397334013** get_address_of_organizationName_1() { return &___organizationName_1; } inline void set_organizationName_1(ByteU5BU5D_t3397334013* value) { ___organizationName_1 = value; Il2CppCodeGenWriteBarrier(&___organizationName_1, value); } inline static int32_t get_offset_of_organizationalUnitName_2() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___organizationalUnitName_2)); } inline ByteU5BU5D_t3397334013* get_organizationalUnitName_2() const { return ___organizationalUnitName_2; } inline ByteU5BU5D_t3397334013** get_address_of_organizationalUnitName_2() { return &___organizationalUnitName_2; } inline void set_organizationalUnitName_2(ByteU5BU5D_t3397334013* value) { ___organizationalUnitName_2 = value; Il2CppCodeGenWriteBarrier(&___organizationalUnitName_2, value); } inline static int32_t get_offset_of_commonName_3() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___commonName_3)); } inline ByteU5BU5D_t3397334013* get_commonName_3() const { return ___commonName_3; } inline ByteU5BU5D_t3397334013** get_address_of_commonName_3() { return &___commonName_3; } inline void set_commonName_3(ByteU5BU5D_t3397334013* value) { ___commonName_3 = value; Il2CppCodeGenWriteBarrier(&___commonName_3, value); } inline static int32_t get_offset_of_localityName_4() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___localityName_4)); } inline ByteU5BU5D_t3397334013* get_localityName_4() const { return ___localityName_4; } inline ByteU5BU5D_t3397334013** get_address_of_localityName_4() { return &___localityName_4; } inline void set_localityName_4(ByteU5BU5D_t3397334013* value) { ___localityName_4 = value; Il2CppCodeGenWriteBarrier(&___localityName_4, value); } inline static int32_t get_offset_of_stateOrProvinceName_5() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___stateOrProvinceName_5)); } inline ByteU5BU5D_t3397334013* get_stateOrProvinceName_5() const { return ___stateOrProvinceName_5; } inline ByteU5BU5D_t3397334013** get_address_of_stateOrProvinceName_5() { return &___stateOrProvinceName_5; } inline void set_stateOrProvinceName_5(ByteU5BU5D_t3397334013* value) { ___stateOrProvinceName_5 = value; Il2CppCodeGenWriteBarrier(&___stateOrProvinceName_5, value); } inline static int32_t get_offset_of_streetAddress_6() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___streetAddress_6)); } inline ByteU5BU5D_t3397334013* get_streetAddress_6() const { return ___streetAddress_6; } inline ByteU5BU5D_t3397334013** get_address_of_streetAddress_6() { return &___streetAddress_6; } inline void set_streetAddress_6(ByteU5BU5D_t3397334013* value) { ___streetAddress_6 = value; Il2CppCodeGenWriteBarrier(&___streetAddress_6, value); } inline static int32_t get_offset_of_domainComponent_7() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___domainComponent_7)); } inline ByteU5BU5D_t3397334013* get_domainComponent_7() const { return ___domainComponent_7; } inline ByteU5BU5D_t3397334013** get_address_of_domainComponent_7() { return &___domainComponent_7; } inline void set_domainComponent_7(ByteU5BU5D_t3397334013* value) { ___domainComponent_7 = value; Il2CppCodeGenWriteBarrier(&___domainComponent_7, value); } inline static int32_t get_offset_of_userid_8() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___userid_8)); } inline ByteU5BU5D_t3397334013* get_userid_8() const { return ___userid_8; } inline ByteU5BU5D_t3397334013** get_address_of_userid_8() { return &___userid_8; } inline void set_userid_8(ByteU5BU5D_t3397334013* value) { ___userid_8 = value; Il2CppCodeGenWriteBarrier(&___userid_8, value); } inline static int32_t get_offset_of_email_9() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___email_9)); } inline ByteU5BU5D_t3397334013* get_email_9() const { return ___email_9; } inline ByteU5BU5D_t3397334013** get_address_of_email_9() { return &___email_9; } inline void set_email_9(ByteU5BU5D_t3397334013* value) { ___email_9 = value; Il2CppCodeGenWriteBarrier(&___email_9, value); } inline static int32_t get_offset_of_dnQualifier_10() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___dnQualifier_10)); } inline ByteU5BU5D_t3397334013* get_dnQualifier_10() const { return ___dnQualifier_10; } inline ByteU5BU5D_t3397334013** get_address_of_dnQualifier_10() { return &___dnQualifier_10; } inline void set_dnQualifier_10(ByteU5BU5D_t3397334013* value) { ___dnQualifier_10 = value; Il2CppCodeGenWriteBarrier(&___dnQualifier_10, value); } inline static int32_t get_offset_of_title_11() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___title_11)); } inline ByteU5BU5D_t3397334013* get_title_11() const { return ___title_11; } inline ByteU5BU5D_t3397334013** get_address_of_title_11() { return &___title_11; } inline void set_title_11(ByteU5BU5D_t3397334013* value) { ___title_11 = value; Il2CppCodeGenWriteBarrier(&___title_11, value); } inline static int32_t get_offset_of_surname_12() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___surname_12)); } inline ByteU5BU5D_t3397334013* get_surname_12() const { return ___surname_12; } inline ByteU5BU5D_t3397334013** get_address_of_surname_12() { return &___surname_12; } inline void set_surname_12(ByteU5BU5D_t3397334013* value) { ___surname_12 = value; Il2CppCodeGenWriteBarrier(&___surname_12, value); } inline static int32_t get_offset_of_givenName_13() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___givenName_13)); } inline ByteU5BU5D_t3397334013* get_givenName_13() const { return ___givenName_13; } inline ByteU5BU5D_t3397334013** get_address_of_givenName_13() { return &___givenName_13; } inline void set_givenName_13(ByteU5BU5D_t3397334013* value) { ___givenName_13 = value; Il2CppCodeGenWriteBarrier(&___givenName_13, value); } inline static int32_t get_offset_of_initial_14() { return static_cast<int32_t>(offsetof(X501_t349661535_StaticFields, ___initial_14)); } inline ByteU5BU5D_t3397334013* get_initial_14() const { return ___initial_14; } inline ByteU5BU5D_t3397334013** get_address_of_initial_14() { return &___initial_14; } inline void set_initial_14(ByteU5BU5D_t3397334013* value) { ___initial_14 = value; Il2CppCodeGenWriteBarrier(&___initial_14, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
import pandas as pd from visualization import * from chameleon import * if __name__ == "__main__": # get a set of data points df = pd.read_csv('./datasets/Aggregation.csv', sep=' ', header=None) # returns a pands.dataframe of cluster res = cluster(df, 7, knn_params=dict(n_neighbors=20, metric='euclidean', n_jobs=-1), m=40, alpha=2.0, plot=False) # draw a 2-D scatter plot with cluster plot2d_data(res)
import os import sys from pathlib import Path def replace_file_extension(input_file): """ read {train/val/test/trainval}.txt file (downloaded from https://github.com/fxia22/pointnet.pytorch/issues/52#issuecomment-561013797) These files contain list of .ply models. ModelNet40 dataset now contains .off files instead of .ply This methods replaces the model file extensions to .off :param input_file: string: location of {train/val/test/trainval}.txt :return: """ path = Path(input_file) text = path.read_text() if ".ply" in text: text = text.replace(".ply", ".off") # write in the same file path.write_text(text) print(f"Extension .ply replaced with .off in file {input_file}") def write_log(logfile, msg): logfile.write(f'{msg}\n') print(msg) logfile.flush() def write_loss_acc(loss_acc_file, mode, epoch, loss, acc): loss_acc_file.write(f'{mode},{epoch},{loss:.6f},{acc:.6f}\n') loss_acc_file.flush() def main(): # if __name__ == '__main__': dataset_folder = sys.argv[1] replace_file_extension(os.path.join(dataset_folder, 'train.txt')) replace_file_extension(os.path.join(dataset_folder, 'val.txt')) replace_file_extension(os.path.join(dataset_folder, 'test.txt')) replace_file_extension(os.path.join(dataset_folder, 'trainval.txt'))
"""Add sentences for understanding the context of matched terms.""" import csv import os import re from glob import glob from typing import List import nltk import pandas as pd import textdistance from nltk import ne_chunk, pos_tag, word_tokenize from nltk.stem.wordnet import WordNetLemmatizer from ontorunner.post.util import (consolidate_rows, filter_synonyms, get_ancestors, get_column_doc_ratio) # if not nltk.find("corpora/wordnet"): nltk.download("wordnet") nltk.download("punkt") nltk.download("omw-1.4") nltk.download("averaged_perceptron_tagger") # for GH Actions. nltk.download("maxent_ne_chunker") nltk.download("words") pd.options.mode.chained_assignment = None # default='warn' def find_extensions(dr, ext) -> List[str]: """Find files with a specific extension. :param dr: Directory path. :param ext: Extension. :return: List of relevant files. """ return glob(os.path.join(dr, "*.{}".format(ext))) def sentencify(input_df, output_df, output_fn): """ Add relevant sentences to the tokenized term in every row of a pandas DataFrame. :param df: (DataFrame) pandas DataFrame. :return: None """ for _, row in input_df.iterrows(): idx = row.id text = row.text # Check for text = NaN if text == text: text = ( text.replace("\t", " ") .replace("\u2028", " ") .replace("\n", "") .replace( "\r", "", ) .replace( ")", " " ) # reason: re.error: unbalanced parenthesis at position x .replace("(", " ") ) sent_tok = nltk.sent_tokenize(text) # ** This block is for freq count of term in text # # Calcualte frquencies of words and phrases # word_tok = nltk.word_tokenize(text.lower()) # # This gets freq count for each word # word_tok_freq = FreqDist(word_tok) # # This will capture phrases and corresponding frequencies # phrases = dict() # for size in 2, 3, 4, 5: # phrases[size] = FreqDist(ngrams(word_tok, size)) sub_df = output_df[output_df["document_id"] == idx] # In certain instances, in spite of the 'matched' and 'preferred' # terms being the same, the term is registered as a synonym by KGX # and hence the biohub_converter codes this with a '_SYNONYM' tag. # In order to counter this, we need to filter these extra rows out. if not sub_df.empty and any(sub_df["object_id"].str.endswith("_SYNONYM")): sub_df = filter_synonyms(sub_df) if len(sent_tok) == 1: sub_df["sentence"] = text else: relevant_sents = [] for i, row2 in sub_df.iterrows(): start_reached = False end_reached = False term_of_interest = str(row2["matched_term"]) start_pos = int(row2["start_position"]) if start_pos == 0: start_reached = True end_pos = int(row2["end_position"]) if end_pos == len(text): end_reached = True if term_of_interest == "nan": # get just the portion where # 'matched_term' == 'preferred_form' # because in case of _SYNONYM, # there will be extra metadata which # will not be present in the tokenized sentence. term_of_interest = str(row2["preferred_form"]) relevant_sents = [ x for x in sent_tok if re.search(term_of_interest, x, re.IGNORECASE) ] if relevant_sents == []: relevant_sents = ["irrelevant token: can be ignored."] list_of_sents = relevant_sents count = 0 while len(list_of_sents) > 1: count += 1 # This keeps track of the # of times the start_pos # and/or end_pos are shifted # Detect the beginning and ending of sentences # --------------------- if not start_reached: start_pos -= 1 for sent in list_of_sents: if sent.startswith(text[start_pos:end_pos]): start_reached = True elif text[start_pos:end_pos].startswith("."): start_pos += 1 start_reached = True if not end_reached: end_pos += 1 for sent in list_of_sents: if sent.endswith(text[start_pos:end_pos]): end_reached = True elif text[start_pos:end_pos].endswith("."): end_pos -= 1 end_reached = True # ------------------------------------------------------------------- term_of_interest = text[start_pos:end_pos] print( f"Doc: {row.id} |" f" iter: {i} |" f" count: {count} |" f" #_of_sent: {len(list_of_sents)}" f" search_term: {term_of_interest}" ) list_of_sents = [ x for x in relevant_sents if re.search(term_of_interest.strip(), x) ] if count > 30 and 1 < len(list_of_sents): list_of_sents = [list_of_sents[0]] count = 0 break # Reason for the break: # In some instance the sentences are repeated. # In such cases the expanding window with start_pos and # end_pos goes expanding after 30 character match # (arbitrary) we take the first element out of the # common terms and take that as the SENTENCE # and then 'break'-ing out of the 'while' loop. # Else, it'll continue looking for the unique # sentence forever. It's a hack but for now it'll # do until severe consequences detected. sub_df.loc[i, "sentence"] = list_of_sents[0] if not sub_df.empty: sub_df["object_sentence_%"] = sub_df.apply( lambda x: 1 - textdistance.jaccard.distance( x.matched_term.lower(), x.sentence.lower() ), axis=1, ) sub_df.to_csv(output_fn, mode="a", sep="\t", header=None, index=None) def get_match_type(token1: str, token2: str) -> str: """ Return type of token match. :param token1: token from 'matched_term' :type token1: str :param token2: token from 'preferred_term' :type token2: str :return: Type of match [e.g.: 'exact_match' etc.] :rtype: str """ match = "" lemma = WordNetLemmatizer() if token1.lower() == token2.lower(): match = "exact_match" elif lemma.lemmatize(token1) == lemma.lemmatize(token2): # pos = NOUN by default match = "lemmatic_match" elif lemma.lemmatize(token1, pos="v") == lemma.lemmatize(token2, pos="v"): # testing pos = VERB match = "lemmatic_match" elif lemma.lemmatize(token1, pos="a") == lemma.lemmatize(token2, pos="a"): # testing pos = ADJECTIVE match = "lemmatic_match" elif lemma.lemmatize(token1, pos="r") == lemma.lemmatize(token2, pos="r"): # testing pos = ADVERB match = "lemmatic_match" return match def parse( input_directory: str, output_directory: str, nodes_and_edges: str, need_ancestors: bool, ) -> None: """ Parse OGER output and add sentences of tokenized terms. :param input_directory: (str) Input directory path. :param output_directory: (str) Output directory path. :param nodes_and_edges: (str) Nodes and edges file directory path. :return: None. """ # Get a list of potential input files for particular formats input_list_tsv = find_extensions(input_directory, "tsv") input_list_txt = find_extensions(input_directory, "txt") output_files = find_extensions(output_directory, "tsv") output_file_list = [ x for x in output_files if "_node" not in x if "_edge" not in x if "ontoRunNER" not in x ] for output_file in output_file_list: output_df = pd.read_csv(output_file, sep="\t", low_memory=False) output_df.columns = output_df.columns.str.replace(" ", "_").str.lower() # Consolidate rows where the entitys is the same # and recognized from multiple origins output_df = output_df.rename( columns={"entity_id": "object_id", "type": "object_category"} ) output_df = consolidate_rows(output_df) output_df[["preferred_form", "object_label"]] = output_df[ "preferred_form" ].str.split("\\[SYNONYM_OF:", expand=True) output_df["object_label"] = output_df["object_label"].str.replace( "]", "", regex=True ) output_df["object_label"] = output_df["object_label"].fillna( output_df["preferred_form"] ) output_df["pos_and_ne_chunk"] = ( output_df["matched_term"] .apply(word_tokenize) .apply(pos_tag) .apply(ne_chunk) ) output_df = get_column_doc_ratio(output_df, "object_label") output_df = get_column_doc_ratio(output_df, "matched_term") # Add column which indicates how close # of a match is the recognized entity. output_df.insert( 6, "match_type", output_df.apply( lambda x: get_match_type( x.matched_term.lower(), x.preferred_form.lower() ), axis=1, ), ) # Levenshtein distances output_df.insert( 7, "levenshtein_distance", output_df.apply( lambda x: textdistance.levenshtein.distance( x.matched_term.lower(), x.preferred_form.lower() ), axis=1, ), ) # Jaccard Index output_df.insert( 8, "jaccard_index", output_df.apply( lambda x: textdistance.jaccard.distance( x.matched_term.lower(), x.preferred_form.lower() ), axis=1, ), ) # Monge-Elkan output_df.insert( 9, "monge_elkan", output_df.apply( lambda x: textdistance.monge_elkan.distance( x.matched_term.lower(), x.preferred_form.lower() ), axis=1, ), ) output_df["sentence"] = "" output_df["object_sentence_%"] = "" output_df = output_df.reindex( columns=[ "document_id", "object_category", "start_position", "end_position", "matched_term", "preferred_form", "object_label", "object_label_doc_ratio", "matched_term_doc_ratio", "match_type", "levenshtein_distance", "jaccard_index", "monge_elkan", "object_id", "pos_and_ne_chunk", "sentence_id", "umls_cui", "origin", "sentence", "object_sentence_%", ] ) # TODO: Maybe use OAK for getting ancestors (?) if need_ancestors: output_df = get_ancestors(output_df, nodes_and_edges) final_output_file = output_file.replace(".tsv", "_ontoRunNER.tsv") pd.DataFrame(output_df.columns).T.to_csv( final_output_file, sep="\t", index=None, header=None ) if len(input_list_tsv) > 0: for f in input_list_tsv: input_df = pd.read_csv(f, sep="\t", low_memory=False, index_col=None) sentencify(input_df, output_df, final_output_file) if len(input_list_txt) > 0: # Read each text file such that Id = filename and text = full text for f in input_list_txt: input_df = pd.DataFrame(columns=["id", "text"]) sniffer = csv.Sniffer() sample_bytes = 128 dialect = sniffer.sniff(open(f).readline(sample_bytes)) if dialect.delimiter == "\t" or dialect.delimiter == ",": input_df = pd.read_csv( f, sep="\t", low_memory=False, index_col=None ) else: id = f.split("/")[-1].split(".txt")[0] with open(f, "r") as fn: text = fn.readlines() text = "".join(text).replace("\n", " ") input_df = input_df.append( {"id": id, "text": text}, ignore_index=True ) sentencify(input_df, output_df, final_output_file)
#include <stdbool.h> #define ONYX_CHAR_TAG 0xA struct object* onyx_char_tag(char); char onyx_char_untag(struct object*); bool onyx_is_char(struct object*);
// flow-typed signature: 5d4e04838fec1f4406da93fbe7e1a4e9 // flow-typed version: 2b421a3da9/chai_v4.x.x/flow_>=v0.15.0 declare module "chai" { declare type ExpectChain<T> = { and: ExpectChain<T>, at: ExpectChain<T>, be: ExpectChain<T>, been: ExpectChain<T>, have: ExpectChain<T>, has: ExpectChain<T>, is: ExpectChain<T>, of: ExpectChain<T>, same: ExpectChain<T>, that: ExpectChain<T>, to: ExpectChain<T>, which: ExpectChain<T>, with: ExpectChain<T>, not: ExpectChain<T>, deep: ExpectChain<T>, any: ExpectChain<T>, all: ExpectChain<T>, a: ExpectChain<T> & ((type: string) => ExpectChain<T>), an: ExpectChain<T> & ((type: string) => ExpectChain<T>), include: ExpectChain<T> & ((value: mixed) => ExpectChain<T>), includes: ExpectChain<T> & ((value: mixed) => ExpectChain<T>), contain: ExpectChain<T> & ((value: mixed) => ExpectChain<T>), contains: ExpectChain<T> & ((value: mixed) => ExpectChain<T>), eq: (value: T) => ExpectChain<T>, eql: (value: T) => ExpectChain<T>, equal: (value: T) => ExpectChain<T>, equals: (value: T) => ExpectChain<T>, above: (value: T & number) => ExpectChain<T>, least: (value: T & number) => ExpectChain<T>, below: (value: T & number) => ExpectChain<T>, most: (value: T & number) => ExpectChain<T>, within: (start: T & number, finish: T & number) => ExpectChain<T>, instanceof: (constructor: mixed) => ExpectChain<T>, nested: ExpectChain<T>, property: <P>( name: string, value?: P ) => ExpectChain<P> & ((name: string) => ExpectChain<mixed>), length: (value: number) => ExpectChain<T> | ExpectChain<number>, lengthOf: (value: number) => ExpectChain<T>, match: (regex: RegExp) => ExpectChain<T>, string: (string: string) => ExpectChain<T>, key: (key: string) => ExpectChain<T>, keys: ( key: string | Array<string>, ...keys: Array<string> ) => ExpectChain<T>, throw: <E>( err?: Class<E> | Error | RegExp | string, errMsgMatcher?: RegExp | string, msg?: string ) => ExpectChain<T>, respondTo: (method: string) => ExpectChain<T>, itself: ExpectChain<T>, satisfy: (method: (value: T) => boolean) => ExpectChain<T>, closeTo: (expected: T & number, delta: number) => ExpectChain<T>, members: (set: mixed) => ExpectChain<T>, oneOf: (list: Array<T>) => ExpectChain<T>, change: (obj: mixed, key: string) => ExpectChain<T>, increase: (obj: mixed, key: string) => ExpectChain<T>, decrease: (obj: mixed, key: string) => ExpectChain<T>, // dirty-chai ok: () => ExpectChain<T>, true: () => ExpectChain<T>, false: () => ExpectChain<T>, null: () => ExpectChain<T>, undefined: () => ExpectChain<T>, exist: () => ExpectChain<T>, empty: () => ExpectChain<T>, extensible: () => ExpectChain<T>, sealed: () => ExpectChain<T>, frozen: () => ExpectChain<T>, NaN: () => ExpectChain<T>, // chai-immutable size: (n: number) => ExpectChain<T>, // sinon-chai called: () => ExpectChain<T>, callCount: (n: number) => ExpectChain<T>, calledOnce: () => ExpectChain<T>, calledTwice: () => ExpectChain<T>, calledThrice: () => ExpectChain<T>, calledBefore: (spy: mixed) => ExpectChain<T>, calledAfter: (spy: mixed) => ExpectChain<T>, calledWith: (...args: Array<mixed>) => ExpectChain<T>, calledWithMatch: (...args: Array<mixed>) => ExpectChain<T>, calledWithExactly: (...args: Array<mixed>) => ExpectChain<T>, // chai-as-promised eventually: ExpectChain<T>, resolvedWith: (value: mixed) => Promise<mixed> & ExpectChain<T>, resolved: () => Promise<mixed> & ExpectChain<T>, rejectedWith: (value: mixed) => Promise<mixed> & ExpectChain<T>, rejected: () => Promise<mixed> & ExpectChain<T>, notify: (callback: () => mixed) => ExpectChain<T>, fulfilled: () => Promise<mixed> & ExpectChain<T>, // chai-subset containSubset: (obj: Object | Object[]) => ExpectChain<T>, // chai-redux-mock-store dispatchedActions: ( actions: Array<Object | ((action: Object) => any)> ) => ExpectChain<T>, dispatchedTypes: (actions: Array<string>) => ExpectChain<T>, // chai-enzyme attr: (key: string, val?: any) => ExpectChain<T>, data: (key: string, val?: any) => ExpectChain<T>, prop: (key: string, val?: any) => ExpectChain<T>, state: (key: string, val?: any) => ExpectChain<T>, value: (val: string) => ExpectChain<T> }; declare function expect<T>(actual: T, message?: string): ExpectChain<T>; declare function use(plugin: (chai: Object, utils: Object) => void): void; declare class assert { static (expression: mixed, message?: string): void; static fail( actual: mixed, expected: mixed, message?: string, operator?: string ): void; static isOk(object: mixed, message?: string): void; static isNotOk(object: mixed, message?: string): void; static equal(actual: mixed, expected: mixed, message?: string): void; static notEqual(actual: mixed, expected: mixed, message?: string): void; static strictEqual(act: mixed, exp: mixed, msg?: string): void; static notStrictEqual(act: mixed, exp: mixed, msg?: string): void; static deepEqual(act: mixed, exp: mixed, msg?: string): void; static notDeepEqual(act: mixed, exp: mixed, msg?: string): void; static ok(val: mixed, msg?: string): void; static isTrue(val: mixed, msg?: string): void; static isNotTrue(val: mixed, msg?: string): void; static isFalse(val: mixed, msg?: string): void; static isNotFalse(val: mixed, msg?: string): void; static isNull(val: mixed, msg?: string): void; static isNotNull(val: mixed, msg?: string): void; static isUndefined(val: mixed, msg?: string): void; static isDefined(val: mixed, msg?: string): void; static isNaN(val: mixed, msg?: string): void; static isNotNaN(val: mixed, msg?: string): void; static isAbove(val: number, abv: number, msg?: string): void; static isBelow(val: number, blw: number, msg?: string): void; static isAtMost(val: number, atmst: number, msg?: string): void; static isAtLeast(val: number, atlst: number, msg?: string): void; static isFunction(val: mixed, msg?: string): void; static isNotFunction(val: mixed, msg?: string): void; static isObject(val: mixed, msg?: string): void; static isNotObject(val: mixed, msg?: string): void; static isArray(val: mixed, msg?: string): void; static isNotArray(val: mixed, msg?: string): void; static isString(val: mixed, msg?: string): void; static isNotString(val: mixed, msg?: string): void; static isNumber(val: mixed, msg?: string): void; static isNotNumber(val: mixed, msg?: string): void; static isBoolean(val: mixed, msg?: string): void; static isNotBoolean(val: mixed, msg?: string): void; static typeOf(val: mixed, type: string, msg?: string): void; static notTypeOf(val: mixed, type: string, msg?: string): void; static instanceOf(val: mixed, constructor: Function, msg?: string): void; static notInstanceOf(val: mixed, constructor: Function, msg?: string): void; static include(exp: string, inc: mixed, msg?: string): void; static include<T>(exp: Array<T>, inc: T, msg?: string): void; static notInclude(exp: string, inc: mixed, msg?: string): void; static notInclude<T>(exp: Array<T>, inc: T, msg?: string): void; static match(exp: mixed, re: RegExp, msg?: string): void; static notMatch(exp: mixed, re: RegExp, msg?: string): void; static property(obj: Object, prop: string, msg?: string): void; static notProperty(obj: Object, prop: string, msg?: string): void; static deepProperty(obj: Object, prop: string, msg?: string): void; static notDeepProperty(obj: Object, prop: string, msg?: string): void; static propertyVal( obj: Object, prop: string, val: mixed, msg?: string ): void; static propertyNotVal( obj: Object, prop: string, val: mixed, msg?: string ): void; static deepPropertyVal( obj: Object, prop: string, val: mixed, msg?: string ): void; static deepPropertyNotVal( obj: Object, prop: string, val: mixed, msg?: string ): void; static lengthOf(exp: mixed, len: number, msg?: string): void; static throws<E>( func: () => any, err?: Class<E> | Error | RegExp | string, errorMsgMatcher?: string | RegExp, msg?: string ): void; static doesNotThrow<E>( func: () => any, err?: Class<E> | Error | RegExp | string, errorMsgMatcher?: string | RegExp, msg?: string ): void; static closeTo( actual: number, expected: number, delta: number, msg?: string ): void; static approximately( actual: number, expected: number, delta: number, msg?: string ): void; } declare var config: { includeStack: boolean, showDiff: boolean, truncateThreshold: number }; }
// Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CLIENTVERSION_H #define BITCOIN_CLIENTVERSION_H #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif //HAVE_CONFIG_H // Check that required client information is defined #if !defined(CLIENT_VERSION_MAJOR) || !defined(CLIENT_VERSION_MINOR) || !defined(CLIENT_VERSION_REVISION) || !defined(CLIENT_VERSION_BUILD) || !defined(CLIENT_VERSION_IS_RELEASE) || !defined(COPYRIGHT_YEAR) #error Client version information missing: version is not defined by bitcoin-config.h or in any other way #endif #if !defined(PEERCOIN_VERSION_MAJOR) || !defined(PEERCOIN_VERSION_MINOR) || !defined(PEERCOIN_VERSION_REVISION) || !defined(PEERCOIN_VERSION_BUILD) #error Client version information missing: version is not defined by bitcoin-config.h or in any other way #endif /** * Converts the parameter X to a string after macro replacement on X has been performed. * Don't merge these into one macro! */ #define STRINGIZE(X) DO_STRINGIZE(X) #define DO_STRINGIZE(X) #X //! Copyright string used in Windows .rc files #define COPYRIGHT_STR "2009-" STRINGIZE(COPYRIGHT_YEAR) " " COPYRIGHT_HOLDERS_FINAL /** * bitcoind-res.rc includes this file, but it cannot cope with real c++ code. * WINDRES_PREPROC is defined to indicate that its pre-processor is running. * Anything other than a define should be guarded below. */ #if !defined(WINDRES_PREPROC) #include <string> #include <vector> static const int CLIENT_VERSION = 1000000 * CLIENT_VERSION_MAJOR + 10000 * CLIENT_VERSION_MINOR + 100 * CLIENT_VERSION_REVISION + 1 * CLIENT_VERSION_BUILD; // note: peercoin version is used for display purpose AND to accept alerts static const int PEERCOIN_VERSION = 1000000 * PEERCOIN_VERSION_MAJOR + 10000 * PEERCOIN_VERSION_MINOR + 100 * PEERCOIN_VERSION_REVISION + 1 * PEERCOIN_VERSION_BUILD; extern const std::string CLIENT_NAME; extern const std::string CLIENT_BUILD; std::string FormatFullVersion(); std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments); #endif // WINDRES_PREPROC #endif // BITCOIN_CLIENTVERSION_H
/* * Backpack - Skyscanner's Design System * * Copyright 2016-2020 Skyscanner Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* @flow */ import commonTests from './BpkTextInput-test.common'; jest.mock('react-native', () => { const reactNative = jest.requireActual('react-native'); Object.defineProperty(reactNative.I18nManager, 'isRTL', { value: true }); return reactNative; }); describe('RTL', () => { commonTests(); });
# Generated by Django 3.1.13 on 2021-08-21 18:39 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.CharField(max_length=255)), ('unit_price', models.IntegerField(default=0)), ('stock', models.IntegerField(default=0)), ], ), ]
/*------------------------------------------------------------------------- * * storage.c * code to create and destroy physical storage for relations * * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/catalog/storage.c * * NOTES * Some of this code used to be in storage/smgr/smgr.c, and the * function names still reflect that. * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/visibilitymap.h" #include "access/xact.h" #include "access/xlogutils.h" #include "catalog/catalog.h" #include "catalog/storage.h" #include "catalog/storage_xlog.h" #include "common/relpath.h" #include "commands/dbcommands.h" #include "storage/freespace.h" #include "storage/smgr.h" #include "utils/memutils.h" #include "utils/rel.h" /* * We keep a list of all relations (represented as RelFileNode values) * that have been created or deleted in the current transaction. When * a relation is created, we create the physical file immediately, but * remember it so that we can delete the file again if the current * transaction is aborted. Conversely, a deletion request is NOT * executed immediately, but is just entered in the list. When and if * the transaction commits, we can delete the physical file. * * To handle subtransactions, every entry is marked with its transaction * nesting level. At subtransaction commit, we reassign the subtransaction's * entries to the parent nesting level. At subtransaction abort, we can * immediately execute the abort-time actions for all entries of the current * nesting level. * * NOTE: the list is kept in TopMemoryContext to be sure it won't disappear * unbetimes. It'd probably be OK to keep it in TopTransactionContext, * but I'm being paranoid. */ typedef struct PendingRelDelete { RelFileNodeWithStorageType relnode; /* relation that may need to be deleted */ BackendId backend; /* InvalidBackendId if not a temp rel */ bool atCommit; /* T=delete at commit; F=delete at abort */ int nestLevel; /* xact nesting level of request */ struct PendingRelDelete *next; /* linked-list link */ bool dbOperation; /* T=operate on database; F=operate on relation */ } PendingRelDelete; static PendingRelDelete *pendingDeletes = NULL; /* head of linked list */ /* * RelationCreateStorage * Create physical storage for a relation. * * Create the underlying disk file storage for the relation. This only * creates the main fork; additional forks are created lazily by the * modules that need them. * * This function is transactional. The creation is WAL-logged, and if the * transaction aborts later on, the storage will be destroyed. */ void RelationCreateStorage(RelFileNode rnode, char relpersistence, char relstorage) { PendingRelDelete *pending; SMgrRelation srel; BackendId backend; bool needs_wal; switch (relpersistence) { case RELPERSISTENCE_TEMP: backend = TempRelBackendId; needs_wal = false; break; case RELPERSISTENCE_UNLOGGED: backend = InvalidBackendId; needs_wal = false; break; case RELPERSISTENCE_PERMANENT: backend = InvalidBackendId; needs_wal = true; break; default: elog(ERROR, "invalid relpersistence: %c", relpersistence); return; /* placate compiler */ } srel = smgropen(rnode, backend); smgrcreate(srel, MAIN_FORKNUM, false); if (needs_wal) log_smgrcreate(&srel->smgr_rnode.node, MAIN_FORKNUM); /* Add the relation to the list of stuff to delete at abort */ pending = (PendingRelDelete *) MemoryContextAlloc(TopMemoryContext, sizeof(PendingRelDelete)); pending->relnode.node = rnode; pending->relnode.relstorage = relstorage; pending->backend = backend; pending->atCommit = false; /* delete if abort */ pending->nestLevel = GetCurrentTransactionNestLevel(); pending->dbOperation = false; pending->next = pendingDeletes; pendingDeletes = pending; } /* * Perform XLogInsert of a XLOG_SMGR_CREATE record to WAL. */ void log_smgrcreate(RelFileNode *rnode, ForkNumber forkNum) { xl_smgr_create xlrec; XLogRecData rdata; /* * Make an XLOG entry reporting the file creation. */ xlrec.rnode = *rnode; xlrec.forkNum = forkNum; rdata.data = (char *) &xlrec; rdata.len = sizeof(xlrec); rdata.buffer = InvalidBuffer; rdata.next = NULL; XLogInsert(RM_SMGR_ID, XLOG_SMGR_CREATE, &rdata); } /* * RelationDropStorage * Schedule unlinking of physical storage at transaction commit. */ void RelationDropStorage(Relation rel) { PendingRelDelete *pending; /* Add the relation to the list of stuff to delete at commit */ pending = (PendingRelDelete *) MemoryContextAlloc(TopMemoryContext, sizeof(PendingRelDelete)); pending->relnode.node = rel->rd_node; pending->relnode.relstorage = rel->rd_rel->relstorage; pending->backend = rel->rd_backend; pending->atCommit = true; /* delete if commit */ pending->nestLevel = GetCurrentTransactionNestLevel(); pending->dbOperation = false; pending->next = pendingDeletes; pendingDeletes = pending; /* * NOTE: if the relation was created in this transaction, it will now be * present in the pending-delete list twice, once with atCommit true and * once with atCommit false. Hence, it will be physically deleted at end * of xact in either case (and the other entry will be ignored by * smgrDoPendingDeletes, so no error will occur). We could instead remove * the existing list entry and delete the physical file immediately, but * for now I'll keep the logic simple. */ RelationCloseSmgr(rel); } /* * DatabaseDropStorage * Schedule unlinking of database directory at transaction commit. */ void DatabaseDropStorage(Oid db_id, Oid tablespace_id) { /* * Drop/Alter database cannot be part of a transaction, therefore * pendingDeletes should be empty */ Assert(pendingDeletes == NULL); PendingRelDelete *pending; /* Add the relation to the list of stuff to delete at commit */ pending = (PendingRelDelete *) MemoryContextAlloc(TopMemoryContext, sizeof(PendingRelDelete)); pending->relnode.node.spcNode = tablespace_id; pending->relnode.node.dbNode = db_id; pending->relnode.node.relNode = InvalidOid; pending->backend = InvalidBackendId; pending->atCommit = true; /* delete if commit */ pending->nestLevel = GetCurrentTransactionNestLevel(); pending->dbOperation = true; pending->next = pendingDeletes; pendingDeletes = pending; } /* * RelationPreserveStorage * Mark a relation as not to be deleted after all. * * We need this function because relation mapping changes are committed * separately from commit of the whole transaction, so it's still possible * for the transaction to abort after the mapping update is done. * When a new physical relation is installed in the map, it would be * scheduled for delete-on-abort, so we'd delete it, and be in trouble. * The relation mapper fixes this by telling us to not delete such relations * after all as part of its commit. * * We also use this to reuse an old build of an index during ALTER TABLE, this * time removing the delete-at-commit entry. * * No-op if the relation is not among those scheduled for deletion. */ void RelationPreserveStorage(RelFileNode rnode, bool atCommit) { PendingRelDelete *pending; PendingRelDelete *prev; PendingRelDelete *next; prev = NULL; for (pending = pendingDeletes; pending != NULL; pending = next) { next = pending->next; if (RelFileNodeEquals(rnode, pending->relnode.node) && pending->atCommit == atCommit) { /* unlink and delete list entry */ if (prev) prev->next = next; else pendingDeletes = next; pfree(pending); /* prev does not change */ } else { /* unrelated entry, don't touch it */ prev = pending; } } } /* * RelationTruncate * Physically truncate a relation to the specified number of blocks. * * This includes getting rid of any buffers for the blocks that are to be * dropped. */ void RelationTruncate(Relation rel, BlockNumber nblocks) { bool fsm; bool vm; /* Open it at the smgr level if not already done */ RelationOpenSmgr(rel); /* * Make sure smgr_targblock etc aren't pointing somewhere past new end */ rel->rd_smgr->smgr_targblock = InvalidBlockNumber; rel->rd_smgr->smgr_fsm_nblocks = InvalidBlockNumber; rel->rd_smgr->smgr_vm_nblocks = InvalidBlockNumber; /* Truncate the FSM first if it exists */ fsm = smgrexists(rel->rd_smgr, FSM_FORKNUM); if (fsm) FreeSpaceMapTruncateRel(rel, nblocks); /* Truncate the visibility map too if it exists. */ vm = smgrexists(rel->rd_smgr, VISIBILITYMAP_FORKNUM); if (vm) visibilitymap_truncate(rel, nblocks); /* * We WAL-log the truncation before actually truncating, which means * trouble if the truncation fails. If we then crash, the WAL replay * likely isn't going to succeed in the truncation either, and cause a * PANIC. It's tempting to put a critical section here, but that cure * would be worse than the disease. It would turn a usually harmless * failure to truncate, that might spell trouble at WAL replay, into a * certain PANIC. */ if (RelationNeedsWAL(rel)) { /* * Make an XLOG entry reporting the file truncation. */ XLogRecPtr lsn; XLogRecData rdata; xl_smgr_truncate xlrec; xlrec.blkno = nblocks; xlrec.rnode = rel->rd_node; rdata.data = (char *) &xlrec; rdata.len = sizeof(xlrec); rdata.buffer = InvalidBuffer; rdata.next = NULL; lsn = XLogInsert(RM_SMGR_ID, XLOG_SMGR_TRUNCATE, &rdata); /* * Flush, because otherwise the truncation of the main relation might * hit the disk before the WAL record, and the truncation of the FSM * or visibility map. If we crashed during that window, we'd be left * with a truncated heap, but the FSM or visibility map would still * contain entries for the non-existent heap pages. */ if (fsm || vm) XLogFlush(lsn); } /* Do the real work */ smgrtruncate(rel->rd_smgr, MAIN_FORKNUM, nblocks); } /* * smgrDoPendingDeletes() -- Take care of relation deletes at end of xact. * * This also runs when aborting a subxact; we want to clean up a failed * subxact immediately. * * Note: It's possible that we're being asked to remove a relation that has * no physical storage in any fork. In particular, it's possible that we're * cleaning up an old temporary relation for which RemovePgTempFiles has * already recovered the physical storage. */ void smgrDoPendingDeletes(bool isCommit) { int nestLevel = GetCurrentTransactionNestLevel(); PendingRelDelete *pending; PendingRelDelete *prev; PendingRelDelete *next; int nrels = 0, i = 0, maxrels = 0; SMgrRelation *srels = NULL; char *relstorages = NULL; prev = NULL; for (pending = pendingDeletes; pending != NULL; pending = next) { next = pending->next; if (pending->nestLevel < nestLevel) { /* outer-level entries should not be processed yet */ prev = pending; } else { /* unlink list entry first, so we don't retry on failure */ if (prev) prev->next = next; else pendingDeletes = next; /* do deletion if called for */ if (pending->atCommit == isCommit) { if (pending->dbOperation) { Assert(next == NULL); Assert(pending->relnode.node.relNode == InvalidOid); DropDatabaseDirectory(pending->relnode.node.dbNode, pending->relnode.node.spcNode); pfree(pending); return; } SMgrRelation srel; srel = smgropen(pending->relnode.node, pending->backend); /* allocate the initial array, or extend it, if needed */ if (maxrels == 0) { maxrels = 8; srels = palloc(sizeof(SMgrRelation) * maxrels); relstorages = palloc(maxrels * sizeof(char)); } else if (maxrels <= nrels) { maxrels *= 2; srels = repalloc(srels, sizeof(SMgrRelation) * maxrels); relstorages = repalloc(relstorages, sizeof(char) * maxrels); } relstorages[nrels] = pending->relnode.relstorage; srels[nrels++] = srel; } /* must explicitly free the list entry */ pfree(pending); /* prev does not change */ } } if (nrels > 0) { smgrdounlinkall(srels, nrels, false, relstorages); for (i = 0; i < nrels; i++) smgrclose(srels[i]); pfree(srels); pfree(relstorages); } } /* * smgrGetPendingDeletes() -- Get a list of non-temp relations to be deleted. * * The return value is the number of relations scheduled for termination. * *ptr is set to point to a freshly-palloc'd array of RelFileNodes. * If there are no relations to be deleted, *ptr is set to NULL. * * Only non-temporary relations are included in the returned list. This is OK * because the list is used only in contexts where temporary relations don't * matter: we're either writing to the two-phase state file (and transactions * that have touched temp tables can't be prepared) or we're writing to xlog * (and all temporary files will be zapped if we restart anyway, so no need * for redo to do it also). * * Note that the list does not include anything scheduled for termination * by upper-level transactions. * * Greenplum-specific notes: We *do* include temporary relations in the returned * list. Because unlike in Upstream Postgres, Greenplum two-phase commits can * involve temporary tables, which necessitates including the temporary * relations in the two-phase state files (PREPARE xlog record). Otherwise the * relation files won't get unlink(2)'d, or the shared buffers won't be * dropped at the end of COMMIT phase. */ int smgrGetPendingDeletes(bool forCommit, RelFileNodeWithStorageType **ptr) { int nestLevel = GetCurrentTransactionNestLevel(); int nrels; RelFileNodeWithStorageType *rptr; PendingRelDelete *pending; nrels = 0; for (pending = pendingDeletes; pending != NULL; pending = pending->next) { if (pending->nestLevel >= nestLevel && pending->atCommit == forCommit && !pending->dbOperation /* * Greenplum allows transactions that access temporary tables to be * prepared. */ /* && pending->backend == InvalidBackendId) */ ) nrels++; } if (nrels == 0) { *ptr = NULL; return 0; } rptr = (RelFileNodeWithStorageType *) palloc(nrels * sizeof(RelFileNodeWithStorageType)); *ptr = rptr; for (pending = pendingDeletes; pending != NULL; pending = pending->next) { if (pending->nestLevel >= nestLevel && pending->atCommit == forCommit && !pending->dbOperation /* * Keep this loop condition identical to above */ /* && pending->backend == InvalidBackendId) */ ) { *rptr = pending->relnode; rptr++; } } return nrels; } /* * PostPrepare_smgr -- Clean up after a successful PREPARE * * What we have to do here is throw away the in-memory state about pending * relation deletes. It's all been recorded in the 2PC state file and * it's no longer smgr's job to worry about it. */ void PostPrepare_smgr(void) { PendingRelDelete *pending; PendingRelDelete *next; for (pending = pendingDeletes; pending != NULL; pending = next) { next = pending->next; pendingDeletes = next; /* must explicitly free the list entry */ pfree(pending); } } /* * AtSubCommit_smgr() --- Take care of subtransaction commit. * * Reassign all items in the pending-deletes list to the parent transaction. */ void AtSubCommit_smgr(void) { int nestLevel = GetCurrentTransactionNestLevel(); PendingRelDelete *pending; for (pending = pendingDeletes; pending != NULL; pending = pending->next) { if (pending->nestLevel >= nestLevel) pending->nestLevel = nestLevel - 1; } } /* * AtSubAbort_smgr() --- Take care of subtransaction abort. * * Delete created relations and forget about deleted relations. * We can execute these operations immediately because we know this * subtransaction will not commit. */ void AtSubAbort_smgr(void) { smgrDoPendingDeletes(false); } void smgr_redo(XLogRecPtr beginLoc, XLogRecPtr lsn, XLogRecord *record) { uint8 info = record->xl_info & ~XLR_INFO_MASK; /* Backup blocks are not used in smgr records */ Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK)); if (info == XLOG_SMGR_CREATE) { xl_smgr_create *xlrec = (xl_smgr_create *) XLogRecGetData(record); SMgrRelation reln; reln = smgropen(xlrec->rnode, InvalidBackendId); smgrcreate(reln, xlrec->forkNum, true); } else if (info == XLOG_SMGR_TRUNCATE) { xl_smgr_truncate *xlrec = (xl_smgr_truncate *) XLogRecGetData(record); SMgrRelation reln; Relation rel; reln = smgropen(xlrec->rnode, InvalidBackendId); /* * Forcibly create relation if it doesn't exist (which suggests that * it was dropped somewhere later in the WAL sequence). As in * XLogReadBuffer, we prefer to recreate the rel and replay the log as * best we can until the drop is seen. */ smgrcreate(reln, MAIN_FORKNUM, true); /* * Before we perform the truncation, update minimum recovery point to * cover this WAL record. Once the relation is truncated, there's no * going back. The buffer manager enforces the WAL-first rule for * normal updates to relation files, so that the minimum recovery * point is always updated before the corresponding change in the data * file is flushed to disk. We have to do the same manually here. * * Doing this before the truncation means that if the truncation fails * for some reason, you cannot start up the system even after restart, * until you fix the underlying situation so that the truncation will * succeed. Alternatively, we could update the minimum recovery point * after truncation, but that would leave a small window where the * WAL-first rule could be violated. */ XLogFlush(lsn); smgrtruncate(reln, MAIN_FORKNUM, xlrec->blkno); /* Also tell xlogutils.c about it */ XLogTruncateRelation(xlrec->rnode, MAIN_FORKNUM, xlrec->blkno); /* Truncate FSM and VM too */ rel = CreateFakeRelcacheEntry(xlrec->rnode); if (smgrexists(reln, FSM_FORKNUM)) FreeSpaceMapTruncateRel(rel, xlrec->blkno); if (smgrexists(reln, VISIBILITYMAP_FORKNUM)) visibilitymap_truncate(rel, xlrec->blkno); FreeFakeRelcacheEntry(rel); } else elog(PANIC, "smgr_redo: unknown op code %u", info); }
"""Download Files to your local server Syntax: .download .download url | file.name to download files from a Public Link""" import asyncio import math import os import time from datetime import datetime from pySmartDL import SmartDL from uniborg.util import admin_cmd, humanbytes, progress @borg.on(admin_cmd(pattern="download ?(.*)", allow_sudo=True)) async def _(event): if event.fwd_from: return mone = await event.reply("Processing ...") input_str = event.pattern_match.group(1) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: start = datetime.now() reply_message = await event.get_reply_message() try: c_time = time.time() downloaded_file_name = await borg.download_media( reply_message, Config.TMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, mone, c_time, "trying to download") ) ) except Exception as e: # pylint:disable=C0103,W0703 await mone.edit(str(e)) else: end = datetime.now() ms = (end - start).seconds await mone.edit("Downloaded to `{}` in {} seconds.".format(downloaded_file_name, ms)) elif input_str: start = datetime.now() url = input_str file_name = os.path.basename(url) to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY if "|" in input_str: url, file_name = input_str.split("|", maxsplit=1) url = url.strip() file_name = file_name.strip() downloaded_file_name = os.path.join(to_download_directory, file_name) downloader = SmartDL(url, downloaded_file_name, progress_bar=False) downloader.start(blocking=False) display_message = "" c_time = time.time() while not downloader.isFinished(): total_length = downloader.filesize if downloader.filesize else None downloaded = downloader.get_dl_size() now = time.time() diff = now - c_time percentage = downloader.get_progress() * 100 speed = downloader.get_speed() round(diff) * 1000 progress_str = "[{0}{1}]\nProgress: {2}%".format( ''.join("█" for _ in range(math.floor(percentage / 5))), ''.join("░" for _ in range(20 - math.floor(percentage / 5))), round(percentage, 2)) estimated_total_time = downloader.get_eta(human=True) try: current_message = f"trying to download\n"\ f"URL: {url}\n"\ f"File Name: {file_name}\n" \ f"Speed: {speed}"\ f"{progress_str}\n"\ f"{humanbytes(downloaded)} of {humanbytes(total_length)}\n"\ f"ETA: {estimated_total_time}" if round( diff % 10.00) == 0 and current_message != display_message: await mone.edit(current_message) display_message = current_message except Exception as e: logger.info(str(e)) end = datetime.now() ms = (end - start).seconds if downloader.isSuccessful(): await mone.edit("Downloaded to `{}` in {} seconds.".format(downloaded_file_name, ms)) else: await mone.edit("Incorrect URL\n {}".format(input_str)) else: await mone.edit("Reply to a message to download to my local server.")
try: from ciscosparkapi import CiscoSparkAPI, DEFAULT_BASE_URL except ImportError: message = ('Missing "ciscosparkapi", please install it using pip:\n' 'pip install ciscosparkapi') raise ImportError(message) from st2actions.runners.pythonrunner import Action __all__ = [ 'CiscoSparkAction', ] class CiscoSparkAction(Action): def __init__(self, config): super(CiscoSparkAction, self).__init__(config) self._access_token = self.config['access_token'] self._base_url = self.config.get('base_url', DEFAULT_BASE_URL) self.connect() def connect(self): self.connection = CiscoSparkAPI(access_token=self._access_token, base_url=self._base_url)
self.addEventListener('install', function(e) { e.waitUntil( caches.open('shosho-canel-store').then(function(cache) { return cache.addAll([ '/packages/bootstrap/dist/index.html', '/packages/bootstrap/dist/bundle.min.js', '/packages/bootstrap/dist/icon/fox-icon.png', '/packages/bootstrap/dist/manifest.webmanifest', ]); }) ); }); self.addEventListener('fetch', function(e) { console.log(e.request.url); e.respondWith( caches.match(e.request).then(function(response) { return response || fetch(e.request); }) ); });
""" Hashtable """ class Hashtable: def __init__(self, size): self.size = size self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): hashvalue = self.hashfunction(key, len(self.slots)) if not self.slots[hashvalue]: # Add new value self.slots[hashvalue] = key self.data[hashvalue] = data else: if self.slots[hashvalue] == key: # Override self.data[hashvalue] = data else: nextslot = self.rehash(hashvalue, len(self.slots)) while self.slots[nextslot] != None or self.slots[nextslot] != key: nextslot = self.rehash(nextslot, len(self.slots)) if self.slots[nextslot] == None: self.slots[nextslot] = key self.data[nextslot] = data else: self.data[nextslot] = data # Override def hashfunction(self, key, size): return key % size def rehash(self, oldhashvalue, size): return (oldhashvalue + 1) % size def get(self, key): startslot = self.hashfunction(key, len(self.slots)) data = None stop = False found = False position = startslot while self.slots[position] != None and not found and not stop: if self.slots[position] == key: found = True data = self.data[position] else: position = self.rehash(position, len(self.slots)) if position == startslot: stop = True return data def __getitem__(self, key): return self.get(key) def __setitem__(self, key, data): self.put(key, data) if __name__ == "__main__": h = Hashtable(5) h[1] = "one" # h[2] = 'two' # h[3] = 'two' # h[4] = 'twooverlapped' # h[5] = '5 added' print(h[5])
import re import os import sys from math import log re_eng = re.compile('[a-zA-Z0-9]', re.U) re_han = re.compile("([\u4E00-\u9FD5a-zA-Z0-9+#&\._%\-]+)", re.U) re_skip = re.compile("(\r\n|\s)", re.U) class Segment: def __init__(self): self.vocab = {} self.max_word_len = 0 self.max_freq = 0 self.total_freq = 0 self.initialized = False def init(self, vocab_path='dict/jiagu.dict', user_vocab='dict/user.dict'): self.load_vocab(os.path.join(os.path.dirname(__file__), vocab_path)) self.load_vocab(os.path.join(os.path.dirname(__file__), user_vocab)) self.initialized = True def load_vocab(self, vocab_path): fin = open(vocab_path, 'r', encoding='utf8') for index, line in enumerate(fin): line = line.strip() if line == '': continue word_freq_tag = line.split('\t') if len(word_freq_tag) == 1: word = word_freq_tag[0] self.add_vocab(word) elif len(word_freq_tag) == 2: word = word_freq_tag[0] freq = int(word_freq_tag[1]) self.add_vocab(word, freq) fin.close() def add_vocab(self, word=None, freq=None, tag=None): if freq == None: freq = self.max_freq if word not in self.vocab: self.vocab[word] = 0 self.vocab[word] += freq self.total_freq += freq if freq > self.max_freq: self.max_freq = freq if len(word) > self.max_word_len: self.max_word_len = len(word) def load_userdict(self, userdict): if self.initialized == False: self.init() if isinstance(userdict, str): self.load_vocab(userdict) for item in userdict: if isinstance(item, list): if len(item) == 1: word = item[0] self.add_vocab(word) elif len(item) == 2: word = item[0] freq = item[1] self.add_vocab(word, freq) elif isinstance(item, str): self.add_vocab(word=item) def calc_route(self, sentence, DAG, route): vocab = self.vocab N = len(sentence) route[N] = (0, 0) logtotal = log(self.total_freq) for idx in range(N - 1, -1, -1): route[idx] = max((log(vocab.get(sentence[idx:x + 1]) or 1) - logtotal + route[x + 1][0], x) for x in DAG[idx]) def create_DAG(self, sentence): vocab = self.vocab max_word_len = self.max_word_len DAG = {} N = len(sentence) for idx in range(N): cand_idx = [idx] for i in range(idx+1, idx + min(max_word_len, N - idx), 1): cand = sentence[idx: i+1] if cand in vocab: cand_idx.append(i) DAG[idx] = cand_idx return DAG def cut_search(self, sentence): DAG = self.create_DAG(sentence) old_j = -1 for k, L in DAG.items(): if len(L) == 1 and k > old_j: yield sentence[k:L[0] + 1] old_j = L[0] else: for j in L: if j > k: yield sentence[k:j + 1] old_j = j def cut_vocab(self, sentence): DAG = self.create_DAG(sentence) route = {} self.calc_route(sentence, DAG, route) x = 0 N = len(sentence) buf = '' while x < N: y = route[x][1] + 1 l_word = sentence[x:y] if buf: yield buf buf = '' yield l_word x = y if buf: yield buf buf = '' def cut_words(self, sentence): DAG = self.create_DAG(sentence) route = {} self.calc_route(sentence, DAG, route) x = 0 N = len(sentence) buf = '' while x < N: y = route[x][1] + 1 l_word = sentence[x:y] if re_eng.match(l_word) and len(l_word) == 1: buf += l_word x = y else: if buf: yield buf buf = '' yield l_word x = y if buf: yield buf buf = '' def seg_default(self, sentence, mode): blocks = re_han.split(sentence) cut_block = self.cut_words cut_all = False for block in blocks: if not block: continue if re_han.match(block): for word in cut_block(block): yield word else: tmp = re_skip.split(block) for x in tmp: if re_skip.match(x): yield x elif not cut_all: for xx in x: yield xx else: yield x def seg(self, sentence, mode="default"): if self.initialized == False: self.init() return list(self.seg_default(sentence, mode=mode)) if __name__=='__main__': s = Segment() # sg.load_userdict('dict/user.dict') # s.load_userdict(['知识图谱']) text = '张华平等' text = '美国纽约州立大学' text = '海康威视' words = s.seg(text) print(words)
#!/usr/bin/env python """ See the file "LICENSE" for the full license governing this code. Copyright 2011,2012,2013,2017 Ken Farmer """ #adjust pylint for pytest oddities: #pylint: disable=missing-docstring #pylint: disable=unused-argument #pylint: disable=attribute-defined-outside-init #pylint: disable=protected-access #pylint: disable=no-self-use import pytest import datagristle.common as mod class TestFunctions(object): def test_get_common_key(self): d = {'car': 7, 'truck':8, 'boat':30, 'plane': 5} assert mod.get_common_key(d) == ('boat', 0.6) class TestColnamesToColoff0(object): def test_empty_lists(self): assert mod.colnames_to_coloff0([], []) == [] def test_col_numbers_only(self): assert mod.colnames_to_coloff0([], [0, 3, 5]) == [0, 3, 5] def test_string_lookuplist_int_namelist(self): assert mod.colnames_to_coloff0(['0', '1', '2'], [0]) == [0] def test_int_lookuplist_string_namelist(self): assert mod.colnames_to_coloff0([0, 1, 2], ['0']) == [0] def test_col_numbers_strings_only(self): assert mod.colnames_to_coloff0([], ['0', '3', '5']) == [0, 3, 5] def test_col_all_names_only(self): assert mod.colnames_to_coloff0(['foo', 'bar', 'baz'], ['foo', 'bar', 'baz']) == [0, 1, 2] def test_col_some_names_only(self): assert mod.colnames_to_coloff0(['foo', 'bar', 'baz'], ['bar']) == [1] def test_col_mix_of_names_and_numbers(self): assert mod.colnames_to_coloff0(['foo', 'bar', 'baz'], [0, 'bar', 'baz']) == [0, 1, 2] def test_error_name_not_found(self): with pytest.raises(KeyError): assert mod.colnames_to_coloff0(['foo', 'bar', 'baz'], ['gorilla']) def test_error_number_not_found(self): with pytest.raises(KeyError): assert mod.colnames_to_coloff0(['foo', 'bar', 'baz'], [5])
import { createStore, applyMiddleware } from "redux"; import { createPlayMiddleware } from "redux-play"; import rootReducer from "./reducers"; import * as rootPlay from "./plays"; const errorHandler = error => store.dispatch({ type: ":device--unexpected-error", error }); const playMiddleware = createPlayMiddleware(rootPlay, { errorHandler }); const store = createStore(rootReducer, applyMiddleware(playMiddleware)); if (module.hot) { module.hot.accept("./reducers", () => { const nextRootReducer = require("./reducers").default; store.replaceReducer(nextRootReducer); }); module.hot.accept("./plays", () => { const nextRootPlay = require("./plays"); playMiddleware.replacePlay(nextRootPlay); }); } export default store;
import attr from .utils import listify @attr.s(frozen=True) class Version: """A version number of the form 1.0.0-1.""" major = attr.ib(default=0) minor = attr.ib(default=0) patch = attr.ib(default=0) downstream = attr.ib(default=0) @classmethod def parse(cls, rep): """Parse the version from a string.""" upstream, downstream = rep.split("-", 1) major, minor, patch = map(int, upstream.split(".")) downstream = int(downstream) return cls(major, minor, patch, downstream) def __str__(self): """Convert the version to a string.""" return f"{self.major}.{self.minor}.{self.patch}-{self.downstream}" @staticmethod def format(parts): """Convert the version-tuple to a string.""" if len(parts) < 4: return ".".join(str(part) for part in parts) return str(Version(*parts)) @property def upstream(self): """Return the upstream version.""" return self.major, self.minor, self.patch def to_tuple(self): """Return the version as a tuple.""" return self.major, self.minor, self.patch, self.downstream def startswith(self, prefix): """Return true if the initial version components are equal to the prefix.""" return prefix == self.to_tuple()[: len(prefix)] @listify def prefixes(self): """Return all prefixes of the version.""" parts = self.to_tuple() while parts: yield parts parts = parts[:-1] yield parts @staticmethod def canonical(versions, prefix=()): """Find the greatest version with the given prefix.""" return max(version for version in versions if version.startswith(prefix)) def is_canonical(self, versions, prefix=None): if prefix is None: prefix = self.upstream return self == Version.canonical(versions, prefix=prefix)
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads_v1/proto/errors/conversion_adjustment_upload_error.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='google/ads/googleads_v1/proto/errors/conversion_adjustment_upload_error.proto', package='google.ads.googleads.v1.errors', syntax='proto3', serialized_options=_b('\n\"com.google.ads.googleads.v1.errorsB$ConversionAdjustmentUploadErrorProtoP\001ZDgoogle.golang.org/genproto/googleapis/ads/googleads/v1/errors;errors\242\002\003GAA\252\002\036Google.Ads.GoogleAds.V1.Errors\312\002\036Google\\Ads\\GoogleAds\\V1\\Errors\352\002\"Google::Ads::GoogleAds::V1::Errors'), serialized_pb=_b('\nMgoogle/ads/googleads_v1/proto/errors/conversion_adjustment_upload_error.proto\x12\x1egoogle.ads.googleads.v1.errors\x1a\x1cgoogle/api/annotations.proto\"\xae\x03\n#ConversionAdjustmentUploadErrorEnum\"\x86\x03\n\x1f\x43onversionAdjustmentUploadError\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0b\n\x07UNKNOWN\x10\x01\x12 \n\x1cTOO_RECENT_CONVERSION_ACTION\x10\x02\x12\x1d\n\x19INVALID_CONVERSION_ACTION\x10\x03\x12 \n\x1c\x43ONVERSION_ALREADY_RETRACTED\x10\x04\x12\x18\n\x14\x43ONVERSION_NOT_FOUND\x10\x05\x12\x16\n\x12\x43ONVERSION_EXPIRED\x10\x06\x12\"\n\x1e\x41\x44JUSTMENT_PRECEDES_CONVERSION\x10\x07\x12!\n\x1dMORE_RECENT_RESTATEMENT_FOUND\x10\x08\x12\x19\n\x15TOO_RECENT_CONVERSION\x10\t\x12N\nJCANNOT_RESTATE_CONVERSION_ACTION_THAT_ALWAYS_USES_DEFAULT_CONVERSION_VALUE\x10\nB\xff\x01\n\"com.google.ads.googleads.v1.errorsB$ConversionAdjustmentUploadErrorProtoP\x01ZDgoogle.golang.org/genproto/googleapis/ads/googleads/v1/errors;errors\xa2\x02\x03GAA\xaa\x02\x1eGoogle.Ads.GoogleAds.V1.Errors\xca\x02\x1eGoogle\\Ads\\GoogleAds\\V1\\Errors\xea\x02\"Google::Ads::GoogleAds::V1::Errorsb\x06proto3') , dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,]) _CONVERSIONADJUSTMENTUPLOADERRORENUM_CONVERSIONADJUSTMENTUPLOADERROR = _descriptor.EnumDescriptor( name='ConversionAdjustmentUploadError', full_name='google.ads.googleads.v1.errors.ConversionAdjustmentUploadErrorEnum.ConversionAdjustmentUploadError', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='UNSPECIFIED', index=0, number=0, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='UNKNOWN', index=1, number=1, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='TOO_RECENT_CONVERSION_ACTION', index=2, number=2, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='INVALID_CONVERSION_ACTION', index=3, number=3, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='CONVERSION_ALREADY_RETRACTED', index=4, number=4, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='CONVERSION_NOT_FOUND', index=5, number=5, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='CONVERSION_EXPIRED', index=6, number=6, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='ADJUSTMENT_PRECEDES_CONVERSION', index=7, number=7, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='MORE_RECENT_RESTATEMENT_FOUND', index=8, number=8, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='TOO_RECENT_CONVERSION', index=9, number=9, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='CANNOT_RESTATE_CONVERSION_ACTION_THAT_ALWAYS_USES_DEFAULT_CONVERSION_VALUE', index=10, number=10, serialized_options=None, type=None), ], containing_type=None, serialized_options=None, serialized_start=184, serialized_end=574, ) _sym_db.RegisterEnumDescriptor(_CONVERSIONADJUSTMENTUPLOADERRORENUM_CONVERSIONADJUSTMENTUPLOADERROR) _CONVERSIONADJUSTMENTUPLOADERRORENUM = _descriptor.Descriptor( name='ConversionAdjustmentUploadErrorEnum', full_name='google.ads.googleads.v1.errors.ConversionAdjustmentUploadErrorEnum', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ ], extensions=[ ], nested_types=[], enum_types=[ _CONVERSIONADJUSTMENTUPLOADERRORENUM_CONVERSIONADJUSTMENTUPLOADERROR, ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=144, serialized_end=574, ) _CONVERSIONADJUSTMENTUPLOADERRORENUM_CONVERSIONADJUSTMENTUPLOADERROR.containing_type = _CONVERSIONADJUSTMENTUPLOADERRORENUM DESCRIPTOR.message_types_by_name['ConversionAdjustmentUploadErrorEnum'] = _CONVERSIONADJUSTMENTUPLOADERRORENUM _sym_db.RegisterFileDescriptor(DESCRIPTOR) ConversionAdjustmentUploadErrorEnum = _reflection.GeneratedProtocolMessageType('ConversionAdjustmentUploadErrorEnum', (_message.Message,), dict( DESCRIPTOR = _CONVERSIONADJUSTMENTUPLOADERRORENUM, __module__ = 'google.ads.googleads_v1.proto.errors.conversion_adjustment_upload_error_pb2' , __doc__ = """Container for enum describing possible conversion adjustment upload errors. """, # @@protoc_insertion_point(class_scope:google.ads.googleads.v1.errors.ConversionAdjustmentUploadErrorEnum) )) _sym_db.RegisterMessage(ConversionAdjustmentUploadErrorEnum) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
from django.utils.translation import ugettext as _ from django.utils.timezone import now as timezone_now from django.conf import settings from django.core import validators from django.core.exceptions import ValidationError from django.db import connection from django.http import HttpRequest, HttpResponse from typing import Dict, List, Set, Text, Any, Callable, Iterable, \ Optional, Tuple, Union from zerver.lib.exceptions import JsonableError, ErrorCode from zerver.lib.html_diff import highlight_html_differences from zerver.decorator import has_request_variables, \ REQ, to_non_negative_int from django.utils.html import escape as escape_html from zerver.lib import bugdown from zerver.lib.actions import recipient_for_emails, do_update_message_flags, \ compute_mit_user_fullname, compute_irc_user_fullname, compute_jabber_user_fullname, \ create_mirror_user_if_needed, check_send_message, do_update_message, \ extract_recipients, truncate_body, render_incoming_message, do_delete_message, \ do_mark_all_as_read, do_mark_stream_messages_as_read, get_user_info_for_message_updates from zerver.lib.queue import queue_json_publish from zerver.lib.message import ( access_message, messages_for_ids, render_markdown, get_first_visible_message_id, ) from zerver.lib.response import json_success, json_error from zerver.lib.sqlalchemy_utils import get_sqlalchemy_connection from zerver.lib.streams import access_stream_by_id, is_public_stream_by_name from zerver.lib.timestamp import datetime_to_timestamp from zerver.lib.topic_mutes import exclude_topic_mutes from zerver.lib.utils import statsd from zerver.lib.validator import \ check_list, check_int, check_dict, check_string, check_bool from zerver.models import Message, UserProfile, Stream, Subscription, \ Realm, RealmDomain, Recipient, UserMessage, bulk_get_recipients, get_personal_recipient, \ get_stream, email_to_domain, get_realm, get_active_streams, \ get_user_including_cross_realm, get_stream_recipient from sqlalchemy import func from sqlalchemy.sql import select, join, column, literal_column, literal, and_, \ or_, not_, union_all, alias, Selectable, Select, ColumnElement, table import re import ujson import datetime LARGER_THAN_MAX_MESSAGE_ID = 10000000000000000 class BadNarrowOperator(JsonableError): code = ErrorCode.BAD_NARROW data_fields = ['desc'] def __init__(self, desc: str) -> None: self.desc = desc # type: str @staticmethod def msg_format() -> str: return _('Invalid narrow operator: {desc}') # TODO: Should be Select, but sqlalchemy stubs are busted Query = Any # TODO: should be Callable[[ColumnElement], ColumnElement], but sqlalchemy stubs are busted ConditionTransform = Any # When you add a new operator to this, also update zerver/lib/narrow.py class NarrowBuilder: ''' Build up a SQLAlchemy query to find messages matching a narrow. ''' # This class has an important security invariant: # # None of these methods ever *add* messages to a query's result. # # That is, the `add_term` method, and its helpers the `by_*` methods, # are passed a Query object representing a query for messages; they may # call some methods on it, and then they return a resulting Query # object. Things these methods may do to the queries they handle # include # * add conditions to filter out rows (i.e., messages), with `query.where` # * add columns for more information on the same message, with `query.column` # * add a join for more information on the same message # # Things they may not do include # * anything that would pull in additional rows, or information on # other messages. def __init__(self, user_profile: UserProfile, msg_id_column: str) -> None: self.user_profile = user_profile self.msg_id_column = msg_id_column self.user_realm = user_profile.realm def add_term(self, query: Query, term: Dict[str, Any]) -> Query: """ Extend the given query to one narrowed by the given term, and return the result. This method satisfies an important security property: the returned query never includes a message that the given query didn't. In particular, if the given query will only find messages that a given user can legitimately see, then so will the returned query. """ # To maintain the security property, we hold all the `by_*` # methods to the same criterion. See the class's block comment # for details. # We have to be careful here because we're letting users call a method # by name! The prefix 'by_' prevents it from colliding with builtin # Python __magic__ stuff. operator = term['operator'] operand = term['operand'] negated = term.get('negated', False) method_name = 'by_' + operator.replace('-', '_') method = getattr(self, method_name, None) if method is None: raise BadNarrowOperator('unknown operator ' + operator) if negated: maybe_negate = not_ else: maybe_negate = lambda cond: cond return method(query, operand, maybe_negate) def by_has(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: if operand not in ['attachment', 'image', 'link']: raise BadNarrowOperator("unknown 'has' operand " + operand) col_name = 'has_' + operand cond = column(col_name) return query.where(maybe_negate(cond)) def by_in(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: if operand == 'home': conditions = exclude_muting_conditions(self.user_profile, []) return query.where(and_(*conditions)) elif operand == 'all': return query raise BadNarrowOperator("unknown 'in' operand " + operand) def by_is(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: if operand == 'private': # The `.select_from` method extends the query with a join. query = query.select_from(join(query.froms[0], table("zerver_recipient"), column("recipient_id") == literal_column("zerver_recipient.id"))) cond = or_(column("type") == Recipient.PERSONAL, column("type") == Recipient.HUDDLE) return query.where(maybe_negate(cond)) elif operand == 'starred': cond = column("flags").op("&")(UserMessage.flags.starred.mask) != 0 return query.where(maybe_negate(cond)) elif operand == 'unread': cond = column("flags").op("&")(UserMessage.flags.read.mask) == 0 return query.where(maybe_negate(cond)) elif operand == 'mentioned': cond1 = column("flags").op("&")(UserMessage.flags.mentioned.mask) != 0 cond2 = column("flags").op("&")(UserMessage.flags.wildcard_mentioned.mask) != 0 cond = or_(cond1, cond2) return query.where(maybe_negate(cond)) elif operand == 'alerted': cond = column("flags").op("&")(UserMessage.flags.has_alert_word.mask) != 0 return query.where(maybe_negate(cond)) raise BadNarrowOperator("unknown 'is' operand " + operand) _alphanum = frozenset( 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') def _pg_re_escape(self, pattern: Text) -> Text: """ Escape user input to place in a regex Python's re.escape escapes unicode characters in a way which postgres fails on, u'\u03bb' to u'\\\u03bb'. This function will correctly escape them for postgres, u'\u03bb' to u'\\u03bb'. """ s = list(pattern) for i, c in enumerate(s): if c not in self._alphanum: if ord(c) >= 128: # convert the character to hex postgres regex will take # \uXXXX s[i] = '\\u{:0>4x}'.format(ord(c)) else: s[i] = '\\' + c return ''.join(s) def by_stream(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: try: # Because you can see your own message history for # private streams you are no longer subscribed to, we # need get_stream, not access_stream, here. stream = get_stream(operand, self.user_profile.realm) except Stream.DoesNotExist: raise BadNarrowOperator('unknown stream ' + operand) if self.user_profile.realm.is_zephyr_mirror_realm: # MIT users expect narrowing to "social" to also show messages to # /^(un)*social(.d)*$/ (unsocial, ununsocial, social.d, ...). # In `ok_to_include_history`, we assume that a non-negated # `stream` term for a public stream will limit the query to # that specific stream. So it would be a bug to hit this # codepath after relying on this term there. But all streams in # a Zephyr realm are private, so that doesn't happen. assert(not stream.is_public()) m = re.search(r'^(?:un)*(.+?)(?:\.d)*$', stream.name, re.IGNORECASE) # Since the regex has a `.+` in it and "" is invalid as a # stream name, this will always match assert(m is not None) base_stream_name = m.group(1) matching_streams = get_active_streams(self.user_profile.realm).filter( name__iregex=r'^(un)*%s(\.d)*$' % (self._pg_re_escape(base_stream_name),)) matching_stream_ids = [matching_stream.id for matching_stream in matching_streams] recipients_map = bulk_get_recipients(Recipient.STREAM, matching_stream_ids) cond = column("recipient_id").in_([recipient.id for recipient in recipients_map.values()]) return query.where(maybe_negate(cond)) recipient = get_stream_recipient(stream.id) cond = column("recipient_id") == recipient.id return query.where(maybe_negate(cond)) def by_topic(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: if self.user_profile.realm.is_zephyr_mirror_realm: # MIT users expect narrowing to topic "foo" to also show messages to /^foo(.d)*$/ # (foo, foo.d, foo.d.d, etc) m = re.search(r'^(.*?)(?:\.d)*$', operand, re.IGNORECASE) # Since the regex has a `.*` in it, this will always match assert(m is not None) base_topic = m.group(1) # Additionally, MIT users expect the empty instance and # instance "personal" to be the same. if base_topic in ('', 'personal', '(instance "")'): cond = or_( func.upper(column("subject")) == func.upper(literal("")), func.upper(column("subject")) == func.upper(literal(".d")), func.upper(column("subject")) == func.upper(literal(".d.d")), func.upper(column("subject")) == func.upper(literal(".d.d.d")), func.upper(column("subject")) == func.upper(literal(".d.d.d.d")), func.upper(column("subject")) == func.upper(literal("personal")), func.upper(column("subject")) == func.upper(literal("personal.d")), func.upper(column("subject")) == func.upper(literal("personal.d.d")), func.upper(column("subject")) == func.upper(literal("personal.d.d.d")), func.upper(column("subject")) == func.upper(literal("personal.d.d.d.d")), func.upper(column("subject")) == func.upper(literal('(instance "")')), func.upper(column("subject")) == func.upper(literal('(instance "").d')), func.upper(column("subject")) == func.upper(literal('(instance "").d.d')), func.upper(column("subject")) == func.upper(literal('(instance "").d.d.d')), func.upper(column("subject")) == func.upper(literal('(instance "").d.d.d.d')), ) else: # We limit `.d` counts, since postgres has much better # query planning for this than they do for a regular # expression (which would sometimes table scan). cond = or_( func.upper(column("subject")) == func.upper(literal(base_topic)), func.upper(column("subject")) == func.upper(literal(base_topic + ".d")), func.upper(column("subject")) == func.upper(literal(base_topic + ".d.d")), func.upper(column("subject")) == func.upper(literal(base_topic + ".d.d.d")), func.upper(column("subject")) == func.upper(literal(base_topic + ".d.d.d.d")), ) return query.where(maybe_negate(cond)) cond = func.upper(column("subject")) == func.upper(literal(operand)) return query.where(maybe_negate(cond)) def by_sender(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: try: sender = get_user_including_cross_realm(operand, self.user_realm) except UserProfile.DoesNotExist: raise BadNarrowOperator('unknown user ' + operand) cond = column("sender_id") == literal(sender.id) return query.where(maybe_negate(cond)) def by_near(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: return query def by_id(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: cond = self.msg_id_column == literal(operand) return query.where(maybe_negate(cond)) def by_pm_with(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: if ',' in operand: # Huddle try: # Ignore our own email if it is in this list emails = [e.strip() for e in operand.split(',') if e.strip() != self.user_profile.email] recipient = recipient_for_emails(emails, False, self.user_profile, self.user_profile) except ValidationError: raise BadNarrowOperator('unknown recipient ' + operand) cond = column("recipient_id") == recipient.id return query.where(maybe_negate(cond)) else: # Personal message self_recipient = get_personal_recipient(self.user_profile.id) if operand == self.user_profile.email: # Personals with self cond = and_(column("sender_id") == self.user_profile.id, column("recipient_id") == self_recipient.id) return query.where(maybe_negate(cond)) # Personals with other user; include both directions. try: narrow_profile = get_user_including_cross_realm(operand, self.user_realm) except UserProfile.DoesNotExist: raise BadNarrowOperator('unknown user ' + operand) narrow_recipient = get_personal_recipient(narrow_profile.id) cond = or_(and_(column("sender_id") == narrow_profile.id, column("recipient_id") == self_recipient.id), and_(column("sender_id") == self.user_profile.id, column("recipient_id") == narrow_recipient.id)) return query.where(maybe_negate(cond)) def by_group_pm_with(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: try: narrow_profile = get_user_including_cross_realm(operand, self.user_realm) except UserProfile.DoesNotExist: raise BadNarrowOperator('unknown user ' + operand) self_recipient_ids = [ recipient_tuple['recipient_id'] for recipient_tuple in Subscription.objects.filter( user_profile=self.user_profile, recipient__type=Recipient.HUDDLE ).values("recipient_id")] narrow_recipient_ids = [ recipient_tuple['recipient_id'] for recipient_tuple in Subscription.objects.filter( user_profile=narrow_profile, recipient__type=Recipient.HUDDLE ).values("recipient_id")] recipient_ids = set(self_recipient_ids) & set(narrow_recipient_ids) cond = column("recipient_id").in_(recipient_ids) return query.where(maybe_negate(cond)) def by_search(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: if settings.USING_PGROONGA: return self._by_search_pgroonga(query, operand, maybe_negate) else: return self._by_search_tsearch(query, operand, maybe_negate) def _by_search_pgroonga(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: match_positions_character = func.pgroonga.match_positions_character query_extract_keywords = func.pgroonga.query_extract_keywords keywords = query_extract_keywords(operand) query = query.column(match_positions_character(column("rendered_content"), keywords).label("content_matches")) query = query.column(match_positions_character(column("subject"), keywords).label("subject_matches")) condition = column("search_pgroonga").op("@@")(operand) return query.where(maybe_negate(condition)) def _by_search_tsearch(self, query: Query, operand: str, maybe_negate: ConditionTransform) -> Query: tsquery = func.plainto_tsquery(literal("zulip.english_us_search"), literal(operand)) ts_locs_array = func.ts_match_locs_array query = query.column(ts_locs_array(literal("zulip.english_us_search"), column("rendered_content"), tsquery).label("content_matches")) # We HTML-escape the subject in Postgres to avoid doing a server round-trip query = query.column(ts_locs_array(literal("zulip.english_us_search"), func.escape_html(column("subject")), tsquery).label("subject_matches")) # Do quoted string matching. We really want phrase # search here so we can ignore punctuation and do # stemming, but there isn't a standard phrase search # mechanism in Postgres for term in re.findall('"[^"]+"|\S+', operand): if term[0] == '"' and term[-1] == '"': term = term[1:-1] term = '%' + connection.ops.prep_for_like_query(term) + '%' cond = or_(column("content").ilike(term), column("subject").ilike(term)) query = query.where(maybe_negate(cond)) cond = column("search_tsvector").op("@@")(tsquery) return query.where(maybe_negate(cond)) # The offsets we get from PGroonga are counted in characters # whereas the offsets from tsearch_extras are in bytes, so we # have to account for both cases in the logic below. def highlight_string(text: Text, locs: Iterable[Tuple[int, int]]) -> Text: highlight_start = u'<span class="highlight">' highlight_stop = u'</span>' pos = 0 result = '' in_tag = False text_utf8 = text.encode('utf8') for loc in locs: (offset, length) = loc # These indexes are in byte space for tsearch, # and they are in string space for pgroonga. prefix_start = pos prefix_end = offset match_start = offset match_end = offset + length if settings.USING_PGROONGA: prefix = text[prefix_start:prefix_end] match = text[match_start:match_end] else: prefix = text_utf8[prefix_start:prefix_end].decode() match = text_utf8[match_start:match_end].decode() for character in (prefix + match): if character == '<': in_tag = True elif character == '>': in_tag = False if in_tag: result += prefix result += match else: result += prefix result += highlight_start result += match result += highlight_stop pos = match_end if settings.USING_PGROONGA: final_frag = text[pos:] else: final_frag = text_utf8[pos:].decode() result += final_frag return result def get_search_fields(rendered_content: Text, subject: Text, content_matches: Iterable[Tuple[int, int]], subject_matches: Iterable[Tuple[int, int]]) -> Dict[str, Text]: return dict(match_content=highlight_string(rendered_content, content_matches), match_subject=highlight_string(escape_html(subject), subject_matches)) def narrow_parameter(json: str) -> Optional[List[Dict[str, Any]]]: data = ujson.loads(json) if not isinstance(data, list): raise ValueError("argument is not a list") if len(data) == 0: # The "empty narrow" should be None, and not [] return None def convert_term(elem: Union[Dict[str, Any], List[str]]) -> Dict[str, Any]: # We have to support a legacy tuple format. if isinstance(elem, list): if (len(elem) != 2 or any(not isinstance(x, str) and not isinstance(x, Text) for x in elem)): raise ValueError("element is not a string pair") return dict(operator=elem[0], operand=elem[1]) if isinstance(elem, dict): validator = check_dict([ ('operator', check_string), ('operand', check_string), ]) error = validator('elem', elem) if error: raise JsonableError(error) # whitelist the fields we care about for now return dict( operator=elem['operator'], operand=elem['operand'], negated=elem.get('negated', False), ) raise ValueError("element is not a dictionary") return list(map(convert_term, data)) def ok_to_include_history(narrow: Optional[Iterable[Dict[str, Any]]], realm: Realm) -> bool: # There are occasions where we need to find Message rows that # have no corresponding UserMessage row, because the user is # reading a public stream that might include messages that # were sent while the user was not subscribed, but which they are # allowed to see. We have to be very careful about constructing # queries in those situations, so this function should return True # only if we are 100% sure that we're gonna add a clause to the # query that narrows to a particular public stream on the user's realm. # If we screw this up, then we can get into a nasty situation of # polluting our narrow results with messages from other realms. include_history = False if narrow is not None: for term in narrow: if term['operator'] == "stream" and not term.get('negated', False): if is_public_stream_by_name(term['operand'], realm): include_history = True # Disable historical messages if the user is narrowing on anything # that's a property on the UserMessage table. There cannot be # historical messages in these cases anyway. for term in narrow: if term['operator'] == "is": include_history = False return include_history def get_stream_name_from_narrow(narrow: Optional[Iterable[Dict[str, Any]]]) -> Optional[Text]: if narrow is not None: for term in narrow: if term['operator'] == 'stream': return term['operand'].lower() return None def exclude_muting_conditions(user_profile: UserProfile, narrow: Optional[Iterable[Dict[str, Any]]]) -> List[Selectable]: conditions = [] stream_name = get_stream_name_from_narrow(narrow) stream_id = None if stream_name is not None: try: # Note that this code works around a lint rule that # says we should use access_stream_by_name to get the # stream. It is okay here, because we are only using # the stream id to exclude data, not to include results. stream_id = get_stream(stream_name, user_profile.realm).id except Stream.DoesNotExist: pass if stream_id is None: rows = Subscription.objects.filter( user_profile=user_profile, active=True, in_home_view=False, recipient__type=Recipient.STREAM ).values('recipient_id') muted_recipient_ids = [row['recipient_id'] for row in rows] if len(muted_recipient_ids) > 0: # Only add the condition if we have muted streams to simplify/avoid warnings. condition = not_(column("recipient_id").in_(muted_recipient_ids)) conditions.append(condition) conditions = exclude_topic_mutes(conditions, user_profile, stream_id) return conditions @has_request_variables def get_messages_backend(request: HttpRequest, user_profile: UserProfile, anchor: int=REQ(converter=int), num_before: int=REQ(converter=to_non_negative_int), num_after: int=REQ(converter=to_non_negative_int), narrow: Optional[List[Dict[str, Any]]]=REQ('narrow', converter=narrow_parameter, default=None), use_first_unread_anchor: bool=REQ(validator=check_bool, default=False), client_gravatar: bool=REQ(validator=check_bool, default=False), apply_markdown: bool=REQ(validator=check_bool, default=True)) -> HttpResponse: include_history = ok_to_include_history(narrow, user_profile.realm) if include_history and not use_first_unread_anchor: # The initial query in this case doesn't use `zerver_usermessage`, # and isn't yet limited to messages the user is entitled to see! # # This is OK only because we've made sure this is a narrow that # will cause us to limit the query appropriately later. # See `ok_to_include_history` for details. query = select([column("id").label("message_id")], None, table("zerver_message")) inner_msg_id_col = literal_column("zerver_message.id") elif narrow is None and not use_first_unread_anchor: # This is limited to messages the user received, as recorded in `zerver_usermessage`. query = select([column("message_id"), column("flags")], column("user_profile_id") == literal(user_profile.id), table("zerver_usermessage")) inner_msg_id_col = column("message_id") else: # This is limited to messages the user received, as recorded in `zerver_usermessage`. # TODO: Don't do this join if we're not doing a search query = select([column("message_id"), column("flags")], column("user_profile_id") == literal(user_profile.id), join(table("zerver_usermessage"), table("zerver_message"), literal_column("zerver_usermessage.message_id") == literal_column("zerver_message.id"))) inner_msg_id_col = column("message_id") first_visible_message_id = get_first_visible_message_id(user_profile.realm) query = query.where(inner_msg_id_col >= first_visible_message_id) num_extra_messages = 1 is_search = False if narrow is not None: # Add some metadata to our logging data for narrows verbose_operators = [] for term in narrow: if term['operator'] == "is": verbose_operators.append("is:" + term['operand']) else: verbose_operators.append(term['operator']) request._log_data['extra'] = "[%s]" % (",".join(verbose_operators),) # Build the query for the narrow num_extra_messages = 0 builder = NarrowBuilder(user_profile, inner_msg_id_col) search_term = {} # type: Dict[str, Any] for term in narrow: if term['operator'] == 'search': if not is_search: search_term = term query = query.column(column("subject")).column(column("rendered_content")) is_search = True else: # Join the search operators if there are multiple of them search_term['operand'] += ' ' + term['operand'] else: query = builder.add_term(query, term) if is_search: query = builder.add_term(query, search_term) # We add 1 to the number of messages requested if no narrow was # specified to ensure that the resulting list always contains the # anchor message. If a narrow was specified, the anchor message # might not match the narrow anyway. if num_after != 0: num_after += num_extra_messages else: num_before += num_extra_messages sa_conn = get_sqlalchemy_connection() if use_first_unread_anchor: condition = column("flags").op("&")(UserMessage.flags.read.mask) == 0 # We exclude messages on muted topics when finding the first unread # message in this narrow muting_conditions = exclude_muting_conditions(user_profile, narrow) if muting_conditions: condition = and_(condition, *muting_conditions) # The mobile app uses narrow=[] and use_first_unread_anchor=True to # determine what messages to show when you first load the app. # Unfortunately, this means that if you have a years-old unread # message, the mobile app could get stuck in the past. # # To fix this, we enforce that the "first unread anchor" must be on or # after the user's current pointer location. Since the pointer # location refers to the latest the user has read in the home view, # we'll only apply this logic in the home view (ie, when narrow is # empty). if not narrow: pointer_condition = inner_msg_id_col >= user_profile.pointer condition = and_(condition, pointer_condition) first_unread_query = query.where(condition) first_unread_query = first_unread_query.order_by(inner_msg_id_col.asc()).limit(1) first_unread_result = list(sa_conn.execute(first_unread_query).fetchall()) if len(first_unread_result) > 0: anchor = first_unread_result[0][0] else: anchor = LARGER_THAN_MAX_MESSAGE_ID before_query = None after_query = None if num_before != 0: before_anchor = anchor if num_after != 0: # Don't include the anchor in both the before query and the after query before_anchor = anchor - 1 before_query = query.where(inner_msg_id_col <= before_anchor) \ .order_by(inner_msg_id_col.desc()).limit(num_before) if num_after != 0: after_query = query.where(inner_msg_id_col >= anchor) \ .order_by(inner_msg_id_col.asc()).limit(num_after) if anchor == LARGER_THAN_MAX_MESSAGE_ID: # There's no need for an after_query if we're targeting just the target message. after_query = None if before_query is not None: if after_query is not None: query = union_all(before_query.self_group(), after_query.self_group()) else: query = before_query elif after_query is not None: query = after_query else: # This can happen when a narrow is specified. query = query.where(inner_msg_id_col == anchor) main_query = alias(query) query = select(main_query.c, None, main_query).order_by(column("message_id").asc()) # This is a hack to tag the query we use for testing query = query.prefix_with("/* get_messages */") query_result = list(sa_conn.execute(query).fetchall()) # The following is a little messy, but ensures that the code paths # are similar regardless of the value of include_history. The # 'user_messages' dictionary maps each message to the user's # UserMessage object for that message, which we will attach to the # rendered message dict before returning it. We attempt to # bulk-fetch rendered message dicts from remote cache using the # 'messages' list. message_ids = [] # type: List[int] user_message_flags = {} # type: Dict[int, List[str]] if include_history: message_ids = [row[0] for row in query_result] # TODO: This could be done with an outer join instead of two queries um_rows = UserMessage.objects.filter(user_profile=user_profile, message__id__in=message_ids) user_message_flags = {um.message_id: um.flags_list() for um in um_rows} for message_id in message_ids: if message_id not in user_message_flags: user_message_flags[message_id] = ["read", "historical"] else: for row in query_result: message_id = row[0] flags = row[1] user_message_flags[message_id] = UserMessage.flags_list_for_flags(flags) message_ids.append(message_id) search_fields = dict() # type: Dict[int, Dict[str, Text]] if is_search: for row in query_result: message_id = row[0] (subject, rendered_content, content_matches, subject_matches) = row[-4:] try: search_fields[message_id] = get_search_fields(rendered_content, subject, content_matches, subject_matches) except UnicodeDecodeError as err: # nocoverage # No coverage for this block since it should be # impossible, and we plan to remove it once we've # debugged the case that makes it happen. raise Exception(str(err), message_id, search_term) message_list = messages_for_ids( message_ids=message_ids, user_message_flags=user_message_flags, search_fields=search_fields, apply_markdown=apply_markdown, client_gravatar=client_gravatar, allow_edit_history=user_profile.realm.allow_edit_history, ) statsd.incr('loaded_old_messages', len(message_list)) ret = {'messages': message_list, "result": "success", "msg": ""} return json_success(ret) @has_request_variables def update_message_flags(request: HttpRequest, user_profile: UserProfile, messages: List[int]=REQ(validator=check_list(check_int)), operation: Text=REQ('op'), flag: Text=REQ()) -> HttpResponse: count = do_update_message_flags(user_profile, operation, flag, messages) target_count_str = str(len(messages)) log_data_str = "[%s %s/%s] actually %s" % (operation, flag, target_count_str, count) request._log_data["extra"] = log_data_str return json_success({'result': 'success', 'messages': messages, 'msg': ''}) @has_request_variables def mark_all_as_read(request: HttpRequest, user_profile: UserProfile) -> HttpResponse: count = do_mark_all_as_read(user_profile) log_data_str = "[%s updated]" % (count,) request._log_data["extra"] = log_data_str return json_success({'result': 'success', 'msg': ''}) @has_request_variables def mark_stream_as_read(request: HttpRequest, user_profile: UserProfile, stream_id: int=REQ(validator=check_int)) -> HttpResponse: stream, recipient, sub = access_stream_by_id(user_profile, stream_id) count = do_mark_stream_messages_as_read(user_profile, stream) log_data_str = "[%s updated]" % (count,) request._log_data["extra"] = log_data_str return json_success({'result': 'success', 'msg': ''}) @has_request_variables def mark_topic_as_read(request: HttpRequest, user_profile: UserProfile, stream_id: int=REQ(validator=check_int), topic_name: Text=REQ()) -> HttpResponse: stream, recipient, sub = access_stream_by_id(user_profile, stream_id) if topic_name: topic_exists = UserMessage.objects.filter(user_profile=user_profile, message__recipient=recipient, message__subject__iexact=topic_name).exists() if not topic_exists: raise JsonableError(_('No such topic \'%s\'') % (topic_name,)) count = do_mark_stream_messages_as_read(user_profile, stream, topic_name) log_data_str = "[%s updated]" % (count,) request._log_data["extra"] = log_data_str return json_success({'result': 'success', 'msg': ''}) def create_mirrored_message_users(request: HttpRequest, user_profile: UserProfile, recipients: Iterable[Text]) -> Tuple[bool, Optional[UserProfile]]: if "sender" not in request.POST: return (False, None) sender_email = request.POST["sender"].strip().lower() referenced_users = set([sender_email]) if request.POST['type'] == 'private': for email in recipients: referenced_users.add(email.lower()) if request.client.name == "zephyr_mirror": user_check = same_realm_zephyr_user fullname_function = compute_mit_user_fullname elif request.client.name == "irc_mirror": user_check = same_realm_irc_user fullname_function = compute_irc_user_fullname elif request.client.name in ("jabber_mirror", "JabberMirror"): user_check = same_realm_jabber_user fullname_function = compute_jabber_user_fullname else: # Unrecognized mirroring client return (False, None) for email in referenced_users: # Check that all referenced users are in our realm: if not user_check(user_profile, email): return (False, None) # Create users for the referenced users, if needed. for email in referenced_users: create_mirror_user_if_needed(user_profile.realm, email, fullname_function) sender = get_user_including_cross_realm(sender_email, user_profile.realm) return (True, sender) def same_realm_zephyr_user(user_profile: UserProfile, email: Text) -> bool: # # Are the sender and recipient both addresses in the same Zephyr # mirroring realm? We have to handle this specially, inferring # the domain from the e-mail address, because the recipient may # not existing in Zulip and we may need to make a stub Zephyr # mirroring user on the fly. try: validators.validate_email(email) except ValidationError: return False domain = email_to_domain(email) # Assumes allow_subdomains=False for all RealmDomain's corresponding to # these realms. return user_profile.realm.is_zephyr_mirror_realm and \ RealmDomain.objects.filter(realm=user_profile.realm, domain=domain).exists() def same_realm_irc_user(user_profile: UserProfile, email: Text) -> bool: # Check whether the target email address is an IRC user in the # same realm as user_profile, i.e. if the domain were example.com, # the IRC user would need to be username@irc.example.com try: validators.validate_email(email) except ValidationError: return False domain = email_to_domain(email).replace("irc.", "") # Assumes allow_subdomains=False for all RealmDomain's corresponding to # these realms. return RealmDomain.objects.filter(realm=user_profile.realm, domain=domain).exists() def same_realm_jabber_user(user_profile: UserProfile, email: Text) -> bool: try: validators.validate_email(email) except ValidationError: return False # If your Jabber users have a different email domain than the # Zulip users, this is where you would do any translation. domain = email_to_domain(email) # Assumes allow_subdomains=False for all RealmDomain's corresponding to # these realms. return RealmDomain.objects.filter(realm=user_profile.realm, domain=domain).exists() # We do not @require_login for send_message_backend, since it is used # both from the API and the web service. Code calling # send_message_backend should either check the API key or check that # the user is logged in. @has_request_variables def send_message_backend(request: HttpRequest, user_profile: UserProfile, message_type_name: Text=REQ('type'), message_to: List[Text]=REQ('to', converter=extract_recipients, default=[]), forged: bool=REQ(default=False), topic_name: Optional[Text]=REQ('subject', lambda x: x.strip(), None), message_content: Text=REQ('content'), realm_str: Optional[Text]=REQ('realm_str', default=None), local_id: Optional[Text]=REQ(default=None), queue_id: Optional[Text]=REQ(default=None)) -> HttpResponse: client = request.client is_super_user = request.user.is_api_super_user if forged and not is_super_user: return json_error(_("User not authorized for this query")) realm = None if realm_str and realm_str != user_profile.realm.string_id: if not is_super_user: # The email gateway bot needs to be able to send messages in # any realm. return json_error(_("User not authorized for this query")) realm = get_realm(realm_str) if not realm: return json_error(_("Unknown realm %s") % (realm_str,)) if client.name in ["zephyr_mirror", "irc_mirror", "jabber_mirror", "JabberMirror"]: # Here's how security works for mirroring: # # For private messages, the message must be (1) both sent and # received exclusively by users in your realm, and (2) # received by the forwarding user. # # For stream messages, the message must be (1) being forwarded # by an API superuser for your realm and (2) being sent to a # mirrored stream. # # The security checks are split between the below code # (especially create_mirrored_message_users which checks the # same-realm constraint) and recipient_for_emails (which # checks that PMs are received by the forwarding user) if "sender" not in request.POST: return json_error(_("Missing sender")) if message_type_name != "private" and not is_super_user: return json_error(_("User not authorized for this query")) (valid_input, mirror_sender) = \ create_mirrored_message_users(request, user_profile, message_to) if not valid_input: return json_error(_("Invalid mirrored message")) if client.name == "zephyr_mirror" and not user_profile.realm.is_zephyr_mirror_realm: return json_error(_("Invalid mirrored realm")) sender = mirror_sender else: sender = user_profile ret = check_send_message(sender, client, message_type_name, message_to, topic_name, message_content, forged=forged, forged_timestamp = request.POST.get('time'), forwarder_user_profile=user_profile, realm=realm, local_id=local_id, sender_queue_id=queue_id) return json_success({"id": ret}) def fill_edit_history_entries(message_history: List[Dict[str, Any]], message: Message) -> None: """This fills out the message edit history entries from the database, which are designed to have the minimum data possible, to instead have the current topic + content as of that time, plus data on whatever changed. This makes it much simpler to do future processing. Note that this mutates what is passed to it, which is sorta a bad pattern. """ prev_content = message.content prev_rendered_content = message.rendered_content prev_topic = message.subject assert(datetime_to_timestamp(message.last_edit_time) == message_history[0]['timestamp']) for entry in message_history: entry['topic'] = prev_topic if 'prev_subject' in entry: # We replace use of 'subject' with 'topic' for downstream simplicity prev_topic = entry['prev_subject'] entry['prev_topic'] = prev_topic del entry['prev_subject'] entry['content'] = prev_content entry['rendered_content'] = prev_rendered_content if 'prev_content' in entry: del entry['prev_rendered_content_version'] prev_content = entry['prev_content'] prev_rendered_content = entry['prev_rendered_content'] entry['content_html_diff'] = highlight_html_differences( prev_rendered_content, entry['rendered_content'], message.id) message_history.append(dict( topic = prev_topic, content = prev_content, rendered_content = prev_rendered_content, timestamp = datetime_to_timestamp(message.pub_date), user_id = message.sender_id, )) @has_request_variables def get_message_edit_history(request: HttpRequest, user_profile: UserProfile, message_id: int=REQ(converter=to_non_negative_int)) -> HttpResponse: if not user_profile.realm.allow_edit_history: return json_error(_("Message edit history is disabled in this organization")) message, ignored_user_message = access_message(user_profile, message_id) # Extract the message edit history from the message message_edit_history = ujson.loads(message.edit_history) # Fill in all the extra data that will make it usable fill_edit_history_entries(message_edit_history, message) return json_success({"message_history": reversed(message_edit_history)}) @has_request_variables def update_message_backend(request: HttpRequest, user_profile: UserMessage, message_id: int=REQ(converter=to_non_negative_int), subject: Optional[Text]=REQ(default=None), propagate_mode: Optional[str]=REQ(default="change_one"), content: Optional[Text]=REQ(default=None)) -> HttpResponse: if not user_profile.realm.allow_message_editing: return json_error(_("Your organization has turned off message editing")) message, ignored_user_message = access_message(user_profile, message_id) # You only have permission to edit a message if: # you change this value also change those two parameters in message_edit.js. # 1. You sent it, OR: # 2. This is a topic-only edit for a (no topic) message, OR: # 3. This is a topic-only edit and you are an admin. if message.sender == user_profile: pass elif (content is None) and ((message.topic_name() == "(no topic)") or user_profile.is_realm_admin): pass else: raise JsonableError(_("You don't have permission to edit this message")) # If there is a change to the content, check that it hasn't been too long # Allow an extra 20 seconds since we potentially allow editing 15 seconds # past the limit, and in case there are network issues, etc. The 15 comes # from (min_seconds_to_edit + seconds_left_buffer) in message_edit.js; if # you change this value also change those two parameters in message_edit.js. edit_limit_buffer = 20 if content is not None and user_profile.realm.message_content_edit_limit_seconds > 0: deadline_seconds = user_profile.realm.message_content_edit_limit_seconds + edit_limit_buffer if (timezone_now() - message.pub_date) > datetime.timedelta(seconds=deadline_seconds): raise JsonableError(_("The time limit for editing this message has past")) if subject is None and content is None: return json_error(_("Nothing to change")) if subject is not None: subject = subject.strip() if subject == "": raise JsonableError(_("Topic can't be empty")) rendered_content = None links_for_embed = set() # type: Set[Text] prior_mention_user_ids = set() # type: Set[int] mention_user_ids = set() # type: Set[int] if content is not None: content = content.strip() if content == "": content = "(deleted)" content = truncate_body(content) user_info = get_user_info_for_message_updates(message.id) prior_mention_user_ids = user_info['mention_user_ids'] # We render the message using the current user's realm; since # the cross-realm bots never edit messages, this should be # always correct. # Note: If rendering fails, the called code will raise a JsonableError. rendered_content = render_incoming_message(message, content, user_info['message_user_ids'], user_profile.realm) links_for_embed |= message.links_for_preview mention_user_ids = message.mentions_user_ids number_changed = do_update_message(user_profile, message, subject, propagate_mode, content, rendered_content, prior_mention_user_ids, mention_user_ids) # Include the number of messages changed in the logs request._log_data['extra'] = "[%s]" % (number_changed,) if links_for_embed and bugdown.url_embed_preview_enabled_for_realm(message): event_data = { 'message_id': message.id, 'message_content': message.content, # The choice of `user_profile.realm_id` rather than # `sender.realm_id` must match the decision made in the # `render_incoming_message` call earlier in this function. 'message_realm_id': user_profile.realm_id, 'urls': links_for_embed} queue_json_publish('embed_links', event_data) return json_success() @has_request_variables def delete_message_backend(request: HttpRequest, user_profile: UserProfile, message_id: int=REQ(converter=to_non_negative_int)) -> HttpResponse: message, ignored_user_message = access_message(user_profile, message_id) is_user_allowed_to_delete_message = user_profile.is_realm_admin or \ (message.sender == user_profile and user_profile.realm.allow_message_deleting) if not is_user_allowed_to_delete_message: raise JsonableError(_("You don't have permission to edit this message")) do_delete_message(user_profile, message) return json_success() @has_request_variables def json_fetch_raw_message(request: HttpRequest, user_profile: UserProfile, message_id: int=REQ(converter=to_non_negative_int)) -> HttpResponse: (message, user_message) = access_message(user_profile, message_id) return json_success({"raw_content": message.content}) @has_request_variables def render_message_backend(request: HttpRequest, user_profile: UserProfile, content: Text=REQ()) -> HttpResponse: message = Message() message.sender = user_profile message.content = content message.sending_client = request.client rendered_content = render_markdown(message, content, realm=user_profile.realm) return json_success({"rendered": rendered_content}) @has_request_variables def messages_in_narrow_backend(request: HttpRequest, user_profile: UserProfile, msg_ids: List[int]=REQ(validator=check_list(check_int)), narrow: Optional[List[Dict[str, Any]]]=REQ(converter=narrow_parameter) ) -> HttpResponse: first_visible_message_id = get_first_visible_message_id(user_profile.realm) msg_ids = [message_id for message_id in msg_ids if message_id >= first_visible_message_id] # This query is limited to messages the user has access to because they # actually received them, as reflected in `zerver_usermessage`. query = select([column("message_id"), column("subject"), column("rendered_content")], and_(column("user_profile_id") == literal(user_profile.id), column("message_id").in_(msg_ids)), join(table("zerver_usermessage"), table("zerver_message"), literal_column("zerver_usermessage.message_id") == literal_column("zerver_message.id"))) builder = NarrowBuilder(user_profile, column("message_id")) if narrow is not None: for term in narrow: query = builder.add_term(query, term) sa_conn = get_sqlalchemy_connection() query_result = list(sa_conn.execute(query).fetchall()) search_fields = dict() for row in query_result: message_id = row['message_id'] subject = row['subject'] rendered_content = row['rendered_content'] if 'content_matches' in row: content_matches = row['content_matches'] subject_matches = row['subject_matches'] search_fields[message_id] = get_search_fields(rendered_content, subject, content_matches, subject_matches) else: search_fields[message_id] = dict( match_content=rendered_content, match_subject=subject ) return json_success({"messages": search_fields})
import { createActions } from 'redux-actions' export const GET_CLASSES_REQUEST = 'GET_CLASSES_REQUEST' export const GET_CLASSES_SUCCESS = 'GET_CLASSES_SUCCESS' export const GET_CLASSES_FAILURE = 'GET_CLASSES_FAILURE' export const { getClassesRequest, getClassesSuccess, getClassesFailure } = createActions({ GET_CLASSES_REQUEST: undefined, GET_CLASSES_SUCCESS: payload => payload, GET_CLASSES_FAILURE: payload => payload })
/* * MHNodeInsertionProbability.h * * Created on: Jul 30, 2012 * Author: jchen */ #ifndef MHNODEINSERTIONPROBABILITY_H_ #define MHNODEINSERTIONPROBABILITY_H_ #include <tr1/unordered_map> class patMultiModalPath; class patRouter; class patNetworkBase; class MHWeightFunction; class patNode; class MHNodeInsertionProbability { public: MHNodeInsertionProbability(); MHNodeInsertionProbability(const patRouter* router, const patNetworkBase* network, const MHWeightFunction* MHWeight); void setParams(const patRouter* router, const patNetworkBase* network, const MHWeightFunction* MHWeight); void setPath(const patMultiModalPath* path); virtual std::tr1::unordered_map<const patNode*, double> calculate( const patNode* origin, const patNode* destination) const=0; virtual ~MHNodeInsertionProbability(); protected: const patMultiModalPath* m_path; const patRouter* m_router; const patNetworkBase* m_network; const MHWeightFunction* m_MHWeight; }; #endif /* MHNODEINSERTIONPROBABILITY_H_ */
/* * Copyright 2010, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ WebGLUtils=function(){var makeFailHTML=function(msg){return''+'<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>'+'<td align="center">'+'<div style="display: table-cell; vertical-align: middle;">'+'<div style="">'+msg+'</div>'+'</div>'+'</td></tr></table>';};var GET_A_WEBGL_BROWSER=''+'This page requires a browser that supports WebGL.<br/>'+'<a href="http://get.webgl.org">Click here to upgrade your browser.</a>';var OTHER_PROBLEM=''+"It doesn't appear your computer can support WebGL.<br/>"+'<a href="http://get.webgl.org/troubleshooting/">Click here for more information.</a>';var setupWebGL=function(canvas,opt_attribs,opt_onError){function handleCreationError(msg){var container=canvas.parentNode;if(container){var str=window.WebGLRenderingContext?OTHER_PROBLEM:GET_A_WEBGL_BROWSER;if(msg){str+="<br/><br/>Status: "+msg;} container.innerHTML=makeFailHTML(str);}};opt_onError=opt_onError||handleCreationError;if(canvas.addEventListener){canvas.addEventListener("webglcontextcreationerror",function(event){opt_onError(event.statusMessage);},false);} var context=create3DContext(canvas,opt_attribs);if(!context){if(!window.WebGLRenderingContext){opt_onError("");}} return context;};var create3DContext=function(canvas,opt_attribs){var names=["webgl","experimental-webgl","webkit-3d","moz-webgl"];var context=null;for(var ii=0;ii<names.length;++ii){try{context=canvas.getContext(names[ii],opt_attribs);}catch(e){} if(context){break;}} return context;} return{create3DContext:create3DContext,setupWebGL:setupWebGL};}();window.requestAnimFrame=(function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback,element){window.setTimeout(callback,1000/60);};})();/** * @fileoverview gl-matrix - High performance matrix and vector operations * @author Brandon Jones * @author Colin MacKenzie IV * @version 2.2.2 */ /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function(_global){"use strict";var shim={};if(typeof(exports)==='undefined'){if(typeof define=='function'&&typeof define.amd=='object'&&define.amd){shim.exports={};define(function(){return shim.exports;});}else{shim.exports=typeof(window)!=='undefined'?window:_global;}} else{shim.exports=exports;} (function(exports){if(!GLMAT_EPSILON){var GLMAT_EPSILON=0.000001;} if(!GLMAT_ARRAY_TYPE){var GLMAT_ARRAY_TYPE=(typeof Float32Array!=='undefined')?Float32Array:Array;} if(!GLMAT_RANDOM){var GLMAT_RANDOM=Math.random;} var glMatrix={};glMatrix.setMatrixArrayType=function(type){GLMAT_ARRAY_TYPE=type;} if(typeof(exports)!=='undefined'){exports.glMatrix=glMatrix;} var degree=Math.PI/180;glMatrix.toRadian=function(a){return a*degree;};var vec2={};vec2.create=function(){var out=new GLMAT_ARRAY_TYPE(2);out[0]=0;out[1]=0;return out;};vec2.clone=function(a){var out=new GLMAT_ARRAY_TYPE(2);out[0]=a[0];out[1]=a[1];return out;};vec2.fromValues=function(x,y){var out=new GLMAT_ARRAY_TYPE(2);out[0]=x;out[1]=y;return out;};vec2.copy=function(out,a){out[0]=a[0];out[1]=a[1];return out;};vec2.set=function(out,x,y){out[0]=x;out[1]=y;return out;};vec2.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];return out;};vec2.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];return out;};vec2.sub=vec2.subtract;vec2.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];return out;};vec2.mul=vec2.multiply;vec2.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];return out;};vec2.div=vec2.divide;vec2.min=function(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);return out;};vec2.max=function(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);return out;};vec2.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;return out;};vec2.scaleAndAdd=function(out,a,b,scale){out[0]=a[0]+(b[0]*scale);out[1]=a[1]+(b[1]*scale);return out;};vec2.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y);};vec2.dist=vec2.distance;vec2.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y;};vec2.sqrDist=vec2.squaredDistance;vec2.length=function(a){var x=a[0],y=a[1];return Math.sqrt(x*x+y*y);};vec2.len=vec2.length;vec2.squaredLength=function(a){var x=a[0],y=a[1];return x*x+y*y;};vec2.sqrLen=vec2.squaredLength;vec2.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];return out;};vec2.inverse=function(out,a){out[0]=1.0/a[0];out[1]=1.0/a[1];return out;};vec2.normalize=function(out,a){var x=a[0],y=a[1];var len=x*x+y*y;if(len>0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len;} return out;};vec2.dot=function(a,b){return a[0]*b[0]+a[1]*b[1];};vec2.cross=function(out,a,b){var z=a[0]*b[1]-a[1]*b[0];out[0]=out[1]=0;out[2]=z;return out;};vec2.lerp=function(out,a,b,t){var ax=a[0],ay=a[1];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);return out;};vec2.random=function(out,scale){scale=scale||1.0;var r=GLMAT_RANDOM()*2.0*Math.PI;out[0]=Math.cos(r)*scale;out[1]=Math.sin(r)*scale;return out;};vec2.transformMat2=function(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[2]*y;out[1]=m[1]*x+m[3]*y;return out;};vec2.transformMat2d=function(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[2]*y+m[4];out[1]=m[1]*x+m[3]*y+m[5];return out;};vec2.transformMat3=function(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[3]*y+m[6];out[1]=m[1]*x+m[4]*y+m[7];return out;};vec2.transformMat4=function(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[4]*y+m[12];out[1]=m[1]*x+m[5]*y+m[13];return out;};vec2.forEach=(function(){var vec=vec2.create();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=2;} if(!offset){offset=0;} if(count){l=Math.min((count*stride)+offset,a.length);}else{l=a.length;} for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];} return a;};})();vec2.str=function(a){return'vec2('+a[0]+', '+a[1]+')';};if(typeof(exports)!=='undefined'){exports.vec2=vec2;};var vec3={};vec3.create=function(){var out=new GLMAT_ARRAY_TYPE(3);out[0]=0;out[1]=0;out[2]=0;return out;};vec3.clone=function(a){var out=new GLMAT_ARRAY_TYPE(3);out[0]=a[0];out[1]=a[1];out[2]=a[2];return out;};vec3.fromValues=function(x,y,z){var out=new GLMAT_ARRAY_TYPE(3);out[0]=x;out[1]=y;out[2]=z;return out;};vec3.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];return out;};vec3.set=function(out,x,y,z){out[0]=x;out[1]=y;out[2]=z;return out;};vec3.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];return out;};vec3.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];return out;};vec3.sub=vec3.subtract;vec3.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];out[2]=a[2]*b[2];return out;};vec3.mul=vec3.multiply;vec3.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];out[2]=a[2]/b[2];return out;};vec3.div=vec3.divide;vec3.min=function(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);out[2]=Math.min(a[2],b[2]);return out;};vec3.max=function(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);out[2]=Math.max(a[2],b[2]);return out;};vec3.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;return out;};vec3.scaleAndAdd=function(out,a,b,scale){out[0]=a[0]+(b[0]*scale);out[1]=a[1]+(b[1]*scale);out[2]=a[2]+(b[2]*scale);return out;};vec3.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z);};vec3.dist=vec3.distance;vec3.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z;};vec3.sqrDist=vec3.squaredDistance;vec3.length=function(a){var x=a[0],y=a[1],z=a[2];return Math.sqrt(x*x+y*y+z*z);};vec3.len=vec3.length;vec3.squaredLength=function(a){var x=a[0],y=a[1],z=a[2];return x*x+y*y+z*z;};vec3.sqrLen=vec3.squaredLength;vec3.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];return out;};vec3.inverse=function(out,a){out[0]=1.0/a[0];out[1]=1.0/a[1];out[2]=1.0/a[2];return out;};vec3.normalize=function(out,a){var x=a[0],y=a[1],z=a[2];var len=x*x+y*y+z*z;if(len>0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len;out[2]=a[2]*len;} return out;};vec3.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2];};vec3.cross=function(out,a,b){var ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];out[0]=ay*bz-az*by;out[1]=az*bx-ax*bz;out[2]=ax*by-ay*bx;return out;};vec3.lerp=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);return out;};vec3.random=function(out,scale){scale=scale||1.0;var r=GLMAT_RANDOM()*2.0*Math.PI;var z=(GLMAT_RANDOM()*2.0)-1.0;var zScale=Math.sqrt(1.0-z*z)*scale;out[0]=Math.cos(r)*zScale;out[1]=Math.sin(r)*zScale;out[2]=z*scale;return out;};vec3.transformMat4=function(out,a,m){var x=a[0],y=a[1],z=a[2],w=m[3]*x+m[7]*y+m[11]*z+m[15];w=w||1.0;out[0]=(m[0]*x+m[4]*y+m[8]*z+m[12])/w;out[1]=(m[1]*x+m[5]*y+m[9]*z+m[13])/w;out[2]=(m[2]*x+m[6]*y+m[10]*z+m[14])/w;return out;};vec3.transformMat3=function(out,a,m){var x=a[0],y=a[1],z=a[2];out[0]=x*m[0]+y*m[3]+z*m[6];out[1]=x*m[1]+y*m[4]+z*m[7];out[2]=x*m[2]+y*m[5]+z*m[8];return out;};vec3.transformQuat=function(out,a,q){var x=a[0],y=a[1],z=a[2],qx=q[0],qy=q[1],qz=q[2],qw=q[3],ix=qw*x+qy*z-qz*y,iy=qw*y+qz*x-qx*z,iz=qw*z+qx*y-qy*x,iw=-qx*x-qy*y-qz*z;out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;return out;};vec3.rotateX=function(out,a,b,c){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[0];r[1]=p[1]*Math.cos(c)-p[2]*Math.sin(c);r[2]=p[1]*Math.sin(c)+p[2]*Math.cos(c);out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out;};vec3.rotateY=function(out,a,b,c){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[2]*Math.sin(c)+p[0]*Math.cos(c);r[1]=p[1];r[2]=p[2]*Math.cos(c)-p[0]*Math.sin(c);out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out;};vec3.rotateZ=function(out,a,b,c){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[0]*Math.cos(c)-p[1]*Math.sin(c);r[1]=p[0]*Math.sin(c)+p[1]*Math.cos(c);r[2]=p[2];out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out;};vec3.forEach=(function(){var vec=vec3.create();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=3;} if(!offset){offset=0;} if(count){l=Math.min((count*stride)+offset,a.length);}else{l=a.length;} for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];vec[2]=a[i+2];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];a[i+2]=vec[2];} return a;};})();vec3.str=function(a){return'vec3('+a[0]+', '+a[1]+', '+a[2]+')';};if(typeof(exports)!=='undefined'){exports.vec3=vec3;};var vec4={};vec4.create=function(){var out=new GLMAT_ARRAY_TYPE(4);out[0]=0;out[1]=0;out[2]=0;out[3]=0;return out;};vec4.clone=function(a){var out=new GLMAT_ARRAY_TYPE(4);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out;};vec4.fromValues=function(x,y,z,w){var out=new GLMAT_ARRAY_TYPE(4);out[0]=x;out[1]=y;out[2]=z;out[3]=w;return out;};vec4.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out;};vec4.set=function(out,x,y,z,w){out[0]=x;out[1]=y;out[2]=z;out[3]=w;return out;};vec4.add=function(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];return out;};vec4.subtract=function(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];return out;};vec4.sub=vec4.subtract;vec4.multiply=function(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];out[2]=a[2]*b[2];out[3]=a[3]*b[3];return out;};vec4.mul=vec4.multiply;vec4.divide=function(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];out[2]=a[2]/b[2];out[3]=a[3]/b[3];return out;};vec4.div=vec4.divide;vec4.min=function(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);out[2]=Math.min(a[2],b[2]);out[3]=Math.min(a[3],b[3]);return out;};vec4.max=function(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);out[2]=Math.max(a[2],b[2]);out[3]=Math.max(a[3],b[3]);return out;};vec4.scale=function(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;return out;};vec4.scaleAndAdd=function(out,a,b,scale){out[0]=a[0]+(b[0]*scale);out[1]=a[1]+(b[1]*scale);out[2]=a[2]+(b[2]*scale);out[3]=a[3]+(b[3]*scale);return out;};vec4.distance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2],w=b[3]-a[3];return Math.sqrt(x*x+y*y+z*z+w*w);};vec4.dist=vec4.distance;vec4.squaredDistance=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2],w=b[3]-a[3];return x*x+y*y+z*z+w*w;};vec4.sqrDist=vec4.squaredDistance;vec4.length=function(a){var x=a[0],y=a[1],z=a[2],w=a[3];return Math.sqrt(x*x+y*y+z*z+w*w);};vec4.len=vec4.length;vec4.squaredLength=function(a){var x=a[0],y=a[1],z=a[2],w=a[3];return x*x+y*y+z*z+w*w;};vec4.sqrLen=vec4.squaredLength;vec4.negate=function(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=-a[3];return out;};vec4.inverse=function(out,a){out[0]=1.0/a[0];out[1]=1.0/a[1];out[2]=1.0/a[2];out[3]=1.0/a[3];return out;};vec4.normalize=function(out,a){var x=a[0],y=a[1],z=a[2],w=a[3];var len=x*x+y*y+z*z+w*w;if(len>0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len;out[2]=a[2]*len;out[3]=a[3]*len;} return out;};vec4.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3];};vec4.lerp=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2],aw=a[3];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);out[3]=aw+t*(b[3]-aw);return out;};vec4.random=function(out,scale){scale=scale||1.0;out[0]=GLMAT_RANDOM();out[1]=GLMAT_RANDOM();out[2]=GLMAT_RANDOM();out[3]=GLMAT_RANDOM();vec4.normalize(out,out);vec4.scale(out,out,scale);return out;};vec4.transformMat4=function(out,a,m){var x=a[0],y=a[1],z=a[2],w=a[3];out[0]=m[0]*x+m[4]*y+m[8]*z+m[12]*w;out[1]=m[1]*x+m[5]*y+m[9]*z+m[13]*w;out[2]=m[2]*x+m[6]*y+m[10]*z+m[14]*w;out[3]=m[3]*x+m[7]*y+m[11]*z+m[15]*w;return out;};vec4.transformQuat=function(out,a,q){var x=a[0],y=a[1],z=a[2],qx=q[0],qy=q[1],qz=q[2],qw=q[3],ix=qw*x+qy*z-qz*y,iy=qw*y+qz*x-qx*z,iz=qw*z+qx*y-qy*x,iw=-qx*x-qy*y-qz*z;out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;return out;};vec4.forEach=(function(){var vec=vec4.create();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=4;} if(!offset){offset=0;} if(count){l=Math.min((count*stride)+offset,a.length);}else{l=a.length;} for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];vec[2]=a[i+2];vec[3]=a[i+3];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];a[i+2]=vec[2];a[i+3]=vec[3];} return a;};})();vec4.str=function(a){return'vec4('+a[0]+', '+a[1]+', '+a[2]+', '+a[3]+')';};if(typeof(exports)!=='undefined'){exports.vec4=vec4;};var mat2={};mat2.create=function(){var out=new GLMAT_ARRAY_TYPE(4);out[0]=1;out[1]=0;out[2]=0;out[3]=1;return out;};mat2.clone=function(a){var out=new GLMAT_ARRAY_TYPE(4);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out;};mat2.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out;};mat2.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=1;return out;};mat2.transpose=function(out,a){if(out===a){var a1=a[1];out[1]=a[2];out[2]=a1;}else{out[0]=a[0];out[1]=a[2];out[2]=a[1];out[3]=a[3];} return out;};mat2.invert=function(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],det=a0*a3-a2*a1;if(!det){return null;} det=1.0/det;out[0]=a3*det;out[1]=-a1*det;out[2]=-a2*det;out[3]=a0*det;return out;};mat2.adjoint=function(out,a){var a0=a[0];out[0]=a[3];out[1]=-a[1];out[2]=-a[2];out[3]=a0;return out;};mat2.determinant=function(a){return a[0]*a[3]-a[2]*a[1];};mat2.multiply=function(out,a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=a0*b0+a2*b1;out[1]=a1*b0+a3*b1;out[2]=a0*b2+a2*b3;out[3]=a1*b2+a3*b3;return out;};mat2.mul=mat2.multiply;mat2.rotate=function(out,a,rad){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],s=Math.sin(rad),c=Math.cos(rad);out[0]=a0*c+a2*s;out[1]=a1*c+a3*s;out[2]=a0*-s+a2*c;out[3]=a1*-s+a3*c;return out;};mat2.scale=function(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],v0=v[0],v1=v[1];out[0]=a0*v0;out[1]=a1*v0;out[2]=a2*v1;out[3]=a3*v1;return out;};mat2.str=function(a){return'mat2('+a[0]+', '+a[1]+', '+a[2]+', '+a[3]+')';};mat2.frob=function(a){return(Math.sqrt(Math.pow(a[0],2)+Math.pow(a[1],2)+Math.pow(a[2],2)+Math.pow(a[3],2)))};mat2.LDU=function(L,D,U,a){L[2]=a[2]/a[0];U[0]=a[0];U[1]=a[1];U[3]=a[3]-L[2]*U[1];return[L,D,U];};if(typeof(exports)!=='undefined'){exports.mat2=mat2;};var mat2d={};mat2d.create=function(){var out=new GLMAT_ARRAY_TYPE(6);out[0]=1;out[1]=0;out[2]=0;out[3]=1;out[4]=0;out[5]=0;return out;};mat2d.clone=function(a){var out=new GLMAT_ARRAY_TYPE(6);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];return out;};mat2d.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];return out;};mat2d.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=1;out[4]=0;out[5]=0;return out;};mat2d.invert=function(out,a){var aa=a[0],ab=a[1],ac=a[2],ad=a[3],atx=a[4],aty=a[5];var det=aa*ad-ab*ac;if(!det){return null;} det=1.0/det;out[0]=ad*det;out[1]=-ab*det;out[2]=-ac*det;out[3]=aa*det;out[4]=(ac*aty-ad*atx)*det;out[5]=(ab*atx-aa*aty)*det;return out;};mat2d.determinant=function(a){return a[0]*a[3]-a[1]*a[2];};mat2d.multiply=function(out,a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5];out[0]=a0*b0+a2*b1;out[1]=a1*b0+a3*b1;out[2]=a0*b2+a2*b3;out[3]=a1*b2+a3*b3;out[4]=a0*b4+a2*b5+a4;out[5]=a1*b4+a3*b5+a5;return out;};mat2d.mul=mat2d.multiply;mat2d.rotate=function(out,a,rad){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],s=Math.sin(rad),c=Math.cos(rad);out[0]=a0*c+a2*s;out[1]=a1*c+a3*s;out[2]=a0*-s+a2*c;out[3]=a1*-s+a3*c;out[4]=a4;out[5]=a5;return out;};mat2d.scale=function(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],v0=v[0],v1=v[1];out[0]=a0*v0;out[1]=a1*v0;out[2]=a2*v1;out[3]=a3*v1;out[4]=a4;out[5]=a5;return out;};mat2d.translate=function(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],v0=v[0],v1=v[1];out[0]=a0;out[1]=a1;out[2]=a2;out[3]=a3;out[4]=a0*v0+a2*v1+a4;out[5]=a1*v0+a3*v1+a5;return out;};mat2d.str=function(a){return'mat2d('+a[0]+', '+a[1]+', '+a[2]+', '+ a[3]+', '+a[4]+', '+a[5]+')';};mat2d.frob=function(a){return(Math.sqrt(Math.pow(a[0],2)+Math.pow(a[1],2)+Math.pow(a[2],2)+Math.pow(a[3],2)+Math.pow(a[4],2)+Math.pow(a[5],2)+1))};if(typeof(exports)!=='undefined'){exports.mat2d=mat2d;};var mat3={};mat3.create=function(){var out=new GLMAT_ARRAY_TYPE(9);out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=1;out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out;};mat3.fromMat4=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[4];out[4]=a[5];out[5]=a[6];out[6]=a[8];out[7]=a[9];out[8]=a[10];return out;};mat3.clone=function(a){var out=new GLMAT_ARRAY_TYPE(9);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out;};mat3.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out;};mat3.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=1;out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out;};mat3.transpose=function(out,a){if(out===a){var a01=a[1],a02=a[2],a12=a[5];out[1]=a[3];out[2]=a[6];out[3]=a01;out[5]=a[7];out[6]=a02;out[7]=a12;}else{out[0]=a[0];out[1]=a[3];out[2]=a[6];out[3]=a[1];out[4]=a[4];out[5]=a[7];out[6]=a[2];out[7]=a[5];out[8]=a[8];} return out;};mat3.invert=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],b01=a22*a11-a12*a21,b11=-a22*a10+a12*a20,b21=a21*a10-a11*a20,det=a00*b01+a01*b11+a02*b21;if(!det){return null;} det=1.0/det;out[0]=b01*det;out[1]=(-a22*a01+a02*a21)*det;out[2]=(a12*a01-a02*a11)*det;out[3]=b11*det;out[4]=(a22*a00-a02*a20)*det;out[5]=(-a12*a00+a02*a10)*det;out[6]=b21*det;out[7]=(-a21*a00+a01*a20)*det;out[8]=(a11*a00-a01*a10)*det;return out;};mat3.adjoint=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8];out[0]=(a11*a22-a12*a21);out[1]=(a02*a21-a01*a22);out[2]=(a01*a12-a02*a11);out[3]=(a12*a20-a10*a22);out[4]=(a00*a22-a02*a20);out[5]=(a02*a10-a00*a12);out[6]=(a10*a21-a11*a20);out[7]=(a01*a20-a00*a21);out[8]=(a00*a11-a01*a10);return out;};mat3.determinant=function(a){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8];return a00*(a22*a11-a12*a21)+a01*(-a22*a10+a12*a20)+a02*(a21*a10-a11*a20);};mat3.multiply=function(out,a,b){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],b00=b[0],b01=b[1],b02=b[2],b10=b[3],b11=b[4],b12=b[5],b20=b[6],b21=b[7],b22=b[8];out[0]=b00*a00+b01*a10+b02*a20;out[1]=b00*a01+b01*a11+b02*a21;out[2]=b00*a02+b01*a12+b02*a22;out[3]=b10*a00+b11*a10+b12*a20;out[4]=b10*a01+b11*a11+b12*a21;out[5]=b10*a02+b11*a12+b12*a22;out[6]=b20*a00+b21*a10+b22*a20;out[7]=b20*a01+b21*a11+b22*a21;out[8]=b20*a02+b21*a12+b22*a22;return out;};mat3.mul=mat3.multiply;mat3.translate=function(out,a,v){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],x=v[0],y=v[1];out[0]=a00;out[1]=a01;out[2]=a02;out[3]=a10;out[4]=a11;out[5]=a12;out[6]=x*a00+y*a10+a20;out[7]=x*a01+y*a11+a21;out[8]=x*a02+y*a12+a22;return out;};mat3.rotate=function(out,a,rad){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],s=Math.sin(rad),c=Math.cos(rad);out[0]=c*a00+s*a10;out[1]=c*a01+s*a11;out[2]=c*a02+s*a12;out[3]=c*a10-s*a00;out[4]=c*a11-s*a01;out[5]=c*a12-s*a02;out[6]=a20;out[7]=a21;out[8]=a22;return out;};mat3.scale=function(out,a,v){var x=v[0],y=v[1];out[0]=x*a[0];out[1]=x*a[1];out[2]=x*a[2];out[3]=y*a[3];out[4]=y*a[4];out[5]=y*a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out;};mat3.fromMat2d=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=0;out[3]=a[2];out[4]=a[3];out[5]=0;out[6]=a[4];out[7]=a[5];out[8]=1;return out;};mat3.fromQuat=function(out,q){var x=q[0],y=q[1],z=q[2],w=q[3],x2=x+x,y2=y+y,z2=z+z,xx=x*x2,yx=y*x2,yy=y*y2,zx=z*x2,zy=z*y2,zz=z*z2,wx=w*x2,wy=w*y2,wz=w*z2;out[0]=1-yy-zz;out[3]=yx-wz;out[6]=zx+wy;out[1]=yx+wz;out[4]=1-xx-zz;out[7]=zy-wx;out[2]=zx-wy;out[5]=zy+wx;out[8]=1-xx-yy;return out;};mat3.normalFromMat4=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32,det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det){return null;} det=1.0/det;out[0]=(a11*b11-a12*b10+a13*b09)*det;out[1]=(a12*b08-a10*b11-a13*b07)*det;out[2]=(a10*b10-a11*b08+a13*b06)*det;out[3]=(a02*b10-a01*b11-a03*b09)*det;out[4]=(a00*b11-a02*b08+a03*b07)*det;out[5]=(a01*b08-a00*b10-a03*b06)*det;out[6]=(a31*b05-a32*b04+a33*b03)*det;out[7]=(a32*b02-a30*b05-a33*b01)*det;out[8]=(a30*b04-a31*b02+a33*b00)*det;return out;};mat3.str=function(a){return'mat3('+a[0]+', '+a[1]+', '+a[2]+', '+ a[3]+', '+a[4]+', '+a[5]+', '+ a[6]+', '+a[7]+', '+a[8]+')';};mat3.frob=function(a){return(Math.sqrt(Math.pow(a[0],2)+Math.pow(a[1],2)+Math.pow(a[2],2)+Math.pow(a[3],2)+Math.pow(a[4],2)+Math.pow(a[5],2)+Math.pow(a[6],2)+Math.pow(a[7],2)+Math.pow(a[8],2)))};if(typeof(exports)!=='undefined'){exports.mat3=mat3;};var mat4={};mat4.create=function(){var out=new GLMAT_ARRAY_TYPE(16);out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=1;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=1;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;};mat4.clone=function(a){var out=new GLMAT_ARRAY_TYPE(16);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out;};mat4.copy=function(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out;};mat4.identity=function(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=1;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=1;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;};mat4.transpose=function(out,a){if(out===a){var a01=a[1],a02=a[2],a03=a[3],a12=a[6],a13=a[7],a23=a[11];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a01;out[6]=a[9];out[7]=a[13];out[8]=a02;out[9]=a12;out[11]=a[14];out[12]=a03;out[13]=a13;out[14]=a23;}else{out[0]=a[0];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a[1];out[5]=a[5];out[6]=a[9];out[7]=a[13];out[8]=a[2];out[9]=a[6];out[10]=a[10];out[11]=a[14];out[12]=a[3];out[13]=a[7];out[14]=a[11];out[15]=a[15];} return out;};mat4.invert=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32,det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det){return null;} det=1.0/det;out[0]=(a11*b11-a12*b10+a13*b09)*det;out[1]=(a02*b10-a01*b11-a03*b09)*det;out[2]=(a31*b05-a32*b04+a33*b03)*det;out[3]=(a22*b04-a21*b05-a23*b03)*det;out[4]=(a12*b08-a10*b11-a13*b07)*det;out[5]=(a00*b11-a02*b08+a03*b07)*det;out[6]=(a32*b02-a30*b05-a33*b01)*det;out[7]=(a20*b05-a22*b02+a23*b01)*det;out[8]=(a10*b10-a11*b08+a13*b06)*det;out[9]=(a01*b08-a00*b10-a03*b06)*det;out[10]=(a30*b04-a31*b02+a33*b00)*det;out[11]=(a21*b02-a20*b04-a23*b00)*det;out[12]=(a11*b07-a10*b09-a12*b06)*det;out[13]=(a00*b09-a01*b07+a02*b06)*det;out[14]=(a31*b01-a30*b03-a32*b00)*det;out[15]=(a20*b03-a21*b01+a22*b00)*det;return out;};mat4.adjoint=function(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];out[0]=(a11*(a22*a33-a23*a32)-a21*(a12*a33-a13*a32)+a31*(a12*a23-a13*a22));out[1]=-(a01*(a22*a33-a23*a32)-a21*(a02*a33-a03*a32)+a31*(a02*a23-a03*a22));out[2]=(a01*(a12*a33-a13*a32)-a11*(a02*a33-a03*a32)+a31*(a02*a13-a03*a12));out[3]=-(a01*(a12*a23-a13*a22)-a11*(a02*a23-a03*a22)+a21*(a02*a13-a03*a12));out[4]=-(a10*(a22*a33-a23*a32)-a20*(a12*a33-a13*a32)+a30*(a12*a23-a13*a22));out[5]=(a00*(a22*a33-a23*a32)-a20*(a02*a33-a03*a32)+a30*(a02*a23-a03*a22));out[6]=-(a00*(a12*a33-a13*a32)-a10*(a02*a33-a03*a32)+a30*(a02*a13-a03*a12));out[7]=(a00*(a12*a23-a13*a22)-a10*(a02*a23-a03*a22)+a20*(a02*a13-a03*a12));out[8]=(a10*(a21*a33-a23*a31)-a20*(a11*a33-a13*a31)+a30*(a11*a23-a13*a21));out[9]=-(a00*(a21*a33-a23*a31)-a20*(a01*a33-a03*a31)+a30*(a01*a23-a03*a21));out[10]=(a00*(a11*a33-a13*a31)-a10*(a01*a33-a03*a31)+a30*(a01*a13-a03*a11));out[11]=-(a00*(a11*a23-a13*a21)-a10*(a01*a23-a03*a21)+a20*(a01*a13-a03*a11));out[12]=-(a10*(a21*a32-a22*a31)-a20*(a11*a32-a12*a31)+a30*(a11*a22-a12*a21));out[13]=(a00*(a21*a32-a22*a31)-a20*(a01*a32-a02*a31)+a30*(a01*a22-a02*a21));out[14]=-(a00*(a11*a32-a12*a31)-a10*(a01*a32-a02*a31)+a30*(a01*a12-a02*a11));out[15]=(a00*(a11*a22-a12*a21)-a10*(a01*a22-a02*a21)+a20*(a01*a12-a02*a11));return out;};mat4.determinant=function(a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;return b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;};mat4.multiply=function(out,a,b){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=b0*a00+b1*a10+b2*a20+b3*a30;out[1]=b0*a01+b1*a11+b2*a21+b3*a31;out[2]=b0*a02+b1*a12+b2*a22+b3*a32;out[3]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[4];b1=b[5];b2=b[6];b3=b[7];out[4]=b0*a00+b1*a10+b2*a20+b3*a30;out[5]=b0*a01+b1*a11+b2*a21+b3*a31;out[6]=b0*a02+b1*a12+b2*a22+b3*a32;out[7]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[8];b1=b[9];b2=b[10];b3=b[11];out[8]=b0*a00+b1*a10+b2*a20+b3*a30;out[9]=b0*a01+b1*a11+b2*a21+b3*a31;out[10]=b0*a02+b1*a12+b2*a22+b3*a32;out[11]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[12];b1=b[13];b2=b[14];b3=b[15];out[12]=b0*a00+b1*a10+b2*a20+b3*a30;out[13]=b0*a01+b1*a11+b2*a21+b3*a31;out[14]=b0*a02+b1*a12+b2*a22+b3*a32;out[15]=b0*a03+b1*a13+b2*a23+b3*a33;return out;};mat4.mul=mat4.multiply;mat4.translate=function(out,a,v){var x=v[0],y=v[1],z=v[2],a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;if(a===out){out[12]=a[0]*x+a[4]*y+a[8]*z+a[12];out[13]=a[1]*x+a[5]*y+a[9]*z+a[13];out[14]=a[2]*x+a[6]*y+a[10]*z+a[14];out[15]=a[3]*x+a[7]*y+a[11]*z+a[15];}else{a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];out[0]=a00;out[1]=a01;out[2]=a02;out[3]=a03;out[4]=a10;out[5]=a11;out[6]=a12;out[7]=a13;out[8]=a20;out[9]=a21;out[10]=a22;out[11]=a23;out[12]=a00*x+a10*y+a20*z+a[12];out[13]=a01*x+a11*y+a21*z+a[13];out[14]=a02*x+a12*y+a22*z+a[14];out[15]=a03*x+a13*y+a23*z+a[15];} return out;};mat4.scale=function(out,a,v){var x=v[0],y=v[1],z=v[2];out[0]=a[0]*x;out[1]=a[1]*x;out[2]=a[2]*x;out[3]=a[3]*x;out[4]=a[4]*y;out[5]=a[5]*y;out[6]=a[6]*y;out[7]=a[7]*y;out[8]=a[8]*z;out[9]=a[9]*z;out[10]=a[10]*z;out[11]=a[11]*z;out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out;};mat4.rotate=function(out,a,rad,axis){var x=axis[0],y=axis[1],z=axis[2],len=Math.sqrt(x*x+y*y+z*z),s,c,t,a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23,b00,b01,b02,b10,b11,b12,b20,b21,b22;if(Math.abs(len)<GLMAT_EPSILON){return null;} len=1/len;x*=len;y*=len;z*=len;s=Math.sin(rad);c=Math.cos(rad);t=1-c;a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];b00=x*x*t+c;b01=y*x*t+z*s;b02=z*x*t-y*s;b10=x*y*t-z*s;b11=y*y*t+c;b12=z*y*t+x*s;b20=x*z*t+y*s;b21=y*z*t-x*s;b22=z*z*t+c;out[0]=a00*b00+a10*b01+a20*b02;out[1]=a01*b00+a11*b01+a21*b02;out[2]=a02*b00+a12*b01+a22*b02;out[3]=a03*b00+a13*b01+a23*b02;out[4]=a00*b10+a10*b11+a20*b12;out[5]=a01*b10+a11*b11+a21*b12;out[6]=a02*b10+a12*b11+a22*b12;out[7]=a03*b10+a13*b11+a23*b12;out[8]=a00*b20+a10*b21+a20*b22;out[9]=a01*b20+a11*b21+a21*b22;out[10]=a02*b20+a12*b21+a22*b22;out[11]=a03*b20+a13*b21+a23*b22;if(a!==out){out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];} return out;};mat4.rotateX=function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11];if(a!==out){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];} out[4]=a10*c+a20*s;out[5]=a11*c+a21*s;out[6]=a12*c+a22*s;out[7]=a13*c+a23*s;out[8]=a20*c-a10*s;out[9]=a21*c-a11*s;out[10]=a22*c-a12*s;out[11]=a23*c-a13*s;return out;};mat4.rotateY=function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a00=a[0],a01=a[1],a02=a[2],a03=a[3],a20=a[8],a21=a[9],a22=a[10],a23=a[11];if(a!==out){out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];} out[0]=a00*c-a20*s;out[1]=a01*c-a21*s;out[2]=a02*c-a22*s;out[3]=a03*c-a23*s;out[8]=a00*s+a20*c;out[9]=a01*s+a21*c;out[10]=a02*s+a22*c;out[11]=a03*s+a23*c;return out;};mat4.rotateZ=function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7];if(a!==out){out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];} out[0]=a00*c+a10*s;out[1]=a01*c+a11*s;out[2]=a02*c+a12*s;out[3]=a03*c+a13*s;out[4]=a10*c-a00*s;out[5]=a11*c-a01*s;out[6]=a12*c-a02*s;out[7]=a13*c-a03*s;return out;};mat4.fromRotationTranslation=function(out,q,v){var x=q[0],y=q[1],z=q[2],w=q[3],x2=x+x,y2=y+y,z2=z+z,xx=x*x2,xy=x*y2,xz=x*z2,yy=y*y2,yz=y*z2,zz=z*z2,wx=w*x2,wy=w*y2,wz=w*z2;out[0]=1-(yy+zz);out[1]=xy+wz;out[2]=xz-wy;out[3]=0;out[4]=xy-wz;out[5]=1-(xx+zz);out[6]=yz+wx;out[7]=0;out[8]=xz+wy;out[9]=yz-wx;out[10]=1-(xx+yy);out[11]=0;out[12]=v[0];out[13]=v[1];out[14]=v[2];out[15]=1;return out;};mat4.fromQuat=function(out,q){var x=q[0],y=q[1],z=q[2],w=q[3],x2=x+x,y2=y+y,z2=z+z,xx=x*x2,yx=y*x2,yy=y*y2,zx=z*x2,zy=z*y2,zz=z*z2,wx=w*x2,wy=w*y2,wz=w*z2;out[0]=1-yy-zz;out[1]=yx+wz;out[2]=zx-wy;out[3]=0;out[4]=yx-wz;out[5]=1-xx-zz;out[6]=zy+wx;out[7]=0;out[8]=zx+wy;out[9]=zy-wx;out[10]=1-xx-yy;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;};mat4.frustum=function(out,left,right,bottom,top,near,far){var rl=1/(right-left),tb=1/(top-bottom),nf=1/(near-far);out[0]=(near*2)*rl;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=(near*2)*tb;out[6]=0;out[7]=0;out[8]=(right+left)*rl;out[9]=(top+bottom)*tb;out[10]=(far+near)*nf;out[11]=-1;out[12]=0;out[13]=0;out[14]=(far*near*2)*nf;out[15]=0;return out;};mat4.perspective=function(out,fovy,aspect,near,far){var f=1.0/Math.tan(fovy/2),nf=1/(near-far);out[0]=f/aspect;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=f;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=(far+near)*nf;out[11]=-1;out[12]=0;out[13]=0;out[14]=(2*far*near)*nf;out[15]=0;return out;};mat4.ortho=function(out,left,right,bottom,top,near,far){var lr=1/(left-right),bt=1/(bottom-top),nf=1/(near-far);out[0]=-2*lr;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=-2*bt;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=2*nf;out[11]=0;out[12]=(left+right)*lr;out[13]=(top+bottom)*bt;out[14]=(far+near)*nf;out[15]=1;return out;};mat4.lookAt=function(out,eye,center,up){var x0,x1,x2,y0,y1,y2,z0,z1,z2,len,eyex=eye[0],eyey=eye[1],eyez=eye[2],upx=up[0],upy=up[1],upz=up[2],centerx=center[0],centery=center[1],centerz=center[2];if(Math.abs(eyex-centerx)<GLMAT_EPSILON&&Math.abs(eyey-centery)<GLMAT_EPSILON&&Math.abs(eyez-centerz)<GLMAT_EPSILON){return mat4.identity(out);} z0=eyex-centerx;z1=eyey-centery;z2=eyez-centerz;len=1/Math.sqrt(z0*z0+z1*z1+z2*z2);z0*=len;z1*=len;z2*=len;x0=upy*z2-upz*z1;x1=upz*z0-upx*z2;x2=upx*z1-upy*z0;len=Math.sqrt(x0*x0+x1*x1+x2*x2);if(!len){x0=0;x1=0;x2=0;}else{len=1/len;x0*=len;x1*=len;x2*=len;} y0=z1*x2-z2*x1;y1=z2*x0-z0*x2;y2=z0*x1-z1*x0;len=Math.sqrt(y0*y0+y1*y1+y2*y2);if(!len){y0=0;y1=0;y2=0;}else{len=1/len;y0*=len;y1*=len;y2*=len;} out[0]=x0;out[1]=y0;out[2]=z0;out[3]=0;out[4]=x1;out[5]=y1;out[6]=z1;out[7]=0;out[8]=x2;out[9]=y2;out[10]=z2;out[11]=0;out[12]=-(x0*eyex+x1*eyey+x2*eyez);out[13]=-(y0*eyex+y1*eyey+y2*eyez);out[14]=-(z0*eyex+z1*eyey+z2*eyez);out[15]=1;return out;};mat4.str=function(a){return'mat4('+a[0]+', '+a[1]+', '+a[2]+', '+a[3]+', '+ a[4]+', '+a[5]+', '+a[6]+', '+a[7]+', '+ a[8]+', '+a[9]+', '+a[10]+', '+a[11]+', '+ a[12]+', '+a[13]+', '+a[14]+', '+a[15]+')';};mat4.frob=function(a){return(Math.sqrt(Math.pow(a[0],2)+Math.pow(a[1],2)+Math.pow(a[2],2)+Math.pow(a[3],2)+Math.pow(a[4],2)+Math.pow(a[5],2)+Math.pow(a[6],2)+Math.pow(a[7],2)+Math.pow(a[8],2)+Math.pow(a[9],2)+Math.pow(a[10],2)+Math.pow(a[11],2)+Math.pow(a[12],2)+Math.pow(a[13],2)+Math.pow(a[14],2)+Math.pow(a[15],2)))};if(typeof(exports)!=='undefined'){exports.mat4=mat4;};var quat={};quat.create=function(){var out=new GLMAT_ARRAY_TYPE(4);out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out;};quat.rotationTo=(function(){var tmpvec3=vec3.create();var xUnitVec3=vec3.fromValues(1,0,0);var yUnitVec3=vec3.fromValues(0,1,0);return function(out,a,b){var dot=vec3.dot(a,b);if(dot<-0.999999){vec3.cross(tmpvec3,xUnitVec3,a);if(vec3.length(tmpvec3)<0.000001) vec3.cross(tmpvec3,yUnitVec3,a);vec3.normalize(tmpvec3,tmpvec3);quat.setAxisAngle(out,tmpvec3,Math.PI);return out;}else if(dot>0.999999){out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out;}else{vec3.cross(tmpvec3,a,b);out[0]=tmpvec3[0];out[1]=tmpvec3[1];out[2]=tmpvec3[2];out[3]=1+dot;return quat.normalize(out,out);}};})();quat.setAxes=(function(){var matr=mat3.create();return function(out,view,right,up){matr[0]=right[0];matr[3]=right[1];matr[6]=right[2];matr[1]=up[0];matr[4]=up[1];matr[7]=up[2];matr[2]=-view[0];matr[5]=-view[1];matr[8]=-view[2];return quat.normalize(out,quat.fromMat3(out,matr));};})();quat.clone=vec4.clone;quat.fromValues=vec4.fromValues;quat.copy=vec4.copy;quat.set=vec4.set;quat.identity=function(out){out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out;};quat.setAxisAngle=function(out,axis,rad){rad=rad*0.5;var s=Math.sin(rad);out[0]=s*axis[0];out[1]=s*axis[1];out[2]=s*axis[2];out[3]=Math.cos(rad);return out;};quat.add=vec4.add;quat.multiply=function(out,a,b){var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=b[0],by=b[1],bz=b[2],bw=b[3];out[0]=ax*bw+aw*bx+ay*bz-az*by;out[1]=ay*bw+aw*by+az*bx-ax*bz;out[2]=az*bw+aw*bz+ax*by-ay*bx;out[3]=aw*bw-ax*bx-ay*by-az*bz;return out;};quat.mul=quat.multiply;quat.scale=vec4.scale;quat.rotateX=function(out,a,rad){rad*=0.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+aw*bx;out[1]=ay*bw+az*bx;out[2]=az*bw-ay*bx;out[3]=aw*bw-ax*bx;return out;};quat.rotateY=function(out,a,rad){rad*=0.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3],by=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw-az*by;out[1]=ay*bw+aw*by;out[2]=az*bw+ax*by;out[3]=aw*bw-ay*by;return out;};quat.rotateZ=function(out,a,rad){rad*=0.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3],bz=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+ay*bz;out[1]=ay*bw-ax*bz;out[2]=az*bw+aw*bz;out[3]=aw*bw-az*bz;return out;};quat.calculateW=function(out,a){var x=a[0],y=a[1],z=a[2];out[0]=x;out[1]=y;out[2]=z;out[3]=Math.sqrt(Math.abs(1.0-x*x-y*y-z*z));return out;};quat.dot=vec4.dot;quat.lerp=vec4.lerp;quat.slerp=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=b[0],by=b[1],bz=b[2],bw=b[3];var omega,cosom,sinom,scale0,scale1;cosom=ax*bx+ay*by+az*bz+aw*bw;if(cosom<0.0){cosom=-cosom;bx=-bx;by=-by;bz=-bz;bw=-bw;} if((1.0-cosom)>0.000001){omega=Math.acos(cosom);sinom=Math.sin(omega);scale0=Math.sin((1.0-t)*omega)/sinom;scale1=Math.sin(t*omega)/sinom;}else{scale0=1.0-t;scale1=t;} out[0]=scale0*ax+scale1*bx;out[1]=scale0*ay+scale1*by;out[2]=scale0*az+scale1*bz;out[3]=scale0*aw+scale1*bw;return out;};quat.invert=function(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],dot=a0*a0+a1*a1+a2*a2+a3*a3,invDot=dot?1.0/dot:0;out[0]=-a0*invDot;out[1]=-a1*invDot;out[2]=-a2*invDot;out[3]=a3*invDot;return out;};quat.conjugate=function(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=a[3];return out;};quat.length=vec4.length;quat.len=quat.length;quat.squaredLength=vec4.squaredLength;quat.sqrLen=quat.squaredLength;quat.normalize=vec4.normalize;quat.fromMat3=function(out,m){var fTrace=m[0]+m[4]+m[8];var fRoot;if(fTrace>0.0){fRoot=Math.sqrt(fTrace+1.0);out[3]=0.5*fRoot;fRoot=0.5/fRoot;out[0]=(m[5]-m[7])*fRoot;out[1]=(m[6]-m[2])*fRoot;out[2]=(m[1]-m[3])*fRoot;}else{var i=0;if(m[4]>m[0]) i=1;if(m[8]>m[i*3+i]) i=2;var j=(i+1)%3;var k=(i+2)%3;fRoot=Math.sqrt(m[i*3+i]-m[j*3+j]-m[k*3+k]+1.0);out[i]=0.5*fRoot;fRoot=0.5/fRoot;out[3]=(m[j*3+k]-m[k*3+j])*fRoot;out[j]=(m[j*3+i]+m[i*3+j])*fRoot;out[k]=(m[k*3+i]+m[i*3+k])*fRoot;} return out;};quat.str=function(a){return'quat('+a[0]+', '+a[1]+', '+a[2]+', '+a[3]+')';};if(typeof(exports)!=='undefined'){exports.quat=quat;};})(shim.exports);})(this);
/** * This file uses the Page Object pattern to define the main page for tests * https://docs.google.com/presentation/d/1B6manhG0zEXkC-H-tPo2vwU06JhL8w9-XCF9oehXzAQ */ 'use strict'; var OauthButtons = function() { var oauthButtons = this.oauthButtons = element(by.css('oauth-buttons')); oauthButtons.twitter = oauthButtons.element(by.css('.btn.btn-social.btn-twitter')); }; module.exports = new OauthButtons();
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- """Defines an explainable linear model.""" import numpy as np from scipy.sparse import csr_matrix, issparse from sklearn.linear_model import (Lasso, LinearRegression, LogisticRegression, SGDClassifier, SGDRegressor) from ...common.constants import ExplainableModelType, Extension, SHAPDefaults from ...common.explanation_utils import _summarize_data from ...common.warnings_suppressor import shap_warnings_suppressor from .explainable_model import (BaseExplainableModel, _clean_doc, _get_initializer_args) with shap_warnings_suppressor(): import shap DEFAULT_RANDOM_STATE = 123 FEATURE_DEPENDENCE = 'interventional' LINEAR_PENALTY = 'penalty' LINEAR_L2 = 'l2' LINEAR_SOLVER = 'solver' LINEAR_LBFGS = 'lbfgs' LINEAR_MULTICLASS = 'multi_class' LINEAR_MULTINOMIAL = 'multinomial' LINEAR_RANDOM_STATE = 'random_state' class LinearExplainer(shap.LinearExplainer): """Linear explainer with support for sparse data and sparse output.""" def __init__(self, model, data, feature_dependence=FEATURE_DEPENDENCE): """Initialize the LinearExplainer. :param model: The linear model to compute the shap values for as a (coef, intercept) tuple. :type model: (numpy.matrix, double) :param data: The mean and covariance of the dataset. :type data: (scipy.csr_matrix, None) :param feature_dependence: Indicates the type of feature dependency, interventional by default. :type feature_dependence: str """ self.is_sparse = data[1] is None if self.is_sparse: # Sparse case self.coef = model[0] if not issparse(self.coef): self.coef = np.asmatrix(self.coef) self.intercept = model[1] self._background = data[0] self.expected_value = np.array(self._background.dot(self.coef.T) + self.intercept).flatten() else: # Dense case super(LinearExplainer, self).__init__(model, data, feature_dependence=feature_dependence) def shap_values(self, evaluation_examples): """Estimate the SHAP values for a set of samples. :param evaluation_examples: The evaluation examples. :type evaluation_examples: numpy.ndarray or pandas.DataFrame or scipy.sparse.csr_matrix :return: For models with a single output this returns a matrix of SHAP values (# samples x # features). Each row sums to the difference between the model output for that sample and the expected value of the model output (which is stored as expected_value attribute of the explainer). :rtype: Union[list, numpy.ndarray] """ if self.is_sparse: assert len(evaluation_examples.shape) == 2, "Sparse instance must have 2 dimensions!" assert self.coef.shape[0] == 1, "Multiclass coefficients need to be evaluated separately" mean_multiplier = csr_matrix(np.ones((evaluation_examples.shape[0], 1))) return (evaluation_examples - mean_multiplier * self._background).multiply(self.coef[0]).tocsr() else: return super().shap_values(evaluation_examples) def _create_linear_explainer(model, multiclass, mean, covariance, seed): """Create the linear explainer or, in multiclass case, list of explainers. :param model: The linear model to compute the shap values for. A linear model that implements sklearn.predict or sklearn.predict_proba. :type model: object :param multiclass: True if this is a multiclass model. :type multiclass: bool :param mean: The mean of the dataset by columns. :type mean: numpy.ndarray :param covariance: The covariance matrix of the dataset. :type covariance: numpy.ndarray :param seed: Random number seed. :type seed: int """ np.random.seed(seed) if multiclass: explainers = [] coefs = model.coef_ intercepts = model.intercept_ if isinstance(intercepts, np.ndarray): intercepts = intercepts.tolist() if isinstance(intercepts, list): coef_intercept_list = zip(coefs, intercepts) else: coef_intercept_list = [(coef, intercepts) for coef in coefs] for class_coef, intercept in coef_intercept_list: linear_explainer = LinearExplainer((class_coef, intercept), (mean, covariance), feature_dependence=SHAPDefaults.INDEPENDENT) explainers.append(linear_explainer) return explainers else: model_coef = model.coef_ model_intercept = model.intercept_ return LinearExplainer((model_coef, model_intercept), (mean, covariance), feature_dependence=SHAPDefaults.INDEPENDENT) def _compute_local_shap_values(linear_explainer, evaluation_examples, classification): """Compute the local shap values. :param linear_explainer: The linear explainer or list of linear explainers in multiclass case. :type linear_explainer: Union[LinearExplainer, list[LinearExplainer]] :param evaluation_examples: The evaluation examples. :type evaluation_examples: numpy.ndarray or pandas.DataFrame or scipy.sparse.csr_matrix """ # Multiclass case if isinstance(linear_explainer, list): shap_values = [] for explainer in linear_explainer: explainer_shap_values = explainer.shap_values(evaluation_examples) if isinstance(explainer_shap_values, list): explainer_shap_values = explainer_shap_values[0] shap_values.append(explainer_shap_values) return shap_values shap_values = linear_explainer.shap_values(evaluation_examples) if not classification and isinstance(shap_values, list): shap_values = shap_values[0] return shap_values def _compute_background_data(dataset): """Compute the background data for linear explainer. :param dataset: The input dataset to compute background for. :type dataset: numpy.ndarray or pandas.DataFrame or scipy.sparse.csr_matrix """ background = _summarize_data(dataset) if str(type(background)).endswith(".DenseData'>"): background = background.data if not issparse(background) and len(background.shape) == 2: mean_shape = background.shape[1] # Take mean of clusters to get better representation of background if background.shape[0] > 1: background = background.mean(axis=0) # Check again prior to reshape if len(background.shape) == 2: background = background.reshape((mean_shape,)) return background class LinearExplainableModel(BaseExplainableModel): available_explanations = [Extension.GLOBAL, Extension.LOCAL] explainer_type = Extension.GLASSBOX """Linear explainable model. :param multiclass: Set to true to generate a multiclass model. :type multiclass: bool :param random_state: Int to seed the model. :type random_state: int :param classification: Indicates whether the model is used for classification or regression scenario. :type classification: bool :param sparse_data: Indicates whether the training data will be sparse. :type sparse_data: bool """ def __init__(self, multiclass=False, random_state=DEFAULT_RANDOM_STATE, classification=True, sparse_data=False, **kwargs): """Initialize the LinearExplainableModel. :param multiclass: Set to true to generate a multiclass model. :type multiclass: bool :param random_state: Int to seed the model. :type random_state: int :param classification: Indicates whether the model is used for classification or regression scenario. :type classification: bool :param sparse_data: Indicates whether the training data will be sparse. :type sparse_data: bool """ self.multiclass = multiclass self.random_state = random_state self._sparse_data = sparse_data if self.multiclass: initializer = LogisticRegression if self._sparse_data: kwargs[LINEAR_PENALTY] = LINEAR_L2 if LINEAR_SOLVER not in kwargs: kwargs[LINEAR_SOLVER] = LINEAR_LBFGS kwargs[LINEAR_MULTICLASS] = LINEAR_MULTINOMIAL kwargs[LINEAR_RANDOM_STATE] = random_state else: if self._sparse_data: initializer = Lasso else: initializer = LinearRegression initializer_args = _get_initializer_args(kwargs) self._linear = initializer(**initializer_args) super(LinearExplainableModel, self).__init__(**kwargs) self._logger.debug('Initializing LinearExplainableModel') self._method = 'linear' self._linear_explainer = None self._classification = classification __init__.__doc__ = (__init__.__doc__ + '\nIf multiclass=True, uses the parameters for LogisticRegression:\n' + _clean_doc(LogisticRegression.__doc__) + '\nOtherwise, if multiclass=False, uses the parameters for LinearRegression:\n' + _clean_doc(LinearRegression.__doc__)) def fit(self, dataset, labels, **kwargs): """Call linear fit to fit the explainable model. Store the mean and covariance of the background data for local explanation. :param dataset: The dataset to train the model on. :type dataset: numpy.ndarray or pandas.DataFrame or scipy.sparse.csr_matrix :param labels: The labels to train the model on. :type labels: numpy.ndarray """ self._linear.fit(dataset, labels, **kwargs) self._background = _compute_background_data(dataset) if not issparse(dataset): self.covariance = np.cov(dataset, rowvar=False) else: # Not needed for sparse case self.covariance = None fit.__doc__ = (fit.__doc__ + '\nIf multiclass=True, uses the parameters for LogisticRegression:\n' + _clean_doc(LogisticRegression.fit.__doc__) + '\nOtherwise, if multiclass=False, uses the parameters for LinearRegression:\n' + _clean_doc(LinearRegression.fit.__doc__)) def predict(self, dataset, **kwargs): """Call linear predict to predict labels using the explainable model. :param dataset: The dataset to predict on. :type dataset: numpy.ndarray or pandas.DataFrame or scipy.sparse.csr_matrix :return: The predictions of the model. :rtype: list """ return self._linear.predict(dataset) predict.__doc__ = (predict.__doc__ + '\nIf multiclass=True, uses the parameters for LogisticRegression:\n' + _clean_doc(LogisticRegression.predict.__doc__) + '\nOtherwise, if multiclass=False, uses the parameters for LinearRegression:\n' + _clean_doc(LinearRegression.predict.__doc__)) def predict_proba(self, dataset, **kwargs): """Call linear predict_proba to predict probabilities using the explainable model. :param dataset: The dataset to predict probabilities on. :type dataset: numpy.ndarray or pandas.DataFrame or scipy.sparse.csr_matrix :return: The predictions of the model. :rtype: list """ if self.multiclass: return self._linear.predict_proba(dataset) else: raise Exception('predict_proba not supported for regression or binary classification dataset') predict_proba.__doc__ = (predict_proba.__doc__ + '\nIf multiclass=True, uses the parameters for LogisticRegression:\n' + _clean_doc(LogisticRegression.predict_proba.__doc__) + '\nOtherwise predict_proba is not supported for regression or binary classification.\n') def explain_global(self, **kwargs): """Call coef to get the global feature importances from the linear surrogate model. :return: The global explanation of feature importances. :rtype: list """ coef = self._linear.coef_ if (len(coef.shape) == 2): return np.mean(coef, axis=0) return coef def explain_local(self, evaluation_examples, **kwargs): """Use LinearExplainer to get the local feature importances from the trained explainable model. :param evaluation_examples: The evaluation examples to compute local feature importances for. :type evaluation_examples: numpy.ndarray or pandas.DataFrame or scipy.sparse.csr_matrix :return: The local explanation of feature importances. :rtype: Union[list, numpy.ndarray] """ if self._linear_explainer is None: self._linear_explainer = _create_linear_explainer(self._linear, self.multiclass, self._background, self.covariance, self.random_state) return _compute_local_shap_values(self._linear_explainer, evaluation_examples, self._classification) @property def expected_values(self): """Use LinearExplainer to get the expected values. :return: The expected values of the linear model. :rtype: list """ if self._linear_explainer is None: self._linear_explainer = _create_linear_explainer(self._linear, self.multiclass, self._background, self.covariance, self.random_state) if isinstance(self._linear_explainer, list): expected_values = [] for explainer in self._linear_explainer: expected_values.append(explainer.expected_value) return expected_values else: expected_values = self._linear_explainer.expected_value if self._classification and not self.multiclass: expected_values = [-expected_values, expected_values] return expected_values @property def model(self): """Retrieve the underlying model. :return: The linear model, either classifier or regressor. :rtype: Union[LogisticRegression, LinearRegression] """ return self._linear @staticmethod def explainable_model_type(): """Retrieve the model type. :return: Linear explainable model type. :rtype: ExplainableModelType """ return ExplainableModelType.LINEAR_EXPLAINABLE_MODEL_TYPE class SGDExplainableModel(BaseExplainableModel): available_explanations = [Extension.GLOBAL, Extension.LOCAL] explainer_type = Extension.GLASSBOX """Stochastic Gradient Descent explainable model. :param multiclass: Set to true to generate a multiclass model. :type multiclass: bool :param random_state: Int to seed the model. :type random_state: int """ def __init__(self, multiclass=False, random_state=DEFAULT_RANDOM_STATE, classification=True, **kwargs): """Initialize the SGDExplainableModel. :param multiclass: Set to true to generate a multiclass model. :type multiclass: bool :param random_state: Int to seed the model. :type random_state: int """ self.multiclass = multiclass self.random_state = random_state if self.multiclass: initializer = SGDClassifier else: initializer = SGDRegressor initializer_args = _get_initializer_args(kwargs) self._sgd = initializer(random_state=random_state, **initializer_args) super(SGDExplainableModel, self).__init__(**kwargs) self._logger.debug('Initializing SGDExplainableModel') self._method = 'sgd' self._sgd_explainer = None self._classification = classification __init__.__doc__ = (__init__.__doc__ + '\nIf multiclass=True, uses the parameters for SGDClassifier:\n' + _clean_doc(SGDClassifier.__doc__) + '\nOtherwise, if multiclass=False, uses the parameters for SGDRegressor:\n' + _clean_doc(SGDRegressor.__doc__)) def fit(self, dataset, labels, **kwargs): """Call linear fit to fit the explainable model. Store the mean and covariance of the background data for local explanation. :param dataset: The dataset to train the model on. :type dataset: numpy.ndarray or pandas.DataFrame or scipy.sparse.csr_matrix :param labels: The labels to train the model on. :type labels: numpy.ndarray """ self._sgd.fit(dataset, labels, **kwargs) self._background = _compute_background_data(dataset) if not issparse(dataset): self.covariance = np.cov(dataset, rowvar=False) else: # Not needed for sparse case self.covariance = None fit.__doc__ = (fit.__doc__ + '\nIf multiclass=True, uses the parameters for SGDClassifier:\n' + _clean_doc(SGDClassifier.fit.__doc__) + '\nOtherwise, if multiclass=False, uses the parameters for SGDRegressor:\n' + _clean_doc(SGDRegressor.fit.__doc__)) def predict(self, dataset, **kwargs): """Call SGD predict to predict labels using the explainable model. :param dataset: The dataset to predict on. :type dataset: numpy.ndarray or pandas.DataFrame or scipy.sparse.csr_matrix :return: The predictions of the model. :rtype: list """ return self._sgd.predict(dataset) predict.__doc__ = (predict.__doc__ + '\nIf multiclass=True, uses the parameters for SGDClassifier:\n' + _clean_doc(SGDClassifier.predict.__doc__) + '\nOtherwise, if multiclass=False, uses the parameters for SGDRegressor:\n' + _clean_doc(SGDRegressor.predict.__doc__)) def predict_proba(self, dataset, **kwargs): """Call SGD predict_proba to predict probabilities using the explainable model. :param dataset: The dataset to predict probabilities on. :type dataset: numpy.ndarray or pandas.DataFrame or scipy.sparse.csr_matrix :return: The predictions of the model. :rtype: list """ if self.multiclass: return self._sgd.predict_proba(dataset) else: raise Exception('predict_proba not supported for regression or binary classification dataset') predict_proba.__doc__ = (predict_proba.__doc__ + '\nIf multiclass=True, uses the parameters for SGDClassifier:\n' + _clean_doc(SGDClassifier.predict_proba.__doc__) .replace(':class:`sklearn.calibration.CalibratedClassifierCV`', 'CalibratedClassifierCV') + '\nOtherwise predict_proba is not supported for regression or binary classification.\n') def explain_global(self, **kwargs): """Call coef to get the global feature importances from the SGD surrogate model. :return: The global explanation of feature importances. :rtype: list """ coef = self._sgd.coef_ if (len(coef.shape) == 2): return np.mean(coef, axis=0) return coef def explain_local(self, evaluation_examples, **kwargs): """Use LinearExplainer to get the local feature importances from the trained explainable model. :param evaluation_examples: The evaluation examples to compute local feature importances for. :type evaluation_examples: numpy.ndarray or pandas.DataFrame or scipy.sparse.csr_matrix :return: The local explanation of feature importances. :rtype: Union[list, numpy.ndarray] """ if self._sgd_explainer is None: self._sgd_explainer = _create_linear_explainer(self._sgd, self.multiclass, self._background, self.covariance, self.random_state) return _compute_local_shap_values(self._sgd_explainer, evaluation_examples, self._classification) @property def expected_values(self): """Use LinearExplainer to get the expected values. :return: The expected values of the linear model. :rtype: list """ if self._sgd_explainer is None: self._sgd_explainer = _create_linear_explainer(self._sgd, self.multiclass, self._background, self.covariance, self.random_state) if isinstance(self._sgd_explainer, list): expected_values = [] for explainer in self._sgd_explainer: expected_values.append(explainer.expected_value) return expected_values else: expected_values = self._sgd_explainer.expected_value if self._classification and not self.multiclass: expected_values = [-expected_values, expected_values] return expected_values @property def model(self): """Retrieve the underlying model. :return: The SGD model, either classifier or regressor. :rtype: Union[SGDClassifier, SGDRegressor] """ return self._sgd
# exported from PySB model 'model' from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD Model() Monomer('C6A', ['C8pro']) Monomer('BaxA', ['BaxM', 'BaxA_1', 'BaxA_2', 'SmacM']) Monomer('Ligand', ['Receptor']) Monomer('C6pro', ['C3A']) Monomer('ParpU', ['C3A']) Monomer('BidU', ['C8A']) Monomer('BidT') Monomer('C3A', ['Xiap', 'ParpU', 'C6pro']) Monomer('BidM', ['BaxM']) Monomer('BaxM', ['BidM', 'BaxA']) Monomer('C8A', ['BidU', 'C3pro']) Monomer('Xiap', ['SmacC', 'C3A']) Monomer('Receptor', ['Ligand', 'Fadd']) Monomer('C3ub') Monomer('Fadd', ['Receptor', 'C8pro']) Monomer('C3pro', ['C8A']) Monomer('SmacM', ['BaxA']) Monomer('SmacC', ['Xiap']) Monomer('C8pro', ['Fadd', 'C6A']) Monomer('ParpC') Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0) Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0) Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0) Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kf', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kr', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr', 1.0) Parameter('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr', 1.0) Parameter('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc', 1.0) Parameter('pore_formation_0_BaxA_pore_2kf', 1.0) Parameter('pore_formation_0_BaxA_pore_1kr', 1.0) Parameter('pore_formation_1_BaxA_pore_2kf', 1.0) Parameter('pore_formation_1_BaxA_pore_1kr', 1.0) Parameter('pore_formation_2_BaxA_pore_2kf', 1.0) Parameter('pore_formation_2_BaxA_pore_1kr', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc', 1.0) Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf', 1.0) Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr', 1.0) Parameter('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('C6A_0', 0.0) Parameter('BaxA_0', 0.0) Parameter('Ligand_0', 1000.0) Parameter('C6pro_0', 100.0) Parameter('ParpU_0', 1000000.0) Parameter('BidU_0', 171000.0) Parameter('BidT_0', 0.0) Parameter('C3A_0', 0.0) Parameter('BidM_0', 0.0) Parameter('BaxM_0', 40000.0) Parameter('C8A_0', 0.0) Parameter('Xiap_0', 149500.0) Parameter('Receptor_0', 100.0) Parameter('C3ub_0', 0.0) Parameter('Fadd_0', 130000.0) Parameter('C3pro_0', 21000.0) Parameter('SmacM_0', 100000.0) Parameter('SmacC_0', 0.0) Parameter('C8pro_0', 130000.0) Parameter('ParpC_0', 0.0) Observable('C6A_obs', C6A()) Observable('BaxA_obs', BaxA()) Observable('Ligand_obs', Ligand()) Observable('C6pro_obs', C6pro()) Observable('ParpU_obs', ParpU()) Observable('BidU_obs', BidU()) Observable('BidT_obs', BidT()) Observable('C3A_obs', C3A()) Observable('BidM_obs', BidM()) Observable('BaxM_obs', BaxM()) Observable('C8A_obs', C8A()) Observable('Xiap_obs', Xiap()) Observable('Receptor_obs', Receptor()) Observable('C3ub_obs', C3ub()) Observable('Fadd_obs', Fadd()) Observable('C3pro_obs', C3pro()) Observable('SmacM_obs', SmacM()) Observable('SmacC_obs', SmacC()) Observable('C8pro_obs', C8pro()) Observable('ParpC_obs', ParpC()) Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr) Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr) Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None, C6A=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr) Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None) >> Fadd(Receptor=ANY, C8pro=None) + C8A(BidU=None, C3pro=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc) Rule('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=None, C3pro=None) + BidU(C8A=None) | C8A(BidU=1, C3pro=None) % BidU(C8A=1), catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf, catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr) Rule('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=1, C3pro=None) % BidU(C8A=1) >> C8A(BidU=None, C3pro=None) + BidT(), catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc) Rule('inhibition_0_SmacC_inhibitor_Xiap_inh_target', SmacC(Xiap=None) + Xiap(SmacC=None, C3A=None) | SmacC(Xiap=1) % Xiap(SmacC=1, C3A=None), inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf, inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr) Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, C3A=None) + C3A(Xiap=None, ParpU=None, C6pro=None) | Xiap(SmacC=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr) Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None) >> Xiap(SmacC=None, C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc) Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None, C6pro=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr) Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc) Rule('equilibration_0_BidT_equil_a_BidM_equil_b', BidT() | BidM(BaxM=None), equilibration_0_BidT_equil_a_BidM_equil_b_1kf, equilibration_0_BidT_equil_a_BidM_equil_b_1kr) Rule('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=None) + BaxM(BidM=None, BaxA=None) | BidM(BaxM=1) % BaxM(BidM=1, BaxA=None), catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf, catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr) Rule('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=1) % BaxM(BidM=1, BaxA=None) >> BidM(BaxM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None), catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc) Rule('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None) + BaxM(BidM=None, BaxA=None) | BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None) % BaxM(BidM=None, BaxA=1), self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf, self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr) Rule('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None) % BaxM(BidM=None, BaxA=1) >> BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None), self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc) Rule('pore_formation_0_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None) | BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None), pore_formation_0_BaxA_pore_2kf, pore_formation_0_BaxA_pore_1kr) Rule('pore_formation_1_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None) | BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None), pore_formation_1_BaxA_pore_2kf, pore_formation_1_BaxA_pore_1kr) Rule('pore_formation_2_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None) + BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None), pore_formation_2_BaxA_pore_2kf, pore_formation_2_BaxA_pore_1kr) Rule('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None) + SmacM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5) % SmacM(BaxA=5), transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf, transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr) Rule('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5) % SmacM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None) + SmacC(Xiap=None), transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc) Rule('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=None) + C3pro(C8A=None) | C8A(BidU=None, C3pro=1) % C3pro(C8A=1), catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=1) % C3pro(C8A=1) >> C8A(BidU=None, C3pro=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=None) + C6pro(C3A=None) | C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1), catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf, catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr) Rule('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + C6A(C8pro=None), catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc) Rule('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=None) + C8pro(Fadd=None, C6A=None) | C6A(C8pro=1) % C8pro(Fadd=None, C6A=1), catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf, catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr) Rule('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=1) % C8pro(Fadd=None, C6A=1) >> C6A(C8pro=None) + C8A(BidU=None, C3pro=None), catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc) Initial(C6A(C8pro=None), C6A_0) Initial(BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None), BaxA_0) Initial(Ligand(Receptor=None), Ligand_0) Initial(C6pro(C3A=None), C6pro_0) Initial(ParpU(C3A=None), ParpU_0) Initial(BidU(C8A=None), BidU_0) Initial(BidT(), BidT_0) Initial(C3A(Xiap=None, ParpU=None, C6pro=None), C3A_0) Initial(BidM(BaxM=None), BidM_0) Initial(BaxM(BidM=None, BaxA=None), BaxM_0) Initial(C8A(BidU=None, C3pro=None), C8A_0) Initial(Xiap(SmacC=None, C3A=None), Xiap_0) Initial(Receptor(Ligand=None, Fadd=None), Receptor_0) Initial(C3ub(), C3ub_0) Initial(Fadd(Receptor=None, C8pro=None), Fadd_0) Initial(C3pro(C8A=None), C3pro_0) Initial(SmacM(BaxA=None), SmacM_0) Initial(SmacC(Xiap=None), SmacC_0) Initial(C8pro(Fadd=None, C6A=None), C8pro_0) Initial(ParpC(), ParpC_0)
const crypto = require('crypto') const Sequelize = require('sequelize') const db = require('../db') const User = db.define('user', { name: { type: Sequelize.STRING }, email: { type: Sequelize.STRING, unique: true, allowNull: false, validate: { isEmail: true } }, phone: { type: Sequelize.STRING }, delivery: { type: Sequelize.STRING }, billing: { type: Sequelize.STRING }, userStatus: { type: Sequelize.ENUM('user', 'admin'), defaultValue: 'user' }, password: { type: Sequelize.STRING, // Making `.password` act like a func hides it when serializing to JSON. // This is a hack to get around Sequelize's lack of a "private" option. get() { return () => this.getDataValue('password') } }, salt: { type: Sequelize.STRING, // Making `.salt` act like a function hides it when serializing to JSON. // This is a hack to get around Sequelize's lack of a "private" option. get() { return () => this.getDataValue('salt') } }, googleId: { type: Sequelize.STRING } }) module.exports = User /** * instanceMethods */ User.prototype.correctPassword = function(candidatePwd) { return User.encryptPassword(candidatePwd, this.salt()) === this.password() } /** * classMethods */ User.generateSalt = function() { return crypto.randomBytes(16).toString('base64') } User.encryptPassword = function(plainText, salt) { return crypto .createHash('RSA-SHA256') .update(plainText) .update(salt) .digest('hex') } /** * hooks */ const setSaltAndPassword = user => { if (user.changed('password')) { user.salt = User.generateSalt() user.password = User.encryptPassword(user.password(), user.salt()) } } User.beforeCreate(setSaltAndPassword) User.beforeUpdate(setSaltAndPassword) User.beforeBulkCreate(users => { users.forEach(setSaltAndPassword) }) // "prepare": "if [ -d .git ]; then npm-merge-driver install; fi",
Molpy.DefineGUI = function() { function InnerMolpify(number, raftcastle, shrinkify) { if(isNaN(number)) return 'Mustard'; if(!isFinite(parseFloat(number))) return 'Infinite'; if(number < 0) return '-' + InnerMolpify(-number, raftcastle, shrinkify); var molp = ''; if(shrinkify == 2) shrinkify = 0; else if(Molpy && !shrinkify) shrinkify = !Molpy.options.science; if(shrinkify) { for( var i in postfixes) { var p = postfixes[i]; if(number >= p.limit) { return InnerMolpify(number / p.divisor, raftcastle, 1) + p.postfix[Molpy.options.longpostfix]; } } } else { if(number == 3) return 'Math.floor(Math.PI)'; if(number == 4) return 'Math.ceil(Math.PI)'; } if(raftcastle > 0) { var numCopy = number; //get the right number of decimal places to stick on the end: var raft = numCopy * Math.pow(10, raftcastle) - Math.floor(numCopy) * Math.pow(10, raftcastle); var sraft = Math.floor(raft) + ''; if((sraft).length > raftcastle) { numCopy++; sraft = ''; //rounded decimal part up to 1 } else if(raft) while(sraft.length < raftcastle) { sraft = '0' + sraft; //needs leading zeroes because it's a number like 1.01 } molp = InnerMolpify(numCopy, 0, shrinkify) + (raft ? ('.' + sraft) : ''); //stick them on the end if there are any } else { number = Math.floor(number); //drop the decimal bit var sep = (number + '').indexOf('e') == -1; //true if not in exponential notation number = (number + '').split('').reverse(); //convert to string, then array of chars, then backwards for( var i in number) { if(sep && i % 3 == 0 && i > 0) molp = ',' + molp;//stick commas in every 3rd spot but not 0th molp = number[i] + molp; } if(!sep) { var dot = molp.indexOf('.') + 1; var exp = molp.indexOf('e'); molp = molp.slice(0, dot) + molp.slice(dot, exp).slice(0, 6) + molp.slice(exp);//truncate after 6 decimal places } } return molp; } Molpy.IsChildOf = function(child, parent) { if(!child) return; var current = child; while(current = current.parentNode) { if(current == parent) return 1; } } Molpy.hoverTimer = 0; Molpy.hovering = false; Molpy.onMouseOver = function(e) { // Can add argument later if we want // Calls change to $().mouseover({arg1: 1, arg2: 3}, Molpy.onMouseOver) // and are referenced thus: e.data.arg1, e.data.arg2 if(Molpy.Boosts['Expando'].IsEnabled) return; var over = e.data.overID; var div = this; setTimeout(function(){ if(Molpy.mouseIsOver == over) $(div).find('.description').show(); }, 200); Molpy.mouseIsOver = over; Molpy.hovering = true; if(!Molpy.Boosts['Expando'].unlocked) Molpy.UnlockBoost('Expando'); } Molpy.onMouseOut = function(e) { if(Molpy.Boosts['Expando'].IsEnabled) return; var div = this; setTimeout(function(){ if(Molpy.mouseIsOver != e.data.overID) $(div).find('.description').hide(); }, 1000); Molpy.mouseIsOver = null; Molpy.hovering = false; } Molpy.monumentOver = function(e) { Molpy.onMouseOver.call(this, e); if(e.data.alias.indexOf('diamm') == 0) { setTimeout(function(){ if(Molpy.mouseIsOver == e.data.overID) Molpy.Master.Create(e.data.np,'short'); }, 500); } else if(e.data.alias.indexOf('monumg') == 0 && Molpy.previewNP != e.data.np) { Molpy.previewNP = e.data.np; Molpy.UpdateBeach(e.data.np); } else if(e.data.alias.indexOf('monums') == 0) { g('img-monums' + e.data.np).style.backgroundImage = Molpy.Url(Molpy.ThumbNewPixFor(Math.abs(e.data.np))); } } Molpy.monumentOut = function(e) { Molpy.onMouseOut.call(this, e); if(e.data.alias.indexOf('monumg') == 0 && Molpy.previewNP == e.data.np) { Molpy.previewNP = 0; Molpy.UpdateBeach(); } } Molpy.ShowhideButton = function(key) { return '<input type="Button" value="' + (Molpy.activeLayout.lootVis[key] ? 'Hide' : 'Show') + '" onclick="Molpy.ShowhideToggle(\'' + key + '\')"></input>' } Molpy.ShowhideToggle = function(key, val) { Molpy.Anything = 1; if(val == undefined) { Molpy.activeLayout.lootVis[key] = !Molpy.activeLayout.lootVis[key]; } else { Molpy.activeLayout.lootVis[key] = val == true; } if(Molpy.activeLayout.lootVis[key]) { if(key == 'tagged' || key == 'search' || key == 'faves') { for( var k in Molpy.activeLayout.lootVis) { Molpy.activeLayout.lootVis[k] = k == key; //when showing tagged or favourites, hide all others } } else { Molpy.activeLayout.lootVis.search = 0; Molpy.activeLayout.lootVis.tagged = 0; //hide tagged when showing anything else Molpy.activeLayout.lootVis.faves = 0; //hide favourites when showing anything else } } Molpy.restoreLootScroll = false; Molpy.lootPageNum = 1; Molpy.lootNeedRepaint = 1; } Molpy.ShowGroup = function(group, tagged) { if(Molpy.Redacted.drawType[Molpy.Redacted.drawType.length - 1] != 'hide1') { if(!Molpy.activeLayout.lootVis[group]) { if(tagged) { if (!Molpy.activeLayout.lootVis.tagged) { Molpy.ShowhideToggle('tagged'); } } else { Molpy.ShowhideToggle(group); } } } } Molpy.priceComparisons = ['GlassBlocks', 'Sand', 'Castles']; Molpy.IDSort = function(a,b) { return a.id > b.id; } Molpy.NameSort = function(a, b) { var an = a.sortName; var bn = b.sortName; return an > bn; } Molpy.PriceSort = function(a, b) { var p1 = a.CalcPrice(a.price); var p2 = b.CalcPrice(b.price); for( var i in Molpy.priceComparisons) { var stuff = Molpy.priceComparisons[i]; var s1 = p1[stuff] || 0; var s2 = p2[stuff] || 0; if(s1 > s2) return 1; else if(s1 < s2) return -1; } return a.name > b.name; } Molpy.ClassNameSort = function(a, b) { var at = a.className || 'z'; var bt = b.className || 'z'; var ag = a.group; var bg = b.group; if(at > bt) return 1; else if(at < bt) return -1; else if(ag > bg) return 1; else if(ag < bg) return -1; else return Molpy.NameSort(a,b); } Molpy.FormatPrice = function(monies, item) { return Molpify(Math.floor(EvalMaybeFunction(monies, item, 1) * Molpy.priceFactor), 1); } Molpy.ToggleView = function(name, val) { if(!name) return; var sh = Molpy.activeLayout.boxVis; if(val == undefined) { sh[name] = !sh[name]; } else { sh[name] = val == true;//ensure boolean for jQuery } $('#' + 'section' + name).toggleClass('hidden', !sh[name]); $('#toggle' + name).toggleClass('depressed', sh[name]); if(name == 'Export') $('.exportButton').toggleClass('depressed', sh[name]); if(sh[name]) { var refresh = Molpy['Refresh' + name]; if(refresh) refresh(); } else { var cleanup = Molpy['Cleanup' + name]; if(cleanup) cleanup(); } } Molpy.selectedFave = 'None'; Molpy.SelectFave = function(f) { Molpy.selectedFave = f.options[f.selectedIndex].value; $('#faveControls').toggleClass('hidden', Molpy.selectedFave == 'None'); $('#toggleFave').toggleClass('depressed', Molpy.activeLayout.faves[Molpy.selectedFave].vis == true); } Molpy.ConfigureFave = function(n) { Molpy.Anything = 1; if(n == undefined) n = Molpy.selectedFave; var f = Molpy.activeLayout.faves[n]; var def = 'Chromatic Heresy'; if(f.boost) def = f.boost.name; var name = prompt('Enter the name of the boost or badge you wish to display as Favourite ' + n + '.\nNames are case sensitive.\nLeave blank to disable.', def); if(name == undefined) return; if(name) { var item = Molpy.Boosts[name]; if(!item) { item = Molpy.Boosts[Molpy.BoostAKA[name]]; } if(!item) { item = Molpy.Badges[name]; } if(!item) { item = Molpy.Badges[Molpy.BadgeAKA[name]]; } if(item) { if(!(item.bought || item.earned)) { Molpy.Notify('You do not own ' + item.name, 1); } else { f.boost = item; Molpy.Notify('You have chosen ' + item.name + ' as Favourite ' + n, 0); Molpy.UnlockBoost('Sand'); Molpy.UnlockBoost('Castles'); } } } else { f.boost = 0; } f.BoostToScreen(); } Molpy.ToggleFave = function(n, val) { Molpy.Anything = 1; if(n == undefined) n = Molpy.selectedFave; var name = 'sectionFave' + n; var f = Molpy.activeLayout.faves; if(val == undefined) { f[n].vis = !f[n].vis; } else { f[n].vis = val == true;//ensure boolean for jQuery } if(f[n].vis && f[n].boost) f[n].boost.Refresh(); $('#' + name).toggleClass('hidden', !f[n].vis); $('#toggleFave').toggleClass('depressed', f[n].vis); } Molpy.ToggleViews = function(views) { var primary = views[0]; var vis = Molpy.activeLayout.boxVis; Molpy.ToggleView(primary); if(vis[primary]) { for( var i in views) { if(+i) Molpy.ToggleView(views[i], false); } } else { Molpy.ToggleView(views[1], true); } } Molpy.RefreshStats = function() { if(!Molpy.molpish) return; Molpy.EarnBadge('Far End of the Bell Curve'); Molpy.allNeedRepaint = 1; Molpy.UpdateFaves(1); } Molpy.CleanupStats = Molpy.RefreshStats; Molpy.RefreshExport = function() { if(!Molpy.molpish) return; _gaq && _gaq.push(['_trackEvent', 'Export', 'Begin']); var threads = Molpy.ToNeedlePulledThing(); _gaq && _gaq.push(['_trackEvent', 'Export', 'Complete']); var thread = ''; for( var i in threads) { thread += threads[i] } g('exporttext').value = Molpy.CuegishToBeanish(thread); } Molpy.RefreshLayouts = function() { if(!Molpy.molpish) return; Molpy.layoutNeedRepaint = 1; } Molpy.RefreshQuickLayout = Molpy.RefreshLayouts; Molpy.UpdateColourScheme = function() { var heresy = ''; if(g('game')) { if(Molpy.Got('Chromatic Heresy') && Molpy.Boosts['Chromatic Heresy'].power > 0) { heresy = ' heresy' } Molpy.UpdateBeach(); } if(Molpy.options.colourscheme) { document.body.className = 'lightscheme' + heresy; } else { document.body.className = 'darkscheme' + heresy; } } Molpy.AdjustFade = function() { var val = ''; if(Molpy.options.fade) { for( var i in fadeProps) { if(+i) val += ', '; val += fadeProps[i] + ' ' + Molpy.options.fade / 2 + 's ease-out'; } } var fc = $(fadeClasses); for( var j in vendors) fc.css(vendors[j] + 'transition', val); if(Molpy.options.fade) { val = ',background-image ' + Molpy.options.fade / 2 + 's ease-out'; } var fc = $('#beach'); for( var j in vendors) fc.css(vendors[j] + 'transition', 'opacity 0.1s ease-out,' + vendors[j] + 'transform 0.1s ease-out' + val); } if(!g('game')) { Molpy.Load(); if(g('indexversion')) { g('indexversion').innerHTML = 'The Game of Time. Version ' + Molpy.version + (Molpy.versionName?' '+Molpy.versionName:''); } else { Molpy.StartIdle = function() { if(!Molpy.supportsLocalStorage) { g('idlescore').innerHTML = 'localstorage not supported'; return; } var score = parseFloat(localStorage['idlescore']) || 0; var prestige = parseFloat(localStorage['idleprestige']) || 0; if(!Molpy.forcedReload) { prestige += score; score = 0; } g('idlescore').innerHTML = 'Score: ' + Molpify(score, 3); g('idleprestige').innerHTML = 'Prestige: ' + Molpify(prestige, 3); localStorage['idlescore'] = score; localStorage['idleprestige'] = prestige; setTimeout(Molpy.Idle, 1000); } Molpy.Idle = function() { var score = parseFloat(localStorage['idlescore']) || 0; var prestige = parseFloat(localStorage['idleprestige']) || 0; inc = 1 + Math.max(0, Math.floor(Math.log(prestige) * Math.LOG2E)); score += inc; g('idlescore').innerHTML = 'Score: ' + Molpify(score, 3); localStorage['idlescore'] = score; if(score % 1000 == 0) _gaq && _gaq.push(['_trackEvent', 'PureIdle', 'Milestone', '' + score]); setTimeout(Molpy.Idle, 1000); } } return; } createClockHand(); var fadeClasses = 'body , .floatbox , .lootbox , .minifloatbox , .floatsquare , .infobox , .icon , .descshow , .deschide , .badge.shop h1, #toolSTitle, #toolCTitle, #boostTitle'; var vendors = ['-webkit-', '-moz-', '-o-', '-ms-', '']; var fadeProps = ['color', 'border-color', 'background-color', 'background-image']; Molpy.unlockedGroups = {}; Molpy.PaintLootToggle = function(gr, kind) { var str = ''; if(Molpy.unlockedGroups[gr]) { var type = kind == 4 ? 'boost' : 'badge'; var id = Molpy.groupNames[gr][2] || ''; if(id) id = ' id="' + id + '"'; var r = (Molpy.Redacted.location == kind && Molpy.Redacted.group == gr); if(r) id = ''; str += '<div class="floatsquare loot ' + (r ? 'redacted-area ' : '') + type + '"><h3>' + Molpy.groupNames[gr][1] + '</h3><br>' + Molpy.ShowhideButton(gr) + '<div class="icon' + (r ? ' redacted"' : '"') + id + '></div></div>'; } return str; } Molpy.RepaintLootSelection = function() { Molpy.lootSelectionNeedRepaint = 0; var str = ''; var groups = ['boosts', 'stuff', 'land', 'ninj', 'cyb', 'hpt', 'bean', 'chron', 'dimen', 'ceil', 'drac', 'prize', 'varie','faves']; for( var i in groups) { str += Molpy.PaintLootToggle(groups[i], 4); } if(Molpy.BadgesOwned) { var r = Molpy.Redacted.location == 5 && Molpy.Redacted.group == 'badges'; str += '<div class="floatsquare badge loot' + (r ? ' redacted-area' : '') + '"><h3>Badges<br>Earned</h3>' + Molpy.ShowhideButton('badges') + '<div id="badges" class="icon ' + (r ? 'redacted' : '') + '"></div></div>'; } var groups = ['discov', 'monums', 'monumg', 'diamm']; for( var i in groups) { str += Molpy.PaintLootToggle(groups[i], 5); } if(Molpy.BadgeN - Molpy.BadgesOwned) { var r = Molpy.Redacted.location == 6; str += '<div class="floatsquare badge shop' + (r ? ' redacted-area' : '') + '"><h3>Badges<br>Available</h3>' + Molpy.ShowhideButton('badgesav') + '<div id ="badgesAv" class="icon ' + (r ? 'redacted' : '') + '"></div></div>'; } if(Molpy.Boosts['Chromatic Heresy'].unlocked) { var r = Molpy.Redacted.location == 7; str += '<div class="floatsquare boost loot' + (r ? ' redacted-area' : ' alert') + '"><h3>Tagged<br>Items</h3>' + Molpy.ShowhideButton('tagged') + '<div id="tagged" class="icon ' + (r ? 'redacted' : '') + '"></div></div>'; } g('lootselection').innerHTML = str; } Molpy.removeGroupFromDispObjectsCategory = function(group, category) { for(var i in group) { var thing = group[i]; var index = $.inArray(thing, Molpy.dispObjects[category]); if(index > -1) { Molpy.removeDiv(thing); Molpy.dispObjects[category].splice(index, 1); } } } Molpy.removeAllObjectDivs = function() { for(var i in Molpy.SandTool) Molpy.removeDiv(Molpy.SandTool[i]); for(var i in Molpy.CastleTool) Molpy.removeDiv(Molpy.CastleTool[i]); for(var i in Molpy.Boosts) Molpy.removeDiv(Molpy.Boosts[i]); for(var i in Molpy.Badges) Molpy.removeDiv(Molpy.Badges[i]); } Molpy.removeAllDisplayedDivs = function() { for(var grp in Molpy.dispObjects) { Molpy.removeGroupDivs(Molpy.dispObjects[grp]); } } Molpy.removeGroupDivs = function(group) { for(var obj in group) { Molpy.removeDiv(group[obj]); } } Molpy.removeDiv = function(object) { if(object.hasDiv()) { object.divElement.remove(); object.divElement = null; } } Molpy.repaintAll = function() { Molpy.allNeedRepaint = 0; Molpy.CalcPriceFactor(); Molpy.repaintLoot(); Molpy.repaintShop(); Molpy.repaintTools(); Molpy.repaintFaves(); } Molpy.restoreLootScroll = true; Molpy.getScrollLoc = function(divString) { // var div = $(divString); // var pos = [div.scrollTop(), div.scrollLeft()]; // return pos; } Molpy.setScrollLoc = function(divString, pos) { // var div = $(divString); // div.scrollTop(pos[0]).scrollLeft(pos[1]); } Molpy.lootPerPage = 20; Molpy.lootPerPageBox = $('#navPerPage'); Molpy.lootPageNum = 1; Molpy.lootPageNumBox = $('#navPageNum'); Molpy.lootPageNumMax = $('#navMaxPages'); Molpy.changeLootPage = function(change) { Molpy.Anything = 1; if(change != 'max' && change != 'first') Molpy.lootPageNum += change; else if(change == 'first') Molpy.lootPageNum = 1; else if(change == 'max') Molpy.lootPageNum = 'max'; Molpy.restoreLootScroll = false; Molpy.lootNeedRepaint = 1; } Molpy.checkLootNums = function(force) { var perPage = parseInt(Molpy.lootPerPageBox.val()); var pageNum = parseInt(Molpy.lootPageNumBox.val()); if((force || !Molpy.lootPerPageBox.is(':focus')) && !isNaN(perPage) && perPage != Molpy.lootPerPage) { Molpy.lootPerPage = perPage; Molpy.lootNeedRepaint = 1; } if((force || !Molpy.lootPageNumBox.is(':focus')) && !isNaN(pageNum) && pageNum != Molpy.lootPageNum) { Molpy.lootPageNum = pageNum; Molpy.lootNeedRepaint = 1; } } Molpy.lootNavBoxChanged = function(e) { if (!e) e = window.event; var keyCode = e.keyCode || e.which; if (keyCode == '13'){ // Enter pressed Molpy.checkLootNums(true); } } Molpy.searchList = []; Molpy.lootSearchBoxChanged = function(e) { if (!e) e = window.event; var keyCode = e.keyCode || e.which; if (keyCode == '13'){ // Enter pressed Molpy.searchLoot(); } } Molpy.searchLoot = function() { Molpy.Anything = 1; Molpy.ShowhideToggle('search', true); Molpy.restoreLootScroll = false; Molpy.lootNeedRepaint = 1; } Molpy.repaintLoot = function() { Molpy.lootNeedRepaint = 0; var pos = null; if(!noLayout) pos = Molpy.getScrollLoc('#loot'); if(noLayout) pos = Molpy.getScrollLoc('#inventory'); if(Molpy.lootPerPage < 1) Molpy.lootPerPage = 1; if(Molpy.lootPageNum < 1) Molpy.lootPageNum = 1; //clear out all the old loot stuff Molpy.removeGroupDivs(Molpy.dispObjects.boosts); Molpy.removeGroupDivs(Molpy.dispObjects.badges); Molpy.removeGroupDivs(Molpy.dispObjects.tagged); Molpy.removeGroupDivs(Molpy.dispObjects.faves); Molpy.removeGroupDivs(Molpy.dispObjects.search); Molpy.dispObjects.boosts = []; Molpy.dispObjects.badges = []; Molpy.dispObjects.tagged = []; Molpy.dispObjects.faves = []; Molpy.dispObjects.search = []; var taggedList = Molpy.TaggedLoot; var favesList = []; for(var i in Molpy.Boosts.favs.FavesList) { favesList.push(Molpy.BoostsById[Molpy.Boosts.favs.FavesList[i]]); } var boostList = []; var badgeList = []; var maxPageNum = 1; var startIndex = 0; var endIndex = 0; if(Molpy.activeLayout.lootVis.search) { Molpy.searchList = []; var searchText = $('#lootSearchBox').val().toLowerCase(); if($('#searchBoosts').prop('checked') || !$('#searchBadges').prop('checked')){ for(var i in Molpy.BoostsBought) { var me = Molpy.BoostsBought[i]; if(me.name && me.name.toLowerCase().indexOf(searchText) >= 0) Molpy.searchList.push(me); } } if($('#searchBadges').prop('checked')){ for(var i in Molpy.BadgesEarned) { var me = Molpy.BadgesEarned[i]; if(me.name && me.name.toLowerCase().indexOf(searchText) >= 0) Molpy.searchList.push(me); } for(var i in Molpy.BadgesAvailable) { var me = Molpy.BadgesAvailable[i]; if(me.name && me.name.toLowerCase().indexOf(searchText) >= 0) Molpy.searchList.push(me); } for(var i in Molpy.DiscovMonumEarned) { var me = Molpy.DiscovMonumEarned[i]; if(me.name && me.name.toLowerCase().indexOf(searchText) >= 0) Molpy.searchList.push(me); } } maxPageNum = Math.ceil(Molpy.searchList.length / Molpy.lootPerPage); } else if(Molpy.activeLayout.lootVis.tagged) { maxPageNum = Math.ceil(taggedList.length / Molpy.lootPerPage); } else if(Molpy.activeLayout.lootVis.faves) { maxPageNum = Math.ceil(favesList.length / Molpy.lootPerPage); } else { // Setup Boost list for use for(var i in Molpy.BoostsBought) { var me = Molpy.BoostsBought[i]; if(Molpy.activeLayout.lootVis[me.group] && me.bought >= me.unlocked) boostList.push(me); } // Setup Badge list for use for(var i in Molpy.BadgesEarned) { var me = Molpy.BadgesEarned[i]; if(Molpy.activeLayout.lootVis[me.group]) badgeList.push(me); } for(var i in Molpy.BadgesAvailable) { var me = Molpy.BadgesAvailable[i]; if(Molpy.activeLayout.lootVis.badgesav) badgeList.push(me); } for(var i in Molpy.DiscovMonumEarned) { var me = Molpy.DiscovMonumEarned[i]; if(Molpy.activeLayout.lootVis[me.group]) badgeList.push(me); } maxPageNum = Math.ceil((boostList.length + badgeList.length) / Molpy.lootPerPage); } BoostNum = boostList.length; BoostList = boostList.slice(0); if(Molpy.lootPageNum == 'max') Molpy.lootPageNum = maxPageNum; if(Molpy.lootPageNum > maxPageNum) Molpy.lootPageNum = maxPageNum; startIndex = (Molpy.lootPageNum - 1 ) * Molpy.lootPerPage; endIndex = startIndex + Molpy.lootPerPage - 1; if(Molpy.activeLayout.lootVis.search && Molpy.searchList.length> 0){ Molpy.addGroupToDiv($('#loot'), Molpy.searchList, startIndex, endIndex, 'search', {autoAdd: true, recalc: false}); } else if(Molpy.activeLayout.lootVis.tagged && taggedList.length > 0) { Molpy.addGroupToDiv($('#loot'), taggedList, startIndex, endIndex, 'tagged', {autoAdd: true, recalc: false}); } else if(Molpy.activeLayout.lootVis.faves && favesList.length > 0) { Molpy.addGroupToDiv($('#loot'), favesList, startIndex, endIndex, 'faves', {autoAdd: true, recalc: false}); } else if(!(boostList.length == 0 && badgeList.length == 0)) { var boostStartIndex = 0; var boostEndIndex = -1; var badgeStartIndex = 0; var badgeEndIndex = -1; if(boostList.length < startIndex) { badgeStartIndex = startIndex - boostList.length; badgeEndIndex = endIndex - boostList.length; } else { boostStartIndex = startIndex; if(boostList.length > endIndex){ boostEndIndex = endIndex; } else { boostEndIndex = boostList.length - 1; badgeEndIndex = endIndex - boostList.length; } } Molpy.addGroupToDiv($('#loot'), boostList, boostStartIndex, boostEndIndex, 'boosts', {autoAdd: true, recalc: false}); Molpy.addGroupToDiv($('#loot'), badgeList, badgeStartIndex, badgeEndIndex, 'badges', {autoAdd: true, recalc: false}); } if(Molpy.restoreLootScroll) { if(!noLayout) Molpy.setScrollLoc('#loot', pos); else Molpy.setScrollLoc('#inventory', pos); } Molpy.restoreLootScroll = true; if(!Molpy.lootPerPageBox.is(':focus')) Molpy.lootPerPageBox.val(Molpy.lootPerPage); if(!Molpy.lootPageNumBox.is(':focus')) Molpy.lootPageNumBox.val(Molpy.lootPageNum); Molpy.lootPageNumMax.text(maxPageNum); Molpy.UnlockBoost('Chromatic Heresy'); } Molpy.repaintShop = function() { Molpy.shopNeedRepaint = 0; var pos = null; if(!noLayout) pos = Molpy.getScrollLoc('#boosts'); Molpy.removeGroupDivs(Molpy.dispObjects.shop); Molpy.dispObjects.shop = []; var shopList = []; for( var i in Molpy.Boosts) { var boost = Molpy.Boosts[i]; if(boost.bought < boost.unlocked) shopList.push(boost); } if(Molpy.options.boostsort > 0) shopList.sort(Molpy.NameSort); else shopList.sort(Molpy.PriceSort); Molpy.addGroupToDiv($('#boosts'), shopList, 0, shopList.length - 1, 'shop', {autoAdd: true, recalc: true}); if(!noLayout) Molpy.setScrollLoc('#boosts', pos); } Molpy.repaintTools = function(args) { if(!args) args = {}; Molpy.toolsNeedRepaint = 0; // this causes scroll location to mess up, but is faster // would be good to write it so skipclear can be true //Molpy.removeGroupDivs(Molpy.dispObjects.tools); //Molpy.dispObjects.tools = []; Molpy.CalcPriceFactor(); Molpy.repaintSandTools({skipClear: false, recalc: false}); Molpy.repaintCastleTools({skipClear: false, recalc: false}); } Molpy.repaintSandTools = function(args) { if(!args) args = {}; Molpy.sandToolsNeedRepaint = 0; var pos = null; if(!noLayout) pos = Molpy.getScrollLoc('#sandtools'); // Remove all Sand Tools from dispObjects for a fresh start if(!args.skipClear) { Molpy.removeGroupFromDispObjectsCategory(Molpy.SandTools, 'tools'); } var toolsUnlocked = 1; for(var i in Molpy.SandToolsById){ if(Molpy.SandToolsById[i].bought >= Molpy.SandToolsById[i].nextThreshold) toolsUnlocked ++; } var max = Math.min(toolsUnlocked -1 , Molpy.SandToolsN - 1); var dorecalc = args.recalc == false ? false : true; Molpy.addGroupToDiv($('#sandtools'), Molpy.SandToolsById, 0, max, 'tools', {autoAdd: true, recalc: dorecalc}); if(!noLayout) Molpy.setScrollLoc('#sandtools', pos); } Molpy.repaintCastleTools = function(args) { if(!args) args = {}; Molpy.castleToolsNeedRepaint = 0; var pos = null; if(!noLayout) pos = Molpy.getScrollLoc('#castletools'); // Remove all Castle Tools from dispObjects for a fresh start if(!args.skipClear) { Molpy.removeGroupFromDispObjectsCategory(Molpy.CastleTools, 'tools'); } var toolsUnlocked = 1; for(var i in Molpy.CastleToolsById){ if(Molpy.CastleToolsById[i].bought >= Molpy.CastleToolsById[i].nextThreshold) toolsUnlocked ++; } var max = Math.min(toolsUnlocked - 1, Molpy.CastleToolsN - 1); var dorecalc = args.recalc == false ? false : true; Molpy.addGroupToDiv($('#castletools'), Molpy.CastleToolsById, 0, max, 'tools', {autoAdd: true, recalc: dorecalc}); if(!noLayout) Molpy.setScrollLoc('#castletools', pos); } Molpy.repaintBoosts = function() { Molpy.boostNeedRepaint = 0; Molpy.badgesNeedRepaint = 0; // This includes all badge calls Molpy.repaintShop(); Molpy.repaintLoot(); Molpy.repaintFaves(); } Molpy.repaintBadges = function() { Molpy.badgeNeedRepaint = 0; Molpy.repaintLoot(); Molpy.repaintFaves(); } Molpy.repaintFaves = function() { Molpy.favesNeedRepaint = 0; //Molpy.dispObjects.faves = []; } Molpy.repaintRedacted = function() { Molpy.redactedNeedRepaint = 0; if(Molpy.Redacted.location == 0 /*|| !Molpy.PuzzleGens.redacted.active*/) return; var redDiv = Molpy.Redacted.divList[Molpy.Redacted.location]; if (0 && !Molpy.PuzzleGens.redacted.active ) { Molpy.Redacted.getDiv().detach(); // Take it out of where it is in case it exists already Molpy.Redacted.location = 0; return; } // Make sure the div is an open one, if not, re jump and set it again if(!redDiv || !redDiv.is(':visible')) { Molpy.Redacted.getDiv().detach(); // Take it out of where it is in case it exists already Molpy.Redacted.jump(); if(Molpy.Redacted.location == 0) return; // No available spots to spawn redDiv = Molpy.Redacted.divList[Molpy.Redacted.location]; } else if (Molpy.Redacted.keepPosition == 2) return else Molpy.Redacted.getDiv().detach(); // Take it out of where it is in case it exists already Molpy.Redacted.titleList[Molpy.Redacted.location].toggleClass('redacted-area', true); // Find max Index var maxIndex = 0; var lootArray = null; if(Molpy.Redacted.location <= 3) { maxIndex = redDiv.children().length + 1; } else if(Molpy.Redacted.location >= 4 && Molpy.Redacted.location <= 7) { if(Molpy.Redacted.location == 4) lootArray = Molpy.BoostsBought; else if(Molpy.Redacted.location == 5) lootArray = Molpy.BadgesEarned; else if(Molpy.Redacted.location == 6) lootArray = Molpy.BadgesAvailable; else if(Molpy.Redacted.location == 7) lootArray = Molpy.TaggedLoot; else if(Molpy.Redacted.location == 8) lootArray = Molpy.Boosts.favs.FavesList; maxIndex = lootArray.length; Molpy.lootSelectionNeedRepaint = 1; } // If a position is invalid, get a random new position if(Molpy.Redacted.dispIndex == -1 || Molpy.Redacted.dispIndex > maxIndex) { Molpy.Redacted.dispIndex = Math.floor(maxIndex * Math.random()); } if(Molpy.Redacted.location >= 4 && Molpy.Redacted.location <= 6) { if (!lootArray || !lootArray.length) { Molpy.Redacted.location = 0; return; }; if(Molpy.Redacted.dispIndex > lootArray.length -1) Molpy.Redacted.group = lootArray[lootArray.length - 1].group; else Molpy.Redacted.group = lootArray[Molpy.Redacted.dispIndex].group; } // Figure out where it will go var specialIndex = -1; if(Molpy.Redacted.location >= 4 && Molpy.Redacted.location <= 7) { if(lootArray[Molpy.Redacted.dispIndex] && lootArray[Molpy.Redacted.dispIndex].hasDiv()) { var div = lootArray[Molpy.Redacted.dispIndex].getDiv({}); specialIndex = div ? div.index(): Molpy.Redacted.dispIndex; } } else { specialIndex = Molpy.Redacted.dispIndex; } if(specialIndex == 0) { redDiv.prepend(Molpy.Redacted.getDiv()); } else if(specialIndex > redDiv.children().length - 1) { redDiv.append(Molpy.Redacted.getDiv()); } else if(specialIndex > 0){ redDiv.children().eq(specialIndex).before(Molpy.Redacted.getDiv()); } if (Molpy.Redacted.keepPosition == 1 && specialIndex != -1) { // Molpy.Notify('Setting keepPosition to 2',1); Molpy.Redacted.keepPosition=2; } } Molpy.addGroupToDiv = function(whichDiv, group, startIndex, maxIndex, dispCat, args) { if(!args) args = {}; if(args.recalc) Molpy.CalcPriceFactor(); var fnew = args.forceNew || true; var addHover = args.hover || true; var i = startIndex; while(i <= maxIndex && i < group.length) { var nh = false; var object = group[i]; // If mouse is currently hovering over this, it will start hovered var overID = '' + object.name + object.id; if(Molpy.mouseIsOver == overID) nh = true; whichDiv.append(object.getDiv({forceNew: fnew, hover: addHover, nohide: nh})); if(args.autoAdd) { var suc = Molpy.dispObjects[dispCat].push(object); } else { if($.inArray(object, Molpy.dispObjects[dispCat]) == -1) Molpy.dispObjects[dispCat].push(object); } i ++; } Molpy.redactedNeedRepaint = 1; } Molpy.updateShop = function() { for(var i in Molpy.dispObjects.shop) Molpy.dispObjects.shop[i].updateAll(); } Molpy.updateTools = function() { for(var i in Molpy.dispObjects.tools) Molpy.dispObjects.tools[i].updateAll(); } Molpy.updateLoot = function() { for(var grp in Molpy.dispObjects) if(grp != 'boosts' || grp != 'tagged' || grp != 'faves') continue; for(var i in Molpy.dispObject[grp]) Molpy.dispObjects[grp][i].updateAll(); } Molpy.updateBoosts = function() { for(var grp in Molpy.dispObjects) if(grp != 'boosts' || grp != 'tagged' || grp != 'faves') continue; for(var i in Molpy.dispObject[grp]) Molpy.dispObjects[grp][i].updateAll(); } //the numbers that fly up when you click the pic for sand Molpy.sParticles = []; var str = ''; for( var i = 0; i < 20; i++) { Molpy.sParticles[i] = { x: 0, y: 0, dx: 0, life: -1, text: '' }; str += '<div id="sparticle' + i + '" class="notif"></div>'; } g('sparticles').innerHTML = str; Molpy.sparticlesUpdate = function() { for( var i in Molpy.sParticles) { var me = Molpy.sParticles[i]; if(me.life != -1) { me.y -= 300 / Molpy.fps; me.x += me.dx / Molpy.fps; me.life++; var el = me.l; me.l.style.left = Math.floor(me.x) + 'px'; me.l.style.top = Math.floor(me.y) + 'px'; el.style.opacity = 1;//-(me.life/(Molpy.fps*2)); if(me.life >= Molpy.fps * 2) { me.life = -1; el.style.opacity = 0; el.style.display = 'none'; } } } } Molpy.LayoutString = function(i) { var me = Molpy.layouts[i]; var h = '<h1>' + me.name + '</h1>'; var str = '<div class="layout minifloatbox">' + h; str += '<div class="minifloatbox layoutcontrol' + (me == Molpy.activeLayout ? ' depressed' : '') + '"><a onclick="Molpy.layouts[' + i + '].Activate()">Activate</a></div>'; str += '<div class="minifloatbox layoutcontrol"><a onclick="Molpy.layouts[' + i + '].Rename()">Rename</a></div>'; str += '<div class="minifloatbox layoutcontrol"><a onclick="Molpy.layouts[' + i + '].Clone()">Clone</a></div>'; str += '<div class="minifloatbox layoutcontrol"><a onclick="Molpy.layouts[' + i + '].Overwrite()">Overwrite</a></div>'; str += '<div class="minifloatbox layoutcontrol exportButton"><a onclick="Molpy.layouts[' + i + '].Export()">Export</a></div>'; if(me != Molpy.activeLayout) str += '<div class="minifloatbox layoutcontrol"><a onclick="Molpy.layouts[' + i + '].Delete()">Delete</a></div>'; return str + '</div>'; } Molpy.RepaintLayouts = function() { Molpy.layoutNeedRepaint = 0; if(noLayout) return; if(Molpy.activeLayout.boxVis['Layouts']) { var str = ''; for( var i in Molpy.layouts) { str += Molpy.LayoutString(i); } g('layouts').innerHTML = str; } if(Molpy.activeLayout.boxVis['QuickLayout']) { var str = ''; for( var i in Molpy.layouts) { var me = Molpy.layouts[i]; str += '<div class="minifloatbox layoutcontrol' + (me === Molpy.activeLayout ? ' depressed' : '') + '"><a onclick="Molpy.layouts[' + i + '].Activate()">' + me.name + '</a></div>' } g('quickLayouts').innerHTML = str; } } Molpy.AddSandParticle = function(text) { //pick the first free (or the oldest) notification to replace it var highest = 0; var highestI = 0; for( var i in Molpy.sParticles) { if(Molpy.sParticles[i].life == -1) { highestI = i; break; } if(Molpy.sParticles[i].life > highest) { highest = Molpy.sParticles[i].life; highestI = i; } } var i = highestI; var rect = g('beach').getBoundingClientRect(); var x = 0; var y = Math.floor((rect.height) * .7); x += (Math.random() - 0.5) * 180; y += (Math.random() - 0.5) * 120; var dx = (Math.random() - 0.5) * 60; var me = Molpy.sParticles[i]; if(!me.l) me.l = g('sparticle' + i); me.life = 0; me.x = x; me.y = y; me.dx = dx; me.text = text; me.l.innerHTML = text; me.l.style.left = Math.floor(me.x) + 'px'; me.l.style.top = Math.floor(me.y) + 'px'; me.l.style.display = 'block'; } //notifications. Molpy.notifs = []; Molpy.notifsY = 0; var str = ''; for( var i = 0; i < 20; i++) { Molpy.notifs[i] = { x: 0, y: 0, life: -1, text: '' }; str += '<div id="notif' + i + '" class="notif"></div>'; } g('notifs').innerHTML = str; Molpy.notifsReceived = 0; Molpy.notifsUpdate = function() { var dy = 10 + Molpy.notifsY/100; Molpy.notifsY = 0; var trans = 0; for( var i in Molpy.notifs) { var me = Molpy.notifs[i]; if(me.life != -1) { if(me.life < Molpy.fps * 3) Molpy.notifsY += me.l.clientHeight; var y = me.y; if(me.life < Molpy.fps / 2) { y -= dy; } else { y -= dy * (1 - (me.life - Molpy.fps / 2) / (Molpy.fps * 5)); } me.y = y; me.life++; var el = me.l; el.style.left = Math.floor(-200 + me.x) + 'px'; el.style.bottom = Math.floor(-y) + 'px'; if(trans < 9) { el.style.opacity = 1 - Math.pow(me.life / (Molpy.fps * 5), 2); trans++; } else { el.style.opacity = 1; } if(me.life >= Molpy.fps * 5) { me.life = -1; el.style.opacity = 0; el.style.display = 'none'; } } } } Molpy.Log = function() { this.np = Math.floor(Molpy.newpixNumber); this.time = moment(); this.text = []; this.qty = []; this.joinedString = function() { str = ""; for (i = 0; i < this.text.length; i++){ str += "<div \">" + this.text[i]; if (this.qty[i] > 1) str += "(x" + this.qty[i] + ")"; str +="</div>"; } return str; } return this; } Molpy.ClearLog = function() { Molpy.Anything = 1; Molpy.logArchive = [] Molpy.logArchive[0] = new Molpy.Log(); Molpy.logArchive[0].text.push("Loading..."); Molpy.logArchive[0].qty.push(1); Molpy.currentLog = 0; Molpy.selectedLog = 0; Molpy.notifLogPaint = 1; Molpy.logUpdatePaint = 0; g('logCurrent').value="Current"; } Molpy.ClearLog(); Molpy.InMyPants = 0; Molpy.CleanLogs = function() { //gets rid of older logs if (!Molpy.options.loglimit) return; if (Molpy.logArchive.length > Molpy.options.loglimit) { Molpy.logArchive.shift(); Molpy.currentLog--; Molpy.selectedLog--; if (Molpy.selectedLog < 0) Molpy.selectedLog = 0; Molpy.notifLogPaint = 1; Molpy.CleanLogs(); // In case more need to go } } Molpy.LogONG = function(){ Molpy.currentLog++; Molpy.selectedLog = Molpy.currentLog; Molpy.logArchive[Molpy.selectedLog] = new Molpy.Log(); Molpy.notifLogPaint = 1; Molpy.CleanLogs(); } Molpy.LogBack = function(){ Molpy.Anything = 1; if (Molpy.selectedLog > 0){ Molpy.selectedLog--; Molpy.notifLogPaint = 1; } } Molpy.LogForward = function(){ Molpy.Anything = 1; if (Molpy.selectedLog < Molpy.currentLog){ Molpy.selectedLog++; Molpy.notifLogPaint = 1; if (Molpy.selectedLog == Molpy.currentLog) g('logCurrent').value="Current"; } } Molpy.LogCurrent = function(){ Molpy.Anything = 1; if (Molpy.selectedLog != Molpy.currentLog){ Molpy.selectedLog = Molpy.currentLog; Molpy.notifLogPaint = 1; } else { var log = g('logItems'); log.scrollTop = log.scrollHeight; } g('logCurrent').value="Current"; } Molpy.logLengths = [Infinity,1,5,10,20,50,100]; Molpy.Notify = function(text, importance,nolog) { if(importance==undefined) importance=0; if(Molpy.InMyPants) text += ' in my pants'; text = format(text); if(importance + 1 >= Molpy.options['notifsilence'] && !nolog){ var log = Molpy.logArchive[Molpy.currentLog]; if (log.text[log.text.length - 1] == text){ log.qty[log.text.length - 1] ++; } else { log.text.push(text); log.qty.push(1); if(log.text.length > Molpy.logLengths[Molpy.options['loglength']]){ log.text.splice(0, Molpy.logLengths[Molpy.options['loglength']] - log.text.length); log.qty.splice(0, Molpy.logLengths[Molpy.options['loglength']] - log.text.length); } } Molpy.logUpdatePaint = 1; } if(Molpy.options['notifsilence']>importance){return;} //pick the first free (or the oldest) notification to replace it var highest = 0; var highestI = 0; for( var i in Molpy.notifs) { if(Molpy.notifs[i].life == -1) { highestI = i; break; } if(Molpy.notifs[i].life > highest) { highest = Molpy.notifs[i].life; highestI = i; } } var i = highestI; var x = Math.floor($(window).width() / 2); var y = Math.floor($(window).height() * 0.95); x += (Math.random() - 0.5) * 40; var me = Molpy.notifs[i]; if(!me.l) me.l = g('notif' + i); me.life = 0; me.x = x; me.y = y + Molpy.notifsY; me.text = text; me.l.innerHTML = text; me.l.style.left = Math.floor(Molpy.notifs[i].x - 200) + 'px'; me.l.style.bottom = Math.floor(-Molpy.notifs[i].y) + 'px'; me.l.style.display = 'block'; Molpy.notifsY += me.l.clientHeight; me.y += me.l.clientHeight; Molpy.notifsReceived++; Molpy.EarnBadge('Notified'); if(Molpy.notifsReceived >= 2000) { Molpy.EarnBadge('Thousands of Them!'); } } Molpy.PaintLogUpdate = function() { Molpy.logUpdatePaint = 0; g('logCurrent').value="*NEW*" if(Molpy.currentLog == Molpy.selectedLog){ var log = g('logItems'); var scroll = (log.scrollTop == (log.scrollHeight - log.clientHeight)); log.innerHTML = Molpy.logArchive[Molpy.selectedLog].joinedString(); if(scroll) { log.scrollTop = log.scrollHeight; g('logCurrent').value="Current"; } } Molpy.logArchive[Molpy.currentLog].string += Molpy.logBuffer; Molpy.logBuffer = ""; } Molpy.PaintNotifLog = function() { Molpy.notifLogPaint = 0; var title = g('logTitle'); var today = Molpy.logArchive[Molpy.selectedLog].time; var h = today.hours(); var m = today.minutes(); if(m < 10) m = "0" + m; title.title = h + ":" + m; title.innerHTML = "Notification log for Newpix " + Molpy.logArchive[Molpy.selectedLog].np; var log = g('logItems'); log.innerHTML = Molpy.logArchive[Molpy.selectedLog].joinedString(); log.scrollTop = log.scrollHeight; } Molpy.subPixLetters = ['', 'a', 'b', 'c', 'd', 'e']; Molpy.fixLength=function(a,l){ a=String(a) if(a.length<l){return Molpy.fixLength('0'+String(a),l)} else{return a} } Molpy.FormatNP = function(np, format) { var minus = (np < 0); var subp = Molpy.subPixLetters[Molpy.currentSubFrame]; return (minus ? '-' : '') + np + subp; } Molpy.NewPixFloor=function(num){ if((num>=1)||(num<0)){num=num-Math.floor(num)} num=Number(num.toFixed(3)) return ['t1i-'][Number(Molpy.fracParts.indexOf(num))] } Molpy.NewPixFor = function(np) { np=Math.abs(np) var newp = Molpy.FormatNP(np); var floor = Math.floor(np); var frac=np-floor frac=Number(Number(frac.toFixed(3))) var x = 200 + flandom(200); var y = 200 + flandom(400); if(np===0) return 'http://xkcd.mscha.org/tmp/np0.png' if(Molpy.Got('Chromatic Heresy') && Molpy.options.colpix) { if(((floor > 3094)&&(frac==0))||((floor > 1417)&&(frac==0.1))){ return 'http://placekitten.com/'+ (Molpy.IsEnabled('Chromatic Heresy') ? '' : 'g/') + x + '/' + y; }else if(frac==0){ return 'http://139.162.169.39/Time/otcolorization/' + newp; } else if(Molpy.fracParts.indexOf(frac)>-1){ return 'http://xkcd.mscha.org/otcstories/'+Molpy.NewPixFloor(frac)+Molpy.fixLength(floor,4)+'.png' } else if(Molpy.fracParts.indexOf(frac)==-1){return 'http://placekitten.com/g/' + x + '/' + y;} //ErrorCat is error } else { if(((floor > 3094)&&(frac===0))||((floor > 1417)&&(frac===0.1))){ return 'http://placekitten.com/' + (Molpy.IsEnabled('Chromatic Heresy') ? '' : 'g/') +x + '/' + y; } else if(frac==0){ return 'http://xkcd.mscha.org/frame/' + newp; } else if(Molpy.fracParts.indexOf(frac)>-1){ return 'http://xkcd.mscha.org/otcstories/'+Molpy.NewPixFloor(frac)+Molpy.fixLength(floor,4)+'.png' } else if(Molpy.fracParts.indexOf(frac)==-1) {return 'http://placekitten.com/' +(Molpy.IsEnabled('Chromatic Heresy') ? '' : '/g') + x + '/' + y;} //ErrorCat is error } } Molpy.ThumbNewPixFor = function(np) { np = Math.abs(np); var newp = Molpy.FormatNP(np); var floor = Math.floor(np); var frac=np-floor frac=Number(frac.toFixed(3)) if(((floor > 3094)&&(frac==0))||((floor > 1417)&&(frac==0.1))) return 'http://placekitten.com/' + (Molpy.IsEnabled('Chromatic Heresy') ? '' : '/g') +x + '/' + y; else if(frac==0){ return 'http://xkcd.mscha.org/frame/' + newp; } else if(Molpy.fracParts.indexOf(frac)>-1){ return 'http://xkcd.mscha.org/otcstories/'+Molpy.NewPixFloor(frac)+Molpy.fixLength(floor,4)+'.png' } else if(Molpy.fracParts.indexOf(frac)==-1){return 'http://placekitten.com/' + (Molpy.IsEnabled('Chromatic Heresy') ? '' : '/g') +x + '/' + y;} //ErrorCat is error } Molpy.Url = function(address) { return 'url(' + address + ')'; } //call with argument to change to a specific np, otherwise defaults to the current np Molpy.UpdateBeach = function(np) { np = np || Molpy.newpixNumber; g('beach').style.backgroundImage = Molpy.Url(Molpy.NewPixFor(np)); Molpy.preloadedBeach = 0; } Molpy.preloadedBeach = 0; Molpy.PreloadBeach = function(np) { //REMOVED because it's giving people console errors and wasn't working for me anyway: //$.get(Molpy.NewPixFor(np||Molpy.newpixNumber+1)); if(!np) Molpy.preloadedBeach = 1; } /* In which we figure out how to draw stuff +++++++++++++++++++++++++++++++++++++++++++*/ Molpy.drawFrame = 0; Molpy.Draw = function() { var castleAmt = Molpy.Boosts['Castles'].power; //so we don't need lots of lookups g('castlecount').innerHTML = Molpify(castleAmt, 1) + ' castle' + plural(castleAmt); g('sandcount').innerHTML = Molpify(Molpy.Boosts['Sand'].power, 1) + ' sand' + (isFinite(castleAmt) ? ' of ' + Molpify(Molpy.Boosts['Castles'].nextCastleSand, 1) + ' needed' : ''); g('sandrate').innerHTML = Molpify(Molpy.Boosts['Sand'].sandPermNP, 1) + ' sand/mNP'; g('chipcount').innerHTML = Molpify(Molpy.Boosts['TF'].power, 1) + ' chips'; g('chiprate').innerHTML = Molpify(Molpy.Boosts['TF'].loadedPermNP, 1) + ' chips/mNP'; g('newtools').innerHTML = 'Built ' + Molpify(Molpy.toolsBuilt, 1) + ' new tool' + plural(Molpy.toolsBuilt); if(noLayout) { var finite = isFinite(Molpy.Boosts['Sand'].power) || isFinite(castleAmt) || isFinite(Molpy.spmNP); var tf = Molpy.Got('TF'); if (Molpy.TotalDragons) { $('#sectionDragonsNP').removeClass('hidden'); $('#sectionTFCounts').addClass('hidden'); } else if (tf) { $('#sectionTFCounts').removeClass('hidden'); } else { $('#sectionTFCounts').addClass('hidden'); } if(tf) { $('#sectionSandCounts').toggleClass('hidden', !finite); $('#sectionAbout').toggleClass('hidden', finite); } else { $('#sectionSandCounts').removeClass('hidden'); $('#sectionAbout').removeClass('hidden'); } } else { $('#toggleTFCounts').removeClass('hidden'); } var str='Newpix'+(Molpy.newpixNumber<0?' -':' ') + (Math.floor(Math.abs(Molpy.newpixNumber))); if(Molpy.currentStory>=0){str=str+[' of t1i'][Molpy.currentStory]} g('newpixnum').innerHTML = str g('eon').innerHTML = Molpy.TimeEon; g('era').innerHTML = Molpy.TimeEra; g('period').innerHTML = Molpy.TimePeriod; $('.timeflip').toggleClass('flip-horizontal', (Molpy.previewNP ? Molpy.previewNP < 0 : Molpy.newpixNumber < 0)); g('version').innerHTML = '<br>Version: ' + Molpy.version + (Molpy.versionName?'<br>'+Molpy.versionName:''); var npd = Molpy.NPdata[Molpy.newpixNumber]; if (npd && npd.amount) { var dq = Molpy.Boosts['DQ']; var dt = Molpy.DragonsById[npd.DragonType]; var str = Molpify(npd.amount) + ' ' + dt.name + (npd.amount > 1?'s':'') + '<br>'; str += ['Digging','Recovering','Hiding','Celebrating'][dq.overallState]; if (dq.overallState > 0) str += ' for ' + MolpifyCountdown(dq.countdown, 1); str += '<br>'; var Stats = Molpy.DragonStatsNow(Molpy.newpixNumber); str += 'Def: ' + Molpify(Stats.defence,2) + ' Atk: ' + Molpify(Stats.attack+0.001,2) + ' Dig:&nbsp;' + Molpify(Stats.dig,2) ; if (Stats.breath) str += ' Breath:&nbsp;' + Molpify(Stats.breath,2); if (Stats.magic1) str += ' Magic1:&nbsp;' + Molpify(Stats.magic1,2); if (Stats.magic2) str += ' Magic2:&nbsp;' + Molpify(Stats.magic2,2); if (Stats.magic3) str += ' Magic3:&nbsp;' + Molpify(Stats.magic3,2); g('DragonsNP').innerHTML = str; } else { g('DragonsNP').innerHTML = 'No Dragons here'; } if(!noLayout) { g('stuffSandCount').innerHTML = 'Sand: ' + Molpify(Molpy.Boosts['Sand'].power, 3); g('stuffCastleCount').innerHTML = 'Castles: ' + Molpify(castleAmt, 3); g('stuffTFChipCount').innerHTML = 'TF Chips: ' + Molpify(Molpy.Boosts['TF'].Level, 3); for( var i in Molpy.BoostsByGroup['stuff']) { var bst = Molpy.BoostsByGroup['stuff'][i]; if(bst.alias == "Sand" || bst.alias == "Castles") continue; if($('#stuff' + bst.alias + 'Count').length == 0) { $("#stuffItems").append("<div id=\"stuff" + bst.alias + "Count\"></div>"); } if (bst.alias == 'Gold' && bst.Level < 1) { var name = 'Silver'; var amt = bst.Level*1000; if (amt < 1) { name = 'Copper'; amt = Math.round(amt*1000)}; g('stuff' + bst.alias + 'Count').innerHTML = name + ': ' + Molpify(amt, 3); } else { g('stuff' + bst.alias + 'Count').innerHTML = bst.plural + ': ' + Molpify(bst.Level, 3); } $('#stuff' + bst.alias + 'Count').toggleClass('hidden', !Molpy.Got(bst.alias)); } g('incomeSandRate').innerHTML = 'Sand: ' + Molpify(Molpy.Boosts['Sand'].sandPermNP, 1) + '/mNP'; g('incomeSandClickRate').innerHTML = 'Sand/click: ' + Molpify(Molpy.Boosts['Sand'].sandPerClick, 1); g('incomeChipRate').innerHTML = 'TF Chips: ' + Molpify(Molpy.Boosts['TF'].loadedPermNP, 1) + '/mNP'; g('incomeChipClickRate').innerHTML = 'TF Chips/click: ' + Molpify(Molpy.Boosts['TF'].loadedPerClick, 1); g('incomeNewTools').innerHTML = 'Tools: ' + Molpify(Molpy.toolsBuilt, 1) + ' built this mNP'; var tf = Molpy.Got('TF'); $('#stuffTFChipCount').toggleClass('hidden', !tf); $('#incomeChipRate').toggleClass('hidden', !tf); $('#incomeChipClickRate').toggleClass('hidden', !tf); $('#incomeNewTools').toggleClass('hidden', !tf); } var repainted = Molpy.allNeedRepaint || Molpy.shopNeedRepaint || Molpy.boostNeedRepaint || Molpy.badgeNeedRepaint || Molpy.toolsNeedRepaint || Molpy.lootNeedRepaint; Molpy.lootSelectionNeedRepaint = Molpy.allNeedRepaint || Molpy.boostNeedRepaint || Molpy.badgeNeedRepaint || Molpy.lootNeedRepaint || Molpy.lootSelectionNeedRepaint; //var updated = Molpy.shopNeedUpdate || Molpy.toolsNeedUpdate || Molpy.lootNeedUpdate; //TODO want to repaint as little as possible, favoring updates instead if(Molpy.allNeedRepaint) { Molpy.repaintAll(); } if(Molpy.boostNeedRepaint) { Molpy.repaintBoosts(); } if(Molpy.badgeNeedRepaint) { Molpy.repaintBadges(); } if(Molpy.lootNeedRepaint) { Molpy.repaintLoot(); } if(Molpy.shopNeedRepaint) { Molpy.repaintShop(); } if(Molpy.toolsNeedRepaint) { Molpy.repaintTools(); } if(Molpy.layoutNeedRepaint) { Molpy.RepaintLayouts(); } if(Molpy.lootSelectionNeedRepaint) Molpy.RepaintLootSelection(); if(Molpy.shopNeedUpdate) { Molpy.updateShop(); } if(Molpy.toolsNeedUpdate) { Molpy.updateTools(); } if(Molpy.lootNeedUpdate) { Molpy.updateLoot(); } if(Molpy.Redacted.location) Molpy.redactedHighlight(repainted); if(repainted && Molpy.options.fade) Molpy.AdjustFade(); if(repainted) { for( var grp in Molpy.dispObjects) { if(!(grp == 'tools' || grp == 'shop')) continue; for(var i in Molpy.dispObjects[grp]) Molpy.dispObjects[grp][i].updateBuy(); } } if(Molpy.redactedNeedRepaint) Molpy.repaintRedacted(); drawClockHand(); Molpy.PaintStats(); Molpy.UpdateFaves(); Molpy.notifsUpdate(); if(Molpy.notifLogPaint) Molpy.PaintNotifLog(); if(Molpy.logUpdatePaint) Molpy.PaintLogUpdate(); if(Molpy.options.numbers) Molpy.sparticlesUpdate(); Molpy.CheckBeachClass(); Molpy.Boosts['Temporal Rift'].updateRiftIMG(); } Molpy.MiniDraw = function() { Molpy.notifsUpdate(); Molpy.redactedHighlight(0); if(Molpy.options.numbers) Molpy.sparticlesUpdate(); } Molpy.redactedHighlight = function(repainted) { if(Molpy.Redacted.location) { var ra = $('.redacted-area'); if(ra) { Molpy.drawFrame++; if(Molpy.drawFrame >= Molpy.fps / 3) Molpy.drawFrame = 0; if(repainted || Molpy.drawFrame == 0) { var className = Molpy.Redacted.classNames[Molpy.Redacted.location]; if(Molpy.Boosts['Chromatic Heresy'].power > 0 && Molpy.Got('Technicolour Dream Cat') && Molpy.IsEnabled('Technicolour Dream Cat') && Molpy.Redacted.drawType[Molpy.Redacted.drawType.length - 1] != 'hide2') { ra.removeClass(Molpy.Redacted.tempAreaClass); Molpy.Redacted.tempAreaClass = ['alert', 'action', 'toggle', '', ''][flandom(4)]; className += ' ' + Molpy.Redacted.tempAreaClass; ra.addClass(Molpy.Redacted.tempAreaClass); } var redacteditem = g('redacteditem'); if(redacteditem) redacteditem.className = className; } } } } Molpy.PaintStats = function() { g('totalsandstat').innerHTML = Molpify(Molpy.Boosts['Sand'].totalDug, 4); g('manualsandstat').innerHTML = Molpify(Molpy.Boosts['Sand'].manualDug, 4); g('clicksstat').innerHTML = Molpify(Molpy.beachClicks, 4); g('spclickstat').innerHTML = Molpify(Molpy.Boosts['Sand'].sandPerClick, 4); g('sandspentstat').innerHTML = Molpify(Molpy.Boosts['Sand'].spent, 4); g('totalcastlesstat').innerHTML = Molpify(Molpy.Boosts['Castles'].totalBuilt, 4); g('destroyedcastlesstat').innerHTML = Molpify(Molpy.Boosts['Castles'].totalDestroyed, 4); g('downcastlesstat').innerHTML = Molpify(Molpy.Boosts['Castles'].totalDown, 4); g('spentcastlesstat').innerHTML = Molpify(Molpy.Boosts['Castles'].spent, 4); g('ninjatimestat').innerHTML = Molpify(Molpy.CastleTools['NewPixBot'].ninjaTime / Molpy.NPlength, 1) + 'mNP'; g('ninjastealthstat').innerHTML = Molpify(Molpy.ninjaStealth, 1) + 'NP'; g('ninjaforgivestat').innerHTML = Molpify(Molpy.Boosts['Ninja Hope'].power * Molpy.Got('Ninja Hope') + Molpy.Boosts['Ninja Penance'].power * Molpy.Got('Ninja Penance') + Molpy.Boosts['Impervious Ninja'].power * Molpy.Got('Impervious Ninja')); g('dragontypestat').innerHTML = Molpy.DragonsById[Molpy.Level('DQ')].name; g('dragonnumbersstat').innerHTML = Molpify(Molpy.TotalDragons, 1); g('npswithdragonsstat').innerHTML = Molpify(Molpy.TotalNPsWithDragons, 1); g('dragondiggingstat').innerHTML = Molpify(Molpy.DragonDigRate, 3); g('dragonsloststat').innerHTML = Molpify(Molpy.Boosts['DQ'].totalloses, 2); g('dragonfightstat').innerHTML = Molpify(Molpy.Boosts['DQ'].totalfights, 2); g('loadcountstat').innerHTML = Molpify(Molpy.loadCount, 1); g('savecountstat').innerHTML = Molpify(Molpy.saveCount, 1); g('notifstat').innerHTML = Molpify(Molpy.notifsReceived, 2); g('autosavecountstat').innerHTML = Molpify(Molpy.autosaveCountup, 1); g('sandtoolsownedstat').innerHTML = Molpify(Molpy.SandToolsOwned, 4); g('castletoolsownedstat').innerHTML = Molpify(Molpy.CastleToolsOwned, 4); g('boostsownedstat').innerHTML = Molpify(Molpy.BoostsOwned, 4); g('badgesownedstat').innerHTML = Molpify(Molpy.BadgesOwned, 4); g('discoveriesstat').innerHTML = Molpify((Molpy.groupBadgeCounts.discov || 0), 4); g('sandmonstat').innerHTML = Molpify((Molpy.groupBadgeCounts.monums || 0), 4); g('glassmonstat').innerHTML = Molpify((Molpy.groupBadgeCounts.monumg || 0), 4); g('diammaststat').innerHTML = Molpify((Molpy.groupBadgeCounts.diamm || 0), 4); g('sandmultiplierstat').innerHTML = Molpify(Molpy.globalSpmNPMult * 100, 4) + '%'; g('redactedstat').innerHTML = Molpy.Redacted.words + ": " + Molpify(Molpy.Redacted.totalClicks, 1); g('redactedmaxstat').innerHTML = 'Max ' + Molpy.Redacted.word + " Chain: " + Molpify(Molpy.Redacted.chainMax, 1); g('glasschipstat').innerHTML = Molpify(Molpy.Boosts['GlassChips'].power, 4); g('glassblockstat').innerHTML = Molpify(Molpy.Boosts['GlassBlocks'].power, 4); g('sandusestat').innerHTML = Molpify(Molpy.CalcGlassUse(), 6) + '%'; $('#chipspmnp').toggleClass('hidden', !Molpy.Got('AA')); $('#blockspmnp').toggleClass('hidden', !Molpy.Got('AA')); g('chipspmnpstat').innerHTML = Molpify(Molpy.Boosts['GlassChips'].chipsPermNP, 3); g('blockspmnpstat').innerHTML = Molpify(Molpy.Boosts['GlassBlocks'].blocksPermNP, 3); g('blackstat').innerHTML = Molpy.BlackprintReport(); g('logicatstat').innerHTML = Molpify(Molpy.Boosts['Logicat'].bought, 1); g('totaltoolchipsstat').innerHTML = Molpify(Molpy.Boosts['TF'].totalLoaded, 4); g('destroyedtoolchipsstat').innerHTML = Molpify(Molpy.Boosts['TF'].totalDestroyed, 4); g('manualchipsstat').innerHTML = Molpify(Molpy.Boosts['TF'].manualLoaded, 4); g('chipclickstat').innerHTML = Molpify(Molpy.Boosts['TF'].loadedPerClick, 4); g('storagestat').innerHTML = (Molpy.supportsLocalStorage ? 'html5localstorage' : 'c**kies'); } Molpy.UpdateFaves = function(force) { var fav = Molpy.activeLayout.faves; for( var i in fav) { var f = fav[i]; if(f.boost && (f.boost.faveRefresh || force)) { f.BoostToScreen(); } } for( var i in fav) { var f = fav[i]; if(f.boost && f.boost.faveRefresh) { f.boost.faveRefresh = 0; } } } Molpy.oldBeachClass = ''; Molpy.UpdateBeachClass = function(stateClass) { stateClass = stateClass || ''; if(Molpy.Boosts['Beachball'].power) { if(Molpy.oldBeachClass != stateClass) { $('#beach').removeClass(Molpy.oldBeachClass).addClass(stateClass); Molpy.oldBeachClass = stateClass; } } else if(Molpy.oldBeachClass) { $('#beach').removeClass(Molpy.oldBeachClass); Molpy.oldBeachClass = ''; } } Molpy.clockDegrees = 0; function createClockHand() { var clockSizeX = 40, clockSizeY = 40, handOriginX = clockSizeX / 2, handOriginY = clockSizeY / 2, handSize = 12; var hand = document.createElement("div"); $(hand).css({ position: "relative", left: handOriginX + "px", top: handOriginY + "px", width: "2px", height: handSize + "px", backgroundColor: "#222", }); g("clockface").appendChild(hand); } function drawClockHand() { if(!g('game')) { return; } if(!Molpy.ONGelapsed) { Molpy.ONGelapsed = moment().valueOf() - Molpy.ONGstart.valueOf(); } var npPercent = Molpy.ONGelapsed / (Molpy.NPlength * 1000); Molpy.clockDegrees = (npPercent * 360) + 180; //rotation from top $("#clockface").children('div').css({ transformOrigin: "0% 0%", transform: "rotate(" + Molpy.clockDegrees + "deg)", '-ms-transform': "rotate(" + Molpy.clockDegrees + "deg)", '-ms-transform-origin': "0% 0%", WebkitTransform: "rotate(" + Molpy.clockDegrees + "deg)", '-webkit-transform-origin': "0% 0%" }); } Molpy.LockLayoutToggle = function() { Molpy.Anything = 1; Molpy.layoutLocked = !Molpy.layoutLocked; $('.draggable-element,.resizable-element').toggleClass('editlock', Molpy.layoutLocked); $('.ui-resizable-handle').toggleClass('hidden', Molpy.layoutLocked); $('#toggleSnap').toggleClass('hidden', Molpy.layoutLocked); $('#toggleGrid').toggleClass('hidden', Molpy.layoutLocked); $('#toggleLockLayout').toggleClass('depressed', Molpy.layoutLocked); //toggling hidden doesn't work for some reason, would be nice if it did if(Molpy.layoutLocked) { $('.ui-border-color-button').hide(); } else { $('.ui-border-color-button').show(); } } Molpy.SnapLayoutToggle = function() { Molpy.Anything = 1; Molpy.layoutSnap = !Molpy.layoutSnap; $('#toggleSnap').toggleClass('depressed', Molpy.layoutSnap); $('.draggable-element').draggable('option', 'snap', Molpy.layoutSnap) } Molpy.GridLayoutToggle = function() { Molpy.Anything = 1; Molpy.layoutGrid = !Molpy.layoutGrid; $('#toggleGrid').toggleClass('depressed', Molpy.layoutGrid); var size = Molpy.layoutGrid ? 10 : 1; $('.draggable-element').draggable('option', 'grid', [size, size]) } //Handles player clicking, not needed for loading layouts Molpy.CycleBorderClick = function(e) { var sectionName = $(e.target).parent().attr('id').match(/section(.+)/)[1]; Molpy.CyclePanelBorder(sectionName); } //Does the actual Color cycling Molpy.CyclePanelBorder = function(panelName) { var newColor = ++Molpy.activeLayout.borderColors[panelName] || (Molpy.activeLayout.borderColors[panelName] = 0); if(newColor >= 11) { Molpy.activeLayout.borderColors[panelName] = newColor = 0; } var thisPanel = $('#section' + panelName); var borderbutton = thisPanel.find('.ui-border-color-button') for(var i=0; i<11; i++){ thisPanel.removeClass('bordercolor' + i); borderbutton.removeClass('bordercolor' + i); } thisPanel.addClass('borderActive bordercolor' + newColor); Molpy.activeLayout.borderColors[panelName] = newColor; if(newColor != 0) { borderbutton.css('border-color', ''); borderbutton.addClass('bordercolor' + newColor); } else { thisPanel.removeClass('borderActive'); borderbutton.css('border-color', '#999'); } } Molpy.nFaves = 40; Molpy.Layout = function(args) { this.name = args.name || ''; this.lootVis = $.extend({}, args.lootVis); this.boxVis = $.extend({}, args.boxVis); this.positions = $.extend({}, args.positions); this.sizes = $.extend({}, args.sizes); this.borderColors = $.extend({}, args.borderColors) if(!noLayout) { this.faves = Molpy.EmptyFavePanes(Molpy.nFaves); } this.toString = function() { var p = 'P'; //Pipe seParator var s = 'S'; //Semicolon var c = 'C'; //Comma var thread = ''; var threads = []; thread += Molpy.version + p + p;//some extra space! thread += this.name.toLowerCase() + p; for( var i in Molpy.lootVisOrder) { thread += this.lootVis[Molpy.lootVisOrder[i]] ? 1 : 0; } thread += p; for( var i in Molpy.boxVisOrder) { thread += this.boxVis[Molpy.boxVisOrder[i]] ? 1 : 0; } thread += p; for( var i in Molpy.draggableOrder) { var item = this.positions[Molpy.draggableOrder[i]] thread += item.left + c + item.top + s; } thread += p; for( var i in Molpy.sizableOrder) { var item = this.sizes[Molpy.sizableOrder[i]] thread += item.width + c + item.height + s; } thread += p; for( var i in this.faves) { var item = this.faves[i]; thread += item.toString() + s; } thread+=p; for(var i in Molpy.borderColorOrder) { var item=this.borderColors[Molpy.borderColorOrder[i]] || 0; thread += item + s; } thread += p; return thread; } this.FromString = function(string) { var p = 'P'; //Pipe seParator var s = 'S'; //Semicolon var c = 'C'; //Comma var threads = string.split(p); var version = parseFloat(threads[0]); this.name = threads[2].replace(/\W/g, '').toLowerCase(); this.lootVis = {}; var pixels = threads[3].split(''); for( var i in Molpy.lootVisOrder) { var vis = parseInt(pixels[i]) == 1;//we want a boolean because jQuery this.lootVis[Molpy.lootVisOrder[i]] = vis; } this.boxVis = {}; pixels = threads[4].split(''); for( var i in Molpy.boxVisOrder) { var vis = parseInt(pixels[i]) == 1;//ditto this.boxVis[Molpy.boxVisOrder[i]] = vis; } this.positions = {}; pixels = threads[5].split(s); for( var i in Molpy.draggableOrder) { if(!pixels[i]) pixels[i] = '0C0'; var pos = pixels[i].split(c); this.positions[Molpy.draggableOrder[i]] = { left: parseFloat(pos[0]), top: parseFloat(pos[1]) }; } this.sizes = {}; pixels = threads[6].split(s); for( var i in Molpy.sizableOrder) { if(!pixels[i]) pixels[i] = '0C0'; var pos = pixels[i].split(c); this.sizes[Molpy.sizableOrder[i]] = { width: parseFloat(pos[0]), height: parseFloat(pos[1]) }; } if(threads[7] && !noLayout) { this.faves = Molpy.EmptyFavePanes(Molpy.nFaves); pixels = threads[7].split(s); for( var i in pixels) { if(!pixels[i]) break; var fav = this.faves[i]; fav.FromString(pixels[i]); this.faves.push(fav); } } if(threads[8] && !noLayout) { this.borderColors = {}; pixels = threads[8].split(s); for( var i in Molpy.borderColorOrder) { if(!pixels[i]) pixels[i] = '0'; this.borderColors[Molpy.borderColorOrder[i]] = parseInt(pixels[i]) || 0; } } if ((this.boxVis['LootNavigation'] == 0) && (this.positions['LootNavigation'].left == 0) && (this.positions['LootNavigation'].top == 0) && !noLayout) { this.boxVis['LootNavigation'] = 1; this.positions['LootNavigation'].left = this.positions['Inventory'].left; this.positions['LootNavigation'].top = this.positions['Inventory'].top; this.positions['Inventory'].top+=25; } } this.ToScreen = function() { Molpy.Overview.SetSizes(); for( var i in Molpy.lootVisOrder) { var el = Molpy.lootVisOrder[i]; Molpy.ShowhideToggle(el, this.lootVis[el] == true); //==true incase there are missing values (otherwise they would toggle instead of set to false) } for( var i in Molpy.boxVisOrder) { var el = Molpy.boxVisOrder[i]; Molpy.ToggleView(el, this.boxVis[el] == true); } if(noLayout) return; for( var i in Molpy.draggableOrder) { var item = Molpy.draggableOrder[i]; var pos = this.positions[item]; $('#section' + item).css(pos); } for( var i in Molpy.sizableOrder) { var item = Molpy.sizableOrder[i]; var size = this.sizes[item]; $('#section' + item + 'Body').css(size); } for( var i in this.faves) { this.faves[i].ToScreen(); } for( var i in Molpy.borderColorOrder) { var item = Molpy.borderColorOrder[i]; this.borderColors[item]--; Molpy.CyclePanelBorder(item); } Molpy.FixPaneWidths(); } this.FromScreen = function() { this.positions = {}; this.sizes = {}; for( var i in Molpy.draggableOrder) { var item = g('section' + Molpy.draggableOrder[i]); this.positions[Molpy.draggableOrder[i]] = { left: parseFloat(item.style.left), top: parseFloat(item.style.top) }; } for( var i in Molpy.sizableOrder) { var item = $('#section' + Molpy.sizableOrder[i] + 'Body'); this.sizes[Molpy.sizableOrder[i]] = { width: item.width(), height: item.height() }; } this.lootVis = $.extend({}, Molpy.activeLayout.lootVis); //because the active layout's vis settings ARE the screen settings this.boxVis = $.extend({}, Molpy.activeLayout.boxVis); for( var i in this.faves) { this.faves[i].FromScreen(); } this.borderColors = $.extend({}, Molpy.activeLayout.borderColors); } this.Export = function() { Molpy.Anything = 1; Molpy.ToggleView('Export'); g('exporttext').value = this.toString(); } this.Overwrite = function() { Molpy.Anything = 1; if(confirm('Really overwrite the layout "' + this.name + '"with the current settings?')) { this.FromScreen(); } } this.Activate = function() { Molpy.Anything = 1; Molpy.activeLayout = this; this.ToScreen(); Molpy.layoutNeedRepaint = 1; } this.Clone = function() { Molpy.Anything = 1; var clone = new Molpy.Layout(this); clone.name += ' clone'; Molpy.layouts.push(clone); Molpy.layoutNeedRepaint = 1; } this.Delete = function() { Molpy.Anything = 1; if(Molpy.layouts.length < 2) { Molpy.Notify('You need at least 1 layout!',1); return; } if(confirm('Really delete the layout "' + this.name + '"?')) { var i = Molpy.layouts.indexOf(this); if(i >= 0) { Molpy.layouts.splice(i, 1); Molpy.layoutNeedRepaint = 1; } } } this.Rename = function() { Molpy.Anything = 1; var str = prompt('Enter a layout name here:', 'lowercase123'); str = str.replace(/\W/g, '').toLowerCase(); if(!str) return; this.name = str; Molpy.layoutNeedRepaint = 1; } } Molpy.NewLayout = function() { Molpy.Anything = 1; var newLayout = new Molpy.Layout({}); newLayout.FromScreen(); newLayout.name = "new"; Molpy.layouts.push(newLayout); Molpy.layoutNeedRepaint = 1; } Molpy.ImportLayout = function() { Molpy.Anything = 1; var thread = prompt('Paste a valid layout code here:\n(write "default" or "default2" for the defaults)', ''); if(!thread) return; if(thread == 'default') thread = Molpy.defaultLayoutData; if(thread == 'default2') thread = Molpy.defaultLayoutData2; var newLayout = new Molpy.Layout({}); newLayout.FromString(thread); Molpy.layouts.push(newLayout); Molpy.layoutNeedRepaint = 1; } Molpy.FixPaneWidths = function() { $('#lootselection').css({width: $('#sectionInventoryBody').width()}); $('.layoutcontrols').css({width: $('#sectionLayoutsBody').width()}); } Molpy.IsStatsVisible = function() { return Molpy.activeLayout.boxVis['Stats']; } Molpy.FavePane = function(i) { this.i = i; this.boost = 0; this.vis = false; this.position = { left: 0, top: 0 }; this.size = { width: 140, height: 50 }; this.toString = function() { var c = 'C'; //Comma var id = 'n'; if(this.boost) { id = '' + this.boost.id; if(Molpy.BoostsById[id] !== this.boost) { if (id >= Molpy.DiscoveriesStartAt) { id = -1000000 -id +Molpy.DiscoveriesStartAt; } else { id = 1 - id; } } } return id + c + (this.vis ? 1 : 0) + c + (this.position.left || 0) + c + (this.position.top || 0) + c + (this.size.width || 0) + c + (this.size.height || 0); } this.FromString = function(str) { var c = 'C'; //Comma var pixels = str.split(c); var n = pixels[0]; if (n == 'n') { this.boost = 0 } else if (n >= 0) { this.boost = Molpy.BoostsById[parseInt(n) || 0] } else if (n > -1000000) { this.boost = Molpy.BadgesById[1 - parseInt(n) || 0] } else { this.boost = Molpy.BadgesById[Molpy.DiscoveriesStartAt + 1000000 + parseInt(n) || 0] }; if (this.boost) this.boost.faveRefresh = 1; this.vis = pixels[1] == true; this.position = { left: parseFloat(pixels[2]), top: parseFloat(pixels[3]) }; this.size = { width: parseFloat(pixels[4]), height: parseFloat(pixels[5]) }; } this.ToScreen = function() { $('#sectionFave' + this.i).css(this.position); $('#sectionFaveBody' + this.i).css(this.size); this.BoostToScreen(); } this.BoostToScreen = function() { var n = this.i; if(this.boost) { Molpy.DisplayingFave =1; g('optionFave' + n).text = this.boost.name; g('faveHeader' + n).innerHTML = '<H1 class="groupTitle">[' + this.boost.getHeading() + ']</H1><H2 class="objName">' + this.boost.getFormattedName() + '</H2>'; if(this.boost.boost) { g('faveContent' + n).innerHTML = (this.boost.unlocked ? this.boost.getDesc() : 'This Boost is locked!'); this.boost.updateBuy(1); } else { g('faveContent' + n).innerHTML = (this.boost.earned ? this.boost.getDesc() : 'This Badge is unearned!'); } g('sectionFave' + n).className = 'draggable-element table-wrapper ' + this.boost.getFullClass(); Molpy.DisplayingFave =0; } else { g('optionFave' + n).text = n + ' (empty)'; g('faveHeader' + n).innerHTML = ''; g('faveContent' + n).innerHTML = 'Fave ' + n; g('sectionFave' + n).className = 'draggable-element table-wrapper'; } $('#sectionFave' + this.i).toggleClass('hidden', !this.vis).toggleClass('editlock', Molpy.layoutLocked); } this.FromScreen = function() { var item = g('sectionFave' + this.i); this.position = { left: parseFloat(item.style.left), top: parseFloat(item.style.top) }; var item = $('#sectionFaveBody' + this.i); this.size = { width: item.width(), height: item.height() }; this.vis = Molpy.activeLayout.faves[this.i].vis; //because the active layout's vis settings ARE the screen settings } } Molpy.EmptyFavePanes = function(n) { var f = []; for( var i = 0; i < n; i++) { f.push(new Molpy.FavePane(i)); } return f; } Molpy.MakeFavePanes = function() { var str = ''; for( var i in Molpy.activeLayout.faves) { str += '<div id="sectionFave' + i + '" class="hidden draggable-element table-wrapper">\<div id="faveHeader' + i + '" class="table-header"></div>\<div id="sectionFaveBody' + i + '" class="table-content resizable-element">\<div id="faveContent' + i + '" class="table-content-wrapper">Fave ' + i + '\</div>\</div>\</div>'; } if(str) g('sectionFavePanes').innerHTML = str; var str = ''; for( var i in Molpy.activeLayout.faves) { str += '<option id="optionFave' + i + '" value="' + i + '">' + i + ' (empty)</option>'; } if(str) g('selectFave').innerHTML = '<option>None</option>' + str; } Molpy.InitGUI = function() { Molpy.lootVisOrder = ['boosts', 'ninj', 'cyb', 'hpt', 'chron', 'bean', 'dimen', 'badges', 'badgesav', 'discov', 'monums', 'monumg', 'tagged', 'ceil', 'drac', 'stuff', 'land', 'prize', 'varie','search', 'faves']; Molpy.boxVisOrder = ['Clock', 'Timer', 'View', 'File', 'Links', 'Beach', 'Shop', 'Inventory', 'SandTools', 'CastleTools', 'Options', 'Stats', 'Log', 'Export', 'About', 'SandCounts', 'NPInfo', 'Layouts', 'Codex', 'Alerts', 'SandStats', 'GlassStats', 'NinjaStats', 'OtherStats', 'QuickLayout', 'TFCounts', 'Faves', 'StuffCounts', 'IncomeCounts','LootSearch','LootNavigation', 'DragonStats','DragonsNP','DragonOverview']; Molpy.draggableOrder = ['Clock', 'Timer', 'View', 'File', 'Links', 'Beach', 'Options', 'Stats', 'Log', 'Export', 'SandCounts', 'TFCounts', 'NPInfo', 'About', 'SandTools', 'CastleTools', 'Shop', 'Inventory', 'Layouts', 'Codex', 'Alerts', 'SandStats', 'GlassStats', 'NinjaStats', 'OtherStats', 'QuickLayout', 'Faves', 'StuffCounts', 'IncomeCounts','LootSearch','LootNavigation', 'DragonStats','DragonsNP','DragonOverview']; Molpy.sizableOrder = ['View', 'File', 'Links', 'Options', 'Stats', 'Log', 'Export', 'SandTools', 'CastleTools', 'Shop', 'Inventory', 'Layouts', 'Codex', 'Alerts', 'SandStats', 'GlassStats', 'NinjaStats', 'OtherStats', 'QuickLayout', 'Faves', 'StuffCounts', 'IncomeCounts','LootSearch','LootNavigation', 'DragonStats','DragonsNP','DragonOverview']; Molpy.borderColorOrder = ['Clock', 'Timer', 'View', 'File', 'Links', 'Beach', 'Shop', 'Inventory', 'SandTools', 'CastleTools', 'Options', 'Stats', 'Log', 'Export', 'About', 'SandCounts', 'NPInfo', 'Layouts', 'Codex', 'Alerts', 'SandStats', 'GlassStats', 'NinjaStats', 'OtherStats', 'QuickLayout', 'TFCounts', 'Faves', 'StuffCounts', 'IncomeCounts','LootSearch','LootNavigation', 'DragonStats','DragonsNP','DragonOverview']; $('#sectionInventoryBody').resize(Molpy.FixPaneWidths); $('#sectionLayoutsBody').resize(Molpy.FixPaneWidths); Molpy.activeLayout = new Molpy.Layout({ name: 'default', lootVis: { boosts: 1, badges: 1, } }); Molpy.activeLayout.FromString(Molpy.defaultLayoutData); if(!noLayout) Molpy.MakeFavePanes(); Molpy.activeLayout.ToScreen(); Molpy.layouts = []; Molpy.layouts.push(Molpy.activeLayout); if(!noLayout) { Molpy.layouts.push(new Molpy.Layout({})); Molpy.layouts[1].FromString(Molpy.defaultLayoutData2); Molpy.LoadLayouts(); $('.resizable-element').resizable({cancel: '.editlock'}); $('.draggable-element').draggable({cancel: '.editlock', scroll: true, grid: [10, 10], snap: true}).canColorBorder(); Molpy.LockLayoutToggle(); } else { Molpy.layoutLocked = true; } new Molpy.Puzzle('redacted', function() { Molpy.Redacted.drawType[Molpy.Redacted.drawType.length - 1] = 'show'; Molpy.Redacted.onClick(Molpy.Redacted.drawType.length - 1,1); }); Molpy.allNeedRepaint = 1; } Molpy.newObjectDiv = function(type, object, flags) { var headingHTML = ''; var purchaseHTML = ''; var ownedHTML = ''; var priceHTML = ''; var productionHTML = ''; var heading = object.getHeading(); if (heading == 'prize LMath.floor(Math.PI)') { heading = 'prize L&lfloor;&pi;&rfloor;'; } if (heading =='prize LMath.ceil(Math.PI)') { heading = 'prize L&lceil;&pi;&rceil;'; } if(heading != '') headingHTML = ' <H1 class="groupTitle">[' + heading + ']</H1>'; var buysell = object.getBuySell(); if(buysell != '') { purchaseHTML = ' <div class="purchase ">' + buysell + '</div>'; var price = object.getPrice(); if(price != '') { priceHTML = ' <div class="price ">' + Molpy.createPriceHTML(price) + ' </div>'; } } var owned = object.getOwned(); if(owned != '') ownedHTML = '<div class="owned">Owned: ' + owned + '</div>'; var production = object.getProduction(); if(production != '') productionHTML = ' <div class="production">' + production + '</div>'; var divHTML = '<div class="objDiv ' + object.getFullClass() + '">' + ' <div class="icon ' + type + '_' + (object.icon ? object.icon : 'generic') + '" />' + headingHTML + ' <H2 class="objName">' + object.getFormattedName() + '</H2>' + purchaseHTML + ownedHTML + priceHTML + productionHTML + ' <div class="description"><br />' + object.getDesc() + '</div>' + '</div>'; var div = $(divHTML); if(flags.hover) { var oid = '' + object.name + object.id; if(object.earned && object.np) { div.mouseover({overID: oid, np: object.np, alias: object.alias}, Molpy.monumentOver).mouseout({overID: oid, np: object.np, alias: object.alias}, Molpy.monumentOut); } else { div.mouseover({overID: oid}, Molpy.onMouseOver).mouseout({overID: oid}, Molpy.onMouseOut); } if(!Molpy.Boosts['Expando'].IsEnabled && !flags.nohide) { div.find('.description').hide(); } } return div; } Molpy.createPriceHTML = function(price) { var innerHTML = 'Price:'; for(var p in price) { var pNum = price[p]; //change all number representations into a number (40,000 40k 4e4) pNum = isNaN(pNum) ? DeMolpify(pNum) : pNum; // if (!Molpy.Boosts[p]) { // Molpy.Notify('EEEP '+p,1) // } else { innerHTML += '<br>&nbsp;&nbsp;- ' + Molpify(pNum, 2) + ' ' + Molpy.Boosts[p].plural; // } } return innerHTML; } Molpy.defineWindowSizes = function() { if(noLayout) return; $("#sectionStuffCountsBody").resizable({ minHeight: 42, minWidth: 150 }); $("#sectionIncomeCountsBody").resizable({ minHeight: 42, minWidth: 150 }); $("#sectionDragonOverviewBody").resizable({ minHeight: 120, minWidth: 520 }); } }
#!/usr/bin/env python COPY_GOOGLE_DOC_KEY = '1mOD2BYeca0vjKXdfYVHi5EhoqOSSiYzVPAqYAEQBVKs' USE_ASSETS = False # Use these variables to override the default cache timeouts for this graphic # DEFAULT_MAX_AGE = 20 # ASSETS_MAX_AGE = 300
# GGearing # Simple encryption script for text # This was one my first versions of this script # 09/07/2017 from __future__ import print_function import math import sys input_fun = None key = int(math.pi * 1e14) if sys.version_info.major >= 3: input_fun = input else: input_fun = raw_input text = input_fun("Enter text: ") values = [] reverse = [] def encryptChar(target): # encrytion algorithm target = (((target + 42) * key) - 449) return target def decryptChar(target): target = (((target + 449) / key) - 42) return target def encrypt(input_text): col_values = [] for i in range(len(input_text)): current = ord(input_text[i]) current = encryptChar(current) col_values.append(current) return col_values def decrypt(enc_text): col_values = [] for i in range(len(enc_text)): current = int(decryptChar(enc_text[i])) current = chr(current) col_values.append(current) return col_values def readAndDecrypt(filename): file = open(filename, "r") data = file.read() datalistint = [] actualdata = [] datalist = data.split(" ") datalist.remove('') for i in range(len(datalist)): datalistint.append(float(datalist[i])) for i in range(len(datalist)): current1 = int(decryptChar(datalistint[i])) current1 = chr(current1) actualdata.append(current1) file.close() return actualdata def readAndEncrypt(filename): file = open(filename, "r") data = file.read() datalist = list(data) encrypted_list = list() encrypted_list_str = list() for i in range(len(datalist)): current = ord(datalist[i]) current = encryptChar(current) encrypted_list.append(current) file.close() return encrypted_list def readAndEncryptAndSave(inp_file, out_file): enc_list = readAndEncrypt(inp_file) output = open(out_file, "w") for i in range(len(enc_list)): output.write(str(enc_list[i]) + " ") output.close() def readAndDecryptAndSave(inp_file, out_file): dec_list = readAndDecrypt(inp_file) output = open(out_file, "w") for i in range(len(dec_list)): output.write(str(dec_list[i])) output.close() # encryption for i in range(len(text)): current = ord(text[i]) current = encryptChar(current) values.append(current) # decryption for i in range(len(text)): current = int(decryptChar(values[i])) current = chr(current) reverse.append(current) print(reverse) # saves encrypted in txt file output = open("encrypted.txt", "w") for i in range(len(values)): output.write(str(values[i]) + " ") output.close() # read and decrypts print(readAndDecrypt("encrypted.txt"))
from icarus_backend.user.UserController import UserController from icarus_backend.pilot.PilotModel import Pilot from users.models import IcarusUser as User from icarus_backend.pilot.PilotData import PilotRegistrationData class PilotController: @staticmethod # Used to register an existing user as a Pilot def register_pilot(pilot_data: PilotRegistrationData, domain) -> (int, dict): status, message = UserController.register_user(pilot_data.username, pilot_data.email, pilot_data.password, pilot_data.first_name, pilot_data.last_name, domain) if status == 200: user = User.objects.filter(email=pilot_data.email).first() pilot = Pilot(user=user, remotePilotCertificateNumber=pilot_data.remote_pilot_certificate_number, mobilePhoneNumber=pilot_data.mobile_phone_number) pilot.save() return 200, {'message': 'Successfully registered pilot.'} return status, message @staticmethod def get_pilot_data(id) -> (int, dict): # Get information about an existing pilot, return it as JSON pilot = Pilot.objects.filter(user=id).first() if not pilot: return 400, {'message': 'No pilot with this id exists.'} return 200, pilot.as_dict() @staticmethod def update_info(user_id, pilot_changes) -> (int, dict): # Find the pilot pilot = Pilot.objects.filter(user_id=user_id).first() # If there's a pilot cert number in the request AND it's not equal to the existing one if 'remote_pilot_certificate_number' in pilot_changes and pilot.remotePilotCertificateNumber \ != pilot_changes['remote_pilot_certificate_number']: # Change it pilot.remotePilotCertificateNumber = pilot_changes['remote_pilot_certificate_number'] # If there's a phonne number in the request AND it's not equal to the existing one if 'mobile_phone_number' in pilot_changes and pilot.mobilePhoneNumber != pilot_changes['mobile_phone_number']: # Change it pilot.mobilePhoneNumber = pilot_changes['mobile_phone_number'] # Commit to DB pilot.save() return 200, {'message': 'Info updated successfully.'}
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_REVOCABLE_STORE_H__ #define BASE_REVOCABLE_STORE_H__ #include "base/basictypes.h" #include "base/logging.h" #include "base/ref_counted.h" // |RevocableStore| is a container of items that can be removed from the store. class RevocableStore { public: // A |StoreRef| is used to link the |RevocableStore| to its items. There is // one StoreRef per store, and each item holds a reference to it. If the // store wishes to revoke its items, it sets |store_| to null. Items are // permitted to release their reference to the |StoreRef| when they no longer // require the store. class StoreRef : public base::RefCounted<StoreRef> { public: StoreRef(RevocableStore* store) : store_(store) { } void set_store(RevocableStore* store) { store_ = store; } RevocableStore* store() const { return store_; } private: RevocableStore* store_; DISALLOW_EVIL_CONSTRUCTORS(StoreRef); }; // An item in the store. On construction, the object adds itself to the // store. class Revocable { public: Revocable(RevocableStore* store); ~Revocable(); // This item has been revoked if it no longer has a pointer to the store. bool revoked() const { return !store_reference_->store(); } private: // We hold a reference to the store through this ref pointer. We release // this reference on destruction. scoped_refptr<StoreRef> store_reference_; DISALLOW_EVIL_CONSTRUCTORS(Revocable); }; RevocableStore(); ~RevocableStore(); // Revokes all the items in the store. void RevokeAll(); // Returns true if there are no items in the store. bool empty() const { return count_ == 0; } private: friend class Revocable; // Adds an item to the store. To add an item to the store, construct it // with a pointer to the store. void Add(Revocable* item); // This is the reference the unrevoked items in the store hold. scoped_refptr<StoreRef> owning_reference_; // The number of unrevoked items in the store. int count_; DISALLOW_EVIL_CONSTRUCTORS(RevocableStore); }; #endif // BASE_REVOCABLE_STORE_H__
import glob import os import pathlib import subprocess from talon import Context, Module, actions, settings mod = Module() mod.tag("obs_studio_global", desc="tag that's active if oba-studio is running") mod.setting( "obs_recording_folder", type=str, default=None, desc="the default location to record files with obs-studio", ) mod.setting( "obs_clip_folder", type=str, default=None, desc="the default location to save clipped viedo files", ) @mod.action_class class Actions: def obs_play_last_clip(): """Plays the last recorded clip after putting talon to sleep""" folder = settings.get("user.obs_clip_folder") list_of_files = glob.glob(f"{folder}/*") latest_file = max(list_of_files, key=os.path.getctime) actions.speech.disable() # XXX - this should launch new app subprocess.Popen(["vlc", f"{latest_file}"]) # XXX - re-wake talon
/* * System Control Driver * * Copyright (C) 2012 Freescale Semiconductor, Inc. * Copyright (C) 2012 Linaro Ltd. * * Author: Dong Aisheng <dong.aisheng@linaro.org> * * 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. */ #include <linux/err.h> #include <linux/io.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <linux/regmap.h> static struct platform_driver syscon_driver; struct syscon { struct device *dev; void __iomem *base; struct regmap *regmap; }; static int syscon_match(struct device *dev, void *data) { struct syscon *syscon = dev_get_drvdata(dev); struct device_node *dn = data; return (syscon->dev->of_node == dn) ? 1 : 0; } struct regmap *syscon_node_to_regmap(struct device_node *np) { struct syscon *syscon; struct device *dev; dev = driver_find_device(&syscon_driver.driver, NULL, np, syscon_match); if (!dev) return ERR_PTR(-EPROBE_DEFER); syscon = dev_get_drvdata(dev); return syscon->regmap; } EXPORT_SYMBOL_GPL(syscon_node_to_regmap); struct regmap *syscon_regmap_lookup_by_compatible(const char *s) { struct device_node *syscon_np; struct regmap *regmap; syscon_np = of_find_compatible_node(NULL, NULL, s); if (!syscon_np) return ERR_PTR(-ENODEV); regmap = syscon_node_to_regmap(syscon_np); of_node_put(syscon_np); return regmap; } EXPORT_SYMBOL_GPL(syscon_regmap_lookup_by_compatible); struct regmap *syscon_regmap_lookup_by_phandle(struct device_node *np, const char *property) { struct device_node *syscon_np; struct regmap *regmap; syscon_np = of_parse_phandle(np, property, 0); if (!syscon_np) return ERR_PTR(-ENODEV); regmap = syscon_node_to_regmap(syscon_np); of_node_put(syscon_np); return regmap; } EXPORT_SYMBOL_GPL(syscon_regmap_lookup_by_phandle); static const struct of_device_id of_syscon_match[] = { { .compatible = "syscon", }, { }, }; static struct regmap_config syscon_regmap_config = { .reg_bits = 32, .val_bits = 32, .reg_stride = 4, }; static int __devinit syscon_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *np = dev->of_node; struct syscon *syscon; struct resource res; int ret; if (!np) return -ENOENT; syscon = devm_kzalloc(dev, sizeof(struct syscon), GFP_KERNEL); if (!syscon) return -ENOMEM; syscon->base = of_iomap(np, 0); if (!syscon->base) return -EADDRNOTAVAIL; ret = of_address_to_resource(np, 0, &res); if (ret) return ret; syscon_regmap_config.max_register = res.end - res.start - 3; syscon->regmap = devm_regmap_init_mmio(dev, syscon->base, &syscon_regmap_config); if (IS_ERR(syscon->regmap)) { dev_err(dev, "regmap init failed\n"); return PTR_ERR(syscon->regmap); } syscon->dev = dev; platform_set_drvdata(pdev, syscon); dev_info(dev, "syscon regmap start 0x%x end 0x%x registered\n", res.start, res.end); return 0; } static int __devexit syscon_remove(struct platform_device *pdev) { struct syscon *syscon; syscon = platform_get_drvdata(pdev); iounmap(syscon->base); platform_set_drvdata(pdev, NULL); return 0; } static struct platform_driver syscon_driver = { .driver = { .name = "syscon", .owner = THIS_MODULE, .of_match_table = of_syscon_match, }, .probe = syscon_probe, .remove = __devexit_p(syscon_remove), }; static int __init syscon_init(void) { return platform_driver_register(&syscon_driver); } postcore_initcall(syscon_init); static void __exit syscon_exit(void) { platform_driver_unregister(&syscon_driver); } module_exit(syscon_exit); MODULE_AUTHOR("Dong Aisheng <dong.aisheng@linaro.org>"); MODULE_DESCRIPTION("System Control driver"); MODULE_LICENSE("GPL v2");
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #define SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #import <Cocoa/Cocoa.h> #include <memory> #include <queue> #include <string> #include <tuple> #include <vector> #include "base/mac/scoped_nsobject.h" #include "shell/browser/native_window.h" #include "ui/display/display_observer.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/native/native_view_host.h" @class ElectronNSWindow; @class ElectronNSWindowDelegate; @class ElectronPreviewItem; @class ElectronTouchBar; @class WindowButtonsView; namespace electron { class RootViewMac; class NativeWindowMac : public NativeWindow, public ui::NativeThemeObserver, public display::DisplayObserver { public: NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowMac() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate = false) override; gfx::Rect GetBounds() override; bool IsNormal() override; gfx::Rect GetNormalBounds() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; void SetBackgroundColor(SkColor color) override; SkColor GetBackgroundColor() override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetRepresentedFilename(const std::string& filename) override; std::string GetRepresentedFilename() override; void SetDocumentEdited(bool edited) override; bool IsDocumentEdited() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; void SetProgressBar(double progress, const ProgressState state) override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetAutoHideCursor(bool auto_hide) override; void SetVibrancy(const std::string& type) override; void SetWindowButtonVisibility(bool visible) override; bool GetWindowButtonVisibility() const override; void SetTrafficLightPosition(base::Optional<gfx::Point> position) override; base::Optional<gfx::Point> GetTrafficLightPosition() const override; void RedrawTrafficLights() override; void UpdateFrame() override; void SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) override; void RefreshTouchBarItem(const std::string& item_id) override; void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override; void SelectPreviousTab() override; void SelectNextTab() override; void MergeAllWindows() override; void MoveTabToNewWindow() override; void ToggleTabBar() override; bool AddTabbedWindow(NativeWindow* window) override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void PreviewFile(const std::string& path, const std::string& display_name) override; void CloseFilePreview() override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; void NotifyWindowEnterFullScreen() override; void NotifyWindowLeaveFullScreen() override; void NotifyWindowWillEnterFullScreen(); void NotifyWindowWillLeaveFullScreen(); // Cleanup observers when window is getting closed. Note that the destructor // can be called much later after window gets closed, so we should not do // cleanup in destructor. void Cleanup(); // Use a custom content view instead of Chromium's BridgedContentView. void OverrideNSWindowContentView(); void UpdateVibrancyRadii(bool fullscreen); // Set the attribute of NSWindow while work around a bug of zoom button. void SetStyleMask(bool on, NSUInteger flag); void SetCollectionBehavior(bool on, NSUInteger flag); void SetWindowLevel(int level); enum class FullScreenTransitionState { ENTERING, EXITING, NONE }; // Handle fullscreen transitions. void SetFullScreenTransitionState(FullScreenTransitionState state); void HandlePendingFullscreenTransitions(); enum class VisualEffectState { kFollowWindow, kActive, kInactive, }; enum class TitleBarStyle { kNormal, kHidden, kHiddenInset, kCustomButtonsOnHover, }; TitleBarStyle title_bar_style() const { return title_bar_style_; } ElectronPreviewItem* preview_item() const { return preview_item_.get(); } ElectronTouchBar* touch_bar() const { return touch_bar_.get(); } bool zoom_to_page_width() const { return zoom_to_page_width_; } bool always_simple_fullscreen() const { return always_simple_fullscreen_; } protected: // views::WidgetDelegate: bool CanResize() const override; views::View* GetContentsView() override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // display::DisplayObserver: void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; private: // Add custom layers to the content view. void AddContentViewLayers(); void InternalSetWindowButtonVisibility(bool visible); void InternalSetStandardButtonsVisibility(bool visible); void InternalSetParentWindow(NativeWindow* parent, bool attach); void SetForwardMouseMessages(bool forward); ElectronNSWindow* window_; // Weak ref, managed by widget_. base::scoped_nsobject<ElectronNSWindowDelegate> window_delegate_; base::scoped_nsobject<ElectronPreviewItem> preview_item_; base::scoped_nsobject<ElectronTouchBar> touch_bar_; base::scoped_nsobject<WindowButtonsView> buttons_view_; // Event monitor for scroll wheel event. id wheel_event_monitor_; // The NSView that used as contentView of window. // // For frameless window it would fill the whole window. base::scoped_nsobject<NSView> container_view_; // The views::View that fills the client area. std::unique_ptr<RootViewMac> root_view_; bool is_kiosk_ = false; bool zoom_to_page_width_ = false; bool resizable_ = true; base::Optional<gfx::Point> traffic_light_position_; std::queue<bool> pending_transitions_; FullScreenTransitionState fullscreen_transition_state() const { return fullscreen_transition_state_; } FullScreenTransitionState fullscreen_transition_state_ = FullScreenTransitionState::NONE; NSInteger attention_request_id_ = 0; // identifier from requestUserAttention // The presentation options before entering kiosk mode. NSApplicationPresentationOptions kiosk_options_; // The "titleBarStyle" option. TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal; // The "visualEffectState" option. VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow; // The visibility mode of window button controls when explicitly set through // setWindowButtonVisibility(). base::Optional<bool> window_button_visibility_; // Maximizable window state; necessary for persistence through redraws. bool maximizable_ = true; // Simple (pre-Lion) Fullscreen Settings bool always_simple_fullscreen_ = false; bool is_simple_fullscreen_ = false; bool was_maximizable_ = false; bool was_movable_ = false; NSRect original_frame_; NSInteger original_level_; NSUInteger simple_fullscreen_mask_; std::string vibrancy_type_; // The presentation options before entering simple fullscreen mode. NSApplicationPresentationOptions simple_fullscreen_options_; DISALLOW_COPY_AND_ASSIGN(NativeWindowMac); }; } // namespace electron #endif // SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
"""Amazon Product Advertising API wrapper for Python""" __version__ = '3.2.0' __author__ = 'Sergio Abad'
const crypto = require('crypto') /** * @module Util */ module.exports = { /** * Performs string formatting for things like custom nicknames. * * @param {string} formatString The string to format (contains replacement strings) * @param {object} data The data to replace the string replacements with * @param {GuildMember} member The guild member this string is being formatted for * @returns {string} The processed string */ formatDataString (formatString, data, member) { const replacements = { '%USERNAME%': data.robloxUsername, '%USERID%': data.robloxId, '%RANK%': data.groupRank || '', '%DISCORDNAME%': data.discordName || '', '%DISCORDID%': data.discordId || '' } if (member != null) { replacements['%DISCORDNAME%'] = member.user.username replacements['%DISCORDID%'] = member.id replacements['%SERVER%'] = member.guild.name } return formatString.replace(/%\w+%/g, (all) => { return typeof replacements[all] !== 'undefined' ? replacements[all] : all }) }, /** * Returns a promise that resolves after the given time in milliseconds. * @param {int} sleepTime The amount of time until the promise resolves * @returns Promise */ async sleep (sleepTime) { return new Promise(resolve => { setTimeout(resolve, sleepTime) }) }, /** * Takes an array of numbers and simplifies it into a string containing ranges, e.g.: * [0, 1, 2, 4, 6, 7, 8] --> "0-2, 4, 6-8" * @param {array} numbers The input numbers * @returns {string} The output string */ simplifyNumbers (numbers) { const output = [] let rangeStart for (let i = 0; i < numbers.length; i++) { const number = numbers[i] const next = numbers[i + 1] if (rangeStart != null && (next - number !== 1 || next == null)) { output.push(`${rangeStart}-${number}`) rangeStart = null } else if (next == null || next - number !== 1) { output.push(`${number}`) } else if (rangeStart == null) { rangeStart = number } } return output.join(', ') }, /** * Takes a number and converts it into a simplified and human readable number * 1,142,546 --> 1.1M * @param {float} toCompress The number to compress * @returns {string} The compressed number */ toHumanReadableNumber (toCompress) { const numberAbbreviations = ['K', 'M', 'B', 'T'] let compressedNumber = parseInt(toCompress, 10).toFixed(1) // Count how many times the place is shifted let placeShift = 0 while (compressedNumber >= 1000) { compressedNumber = (compressedNumber / 1000).toFixed(1) placeShift++ } // If the number was simplified, put a number abbreviation on the end // Removes the decimal if it wasn't if (placeShift > 0) { compressedNumber += numberAbbreviations[placeShift - 1] } else { compressedNumber = Math.floor(compressedNumber) } return compressedNumber }, /** * Returns an md5 hash of the input string. * This is used for a key for a group binding. The key is the hash of the json of the rank binding. * @param {string} string The input string. * @returns {string} The md5 hash of the string. */ md5 (string) { return crypto.createHash('md5').update(string).digest('hex') }, /** * Gets group rank binding text for a binding. * Turns a rank binding object into a human-readable format. * @param {object} binding The binding object. * @param {boolean} [addCodeBlock=false] Whether or not to wrap the binding in markdown code block. * @returns {string} The binding in human-readable format. */ getBindingText (binding, addCodeBlock = false) { let bindingMessage = addCodeBlock ? '```markdown\n' : '' if (binding.groups == null) { return `\nInvalid Group Format - Unbind role ${binding.role} to fix this problem.\n` } for (const [index, group] of binding.groups.entries()) { if (index > 0) bindingMessage += '...or\n' if (group.id.match(/[a-z]/i)) { bindingMessage += `# Virtual Group ${group.id}\n` bindingMessage += `Argument ${group.ranks.length > 0 ? group.ranks[0] : 'none'}` } else { bindingMessage += `# Group ${group.id}\n` bindingMessage += `Rank${group.ranks.length === 1 ? '' : 's'} ` + module.exports.simplifyNumbers(group.ranks) } bindingMessage += '\n\n' } return addCodeBlock ? bindingMessage + '\n```' : bindingMessage }, /** * Gets the user-facing link for the verification registry. * This is not used for actually checking against the registry. * This is for functionality in the future where we want to know where the user came from to help make sure that * they are on the right account on the website by making sure the user is in the guild they came from. * @param {Guild} guild The guild this link is being generated for. * @returns {string} The link to the verification site */ getVerifyLink (guild) { return 'https://verify.eryn.io' // /?from=${guild.id}` } }
$(document).ready(function () { $('#payment-check-all').click(function () { $('.payment-checkbox').prop('checked', this.checked); }); $('#create-new-payment').click(function() { location.href = '/payment/create'; }); $('#split-payments').click(function() { let paymentIds = getPaymentIds(); if (paymentIds.length == 0) { flash('You need to select the payments first.', 'warning'); } else { $("#group-split-payment-modal #paymentIds").val(paymentIds); $("#group-split-payment-modal").modal(); } }); $(".pay-transaction-button").click(function () { var element = this; let transactionId = element.dataset.transactionId; $.ajax({ url: '/transaction/' + transactionId + '/pay', success: function(result) { flash('Payment successfull.'); element.parentElement.parentElement.remove() }, error: function() { flash('This transaction is not yours to pay..', 'danger'); } }); }); $(".delete-payment-button").click(function () { var element = this; let paymentId = element.dataset.paymentId; let token = element.dataset.token; $.ajax({ url: '/payment/' + paymentId, method: 'POST', data: { _method: 'delete', _token: token }, success: function(result) { flash('Payment was deleted!'); element.parentElement.parentElement.remove() }, error: function() { flash('There was an error do delete this payment.', 'danger'); } }); }); $(".see-bill-button").click(function () { let billId = this.dataset.billId; let billName = this.dataset.billName; $.ajax({ url: '/bill/' + billId, success: function(result) { $("#bill-modal").modal(); $("#bill-modal .modal-title").html(billName); $("#bill-modal .modal-body").html(result); }, error: function() { flash('There was a problem to show this bill.', 'danger'); } }); }); getPaymentIds = function() { let paymentCheckbox = document.querySelectorAll('.payment-checkbox:checked'); let paymentIds = []; paymentCheckbox.forEach( function(element) { paymentIds.push(element.value); } ) return paymentIds; } });
var data = { "body": "<g fill=\"currentColor\"><path d=\"M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm0 18a8 8 0 1 1 8-8a8 8 0 0 1-8 8z\"/><path d=\"M15 11h-2V9a1 1 0 0 0-2 0v2H9a1 1 0 0 0 0 2h2v2a1 1 0 0 0 2 0v-2h2a1 1 0 0 0 0-2z\"/></g>", "width": 24, "height": 24 }; export default data;
/// <reference types="cypress" /> // *********************************************************** // This example plugins/index.js can be used to load plugins // // You can change the location of this file or turn off loading // the plugins file with the 'pluginsFile' configuration option. // // You can read more here: // https://on.cypress.io/plugins-guide // *********************************************************** // This function is called when a project is opened or re-opened (e.g. due to // the project's config changing) /** * @type {Cypress.PluginConfig} */ module.exports = (on, config) => { // `on` is used to hook into various events Cypress emits // `config` is the resolved Cypress config if (config.env.COVERAGE_RUN) { require('@cypress/code-coverage/task')(on, config) } return config }
// 身份验证 import Taro, { Component } from '@tarojs/taro' import { View, Image, Text } from '@tarojs/components' import { connect } from '@tarojs/redux' import { AtButton, AtInput } from 'taro-ui' import BackHeader from '../../../../components/BackHead' import Info from '../../../../images/user/authentication/info.png' import Close from '../../../../images/user/authentication/close.png' import Unknow from '../../../../images/user/authentication/unknow.png' import Add from '../../../../images/user/authentication/add.png' import '../index.scss' import './index.scss' @connect(({ user }) => ({ ...user, })) export default class Authentication extends Component { config = { navigationBarTitleText: '身份认证', }; state = { name: '', closeFlag: true, code: '', frontFlag:false, behindFlag:false, frontImage:'', behidndImage:'' } componentDidMount = () => { } close = () => { this.setState({ closeFlag: false }) } getName = (value) => { this.setState({ name: value }) } getCode = (value) => { this.setState({ code: value }) } upload = (type) => { let that = this Taro.chooseImage({ count: 1, sizeType: ['compressed'], sourceType: ['camera','album'], success(res) { if (type == 'front') { that.setState({ frontImage:res.tempFilePaths, frontFlag:true }) } else { that.setState({ behidndImage:res.tempFilePaths, behindFlag:true }) } } }).then() } render() { const { userInfo } = this.props const { closeFlag, name, code, frontFlag, behindFlag ,frontImage, behidndImage} = this.state return ( <View className='edit-info edit-name'> <BackHeader title='身份认证' /> {closeFlag && <View className='at-row at-row__align--center at-row__justify--center info-warp'> <View className='at-col at-col-2'> <Image src={Info} /> </View> <View className='at-col at-col--wrap'>为保障为您本人购买/租用商品,现需上传身份证,请确保身份证正确、清晰无反光</View> <View className='at-col at-col-2'> <Image src={Close} onClick={this.close} /> </View> </View> } <View className='info-title'> 个人信息认证 </View> <View className='authentication-form'> <View className='attribute-name'> 姓名 </View> <AtInput name='name' title='' type='text' placeholder='请输入姓名' value={name} onChange={this.getName} /> <View className='attribute-name'> 证件号(将加密处理) </View> <AtInput name='code' title='' type='idcard' placeholder='请输入身份证号' value={code} onChange={this.getCode} /> <View className='attribute-name at-row'> <View className='at-col at-col-8'> 证件照(将加密处理) </View> <View className='at-col approve at-col-4 at-row'> <Image src={Unknow} /> <Text>审核标准</Text> </View> </View> </View> <View className='at-row upload-warp at-row__justify--around'> <View className='upload-card at-col-5'> {!frontFlag && <Image src={Add} onClick={()=>this.upload('front')} />} {frontFlag && <Image src={frontImage} className='fullImage' onClick={()=>this.upload('front')} />} </View> <View className='upload-card at-col-5'> {!behindFlag && <Image src={Add} onClick={() => this.upload('behind')} />} {behindFlag && <Image src={behidndImage} className='fullImage' onClick={()=> this.upload('behind')} />} </View> </View> <AtButton type='primary' size='normal'>认证</AtButton> </View> ) } }
'use strict' const Joi = require('@hapi/joi') const { isBuildStatus } = require('../build-status') const keywords = ['vso', 'vsts', 'azure-devops'] const schema = Joi.object({ message: Joi.alternatives() .try( isBuildStatus, Joi.equal('unknown'), Joi.equal('set up now'), Joi.equal('never built'), Joi.equal('never deployed') ) .required(), }).required() async function fetch(serviceInstance, { url, qs = {}, errorMessages }) { // Microsoft documentation: https://docs.microsoft.com/en-us/rest/api/vsts/build/status/get const { message: status } = await serviceInstance._requestSvg({ schema, url, options: { qs }, errorMessages, }) return { status } } module.exports = { keywords, fetch }
# gunicorn configuration file import os bind = "{}:{}".format(os.getenv("FLASK_HOST", "0.0.0.0"), os.getenv("FLASK_PORT", 5080)) # Run the web service on container startup. Here we use the gunicorn # webserver, with one worker process and 8 threads. # For environments with multiple CPU cores, increase the number of workers # to be equal to the cores available. # Using recommendations from https://pythonspeed.com/articles/gunicorn-in-docker/ workers = 2 threads = 4 worker_class = "gthread" # Timeout is set to 0 to disable the timeouts of the workers to allow Cloud Run to handle instance scaling. timeout = 0 # Fix heartbeat system writing to /tmp - https://docs.gunicorn.org/en/stable/faq.html#blocking-os-fchmod worker_tmp_dir = "/dev/shm"
from django.conf.urls import url, include from django.contrib import admin from django.urls import path from apps.endpoints.urls import urlpatterns as endpoints_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += endpoints_urlpatterns
import sys import os import sty from autopalette import BasicTheme from autopalette.colormatch import ColorPoint from autopalette.colortrans import rgb2short from autopalette.utils import ( terminal_colors, select_render_engine, parse_color, select_palette, ) class ColoredString(str): def __new__(cls, body, theme, key='', term_colors=0): return super().__new__(cls, body) def __init__(self, body, theme, key='', term_colors=0): super().__init__() self.theme = theme self.key = key self.render = self.theme.renderer.render self._render = self.theme.renderer._render self.term_colors = term_colors @property def _raw(self): return super().__repr__() @property def _body(self): return super().__str__() def copy(self, body): return ColoredString(body, theme=self.theme) @property def id(self): if self.key: color = parse_color(self.key) else: color = parse_color(self._body) text = self.render(self._body, fg=color) return self.copy(text) @property def id256(self): if self.term_colors == 0: return self.copy(self._body) if self.key: color = parse_color(self.key) else: color = parse_color(self._body) ansi = int(rgb2short(color.hex_l)[0]) match = ColorPoint(source=color, target=color, ansi=ansi) text = self._render(self._body, fg=match) return self.copy(text) @property def p(self): text = self.theme.base(self._body) return self.copy(text) @property def light(self): text = self.theme.light(self._body) return self.copy(text) @property def dark(self): text = self.theme.dark(self._body) return self.copy(text) @property def h1(self): text = self.theme.h1(self._body) return self.copy(text) @property def h2(self): text = self.theme.h2(self._body) return self.copy(text) @property def h3(self): text = self.theme.h3(self._body) return self.copy(text) @property def h4(self): text = self.theme.h4(self._body) return self.copy(text) @property def li(self): text = self.theme.light('- ' + self._body) return self.copy(text) @property def err(self): text = self.theme.error(self._body) return self.copy(text) @property def warn(self): text = self.theme.warning(self._body) return self.copy(text) @property def info(self): text = self.theme.info(self._body) return self.copy(text) @property def ok(self): text = self.theme.ok(self._body) return self.copy(text) @property def b(self): if terminal_colors() == 0: return self.copy(self._body) text = self._body text = sty.ef.bold + text + sty.rs.all return self.copy(text) @property def i(self): if terminal_colors() == 0: return self.copy(self._body) text = self._body text = sty.ef.italic + text + sty.rs.all return self.copy(text) @property def u(self): if terminal_colors() == 0: return self.copy(self._body) text = self._body text = sty.ef.underl + text + sty.rs.all return self.copy(text) @property def r(self): if terminal_colors() == 0: return self.copy(self._body) text = self._body text = sty.ef.inverse + text + sty.rs.all return self.copy(text) @property def m(self): if terminal_colors() == 0: return self.copy(self._body) text = self._body text = sty.ef.dim + text + sty.rs.all return self.copy(text) @property def raw(self): return repr(self) class AutoFormat(object): def __init__(self, term_colors=0, renderer=None, palette=None, theme=None): self.init(term_colors=term_colors, renderer=renderer, palette=palette, theme=theme) def init(self, term_colors=0, renderer=None, palette=None, theme=None, fix_all=False, fix_text=False): self.term_colors = term_colors or terminal_colors(sys.stdout) self.renderer = renderer or select_render_engine(self.term_colors) self.palette = palette or select_palette(self.term_colors) self.theme = theme(palette=self.palette, renderer=self.renderer) if theme else BasicTheme( palette=self.palette, renderer=self.renderer) self._need_text_fix = self.need_text_fix() self._need_emoji_fix = self.need_emoji_fix() if fix_all and self._need_emoji_fix: fix_text = True try: from emoji2text import emoji2text self.fix_emoji = emoji2text except ImportError: raise ImportError('Please install python package: emoji2text') if fix_text and self._need_text_fix: try: from ftfy import fix_text self.fix_text = fix_text except ImportError: raise ImportError('Please install python package: ftfy') def need_text_fix(self): if 0 <= self.term_colors <= 16: return True return False def need_emoji_fix(self): if 0 <= self.term_colors <= 16: return True return False def fix_text(self, text): return text def fix_emoji(self, text, sep): return text def __call__(self, content, *, key=''): if self._need_text_fix: content = self.fix_text(content) if self._need_emoji_fix: content = self.fix_emoji(content, ':') return ColoredString(content, theme=self.theme, key=key, term_colors=self.term_colors)
/* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const jade = require("jade") const path = require("path") const fs = require("fs") const Backbone = require("backbone") const { fabricate } = require("@artsy/antigravity") const Profile = require("../../../models/profile") const render = function (templateName) { const filename = path.resolve(__dirname, `../templates/${templateName}.jade`) return jade.compile(fs.readFileSync(filename), { filename }) } describe("Partner header", () => describe("canonical links", function () { beforeEach(function () { return (this.profile = new Profile(fabricate("profile"))) }) it("has a canonical link to the full artist page on partner artist pages", function () { this.template = render("index")({ profile: this.profile, sd: { APP_URL: "http://localhost:3004", CURRENT_PATH: "/pace-gallery" }, asset() {}, params: { id: "pace-gallery", artistId: "yoshitomo-nara" }, }) return this.template.should.containEql( '<link rel="canonical" href="http://localhost:3004/artist/yoshitomo-nara">' ) }) it("has a canonical link to current url on other pages", function () { this.template = render("index")({ profile: this.profile, sd: { APP_URL: "http://localhost:3004", CURRENT_PATH: "/pace-gallery" }, asset() {}, params: { id: "pace-gallery" }, }) return this.template.should.containEql( '<link rel="canonical" href="http://localhost:3004/pace-gallery">' ) }) return describe("followers", function () { describe("galleries", () => it("does not display follower count", function () { this.profile.set({ owner_type: "PartnerGallery", follows_count: 999 }) this.template = render("index")({ profile: this.profile, tab: "overview", sd: { APP_URL: "http://localhost:3004", CURRENT_PATH: "/pace-gallery", }, asset() {}, params: { id: "pace-gallery" }, }) return this.template.should.not.containEql("partner-followers") })) return describe("institutions", function () { beforeEach(function () { return (this.profile = new Profile( fabricate("profile", { owner_type: "PartnerInstitution" }) )) }) return it("does not display follower count", function () { this.profile.set({ follows_count: 2222 }) this.template = render("index")({ profile: this.profile, tab: "overview", sd: { APP_URL: "http://localhost:3004", CURRENT_PATH: "/philadelphia-museum-of-art", }, asset() {}, params: { id: "philadelphia-museum-of-art" }, }) return this.template.should.not.containEql("partner-followers") }) }) }) }))
this.wp=this.wp||{},this.wp.formatLibrary=function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=350)}({0:function(t,e){!function(){t.exports=this.wp.element}()},1:function(t,e){!function(){t.exports=this.wp.i18n}()},10:function(t,e,n){"use strict";function r(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}n.d(e,"a",(function(){return r}))},11:function(t,e,n){"use strict";function r(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function i(t,e,n){return e&&r(t.prototype,e),n&&r(t,n),t}n.d(e,"a",(function(){return i}))},12:function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}n.d(e,"a",(function(){return r}))},13:function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var r=n(31),i=n(5);function o(t,e){return!e||"object"!==Object(r.a)(e)&&"function"!=typeof e?Object(i.a)(t):e}},14:function(t,e,n){"use strict";function r(t){return(r=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}n.d(e,"a",(function(){return r}))},15:function(t,e,n){"use strict";function r(t,e){return(r=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&r(t,e)}n.d(e,"a",(function(){return i}))},18:function(t,e,n){"use strict";function r(){return(r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}n.d(e,"a",(function(){return r}))},19:function(t,e){!function(){t.exports=this.wp.keycodes}()},2:function(t,e){!function(){t.exports=this.lodash}()},21:function(t,e,n){"use strict";function r(t,e){if(null==t)return{};var n,r,i=function(t,e){if(null==t)return{};var n,r,i={},o=Object.keys(t);for(r=0;r<o.length;r++)n=o[r],e.indexOf(n)>=0||(i[n]=t[n]);return i}(t,e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(r=0;r<o.length;r++)n=o[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}n.d(e,"a",(function(){return r}))},22:function(t,e){!function(){t.exports=this.wp.richText}()},25:function(t,e){!function(){t.exports=this.wp.dom}()},26:function(t,e){!function(){t.exports=this.wp.url}()},3:function(t,e){!function(){t.exports=this.wp.components}()},31:function(t,e,n){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function i(t){return(i="function"==typeof Symbol&&"symbol"===r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)})(t)}n.d(e,"a",(function(){return i}))},350:function(t,e,n){"use strict";n.r(e);var r=n(21),i=n(22),o=n(0),a=n(1),c=n(6),u=Object(a.__)("Bold"),l={name:"core/bold",title:u,tagName:"strong",className:null,edit:function(t){var e=t.isActive,n=t.value,r=t.onChange,a=function(){return r(Object(i.toggleFormat)(n,{type:"core/bold"}))};return Object(o.createElement)(o.Fragment,null,Object(o.createElement)(c.RichTextShortcut,{type:"primary",character:"b",onUse:a}),Object(o.createElement)(c.RichTextToolbarButton,{name:"bold",icon:"editor-bold",title:u,onClick:a,isActive:e,shortcutType:"primary",shortcutCharacter:"b"}),Object(o.createElement)(c.__unstableRichTextInputEvent,{inputType:"formatBold",onInput:a}))}},s=Object(a.__)("Inline Code"),b={name:"core/code",title:s,tagName:"code",className:null,__unstableInputRule:function(t){var e=t,n=e.start,r=e.text;if("`"!==r.slice(n-1,n))return t;var o=r.slice(0,n-1).lastIndexOf("`");if(-1===o)return t;var a=o,c=n-2;return a===c?t:(t=Object(i.remove)(t,a,a+1),t=Object(i.remove)(t,c,c+1),t=Object(i.applyFormat)(t,{type:"core/code"},a,c))},edit:function(t){var e=t.value,n=t.onChange,r=t.isActive;return Object(o.createElement)(c.RichTextToolbarButton,{icon:"editor-code",title:s,onClick:function(){return n(Object(i.toggleFormat)(e,{type:"core/code"}))},isActive:r})}},p=n(7),f=n(12),d=n(11),m=n(13),h=n(14),O=n(5),v=n(15),j=n(18),y=n(3),g=n(19),k=n(25),w=["image"],_=Object(a.__)("Inline image"),E=function(t){return t.stopPropagation()},C=function(t){var e=t.dependencies,n=Object(r.a)(t,["dependencies"]);return Object(o.createElement)(y.Popover,Object(j.a)({position:"bottom center",focusOnMount:!1,anchorRect:Object(o.useMemo)((function(){return Object(k.computeCaretRect)()}),e)},n))},S={name:"core/image",title:_,keywords:[Object(a.__)("photo"),Object(a.__)("media")],object:!0,tagName:"img",className:null,attributes:{className:"class",style:"style",url:"src",alt:"alt"},edit:function(t){function e(){var t;return Object(f.a)(this,e),(t=Object(m.a)(this,Object(h.a)(e).apply(this,arguments))).onChange=t.onChange.bind(Object(O.a)(t)),t.onKeyDown=t.onKeyDown.bind(Object(O.a)(t)),t.openModal=t.openModal.bind(Object(O.a)(t)),t.closeModal=t.closeModal.bind(Object(O.a)(t)),t.state={modal:!1},t}return Object(v.a)(e,t),Object(d.a)(e,[{key:"onChange",value:function(t){this.setState({width:t})}},{key:"onKeyDown",value:function(t){[g.LEFT,g.DOWN,g.RIGHT,g.UP,g.BACKSPACE,g.ENTER].indexOf(t.keyCode)>-1&&t.stopPropagation()}},{key:"openModal",value:function(){this.setState({modal:!0})}},{key:"closeModal",value:function(){this.setState({modal:!1})}},{key:"render",value:function(){var t=this,e=this.props,n=e.value,r=e.onChange,u=e.isObjectActive,l=e.activeObjectAttributes,s=l.style;return Object(o.createElement)(c.MediaUploadCheck,null,Object(o.createElement)(c.RichTextToolbarButton,{icon:Object(o.createElement)(y.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},Object(o.createElement)(y.Path,{d:"M4 16h10c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v9c0 1.1.9 2 2 2zM4 5h10v9H4V5zm14 9v2h4v-2h-4zM2 20h20v-2H2v2zm6.4-8.8L7 9.4 5 12h8l-2.6-3.4-2 2.6z"})),title:_,onClick:this.openModal,isActive:u}),this.state.modal&&Object(o.createElement)(c.MediaUpload,{allowedTypes:w,onSelect:function(e){var o=e.id,a=e.url,c=e.alt,u=e.width;t.closeModal(),r(Object(i.insertObject)(n,{type:"core/image",attributes:{className:"wp-image-".concat(o),style:"width: ".concat(Math.min(u,150),"px;"),url:a,alt:c}}))},onClose:this.closeModal,render:function(t){return(0,t.open)(),null}}),u&&Object(o.createElement)(C,{dependencies:[s,n.start]},Object(o.createElement)("form",{className:"editor-format-toolbar__image-container-content block-editor-format-toolbar__image-container-content",onKeyPress:E,onKeyDown:this.onKeyDown,onSubmit:function(e){var i=n.replacements.slice();i[n.start]={type:"core/image",attributes:Object(p.a)({},l,{style:"width: ".concat(t.state.width,"px;")})},r(Object(p.a)({},n,{replacements:i})),e.preventDefault()}},Object(o.createElement)(y.TextControl,{className:"editor-format-toolbar__image-container-value block-editor-format-toolbar__image-container-value",type:"number",label:Object(a.__)("Width"),value:this.state.width,min:1,onChange:this.onChange}),Object(o.createElement)(y.IconButton,{icon:"editor-break",label:Object(a.__)("Apply"),type:"submit"}))))}}],[{key:"getDerivedStateFromProps",value:function(t,e){var n=t.activeObjectAttributes.style;return n===e.previousStyle?null:n?{width:n.replace(/\D/g,""),previousStyle:n}:{width:void 0,previousStyle:n}}}]),e}(o.Component)},T=Object(a.__)("Italic"),x={name:"core/italic",title:T,tagName:"em",className:null,edit:function(t){var e=t.isActive,n=t.value,r=t.onChange,a=function(){return r(Object(i.toggleFormat)(n,{type:"core/italic"}))};return Object(o.createElement)(o.Fragment,null,Object(o.createElement)(c.RichTextShortcut,{type:"primary",character:"i",onUse:a}),Object(o.createElement)(c.RichTextToolbarButton,{name:"italic",icon:"editor-italic",title:T,onClick:a,isActive:e,shortcutType:"primary",shortcutCharacter:"i"}),Object(o.createElement)(c.__unstableRichTextInputEvent,{inputType:"formatItalic",onInput:a}))}},L=n(26),R=n(52),P=n(2);function A(t){if(!t)return!1;var e=t.trim();if(!e)return!1;if(/^\S+:/.test(e)){var n=Object(L.getProtocol)(e);if(!Object(L.isValidProtocol)(n))return!1;if(Object(P.startsWith)(n,"http")&&!/^https?:\/\/[^\/\s]/i.test(e))return!1;var r=Object(L.getAuthority)(e);if(!Object(L.isValidAuthority)(r))return!1;var i=Object(L.getPath)(e);if(i&&!Object(L.isValidPath)(i))return!1;var o=Object(L.getQueryString)(e);if(o&&!Object(L.isValidQueryString)(o))return!1;var a=Object(L.getFragment)(e);if(a&&!Object(L.isValidFragment)(a))return!1}return!(Object(P.startsWith)(e,"#")&&!Object(L.isValidFragment)(e))}function N(t){var e=t.url,n=t.opensInNewWindow,r=t.text,i={type:"core/link",attributes:{url:e}};if(n){var o=Object(a.sprintf)(Object(a.__)("%s (opens in a new tab)"),r);i.attributes.target="_blank",i.attributes.rel="noreferrer noopener",i.attributes["aria-label"]=o}return i}var F=function(t){return t.stopPropagation()};function I(t,e){return t.addingLink||e.editLink}var M=function(t){var e=t.isActive,n=t.addingLink,i=t.value,a=Object(r.a)(t,["isActive","addingLink","value"]),u=Object(o.useMemo)((function(){var t=window.getSelection(),e=t.rangeCount>0?t.getRangeAt(0):null;if(e){if(n)return Object(k.getRectangleFromRange)(e);var r=e.startContainer;for(r=r.nextElementSibling||r;r.nodeType!==window.Node.ELEMENT_NODE;)r=r.parentNode;var i=r.closest("a");return i?i.getBoundingClientRect():void 0}}),[e,n,i.start,i.end]);return u?Object(o.createElement)(c.URLPopover,Object(j.a)({anchorRect:u},a)):null},V=function(t){function e(){var t;return Object(f.a)(this,e),(t=Object(m.a)(this,Object(h.a)(e).apply(this,arguments))).editLink=t.editLink.bind(Object(O.a)(t)),t.submitLink=t.submitLink.bind(Object(O.a)(t)),t.onKeyDown=t.onKeyDown.bind(Object(O.a)(t)),t.onChangeInputValue=t.onChangeInputValue.bind(Object(O.a)(t)),t.setLinkTarget=t.setLinkTarget.bind(Object(O.a)(t)),t.onFocusOutside=t.onFocusOutside.bind(Object(O.a)(t)),t.resetState=t.resetState.bind(Object(O.a)(t)),t.autocompleteRef=Object(o.createRef)(),t.state={opensInNewWindow:!1,inputValue:""},t}return Object(v.a)(e,t),Object(d.a)(e,[{key:"onKeyDown",value:function(t){[g.LEFT,g.DOWN,g.RIGHT,g.UP,g.BACKSPACE,g.ENTER].indexOf(t.keyCode)>-1&&t.stopPropagation()}},{key:"onChangeInputValue",value:function(t){this.setState({inputValue:t})}},{key:"setLinkTarget",value:function(t){var e=this.props,n=e.activeAttributes.url,r=void 0===n?"":n,o=e.value,a=e.onChange;if(this.setState({opensInNewWindow:t}),!I(this.props,this.state)){var c=Object(i.getTextContent)(Object(i.slice)(o));a(Object(i.applyFormat)(o,N({url:r,opensInNewWindow:t,text:c})))}}},{key:"editLink",value:function(t){this.setState({editLink:!0}),t.preventDefault()}},{key:"submitLink",value:function(t){var e=this.props,n=e.isActive,r=e.value,o=e.onChange,c=e.speak,u=this.state,l=u.inputValue,s=u.opensInNewWindow,b=Object(L.prependHTTP)(l),p=N({url:b,opensInNewWindow:s,text:Object(i.getTextContent)(Object(i.slice)(r))});if(t.preventDefault(),Object(i.isCollapsed)(r)&&!n){var f=Object(i.applyFormat)(Object(i.create)({text:b}),p,0,b.length);o(Object(i.insert)(r,f))}else o(Object(i.applyFormat)(r,p));this.resetState(),A(b)?c(n?Object(a.__)("Link edited."):Object(a.__)("Link inserted."),"assertive"):c(Object(a.__)("Warning: the link has been inserted but may have errors. Please test it."),"assertive")}},{key:"onFocusOutside",value:function(){var t=this.autocompleteRef.current;t&&t.contains(document.activeElement)||this.resetState()}},{key:"resetState",value:function(){this.props.stopAddingLink(),this.setState({editLink:!1})}},{key:"render",value:function(){var t=this,e=this.props,n=e.isActive,r=e.activeAttributes.url,i=e.addingLink,u=e.value;if(!n&&!i)return null;var l=this.state,s=l.inputValue,b=l.opensInNewWindow,p=I(this.props,this.state);return Object(o.createElement)(M,{value:u,isActive:n,addingLink:i,onFocusOutside:this.onFocusOutside,onClose:this.resetState,focusOnMount:!!p&&"firstElement",renderSettings:function(){return Object(o.createElement)(y.ToggleControl,{label:Object(a.__)("Open in New Tab"),checked:b,onChange:t.setLinkTarget})}},p?Object(o.createElement)(c.URLPopover.LinkEditor,{className:"editor-format-toolbar__link-container-content block-editor-format-toolbar__link-container-content",value:s,onChangeInputValue:this.onChangeInputValue,onKeyDown:this.onKeyDown,onKeyPress:F,onSubmit:this.submitLink,autocompleteRef:this.autocompleteRef}):Object(o.createElement)(c.URLPopover.LinkViewer,{className:"editor-format-toolbar__link-container-content block-editor-format-toolbar__link-container-content",onKeyPress:F,url:r,onEditLinkClick:this.editLink,linkClassName:A(Object(L.prependHTTP)(r))?void 0:"has-invalid-link"}))}}],[{key:"getDerivedStateFromProps",value:function(t,e){var n=t.activeAttributes,r=n.url,i="_blank"===n.target;if(!I(t,e)){var o={};return r!==e.inputValue&&(o.inputValue=r),i!==e.opensInNewWindow&&(o.opensInNewWindow=i),Object.keys(o).length?o:null}return null}}]),e}(o.Component),D=Object(y.withSpokenMessages)(V),U=Object(a.__)("Link"),K={name:"core/link",title:U,tagName:"a",className:null,attributes:{url:"href",target:"target"},__unstablePasteRule:function(t,e){var n=e.html,r=e.plainText;if(Object(i.isCollapsed)(t))return t;var o=(n||r).replace(/<[^>]+>/g,"").trim();return Object(L.isURL)(o)?(window.console.log("Created link:\n\n",o),Object(i.applyFormat)(t,{type:"core/link",attributes:{url:Object(R.decodeEntities)(o)}})):t},edit:Object(y.withSpokenMessages)(function(t){function e(){var t;return Object(f.a)(this,e),(t=Object(m.a)(this,Object(h.a)(e).apply(this,arguments))).addLink=t.addLink.bind(Object(O.a)(t)),t.stopAddingLink=t.stopAddingLink.bind(Object(O.a)(t)),t.onRemoveFormat=t.onRemoveFormat.bind(Object(O.a)(t)),t.state={addingLink:!1},t}return Object(v.a)(e,t),Object(d.a)(e,[{key:"addLink",value:function(){var t=this.props,e=t.value,n=t.onChange,r=Object(i.getTextContent)(Object(i.slice)(e));r&&Object(L.isURL)(r)?n(Object(i.applyFormat)(e,{type:"core/link",attributes:{url:r}})):r&&Object(L.isEmail)(r)?n(Object(i.applyFormat)(e,{type:"core/link",attributes:{url:"mailto:".concat(r)}})):this.setState({addingLink:!0})}},{key:"stopAddingLink",value:function(){this.setState({addingLink:!1})}},{key:"onRemoveFormat",value:function(){var t=this.props,e=t.value,n=t.onChange,r=t.speak;n(Object(i.removeFormat)(e,"core/link")),r(Object(a.__)("Link removed."),"assertive")}},{key:"render",value:function(){var t=this.props,e=t.isActive,n=t.activeAttributes,r=t.value,i=t.onChange;return Object(o.createElement)(o.Fragment,null,Object(o.createElement)(c.RichTextShortcut,{type:"primary",character:"k",onUse:this.addLink}),Object(o.createElement)(c.RichTextShortcut,{type:"primaryShift",character:"k",onUse:this.onRemoveFormat}),e&&Object(o.createElement)(c.RichTextToolbarButton,{name:"link",icon:"editor-unlink",title:Object(a.__)("Unlink"),onClick:this.onRemoveFormat,isActive:e,shortcutType:"primaryShift",shortcutCharacter:"k"}),!e&&Object(o.createElement)(c.RichTextToolbarButton,{name:"link",icon:"admin-links",title:U,onClick:this.addLink,isActive:e,shortcutType:"primary",shortcutCharacter:"k"}),Object(o.createElement)(D,{addingLink:this.state.addingLink,stopAddingLink:this.stopAddingLink,isActive:e,activeAttributes:n,value:r,onChange:i}))}}]),e}(o.Component))},W=Object(a.__)("Strikethrough");[l,b,S,x,K,{name:"core/strikethrough",title:W,tagName:"s",className:null,edit:function(t){var e=t.isActive,n=t.value,r=t.onChange;return Object(o.createElement)(c.RichTextToolbarButton,{icon:"editor-strikethrough",title:W,onClick:function(){return r(Object(i.toggleFormat)(n,{type:"core/strikethrough"}))},isActive:e})}},{name:"core/underline",title:Object(a.__)("Underline"),tagName:"span",className:null,attributes:{style:"style"},edit:function(t){var e=t.value,n=t.onChange,r=function(){n(Object(i.toggleFormat)(e,{type:"core/underline",attributes:{style:"text-decoration: underline;"}}))};return Object(o.createElement)(o.Fragment,null,Object(o.createElement)(c.RichTextShortcut,{type:"primary",character:"u",onUse:r}),Object(o.createElement)(c.__unstableRichTextInputEvent,{inputType:"formatUnderline",onInput:r}))}}].forEach((function(t){var e=t.name,n=Object(r.a)(t,["name"]);return Object(i.registerFormatType)(e,n)}))},5:function(t,e,n){"use strict";function r(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}n.d(e,"a",(function(){return r}))},52:function(t,e){!function(){t.exports=this.wp.htmlEntities}()},6:function(t,e){!function(){t.exports=this.wp.blockEditor}()},7:function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var r=n(10);function i(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{},i=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(i=i.concat(Object.getOwnPropertySymbols(n).filter((function(t){return Object.getOwnPropertyDescriptor(n,t).enumerable})))),i.forEach((function(e){Object(r.a)(t,e,n[e])}))}return t}}});
from werkzeug.utils import import_string import errno import os import types import typing as t """ This file was borrowed from the Flask project - BSD-3-Clause License """ class ConfigAttribute: """Makes an attribute forward to the config""" def __init__(self, name: str, get_converter: t.Optional[t.Callable] = None) -> None: self.__name__ = name self.get_converter = get_converter def __get__(self, obj: t.Any, owner: t.Any = None) -> t.Any: if obj is None: return self rv = obj.config[self.__name__] if self.get_converter is not None: rv = self.get_converter(rv) return rv def __set__(self, obj: t.Any, value: t.Any) -> None: obj.config[self.__name__] = value class Config(dict): """Works exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config. Either you can fill the config from a config file:: app.config.from_pyfile('yourconfig.cfg') Or alternatively you can define the configuration options in the module that calls :meth:`from_object` or provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call:: DEBUG = True SECRET_KEY = 'development key' app.config.from_object(__name__) In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application. Probably the most interesting way to load configurations is from an environment variable pointing to a file:: app.config.from_envvar('YOURAPPLICATION_SETTINGS') In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X use the export statement:: export YOURAPPLICATION_SETTINGS='/path/to/config/file' On windows use `set` instead. :param root_path: path to which files are read relative from. When the config object is created by the application, this is the application's :attr:`~flask.Flask.root_path`. :param defaults: an optional dictionary of default values """ def __init__(self, root_path: str, defaults: t.Optional[dict] = None) -> None: dict.__init__(self, defaults or {}) self.root_path = root_path def from_envvar(self, variable_name: str, silent: bool = False) -> bool: """Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:: app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) :param variable_name: name of the environment variable :param silent: set to ``True`` if you want silent failure for missing files. :return: ``True`` if the file was loaded successfully. """ rv = os.environ.get(variable_name) if not rv: if silent: return False raise RuntimeError( f"The environment variable {variable_name!r} is not set" " and as such configuration could not be loaded. Set" " this variable and make it point to a configuration" " file" ) return self.from_pyfile(rv, silent=silent) def from_pyfile(self, filename: str, silent: bool = False) -> bool: """Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the :meth:`from_object` function. :param filename: the filename of the config. This can either be an absolute filename or a filename relative to the root path. :param silent: set to ``True`` if you want silent failure for missing files. :return: ``True`` if the file was loaded successfully. .. versionadded:: 0.7 `silent` parameter. """ filename = os.path.join(self.root_path, filename) d = types.ModuleType("config") d.__file__ = filename try: with open(filename, mode="rb") as config_file: exec(compile(config_file.read(), filename, "exec"), d.__dict__) except OSError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR): return False e.strerror = f"Unable to load configuration file ({e.strerror})" raise self.from_object(d) return True def from_object(self, obj: t.Union[object, str]) -> None: """Updates the values from the given object. An object can be of one of the following two types: - a string: in this case the object with that name will be imported - an actual object reference: that object is used directly Objects are usually either modules or classes. :meth:`from_object` loads only the uppercase attributes of the module/class. A ``dict`` object will not work with :meth:`from_object` because the keys of a ``dict`` are not attributes of the ``dict`` class. Example of module-based configuration:: app.config.from_object('yourapplication.default_config') from yourapplication import default_config app.config.from_object(default_config) Nothing is done to the object before loading. If the object is a class and has ``@property`` attributes, it needs to be instantiated before being passed to this method. You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. See :ref:`config-dev-prod` for an example of class-based configuration using :meth:`from_object`. :param obj: an import name or object """ if isinstance(obj, str): obj = import_string(obj) for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key) def from_file( self, filename: str, load: t.Callable[[t.IO[t.Any]], t.Mapping], silent: bool = False, ) -> bool: """Update the values in the config from a file that is loaded using the ``load`` parameter. The loaded data is passed to the :meth:`from_mapping` method. .. code-block:: python import toml app.config.from_file("config.toml", load=toml.load) :param filename: The path to the data file. This can be an absolute path or relative to the config root path. :param load: A callable that takes a file handle and returns a mapping of loaded data from the file. :type load: ``Callable[[Reader], Mapping]`` where ``Reader`` implements a ``read`` method. :param silent: Ignore the file if it doesn't exist. :return: ``True`` if the file was loaded successfully. .. versionadded:: 2.0 """ filename = os.path.join(self.root_path, filename) try: with open(filename) as f: obj = load(f) except OSError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): return False e.strerror = f"Unable to load configuration file ({e.strerror})" raise return self.from_mapping(obj) def from_json(self, filename: str, silent: bool = False) -> bool: """Update the values in the config from a JSON file. The loaded data is passed to the :meth:`from_mapping` method. :param filename: The path to the JSON file. This can be an absolute path or relative to the config root path. :param silent: Ignore the file if it doesn't exist. :return: ``True`` if the file was loaded successfully. .. deprecated:: 2.0.0 Will be removed in Flask 2.1. Use :meth:`from_file` instead. This was removed early in 2.0.0, was added back in 2.0.1. .. versionadded:: 0.11 """ import warnings import json warnings.warn( "'from_json' is deprecated and will be removed in Flask" " 2.1. Use 'from_file(path, json.load)' instead.", DeprecationWarning, stacklevel=2, ) return self.from_file(filename, json.load, silent=silent) def from_mapping( self, mapping: t.Optional[t.Mapping[str, t.Any]] = None, **kwargs: t.Any ) -> bool: """Updates the config like :meth:`update` ignoring items with non-upper keys. :return: Always returns ``True``. .. versionadded:: 0.11 """ mappings: t.Dict[str, t.Any] = {} if mapping is not None: mappings.update(mapping) mappings.update(kwargs) for key, value in mappings.items(): if key.isupper(): self[key] = value return True def get_namespace( self, namespace: str, lowercase: bool = True, trim_namespace: bool = True ) -> t.Dict[str, t.Any]: """Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage:: app.config['IMAGE_STORE_TYPE'] = 'fs' app.config['IMAGE_STORE_PATH'] = '/var/app/images' app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com' image_store_config = app.config.get_namespace('IMAGE_STORE_') The resulting dictionary `image_store_config` would look like:: { 'type': 'fs', 'path': '/var/app/images', 'base_url': 'http://img.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. :param namespace: a configuration namespace :param lowercase: a flag indicating if the keys of the resulting dictionary should be lowercase :param trim_namespace: a flag indicating if the keys of the resulting dictionary should not include the namespace .. versionadded:: 0.11 """ rv = {} for k, v in self.items(): if not k.startswith(namespace): continue if trim_namespace: key = k[len(namespace) :] else: key = k if lowercase: key = key.lower() rv[key] = v return rv def __repr__(self) -> str: return f"<{type(self).__name__} {dict.__repr__(self)}>"
/**************************************************************************** ** ** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt3D module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL3$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPLv3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or later as published by the Free ** Software Foundation and appearing in the file LICENSE.GPL included in ** the packaging of this file. Please review the following information to ** ensure the GNU General Public License version 2.0 requirements will be ** met: http://www.gnu.org/licenses/gpl-2.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QT3DANIMATION_ANIMATION_CLIPANIMATOR_P_H #define QT3DANIMATION_ANIMATION_CLIPANIMATOR_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists for the convenience // of other Qt classes. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <Qt3DAnimation/private/backendnode_p.h> #include <Qt3DAnimation/private/animationutils_p.h> #include <Qt3DCore/qnodeid.h> QT_BEGIN_NAMESPACE namespace Qt3DAnimation { namespace Animation { struct Channel; class Handler; class Q_AUTOTEST_EXPORT ClipAnimator : public BackendNode { public: ClipAnimator(); void cleanup(); void setClipId(Qt3DCore::QNodeId clipId); Qt3DCore::QNodeId clipId() const { return m_clipId; } void setMapperId(Qt3DCore::QNodeId mapperId); Qt3DCore::QNodeId mapperId() const { return m_mapperId; } void setClockId(Qt3DCore::QNodeId clockId); Qt3DCore::QNodeId clockId() const { return m_clockId; } void setRunning(bool running); bool isRunning() const { return m_running; } void setLoops(int loops) { m_loops = loops; } int loops() const { return m_loops; } void setNormalizedLocalTime(float normalizedLocalTime, bool allowMarkDirty = true); float normalizedLocalTime() const { return m_normalizedLocalTime; } void syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime) override; void setHandler(Handler *handler) { m_handler = handler; } // Called by jobs bool canRun() const { return !m_clipId.isNull() && !m_mapperId.isNull(); } void setMappingData(const QVector<MappingData> &mappingData) { m_mappingData = mappingData; } QVector<MappingData> mappingData() const { return m_mappingData; } void setStartTime(qint64 globalTime) { m_lastGlobalTimeNS = globalTime; } int currentLoop() const { return m_currentLoop; } void setCurrentLoop(int currentLoop) { m_currentLoop = currentLoop; } void animationClipMarkedDirty() { setDirty(Handler::ClipAnimatorDirty); } void setClipFormat(const ClipFormat &clipFormat) { m_clipFormat = clipFormat; } ClipFormat clipFormat() const { return m_clipFormat; } qint64 nsSincePreviousFrame(qint64 currentGlobalTimeNS); void setLastGlobalTimeNS(qint64 lastGlobalTimeNS); double lastLocalTime() const; void setLastLocalTime(double lastLocalTime); float lastNormalizedLocalTime() { return m_lastNormalizedLocalTime; } void setLastNormalizedLocalTime(float normalizedLocalTime); bool isSeeking() const { return isValidNormalizedTime(m_normalizedLocalTime) && !qFuzzyCompare(m_lastNormalizedLocalTime, m_normalizedLocalTime); } private: Qt3DCore::QNodeId m_clipId; Qt3DCore::QNodeId m_mapperId; Qt3DCore::QNodeId m_clockId; bool m_running; int m_loops; // Working state qint64 m_lastGlobalTimeNS; double m_lastLocalTime; QVector<MappingData> m_mappingData; int m_currentLoop; ClipFormat m_clipFormat; float m_normalizedLocalTime; float m_lastNormalizedLocalTime; }; } // namespace Animation } // namespace Qt3DAnimation QT_END_NAMESPACE #endif // QT3DANIMATION_ANIMATION_CLIPANIMATOR_P_H
# Generated from src/blackbird.g4 by ANTLR 4.8 from antlr4 import * if __name__ is not None and "." in __name__: from .blackbirdParser import blackbirdParser else: from blackbirdParser import blackbirdParser # This class defines a complete listener for a parse tree produced by blackbirdParser. class blackbirdListener(ParseTreeListener): # Enter a parse tree produced by blackbirdParser#start. def enterStart(self, ctx:blackbirdParser.StartContext): pass # Exit a parse tree produced by blackbirdParser#start. def exitStart(self, ctx:blackbirdParser.StartContext): pass # Enter a parse tree produced by blackbirdParser#metadatablock. def enterMetadatablock(self, ctx:blackbirdParser.MetadatablockContext): pass # Exit a parse tree produced by blackbirdParser#metadatablock. def exitMetadatablock(self, ctx:blackbirdParser.MetadatablockContext): pass # Enter a parse tree produced by blackbirdParser#declarename. def enterDeclarename(self, ctx:blackbirdParser.DeclarenameContext): pass # Exit a parse tree produced by blackbirdParser#declarename. def exitDeclarename(self, ctx:blackbirdParser.DeclarenameContext): pass # Enter a parse tree produced by blackbirdParser#programname. def enterProgramname(self, ctx:blackbirdParser.ProgramnameContext): pass # Exit a parse tree produced by blackbirdParser#programname. def exitProgramname(self, ctx:blackbirdParser.ProgramnameContext): pass # Enter a parse tree produced by blackbirdParser#version. def enterVersion(self, ctx:blackbirdParser.VersionContext): pass # Exit a parse tree produced by blackbirdParser#version. def exitVersion(self, ctx:blackbirdParser.VersionContext): pass # Enter a parse tree produced by blackbirdParser#versionnumber. def enterVersionnumber(self, ctx:blackbirdParser.VersionnumberContext): pass # Exit a parse tree produced by blackbirdParser#versionnumber. def exitVersionnumber(self, ctx:blackbirdParser.VersionnumberContext): pass # Enter a parse tree produced by blackbirdParser#target. def enterTarget(self, ctx:blackbirdParser.TargetContext): pass # Exit a parse tree produced by blackbirdParser#target. def exitTarget(self, ctx:blackbirdParser.TargetContext): pass # Enter a parse tree produced by blackbirdParser#device. def enterDevice(self, ctx:blackbirdParser.DeviceContext): pass # Exit a parse tree produced by blackbirdParser#device. def exitDevice(self, ctx:blackbirdParser.DeviceContext): pass # Enter a parse tree produced by blackbirdParser#declaretype. def enterDeclaretype(self, ctx:blackbirdParser.DeclaretypeContext): pass # Exit a parse tree produced by blackbirdParser#declaretype. def exitDeclaretype(self, ctx:blackbirdParser.DeclaretypeContext): pass # Enter a parse tree produced by blackbirdParser#programtype. def enterProgramtype(self, ctx:blackbirdParser.ProgramtypeContext): pass # Exit a parse tree produced by blackbirdParser#programtype. def exitProgramtype(self, ctx:blackbirdParser.ProgramtypeContext): pass # Enter a parse tree produced by blackbirdParser#include. def enterInclude(self, ctx:blackbirdParser.IncludeContext): pass # Exit a parse tree produced by blackbirdParser#include. def exitInclude(self, ctx:blackbirdParser.IncludeContext): pass # Enter a parse tree produced by blackbirdParser#program. def enterProgram(self, ctx:blackbirdParser.ProgramContext): pass # Exit a parse tree produced by blackbirdParser#program. def exitProgram(self, ctx:blackbirdParser.ProgramContext): pass # Enter a parse tree produced by blackbirdParser#expressionvar. def enterExpressionvar(self, ctx:blackbirdParser.ExpressionvarContext): pass # Exit a parse tree produced by blackbirdParser#expressionvar. def exitExpressionvar(self, ctx:blackbirdParser.ExpressionvarContext): pass # Enter a parse tree produced by blackbirdParser#arrayvar. def enterArrayvar(self, ctx:blackbirdParser.ArrayvarContext): pass # Exit a parse tree produced by blackbirdParser#arrayvar. def exitArrayvar(self, ctx:blackbirdParser.ArrayvarContext): pass # Enter a parse tree produced by blackbirdParser#name. def enterName(self, ctx:blackbirdParser.NameContext): pass # Exit a parse tree produced by blackbirdParser#name. def exitName(self, ctx:blackbirdParser.NameContext): pass # Enter a parse tree produced by blackbirdParser#invalid. def enterInvalid(self, ctx:blackbirdParser.InvalidContext): pass # Exit a parse tree produced by blackbirdParser#invalid. def exitInvalid(self, ctx:blackbirdParser.InvalidContext): pass # Enter a parse tree produced by blackbirdParser#reserved. def enterReserved(self, ctx:blackbirdParser.ReservedContext): pass # Exit a parse tree produced by blackbirdParser#reserved. def exitReserved(self, ctx:blackbirdParser.ReservedContext): pass # Enter a parse tree produced by blackbirdParser#vartype. def enterVartype(self, ctx:blackbirdParser.VartypeContext): pass # Exit a parse tree produced by blackbirdParser#vartype. def exitVartype(self, ctx:blackbirdParser.VartypeContext): pass # Enter a parse tree produced by blackbirdParser#nonnumeric. def enterNonnumeric(self, ctx:blackbirdParser.NonnumericContext): pass # Exit a parse tree produced by blackbirdParser#nonnumeric. def exitNonnumeric(self, ctx:blackbirdParser.NonnumericContext): pass # Enter a parse tree produced by blackbirdParser#shape. def enterShape(self, ctx:blackbirdParser.ShapeContext): pass # Exit a parse tree produced by blackbirdParser#shape. def exitShape(self, ctx:blackbirdParser.ShapeContext): pass # Enter a parse tree produced by blackbirdParser#arrayval. def enterArrayval(self, ctx:blackbirdParser.ArrayvalContext): pass # Exit a parse tree produced by blackbirdParser#arrayval. def exitArrayval(self, ctx:blackbirdParser.ArrayvalContext): pass # Enter a parse tree produced by blackbirdParser#arrayrow. def enterArrayrow(self, ctx:blackbirdParser.ArrayrowContext): pass # Exit a parse tree produced by blackbirdParser#arrayrow. def exitArrayrow(self, ctx:blackbirdParser.ArrayrowContext): pass # Enter a parse tree produced by blackbirdParser#statement. def enterStatement(self, ctx:blackbirdParser.StatementContext): pass # Exit a parse tree produced by blackbirdParser#statement. def exitStatement(self, ctx:blackbirdParser.StatementContext): pass # Enter a parse tree produced by blackbirdParser#operation. def enterOperation(self, ctx:blackbirdParser.OperationContext): pass # Exit a parse tree produced by blackbirdParser#operation. def exitOperation(self, ctx:blackbirdParser.OperationContext): pass # Enter a parse tree produced by blackbirdParser#measure. def enterMeasure(self, ctx:blackbirdParser.MeasureContext): pass # Exit a parse tree produced by blackbirdParser#measure. def exitMeasure(self, ctx:blackbirdParser.MeasureContext): pass # Enter a parse tree produced by blackbirdParser#forloop. def enterForloop(self, ctx:blackbirdParser.ForloopContext): pass # Exit a parse tree produced by blackbirdParser#forloop. def exitForloop(self, ctx:blackbirdParser.ForloopContext): pass # Enter a parse tree produced by blackbirdParser#arguments. def enterArguments(self, ctx:blackbirdParser.ArgumentsContext): pass # Exit a parse tree produced by blackbirdParser#arguments. def exitArguments(self, ctx:blackbirdParser.ArgumentsContext): pass # Enter a parse tree produced by blackbirdParser#kwarg. def enterKwarg(self, ctx:blackbirdParser.KwargContext): pass # Exit a parse tree produced by blackbirdParser#kwarg. def exitKwarg(self, ctx:blackbirdParser.KwargContext): pass # Enter a parse tree produced by blackbirdParser#val. def enterVal(self, ctx:blackbirdParser.ValContext): pass # Exit a parse tree produced by blackbirdParser#val. def exitVal(self, ctx:blackbirdParser.ValContext): pass # Enter a parse tree produced by blackbirdParser#vallist. def enterVallist(self, ctx:blackbirdParser.VallistContext): pass # Exit a parse tree produced by blackbirdParser#vallist. def exitVallist(self, ctx:blackbirdParser.VallistContext): pass # Enter a parse tree produced by blackbirdParser#rangeval. def enterRangeval(self, ctx:blackbirdParser.RangevalContext): pass # Exit a parse tree produced by blackbirdParser#rangeval. def exitRangeval(self, ctx:blackbirdParser.RangevalContext): pass # Enter a parse tree produced by blackbirdParser#ParameterLabel. def enterParameterLabel(self, ctx:blackbirdParser.ParameterLabelContext): pass # Exit a parse tree produced by blackbirdParser#ParameterLabel. def exitParameterLabel(self, ctx:blackbirdParser.ParameterLabelContext): pass # Enter a parse tree produced by blackbirdParser#BracketsLabel. def enterBracketsLabel(self, ctx:blackbirdParser.BracketsLabelContext): pass # Exit a parse tree produced by blackbirdParser#BracketsLabel. def exitBracketsLabel(self, ctx:blackbirdParser.BracketsLabelContext): pass # Enter a parse tree produced by blackbirdParser#SignLabel. def enterSignLabel(self, ctx:blackbirdParser.SignLabelContext): pass # Exit a parse tree produced by blackbirdParser#SignLabel. def exitSignLabel(self, ctx:blackbirdParser.SignLabelContext): pass # Enter a parse tree produced by blackbirdParser#PowerLabel. def enterPowerLabel(self, ctx:blackbirdParser.PowerLabelContext): pass # Exit a parse tree produced by blackbirdParser#PowerLabel. def exitPowerLabel(self, ctx:blackbirdParser.PowerLabelContext): pass # Enter a parse tree produced by blackbirdParser#NumberLabel. def enterNumberLabel(self, ctx:blackbirdParser.NumberLabelContext): pass # Exit a parse tree produced by blackbirdParser#NumberLabel. def exitNumberLabel(self, ctx:blackbirdParser.NumberLabelContext): pass # Enter a parse tree produced by blackbirdParser#VariableLabel. def enterVariableLabel(self, ctx:blackbirdParser.VariableLabelContext): pass # Exit a parse tree produced by blackbirdParser#VariableLabel. def exitVariableLabel(self, ctx:blackbirdParser.VariableLabelContext): pass # Enter a parse tree produced by blackbirdParser#ArrayIdxLabel. def enterArrayIdxLabel(self, ctx:blackbirdParser.ArrayIdxLabelContext): pass # Exit a parse tree produced by blackbirdParser#ArrayIdxLabel. def exitArrayIdxLabel(self, ctx:blackbirdParser.ArrayIdxLabelContext): pass # Enter a parse tree produced by blackbirdParser#MulLabel. def enterMulLabel(self, ctx:blackbirdParser.MulLabelContext): pass # Exit a parse tree produced by blackbirdParser#MulLabel. def exitMulLabel(self, ctx:blackbirdParser.MulLabelContext): pass # Enter a parse tree produced by blackbirdParser#FunctionLabel. def enterFunctionLabel(self, ctx:blackbirdParser.FunctionLabelContext): pass # Exit a parse tree produced by blackbirdParser#FunctionLabel. def exitFunctionLabel(self, ctx:blackbirdParser.FunctionLabelContext): pass # Enter a parse tree produced by blackbirdParser#AddLabel. def enterAddLabel(self, ctx:blackbirdParser.AddLabelContext): pass # Exit a parse tree produced by blackbirdParser#AddLabel. def exitAddLabel(self, ctx:blackbirdParser.AddLabelContext): pass # Enter a parse tree produced by blackbirdParser#parameter. def enterParameter(self, ctx:blackbirdParser.ParameterContext): pass # Exit a parse tree produced by blackbirdParser#parameter. def exitParameter(self, ctx:blackbirdParser.ParameterContext): pass # Enter a parse tree produced by blackbirdParser#number. def enterNumber(self, ctx:blackbirdParser.NumberContext): pass # Exit a parse tree produced by blackbirdParser#number. def exitNumber(self, ctx:blackbirdParser.NumberContext): pass # Enter a parse tree produced by blackbirdParser#function. def enterFunction(self, ctx:blackbirdParser.FunctionContext): pass # Exit a parse tree produced by blackbirdParser#function. def exitFunction(self, ctx:blackbirdParser.FunctionContext): pass del blackbirdParser
#include "encrypt.h" #include "lora/lora.h" #include <math.h> //#define TIMER_KEY_GENERATION 500000 //interval between each symetric key generation (in ms) #define TIMER_MESURE 3000 //interval between each sample (in ms) //#define BUFF_SIZE_MAX 8 //240 //size max in bit of the buffer to send. in bytes daw ana tita sally //#define MSG_SIZE 24 //size of one message to put in the buffer //#define TEMP_SIZE 8 //#define PRESS_SIZE 8 #define ENCRYPT_DATA_SIZE 10 //Allow to generate the first symetric key before starting sampling int FIRST_KEY=0; //global variable shared between the different task uint8_t key[32]; uint8_t extern_pubkey[64]; uint8_t wraped_key[132]; extern uint8_t privkey[32]; /* * \brief Fullfill global variable wrapped_buffer with iv || tag || encrypted_buffer * * \param encrypted_buffer The encrypted buffer to wrap before sending it * iv Iv used for encryption * tag Tag computed by the encryption * wrapped_buffer The buffer to fullfill * wrap_size */ void wrap_buffer(uint8_t * encrypted_buffer, unsigned buffer_size,uint8_t * iv, uint8_t * tag,uint8_t * key,uint8_t * wrapped_buffer){ memcpy(wrapped_buffer,iv,IV_SIZE); printf("\n wrapped_buffer: iv :"); for(int i=0;i<IV_SIZE;i++){ printf("%x", wrapped_buffer[i]); } memcpy(wrapped_buffer+IV_SIZE,tag,TAG_SIZE); printf("\n wrapped_buffer: iv+tag :"); for(int i=0;i<IV_SIZE+TAG_SIZE;i++){ printf("%x", wrapped_buffer[i]); } memcpy(wrapped_buffer+IV_SIZE+TAG_SIZE,encrypted_buffer,buffer_size); printf("\n wrapped_buffer: iv+tag+msg:"); for(int i=0;i<ENCRYPT_DATA_SIZE+IV_SIZE+TAG_SIZE;i++){ printf("%x", wrapped_buffer[i]); } printf("\n"); memcpy(wrapped_buffer+IV_SIZE+TAG_SIZE+32, key,32); printf("\n wrapped_buffer: iv+tag+msg+key:"); for(int i=0;i<ENCRYPT_DATA_SIZE+IV_SIZE+TAG_SIZE+32;i++){ printf("%x", wrapped_buffer[i]); } printf("\n"); } /* * \brief Fullfill global variable key with a AESGCM symetric key * */ void symetric_generation(){ //generates public key uint8_t ephemeral_pubkey[PUB_KEY_SIZE]; int r=0; if((r=symetric_key_generation(key,extern_pubkey,ephemeral_pubkey))!=1){ printf("error during symetric generation: %d\n",r); } return; } /* * \brief Encrypt the global variable key with ECIES cipher before sending it to the receiver * Send a wrapped key of the form id_curve(3) || length(public_key) || ephemeral pubkey || tag || iv || ciphertext * * \param param Must be a pointer of the socket to send wrapped key * */ void ecc_key_task(void){ memset(key,0,32); memset(wraped_key,0,32+4+PUB_KEY_SIZE+TAG_SIZE+IV_SIZE); symetric_generation(); ECIES_encrypt_key(key,32,extern_pubkey,wraped_key); /* * Send the encrypted key thru LoRa */ printf("\nsending encrypted key\n"); bool res =lora_send(wraped_key); printf("\nsending encrypted key done!\n"); //send(*sock,wraped_key,32+4+PUB_KEY_SIZE+TAG_SIZE+IV_SIZE,0); FIRST_KEY=1; memset(wraped_key,0,32+4+PUB_KEY_SIZE+TAG_SIZE+IV_SIZE); vTaskDelay(1000/portTICK_RATE_MS); } uint8_t* encrypt(uint8_t* dat_encrypt){ //while(FIRST_KEY!=1){ //wait for the first symetric key to be computed and sent //} int i = 0; //uint8_t buffer[BUFF_SIZE_MAX]; uint8_t iv[IV_SIZE]; uint8_t tag[TAG_SIZE]; uint8_t encrypted_buffer[ENCRYPT_DATA_SIZE]; uint8_t decrypted_buffer[ENCRYPT_DATA_SIZE]; static uint8_t wraped_buffer[ENCRYPT_DATA_SIZE+IV_SIZE+TAG_SIZE]; uint8_t encrypt_ecies[ENCRYPT_DATA_SIZE+IV_SIZE+TAG_SIZE]; uint8_t decrypt_ecies[ENCRYPT_DATA_SIZE+IV_SIZE+TAG_SIZE]; uint8_t local_key[32]; random32(&key,32); memcpy(local_key,key,32); printf("\nencrypt\n"); printf("key: "); for(i=0;i<32;i++){ //print plain message printf("%x", local_key[i]); } printf("\n"); //memcpy(buffer, data_param, BUFF_SIZE_MAX); //<-- i need to clarify this AESGCM(dat_encrypt,ENCRYPT_DATA_SIZE,MBEDTLS_ENCRYPT,key,iv,tag,encrypted_buffer); printf("\nreceived message\n"); for(i=0;i<ENCRYPT_DATA_SIZE;i++){ //print plain message printf("%c", dat_encrypt[i]); } printf("\nencrypted message\n"); for(i=0;i<ENCRYPT_DATA_SIZE;i++){ printf("%x", (unsigned int)encrypted_buffer[i]); } wrap_buffer(encrypted_buffer,IV_SIZE+TAG_SIZE+ENCRYPT_DATA_SIZE,iv,key,tag,wraped_buffer); //send(*sock,wraped_buffer,BUFF_SIZE_MAX+IV_SIZE+TAG_SIZE,0); //ECIES_encrypt_key(wraped_buffer, ENCRYPT_DATA_SIZE+IV_SIZE+TAG_SIZE, extern_pubkey, encrypt_ecies); AESGCM(encrypted_buffer,ENCRYPT_DATA_SIZE,MBEDTLS_DECRYPT,key,iv,tag,decrypted_buffer); printf("\ndecrypted message\n"); for(i=0;i<ENCRYPT_DATA_SIZE;i++){ printf("%c", decrypted_buffer[i]); } //ECIES_decrypt_key(encrypt_ecies, ENCRYPT_DATA_SIZE+IV_SIZE+TAG_SIZE, extern_pubkey, privkey, decrypt_ecies); //memset(buffer,0,ENCRYPT_DATA_SIZE); memset(encrypted_buffer,0,ENCRYPT_DATA_SIZE); memset(decrypted_buffer,0, ENCRYPT_DATA_SIZE); memset(iv,0,IV_SIZE); memset(tag,0,TAG_SIZE); //memset(wraped_buffer,0,ENCRYPT_DATA_SIZE+IV_SIZE+TAG_SIZE); //vTaskDelay(TIMER_MESURE/portTICK_RATE_MS); /* * Return the encryted data in a wrapped buffer (42 bytes total) */ return(wraped_buffer); } uint8_t *data_encrypt(uint8_t *data) { // generate key and send ecc_key_task(); //encrypt data and send printf("\ndata encrypting-->\n"); uint8_t *encrypted = encrypt(data); printf("\n"); for(int i=0;i<IV_SIZE+TAG_SIZE+ENCRYPT_DATA_SIZE;i++){ printf("%x", (unsigned int)encrypted[i]); } printf("\ndata encrypting<--finished\n"); return(encrypted); }
import time import torch from NVLL.util.util import GVar from NVLL.util.gpu_flag import device print(device) # # start = time.time() # hard = torch.nn.Hardtanh() # softmax = torch.nn.Softmax() # for i in range(100): # x = torch.zeros(100000).cuda() # y = torch.rand(100000).cuda() # z = y * y * y # c = y * y / (y + y) # d = c * c + c # m = y + z + y # m = GVar(m) # # for j in range(1000): # k = hard(m) # e = softmax(m + m) # q = softmax(m) # # print(time.time() - start) import numpy as np def _sample_weight(kappa, dim): """Rejection sampling scheme for sampling distance from center on surface of the sphere. """ dim = dim - 1 # since S^{n-1} b = dim / (np.sqrt(4. * kappa ** 2 + dim ** 2) + 2 * kappa) # b= 1/(sqrt(4.* kdiv**2 + 1) + 2 * kdiv) x = (1. - b) / (1. + b) c = kappa * x + dim * np.log(1 - x ** 2) # dim * (kdiv *x + np.log(1-x**2)) cnt = 0 while True: cnt += 1 z = np.random.beta(dim / 2., dim / 2.) # concentrates towards 0.5 as d-> inf w = (1. - (1. + b) * z) / (1. - (1. - b) * z) u = np.random.uniform(low=0, high=1) if kappa * w + dim * np.log(1. - x * w) - c >= np.log( u): # thresh is dim *(kdiv * (w-x) + log(1-x*w) -log(1-x**2)) return w, cnt kappa = [32, 64, 128] # for k in kappa: # for d in kappa: # l = [] # for _ in range(1000): # _, cnt =_sample_weight(k,d) # l.append(cnt) # print("{}\t{}\t{}".format(k,d,sum(l)/len(l))) input = torch.FloatTensor() torch.multinomial(input, 1, replacement=False)
/* * Copyright (c) 2020 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-03-24 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ import chai, { expect } from 'chai' import mount from '@tests/unit/setup' import OverviewHeader from '@/pages/ServiceDetail/OverviewHeader' import { dummy_all_services, dummy_service_connection_datasets, dummy_service_connection_info, } from '@tests/unit/utils' import sinon from 'sinon' import sinonChai from 'sinon-chai' chai.should() chai.use(sinonChai) const defaultProps = { currentService: dummy_all_services[0], serviceConnectionsDatasets: dummy_service_connection_datasets, serviceConnectionInfo: dummy_service_connection_info, } const propsMountFactory = props => mount({ shallow: false, component: OverviewHeader, props: props, }) describe('ServiceDetail - OverviewHeader', () => { let wrapper, clock, updateChartSpy beforeEach(async () => { clock = sinon.useFakeTimers() updateChartSpy = sinon.spy(OverviewHeader.methods, 'updateChart') wrapper = mount({ shallow: false, component: OverviewHeader, props: defaultProps, }) }) afterEach(async function() { await clock.restore() await updateChartSpy.restore() // this prevent fetch loop in line-chart await wrapper.setData({ options: null, }) await wrapper.destroy() }) it(`Should emit update-chart event`, async () => { let count = 0 wrapper.vm.$on('update-chart', () => { count++ }) //mockup update chart await wrapper.vm.updateChart() expect(count).to.be.equals(1) }) it(`Should call updateChart after 10s`, async () => { await clock.tick(1000) expect(updateChartSpy).to.not.have.been.called await clock.tick(9000) expect(updateChartSpy).to.have.been.calledOnce }) describe('outlined-overview-card render assertions', () => { const { attributes: { router, started }, } = dummy_all_services[0] let outlineOverviewCards beforeEach(async () => { wrapper = propsMountFactory(defaultProps) outlineOverviewCards = wrapper.findAllComponents({ name: 'outlined-overview-card', }).wrappers }) afterEach(async function() { // this prevent fetch loop in line-chart await wrapper.setData({ options: null, }) await wrapper.destroy() }) it(`Should render 3 outlined-overview-card components`, async () => { expect(outlineOverviewCards.length).to.be.equals(3) }) it(`Should show 'Overview' title in the first outlined-overview-card`, async () => { const title = outlineOverviewCards[0].find('.detail-overview__title') expect(title.text()).to.be.equals('Overview') }) it(`Should show 'Overview' title in the first outlined-overview-card`, async () => { const title = outlineOverviewCards[0].find('.detail-overview__title') expect(title.text()).to.be.equals('Overview') }) it(`Should show router in the first outlined-overview-card`, async () => { const cardTitle = outlineOverviewCards[0].find('.caption') const cardBody = outlineOverviewCards[0].find('.router') expect(cardTitle.text()).to.be.equals('ROUTER') expect(cardBody.text()).to.be.equals(router) }) it(`Should show started time in the second outlined-overview-card`, async () => { const { dateFormat } = wrapper.vm.$help const cardTitle = outlineOverviewCards[1].find('.caption') const cardBody = outlineOverviewCards[1].find('.started') expect(cardTitle.text()).to.be.equals('STARTED AT') expect(cardBody.text()).to.be.equals(dateFormat({ value: started })) }) it(`Should not show tile in the last outlined-overview-card`, async () => { expect(outlineOverviewCards[2].vm.$props.tile).to.be.false }) it(`Should current connections as title in the last outlined-overview-card`, async () => { const title = outlineOverviewCards[2].find('.detail-overview__title') const { connections, total_connections } = dummy_service_connection_info expect(title.text()).to.be.equals( `Current Connections (${connections}/${total_connections})` ) }) it(`Should show connections chart in the last outlined-overview-card`, async () => { const lineChart = outlineOverviewCards[2].findComponent({ name: 'line-chart' }) expect(lineChart.exists()).to.be.true }) }) })
const v1 = require('./v1'); module.exports = { v1 };
# -*- coding: utf-8 -*- from lib import logger, linkedin_scraper, role_occurrence, o365_validation from time import sleep import json def run(data): cookie = data.cookie company_id = data.company_id email_format = data.email_format keyword = data.keyword domain = data.domain validation = data.validation api_key = data.api_key filename = data.filename valid_emails_only = data.valid_emails_only threads = int(data.threads) logger.debug(str(vars(data))) profiles = linkedin_scraper.company_profile(cookie,company_id,keyword) if profiles == None: logger.red('Unable to extract data from LinkedIn') quit() company_profile_json=json.loads(profiles) try: total_employees = company_profile_json['elements'][0]['total'] except: logger.red('Failed to extract users, try generalising the keywords') logger.red('If this problem persists, create a issue on GitHub!') quit() per_page=40 # Each response contains 40 profiles per page. pages = int(total_employees / per_page) # Divide the amount of users by 40, this will give you the amount of pages logger.debug('Per page: %s' % per_page) if total_employees < per_page: logger.debug('Setting per_page to 1') pages=1 logger.blue('Identified %s page(s)' % logger.BLUE(pages)) logger.blue('Identified %s result(s)' % logger.BLUE(total_employees)) if pages == 0: logger.red('Could not identify pages') quit() if total_employees > 1000: logger.red('This method of enumeration can only extract 1000 users') print() sleep(3) users=linkedin_scraper.get_users(data,pages,total_employees,keyword) print() if validation is not None: if o365_validation.verify_o365(domain)[domain]: logger.yellow('Running through email addresses...') users = linkedin_scraper.do_validation(users,threads,validation) print() job_role_count=role_occurrence.count(users,total_employees) if valid_emails_only: logger.valid_emails_only(users,filename) else: logger.dump(users,validation) logger.write_out(users,data,job_role_count,filename) return users
// config.js -- !!!!!!!!!!!!!!! USE ENV VARIABLE FOR secret AND db module.exports = { 'secret': '<Insert secret word for Jwt>', 'db': '<MongoDB url>' }
import _extends from"@babel/runtime/helpers/extends";import _objectWithoutProperties from"@babel/runtime/helpers/objectWithoutProperties";var _jsxFileName="/Users/satya/Workspace/Projects/navigation-ex/packages/native/src/NavigationContainer.tsx";import*as React from'react';import{BaseNavigationContainer}from'@react-navigation/core';import ThemeProvider from'./theming/ThemeProvider';import DefaultTheme from'./theming/DefaultTheme';import useBackButton from'./useBackButton';var NavigationContainer=React.forwardRef(function NavigationContainer(_ref,ref){var _ref$theme=_ref.theme,theme=_ref$theme===void 0?DefaultTheme:_ref$theme,rest=_objectWithoutProperties(_ref,["theme"]);var refContainer=React.useRef(null);useBackButton(refContainer);React.useImperativeHandle(ref,function(){return refContainer.current;});return React.createElement(ThemeProvider,{value:theme,__source:{fileName:_jsxFileName,lineNumber:38}},React.createElement(BaseNavigationContainer,_extends({},rest,{ref:refContainer,__source:{fileName:_jsxFileName,lineNumber:39}})));});export default NavigationContainer; //# sourceMappingURL=NavigationContainer.js.map
class Ninjakiwi: pass
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #pragma once #include "pch.h" #include "common.h" #include "AnimatedVisuals/ProgressRingIndeterminate.h" #include "AnimatedVisuals/ProgressRingDeterminate.h" #include "ProgressRingTemplateSettings.h" #include "ProgressRing.g.h" #include "ProgressRing.properties.h" class ProgressRing : public ReferenceTracker<ProgressRing, winrt::implementation::ProgressRingT>, public ProgressRingProperties { public: ProgressRing(); winrt::AutomationPeer OnCreateAutomationPeer(); void OnApplyTemplate(); void OnIsIndeterminatePropertyChanged(const winrt::DependencyPropertyChangedEventArgs& args); void OnIsActivePropertyChanged(const winrt::DependencyPropertyChangedEventArgs& args); void OnDeterminateSourcePropertyChanged(winrt::DependencyPropertyChangedEventArgs const& args); void OnIndeterminateSourcePropertyChanged(winrt::DependencyPropertyChangedEventArgs const& args); void OnForegroundPropertyChanged(const winrt::DependencyObject&, const winrt::DependencyProperty&); void OnForegroundColorPropertyChanged(const winrt::DependencyObject&, const winrt::DependencyProperty&); void OnBackgroundPropertyChanged(const winrt::DependencyObject&, const winrt::DependencyProperty&); void OnBackgroundColorPropertyChanged(const winrt::DependencyObject&, const winrt::DependencyProperty&); private: void SetAnimatedVisualPlayerSource(); void SetLottieForegroundColor(const winrt::IAnimatedVisualSource); void SetLottieBackgroundColor(const winrt::IAnimatedVisualSource); void OnRangeBasePropertyChanged(const winrt::DependencyObject&, const winrt::DependencyProperty&); void OnSizeChanged(const winrt::IInspectable&, const winrt::IInspectable&); void UpdateStates(); void ApplyTemplateSettings(); void UpdateLottieProgress(); tracker_ref<winrt::Grid> m_layoutRoot{ this }; tracker_ref<winrt::AnimatedVisualPlayer> m_player{ this }; double m_oldValue{ 0 }; };
import 'isomorphic-fetch'; import { callApi } from '../utils/api'; import config from '../config'; export const SELECT_USERS_PAGE = 'SELECT_USERS_PAGE'; export const USERS_QUERY = 'USERS_QUERY'; export const CLEAR_USERS = 'CLEAR_USERS'; export const INVALIDATE_USERS_PAGE = 'INVALIDATE_USERS_PAGE'; export const USERS_REQUEST = 'USERS_REQUEST'; export const USERS_SUCCESS = 'USERS_SUCCESS'; export const USERS_FAILURE = 'USERS_FAILURE'; export function selectUsersPage(page) { return { type: SELECT_USERS_PAGE, page, }; } export function setUsersQuery(query) { return { type: USERS_QUERY, query, }; } export function clearUsers() { return { type: CLEAR_USERS, }; } export function invalidateUsersPage(page) { return { type: INVALIDATE_USERS_PAGE, page, }; } function usersRequest(page) { return { type: USERS_REQUEST, page, }; } // This is a curried function that takes page as argument, // and expects payload as argument to be passed upon API call success. function usersSuccess(page) { return function (payload) { return { type: USERS_SUCCESS, page, users: payload.items, totalCount: payload.total_count, }; }; } // This is a curried function that takes page as argument, // and expects error as argument to be passed upon API call failure. function usersFailure(page) { return function (error) { return { type: USERS_FAILURE, page, error, }; }; } function fetchUsers(page, query) { let query_params='q='+(query||'followers:>0'); const url = `${config.api.root}/search/users?${query_params}&order=desc&page=${page}`; return callApi(url, null, usersRequest, usersSuccess(page), usersFailure(page)); } function shouldFetchUsers(state, page) { // Check cache first const users = state.usersByPage[page]; if (!users) { // Not cached, should fetch return true; } if (users.isFetching) { // Shouldn't fetch since fetching is running return false; } // Should fetch if cache was invalidate return users.didInvalidate; } export function fetchTopUsersIfNeeded(page, query) { return (dispatch, getState) => { if (shouldFetchUsers(getState(), page)) { return dispatch(fetchUsers(page, query)); } }; } export function fetchUsersForQuery(query) { return (dispatch, getState) => { return dispatch(fetchUsers(1,query)); }; }
const { promisify } = require('util'); const { isEmpty } = require('lodash'); const jwt = require('jsonwebtoken'); const { User } = require('../../resources/models'); const ErrorMessages = require('../../constants/errors'); const config = require('../../config'); module.exports = (ctx, next) => { const { authorization } = ctx.headers; const accessToken = authorization && authorization.split(' ')[1]; return jwt.verify(accessToken, config.jwtSecret, async (e, r = {}) => { let error = e; let payload = r; let generateJwt = false; if (error && error.name === 'TokenExpiredError') { error = null; payload = await promisify(jwt.verify)( accessToken, config.jwtSecret, { ignoreExpiration: true } ); generateJwt = true; } const { id = null, accessTokenSalt = null, refreshToken = null } = payload; const user = await User.findOne({ where: { id, accessTokenSalt, refreshToken } }); if (error || isEmpty(user)) { ctx.state.user = null; return ctx.unauthorized({ message: ErrorMessages.UNAUTHORIZED }); } if (generateJwt) { await user.updateRefreshToken(); await user.save(); ctx.set('auth', user.authenticate()); } ctx.state.user = user; return next(); }); };
const x = require('./xendit.test'); const { QrCode } = x; const q = new QrCode({}); module.exports = function() { return q .createCode({ externalID: Date.now().toString(), type: QrCode.Type.Dynamic, callbackURL: 'https://httpstat.us/200', amount: 10000, }) .then(r => q.getCode({ externalID: r.external_id })) .then(r => Promise.all([r.external_id, q.simulate({ externalID: r.external_id })]), ) .then(([externalId, r]) => Promise.all([ externalId, q.getPayments({ externalID: externalId, from: r.created_at, to: new Date().toISOString(), limit: 10, }), ]), ) .then(() => { // eslint-disable-next-line no-console console.log('QR Code integration test done...'); }) .catch(e => { throw new Error( `QR Code integration tests failed with error: ${e.message}`, ); }); };
"""A Python module for interacting with Slack's Web API.""" import copy import hashlib import hmac import io import json import logging import mimetypes import urllib import uuid import warnings from base64 import b64encode from http.client import HTTPResponse from ssl import SSLContext from typing import BinaryIO, Dict, List from typing import Optional, Union from urllib.error import HTTPError from urllib.parse import urlencode from urllib.request import Request, urlopen, OpenerDirector, ProxyHandler, HTTPSHandler import slack_sdk.errors as err from slack_sdk.errors import SlackRequestError from .deprecation import show_2020_01_deprecation from .internal_utils import ( convert_bool_to_0_or_1, get_user_agent, _get_url, _build_req_args, _build_unexpected_body_error_message, ) from .slack_response import SlackResponse from slack_sdk.http_retry import default_retry_handlers from slack_sdk.http_retry.handler import RetryHandler from slack_sdk.http_retry.request import HttpRequest as RetryHttpRequest from slack_sdk.http_retry.response import HttpResponse as RetryHttpResponse from slack_sdk.http_retry.state import RetryState from slack_sdk.proxy_env_variable_loader import load_http_proxy_from_env class BaseClient: BASE_URL = "https://www.slack.com/api/" def __init__( self, token: Optional[str] = None, base_url: str = BASE_URL, timeout: int = 30, ssl: Optional[SSLContext] = None, proxy: Optional[str] = None, headers: Optional[dict] = None, user_agent_prefix: Optional[str] = None, user_agent_suffix: Optional[str] = None, # for Org-Wide App installation team_id: Optional[str] = None, logger: Optional[logging.Logger] = None, retry_handlers: Optional[List[RetryHandler]] = None, ): self.token = None if token is None else token.strip() self.base_url = base_url self.timeout = timeout self.ssl = ssl self.proxy = proxy self.headers = headers or {} self.headers["User-Agent"] = get_user_agent( user_agent_prefix, user_agent_suffix ) self.default_params = {} if team_id is not None: self.default_params["team_id"] = team_id self._logger = logger if logger is not None else logging.getLogger(__name__) self.retry_handlers = ( retry_handlers if retry_handlers is not None else default_retry_handlers() ) if self.proxy is None or len(self.proxy.strip()) == 0: env_variable = load_http_proxy_from_env(self._logger) if env_variable is not None: self.proxy = env_variable def api_call( # skipcq: PYL-R1710 self, api_method: str, *, http_verb: str = "POST", files: dict = None, data: Union[dict] = None, params: dict = None, json: dict = None, # skipcq: PYL-W0621 headers: dict = None, auth: dict = None, ) -> SlackResponse: """Create a request and execute the API call to Slack. Args: api_method (str): The target Slack API method. e.g. 'chat.postMessage' http_verb (str): HTTP Verb. e.g. 'POST' files (dict): Files to multipart upload. e.g. {image OR file: file_object OR file_path} data: The body to attach to the request. If a dictionary is provided, form-encoding will take place. e.g. {'key1': 'value1', 'key2': 'value2'} params (dict): The URL parameters to append to the URL. e.g. {'key1': 'value1', 'key2': 'value2'} json (dict): JSON for the body to attach to the request (if files or data is not specified). e.g. {'key1': 'value1', 'key2': 'value2'} headers (dict): Additional request headers auth (dict): A dictionary that consists of client_id and client_secret Returns: (SlackResponse) The server's response to an HTTP request. Data from the response can be accessed like a dict. If the response included 'next_cursor' it can be iterated on to execute subsequent requests. Raises: SlackApiError: The following Slack API call failed: 'chat.postMessage'. SlackRequestError: Json data can only be submitted as POST requests. """ api_url = _get_url(self.base_url, api_method) headers = headers or {} headers.update(self.headers) req_args = _build_req_args( token=self.token, http_verb=http_verb, files=files, data=data, default_params=self.default_params, params=params, json=json, # skipcq: PYL-W0621 headers=headers, auth=auth, ssl=self.ssl, proxy=self.proxy, ) show_2020_01_deprecation(api_method) return self._sync_send(api_url=api_url, req_args=req_args) # ================================================================= # urllib based WebClient # ================================================================= def _sync_send(self, api_url, req_args) -> SlackResponse: params = req_args["params"] if "params" in req_args else None data = req_args["data"] if "data" in req_args else None files = req_args["files"] if "files" in req_args else None _json = req_args["json"] if "json" in req_args else None headers = req_args["headers"] if "headers" in req_args else None token = params.get("token") if params and "token" in params else None auth = ( req_args["auth"] if "auth" in req_args else None ) # Basic Auth for oauth.v2.access / oauth.access if auth is not None: if isinstance(auth, str): headers["Authorization"] = auth elif isinstance(auth, dict): client_id, client_secret = auth["client_id"], auth["client_secret"] value = b64encode( f"{client_id}:{client_secret}".encode("utf-8") ).decode("ascii") headers["Authorization"] = f"Basic {value}" else: self._logger.warning( f"As the auth: {auth}: {type(auth)} is unsupported, skipped" ) body_params = {} if params: body_params.update(params) if data: body_params.update(data) return self._urllib_api_call( token=token, url=api_url, query_params={}, body_params=body_params, files=files, json_body=_json, additional_headers=headers, ) def _request_for_pagination(self, api_url, req_args) -> Dict[str, any]: """This method is supposed to be used only for SlackResponse pagination You can paginate using Python's for iterator as below: for response in client.conversations_list(limit=100): # do something with each response here """ response = self._perform_urllib_http_request(url=api_url, args=req_args) return { "status_code": int(response["status"]), "headers": dict(response["headers"]), "data": json.loads(response["body"]), } def _urllib_api_call( self, *, token: str = None, url: str, query_params: Dict[str, str] = {}, json_body: Dict = {}, body_params: Dict[str, str] = {}, files: Dict[str, io.BytesIO] = {}, additional_headers: Dict[str, str] = {}, ) -> SlackResponse: """Performs a Slack API request and returns the result. Args: token: Slack API Token (either bot token or user token) url: Complete URL (e.g., https://www.slack.com/api/chat.postMessage) query_params: Query string json_body: JSON data structure (it's still a dict at this point), if you give this argument, body_params and files will be skipped body_params: Form body params files: Files to upload additional_headers: Request headers to append Returns: API response """ files_to_close: List[BinaryIO] = [] try: # True/False -> "1"/"0" query_params = convert_bool_to_0_or_1(query_params) body_params = convert_bool_to_0_or_1(body_params) if self._logger.level <= logging.DEBUG: def convert_params(values: dict) -> dict: if not values or not isinstance(values, dict): return {} return { k: ("(bytes)" if isinstance(v, bytes) else v) for k, v in values.items() } headers = { k: "(redacted)" if k.lower() == "authorization" else v for k, v in additional_headers.items() } self._logger.debug( f"Sending a request - url: {url}, " f"query_params: {convert_params(query_params)}, " f"body_params: {convert_params(body_params)}, " f"files: {convert_params(files)}, " f"json_body: {json_body}, " f"headers: {headers}" ) request_data = {} if files is not None and isinstance(files, dict) and len(files) > 0: if body_params: for k, v in body_params.items(): request_data.update({k: v}) for k, v in files.items(): if isinstance(v, str): f: BinaryIO = open(v.encode("utf-8", "ignore"), "rb") files_to_close.append(f) request_data.update({k: f}) elif isinstance(v, (bytearray, bytes)): request_data.update({k: io.BytesIO(v)}) else: request_data.update({k: v}) request_headers = self._build_urllib_request_headers( token=token or self.token, has_json=json is not None, has_files=files is not None, additional_headers=additional_headers, ) request_args = { "headers": request_headers, "data": request_data, "params": body_params, "files": files, "json": json_body, } if query_params: q = urlencode(query_params) url = f"{url}&{q}" if "?" in url else f"{url}?{q}" response = self._perform_urllib_http_request(url=url, args=request_args) response_body = response.get("body", None) # skipcq: PTC-W0039 response_body_data: Optional[Union[dict, bytes]] = response_body if response_body is not None and not isinstance(response_body, bytes): try: response_body_data = json.loads(response["body"]) except json.decoder.JSONDecodeError: message = _build_unexpected_body_error_message( response.get("body", "") ) raise err.SlackApiError(message, response) if query_params: all_params = copy.copy(body_params) all_params.update(query_params) else: all_params = body_params request_args["params"] = all_params # for backward-compatibility return SlackResponse( client=self, http_verb="POST", # you can use POST method for all the Web APIs api_url=url, req_args=request_args, data=response_body_data, headers=dict(response["headers"]), status_code=response["status"], ).validate() finally: for f in files_to_close: if not f.closed: f.close() def _perform_urllib_http_request( self, *, url: str, args: Dict[str, Dict[str, any]] ) -> Dict[str, any]: """Performs an HTTP request and parses the response. Args: url: Complete URL (e.g., https://www.slack.com/api/chat.postMessage) args: args has "headers", "data", "params", and "json" "headers": Dict[str, str] "data": Dict[str, any] "params": Dict[str, str], "json": Dict[str, any], Returns: dict {status: int, headers: Headers, body: str} """ headers = args["headers"] if args["json"]: body = json.dumps(args["json"]) headers["Content-Type"] = "application/json;charset=utf-8" elif args["data"]: boundary = f"--------------{uuid.uuid4()}" sep_boundary = b"\r\n--" + boundary.encode("ascii") end_boundary = sep_boundary + b"--\r\n" body = io.BytesIO() data = args["data"] for key, value in data.items(): readable = getattr(value, "readable", None) if readable and value.readable(): filename = "Uploaded file" name_attr = getattr(value, "name", None) if name_attr: filename = ( name_attr.decode("utf-8") if isinstance(name_attr, bytes) else name_attr ) if "filename" in data: filename = data["filename"] mimetype = ( mimetypes.guess_type(filename)[0] or "application/octet-stream" ) title = ( f'\r\nContent-Disposition: form-data; name="{key}"; filename="{filename}"\r\n' + f"Content-Type: {mimetype}\r\n" ) value = value.read() else: title = f'\r\nContent-Disposition: form-data; name="{key}"\r\n' value = str(value).encode("utf-8") body.write(sep_boundary) body.write(title.encode("utf-8")) body.write(b"\r\n") body.write(value) body.write(end_boundary) body = body.getvalue() headers["Content-Type"] = f"multipart/form-data; boundary={boundary}" headers["Content-Length"] = len(body) elif args["params"]: body = urlencode(args["params"]) headers["Content-Type"] = "application/x-www-form-urlencoded" else: body = None if isinstance(body, str): body = body.encode("utf-8") # NOTE: Intentionally ignore the `http_verb` here # Slack APIs accepts any API method requests with POST methods req = Request(method="POST", url=url, data=body, headers=headers) resp = None last_error = None retry_state = RetryState() counter_for_safety = 0 while counter_for_safety < 100: counter_for_safety += 1 # If this is a retry, the next try started here. We can reset the flag. retry_state.next_attempt_requested = False try: resp = self._perform_urllib_http_request_internal(url, req) # The resp is a 200 OK response return resp except HTTPError as e: resp = {"status": e.code, "headers": e.headers} if e.code == 429: # for compatibility with aiohttp resp["headers"]["Retry-After"] = resp["headers"]["retry-after"] # read the response body here charset = e.headers.get_content_charset() or "utf-8" response_body: str = e.read().decode(charset) resp["body"] = response_body # Try to find a retry handler for this error retry_request = RetryHttpRequest.from_urllib_http_request(req) retry_response = RetryHttpResponse( status_code=e.code, headers={k: [v] for k, v in e.headers.items()}, data=response_body.encode("utf-8") if response_body is not None else None, ) for handler in self.retry_handlers: if handler.can_retry( state=retry_state, request=retry_request, response=retry_response, error=e, ): if self._logger.level <= logging.DEBUG: self._logger.info( f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {e}" ) handler.prepare_for_next_attempt( state=retry_state, request=retry_request, response=retry_response, error=e, ) break if retry_state.next_attempt_requested is False: return resp except Exception as err: last_error = err self._logger.error( f"Failed to send a request to Slack API server: {err}" ) # Try to find a retry handler for this error retry_request = RetryHttpRequest.from_urllib_http_request(req) for handler in self.retry_handlers: if handler.can_retry( state=retry_state, request=retry_request, response=None, error=err, ): if self._logger.level <= logging.DEBUG: self._logger.info( f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {err}" ) handler.prepare_for_next_attempt( state=retry_state, request=retry_request, response=None, error=err, ) self._logger.info( f"Going to retry the same request: {req.method} {req.full_url}" ) break if retry_state.next_attempt_requested is False: raise err if resp is not None: return resp raise last_error def _perform_urllib_http_request_internal( self, url: str, req: Request, ) -> Dict[str, any]: # urllib not only opens http:// or https:// URLs, but also ftp:// and file://. # With this it might be possible to open local files on the executing machine # which might be a security risk if the URL to open can be manipulated by an external user. # (BAN-B310) if url.lower().startswith("http"): opener: Optional[OpenerDirector] = None if self.proxy is not None: if isinstance(self.proxy, str): opener = urllib.request.build_opener( ProxyHandler({"http": self.proxy, "https": self.proxy}), HTTPSHandler(context=self.ssl), ) else: raise SlackRequestError( f"Invalid proxy detected: {self.proxy} must be a str value" ) # NOTE: BAN-B310 is already checked above resp: Optional[HTTPResponse] = None if opener: resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310 else: resp = urlopen( # skipcq: BAN-B310 req, context=self.ssl, timeout=self.timeout ) if resp.headers.get_content_type() == "application/gzip": # admin.analytics.getFile body: bytes = resp.read() if self._logger.level <= logging.DEBUG: self._logger.debug( "Received the following response - " f"status: {resp.code}, " f"headers: {dict(resp.headers)}, " f"body: (binary)" ) return {"status": resp.code, "headers": resp.headers, "body": body} charset = resp.headers.get_content_charset() or "utf-8" body: str = resp.read().decode(charset) # read the response body here if self._logger.level <= logging.DEBUG: self._logger.debug( "Received the following response - " f"status: {resp.code}, " f"headers: {dict(resp.headers)}, " f"body: {body}" ) return {"status": resp.code, "headers": resp.headers, "body": body} raise SlackRequestError(f"Invalid URL detected: {url}") def _build_urllib_request_headers( self, token: str, has_json: bool, has_files: bool, additional_headers: dict ) -> Dict[str, str]: headers = {"Content-Type": "application/x-www-form-urlencoded"} headers.update(self.headers) if token: headers.update({"Authorization": "Bearer {}".format(token)}) if additional_headers: headers.update(additional_headers) if has_json: headers.update({"Content-Type": "application/json;charset=utf-8"}) if has_files: # will be set afterwards headers.pop("Content-Type", None) return headers # ================================================================= @staticmethod def validate_slack_signature( *, signing_secret: str, data: str, timestamp: str, signature: str ) -> bool: """ Slack creates a unique string for your app and shares it with you. Verify requests from Slack with confidence by verifying signatures using your signing secret. On each HTTP request that Slack sends, we add an X-Slack-Signature HTTP header. The signature is created by combining the signing secret with the body of the request we're sending using a standard HMAC-SHA256 keyed hash. https://api.slack.com/docs/verifying-requests-from-slack#how_to_make_a_request_signature_in_4_easy_steps__an_overview Args: signing_secret: Your application's signing secret, available in the Slack API dashboard data: The raw body of the incoming request - no headers, just the body. timestamp: from the 'X-Slack-Request-Timestamp' header signature: from the 'X-Slack-Signature' header - the calculated signature should match this. Returns: True if signatures matches """ warnings.warn( "As this method is deprecated since slackclient 2.6.0, " "use `from slack.signature import SignatureVerifier` instead", DeprecationWarning, ) format_req = str.encode(f"v0:{timestamp}:{data}") encoded_secret = str.encode(signing_secret) request_hash = hmac.new(encoded_secret, format_req, hashlib.sha256).hexdigest() calculated_signature = f"v0={request_hash}" return hmac.compare_digest(calculated_signature, signature)
#define REPT_IRPC__C /* .REPT .IRPC streams */ #include <stdlib.h> #include <string.h> #include "rept_irpc.h" /* my own definitions */ #include "util.h" #include "assemble_aux.h" #include "parse.h" #include "listing.h" #include "macros.h" #include "assemble_globals.h" /* *** implement REPT_STREAM */ typedef struct rept_stream { BUFFER_STREAM bstr; int count; /* The current repeat countdown */ int savecond; /* conditional stack level at time of expansion */ } REPT_STREAM; /* rept_stream_gets gets a line from a repeat stream. At the end of each count, the coutdown is decreated and the stream is reset to its beginning. */ char *rept_stream_gets( STREAM *str) { REPT_STREAM *rstr = (REPT_STREAM *) str; char *cp; for (;;) { if (rstr->count <= 0) return NULL; if ((cp = buffer_stream_gets(str)) != NULL) return cp; buffer_stream_rewind(str); rstr->count--; } } /* rept_stream_delete unwinds nested conditionals like .MEXIT does. */ void rept_stream_delete( STREAM *str) { REPT_STREAM *rstr = (REPT_STREAM *) str; pop_cond(rstr->savecond); /* complete unterminated conditionals */ buffer_stream_delete(&rstr->bstr.stream); } /* The VTBL */ STREAM_VTBL rept_stream_vtbl = { rept_stream_delete, rept_stream_gets, buffer_stream_rewind }; /* expand_rept is called when a .REPT is encountered in the input. */ STREAM *expand_rept( STACK *stack, char *cp) { EX_TREE *value; BUFFER *gb; REPT_STREAM *rstr; int levelmod; value = parse_expr(cp, 0); if (value->type != EX_LIT) { report(stack->top, ".REPT value must be constant\n"); free_tree(value); return NULL; } /* * Reading the next lines-to-be-repeated overwrites the line buffer * that the caller is using. So for junk-at-end-of-line checking we * need to do it here. */ check_eol(stack, value->cp); list_value(stack->top, value->data.lit); gb = new_buffer(); levelmod = 0; if (!list_md) { list_level--; levelmod = 1; } read_body(stack, gb, NULL, FALSE); list_level += levelmod; rstr = memcheck(malloc(sizeof(REPT_STREAM))); { char *name = memcheck(malloc(strlen(stack->top->name) + 32)); sprintf(name, "%s:%d->.REPT", stack->top->name, stack->top->line); buffer_stream_construct(&rstr->bstr, gb, name); free(name); } rstr->count = value->data.lit; rstr->bstr.stream.vtbl = &rept_stream_vtbl; rstr->savecond = last_cond; buffer_free(gb); free_tree(value); return &rstr->bstr.stream; } /* *** implement IRP_STREAM */ typedef struct irp_stream { BUFFER_STREAM bstr; char *label; /* The substitution label */ char *items; /* The substitution items (in source code format) */ int offset; /* Current offset into "items" */ BUFFER *body; /* Original body */ int savecond; /* Saved conditional level */ } IRP_STREAM; /* irp_stream_gets expands the IRP as the stream is read. */ /* Each time an iteration is exhausted, the next iteration is generated. */ char *irp_stream_gets( STREAM *str) { IRP_STREAM *istr = (IRP_STREAM *) str; char *cp; BUFFER *buf; ARG *arg; for (;;) { if ((cp = buffer_stream_gets(str)) != NULL) return cp; cp = istr->items + istr->offset; if (!*cp) return NULL; /* No more items. EOF. */ arg = new_arg(); arg->next = NULL; arg->locsym = 0; arg->label = istr->label; arg->value = getstring_macarg(str, cp, &cp); cp = skipdelim(cp); istr->offset = (int) (cp - istr->items); buf = subst_args(istr->body, arg); free(arg->value); free(arg); buffer_stream_set_buffer(&istr->bstr, buf); buffer_free(buf); } } /* irp_stream_delete - also pops the conditional stack */ void irp_stream_delete( STREAM *str) { IRP_STREAM *istr = (IRP_STREAM *) str; pop_cond(istr->savecond); /* complete unterminated conditionals */ buffer_free(istr->body); free(istr->items); free(istr->label); buffer_stream_delete(str); } STREAM_VTBL irp_stream_vtbl = { irp_stream_delete, irp_stream_gets, buffer_stream_rewind }; /* expand_irp is called when a .IRP is encountered in the input. */ STREAM *expand_irp( STACK *stack, char *cp) { char *label, *items; BUFFER *gb; int levelmod = 0; IRP_STREAM *str; label = get_symbol(cp, &cp, NULL); if (!label) { report(stack->top, "Illegal .IRP syntax\n"); return NULL; } cp = skipdelim(cp); items = getstring(cp, &cp); if (!items) { report(stack->top, "Illegal .IRP syntax\n"); free(label); return NULL; } check_eol(stack, cp); gb = new_buffer(); levelmod = 0; if (!list_md) { list_level--; levelmod++; } read_body(stack, gb, NULL, FALSE); list_level += levelmod; str = memcheck(malloc(sizeof(IRP_STREAM))); { char *name = memcheck(malloc(strlen(stack->top->name) + 32)); sprintf(name, "%s:%d->.IRP", stack->top->name, stack->top->line); buffer_stream_construct(&str->bstr, NULL, name); free(name); } str->bstr.stream.vtbl = &irp_stream_vtbl; str->body = gb; str->items = items; str->offset = 0; str->label = label; str->savecond = last_cond; return &str->bstr.stream; } /* *** implement IRPC_STREAM */ typedef struct irpc_stream { BUFFER_STREAM bstr; char *label; /* The substitution label */ char *items; /* The substitution items (in source code format) */ int offset; /* Current offset in "items" */ BUFFER *body; /* Original body */ int savecond; /* conditional stack at invocation */ } IRPC_STREAM; /* irpc_stream_gets - same comments apply as with irp_stream_gets, but the substitution is character-by-character */ char *irpc_stream_gets( STREAM *str) { IRPC_STREAM *istr = (IRPC_STREAM *) str; char *cp; BUFFER *buf; ARG *arg; for (;;) { if ((cp = buffer_stream_gets(str)) != NULL) return cp; cp = istr->items + istr->offset; if (!*cp) return NULL; /* No more items. EOF. */ arg = new_arg(); arg->next = NULL; arg->locsym = 0; arg->label = istr->label; arg->value = memcheck(malloc(2)); arg->value[0] = *cp++; arg->value[1] = 0; istr->offset = (int) (cp - istr->items); buf = subst_args(istr->body, arg); free(arg->value); free(arg); buffer_stream_set_buffer(&istr->bstr, buf); buffer_free(buf); } } /* irpc_stream_delete - also pops contidionals */ void irpc_stream_delete( STREAM *str) { IRPC_STREAM *istr = (IRPC_STREAM *) str; pop_cond(istr->savecond); /* complete unterminated conditionals */ buffer_free(istr->body); free(istr->items); free(istr->label); buffer_stream_delete(str); } STREAM_VTBL irpc_stream_vtbl = { irpc_stream_delete, irpc_stream_gets, buffer_stream_rewind }; /* expand_irpc - called when .IRPC is encountered in the input */ STREAM *expand_irpc( STACK *stack, char *cp) { char *label, *items; BUFFER *gb; int levelmod = 0; IRPC_STREAM *str; label = get_symbol(cp, &cp, NULL); if (!label) { report(stack->top, "Illegal .IRPC syntax\n"); return NULL; } cp = skipdelim(cp); items = getstring(cp, &cp); if (!items) { report(stack->top, "Illegal .IRPC syntax\n"); free(label); return NULL; } check_eol(stack, cp); gb = new_buffer(); levelmod = 0; if (!list_md) { list_level--; levelmod++; } read_body(stack, gb, NULL, FALSE); list_level += levelmod; str = memcheck(malloc(sizeof(IRPC_STREAM))); { char *name = memcheck(malloc(strlen(stack->top->name) + 32)); sprintf(name, "%s:%d->.IRPC", stack->top->name, stack->top->line); buffer_stream_construct(&str->bstr, NULL, name); free(name); } str->bstr.stream.vtbl = &irpc_stream_vtbl; str->body = gb; str->items = items; str->offset = 0; str->label = label; str->savecond = last_cond; return &str->bstr.stream; }
# The basic djangorecipebook tests were taken from djangorecipe, # (c) Roland van Laar, BSD license, [https://github.com/rvanlaar/djangorecipe] # and were simply adapted to the needs of djangorecipebook import sys import os import shutil import tempfile import unittest try: from unittest import mock except ImportError: # python2 import mock from zc.buildout.testing import TestOptions, Buildout __test__ = False test_project = 'project' test_settings = 'settings' is_win32 = sys.platform == 'win32' class ScriptTests(unittest.TestCase): def setUp(self): # fake the settings file's module self.settings = mock.sentinel.Settings sys.modules[test_settings] = self.settings def tearDown(self): # We will clear out sys.modules again to clean up del sys.modules[test_settings] class RecipeTests(unittest.TestCase): recipe_class = None recipe_name = '' recipe_options = {} def setUp(self): # Create a directory for our buildout files created by the recipe self.buildout_dir = tempfile.mkdtemp('djangorecipebook') self.bin_dir = os.path.join(self.buildout_dir, 'bin') self.develop_eggs_dir = os.path.join(self.buildout_dir, 'develop-eggs') self.eggs_dir = os.path.join(self.buildout_dir, 'eggs') self.parts_dir = os.path.join(self.buildout_dir, 'parts') # We need to create the bin and eggs dir since the recipe expects # them to exist os.mkdir(self.bin_dir) os.mkdir(self.eggs_dir) self.init_recipe() def init_recipe(self, options={}, name=None): buildout_opts = {'buildout': { 'eggs-directory': self.eggs_dir, 'develop-eggs-directory': self.develop_eggs_dir, 'bin-directory': self.bin_dir, 'parts-directory': self.parts_dir, 'directory': self.buildout_dir, 'allow-hosts': '', # don't visit any URL 'find-links': '', 'python': 'buildout', 'executable': sys.executable, }} name = name or self.recipe_name options_obj = TestOptions(buildout_opts, name, dict(self.recipe_options, **options)) buildout_obj = Buildout() buildout_obj['buildout'].update(buildout_opts['buildout']) self.recipe = self.recipe_class(buildout_obj, name, options_obj) def tearDown(self): # Remove our test dir shutil.rmtree(self.buildout_dir) def script_path(self, *names): """ Gets the path to a script, adding the -script.py suffix if necessary """ path = os.path.join(self.bin_dir, *names) if is_win32 and not os.path.exists(path): path_win = path + '-script.py' if os.path.exists(path_win): path = path_win return path def script_cat(self, *names): """ Reads a script file, adding the -script.py suffix if necessary """ path = self.script_path(self.bin_dir, *names) return open(path).read().replace('\\\\', '\\')
import React from 'react'; import { Icon } from './Icon'; export var SharpViewWeek = /*#__PURE__*/ function SharpViewWeek(props) { return React.createElement(Icon, props, React.createElement("path", { d: "M7 5H2v14h5zm14 0h-5v14h5zm-7 0H9v14h5z" })); };
CKEDITOR.plugins.setLang("language","gl",{button:"Estabelezer o idioma",remove:"Retirar o idioma"});
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = [ 'ListWebAppMetadataSlotResult', 'AwaitableListWebAppMetadataSlotResult', 'list_web_app_metadata_slot', ] @pulumi.output_type class ListWebAppMetadataSlotResult: """ String dictionary resource. """ def __init__(__self__, id=None, kind=None, name=None, properties=None, type=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if kind and not isinstance(kind, str): raise TypeError("Expected argument 'kind' to be a str") pulumi.set(__self__, "kind", kind) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if properties and not isinstance(properties, dict): raise TypeError("Expected argument 'properties' to be a dict") pulumi.set(__self__, "properties", properties) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) @property @pulumi.getter def id(self) -> str: """ Resource Id. """ return pulumi.get(self, "id") @property @pulumi.getter def kind(self) -> Optional[str]: """ Kind of resource. """ return pulumi.get(self, "kind") @property @pulumi.getter def name(self) -> str: """ Resource Name. """ return pulumi.get(self, "name") @property @pulumi.getter def properties(self) -> Mapping[str, str]: """ Settings. """ return pulumi.get(self, "properties") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") class AwaitableListWebAppMetadataSlotResult(ListWebAppMetadataSlotResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return ListWebAppMetadataSlotResult( id=self.id, kind=self.kind, name=self.name, properties=self.properties, type=self.type) def list_web_app_metadata_slot(name: Optional[str] = None, resource_group_name: Optional[str] = None, slot: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListWebAppMetadataSlotResult: """ String dictionary resource. :param str name: Name of the app. :param str resource_group_name: Name of the resource group to which the resource belongs. :param str slot: Name of the deployment slot. If a slot is not specified, the API will get the metadata for the production slot. """ __args__ = dict() __args__['name'] = name __args__['resourceGroupName'] = resource_group_name __args__['slot'] = slot if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:web/v20190801:listWebAppMetadataSlot', __args__, opts=opts, typ=ListWebAppMetadataSlotResult).value return AwaitableListWebAppMetadataSlotResult( id=__ret__.id, kind=__ret__.kind, name=__ret__.name, properties=__ret__.properties, type=__ret__.type)
define(["utils/utils","mvc/ui/ui-misc"],function(a){return Backbone.View.extend({colors:{standard:["c00000","ff0000","ffc000","ffff00","92d050","00b050","00b0f0","0070c0","002060","7030a0"],base:["ffffff","000000","eeece1","1f497d","4f81bd","c0504d","9bbb59","8064a2","4bacc6","f79646"],theme:[["f2f2f2","7f7f7f","ddd9c3","c6d9f0","dbe5f1","f2dcdb","ebf1dd","e5e0ec","dbeef3","fdeada"],["d8d8d8","595959","c4bd97","8db3e2","b8cce4","e5b9b7","d7e3bc","ccc1d9","b7dde8","fbd5b5"],["bfbfbf","3f3f3f","938953","548dd4","95b3d7","d99694","c3d69b","b2a2c7","92cddc","fac08f"],["a5a5a5","262626","494429","17365d","366092","953734","76923c","5f497a","31859b","e36c09"],["7f7f7e","0c0c0c","1d1b10","0f243e","244061","632423","4f6128","3f3151","205867","974806"]]},optionsDefault:{},initialize:function(b){this.options=a.merge(b,this.optionsDefault),this.setElement(this._template()),this.$panel=this.$(".ui-color-picker-panel"),this.$view=this.$(".ui-color-picker-view"),this.$value=this.$(".ui-color-picker-value"),this.$header=this.$(".ui-color-picker-header"),this._build(),this.visible=!1,this.value(this.options.value),this.$boxes=this.$(".ui-color-picker-box");var c=this;this.$boxes.on("click",function(){c.value($(this).css("background-color")),c.$header.trigger("click")}),this.$header.on("click",function(){c.visible=!c.visible,c.visible?c.$view.fadeIn("fast"):c.$view.fadeOut("fast")})},value:function(a){return void 0!==a&&null!==a&&(this.$value.css("background-color",a),this.$(".ui-color-picker-box").empty(),this.$(this._getValue()).html(this._templateCheck()),this.options.onchange&&this.options.onchange(a)),this._getValue()},_getValue:function(){function a(a){return("0"+parseInt(a).toString(16)).slice(-2)}var b=this.$value.css("background-color");return b=b.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/),b?"#"+a(b[1])+a(b[2])+a(b[3]):null},_build:function(){this._content({label:"Theme Colors",colors:this.colors.base,padding:10});for(var a in this.colors.theme){var b={};0==a?b.bottom=!0:a!=this.colors.theme.length-1?(b.top=!0,b.bottom=!0):(b.top=!0,b.padding=5),b.colors=this.colors.theme[a],this._content(b)}this._content({label:"Standard Colors",colors:this.colors.standard,padding:5})},_content:function(a){var b=(a.label,a.colors),c=a.padding,d=a.top,e=a.bottom,f=$(this._templateContent()),g=f.find(".label");a.label?g.html(a.label):g.hide();var h=f.find(".line");this.$panel.append(f);for(var i in b){var j=$(this._templateBox(b[i]));d&&(j.css("border-top","none"),j.css("border-top-left-radius","0px"),j.css("border-top-right-radius","0px")),e&&(j.css("border-bottom","none"),j.css("border-bottom-left-radius","0px"),j.css("border-bottom-right-radius","0px")),h.append(j)}return c&&h.css("padding-bottom",c),f},_templateCheck:function(){return'<div class="ui-color-picker-check fa fa-check"/>'},_templateContent:function(){return'<div class="ui-color-picker-content"><div class="label"/><div class="line"/></div>'},_templateBox:function(a){return'<div id="'+a+'" class="ui-color-picker-box" style="background-color: #'+a+';"/>'},_template:function(){return'<div class="ui-color-picker"><div class="ui-color-picker-header"><div class="ui-color-picker-value"/><div class="ui-color-picker-label">Select a color</div></div><div class="ui-color-picker-view ui-input"><div class="ui-color-picker-panel"/></div>'}})}); //# sourceMappingURL=../../../maps/mvc/ui/ui-color-picker.js.map
from dataclasses import dataclass, field from enum import Enum from typing import Optional __NAMESPACE__ = "NISTSchema-SV-IV-list-integer-enumeration-1-NS" class NistschemaSvIvListIntegerEnumeration1Type(Enum): VALUE_19789855_80316791588179803_3753891915009565_85394693894_2740498569495700_383_50766809891822_7192397142_1150 = ( -19789855, -80316791588179803, 3753891915009565, -85394693894, -2740498569495700, 383, 50766809891822, 7192397142, 1150, ) VALUE_575016907_24115387894653028_8794168478_171386831453520_8281_403702441_3794110_97012666 = ( -575016907, -24115387894653028, -8794168478, -171386831453520, -8281, -403702441, -3794110, 97012666, ) VALUE_84588865_64088268_97901153732606471_316613361439464_2982862088092316_4018148061_159106676246 = ( -84588865, -64088268, -97901153732606471, -316613361439464, -2982862088092316, -4018148061, 159106676246, ) VALUE_778792206055968_7316850324037_97_574_6603_29065461237_2_1991592157143 = ( -778792206055968, 7316850324037, -97, -574, 6603, 29065461237, -2, -1991592157143, ) VALUE_9640759352426359_998901040_36383199440838_485009177842248_5405402788920_28 = ( 9640759352426359, -998901040, -36383199440838, -485009177842248, -5405402788920, 28, ) VALUE_85823_47776877387_42_80863_515351580363_85858016557082206 = ( 85823, 47776877387, -42, -80863, 515351580363, -85858016557082206, ) VALUE_7033980_7897438_78863_6185711_8_4443407_627017786186059 = ( -7033980, 7897438, -78863, 6185711, -8, -4443407, -627017786186059, ) VALUE_61693722830317598_6658674442_77486848717532_384208848490567_182925095212482013_220546217025_624907935 = ( 61693722830317598, 6658674442, 77486848717532, -384208848490567, -182925095212482013, 220546217025, -624907935, ) @dataclass class NistschemaSvIvListIntegerEnumeration1: class Meta: name = "NISTSchema-SV-IV-list-integer-enumeration-1" namespace = "NISTSchema-SV-IV-list-integer-enumeration-1-NS" value: Optional[NistschemaSvIvListIntegerEnumeration1Type] = field( default=None, metadata={ "required": True, } )
#ifndef CPP_HTMLPARSER_STRINGS_H_ #define CPP_HTMLPARSER_STRINGS_H_ #include <optional> #include <sstream> #include <string> #include <string_view> #include <vector> namespace htmlparser { class Strings { public: // One of: // U+0009 CHARACTER TABULATION, // U+000A LINE FEED (LF), // U+000C FORM FEED (FF), // U+000D CARRIAGE RETURN (CR), or // U+0020 SPACE. inline static const std::string kWhitespace { // Do not sort or re-order. ' ', '\t', '\r', '\n', '\f', '\v'}; // kWhitespace plus null char. inline static const std::string kWhitespaceOrNull { // Do not sort or re-order. ' ', '\t', '\r', '\n', '\f', '\0', '\v'}; inline static const std::string kEscapeChars { // Do not sort or re-order. '&', '\'', '<', '>', '"'}; inline static const std::string kNullChar = {'\0'}; inline static const std::string kNullReplacementChar { '\xef', '\xbf', '\xbd'}; // encoded \ufffd (3 bytes). // Decodes a percent encoded string like "google.com%20%2F%20%3Fx%3Db" to // "google.com / ?x=b". static std::optional<std::string> DecodePercentEncodedURL( std::string_view uri); // Returns hex string representation of a 4 byte codepoint. static std::string ToHexString(char32_t c); // byte is in the range 0x41-0x5A or 0x61-0x7A (A-Z or a-z). static bool IsCharAlphabet(char c); // byte is in the range 0x30-0x39 (chars: 0-9) static bool IsDigit(char c); // Converts "\r" and "\r\n" in s to "\n". // The conversion happens in place, but the resulting string may be shorter. static void ConvertNewLines(std::string* s); // UTF-8 Encoding/Decoding utility functions. // ================================= // // Checks if the byte is a beginning of a unicode codepoint byte sequence. // First byte is masked as follows: // 0b110xxxxx - 2 byte sequence. // 0b1110xxxx - 3 byte sequence. // 0b11110xxx - 4 byte sequence. // // Returns number of byte sequence needed to encode the codepoint. static int8_t CodePointByteSequenceCount(uint8_t c); // Similar to CodePointByteSequenceCount except that it accepts entire // codepoint and tells how many bytes the codepoint contains. static int8_t CodePointNumBytes(char32_t c); // Decodes byte sequence to utf-8 codepoint. // The s points to the first byte in the sequence. Moves the cursor past // the byte sequence if decoding is successful. // // Returns 4 byte utf-8 codepoint value, or nullopt if: // - First byte is not valid (IsCodePoint), // - The three byte sequence includes unpaired surrogate which is not a scalar // value. // - Invalid utf-8 data. static std::optional<char32_t> DecodeUtf8Symbol(std::string_view* s); // Same as DecodeUtf8Symbol(string_view*) except that the prefix is not // updated, meaning cursor is at the first byte of the current character // decoded in s. static std::optional<char32_t> DecodeUtf8Symbol(std::string_view s, std::size_t position = 0) { if (position < 0 || position > s.size()) return std::nullopt; if (position == 0) { return DecodeUtf8Symbol(&s); } std::string_view s_at_prefix = s.substr(position); return DecodeUtf8Symbol(&s_at_prefix); } // Encodes a utf-8 codepoint. // Fills the codepoint in the following sequence: // // 7 bits US ASCII characters. // 0b0xxxxxx // // Codepoint upto 11 bits. // 0b110xxxxx 0b10xxxxxx // // Codepoint upto 16 bits. // 0b1110xxxx 0b10xxxxxx 0b10xxxxxx // // Codepoint upto 21 bits. // 0b11110xxx 0b10xxxxxx 0b10xxxxxx 0b10xxxxxx // // Returns nullopt on error. static std::optional<std::string> EncodeUtf8Symbol(char32_t code_point); static std::vector<char32_t> Utf8ToCodepoints(std::string_view utf8) { std::vector<char32_t> out; out.reserve(utf8.size() / 2); // We use the UnicodeText abstraction because it handles // validation / coersion under the hood, so what comes out of this is // surely valid UTF8. auto codepoint = DecodeUtf8Symbol(&utf8); while (codepoint) { out.push_back(*codepoint); codepoint = DecodeUtf8Symbol(&utf8); } return out; } static void AppendCodepointToUtf8String(char32_t code, std::string* utf8_str) { // The implementation is modified from UnicodeText::push_back to append // to an existing string, rather than allocate a new one. auto encoded = EncodeUtf8Symbol(code); if (encoded) { *utf8_str += *encoded; } else { utf8_str->push_back(' '); } } static std::string CodepointToUtf8String(char32_t code) { auto output = htmlparser::Strings::EncodeUtf8Symbol(code); return output ? std::move(output.value()) : ""; } // Converts unicode code points to a string. static std::string CodepointsToUtf8String(std::vector<char32_t> codes) { std::stringbuf buf; for (auto c : codes) { if (auto encoded = htmlparser::Strings::EncodeUtf8Symbol(c); encoded) { buf.sputn(encoded->c_str(), encoded->size()); } } return buf.str(); } // Returns index of the first instance of any character in chars or // npos if no character found. For unicode character returns the index of // initial byte of the sequence of bytes. static std::size_t IndexAny(std::string_view s, std::string_view chars); // Escapes special characters like "<" to become "&lt;". It escapes only // five such characters: <, >, &, ' and ". // UnescapeString(EscapeString(s)) == s always holds, but the converse isn't // always true. static std::string EscapeString(std::string_view s); static void Escape(std::string_view s, std::stringbuf* escaped); // Unescapes s's entities in-place, so that "a&lt;b" becomes "a<b". // attribute should be true if passing an attribute value. // UnescapeString(EscapeString(s)) == s always holds, but the converse isn't // always true. static void UnescapeString(std::string* s, bool attribute = false); // Converts case of string in-place. static void ToLower(std::string* s); static void ToUpper(std::string* s); // Checks if string contains whitespace only chracters. static bool IsAllWhitespaceChars(std::string_view s, std::string_view whitespace_chars = kWhitespace); // Case insensitive equals. static bool EqualFold(std::string_view l, std::string_view r); // Search replace functions. // Replaces first occurrence of the f in s with t. static void Replace(std::string* s, std::string_view f, std::string_view t); // Replaces all occurrences of the f in s with t. static void ReplaceAll(std::string* s, std::string_view f, std::string_view t); static void ReplaceAny(std::string* s, std::string_view chars, std::string_view to); // Replaces the string of characters in abc with the string of characters // in xyz. The first character in xyz will replace every occurrence of the // first character in abc that appears in the str. // // Example: // Translate("The quick brown fox.", // "abcdefghijklmnopqrstuvwxyz", // "ABCDEFGHIJKLMNOPQRSTUVWXYZ") // Returns: // THE QUICK BROWN FOX. // // This works for utf-8 characters. // Strings::Translate("AmAltAs", "A", "서") outputs: 서m서lt서s. // // If abc contains duplicates, replacements are performed in the order they // appear in the target string. So Translate("amaltas", "atas", "ipox") will // replace all occurrences of 'a' with 'i'. The later 'a'->'o' mapping is // ignored. // // If abc is longer than xyz, then every occurrence of characters from str // that do not have a corresponding character in xyz will be removed. // // Example: // Strings::Translate("The quick brown fox.", "brown", "red"); // returns: "The quick red fdx." // // The translated string may be smaller or larger than the evaluated string. // // Translation is guaranteed for ASCII characters. Translation may fail if // any of the strings str, abc, xyz contains utf-8 chars and decoding of those // chars failed, in which case this function returns std::nullopt. static std::optional<std::string> Translate( std::string_view str, // String to evaluate. std::string_view abc, // Chars that will be replaced. std::string_view xyz); // Chars used for replacement. // Strips whitespace from a string in-place. static void TrimLeft(std::string* s, std::string_view chars_to_trim = kWhitespace); static void TrimRight(std::string* s, std::string_view chars_to_trim = kWhitespace); static void Trim(std::string* s, std::string_view chars_to_trim = kWhitespace); static void TrimLeft(std::string_view* s, std::string_view chars_to_trim = kWhitespace); static void TrimRight(std::string_view* s, std::string_view chars_to_trim = kWhitespace); static void Trim(std::string_view* s, std::string_view chars_to_trim = kWhitespace); static bool StripTrailingNewline(std::string* s); // Reduces all consecutive sequences of space characters to a single space // character. // Resulting string may be smaller (resized) than the original string. static void RemoveExtraSpaceChars(std::string* s); // Prefix and suffix matching functions. static bool StartsWith(std::string_view s, std::string_view prefix); static bool EndsWith(std::string_view s, std::string_view suffix); // Splits a string at delimiter character and returns the columns. static std::vector<std::string> SplitStringAt( std::string_view s, char delimiter); // Splits the string at any utf8 or ascii whitespace and returns the columns. // The returned values are the views of original string argument passed to // this method. If the original string goes out of scope after this method is // called, the contents of the columns is undefined. static std::vector<std::string_view> SplitStrAtUtf8Whitespace( std::string_view s); // Determines if a character at current position is a whitespace char. // Returns the number of bytes from current character that are part of the // whitespace. For multichar whitespace like ideographic space \u3000 it // returns 3 as ideographic space has 3 codepoints. // // Returns 0, if the character at current position is not a whitespace. static int IsUtf8WhiteSpaceChar(std::string_view s, std::size_t position = 0); // Counts number of terms in a text separated by whitespace and punctuations. static int CountTerms(std::string_view s); private: // No instance of this class. Strings() = default; }; } // namespace htmlparser #endif // CPP_HTMLPARSER_STRINGS_H_
// // Created by Andrew Podkovyrin // Copyright © 2019 Dash Core Group. All rights reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class DWTitleActionHeaderView; @protocol DWTitleActionHeaderViewDelegate <NSObject> - (void)titleActionHeaderView:(DWTitleActionHeaderView *)view buttonAction:(UIView *)sender; @end @interface DWTitleActionHeaderView : UICollectionReusableView @property (strong, nonatomic) IBOutlet UILabel *titleLabel; @property (strong, nonatomic) IBOutlet UIButton *actionButton; @property (nullable, nonatomic, weak) id<DWTitleActionHeaderViewDelegate> delegate; @end NS_ASSUME_NONNULL_END
import sys class Matchers(object): def __init__(self, driver, verification_errors): self.driver = driver self.verification_erorrs = verification_errors # # unittest.TestCase provided # def assert_equal(self, first, second, msg=""): """ Hard assert for equality :params first: the value to compare against :params second: the value to compare with :params msg: (Optional) msg explaining the difference """ assert first == second def verify_equal(self, first, second, msg=""): """ Soft assert for equality :params want: the value to compare against :params second: the value to compare with :params msg: (Optional) msg explaining the difference """ try: self.assert_equal(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def assert_not_equal(self, first, second, msg=""): """ Hard assert for inequality :params want: the value to compare against :params secondv: the value to compare with :params msg: (Optional) msg explaining the difference """ assert first != second def verify_not_equal(self, first, second, msg=""): """ Soft assert for inequality :params want: the value to compare against :params second: the value to compare with :params msg: (Optional) msg explaining the difference """ try: self.assert_not_equal(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def assert_true(self, expr, msg=None): """ Soft assert for whether the condition is true :params expr: the statement to evaluate :params msg: (Optional) msg explaining the difference """ assert bool(expr) is True def verify_true(self, expr, msg=None): """ Soft assert for whether the condition is true :params expr: the statement to evaluate :params msg: (Optional) msg explaining the difference """ try: self.assert_true(expr, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def assert_false(self, expr, msg=None): """ Soft assert for whether the condition is false :params expr: the statement to evaluate :params msg: (Optional) msg explaining the difference """ assert bool(expr) is False def verify_false(self, expr, msg=None): """ Soft assert for whether the condition is false :params expr: the statement to evaluate :params msg: (Optional) msg explaining the difference """ try: self.assert_false(expr, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def assert_is(self, first, second, msg=None): """ Hard assert for whether the parameters evaluate to the same object :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """ assert first is second def verify_is(self, first, second, msg=None): """ Soft assert for whether the parameters evaluate to the same object :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """ try: self.assert_is(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def assert_is_not(self, first, second, msg=None): """ Hard assert for whether the parameters do not evaluate to the same object :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """ assert first is not second def verify_is_not(self, first, second, msg=None): """ Soft assert for whether the parameters do not evaluate to the same object :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """ try: self.assert_is_not(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def assert_is_none(self, expr, msg=None): """ Hard assert for whether the expr is None :params expr: the expression to execute :params msg: (Optional) msg explaining the difference """ assert expr is None def verify_is_none(self, expr, msg=None): """ Soft assert for whether the expr is None :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """ try: self.assert_is_none(expr, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def assert_is_not_none(self, expr, msg=None): """ Hard assert for whether the expr is not None :params expr: the expression to execute :params msg: (Optional) msg explaining the difference """ assert expr is not None def verify_is_not_none(self, expr, msg=None): """ Soft assert for whether the expr is not None :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """ try: self.assert_is_not_none(expr, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def assert_in(self, first, second, msg=""): """ Hard assert for whether the first is in second :params first: the value to check :params second: the container to check in :params msg: (Optional) msg explaining the difference """ assert first in second def verify_in(self, first, second, msg=""): """ Soft assert for whether the first is in second :params first: the value to check :params second: the container to check in :params msg: (Optional) msg explaining the difference """ try: self.assert_in(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def assert_not_in(self, first, second, msg=""): """ Hard assert for whether the first is not in second :params first: the value to check :params second: the container to check in :params msg: (Optional) msg explaining the difference """ assert first not in second def verify_not_in(self, first, second, msg=""): """ Soft assert for whether the first is not in second :params first: the value to check :params second: the container to check in :params msg: (Optional) msg explaining the difference """ try: self.assert_not_in(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def assert_is_instance(self, obj, cls, msg=""): """ Hard assert for whether the is an instance of cls :params obj: the object instance :params cls: the class to compare against :params msg: (Optional) msg explaining the difference """ assert isinstance(obj, cls) def verify_is_instance(self, obj, cls, msg=""): """ Soft assert for whether the is an instance of cls :params obj: the object instance :params cls: the class to compare against :params msg: (Optional) msg explaining the difference """ try: self.assert_is_instance(obj, cls, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def assert_is_not_instance(self, obj, cls, msg=""): """ Hard assert for whether the is not an instance of cls :params obj: the object instance :params cls: the class to compare against :params msg: (Optional) msg explaining the difference """ assert not isinstance(obj, cls) def verify_is_not_instance(self, obj, cls, msg=""): """ Soft assert for whether the is not an instance of cls :params obj: the object instance :params cls: the class to compare against :params msg: (Optional) msg explaining the difference """ try: self.assert_is_not_instance(obj, cls, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) # # selenium specific # def assert_text_present(self, text, msg=None): """ Hard assert for whether the text if visible in the current window/frame :params text: the string to search for :params msg: (Optional) msg explaining the difference """ e = driver.find_element_by_tag_name('body') assert text in e.text def verify_text_present(self, text, msg=None): """ Soft assert for whether the text if visible in the current window/frame :params text: the string to search for :params msg: (Optional) msg explaining the difference """ try: self.assert_text_present(text, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def asset_element_present(self, locator, msg=None): """ Hard assert for whether and element is present in the current window/frame :params locator: the locator of the element to search for :params msg: (Optional) msg explaining the difference """ e = driver.find_elements_by_locator(locator) if len(e) == 0: raise AssertionError("Element at %s was not found" % locator) def verify_element_present(self, locator, msg=None): """ Soft assert for whether and element is present in the current window/frame :params locator: the locator of the element to search for :params msg: (Optional) msg explaining the difference """ try: self.asset_element_present(locator, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m) def assert_visible(self, locator, msg=None): """ Hard assert for whether and element is present and visible in the current window/frame :params locator: the locator of the element to search for :params msg: (Optional) msg explaining the difference """ e = driver.find_elements_by_locator(locator) if len(e) == 0: raise AssertionError("Element at %s was not found" % locator) assert e.is_displayed() def verify_visible(self, locator, msg=None): """ Soft assert for whether and element is present and visible in the current window/frame :params locator: the locator of the element to search for :params msg: (Optional) msg explaining the difference """ try: self.assert_visible(locator, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
// Styles import "./App.css"; // Components import Routes from "./pages/Routes"; import { HashRouter } from "react-router-dom"; import { Container } from "react-bootstrap"; function App() { return ( <HashRouter> <Container fluid> <Routes /> </Container> </HashRouter> ); } export default App;
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@ag-grid-community/core"); var StatusBarService = /** @class */ (function () { // tslint:disable-next-line function StatusBarService() { this.allComponents = {}; } StatusBarService.prototype.registerStatusPanel = function (key, component) { this.allComponents[key] = component; }; StatusBarService.prototype.getStatusPanel = function (key) { return this.allComponents[key]; }; StatusBarService = __decorate([ core_1.Bean('statusBarService') ], StatusBarService); return StatusBarService; }()); exports.StatusBarService = StatusBarService;
# -*- coding: utf-8 -*- """ Implementation of the JSON-LD Context structure. See: http://json-ld.org/ """ from collections import namedtuple from rdflib.namespace import RDF from ._compat import basestring, unicode from .keys import (BASE, CONTAINER, CONTEXT, GRAPH, ID, INDEX, LANG, LIST, REV, SET, TYPE, VALUE, VOCAB) from . import errors from .util import source_to_json, urljoin, urlsplit, split_iri, norm_url NODE_KEYS = set([LANG, ID, TYPE, VALUE, LIST, SET, REV, GRAPH]) class Defined(int): pass UNDEF = Defined(0) class Context(object): def __init__(self, source=None, base=None): self.language = None self.vocab = None self.base = base self.doc_base = base self.terms = {} self._alias = {} self._lookup = {} self._prefixes = {} self.active = False if source: self.load(source) @property def base(self): return self._base @base.setter def base(self, base): if base: hash_index = base.find('#') if hash_index > -1: base = base[0:hash_index] self._base = self.resolve_iri(base) if ( hasattr(self, '_base') and base is not None) else base self._basedomain = '%s://%s' % urlsplit(base)[0:2] if base else None def subcontext(self, source): # IMPROVE: to optimize, implement SubContext with parent fallback support ctx = Context() ctx.language = self.language ctx.vocab = self.vocab ctx.base = self.base ctx.doc_base = self.doc_base ctx._alias = self._alias.copy() ctx.terms = self.terms.copy() ctx._lookup = self._lookup.copy() ctx._prefixes = self._prefixes.copy() ctx.load(source) return ctx def get_id(self, obj): return self._get(obj, ID) def get_type(self, obj): return self._get(obj, TYPE) def get_language(self, obj): return self._get(obj, LANG) def get_value(self, obj): return self._get(obj, VALUE) def get_graph(self, obj): return self._get(obj, GRAPH) def get_list(self, obj): return self._get(obj, LIST) def get_set(self, obj): return self._get(obj, SET) def get_rev(self, obj): return self._get(obj, REV) def _get(self, obj, key): return obj.get(self._alias.get(key)) or obj.get(key) def get_key(self, key): return self._alias.get(key, key) lang_key = property(lambda self: self.get_key(LANG)) id_key = property(lambda self: self.get_key(ID)) type_key = property(lambda self: self.get_key(TYPE)) value_key = property(lambda self: self.get_key(VALUE)) list_key = property(lambda self: self.get_key(LIST)) rev_key = property(lambda self: self.get_key(REV)) graph_key = property(lambda self: self.get_key(GRAPH)) def add_term(self, name, idref, coercion=UNDEF, container=UNDEF, language=UNDEF, reverse=False): term = Term(idref, name, coercion, container, language, reverse) self.terms[name] = term self._lookup[(idref, coercion or language, container, reverse)] = term self._prefixes[idref] = name def find_term(self, idref, coercion=None, container=UNDEF, language=None, reverse=False): lu = self._lookup if coercion is None: coercion = language if coercion is not UNDEF and container: found = lu.get((idref, coercion, container, reverse)) if found: return found if coercion is not UNDEF: found = lu.get((idref, coercion, UNDEF, reverse)) if found: return found if container: found = lu.get((idref, coercion, container, reverse)) if found: return found elif language: found = lu.get((idref, UNDEF, LANG, reverse)) if found: return found else: found = lu.get((idref, coercion or UNDEF, SET, reverse)) if found: return found return lu.get((idref, UNDEF, UNDEF, reverse)) def resolve(self, curie_or_iri): iri = self.expand(curie_or_iri, False) if self.isblank(iri): return iri return self.resolve_iri(iri) def resolve_iri(self, iri): return norm_url(self._base, iri) def isblank(self, ref): return ref.startswith('_:') def expand(self, term_curie_or_iri, use_vocab=True): if use_vocab: term = self.terms.get(term_curie_or_iri) if term: return term.id is_term, pfx, local = self._prep_expand(term_curie_or_iri) if pfx == '_': return term_curie_or_iri if pfx is not None: ns = self.terms.get(pfx) if ns and ns.id: return ns.id + local elif is_term and use_vocab: if self.vocab: return self.vocab + term_curie_or_iri return None return self.resolve_iri(term_curie_or_iri) def shrink_iri(self, iri): ns, name = split_iri(unicode(iri)) pfx = self._prefixes.get(ns) if pfx: return u":".join((pfx, name)) elif self._base: if unicode(iri) == self._base: return "" elif iri.startswith(self._basedomain): return iri[len(self._basedomain):] return iri def to_symbol(self, iri): iri = unicode(iri) term = self.find_term(iri) if term: return term.name ns, name = split_iri(iri) if ns == self.vocab: return name pfx = self._prefixes.get(ns) if pfx: return u":".join((pfx, name)) return iri def load(self, source, base=None): self.active = True sources = [] source = source if isinstance(source, list) else [source] self._prep_sources(base, source, sources) for source_url, source in sources: self._read_source(source, source_url) def _prep_sources(self, base, inputs, sources, referenced_contexts=None, in_source_url=None): referenced_contexts = referenced_contexts or set() for source in inputs: if isinstance(source, basestring): source_url = urljoin(base, source) if source_url in referenced_contexts: raise errors.RECURSIVE_CONTEXT_INCLUSION referenced_contexts.add(source_url) source = source_to_json(source_url) if CONTEXT not in source: raise errors.INVALID_REMOTE_CONTEXT else: source_url = in_source_url if isinstance(source, dict): if CONTEXT in source: source = source[CONTEXT] source = source if isinstance(source, list) else [source] if isinstance(source, list): self._prep_sources(base, source, sources, referenced_contexts, source_url) else: sources.append((source_url, source)) def _read_source(self, source, source_url=None): self.vocab = source.get(VOCAB, self.vocab) for key, value in source.items(): if key == LANG: self.language = value elif key == VOCAB: continue elif key == BASE: if source_url: continue self.base = value else: self._read_term(source, key, value) def _read_term(self, source, name, dfn): if isinstance(dfn, dict): #term = self._create_term(source, key, value) rev = dfn.get(REV) idref = rev or dfn.get(ID, UNDEF) if idref == TYPE: idref = unicode(RDF.type) elif idref is not UNDEF: idref = self._rec_expand(source, idref) elif ':' in name: idref = self._rec_expand(source, name) elif self.vocab: idref = self.vocab + name coercion = dfn.get(TYPE, UNDEF) if coercion and coercion not in (ID, TYPE, VOCAB): coercion = self._rec_expand(source, coercion) self.add_term(name, idref, coercion, dfn.get(CONTAINER, UNDEF), dfn.get(LANG, UNDEF), bool(rev)) else: idref = self._rec_expand(source, dfn) self.add_term(name, idref) if idref in NODE_KEYS: self._alias[idref] = name def _rec_expand(self, source, expr, prev=None): if expr == prev or expr in NODE_KEYS: return expr is_term, pfx, nxt = self._prep_expand(expr) if pfx: iri = self._get_source_id(source, pfx) or self.expand(pfx) if iri is None: nxt = expr else: nxt = iri + nxt else: nxt = self._get_source_id(source, nxt) or nxt if ':' not in nxt and self.vocab: return self.vocab + nxt return self._rec_expand(source, nxt, expr) def _prep_expand(self, expr): if ':' not in expr: return True, None, expr pfx, local = expr.split(':', 1) if not local.startswith('//'): return False, pfx, local else: return False, None, expr def _get_source_id(self, source, key): # .. from source dict or if already defined term = source.get(key) if term is None: dfn = self.terms.get(key) if dfn: term = dfn.id elif isinstance(term, dict): term = term.get(ID) return term Term = namedtuple('Term', 'id, name, type, container, language, reverse') Term.__new__.__defaults__ = (UNDEF, UNDEF, UNDEF, False)
// Init App var myApp = new Framework7({ modalTitle: 'Framework7', // Enable Material theme material: true, }); // Expose Internal DOM library var $$ = Dom7; // Add main view var mainView = myApp.addView('.view-main', { }); // Add another view, which is in right panel var rightView = myApp.addView('.view-right', { }); // Show/hide preloader for remote ajax loaded pages // Probably should be removed on a production/local app $$(document).on('ajaxStart', function (e) { if (e.detail.xhr.requestUrl.indexOf('autocomplete-languages.json') >= 0) { // Don't show preloader for autocomplete demo requests return; } myApp.showIndicator(); }); $$(document).on('ajaxComplete', function (e) { if (e.detail.xhr.requestUrl.indexOf('autocomplete-languages.json') >= 0) { // Don't show preloader for autocomplete demo requests return; } myApp.hideIndicator(); }); // Callbacks for specific pages when it initialized /* ===== Modals Page events ===== */ myApp.onPageInit('modals', function (page) { $$('.demo-alert').on('click', function () { myApp.alert('Hello!'); }); $$('.demo-confirm').on('click', function () { myApp.confirm('Are you feel good today?', function () { myApp.alert('Great!'); }); }); $$('.demo-prompt').on('click', function () { myApp.prompt('What is your name?', function (data) { // @data contains input value myApp.confirm('Are you sure that your name is ' + data + '?', function () { myApp.alert('Ok, your name is ' + data + ' ;)'); }); }); }); $$('.demo-login').on('click', function () { myApp.modalLogin('Enter your username and password', function (username, password) { myApp.alert('Thank you! Username: ' + username + ', password: ' + password); }); }); $$('.demo-password').on('click', function () { myApp.modalPassword('Enter your password', function (password) { myApp.alert('Thank you! Password: ' + password); }); }); $$('.demo-modals-stack').on('click', function () { // Open 5 alerts myApp.alert('Alert 1'); myApp.alert('Alert 2'); myApp.alert('Alert 3'); myApp.alert('Alert 4'); myApp.alert('Alert 5'); }); $$('.demo-picker-modal').on('click', function () { myApp.pickerModal('.picker-modal-demo'); }); }); /* ===== Preloader Page events ===== */ myApp.onPageInit('preloader', function (page) { $$('.demo-indicator').on('click', function () { myApp.showIndicator(); setTimeout(function () { myApp.hideIndicator(); }, 2000); }); $$('.demo-preloader').on('click', function () { myApp.showPreloader(); setTimeout(function () { myApp.hidePreloader(); }, 2000); }); $$('.demo-preloader-custom').on('click', function () { myApp.showPreloader('My text...'); setTimeout(function () { myApp.hidePreloader(); }, 2000); }); }); /* ===== Swipe to delete events callback demo ===== */ myApp.onPageInit('swipe-delete', function (page) { $$('.demo-remove-callback').on('deleted', function () { myApp.alert('Thanks, item removed!'); }); }); myApp.onPageInit('swipe-delete media-lists', function (page) { $$('.demo-reply').on('click', function () { myApp.alert('Reply'); }); $$('.demo-mark').on('click', function () { myApp.alert('Mark'); }); $$('.demo-forward').on('click', function () { myApp.alert('Forward'); }); }); /* ===== Action sheet, we use it on few pages ===== */ myApp.onPageInit('swipe-delete modals media-lists', function (page) { var actionSheetButtons = [ // First buttons group [ // Group Label { text: 'Choose some action', label: true }, // First button { text: 'Alert', onClick: function () { myApp.alert('He Hoou!'); } }, // Second button { text: 'Second Alert', onClick: function () { myApp.alert('Second Alert!'); } }, // Another red button { text: 'Nice Red Button ', color: 'red', onClick: function () { myApp.alert('You have clicked red button!'); } }, ], // Second group [ { text: 'Cancel' } ] ]; $$('.demo-actions').on('click', function (e) { myApp.actions(actionSheetButtons); }); $$('.demo-actions-popover').on('click', function (e) { // We need to pass additional target parameter (this) for popover myApp.actions(this, actionSheetButtons); }); }); /* ===== Messages Page ===== */ myApp.onPageInit('messages', function (page) { var conversationStarted = false; var answers = [ 'Yes!', 'No', 'Hm...', 'I am not sure', 'And what about you?', 'May be ;)', 'Lorem ipsum dolor sit amet, consectetur', 'What?', 'Are you sure?', 'Of course', 'Need to think about it', 'Amazing!!!', ]; var people = [ { name: 'Kate Johnson', avatar: 'http://lorempixel.com/output/people-q-c-100-100-9.jpg' }, { name: 'Blue Ninja', avatar: 'http://lorempixel.com/output/people-q-c-100-100-7.jpg' }, ]; var answerTimeout, isFocused; // Initialize Messages var myMessages = myApp.messages('.messages'); // Initialize Messagebar var myMessagebar = myApp.messagebar('.messagebar'); $$('.messagebar a.send-message').on('touchstart mousedown', function () { isFocused = document.activeElement && document.activeElement === myMessagebar.textarea[0]; }); $$('.messagebar a.send-message').on('click', function (e) { // Keep focused messagebar's textarea if it was in focus before if (isFocused) { e.preventDefault(); myMessagebar.textarea[0].focus(); } var messageText = myMessagebar.value(); if (messageText.length === 0) { return; } // Clear messagebar myMessagebar.clear(); // Add Message myMessages.addMessage({ text: messageText, avatar: 'http://lorempixel.com/output/people-q-c-200-200-6.jpg', type: 'sent', date: 'Now' }); conversationStarted = true; // Add answer after timeout if (answerTimeout) clearTimeout(answerTimeout); answerTimeout = setTimeout(function () { var answerText = answers[Math.floor(Math.random() * answers.length)]; var person = people[Math.floor(Math.random() * people.length)]; myMessages.addMessage({ text: answers[Math.floor(Math.random() * answers.length)], type: 'received', name: person.name, avatar: person.avatar, date: 'Just now' }); }, 2000); }); }); /* ===== Pull To Refresh Demo ===== */ myApp.onPageInit('pull-to-refresh', function (page) { // Dummy Content var songs = ['Yellow Submarine', 'Don\'t Stop Me Now', 'Billie Jean', 'Californication']; var authors = ['Beatles', 'Queen', 'Michael Jackson', 'Red Hot Chili Peppers']; // Pull to refresh content var ptrContent = $$(page.container).find('.pull-to-refresh-content'); // Add 'refresh' listener on it ptrContent.on('refresh', function (e) { // Emulate 2s loading setTimeout(function () { var picURL = 'http://lorempixel.com/88/88/abstract/' + Math.round(Math.random() * 10); var song = songs[Math.floor(Math.random() * songs.length)]; var author = authors[Math.floor(Math.random() * authors.length)]; var linkHTML = '<li class="item-content">' + '<div class="item-media"><img src="' + picURL + '" width="44"/></div>' + '<div class="item-inner">' + '<div class="item-title-row">' + '<div class="item-title">' + song + '</div>' + '</div>' + '<div class="item-subtitle">' + author + '</div>' + '</div>' + '</li>'; ptrContent.find('ul').prepend(linkHTML); // When loading done, we need to "close" it myApp.pullToRefreshDone(); }, 2000); }); }); /* ===== Sortable page ===== */ myApp.onPageInit('sortable-list', function (page) { // Sortable toggler $$('.list-block.sortable').on('open', function () { $$('.toggle-sortable').text('Done'); }); $$('.list-block.sortable').on('close', function () { $$('.toggle-sortable').text('Edit'); }); }); /* ===== Photo Browser Examples ===== */ // Create photoprobsers first: var photoBrowserPhotos = [ { url: 'img/beach.jpg', caption: 'Amazing beach in Goa, India' }, 'http://placekitten.com/1024/1024', 'img/lock.jpg', { url: 'img/monkey.jpg', caption: 'I met this monkey in Chinese mountains' }, { url: 'img/mountains.jpg', caption: 'Beautiful mountains in Zhangjiajie, China' } ]; var photoBrowserStandalone = myApp.photoBrowser({ photos: photoBrowserPhotos }); var photoBrowserPopup = myApp.photoBrowser({ photos: photoBrowserPhotos, type: 'popup' }); var photoBrowserPage = myApp.photoBrowser({ photos: photoBrowserPhotos, type: 'page' }); var photoBrowserDark = myApp.photoBrowser({ photos: photoBrowserPhotos, theme: 'dark' }); var photoBrowserPopupDark = myApp.photoBrowser({ photos: photoBrowserPhotos, theme: 'dark', type: 'popup' }); var photoBrowserLazy = myApp.photoBrowser({ photos: photoBrowserPhotos, lazyLoading: true, theme: 'dark' }); myApp.onPageInit('photo-browser', function (page) { $$('.ks-pb-standalone').on('click', function () { photoBrowserStandalone.open(); }); $$('.ks-pb-popup').on('click', function () { photoBrowserPopup.open(); }); $$('.ks-pb-page').on('click', function () { photoBrowserPage.open(); }); $$('.ks-pb-popup-dark').on('click', function () { photoBrowserPopupDark.open(); }); $$('.ks-pb-standalone-dark').on('click', function () { photoBrowserDark.open(); }); $$('.ks-pb-lazy').on('click', function () { photoBrowserLazy.open(); }); }); /* ===== Infinite Scroll Page ===== */ myApp.onPageInit('infinite-scroll', function (page) { // Loading trigger var loading = false; // Last loaded index, we need to pass it to script var lastLoadedIndex = $$('.infinite-scroll .list-block li').length; // Attach 'infinite' event handler $$('.infinite-scroll').on('infinite', function () { // Exit, if loading in progress if (loading) return; // Set loading trigger loading = true; // Request some file with data $$.get('infinite-scroll-load.php', {leftIndex: lastLoadedIndex + 1}, function (data) { loading = false; if (data === '') { // Nothing more to load, detach infinite scroll events to prevent unnecessary loadings myApp.detachInfiniteScroll($$('.infinite-scroll')); } else { // Append loaded elements to list block $$('.infinite-scroll .list-block ul').append(data); // Update last loaded index lastLoadedIndex = $$('.infinite-scroll .list-block li').length; } }); }); }); /* ===== Notifications Page ===== */ myApp.onPageInit('notifications', function (page) { $$('.ks-notification-1').on('click', function () { myApp.addNotification({ message: 'Simple message' }); }); $$('.ks-notification-2').on('click', function () { myApp.addNotification({ message: 'Multi-line message. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc in magna nisi.', }); }); $$('.ks-notification-3').on('click', function () { myApp.addNotification({ message: 'Nice yellow button', button: { text: 'Click me', color: 'yellow' } }); }); $$('.ks-notification-4').on('click', function () { myApp.addNotification({ message: 'Close me to see Alert', button: { text: 'Close', color: 'lightgreen' }, onClose: function () { myApp.alert('Notification closed'); } }); }); }); /* ===== Login screen page events ===== */ myApp.onPageInit('login-screen-embedded', function (page) { $$(page.container).find('.button').on('click', function () { var username = $$(page.container).find('input[name="username"]').val(); var password = $$(page.container).find('input[name="password"]').val(); myApp.alert('Username: ' + username + ', password: ' + password, function () { mainView.router.back(); }); }); }); $$('.login-screen').find('.button').on('click', function () { var username = $$('.login-screen').find('input[name="username"]').val(); var password = $$('.login-screen').find('input[name="password"]').val(); myApp.alert('Username: ' + username + ', password: ' + password, function () { myApp.closeModal('.login-screen'); }); }); /* ===== Demo Popover ===== */ $$('.popover a').on('click', function () { myApp.closeModal('.popover'); }); /* ===== Color themes ===== */ myApp.onPageInit('color-themes', function (page) { $$(page.container).find('.ks-color-theme').click(function () { var classList = $$('body')[0].classList; for (var i = 0; i < classList.length; i++) { if (classList[i].indexOf('theme') === 0) classList.remove(classList[i]); } classList.add('theme-' + $$(this).attr('data-theme')); }); $$(page.container).find('.ks-layout-theme').click(function () { var classList = $$('body')[0].classList; for (var i = 0; i < classList.length; i++) { if (classList[i].indexOf('layout-') === 0) classList.remove(classList[i]); } classList.add('layout-' + $$(this).attr('data-theme')); }); }); /* ===== Virtual List ===== */ myApp.onPageInit('virtual-list', function (page) { // Generate array with 10000 demo items: var items = []; for (var i = 0; i < 10000; i++) { items.push({ title: 'Item ' + i, subtitle: 'Subtitle ' + i }); } // Create virtual list var virtualList = myApp.virtualList($$(page.container).find('.virtual-list'), { // Pass array with items items: items, // Custom search function for searchbar searchAll: function (query, items) { var found = []; for (var i = 0; i < items.length; i++) { if (items[i].title.indexOf(query) >= 0 || query.trim() === '') found.push(i); } return found; //return array with mathced indexes }, // List item Template7 template template: '<li>' + '<a href="#" class="item-link item-content">' + '<div class="item-inner">' + '<div class="item-title-row">' + '<div class="item-title">{{title}}</div>' + '</div>' + '<div class="item-subtitle">{{subtitle}}</div>' + '</div>' + '</a>' + '</li>', // Item height height: 73, }); }); /* ===== Swiper Two Way Control Gallery ===== */ myApp.onPageInit('swiper-gallery', function (page) { var swiperTop = myApp.swiper('.ks-swiper-gallery-top', { nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', spaceBetween: 10 }); var swiperThumbs = myApp.swiper('.ks-swiper-gallery-thumbs', { slidesPerView: 'auto', spaceBetween: 10, centeredSlides: true, touchRatio: 0.2, slideToClickedSlide: true }); swiperTop.params.control = swiperThumbs; swiperThumbs.params.control = swiperTop; }); /* ===== Calendar ===== */ myApp.onPageInit('calendar', function (page) { // Default var calendarDefault = myApp.calendar({ input: '#ks-calendar-default', }); // With custom date format var calendarDateFormat = myApp.calendar({ input: '#ks-calendar-date-format', dateFormat: 'DD, MM dd, yyyy' }); // With multiple values var calendarMultiple = myApp.calendar({ input: '#ks-calendar-multiple', dateFormat: 'M dd yyyy', multiple: true }); // Range Picker var calendarRange = myApp.calendar({ input: '#ks-calendar-range', dateFormat: 'M dd yyyy', rangePicker: true }); // Inline with custom toolbar var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August' , 'September' , 'October', 'November', 'December']; var calendarInline = myApp.calendar({ container: '#ks-calendar-inline-container', value: [new Date()], weekHeader: false, header: false, footer: false, toolbarTemplate: '<div class="toolbar calendar-custom-toolbar">' + '<div class="toolbar-inner">' + '<div class="left">' + '<a href="#" class="link icon-only"><i class="icon icon-back"></i></a>' + '</div>' + '<div class="center"></div>' + '<div class="right">' + '<a href="#" class="link icon-only"><i class="icon icon-forward"></i></a>' + '</div>' + '</div>' + '</div>', onOpen: function (p) { $$('.calendar-custom-toolbar .center').text(monthNames[p.currentMonth] +', ' + p.currentYear); $$('.calendar-custom-toolbar .left .link').on('click', function () { calendarInline.prevMonth(); }); $$('.calendar-custom-toolbar .right .link').on('click', function () { calendarInline.nextMonth(); }); }, onMonthYearChangeStart: function (p) { $$('.calendar-custom-toolbar .center').text(monthNames[p.currentMonth] +', ' + p.currentYear); } }); }); /* ===== Pickers ===== */ myApp.onPageInit('pickers', function (page) { var today = new Date(); // iOS Device picker var pickerDevice = myApp.picker({ input: '#ks-picker-device', cols: [ { textAlign: 'center', values: ['iPhone 4', 'iPhone 4S', 'iPhone 5', 'iPhone 5S', 'iPhone 6', 'iPhone 6 Plus', 'iPad 2', 'iPad Retina', 'iPad Air', 'iPad mini', 'iPad mini 2', 'iPad mini 3'] } ] }); // Describe yourself picker var pickerDescribe = myApp.picker({ input: '#ks-picker-describe', rotateEffect: true, cols: [ { textAlign: 'left', values: ('Super Lex Amazing Bat Iron Rocket Lex Cool Beautiful Wonderful Raining Happy Amazing Funny Cool Hot').split(' ') }, { values: ('Man Luthor Woman Boy Girl Person Cutie Babe Raccoon').split(' ') }, ] }); // Dependent values var carVendors = { Japanese : ['Honda', 'Lexus', 'Mazda', 'Nissan', 'Toyota'], German : ['Audi', 'BMW', 'Mercedes', 'Volkswagen', 'Volvo'], American : ['Cadillac', 'Chrysler', 'Dodge', 'Ford'] }; var pickerDependent = myApp.picker({ input: '#ks-picker-dependent', rotateEffect: true, formatValue: function (picker, values) { return values[1]; }, cols: [ { textAlign: 'left', values: ['Japanese', 'German', 'American'], onChange: function (picker, country) { if(picker.cols[1].replaceValues){ picker.cols[1].replaceValues(carVendors[country]); } } }, { values: carVendors.Japanese, width: 160, }, ] }); // Custom Toolbar var pickerCustomToolbar = myApp.picker({ input: '#ks-picker-custom-toolbar', rotateEffect: true, toolbarTemplate: '<div class="toolbar">' + '<div class="toolbar-inner">' + '<div class="left">' + '<a href="#" class="link toolbar-randomize-link">Randomize</a>' + '</div>' + '<div class="right">' + '<a href="#" class="link close-picker">That\'s me</a>' + '</div>' + '</div>' + '</div>', cols: [ { values: ['Mr', 'Ms'], }, { textAlign: 'left', values: ('Super Lex Amazing Bat Iron Rocket Lex Cool Beautiful Wonderful Raining Happy Amazing Funny Cool Hot').split(' ') }, { values: ('Man Luthor Woman Boy Girl Person Cutie Babe Raccoon').split(' ') }, ], onOpen: function (picker) { picker.container.find('.toolbar-randomize-link').on('click', function () { var col0Values = picker.cols[0].values; var col0Random = col0Values[Math.floor(Math.random() * col0Values.length)]; var col1Values = picker.cols[1].values; var col1Random = col1Values[Math.floor(Math.random() * col1Values.length)]; var col2Values = picker.cols[2].values; var col2Random = col2Values[Math.floor(Math.random() * col2Values.length)]; picker.setValue([col0Random, col1Random, col2Random]); }); } }); // Inline date-time var pickerInline = myApp.picker({ input: '#ks-picker-date', container: '#ks-picker-date-container', toolbar: false, rotateEffect: true, value: [today.getMonth(), today.getDate(), today.getFullYear(), today.getHours(), (today.getMinutes() < 10 ? '0' + today.getMinutes() : today.getMinutes())], onChange: function (picker, values, displayValues) { var daysInMonth = new Date(picker.value[2], picker.value[0]*1 + 1, 0).getDate(); if (values[1] > daysInMonth) { picker.cols[1].setValue(daysInMonth); } }, formatValue: function (p, values, displayValues) { return displayValues[0] + ' ' + values[1] + ', ' + values[2] + ' ' + values[3] + ':' + values[4]; }, cols: [ // Months { values: ('0 1 2 3 4 5 6 7 8 9 10 11').split(' '), displayValues: ('January February March April May June July August September October November December').split(' '), textAlign: 'left' }, // Days { values: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31], }, // Years { values: (function () { var arr = []; for (var i = 1950; i <= 2030; i++) { arr.push(i); } return arr; })(), }, // Space divider { divider: true, content: '&nbsp;&nbsp;' }, // Hours { values: (function () { var arr = []; for (var i = 0; i <= 23; i++) { arr.push(i); } return arr; })(), }, // Divider { divider: true, content: ':' }, // Minutes { values: (function () { var arr = []; for (var i = 0; i <= 59; i++) { arr.push(i < 10 ? '0' + i : i); } return arr; })(), } ] }); }); /* ===== Chips ===== */ myApp.onPageInit('chips', function (page) { $$(page.container).find('.chip-delete').on('click', function (e) { e.preventDefault(); var chip = $$(this).parents('.chip'); myApp.confirm('Do you want to delete this tiny demo Chip?', function () { chip.remove(); }); }); }); /* ===== Progress Bars ===== */ myApp.onPageInit('progressbar', function (page) { $$('.ks-demo-progressbar-inline .button').on('click', function () { var progress = $$(this).attr('data-progress'); var progressbar = $$('.ks-demo-progressbar-inline .progressbar'); myApp.setProgressbar(progressbar, progress); }); $$('.ks-demo-progressbar-load-hide .button').on('click', function () { var container = $$('.ks-demo-progressbar-load-hide p:first-child'); if (container.children('.progressbar').length) return; //don't run all this if there is a current progressbar loading myApp.showProgressbar(container, 0); // Simluate Loading Something var progress = 0; function simulateLoading() { setTimeout(function () { var progressBefore = progress; progress += Math.random() * 20; myApp.setProgressbar(container, progress); if (progressBefore < 100) { simulateLoading(); //keep "loading" } else myApp.hideProgressbar(container); //hide }, Math.random() * 200 + 200); } simulateLoading(); }); $$('.ks-demo-progressbar-overlay .button').on('click', function () { // Add Directly To Body var container = $$('body'); if (container.children('.progressbar, .progressbar-infinite').length) return; //don't run all this if there is a current progressbar loading myApp.showProgressbar(container, 0, 'yellow'); // Simluate Loading Something var progress = 0; function simulateLoading() { setTimeout(function () { var progressBefore = progress; progress += Math.random() * 20; myApp.setProgressbar(container, progress); if (progressBefore < 100) { simulateLoading(); //keep "loading" } else myApp.hideProgressbar(container); //hide }, Math.random() * 200 + 200); } simulateLoading(); }); $$('.ks-demo-progressbar-infinite-overlay .button').on('click', function () { var container = $$('body'); if (container.children('.progressbar, .progressbar-infinite').length) return; //don't run all this if there is a current progressbar loading myApp.showProgressbar(container, 'yellow'); setTimeout(function () { myApp.hideProgressbar(); }, 5000); }); $$('.ks-demo-progressbar-infinite-multi-overlay .button').on('click', function () { var container = $$('body'); if (container.children('.progressbar, .progressbar-infinite').length) return; //don't run all this if there is a current progressbar loading myApp.showProgressbar(container, 'multi'); setTimeout(function () { myApp.hideProgressbar(); }, 5000); }); }); /* ===== Autocomplete ===== */ myApp.onPageInit('autocomplete', function (page) { // Fruits data demo array var fruits = ('Apple Apricot Avocado Banana Melon Orange Peach Pear Pineapple').split(' '); // Simple Dropdown var autocompleteDropdownSimple = myApp.autocomplete({ input: '#autocomplete-dropdown', openIn: 'dropdown', source: function (autocomplete, query, render) { var results = []; if (query.length === 0) { render(results); return; } // Find matched items for (var i = 0; i < fruits.length; i++) { if (fruits[i].toLowerCase().indexOf(query.toLowerCase()) >= 0) results.push(fruits[i]); } // Render items by passing array with result items render(results); } }); // Dropdown with all values var autocompleteDropdownAll = myApp.autocomplete({ input: '#autocomplete-dropdown-all', openIn: 'dropdown', source: function (autocomplete, query, render) { var results = []; // Find matched items for (var i = 0; i < fruits.length; i++) { if (fruits[i].toLowerCase().indexOf(query.toLowerCase()) >= 0) results.push(fruits[i]); } // Render items by passing array with result items render(results); } }); // Dropdown with placeholder var autocompleteDropdownPlaceholder = myApp.autocomplete({ input: '#autocomplete-dropdown-placeholder', openIn: 'dropdown', dropdownPlaceholderText: 'Try to type "Apple"', source: function (autocomplete, query, render) { var results = []; if (query.length === 0) { render(results); return; } // Find matched items for (var i = 0; i < fruits.length; i++) { if (fruits[i].toLowerCase().indexOf(query.toLowerCase()) >= 0) results.push(fruits[i]); } // Render items by passing array with result items render(results); } }); // Dropdown with ajax data var autocompleteDropdownAjax = myApp.autocomplete({ input: '#autocomplete-dropdown-ajax', openIn: 'dropdown', preloader: true, //enable preloader valueProperty: 'id', //object's "value" property name textProperty: 'name', //object's "text" property name limit: 20, //limit to 20 results dropdownPlaceholderText: 'Try "JavaScript"', source: function (autocomplete, query, render) { var results = []; if (query.length === 0) { render(results); return; } // Show Preloader autocomplete.showPreloader(); // Do Ajax request to Autocomplete data $$.ajax({ url: 'js/autocomplete-languages.json', method: 'GET', dataType: 'json', //send "query" to server. Useful in case you generate response dynamically data: { query: query }, success: function (data) { // Find matched items for (var i = 0; i < data.length; i++) { if (data[i].name.toLowerCase().indexOf(query.toLowerCase()) >= 0) results.push(data[i]); } // Hide Preoloader autocomplete.hidePreloader(); // Render items by passing array with result items render(results); } }); } }); // Simple Standalone var autocompleteStandaloneSimple = myApp.autocomplete({ openIn: 'page', //open in page opener: $$('#autocomplete-standalone'), //link that opens autocomplete backOnSelect: true, //go back after we select something source: function (autocomplete, query, render) { var results = []; if (query.length === 0) { render(results); return; } // Find matched items for (var i = 0; i < fruits.length; i++) { if (fruits[i].toLowerCase().indexOf(query.toLowerCase()) >= 0) results.push(fruits[i]); } // Render items by passing array with result items render(results); }, onChange: function (autocomplete, value) { // Add item text value to item-after $$('#autocomplete-standalone').find('.item-after').text(value[0]); // Add item value to input value $$('#autocomplete-standalone').find('input').val(value[0]); } }); // Standalone Popup var autocompleteStandalonePopup = myApp.autocomplete({ openIn: 'popup', //open in page opener: $$('#autocomplete-standalone-popup'), //link that opens autocomplete backOnSelect: true, //go back after we select something source: function (autocomplete, query, render) { var results = []; if (query.length === 0) { render(results); return; } // Find matched items for (var i = 0; i < fruits.length; i++) { if (fruits[i].toLowerCase().indexOf(query.toLowerCase()) >= 0) results.push(fruits[i]); } // Render items by passing array with result items render(results); }, onChange: function (autocomplete, value) { // Add item text value to item-after $$('#autocomplete-standalone-popup').find('.item-after').text(value[0]); // Add item value to input value $$('#autocomplete-standalone-popup').find('input').val(value[0]); } }); // Multiple Standalone var autocompleteStandaloneMultiple = myApp.autocomplete({ openIn: 'page', //open in page opener: $$('#autocomplete-standalone-multiple'), //link that opens autocomplete multiple: true, //allow multiple values source: function (autocomplete, query, render) { var results = []; if (query.length === 0) { render(results); return; } // Find matched items for (var i = 0; i < fruits.length; i++) { if (fruits[i].toLowerCase().indexOf(query.toLowerCase()) >= 0) results.push(fruits[i]); } // Render items by passing array with result items render(results); }, onChange: function (autocomplete, value) { // Add item text value to item-after $$('#autocomplete-standalone-multiple').find('.item-after').text(value.join(', ')); // Add item value to input value $$('#autocomplete-standalone-multiple').find('input').val(value.join(', ')); } }); // Standalone With Ajax var autocompleteStandaloneAjax = myApp.autocomplete({ openIn: 'page', //open in page opener: $$('#autocomplete-standalone-ajax'), //link that opens autocomplete multiple: true, //allow multiple values valueProperty: 'id', //object's "value" property name textProperty: 'name', //object's "text" property name limit: 50, preloader: true, //enable preloader source: function (autocomplete, query, render) { var results = []; if (query.length === 0) { render(results); return; } // Show Preloader autocomplete.showPreloader(); // Do Ajax request to Autocomplete data $$.ajax({ url: 'js/autocomplete-languages.json', method: 'GET', dataType: 'json', //send "query" to server. Useful in case you generate response dynamically data: { query: query }, success: function (data) { // Find matched items for (var i = 0; i < data.length; i++) { if (data[i].name.toLowerCase().indexOf(query.toLowerCase()) >= 0) results.push(data[i]); } // Hide Preoloader autocomplete.hidePreloader(); // Render items by passing array with result items render(results); } }); }, onChange: function (autocomplete, value) { var itemText = [], inputValue = []; for (var i = 0; i < value.length; i++) { itemText.push(value[i].name); inputValue.push(value[i].id); } // Add item text value to item-after $$('#autocomplete-standalone-ajax').find('.item-after').text(itemText.join(', ')); // Add item value to input value $$('#autocomplete-standalone-ajax').find('input').val(inputValue.join(', ')); } }); }); /* ===== Change statusbar bg when panel opened/closed ===== */ $$('.panel-left').on('open', function () { $$('.statusbar-overlay').addClass('with-panel-left'); }); $$('.panel-right').on('open', function () { $$('.statusbar-overlay').addClass('with-panel-right'); }); $$('.panel-left, .panel-right').on('close', function () { $$('.statusbar-overlay').removeClass('with-panel-left with-panel-right'); }); /* ===== Generate Content Dynamically ===== */ var dynamicPageIndex = 0; function createContentPage() { mainView.router.loadContent( ' <!-- Page, data-page contains page name-->' + ' <div data-page="dynamic-content" class="page">' + ' <!-- Top Navbar-->' + ' <div class="navbar">' + ' <div class="navbar-inner">' + ' <div class="left"><a href="#" class="back link icon-only"><i class="icon icon-back"></i></a></div>' + ' <div class="center">Dynamic Page ' + (++dynamicPageIndex) + '</div>' + ' </div>' + ' </div>' + ' <!-- Scrollable page content-->' + ' <div class="page-content">' + ' <div class="content-block">' + ' <p>Here is a dynamic page created on ' + new Date() + ' !</p>' + ' <p>Go <a href="#" class="back">back</a> or generate <a href="#" class="ks-generate-page">one more page</a>.</p>' + ' </div>' + ' </div>' + ' </div>' ); return; } $$(document).on('click', '.ks-generate-page', createContentPage);
/* * Copyright 2018 dialog LLC <info@dlg.im> * @flow */ import type { Call } from '@dlghq/dialog-types'; function hasTheirVideos(call: Call): boolean { return Boolean(call.theirVideos.length); } function hasOwnVideos(call: Call): boolean { return Boolean(call.ownVideos.length); } function hasVideos(call: Call): boolean { return Boolean(hasOwnVideos(call) || hasTheirVideos(call)); } export { hasVideos, hasOwnVideos, hasTheirVideos };
# coding: utf-8 n, m = [int(i) for i in input().split()] d = {} for i in range(m): tmp = input().split() d[tmp[0]] = tmp[1] s = input().split() for i in range(n): if len(s[i])>len(d[s[i]]): s[i] = d[s[i]] print(' '.join(s))
const parameter = require("./app/parameter"); const errorVerify = require("./app/error"); // error verify function validate(rules, data) { return (proto, propertyKey, descriptor) => { const oldFunc = descriptor.value; descriptor.value = async function validateWrap(ctx, next) { // 从获取 query body ctx.verifyParams(rules, data); await oldFunc.call(this, ...arguments); await next(); }; }; } module.exports = { parameter, validate, errorVerify, };
import os from tkinter import * from tkinter import ttk from PIL import ImageTk, Image def option_menu_value(*args): v = menu.get() menu.set('MENU') print(v) a = Tk() a.geometry('1350x720') tvs_image_location = os.path.abspath('../tvs_project/tvs logo.png') image_frame = Frame(a, bg='orange') image_frame.grid(row=0, column=0) widget_frame = Frame(a) widget_frame.grid(row=1, column=0) output_frame = Frame(a, bg='white', width=50) output_frame.grid(row=2, column=0) opened_image = Image.open(tvs_image_location) global tvs_logo tvs_logo = ImageTk.PhotoImage(opened_image) lbl_tvs_logo = Label(image_frame, image=tvs_logo, bg='orange') lbl_tvs_logo.pack(side=TOP, padx=274) menu_list = ['ABOUT US', 'OFFERS', 'OUR PRODUCTS', 'SERVICE DETAILS', 'DEALER LOCATOR'] menu = StringVar() menu.set('MENU') menu_button = OptionMenu(widget_frame, menu, *menu_list, command=option_menu_value) menu_button.config(font=('bold', 22), bg="black", fg="white", padx=50, pady=10, relief='groove') menu_button["menu"].config(bg="white", font=32) menu_button.pack(side=LEFT, anchor='w') about_button = Button(widget_frame, text="Test Drive", font=('bold', 22), bg="black", fg="white", padx=40, relief='groove') about_button.pack(side=LEFT) vechile_button = Button(widget_frame, text="Vechile", font=('bold', 22), bg="black", fg="white", padx=50, relief='groove') vechile_button.pack(side=LEFT) award_button = Button(widget_frame, text="Awards", font=('bold', 22), bg="black", fg="white", padx=40, relief='groove') award_button.pack(side=LEFT) feedback_button = Button(widget_frame, text="Feedback", font=('bold', 22), bg="black", fg="white", padx=40, relief='groove') feedback_button.pack(side=LEFT) exit_button = Button(widget_frame, text="Exit", font=('bold', 22), bg="black", fg="white", padx=40, relief='groove') exit_button.pack(side=RIGHT) a.mainloop()
import React from "react"; import Layout from '../components/layout'; import IndexHeader from "../components/index/indexHeader"; import MainContentIndex from "../components/index/mainContentIndex"; const IndexPage = () => { return ( <Layout> <IndexHeader /> <MainContentIndex /> </Layout> ) } export default IndexPage;
# coding=utf-8 import unittest from smallinvoice.commons import Recipient, Mail, PREVIEW_SIZE from smallinvoice.offers import Offer, OfferState from smallinvoice.tests import get_smallinvoice, generate_address, \ generate_customer, generate_position def generate_offer(): return Offer( client_id='', client_address_id='', currency='CHF', date='2013-07-03', due='2013-07-28', language='en' ) class OfferTests(unittest.TestCase): def setUp(self): self.address = generate_address() self.client = generate_customer() self.client.add_address(self.address) self.position = generate_position() self.offer = generate_offer() self.offer.add_position(self.position) self.customer_id = get_smallinvoice().clients.add(self.client) self.offer.client_id = self.customer_id test = get_smallinvoice().clients.details(self.customer_id) self.offer.client_address_id = test['main_address_id'] self.offer_id = get_smallinvoice().offers.add(self.offer) def tearDown(self): get_smallinvoice().clients.delete(self.customer_id) get_smallinvoice().offers.delete(self.offer_id) def test_offer(self): self.assertIsNotNone(self.offer_id) def test_offer_details(self): self.assertEqual(self.offer.language, 'en') def test_offer_update(self): self.assertEqual(self.offer.language, 'en') self.offer.language = 'de' self.assertEqual(self.offer.language, 'de') def test_offer_pdf(self): pdf = get_smallinvoice().offers.pdf(self.offer_id) self.assertTrue(len(pdf) > 0) def test_offer_preview(self): preview = get_smallinvoice().offers.preview(self.offer_id, 1, PREVIEW_SIZE.SMALL) self.assertTrue(len(preview) > 0) def test_email_offer(self): r = Recipient(cc=False, email="philipp.laeubli@dreipol.ch", name="Test Name") m = Mail(subject="Testsubject", body="Test email body", sendstatus=1, afterstatus=1) m.add_recipient(r) m.id = self.offer_id get_smallinvoice().offers.email(m.id, m) self.assertEqual(m.id, self.offer_id) def test_status_offer(self): s = OfferState(status=OfferState.OK) get_smallinvoice().offers.status(self.offer_id, data=s) self.assertTrue(get_smallinvoice().offers.details(self.offer_id) ["status"] == 9)
import time from bs4 import BeautifulSoup import requests import pymysql.cursors import unittest import warnings class UnitTestsDataMinerYellowPagesPoland(unittest.TestCase): def test_extract_one_email(self): headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103' } url = "https://www.pkt.pl/firma/kom-rol-kobylniki-sp-z-o-o-120512369" # Request the content of a page from the url html = requests.get(url, headers=headers) # Parse the content of html_doc soup = BeautifulSoup(html.content, 'html.parser') if soup.find('div', {'class': 'call-cell call--email'})\ .find('a', {'data-popup': 'email-popup'})\ .find('span', {'data-tooltip': 'tooltip'}) is not None: email = "info@" + soup.find('div', {'class': 'call-cell call--email'})\ .find('a', {'data-popup': 'email-popup'})\ .find('span', {'data-tooltip': 'tooltip'})\ .get('title')\ .split("@")[1] print("email : " + email) else: print("no call-cell call--email") def test_extract_emails_from_all_page_of_results_for_one_activity_and_capital(self): activity = "hotel" city = "kujawsko-pomorskie" url_search = "https://www.pkt.pl/szukaj/" + activity + "/" + city headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' } html_search = requests.get(url_search, headers=headers) soup_search = BeautifulSoup(html_search.content, 'html.parser') number_of_pages = 0 if soup_search.select_one('#main') is not None: number_of_pages_with_coma = int(soup_search .find('div', {'class': 'box-fall-back-messages'}) .find('h1') .find_all('b')[0] .text )/25 if int(str(number_of_pages_with_coma).split(".")[1][:1]) < 5: number_of_pages += round(number_of_pages_with_coma) + 1 print('number_of_pages : ' + str(number_of_pages)) elif int(str(number_of_pages_with_coma).split(".")[1][:1]) >= 5: number_of_pages += round(number_of_pages_with_coma) print('number_of_pages : ' + str(number_of_pages)) else: print("no result header") i_1 = 0 for i in range(1, number_of_pages+1): url_of_one_page_of_results = url_search + "/" + str(i) print(url_of_one_page_of_results) time.sleep(2) html_of_one_page_of_results = requests.get(url_of_one_page_of_results, headers=headers) soup_of_one_page_of_results = BeautifulSoup(html_of_one_page_of_results.content, 'html.parser') if soup_of_one_page_of_results.find('div', {'class': 'box-content'}) is not None: for result_item in soup_of_one_page_of_results.find_all('div', {'class': 'box-content'}): if result_item.find('h2', {'class': 'company-name'}) is not None: i_1 += 1 url_result = "https://www.pkt.pl" + result_item.find('h2', {'class': 'company-name'})\ .find('a')\ .get('href') time.sleep(2) # Request the content of a page from the url html = requests.get(url_result, headers=headers) # Parse the content of html_doc soup = BeautifulSoup(html.content, 'html.parser') if soup.find('div', {'class': 'call-cell call--email'}) is not None: if soup.find('div', {'class': 'call-cell call--email'})\ .find('a', {'data-popup': 'email-popup'})\ .find('span', {'data-tooltip': 'tooltip'}) is not None: email = "info@" + soup.find('div', {'class': 'call-cell call--email'}) \ .find('a', {'data-popup': 'email-popup'}) \ .find('span', {'data-tooltip': 'tooltip'}) \ .get('title') \ .split("@")[1] print(str(i_1) + " - email : " + email) else: print(str(i_1) + " - no call-cell call--email") else: print(str(i_1) + " - no more info") else: print('sorry there is nothing') def test_extract_emails_from_all_page_of_results_for_all_activities_and_capitals(self): activites = [ {'id': '1', 'url': 'Agencje pracy tymczasowej'}, {'id': '2', 'url': 'nieruchomość'}, {'id': '3', 'url': 'rekrutacja'}, {'id': '4', 'url': 'oprogramowanie'}, {'id': '5', 'url': 'hotel'}, {'id': '6', 'url': 'gospodarz'}, {'id': '7', 'url': 'czyszczenie'}, {'id': '8', 'url': 'stowarzyszenie'}, {'id': '9', 'url': 'budżetowy'}, {'id': '10', 'url': 'restauracja'}, {'id': '11', 'url': 'budynek'}, {'id': '12', 'url': 'fryzjer'}, {'id': '13', 'url': 'kwiaciarz'}, {'id': '14', 'url': 'ślusarz'}, {'id': '15', 'url': 'piekarnia'}, {'id': '16', 'url': 'ubezpieczenie'}, {'id': '17', 'url': 'apteka'}, {'id': '18', 'url': 'w ruchu'}, {'id': '19', 'url': 'Elektryczność'}, {'id': '20', 'url': 'instalacja wodociągowa'}, {'id': '21', 'url': 'bezpieczeństwo'}, {'id': '22', 'url': 'prawni'}, {'id': '23', 'url': 'banki'}, {'id': '24', 'url': 'garaż'}, {'id': '25', 'url': 'stomatolodzy'}, {'id': '26', 'url': 'lekarz'}, {'id': '27', 'url': 'biura rachunkowe'}, {'id': '28', 'url': 'centra handlowe'}, {'id': '29', 'url': 'notariusze'}, {'id': '30', 'url': 'jubilerzy'}, {'id': '31', 'url': 'dostosować'}, {'id': '32', 'url': 'mięso'}, {'id': '33', 'url': 'biblioteki i czytelnie'}, {'id': '34', 'url': 'architekci'}, {'id': '36', 'url': 'cement'}, {'id': '37', 'url': 'ogrzewanie'}, {'id': '38', 'url': 'łódź'}, {'id': '39', 'url': 'zimno'}, {'id': '41', 'url': 'stal'}, {'id': '42', 'url': 'chemikalia'}, {'id': '43', 'url': 'gaz'}, {'id': '44', 'url': 'złoto'} ] capitales_du_monde = [ {'id': '494', 'nom': 'wielkopolskie'}, {'id': '495', 'nom': 'kujawsko-pomorskie'}, {'id': '496', 'nom': 'małopolskie'}, {'id': '497', 'nom': 'łódzkie'}, {'id': '498', 'nom': 'dolnośląskie'}, {'id': '499', 'nom': 'lubelskie'}, {'id': '500', 'nom': 'lubuskie'}, {'id': '501', 'nom': 'mazowieckie'}, {'id': '502', 'nom': 'opolskie'}, {'id': '503', 'nom': 'podlaskie'}, {'id': '504', 'nom': 'pomorskie'}, {'id': '505', 'nom': 'śląskie'}, {'id': '506', 'nom': 'podkarpackie'}, {'id': '507', 'nom': 'świętokrzyskie'}, {'id': '508', 'nom': 'warmińsko-mazurskie'}, {'id': '509', 'nom': 'zachodniopomorskie'}, ] try: for capitale in capitales_du_monde: for activite in activites: try: activity = activite.get('url') city = capitale.get('nom') url_search = "https://www.pkt.pl/szukaj/" + activity + "/" + city headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' } html_search = requests.get(url_search, headers=headers) soup_search = BeautifulSoup(html_search.content, 'html.parser') number_of_pages = 0 if soup_search.select_one('#main') is not None: number_of_pages_with_coma = int(soup_search .find('div', {'class': 'box-fall-back-messages'}) .find('h1') .find_all('b')[0] .text ) / 25 if int(str(number_of_pages_with_coma).split(".")[1][:1]) < 5: number_of_pages += round(number_of_pages_with_coma) + 1 print('number_of_pages : ' + str(number_of_pages)) elif int(str(number_of_pages_with_coma).split(".")[1][:1]) >= 5: number_of_pages += round(number_of_pages_with_coma) print('number_of_pages : ' + str(number_of_pages)) else: print("no result header") i_1 = 0 for i in range(1, number_of_pages + 1): url_of_one_page_of_results = url_search + "/" + str(i) print(url_of_one_page_of_results) time.sleep(2) html_of_one_page_of_results = requests.get(url_of_one_page_of_results, headers=headers) soup_of_one_page_of_results = BeautifulSoup(html_of_one_page_of_results.content, 'html.parser') if soup_of_one_page_of_results.find('div', {'class': 'box-content'}) is not None: for result_item in soup_of_one_page_of_results.find_all('div', {'class': 'box-content'}): if result_item.find('h2', {'class': 'company-name'}) is not None: i_1 += 1 url_result = "https://www.pkt.pl" + result_item\ .find('h2', {'class': 'company-name'}) \ .find('a') \ .get('href') time.sleep(2) # Request the content of a page from the url html = requests.get(url_result, headers=headers) # Parse the content of html_doc soup = BeautifulSoup(html.content, 'html.parser') if soup.find('div', {'class': 'call-cell call--email'}) is not None: if soup.find('div', {'class': 'call-cell call--email'}) \ .find('a', {'data-popup': 'email-popup'}) \ .find('span', {'data-tooltip': 'tooltip'}) is not None: email = "info@" + soup.find('div', {'class': 'call-cell call--email'}) \ .find('a', {'data-popup': 'email-popup'}) \ .find('span', {'data-tooltip': 'tooltip'}) \ .get('title') \ .split("@")[1] print(str(i_1) + " - email : " + email) try: connection = pymysql.connect( host='localhost', port=3306, user='', password='', db='contacts_professionnels', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) with connection.cursor() as cursor: try: sql = "INSERT INTO `emails` (" \ "`id_activite`, " \ "`id_capitale_du_monde`, " \ "`email`) VALUE (%s, %s, %s)" cursor.execute(sql, ( activite.get('id'), capitale.get('id'), email)) connection.commit() print(str(i_1) + " The record is stored : " + email) connection.close() except Exception as e: print(str(i_1) + " The record already exists : " + email + " " + str(e)) connection.close() except Exception as e: print(str(i_1) + " An error with the email : " + email + " " + str(e)) else: print(str(i_1) + " - no call-cell call--email") else: print(str(i_1) + " - no more info") else: print('sorry there is nothing') except Exception as e: print("There is an error connection at url : " + str(e)) finally: print('done') if __name__ == '__main__': warnings.filterwarnings(action="ignore", message="unclosed", category=ResourceWarning) unittest.main()
/** * @license * Copyright 2012 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 * * 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. */ /** * @fileoverview Generating JavaScript for math blocks. * @author q.neutron@gmail.com (Quynh Neutron) */ 'use strict'; goog.provide('Blockly.JavaScript.math'); goog.require('Blockly.JavaScript'); Blockly.JavaScript['math_number'] = function(block) { // Numeric value. var code = Number(block.getFieldValue('NUM')); var order = code >= 0 ? Blockly.JavaScript.ORDER_ATOMIC : Blockly.JavaScript.ORDER_UNARY_NEGATION; return [code, order]; }; Blockly.JavaScript['math_integer'] = function(block) { // Numeric value. var code = Number(block.getFieldValue('NUM')); var order = code >= 0 ? Blockly.JavaScript.ORDER_ATOMIC : Blockly.JavaScript.ORDER_UNARY_NEGATION; return [code, order]; }; Blockly.JavaScript['math_whole_number'] = function(block) { // Numeric value. var code = Number(block.getFieldValue('NUM')); var order = code >= 0 ? Blockly.JavaScript.ORDER_ATOMIC : Blockly.JavaScript.ORDER_UNARY_NEGATION; return [code, order]; }; Blockly.JavaScript['math_positive_number'] = function(block) { // Numeric value. var code = Number(block.getFieldValue('NUM')); var order = code >= 0 ? Blockly.JavaScript.ORDER_ATOMIC : Blockly.JavaScript.ORDER_UNARY_NEGATION; return [code, order]; }; Blockly.JavaScript['math_arithmetic'] = function(block) { // Basic arithmetic operators, and power. var OPERATORS = { 'ADD': [' + ', Blockly.JavaScript.ORDER_ADDITION], 'MINUS': [' - ', Blockly.JavaScript.ORDER_SUBTRACTION], 'MULTIPLY': [' * ', Blockly.JavaScript.ORDER_MULTIPLICATION], 'DIVIDE': [' / ', Blockly.JavaScript.ORDER_DIVISION], 'POWER': [null, Blockly.JavaScript.ORDER_COMMA] // Handle power separately. }; var tuple = OPERATORS[block.getFieldValue('OP')]; var operator = tuple[0]; var order = tuple[1]; var argument0 = Blockly.JavaScript.valueToCode(block, 'A', order) || '0'; var argument1 = Blockly.JavaScript.valueToCode(block, 'B', order) || '0'; var code; // Power in JavaScript requires a special case since it has no operator. if (!operator) { code = 'Math.pow(' + argument0 + ', ' + argument1 + ')'; return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]; } code = argument0 + operator + argument1; return [code, order]; }; Blockly.JavaScript['math_single'] = function(block) { // Math operators with single operand. var operator = block.getFieldValue('OP'); var code; var arg; if (operator == 'NEG') { // Negation is a special case given its different operator precedence. arg = Blockly.JavaScript.valueToCode(block, 'NUM', Blockly.JavaScript.ORDER_UNARY_NEGATION) || '0'; if (arg[0] == '-') { // --3 is not legal in JS. arg = ' ' + arg; } code = '-' + arg; return [code, Blockly.JavaScript.ORDER_UNARY_NEGATION]; } if (operator == 'SIN' || operator == 'COS' || operator == 'TAN') { arg = Blockly.JavaScript.valueToCode(block, 'NUM', Blockly.JavaScript.ORDER_DIVISION) || '0'; } else { arg = Blockly.JavaScript.valueToCode(block, 'NUM', Blockly.JavaScript.ORDER_NONE) || '0'; } // First, handle cases which generate values that don't need parentheses // wrapping the code. switch (operator) { case 'ABS': code = 'Math.abs(' + arg + ')'; break; case 'ROOT': code = 'Math.sqrt(' + arg + ')'; break; case 'LN': code = 'Math.log(' + arg + ')'; break; case 'EXP': code = 'Math.exp(' + arg + ')'; break; case 'POW10': code = 'Math.pow(10,' + arg + ')'; break; case 'ROUND': code = 'Math.round(' + arg + ')'; break; case 'ROUNDUP': code = 'Math.ceil(' + arg + ')'; break; case 'ROUNDDOWN': code = 'Math.floor(' + arg + ')'; break; case 'SIN': code = 'Math.sin(' + arg + ' / 180 * Math.PI)'; break; case 'COS': code = 'Math.cos(' + arg + ' / 180 * Math.PI)'; break; case 'TAN': code = 'Math.tan(' + arg + ' / 180 * Math.PI)'; break; } if (code) { return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]; } // Second, handle cases which generate values that may need parentheses // wrapping the code. switch (operator) { case 'LOG10': code = 'Math.log(' + arg + ') / Math.log(10)'; break; case 'ASIN': code = 'Math.asin(' + arg + ') / Math.PI * 180'; break; case 'ACOS': code = 'Math.acos(' + arg + ') / Math.PI * 180'; break; case 'ATAN': code = 'Math.atan(' + arg + ') / Math.PI * 180'; break; default: throw Error('Unknown math operator: ' + operator); } return [code, Blockly.JavaScript.ORDER_DIVISION]; }; Blockly.JavaScript['math_constant'] = function(block) { // Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY. var CONSTANTS = { 'PI': ['Math.PI', Blockly.JavaScript.ORDER_MEMBER], 'E': ['Math.E', Blockly.JavaScript.ORDER_MEMBER], 'GOLDEN_RATIO': ['(1 + Math.sqrt(5)) / 2', Blockly.JavaScript.ORDER_DIVISION], 'SQRT2': ['Math.SQRT2', Blockly.JavaScript.ORDER_MEMBER], 'SQRT1_2': ['Math.SQRT1_2', Blockly.JavaScript.ORDER_MEMBER], 'INFINITY': ['Infinity', Blockly.JavaScript.ORDER_ATOMIC] }; return CONSTANTS[block.getFieldValue('CONSTANT')]; }; Blockly.JavaScript['math_number_property'] = function(block) { // Check if a number is even, odd, prime, whole, positive, or negative // or if it is divisible by certain number. Returns true or false. var number_to_check = Blockly.JavaScript.valueToCode(block, 'NUMBER_TO_CHECK', Blockly.JavaScript.ORDER_MODULUS) || '0'; var dropdown_property = block.getFieldValue('PROPERTY'); var code; if (dropdown_property == 'PRIME') { // Prime is a special case as it is not a one-liner test. var functionName = Blockly.JavaScript.provideFunction_( 'mathIsPrime', ['function ' + Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(n) {', ' // https://en.wikipedia.org/wiki/Primality_test#Naive_methods', ' if (n == 2 || n == 3) {', ' return true;', ' }', ' // False if n is NaN, negative, is 1, or not whole.', ' // And false if n is divisible by 2 or 3.', ' if (isNaN(n) || n <= 1 || n % 1 != 0 || n % 2 == 0 ||' + ' n % 3 == 0) {', ' return false;', ' }', ' // Check all the numbers of form 6k +/- 1, up to sqrt(n).', ' for (var x = 6; x <= Math.sqrt(n) + 1; x += 6) {', ' if (n % (x - 1) == 0 || n % (x + 1) == 0) {', ' return false;', ' }', ' }', ' return true;', '}']); code = functionName + '(' + number_to_check + ')'; return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]; } switch (dropdown_property) { case 'EVEN': code = number_to_check + ' % 2 == 0'; break; case 'ODD': code = number_to_check + ' % 2 == 1'; break; case 'WHOLE': code = number_to_check + ' % 1 == 0'; break; case 'POSITIVE': code = number_to_check + ' > 0'; break; case 'NEGATIVE': code = number_to_check + ' < 0'; break; case 'DIVISIBLE_BY': var divisor = Blockly.JavaScript.valueToCode(block, 'DIVISOR', Blockly.JavaScript.ORDER_MODULUS) || '0'; code = number_to_check + ' % ' + divisor + ' == 0'; break; } return [code, Blockly.JavaScript.ORDER_EQUALITY]; }; Blockly.JavaScript['math_change'] = function(block) { // Add to a variable in place. var argument0 = Blockly.JavaScript.valueToCode(block, 'DELTA', Blockly.JavaScript.ORDER_ADDITION) || '0'; var varName = Blockly.JavaScript.variableDB_.getName( block.getFieldValue('VAR'), Blockly.VARIABLE_CATEGORY_NAME); return varName + ' = (typeof ' + varName + ' == \'number\' ? ' + varName + ' : 0) + ' + argument0 + ';\n'; }; // Rounding functions have a single operand. Blockly.JavaScript['math_round'] = Blockly.JavaScript['math_single']; // Trigonometry functions have a single operand. Blockly.JavaScript['math_trig'] = Blockly.JavaScript['math_single']; Blockly.JavaScript['math_on_list'] = function(block) { // Math functions for lists. var func = block.getFieldValue('OP'); var list, code; switch (func) { case 'SUM': list = Blockly.JavaScript.valueToCode(block, 'LIST', Blockly.JavaScript.ORDER_MEMBER) || '[]'; code = list + '.reduce(function(x, y) {return x + y;})'; break; case 'MIN': list = Blockly.JavaScript.valueToCode(block, 'LIST', Blockly.JavaScript.ORDER_COMMA) || '[]'; code = 'Math.min.apply(null, ' + list + ')'; break; case 'MAX': list = Blockly.JavaScript.valueToCode(block, 'LIST', Blockly.JavaScript.ORDER_COMMA) || '[]'; code = 'Math.max.apply(null, ' + list + ')'; break; case 'AVERAGE': // mathMean([null,null,1,3]) == 2.0. var functionName = Blockly.JavaScript.provideFunction_( 'mathMean', ['function ' + Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(myList) {', ' return myList.reduce(function(x, y) {return x + y;}) / ' + 'myList.length;', '}']); list = Blockly.JavaScript.valueToCode(block, 'LIST', Blockly.JavaScript.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; break; case 'MEDIAN': // mathMedian([null,null,1,3]) == 2.0. var functionName = Blockly.JavaScript.provideFunction_( 'mathMedian', ['function ' + Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(myList) {', ' var localList = myList.filter(function (x) ' + '{return typeof x == \'number\';});', ' if (!localList.length) return null;', ' localList.sort(function(a, b) {return b - a;});', ' if (localList.length % 2 == 0) {', ' return (localList[localList.length / 2 - 1] + ' + 'localList[localList.length / 2]) / 2;', ' } else {', ' return localList[(localList.length - 1) / 2];', ' }', '}']); list = Blockly.JavaScript.valueToCode(block, 'LIST', Blockly.JavaScript.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; break; case 'MODE': // As a list of numbers can contain more than one mode, // the returned result is provided as an array. // Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1]. var functionName = Blockly.JavaScript.provideFunction_( 'mathModes', ['function ' + Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(values) {', ' var modes = [];', ' var counts = [];', ' var maxCount = 0;', ' for (var i = 0; i < values.length; i++) {', ' var value = values[i];', ' var found = false;', ' var thisCount;', ' for (var j = 0; j < counts.length; j++) {', ' if (counts[j][0] === value) {', ' thisCount = ++counts[j][1];', ' found = true;', ' break;', ' }', ' }', ' if (!found) {', ' counts.push([value, 1]);', ' thisCount = 1;', ' }', ' maxCount = Math.max(thisCount, maxCount);', ' }', ' for (var j = 0; j < counts.length; j++) {', ' if (counts[j][1] == maxCount) {', ' modes.push(counts[j][0]);', ' }', ' }', ' return modes;', '}']); list = Blockly.JavaScript.valueToCode(block, 'LIST', Blockly.JavaScript.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; break; case 'STD_DEV': var functionName = Blockly.JavaScript.provideFunction_( 'mathStandardDeviation', ['function ' + Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(numbers) {', ' var n = numbers.length;', ' if (!n) return null;', ' var mean = numbers.reduce(function(x, y) {return x + y;}) / n;', ' var variance = 0;', ' for (var j = 0; j < n; j++) {', ' variance += Math.pow(numbers[j] - mean, 2);', ' }', ' variance = variance / n;', ' return Math.sqrt(variance);', '}']); list = Blockly.JavaScript.valueToCode(block, 'LIST', Blockly.JavaScript.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; break; case 'RANDOM': var functionName = Blockly.JavaScript.provideFunction_( 'mathRandomList', ['function ' + Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(list) {', ' var x = Math.floor(Math.random() * list.length);', ' return list[x];', '}']); list = Blockly.JavaScript.valueToCode(block, 'LIST', Blockly.JavaScript.ORDER_NONE) || '[]'; code = functionName + '(' + list + ')'; break; default: throw Error('Unknown operator: ' + func); } return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]; }; Blockly.JavaScript['math_modulo'] = function(block) { // Remainder computation. var argument0 = Blockly.JavaScript.valueToCode(block, 'DIVIDEND', Blockly.JavaScript.ORDER_MODULUS) || '0'; var argument1 = Blockly.JavaScript.valueToCode(block, 'DIVISOR', Blockly.JavaScript.ORDER_MODULUS) || '0'; var code = argument0 + ' % ' + argument1; return [code, Blockly.JavaScript.ORDER_MODULUS]; }; Blockly.JavaScript['math_constrain'] = function(block) { // Constrain a number between two limits. var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE', Blockly.JavaScript.ORDER_COMMA) || '0'; var argument1 = Blockly.JavaScript.valueToCode(block, 'LOW', Blockly.JavaScript.ORDER_COMMA) || '0'; var argument2 = Blockly.JavaScript.valueToCode(block, 'HIGH', Blockly.JavaScript.ORDER_COMMA) || 'Infinity'; var code = 'Math.min(Math.max(' + argument0 + ', ' + argument1 + '), ' + argument2 + ')'; return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]; }; Blockly.JavaScript['math_random_int'] = function(block) { // Random integer between [X] and [Y]. var argument0 = Blockly.JavaScript.valueToCode(block, 'FROM', Blockly.JavaScript.ORDER_COMMA) || '0'; var argument1 = Blockly.JavaScript.valueToCode(block, 'TO', Blockly.JavaScript.ORDER_COMMA) || '0'; var functionName = Blockly.JavaScript.provideFunction_( 'mathRandomInt', ['function ' + Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(a, b) {', ' if (a > b) {', ' // Swap a and b to ensure a is smaller.', ' var c = a;', ' a = b;', ' b = c;', ' }', ' return Math.floor(Math.random() * (b - a + 1) + a);', '}']); var code = functionName + '(' + argument0 + ', ' + argument1 + ')'; return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]; }; Blockly.JavaScript['math_random_float'] = function(block) { // Random fraction between 0 and 1. return ['Math.random()', Blockly.JavaScript.ORDER_FUNCTION_CALL]; }; Blockly.JavaScript['math_atan2'] = function(block) { // Arctangent of point (X, Y) in degrees from -180 to 180. var argument0 = Blockly.JavaScript.valueToCode(block, 'X', Blockly.JavaScript.ORDER_COMMA) || '0'; var argument1 = Blockly.JavaScript.valueToCode(block, 'Y', Blockly.JavaScript.ORDER_COMMA) || '0'; return ['Math.atan2(' + argument1 + ', ' + argument0 + ') / Math.PI * 180', Blockly.JavaScript.ORDER_DIVISION]; };
Ext.define('AM.model.User', { extend: 'Ext.data.Model', fields: ['name', 'email'] });
import { createElement } from 'lwc'; import Container from 'x/container'; // synthetic shadow can't do this kind of style encapsulation if (process.env.DISABLE_SYNTHETIC === true) { describe('Light DOM styling with :host', () => { it(':host can style a containing shadow component', () => { const elm = createElement('x-container', { is: Container }); document.body.appendChild(elm); expect(elm.shadowRoot).not.toBeNull(); expect(getComputedStyle(elm).backgroundColor).toEqual('rgb(139, 69, 19)'); }); }); }
const {Rule} = require('../src') describe('child rules', () => { // --- ALL --- test('all() rules - single failure', async () => { const rule = Rule.string().all([ Rule.string() .regex(/^[A-Z]/) .error('Must start with an uppercase character'), Rule.string() .regex(/[a-z]+/) .error('Must follow with lowercase characters') ]) await expect(rule.validate('Sanity')).resolves.toMatchSnapshot('all() rules - match') await expect(rule.validate('moop')).resolves.toMatchSnapshot( 'all() rules - single failure, custom message' ) }) test('all() rules - multiple failures', async () => { const rule = Rule.string().all([ Rule.string() .regex(/^[A-Z]/) .error('Must start with an uppercase character'), Rule.string() .min(5) .error('5 chars or more'), Rule.string() .regex(/[a-z]+/) .error('Must follow with lowercase characters') ]) await expect(rule.validate('Sanity')).resolves.toMatchSnapshot('all() rules - match') await expect(rule.validate('moop')).resolves.toMatchSnapshot( 'all() rules - multiple failures, custom messages' ) }) test('all() rules - single failure, custom, common error', async () => { const rule = Rule.string() .all([Rule.string().regex(/^[A-Z]/), Rule.string().regex(/[a-z]+/)]) .error('Needs to start with a capital letter and then follow with lowercase characters') await expect(rule.validate('moop')).resolves.toMatchSnapshot('all() rules - single failure, common error') }) test('all() rules - single failure, custom, common error', async () => { const rule = Rule.string() .all([Rule.string().regex(/^[A-Z]/), Rule.string().min(5), Rule.string().regex(/[a-z]+/)]) .error('Needs to be a capital letter followed by at least 4 lowercase characters') await expect(rule.validate('moop')).resolves.toMatchSnapshot( 'all() rules - multiple failures, common error' ) }) // --- EITHER --- test('either() rules - single failure', async () => { const rule = Rule.string().either([ Rule.string() .regex(/^rgb(\d+,\s*\d+,\s*\d+)$/) .error('Must be rgb(num, num, num) format'), Rule.string() .regex(/^#([a-f0-9]{3}|[a-f0-9]{6})$/) .error('Must be hex color with #-prefix') ]) await expect(rule.validate('rgb(16, 22, 133)')).resolves.toMatchSnapshot('either() rules - match') await expect(rule.validate('#bf')).resolves.toMatchSnapshot( 'either() rules - single failure, custom message' ) }) test('either() rules - all matches', async () => { const rule = Rule.string().either([ Rule.string() .regex(/^R/) .error('Must start with a capital R'), Rule.string() .regex(/ed$/) .error('Must end with "ed"') ]) await expect(rule.validate('Red')).resolves.toMatchSnapshot('either() rules - all match') await expect(rule.validate('nope')).resolves.toMatchSnapshot('either() rules - no matches') }) test('either() rules - all fail, custom, common error', async () => { const rule = Rule.string() .either([Rule.string().regex(/^[A-Z]/), Rule.string().regex(/^i[A-Z]/)]) .error("Needs to start with a capital letter, unless it's an iProduct") await expect(rule.validate('mopatis!')).resolves.toMatchSnapshot( 'either() rules - all fail, common error' ) }) })
function calcDiagonalsSums(matrix) { let mainDiagonal = 0; let secondaryDiagonal = 0; for (let row = 0; row < matrix.length; row++) { mainDiagonal += matrix[row][row]; secondaryDiagonal += matrix[row][matrix.length - 1 - row]; } console.log(mainDiagonal + ' ' + secondaryDiagonal); } calcDiagonalsSums([[3, 5, 17], [-1, 7, 14], [1, -8, 89]] )
/* * BSD LICENSE * * Copyright(c) 2020-2021 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MOCK_CAP_H_ #define MOCK_CAP_H_ #include "pqos.h" int __wrap__pqos_check_init(const int expect); void __wrap__pqos_api_lock(void); void __wrap__pqos_api_unlock(void); void __wrap__pqos_cap_get(const struct pqos_cap **cap, const struct pqos_cpuinfo **cpu); void __wrap__pqos_cap_l3cdp_change(const enum pqos_cdp_config cdp); void __wrap__pqos_cap_l2cdp_change(const enum pqos_cdp_config cdp); void __wrap__pqos_cap_mba_change(const enum pqos_mba_config cfg); #endif /* MOCK_CAP_H_ */
import { Helmet } from "react-helmet"; import PageBody from "../components/PageBody"; export default function NotFound() { return ( <PageBody> <Helmet> <title>404: Not Found</title> </Helmet> <h1>404: Not Found</h1> </PageBody> ); }
import {STORAGE_KEY} from './mutations'; const localStoragePlugin = store => { store.subscribe((mutation, {user}) => { window.localStorage.setItem(STORAGE_KEY, JSON.stringify(user)); }); }; export default [localStoragePlugin];
var express = require('express'); var app = express(); app.use(express.static(__dirname + '/public')); app.listen(process.env.PORT || 3000);
import os import sys import django from django.conf import settings if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'travis_ci_test', 'USER': 'postgres' if os.getenv('CI', False) else '', } }, ROOT_URLCONF='boundaries.urls', INSTALLED_APPS=( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.sessions', 'django.contrib.messages', 'boundaries', ), MIDDLEWARE=[ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ], TEMPLATES=[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ], ) django.setup() if __name__ == '__main__': from django.test.runner import DiscoverRunner runner = DiscoverRunner(failfast=False) failures = runner.run_tests(['boundaries']) sys.exit(failures)
# # 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. """ Stochastic weight handler This weight handler differs from the default weight handler by giving every pool a chance to be chosen where the probability is proportional to each pools' weight. """ import random from cinder.scheduler import base_weight from cinder.scheduler import weights as wts class StochasticHostWeightHandler(base_weight.BaseWeightHandler): def __init__(self, namespace): super(StochasticHostWeightHandler, self).__init__(wts.BaseHostWeigher, namespace) def get_weighed_objects(self, weigher_classes, obj_list, weighing_properties): # The normalization performed in the superclass is nonlinear, which # messes up the probabilities, so override it. The probabilistic # approach we use here is self-normalizing. # Also, the sorting done by the parent implementation is harmless but # useless for us. # Compute the object weights as the parent would but without sorting # or normalization. weighed_objs = [wts.WeighedHost(obj, 0.0) for obj in obj_list] for weigher_cls in weigher_classes: weigher = weigher_cls() weights = weigher.weigh_objects(weighed_objs, weighing_properties) for i, weight in enumerate(weights): obj = weighed_objs[i] obj.weight += weigher.weight_multiplier() * weight # Avoid processing empty lists if not weighed_objs: return [] # First compute the total weight of all the objects and the upper # bound for each object to "win" the lottery. total_weight = 0 table = [] for weighed_obj in weighed_objs: total_weight += weighed_obj.weight max_value = total_weight table.append((max_value, weighed_obj)) # Now draw a random value with the computed range winning_value = random.random() * total_weight # Scan the table to find the first object with a maximum higher than # the random number. Save the index of the winner. winning_index = 0 for (i, (max_value, weighed_obj)) in enumerate(table): if max_value > winning_value: # Return a single element array with the winner. winning_index = i break # It's theoretically possible for the above loop to terminate with no # winner. This happens when winning_value >= total_weight, which # could only occur with very large numbers and floating point # rounding. In those cases the actual winner should have been the # last element, so return it. return weighed_objs[winning_index:] + weighed_objs[0:winning_index]
#include "ble.h" #include <stdio.h> #include <string.h> int ble_adv_set_txpower(BLE_TX_Power_t power) { return command(DRIVER_RADIO, BLE_CFG_TX_POWER, power); } int ble_adv_set_interval(uint16_t interval) { return command(DRIVER_RADIO, BLE_CFG_ADV_INTERVAL, interval); } int ble_adv_data(uint8_t type, const unsigned char *data, uint8_t len) { return allow(DRIVER_RADIO, type, (void*)data, len); } int ble_adv_clear_data(void){ return command(DRIVER_RADIO, BLE_ADV_CLEAR_DATA, 1); } int ble_adv_start(BLE_Gap_Mode_t mode) { return command(DRIVER_RADIO, BLE_ADV_START, mode); } int ble_adv_scan(const unsigned char *data, uint8_t len, subscribe_cb callback) { int err; err = subscribe(DRIVER_RADIO, BLE_SCAN_CALLBACK, callback, NULL); if (err < TOCK_SUCCESS) return err; err = allow(DRIVER_RADIO, BLE_CFG_SCAN_BUF, (void*)data, len); if (err < TOCK_SUCCESS) return err; return command(DRIVER_RADIO, BLE_SCAN, 1); } int ble_adv_stop(void) { return command(DRIVER_RADIO, BLE_ADV_STOP, 1); } int ble_adv_set_address(const unsigned char *data, uint8_t len) { return allow(DRIVER_RADIO, BLE_CFG_ADV_ADDR, (void*)data, len); }
from django.db import models class Subject(models.Model): subject_code = models.CharField(max_length=10) name = models.CharField(max_length=100) slug = models.SlugField(max_length=150, blank=True, null=True) description = models.TextField(blank=True, null=True) profile = models.URLField(blank=True, null=True) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'subjects' def __str__(self) -> str: return self.name
/** * @file lv_test_slider.h * */ #ifndef LV_TEST_SLIDER_H #define LV_TEST_SLIDER_H #ifdef __cplusplus extern "C" { #endif /********************* * INCLUDES *********************/ #include "../../../../lv_ex_conf.h" #include "../../../../lvgl/lvgl.h" #if USE_LV_SLIDER && USE_LV_TESTS /********************* * DEFINES *********************/ /********************** * TYPEDEFS **********************/ /********************** * GLOBAL PROTOTYPES **********************/ /** * Create sliders to test their functionalities */ void lv_test_slider_1(void); /********************** * MACROS **********************/ #endif /*USE_LV_SLIDER*/ #ifdef __cplusplus } /* extern "C" */ #endif #endif /*USE_LV_SLIDER && USE_LV_TESTS*/
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems */ /* */ /* 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. */ /* -------------------------------------------------------------------------- */ define(function(require) { var Locale = require('utils/locale'); var Buttons = { "Service.refresh" : { type: "action", layout: "refresh", alwaysActive: true }, "Service.update_dialog" : { type: "action", text: Locale.tr("Update"), layout: "main", }, "Service.create_dialog" : { type: "action", layout: "create", alwaysActive: true }, "Service.chown" : { type: "confirm_with_select", text: Locale.tr("Change owner"), select: "User", tip: Locale.tr("Select the new owner"), layout: "user_select" }, "Service.chgrp" : { type: "confirm_with_select", text: Locale.tr("Change group"), select: "Group", tip: Locale.tr("Select the new group"), layout: "user_select" }, "Service.recover" : { type: "action", text: Locale.tr("Recover"), layout: "vmsplanification_buttons", }, "Service.recover_delete" : { type: "action", text: Locale.tr("Recover") + ' <span class="label secondary radius">' + Locale.tr("delete") + '</span>', layout: "vmsplanification_buttons", }, "Service.shutdown" : { type: "confirm", text: Locale.tr("Terminate"), layout: "vmsdelete_buttons", tip: Locale.tr("This will remove information from non-persistent hard disks") }, "Service.delete" : { type: "confirm", text: Locale.tr("Delete"), layout: "vmsdelete_buttons", tip: Locale.tr("This will delete the selected services") }, "Service.edit_labels" : { layout: "labels", } }; return Buttons; });