I received memory warning and my app crashed. Does it kill autorelease objects?

Question: I received two memory warnings. It doesn't show warning level. It shows brief phrase:
<code>Received memory warning.
Received memory warning.
</code>
I received memory warning and after a few seconds my application crashed. Does my application crashed because I received memory warning?
I know that memory warning level 2 killes autorelease objects. Does memory warning without any level indication kill autorelease objects?
Answer: Are you working with MRC? In that case, when memory warning is received, dealloc methos will be called to dealloc all the necessary views and objects to free some memory.
Check that everything is being released correctly in dealloc.
Autorelease objects are released automatically when your app goes out of their scope.
Answer: autorelease objects aren't always released immediately
for example...if you have a loop where you alloc a lot of a autorelease objects the objects wont get released until the loop is over...so if they are big in size you can get memory warning and app crash before the loop is over and they have a chance to get released
if its this ..just alloc and release objects yourself to manage memory problem
Comment: in ARC we can't release own, so can we use nil instead of release?
Comment: Well actually you can release objects yourself if you exclude file from ARC. And for the other objects in the class you can just call autorelease yourself( instead of being automatic)
Comment: but i want to use ARC, so how to free our object in ARC,
Comment: add [[[object alloc]init]autorelease] when you init the object (if you don't use a method that returns an autoreleased object) or release the object yourself after you're done with it to avoid the problem above. To enable ARC for the full project...google it
Answer:
Use virtual memory
iOS doesn't use swap file but it does support virtual memory. If an app keeps a lot of data in memory for random access (like vocabulary in Letter Blocks 3D) you want to organize it as a mapfile rather then loading it to RAM with
malloc()
. An easiest way to do that is to call
NSData initWithContentsOfMappedFile:
Avoid stacking autoreleased objects
When you instantiate objects like NSString with no explicit allocation they live until the release of your autorelease pool – typically until your app quits. Extensive usage of such techniques may lead to a lot of garbage in RAM. Use
NSString initWithContentsOfFile:
so you can later release it instead of
NSString stringWithContentsOfFile:
. The same rule applies to
UIImage imageNamed:
– this is not recommended to use for image loading.
Handle memory warnings
Unload unnecessary resources when handling memory warning. Even if you can't unload any of your stuff call
[super didReceiveMemoryWarning]
in all your UIViewControllers. That will by default free some resources like UI controls on non-front views. Failing to handle this event may make iOS decide that your app deserves killing.
Consider limited usage of animated view transitions
Animations like flip transition are noticed to cause RAM usage spikes when executed. This feature is very neat and should be used in many cases but it may trigger memory warnings in a heavily loaded multitasking environment. In particular we strongly recommend to avoid animating OpenGL views.
Test your memory footprint on device
Use instruments to test. The most useful tools are Allocations, Leaks and Activity Monitor. Testing on simulator is not relevant in most cases since its memory footprint tends to be completely different. Once you test you can figure out how much RAM each part of your app uses, where are the bottlenecks and how you can optimize.

From:  http://surgeworks.com/blog/lab-mobile/iphone/5-tips-to-reduce-memory-issues-in-ios-apps


Amazon Location Services - searchPlaceIndexForSuggestions is not a function

Question: I'm using Amazon Location Services for a mapping project that I'm working on and I want to implement autocomplete using searchPlaceIndexForSuggestions as outlined at https://docs.aws.amazon.com/location/latest/developerguide/search-place-index-autocomplete.html
and documented at https://docs.aws.amazon.com/location-places/latest/APIReference/API_SearchPlaceIndexForSuggestions.html
I'm able to call location.searchPlaceIndexForText and location.searchPlaceIndexForPosition just fine and get the expected responses, but when I call location.searchPlaceIndexForSuggestions with relevant parameters I get Uncaught TypeError: location.searchPlaceIndexForSuggestions is not a function.
My declaration for location is
const location = new AWS.Location({credentials, region: AWS.config.region});

The relevant IAM role has the following in its policy:
"Action": [
                "geo:GetMapGlyphs",
                "geo:GetMapSprites",
                "geo:GetMapStyleDescriptor",
                "geo:SearchPlaceIndex*",
                "geo:GetMapTile"
            ],

I'm not sure if I'm missing something in the policy, calling the function incorrectly, declaring location incorrectly, or what. Any ideas or assistance would be appreciated :)
Answer: Your IAM policy seems fine. There are a couple of things I'd suggest:

Take a look at a blog I wrote or a video I published on how to add a location search with autocomplete to your web app using AWS Amplify (Amplify Geo).
Take a look at the following code snippet, which uses the AWS SDK V3 Location Client

import {
  LocationClient,
  SearchPlaceIndexForSuggestionsCommand
} from '@aws-sdk/client-location';

const client = new LocationClient({
    credentials: YOUR_AWS_CREDENTIALS,
    region: YOUR_AWS_REGION
  });

const command = new SearchPlaceIndexForSuggestionsCommand({ Text: YOUR_SEARCH_TERM, IndexName: YOUR_PLACE_INDEX_NAME });
const response = await client.send(command)
console.log(response);

Hope this helps.


How to modify the incoming call view on iOS

Question: I want to modify the labels that the spring board shows on the view of an incoming call (e.g adding city info). My app does not need to be uploaded to the AppStore, but has to work on a device without jailbreak. Thanks.
Answer: You can't do it without jailbreaking.


Frequency table when there are multiple columns representing one value (R)

Question: I have a dataset like this:
ID    color1   color2  color3   shape1       shape2        size
55    red     blue     NA       circle       triangle      small
67    yellow  NA       NA       triangle     NA            medium
83    blue    yellow   NA       circle       NA            large
78    red     yellow   blue     square       circle        large
43    green   NA       NA       square       circle        small
29    yellow  green    NA       circle       triangle      medium

I would like to create a dataframe where I have the frequency and percentage of each variable, but I am having trouble because there are multiple columns of the same variable in some cases.

Variable      Level        Freq        Percent

color         blue          3           27.27
              red           2           18.18
              yellow        4           36.36
              green         2           18.18
              total         11          100.00

shape         circle        5           50.0
              triangle      3           30.0
              square        2           20.0
              total         10          100.0

size          small         2           33.3
              medium        2           33.3
              large         2           33.3
              total         6           100.0

I believe that I need to convert these variables to long and then use summarize/mutate to get the frequencies, but I can't seem to figure it out. Any help is greatly appreciated.
Answer: You can use tidyverse package to transform the data into a long format and then just summarise the desired stats.
library(tidyverse)

df |>
  # Transform all columns into a long format
  pivot_longer(cols = -ID,
               names_pattern = "([A-z]+)",
               names_to = c("variable")) |>
  # Drop NA entries
  drop_na(value) |>
  # Group by variable
  group_by(variable) |>
  # Count
  count(value) |>
  # Calculate percentage as n / sum of n by variable
  mutate(perc = 100* n / sum(n))

# A tibble: 10 x 4
# Groups:   variable [3]
#   variable value        n  perc
#   <chr>    <chr>    <int> <dbl>
# 1 color    blue         3  27.3
# 2 color    green        2  18.2
# 3 color    red          2  18.2
# 4 color    yellow       4  36.4
# 5 shape    circle       5  50
# 6 shape    square       2  20
# 7 shape    triangle     3  30
# 8 size     large        2  33.3
# 9 size     medium       2  33.3
#10 size     small        2  33.3

Comment: You can use a slightly different regular expression in the "names_pattern" argument for `pivot_longer`. For example, something like: "([A-z]+|[A-z]+\\s[A-z]+)" to include column names with either a single word or (|) two words separated by a space (\\s).
Comment: Thank you! I'm sure this works, but I realized in my real dataset some of the column names have multiple words and this is splitting them up into individual columns. Do you know of a way to prevent this?
Answer: Combining and adding to:

Merge multiple frequency tables together in R

Adding a column of total n for each group in a stacked frequency table

library(dplyr)
library(tidyr)
library(janitor)

options(digits = 3)

df %>%
  pivot_longer(
    -ID,
    names_to = "Variable",
    values_to = "Level"
  ) %>%
  mutate(Variable = str_extract(Variable, '[A-Za-z]*')) %>%
  group_by(Variable, Level) %>%
  count(Level, name = "Freq") %>%
  na.omit() %>%
  group_by(Variable) %>%
  mutate(Percent = Freq/sum(Freq)*100) %>%
  group_split() %>%
  adorn_totals() %>%
  bind_rows() %>%
  mutate(Level = ifelse(Level == last(Level), last(Variable), Level)) %>%
  mutate(Variable = ifelse(duplicated(Variable) |
                             Variable == "Total", NA, Variable))

 Variable    Level Freq Percent
    color     blue    3    27.3
     <NA>    green    2    18.2
     <NA>      red    2    18.2
     <NA>   yellow    4    36.4
     <NA>    Total   11   100.0
    shape   circle    5    50.0
     <NA>   square    2    20.0
     <NA> triangle    3    30.0
     <NA>    Total   10   100.0
     size    large    2    33.3
     <NA>   medium    2    33.3
     <NA>    small    2    33.3
     <NA>    Total    6   100.0

Comment: Thank you! I'm sure this works, but I realized in my real dataset some of the column names have multiple words and this is splitting them up into individual columns. Do you know of a way to prevent this?
Answer: Try this matrix in list in base R
uniq <- unique( sub( "[0-9]","", colnames(dat[,-1]) ) )
uniq
[1] "color" "shape" "size"

