exposure.Rmd
A data frame of the instruments for an exposure is required. Each line has the information for one variant for one exposure. The minimum information required for MR analysis is the following:
SNP
- rs IDbeta
- The effect size. If the trait is binary then log(OR) should be usedse
- The standard error of the effect sizeeffect_allele
- The allele of the SNP which has the effect marked in beta
Other information that is useful for MR can also be provided:
other_allele
- The non-effect alleleeaf
- The effect allele frequencyPhenotype
- The name of the phenotype for which the SNP has an effectYou can also provide the following extra information:
chr
- Physical position of variant (chromosome)position
- Physical position of variant (position)samplesize
- Sample size for estimating the effect sizencase
- Number of casesncontrol
- Number of controlspval
- The P-value for the SNP’s association with the exposureunits
- The units in which the effects are presentedgene
- The gene or other annotation for the the SNPThe data can be read in from a text file using the read_exposure_data
function. The file must have a header with column names corresponding to the columns described above.
An example of a text file with the default column names is provided as part of the package, the first few rows look like this:
Phenotype SNP beta se effect_allele other_allele eaf pval units gene samplesize
BMI rs10767664 0.19 0.0306122448979592 A T 0.78 5e-26 kg/m2 BDNF 225238
BMI rs13078807 0.1 0.0204081632653061 G A 0.2 4e-11 kg/m2 CADM2 221431
BMI rs1514175 0.07 0.0204081632653061 A G 0.43 8e-14 kg/m2 TNNI3K 207641
BMI rs1558902 0.39 0.0204081632653061 A T 0.42 5e-120 kg/m2 FTO 222476
BMI rs10968576 0.11 0.0204081632653061 G A 0.31 3e-13 kg/m2 LRRN6C 247166
BMI rs2241423 0.13 0.0204081632653061 G A 0.78 1e-18 kg/m2 LBXCOR1 227886
The exact path to the file will be different on everyone’s computer, but it can be located like this:
bmi_file <- system.file("extdata", "bmi.txt", package="TwoSampleMR")
You can read the data in like this:
bmi_exp_dat <- read_exposure_data(bmi_file)
head(bmi_exp_dat)
#> SNP beta.exposure se.exposure effect_allele.exposure
#> 1 rs10767664 0.19 0.03061224 A
#> 2 rs13078807 0.10 0.02040816 G
#> 3 rs1514175 0.07 0.02040816 A
#> 4 rs1558902 0.39 0.02040816 A
#> 5 rs10968576 0.11 0.02040816 G
#> 6 rs2241423 0.13 0.02040816 G
#> other_allele.exposure eaf.exposure pval.exposure units.exposure gene.exposure
#> 1 T 0.78 5e-26 kg/m2 BDNF
#> 2 A 0.20 4e-11 kg/m2 CADM2
#> 3 G 0.43 8e-14 kg/m2 TNNI3K
#> 4 T 0.42 5e-120 kg/m2 FTO
#> 5 A 0.31 3e-13 kg/m2 LRRN6C
#> 6 A 0.78 1e-18 kg/m2 LBXCOR1
#> samplesize.exposure exposure mr_keep.exposure pval_origin.exposure
#> 1 225238 BMI TRUE reported
#> 2 221431 BMI TRUE reported
#> 3 207641 BMI TRUE reported
#> 4 222476 BMI TRUE reported
#> 5 247166 BMI TRUE reported
#> 6 227886 BMI TRUE reported
#> units.exposure_dat id.exposure data_source.exposure
#> 1 kg/m2 0gxFqy textfile
#> 2 kg/m2 0gxFqy textfile
#> 3 kg/m2 0gxFqy textfile
#> 4 kg/m2 0gxFqy textfile
#> 5 kg/m2 0gxFqy textfile
#> 6 kg/m2 0gxFqy textfile
The output from this function is a new data frame with standardised column names:
SNP
exposure
beta.exposure
se.exposure
effect_allele.exposure
other_allele.exposure
eaf.exposure
mr_keep.exposure
pval.exposure
pval_origin.exposure
id.exposure
data_source.exposure
units.exposure
gene.exposure
samplesize.exposure
The function attempts to match the columns to the ones it expects. It also checks that the data type is as expected.
If the required data for MR to be performed is not present (SNP name, effect size, standard error, effect allele) for a particular SNP, then the column mr_keep.exposure
will be FALSE
.
If the text file does not have default column names, this can still be read in as follows. Here are the first few rows of an example:
rsid,effect,SE,a1,a2,a1_freq,p-value,Units,Gene,n
rs10767664,0.19,0.030612245,A,T,0.78,5.00E-26,kg/m2,BDNF,225238
rs13078807,0.1,0.020408163,G,A,0.2,4.00E-11,kg/m2,CADM2,221431
rs1514175,0.07,0.020408163,A,G,0.43,8.00E-14,kg/m2,TNNI3K,207641
rs1558902,0.39,0.020408163,A,T,0.42,5.00E-120,kg/m2,FTO,222476
Note that this is a CSV file, with commas separating fields. The file is located here:
bmi2_file <- system.file("extdata/bmi.csv", package="TwoSampleMR")
To read in this data:
bmi_exp_dat <- read_exposure_data(
filename = bmi2_file,
sep = ",",
snp_col = "rsid",
beta_col = "effect",
se_col = "SE",
effect_allele_col = "a1",
other_allele_col = "a2",
eaf_col = "a1_freq",
pval_col = "p-value",
units_col = "Units",
gene_col = "Gene",
samplesize_col = "n"
)
#> No phenotype name specified, defaulting to 'exposure'.
head(bmi_exp_dat)
#> SNP beta.exposure se.exposure effect_allele.exposure
#> 1 rs10767664 0.19 0.03061224 A
#> 2 rs13078807 0.10 0.02040816 G
#> 3 rs1514175 0.07 0.02040816 A
#> 4 rs1558902 0.39 0.02040816 A
#> 5 rs10968576 0.11 0.02040816 G
#> 6 rs2241423 0.13 0.02040816 G
#> other_allele.exposure eaf.exposure pval.exposure units.exposure gene.exposure
#> 1 T 0.78 5e-26 kg/m2 BDNF
#> 2 A 0.20 4e-11 kg/m2 CADM2
#> 3 G 0.43 8e-14 kg/m2 TNNI3K
#> 4 T 0.42 5e-120 kg/m2 FTO
#> 5 A 0.31 3e-13 kg/m2 LRRN6C
#> 6 A 0.78 1e-18 kg/m2 LBXCOR1
#> samplesize.exposure exposure mr_keep.exposure pval_origin.exposure
#> 1 225238 exposure TRUE reported
#> 2 221431 exposure TRUE reported
#> 3 207641 exposure TRUE reported
#> 4 222476 exposure TRUE reported
#> 5 247166 exposure TRUE reported
#> 6 227886 exposure TRUE reported
#> units.exposure_dat id.exposure data_source.exposure
#> 1 kg/m2 UVOe6Z textfile
#> 2 kg/m2 UVOe6Z textfile
#> 3 kg/m2 UVOe6Z textfile
#> 4 kg/m2 UVOe6Z textfile
#> 5 kg/m2 UVOe6Z textfile
#> 6 kg/m2 UVOe6Z textfile
If the Phenotype
column is not provided (as is the case in this example) then it will assume that the phenotype’s name is simply “exposure.” This is entered in the exposure
column. It can be renamed manually:
bmi_exp_dat$exposure <- "BMI"
If the data already exists as a data frame in R then it can be converted into the correct format using the format_data
function. For example, here is some randomly created data:
random_df <- data.frame(
SNP = c("rs1", "rs2"),
beta = c(1, 2),
se = c(1, 2),
effect_allele = c("A", "T")
)
random_df
#> SNP beta se effect_allele
#> 1 rs1 1 1 A
#> 2 rs2 2 2 T
This can be formatted like so:
random_exp_dat <- format_data(random_df, type="exposure")
#> No phenotype name specified, defaulting to 'exposure'.
#> Warning in format_data(random_df, type = "exposure"): The following columns are not present but are helpful for harmonisation
#> other_alleleeaf
#> Inferring p-values
random_exp_dat
#> SNP beta.exposure se.exposure effect_allele.exposure exposure
#> 1 rs1 1 1 A exposure
#> 2 rs2 2 2 T exposure
#> mr_keep.exposure pval.exposure pval_origin.exposure id.exposure
#> 1 TRUE 0.3173105 inferred TNE0QT
#> 2 TRUE 0.3173105 inferred TNE0QT
#> other_allele.exposure eaf.exposure
#> 1 NA NA
#> 2 NA NA
A number of sources of instruments have already been curated and are available for use. They are provided as data objects in the MRInstruments
package. To install:
devtools::install_github("MRCIEU/MRInstruments")
This package contains a number of data.frames, each of which is a repository of SNP-trait associations. How to access the data frames is detailed below:
The NHGRI-EBI GWAS catalog contains a catalog of significant associations obtained from GWASs. This version of the data is filtered and harmonised to contain associations that have the required data to perform MR, to ensure that the units used to report effect sizes from a particular study are all the same, and other data cleaning operations.
To use the GWAS catalog:
library(MRInstruments)
data(gwas_catalog)
head(gwas_catalog)
#> Phenotype_simple
#> 1 Eosinophil percentage of white cells
#> 2 Eosinophil counts
#> 3 Medication use (agents acting on the renin-angiotensin system)
#> 4 Post bronchodilator FEV1
#> 5 DNA methylation variation (age effect)
#> 6 Ankylosing spondylitis
#> MAPPED_TRAIT_EFO
#> 1 eosinophil percentage of leukocytes
#> 2 eosinophil count
#> 3 Agents acting on the renin-angiotensin system use measurement
#> 4 forced expiratory volume, response to bronchodilator
#> 5 DNA methylation
#> 6 ankylosing spondylitis
#> MAPPED_TRAIT_EFO_URI
#> 1 http://www.ebi.ac.uk/efo/EFO_0007991
#> 2 http://www.ebi.ac.uk/efo/EFO_0004842
#> 3 http://www.ebi.ac.uk/efo/EFO_0009931
#> 4 http://www.ebi.ac.uk/efo/EFO_0004314, http://purl.obolibrary.org/obo/GO_0097366
#> 5 http://purl.obolibrary.org/obo/GO_0006306
#> 6 http://www.ebi.ac.uk/efo/EFO_0003898
#> Initial_sample_description
#> 1 172,378 European ancestry individuals
#> 2 172,275 European ancestry individuals
#> 3 62,752 European ancestry cases, 174,778 European ancestry controls
#> 4 10,094 European ancestry current and former smoker individuals, 3,260 African American current and former smoker individuals, 178 current and former smoker individuals
#> 5 Up to 954 individuals
#> 6 921 Turkish ancestry cases, 907 Turkish ancestry controls, 422 Iranian ancestry cases, 754 Iranian ancestry controls
#> Replication_sample_description STUDY.ACCESSION
#> 1 <NA> GCST004600
#> 2 <NA> GCST004606
#> 3 <NA> GCST007930
#> 4 <NA> GCST003262
#> 5 <NA> GCST006660
#> 6 <NA> GCST007844
#> Phenotype Phenotype_info
#> 1 Eosinophil percentage of white cells
#> 2 Eosinophil counts
#> 3 Medication use (agents acting on the renin-angiotensin system)
#> 4 Post bronchodilator FEV1
#> 5 DNA methylation variation (age effect)
#> 6 Ankylosing spondylitis
#> PubmedID Author Year SNP chr bp_ens_GRCh38 Region gene
#> 1 27863252 Astle WJ 2016 rs1000005 21 33060745 21q22.11 AP000282.2
#> 2 27863252 Astle WJ 2016 rs1000005 21 33060745 21q22.11 AP000282.2
#> 3 31015401 Wu Y 2019 rs1000010 3 11562645 3p25.3 VGLL4
#> 4 26634245 Lutz SM 2015 rs10000225 4 144312789 4q31.21 Intergenic
#> 5 30348214 Zhang Q 2018 rs10000513 4 160334994 4q32.1 NR
#> 6 30946743 Li Z 2019 rs10000518 4 11502867 4p15.33 HS3ST1
#> Gene_ens effect_allele other_allele beta se pval
#> 1 AP000282.2,LINC00945 C G -0.02652552 0.003826531 2e-13
#> 2 AP000282.2,LINC00945 C G -0.02481715 0.003571429 7e-12
#> 3 G A -0.03724189 0.006377551 6e-09
#> 4 Intergenic A T -0.04400000 0.009420188 3e-06
#> 5 NR <NA> <NA> NA NA 4e-08
#> 6 G A 0.73396926 NA 6e-06
#> units eaf date_added_to_MRBASE
#> 1 unit decrease 0.589400 2019-08-29
#> 2 unit decrease 0.589400 2019-08-29
#> 3 unit decrease 0.351806 2019-08-29
#> 4 NR unit decrease 0.350000 2019-08-29
#> 5 <NA> NA 2019-08-29
#> 6 <NA> NA 2019-08-29
For example, to obtain instruments for body mass index using the Speliotes et al 2010 study:
bmi_gwas <-
subset(gwas_catalog,
grepl("Speliotes", Author) & Phenotype == "Body mass index")
bmi_exp_dat <- format_data(bmi_gwas)
Independent top hits from GWASs on 121 metabolites in whole blood are stored in the metab_qtls
data object. Use ?metab_qtls
to get more information.
data(metab_qtls)
head(metab_qtls)
#> phenotype chromosome position SNP effect_allele other_allele eaf
#> 1 AcAce 8 9181395 rs2169387 G A 0.870251
#> 2 AcAce 11 116648917 rs964184 C G 0.857715
#> 3 Ace 6 12042473 rs6933521 C T 0.120256
#> 4 Ala 2 27730940 rs1260326 C T 0.638817
#> 5 Ala 2 65220910 rs2160387 C T 0.403170
#> 6 Ala 12 47201814 rs4554975 G A 0.644059
#> beta se pval n_studies n
#> 1 0.085630 0.015451 3.61e-08 11 19257
#> 2 -0.096027 0.014624 6.71e-11 11 19261
#> 3 -0.091667 0.015885 8.10e-09 14 24742
#> 4 -0.104582 0.009940 7.40e-26 13 22569
#> 5 -0.071001 0.009603 1.49e-13 14 24793
#> 6 -0.069135 0.009598 6.12e-13 14 24792
For example, to obtain instruments for the Alanine:
ala_exp_dat <- format_metab_qtls(subset(metab_qtls, phenotype=="Ala"))
Independent top hits from GWASs on 47 protein levels in whole blood are stored in the proteomic_qtls
data object. Use ?proteomic_qtls
to get more information.
data(proteomic_qtls)
head(proteomic_qtls)
#> analyte chr position SNP gene location annotation other_allele
#> 1 CFHR1 1 196698945 rs12144939 CFH cis missense T
#> 2 IL6r 1 154425456 rs12126142 IL6R cis missense A
#> 3 ApoA4 11 116677723 rs1263167 APOA4 cis intergenic G
#> 4 SELE 9 136149399 rs507666 ABO trans intronic A
#> 5 FetuinA 3 186335941 rs2070633 AHSG cis missense T
#> 6 ACE 17 61566031 rs4343 ACE cis synonymous A
#> effect_allele eaf maf pval beta se
#> 1 G 0.643 0.357 8.99e-143 -1.108 0.04355258
#> 2 G 0.608 0.392 1.81e-106 0.850 0.03878364
#> 3 A 0.803 0.197 2.64e-54 -0.919 0.05922332
#> 4 G 0.809 0.191 1.01e-52 -0.882 0.05771545
#> 5 C 0.676 0.324 2.88e-44 -0.629 0.04506925
#> 6 G 0.508 0.492 6.66e-44 0.493 0.03547679
For example, to obtain instruments for the ApoH protein:
apoh_exp_dat <-
format_proteomic_qtls(subset(proteomic_qtls, analyte == "ApoH"))
#> Warning in format_data(proteomic_qtls_subset, type = type, phenotype_col =
#> "analyte"): effect_allele column is not character data. Coercing...
#> Warning in format_data(proteomic_qtls_subset, type = type, phenotype_col =
#> "analyte"): other_allele column is not character data. Coercing...
Independent top hits from GWASs on 32432 gene identifiers and in 44 tissues are available from the GTEX study in gtex_eqtl
. Use ?gtex_eqtl
to get more information.
data(gtex_eqtl)
head(gtex_eqtl)
#> tissue gene_name gene_start SNP snp_position
#> 1 Adipose Subcutaneous RP4-669L17.10 1:317720 rs2519065 1:787151
#> 2 Adipose Subcutaneous RP11-206L10.1 1:661611 rs11804171 1:723819
#> 3 Adipose Subcutaneous RP11-206L10.3 1:677193 rs149110718 1:759227
#> 4 Adipose Subcutaneous RP11-206L10.2 1:700306 rs148649543 1:752796
#> 5 Adipose Subcutaneous RP11-206L10.9 1:714150 rs12184279 1:717485
#> 6 Adipose Subcutaneous RP11-206L10.8 1:736259 rs10454454 1:754954
#> effect_allele other_allele beta se pval n
#> 1 A G 0.551788 0.0747180 2.14627e-12 298
#> 2 A T -0.917475 0.1150060 4.99967e-14 298
#> 3 T C 0.807571 0.1776530 8.44694e-06 298
#> 4 T C 0.745393 0.0958531 1.82660e-13 298
#> 5 A C 1.927250 0.2247390 9.55098e-16 298
#> 6 A G 1.000400 0.1787470 5.61079e-08 298
For example, to obtain instruments for the IRAK1BP1 gene expression levels in subcutaneous adipose tissue:
irak1bp1_exp_dat <-
format_gtex_eqtl(subset(
gtex_eqtl,
gene_name == "IRAK1BP1" & tissue == "Adipose Subcutaneous"
))
#> Warning in format_data(gtex_eqtl_subset, type = type, phenotype_col = type, : The following columns are not present but are helpful for harmonisation
#> eaf
#> Inferring p-values
Independent top hits from GWASs on 0 DNA methylation levels in whole blood across 5 time points are available from the ARIES study in aries_mqtl
. Use ?aries_mqtl
to get more information.
data(aries_mqtl)
head(aries_mqtl)
#> SNP timepoint cpg beta pval se snp_chr
#> 1 esv2656832 1 cg21826606 0.3459 1.60408e-26 0.03265336 1
#> 2 esv2658098 1 cg22681495 -0.6263 1.55765e-66 0.03643240 15
#> 3 esv2660043 1 cg24276624 -0.5772 3.16370e-26 0.05481823 11
#> 4 esv2660043 1 cg11157765 -0.5423 1.33928e-22 0.05583777 11
#> 5 esv2660673 1 cg05832925 -0.5919 2.88011e-50 0.03982467 11
#> 6 esv2660769 1 cg05859533 -0.6224 1.49085e-58 0.03868158 16
#> snp_pos effect_allele other_allele eaf sex age units
#> 1 25591901 I R 0.3974 mixed Birth SD units
#> 2 86057007 D R 0.2076 mixed Birth SD units
#> 3 69982552 D R 0.1450 mixed Birth SD units
#> 4 69982552 D R 0.1450 mixed Birth SD units
#> 5 74024905 D R 0.1671 mixed Birth SD units
#> 6 57725395 D R 0.2136 mixed Birth SD units
#> island_location cpg_chr cpg_pos gene gene_location cis_trans
#> 1 N_Shore 1 25593055 cis
#> 2 15 86058755 AKAP13 Body cis
#> 3 11 69982941 ANO1 Body cis
#> 4 11 69982996 ANO1 Body cis
#> 5 S_Shelf 11 74026371 cis
#> 6 16 57727230 CCDC135 TSS1500 cis
For example, to obtain instruments for cg25212131 CpG DNA methylation levels in at birth:
cg25212131_exp_dat <-
format_aries_mqtl(subset(aries_mqtl, cpg == "cg25212131" &
age == "Birth"))
The IEU GWAS database contains the entire summary statistics for thousands of GWASs. You can browse them here: https://gwas.mrcieu.ac.uk/
You can use this database to define the instruments for a particular exposure. You can also use this database to obtain the effects for constructing polygenic risk scores using different p-value thresholds.
You can check the status of the API:
ieugwasr::api_status()
#> API: public: http://gwas-api.mrcieu.ac.uk/
#> $`API version`
#> [1] "3.7.4"
#>
#> $Access
#> [1] "public"
#>
#> $`Neo4j status`
#> [1] "Available"
#>
#> $`ElasticSearch status`
#> [1] "Available"
#>
#> $`LD reference panel`
#> [1] "Available"
#>
#> $`1000 genomes annotation VCF`
#> [1] "Available"
#>
#> $`PLINK executable`
#> [1] "Available"
#>
#> $Cromwell
#> [1] "Available"
#>
#> $`Total associations`
#> [1]<PHONE_NUMBER>17
#>
#> $`Total complete datasets`
#> [1] 39791
#>
#> $`Total public datasets`
#> [1] 39604
#>
#> attr(,"class")
#> [1] "ApiStatus"
To obtain a list and details about the available GWASs do the following:
ao <- available_outcomes()
head(ao)
#> # A tibble: 6 x 22
#> id trait group_name year consortium author sex population unit
#> <chr> <chr> <chr> <int> <chr> <chr> <chr> <chr> <chr>
#> 1 ieu-b-~ Number o~ public 2021 MRC-IEU Clare~ Male~ European SD
#> 2 prot-a~ Leptin r~ public 2018 NA Sun BB Male~ European NA
#> 3 prot-a~ Adapter ~ public 2018 NA Sun BB Male~ European NA
#> 4 ukb-e-~ Impedanc~ public 2020 NA Pan-U~ Male~ Greater Midd~ NA
#> 5 prot-a~ Dual spe~ public 2018 NA Sun BB Male~ European NA
#> 6 eqtl-a~ ENSG0000~ public 2018 NA Vosa U Male~ European NA
#> # ... with 13 more variables: sample_size <int>, nsnp <int>, build <chr>,
#> # category <chr>, subcategory <chr>, ontology <chr>, note <chr>, mr <int>,
#> # pmid <int>, priority <int>, ncase <int>, ncontrol <int>, sd <dbl>
For information about authentication see https://github.com/MRCIEU/ieugwasr/blob/master/README.md#authentication.
The available_outcomes
function returns a table of all the available studies in the database. Each study has a unique ID. e.g.
head(subset(ao, select=c(trait, id)))
#> # A tibble: 6 x 2
#> trait id
#> <chr> <chr>
#> 1 Number of children ieu-b-4760
#> 2 Leptin receptor prot-a-1725
#> 3 Adapter molecule crk prot-a-664
#> 4 Impedance of arm (right) ukb-e-23109_MID
#> 5 Dual specificity mitogen-activated protein kinase kinas~ prot-a-1841
#> 6 ENSG00000167699 eqtl-a-ENSG000001676~
To extract instruments for a particular trait using a particular study, for example to obtain SNPs for body mass index using the Locke et al 2015 GIANT study, you specify the study ID as follows:
bmi2014_exp_dat <- extract_instruments(outcomes='ieu-a-2')
This returns a set of LD clumped SNPs that are GWAS significant for BMI. You can specify various parameters for this function:
p1
= P-value threshold for keeping a SNPclump
= Whether or not to return independent SNPs only (default is TRUE
)r2
= The maximum LD R-square allowed between returned SNPskb
= The distance in which to search for LD R-square valuesBy changing changing the p1
parameter it is possible to obtain SNP effects for constructing polygenic risk scores.
For standard two sample MR it is important to ensure that the instruments for the exposure are independent. Once instruments have been identified for an exposure variable, the IEU GWAS database can be used to perform clumping.
You can provide a list of SNP IDs, the SNPs will be extracted from 1000 genomes data, LD calculated between them, and amongst those SNPs that have LD R-square above the specified threshold only the SNP with the lowest P-value will be retained. To do this, use the following command:
bmi_exp_dat <- clump_data(bmi_exp_dat)
#> Please look at vignettes for options on running this locally if you need to run many instances of this command.
#> Clumping UVOe6Z, 30 variants, using EUR population reference
#> Removing 3 of 30 variants due to LD with other variants or absence from LD reference panel
The clump_data
command takes any data frame that has been formatted to be an exposure data type of data frame. Note that for the instruments in the R/MRInstruments package the SNPs are already LD clumped.
Note: The LD reference panel only includes SNPs (no INDELs). There are five super-populations from which LD can be calculated, by default European samples are used. Only SNPs with MAF > 0.01 within-population are available.
NOTE: If a variant is dropped from your unclumped data it could be because it is absent from the reference panel. For more flexibility, including using your own LD reference data, see here: https://mrcieu.github.io/ieugwasr/


