Why do we need the vector normal to the surface in surface integration?

Question: I've been struggling with understanding how surface integrals come to be. Can someone please explain why they have such a format with a normal vector to the surface?
thanks!
Answer: Part of it is because of the fact that these methods were first used to understand physics, and there are clear physical interpretations. The vector coming out of the surface is the "flow", and so a lot of physical laws like Guass' law and Fick's ask about balancing flows (i.e. for Gauss' law, if a ball contains electrical charge, then the total flow of "electric force" out of the ball is proportional to the total charge, since any electrical charge outside the ball has a force which flows inward and one that flows outward and together those cancel).
Geometrically, it's because you have to scale the quantity by the "infinitesimal area", and the normal vector comes from the cross product of vectors on the surface and is thus a measure of area. If you need to dot the vector with something to get a scalar, then this is the "natural" quantity.
More mathematically, it's because the gradient (or differential form) is a covector, and thus is a function that takes in a vector and spits out a number (this is something that you go into depth in differential geometry). This is because of how it has to handle coordinate transformations.
Answer: Let $F$ be a vector field, $n$ a normal vector to the surface, with $u=\frac{n}{|n|}$ the unit normal vector.
The integral of the flux of a vector field through a surface requires an orientation (direction) that defines an "inside" and an "outside" relative to the surface that is the boundary between the "inside" and the "outside" .
We want to ask, for example, how much of the vector field $F$ is "escaping" from the the inside to the outside. To do this, we decompose the vector field into two orthogonal components: (1) the part normal to the surface; (2) the part tangent to the surface. At any given point on the surface, only the part normal to the surface escapes. We find this part by taking the dot product with the unit normal vector, which gives the orthogonal projection of the vector field onto the normal line: $F\cdot u=|F|\cos\theta,$ where $\theta$ is the angle between the two vectors.
The local surface area about a  point on the surface is given by the magnitude of the cross product of two vectors tangent to the surface at that point. This cross product depends on orientation, $u\times v=-v\times u,$  but both of these are normal vectors to the surface (they point in opposite directions).  Depending on our choice of orientation, we choose one of these to be $n.$ Then
$n=u|n|$, where $u$ is our unit normal vector, and $n=dS$ is the infinitesimal area.
At each point on the surface, we see that the total of the vector field escaping through the surface is the normal component $F\cdot u$ multiplied by the local (infinitesimal) surface area $|n|=dS.$ Summing over all points on the surface we get
$$
\int_S F\cdot u\ dS.
$$


Overfitting issues with convolutional neural network classifier

Question: I'm working on a classifier that uses a convolutional neural network. As part of this, the AdamOptimizer is used during gradient descent.
When I examine the results of training and testing, I'm finding significant overfitting given that the data available tends to be concentrated in several classes.
How can I reduce overfitting here? Ideas I've had, that I'm not sure are sound, or how they would work:

Change training data to make it more evenly distributed across classes
Modify the loss function in some way
Change the hyperparameters (learning rate?) for the Adam Optimizer
Answer: Have you tried adding dropout regularization? This is essentially removing a certain percentage of the neurons on every training iteration, resulting in a network less sensitive to the activations of specific neurons, therefore less fragile and sensitive to details in images in the training set.
It's perhaps explained better here: https://www.tensorflow.org/tutorials/layers. In the case of TensorFlow it's just a layer that you can stick between two arbitrary layers.


Error: creating build container: no such file or directory

Question: When running podman build, I get:
Error: creating build container: creating container: creating read-write layer with ID "d46b51efb16fd01f507af3bf70392b3c9376ba3d53b76170ab09407f097aabb4": Stat /home/federico/.local/share/containers/storage/overlay/f8c686ca891a580ae2a7931da6d670266e87e79a67b96fac2f9a97ab67bd2867/diff: no such file or directory

What does this mean? The parent directory exists.
Answer: Permissions in those directories probably got messed up somehow. Just remove the entire containers directory (assuming you don't have anything valuable there) and issue the command again. In your case:
rm -rf /home/federico/.local/share/containers/

Comment: worked for me :)


Ask 2 questions and have 3 different outcomes

Question: I am trying to ask users with a MsgBox two seperate questions. Depending on what they select yes to print the appropriate set of drawings.
This is where I am at so far. The single option Yes & No will work but the Yes & Yes does not.
Dim acadMsgBox As String, exclMsgBox As String
Dim LoginName As String, destFolder As String

acadMsgBox = MsgBox("Print all AutoCad Drawings to PDF?", vbYesNo, "Drawings (" & Worksheets("Drawing Index").Range("D2") & " Package)")
exclMsgBox = MsgBox("Print all Excel Spreadsheets to PDF?", vbYesNo, "Spreadsheets (" & Worksheets("Drawing Index").Range("D2") & " Package)")

LoginName = UCase(GetUserID)
destFolder = "C:\Users\" & LoginName & "\Desktop\"

If acadMsgBox & exclMsgBox = vbYes Then
    Call AcadPlot
    On Error Resume Next
    Call ExcelPlot
    Shell "Explorer.exe" & " " & destFolder, vbNormalFocus
ElseIf acadMsgBox = vbYes Then
    Call AcadPlot
    Shell "Explorer.exe" & " " & destFolder, vbNormalFocus
ElseIf exclMsgBox = vbYes Then
    Call ExcelPlot
    Shell "Explorer.exe" & " " & destFolder, vbNormalFocus
End If

Thanks for any feedback
Comment: `vbYes` is a constant with a value of 6.  `6 & 6` concatenates the strings "6" and "6", and gives you "66". You're probably looking for the `And` operator there.
Answer: The MsgBox function returns a VbMsgBoxResult enum value, which is essentially a named Long constant.

Dim acadMsgBox As String, exclMsgBox As String

Declare them As VbMsgBoxResult, not As String.

If acadMsgBox & exclMsgBox = vbYes Then

Declaring them As Long would work too, but with VbMsgBoxResult you get free autocompletion after the = sign.
& is the string concatenation operator, Comintern briefed you on it. You want to use a logical operator here:
If acadMsgBox = vbYes And exclMsgBox = vbYes Then

Note  that this would involve a bitwise operation that wouldn't produce the expected outcome:
If acadMsgBox And exclMsgBox = vbYes Then


Does the isomorphic image of a stabilizer subgroup fix a point

Question: Here is an exercise from [Birkhoff and MacLane, A Survey of Modern Algebra]:

Let $\phi: G \rightarrow G'$ be an isomorphism between two groups of permutations.  Let $S$ consist of those permutations of $G$ leaving one letter fixed.  Does its image $S'$ form a subgroup of $G'$?  Must the set $S'$ leave a letter fixed? Illustrate.

I can show that $S'$ forms a subgroup of $G'$. I was wondering about whether $S'$ must leave a letter fixed.  I think the answer is a `no' in general, and here is one solution, though I'd be glad to know of other approaches.
We can let $G$ be an embedding of $S_3$ into $S_4$, and $G'$ an embedding of $S_3$ into $S_6$, as follows.  $G:= \langle (a,b,c)(d), (a,b)(d) \rangle$.  To define $G'$, let $r=(1,2,3,4,5,6),s=(2,6)(3,5)$ (these are the usual rotation and reflection in the symmetries of the regular hexagon).  Take $G' := \langle rs,r^2 \rangle = \langle (1,2)(3,6)(4,5),(1,3,5)(2,4,5)\rangle$.  Then $G'$, which is a subgroup of the dihedral group $D_{12}$, is isomorphic to $S_3$ (it is a transitive embedding of $S_3$ into $S_6$).  Thus, $G \cong G'$, and an explicit isomorphism is given by $\phi: (a,b) \mapsto rs, (a,b,c) \mapsto r^2$.
If we let $S$ be the stabilizer in $G$ of $d$, then $S$ equals all of $G$ since $G$ itself fixes $d$.  And $S'$ equals all of $G'$ and hence has no fixed points. This gives an example where $S$ fixes a point but $S'$ doesn't.
If we let $S$ be the stabilizer in $G$ of $c$, then $S = \langle (a,b) \rangle$, and $S' = \langle rs \rangle = \langle (1,2)(3,6)(4,5) \rangle$.  Here too, $S$ fixes a point but $S'$ doesn't.
Of course, if the two permutation groups $G,G'$ are identical (which implies that their degrees are equal), then the image of a stabilizer would be another stabilizer.
Comment: Seems fine. If $\phi$ is an isomorphism of permutation groups (so not only are $G$ and $G'$ of the same degree, but they act in the same way, just on different things), then of course $S'$ fixes the point corresponding the point fixed by $S$. If $\phi$ is only an isomorphism of groups (but $G$ and $G'$ happen to be permutation groups), then your examples are clear and correct.
Answer: How about $S = \{1,2,3,4\}$, $G_1 = \{\mathrm{id}, (24)\}$, $G_2 = \{\mathrm{id}, (13)(24)\}$? $G_1$ and $G_2$ are isomorphic, and $G_1$ fixes $1$ and $3$ but $G_2$ doesn't fix anything.


iCloud not syncing properly for Core Data (iOS7)

Question: I'm attempting to sync Core Data among devices using iCloud (using the new iOS7 method). I'm still seeing issues with the syncing when testing with the simulators. Sometimes data from one simulator won't sync to another simulator. What could ever be the problem? Here's most of the code from the AppDelegate.m:
NSManagedObjectContext *context = [self managedObjectContext];
if (!context)
    [self displayAlert];
rvc.managedObjectContext = context;

The main code:
#pragma mark -
#pragma mark Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext {

    if (__managedObjectContext != nil) {
        return __managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (coordinator != nil) {
        NSManagedObjectContext* moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];

        [moc performBlockAndWait:^{
            [moc setPersistentStoreCoordinator: coordinator];
            if(!isOldVersion){
                [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(mergeChangesFrom_iCloud:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coordinator];
                [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(storesWillChange:) name:NSPersistentStoreCoordinatorStoresWillChangeNotification object:coordinator];
                [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(storesDidChange:) name:NSPersistentStoreCoordinatorStoresDidChangeNotification object:coordinator];
                [moc setMergePolicy:[[NSMergePolicy alloc] initWithMergeType:NSMergeByPropertyObjectTrumpMergePolicy]];
            }
        }];
        __managedObjectContext = moc;
    }

    return __managedObjectContext;
}

- (void)storesWillChange:(NSNotification *)notification {
    if (__managedObjectContext) {
        [__managedObjectContext performBlockAndWait:^{
            if ([__managedObjectContext hasChanges]) {
                NSError *error = nil;
                [__managedObjectContext save:&error];
            }
            [__managedObjectContext reset];
        }];

        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SCEmptyClips" object:self userInfo:nil];
        });

    }

}

-(void)storesDidChange:(NSNotification *)n{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SCDataChange" object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:@"SCPBUpdateCheck"]];
}

/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
 */
- (NSManagedObjectModel *)managedObjectModel {

    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    return managedObjectModel;
}

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil){
        return __persistentStoreCoordinator;
    }

    firstPost = NO;

    NSLog(@"STARTING to configure iCloud / new persistent store");

    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"SmartCopy.sqlite"]];

    NSDictionary *options;

    if(!isOldVersion && [[userDefaults valueForKey:@"SCiCloudMode"] boolValue]){
        options = @{NSPersistentStoreUbiquitousContentNameKey: @"MYStoreName"};
    }else if(!isOldVersion){
        options = @{NSPersistentStoreRemoveUbiquitousMetadataOption: @YES};
    }else{
        options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
    }

    [__persistentStoreCoordinator lock];

    result = [__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:nil];
    if (!result)
        [self displayAlert];
    [__persistentStoreCoordinator unlock];

    NSLog(@"Persistent store added. Now **%u** store(s)", [[[self persistentStoreCoordinator] persistentStores] count]);

    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"SCDataChange" object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:@"SCPBUpdateCheck"]];
        firstPost = YES;
    });

    return __persistentStoreCoordinator;
}