sapply( uniq, function(x){ tbl <- table( unlist( dat[,grep( x, colnames(dat) )] ) );
  rbind( cbind( Percent=round( tbl/sum(tbl)*100, digits=2 ), Freq=tbl ),
         cbind( sum(tbl/sum(tbl)*100), sum(tbl) ) ) } )
$color
         Percent Freq
blue       27.27    3
green      18.18    2
red        18.18    2
yellow     36.36    4
          100.00   11

$shape
         Percent Freq
circle        50    5
square        20    2
triangle      30    3
             100   10

$size
         Percent Freq
large      33.33    2
medium     33.33    2
small      33.33    2
          100.00    6

To get a data.frame
data.frame( do.call( rbind, sapply( uniq, function(x){
  tbl <- table( unlist( dat[,grep( x, colnames(dat) )] ) );
  rbind( cbind( Percent=round( tbl/sum(tbl)*100, digits=2 ), Freq=tbl, var=x ),
         cbind( sum(tbl/sum(tbl)*100), sum(tbl), var=x ) ) } )
 ) )
         Percent Freq   var
blue       27.27    3 color
green      18.18    2 color
red        18.18    2 color
yellow     36.36    4 color
X            100   11 color
circle        50    5 shape
square        20    2 shape
triangle      30    3 shape
X.1          100   10 shape
large      33.33    2  size
medium     33.33    2  size
small      33.33    2  size
X.2          100    6  size

Data
dat <- structure(list(ID = c(55L, 67L, 83L, 78L, 43L, 29L), color1 = c("red",
"yellow", "blue", "red", "green", "yellow"), color2 = c("blue",
NA, "yellow", "yellow", NA, "green"), color3 = c(NA, NA, NA,
"blue", NA, NA), shape1 = c("circle", "triangle", "circle", "square",
"square", "circle"), shape2 = c("triangle", NA, NA, "circle",
"circle", "triangle"), size = c("small", "medium", "large", "large",
"small", "medium")), class = "data.frame", row.names = c(NA,
-6L))

Comment: Thank you! Do you know how I could convert it from a list to a dataframe or table? as.data.frame() isn't working
Comment: @alex See edit. Also includes totals.


Equivalent to product flavors in non-Android Gradle?

Question: I'm creating a desktop Java app and would like to create two versions: free and paid. The difference is mainly in which resource files are included (at a future date, it may involve different code as well, but not right now).
I've read about Android build variants allowing for just this sort of thing through "product flavors". However, this seems to be a feature unique to the android plugin, which is obviously not available on the desktop.
Is there an equivalent to these product flavors that does not depend on the androidplugin?
If it helps, my end goal is to find a way that I can run the Gradle build task and output two different versions of the app, which is my understanding of what the Android build variants accomplishes.
Answer: Sure you can use sourceSets and customize the Jar tasks to accomplish the same effect.
group 'com.jbirdvegas.example'
version '1.0-SNAPSHOT'

repositories {
    jcenter()
}

// adding the java plugin add the `jar` task to the build task graph
apply plugin: 'java'