--- title: Performance of my stock vs. cpi author: ck date: '2020-01-05' slug: performance-of-my-stock-vs-cpi categories: - stock analysis tags: - analysis - R - quantmod subtitle: '' summary: '' authors: [] lastmod: '2020-01-05T17:18:50Z' featured: no image: caption: '' focal_point: '' preview_only: no projects: [] ---
As a new years resolution, I made a promise to myself to be more conscious about the investments that I’m making. Of the few that I have, I’ve decided to look into the historical performance of one of the funds that I have. I want to compare the stock price increase over time with the overall consumer price for products in the U.S. (using the CPI-U).
quantmod
to see performancequantmod
is an R package that makes it easy for users to track their stock. I’m going to specifically look into VTSAX
which is an index fund managed by vanguard.
library("pacman")
p_load(quantmod, blscrapeR, purrr)
## Installing package into '/home/ck1/R/x86_64-pc-linux-gnu-library/3.6'
## (as 'lib' is unspecified)
## also installing the dependencies 'xts', 'zoo', 'TTR'
##
## quantmod installed
## Installing package into '/home/ck1/R/x86_64-pc-linux-gnu-library/3.6'
## (as 'lib' is unspecified)
##
## blscrapeR installed
getSymbols("VTSAX")
## 'getSymbols' currently uses auto.assign=TRUE by default, but will
## use auto.assign=FALSE in 0.5-0. You will still be able to use
## 'loadSymbols' to automatically load data. getOption("getSymbols.env")
## and getOption("getSymbols.auto.assign") will still be checked for
## alternate defaults.
##
## This message is shown once per session and may be disabled by setting
## options("getSymbols.warning4.0"=FALSE). See ?getSymbols for details.
## [1] "VTSAX"
chartSeries(VTSAX, subset="last 11 years")
addBBands()
addMACD()
The chart shows the stock price from 2010 to 2020. I’m happy to see that the overall stock is increasing over time (albeit some dips here and there). There are many more features to the quantmod
package that allows users to calculate the performance of their stocks (i.e. other measures of trend, volatility, momentum, and volume). I don’t want to complicate this post so I won’t go into the details but feel free to check them out here.
blscrapeR
to access the BLS CPI APIWe’re going to access the Consumer Price Index All Urban Consumers (CPI-U) using the blscrapeR
package (data is based on the Bureau of Labor Statistics (BLS) website).
cpidf <- bls_api("CUSR0000SA0", startyear = 2010, endyear = 2019)
## REQUEST_SUCCEEDED
head(cpidf)
## # A tibble: 6 x 7
## year period periodName latest value footnotes seriesID
## <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 2019 M11 November true 258. "" CUSR0000SA0
## 2 2019 M10 October <NA> 257. "" CUSR0000SA0
## 3 2019 M09 September <NA> 256. "" CUSR0000SA0
## 4 2019 M08 August <NA> 256. "" CUSR0000SA0
## 5 2019 M07 July <NA> 256. "" CUSR0000SA0
## 6 2019 M06 June <NA> 255. "" CUSR0000SA0
As described in their website, the CPI is:
The value column is essentially the average prices of good and services in all U.S. cities for that year/month.
As indicated earlier, I’m interested in understanding the performance of VTSAX
compared to the CPI. I’m really looking to see if the increase in the stock price beats the CPI (and hopefully by a lot).
Below is a few lines of code to create a dataframe that calculates the difference in the price from January of each year from 2010 to 2019. The code also produces a plot to show the difference in the inflation rates over time.
plotdf <- data.frame(yr = seq(2010,2018)) %>%
pmap_dfr(function(yr){
# CPI
base_cpi <- subset(cpidf, year == yr & periodName == "January", select="value")[[1]]
new_cpi <- subset(cpidf, year == (yr+1) & periodName == "January", select="value")[[1]]
# Stock
old_val <- head(VTSAX[paste0(yr,"-01"), "VTSAX.Close"],1)[[1]]
new_val <- tail(VTSAX[paste0(yr+1,"-01"), "VTSAX.Close"],1)[[1]]
data.frame(
StartYr = yr,
EndYr = yr+1,
CPI_inflation = ((new_cpi/base_cpi) - 1) * 100,
Stock_inflation = ((new_val/old_val) - 1) * 100
)
})
plot(Stock_inflation ~ EndYr, plotdf, col="blue", type="l", xlab="Year", ylab = "Inflation (%)")
lines(CPI_inflation ~ EndYr, plotdf, col="red")
legend("bottomleft", c("Stock-VTSAX", "CPI"), lty = c(1,1), col = c("blue","red"))
Based on the plot above, I’m quite happy that my stocks are outperforming the CPI almost every year (except for 2016). This practically means that the money that I’m putting into the stock market (compared to storing it in the bank with an account providing < 2 % APR ) is gaining more value even when inflation is continuing over time at a steady rate (inflation means the prices of products and services goes up).
Based on the short analysis above, the stock that I have is outperforming the CPI and the value of my assets are increasing more than the price of products and services sold in the U.S. We could do a more in-depth analysis of the performance of the stock but my philosophy towards trading is to invest based on long-term trends of the market and not to stress out about the minutia.
Again, thanks for reading my blog and I hope you find this post useful!