- (void)mergeChangesFrom_iCloud:(NSNotification *)notification {
    NSLog(@"iCloud actual import");
    NSLog(@"insert %@", [[notification userInfo] valueForKey:@"inserted"]);
    NSLog(@"delete %@", [[notification userInfo] valueForKey:@"deleted"]);
    NSLog(@"update %@", [[notification userInfo] valueForKey:@"updated"]);
    [__managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SCDataChange" object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:@"SCPBUpdateCheck"]];
}

#pragma mark -
#pragma mark Application's documents directory

/**
 Returns the path to the application's documents directory.
 */
- (NSString *)applicationDocumentsDirectory {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

Does anything there look wrong?
Answer: Here is how I do it. It might be an easy way to simplify and unclutter your code.
self.managedObjectContext = [[NSManagedObjectContext alloc]
                            initWithConcurrencyType:NSMainQueueConcurrencyType];
self.managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;
self.managedObjectContext.persistentStoreCoordinator =
                            [[NSPersistentStoreCoordinator alloc]
                            initWithManagedObjectModel:self.managedObjectModel];

[self.managedObjectContext.persistentStoreCoordinator
    addPersistentStoreWithType:NSSQLiteStoreType
    configuration:nil
    URL:self.storeURL
    options:@{ NSPersistentStoreUbiquitousContentNameKey : @"iCloudStore" }
    error:&error];

The only iCloud bit is the options parameter. (I removed other options for clarity.) The store URL is just [documentsDirectory URLByAppendingPathComponent:@"Store.sqlite"].
I am also listening to these:
NSPersistentStoreDidImportUbiquitousContentChangesNotification
NSPersistentStoreCoordinatorStoresWillChangeNotification
NSPersistentStoreCoordinatorStoresDidChangeNotification

In the first one, I call
[self.managedObjectContext mergeChangesFromContextDidSaveNotification:note];

and post another notification to update the UI; in the second one, I save; in the third one I also update the UI.
For me that's really all there is to it. It works flawlessly up to now.
Credit goes to iCloudCoreDataStack.
Comment: Thanks, I like that GitHub project. The idea of keeping the Core Data Stack in a separate class is great. Sync seems better now, however there still seems to be some simulator sync issues. Is it a problem to add new data to Core Data before the logs say "... Using local storage: 0"?
Comment: From my testing, `NSPersistentStoreDidImportUbiquitousContentChangesNotification` has never been called. However, I never have two devices running at once. I've seen where I add an entry with one simulator, and it doesn't appear on the second simulator. Should that notification be called to import the new entry, and it isn't?
Comment: No, it should be fired once the second instance of your app starts and there are changes. Not sure about your first question.
Comment: @Hope4You if you have an active iCloud store then it seems to be best if you wait until Core Data has switched to use that store.  This is especially true if you have data relationships that need to be satisfied.  I struggled for a while with this and now seem to have a stable operation.  Take a look at this link, and in particular the associated page about Enabling the User Interface, so far the approach has proven quite reliable. http://ossh.com.au/design-and-technology/software-development/uimanageddocument-icloud-integration/
Comment: @DuncanGroenewald Do you have any sample code for how to detect once Core Data has switched to the iCloud store?
Comment: Yes it's in the code I posted at the link above. Using UIManagedDocument the completion handler seems to get called once the fallback store has been opened, then you know that the next storeDidChange notification means the store has been switched to the iCloud store.  I typically then also check for the presence of seed data as well to allow for the seed data to be imported from transaction logs. If the network if not available then the logs won't get imported so your app need to handle this.
Comment: Here is a link with an explanation. I moved all This code to the OSDocumentManager now, but the logic is the same. http://ossh.com.au/design-and-technology/software-development/uimanageddocument-icloud-integration/when-to-enable-the-user-interface/
Comment: I just posted a sample library style app that uses the native Core Data stack not UIManagedDocument.  It includes a Settings Bundle to allow the user to chose to Use iCloud or not and handles migration of the store to and from iCloud.  Also provides the option to merge data from a device if the iCloud store already exists (i.e. another device already synced with iCloud).  http://ossh.com.au/design-and-technology/software-development/sample-library-style-ios-core-data-app-with-icloud-integration/
Comment: @Mundi Can you please have a look on this question? http://stackoverflow.com/questions/22420240/core-data-with-icloud-will-not-synchronize-after-reinstalling-the-app-on-ios-7
Comment: @DuncanGroenewald Can you please have a look on this question? http://stackoverflow.com/questions/22420240/core-data-with-icloud-will-not-synchronize-after-reinstalling-the-app-on-ios-7


How to reduce request to my database?

Question: i have a partial view with a gridview in it. so when user clicks add button request will redirect to Add method of unitsController. After add it to database I should refetch all data from database. Is there a way to prevent controller from get all database records?
Below is my current controller
public class UnitsController : Controller
{
    TList<Units> model=null;

    public ActionResult UnitsPartial()
    {
        if(model==null)
          model = database.GetAll();
        return PartialView(model);
    }

    [HttpPost]
    public ActionResult Add(Units unit)
    {
        if (ModelState.IsValid)
        {
            database.Save(unit);
            model.Add(unit);
        }

        return PartialView("UnitsPartial", model);
    }

In the last line I want to use return PartialView("UnitsPartial", model) instead of return database.GetAll() to prevent a database query.  But model is null in Add method.
Is my approach correct or not?  And why is model is null in add() method?
--UPDATED
first of all control redirect to UnitsPartial() and will fill model object correctly. after press add button, control will redirect to Add(...) method but this time model is equal to null !!!
what is the problem with it? i tried to pass model.Clone() to partial view
return PartialView("UnitsPartial", model.Clone());
but the result is the same
Comment: What do you mean by "Why is model is null in add() method?  As a code line that is not in the add method.  If you mean "why does model equal null in Add" then it would be null until you add the first unit.
Comment: @BalamBalam i update my question please read it.
Answer: I don't know if it is the right approach or not, since I do not fully understand what you try to do, but your model is null because you initialize it as null when the controller is created. you should do a model = new TList() before adding something to it....
Comment: the problem is pressing the add button is a new request which creates a new instance of the controller. When this is done, model is set to null upon creation of the controller, and still null when the Add method is executed. You need to set the model to something.
Comment: uhhh! am i in the wrong way totally? but wait i declared a bool variable and it`s worked! but model still is equal to null! that means controller is not such stateless!!!
Comment: I am not following you about the boolean, but again: When you press the Add button, a new request is done to the server, this creates a total new UnitsController object, upon creation `TList model=null;` is set, before executing the `public ActionResult Add(Units unit)` method. So, inside your add method, *model* is still NULL, either set it by doing `model = database.GetAll()` or create a new TList object. The fact that the model == null at the second request means that it **is** stateless
Answer: You can't cache values in the controller class like this using member variables.  HTTP is stateless and MVC 3 follows that approach.  Each individual call to an action method is going to have a brand new instance of Controller class with the model set to null.
So start by calling database.GetAll() in both action methods and then ask the question "How do I make this more efficient".

How to reduce request to my database?


Is $\frac{R[x]}{(f(x))}$ finite for $R$ finite and $f$ not monic polynomial?

Question:
If $R$ is a finite commutative ring, then is $\frac{R[x]}{(f(x))}$ finite with $f$ not monic polynomial?

I can prove above claim if f(x) is monic polynomial using division algorithm? But I am not possible further as if f(x) is not monic polynomials then I can not use division algorithm.
Any Help will be appreciated
Answer: In $\Bbb Z_4[x]/(2x)$, the elements $1, x, x^2, x^3, \ldots$ are all distinct.


Delphi arendondamento valores

Question: Estou com o seguinte problema:
                  | Result |
10     / 0,9280 = | 10,77  |
10     / 0,8740 = | 11,44  |
214,35 / 0,9280 = | 230,98 |

Obs: Essas informações estão gravadas no servidor com arredondamento, igual o exemplo.
Agora se eu pegar essas informações e inverter para mostrar para o usuário o valor original:
                   |  Result   |Correto |
10,77   * 0,9280 = | 9,99456   |  10    |
11,44   * 0,8740 = | 9,99856   |  10    |
230,98  * 0,9280 = | 214,34944 | 214,35 |

Como eu consigo fazer esse arredondamento?
Comment: você poderia arredondar com o método RoundTo desta forma, segue exemplo: RoundTo (1.234, -2); //retorna 1.23, então se vc arredondar RoundTo(9,99456, -3) acho que vc consegue o resultado.
Comment: Conseguiu resolver amigo?
Answer: Creio que possa utilizar a função System.Math.SetRoundMode. Segundo a documentação, ele pode assumir rmNearest, rmDown, rmUp ou rmTruncate. A documentação traz um exemplo aqui.
SetRoundMode(rmNearest); // Arredonda para o valor mais próximo

Answer: Você está salvando o resultado com apenas duas casas decimais, evidentemente a posterior multiplicação levará em conta apenas as duas casas e consequentemente não chegará ao valor desejado.
Como exemplo, veja:
Correto:
10     / 0,9280 = | 10,77586206896552

Seu código
10     / 0,9280 = | 10,77

Comment: Sim, mas não sou eu que gravo, essas informações já estão assim no servidor. Estou querendo achar uma forma de pegar esse valor do servidor com apenas duas casas decimais e converter no valor original.
Comment: Não tem como com 100% de garantia... pode tentar arredondar o valor final, ex.: `StrToFloat(FormatFloat('0.00',9.99456))` = 10.
Mas não é garantido que chegará no valor que vc quer...
Comment: Se verificar o terceiro numero depois da vírgula foi menor que 5, alterar para 5 no caso ficaria:
StrToFloat(FormatFloat('0.00',9.99556)) = 10. Será que dessa forma não daria certo?
Comment: Nesse caso específico sim, mas a questão é que nem sempre deverá arredondar para cima. No seu caso não vejo saída.

Delphi arendondamento valores


Using auth tokens in .npmrc

Question: I have a project where we use font awesome 5 library. I followed the instructions that are written here and added an .npmrc file with my auth token.
Is this a safe behaviour to put this in a repo? I want the devs to have access to it, but if the repo goes public we might be exposing the token.
What is the best practice in situation like this?
Answer: https://docs.npmjs.com/using-private-packages-in-a-ci-cd-workflow
Export your secret token into your session, e.g., export NPM_TOKEN="00000000-0000-0000-0000-000000000000"
Inside your ~/.npmrc, add //registry.npmjs.org/:_authToken=${NPM_TOKEN}
Comment: THIS is the answer I was looking for the last 4 HOURS! I don't know if all other answers I found work good on Win & Mac, but this is actually the only solution that worked on Linux for me! THANK YOU! ( I can only upvote 1 time.. this needs more upvotes!)
Comment: Is there a reason why `:_authToken=` doesn't work and that I had to put it on a separate line as `_auth=`? Was there some kind of syntax change or something?
Comment: With `{}` it returns: `error An unexpected error occurred: "Failed to replace env in config: ${NODE_AUTH_TOKEN}".`, without `{}` it works, as post above says.
Comment: without the {} it will fail in the remote pipelines :(
Comment: I keep my pw in `~/.ssh` (as this is a good, rights-deprived as much as possible folder anyway…)
And load it into the env var with: `export NPM_TOKEN=$(sudo cat ~/.ssh/npmpass | tr -d '[:space:]')`  (I am not going for full automation, just lazyness, so the inner sudo is just perfect for me as a barrier, allowing me to not even grant myself user rights to this file.)
Comment: This worked for me with `{}`.
`yarn version v1.22.19`
Answer: UPDATE 2021-05-02
This answer remains questionable - see the comments below. I no longer have access to a private ($paid) npm account anymore, so I can no longer test to answer questions.
Perhaps try @konyak's answer.

It is definitely NOT a safe behavior to put the token in any git checked file, including .npmrc.
Below are the steps your team can take to safely leverage your npm token.
There are two different environments to consider:

each developer's local dev machine
the app's deployment platform

local dev
Following the Global Set Up instructions you linked to in your question, is not the solution.
Create the .npmrc file similar to the "Per project" instructions, but substitute your real token with a variable name, prefixed by $. ie:
@fontawesome:registry=https://npm.fontawesome.com/
//npm.fontawesome.com/:_authToken=$TOKEN

npm will detect an environment variables file named .env. So, in a .gitignored .env file, add your secret key value pair, ie:
TOKEN=ABC123

You can also prefix the variable name with "NPM_CONFIG_", according to the npm-config docs, ie:
NPM_CONFIG_TOKEN=ABC123

Now, when the dev runs npm i, font-awesome dependencies will load from the private repo.
NOTE: Don't follow the current npm-config docs about the environment variables syntax! See this stack overflow answer, ie:
 BAD npm-config ENVIRONMENT VAR SYNTAX

${TOKEN}

 GOOD npm-config ENVIRONMENT VAR SYNTAX

$TOKEN

app deployment platform
Do all the steps from the local dev section above, PLUS:

create an environment variable on the platform with the same name as in the .npmrc file.

If your app host is Netlify, see their Build Environment Variables docs.
Comment: Where is it documented that npm install reads from .env? This solution is not working for me, the environment variables are not being detected.
Comment: The answer you linked to on why `$TOKEN` is preferable than `${TOKEN}` has been deleted (and also, never explained *why* `$TOKEN` should be preffered, just stated that it should). Can you please elaborate on this: why is `$TOKEN` preferable to `${TOKEN}`? If one works for you and the other doesn't, which OS are you on?
Comment: The answer about expansion isn't correct `$TOKEN` and `${TOKEN}` are identical in regards to what they expand to. Quoting the bash manual `The '$' character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional` (lmk if you want me to link to the zsh manual saying the same thing :D)
Comment: Saving to a `.env` file did not work for me. Had to export to my session
Comment: in .npmrc the '$' is not needed
Comment: Using a .env file did not work either for me. It somehow seems that the variable replacement does not fetch what's defined in the .env file. Is there some way to tell npm to read the .env file ?
Using $TOKEN just fails with authorization errors while using ${TOKEN} fails with error " Failed to replace env in config : ${TOKEN}".
(Note : placing the token directly in the .npmrc file works just fine, so the token itself is valid)
Comment: How do you prevent `npm login` from just putting your auth token right back in there?
Comment: Locally I can use `TOKEN` or `$TOKEN`, both work, but `${TOKEN}` fails!
But on GitHub CI and Heroku it has to be `${TOKEN}`!!!
Otherwise I get `Request failed \"401 Unauthorized\"`
Comment: do we have any work around for this @Brian Zelip ? I also see similar error failed to replace env in config?
Comment: It was the only working solution for me, thank you very much. MacOS.
Comment: when using expo eas build the "bad syntax" worked while the "good syntax" failed
Comment: `$TOKEN` never worked for me, had to use the curly brackets `${TOKEN}`...
Answer: I put the relevant config line, with the token in plaintext, in a .npmrc file in my home directory.  You can then use filesystem / OS permissions to protect it, avoid accidentally checking it in to source control, and NPM will read it automatically with no further action on your part.
In the project directory, we have .npmrc with a scoped registry declaration only (@fontawesome:registry=https://npm.fontawesome.com/), and a separate ci.npmrc which has that plus the variable-substitution authToken assignment:
@fontawesome:registry=https://npm.fontawesome.com/
//npm.fontawesome.com/:_authToken=$FONTAWESOME_NPM_TOKEN

The CI build job just has to replace .npmrc with ci.npmrc before doing anything with npm, and set a secret environment variable with an auth token assigned to the appropriate service account.
Answer: As an additional answer:
If you are using docker and passing env threw build args
Dont forget to add
ARG NPM_TOKEN
In your Dockerfile
Answer: Just an additional, regarding on Brian Zelip updated answer, I try to use custom variable name but it doesn't work, I guess there are variable enumeration behind this, because I use NPM_TOKEN and it works fine as well

Using auth tokens in .npmrc


Why isn't an image from the local domain shown with the explanation that, for security reasons, only images from the local domain are allowed?

Question: I'm running Drupal Core 9.3.7, with basically the default set up. The Basic HTML editor is CKEditor. If I include an image in a page, that image is not shown when I view the page; on inspection, it is actually there, but with the height="16" width="16" attributes, and a title that says:

This image has been removed. For security reasons, only images from the local domain are allowed

The image is in the local domain (the relative path is /files/inline-images/Picture%201.png); it was literally uploaded in the content editor. If I put in the URL of the image into the browser, it works. It doesn't seem an upload or a permission issue.
If I go to Configuration » Text formats and editors » Basic HTML » Configure and deselect Restrict images to this site, the images appear.
Any help would be much appreciated. I'm a complete Drupal newbie.
Comment: Is there a query string on the image URL?
Comment: @cliefen - no, just the URL to the file.
Comment: Does the text format have other filters active that might interfere here? I just read on https://www.drupal.org/project/inline_responsive_images/issues/2875845 (rather old though and for D8) that the "Display responsive images" and "Track images uploaded via a Text Editor" might have an effect on this.
Comment: @berliner There are a few other (default) ones on (Limit allowed HTML tags and correct faulty HTML, align images, caption images, Track images uploaded via a Text Editor) but turning this off does not fix the problem.
Answer: I solved this by re-ordering the filters, so tracking is done before the Restriction check.

Track images uploaded via a Text Editor
Restrict images to this site*
Image Resize Filter: Resize images based on their given height and
width attributes


How do I copy an open file to a database using "System.IO.File.ReadAllBytes()" or some other method?

Question: I need to make to following snippet of code work in the context of an open file.  This code needs to run in an Excel add-in to write the currently open document to a database.  At line 3, System.IO.File.ReadAllBytes() an error occurs indicating that the document is currently in use.  Is there an equivalent method that I can use that will work on an open document? If not, what is the solution?
Foo.DataClasses1DataContext db = new Foo.DataClasses1DataContext();
string ThisDocument = Globals.ThisAddIn.Application.ActiveWorkbook.FullName;
byte[] inputBuffer = System.IO.File.ReadAllBytes(ThisDocument);
Foo.RFP_Document rfpDocument = new Foo.RFP_Document();
rfpDocument.DocumentName = "Some Name";
rfpDocument.DocumentFile = new System.Data.Linq.Binary(inputBuffer);
db.RFP_Documents.InsertOnSubmit(rfpDocument);
db.SubmitChanges();

Here's a link to a similar question related to VB.  How do I copy an open file in VB6?
Comment: I would generally avoid storing whole files in the database, especially if they are large. Why not store the files as files in a specific folder, and then (from the database) point to that filepath?
Comment: I generally do that as well.  However in this case I know that the files will always be small, <1mb.  And I want the content of each document to be searchable.
Comment: I would still claim that 1 megabyte is too large. Afterall, that's approximately 1.000.000 characters (bytes) in UTF8 encoding. Why not just search through the files themselves?
Answer: You could just save a copy of the file using Workbook.SaveCopyAs, use this one and delete it afterwards.


Dead QML elements receiving signals?

Question: I have code similar to the following:
...
id: myComponent
signal updateState()
property variant modelList: []
Repeater {
    model: modelList
    MyButton {
        ...
        Connection {
            target: myComponent
            onUpdateState: {
                ...
            }
        }
    }
}

I assign a value to modelList and then issue myComponent.updateState() to update the MyButton components in the repeater. At this point I get a lot of warnings about non existent properties
It seems like the signal gets passed to the MyButton(s) that doesn't exist anymore (since the repeater will rerun when I change modelList).
Is there a way of avoiding this or should I simply ignore the warnings?
Answer: I had a similar problem when destroying QML components connected to C++ signals. The problem was solved by adding a handler for disconnecting the signals when the components were destroyed. In the dynamically generated components you could try manually connecting the signals, in order to manually disconnect them on destruction. In my case the code looks something like this:
MyComponent {
    Component.onCompleted: signal.connect(callback_function)
    Component.onDestruction: signal.disconnect(callback_function)

    function callback_function() {
        // process signal
    }
}

It might be, there is a better solution not needing manually connecting and disconnecting the signals, but this worked for me. If you add a console.log("Destroying...") to the onDestruction handler you can check whether or not the components are disconnecting the signal, thus actually being destroyed.

Dead QML elements receiving signals?


Construction of a space with fundamental group $\pi(S)=\mathbb{Z}/n\mathbb{Z}$ (with obstacles!)

Question: I've been reading the algebraic topology book by Massey and I've been trying to do the next exercise, from chapter 4, about the van Kampen's theorem:

Construct for every integer $n>2$ a space such that it's fundamental group is cyclic and of order $n$

From what I have seen we can do this exercise fairly easy with covering maps. The problem is that the exercise appears before the chapter that covers covering maps. I asked my teacher and he told me that you can do this exercise considering a $n$-polygon where each edge is identified as the same and we consider the same orientation.
For example the projective plane is a $2$-polygon where each edge is identified as the same and we follow the same orientation. When we consider a $n$-polygon we are obviously not treating with a surface.
How can we use van Kampen's theorem, to prove that the group is (I assume) a group of 1 generator and relations that is isomorphic to $\mathbb{Z}/n\mathbb{Z}$?
Could you please elaborate on how to do it? I have only seen the fundamental group of surfaces and I don't know how to get it on this particular example.
Comment: Your space is not a polygon. Your space is a *quotient space* of a polygon, obtained by identifying all of the edges of the polygon (oriented in the same way around the boundary of the polygon) to a single loop. The link in my comment contains a more explicit description of that quotient space.
Comment: Does [this](https://math.stackexchange.com/questions/900500/whats-the-meaning-of-this-about-the-cyclic-fundamental-group) answer your question?
Comment: Lens space is another example.
Comment: @BobDobbs: One might say that a lens space example would require covering space theory, although one can also show that a lens space has a cell decomposition whose 2-skeleton is homeomorphic to the object described in this post.
Comment: I'm afraid not, I am looking for the fundamental group of the n-polygon described. Also, in your link the edges don'tt appear in the orientation I am looking for.
Comment: @LeeMosher It seems like the *quotient space* appears in the next chapter in Massey's book. In the link they end up talking about the p-fold Dunce cap, which is similar to the one my teacher suggested. But it isn't exactly the same, right? It seems in the dunce hat there is a edge that don't follow the orientation as the others. Or I am seeing something wrong?
Comment: @LeeMosher Also, in the link you have provided, when they consider p=2 it is a Möbius band, meanwhile in my example it's a projective plane.
Comment: No, when $p=2$ they do indeed get the projective plane.
Comment: Anyway, despite the fact that the book you are reading does not get to quotient spaces until the next chapter, in order to make any sense of *your own post* one needs concepts of quotient spaces; furthermore, application of Van Kampen's theorem can only take place in the quotient space.
Comment: This may be tangential, but do you (OP) see intuitively (geometrically) how the proposed "$n$-fold dunce cap" example works?
Comment: do you know how to prove this for the $\mathbb RP^2$ case via van kampen?
Comment: @LeeMosher Here it is said that p=2 is a Möbius strip, is it incorrect? https://chat.stackexchange.com/rooms/16497/discussion-between-joseph-and-daniel-rust

Anyway, I think I see it more clearly now, I'll try to do it tomorrow, thank so much for the help!
Comment: @AndrewD.Hwang I think I do understand the majority of it. I have the doubt if, for example, when given the 3-fold dunce cap, the one in the wikipedia article, can we consider it a surface?
Comment: I shuould have searched first, there is a proof that it isn't a surface [here](https://math.stackexchange.com/questions/88180/how-do-you-prove-that-the-dunce-cap-is-not-a-surface)
Comment: @q19a: That conversation that you linked to is in the middle of a discussion about how to apply Van Kampen's Theorem in the quotient space. Van Kampen's Theorem uses a certain decomposition of the quotient space into a union of two open connected subsets. One of those subsets, denoted $U$, is a Möbius band, yes. But, like in any application of Van Kampen's Theorem, that subset $U$ is not the whole of the quotient space, it is a proper subset thereof.
Comment: It seems that you have some misunderstandings of the concepts of quotient spaces and how they are used to construct the spaces in your post. Let me suggest that you focus more directly on understanding those constructions first, rather than on the harder question of how to compute their fundamental groups.
Comment: @LeeMosher The construction of the space begins with the n-polygon, we consider the quotient space identifying every edge with each other in the same orientation. This yields a space that is contractible to a point and thus is not a surface. Am I missing something?
Comment: That last comment of yours would make an excellent question, *if* you also included your argument for why you think it is contractible to a point.
Comment: @LeeMosher When we consider the identification of the edges we get a 1-cell, which is homeomorphic to the 1-dimensional ball, which is essentially a line segment. For that reason it is contractible to a point.
Comment: Let me add to my previous comment: if you are arguing that the quotient space is contractible, then you should edit your post to insert this argument ***and*** to clarify what you are asking. That way, your argument can be seen by anyone on this site, and therefore it can be critiqued and answered by anyone on this site, rather than just by those who are willing to scroll down through the comments.
Answer: Let's call $X$ the space, the quotiented polygon, so the trick to computing this homotopy group is the following, let $*$ be a point in the center of the polygon, let $U$ be a neighbourhood around it wich doesn't touch the boundary, and $V=X\\{*\}$. Now this two open sets satisfie the hypothesis of Seifert Van Kampen, and each open set involved has the following homotopy type:
U is contractible
$U \cap V = U\setminus \{*\} \cong \mathbb{S}^1$
and the most difficult seeing is $V$, but to figure it out, you can see that before the identifications, $V$ has the $\mathbb{S}^1$ as a deformation retract, and after the identifications this is also an $\mathbb{S}^1$, to see this check that you are partiotioning the circle into equal pieces and pasting one after the other, this is just another $\mathbb{S}^1$. However the important point is that in the inclusion of $U \cap V$ in $V$ after doing the different reformation retractions this is not an inclusion anymore but can be represented as winding the first $\mathbb{S}^1$ $n$ times around the other.
Now, Seifert-Van Kampen tells you that the fundamental group of the pasted polygon is $\mathbb{Z}$, free product with the trivial group, which doesn't change anything, and with the quotient by the image of the inclusion of the intersection of the two open sets into the second one (this is the quotient because it must equal the map induced through the other inclusion, but as that other fundamental group is trivial, this must be 0). Thus the fundamental group is $\mathbb{Z}/n\mathbb{Z}$ as we wanted to see.


object xml is not a member of package scala

Question: The following code in the compiler:
abstract class query {def get: Unit => scala.xml.Elem}

gives me the error: "object xml is not a member of package scala"
however when I use scala.xml.Elem in sbt through the command line it works just fine,
how do I fix this?
Thanks in advance
Answer: Scala-XML has been factored out into a separate library as of Scala 2.11, so it is not included in Scala projects by default. To include it in your project via sbt add this dependency:
libraryDependencies += "org.scala-lang.modules" %% "scala-xml" % "1.0.2"

Comment: I'm using eclipse, where should I place this is my project?
Comment: You didn't specify that in your question. I don't use Eclipse so I'm not sure. If it is still an sbt project within Eclipse, it should go in `build.sbt` or `Build.scala`, but other than that I have no idea.
Comment: How do I know if my project is an sbt project? (Sorry, I'm a huge noob to a lot of this)
Comment: @user3369872 how did you set up your project? Did you just created empty eclipse project, put scala jar on a classpath and written some code? If so, yes, likely your project isn't managed via sbt.
Comment: @user3369872 You tried that for a Scala 2.10 project, where the XML library is still part of the main Scala library. That would only work in Scala 2.11.
Comment: I tried adding the dependancy in a separate sbt file and got this at run time:
[warn]  module not found: org.scala-lang.modules#scala-xml_2.10;1.0.2
Comment: in my case clearing the `.bsp` and `.bloop/{projectname}` project-subfolders was additionally needed to get it running
Answer: (This is for Windows at least)
In Eclipse go to

Project > Properties

On the windows that appears (should be on Java Build Path on the left) choose the "libraries" section and click on "Add External JARs".
Navigate to your installation folder and then to the "lib" folder (usually

C:\Program Files (x86)\scala\lib

or

C:\Program Files\scala\lib

)
and add

scala-xml_2.11-1.0.2

or whatever version you have.
Comment: Where do you download JUST scala, then?
Answer: Update the dependency
// https://mvnrepository.com/artifact/org.scala-lang.modules/scala-xml_2.12
libraryDependencies += "org.scala-lang.modules" % "scala-xml_2.12" % "1.0.6"

Answer: I have the same error, I tried lots of ways. Finally, I found it is the Java Loading dependencies order issue. If I move it to the last one. it works fine for me.
I modify it in my IntelliJ Idea:
cmd-; Project Settings -- Modules -- Dependencies
click + in bottom-left -- 2 Library -- From Maven


How to check given string date is my dd-mm-yyyy format in PL/SQL

Question: My date format is dd-mm-yyyy. there is a string date I want to check that string date is 'dd-mm-yyyy' if not( like dd/mm/yyyy, 10-OCT-2013) that function will return 'NO'
function checkMydateFormat(checkDate IN VARCHAR)VARCHAR{

IF(check date is 'dd-mm-yyyy')THEN
  RETURN 'YES';
ELSE
  RETURN 'NO';
END IF;

}

How can I write a PL/SQL function to check string date is correct format?
Comment: use FORMAT(Now(),'YYYY-MM-DD') to check date format
Comment: possible duplicate of [How to test if date format string is a valid date format string in Oracle](http://stackoverflow.com/questions/7979654/how-to-test-if-date-format-string-is-a-valid-date-format-string-in-oracle)
Answer: Try something like this
var par varchar2(20);
exec :par := '17-10-2013';
DECLARE
FUNCTION checkMydateFormat(checkDate IN VARCHAR2)
    RETURN VARCHAR2 IS RESULT VARCHAR2(10);
  BEGIN
    SELECT CASE
             WHEN regexp_like('7-10-2013', '\d{2}\-\d{2}\-\d{4}\', 'i') THEN
              'yes'
             ELSE
              'no'
           END into RESULT
      FROM dual;
    RETURN(RESULT);
  END checkMydateFormat;

BEGIN
  dbms_output.enable(NULL);
  dbms_output.put_line(checkMydateFormat(:par));

END;

Comment: WRONG.you did not bind the variable used, and the logic is wrong  , as it return 'YES' for '99-99-9999' too.:)
Comment: regexlike works for me like this :
if regexlike(value,'99.99') then
 //statements
end if :)
Answer: you can try to convert the string to the date using the desired format, and catch Exceptions. Somthing like the following:
create function checkMydateFormat(checkDate IN VARCHAR2)
RETURN VARCHAR2
IS
  v_result VARCHAR2(3);
  v_date    DATE;
BEGIN
  BEGIN
    v_date  := to_date(checkDate,'fxdd-mm-yyyy');
    v_result := 'YES';
  EXCEPTION
  WHEN OTHERS THEN v_result := 'NO';
  END;
  RETURN v_result;
END;
/

Comment: You don't need the interior begin and end and this will throw an error if the date is in the correct format...
Comment: It may return `yes` even if date string literal is of wrong format. For instance `10-OCT-2013`, but date format model clearly states that the month should be represented by two digits. To enforce exact matching between character date literal format model add `FX` format model modifier. (`'fxdd-mm-yyyy'`)
Comment: how can be 'YES' be saved in a datatype of varchar(2)?
Answer: CREATE OR REPLACE
FUNCTION checkMydateFormat(
          checkDate IN VARCHAR2)
     RETURN VARCHAR2
IS
     v_result VARCHAR2(3);
     v_date   DATE;
BEGIN
     v_date   := to_date(checkDate,'fxdd-mm-yyyy');
     V_RESULT := 'YES';
     RETURN V_RESULT;
EXCEPTION WHEN OTHERS THEN
     V_RESULT := 'NO';
     RETURN v_result;
END;

Answer: create or replace function checkMydateFormat(checkDate IN VARCHAR2)
RETURN VARCHAR2
IS
  v_date    DATE;
BEGIN
    v_date  := to_date(checkDate,'dd-mm-yyyy');
    RETURN 'YES';
  EXCEPTION
  WHEN OTHERS THEN
    RETURN 'NO';
END checkMydateFormat;


User roles and keeping their IDs when using features

Question: I have defined some user roles and I'm assigning them to users through the rules module. I have created a feature with the rules and the roles and moved them to another site. My problem is that the user roles get new IDs and that the IDs are hardcodet in the exportet rules. Therefore the rules assigns wrong roles and I don't want to fix that each time I install the feature.
Can I somehow hardcode the user roles programatically and let the rules module work on them? Is there a better solution for the problem?
It is more or less the same problem for taxonomies that also get assigned new IDs.
Answer: The Role Export module causes Role IDs to be hashes of Role Names — so the same Role Name will have the same Role ID on all sites.  Great in conjunction with Features.
For Taxonomies, the UUID Features module may be helpful.
Answer: In short, this is a limitation in Core. Not everything has a machine name, and thus cannot be reliably exportable. Perhaps by D8's release everything will have UUID or a similar solution, allowing us to solve this. Then again, it's not a "magic bullet", as it comes with it's own set of issues, which is why we still have this problem around.
I have a question over here that revolves around how to handle this problem. There are no perfect solutions, but you have some good input over there.
Answer: This is a limitation of the features module. The makers of the features module have decided to use a so called machine name to identify exportables. Roles don't have a machine name. You can, however write your own module that exports roles based on the rid of the role. See the file API.txt in the feature module directory for an explanation about which hooks to implement.


How to read Json result back from httprequest

Question: I making a get request to Zoho support endpoint, and the result for this call can be of two different structures. Either a result with error . which should look something like below(if the search results are none).
{
 "response": {
    "uri": "/api/json/accounts/getrecordsbysearch",
    "error": {
       "code": 4832,
       "message": "There is no data to show"
    }
  }
}

Or if the search results has one or more objects to be returned. It would look like:
{
 "response": {
"result": {
  "Accounts": {
    "row": {
      "no": "1",
      "fl": [
        {
          "val": "ACCOUNTID",
          "content": "8046200"
        },
        {
          "val": "URI",
          "content": "/support/"
        },
        {
          "val": "IsCommented",
          "content": "false"
        },
        {
          "val": "Username",
          "content": "Outdoo"
        }
      ]
    }
  }
},
"uri": "/api/json/accounts/getrecordsbysearch"
}
}

What would be the best way for me to parse the result, and do the following
:

An error : If so run Method A
if there is just one record that returns, then run Method B
If there is more than one record, then run Method C.

I am not too sure which will be the best approach to parse the json and check the content
Comment: You can create two C# types: one for result and one for error. First try to deserialize result. If reult is NULL than try to deserialize as error type. Not sure did I understand you properly.
Comment: @kat1330 : You got me correctly, and thats exactly what I had in mind too. But isnt there a better way to do , than creating multiple classes
Answer: If you create a class structure like the one below(Result class and classes below that structure were removed to make this example shorter), the json string always gets deserialized and you can then check if the error class has a value.
public class Error
{
    public int code { get; set; }
    public string message { get; set; }
}

public class Response
{
    public Result result { get; set; }
    public string uri { get; set; }
    public Error error { get; set; }
}

public class RootObject
{
    public Response response { get; set; }
}

Deserialize:
var o = new JavaScriptSerializer().Deserialize<RootObject>(json);

Comment: Thanks. That helped


Rules to convert a CFG to a NDPA?

Question: I have to define an FA by using this grammar:
S -> aSb
S -> c
S -> dA
A -> Sd

How do I manage the first rule and the last one?
For the second one I think I have to create another state (the final one) and link S and this new state. For the third one instead, I think I have to create the state "A" and link it to S by passing "d".
Comment: No a LLG is one in which _all_ rules, not just one, have a single nonterminal on the left. You cannot create an FA with this grammar. The grammar is not regular (because of the first rule). No FA exists. You can make an NDPA though because the language is definitely context-free. Where did you get this problem?
Comment: The title of your question indicates that you have a LLG, but you certainly do not. What are you asking? Are you asking how to make a finite automata for that grammar? That grammar isn't regular.
Comment: Hello, I though this was a left linear grammar because of the last rule. How do I proceed to create the FA?
Comment: If I would create an NDPA, which rules should I follow?
Comment: You can find dozens of tutorials and examples online. I just googled "how to make an NPDA from a CFG" and got quite a few hits.
Answer: There are algorithms you can use to get a PDA from a CFG: look into top-down and bottom-up parsers, for instance. What I think of as the usual proof that PDAs accept languages generated by CFGs, and vice versa, uses such a construction.
An alternative is to understand the language generated by the grammar, and to design a PDA for it directly. This is less mechanical but has the potential to yield a more concise PDA. If you want to go this route, we can first simplify the grammar by recognizing the nonterminal A can safely be replaced by the RHS of the only production for it:
S -> aSb
S -> c
S -> dSd    // removed A -> Sd and replaced here

How does this grammar work?

You have c in the middle by the 2nd production;
You have matching ds on the left and right of the c;
You have as on the left matching bs on the right of c.

A PDA should work as follows:

Read as and ds until you see a c. Push everything on the stack as you go. When you see a c, go to the next state, but don't push the c.
Read bs and ds, popping as and ds from the stack, until:

The topmost stack symbol doesn't match input; crash.
You run out of input with symbols still on the stack; crash.
You run out of stack symbols with input remaining; crash.
You run out of stack and input simultaneously; accept.

Here's a transition table:
q    s      x    q'   s'
------------------------------
q0   a,d,Z  a    q0   aa,ad,aZ
q0   a,d,Z  d    q0   da,dd,dZ
q0   a,d,Z  c    q1   a,d,Z
q1   a      b    q1   -
q1   d      d    q1   -

If we accept in q1 by empty stack, these transitions are enough. If we want to accept by empty stack or accepting state, we could add a transition like f(q1, Z, -) = (q2, Z) and make q2 accepting; the PDA would transition there nondeterministically and would crash unless the input were also exhausted.

Rules to convert a CFG to a NDPA?


Is this statement true or false? Find its negation.

Question:
Consider the statement
$$\forall x \in \mathbb{R}\;\forall y \in \mathbb{R}\ x+y>0$$
Is this statement true or false? Also, find its negation.

I think this statement is false because the inequality is not always true; for example, for $y=-x$, the inequality is false.
Can you show me how to write the solution in the proper way?
Comment: To show that the statement above is false, you simply need to prove that its negation is true.  You've found an $x$ and $y$ so that $x + y \le 0$, so done.
Comment: @ultralegend5385 the negated statement starts with a quantifier "there exists", so one example does prove it.
Comment: When $x=1$, $y=-2$ we have $x+y=-1<0$. Therefore the statement is false.
Comment: @GNUSupporter: One example *verifies* a statement, doesn't *prove* it.
Comment: Sorry, I misunderstood.
Answer: Write:
Since for $x=-1$ and $y=-1$, $(-1)+(-1)=-2>0$ is false. So, the given statement is false.
Clearly, the negation is:
$$\exists x,y\in\mathbb{R}\ x+y\leq0$$

DISCUSSION

To show that the statement is false, we just need one counterexample and we are done.

To find the negation, remember that the negative of "for all" is "there exists" and that of $>$ is $\ngtr$ or $\leq$.

Hope this helps. Ask anything if not clear :)
Comment: I'd choose $x=y=0$ ...
Comment: @MichaleHoppe: People are exercising their freedom of choice of counterexample lol.
Answer: For the sake of contradiction, assume the statement holds true.
Next, we fix $x\in\mathbb{R}$ and set $y = -x$. Observe that from our contradiction assumption, we have
\begin{align*}
x + y &>0\\
x + (-x)&>0\\
0 &>0
\end{align*}
However, this is impossible and hence it is a contradiction. Therefore, the statement must be false.


How do I create HMAC credentials for IBM Cloud Object Storage using the CLI?

Question: I am using the IBM Cloud CLI and tried to generate credentials for my cloud object storage service. However, the following command does not create HMAC credentials needed for using some S3 tools and APIs:
ibmcloud resource service-key-create cos-hmac-cli Writer --instance-name myobjectstorage

How can I create HMAC credentials using the command line interface?
Answer: The trick is to provide an additional parameter that tells the service to generate the HMAC part, too:
ibmcloud resource service-key-create cos-hmac-cli Writer \
--instance-name myobjectstorage --parameters '{"HMAC":true}'

The --parameters '{"HMAC":true}' adds the feature request in JSON format.


How to run build on a docker container when jenkins is in a docker container

Question: I have a jenkins single instance running in a docker container. The host is AWS 16.04.3 LTS (Xenial Xerus) system. I want the jenkins run my build inside a docker container but since jenkins is already running inside a docker. I don't want a nested docker container running in the build. How can I make jenkins launch a docker container on the host instead of itself container?
Answer: I found a solution for that is to mount this directory on jenkins container:
docker run -v /var/run/docker.sock:/var/run/docker.sock


Dynamically changing lat and lon in my LocationIQ url request

Question: I'm working on a website for my internship and I need to reverse geocode the lat and long coordinates of visitors, but I can't integrate those coordinates to my url string who request the reverse goecoding from a service called LocationIQ.
I've already tried to concatenate the plain variables into the string, I also tried to getElementById but it doesn't work either and then I called my callback() function but it still errors. For the notice I'm working with the given examples from http://geoip-db.com/ for the lat and long data and with  https://locationiq.com/docs#forward-geocoding for the reverse geocoding. Probably the examples don't like each other but since I'm a newbie in web dev I need a little help :)

Either it errors to the latitude call, or the request returns me "Invalid request". I want it to output all the reversed data into a json file like this:

{
      "place_id": "26693344",
      "licence": "© LocationIQ.com CC BY 4.0, Data © OpenStreetMap contributors, ODbL 1.0",
      "osm_type": "node",
      "osm_id": "2525193585",
      "lat": "-37.870662",
      "lon": "144.9803321",
      "display_name": "Imbiss 25, Blessington Street, St Kilda, City of Port Phillip, Greater Melbourne, Victoria, 3182, Australia",
      "address": {
          "cafe": "Imbiss 25",
          "road": "Blessington Street",
          "suburb": "St Kilda",
          "county": "City of Port Phillip",
          "region": "Greater Melbourne",
          "state": "Victoria",
          "postcode": "3182",
          "country": "Australia",
          "country_code": "au"
      },
      "boundingbox": [
          "-37.870762",
          "-37.870562",
          "144.9802321",
          "144.9804321"
      ] }
Answer: I have reviewed your code and found 2 mistakes.

You don't have jquery included so you can't use $.
And you shouldn't make locationiq api call outside of callback function but inside your function.

Here's my full code and it works. Please let me know if you have any questions.
<!DOCTYPE html>

    <title>GEOIP DB - javascript example</title>

Country:

Latitude:

Longitude:

IP:


Azure - API Management - Management API SAS token expiry

Question: We have an API management instance in azure.We have also enabled the management API. There we have set a SAS token & that has been used in the application. Here, we have to change the SAS token in every 30 days. If the token is expired, that will result into an application outage. Is there any way to get notified via email or any other means about the token expiry (in advance). I did some research on this, but , unfortunately could not find anything useful.
Answer: I don't believe there is built-in support for this.
You could instead have a logic app that takes in a SAS Token as input and schedules emails based on the expiry of the token.
TIP Apart from an email, you could do more interesting workflows like sending actionable messages using office 365 outlook or https://learn.microsoft.com/en-us/connectors/teams/#post-an-adaptive-card-to-a-teams-channel-and-wait-for-a-response connectors and even create a work item in Azure Devops or create an issue on GitHub, depending on what you use.
Answer: Alternatively you could create Azure AD application with client id and client secret, give it permissions to do what you need to be done in APIM and use its credentials to do all the same operations via ARM.


Rails Elasticsearch - multiple filter terms

Question: I have a model Campaign which can be created by a user of types: "NonProfit" and "Individual".
Now I want to search campaigns who are created by either NonProfit or Individual only, or by any of them.
Here is my model:
class Campaign < ActiveRecord::Base
after_commit lambda { __elasticsearch__.index_document  },  on: :create
after_commit lambda { __elasticsearch__.update_document },  on: :update

belongs_to :user

enum status: { waiting: 0, approved: 1, disapproved: 2, expired: 3, canceled: 4, draft: 5, published: 6}

def user_type
   self.user.rolable_type
end

def as_json(options={})
  super(:only => [:id, :status, :title, :description],
        :methods => [:user_type])
end

settings index: {
number_of_shards: 1,
analysis: {
  filter: {
    trigrams_filter: {
      type: 'ngram',
      min_gram: 2,
      max_gram: 10
    },
    content_filter: {
      type: 'ngram',
      min_gram: 4,
      max_gram: 20
    }
  },
  analyzer: {
    index_trigrams_analyzer: {
      type: 'custom',
      tokenizer: 'standard',
      filter: ['lowercase', 'trigrams_filter', 'asciifolding']
    },
    search_trigrams_analyzer: {
      type: 'custom',
      tokenizer: 'whitespace',
      filter: ['lowercase']
    },
    english: {
      tokenizer: 'standard',
      filter: ['standard', 'lowercase', 'content_filter']
    },
    czech: {
      tokenizer: 'standard',
      filter: ['standard','lowercase','content_filter', 'asciifolding']
    }
  }
}
} do
mappings dynamic: 'false' do
  indexes :status, type: 'string'
  indexes :user_type, type: 'string'
  indexes :en_title, index_analyzer: 'english', search_analyzer: 'english'
  indexes :ma_title, index_analyzer: 'czech', search_analyzer: 'czech'
  indexes :cs_title, index_analyzer: 'czech', search_analyzer: 'czech'
  indexes :en_description, index_analyzer: 'english', search_analyzer: 'english'
  indexes :ma_description, index_analyzer: 'czech', search_analyzer: 'czech'
  indexes :cs_description, index_analyzer: 'czech', search_analyzer: 'czech'
end
end

  def as_indexed_json(options={})
{ id: id,
  status: status,
  user_type: user_type,
  ma_title: ma_title,
  cs_title: cs_title,
  en_title: en_title,
  ma_description: ma_description,
  cs_description: cs_description,
  en_description: en_description
}
  end

   def self.search(query, user_type)
__elasticsearch__.search(
  {
    query: {
      filtered: {
        query: {
          multi_match: {
            query: query,
            fields: ['ma_title^10', 'cs_title^10', 'en_title^10', 'ma_description', 'cs_description', 'en_description']
          }
        },
        filter: {
          term: {
            status: "published"
          },
          term: {
            user_type: user_type
          }
        }
      }
    }
  }
)
 end

end

My Controller would look something like this:
Campaign.search(params[:q], 'NonProfit') # to search only NonProfit campaigns
Campaign.search(params[:q], 'Individual') # to search only Individual campaigns
Campaign.search(params[:q], ['NonProfit','Individual']) # to search any of the campaigns

However I always get 0 results. I works just fine when I remove the filter term 'user_type'. I am not succesffull to get the user_type filter term working as expected.
Any idea, how to make it working?
Thanks, Miroslav
UPDATE 1 (the filter user_type still does not work - 0 results):
def as_json(options={})
  super(:only => [:id, :status, :title, :description],
        :methods => [:user_type]
     #   :include => {
     #     :employers => {:only => [:title]},
     #     :roles => {:only => [:name]}
     #   }
  )
end

settings index: {
number_of_shards: 1,
analysis: {
  filter: {
    trigrams_filter: {
      type: 'ngram',
      min_gram: 2,
      max_gram: 10
    },
    content_filter: {
      type: 'ngram',
      min_gram: 4,
      max_gram: 20
    }
  },
  analyzer: {
    index_trigrams_analyzer: {
      type: 'custom',
      tokenizer: 'standard',
      filter: ['lowercase', 'trigrams_filter', 'asciifolding']
    },
    search_trigrams_analyzer: {
      type: 'custom',
      tokenizer: 'whitespace',
      filter: ['lowercase']
    },
    english: {
      tokenizer: 'standard',
      filter: ['standard', 'lowercase', 'content_filter']
    },
    czech: {
      tokenizer: 'standard',
      filter: ['standard','lowercase','content_filter', 'asciifolding']
    }
  }
}
} do
mappings dynamic: 'false' do
  indexes :status, type: 'string', index: 'not_analyzed'
  indexes :user_type, type: 'string', index: 'not_analyzed'
  indexes :en_title, index_analyzer: 'english', search_analyzer: 'english'
  indexes :ma_title, index_analyzer: 'czech', search_analyzer: 'czech'
  indexes :cs_title, index_analyzer: 'czech', search_analyzer: 'czech'
  indexes :en_description, index_analyzer: 'english', search_analyzer: 'english'
  indexes :ma_description, index_analyzer: 'czech', search_analyzer: 'czech'
  indexes :cs_description, index_analyzer: 'czech', search_analyzer: 'czech'
end
end

def as_indexed_json(options={})
{ id: id,
  status: status,
  ma_title: ma_title,
  cs_title: cs_title,
  en_title: en_title,
  ma_description: ma_description,
  cs_description: cs_description,
  en_description: en_description,
  :methods => [:user_type]
}
end

def self.search(query, user_type)
__elasticsearch__.search(
  {
    query: {
      filtered: {
        query: {
          multi_match: {
            query: query,
            fields: ['ma_title^10', 'cs_title^10', 'en_title^10', 'ma_description', 'cs_description', 'en_description']
          }
        },
        filter: {
          bool: {
            must: [
              {
                term: {
                  status: "published"
                }
              },
              {
                terms: {
                  user_type: user_type
                }
              }
            ]
          }
        }
      }
    }
  }
)
end

Comment: This hasn't to do with your question directly, but take a look into the [Searchkick Gem](https://github.com/ankane/searchkick). It's pretty popular in the Rails-Searchkick world. It provides a great interface for communicating with Elasticsearch and is very well tested.
Comment: Thanks Tobias. This is in my plan in future to look at that in more detail and reimplement the current app parts, but at the moment I need to finish the first version of the product as soon as possible and push it live.
Answer: You need to add "index" : "not_analyzed" to your mapping for the fields status and user_type. As you did not specify any analyzer ES was using standard analyzer for those fields.
mappings dynamic: 'false' do
  indexes :status, type: 'string', index : 'not_analyzed' <--- here
  indexes :user_type, type: 'string', index : 'not_analyzed' <--- here

If you need to use term filter, you need to make sure it is exact match as term queries do not perform any analysis.
Also for Campaign.search(params[:q], ['NonProfit','Individual']) # to search any of the campaigns you need to use terms filter as you are searching for more than one value.
EDIT Terms Query
Terms Query expect array of values
Campaign.search(params[:q], ['NonProfit'])

Try this
{
   "terms": {
      "user_type": ['NonProfit']
   }
 }

I hope this helps.
Comment: Thanks @ChintanShah25. I made the changes, but for some reason the "user_type" filter still does not work :/. I edit the content above - UPDATE 1.
Comment: I have updated my answer, can you try again? It should work now.
Comment: Actually I am passing an array like this, but 0 results:
Campaign.search(params[:q], ['NonProfit'])

Also this is the value stored in ES DB:
{"id":7,"status":"published","user_type":"NonProfit",....}
Comment: could you try querying only for user_type and see if it returns expected results? like `curl -XGET 'localhost:9200/your_index/_search?pretty=true' -d '{"query":{"terms":{"user_type":["NonProfit"]}}}'`
Comment: When I remove the user_type filter and keep the status one, it works just fine. If vice-versa (remove status and keep user_type filter) it does not work.  I think there is something wrong with the user_type method as this is the difference between status and user_type. Are the definitions for all user_type  occurrences in the model correct?
Comment: did you reindex the data after changing mapping? could you please double check the mapping with `curl -XGET 'localhost:9200/your_index/_mapping?pretty=true'`  I cant seem to figure out what is wrong, because same type of query is working on my dataset
Comment: You were right with the reindexing. For some reason I though that when I see user_type as part of the records in ES it is fine. And I was wrong. Thank you ChintanShah25! Now it works.


Theorem : If the moment of order t exists for an RV X, moments of order 0 < s < t exist.

Question: An Introduction to probability and statistics - Rohatgi Pg. No. 74 Theorem 2
Theorem : If the moment of order $t$ exists for an RV $X$, moments of order $0 < s < t$ exist.
The proof is given in the text.
I am not able to understand the proof. He uses a notation $|x|^s \leqslant 1$ in integral that I am not aware. Can someone help me understand the proof.
Also, I find Rohatgi really high level, but since my instructor follows this book, I am stuck with reading this book. Are there any good books that explains things a bit more and in line with Rohatgi's contents?
Thanks.
Answer: The idea is to compare $|X|^s$ and $|X|^t$: if $|X(\omega)|\geqslant 1$, then $|X(\omega)|^s\leqslant|X(\omega)|^t$, so $\mathbb E[|X|^s\chi_{\{|X|\geqslant 1\}}]$ is convergent. The integration over the set $\{|X(\omega)|\lt 1\}$ is not problematic as $|X|^s$ is bounded.


Runs-Up/Down RNG test question.

Question: There is not much relevant information to be found about Runs-Up/Down test on the great web. All I find is more or less just recycling the info than can be found in Knuth, The Art of Computer Programming Volume 2, 1998, pp. 66.
The Runs-Up/Down test should be run on a sample that has no ties between adjacent numbers (see Algorithm AS 157 on JSTOR or Knuth Vol.2). But what to do when I have ties between adjacent elements? My testing samples are random Integer numbers on interval from 0 to as low as 20 (usually the upper limit is around 150). In such sample there will be a lot of ties. The Algorithm AS 157 checks the sample and returns an error if ties are detected. But why should the Runs-Up test be limited to sample without ties?
To avoid ties I decided to check the sample and remove the ties (this lowers the sample size, but it is still well above the recommended minimum of 4000 elements). But then we noticed that the test will Fail badly for RNG on small interval (ex. 0 - 50), but Pass for larger intervals (ex. 0 - 300). Smaller RNG interval will produce more ties than larger interval, so this may be the cause of failed tests. Can anyone explain why?
Anyhow, the removing of ties is not OK because I should not alter the RNG output.
Another idea we had, was to let the ties and just re-define what an Up-Run is. We could say that the up run continues until the next number in a sequence is bigger or equal to previous number. But than what should I do with the length of run that contains ties. Should the run length be increased on a tie or not. Another problem is that I do not know if the matrix used in the algorithm remains the same (probably not).
So the question is: How can Runs-Up/Down test be used on a RNG sample of integers that have ties between adjacent numbers.
Note: The RNG is not causing the failed tests. Also the scaling of RNG output is not the cause (RNG usually outputs Integer from 0 to MAX_INT, this is than scaled to the desired interval). It has been tested on different "known to be good" RNG-s many many times.
Note2: When RNG is used only to produce shuffled arrays it will pass the test. For example, array [0,1,2...,14,15] is shuffled 1000 times to produce the output of length 15000 elements. Of course there can be ties between adjacent elements, but they are much rarer as the tie can occur only where two shuffled arrays "touch".
Comment: I am currently having this exact same problem. How did you decide to handle it? Did you use the answer below or something else?
Comment: Hello. I am still without good answer. But also I had other priorities since then .This is still open question. If you get some good info please share!
Comment: Thank you for your response! I am still trying to navigate these tests, so if I learn anything I will share!
Comment: do you know any tools that can use to implement this "runs test" for the RNG?
Answer: In the runs test, the mean and variance of the number of runs, which Google tells me are
$$
    \mu = \frac{2N-1}{3} , \qquad \sigma^2 = \frac{16N - 29}{90},
$$
are assuming that there will be no ties. So the correct thing to do to fix the test is to compute the mean and variance of the number of runs when ties are possible, and use these new values for seeing if the sample passes or fails.
To do this, imagine that all ties between adjacent values are arbitrarily broken: e.g. the run $1, 3, 5, 5, 8, 9$ is turned into $1, 3, 5, 5.1, 8, 9$ and $1, 3, 5.1, 5, 8, 9$ with equal probability. In that case, the single run is equally likely to remain a single run or to turn into three runs.
So we see that all ties contribute $1$ to the number of runs in expected value. (I'm ignoring the case of three or more equal elements in a row, which would have a different contribution but are much less likely.) Therefore the correct test statistic to use should be the number of runs plus the number of ties between adjacent values, and this will also have mean $\frac{2N-1}{3}$.
However, to apply the test, we also need to know the variance of this test statistic, which might be different from the $\sigma^2$ computed above.
Let $\mathbf R$ be the number of runs, $\mathbf T$ be the number of adjacent ties, and $\mathbf X = \mathbf R + \mathbf T$ be the test statistic. If there are $k$ possible values for the random numbers, then $\mathbf T$ has the $\text{Binomial}(N-1, \frac1k)$ distribution: there are $N-1$ chances for a tie to occur, and they occur independently with probability $\frac1k$. In particular, $\text{E}[\mathbf T] = \frac{N-1}{k}$ and $\text{Var}(\mathbf T) = (N-1)(\frac1k)(1 -\frac1k)$.
By the law of total variance,
$$
   \text{Var}(\mathbf X) = \text{E}[\text{Var}(\mathbf X \mid \mathbf T)] + \text{Var}(\text{E}[\mathbf X \mid \mathbf T]).
$$
For the first term, we have $\text{Var}(\mathbf X \mid \mathbf T) = \text{Var}(\mathbf R \mid \mathbf T)$. The distribution of $(\mathbf R \mid \mathbf T=t)$ - the number of runs, given that there are $t$ adjacent ties - is the same as the distribution of the number of runs in a sample of size $N - t$. So its variance is $\frac{16(N-t)-29}{90}$, and $\text{Var}(\mathbf X \mid \mathbf T) = \frac{16(N-\mathbf T)-29}{90}$. Finally, since $\text{E}[\mathbf T] = \frac{N-1}{k}$, the first term simplifies to
$$
   \text{E}[\text{Var}(\mathbf X \mid \mathbf T)] = \frac{16(N-\frac{N-1}{k})-29}{90}
$$
For the second term, we have $\text{E}[\mathbf X \mid \mathbf T=k] = \text{E}[\mathbf R \mid \mathbf T=t] + t$, and by the same argument as above, $\text{E}[\mathbf R \mid \mathbf T=t] = \frac{2(N-t)-1}{3}$. Therefore $\text{E}[\mathbf X \mid \mathbf T] = \frac{2(N-\mathbf T)-1}{3} + \mathbf T = \frac{2N-1}{3} + \frac{\mathbf T}{3}$. For the variance, the constant is irrelevant, and we just get $\text{Var}(\frac{\mathbf T}{3}) = \frac{N-1}{9} \cdot \frac1k \cdot (1 - \frac1k)$.

So, to summarize: the correct way to adjust for ties is to let $\mathbf X$ be the number of runs plus the number of ties, and compare it to a normal random variable with
$$
    \mu = \frac{2N-1}{3},\quad \sigma^2 = \frac{16(N-\frac{N-1}{k})-29}{90} + \frac{N-1}{9} \cdot \frac1k \cdot \left(1 - \frac1k\right)
$$
where $k$ is the number of possible values the random numbers can take on.
The variance is exactly correct, the mean is an approximation up to an order $\frac{N}{k^2}$ error term because I didn't take into account the number of triple ties: three consecutive elements, all equal.
Comment: Thank you for answering, but what you presented here is very simplified runs test.  Runs test (as described by Knuth) is not about average run length but about number of runs of length 1, 2, 3, 4, 5 and length 6 or more (look at both references in my question).
Comment: Here I am also not measuring run length but number of runs. I am not breaking them down by length but that is a more straightforward adjustment: we should just figure out what is $\mu$ and $\sigma^2$ for number of runs of length $k$ for $k=1, 2, 3, 4, 5$. Unfortunately, I don't have access to your references...
Comment: Problematic part of this approach is that runs are not independent. Long runs have bigger probability to be followed by short run than being followed by another long run.
Comment: The general approach should probably still work - see how breaking ties at random affects the number of runs, and adjust accordingly - but it's nontrivial to modify for the fancier version of the algorithm.

Runs-Up/Down RNG test question.


Using clientside_validation project, default validation plugin message not being overridden for states dependent field

Question: I am currently using clientside_validation with clientside_validation_states to validate conditionally required fields.
The issue I am experiencing is when the conditionally required element is invalid (empty), it is showing the generic "This field is required" (from jQuery.validation defaults) instead of using a message that is typically seen (and shows on all other, non-conditionally required fields) - for example, "First Name field is required".
I am using a custom errorPlacement method, but I'm not sure that it matters:
    // custom error placement
    Drupal.clientsideValidation.prototype.replaceLabel = function (error, element)  {
      var label, origLabel;
      var wrapperClass = 'formReplacedLabel';
      var WrapperEl = 'span';
      label = element.siblings('label');
      if (label.find('.form-replaced-label').length === 0) {
        label.wrapInner("");
      }
      label.addClass('labelError');
      label.prepend(error);
    };

So, the error being passed (for the states dependent control) to the custom errorPlacement method is just the default $.validator.messages.required instead of what is passed for the other controls.  I can't just change .messages.required to something that is for this field specifically either, as I have several forms with state dependent fields.
I have attached an animated gif that I think can explain the issue better than I do.
Answer: Turns out this is a bug. The hot fix is to add the $message argument to the _clientside_validation_set_equal() call on clientside_validation_fapi.module. So that it looks like:
_clientside_validation_set_equal($name, $title, $params[0], $js_rules, $message);.
I've started an issue and submitted a patch https://drupal.org/node/2140163


Apache Solr Search, add taxonomy field in search results

Question: I'm really bumping my head on this.
I simply need to add tids from a term reference field on nodes returned by a solr search result.
It's a unique term reference.
I looked for the field in solr console and it's 'im_field_arbo'.
I followed this and that and came to this :
1.
    function MYMODULE_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {
      if(isset($entity->field_arbo)) {
        $document->addField('im_field_arbo', $entity->field_arbo['und'][0]['tid']);
      }
    }

This doesn't throw back any errors.
2.
Then, to retrieve it, I tried either hook_apachesolr_query_alter, hook_apachesolr_query_prepare with :
    $query->addParam('im', 'im_field_arbo');

and hook_apachesolr_modify_query with :
    $params['im'] .= ',im_field_arbo';

Still, no trace of my field in my search results.
Any help ? Thx very much.

Update
I think my field is well indexed : _apachesolr_index_document_build_node works like a charm.
Now the question is : "How do I get them back in search results ?"
Comment: I know this isn't very helpful, but your code should work (with the `addParam()` method in `hook_apachesolr_query_alter()`). I have a nearly identical setup, just using a different field name, and it works great
Comment: Tell a lie, I'm actually using a hook named `hook_apachesolr_index_document_build_node()`, with `_node` on the end. Might be worth changing that, clearing the cache, and giving it a try
Comment: Thx @Clive , but still nothing... No error though *(after I removed "entity_type" from index_document_build_node's args)*.
Answer: To show the field you have added to your Solr index you first need to add it to the search result. Add this to template.php
function template_preprocess_search_result(&$variables) {
  $variables['im_field_arbo'] = $variables['result']['fields']['im_field_arbo'];
}

Then in your search-result.tpl.php you can access the field like this:
<?php if ($im_field_arbo): ?>
  <?php print $im_field_arbo; ?>
<?php endif; ?>

Comment: Thx. Very weird : I can't get that function to act on search... Nor var_dump, dpm, even kill won't be fired. In my theme's template.php, either with template_preprocess_search_result or *my_theme*_preprocess_search_result... Any help ?
Comment: update : I of course checked preprocessing, with __template_preprocess_*mymodule*_results__, and no trace of the field in $variables.
Comment: You need to put the function template_preprocess_search_result in your themes template.php file. Rename template with the name of your theme.
Comment: Tried it already :(
Comment: Still nothing ; does it work also with solr search ?
Comment: That function should be called `THEMENAME_preprocess_search_result`, not `template_preprocess_...`, if you're using search API solr or Apachesolr modules then you should definitely see it being invoked
Answer: Try this,
/**
 * Implements hook_apachesolr_process_results().
 */
function mymodule_apachesolr_process_results(&$results) {
  foreach ($results as $key => &$result) {
    $result['foo'] = $result['node']->im_field_arbo;
  }
}

Call this variable in you search-result.tpl.php
e.g.
<?php print $result['foo']; ?>

I think this code will work with the combination of:
function mymodule_apachesolr_query_alter(DrupalSolrQueryInterface $query) {
  $query->addParam('fl', 'im_field_arbo');
}

function mymodule_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type) {
  // I think you should do a foreach here, since you are using multi-valued field.
  foreach ($entity->field_arbo[LANGUAGE_NONE] as $key => $val) {
    $tid = $val['tid'];
    // The 1st letter indicates the data type and the last letter is
    // 'm' for multi-valued.
    $document->addField('im_field_arbo', $tid);
  }
}

I hope it helps.


Rewriting $X\leftrightarrow Y$ using only $\neg$ and $\lor$

Question: Note: The book I'm using doesn't have any solutions/answers so I will be posting some of the questions I'm unsure about in the hope that someone will check it for me.
Question: Re-write $X\leftrightarrow Y$ using only $\neg$ and $\vee$.
My attempt: We have $$X\leftrightarrow Y$$ $$\equiv (X\rightarrow Y)\wedge (Y\rightarrow X)$$ $$\equiv ((\neg X)\vee Y)\wedge ((\neg Y)\vee X)$$ where the last equivalence follows from the fact that $(A\rightarrow B)\leftrightarrow ((\neg A)\vee B)$.
Now since $(X\wedge Y)\equiv \neg ((\neg X)\vee (\neg Y))$, the last line above becomes $$\neg ((\neg ((\neg X)\vee Y))\vee (\neg ((\neg Y)\vee X)))$$ which is our answer. $\Box$
Thank you very much for your help.
Answer: I think your answer looks correct. Alternatively, the two-way implication says that either both are true or both are false:
$$\begin{align}
X\leftrightarrow Y&\equiv(X\wedge Y)\vee(\neg X\wedge\neg Y)\\
&\equiv\neg(\neg X\vee\neg Y)\vee\neg(X\vee Y)
\end{align}$$


Pass absolute url path to handlebars view in express

Question: I am trying to just set the canonical meta tag using an express server with handlebars as the templating engine.  I cannot figure out how to get the absolute url path and pass it to the handlebars view.  I was going to create a helper function in handlebars to do so but it would be outside of the req so I don't really know how to get the url or how to go about this.  I would like to set the canonical dynamically and not manually.  Thanks.
Here is my simple server:
const express = require('express');
const router = require('./routes/router');
const handlebars = require('express-handlebars');
const PORT = process.env.PORT || 5000;
const path = require('path');
const app = express();

var hbs = handlebars.create({
  defaultLayout: 'main',
  helpers: {
    canonical: function() {
      //get absolute url path
    }
  }
});

app.use(express.json());
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

router(app);

app.listen(PORT, err => {
  if (err) throw err;
  console.log(`ready at http://localhost:${PORT}`);
});

Answer: You shouldn't need a helper for this.  You can add the value to res.locals and access it via Handlebars.
app.use("*", function(req, res, next){
    res.locals.absoluteUrl = absoluteUrl; // Note, you'll need to calculate this yourself
    next();
});

In Handlebars, you access it as a standard variable:
{{absoluteUrl}}


Finding roots of complex polynomial with conjugates

Question: I am having problem with the following question...
I know that I should use De Moivre's formula somewhere... but can't quite get to it
$$ (-15w + 34\bar{w})^4 = -1 $$
will be happy to get some help,
Thanks!
Ron
Comment: Have you tried breaking it into two parts?  First solving for when $z^4 = -1$, and then for each solution finding $w$ such that $-15w+34\bar{w}=z$.
Answer: Let $w=a+ib\iff \bar w$
$$(19a-49ib)^4=1=e^{2n\pi i}$$ where $n$ is any integer
$19a+(-49b)i=e^{\dfrac{2n\pi i}4}$ where $n\equiv0,1,2,3\pmod4$
Now for each case, equate the real & the imaginary parts
Comment: Can you explain the  $e^{2n\pi i}$ ?


Como totalizar campos no blade usando Laravel?

Question: Caros,
eu estou fazendo um dashboard, e montei uma tabela no HTML, em uma View e preciso totalizar algumas colunas, e gostaria de fazer isso direto no HTML, porém como estou utilizando DB::select eu não consigo usar o comando SUM.

Será que existe alguma outra forma?
Será que consigo somar dentro do HTML, usando algum comando?
Comment: Coloque seu código? por favor! A `View` e o `Controller` responsável!
Comment: Qual a versão do Laravel?
Comment: Você pode usar variáveis para fazer  soma dos valores
Comment: Variáveis no próprio html
Answer: No Laravel o objeto retornado na consulta é o Collection. O mesmo tem um método chamado sum, que você pode usar para somar campos específicos (só que a soma é baseada nos resultados carregados pelo PHP, e não no que está no banco).
$produtos = DB::table('produtos')->select('quantidade', 'preco')->get();

$total_produtos = $produtos->sum('quantidade');

$total_preco = $produtos->sum('preco');

return view('minha_view', compact('total_produtos', 'total_preco');

Comment: Eu fiz os totais e joguei em variaveis, mas como eu tenho que exibir o total de colunas diferentes, de acordo com o módulo, eu acabei fazendo totais de todas as colunas. Mas eu queria que tivesse algo que pudesse usar direto no .blade para totalizar a coluna.
Se alguém tiver outra solução agradeço.
Answer: Para resolver esse problema você pode colocar o retorno da sua query em uma variável e passar para a view o total de itens dessa variável. ficaria algo como:
Controller
$dados = DB::select('sua query');
$total = $dados->count();
return view('nome da sua view')

Na sua view você pode pegar o valor total dessa maneira:

 {{$total}}


new array formation from current array in php

Question: I have an array like this in php
Array
(
    [0] => 1
    [1] => 3
    [2] => 5
    [3] => 10
    [4] => 14
    [5] => 15
)

Now I want it to look like
Array
(
    [0] => Array
        (
           [0] => 1
           [1] => 3
        )
    [1] => => Array
        (
           [0] => 5
           [1] => 10
        )
    [2] => => Array
        (
           [0] => 14
           [1] => 15
        )
)

Please suggest how to get the desired output using for loop.
Comment: Why use a `for` loop? Why not simply use array_chunk()? http://www.php.net/manual/en/function.array-chunk.php
Comment: Thanks Mark for the inbuilt function.Actually I like for loop with nested array which is really interesting(sometimes).
Answer: You could try something like this
$length = count($array);
$newArray = array();
for ($i = 0; $i < $length; $i +=2){
   $newArray[] = array($array[$i], $array[$i + 1])
}

Comment: @FritsvanCampen Thank you for your politeness, but I think I'll disagree with you on that one. Check out this test http://codepad.org/oVFpsRdI
Comment: A minor note but I believe caching the value of `count($array)` to `$length` doesn't do much here. It's a different case when you have something like `$i < $list->length` because then every time the interpreter will have to find `$list` and look at it's property `$length`. Something to keep in mind ;)
Comment: Thanks a lot Adnan.It's a great help.
Answer: for($i = 0, $count = count($array1); $i < $count; $i = $i + 2) {
    $array2[] = array($array1[$i], $array1[$i+1]);
}

print_r($array2);

Comment: One word 'brilliant'...thanks Michael for your help.The trick is in the for loop ($i = $ + 2)).I missed this part....Thanks.
Answer: Something that looks like :
for ($i = 0 ; $i < count($arr) ; $i += 2) {
    ...
}

Note that I increment $i twice on each iteration as I'm working with pairs of items : int the loop, I'll use $arr[$i] and $arr[$i+1] on each iteration. Note that this will not work correctly is the n# of items is not even !
The rest should be rather straightforward.
Comment: Thanks a bunch Fab.It was driving me nuts..:)


Migrating taxonomy terms when source is a separate table?

Question: I'm writing a migrator for a now-unsupported WordPress plugin that used a single "attachments" table to store data ranging from thumbnails to musical genres. It looks like this:
mysql> describe attachment;
+----------------------+--------------+------+-----+---------+----------------+
| Field                | Type         | Null | Key | Default | Extra          |
+----------------------+--------------+------+-----+---------+----------------+
| attachment_id        | mediumint(7) | NO   | PRI | NULL    | auto_increment |
| attachment_target    | varchar(32)  | YES  |     | NULL    |                |
| attachment_target_id | mediumint(7) | YES  |     | 0       |                |
| attachment_type      | varchar(32)  | YES  |     | NULL    |                |
| attachment_info      | text         | YES  |     | NULL    |                |
+----------------------+--------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

attachment_id is just an ID, attachment_target_id will correspond to a NID from the "artist" content type I'm trying to import this into, attachment_type is either "genre" or "thumbnail" and attachment_info is the actual data contained in the row ("Disco", as an example for a genre.).
To import all the genres into a taxonomy field, it seems I would extend the class that imports all the artists from the other table, then using $this->systemOfRecord = Migration::DESTINATION, import each row into the existing nodes. Alas, given each row would be a new migration item, it seems this would overwrite the values.
I've also thought about adding a sub-query to my initial artist migration that returns a comma-separated list of genres; alas, I'm not sure how I'd do that with Drupal database abstraction layer.
Any help? Thanks!
Comment: Don't get so complex. The only time you should use a dynamic query is when you have to customize the query terms based on the use case. Over 90% of the queries run in drupal are static queries using $result = db_query(). Then iterate through the rows to create an array: $artist[$target][$type][] = $info. Then implode(',', $artist[$target]['genre']) will give you your comma separated list.
Comment: just do 2 migrations. Create a copy of your taxonomy terms in D7 with some php code. Then 1) move artists 2) go thru second table with a simple migration query and assign the correct ID of your existing D7 terms.

you can try the approaches you've mentioned -- they seem more complicated.
Comment: @tenken -- So, migrate the genres *first*, you're saying? That's an idea...
Comment: @Triskelion Wait, you mean, just make a separate query inside of the class, using maybe prepareRow? That's an idea too... Thanks!
Comment: @Triskelion -- I've replaced my dynamic query with a nice static query that does everything I need it to, however, now I get the following error: "Recoverable fatal error: Argument 1 passed to MigrateSourceSQL::__construct() must implement interface SelectQueryInterface, instance of DatabaseConnection_mysql given, called in x/sites/all/modules/wordtour/wordtour.migrate.inc on line 116 and defined in MigrateSourceSQL->__construct() (line 108 of x/sites/all/modules/migrate/plugins/sources/sql.inc)"?
Comment: I am assuming you are simply migrating information from a wordpress site to a drupal site. Why fight with OOP? Just do it outside of the class as a simple function.
Comment: @Triskelion Still not following you. I do a static query outside of the migration class' constructor? Really lost...
Comment: Determine the information structure you will need in your class. Set up an external function to do the query and return the data structure. Call that function from within the class to inject the information.
Answer: The piece I was missing was GROUP_CONCAT for the attachment table. My query now looks like this:
$query = Database::getConnection('default', 'wp')
       ->select('artists', 'a');
$query->join('attachment', 'at', 'a.artist_id = at.attachment_target_id');
$query->fields('a',
          array(
              'artist_id',
              'artist_name',
              'artist_publish_date',
              'artist_bio',
              'artist_record_company',
              'artist_social_links',
          )
        );
//Pull in genres.
$query->addExpression('GROUP_CONCAT(DISTINCT at.attachment_info)', 'genres');
$query->condition('at.attachment_target', 'artist');
$query->condition('at.attachment_type', 'genre');
$query->groupBy('a.artist_id');