compileJava {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

/**
 * SourceSets allows different builds to have their own
 * code.  If main and flavorOne contain com.foo.Bar then
 * the `flavorOne` jar will contain the file specified by
 * the `flavorOne` source set files.
 */
sourceSets {
    main {
        // you could also do per sourceSet resources if needed
        java.srcDir 'src/main/java'
    }
    flavorOne {
        java.srcDir 'src/flavorOne/java'
    }
    flavorTwo {
        java.srcDir 'src/flavorTwo/java'
    }
}

/**
 * Creates the first flavor's jar when the Java plugin's `Jar`
 * task is called.  Since the `jar` task depends on `flavorOne` task
 * this task will run before the generic `jar` task which produces
 * the base .jar artifact.
 */
task flavorOne(type: Jar) {
    from sourceSets.flavorOne.output
    classifier = 'flavorOneJar'
    manifest {
        attributes "Main-Class": "de.jeha.photo.mosaic.cli.Main"
    }
}

/**
 * Creates the second flavor's jar when the Java plugin's `Jar`
 * task is called.  `flavorTwo` can run before `flavorOne` because
 * both must just run before the `jar` task (base artifact)
 */
task flavorTwo(type: Jar) {
    from sourceSets.flavorTwo.output
    classifier = 'flavorTwoJar'
    manifest {
        attributes "Main-Class": "de.jeha.photo.mosaic.cli.Main"
    }
}

// be sure to build all flavors whenever the `jar` task runs
jar.dependsOn flavorOne, flavorTwo

dependencies {
    // you can declare different dependencies per sourceSets
    flavorOneCompile 'com.google.code.gson:gson:2.5'
    flavorTwoCompile 'com.something:else:1.0'
    compile 'commons-io:commons-io:2.4'
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

/**
 * if you want to have specific control over the main jar's
 * build then you could configure the main jar as needed.
 * This is the equivalent of the `flavorBlah` tasks except
 * this task was added for us by the `java` plugin.  Changes
 * here will only affect the main jar built from `sourceSet.main`
 *
 * Think of this as the default where other `productFlavors` are
 * completely divorced from this jar's configuration.
 */
jar {
    manifest {
        attributes "Main-Class": "de.jeha.photo.mosaic.cli.Main"
    }
}

Then we can see the different builds. Our flavors and the main source set jar.
$ ls -l build/libs/
-rw-r--r--  1 jbirdvegas  63209268   1.3K Jan  6 08:58 my-sweet-jar-1.0-SNAPSHOT-flavorOneJar.jar
-rw-r--r--  1 jbirdvegas  63209268   302B Jan  6 08:58 my-sweet-jar-1.0-SNAPSHOT-flavorTwoJar.jar
-rw-r--r--  1 jbirdvegas  63209268    18K Jan  6 08:58 my-sweet-jar-1.0-SNAPSHOT.jar

Comment: Added more comments and added a jar closure to show how to apply configurations to the main jar.  This is the equivalent method for the `flavorBlah` tasks.  I can explain any part further it would help
Comment: Thanks, I appreciate it! I'll wait a bit to see if other answers emerge.
Comment: Thank you. One more question: how to choose a certain flavour and get IntelliJ IDEA support? I mean, I want autocompletion to work with libraries I've included through `flavorXCompile`.
Comment: @Miha_x64, you might be able to do something like `configurations.compile.extendsFrom flavorX`
Comment: @JBirdVegas I'm getting 'Could not find method extendsFrom() for arguments [task ':someFlavor'] on configuration ':compile' of type org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.'
Comment: Odd, perhaps it wants you to do it in the blocks `configurations { compile { extendsFrom(flavorX) } }`.  The method definitely exists: https://github.com/gradle/gradle/blob/master/subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/configurations/DefaultConfiguration.java#L278
Comment: @JBirdVegas same. :'(
Comment: is any plugins out there to simpilify this work just like android did?


Can rectifiable varifolds be thought of as generalized characteristic functions?

Question: Consider an $n$-rectifiable varifold $V$, that is, a pair (or rather an equivalence class of pairs) $(M, θ)$ where $M$ is a countably $n$-rectifiable, $ℋ^n$-measurable subset of $ℝ^N$ and $θ$ is a positive and locally $ℋ^n$-integrable function on $M$. (All definitions as in Leon Simon's 2014 notes on Geometric Measure Theory.)
The associated Radon measure $μ_V$ is given by
$$
  μ_V(A) ≔ ∫_{M ∩ A} θ dℋ^n
$$
for all $ℋ^n$-measurable sets $A$. Consider the support of this measure:
$$
  \operatorname{supp}(μ_V) ≔ \{ x ∈ ℝ^N | ∀ \text{ open neighborhoods U of x: } μ_V(U) > 0 \}
$$
which is a closed set.
Question: (When) Do we have $\operatorname{supp}(μ_V) = M$ up to a set of $ℋ^n$-measure zero?
Attempt at a proof: By remark 1.8(2) and theorem 1.9 in Leon Simon's notes we have that the $n$-dimensional density $Θ^{*n}$ of $μ_V$ is:
$$
  Θ^{*n}(μ_V, x) = θ(x) > 0
$$
for $ℋ^n$-almost every $x ∈ M$. But by definition of the density this means that $ℋ^n$-almost every $x ∈ M$ has a neighborhood with positive $μ_V$-measure and therefore lies in $\operatorname{supp}(μ_V)$.
Conversely, let $x ∈ \operatorname{supp}(μ_V)$. Then by definition all balls centered at $x$ have non-zero $μ_V$ measure. But by definition of $μ_V$, this means that every ball centered at $x$ has to have non-empty intersection with $M$. Therefore, $\operatorname{supp}(μ_V)$ consists entirely of adherent points of $M$ and is therefore contained in the closure of $M$. It remains to show that $\operatorname{supp}(μ_V) ∖ M$ has vanishing measure. But here I'm not getting any further since, a priori, $\bar{M}∖M$ might easily have non-zero measure. (Consider that $ℝ$ is the closure of $ℚ$ and $ℝ∖ℚ$ has full measure.) I suppose I need to employ rectifiability of $M$ somehow.
Anyway, suppose the proof can be done and indeed $\operatorname{supp}(μ_V) = M$. But in this case we can forget about $M$ entirely: Set $\bar{θ} ≔ θ · χ_{\operatorname{supp}(μ_V)}$ where $χ_{\operatorname{supp}(μ_V)}$ is the characteristic function. Then we obviously have:
$$
  μ_V(A) = ∫_{M ∩ A} \bar{θ} dℋ^n = ∫_A \bar{θ} dℋ^n
$$
Since $θ$ was positive everywhere on $M = \operatorname{supp}(μ_V)$, we have $\operatorname{supp}(\bar{θ}) = \operatorname{supp}(μ_V) = M$. But the latter was $n$-rectifiable. So it seems that any varifold is given entirely in terms of a non-negative function $\bar{θ}$ whose support is $n$-rectifiable.
Question 2: Can $n$-rectifiable varifolds therefore be thought of generalizations of characteristic functions in the sense that they are given by non-negative functions (whose support is $n$-rectifiable)?
Comment: I am sorry for this vague comment, but let me toss in a couple key words: could "pure unrectifiability" be the answer to your first question? Like, use Federer's structure theorem to prove that the leftover must be purely unrectifiable, and since our whole space is rectifiable it must have measure zero. For question 2, my key word is "rectifiable measures." Rectifiable surfaces I would say are a subset of rectifiable measures. Again, this is only a vague comment.
Comment: Thanks for your comment! As for the first question: I don't think Federer's Structure Theorem helps: Since the set $M$ is already rectifiable it amounts to a tautology. Or at least I don't see how the purely unrectifiable set having measure zero would imply that $\operatorname{supp}(\mu_V) \setminus M$ has measure zero?
Comment: I was imagining that one might prove that $\text{supp}(\mu_V) \backslash M$ is purely rectifiable, and that $\text{supp}(\mu_V)$ itself is rectifiable. So, by structure theorem has no unrectifiable part of positive measure. Thus, forcing $\text{supp}(\mu_V) \backslash M$ to be of measure zero. Just thoughts.
Answer: The support of a rectifiable measure could be the whole space. Take an enumeration of $\mathbb{Q}^n$ and at each point $q_i\in\mathbb{Q}^n$ centre a segment of lenght $1/2^i$. This is a $1$ rectifiable set and which support is dense. I'd say that a good example of when the support is a good description of the geometry of the measure is when the its $n$-dimensional lower density is bounded away from $0$. Furthermore, keep in mind that the upper density is just a very weak information: the lower one is the real deal.
It's not clear what Q2 means precisely, but my answer tends to be "yes. They are a way of making computations with rectifiable sets, but I prefer currents".
EDIT: about the easy way of distinguishing when the support of $\mu_V$ has non-empty interior I do not have a really "always working idea". For general rectifiable sets you cannot expect any good behaviour in general.
If you prove that your set is contained in the complement of a cone, you can show it is a graph, for instance (chapter 15 of Mattila's book).
You can be sure that if the measure $\mu_V$ is such that $\mu_V(B(x,r))=h(r)$ for some increasing $h$ independent on $x$, then $supp(\mu_V)$ is an analytic manifold (Preiss-Kirchheim paper)
You could direcltly assume that $M$ is a closed set. Indeed, proofs don't care much about the support anyway since you can always restrict your computations to a compact set inside a borel set of the right dimension $supporting$ the measure and make the computations there.
Comment: That's a really neat example and it is providing me with more and more intuition the more I think about it! Thank you! Is there an easy way to see, though, that the difference between the support and your rectifiable set $M$, i.e. $\mathbb{R}^n \setminus M$, has 1-dimensional measure $> 0$? (So that it is indeed a counterexample to my question 1?)
Comment: Speaking of question 1, is there any criterion to decide when the support $S$ of $\mu_V$ will agree (up to the symmetric difference having measure zero) with the rectifiable set $M$ we're taking the integral over? (So that, in particular, $S$ is rectifiable, too?) More generally, is there any criterion to decide when $S$ will be rectifiable itself (though not necessarily equal to $M$ up to a set of measure zero)?
Comment: As for question 2, it seems the answer is *no*, though, doesn't it? The support of the function $\bar{θ} = θ · χ_{\operatorname{supp}(μ_V)}$ is, by definition, the intersection of $\operatorname{supp}(θ) = \bar{M}$ and $\operatorname{supp}(μ_V) ≡ S$. But $S$ and $\bar{M}$ in your example are all of $ℝ^n$ and the latter doesn't look very $1$-rectifiable to me?
Comment: On a side note, I'm now realizing that I, at times, confused the support $S$ of the measure $\mu_V$ with the support of the function $θ$, which is the closure of $M$. But they are not at all the same (this is rather meant as a note to myself but please correct me if I'm wrong): …
Comment: … The support $S$ of the measure is necessarily contained in the closure $\bar{M} = \operatorname{supp}{θ}$ of the rectifiable set $M$ (because outside the closure one can always find open neighborhoods not intersecting $M$, so on these neighborhoods the integral will yield nothing). At the same time, $S$ might be strictly smaller than $\bar{M}$ and even than $M$, namely if $M$ contains "parts" of measure zero. (As an extreme example, the 1-rectifiable set $M = ℚ^n$ would yield $\bar{M} = \operatorname{supp}{θ} = ℝ^n$ but $S ≡ \operatorname{supp}(μ_V) = ∅$.)


Angular 4 router: prevent direct browser navigation

Question: How can I convince the Angular 4 router to disable direct browser navigation within my app?
I have looked into the router hooks CanActivate and CanDeactivate and implemented them but CanDeactivate does not fire at all when using direct browser navigation.
I can use CanActivate to prevent the url but only after the app reboots, which takes time and undesired changes in the browser window.
I want to be able to catch the direct browser navigation BEFORE the app reboots.
In case this helps:
I want to disallow direct browser navigation altogether, so I don't need a solution that allows certain urls and disables others.
Here's my router definition:
const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent, canActivate: [RouteGuardService] },
  { path: 'users', component: UsersMainComponent, canActivate: [RouteGuardService] },
  { path: 'vendors', component: VendorMainComponent, canActivate: [RouteGuardService] },
  { path: 'invoices', component: InvoicesMainComponent, canActivate: [RouteGuardService] },
  { path: 'offers' , component: EsdMainComponent, canActivate: [RouteGuardService] },
  { path: 'settings' , component: SettingsMainComponent, canActivate: [RouteGuardService] },
  // Callback MUST not be route guard protected.
  { path: 'callback' , component: CallbackComponent },
  { path: 'createvendor' , component: CreateVendorsComponent, canActivate: [RouteGuardService] },
  { path: 'customerdashboard' , component: CustomerDashboardComponent, canActivate: [RouteGuardService] },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [RouteGuardService]
})
export class AppRoutingModule { }

Comment: Can you provide your router code?
Answer: The following solution is not an Angular based one. As Maximus explained in his answer this is a browser issue and therefor the solution must be browser based.
This solution is derived from an answer on this site (see here) I have written a little (typescript) service with the following three methods:
  private preventNavigation(): void {
    const location = window.document.location;
    const originalHashValue = location.hash;

    window.setTimeout(() => {
      location.hash = 'preventNavigation' + (9999 * Math.random());
      location.hash = originalHashValue;
    }, 0);
  }

  public disableBrowserNavigation(): void {
    window.addEventListener('beforeunload', this.preventNavigation, false);
    window.addEventListener('unload', this.preventNavigation, false);
  }

  public enableBrowserNavigation(): void {
    window.removeEventListener('beforeunload', this.preventNavigation);
    window.removeEventListener('unload', this.preventNavigation);
  }

This works fine but I'm still open to other solutions.
Answer:
How can I convince the Angular 4 router to disable direct browser
  navigation within my app?

Angular can't do that because that's not something controlled by Angular. When you go the address bar and type in address and then press enter a browser loads a new page. It can be an Angular application or can be any other application. It's a browser functionality. Angular controls navigation only inside the app when you click on the routerLink.
You could try to use onbeforeunload but it has its limitations.
Comment: onbeforeunload by itself doesn't work in my case because of the limitations you mentioned. However, going deeper in that direction has led to a possible solution. I'll check it out and if it works will share it as an answer. I understand and agree with your argument that it is out of Angular's control because it is a browser functionality.


Can't set class attributes in python using a method

Question: Initialising the Foo object does run the method func(), but the value of self.a gets set to None anyway.
How can I get the following code to work?
#!/usr/bin/env python

class Foo(object):

    def __init__(self, num):
        self.a = self.func(num)
        print self.a

    def func(self, num):
        self.a = range(num)
        print self.a

    def __str__(self):
        return str(self.a)

def main():
    f = Foo(20)
    print f

if __name__ == "__main__":
    main()

The output is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
None
None

Comment: You don't have any class attributes, only instance attributes.
Answer: You're resetting self.a to the return value of the function. Since the function returns nothing, the value gets set to None.
def __init__(self, num):
    self.a = self.func(num)  # return value of function is None
    print self.a             # self.a is now None

def func(self, num):
    self.a = range(num)      # sets self.a to [0..19]
    print self.a             # prints [0..19]
    # implicit "return None"

Answer: jterrace is correct. What's happening is that the func() method is printing first, not the init method. Consider this program:
#!/usr/bin/env python