Order to nine policemen to shave beards withdrawn
Alwar SP does U-turn after facing flak on social media
by Special CorrespondentFacing flak over their edict to nine Muslim members of the force to shave their beards, the police in Rajasthan’s Alwar district on Friday withdrew the order after getting representation from the aggrieved policemen. Superintendent of Police Anil Paris Deshmukh had on Thursday cancelled the permission granted earlier to the policemen to sport beards.
Mr. Deshmukh told reporters that the policemen had been asked to cut their beards to ensure that they looked “unbiased”.
“Policemen should not only work in an impartial manner, but they should also look like that,” the SP said.
Thursday’s order was issued by the district police chief to Assistant Sub-Inspector Israel Ahmed, head constable Chhotey Khan and seven constables. The order mentioned various dates when they were given permission to grow a beard and stated that it had been cancelled “with immediate effect”.
‘Administrative order’
Mr. Deshmukh said it was an administrative order which had been withdrawn after getting representation from the policemen concerned. “The permission to sport a beard has been given,” he said. The decision of the police drew angry reactions on social media.


Audio Sample Labeler
Labeler
Vocals
Fore:
Back:
None:
Saxophone
Fore:
Back:
None:
Piano
Fore:
Back:
None:
Need a refresher on directions?


Welcome to CSS
We're making great progress
Let's keep going
This is the color from the CSS File.
This is another paragraph


Version 3.2.3, 2019-01-23 (Anton Haumer, Christian Kral)
- Shortened default component names, see #2301
- Added new example
SMEE_DOL, see #2388
- Fixed bug of wrong smooth order in Brush,
see #2315
- Unified communication interval, see #2279
- Unified simulation tolerances, see #2278
- Fixed icons of
Modelica.Electrical.Machines.BasicMachines.Components, see #2031
- Updated blocks and functions towards multi phase systems
greater or equal to three
- Added standard blocks and functions
- Improved documentation
- Added alias for rotor current in squirrel cage model
- Changed icon and location of terminal box according to #1706
- Updated documentation according to #1753,
#1754
and #1755
Version 3.2.1, 2014-10-05 (Anton Haumer, Christian Kral)
- Fixed bugs of wrong sign of power calculation and orientation
of secondary components; see #1474
- Corrected bug in wrong orientation of rotor current; see
#1226
- Fixed bug of wrong temperature propagation in transformer
ambient model; see #1579
Version 2.6.0, 2013-02-25 (Anton Haumer)
- Corrected turnsRatio bug in asynchronous induction machine with
slipring rotor
- Corrected parameter descriptions
Version 2.5.0, 2012-XX-XX (Anton Haumer)
- Included permanent magnet losses
Version 2.4.0, 2010-04-20 (Anton Haumer)
- Included core, friction and stray load models for rotating
electric machines
Version 2.3.0, 2010-02-16 (Anton Haumer)
- Included quasi stationary DC machine models
Version 2.2.0, 2010-02-10 (Anton Haumer)
- Conditional ThermalPort for all machines
Version 2.1.3, 2010-02-10 (Anton Haumer)
- Prepared conditionalHeatPort of SquirrelCage and
DamperCage
Version 2.1.2, 2010-02-09 (Anton Haumer)
Version 2.1.1, 2010-02-05 (Anton Haumer, Christian Kral)
Version 2.1.0, 2009-08-26 (Anton Haumer)
- Set all useHeatPort=false
Version 2.0.0, 2007-11-13 (Anton Haumer)
- Removed replaceable from air gaps
- Removed cardinality from support, using a Boolean
parameter
- Removed all nonSIunits
Version 1.9.2, 2007-10-15 (Anton Haumer)
- Changed some names to be more concise (see conversion
script)
Version 1.9.1, 2007-10-15 (Anton Haumer)
- Solved a bug with replaceable air gap / partial machines
Version 1.9.0, 2007-08-24 (Anton Haumer)
- Removed redeclare type SignalType
Version 1.8.8, 2007-08-20 (Anton Haumer)
Version 1.8.7, 2007-08-20 (Anton Haumer)
- Corrected typo in documentation
Version 1.8.6, 2007-08-12 (Anton Haumer)
Version 1.8.5, 2007-06-26 (Anton Haumer)
- Consistent parameters of DCSE
Version 1.8.4, 2007-06-25 (Anton Haumer)
- Corrected some typos in documentation
Version 1.8.3, 2007-06-08 (Anton Haumer)
Version 1.8.2, 2007-01-15 (Anton Haumer)
- Resolved a bug in electrical excited synchronous induction
machine
Version 1.8.1, 2006-12-01 (Anton Haumer)
- Resolved a compatibility issue with airGap
Version 1.8.0, 2006-11-26 (Anton Haumer)
- Introduced package Transformers
- Moved common parameters and functionality to partial models,
keeping Interfaces.PartialBasicInductionMachines and
PartialBasicDCMachine, respectively, for compatibility reasons
- Implemented support showing reaction torque if connected
Version 1.7.1, 2006-02-06 (Anton Haumer)
- Changed some naming of synchronous machines, not affecting
existing models
Version 1.7.0, 2005-12-15 (Anton Haumer)
- Back-changed the naming to ensure backward compatibility
Version 1.6.3, 2005-11-25 (Anton Haumer)
- Easier parameterization of
AsynchronousInductionMachines.AIM_SlipRing model
Version 1.6.2, 2005-10-23 (Anton Haumer)
- Selectable DamperCage for Synchronous Machines
Version 1.6.1, 2005-11-22 (Anton Haumer)
- Improved transformation and rotation in SpacePhasor
- Introduced Examples.Utilities.TerminalBox
Version 1.60, 2005-11-04 (Anton Haumer)
- Added
Rotator
- Corrected consistent naming of parameters and variables
Version 1.53, 2005-10-14 (Anton Haumer)
- Introduced unsymmetrical damper cage for synchronous
machines
Version 1.52, 2005-10-12 (Anton Haumer)
Version 1.51, 2005-02-01 (Anton Haumer)
- Changed parameter polePairs to Integer
Version 1.4, 2004-11-11 (Anton Haumer)
- Removed mechanical flange support to ease the implementation of
a 3D-frame in a future release
Version 1.3.2, 2004-11-10 (Anton Haumer)
- ReluctanceRotor moved to SynchronousMachines
Version 1.3.1, 2004-11-06 (Anton Haumer)
- Small changes in Examples.Utilities.VfController
Version 1.3, 2004-11-05 (Anton Haumer)
- Several improvements in SpacePhasors.Blocks
Version 1.2, 2004-10-27 (Anton Haumer)
- Fixed a bug with support (formerly bearing)
Version 1.1, 2004-10-01 (Anton Haumer)
- Changed naming and structure issued to Modelica Standard
Library 2.1
Version 1.03, 2004-09-24 (Anton Haumer)
- Added package Sensors
- Added DC machine with series excitation
- Debugged and improved MoveToRotational
Version 1.02, 2004-09-19 (Anton Haumer)
- New package structure for machine types added DC machine
models
Version 1.01, 2004-09-18 (Anton Haumer)
- Moved common equations from machine models to PartialMachine
improved MoveToRotational
Version 1.00, 2004-09-16 (Anton Haumer)
Generated at 2019-01-25T16:44:03Z by OpenModelica 1.14.0~dev-130-gefa44fb


