text:
Q: remove  tags from the_content I've got a post format of Image, and I am running into an issue where the image is being wrapped by a <p> tag. I want to get rid of that tag (specifically on the single.php version) of those post types.
How can I get inside the formatting in a theme and remove the <p> tags, or create any format that I want for the output of this type of post, without affecting posts of a different post format?

A: Wordpress automatically ads the <p> tags to the content. So it shows up while loading the content. This is with the filter wpautop. So we will remove this filter for the image post type only. You can manage this by adding the following code in functions.php file.
// Add the filter to manage the p tags
add_filter( 'the_content', 'wti_remove_autop_for_image', 0 );

function wti_remove_autop_for_image( $content )
{
     global $post;

     // Check for single page and image post type and remove
     if ( is_single() && $post->post_type == 'image' )
          remove_filter('the_content', 'wpautop');

     return $content;
}

is_single() checks if a single post is being displayed.

A: If this post type is called "image", you can create a single template to handle the display of just the image post type.
Just copy your 'single.php' file and rename the copy 'single-image.php'. Now you can control just the image posts. To strip out tags, I like to use the strip_tags() function. If you print the content of the post with the_content() it already applies the content filter, wrapping lines in <p> tags.
Here is an example of how you could get the content of your image without the tags:
$imageContent = get_the_content();
$stripped = strip_tags($imageContent, '<p> <a>'); //replace <p> and <a> with whatever tags you want to keep after the strip
echo $stripped;

Hope this helps!

A: By default, WordPress adds paragraph  tags to category descriptions. Stop this by adding the following to your functions.php file
// Remove p tags from category description
remove_filter('term_description','wpautop');

Simple and easy (codeless).
Thank you

A: You can use get_the_content() instead of the_content().
This may solve your problem and another solution is same as described by @Chittaranjan

A: Simply add below line of code in your theme's functions.php file
For content :
remove_filter( 'the_content', 'wpautop' );

For excerpt
remove_filter( 'the_excerpt', 'wpautop' );

learn more : https://codex.wordpress.org/Function_Reference/wpautop

A: You can use specific post class for the single-post or single-format-standard and make it hide as you require only in a single page so that it won't be a conflict for other parts of the website.
Example CSS Code*
.single-post .entry-content p:empty { display: none; }

Example CSS Code for specific post format Image
.single-format-image .entry-content p:empty { display: none; }

A: Inorder to remove the p tag from the content you can use the below code
<?php remove_filter ('the_content', 'wpautop'); ?>

A: Another way to code it based on the solution by @chittaranjan
add_filter( 'the_content', 'remove_autop_for_image', 0 );

function remove_autop_for_image( $content ) {
     global $post;

     if ( is_singular('image'))
          remove_filter('the_content', 'wpautop');

     return $content;
}

A: put this code in "style.css" of "Active child theme"
p:empty {
  display: none;
}

A: if want to remove from particular page or post you can call this
<?php remove_filter ('the_content', 'wpautop'); the_content(); ?>

A: Using wp_strip_all_tags you can get rid of all html tags including p, div and etc
https://developer.wordpress.org/reference/functions/wp_strip_all_tags/
wp_strip_all_tags(category_description());

A: though the query has been answered, I'm posting the below for further reference.
remove_filter ('the_exceprt', 'wpautop');

remove_filter ('the_content', 'wpautop');

remove_filter('term_description','wpautop');

Source


text:
Q: How do I keep the last 10 entries and delete the rest? User has more than 20 records in a table. I only want to keep the last 10 entries. Which means I want to delete the rest.
I want to do this for each user in that table as well.
How should I go about this?

A: Item.destroy(Item.order('created_at').all.last(10).map(&:id))

There's probably a less expensive way to do it, but that should work for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ductile metal makes sharper edge? I've read that, because it is so malleable, gold can be made into an extremely thin sheet, thinner than most other metals. Coming straight to the point, my question would be: While it would wear out practically instantly, would this allow gold to get a sharper edge than other metals, essentially becoming a super-single use scalpel? And how would it stack up against other super edges, like obsidian and diamond blades? Just curious.

A: Ductility is not related to the property of accept a sharp edge. As you said, it can be done also with brittle materials like obsidian or diamond.
Really it is more difficult to sharpen a gold sword than a quenched and tempered steel one. Fragments of material goes along with the cutting tool, instead of falling down as small chips. Sharpen is more a cutting process than a plastic deformation one.
But a gold sword with a sharp edge can hurt a lot anyway


text:
Q: Correct GLM or NLS to model exponential model with response variable with positive and negative values I have been struggling to find the right way to model this dataset, this is a Data Frame with the dataset:
Example_Data <- structure(list(Y = c(
  -0.646528881822999, -0.5172231054584, -0.510079139913394,
  -0.402518490005774, -0.385693032482023, -0.372908622908623, -0.328852788959172,
  -0.323765626091208, -0.323360507610136, -0.322561692126909, -0.319093286835222,
  -0.31441821757193, -0.312787095395791, -0.304006133793368, -0.289417944590358,
  -0.283638477186864, -0.273148888533504, -0.269428962035966, -0.265198174045359,
  -0.262437948152234, -0.258498917035502, -0.254570747217806, -0.246911498081545,
  -0.234405021134879, -0.229087757591321, -0.226531875386837, -0.203956533853441,
  -0.20265079420009, -0.200511322132944, -0.195576484733111, -0.189092318124576,
  -0.186287982898152, -0.183940138485593, -0.183864161559329, -0.173351884195258,
  -0.168372627947096, -0.167440878378378, -0.163389817897733, -0.15827027027027,
  -0.157639711424572, -0.157263782065054, -0.156517276770441, -0.156517276770441,
  -0.156449763926399, -0.155584392339359, -0.151310009818614, -0.151252169600793,
  -0.149030386318522, -0.149004876153113, -0.148193136957182, -0.148082213950477,
  -0.147996452050506, -0.146546546546547, -0.143490725539683, -0.141565536914374,
  -0.13960331299041, -0.137387387387387, -0.137047487863915, -0.133134480375396,
  -0.131891891891892, -0.128133314661812, -0.122547634742757, -0.116427881027247,
  -0.115021998742929, -0.113050193050193, -0.110937105329629, -0.110678510678511,
  -0.109706749263126, -0.105046639559914, -0.100467797463142, -0.100425298394842,
  -0.0995410504844467, -0.0974570629743044, -0.0940293906073374,
  -0.0891161431701972, -0.084186313973548, -0.0791351351351351,
  -0.0785070785070785, -0.0781967738489478, -0.075945427193028,
  -0.0742123805581136, -0.0742123805581136, -0.0704049244974512,
  -0.052992277992278, -0.052476880063087, -0.0440618792511888,
  -0.0432905553255663, -0.0416500711237553, -0.039449219907844,
  -0.0393315780989737, -0.0381435419995831, -0.036036036036036,
  -0.0309121621621622, -0.0291903855164645, -0.0275924460024878,
  -0.0154681655854447, 0, 0, 0, 0.0367046081331796, 0.0666120666120666,
  0.0746910194762956, 0.0873456237694648, 0.0958516656191075, 0.0960377853581737,
  0.101125288857631, 0.10250665172945, 0.103399566814201, 0.106136179097552,
  0.110318496935597, 0.116603833696172, 0.125531622993552, 0.147769914026505,
  0.158059524237953, 0.169736943807487, 0.173461879045635, 0.207160039620773,
  0.213713713713714, 0.222289705435773, 0.234474474474474, 0.250163757013072,
  0.285171658144631, 0.287848997247346, 0.324577702702703, 0.3377032793818,
  0.367338160441609, 0.378598468175015, 0.399096502842901, 0.415241281836799,
  0.437396580253723, 0.525422983959569, 0.554944846669952, 0.567365370357889,
  0.590560709963695, 0.594765651727677, 0.608324902442549, 0.616999293055631,
  0.689630807277866, 0.706113379153532, 0.719933907706833, 0.727344992050874,
  0.80750137892995, 0.820986978881716, 0.827458637344569, 0.961454912856782,
  0.980114059013142, 0.985539044579635, 1
), X = c(
  73376.3934991615,
  108989.76203822, 80956.8990471898, 76099.2985812133, 76900.623531451,
  98260.7092009951, 5157.57790114048, 30820.6795387321, 90177.3769949584,
  75777.9251254972, 54144.4989988793, 88978.3064788961, 27888.23288993,
  56461.8353689865, 110448.861738318, 112173.820609583, 113866.481090548,
  88193.5496923359, 86624.8100834148, 104085.434778549, 85741.3583741874,
  41186.6833252131, 65284.5646726949, 85149.9525214302, 85559.9150389397,
  61195.0493263041, 73264.2724621648, 32068.2542638019, 50869.4024020612,
  107091.769124836, 82257.9544395188, 9849.60340487854, 99159.7652222794,
  32303.6208808293, 69944.3311966181, 90770.2172968661, 12471.3741701687,
  95130.3127734323, 90038.1538169062, 90718.7440528133, 71250.124670451,
  102463.634147458, 89278.7280055428, 92136.0067933825, 73703.8477614749,
  63523.8780758179, 74230.2280241016, 101628.622525462, 61167.5732580155,
  60638.6442549899, 90108.1047746354, 73212.7788821735, 9096.17727006117,
  102435.432907824, 106029.219757365, 85754.9862715359, 6477.95629541751,
  91342.5519621444, 98035.8912685832, 104090.254520417, 66597.7900871458,
  22715.0411128533, 52856.0764092185, 68351.0264782874, 94902.9575756876,
  37534.2825114403, 140021.073330153, 92888.6648850076, 73356.3839464727,
  17218.2818121902, 90718.7440528133, 66146.0292524013, 98169.2858363378,
  101260.526266798, 103114.827080279, 107334.571092804, 50497.6004070263,
  26118.1914947915, 75551.3027817467, 112555.168771616, 95222.2180390191,
  95222.2180390191, 99970.5161385444, 60124.3745720035, 84533.5577261424,
  88797.6323826909, 85979.6084009005, 40395.2474581588, 29622.485242982,
  34021.650581241, 104188.944439581, 97363.0590907177, 41991.8378331259,
  90983.4443890642, 37402.2319634528, 68992.367022227, 20453.7899292494,
  96289.402156546, 62203.7060150694, 25262.275303754, 43726.5886744504,
  17130.9939045931, 22884.9895481025, 7145.63899258642, 72058.1892781364,
  3227.33385134628, 51966.2649320912, 5360.16800260167, 6214.23467758991,
  54768.4704168219, 8099.89207587154, 17175.2636997988, 6198.3000754135,
  28297.3261202508, 45073.8418558188, 6124.85470448711, 4732.46793860604,
  85195.2162860544, 10431.1362666056, 44405.1338499369, 29838.2693636617,
  63630.8310422971, 5499.65480547125, 4992.30879089013, 8817.58452161529,
  5801.14057475208, 5921.92115270202, 8528.42240081873, 7063.86021329663,
  10278.4337738267, 6029.81388864381, 7040.69161676212, 57556.0389612851,
  6753.0933741021, 5665.54685867964, 5317.56598804313, 6897.71522436381,
  7805.38044965523, 6174.40416180664, 97386.2972828469, 6154.75085293128,
  5413.95743794229, 8126.04433315438, 5774.28385069807, 6322.22812627604,
  3479.24351961031, 4991.36126383291, 5385.39494240332
)), row.names = c(
  NA,
  -148L
), class = c("tbl_df", "tbl", "data.frame"))