class Foo(object):

    def __init__(self, num):
        self.a = self.func(num)
        print '__init__:', self.a

    def func(self, num):
        self.a = range(num)
        print 'func:', self.a

    def __str__(self):
        return str(self.a)

if __name__ == '__main__':
    f = Foo(20)
    print '__main__:', f

It's very similar to yours except I added __init__:, func:, and __main__: to the respective function's print statements. Run this and you should have a better understanding of what's going on.


How would you analyse this problem?

Question: Following the confusion (on my part) here, and as suggested, I am presenting my question in a neutral way below:
Problem:
I am looking at the relationship between "product research" (variable A) and "product purchase" (variable B). 'Product' means any consumer goods (e.g. toys, clothes etc.).
A and B are composite scores (i.e. made up of responses to several questions). The compositie scores for A corresponds to a five point scale (going from no research to a lot of research), while scores for B also corresponds to a five point scale (going from decision not to buy to always buy). I need to better describe my scale labels, but they are based on a five point Likert scale.
I am treating my composite scores as interval level data. I have checked the scatterplot and there is a linear relationship between A and B.
A selection of my data set is as follows:
Variable A - Product Research:
2.98
2.98
3.12
3.14
3.16
3.32
3.19
3.21
3.32
3.34
3.46
3.55
3.72
3.76
3.96
4.03
4.14
1.21
1.65
1.78
1.72
1.08
1.04
1.98
Variable B - Product Purchase:
3.54
2.53
2.52
3.14
3.09
3.34
2.57
3.11
2.99
2.89
3.45
3.39
3.26
3.77
3.68
3.86
4.03
1.22
1.34
1.68
1.65
1.09
1.32
2.09
Question 1
How should I calculate if a relationship exists betwen product research and product purchase?
Question 2
How do I find out if certain demographic characteristics such as gender and age influence the relationship between product research and product purchase?
Note: My focus is on the overall relationship between product research and product purchase and how this relationship is shaped by demographic characteritics.
In other words, I am NOT interested in the difference between males and females on its own; rather on the difference (if any) between the relationship of A and B for males and females. (unsure if this is the same thing but to me, there is a subtle difference)
Comment: Presumably these data are meant to be paired in the order given.
Comment: Yes, that is the intention
Answer: It seems clear to me that purchase must depend (in the statistical sense) on research rather than the other way round.  Therefore, I'd regress that way, plus "maleness" (that is, 1 for male, 0 for female) plus the interaction between these two, plus age, plus the interaction of age and research, and so on. The coefficient on research tells you about the relationship between research and purchase, and the coefficients on the interactions tell you if this relationship varies.
I'd also plot the data. Interactions are often not easy to interpret. Both SAS and R (and probably other statistical software) makes this sort of interaction plot fairly easy.
Comment: When you do regression in any common statistical program, you get a bunch of standard output. This will include F test for the overall model and t-tests for the individual effects. For example, in R, the syntax would look something like

m1 <- lm(purchase~research, age, sex, age*research, sex*research)

in SAS, you could use PROC GLM.
Comment: Thanks. I would love a little more detail to make sense of your answer. When you say "I'd regress it that way...", what test should I use. (As suggested in the other post, I am keeping my thoughts to myself I know this sounds pretty basic but I am starting from scratch....

How would you analyse this problem?


XML Schema MaxOccurs and MinOccurs is not validating

Question: I've created a XML Schema that features MaxOccurs and MinOccurs on some of my elements, however when i try to validate it comes up with the errors of "91 s4s-att-not-allowed: Attribute 'MaxOccurs' cannot appear in element 'element'."
Below is an example of one of my elements:
From previous posts they mention that it needs to be in a sequence. Which I'm pretty sure i have done.
Answer: You have two problems, at least:
1) The error
Attribute 'MaxOccurs' cannot appear in element 'element'."

Explains it all. It's maxOccurs. Case matters.
2) You are defining your enginesize element as a simple type (type="integer") while at the same time defining it as a complex type (nested <complexType>). You can't have them both.
If you want an enginesize element that has an attribute and also accepts an integer as simple content, you have to define it as having simple content, and use an extension to add the attribute.
What I believe you want to achieve is something like this:
<xsd:element name="enginesize" maxOccurs="2">
    <xsd:complexType mixed="true">
        <xsd:simpleContent>
            <xsd:extension base="xsd:integer">
                <xsd:attribute name="unit" use="required">
                    <xsd:simpleType>
                        <xsd:restriction base="xsd:string">
                            <xsd:enumeration value="CC"/>
                            <xsd:enumeration value="CL"/>
                        </xsd:restriction>
                    </xsd:simpleType>
                </xsd:attribute>
            </xsd:extension>
        </xsd:simpleContent>
    </xsd:complexType>
</xsd:element>


Como calcular o valor total considerando determinado atributo como parametro de incremento ou decremento?

Question: Tenho uma planilha em excel onde são registradas ações de compra (C) e venda (V) na mesma coluna, já em outra coluna tenho os valores negociados.
Exemplo:
  Ação |  Valores
  ----------------
    C  |  3.000,00
    C  |  200
    V  |  3.500,00

Em uma segunda tabela tenho registros de deposito (D) e saque (S):
  Ação  |  Valor
  --------------
    D   |  5.000
    S   |  500

Como posso calcular o saldo total em carteira considerando que, cada saque (S) ou compra (C) deve decrementar o saldo, já ações de venda (V) ou deposito (D) devem incrementar o saldo?
Answer: Criei um exemplo de acordo com as informações que você fez:

A fórmula que está contido na célula K3, que representa o Saldo atual:
=SOMA(C:C;G:G) - ( SOMASES(C:C;B:B;"C") + SOMASES(G:G;F:F;"S") )

Onde somo todos os valores e decremento de acordo com as Compras(C) e Saques(S)


Can't run drush from within website folder configured with IIS on Windows Server 2012

Question: I am trying to setup Drupal 8 on Windows Server 2012 on IIS. I have installed PHP7.0 and Composer. Using Composer I then installed Drush globally using composer global require drush/drush:8.*. Drush was installed at C:\Users\Myusername\AppData\Roaming\Composer\vendor\drush\drush. I have set the Path variable for the user 'Myusername' to include C:\Users\Myusername\AppData\Roaming\Composer\vendor\bin.
The problem I have is that if I cd into the website folder as configured in IIS, and then run drush version, I receive the following error:
"C:\\inetpub\\wwwroot\\mysite\\vendor\\bin\\drush.php.bat" is not recognized as an internal or external command, operable program or batch file.