New Inspiration 2020 20% off on new season Browse collections New Inspiration 2020 20% off on new season Browse collections


v
AUBURN, Ala. — President Trump on Monday strongly endorsed Roy S. Moore, the Republican nominee for a United States Senate seat here, prompting the Republican National Committee to restore its support for a candidate accused of sexual misconduct against teenage girls. Mr. Trump’s endorsement strengthened what had been his subdued, if symbolically significant, embrace of Mr. Moore’s campaign. At Mr. Trump’s direct urging, and to the surprise of some Republican Party officials, the national committee, which severed ties to Mr. Moore weeks ago, opened a financial spigot that could help Mr. Moore with voter turnout in the contest’s closing days. “Democrats refusal to give even one vote for massive Tax Cuts is why we need Republican Roy Moore to win in Alabama,” Mr. Trump posted on Twitter on Monday, before he formally endorsed Mr. Moore during a telephone call. “We need his vote on stopping crime, illegal immigration, Border Wall, Military, Pro Life, V.A., Judges 2nd Amendment and more.”
Enter your email address Sign Up DOCUMENT Statement on Behalf of Gloria Deason On Monday, the lawyer Paula Cobia released a statement on behalf of her client Gloria Deason, who said she was 18 when she dated Roy Moore. It said that Mr. Moore, a Republican candidate for a Senate seat in Alabama, lied when he said he did not know the women who accused him of sexual misconduct.
“I like Trump, I’m a fan of Trump,” said Kyle Smith, 20, who is studying to be a welder and said he needed more time to study the race. “But, I mean, I’m not making my decision off him.” Richard Fausset reported from Auburn, Alan Blinder from Atlanta and Jonathan Martin from Houston. Jess Bidgood contributed reporting from Birmingham, Ala., Maggie Haberman from New York, and Thomas Kaplan and Eileen Sullivan from Washington. A version of this article appears in print on December 5, 2017, on Page A1 of the New York edition with the headline: For Moore, a Nod From Trump and Lots of Cash. Order Reprints| Today's Paper|Subscribe Continue reading the main story


#include "_doctype.html"
curl - Release procedure and release schedule
#include "css.t"
#define DEVEL_RELEASEPROC
#define CURL_URL release-procedure.html
#include "_menu.html"
#include "setup.t"
WHERE2(Development, "/dev/", Release Procedure)
#include "release-procedure.gen"
#include "_footer.html"


|
| function | cell2mat (in inpCArr) |
| | CELL2MAT does the same as the built-in cell2mat function but a) 20% faster b) works with cell arrays of objects and even values of different types, the only limitation is ability of the built-in cat function to concatenate values from inpCArr to process them. More...
|
| |
| function | cell2tablestr (in titleList, in dataCell, in colSepSeq, in varargin) |
| | CELL2TABLESTR - converts a cell array into a table-like char array (or a cell array of strings representing table rows). More...
|
| |
| function | cellformatter (in inpCont) |
| |
| function | cellstr2colstr (in inpCArr, in indentStr) |
| | CELLSTR2COLSTR transforms a cell array of strings into a row string that looks like a column when displayed. More...
|
| |
| function | cellstr2expression (in inpCMat, in isMatrixStyle, in isQuotingSkipped) |
| | CELLSTR2EXPRESSION creates Matlab expression based on cell matrix of expressions corresponding to the individual elements of the matrix. More...
|
| |
| function | cellstr2func (in inpCMat, in inpArgNameList) |
| | CELLSTR2EXPRESSION creates Matlab expression based on cell matrix of expressions corresponding to the individual elements of the matrix. More...
|
| |
| function | csvwrite (in fileName, in inpCMat, in varargin) |
| | CSVWRITE writes a specified cell matrix into a comma-separated file specified by name. All columns of the matrix are expected to be of the same type. As of the moment only 'char' and all numeric types are supported. More...
|
| |
| function | checkTypeOfAllRows (in isNeededTypeMat, in typeName) |
| |
| function | showcell (in inpCArr, in varargin) |
| | SHOWCELL generates a string representation of cell array or displays it in a console. More...
|
| |
| function | showCellInternal (in inpCMat, in nSpaces, in fNumPrint, in fCharPrint, in fCellPrint, in isAsExpression, in nMaxShownArrayElems) |
| |
| function | other2str (in inpVal) |
| |
| function | numArr2str (in inpVal, in ignoredArg, in isClassShown, in varargin) |
| |
| function | charArr2str (in inpVal, in isAsExpression) |
| |
| function | getEmptyStr (in x) |
| |
| function mxberry::core::cell::cell2tablestr |
( |
in |
titleList, |
|
|
in |
dataCell, |
|
|
in |
colSepSeq, |
|
|
in |
varargin |
|
) |
| |
CELL2TABLESTR - converts a cell array into a table-like char array (or a cell array of strings representing table rows).
* Usage: tableStr=cell2tablestr(titles,dataCell,sepSymbol,varargin)
*
* Input:
* regular:
* titleList: cell[1,nCols]- cell array of column titles
* dataCell: cell[nRows,nCols] - data cell array
* colSepSeq: char[1,] - a string used for separating neighboring
* columns
*
* properties:
* isMatlabSyntax: logical[1,1] - forms result according to Matlab
* syntax(default=0);
* UniformOutput: logical[1,1] - if true, output is char array, if
* false - output is cell array; by default true;
* minSepCount: double[1] - minimal number of separation used for
* separating neighboring columns
* numPrecision: double[1,1] - number of digits used for displaying
* numeric values
*
* Output:
* tableStr: char[nRows,nCols] or cell[nLines,1] of char[1,] - output character
* array or cell array of lines
*
- Author
- Peter Gagarinov, PhD pgaga.nosp@m.rino.nosp@m.v@gma.nosp<EMAIL_ADDRESS>- Copyright
- 2015-2016 Peter Gagarinov, PhD
2015 Moscow State University,
Faculty of Computational Mathematics and Computer Science,
System Analysis Department
| function mxberry::core::cell::cellstr2expression |
( |
in |
inpCMat, |
|
|
in |
isMatrixStyle, |
|
|
in |
isQuotingSkipped |
|
) |
| |
CELLSTR2EXPRESSION creates Matlab expression based on cell matrix of expressions corresponding to the individual elements of the matrix.
* Input:
* regular:
* inpCMat: cell[nRows,nCols] of char[1,] - input matrix of
* expression
* isMatrixStyle: logical[1,1] - if false (default) the
* curcly (cell style braces are used) and each cell is surrounded
* by quotes (unless isQuotingSkipped=true). If true square braces
* (matrix style) are used and no quotes are used.
*
* optional:
* isQuotingSkipped: logical[1,1] - if true, no quotes are used even
* for isMatrixStyle=false
*
* Output:
* resStr: char[1,] - resulting expression for the matrix
*
- Author
- Peter Gagarinov, PhD pgaga.nosp@m.rino.nosp@m.v@gma.nosp<EMAIL_ADDRESS>- Copyright
- 2015-2016 Peter Gagarinov, PhD
2015 Moscow State University,
Faculty of Computational Mathematics and Computer Science,
System Analysis Department
| function mxberry::core::cell::cellstr2func |
( |
in |
inpCMat, |
|
|
in |
inpArgNameList |
|
) |
| |
CELLSTR2EXPRESSION creates Matlab expression based on cell matrix of expressions corresponding to the individual elements of the matrix.
* Input:
* regular:
* inpCMat: cell[nRows,nCols] of char[1,] - input matrix of
* expressiosn
* inpArgNameList: cell[1,nArgs] of char[1,]/char[1,] - names of input
* arguments for the resulting function
* Output:
* fHandle: function_handle[1,1] - resulting expression for the matrix
*
- Author
- Peter Gagarinov, PhD pgaga.nosp@m.rino.nosp@m.v@gma.nosp<EMAIL_ADDRESS>- Copyright
- 2015-2016 Peter Gagarinov, PhD
2015 Moscow State University,
Faculty of Computational Mathematics and Computer Science,
System Analysis Department
| function mxberry::core::cell::csvwrite |
( |
in |
fileName, |
|
|
in |
inpCMat, |
|
|
in |
varargin |
|
) |
| |
CSVWRITE writes a specified cell matrix into a comma-separated file specified by name. All columns of the matrix are expected to be of the same type. As of the moment only 'char' and all numeric types are supported.
* Input:
* regular:
* fileName: char[1,] - name of the destination file
* dataCMat: cell[nRows,nCols] - cell array containing numberic and
* character data
*
* properties:
* delimiter: char[1,] - delimiter used for separating columns
* Default: ','
* columnNameList: cell[1,] of char[1,] - list of column names
* numFormat: char[1,] - numbers display format string for
* built-in sprintf function
* Default: %10.10g
*
- Author
- Peter Gagarinov, PhD pgaga.nosp@m.rino.nosp@m.v@gma.nosp<EMAIL_ADDRESS>- Copyright
- 2015-2016 Peter Gagarinov, PhD
2015 Moscow State University,
Faculty of Computational Mathematics and Computer Science,
System Analysis Department
| function mxberry::core::cell::showcell |
( |
in |
inpCArr, |
|
|
in |
varargin |
|
) |
| |
SHOWCELL generates a string representation of cell array or displays it in a console.
* Input:
* regular:
* inpCArr: cell[] - cell array of arbitrary dimension
* properties:
* nSpaces: numeric[1,1] - column spacing.
* Default is 4.
* nDigits: numeric[1,1] - maximum number of significant digits
* in the output string,specified as a positive integer.
* Default is 5.
* printVarName: logical[1,1] - if true (default),variable name is
* printed when no output arguments is requested
* varName: char[1,] - variable name to print,by default it is
* determined automatically
* showClass: logical[1,1] - if true, a class of numeric values is
* displayed in the format used by the built-in 'mat2str'
* function
* asExpression: logical[1,1] - if true, the output string is
* displayed as Matlab expression.
* nMaxShownArrayElems: double[1,1] - maximum number of scalar
* array elements show "as is"; if an array has more elements or
* more than 1 dimension its content is not shown, only type
* and size information
*
- Author
- Peter Gagarinov, PhD pgaga.nosp@m.rino.nosp@m.v@gma.nosp<EMAIL_ADDRESS>- Copyright
- 2015-2016 Peter Gagarinov, PhD
2015 Moscow State University,
Faculty of Computational Mathematics and Computer Science,
System Analysis Department