For this problem I will use the following packages
# For data wrangling and graphs
library(tidyverse)
# For makin NLS models easier
library(minpack.lm)
# For doing some test with negative binomial distributions
library(MASS)
#>
#> Attaching package: 'MASS'
#> The following object is masked from 'package:dplyr':
#>
#>     select

I will show a lot of what I have done, but I am looking for the best way on how to model this data
First lets see a the structure of the dataset:
As seen in the following graph

the relationship is clearly exponential (at least to my eyes), however there are some complications. Namely the response variable has positive and negative values (which complicates log transformations and exponentials), and also the values are not intergers, which complicates poisson and similar models.
If we look at the distribution of Y, we can see that is more or less normally distributed

This is what I have tried
So I have tried 3 approximations, a NLS using the minpack.lm, a GLM using quasipoisson family and a negative binomial, here are my issues and ideas
NLS
First thing I just tried to use an NLS, which seems reasonable to me, for that I used the minpack.lm package, here is the fitted model:
FitNLS <- nlsLM(Y ~ a * X^b, data = Example_Data, start = list(a = 0.3, b = -2.32999e-05))

Which gives me the following model:
summary(FitNLS)
#>
#> Formula: Y ~ a * X^b
#>
#> Parameters:
#>     Estimate Std. Error t value Pr(>|t|)
#> a  7.292e+04  2.027e+05   0.360     0.72
#> b -1.402e+00  3.242e-01  -4.324 2.82e-05 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 0.2654 on 146 degrees of freedom
#>
#> Number of iterations to convergence: 42
#> Achieved convergence tolerance: 1.49e-08

And the following graph of data vs prediction

This approach has some clear issues, as for example that this model will never make a prediction bellow zero, and in this case this might be quite important
GLM quasipoisson
In order to be able to make this model, I need to transform the Y variable so that is only has positive values, so in order to do that I tried this:
MinY <- abs(min(Example_Data$Y)) + (abs(min(Example_Data$Y)) * 0.01)

Example_Data <- Example_Data %>%
  mutate(Positive_Y = Y + MinY)

This will set my values to go all positive but at the same time some of the values will exceed 1, with this I can try the following:
FitGLM <- glm(Positive_Y ~ I(log(X)), data = Example_Data, family = quasipoisson)

This gives me the following model
summary(FitGLM)
#>
#> Call:
#> glm(formula = Positive_Y ~ I(log(X)), family = quasipoisson,
#>     data = Example_Data)
#>
#> Deviance Residuals:
#>      Min        1Q    Median        3Q       Max
#> -0.99025  -0.15909  -0.00601   0.13789   1.03932
#>
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)
#> (Intercept)  2.48135    0.23382   10.61   <2e-16 ***
#> I(log(X))   -0.27896    0.02293  -12.16   <2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> (Dispersion parameter for quasipoisson family taken to be 0.07508724)
#>
#>     Null deviance: 21.923  on 147  degrees of freedom
#> Residual deviance: 11.213  on 146  degrees of freedom
#> AIC: NA
#>
#> Number of Fisher Scoring iterations: 4

And backtransforming everything I can get the following reponse:

Although this looks quite good and I can get negative values, I am not quite convinced, I choose quasipoisson family because of the fractional data, but this might not be the best option, I guess I could transform this values from 0 to 1 and go quasibinomial with a log link, but that does not sound right either. I have tried also Negative Binomial GLM, but I think I am making my point clear. Any help on the best way of modelling this dataset would be greatly apprecieated
Session info

Standard output and standard error

-- nothing to show --

Session info

sessioninfo::session_info()
#> ─ Session info ───────────────────────────────────────────────────────────────
#>  setting  value
#>  version  R version 4.1.2 (2021-11-01)
#>  os       Ubuntu 18.04.6 LTS
#>  system   x86_64, linux-gnu
#>  ui       X11
#>  language (EN)
#>  collate  en_US.UTF-8
#>  ctype    en_US.UTF-8
#>  tz       Europe/Copenhagen
#>  date     2021-11-08
#>
#> ─ Packages ───────────────────────────────────────────────────────────────────
#>  package     * version date       lib source
#>  assertthat    0.2.1   2019-03-21 [1] CRAN (R 4.1.0)
#>  backports     1.2.1   2020-12-09 [1] CRAN (R 4.1.0)
#>  broom         0.7.9   2021-07-27 [1] CRAN (R 4.1.1)
#>  cellranger    1.1.0   2016-07-27 [1] CRAN (R 4.1.0)
#>  cli           3.0.1   2021-07-17 [1] CRAN (R 4.1.0)
#>  codetools     0.2-18  2020-11-04 [1] CRAN (R 4.1.0)
#>  colorspace    2.0-2   2021-06-24 [1] CRAN (R 4.1.0)
#>  crayon        1.4.1   2021-02-08 [1] CRAN (R 4.1.0)
#>  curl          4.3.2   2021-06-23 [1] CRAN (R 4.1.0)
#>  DBI           1.1.1   2021-01-15 [1] CRAN (R 4.1.0)
#>  dbplyr        2.1.1   2021-04-06 [1] CRAN (R 4.1.0)
#>  digest        0.6.28  2021-09-23 [1] CRAN (R 4.1.1)
#>  dplyr       * 1.0.7   2021-06-18 [1] CRAN (R 4.1.0)
#>  ellipsis      0.3.2   2021-04-29 [1] CRAN (R 4.1.0)
#>  evaluate      0.14    2019-05-28 [1] CRAN (R 4.1.0)
#>  fansi         0.5.0   2021-05-25 [1] CRAN (R 4.1.0)
#>  farver        2.1.0   2021-02-28 [1] CRAN (R 4.1.0)
#>  fastmap       1.1.0   2021-01-25 [1] CRAN (R 4.1.0)
#>  forcats     * 0.5.1   2021-01-27 [1] CRAN (R 4.1.0)
#>  fs            1.5.0   2020-07-31 [1] CRAN (R 4.1.0)
#>  generics      0.1.0   2020-10-31 [1] CRAN (R 4.1.0)
#>  ggplot2     * 3.3.5   2021-06-25 [1] CRAN (R 4.1.0)
#>  glue          1.4.2   2020-08-27 [1] CRAN (R 4.1.0)
#>  gtable        0.3.0   2019-03-25 [1] CRAN (R 4.1.0)
#>  haven         2.4.3   2021-08-04 [1] CRAN (R 4.1.1)
#>  highr         0.9     2021-04-16 [1] CRAN (R 4.1.0)
#>  hms           1.1.1   2021-09-26 [1] CRAN (R 4.1.1)
#>  htmltools     0.5.2   2021-08-25 [1] CRAN (R 4.1.1)
#>  httr          1.4.2   2020-07-20 [1] CRAN (R 4.1.0)
#>  jsonlite      1.7.2   2020-12-09 [1] CRAN (R 4.1.0)
#>  knitr         1.36    2021-09-29 [1] CRAN (R 4.1.1)
#>  labeling      0.4.2   2020-10-20 [1] CRAN (R 4.1.0)
#>  lifecycle     1.0.1   2021-09-24 [1] CRAN (R 4.1.1)
#>  lubridate     1.7.10  2021-02-26 [1] CRAN (R 4.1.0)
#>  magrittr      2.0.1   2020-11-17 [1] CRAN (R 4.1.0)
#>  MASS        * 7.3-54  2021-05-03 [1] CRAN (R 4.1.0)
#>  mime          0.12    2021-09-28 [1] CRAN (R 4.1.1)
#>  minpack.lm  * 1.2-1   2016-11-20 [1] CRAN (R 4.1.0)
#>  modelr        0.1.8   2020-05-19 [1] CRAN (R 4.1.0)
#>  munsell       0.5.0   2018-06-12 [1] CRAN (R 4.1.0)
#>  pillar        1.6.3   2021-09-26 [1] CRAN (R 4.1.1)
#>  pkgconfig     2.0.3   2019-09-22 [1] CRAN (R 4.1.0)
#>  purrr       * 0.3.4   2020-04-17 [1] CRAN (R 4.1.0)
#>  R.cache       0.15.0  2021-04-30 [1] CRAN (R 4.1.1)
#>  R.methodsS3   1.8.1   2020-08-26 [1] CRAN (R 4.1.1)
#>  R.oo          1.24.0  2020-08-26 [1] CRAN (R 4.1.1)
#>  R.utils       2.11.0  2021-09-26 [1] CRAN (R 4.1.1)
#>  R6            2.5.1   2021-08-19 [1] CRAN (R 4.1.1)
#>  Rcpp          1.0.7   2021-07-07 [1] CRAN (R 4.1.0)
#>  readr       * 2.0.1   2021-08-10 [1] CRAN (R 4.1.1)
#>  readxl        1.3.1   2019-03-13 [1] CRAN (R 4.1.0)
#>  rematch2      2.1.2   2020-05-01 [1] CRAN (R 4.1.0)
#>  reprex        2.0.0   2021-04-02 [1] CRAN (R 4.1.0)
#>  rlang         0.4.11  2021-04-30 [1] CRAN (R 4.1.0)
#>  rmarkdown     2.11    2021-09-14 [1] CRAN (R 4.1.1)
#>  rstudioapi    0.13    2020-11-12 [1] CRAN (R 4.1.0)
#>  rvest         1.0.0   2021-03-09 [1] CRAN (R 4.1.0)
#>  scales        1.1.1   2020-05-11 [1] CRAN (R 4.1.0)
#>  sessioninfo   1.1.1   2018-11-05 [1] CRAN (R 4.1.0)
#>  stringi       1.7.5   2021-10-04 [1] CRAN (R 4.1.1)
#>  stringr     * 1.4.0   2019-02-10 [1] CRAN (R 4.1.0)
#>  styler        1.6.2   2021-09-23 [1] CRAN (R 4.1.2)
#>  tibble      * 3.1.5   2021-09-30 [1] CRAN (R 4.1.1)
#>  tidyr       * 1.1.4   2021-09-27 [1] CRAN (R 4.1.1)
#>  tidyselect    1.1.1   2021-04-30 [1] CRAN (R 4.1.0)
#>  tidyverse   * 1.3.1   2021-04-15 [1] CRAN (R 4.1.0)
#>  tzdb          0.1.2   2021-07-20 [1] CRAN (R 4.1.1)
#>  utf8          1.2.2   2021-07-24 [1] CRAN (R 4.1.1)
#>  vctrs         0.3.8   2021-04-29 [1] CRAN (R 4.1.0)
#>  withr         2.4.2   2021-04-18 [1] CRAN (R 4.1.0)
#>  xfun          0.26    2021-09-14 [1] CRAN (R 4.1.1)
#>  xml2          1.3.2   2020-04-23 [1] CRAN (R 4.1.0)
#>  yaml          2.2.1   2020-02-01 [1] CRAN (R 4.1.0)
#>
#> [1] /home/derek/R/x86_64-pc-linux-gnu-library/4.1
#> [2] /usr/local/lib/R/site-library
#> [3] /usr/lib/R/site-library
#> [4] /usr/lib/R/library

A: I would not try and fit a line through the data points.
The image below, with the x-axis on a log scale, shows that the variation in the y-axis does not strongly relate to the position on the x-axis.
Instead of some smooth curve with 'y' some function of 'x' the distribution seems to be more like a sort of step function. You have very different behavior of the points below and above 15 km.
You might plot some sort of sinusoid curve through the points. But it won't be well determined with a regression algorithm.

*

*In the image below I have manually plotted a curve. In the region below 15 km (the blue points) you can see that the points mostly differentiate in the horizontal direction. In the vertical direction, there are large variations.