If I run the same command outside of the site folder as configured in IIS, then drush version executes successfully.
It seems that when run from within the web site folder it is trying to run drush from within the website project instead of using the globally installed drush.
Any suggestions on how to get Drush running for the site?
Updated:
After some experimenting it seems that when I run Drush it looks for the closest vendor\bin directory. If it is not in the current directory, it works its way up the parent directories until it finds it. If it can't find it, it uses the globally set one. For example, if I run drush from either C:\\inetpub, C:\\inetpub\\wwwroot then will get this error:
`"C:\inetpub\vendor\bin\drush.php.bat" is not recognized as an internal or external command, operable program or batch file.
If I run drush version from outsite of C:\\inetpub directory then it works correctly.
Answer: Drush Launcher solved the issue for me.
Step 1 Download drush.phar and put it in project root folder
Step 2 Create drush.bat file in project root folder and put following content (it will run phar in window)
@echo off
php "%~dp0\drush.phar" %*

Now it will use local drush.
Comment: +1 Running Windows 10 MAMP Drupal installed with composer but Drush would not run. This helped. Thanks,
Answer: Try to copy C:\xampp\htdocs\drupalDrush\vendor\bin\drush.bat -> C:\xampp\htdocs\drupalDrush\vendor\bin\drush.php.bat
Answer: Your global drush version was not compatible with the site specific drush version or the site specific version of drush was broken. As you indicated, when you run drush version from outside your site the command works but not when the site specific version takes priority.
In my case the global drush version was drush 8.1 and the site specific version was 9.0 beta. To fix the problem I removed the site specific 9.0 beta version and relied on the global version.


Webforms with subheadings that have their own fields

Question: I realise what field sets are as they can group parts of your webform together. What I am looking for though is to have subheadings within those fieldsets.
I've been trying to find tutorials about this but all I can find is tutorials on how to build a simple webform with just a title, description and then label-field pairs.
Edit: Say I want a form that calculates taxes for someone and I want to start off with a fieldset that has a couple of radiobuttons like male/female, I live rural/I live in the city and whatnot. Then I want some label/textfield pairs like name address phone, etc...
Then within the same fieldset I would have a title that says 'do you have a secondary address?' and have that be the title for a subset of fields with again address and zipcode, etc..
Comment: Do you want to have a fieldset with a title, description _and_ a subheading?
Comment: Yes but description is not even the issue here. I'll do an edit with an example.
Comment: Can't you use a nested fieldset for that? (Or am I still not getting it?!)
Answer: Basically I got away with just putting up a markup title. I thought it was really necessary to have field groups in order to make a valid web form since it was suggested to me. I guess like Andy said, nested fieldsets might have worked as well.


Global denial of certain file(s) on Apache

Question: I run a webserver under Apache with several virtual hosts. I would like to prohobit the access to certain file names, but instead of using a deny rule on each vh I would like to know if I can achieve this with global configuration?
Update
I found the following to suit my needs.
<FilesMatch "myfile.ext">
    Require all denied
</FilesMatch>

Comment: I'm not certain you cannot (you can try it), but even if you can it will be highly unusual. Instead, you could use `include`.
Answer: According to the manual

Configuration directives set in the main server context (outside any <VirtualHost> container) will be used only if they are not overridden by the virtual host settings.

So in theory setting directives in the main config, if allowed by the context of the directive, should work and be enforced as long as you don't override the directive in either the <VirtualHost> section and prohibit .htaccess overrides.
But it is a simple case of testing if things actually work as expected...
Comment: Thank you very much HBrujin! Ofcourse .htaccess is a restricted file so I just copied that part to fit my needs :)


Model assumptions - not worth the effort?

Question: This question was inspired by this discussion I read recently. After obtaining our results, the assumptions from the models we used should be checked, otherwise these results may be deceiving.
Unfortunately, this important step is often skipped in practice in my field (health sciences), as I see it mostly because
i) checking model assumptions can be very time-consuming,
ii) it can make interpreting the results more difficult for the layman,
iii) it makes the results seem less attractive (e.g., if p-values are reduced after updating the statistical methodology in response to the violation of a model assumption, and
iv) analysts don't know the assumptions, how to check them or what to do when they're violated.
Whilst the consequences of the violation of these assumptions are not trivial, my question is how much would the literature actually benefit from every analyst verifying every assumption?
On the one hand, this would very probably improve the overall quality of the literature, such as reducing false positive and false negative findings and the occurrence of inflated coefficients and deceptively small standard errors and p-values.
On the other hand, the slower time taken to perform rigorous statistical analysis would greatly lower the publication rate. If we assume that the false findings described above are non-systematic due to the use of different data sets and methodologies, then I can foresee how it could be beneficial to have a higher publication rate – even if the quality of the results is lower.
Is there any truth to this?
Comment: Having written a comment paper on a paper that performed tests of assumptions and ignored the results, it is potentially wasting the time of other researchers not to test your assumptions before publishing (on the bright side I had always wanted to publish a paper about dinosaurs ;o).  Always be your own "reviewer 3" - find and correct your own problems before the reviewers get a chance to point them out.  Better to write a good paper slowly than a bad one quickly.
Comment: "as the "true" results will eventually reveal themselves as the number of publications increases." this is incorrect, it isn't difficult to find very well cited papers (over many years) where the findings are incorrect or the method useless.  This may be a better question for the Academia SE.
Comment: I think it would help to ask a more specific question. Which assumptions? Which test of those assumptions. For example, normality tests are rarely useful even though gaussian distributions are assumed.
Comment: If you don't want to check assumptions, then use robust methods that use fewer assumptions
Comment: @MikeHunter thanks for sharing! I love Harrell's work
Comment: Thanks for the discussion and thanks for both of your helpful answers on questions on this site :)
Comment: @DikranMarsupial Edited, thanks!
Comment: @FrankHarrell has some recent comments on this topic.  https://www.fharrell.com/post/assume/
Answer: Well, there is some truth to it, but it's problematic.

It would lower the publication rate.  OK. But getting rid of bad publications is a good thing. Too much garbage is published.

Checking model assumptions is time consuming  True, but it is time well spent.

It can make interpreting results more difficult for the layman  So, data analysts will learn ways to communicate.

It can make results less attractive  Ummm, if you rig your scale to say you weigh 10 pounds less than you do, you still need the same size pants.

Analysts don't know ....  Then train them or fire them. Better yet, hire analysts who know what they are doing.

True results will appear as studies are replicated Not necessarily, or even usually. And, if they are, then you look like an idiot. Do you want to be the one who has the most retracted articles?  Worse yet, someone might make an important decision based on your analysis.  And the Challenger exploded, killing the crew.
Comment: Edited in response to point 6!


LilyPond - dotted note chords

Question: I have a problem with dotted note chords in LilyPond, for example:
\version "2.22.2"
\relative c
{
    <f' g a c>4.\arpeggio
}

This produces:

For the sake of presentation, I am wondering is there a method to avoid showing the dot under line 1?
Answer: Reducing the number of augmentation dots displayed for a close position chord can be achieved by changing the number of "extra" dots that can occur (from the default 3, to 1):
\once \override Staff.DotColumn.chord-dots-limit = #1
See this page of the internals for more details and related settings:
https://lilypond.org/doc/v2.22/Documentation/internals/dotcolumn

Depending on the particular voicing of the chord and where it sits on the staff, you might also need to move the dots up or down slightly:
\once \override Staff.Dots.staff-position = #1
See: https://lilypond.org/doc/v2.22/Documentation/internals/dots
Comment: Thank you, that was nice and neat~:)

LilyPond - dotted note chords


where does wildfly store jdbc driver jar file?

Question: I'm using wildfly 8.2.  I registered the sqlite driver and created a datasource for it already.  It's connected fine and I can see it in the standalone.xml.
But when I search under the "wildfly-8.2.0.Final" directory, I can't find the "sqlite-jdbc-3.8.7.jar" file.
Do you know where wildfly store the physical jar file?
Thanks
Comment: How did you "register" the driver? Added it as a module? Deployed it?
Answer: You can just put the Jar-File of the driver in the Deployment-Folder of the Wildfly. "/wildfly-path/standalone/deployments" The files in this folder will always deploy on startup.
https://bitbucket.org/xerial/sqlite-jdbc/downloads/sqlite-jdbc-3.8.7.jar
Comment: Thanks but everything is started up fine for me. I can see in the console that it loaded up the jdbc driver fine. I'm just curious where it put the jar file.  I can't find it anywhere under the  directory.
Comment: The h2-jdbc-driver is the only one, which is included by default. Normally you have to add other specific driver, like postgresql or mysql. Do you deploy a maven-project or you added the driver to your lib-path? You can post your datasource and persistence-file if you like.


Kahler intonation screws

Question: I am looking to get some replacement intonation screws for the kahler bridge. Does anyone know what type of screw these as ordering from whammy parts would get expensive with shipping. I have placed the screw I'm looking for below, is there any alternatives?
https://www.whammyparts.com/kahler-replacement-parts/23xx-professional/kahler-clamp-plate-screw-detail
Answer: Despite the fact it states use a Phillips screwdriver, that head looks far more like a Pozidriv. You're probably not going to torque it so tight that it wrecks the screw or screwdriver bit, but it helps to use the right tool!
Need to take a sample along to an ironmongers - or machine shop, where the thread can be established. If it's made in the States, it could well be an imperial thread, otherwise it's going to be a metric. They all come in different pitches for the same diameter, but a thread gauge will verify which. Then it's simply a matter of buying a packet of them - maybe £1 for ten! If they're too long, it's a simple matter to saw them to length. Good luck!

Kahler intonation screws


Replace character with other character in a text file using perl

Question: I am having problem in parsing the output from the text file. I want to add pipe symbol in between the character to do mutliple search similar to egrep, the text file is as follows
service entered the stopped state,critical
service entered the running state,clear

Code:
open(my $data, '<', $Config_File) or die "Could not open '$Config_File"
my $reg_exp;
my $severity;
my @fields=();
while (my $line = <$data>)
{
   chomp $line;
   if(!$line =~ /^$/)
   {
   @fields = split "," , $line;
   $reg_exp = $fields[0];
   $severity = $fields[1];
   print $reg_exp;
   }
 }

 #print $fields[0];
 #last unless defined $line;

 close($data);

expected output
service entered the stopped state|service entered the running state

Comment: Can we see some input as well?
Comment: your code has nothing to do with the question asked; neither has the output. Please ask a real question, with real code and real input/output...
Comment: I had added the complete question, sorry missed full question while pasting
Comment: The input seems to be on two different lines. You want to concatenate them into one line? Are there other lines in the file? I.e. should *all* the lines in the file be concatenated to the line after?
Comment: @TLP yes what you posted is correct
Answer: You are not far off, you just need to actually concatenate the strings. The simplest way would be to push the $fields[0] to an array, and wait until the input is done to print it. I.e.:
my @data;
while (my $line = <$data>) {
   next if $line =~ /^$/;            # no need to chomp
   my @fields = split /,/, $line;
   push @data, $fields[0];
}
print join("|", @data), "\n";

I sense that you are trying to achieve something else with this code, and that this is a so-called XY-problem.


Is it possible to custom Event Date format?

Question: On the Drupal 7 Upcoming Event, I would like to show the Event Date with abbreviated "Day, Month date, Year - Time". However, There an option that I like, which is "Fri, Mar 28, 2014 @ 4:55pm", but it contained with the "@" symbol. Is there a way to custom this being "Fri, Mar 28, 2014 - 4:55pm"?
PS: I know there is a way to add new date type, by going to "Administration/Configuration/Regional and Language". But none of them work like the way I wanted.
Answer: You can add a new date/time format by going to Administration > Configuration > Regional and Language > Date and Time. In the upper right corner of the screen you see two tabs: Types & Formats. First go to Formats and add your desired date format there (according to PHP date formatting). In your case, this will probably be something like
<code>D, M j, Y - g:i a
</code>
Next, you go to Types and create a new date type. You can assign your custom date format to this new date type.


preg_match() [function.preg-match]: No ending delimiter '^'

Question: Consigo alguma ajuda em colocar os delimitadores corretos abaixo:
if (preg_match('/^[a-zA-Z0-9_-]+[/]{1}[a-zA-Z0-9_-]+$', $bloco)) {
  ....
}

Answer: Você colocou o delimitador no começo da expressão, falta o mesmo delimitador no final. Além disso, você não escapou a barra (/).
'/^[a-zA-Z0-9_-]+\/{1}[a-zA-Z0-9_-]+$/'

Outra coisa: quando você exige uma única ocorrência de um caractere, não é necessário usar quantificadores. Então, sua expressão ficaria assim:
'/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/'

Por fim, uma última melhoria: pode-se substituir os character ranges por classes de caracteres:

a-zA-Z por \w
0-9 por \d

Portanto, sua expressão ficaria assim:
'/^[\w\d_-]+\/[\w\d_-]+$/'

Comment: obrigado, mas voltou um erro : Warning: preg_match() [function.preg-match]: Unknown modifier ']'
Comment: Faltou escapar a "/". Alterei a resposta.


What is difference between .\, (local), localhost, and computername in windows?

Question: I had a question regarding the different ways to pull up the servername when trying to access a database located on your server.
What is the difference between .\, (local), localhost, and yourcomputername? I can use all of them as the server name when I log into SQL Server.
Can I use them interchangeably or only in specific scenarios? Is there a limitation on when I can use one vs the other?
I am confused about how windows resolves all of these to the same value. Would these still work when say you are using them on the same network but across different computers (i.e. trying to access a server located on a different machine)?
Answer: "localhost" will not work when you'll try to access SQL server from another computer because it pointing to 127.0.0.1.
"yourcomputername" should work if both computers (client and server) located in one workgroup/domain.
Answer: I would say there isn't really a difference in functionality when accessing a SQL server. It's a matter of personal preference.
(local) - I don't like it because it is SQL Server specific and has special characters.
localhost - is fine if you always want to connect to the local instance of SQL-Server and when using it in a script want to make it portable between many servers.
yourcomputername - works okay interactively, but when using in scripts it will connect to the same specific server when run on another server not the local machine. This may be what you want to do, but it may not be.
.\ - I never knew this existed, I personally always use . which is the same as localhost but much shorter and works in other Windows networking scenarios as well.


User's AD account deleted then recreated, now cannot access TFS

Question: I have a user who a couple months ago had access to our Team Foundation Server (TFS) 2013 instance (he was able to access queries, work items, backlogs etc via the web interface). Recently, we needed to delete his account, and recreate it. He no longer has access to TFS with the recreated account (it's the same domain\username).
What do I need to do to grant them access again? I've tried removing all permissions and adding them back, to no avail.
Comment: As Daniel stated in his answer, the new user account and the old user account are different objects and have different SID's, despite their being named the same. You'll need to grant the new user account the permissions that the old user account had in TFS as well as adding them to the same groups as the old user account and granting them NTFS permissions to any files/folders that the old user account had individual permissions to (if permissions were granted to users rather than groups).
Answer: If you delete a user account three things happen.

The account is deleted. More importantly, the SID of the user account gets deleted.
The account's SID reference is removed from all security groups.
The account's SID reference in any resource permissions becomes an orphan.

If you recreate a user account with the same name it will have a different SID. That is why you need to reassign permissions for that user to any group or resource (files, folders, printers, etc.) again. Even if the SAM account name (the user name) and the password are the same as before.

What do I need to do to grant them access again? I've tried removing all permissions and adding them back, to no avail.

I can say with absolute certainty that you did overlook a significant (maybe small) spot, when you added those permissions back. Probably group permissions (see point 2. above).
Answer: Daniel answer is correct, but you can do better. TFS has a little know utility to manage user identities described at https://msdn.microsoft.com/en-us/library/ms253054.aspx.
<code>TFSConfig Identities /change
</code>
Probably is too late, but imagine this sequence of actions.

Account DOMAIN\user is deleted (SID 1234) from AD
TFS will mark the identity deleted in its DB
Create account DOMAIN\user-temp (SID 2345)
Reassociate TFS identity DOMAIN\user to DOMAIN\user-temp using TFSConfig
Rename DOMAIN\user-temp to DOMAIN\user


Is it possible to set project's Output Path property from nuget powershell?

Question: I would like to set Visual Studio project property "Output Path" from nuget powershell console. How could it be done?
I have found a blog post describing how to set some project properties, but Output Path is not included.
Furthermore, the Output Path property depends on current build configuration (Debug/Release). How can be the Output Path set for any configuration (not active at the time)?
Answer: You want to set <code>(Get-Project).ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value</code> for example:
<code>(Get-Project).ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value = "bin\NewDebugPath"
</code>


How to Move files to the recycle bin

Question: I need to Move a file to recycle bin in .net 2003
I added microsft.visualbasic.runtime dll from refrence, but I could not able to get filesystem.deletedirectory, So what to do..Can any one help me?
Comment: This question WAS the top result on Google when I searched.  Isn't the point of stackoverflow to be a comprehensive database of programmer questions and answers, rather than to simply fill in the gaps?
Comment: I also agree with Matt on this. Chances are this guy just registered to ask this, then finds the answer before he gets and answer here, and then is never heard from again.
Comment: Have you tried Google? http://www.google.com/search?q=C%23+delete+file+to+recycle+bin
Comment: There really should be a "too easy to find on Google" reason for closing a question.
Comment: agreed, you really should try google first. Or at least report what you've tried?
Comment: NOW you're talking, guys! I've always discouraged easily Google-able questions.
Comment: Possible duplicate of [Send a File to the Recycle Bin](http://stackoverflow.com/questions/3282418/send-a-file-to-the-recycle-bin)
Answer: I found this, don't know if it works, but it's worth a shot.
using Microsoft.VisualBasic;

string path = @"c:\myfile.txt";
FileIO.FileSystem.DeleteDirectory(path, FileIO.UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);

EDIT: Wise words from Nifle:
Just remember to add a reference to Microsoft.VisualBasic.dll
Comment: Just remember to add a reference to Microsoft.VisualBasic.dll
Comment: +1 This does indeed work. I was just going to post the same answer myself.
Comment: Btw, it uses P/Invoke, as it seems from Reflector
Answer: Basically, between the reference at the top and actually calling the method you need the full name (after adding the library of course)
You can either fully call it:
Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(
    path,
    FileIO.UIOption.OnlyErrorDialogs,
    RecycleOption.SendToRecycleBin);

OR you can add the reference to the top with the others:
using Microsoft.VisualBasic.FileIO

and then
FilesSystem.DeleteDirectory( etc );

Answer: This might help you.  Looks like you need to either add a reference to Microsoft.VisualBasic.dll or use P/Invoke.
Answer: Have you got a
using Microsoft.VisualBasic.FileIO;

at the top of your page?
Answer: Using
FileIO.FileSystem.DeleteDirectory(path, FileIO.UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);

needs: 00:00:00.4036573 to delete one file. Using
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);

only needs: 00:00:00.1107684 to delete one file.
An implementation can be found there:
Send a File to the Recycle Bin
Comment: @xmenW.K. Sorry, it's to long ago but I think I used 1000 generated files and devided the time that was used to delete them to get an average time ;-)

How to Move files to the recycle bin


Erro ao passar o script de uma tabela do banco Firebird para PostgreSQL

Question: Estou tentando passar um script de criação e inserção de dados de um banco Firebird para PostgreSQL, porém em algumas tabelas está ocorrendo erro de sintaxe, estou utilizando a ferramenta SQL Manager Interbase & Firebird para gerar os arquivos *.sql das minhas tabelas do banco Firebird. Já tentei via CMD enviar os arquivos para o banco atrav´s do seguinte comando:
psql -h host -p 5432 -U postgres -d database -f (Local do arquivo *.sql)
mas o seguinte erro me retorna:
psql:C:/Backup/Script/CONTROLEIMPRESSOES.sql:573: ERROR: column "DATA" is of type date but expression is of type integer
LINHA 6: (163, 6, 2007-02-01, 29138, 31432, 2294, 160.58, 31388, 33...)
DICA: You will need to rewrite or cast the expression

Então fui fazer através do pgAdmin e o único modo de inserir assim no banco foi colocando a data entre "2007-02-01".
Minha dúvida é, como posso gerar um arquivo *.sql onde as datas já venham entre parênteses, para que não precise alterar linha por linha adicionando "" em cada data.
Answer: Se você tem a mesma estrutura nos dois bancos e está migrando de um para o outro, pode estar utilizando a ferramenta FullCopyConvert que é paga mas acho que a versão de testes pode te ajudar.
Se for um processo a ser executado poucas vezes você pode utilizar um editor de texto com suporte a expressão regular e adicionar aspas nas datas, assim não precisaria fazer manualmente em cada linha. Pode utilizar o Notepad++ e usar a opção de substituir como na imagem abaixo:
Comment: Obrigado pela dica do Notepad++, se encaixou perfeitamente para o que eu precisava


Bad training results when I am trying to find out defected and non-defected solar cells

Question: I am trying to classify which are defected solar cells. I have a huge dataset of both defected plates and non-defected solar cells. As per a few suggestions from research papers I have been using the VGG 16 model for the training purpose. But even after 3 epochs, it is showing 100 % accuracy. I don't why it is coming like this. Is there any other way to solve this problem, any other Algorithm.
I am uploading some of the defected cells which I have in my dataset
]2]2]3
<code>from keras.layers import Input, Lambda, Dense, Flatten
from keras.models import Model
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
import numpy as np
from glob import glob
import matplotlib.pyplot as plt

# re-size all the images to this
IMAGE_SIZE = [224, 224]

train_path = 'Datasets/Train'
valid_path = 'Datasets/Test'

# add preprocessing layer to the front of VGG
vgg = VGG16(input_shape=IMAGE_SIZE + [3], weights='imagenet', include_top=False)

# don't train existing weights
for layer in vgg.layers:
  layer.trainable = False

  # useful for getting number of classes
folders = glob('Datasets/Train/*')

# our layers - you can add more if you want
x = Flatten()(vgg.output)
# x = Dense(1000, activation='relu')(x)
prediction = Dense(len(folders), activation='softmax')(x)

# create a model object
model = Model(inputs=vgg.input, outputs=prediction)

# view the structure of the model
model.summary()

# tell the model what cost and optimization method to use
model.compile(
  loss='categorical_crossentropy',
  optimizer='adam',
  metrics=['accuracy']
)

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)

test_datagen = ImageDataGenerator(rescale = 1./255)

training_set = train_datagen.flow_from_directory('Datasets/Train',
                                                 target_size = (224, 224),
                                                 batch_size = 32,
                                                 class_mode = 'categorical')

test_set = test_datagen.flow_from_directory('Datasets/Test',
                                            target_size = (224, 224),
                                            batch_size = 32,
                                            class_mode = 'categorical')

# fit the model
r = model.fit_generator(
  training_set,
  validation_data=test_set,
  epochs=10,
  steps_per_epoch=len(training_set),
  validation_steps=len(test_set)
)
# loss
plt.plot(r.history['loss'], label='train loss')
plt.plot(r.history['val_loss'], label='val loss')
plt.legend()
plt.show()
plt.savefig('LossVal_loss')

# accuracies
plt.plot(r.history['acc'], label='train acc')
plt.plot(r.history['val_acc'], label='val acc')
plt.legend()
plt.show()
plt.savefig('AccVal_acc')

import tensorflow as tf

from keras.models import load_model

model.save('defect_features_new_model.h5')
</code>
Comment: is the 100% accuracy in train or validation?
Comment: This is what I am getting ,,      Epoch 10/10
43/43 [==============================] - 21s 481ms/step - loss: 0.0118 - accuracy: 1.0000 - val_loss: 0.0177 - val_accuracy: 1.0000
Comment: So what is the problem? Your accuracy on validation is also 100%. Is it good?
Comment: I suspect something odd, getting 100% even after 3 epochs. Or else is there any other good method or any deep learning method to solve this problem.
Answer: It feels like the images are too simple and do not contain any complicated data. Hence they tend to overfit the VGG16 model. VGG16 models are generally trained on much more complicated data. You can try defining your own convolutional neural network. Since you are already using keras you can create sequential model to define your own model with minimum as 2 or 3 convolutional layersPlease refer the link for keras sequential model
Answer: Your data for the network looks very simple so it is not unexpected that you achieve high accuracy. Remember the network trains in batches so for every 32 images it goes through a back propagation cycle and updates the weights accordingly. So if you have a lot of images which you say you do then you are executing a lot of iterations on the weights.
I do not see a problem here. You are not  over training in the sense that your validation accuracy is 100%. Certainly you could get good results with a simpler model but why bother your results are what you would want.


Find a basis for which the transformation described by the matrix, A, can be described by a diagonal matrix

Question: I've been trying to find out how to answer this question.  Neither the notes from class, nor the textbook assigned for the class help.
Find a basis for which the transformation described by the matrix:
$$
 A = \begin{pmatrix}
    2 & 1\\
    2 & 3\\
    \end{pmatrix}
$$
can be described using a diagonal matrix.  Also, find a general expression for $A^k. $
Comment: Do you know about eigenvalues and eigenvectors? If you can find a basis for ${\bf R}^2$ consisting of eigenvectors of $A$, you win.
Comment: Is that what it was asking?  I wasn't even sure what it was asking.  But yes, we had been going over eigenvalues and eigenvectors.
Comment: If $Av=\lambda v$, and $Aw=\mu w$, then that says that with respect to the basis $\{\,v,w\,\}$ the transformation $T$ is described by the diagonal matrix $\pmatrix{\lambda&0\cr0&\mu\cr}$. So the question didn't specifically mention eigenstuff, but somewhere in your course materials I'm sure it points out this connection between eigenstuff and diagonalization.
Answer: First of all, find the eigenvalues of $A$. Then, find a basis $\beta$ of eigenvectors. If $A$ is the matrix of a linear transformation $T$ relative to the canonical basis of $\mathbb{R}^2$, then the matrix $D$ of $T$, relative to the basis $\beta$, is diagonal.
If $P$ is the change of basis from $\beta$ to the canonical basis, then $A = PDP^{-1}$. Then $A^2 = PDP^{-1}PDP^{-1} = PD^{2}P^{-1}$. By induction, we have that $$A^k = PD^kP^{-1}$$
Finally, since $D$ is diagonal, the powers of $D$ are very easy to find: they are also diagonal, and the elements in the diagonal are exactly the powers of the eigenvalues, that is, if $D = diag(\lambda_1,\lambda_2)$, then $D^k = diag(\lambda_1^k, \lambda_2^k)$.


Sort on Custom field in views

Question: I am using views 3 in D7 and have added custom field of percentage on students result listing. I want to sort on the percentage field, how can I add sort on custom field?
Thanks for your help.
Answer: Your custom field is added after the query is performed by views, and a the sort is done as part of the query, therefore your sort doesn't know about your custom field.
I'd probably try to store the percentage in a field on the content type and then you'll be able to sort using the normal views sort handlers.
Answer: I would go with using views php, they have a sorting option on there.
Comment: Views php is probably the worst module on http://drupal.org

Sort on Custom field in views


Testing custom hook and getting "Warning: An update to TestHook inside a test was not wrapped in act

Question: EDIT: I found a solution, coming from this video from Kent C. Dodds.
Just wrap the jest.advanceTimersByTime calls in an act function.
So this:
jest.advanceTimersByTime(510);

becomes:
act(()=>jest.advanceTimersByTime(510));

I've implemented a simple custom hook in order to debounce a value update.
Here is the code:
function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

The client of this hook is something like this (very simplified):
function Search(props) {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500);

  // doing something useful with debouncedSearchTerm....
  // ...
  // ...
}

So, I'm trying to test the hook with the code below:
import { renderHook, act } from 'react-hooks-testing-library';
import useDebounce from '../useDebounce';

jest.useFakeTimers();

it.only('should update value after specified delay', () => {
  const { result, rerender } = renderHook(
    ({ value, delay }) => useDebounce(value, delay),
    { initialProps: { value: '', delay: 500 } }
  );

  expect(result.current).toBe('');
  jest.advanceTimersByTime(510);
  expect(result.current).toBe('');

  rerender({ value: 'Hello World', delay: 500 });

  expect(result.current).toBe('');
  jest.advanceTimersByTime(498);
  expect(result.current).toBe('');
  jest.advanceTimersByTime(3);
  expect(result.current).toBe('Hello World');
});

Although, the test passes, I get the following warning:
console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:102

Warning: An update to TestHook inside a test was not wrapped in act(...).        When testing, code that causes React state updates should be wrapped into act(...):        act(() => {      /* fire events that update state */    });    /* assert on the output */        This ensures that you're testing the behavior the user would see in the browser. Learn more at.....       in TestHook        in Suspense

I get that if I'm about to call a function in order to update the internal state of the hook (e.g. increment() of a useCounter hook), I have to do it in an act function, as the documentation instructs.
But, the useDebounce hook I've implemented changes state by an internal useEffect that runs whenever value or delay change.
How can I get rid of this warning? Is it something wrong with my code? Am I forgetting to add  something in the test code?
Please help!
Comment: Possible duplicate of [Jest + react-testing-library: Warning update was not wrapped in act()](https://stackoverflow.com/questions/55181009/jest-react-testing-library-warning-update-was-not-wrapped-in-act)
Comment: I managed to solve the problem!
Check this: https://github.com/mpeyper/react-hooks-testing-library/issues/97
Answer: wrap this line into act:
it.only('should update value after specified delay', () => {
  const { result, rerender } = renderHook(
    ({ value, delay }) => useDebounce(value, delay),
    { initialProps: { value: '', delay: 500 } }
  );

  expect(result.current).toBe('');
  jest.advanceTimersByTime(510);
  expect(result.current).toBe('');

  rerender({ value: 'Hello World', delay: 500 });

  expect(result.current).toBe('');
  jest.advanceTimersByTime(498);
  expect(result.current).toBe('');
  // once delay time is passed, component is rerendered, so to capture that
  // in unit test, this line should be wrapped in act
  act(() => jest.advanceTimersByTime(3));
  expect(result.current).toBe('Hello World');
});```