Galvanize Delivers
Order Delivery
Navbar Link
menu
Menu
Royale with Cheese
$8.99
Add to Order
Arugula pie
$11.99
Add to Order
Smoked Swine
$14.99
Add to Order
Ice Cream Biscuit
$7.99
Add to Order
Order
Item
Price
Subtotal
Tax
Total
account_circle
First Name
phone
Phone Number
home
Address
Place Order
send


Try to answer the following code-related questions within the time limit. Keep in mind that incorrect answers will penalize your score/time by ten seconds!
Enter initials:
Wrong!
Correct!


| | |
- enum.Enum(builtins.object)
-
- RTN
class RTN(enum.Enum) |
| |
RTN(value, names=None, *, module=None, qualname=None, type=None, start=1)
An enumeration. |
| |
- Method resolution order:
- RTN
- enum.Enum
- builtins.object
Data and other attributes defined here:
- CMD_FAILED = <RTN.CMD_FAILED: 2>
- ERROR_CMD = <RTN.ERROR_CMD: 5>
- INVALID_CMD = <RTN.INVALID_CMD: 4>
- LINE_REMOVED = <RTN.LINE_REMOVED: 11>
- NAME_ALREADY = <RTN.NAME_ALREADY: 3>
- POINT_DOES_EXIST = <RTN.POINT_DOES_EXIST: 6>
- POINT_IS_USED = <RTN.POINT_IS_USED: 9>
- POINT_REMOVED = <RTN.POINT_REMOVED: 10>
- SUCCESS_LINE = <RTN.SUCCESS_LINE: 7>
- SUCCESS_POINT = <RTN.SUCCESS_POINT: 8>
- SUCCESS_VECTOR = <RTN.SUCCESS_VECTOR: 1>
- VECTOR_REMOVED = <RTN.VECTOR_REMOVED: 12>
Data descriptors inherited from enum.Enum:
- name
- The name of the Enum member.
- value
- The value of the Enum member.
Readonly properties inherited from enum.EnumMeta:
- __members__
- Returns a mapping of member name->value.
This mapping lists all enum members, including aliases. Note that this
is a read-only view of the internal mapping.
| |


Personal Information
*
Email Address:
*
Personal URL:
*
Date of Birth:
*
Gender:
Male
Female
Other
Comments:
I accept the
Terms and Conditions
Clear All


JavaScript is disabled on your browser.
Skip navigation links
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Prev Letter
Next Letter
Frames
No Frames
All Classes
C
D
E
F
G
I
M
N
P
R
S
T
E
endTime
- Variable in class com.suman.euler.problem.
EulerTest
The end time.
EulerProblem
- Interface in
com.suman.euler.problem
The Interface EulerProblem.
eulerProblem
- Variable in class com.suman.euler.problem.
EulerTest
The euler problem.
EulerTest
- Class in
com.suman.euler.problem
The Class EulerTest.
EulerTest(EulerProblem)
- Constructor for class com.suman.euler.problem.
EulerTest
Instantiates a new euler test.
executeSoultion()
- Method in interface com.suman.euler.problem.
EulerProblem
Execute soultion.
executeSoultion()
- Method in class com.suman.euler.solution.
Problem001
executeSoultion()
- Method in class com.suman.euler.solution.
Problem002
executeSoultion()
- Method in class com.suman.euler.solution.
Problem003
executeSoultion()
- Method in class com.suman.euler.solution.
Problem004
executeSoultion()
- Method in class com.suman.euler.solution.
Problem005
executeSoultion()
- Method in class com.suman.euler.solution.
Problem006
executeSoultion()
- Method in class com.suman.euler.solution.
Problem007
executeSoultion()
- Method in class com.suman.euler.solution.
Problem008
executeSoultion()
- Method in class com.suman.euler.solution.
Problem009
executeSoultion()
- Method in class com.suman.euler.solution.
Problem010
executeSoultion()
- Method in class com.suman.euler.solution.
Problem011
expected
- Variable in class com.suman.euler.solution.
Problem001Test
The expected.
expected
- Variable in class com.suman.euler.solution.
Problem002Test
The expected.
expected
- Variable in class com.suman.euler.solution.
Problem003Test
The expected.
expected
- Variable in class com.suman.euler.solution.
Problem004Test
The expected.
expected
- Variable in class com.suman.euler.solution.
Problem005Test
The expected.
expected
- Variable in class com.suman.euler.solution.
Problem006Test
The expected.
expected
- Variable in class com.suman.euler.solution.
Problem007Test
The expected.
expected
- Variable in class com.suman.euler.solution.
Problem008Test
The expected.
expected
- Variable in class com.suman.euler.solution.
Problem009Test
The expected.
expected
- Variable in class com.suman.euler.solution.
Problem010Test
The expected.
expected
- Variable in class com.suman.euler.solution.
Problem011Test
The expected.
C
D
E
F
G
I
M
N
P
R
S
T
Skip navigation links
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Prev Letter
Next Letter
Frames
No Frames
All Classes


Clicking this menu item opens the CT Book as PDF document.
In the CT Book you will find predominantly mathematically oriented information on using cryptographic procedures.
The script offers background reading about many methods implemented in CrypTool-- with many examples and references.


You can find us every day from 6am - 8pm at the following locations:
1st and Pike
SeaTac Airport
Seattle Center
Capitol Hill
Alki


Important Concepts In Qt Quick - Graphical Effects
Graphical Effects and Particles
Visually appealing user-interfaces are more engaging than lacklustre ones. That said, the designer must bear in mind that visual effects simply provide a useful way to subtly communicate to the user (for example, which visual item is active, or how focus is being transferred). Over-use of visual effects can actually detract from the user-experience.
Visual Transformation
Visual objects can be transformed. For example, they can be scaled or rotated. These sort of transformations can provide hints about focus or selection, and can provide intuitive hints about what events are occurring in an application.
For information about visual transformations to visual objects, see the page titled Qt Quick Transformation Types.
Shader Effects
Shader effects allow the full, raw power of a graphics processing unit to be utilized directly via vertex and fragment shaders. Using too many shader effects can result in increased power usage and sometimes slow performance, but if used sparingly and carefully, a shader can allow complex and visually appealing effects to be applied to a visual object (for example, ripples in water).
For information about shader effects, see the ShaderEffect reference documentation.
Particles
A particle system allows explosions, fireworks, smoke, fog and wind effects to be simulated and displayed to the user. Qt Quick provides a particle system which allows these sort of complex, 2D simulations to be performed, including support for environmental effects like gravity and turbulence. Particles are most commonly used to add subtle and visually appealing effects to currently selected items in lists or in activity notifiers, and in games.
For information about particles, see the documentation about the Qt Quick Particle System.
Sprites
A sprite is an animated image made up of frames. Sprites are commonly found in games. Qt Quick provides a visual type to display sprites, as well as a complex, stochastic, frame-transition controller for more complex applications which use sprites extensively (such as games).
For information about sprite animations, see the page titled Sprite Animations.
Opacity
Visual objects can be opaque or translucent. For example, an application can make one visual object opaque and other visual objects translucent to focus the users attention on the opaque one. This is controlled using the opacity
property of the Item.
For more information about opacity, see the Item documentation.


Welcome to My Salmon Cookie shop
New Cookie Stand
Shop Name
Min Customers
Max Customers
Avg sale
Add New Cookie Stand


The analytics we’ll need for this metric are often available through the social media platforms prg.ai chooses to employ (like Facebook, for example), and can show how well your social media department is performing
The success of educational workshops, networking activities etc. can be measured by the amount of students who participate regularly rather than the total number of participants.
With the ambitious plan of attracting 30,559 students, a huge amount of schools must be involved. It is recommended that we build an all-country network with some schools in every region rather than making a strong campaign in few big cities.
Over the past decade we have seen the popularity of podcasts, webinars and any form of online learning rise – a trend only exacerbated by the current pandemic.
The number of initially attracted students should be reasonably high with funnel conversion rates close to 20 % (generally considered as the maximum realistically attainable rates) as studies show that majority of student dropouts happen when students do not find their (online) course relevant which is not likely to happen in our case, since the activities we have presented effectively merge theory with practice and overcome the current obstacles (fear of the unknown, stereotypes about ICT students/the general environment). Benchmark: Surveys shows that the implementation of compass technologies is on the rise in Estonia with about 90% of schools being more or less actively involved.
created with
Website Builder Software .


What's this all about?
Trying to lose a few pounds? Give up smoking? Learn a new skill? Bettering yourself is not a simple task. It's hard to stay motivated. That's why you should celebrate your small victories. Share them with the world! Whenever you feel unmotivated, you can look through your past victories and be certain: you did achieve so much already, you can do more!