*If you would fit a curve through these points, then the optimum, that minimizes the vertical distance, would be a curve through the middle, around the value of 0.5. Probably not what you had expected (you might be thinking of a curve that goes to 1).

In my opinion, the best would be to just make the plot and potentially describe some clusters. But fitting a curve may have little value. Especially since, as you mentioned in the comments, you have no theory behind the curve. So what would be the point of putting a curve into the diagram?


text:
Q: Huge exception traces in Doctrine I'm new to Doctrine and I'm not using caching due to server settings limitations.
Problem is that Even outside of Doctrine I am getting really huge exception traces for my custom exceptions( the browser cannot render it properly ). As I see traces are getting large because Doctrine stores bunch of configuration data directly attached to every single entity object.
Have anybody familiar with Doctrine experienced something similar?
Is it because of lacking caching?
Anybody knows good slotution?
Thanks for help.

A: It's true that doctrine generates huge exception traces. I always write exceptions to a file. In that case you can easily read it using an editor or command line tool like tail, vi, etc, etc. ( I prefer tail -f at all times while developing)
My experience is that you don't need to look at the complete stacktrace but only at the x-top lines to see what triggers the exception.
Some extra notes:
Because you're talking about caching I asssume you have this problem on a production environment. If so, remember that the performance of Doctrine relies on caching and that it is bad practice to output exceptions to the browser in a production environment.


text:
Q: Full outer join I have a following situation (table schema: ID, first name, last name, value).:
table 1:
ID | first name  | last name  | value
--------------------------------------
1  |    John     | Goodman    |  5
2  |    Peter    | Snow       |  6
3  |    Mike     | Walker     |  7
4  |    John     | Goodman    |  8

table 2:
ID | first name  | last name  | value
--------------------------------------
1  |  Peter      | Snow       | 2
2  |  Bobby      | White      | 1
3  |  Mike       | Walker     | 1
4  |  Brad       | West       | 2
5  |  Peter      | Snow       | 3

I want to write full outer join to get sum on 4th column, but each name should be placed only once in a result (joined) table, like this:
result table:
ID | first name  | last name  | value.table1 | value.table2
-----------------------------------------------------------
1  |  John       | Goodman    | 5            | 0
2  |  Peter      | Snow       | 6            | 5
3  |  Mike       | Walker     | 7            | 1
4  |  Bobby      | White      | 0            | 1
5  |  Brad       | West       | 0            | 2

How can I achieve this ?

A: Something like this should work (if I ignore the ID column for now):
SELECT
    COALESCE(t1.FirstName,t2.FirstName) as FirstName,
    COALESCE(t1.LastName,t2.LastName) as LastName,
    COALESCE(t1.value,0) as t1value,
    COALESCE(t2.value,0) as t2value
FROM
    (select FirstName,LastName,SUM(value) as value
     from table1
     group by FirstName,LastName) t1
        full outer join
    (select FirstName,LastName,SUM(value) as value
     from table2
     group by FirstName,LastName) t2
        on
            t1.FirstName= t2.FirstName and
            t1.LastName=  t2.LastName

A: With s as (Select firstname, lastname , value
From table1
Union all
Select firstname, lastname , value
From table2)
Select firstname, lastname , sum(value)
From s
Group by firstname , lastname

A: Try this:
SELECT COALESCE(T1.FName,T2.FName) as FName,COALESCE(T1.LName,T2.LName) as LName,ISNULL(T1.Value,0) as Value1,ISNULL(T2.Value,0) as Value2
FROM Table1 T1 FULL OUTER JOIN
     Table2 T2 ON T1.FName=T2.FName AND T1.LName=T2.LName

Explanation:
COALESCE returns the first in the list which is not NULL.
ISNULL is used to replace NULL values with 0.
Result:
FNAME   LNAME   VALUE1  VALUE2
John    Goodman 5       0
Peter   Snow    6       2
Peter   Snow    6       3
Mike    Walker  7       1
John    Goodman 8       0
Bobby   White   0       1
Brad    West    0       2

See result in SQL Fiddle.

A: This is the working solution for mySQL, ignoring the ID column:
SELECT FirstName,
       LastName,
       SUM(tot1)
FROM   (SELECT FirstName,
               LastName,
               sum(value) as tot1
        FROM   table1
        GROUP BY  FirstName,
                  LastName
        UNION  SELECT FirstName,
               LastName,
               sum(value)
        FROM   table2
        GROUP BY  FirstName,
                  LastName) t
GROUP BY  FirstName,
          LastName

A: Declare @table1 Table (ID int, firstname varchar(30), lastname varchar(30), value int)
Declare @table2 Table (ID int, firstname varchar(30), lastname varchar(30), value int)
Insert into @table1 values
(1,'John', 'Goodman', 5 ),
(2,'Peter', 'Snow', 6   ),
(3,'Mike', 'Walker', 7  ),
(4,'John', 'Goodman', 8 )

Insert into @table2 values

(1, 'Peter', 'Snow', 2 ),
(2, 'Bobby', 'White', 1),
(3, 'Mike', 'Walker', 1),
(4, 'Brad', 'West', 2  ),
(5, 'Peter', 'Snow', 3 )

Select  A.*,
        ISNULL(B.value,0) [value.t1],
        ISNULL(C.value,0) [value.t2]
From    (
Select  row_number() over (order by firstname) id,*
From    (
        Select firstname,lastname from @table1
        union all
        Select firstname,lastname from @table2
        ) Lu
group   by firstname,lastname) A
Left Join (Select firstname,lastname,Min(value) value From @table1 Group By firstname,lastname) B On A.firstname = B.firstname And A.lastname = B.lastname
Left Join (Select firstname,lastname,Sum(value) value From @table2 Group By firstname,lastname) C On A.firstname = C.firstname And A.lastname = C.lastname

Result


text:
Q: Uncaught ReferenceError: writeData is not defined at HTMLButtonElement.onclick I try to store some objects in my database but for some reason there's a problem with my function. I get the error named in the title.

//here is the Firebase config stuff
function writeData() {
  firebase.database().ref("User").set({
    name: document.getElementById("namefield").value,
    age: document.getElementById("agefield").value
  });
}

Test

<input type="text" placeholder="name" id="namefield">
<input type="text" placeholder="age" id="agefield">
<button onclick="writeData()">Submit</button>


text:
Q: Determining most/least amount of occurrences within subset row & column group in a data frame I am trying to find the most and least amount of items within a row / column group in a larger data frame. Here is the data to make it clearer:
df <- data.frame(matrix(nrow = 8, ncol = 3))
df$X1 <- c(1, 1, 1, 2, 2, 3, 3, 3)
df$X2 <- c("yellow", "green", "yellow", "blue", NA, "orange", NA, "orange")
df$X3 <- c("green", "yellow", NA, "blue", "red", "purple" , "orange", NA)
names(df) <- c("group", "A", "B")