Why is the slope of an decreasing function is less than or equal to zero?

Question: Let $f(x)=(x^2+a)e^{-x}$ be a decreasing function on the set of real numbers. Find the range of a interval of the real numbers that allows a reduction in the total set of real numbers.
$${d\over dx} f(x)=2x \cdot e^{-x}-(x^2+a) \cdot e^{-x}
=(2x-x^2-a) \cdot e^{-x} \le 0$$
$$e^{-x} \gt 0,-x^2+2x-a \le 0\Rightarrow4-4a \le 0\Rightarrow4 \le 4a\Rightarrow1 \le a$$
Shouldn't it be $1 \lt a$?
Answer: If you think about it carefully you will see that a function can be strictly decreasing even if its derivative has isolated zeros. Consider $f(x)=-x^3$ for a simple example.
Note also that "decreasing" can be used to mean "non-increasing" in some contexts, with "strictly decreasing" used for functions which are never stationary.


Update Laravel One-to-One Relation using dot notation in one request

Question: I have two related models
// User
public function profile()
{
    return $this->hasOne( Profile::class );
}

// Profile
public function user()
{
    return $this->belongsTo( User::class );
}

and I want update them both in one request so I have this form (simplified)
<input name="nickname">
<input name="profile[about]">

nickname field related to User model while profile.about - to Profile.
In my controller method I have this
public function update( User $user, UpdateRequest $request )
{
    $user->update( $request->validated() );
    return redirect()->back();
}