Interop with C Libraries
| 最近更新 | 2018-01-09 |
When writing native applications, oftentimes we need to access certain functionality that is not included in the Kotlin standard library, such as making HTTP requests, reading and writing from disk, etc.
Kotlin/Native provides us with the ability to consume standard C libraries, opening up an entire ecosystem of functionality that exists for pretty much anything we could need. In fact, Kotlin/Native already ships with a set of prebuilt platform libraries which provide some additional common functionality to that of the standard library.
In this tutorial however, we'll see how to use some specific libraries, such as libcurl
. We'll learn to
Generating Bindings
An ideal scenario for interop is to call C functions as if we were calling Kotlin functions, that is, following the same signature and conventions. And that is precisely what the
cinterop
tool provides us with. It takes a C library and generates the corresponding Kotlin bindings for it, which then allow us
to use the library as if it were Kotlin code.
In order to generate these bindings, we need to create a library definition file (def
) that contains some information about the headers we need to generate. In our case we want to use the famous libcurl
library
to make some HTTP calls, so we'll create a file named libcurl.def
with the following contents
headers = curl/curl.h
headerFilter = curl/*
linkerOpts.osx = -L/opt/local/lib -L/usr/local/opt/curl/lib -lcurl
linkerOpts.linux = -L/usr/lib/x86_64-linux-gnu -lcurl
A few things are going on in that file so let's see them one by one. The first entry is headers
which is the list of header files that we want to generate
Kotlin stubs for. We can add multiple files to this entry, separating each one with \
on a new line. In our case we only want curl.h
. The files we reference
need to be relative to the folder where the definition file is, or be available on the system path (in our case it would be /usr/bin/curl
).
The second line is the headerFilter
. This is used to denote what exactly we want included. In C, when one file references another file with the #include
directive,
all the headers are also included. Sometimes this may not be needed, and we can use this parameter, using glob patterns, to fine tune things.
Note, that headerFilter
is an optional argument and mostly only used when the library we're using is being installed as a system library and we do not want to fetch external dependencies
(such as system stdint.h
header) into our interop library. It may be important for both optimising library size and fixing potential conflicts between system and the Kotlin/Native provided compilation environment.
The third and forth lines are about providing linker options, which can vary based on different target platforms. In our cause we are defining it for macOS and Linux. Compiler options can also be specific, albeit in this case it is not necessary.
The convention that is followed is that each library gets its own definition file, usually named the same as the library. For more information on all
the options available to cinterop
, see README available on GitHub
Once we have the definition file ready, we can invoke cinterop
and have it generate the bindings for us
cinterop -def libcurl.def -o build/c_interop/libcurl
The output should be a Kotlin compiled library (extension .klib
). We're also instructing cinterop
to output the contents to the folder build/c_interop/libcurl
which we'll later use as input by konanc
. It's important this folder is created
beforehand as cinterop
needs an existing folder. The c_interop is a convention that is followed for libraries that are for interop.
Consuming the Kotlin API
Now that we have our library and Kotlin stubs, we can consume them from our application. To keep things simple, in this tutorial we're going to convert one of the simplest libcurl examples over to Kotlin.
The code in question is from the simple example (comments removed for brevity)
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
res = curl_easy_perform(curl);
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
curl_easy_cleanup(curl);
}
return 0;
}
The first thing we'll need is a Kotlin file called Main.kt
with the main
function defined in it and then proceed to translate each line
import libcurl.*
fun main(args: Array<String>) {
val curl = curl_easy_init()
if (curl != null) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com")
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L)
val res = curl_easy_perform(curl)
if (res != CURLE_OK) {
println("curl_easy_perform() failed ${curl_easy_strerror(res)?.toKString()}")
}
curl_easy_cleanup(curl)
}
}
As we can see, we've eliminated the explicit variable declarations in the Kotlin version, but everything else is pretty much verbatim to the C version. All the calls we'd
expect in the libcurl
library are available in their Kotlin version.
Note that for the purpose of this tutorial, we've done a line by line literal translation. Obviously we could write this in a more Kotlin idiomatic way.
Compiling and Linking the library
The next step is to compile our application. We already covered the basics of compiling a Kotlin/Native application from the command line in the A Basic Kotlin/Native application tutorial.
The only difference in this case is that we have to include the library that cinterop
generated for us.
konanc Main.kt -library build/c_interop/libcurl
We can see that we're passing in as library
parameter the output path of cinterop
.
If there are no errors during compilation, we should see the output as a file named program.kexe
, which on execution should output
the contents of the site http://example.com
The reason we're seeing the actual output is because the call curl_easy_perform
prints the result to the standard output. We could hide this using
curl_easy_setopt
.
For a more complete example of using libcurl
, the libcurl sample of the Kotlin/Native project shows how to abstract the code into Kotlin
classes as well as display headers. It also demonstrates how to make the steps a little easier by combining them into a shell script or Gradle build. We'll cover these topics though in more detail in subsequent tutorials.


To run cast need setup need gloablly installed packages: npm install -g http-server npm install -g ngrok Change to root directory run http-server and based on started port ngrok http PORT_NUMBER and browse to https://NGROK_ID.ngrok.io/demos/embed/cast-player.html


|
|||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object edu.cmu.sphinx.result.AbstractSausageMaker edu.cmu.sphinx.result.SausageMaker
public class SausageMaker
The SausageMaker takes word lattices as input and turns them into sausages (Confusion Networks) according to Mangu, Brill and Stolcke, "Finding Consensus in Speech Recognition: word error minimization and other applications of confusion networks", Computer Speech and Language, 2000. Note that the
getBestHypothesis
of the
ConfidenceResult object returned by the score
method returns the path where all the words have
the highest posterior probability within its corresponding time slot.
| Field Summary |
|---|
| Fields inherited from class edu.cmu.sphinx.result.AbstractSausageMaker |
|---|
PROP_LANGUAGE_WEIGHT |
| Constructor Summary | |
|---|---|
SausageMaker()
Construct an empty sausage maker |
|
SausageMaker(float languageWieght)
|
|
SausageMaker(Lattice l)
Construct a sausage maker |
| Method Summary | |
|---|---|
int |
getEarliestEndTime(java.util.List<Node> cluster)
Returns the earliest end time of all nodes in the given cluster. |
int |
getLatestBeginTime(java.util.List<Node> cluster)
Returns the latest begin time of all nodes in the given cluster. |
Sausage |
makeSausage()
Turn the lattice contained in this sausage maker into a sausage object. |
ConfidenceResult |
score(Result result)
Computes confidences for a Result and returns a ConfidenceResult, a compact representation of all the hypothesis contained in the result together with their per-word and per-path confidences. |
| Methods inherited from class edu.cmu.sphinx.result.AbstractSausageMaker |
|---|
newProperties |
| Methods inherited from class java.lang.Object |
|---|
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
|---|
public SausageMaker()
public SausageMaker(float languageWieght)
public SausageMaker(Lattice l)
l
- the lattice to construct a sausage from| Method Detail |
|---|
public int getLatestBeginTime(java.util.List<Node> cluster)
cluster
- the cluster to examine
public int getEarliestEndTime(java.util.List<Node> cluster)
cluster
- the cluster to examine
public Sausage makeSausage()
public ConfidenceResult score(Result result)
ConfidenceScorer
result
- the result to compute confidences for
ConfidenceScorer.score(edu.cmu.sphinx.result.Result)
|
|||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


Human Being, Responsible Son, Good Friend, Loving Husband, Aspiring Father & IT Professional.
Apart from being an IT Professional, I enjoy most of my time travelling.I enjoy road biking, hiking, and Going on long road trips.
When forced indoors, I follow a number of Action, Adventure & Documentry genre movies and television shows, I am an aspiring father, and I spend a large amount of my free time exploring the latest technolgy advancements in the Electronic Gadgets, Commercial Aviation & AI.


{% if activity.status_type == 'Review' %}
{% include 'snippets/status_banner.html' with content="reviewed "|add:activity.book.data.title|add:"" %}
{% include 'snippets/book.html' with book=activity.book size=large %}
{{ activity.name }}
{{ activity.rating | stars }}
{{ activity.content | safe }}
{% include 'snippets/interaction.html' with activity=activity %}
{% elif activity.status_type == 'Note' %}
{% include 'snippets/status_banner.html' %}
{{ activity.content | safe }}
{% for book in activity.mention_books.all %}
{% include 'snippets/book.html' with book=book size=large description=True %}
{% endfor %}
{% include 'snippets/interaction.html' with activity=activity %}
{% else %}
{# generic handling for a misc activity, which perhaps should not be displayed at all #}
did {{ activity.activity_type }}
{% endif %}


Outline
R is one of the most popular programming language for statistical programming in ecology, evolution, and conservation. It is also the language taught in the University of Exeter’s undergraduate and masters courses within the Centre for Ecology and Conservation.
RStudio is probably the most popular IDE for people using R. An IDE is an integrated development environment, which allows users to combine multiple aspects of software development in one place to make it easier to use. For RStudio, that means you have different panes that contain the R Console, your script, a file explorer, a pane where plots appear, and much more.
Git is a version control system that allows you to track versions of your files. It is popular when programming to be able to keep a history of all the changes you have made to your work, and be able to retrieve old instances of your work if you have made a mistake later down the line. GitHub is an online hosting service that allows you to share your code and data for free, which is super important in science for being open and reproducible and transparent.
This post gives some details on how to install R, RStudio, and git. This information is mainly aggregated from other sources (see acknowledgements below), but there is some specific advice for Windows users for University of Exeter staff and students.
Prerequisites
- Be willing to endure some pain when installing things.
Learning objectives
This introduction should allow you to:
- install R
- install RStudio
- manage your R, RStudio, and package installation
- install git
Installing R
R can be installed from the Comprehensive R Archive Network (CRAN) here.
For Mac Users
Mac users should click the “Download R for macOS” link in the “Download and Install R” section. Click on the link for the latest version of R and click on the “Download R-[version].pkg” link to download the installer package. Open the downloaded file and follow the installation instructions. You can launch R by clicking the R icon on your Launchpad or in your Applications folder of your Finder, but we recommend using RStudio to code in R because it makes programming in R a much easier and more pleasant experience.
For Windows Users
Windows users should click the “Download R for Windows” link in the “Download and Install R” section. Click on the “base” directory and click on the link for the latest version of R. Then click on the “Download R[version] for Windows” link, open the downloaded file and follow the installation instructions. You can launch R by double-clicking the R icon on your Desktop or in your start menu, but we recommend using RStudio to code in R because it makes programming in R a much easier and more pleasant experience.
Installing RStudio
RStudio can be installed for free from the Posit (the company that was formerly known called RStudio) website here. RStudio is available for Windows, MacOS, and Linux. Just click the “Download RStudio” button and follow the simple instructions. Once you’ve installed RStudio, you can open it like any other program on your computer. Before you install RStudio, make sure you have installed R.
Some general tips for Global Options of RStudio
When setting up RStudio, there are a bunch of things you can change to configure your RStudio to how you like it. Some of these are likely personal, but we have some settings we like to use. These are settings you can change by clicking Tools -> Global Options.
- Unclick “Restore .RData into workspace at startup”. This means that each time you start a new RStudio instance, your environment starts clean and you can be confident that any results you have, or weird R behaviour, is not due to any previous code or session.
- Unclick “Restore most recently opened project at startup”. This means that when you start a new RStudio, it will open an RStudio not associated with a project. This is more of a personal preference of mine as more often than not I have multiple RStudio instances open not associated with the same work, and I got tired of closing the project of new RStudio instances.
- In the “Code” tab, tick “Soft-wrap R source files”. This means that instead of having long lines of code that go off of your source pane and require you to move from left-to-right to view them, the source pane instead “soft-wraps” them into a new line, while preserving the fact that they are, in fact, a single line of code.
- In the “Code -> Display” tab, unclick “Show Margin” which will get rid of the annoying line that can be present in the Source pane sometimes.
- I leave the default colours on for RStudio, but you can change to black background (and loads of other alternatives) in the “Appearance” tab.
Managing where your R packages install
Over many years, I have helped a fair few people at the University try and work out how to install R packages on their University computers. This has mainly been on Windows machines, and is most likely due to the lack of read/write access wherever R by default chooses to install packages.
Consequently, it might be good for you to choose a new location on your computer where your R packages will install. And if you cannot install R packages at the moment then we are here to help! You can learn how to do change the default location your R packages install into by watching this video, but we will whizz through the process here too.
Check where R is installing packages by typing .libPaths() into your R console.
Create a new folder which you would like to install packages, somewhere where you DEFINITELY have read/write access (e.g. “~/Desktop/r_packages”)
We can then change .libPaths() for this R session.
However, when we start a new R session, this change will be lost. To change it by default for R, we need to change our .Renviron file, which allows us to change variables that R looks for every time it starts. To easily manipulate this file, we will first install the R package usethis using install.packages(usethis). It should install into the new directory you have just created, for me it installed into “~/Desktop/r_packages”.
Run usethis::edit_r_environ() in your Console and it should open your .Renviron file in your source pane. From here, add R_LIBS_USER=“~/Desktop/r_packages” to it (obviously change the folder name to the folder you have created), click Save, and close the file.

Installing git
To check if Git is installed on a Windows or Mac machine, follow these steps:
For Windows:
- Open the Command Prompt by pressing the “Windows Key + R” and typing “cmd” in the “Run” dialog box, or open “Git Bash” (or use the Terminal tab of your RStudio).
- Type
git --version
and press Enter. - If git is installed, the version number of git will be displayed in the Command Prompt.
For Mac:
- Open the Terminal application by finding it on your Launchpad or Applications folder in your Finder (or in the Terminal tab of your RStudio).
- Type
git --version
and press Enter. - If git is installed, the version number of git will be displayed in the Terminal window.
Even if git is installed, it is probably a good idea to update to the latest version. git has very good backwards compatibility so it is very unlikely that updating will break anything.
For Mac Users
Git can be installed on Mac from some of the options on the git website. Another alternative is GitHub Desktop, which will install the latest version of Git with itself if you do not already have it.
For Windows Users
Git can be installed from gitforwindows, but if you install GitHub Desktop, the latest version of Git will be installed if you do not already have it. With GitHub Desktop, you get a command line version of Git with a robust GUI.
Make a GitHub profile
Git is version control on your local machine, to share code with other you should create a GitHub (or GitLab) profile. Information on setting up a GitHub account can be found here.
Configure GitHub with local git and RStudio
Now we have git, R, and RStudio installed, and an RStudio profile, we need to make sure they can all talk each other, and that you can communicate with your GitHub profile from your local machine. An extensive walkthrough is available here, but we will cover the main steps.
First, we need to create an access token so that GitHub can securely link your local computer to GitHub. To do this go to Settings -> Developer Settings -> Tokens and create an access token.
For the scopes, I ticked most that I thought would be useful and understood, which were gist, repo, user, workflow. Make sure you name it something useful like “R:GitHubPAT” so that is makes sense if you ever need to make a new token.
Once this code is created, save it to your clipboard or in a text editor while we are storing it in your RStudio. Once you close the webpage you will never see this token again, so make sure you make a note of it! Then going forwards, treat this access token as you would a password. For some of you that might mean using a password manager, and for some of you that might mean a book, your hand, or post it notes on your computer screen.
We will use the R package gitcreds to associate your GitHub PAT with RStudio. First install gitcreds using install.packages(‘gitcreds’). If you want a way to be able to install and load R packages from CRAN, GitHub, and Bioconductor in a simpler way without calls to both install.packages() and library(), then I recommend looking at librarian!
Next run gitcreds::gitcreds_set() and follow the prompts. Specifically make sure you copy in your GitHub PAT!
Once you have set this, you can check it has stored properly using gitcreds::gitcreds_get().
This should mean you are ready to roll (i.e. Git and GitHub like a boss), but if you are getting stuck some common troubleshoots can be found here.
One thing you can check is that RStudio knows where your git executable is. In Tools -> Global Options, you can check where git is stored and being accessed from.
Summary
After this guide, you should have installed R, RStudio, and git on your machine, and also know a little more about how to check where your R packages are installing and some handy RStudio options.
Additional Resources
- This online book about using R and RStudio and git is incredible.
Acknowledgements
We did not create this content alone! Inspiration, tips, and resources have been borrowed from multiple sources.
- We took inspiration from this blog post about someone’s RStudio configuration.
- We watched this video on how to change the location for installing R packages.
- We enjoyed this thread on whether we should update R and our R packages regularly. In conclusion, yes probably.
- Some of the content was created using ChatGPT.


About Melina
Hi ! I'm a classic, punny, girl looking to make a living by getting paid to write amazon reviews!  My name is Catie Novielli and I love to put things in my cart on amazon. I don't buy them tho. Only sometimes. Here we have some of the producs I have bought. They were all bad decisions. Don't impulse buy a yoedeling pickle.


End To End
Note
doLittle is in an Alpha state - but doLittle originates from Bifrost which has a stable version. If you're ok with trying out an Alpha - carry on :) The Bifrost equivalent of this tutorial can be found here
The purpose of this tutorial is to take you through the entire stack of doLittle, all the steps you need and can do to successfully build software using doLittle. The philosophy behind doLittle is somewhat different than what you find in more established architectures. For instance, you'll hardly see any talk about data and doing good old CRUD (Create Read Update Delete), instead we talk about behaviors and their consequences which in most cases result in data being generated, but not necessarily. Often we also find that data is just one of the consequences of a behavior going through the system. Another good point is that we don't necessarily believe in the one size fits all when it comes to data in a system. Some data is best suited to sit inside a relational database, while some might be better off in a document based, and many times its perfectly fine to have it be directly generated to a static file sitting on the file system. Also, any combinations are also in many cases valid. This opens for a few opportunities of focusing in on every feature of your software instead of looking at it as a whole and trying to optimize for the edge cases; leave the edge cases behind and model them explicitly when needed.
Building software is hard, and trying to focus on an entire application all the time really does not make any sense in our oppinion. Instead we believe that applications are actually composed of smaller more focused applications brought together in a bigger setting. When approaching software in this manner you end up with code that is more decoupled, more maintainable and less prone to errors and regression.
The user story
In this tutorial we're going to create a simple feature in a corner of an imagined system. The feature we're looking at creating is the ability to register an employee. We're not going to even try to model this remotely close to anything real, as that is too involved in this tutorial, but rather try to capture the process of creating an end to end feature from the top-down.
Getting started
Projects
The way we recommend working is to have multiple projects that are focused on the different parts. With separating it out and be very clear what their purpose is, we believe you end up with something that is more maintainable and easy to understand were to put things. So, lets get started by setting up a couple of projects. We're going to need the following C# class library projects:
- Concepts
- Domain
- Events
- Read
Once you've created the projects some of these projects will need to reference some of the others. The Domain and the Read project should have a reference to the Concepts and the Events projects. The Events project represents the contract between the Domain and the Read side.
For the client that we are going to make, we will be needing a totally empty ASP.net project without any files in it, except for Web.config.
Name the project "Web".
Nuget
doLittle is available on Nuget, so we will be using Nuget to pull down doLittle and any dependencies it has.
For the Concepts, Domain, Events and Read projects, we need to add a dependency only to doLittle, the core part:
PM> Install-Package doLittle
For the Web project we will need more, as we are going to have to configure things. doLittle has support
for all kinds of combinations of IOC containers, database choices and so forth, but for this tutorial
we will be very specific and use a set of extensions to doLittle that we have neatly packed into a
Nuget package called doLittle.Default
.
Note
doLittle is currently dependending on pre-release versions of some of its dependencies (Ninject & FluentValidation) Due to doLittle being marked as a release package, NuGet inside Visual Studio will complain and not install correctly. This experience is not the same using the dotnet CLI and project.json.
In order for you to get things running, you need to explicitly install the FluentValidation and Ninject parts before
the doLittle.Default
package.
Or through the package manager console:
PM> Install-Package Ninject -version 4.0.0-beta-0134
So select the Web project and do:
PM> Install-Package doLittle.Default
What this does is setup doLittle with Ninject as IOC Container, Newtonsoft JSON, FluentValidation and SignalR. It also configures doLittle to treat this as a single page application and adds an HTML file that just sets up doLittle for you to start working with it.
Frontend
We're fond of doing top-down development, starting in the frontend and move downwards.
The feature we're going to create is going to be the registration of Employees. Inside your web project, add a folder called Features and inside it add another folder called Employees. Now we're going to add the view for the registration. Add an HTML file called register.html inside the Employees folder. We're going to add some HTML within the body tag in the newly created file.
<fieldset>
First Name
<input type="text" />

Last Name
<input type="text" />

Social Security Number
<input type="text" />

<button>Register</button>
</fieldset>
Now we're going to add a viewmodel that will be associated with your feature.
doLittle.namespace("HumanResources.Employees", {
register: doLittle.Type.extend(function() {
})
});
In the index.html file sitting at the root of your Web project, go and add the following within the body tag:

Running your application with index.html as your startup page now should show the registration page you created. For now we're going to leave it at that. We will revisit this when we have the necessary bits ready in the C# code.
Domain
The domain is were you define your systems behaviors, and its what represents the vocabulary of your system, the verbs and the nouns. We will be structuring our domain according to principles found in Domain Driven Design.
Bounded Contexts
A bounded context is a context that contains its own vocabulary or own representations of elements found in the domain in your particular system. For instance if you were doing an e-commerce solution, something that tends to show up is the term product. But in most places within an e-commerce business, product is hardly used by the people in the different bounded contexts. Take the warehouse, they do not see products but rather the boxes and the characteristics of those boxes such as dimensions and weight, while the name of the product inside the box is irrelevant to them. Another bounded context in e-commerce would be the purchasing department were they see other aspects of the product, they are mostly interested in margins and other economical data. While for the user hitting the e-commerce site, they are interested in a lot of details about the product. The purpose of establishing the bounded contexts for these are then to be able to model what is relevant to the different parts of an organization like this.
For this tutorial we will have one bounded context, its going to be called "Human Resources".
Modules
Within a bounded context, we talk about modules. These are more technical in nature. Its a way of grouping relevant elements within a bounded context together. Take the e-commerce example, anything related to Products within a bounded context could for instance be put into a module with the name of Products. We consider Modules as optional, but helpful in structuring an application. One of the things that we highly recommend to do is to not try to make one big application, but rather see them as many small ones and compose them together. Modules is part of this fragmentation and helps focusing on decoupling your software.
Concepts
A concept is a lightweight representation of something you have in your domain vocabulary. Instead of losing what things are by using primitives such as booleans, integers or strings, we encapsulate these parts of the vocabulary into what we call concepts. doLittle has a baseclass to help you out with this and something that is supported throughout doLittle; ConceptAs<>. We recommend making concepts available for both your read side and your execution / behavior side, this is were the Concepts project we created earlier comes into play.
For this particular tutorial we will be needing one Concept. We are working with persons, more specifically employees that we are going to register, a natural key that represent a person is the social security number assigned at birth.
Inside the Concept project create a folder called Persons. Add a new class inside the new folder called SocialSecurityNumber.
using doLittle.Concepts;
namespace Concepts.Persons
{
public class SocialSecurityNumber : ConceptAs<string>
{
public static implicit operator SocialSecurityNumber(string socialSecurityNumber)
{
return new SocialSecurityNumber { Value = socialSecurityNumber };
}
}
}
The concept can now be used and be capable of going back and forth from primitives, something you'll see be handy when we get to applying events. We only need to implement the implicit operator for going from the underlying type; string, to the concept itself. The other implicit operator sits at the base-class.
Command
A command represents the behavior you want to happen in your system. It represents the intent of the user and is optimized for one purpose and the idea is to not reuse commands across the system. With a command, one can also express so much more than just what it is doing, but also the why, its all just a question of how you name the command. And don't be afraid to dive in and make many commands that effectively is doing the same thing, remember that inheritance is fine and you can have a base one representing the actual behavior that you want to happen in the system but be very explicit on the deriviatives of the users intentions. It is very important to recognize a command to be something you want to happen in the system, so we model it so.
For our tutorial we will not be all too creative, we will simply be adding a RegisterEmployee command.
using doLittle.Commands;
using Concepts.Persons;
namespace Domain.HumanResources.Employees
{
public class RegisterEmployee : Command
{
public SocialSecurityNumber SocialSecurityNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Input validation
Performing a behavior in a system needs to be validated that it is correct before we can apply it. Validation is divided into two steps; Input and Business. Input being typically connected with properties and consumed on a client. doLittle generates metadata that can be used directly by clientside validators.
Lets start by adding an Input validator for our command. Add a file next to the command called RegisterEmployeeInputValidator and make it look like below:
using doLittle.Validation;
using FluentValidation;
namespace Domain.HumanResources.Employees
{
public class RegisterEmployeeInputValidator :
CommandInputValidator<RegisterEmployee>
{
public RegisterEmployeeInputValidator()
{
RuleFor(c=>c.FirstName)
.NotEmpty()
.WithMessage("You have to specify the first name");
RuleFor(c=>c.LastName)
.NotEmpty()
.WithMessage("You have to specify the last name");
}
}
}
Business validation
Business validation is the next step after basic input validation has been executed. You would normally use business validation to perform more complex scenarios and things that are more cross cutting within the command and not necessarily linked to a property. Instead of using the RuleFor() method, you might find the ModelRule() method more convenient in this.
Business validators tend to be more involved than property level, they can access resources like the database or similar to get to their validation.
For now, business validation is not something we will be performing at this stage. But the way you would write one is very similar to that of an input validator:
using doLittle.Validation;
using FluentValidation;
namespace Domain.HumanResources.Employees
{
public class RegisterEmployeeBusinessValidator :
CommandBusinessValidator<RegisterEmployee>
{
}
}
Security
Normally we would at this stage be looking at security and doLittle has a very similar approach as with validation to how to setup security. We will not be doing this in this tutorial, it will be the subject of another tutorial.
Events
Now that we have our command and it has been validated through the system, its time to turn what we want to have happen to the system into something that has happened, the things that make up the truth in the system; the events. Naming plays an important role here. We turn the naming around and say that things have happened, so registering an employee becomes; EmployeeRegistered. Notice that we also don't use the domain concept on the event. This is due to the fact that we want to keep our events as simple as possible. This because of serialization, persistence and in general avoid potential problems with versioning of types and such. So only primitives for this particular part.
Recreate the bounded context and module structure in the Events project and add the EmployeeRegistered class into the Employees module and make it look like this:
using System;
using doLittle.Events;
namespace Events.HumanResources.Employees
{
public class EmployeeRegistered : Event
{
public EmployeeRegistered(Guid eventSourceId) : base(eventSourceId) {}
public string SocialSecurityNumber { get; set; }
public string FirstName { get; set; )
public string LastName { get; set; }
}
}
Aggregate Root
Once we have our event we need something to apply it, this is were we create an aggregate, a transactional boundary that can apply the event. These aggregates do not expose any public state, only public behaviors - or methods as we call them in C#. They can hold internal state and have their state be populated from the events they self have generated over time by implementing a private On() method that takes in the event it wants to respond to.
The aggregate should be modelled as the entities that goes together, any invariants that are related to each other and goes together as a transaction should be kept together. This is very different from more traditional ways of modelling a domain were a transaction is just whatever change you are doing.
It also represents the actual business process, rather than the noun. This makes it a lot more clear from a domain perspective.
Going back in the Domain project in the HumanResources and Employees folder, add a class called Registration, it should look like below:
using System;
using doLittle.Domain;
using Events.HumanResources.Employee;
namespace Domain.HumanResources.Employees
{
public class Registration : AggregateRoot
{
public Registration(Guid id) : base(id) {}
public void Register(
SocialSecurityNumber socialSecurityNumber,
string firstName,
string lastName)
{
Apply(new EmployeeRegistered(Id)
{
SocialSecurityNumber = socialSecurityNumber,
FirstName = firstName,
LastName = lastName
}):
}
}
}
As you can see, we're modelling the process of registration, rather than putting in the noun Employee here.
Command Handler
All we've done now is introduce a command, some validation, an event and an aggregate that can apply the event. But we haven't added any code that can handle the command. CommandHandlers are responsible for taking a command and performing the necessary actions in the domain. Implementing command handlers is very easy, all one has to do is create a class and stick a marker interface called IHandleCommands in there and just start implementing by convention public methods called Handle() that takes the specific command you want to handle in as a parameter. There can only be one handle method in the system per command.
In the domain project, lets add a class called CommandHandlers next to the command and the validators and the aggregate. Make it look like below:
using doLittle.Commands;
using doLittle.Domain;
namespace Domain.HumanResources.Employees
{
public class CommandHandlers : IHandleCommands
{
IAggregateRootRepository<Employee> _repository;
public CommandHandlers(IAggregateRootRepository<Employee> repository)
{
_repository = repository;
}
public void Handle(RegisterEmployee command)
{
var employee = _repository.Get(Guid.NewGuid());
employee.Register(
command.SocialSecurityNumber,
command.FirstName,
command.LastName);
}
}
}
CommandCoordinator
In doLittle there is entry point for commands, this is the place that all commands go through. Using the entire stack of doLittle, you don't necessarily see this system. The CommandCoordinator is responsible for coordinating the pipeline of a command, the unit of work in which a command lives in. The unit of work is called CommandContext and is unique for every command instance that goes through the system. At the very end of such a unit of work, doLittle commits any events that was applied during the unit of work. This is similar to a transaction.
CommandResult
From the CommandCoordinator comes an object containing information about the result of handling a command; CommandResult. In this you'll find details about validation, possible exceptions, security rules that might have been broken and such. It does not hold details about what happened in any event subscribers as they are not part of the unit of work of a command, but can be asynchronously processed.
ReadModel
Now that we've taken care of business and applied events, we must look at the consequences of this. Lets start with the end result, the data what we will have. In doLittle we refer to this as a readmodel, and we have a marker interface called IReadModel.
Lets go into the Read project and recreate the bounded context and the module structure; HumanResources.Employees. Add a class called Employee and make it look like below:
using System;
using doLittle.Read;
namespace Read.HumanResources.Employees
{
public class Employee : IReadModel
{
public Guid Id { get; set; }
public SocialSecurityNumber SocialSecurityNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Event processor
With the readmodel in place, we can finally start processing the event and actually insert the data we generate from it into our datasource. We call these processors EventSubscribers and we register subscriptions for them. In order to be able to process events, we do things similar to how we did the command handler. We create a class, mark it with an interface called IProcessEvents and implement a public method called Process() taking the specific event that you want to process as a parameter. You can have multiple of these Process() methods around the system responding differently to the event coming through. For instance, you could have one subscriber that would deal with the data change that the event causes and another dealing with sending an email or similiar, and they would be separated out in different files blissfully unaware of the other subscribers existense.
using doLittle.Events;
using doLittle.Read;
using Events.HumanResources.Employees;
namespace Read.HumanResources.Employees
{
public class EventSubscribers : IProcessEvents
{
IReadModelRepositoryFor<Employee> _repository;
public EventSubscribers(IReadModelRepositoryFor<Employee> repository)
{
_repository = repository;
}
public void Process(EmployeeRegistered @event)
{
_repository.Insert(new Employee
{
Id = @event.EventSourceId,
SocialSecurityNumber = @event.SocialSecurityNumber,
FirstName = @event.FirstName,
LastName = @event.LastName
});
}
}
}
Query
In order to get the data out, doLittle comes with a formalization of querying that we will be using. The formalization involves creating a class representing the different queries one needs with the name of the class giving away the name of the query. All one needs to do then is to implement the IQueryFor<> generic interface and implement the query. The reasoning behind this model is to move the concerns of the client away from the server, so typically paging and similar things is not something you have to concern yourself about - doLittle will amend this information to the IQueryable<> that you return.
In the Read project inside the Employees folder, add a class called AllEmployees and make it look like below:
using doLittle.Read;
namespace Read.HumanResources.Employees
{
public class AllEmployees : IQueryFor<Employee>
{
IReadModelRepositoryFor<Employee> _repository:
public AllEmployees(IReadModelRepositoryFor<Employee> repository)
{
_repository = repository;
}
public IQueryable<Employee> Query
{
get
{
return _repository.Query;
}
}
}
}
Going back up to the frontend
With all the artifacts we now in C#, doLittle produces a set of proxies at runtime that the JavaScript can take advantage of.
ViewModel
Remember the ViewModel that we put in, not very exciting - in fact, nothing happening in it at all. With everything in place now we can basically start taking dependencies into the viewmodel and use data-binding to hook it all up in the view.
Lets modify the viewmodel to look like this:
doLittle.namespace("HumanResources.Employees", {
register: doLittle.Type.extend(function(registerEmployee, allEmployees) {
var self = this;
this.register = registerEmployee;
this.employees = allEmployees.all();
})
});
Basically what we`ve done now is to take a dependency on the command we created and the query we created. doLittle generates a proxy for these and you can just use them directly like above. Inside doLittle there sits an IOC (Inversion of Control) container that resolves dependencies in different ways, one being well known commands and queries coming from proxies.
View
Now that we have that we can go ahead and modify the view to be take advantage of the command and the query. Going into the view file, we need to make it look like this:
<fieldset>
First Name
<input type="text" data-bind="value: register.firstName" />

Last Name
<input type="text" data-bind="value: register.lastName" />

Social Security Number
<input type="text" data-bind="value: register.socialSecurityNumber" />

<button data-bind="command: register">Register</button>
</fieldset>
You might notice that naming is slightly different from the client JavaScript code to the C# code, varying on casing. doLittle adhers to what is expected in the different spaces, read more here.
What the above alteration has done is to add binding of the values on the commands into the inputs. In addition we add validation messages using a binding handler that comes with doLittle called "validationMessageFor" which points to the same values as its input is bound to. The button gets bound up using another binding handler from doLittle; command, and is bound directly to the command sitting on the viewmodel.
The app should now be capable of executing the command and have all validation hooked up automatically. You can confirm this by not entering anything into the fields and clicking the button should yield the error messages in the client. If you use rules that can only be run on the server, the error messages will still propagate into the client.
Showing the consequence; data
Now that we are firing off commands, we want to be able to actually show the data this produced. In our view we just add the following below the fieldset.

Social Security Number
First Name
Last Name

This should now be showing the result.


Module: Pinterest
- Defined in:
- lib/pinterest/client.rb,
lib/pinterest/errors.rb,
lib/pinterest/version.rb,
lib/pinterest/collection.rb,
lib/pinterest/models/pin.rb,
lib/pinterest/models/user.rb,
lib/pinterest/models/board.rb,
lib/pinterest/models/image.rb,
lib/pinterest/models/entity.rb,
lib/pinterest/endpoints/pins.rb,
lib/pinterest/endpoints/users.rb,
lib/pinterest/models/interest.rb,
lib/pinterest/endpoints/boards.rb,
lib/pinterest/endpoints/authentication.rb
Overview
This file is part of the pinterest-ruby gem. Copyright (C) 2017 and above Shogun<EMAIL_ADDRESS>Licensed under the MIT license, which can be found at http://www.opensource.org/licenses/mit-license.php.
Defined Under Namespace
Modules: Endpoints, Errors, Version Classes: Board, Client, Collection, Entity, Image, Interest, Pin, User


Hit and run caught on cam
by Chris Campbell / Burnaby NowA Burnaby driver slammed into a parked SUV and didn't even stop to check the damage.
The hit and run was caught on security camera from across the street in the Duthie/Curtis area on Sunday, about 11:20 a.m.
The older compact car slams into the front of the SUV, and the driver keeps going without a moment's hesitation.
The owner of the crunched SUV shared the video with Glacier Media in hopes someone might recognize the offending vehicle.
The neighbour who captured the video ran outside to get a licence number, but the white male driving was already speeding off.