Here is what that looks like (I have NAs in the original data, so I've included them):
  group      A      B
1     1 yellow  green
2     1  green yellow
3     1 yellow   <NA>
4     2   blue   blue
5     2   <NA>    red
6     3 orange purple
7     3   <NA> orange
8     3 orange   <NA>

In the first "group", for instance, I want to determine which color occurs the most and which color occurs the least. Something that looks like this:
  group      A      B   most  least
1     1 yellow  green yellow  green
2     1  green yellow yellow  green
3     1 yellow   <NA> yellow  green
4     2   blue   blue   blue    red
5     2   <NA>    red   blue    red
6     3 orange purple orange purple
7     3   <NA> orange orange purple
8     3 orange   <NA> orange purple

I am working within a dplyr chain in the original data so I can group_by "group", but I am having a hard time figuring out a method that allows me to work within a "cluster" of two columns with differing numbers of rows. I do not need this to be done with dplyr, but I figured it might be easiest given the usefulness of group_by. Additionally, I need the result to somehow remain in the original data frame as new columns. Any suggestions?

A: A solution uses dplyr and tidyr. The strategy is to find the "most" and "least" item and prepare a new data frame. After that, use the right_join to merge the original data frame and prepare the desired output.
Notice that during the process I used slice to subset the data frame to get the most and least item. This guarantees that there will be only one "most" and one "least" for each group. Nevertheless, it is possible that there could be a tie for each group. If that happens, you may want to think about what could be a good rule to determine which one is the "most" or which one is the "least".
library(dplyr)
library(tidyr)

df2 <- df %>%
  gather(Column, Value, -group, na.rm = TRUE) %>%
  count(group, Value) %>%
  arrange(group, desc(n)) %>%
  group_by(group) %>%
  slice(c(1, n())) %>%
  mutate(Type = c("most", "least")) %>%
  select(-n) %>%
  spread(Type, Value) %>%
  right_join(df, by = "group") %>%
  select(c(colnames(df), "most", "least"))
df2
# A tibble: 8 x 5
  group      A      B   most  least
  <dbl>  <chr>  <chr>  <chr>  <chr>
1     1 yellow  green yellow  green
2     1  green yellow yellow  green
3     1 yellow   <NA> yellow  green
4     2   blue   blue   blue    red
5     2   <NA>    red   blue    red
6     3 orange purple orange purple
7     3   <NA> orange orange purple
8     3 orange   <NA> orange purple

A: Two options:

*

*Reshape to long form and use summarise (or count) to aggregate, subsetting the which.max/which.min:

library(tidyverse)

df <- data_frame(group = c(1, 1, 1, 2, 2, 3, 3, 3),
                 A = c("yellow", "green", "yellow", "blue", NA, "orange", NA, "orange"),
                 B = c("green", "yellow", NA, "blue", "red", "purple" , "orange", NA))

df %>%
    gather(var, color, A:B) %>%
    drop_na(color) %>%
    group_by(group, color) %>%
    summarise(n = n()) %>%
    summarise(most = color[which.max(n)],
              least = color[which.min(n)]) %>%
    left_join(df, .)
#> Joining, by = "group"
#> # A tibble: 8 x 5
#>   group      A      B   most  least
#>   <dbl>  <chr>  <chr>  <chr>  <chr>
#> 1     1 yellow  green yellow  green
#> 2     1  green yellow yellow  green
#> 3     1 yellow   <NA> yellow  green
#> 4     2   blue   blue   blue    red
#> 5     2   <NA>    red   blue    red
#> 6     3 orange purple orange purple
#> 7     3   <NA> orange orange purple
#> 8     3 orange   <NA> orange purple

*Sort a table of values and subset it:
df %>%
    group_by(group) %>%
    mutate(most = last(names(sort(table(c(A, B))))),
           least = first(names(sort(table(c(A, B))))))
#> # A tibble: 8 x 5
#> # Groups:   group [3]
#>   group      A      B   most  least
#>   <dbl>  <chr>  <chr>  <chr>  <chr>
#> 1     1 yellow  green yellow  green
#> 2     1  green yellow yellow  green
#> 3     1 yellow   <NA> yellow  green
#> 4     2   blue   blue   blue    red
#> 5     2   <NA>    red   blue    red
#> 6     3 orange purple orange purple
#> 7     3   <NA> orange orange purple
#> 8     3 orange   <NA> orange purple


text:
Q: postgres: can I prepare unnamed statement from SQL https://www.postgresql.org/docs/current/static/libpq-exec.html
next to PQprepare:

The function creates a prepared statement named stmtName from the
  query string, which must contain a single SQL command. stmtName can be
  "" to create an unnamed statement, in which case any pre-existing
  unnamed statement is automatically replaced; otherwise it is an error
  if the statement name is already defined in the current session.

and further:

Prepared statements for use with PQexecPrepared can also be created by
  executing SQL PREPARE statements.

now https://www.postgresql.org/docs/current/static/sql-prepare.html

PREPARE name [ ( data_type [, ...] ) ] AS statement

and:

name An arbitrary name given to this particular prepared statement. It
  must be unique within a single session and is subsequently used to
  execute or deallocate a previously prepared statement.

Question:
Can I not create unnamed prepared statement using SQL statement PREPARE? silently reusable and all the rest...
t=# prepare ""(int) as select $1,now();
ERROR:  zero-length delimited identifier at or near """"
LINE 1: prepare ""(int) as select $1,now();

and ommiting the name:
ERROR:  syntax error at or near "as"

Or I'm missing something very obvious?..

A: No. Unnamed prepared statements are only supported on the wire protocol.
They're mainly used for one-shot statements with bind parameters, and for batching.


text:
Q: Replacing a php file with a Vaadin view in Java I have been working with Vaadin for a bit, I am wondering if it is possible to substitute a php file with a Vaadin view.
So in Java, I normally go to a PHP-page to retrieve a file from my server. An indirect download, I guess. In my java project, I have the following code:
URL url = new URL("fileinphp.php");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(3000);
            conn.connect();

The php-page that sends the image is as such:
$file_name = $_GET['file'];
$file_url = '/files/' . $file_name;
header("Content-Description: File Transfer");
    header('Content-Type: ' . mime_content_type($file_url));
    header("Content-disposition: attachment; filename=\"".$file_name."\"");
    readfile($file_url);

Now. I want to try to do the same in Vaadin. So I have tried to make the following page, and connect to it through the url-method above.
@Route("myroute")
public class Test extends Div {

public Test() {
    add(new Label("Does this get through?"));
}
}

All of this combined, provides me with the following body:
To test your app with this browser, enable transpilation in development mode.

Transpilation can be enabled by setting the vaadin.devmode.transpile=true property for the deployment configuration using an application or a system property.

Note that transpilation is always enabled for the build-frontend Maven goal, which is also used when creating a production build of the application.


text:
Q: Trying to build a program to organize safety data and display it in graphs I'm pretty new to coding, I've done more with HTML and CSS than anything, but now I'm trying to learn a new language because I have an idea for something I want to build. I'm not exactly sure what language would be the best for this. I've been trying to learn a little python, but I want to make sure I'm on the right road. What I'm trying to build is a program that would let me have a form that we would fill out anytime we have an accident at my job, the form would have questions like, type of injury, department associate was working in, time of injury, day of the week, etc.. It would also keep track of our Non-Meds, Medicals and osha reportables by shift and in total for the week, month, year or whatever time span you want to see and show it in graphs or pie charts, so the information could be used to determine where our weaknesses are in terms of safety. So the form would basically take the information you input, and store it in the correct category and automatically update the charts. I know I'm probably trying to take on something kind of big, being as I don't know a whole lot about coding, but I feel like working on this would give me a good starting point. I've already made a spreadsheet in excel to get us by for now, but I would like to make something thats more user friendly to update anytime an accident occurs. So what language do you guys think would being a good one to learn to tackle this?
Thanks for any help in advance!

A: I think I would use C# and WPF for creating the input form, because it is pretty easy to build GUIs for windows with C# and Visual Studio. Then I would store the input information into a SQL database for easy querying of the data. To analyze the data I would use python with MatPlot lib to make graphs and visualize the data in an understandable way. Then the C# GUI could display the graphs generated by python in a classical GUI with dropdowns or tabs or whatever fits the purpose.


text:
Q: Получить значение из объекта объектов Запутался в этих объектах, имея следующее, как получить значение id?
object(stdClass)#1 (1)
{
  ["response"]=> object(stdClass)#2 (2)
  {
    ["count"]=> int(18)
    ["items"]=> array(1)
    {
        [0]=> object(stdClass)#3 (7)
        {
            ["id"]=> int(119)
            ["date"]=> int(1475281654)
            ["out"]=> int(0)
            ["user_id"]=> int(999000777)
            ["read_state"]=> int(0)
            ["title"]=> string(5) " ... "
            ["body"]=> string(10) "добро"
        }
    }
  }
}

A: $obj->response->items[0]->id ?


text:
Q: Count the frequency of a specific word in a single cell In Microsoft Excel I wish to count the frequency of a specific word in a cell. The cell contains a few sentences. I am using a formula right now that is working, but not the way I want it to.
A1
my uncle ate potatos. potato was his favorite food. Don't mash the potato, just keep it simple.

B1 (word to count the frequency of)
potato

C1 (forumula)
=(LEN(A2)-LEN(SUBSTITUTE(A2;B2;"")))/LEN(B2)

C1 Results:
3

In C1, I am getting a count 3. I want it just to be 2. So, the formula is counting potatos.
How do I make the function only count exact matches?

A: I've got a solution here but it's not pretty.
The problem, as I indicate in my comment, is that Excel has no internal function to see if a cell contains an 'exact match'. You can check if the total value in a cell is an exact match, but you can't check whether a search term has been conjugated like that. So, we'll need to create a special method which checks for every 'acceptable' ending to a word. In my eyes, this would be anything that ends with space, anything that ends with punctuation, and anything at the end of a cell with nothing after it.
ARRAY FORMULAS
You were on the right track with the LEN - SUBSTITUTE method, but the formula will need to be an array formula to work. Array formulas calculate the same thing multiple times over a given range of cells, instead of just once. They resolve the calculation for each individual cell in a formula and provide an array of results. This array of results must be collapsed together to get a single total result.
Consider as follows:
=LEN(C1:C6)

Confirm this formula with CTRL + SHIFT + ENTER instead of just ENTER. This gives us the LEN of C1, followed by C2, C3... etc., resulting in an array of results that looks like this [assume C1 had "a", C2 had "aa", C3 had "a", C4 had "", C5 had "aaa", and C6 had ""]:
={1;2;1;0;3;0}

To get that as a single number providing the total length of each cell individually, wrap that in a SUM function:
    =SUM(LEN(C1:C6))
Confirmed again with CTRL + SHIFT + ENTER instead of just ENTER. This results in the total length of all cells: 7.
DEFINING AN EXACT MATCH
Now to take your question, you are looking to find all 'acceptable' matches of given word B1, within text A1. As I said before, we can define an acceptable answer as one which ends in punctuation, a space, or the end of the cell. Something at the end of the cell is a special case which we will consider later. First, take a look at the formula below. In cells C1:C6, I have manually typed a comma, a period, a semi-colon; a hyphen, a space, and a slash. These will be the 'acceptable' ways to end the word found in B1.
=LEN(SUBSTITUTE(A1,B1&C1:C6,""))

Confirmed with CTRL + SHIFT + ENTER, this takes the length of the substitution for the search term in B1 appended with the acceptable word-end in C1:C6. So it gives the length for 6 new SUBSTITUTED words. But as this is an array of results, we need to add them together to get a single number, like so:
=SUM(LEN(SUBSTITUTE(A1,B1&C1:C6,"")))

FORMULIZING THE RESULT
To work it as you have in your sentence, we will now need to subtract this length from the length of the original word. Note that there is a problem with doing this simply - since we are searching multiple times, we will need to add the length of the original word multiple times. Consider something like this:
=LEN(A1)-SUM(LEN(SUBSTITUTE(A1,B1&C1:C6,"")))

This won't work, because it only adds the length of A1 once, but it subtracts the length of the substituted strings multiple times. How about this?
=LEN(A1)*6-SUM(LEN(SUBSTITUTE(A1,B1&C1:C6,"")))

This works, because there are 6 word-end terms we search for with C1:C6, so the substitution there will occur 6 times. So we have the original length of the word 6 times, and the length of each substituted word 6 times [keep in mind that if there is no match for, say, "potato;", then that term will give the length of the original word, thus negating one of the times we added the length of that word, as expected].
To finalize this, we need to divide by the number of letters in the search term. Keep in mind that where you have "/LEN(B1)", we will need to add a character for the length of each of our word-ends.
=(LEN(A1)*6-SUM(LEN(SUBSTITUTE(A1,B1&C1:C6,""))))/(LEN(B1)+1)

Finally, we need to add the special case where the last portion of A1 is equal to the search term, with no word-end. Alone, this would be:
=IF(RIGHT(A1,LEN(B1))=B1,1,0)

This will give us a 1 if the last part of A1 is equal to B1, otherwise it gives 0. So now simply add this to our previous formula, as follows:
=(LEN(A1)*6-SUM(LEN(SUBSTITUTE(A1,B1&C1:C6,""))))/(LEN(B1)+1)+IF(RIGHT(A1,LEN(B1))=B1,1,0)

Remember to confirm with CTRL + SHIFT + ENTER, instead of just ENTER. That's it, it now gives you the count of all "exact matches" of your search term.
ALTERNATE APPROACH TO ARRAY FORMULAS
Note that instead of using C1:C6, you could instead hardcode your formula to look for specific punctuation as the word-end. This will be harder to maintain but, in my opinion, just as readable. It will look like this:
=(LEN(A1)*6-SUM(LEN(SUBSTITUTE(A1,B1&{",",".",";"," ","/","-"},""))))/(LEN(B1)+1)+IF(RIGHT(A1,LEN(B1))=B1,1,0)

This is still technically an "array formula", and it works on the same principles as I have described above. However, one benefit here is that you can confirm this type of entry with just ENTER. This is good, in case someone accidentally edits your cell and presses ENTER without noticing. Otherwise, this is equivilent to the format above.
Let me know if you would like any portion of this elaborated on.

A: I do have an alternate solution for you to consider. I takes a bit more space and the formulas are a little more convoluted, but in some senses it will be simpler.
Use column C as a new helper column. Column C will take the text from column A, and will substitute out all instances of punctuation with a " ". Once this has been done, the formula to count the instances of the search term from column B will be a simple formula essentially as you have it in your OP.
 =SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,","," "),"."," "),";"," "),"-"," "),"/"," ")

This formula first substitutes all slashes for spaces, then with that substituted text it substitutes dashes for spaces, then with that substited text it substitutes semicolons with spaces, etc. As you indicated, if you use semi-colons as delimiters, you will need to replace my commas separating terms with semi-colons.
Then the formula in D1 is simply what you have above in your OP, with two changes: we will be searching for B1 & " ", because we know all of the 'exact matches' now end in spaces, and we will be adding in an extra '1' if the last part of the text in C1 is the same as the search term in B1 - because if a cell ends in that word, it won't have a space, but it is still an 'exact match'. Like so:
=(LEN(C1)-LEN(SUBSTITUTE(C1,B1&" ","")))/(LEN(B1)+1)+IF(RIGHT(C1,LEN(B1))=B1,1,0)

EDIT
My list of punctuation was only a suggestion; I recommend you really go through some sample text and make sure you don't have any weird characters after words. Also, consider changing uncommon ones I have (like "/", or "-") with "?" or "!". If you want to add more, just follow the pattern of the SUBSTITUTE formula.
To make this case-insensitive, you just need to change the formula in column C to make the result all lower case, and then ensure your search terms in column B are lower case. Change column C like so:
 =LOWER(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,","," "),"."," "),";"," "),"-"," "),"/"," "))

A: Sorry for making it "a new answer". You may move it wherever you want.
I have just found a solution for the answer Liu Kang asked on Aug 3 2015 at 12:15. :)
Unfortunately, I do not have "50 reputation" to comment on Grade 'Eh' Bacon's solution above, where the last comment is this:

Discovered a slight problem. Using =IF(B1<>"";(LEN(A1)-LEN(SUBSTITUTE(A1;B1&" ";"")))/(LEN(B1)+1)+IF(RIGHT(A1;LEN(B1))=B1;1;0);"") with shoe in B1 gives the following result: shoe in A1 = 1 (correct), shoes in A1 = 0 (correct), ladyshoe in A1 = 1 (wrong). Guess this have to do with "RIGHT" in the formula. Is it possible to make the formula non-matching for prefix words? E.g if B1 is containing shoe and A1 is containing ladyshoe dogshoe catshoes shoes I want C1 to result in 0. – Liu Kang Aug 3 '15 at 12:15

The solution is to search for a space at the beginning of the word as well (" "&B1&" ") and to add "one" more LEN(B1)+2. So, it becomes =IF(B1<>"";(LEN(A1)-LEN(SUBSTITUTE(A1;" "&B1&" ";"")))/(LEN(B1)+2)+IF(RIGHT(A1;LEN(B1))=B1;1;0);"").
There is one more problem if the word we are looking for is at the beginning. Because there is obviously no space " " at the beginning of the sentence. I use a workaround for it - I have my sentence in A1, but then I have a hidden column B where there is =" "&A1 in B1 and it puts the "space" I need to the beginning of the sentence and everything from the original Grade 'Eh' Bacon's solution is shifted (A1->B1, B1->C1, C1->D1).
I hope it can help and thanks to all who participated in this thread, you helped me A LOT!

A: Do you need this to be a single formula?  I have an idea, but it takes a few (relaitvely simple) steps.
Since you have a long sentence in A1, what about going to Data -> Text to Columns, and send this sentence into a Row, delimited by spaces.  Then, remove any punctuation.  Then, just do a simple Countif()?
Put the info in A1, then go to Data --> Text to Columns, choose "Delimited", click Next, and choose "Space":

Click Finish, and it'll put the entire thing into Row 1, with a word in each cell.  Now just Find/Replace "." and "," with nothing.
Then, Countif to the rescue!

If that works, we can automate into VB, so you don't have to manually find/replace the puncutation.  Before I jump into that, does this method work?

A: Take the length of the string and minus the length of the string with the keyword replaced with nothing then divide the result by the length of the keyword:
=(LEN(A1)-LEN(SUBSTITUTE(A1,B1,"")))/LEN(B1)


text:
Q: Desktop computer loses wi-fi connection, when I connects to it an Android device by usb cable I have a desktop computer with a wireless (usb dongle) adapter, Android phone and a router.
The computer identifies the WI-FI net from the router (via wireless usb dongle adapter) , and I can surf.
Then I connect the phone to the same computer by a USB cable (The reason I'm doing it, is that I want to debug an Android application).
At the moment I connect the phone, the computer no longer identify the network, although the network exists (The Android phone identifies it).
Does someone have any idea why, and what can I do about it? Appreciate any help.

A: The problem was solved in a very simple way  - I tried to connect the phone to an other usb socket.
The one which caused the disconnection was in the front of the computer, and the one which didn't cause any disconnection, was in the back of the computer.
Hope it will help someone.


text:
Q: Big-O Notation Q I have a few True/False questions I need to answer, I don't know how to do it. Any help would be appreciated!
(a) True or false: Suppose that you develop an algorithm whose run-time is given by f(n) = 5f(n/2) + 3 for n = 2,4,8,16,32,..., and f(1) = 7. Then the run-time of your algorithm is O(n3), but it is not O(n2).
(b) True or false: f (n) = n3n satisfies the recurrence relation f (n) = 6f (n − 1) − 9f(n−2).

A: For part (a) you can apply the master theorem. The non recursive overhead is O(1), the 'critical' function n^{log_b(a)} is n^{\log_2(5)} = n^{2.321928}. So the algorithm runs in θ(n^{2.321928}), meaning it is not O(n^2). But, it is O(n^3).


text:
Q: Can Insert Object > Text from File use a relative path instead of an absolute path? Problem: I am building training documentation for a client. The client has multiple roles that need to perform the same task. However, for each role there must be a distinct job aid or training manual. The content also changes with relative frequency, so it is important that all the duplicated information remain up to date. Copying and pasting changes across documents is inefficient and can lead to errors.
Proposed solution: I have created a master document with all training content. I have bookmarked all of the training materials. I have inserted the bookmarks as links into the appropriate documents. Now I have one source of truth that can be updated, and changes will be reflected in all documents with a quick field update.
Where I need help: All of this works great until I need to copy it from my company's sharepoint to the client's sharepoint (or even move it between directories on my own company's sharepoint). All of the links break because inserting object > text from file uses absolute paths. Is it possible to use a relative path to insert objects? Also, if I'm way off base here, please let me know if there's another solution.

A: It can be done but requires editing each link field. The process is set forth in Paul Edstein's tutorial on Word Fields and Relative Paths to External Files.

Word tends to store paths to external files with absolute paths. The
fields affected by this include Word's DATABASE, INCLUDEPICTURE,
INCLUDETEXT, LINK, RD and HYPERLINK fields. This means that, should
you need to move the files as a group to another folder (eg putting
them on a CD or USB stick for portability), all the links will break.
What is needed is a means of coercing Word into applying some sort of
relative path addressing for fields pointing to other files. Even if
you omit the path from the field code, in most Word versions it still
gets stored in the file's metadata. The only version I know of that
doesn't always do this is Word 2010 - and even that seems to vary
according to whether the path has ever been stored...
Well, there is a solution (based on an idea originally developed by
Peter Jamieson, another MS Word MVP) that works with DATABASE,
INCLUDEPICTURE, INCLUDETEXT, RD and HYPERLINK fields, but not with
LINK fields. For LINK fields, scroll to the bottom of this thread. The
following example employs an INCLUDEPICTURE field, but works equally
well with DATABASE, INCLUDETEXT, RD and HYPERLINK fields.

To make the INCLUDEPICTURE field look in the current folder, cut &
paste the FILENAME field into it, replacing the document path and
inserting '\..\' or '/ /' between that and the hyperlink file's
name, thus: {INCLUDEPICTURE "{FILENAME \p}/../Image.png"} or
{INCLUDEPICTURE "{FILENAME \p}\..\Image.png"}
How this works: The FILENAME p field extracts the current file's name
and path. The following '\..\' or '/../' tells Word to ignore the
filename and get just the path. Then all you need to do is to add the
source file's name & extension.
The same approach can be extended to implement a form of relative
addressing. For example: {INCLUDEPICTURE "{FILENAME \p}\..\My
Pictures\Image.png"} looks in the child folder named 'My Pictures'
and: {INCLUDEPICTURE "{FILENAME \p}\..\..\Image.png"} looks in the
parent folder, while: {INCLUDEPICTURE "{FILENAME \p}\..\..\My
Pictures\Image.png"} looks in the parent folder, then its child
folder named 'My Pictures' (a sibling folder, so to speak).

The original tutorial includes a helpful macro and more of a breakdown on what is being done.


text: Q: Is there a way to tell what image was used to deploy a machine from Windows Deployment Services? Is there a way to tell what image was used to deploy a machine from Windows Deployment Services?  Is there some sort of a hash that would identify a machine being deployed from a particular image?


text:
Q: How to get last point of each dash-line created after CGContextSetLineDash of a CGPath I am converting the path into dashline to get multiple segments of a CGPATH.
float dash[2]={20 ,1};
int index =0;
    CGContextSetLineDash(context,0,dash,2);
    CGContextReplacePathWithStrokedPath(context);
    dashedpath = CGContextCopyPath(context);
   CGPathApply(dashedpath, &thepobj, visitdashedpath);

and in visitdashedpath I am trying to find the end point of previous (each) dash-line.
void visitdashedpath(void* info, const CGPathElement* element)
{
int nPoints;
pathObj * dasharray = (pathObj *)info;
switch (element->type)
{
  case kCGPathElementMoveToPoint:
      dasharray[index-1].endpoint   =  CGPathGetCurrentPoint(dasharray[index-1].path); [my-option1]
        dasharray[index].path   =  CGPathCreateMutable ();
    break;

    case kCGPathElementAddLineToPoint:

    CGPathAddLineToPoint(dasharray[index].path,NULL,element->points[0].x,element->points[0].y);
    dasharray[index].endpoint   =  CGPathGetCurrentPoint(dasharray[index].path);//[my-option1]

brek;
case kCGPathElementAddcurve:
CGPathAddCurveToPoint(path,c1.x,c1.y,c2.x,c2.y,c3.x,c3.y);
  ----

I want to know the the co-ordinates of last point(dasharray[index-1].endpoint)  by processing completed dash line
I tried CGPathGetCurrentPoint but it gives start point of dash line.
I guess each dash line is made a close-path  by CGContextCopyPath. may be thats why I am getting end point as start point.

A: You're missing a key point of what CGContextReplacePathWithStrokedPath and CGPathCreateCopyByStrokingPath do:

The new path is created so that filling it draws the same pixels as stroking the original path.

So, how would you create a fillable path for a line or curve?
Probably something like:

*

*moveto

*curveto (either the outer or the inner curved edge)

*lineto (one end)

*curveto (either the inner or the outer curved edge)

*closepath (the other end)

That closepath, of course, returns the current point to where step 1 (moveto) started. That's why that's the result you get.
The original points you started with no longer exist in this path. Indeed, depending on how long your curve is, the dash pattern may mean that no segment overlaps your final point—the last segment may fall short of it.
If you want the start and end of each segment, get the current point before and after lineto, and take the average, and do the same for the current point before and after closepath. The two points you get from that are the middle of each straight-line element of the path, which, for a simple curved line segment, will be the start and end of the segment.
I hope your path doesn't have any loops.

A: From the Applee docs:

The path also maintains a current point, which is the last point in
  the last subpath.
Returns the current point in a graphics path.

CGPoint CGPathGetCurrentPoint (
       CGPathRef path
    );

A: Erica Sadun's iOS Developer Cookbook series includes recipes that show how to get the points from a CGPath. I don't have my copies on-hand, but the books are readily available in both print and electronic formats. They are worth their weight in gold for things just like this. I'd suggest getting both the "Core" and "Advanced topics" books.


text:
Q: Listview Android onClick defaul event How could I use onClick event from the base ListView in android without using the Adapter. I what to now witch item is selected and in base of that i want to open another layout.
 listview.item="Something"
{
setContentView(R.id.layout.Something);
}

Please help me. I tried with the simple onClick but it doesn't work.

A: You Need To create layout XML file
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
     <ListView
        android:id="@+id/listview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_below="@+id/view1" >
    </ListView>
</RelativeLayout>

In Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ListView mListView = (ListView)findViewById(R.id.listview);

    mListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
        }
    });
}


text:
Q: Loading a method using a string variable How can i work with something like:
$parameter = "get_something()";

$value = $this->method->$parameter;

I'm getting the error "undefined property $get_something()" (note the $).

A: Try to use
$name = "get_something";
$value = $this->method->$name();

instead


text:
Q: Will major config changes discourage users from deploying code? I'm beginning development on a solution that will plug into an existing application. It will be made available for public use.
I have the option of using a newer technology that promotes better architecture, flexibility, speed, etc... or sticking with existing technology that is tried and tested which the application already uses.
The downside of going with the newer technology is that a major change to an essential config file needs to be made to support it. If the change goes wrong the app would be out of service. Uninstall is also an issue as future custom code by other developers may require the newer tech and there's no way this can be determined.
How important is this issue in considering an approach?
Will significant config changes put users off deploying code, or cause problems for them later?
Edit:

*

*Intentionally not going into specifics about technologies here to avoid the question from being siderailed.

*Install/uninstall software can be provided but there is some complexity involved which may cause them to foul up on edge cases resulting in a dead app. (A backup of the original config would be a way to mitigate that.) Also see the issue about uninstall above where I essentially can't provide one.

A: Yes, in my experience, any large amount of work will make users think twice about deploying or upgrading.
It's your standard cost/benefit analysis done by businesses with just about every decision. Will the expected benefits more than outweigh the potential costs?
When we release updates to our software, there's almost always a major component that's there just to assist the users to migrate.
An example (modified enough to protect the guilty): we have a product which generates reports on system performance and other things. But the reports aren't that pretty and the software for viewing them is tied to a specific platform.
We've leveraged BIRT to give us intranet-based reporting that looks much nicer and only needs the client to have a web browser (not some fat client).
Very few customers made the switch until we provided a toolset that would take their standard reports and turn them into BIRT reports. Once we supplied that, customers started taking it seriously - the benefit hadn't changed, but the cost had gone right down.

A: You've given us no detail, so we can't answer with any specificity. But if your question is, will a significant portion of your potential userbase be deterred from using your product if they have to do significant setup work, then the answer is yes.  I've seen this time and time again, with my own products and those that I've installed myself.  When the only config change is an uninstall and reinstall.  People don't like to do work.
You may want to devote more effort than you've considered so far to making the upgrade painless.  Even if you're upgrading someone else's framework, you may find the effort worthwhile and reflected in an increased number of installs.
I have noticed that "power users" - developers, sysadmins, etc. - are willing to put up with more setup work.

A: I'm not sure what you mean by "major config change", but if you're talking about settings / configuration files, then I've been doing something like this:
An application always contains a default configuration which is useful for most users, and which can't be replaced. Instead, users can override one or more of the default settings in their own, separate configuration file. When a new (major) version is released, most users don't need to reconfigure anything: their own custom configurations are still taken from their own configuration file, and possibly required new parameters are taken from the new release's default settings.
It's obvious that most users don't want waste their time adjusting some settings that already were right - and quite rightfully so.


text:
Q: UiBinder: Can UiFactory method be overriden? Before asking a question i will shortly describe the context.
I have a Widget class which "outsources" ui implementation to a separate class (sth like below):
public class SimpleFilmWidget extends Composite implements FilmActivityControl {

    public static interface Ui {

        Panel getMainPanel();

        VoteWidget getVotePanel();

        InlineLabel getHaveNotSeenLabel();

        //...
    }

The actual widget class can get references to specific subfield widget/elements with use of the Ui class instance:
    Ui ui;

    public SimpleFilmWidget() {
        this(new DefaultUi());
    }

    public SimpleFilmWidget(Ui customUi) {

        assert customUi != null : "UI should not be null!!!";

        ui = customUi;

        initWidget(ui.getMainPanel());
    }

I provided the actual UI implementation with UiBinder that uses UiFactory for creation of another one complicated subwidget
class DefaultUi implements Ui {

    //...

    @UiFactory
    protected VoteWidget createVoteWidget(){

        return new VoteWidget(msg){

            @Override
            protected SetVoteEvent onSetVote(Star star, boolean fireEvents) {
                return clientWidget.onSetVote(super.onSetVote(star, fireEvents));
            }
        };
    }

And the question is:
When I provide the subclass of DefaultUi can the UiFactory method be overriden in a subclass not confusing UiBinder parser?
EDIT:
UiFactory method should not be overriden as uibinder sees both methods (the overridden and the overwriting) and becomes confused with two uifactories for the same type: [ERROR] Duplicate factory in class SimpleFilmWidget.DefaultUi for type VoteWidget

A: I see no reason it wouldn't be possible: UiBinder looks at the exposed API, and calls the method on the actual instance passed to createAndBindUi, this is just standard polymorphism.

A: Conclusion:
UiFactory method should not be overriden as uibinder sees both methods (the overridden and the overwriting) and becomes confused with two uifactories for the same type: [ERROR] Duplicate factory in class SimpleFilmWidget.DefaultUi for type VoteWidget.
from comment to @Thomas Broyer:
I suspect, it then calls the superclass'es UiFactory annotated method which is not what I want it to do. I left this issue, as workaround attitude is sufficing to me in this case.
Thanks for Your interest anyway.


text:
Q: Restrict Android application to Android TV I'm implementing an application just specific to Android TV.
I use 2 features in AndoridManifiest.xml
<uses-feature
        android:name="android.hardware.touchscreen"
        android:required="false" />
<uses-feature
        android:name="com.google.android.tv"
        android:required="true" />

It already published to Play Store. But I can not see my application when searching it via Play Store in Toshiba TV, Android Box that running Android OS.
How can I do like Youtube for TV application? It's specific only to Android TV (Google TV, Toshiba, Android Box).
Thanks in advance.

A: For Android TV like Nexus Player the following is recommended in your manifest. It'll help filter your app in Play Store to Android TV devices only.
<application
    ...
    <activity
        android:name=".Mainctivity"
        android:icon="@drawable/app_icon_your_company"
        android:label="@string/app_name"
        android:logo="@drawable/app_icon_your_company"
        android:screenOrientation="landscape" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
        </intent-filter>
    </activity>
    ...
</application>

<uses-feature
    android:name="android.hardware.touchscreen"
    android:required="false" />
<uses-feature
    android:name="android.software.leanback"
    android:required="true" />

A: If you want it to be restricted to just TV devices only.  There is a list of features that every Android TV or similar device needs to implement.  Unfortunately not all of these are clearly documented on Google site, but found in some of their code examples.   These should also help restrict items on Amazon Fire TV devices as well.
<feature name="android.hardware.location" />
<feature name="android.hardware.location.network" />
<feature name="android.hardware.screen.landscape" />
<feature name="android.hardware.type.television" />
<feature name="android.software.app_widgets" />
<feature name="android.software.backup" />
<feature name="android.software.leanback" />
<feature name="android.software.leanback_only" />
<feature name="android.software.live_tv" />
<feature name="android.software.print" />
<feature name="android.software.voice_recognizers" />

The one of the important ones here is android.hardware.type.television.  If you want to restrict things that make sure to set restrictions on the ones that you require for your app.
<uses-feature android:name="android.hardware.type.television"
   android:required="true" />

If you app requires that system have all the Android Leanback functionality in place, then you want to enable support for leanback.
  <uses-feature android:name="android.software.leanback"
   android:required="false" />
  <uses-feature android:name="android.software.leanback_only"
   android:required="false" />

You may want to set these to true if you only support Android TV devices, but leave them as optional if you are targeting Amazon FireTV devices.
Amazon FireTV supported Filters: https://developer.amazon.com/docs/app-submission/supported-filters-on-the-amazon-appstore.html
Google Android TV Core TV Hardware profile: https://android.googlesource.com/device/google/atv/+/578751f94fdc584be22d7b1ea3112723a861b3af/tv_core_hardware.xml
NVIDA Shield: https://developer.nvidia.com/android-tv-deployment-checklist

A: You could restrict the devices in the Google Play Developer Console. Check also the FAQ of Google.

The Device Availability dialog is a powerful tool available to all Android developers. It can be accessed from within the Google Play Developer Console. Device Availability provides a dynamic list of compatible devices based upon your manifest settings. For example, if your APK's manifest file specifies a large screen size, the console will reflect the supported devices that can find your app in Google Play. You can also use the dynamic search feature to see the devices that your application will not be available to. You can search by manufacturer, design name (ie. Passion), or the actual public device name (ie. Nexus One) to see if your manifest settings filtered a device.

A: Maybe if you set the leanback 'requirement' (wich means, the App only works with Leanback/Android TV devices ) from being true to be false.
android:name="android.software.leanback"
android:required="false"

and Sideload it after that.

A: We need to just make user features: leanback as required true to restrict only to AndroidTV on store:
<uses-feature
    android:name="android.software.leanback"
    android:required="true" />


text:
Q: Spark Serializer Kryo setRegistrationRequired(false) I'm using weka.mi.MISVM in a Scala/Spark program and need to serialize my kernels to reuse them later.
For this I use Kryo as this :
conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
conf.registerKryoClasses(
    Array(classOf[Multiset], classOf[MISVM], classOf[(_,_)],
     classOf[Map[_,_]], classOf[Array[_]])
)

...

val patterns: RDD[(Multiset, MISVM)] = ...
patterns.saveAsObjectFile(options.get.out)

(Multiset is one of my objects)
The serialization works well but when I tried to read my kernels with:
objectFile[(Multiset, MISVM)](sc, path)
I obtain this error:
com.esotericsoftware.kryo.KryoException: Encountered unregistered class ID: 13994

I think that it's because I don't have register all the classes used by MISVM and I read that Kryo.setRegistrationRequired(false) could be a solution but I don't understand how to use it in my case.
How to define that the conf KryoSerializer have to use setRegistrationRequired(false)?

A: Try this:
conf.set("spark.serializer", org.apache.spark.serializer.KryoSerializer")
conf.set("spark.kryo.registrationRequired", "false")


text:
Q: XAML - Generic textbox stylewith triggers / parameters? I want to be able to have a generic style template that can switch colors of my textboxes based on a bool.  But I don't want to have to create a unique style for each textbox. How do I do this?
I have put some sample code below how I might expect this to work.
Three textboxes, all with different bindings but attempting to use the same template to select red or green colour based on a bool.
Thanks
<TextBlock Text="{Binding Text1}" Style={DynamicResource MyTextBoxTemplate} DataContext="{Binding MyBool1}" />
<TextBlock Text="{Binding Text2}" Style={DynamicResource MyTextBoxTemplate} DataContext="{Binding MyBool2}" />
<TextBlock Text="{Binding Text3}" Style={DynamicResource MyTextBoxTemplate} DataContext="{Binding MyBool3}" />

            <Style x:Key="MyTextBoxTemplate" TargetType="TextBlock">
                <Style.Triggers>
                    <DataTrigger Value="True" Binding="{Binding ???}">
                        <Setter Property="Foreground" Value="Green" />
                    </DataTrigger>
                    <DataTrigger Value="False" Binding="{Binding ???}">
                        <Setter Property="Foreground" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>

A: You can use the Tag property of TextBox
<TextBlock Text="{Binding Text1}" Style={DynamicResource MyTextBoxTemplate} Tag="{Binding MyBool1}" />
<TextBlock Text="{Binding Text2}" Style={DynamicResource MyTextBoxTemplate} Tag="{Binding MyBool2}" />
<TextBlock Text="{Binding Text3}" Style={DynamicResource MyTextBoxTemplate} Tag="{Binding MyBool3}" />

<Style x:Key="MyTextBoxTemplate" TargetType="TextBlock">
    <Style.Triggers>
        <Trigger Property="Tag" Value="True">
            <Setter Property="Foreground" Value="Green" />
        </Trigger>
        <Trigger Property="Tag" Value="False">
            <Setter Property="Foreground" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

A: You can also use an attached property for that instead of Tag.


text:
Q: How can I abort a request if the XML file is too large? In my servlet, I am currently setting the XML file to a variable like this:
String xmlFileAsString = CharStreams.toString(new
         InputStreamReader(request.getInputStream(), "UTF-8"));

Now after this line I can check if the file size is too large etc., but that means the entire file has already been stream and loaded into memory.
Is there a way for me to get the input stream, but while this is streaming the file it should abort if the file size is say above 10MB?

A: You can read the stream sequentially and count the number of characters read. First don't use CharStreams since it already reads the entire file. Create an InputStreamReader object:
InputStreamReader reader;
        reader = new InputStreamReader(request.getInputStream(), "UTF-8");

A variable to keep track of the char count:
long charCount = 0;

And then the code to read the file:
char[] cbuf = new char[10240]; // size of the read buffer
int charsRead = reader.read(cbuf); // read first set of chars
StringBuilder buffer = new StringBuilder(); // accumulate the data read here

while(charsRead > 0) {
    buffer.append(cbuf, 0, charsRead);
    if (charCount > LIMIT) { // define a LIMIT constant with your size limit
        throw new XMLTooLargeException(); // treat the problem with an exception
    }
}
String xmlFileAsString = buffer.toString(); //if not too large, get the string


text:
Q: Can you make a scope in laravel that calls various other scopes? I have a model in Laravel that has various scopes defined. I want to use all of them in a lot of places so rather than chaining them together I'd rather just be able to call one scope that calls all of the other scopes like so:
function scopeValid($query, $user_id) {
    $query = $this->scopeDateValid($query);
    $query = $this->scopeMaxUsesValid($query);
    $query = $this->scopeCustomerMaxUsesValid($query, $user_id);
    return $query;
}

This doesn't seem to work though, is there a way to achieve this?

A: Original answer
Query scopes are called statically.
$users = Model::dateValid()->get()

There is no $this when making static calls. Try replacing $this->scopeDateValid with self::scopeDateValid
Revised answer
There probably was something else wrong with your code since $this is in fact a Model instance when scopes are called. You should be able to either call the class scope methods directly with the $query parameter (like you did) or use another chain of scope method resolution as proposed by ceejayoz.
Personally, I don't see much of an advantage in going through the whole query scope resolution process when you know you want to call the scope methods on your class, but either way works.
Analysis
Let's walk through the call stack for executing query scopes:
#0 [internal function]: App\User->scopeValid(Object(Illuminate\Database\Eloquent\Builder))
#1 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(829): call_user_func_array(Array, Array)
#2 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(940): Illuminate\Database\Eloquent\Builder->callScope('scopeOff', Array)
#3 [internal function]: Illuminate\Database\Eloquent\Builder->__call('valid', Array)
#4 [internal function]: Illuminate\Database\Eloquent\Builder->valid()
#5 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(3482): call_user_func_array(Array, Array)
#6 [internal function]: Illuminate\Database\Eloquent\Model->__call('valid', Array)
#7 [internal function]: App\User->valid()
#8 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(3496): call_user_func_array(Array, Array)
#9 /app/Http/Controllers/UserController.php(22): Illuminate\Database\Eloquent\Model::__callStatic('valid', Array)
#10 /app/Http/Controllers/UserController.php(22): App\User::valid()

#10 The User::scopeValid() call
#8 __callStatic() handler for Model
From the PHP docs on Method overloading:

public static mixed __callStatic ( string $name , array $arguments )
__callStatic() is triggered when invoking inaccessible methods in a static context.

Annotated code of Model.php's __callStatic() method (lines 3492-3497):
public static function __callStatic($method, $parameters)
{
    // Uses PHP's late static binding to create a new instance of the
    // model class (User in this case)
    $instance = new static;

    // Call the $method (valid()) on $instance (empty User) with $parameters
    return call_user_func_array([$instance, $method], $parameters);
}

#7 User->valid() (which doesn't exist)
#5 __call handler for Model
Again, from the PHP docs on Method overloading:

public mixed __call ( string $name , array $arguments )
__call() is triggered when invoking inaccessible methods in an object context.

Annotated code of Model.php's __call() method (lines 3474-3483):
public function __call($method, $parameters)
{
    // increment() and decrement() methods are called on the Model
    // instance apparently. I don't know what they do.
    if (in_array($method, ['increment', 'decrement'])) {
        return call_user_func_array([$this, $method], $parameters);
    }

    // Create a new \Illuminate\Database\Eloquent\Builder query builder
    // initialized with this model (User)
    $query = $this->newQuery();

    // Call the $method (valid()) on $query with $parameters
    return call_user_func_array([$query, $method], $parameters);
}

#2 __call handler for the query Builder
Annotated code of Builder.php's __call() method (lines 933-946):
public function __call($method, $parameters)
{
    if (isset($this->macros[$method])) {
        // Handle query builder macros (I don't know about them)
        array_unshift($parameters, $this);

        return call_user_func_array($this->macros[$method], $parameters);
    } elseif (method_exists($this->model, $scope = 'scope'.ucfirst($method))) {
        // Now we're getting somewhere! Builds the 'scopeValid' string from
        // the original 'valid()' method call. If that method exists on the
        // model, use it as a scope.
        return $this->callScope($scope, $parameters);
    }

    // Other stuff for fallback
    $result = call_user_func_array([$this->query, $method], $parameters);

    return in_array($method, $this->passthru) ? $result : $this;
}

#1 callScope() method of the query Builder
Annotated code of Builder.php's __call() method (lines 825-830):
protected function callScope($scope, $parameters)
{
    // Add $this (the query) as the first parameter
    array_unshift($parameters, $this);

    // Call the query $scope method (scopeValid) in the context of an
    // empty User model instance with the $parameters.
    return call_user_func_array([$this->model, $scope], $parameters) ?: $this;
}

A: It should work as long as you pass a valid Query object. Maybe typehinting in your function signature will tell you what's wrong? Edit: bernie caught it
Slightly off-topic, here is what I like to do to make my code even more readable :)
static function scopeValid($query, $user_id) {
    return $query->scopeDateValid()
                ->scopeMaxUsesValid()
                ->scopeCustomerMaxUsesValid($user_id);
}

A: As shown in the docs, you'll want to do your scoping against $query, not $this, and use the scope's magic function rather than calling the internal implementation:
public function scopeTesting($query) {
    return $query->testingTwo();
}

public function scopeTestingTwo($query) {
    return $query->where('testing', true);
}

As a demonstration, you can see here calling the testing() scope applies the logic in the testingTwo() scope:
>>> App\User::testing()->toSql();
=> "select * from "users" where "testing" = ?"
>>>

So, for your code, this should do the trick:
function scopeValid($query, $user_id) {
    $query = $query->dateValid();
    $query = $query->maxUsesValid();
    $query = $query->customerMaxUsesValid($user_id);

    return $query;

    // or just return $query->dateValid()
    //                      ->maxUsesValid()
    //                      ->customerMaxUsesValid($user_id);
}

A: Another solution for if, for example:
You have to call a Date Range on multiple scopes
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use DB;
class UserModel extends Model
{
    public function scopeCreatedBetween(Builder $query, \DateTime $start, \DateTime $end) : Builder
    {
        return $query->whereBetween('created_date',[$start->format('Y-m-d H:i:s'),$end->format('Y-m-d H:i:s')]);

    }

    public function scopeBilledBetween(Builder $query, \DateTime $start, \DateTime $end) : Builder
    {
        return $query->whereBetween('billed_date',[$start->format('Y-m-d H:i:s'),$end->format('Y-m-d H:i:s')]);
    }

    public function scopeMonthToDate(Builder $query, string ...$scopes) : Builder
    {
        return $this->applyDateRangeScopes(
            $query,
            $scopes,
            new \DateTime('first day of this month'),
            \DateTime::createFromFormat('Y-m-d',date('Y-m-d'))->sub(new \DateInterval('P1D'))
        );
    }

    /**
     * Applies the scopes used for our date ranges
     * @param  Builder $query
     * @param  array  $scopes
     * @return Builder
     */
    private function applyDateRangeScopes(Builder $query,array $scopes, \DateTime $from, \DateTime $to) : Builder
    {
        // If there are no scopes to apply just return the query
        if(!(bool)$scopes) return $query;
        // So we don't count each iteration
        $scopeCount = count((array)$scopes);

        for ($i=0; $i < $scopeCount; $i++) {
            // Method does NOT exist
            if( !method_exists($this,$scopes[$i]) ) continue;
            // Apply the scope
            $query = $this->{$scopes[$i]}($query,$from,$to);
        }
        return $query;
    }

}

Usage:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\UserModel;

class User extends Controller
{
    public function someAction(UserModel $user)
    {
        $user::scopeMonthToDate('scopeCreatedBetween','scopeCreatedBetween');
    }
}


text:
Q: Https do not start in apache I have been set ssl config on apache in my CentOS server.
When I restart apache server, error occurs following this.

[warn] module ssl_module is already loaded, skipping
  (98)Address already in use: make_sock: could not bind to address [::]:443
  (98)Address already in use: make_sock: could not bind to address 0.0.0.0:443
  no listening sockets available, shutting down
  Unable to open logs

So my httpd don't start.
I comment "Listen 443" line and "LoadModule ssl_module modules/mod_ssl.so" Line.
Then apache starts well.
But I want to uncomment these lines.
How can I do it?
Thanks.


text:
Q: Proof of inverse function theorem I'm reviewing old calculus notes, and we are given the inverse function theorem, note that invertible means injective here, and $f^{-1}:= f^{-1}(f(x))=x, \forall x \in D(f)$.

Theorem. If $f$ is invertible on $(x_0-\delta, x_0+\delta)$ for some $\delta>0$, and $f$ is differentiable at $x_0$, then $f^{-1}$ is invertible at $f(x_0)$, and $(f^{-1})'(f(x_0))=\frac{1}{f'(f^{-1}(x_0))}$, because
\begin{align}
\lim_{x\to x_0}\frac{f^{-1}(x)-f^{-1}(x_0)}{x-x_0}
&=\lim_{x=f(y)\to f(y_0)=x_0}\frac{f^{-1}(f(y))-f^{-1}(f(y_0))}{f(y)-f(y_0))}\\
&=\lim_{y\to y_0}\frac{y-y_0}{f(y)-f(y_0)}
\end{align}

Questions:

*

*We used the first condition to be able to say that $x=f(y),x_0=f(y_0)$, but where did we use the second condition here?

*What is going on with the indices of the limit after the last equality sign?

A: I would write the proof like this:
\begin{align}
\lim_{y\to y_0}\frac{f^{-1}(y)-f^{-1}(y_0)}{y-y_0}
&=\lim_{y=f(x)\to y_0=f(x_0)}\frac{f^{-1}(f(x))-f^{-1}(f(x_0))}{f(x)-f(x_0)}\\
&=\lim_{x\to x_0}\frac{x-x_0}{f(x)-f(x_0)}=\frac{1}{f'(x_0)}
\end{align}
We can make the last transition because $\lim_{f(x)\to f(x_0)}(x-x_0)=0$ since $f$ is continuous. I also think the statement of the theorem contains an error, it should be $(f^{-1})'(x_0)=\frac{1}{f'(f^{-1}(x_0))}$ or (thanks to @TobyBartels),
$(f^{-1})'(f(x_0))=\frac{1}{f'(x_0)}$


text:
Q: Returning a number with varying # of digits between fixed characters Im writing my bachelor thesis on behavioral economics, and in this coherence I have aquired a dataset with 40.000 different observations/rows.
The data is from a forum, and some of the rows are the start of the topic, and the others are the replies. However, i need to group matching rows. I have tried by using the text functions in excel, removing the "RE:" from the replies, giving the topic and replies a variable with an identical value(which is the goal!)..
But because my data has some missing values in the "topic" variable(see attached image), i have to use another variable for identification... Which leads to my question:
Is it possible to run a terminal command(mac user), that can take a list of URLS, and separate digits between characters and output it in a text file of some kind?
My urls looks like this:
http://www.lydmaskinen.dk/viewtopic.php?f=1&t=63898&p=553224#p553224

Where it is the number from "&t=" to "&p", and in some cases nothing at the endI am interested in.
A little more describing screendump
Thanks,

A: Something like this should work for your URLs:
echo 'http://www.lydmaskinen.dk/viewtopic.php?f=1&t=63898&p=553224#p553224' | cut -f2 -d '&' | cut -f2 -d '='

To do it on the whole column of URLs I need to know what the filetype is (CSV, TSV, xls?)


text:
Q: C++ passing by value semantics with copy/move I am trying to understand move is not preferred in the following code. Does it only work with trivial constructors? Without side effect how does one test this?
The code:
#include <iostream>

using namespace std;
struct A {
  A() {cout << "A default constructor called." << endl;}
  A(const A &a);
  A(A &&a) {cout << "A move constructor called." << endl;}
  ~A() {cout << "A destructor called." << endl;}
};
// making sure inlining isn't the problem.
A::A(const A &a) {cout << "A copy constructor called." << endl;}

struct B {
  A a_;
  B(A a) : a_{a} {}
};

int main() {
  cout << "Testing copy elision when passing by value through B constructor." << endl;
  B b = A();
  return 0;
}

Here is the output. Chained copy elision doesn't go through a constructor initializer even though the body does not use the argument?
Testing copy elision when passing by value through B constructor.
A default constructor called.
A copy constructor called.
A destructor called.
A destructor called.

A: From "C++ Programming Language (Fourth Edition)", on move's:
"In a few cases, such as for a return value, the language rules say that it can (because the next action is defined to destroy the element). However, in general we have to tell it by giving an rvalue reference argument".
You have to specify the move in this case:
  B(A a) : a_{std::move(a)} {}


text:
Q: trying to create independent modals and post infomation from different arrays I am trying to do a testing of modal outputs and basically, have it where the content that I am pulling from a multitude of arrays fits in the order of the modals that are being outputted which is the same amount of information that the array info is pulling.
But when I pull the info into the modal it for some reason is just pulling the last array item that I am calling for ALL the modals instead of it being independent.
here is my JS code
                    function showModal() {

                        const modalValues = document.querySelectorAll('#modal');

                            for (a = 0; a < modalValues.length; a ++) {

                                    modalValues[a].classList.remove('hide');

                                }
                    }

                    const arrayOne = {
                        firstName: 'John',
                        Speciality: 'Weldind'
                    }

                    const arrayTwo = {
                        firstName: 'Jack',
                        Speciality: 'Uber'
                    }

                    const arrayThree = {
                        firstName: 'Jill',
                        Speciality: 'Nanny'
                    }

                    const arrayFour = {
                        firstName: 'Mill',
                        Speciality: 'Doctor'
                    }

                    const arrayAlls = [arrayOne , arrayTwo, arrayThree, arrayFour];

                    //value and valueTwo id

                    const valueName =  document.querySelectorAll('#value');

                    for (j = 0; j < valueName.length; j++) {

                        const valueNameArray = [];

                        valueNameArray.push(valueName[j].textContent);

                        const firstName = arrayAlls[j].firstName;
                        valueName[j].textContent = firstName;

                    }

                const modalBtn = document.querySelectorAll('#modalBtn');

                for (s = 0; s < modalBtn.length; s++) {
                    modalBtn[s].addEventListener('click' , showModal)
                }


text:
Q: Erasing lines in pdf context I'm trying to generate a pdf of my UIView. In the view I can simply erase lines using CGContextSetBlendMode(context, CGBlendMode.Clear). While this works properly on the context of the UIView when I draw to the pdf context (as generated using UIGraphicsBeginPDFContextToData) the same code results in a line with the same color as set in CGContextSetStrokeColorWithColor. Does anybody know of an alternative way to achieve erasing in a pdf context?
For instance, when I run the code below a context from drawrect it results in a faint red line (alpha = 0.5) with a small gap running through the red line. However, if I supply  a pdfcontext it becomes a faint redline with a hard red line running through it (as another thin red line with alpha 0.5 is superimposed)
    let path = CGPathCreateMutable()
    CGPathMoveToPoint(path, nil, 10, 10)
    CGPathAddLineToPoint(path, nil, 10,100)
    CGContextAddPath(context, path)

    CGContextSetLineCap(context, CGLineCap.Round)
    CGContextSetStrokeColorWithColor(context, UIColor.redColor().colorWithAlphaComponent(0.5).CGColor)
    CGContextSetLineWidth(context, 10.0)
    CGContextStrokePath(context)

    CGPathMoveToPoint(path, nil, 10, 10)
    CGPathAddLineToPoint(path, nil, 10,100)
    CGContextAddPath(context, path)

    CGContextSetBlendMode(context, CGBlendMode.Clear)
    CGContextSetLineWidth(context, 2.0)
    CGContextStrokePath(context)

A: I ended up solving my problem with a workaround. For the benefit of anyone else with this issue, here goes.
I draw subviews individually in the PDFContext. For each I check if it contains erasing. If this is the case I open a separate ImageContext and generate an image of the view as such.
UIGraphicsBeginImageContext(objectView.frame.size)
if let imageContext = UIGraphicsGetCurrentContext() {
    objectView.drawObjectInContext(imageContext,rect: objectView.bounds)
    self.applyEraser(imageContext, eraserShape: objectView.eraserLayer.eraseShape)
    let image = UIGraphicsGetImageFromCurrentImageContext()

    CGContextTranslateCTM(pdfContext, 0, objectView.bounds.height)
    CGContextScaleCTM(pdfContext, 1.0, -1.0)
    CGContextDrawImage(pdfContext, objectView.bounds, image.CGImage)
}
UIGraphicsEndImageContext()

Note that the image is upside compared to regular drawing in CGContext, which is why I invoke CGContextTranslate en CGContextScale.
The downside is that you get images of subviews in your PDF rather than perhaps simple text. However, if you do it for each view separately you can draw  the views without erasing properly as text or whatever you want.


text:
Q: NiFi: ListFile Processor is not detecting file changes sometimes ListFile processor is not detecting any changes to a previously processed file and reprocess it. FYI, I have tried the following options already for reprocessing and only the finally mentioned hack is working. This is in a single-node NiFi I am running in my development environment.

*

*Update Scenario: ListFile processor is not detecting file content changes and trigger automatically post-update (i.e file updates using VIM editor)

*Timestamp modification Scenario: Changing the file timestamp with touch -c command changes the file timestamp but this does not cause auto-trigger of the ListFile processor either.

*Stop-start Scenario: Stop-start of the whole process group in NiFi after changing the file as mentioned above also does not cause triggering of ListFile processor.

*Waiting Clause: Waiting for long enough after file change also does not help - just in case we assume it will auto-trigger after some delay.

*HACK: The only way I am able to trigger the re-processing of the file by ListFile processor is by changing the wildcard expression for "File Filter" in ListFile processor in a harmless, idempotent manner, for example from .*test.*\.csv to test.*\.csv and vice versa later (i.e go back and forth like this for repeated reprocessing).

Reprocessing of files with same old names and with modified data is a requirement for us. Please help!
And sometimes forced reprocessing of even an unmodified file could be required in case of unanticipated data issues upstream/downstream. Please help!
UPDATE
Still facing this sporadic behavior! Only restart of NiFi helps when the ListFile processor fails to respond to file change.

A: Probably this is delayed answer.
The old List processors like ListFiles/ListFtp/ListSftp etc. used only timestamp tracking strategy to identify the changed files. The processor used to cache last seen timestamp in its processor state and use it to list files with only greater timestamp.
However, this approach was very buggy. Hence they had to come up with much better strategy which is called Entity Tracking. This approach gives broad
 range of monitoring on file changes. It keeps track of below parameters of each file in the specified directory.

*

*Name

*Size

*Last modified timestamp

Any change in file is reflected in these key parameters. Since they are cached, any difference is treated as change, thus changed files appear in the success connection.


text:
Q: How to add more than one space between particular pieces of words? Just wondering if there's a neat way of doing this using html and css only.
I want to display 3 lines, each includes a name and a phone number and it should look something like this:
one name, multiple spaces followed by a phone number. Then a new line starting with one name and multiple spaces followed by another phone number and the same logic goes for the 3rd line.
The purpose of multiple spaces is for indentation so that the names and phone numbers would look nice on a webpage.
I think it's ugly to insert multiple &nbsp there(unless there're no other options)...
Any neat and clever ways to do it?
Thanks a lot!
(btw I'm using 3 paragraphs at the moment for the above.)

A: You probably want a table.
If not, you probably want a list, with some items (phone numbers) set to float: right, or to display: inline-block, with some left margin.

A: use a span class for phone number with margin-left:10px .and can change margin-left position with pixel value you need in b/w name and phone number.see the code below
html
Name1234567890

Name1234567890

Name1234567890

css
.phone
{
    margin-left:10px;
}

A: What about something like this fiddle: http://jsfiddle.net/W7wXa/2/
markup:

Name 1

Name 2

Name 3

123-456-7890

123-456-7890

123-456-7890

css:
.left {
    display: inline-block;
}

.right {
    display: inline-block;
    margin-left: 20px;
}

Hope this helps.

A: If indentation is the issue, you can use a table. You can align the cells within a table to get your desired output.


text:
Q: How to use Labstack Echo ReverseProxy ModifyResponse using streams Labstack Echo v4 has recently been updated to include ModifyResponse hook (ala golang's httputil ReverseProxy).
Most of the examples of using this seem to leverage ioutil.ReadAll().
For example:
func UpdateResponse(r *http.Response) error {
    b, _ := ioutil.ReadAll(r.Body)
    buf := bytes.NewBufferString("Monkey")
    buf.Write(b)
    r.Body = ioutil.NopCloser(buf)
    r.Header["Content-Length"] = []string{fmt.Sprint(buf.Len())}
    return nil
}

What I am looking to do is to avoid waiting for the entire response (from ReadAll) and monitor the stream for certain content (i.e. class='blue') then replace it with different text (i.e. class='blue-green')
How can this be done using streams efficiently and with as little allocations as possible?


text:
Q: Electric field energy density In vacuum, the energy density of the electric field is given by $\mathcal{E}=\epsilon_0\frac{E^2}{2}$ with $E$ the total electric field present. So, if you have a static $E_0$ and dynamic $e(t)$ field, the energy density becomes
$$\mathcal{E}=\epsilon_0\frac{\left[E_0+e(t)\right]^2}{2} = \epsilon_0\frac{E_0^2 +2E_0e(t)+e(t)^2}{2}\,.$$
Is this correct? What does the term $2E_0e(t)$ physically represent? It looks like an additional energy contribution from the interaction between the two fields...

A: The cross term represents interference. It is the term that makes it so that the energy density is reduced when the two fields are in opposite directions and so that the energy density is increased when the two fields are in the same direction.

A: It is correct. Note however that, when dealing with periodic electric fields, one would often be interested in the energy density averaged over a period, where the cross-term disappears:
$$e(t) = E_1\cos(\omega t),\\
\bar{\mathcal{E}} = \frac{\omega}{2\pi}\int_{t_0}^{t_0 + 2\pi/\omega}dt \frac{\epsilon_0|E_0 + E_1\cos (\omega t)|^2}{2} = \frac{\epsilon_0E_0^2}{2} + \frac{\epsilon_0 E_1^2}{4}
$$
The general expression for the energy density can be rigorously obtained from the Maxwell equations within the context of the Pointing theorem.

A: Yes, this is correct. I don't think there is any special interpretation of the cross term, it's just a contribution to the energy density.