Validated data contains
[
  'nickname' => 'some name',
  'profile' => [
    'about' => 'some text'
  ]
]

I hoped profile.about field would update about column of profile table but it is not. Is it possible to update Profile model using this validated data without calling next $user->profile->update( $request->validated('profile') );?
Comment: maybe, just maybe, if you have this in you user controller getProfileAttribute, returning the relation ... but honestly, that's no a good ideia at all
Answer: For your given relationships, you can create a UserRequest class for validate data, more information
https://laravel.com/docs/8.x/validation#form-request-validation
The command php artisan make:request UserRequest will create UserRequest class in App\Http\Request namespace, then you must define your validation rules:
<?php
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserRequest extends FormRequest {
    public function authorize() {
        return true; // YOU WILL BE AUTHORIZE ALL REQUESTS
    }

    public function rules()
    {
        return [
            'nickname' => 'required',
            'profile.about' => 'required' //Nested array elements are validated with dot syntax
            // Other rules you need
        ];
    }

    public function messages()
    {
        return [
            'nickname.required' => 'Custom validation message for rule required',
            'profile.about.required' => 'Custom validation message for rule required'
        ];
    }
}

Then you must define your controller update method like so:
public function update( User $user, UserRequest $request )
{
    // At this point your data is valid, if not, 422 error will be returned with custom messages defined
    $inputs = $request->all();
    $user->update( $inputs );
    $user->profile()->update($inputs['profile'])
    return redirect()->back();
}

Comment: Hi, Daniel! Thanks but that is not what am I asking for. I want to know is there elegant way to deal with request data and avoid calling update again like `$user->profile()->update($inputs['profile']);`. I hope there is some Laravel way of doing this I don't know


PHP array values not being changed

Question: I was trying to make a program to do synthetic division which requires factoring so I wrote this function to factor an integer which works, but it never changes the  values of the php array $factors. Any help will be greatly appreciated.
$factors=array();
$i;
function factor($x){
    if($x==0){
        echo "(0,0)";
        } else {
            $n=false;
            if($x<0) {
                $x=abs($x);
                $n=true;
            }
            for($i=2; $i<=$x; $i++) {
                if($x%$i==0){
                    if($n){
                        $factors[(count($factors))]=(-1*($x/$i));
                        $factors[(count($factors))]=($i);
                        $factors[(count($factors))]=($x/$i);
                        $factors[(count($factors))]=(-1*$i);
                    } else {
                        $factors[(count($factors))]=($x/$i);
                        $factors[(count($factors))]=($i);
                    }
                }
            }
        }
    }
factor(-4);

Comment: Where is the return? they are being changed, but your not returning anything.  And your array `$factors` is outside the functions scope.
Comment: that's because `$factors` is outside the function. if you want to directly modify it in a function without either returning it or passing the memory address you need to use [`global`](http://php.net/language.variables.scope) in the function to manipulate it's scopre
Comment: global is so ugly ....
Comment: @ArtisticPhoenix i know, it's more of a convenient hack for lazy programming/ers
Comment: @Memor-X - yes but I have to admit I did find one valid use for it in my framework ( that I am making ) and that is as the environment ( such as production, debug ).  I thought of using a constant such as CI does, but then I cant change it on a page for page basis ... lol ... but I don't write functions either.
Answer: Try this
function factor($x){
     $factors=array();
    if($x==0){
        echo "(0,0)";
    } else {
        $n=false;
        if($x<0) {
            $x=abs($x);
            $n=true;
        }
        for($i=2; $i<=$x; $i++) {
            if($x%$i==0){
                if($n){
                    $factors[(count($factors))]=(-1*($x/$i));
                    $factors[(count($factors))]=($i);
                    $factors[(count($factors))]=($x/$i);
                    $factors[(count($factors))]=(-1*$i);
                } else {
                    $factors[(count($factors))]=($x/$i);
                    $factors[(count($factors))]=($i);
                }
            }
        } //end for
       echo '(' . implode(',', $factors). ')';
    } //end if $x == 0
}
factor(-4);

$factors is outside the scope of the function, besides that you were not returning or outputting anything. Seeing as you echo (0,0) I assumed you wanted it echoed such as (2,4,8) etc.  Which you can do with implode..

PHP array values not being changed


expected number of repeats in random strings from different sized alphabets

Question: The question is just for fun, and I feel like I'm missing a clever way of thinking about it.
suppose that you are on an alien planet, and you are trying to learn their language. You break into one of the aliens houses and get on his computer and print the contents of a file by accident. you have to figure out if this document is written in their language, or if it's just a binary file.
the idea here I think is that the alphabet for the language is smaller than the alphabet for a printed binary file. You would expect many more repeats from the string with the smaller language. after some string length, you would be able to give a pretty good estimate of the number of letters in the alphabet from which the text was written.
anyway, the question is, what is the probability of a string of length $n$ chosen randomly with an alphabet of size $m$ will have $k$ unique letters?
Answer: The number of words of length $n$ that use exactly $k$ letters from an alphabet of size $m$ is
$$ {m \choose k} k! \, S_{n,k} = \frac{m!}{(m-k)!}S_{n,k}$$
where $S_{n,k}$ is the Stirling number of the second kind, (you can think the alphabet as a set of $m$ urns, and $n$ numbered balls, each one corresponding to a position in the word). The total number of words is $m^n$. Hence the probabilities are given by
$$ p_k^{n,m} = \frac{m!}{(m-k)!} \frac{S_{n,k}}{m^n}$$
Comment: yeah, this is good. $S_{n,k}$ is unlabelled partitions, the $m\choose k$ gives all the label sets and the $k!$ gives all the labelings for each of those sets. This is a good formula to know.
Answer: The expected number of distinct  letters is easy to compute. The distribution of the number of distinct letters is much less pleasant, and I do not know of anything that avoids  messy Inclusion/Exclusion.
Let the letters be $a_1,a_2,\dots,a_m$. For any $i$, let $X_i=1$ if the letter $a_i$ occurs in our text, and let $X_i=0$ otherwise. Then the number of different letters is $X_1+X_2+\cdots +X_m$. By the linearility of expectation, we have
$$E(X_1+X_2+\cdots+X_m)=E(X_1)+E(X_2)+\cdots +E(X_m).$$
To find the expectation of $X_i$, we find the probability that $X_i=1$. This is $1-\left(\frac{m-1}{m}\right)^n$.   So the expected number of distinct letters is
$$m\left( 1-\left(\frac{m-1}{m}\right)^n  \right).$$
Comment: Yeah it's the distribution that was giving me trouble. Although this is a nice way of thinking about the expectation.
Answer: I think you are missing a great deal of information thinking only about the number of distinct characters.  A pure text file of English will have only about 60 of the 256 bytes represented, but 256 seems a natural number to use and maybe their language fills it up better.  On the other hand, maybe their byte is only 6 bits.  But the distribution of those characters will be very representative of text. exe files will have a very different distribution, but it will not be random either as certain instructions are much more common than others.  Compressed files are probably much closer to even in the distribution of bytes-that is what makes compression work.  I think it would be easy to distinguish the population of text files from exe files from compressed files.  Whether you could tell the first two apart seems more questionable.
Comment: these are very tidy aliens, all of their non-text files are perfectly compressed.
Comment: @Zackkenyon:  Then it should be easy to find the text files.  A perfectly compressed file has all the bytes with equal probability (the little stuff at the beginning to specify the compression fades into nothingness).  Any file that doesn't satisfy that is a text file.
Comment: keep in mind that these "files" I'm looking at are extremely finite in size. This is exactly the statement that I am trying to probabilistically extract from my observation.
Comment: @Zackkenyon:  the point is these distributions are *extremely* different.  It won't take much volume to tell one population from the other.  In [Cryptonomicon](http://en.wikipedia.org/wiki/Cryptonomicon) the hero has reduced the decryption of some text to a brute force search over an accessible number of possibilities, but the computer has to find the correct one.  He just checks the letter frequencies of the output.  If the key is incorrect, the frequencies will be *badly* wrong.
Comment: yeah but your confidence obviously increases with the length of the  message. The question is still one of "how long do these strings need to be before I can expect my observation to be useful."