text:
Q: Gradient Filling a PNG with Quartz How can I fill the non-transparent areas of a PNG UIImage with a linear gradient?  I'd like to reuse a PNG shape for MKAnnotationViews, but change the gradient per annotation's properties.

A: To use an image as a mask for a gradient (i.e. to have a gradient in the shape of the non-transparent pixels of your image), you can:

*

*create a simple view with a gradient (you can either create a simple UIView and use the addGradientLayerToView shown below to give it a gradient or you can create the gradient PNG in advance and add it to your bundle).

*apply your PNG as a mask to that gradient view:
UIImage *mask = [UIImage imageNamed:@"mask.png"];
CALayer *maskLayer = [CALayer layer];
maskLayer.frame = CGRectMake(0, 0, mask.size.width, mask.size.height);
maskLayer.contents = (id)[mask CGImage];
gradientViewToMask.layer.mask = maskLayer;

To apply a gradient to the transparent pixels, you can either:

*

*Create a new image with a gradient:
- (UIImage *)imageWithGradient:(UIImage *)image
{
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 1.0);

    CGContextRef context = UIGraphicsGetCurrentContext();

    size_t locationCount = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = { 0.0, 0.8, 0.8, 1.0,   // Start color
                              0.9, 0.9, 0.9, 1.0 }; // End color

    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();

    CGGradientRef gradient = CGGradientCreateWithColorComponents (colorspace, components, locations, locationCount):

    CGPoint startPoint = CGPointMake(0.0, 0.0);
    CGPoint endPoint   = CGPointMake(0.0, image.size.height);
    CGContextDrawLinearGradient (context, gradient, startPoint, endPoint, 0);

    CGContextTranslateCTM(context, 0, image.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextDrawImage(context, CGRectMake(0.0, 0.0, image.size.width, image.size.height), [image CGImage]);

    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorspace);

    return gradientImage;
}

*You can also add a CAGradientLayer to a view and then add the UIImageView as a subview of that view.
- (void)addGradientLayerToView:(UIView *)view
{
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = view.bounds;
    gradient.colors = @[(id)[[UIColor colorWithRed:0.0 green:0.8 blue:0.8 alpha:1.0] CGColor],
                        (id)[[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0] CGColor]];
    [view.layer insertSublayer:gradient atIndex:0];
}

Note, you have to #import <QuartzCore/QuartzCore.h> as well as add the QuartzCore framework to your project.

A: I ended up hacking together some bits of Rob's code and an extension to UIImage I found at http://coffeeshopped.com/2010/09/iphone-how-to-dynamically-color-a-uiimage
+ (UIImage *)imageNamed:(NSString *)name withGradient:(CGGradientRef)gradient
{
    // load the image
    UIImage *img = [UIImage imageNamed:name];

    // begin a new image context, to draw our colored image onto
    UIGraphicsBeginImageContextWithOptions(img.size, NO, [[UIScreen mainScreen] scale]);

    // get a reference to that context we created
    CGContextRef context = UIGraphicsGetCurrentContext();

    // translate/flip the graphics context (for transforming from CG* coords to UI* coords
    CGContextTranslateCTM(context, 0, img.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    // set the blend mode to overlay, and the original image
    CGContextSetBlendMode(context, kCGBlendModeOverlay);
    CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);

    // set a mask that matches the shape of the image, then draw (overlay) a colored rectangle
    CGContextClipToMask(context, rect, img.CGImage);
    CGContextAddRect(context, rect);

    //gradient
    CGPoint startPoint = CGPointMake(0.0, img.size.height);
    CGPoint endPoint   = CGPointMake(0.0, 0.0);
    CGContextDrawLinearGradient (context, gradient, startPoint, endPoint, 0);

    // generate a new UIImage from the graphics context we drew onto
    UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGGradientRelease(gradient);

    //return the color-burned image
    return coloredImg;

}


text:
Q: Making a cross-thread call to a ListView I have a thread running in the background that periodically tries to update a ListView component, but every time it attempts to I get a "Cross-thread operation not valid: Control 'dlList' accessed from a thread other than the thread it was created on." error. I have used a delegate to try and solve this but it isn't fixing the problem. Is there something wrong with my code? I've also tried Invoke instead of BeginInvoke but same issue.
    delegate void updateListItemDelegate(string tag, ListViewItem lv);
    private void updateListItem(string tag, ListViewItem lv)
    {
        if (this.dlList.InvokeRequired)
        {
            this.dlList.BeginInvoke(new updateListItemDelegate(updateListItem),tag,lv);
            return;
        }
        else
        {
            int index = -1;
            foreach (ListViewItem x in dlList.Items)
            {
                if (x.Tag.ToString() == tag)
                    index = x.Index;
            }
            if (index != -1)
            {
                dlList.Items[index].SubItems[1] = lv.SubItems[1];
                dlList.Items[index].SubItems[3] = lv.SubItems[3];
            }
        }
    }

Called via:
    updateListItem(x.url, x.details);

A: Try the AsyncObservableCollection from Thomas Levesque.

A: Ah. I had a try {} catch {} around the code logging the exception, didn't realise that a ListView item I had set in a class also required a delegate to make a call to it as well as the form component. Nice tip Fredrik!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add multiple products to create one opportunity in Salesforce? I have this code snippet which is currently adding Opportunity with one product to Salesforce from Drupal page. Now the problem is that I want to create one opportunity with multiple product inside after user select multiple products at the same time.
    $fields = array(
        'Name' => 'Adhesion - ' . $field_nom_adhesion . ' ' . $field_prenom_adhesion,
        'Pricebook2Id' => 'sr3sdfxcvbwqe',
        'AccountId' => $AccountId_Con,
        'CloseDate' => $today,
        'StageName' => 'Proposition/Devis',
        'Cat_gorie_produit__c' => 'Adhésion',
        'Source__c' => 'Site web',
        'Statut_Adhesion__c' => str_replace("\'", "'", $field_statut_adhesion),
        'Contact__c' => $ContactId_Opp
    );

    $sObject         = new SObject();
    $sObject->fields = $fields;
    $sObject->type   = 'Opportunity';

    $sObject2         = new SObject();
    $sObject2->fields = $fields;
    $sObject2->type   = 'Opportunity';

    echo "<br/>**** Creating the following:\r\n";
    $createResponse = $mySforceConnection->create(array(
        $sObject
    ));


text:
Q: TomEE sesison persistance storage not working I am using TomEE plus 1.7.1 on rhel machine.
I have setup jdbc store for persistence storage to store session data in mysql databse. The jdbc store is not working on rhel machine. Even persistence in file is not working.
Below are the settings the I have done.
In the /conf/context.xml added this
<Manager className="org.apache.catalina.session.PersistentManager"
        maxIdleBackup="0">
  <Store className="org.apache.catalina.session.JDBCStore"
         connectionURL="jdbc:mysql://dbservername:3306/someName?user=[user]&password=[pass]"
         driverName="com.mysql.jdbc.Driver"
         sessionAppCol="app_name"
         sessionDataCol="session_data"
         sessionIdCol="session_id"
         sessionLastAccessedCol="last_access"
         sessionMaxInactiveCol="max_inactive"
         sessionTable="TOMCAT_SESSIONS"
         sessionValidCol="valid_session"/>
</Manager>

I have a TomEE start up script with the below contents. Line 2 is related to jdbc store
export JAVA_OPTS="-Djava.awt.headless=true -Dawt.toolkit=sun.awt.HToolkit"
export CATALINA_OPTS="-Dorg.apache.catalina.session.StandardSession.ACTIVITY_CHECK=true"
sh catalina.sh start

created the following in table in mysql
created following table
 create table tomcat_sessions (
  session_id     varchar(100) not null primary key,
  valid_session  char(1) not null,
  max_inactive   int not null,
  last_access    bigint not null,
  app_name       varchar(255),
  session_data   mediumblob,
  KEY kapp_name(app_name)
);

added mysql-connector-java.jar in /lib
The following error is observed
Errors observed-
for every applicattion deployed in apache i am getting these errors
SEVERE: Error manager.start()
org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.session.PersistentManager[/tomee]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5499)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
        at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1247)
        at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1898)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.session.JDBCStore[org.apache.catalina.session.PersistentManager[/tomee]]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.session.PersistentManagerBase.startInternal(PersistentManagerBase.java:864)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 12 more
Caused by: java.lang.NullPointerException
        at org.apache.catalina.session.JDBCStore.open(JDBCStore.java:961)
        at org.apache.catalina.session.JDBCStore.getConnection(JDBCStore.java:893)
        at org.apache.catalina.session.JDBCStore.startInternal(JDBCStore.java:1064)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 14 more

SEVERE: Error manager.start()
org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.session.PersistentManager[/myAppname1]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5499)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1083)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1880)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.session.JDBCStore[org.apache.catalina.session.PersistentManager[/myAppname1]]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.session.PersistentManagerBase.startInternal(PersistentManagerBase.java:864)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 12 more
Caused by: java.lang.NullPointerException
        at org.apache.catalina.session.JDBCStore.open(JDBCStore.java:961)
        at org.apache.catalina.session.JDBCStore.getConnection(JDBCStore.java:893)
        at org.apache.catalina.session.JDBCStore.startInternal(JDBCStore.java:1064)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 14 more

        SEVERE: Error manager.start()
org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.session.PersistentManager[/myAppname2]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5499)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1083)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1880)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.session.JDBCStore[org.apache.catalina.session.PersistentManager[/myAppname2]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.session.PersistentManagerBase.startInternal(PersistentManagerBase.java:864)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 12 more
Caused by: java.lang.NullPointerException
        at org.apache.catalina.session.JDBCStore.open(JDBCStore.java:961)
        at org.apache.catalina.session.JDBCStore.getConnection(JDBCStore.java:893)
        at org.apache.catalina.session.JDBCStore.startInternal(JDBCStore.java:1064)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 14 more

        SEVERE: Error manager.start()
org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.session.PersistentManager[/myAppname3]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5499)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1083)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1880)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.session.JDBCStore[org.apache.catalina.session.PersistentManager[/myAppname3]]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.session.PersistentManagerBase.startInternal(PersistentManagerBase.java:864)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 12 more
Caused by: java.lang.NullPointerException
        at org.apache.catalina.session.JDBCStore.open(JDBCStore.java:961)
        at org.apache.catalina.session.JDBCStore.getConnection(JDBCStore.java:893)
        at org.apache.catalina.session.JDBCStore.startInternal(JDBCStore.java:1064)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 14 more

A: I would not recommend using JDBC session persistence. Even the Tomcat manual recommends against it. It's unstable, slow, and error-prone.
It would appear something is going wrong with the driver: http://grepcode.com/file/repo1.maven.org/maven2/org.apache.tomcat/tomcat-catalina/7.0.55/org/apache/catalina/session/JDBCStore.java#961
I would look to make sure it's on your classpath first. After that, set a breakpoint in your debugger and see what is actually null.

A: In my case it was because I am using the wrong JDBC URL, especially the scheme part.
I used:
postgres://

(which is okay for psql, but not for JDBC). The correct one is:
jdbc:postgresql://


text:
Q: What is REST API end point for deleting specific version of a SharePoint Document I am trying to delete specific version of SharePoint document by Id.
I have retrieved all the SharePoint Document versions by REST call with below code.
      let URL : string = `${this.context.pageContext.web.absoluteUrl}/_api/Web/lists/getById('${listId}')/items(${documentId.Id})/versions`;
      this.context.spHttpClient.get(URL,SPHttpClient.configurations.v1).then(response=>{
        return response.json();
      }).then(json=>{
        return json.value;
      })

What endpoint should I call to delete specific version by it's version Id?

A: The endpoint for deleting the specific version of a file will like this:
https://Tenant.sharepoint.com/sites/SiteName/_api/web/GetFileByServerRelativeUrl('/sites/SiteName/DocName/code.png')/versions/DeleteByLabel('1.0')

Need to use GetFileByServerRelativeUrl to get the file object and then use DeleteByLabel for deleting the specific version, here is a complete code demo for your reference:
function DeleteFileVersionByVersionLabel() {

    var WebServerRelativeUrl = _spPageContextInfo.webServerRelativeUrl;

    // Provide Internal name of the library here
    var DocuentLibraryInternalName = "Document%20Library";

    // Provide name of the document
    var DocumentName = "test doc.docx";

    var ServerRelativeUrlofFile = _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFileByServerRelativeUrl('" + WebServerRelativeUrl + "/" + DocuentLibraryInternalName + "/" + DocumentName + "')"

    $.ajax
        ({
            // _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.
            // You can replace this with other site URL where you want to apply the function

            // NOTE: Version Label is nothing but the version number you see in the Version History
            url: ServerRelativeUrlofFile + "/versions/DeleteByLabel('4.5')",
            type: "POST",
            headers:
        {
            // Accept header: Specifies the format for response data from the server.
            "Accept": "application/json;odata=verbose",
            //Content-Type header: Specifies the format of the data that the client is sending to the server
            "Content-Type": "application/json;odata=verbose",
            // IF-MATCH header: Provides a way to verify that the object being changed has not been changed since it was last retrieved.
            // "IF-MATCH":"*", will overwrite any modification in the object, since it was last retrieved.
            "IF-MATCH": "*",
            //X-HTTP-Method:  The MERGE method updates only the properties of the entity , while the PUT method replaces the existing entity with a new one that you supply in the body of the POST
            "X-HTTP-Method": "DELETE",
            // X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
            success: function (data, status, xhr) {
                console.log("Success");
            },
            error: function (xhr, status, error) {
                console.log("Failed");
            }
        });
}

Reference:
Delete File Version By Version Label in SharePoint using REST API


text:
Q: Is "result in" a separable phrasal verb? I know *result in" is not separable the way switch on (something), "put on" (some piece of clothes), to name just a few, are. However I wonder if I can compose a sentence using "result in" like the following?

If human resources lack the skills and knowledge required for working in a varying environment, it could undoubtedly be said that any other endeavor and expense will not result but in a loss.

For me, the reason for separating result+in was only aesthetics. On grammatical integrity of my sentence, however, I am not sure.

A: In your examples:

switch on (something)
  put on (some piece of clothes)

these are used a transitive verbs, so the object can split them.

switch (something) on
  put (some piece of clothing) on

But result is an intransitive verb, so there is no object.
In this example:

That will result in sending two notices separately.
    That will result separately in sending two notices.

So you can split it, but not as in your example. When you can split it, I think you can usually turn it around as in the above examples. I would not naturally say say:

any other endeavor and expense will not result in but a loss.


text:
Q: Crashlytics not reporting crash in Release mode Crashlytics has been installed in the app in question for a couple of releases now. It's been working great.
But as we prepare the next release Crashlytics has stopped reporting crashes in Release mode. Here are the things I can think of that have changed since our last release.

*

*Xcode 7.1. The last release was prepared with Xcode 6.

*We upgraded to Fabric.

*We're testing the app on iOS 9.1.

Anyway, with all those changes crashes are still being reported just fine in Debug. Just not in Release (installing from TestFlight after archiving and uploading to iTunes Connect).
Here are the things I've checked:

*

*On the Fabric site the app is there, the version and build are there. When I click on Missing DSYMs it tells me there are none missing.

*startWithAPIKey is being called in didFinishLaunchingWithOptions (added after trojanfoe's question).

*The api key is correct. Checked and double-checked.

*In the build script there isn't (and never was) a distinction between Debug and Release. It looks like this:

*

*In Build Settings DEBUG_INFORMATION_FORMAT is already set to DWARF with dSYM File (added after StormXX's question):

What am I missing?

A: I was also facing this issue. My apps DSYMs files were not being automatically uploaded to Fabric as had previously been the case. The root cause was found to be that xcode 7.1 had defaulted the project to bitcode enabled = YES
Setting Bitcode enabled = NO in my Build Settings fixed the auto upload issue.
From Fabrics advanced set up document:

Bitcode enabled applications are required to download their dSYM from Xcode and then upload it to Crashlytics so that we can symbolicate the crashes.

A: Mike from Crashlytics and Fabric here.
With Fabric, the initialization of Crashlytics did change slightly. Using the following code should work (Obj-C):
#import "AppDelegate.h"
#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [Crashlytics startWithAPIKey:@"YourAPIKey"];
    // You can comment out the above line if you have your Twitter Fabric API key in your info.plist.
    [Fabric with:@[[Crashlytics class]]];
    return YES;
}

Updating the run script build phase to the following is also recommended:
./Fabric.framework/run <YourAPIKey> <YourBuildSecret>

A: I met the same problem and I sovle it...
Check your project's Build Setting , find Debug Information Format. change it to DWARF with dSYM File
Image

A: For me didn't help uploading dsym files from .xcarchive. Only when i've downloaded zip dSYM archive from the iTunesConnect and uploaded it to fabric - it make sense.

A: In my case, it was totally a different issue. Earlier I was getting all the crash reports perfectly but then due to some reasons, I have to update my bundle id of the project.
So If you update your bundle id then the project you have created on Fabric will not receive crash reports since you need to create one new project for that new bundle id.
Important: If bundle id is different on your fabric app then you will never receive any crash reports.
Tip: Create your projects in Fabric using the Fabric desktop application.


text:
Q: Can I do binding for element that is going to be created only at runtime in AngularJS? What I'm really asking is this:
I have array of objects inside a service, that at first load it may be empty.
var arr = {};

In one view the array is being added with objects.
arr[obj.id] = something;

Can I do binding to {{arr[obj.id]}} in html or code?

A: Yes it is allowed. Expression evaluation is forgiving to undefined and null in Angular JS.
Refer this link from angular https://docs.angularjs.org/guide/expression


text:
Q: Angular / DataTables: TypeError: Cannot read property 'aDataSort' of undefined with 2 API calls I've spent several hours trying to sort this issue out and I cannot find an answer that fits my case.
Issue
I want to display in a DataTable data composed using two API calls. Those calls are performed in a service and the data is then emitted as subject. The component subscribed to the subject then displays the data in a datatable.
The problem is that the datable doesn't show up and I have an error: TypeError: Cannot read property 'aDataSort' of undefined. This problem didn't happen when my data source came from a single API call and I suspect my concern is that the datatable is trying to instantiate itself before the data is loaded. I can fix the issue with an *ngFor by I have other kinds of bug, and I'd rather not do it like this.

In short, my question is: What am I doing wrong?

Code
Here is a simplified version of my code
api.service.ts
import {Subject, Subscription} from 'rxjs';
import {HttpClient} from '@angular/common/http';
...

export class APIService implements OnDestroy {
  // first data to be retrieved
  private data1: data1Structure;
  data1Subject = new Subject<data1Structure>();
  data1Subscription: Subscription;

  // second data to be retrieved
  private data2: data2Structure[];
  data2Subject = new Subject<data2Structure[]>();

  constructor(private http: HttpClient) {}

  emitData1Subject(){
    this.data1Subject.next(this.data1);
  }

  getData1() {
    this.http
      .get(`${this.baseURL}data1.json`)
      .subscribe(
        (response) => {
          this.data1Source = response;
          this.emitData1Subject();
        },
        (error) => { console.log(error); }
      );
  }

  emitData2Subject(){
    this.data2Subject.next(this.data2.slice());
  }

  getData2(){
    this.data1Subject.subscribe((data) => {
      this.data1 = data;
      this.http
        .get(`${this.baseURL}data2.json`)
        .subscribe(
          (response) => {
            // Combine the two datasets
            this.data2 = this.formatData2(response);
            this.emitData2Subject();
          },
          (error) => { console.log(error); }
        );
    });
  }
  ...
}

datatable.component.ts
import {ApiService} from '../../../services/api.service';
...

export class DatatableComponent implements OnInit, OnDestroy {

  data2Subscription: Subscription;
  colSettings = [
    {title: '#', data: 'Hid', width: '5%', visible: false},
    {title: 'Date', data: 'date', width: '45%'},
    {title: 'Title', data: 'title', width: '50%'}
  ];
  dtTrigger: Subject<boolean> = new Subject();
  dtOptions: DataTables.Settings;

  constructor(private apiService: ApiService) {
    // first API call
    this.apiService.getData1();
  }

  ngOnInit(): void {
    // second API call
    this.apiService.getData2();
    this.data2Subscription = this.apiService.data2Subject.subscribe(
      (data2) => {
        this.dtOptions = this.dataTable.getTableSettings(data2, this.colSettings);
        this.dtTrigger.next();
      },
      (error) => { console.log(error); }
    );
  }

  getTableSettings(records, colSettings: DataTables.ColumnSettings[]): DataTables.Settings {
    return {
      data: records,
      columns: colSettings,
      pagingType: 'full_numbers',
      pageLength: 50,
      deferRender: true,
      dom: 'lBfrtip'
    };
  }
}

datatable.component.html

Environment
Angular version: 9.1.1
Datatables version: 9.0.2
Chrome / Mac OS Catalina 10.15.5

I hope my question isn't too confusing, I really can't figure out what to do to fix this problem...
Thank you very much for your help!
Edit: fix indentation

A: I strongly suggest you change the way you're making your requests and merge them together in a single Observable. Seeing as you are consuming the results of your HTTP requests in your template, the best practice is to use the async pipe with the final merged Observable:
compiledData$: Observable<CombinedDataObjectType>; // create a custom type here

ngOnInit() {
  this.compiledData$ = this.http.get('firstUrl').pipe(
    switchMap(firstData => this.http.get('secondUrl').pipe(
      map(secondData => ({ firstData, secondData }))
    )),
  );
}

Your Observable now emits an Object containing both sets of data, so in the template:

Basically, avoid putting logic in subscribe callbacks, and in fact avoid subscribing in TS wherever possible. There is almost always a more elegant, more performant, easier maintained way to do things!


text:
Q: Aggregating observations I have observations like this
    Id     Result    Comments
    1      45        Good
    1      12
    1      33
    2      33        Good
    2      43
    2      10

I am trying to group these observations by Id , to produce an output as shown below
    Id      Comments
    1       Good
    2       Good

Need help


text:
Q: How to pass URL variables to javascript in PHP I need to take a URL variable into a PHP page, and then later pass it into some javascript that's in HTML later in the page.  Here's where I need to use the variable:
function dosubmit( ) {
new Ajax.Updater( 'result', 'dial.php', { method: 'post' , parameters: $('dialer').serialize() } );
$('dialer').reset();
}

the URL variable is formatted as dialout.php?ext=1234.  It is stored in PHP as $ext.  result is the div that returned html will be placed in, and dialer is a form that a user would enter a phone number into; I need to pass it along with the $ext variable to dial.php.  My thought was to concatenate the two, as
var ext = "<? $uext ?>";
var par = $('dialer').serialize();
var url = par;

and then using url in place of $('dialer').serialize().  This does not work, though; dial.php reports never gets the ext variable.  What's the best way to move a URL variable into PHP, then into js, then post it back to PHP?  I apologize in advance if I've mis-explained something, this is all new to me.
Thanks!

A: You have the right idea, but you need to use a command like print or echo to populate the variable:
var ext = "<? echo $uext ?>";

Otherwise $uext by itself as a PHP statement effectively does nothing.
Also, you need to include the ext variable into your parameter list.  Your current code as it stands doesn't make any further references to ext after it is populated:
var par = $('dialer').serialize();
par += '&ext=' + ext;

A: I can't understand fully what you want, but for similar cases I've been using:
from URL to PHP GET method, from PHP to JS JSON with jsonencode() (ajax), and finally a POST or GET in ajax to a php page.
There should be better ways to do it though.
At looking again at your example I've seen that you use php inside javascript, but you lack an  echo, so it should be like this:
var ext = "<? echo $uext; ?>";

A: If it's just a get parameter as you mentioned, there's no reason you can't access it directly in JavaScript. Since it's seems you're using jQuery, you may want to take a look at the Query String Object plugin.


text:
Q: Cluster Marker click event not triggering android I am developing an android application that needs to shows markers on map, for that i am using google map with clustering feature. I have downloaded a demo sample from official developers website. It has code of showing cluster of marker, and a method for triggering click event on a particular cluster. Here is my code :
public class ClusteringDemoActivity extends BaseDemoActivity implements ClusterManager.OnClusterClickListener<MyItem> {
    private ClusterManager<MyItem> mClusterManager;
    private ArrayList<My_Lat_Lng> list = new ArrayList<My_Lat_Lng>();
    private My_Lat_Lng my_lat_lng = null;
    private GoogleMap mMap = null;

    @Override
    protected void startDemo() {
        mMap = getMap();
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(21.0000, 78.0000), 1));

        mClusterManager = new ClusterManager<MyItem>(this, mMap);
        mMap.setOnCameraChangeListener(mClusterManager);

        mMap.setOnInfoWindowClickListener(mClusterManager.getMarkerManager());
        mMap.setInfoWindowAdapter(mClusterManager.getMarkerManager());
        mMap.setOnMarkerClickListener(mClusterManager);

        try {
            readItems();
        } catch (JSONException e) {
            Toast.makeText(this, "Problem reading list of markers.", Toast.LENGTH_LONG).show();
        }

        mClusterManager.setOnClusterClickListener(this);

        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

                LatLng latlng = marker.getPosition();

                //Toast.makeText(getApplicationContext(), "" + latlng.toString(), Toast.LENGTH_LONG).show();

                return false;
            }
        });

    }

    private void readItems() throws JSONException {
        //InputStream inputStream = getResources().openRawResource(R.raw.radar_search);
        //List<MyItem> items = new MyItemReader().read(inputStream);
        loadArrayList();
        List<MyItem> items = new MyItemReader().read_Lat_Lng(list);
        mClusterManager.addItems(items);
    }

    private void loadArrayList() {

        my_lat_lng = new My_Lat_Lng("51.5145160", "-0.1270060");
        list.add(my_lat_lng);
        my_lat_lng = new My_Lat_Lng("51.5064490", "-0.1244260");
        list.add(my_lat_lng);
        my_lat_lng = new My_Lat_Lng("51.5097080", "-0.1200450");
        list.add(my_lat_lng);
        my_lat_lng = new My_Lat_Lng("51.5090680", "-0.1421420");
        list.add(my_lat_lng);
        my_lat_lng = new My_Lat_Lng("51.4976080", "-0.1456320");
        list.add(my_lat_lng);
        my_lat_lng = new My_Lat_Lng("51.5046150", "-0.1473780");
        list.add(my_lat_lng);
        my_lat_lng = new My_Lat_Lng("51.5077540", "-0.1378760");
        list.add(my_lat_lng);
        my_lat_lng = new My_Lat_Lng("51.5074250", "-0.1323230");
        list.add(my_lat_lng);
        my_lat_lng = new My_Lat_Lng("51.5070030", "-0.125560");
        list.add(my_lat_lng);
        my_lat_lng = new My_Lat_Lng("51.5061590", "-0.140280");
        list.add(my_lat_lng);
        my_lat_lng = new My_Lat_Lng("51.5047420", "-0.1470490");
        list.add(my_lat_lng);
        my_lat_lng = new My_Lat_Lng("51.5126760", "-0.1189760");
        list.add(my_lat_lng);
        my_lat_lng = new My_Lat_Lng("51.5108480", "-0.1208480");

        list.add(my_lat_lng);
    }

    @Override
    public boolean onClusterClick(Cluster<MyItem> cluster) {
              Toast.makeToast(getApplicationContext(),"click",Toast.LENGTH_LONG).show();
        return true;
    }

}

On debugging above code onClusterClick event is not triggering. I am not able to understand the reason, please provide some help.

A: I think thats because you override the OnMarkerClickListener. try to use only setOnClusterClickListener and setOnClusterItemClickListener.


text:
Q: setting up transparent proxy on gateway computer I am looking to setup a transparent proxy (client) on a computer which will act as a gateway/router for (client) computers connecting to this gateway computer.  The client computers use a VPN client which is not going to be modified (nor will it have any proxy client).  The transparent proxy client will connect to a proxy (server) through which all traffic (including the VPN traffic) should be routed from.  Is this approach even possible with squid or ha proxy?
VPN client on computer -> transparent proxy on computer acting as router/gateway -> proxy on remote server -> VPN server  (and the traffic going back the same way).
Any thoughts or suggestions on this matter will be appreciated.


text:
Q: DataGridView.Sort first Row Bug? Hei, I write an String into the DataGridView in the first Column, then I want to Sort this but there is always a Problem because this Method doesn't affect the first row..
I don't know why this happens but every time I try it writing different things into the Array the same Problem appears again.
Here is my Code which throws this weird seeing Problem to me, maybe you guys can fix it?
public void namenEintrag(string[] name)
    {
        for (int i = 0; i < name.Length; i++)
        {
            dataGridView1.Rows[i].Cells[0].Value = name[i];
        }

        dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Ascending);
    }

And this is the File from which the Array has the Names (changed for this Post)
Laura, Becker
Jessica, Maur
Laura, Holzman
Dominik, Urner
Martina, Schweitzer
Kristin, Hoffmann
Kerstin, Herman
Paul, Eisenberg
Marko Baumgaertner
Paul, Bayer
Matthias, Nussbaum

And now what it looks like in the DataGridView
Laura, Becker
Dominik, Urner
Jessica, Maur
Kerstin, Herman
Kristin, Hoffmann
Laura, Holzman
Marko Baumgaertner
Martina, Schweitzer
Matthias, Nussbaum
Paul, Bayer
Paul, Eisenberg

Thanks for helping my stupid me.
Edit:  This is my Code to create the Table:
public void tabelle()
    {
        DataTable dt = new DataTable("Tabelle");

        dt.Columns.Add(new DataColumn("Namen:"));

        for (int i = 1; i <= spalten; i++)
        {
            dt.Columns.Add(new DataColumn(i.ToString()));
        }

        for (int i = 0; i < namen.Length; i++)
        {
            DataRow dr = dt.NewRow();

            for (int j = 1; j < spalten; j++)
            {
                dr[j] = "";
            }

            dt.Rows.Add(dr);
        }

        dataGridView1.DataSource = dt;
    }

And what I forgot to mention is, that when I click somewhere on the Table it sorts it in the right order, but not at the Start of the Program...


text:
Q: If $f$ is continuous on $[0,1]$, $a\in (0,1)$, the rational derivative of $f$ at $a: \lim_{\Bbb Q\ni r_n\to a}\frac{f(a+r_n)-f(a)}{r_n}=A$.
If $f$ is continuous on $[0,1]$, $a\in (0,1)$, the rational derivative of $f$ at $a: \lim\limits_{\Bbb Q\ni r_n\to0}\frac{f(a+r_n)-f(a)}{r_n}=A$.
Show $f$ is differentiable at $a$.

My attempt:
For any $x_n\searrow 0$, find $0<r_n<x_n<s_n$ such that $s_n\to 0$. But
$\dfrac{f(a+r_n)-f(a)}{r_n}, \dfrac{f(a+x_n)-f(a)}{x_n}, \dfrac{f(a+s_n)-f(a)}{s_n}$
is not compatible. How to use the continuity ?


text:
Q: Ubuntu failed to log in to UI I have a Ubuntu running on a virtual box. I cannot log into the UI with the valid username and password. It just shows black screen and returns to the login page again. Meanwhile the Guest Session is working fine.
What can I do to solve the problem ?

A: Based on your description, it sounds like you ran startx as root, which screwed with permissions on one or more files.
You'll need to get to a text console by pressing a key combination such as: Ctrl + Alt + F1 (any F1-F6 key will work). Next, log in as yourself.
Please check ownership on these two files:
    ls -l ~/.{ICE,X}authority

My guess is that at least one is owned by root, and not you. Change this:
    sudo chown user:user ~/.Xauthority (substitute user for your username).

Then reboot with:
    sudo shutdown -r now .

That should fix the issue for you. Here's more info on xauthority.

A: Try to move your cache directory
mv ~/.cache ~/.cache.old

If it's not working, it can be compiz, so move .compiz folder too.
mv ~/.compiz ~/.compiz.old


text:
Q: How to .pfx sign code using local machine in Azure Devops Pipelines? We have developed for the client Microsoft Office extension, and they do require to be code signed.
For development I have made a .pfx in VS -> Project properties -> Signing -> Create Test Certificate. Put empty password, dumped .pfx into source control and it was building for the whole company while developing.
For the release of the addon, things are different, we need to sign an extension with the clients .pfx and they want to add a step in the Azure DevOps build a pipeline to do it automatically. The thing is they can't use cloud solutions, so as I understand Azure Key Vault is out of the picture. They do have a local trusted machine that we could put their .pfx for signing.
I couldn't find a way how to do a signing in Azure Pipelines, that would not involve Azure Key Vault, or Azure Secure Files but I would expect there to be a mechanism for this as it seems like a quite common thing to do.
What is the preferred solution to .pfx sign code using local machine in Azure Devops Pipelines?

A: We ended up with following:
Added .pfx on local build machine.
Added hidden variable to Azure build pipeline pfxPassword

Then added following build steps tp Azure build pipeline:
trigger:
- main

pool:
  name: 'XXX Build Pool'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'
  #change to actual directory where signtool is.
  pathToSignTool: "\"C:\\Program Files (x86)\\Windows Kits\\10\\bin\\10.0.19041.0\\x64\\signtool.exe\""
  pathToPfx: "C:\\XXX\\Install\\XXX_Applications.pfx"
  pathToBuildDirectory: "\\XXXYYY\\bin\\Release\\"
  pathToMageTool: "\"C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v10.0A\\bin\\NETFX 4.8 Tools\\mage.exe\""
  pathToContinousDeployment: "C:\\ContinousDeployment\\YYY\\"

name: $(MajorVersion).$(MinorVersion).$(date:yy)$(DayOfYear)$(rev:.r)
steps:
- task: Assembly-Info-NetFramework@2
  inputs:
    Path: '$(Build.SourcesDirectory)'
    FileNames: |
      **\AssemblyInfo.cs
    InsertAttributes: true
    FileEncoding: 'auto'
    WriteBOM: false
    VersionNumber: '$(Build.BuildNumber)'
    FileVersionNumber: '$(Build.BuildNumber)'
    InformationalVersion: '$(Build.BuildNumber)'
    LogLevel: 'verbose'
    FailOnWarning: false
    DisableTelemetry: false

- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

- task: VSTest@2
  inputs:
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

- script:
      $(pathToMageTool) -s $(Build.Repository.LocalPath)$(pathToBuildDirectory)XXXYYY.vsto -cf $(pathToPfx) -pwd %MAPPEDPASS%
  env:
    MAPPEDPASS: $(pfxPassword)

- script:
      $(pathToMageTool) -s $(Build.Repository.LocalPath)$(pathToBuildDirectory)XXXYYY.dll.manifest -cf $(pathToPfx) -pwd %MAPPEDPASS%
  env:
    MAPPEDPASS: $(pfxPassword)

- script:
      $(pathToSignTool) sign /f $(pathToPfx) /p %MAPPEDPASS% $(Build.Repository.LocalPath)$(pathToBuildDirectory)XXXYYY.dll
  env:
    MAPPEDPASS: $(pfxPassword)

- task: CopyFiles@2
  inputs:
    SourceFolder: '$(Build.Repository.LocalPath)$(pathToBuildDirectory)'
    Contents: '**'
    TargetFolder: '$(pathToContinousDeployment)'
    OverWrite: true


text:
Q: React-select select menu list support html tag I'm wondering if it's possible to enable html-tag support in react-select.
I'm using promise callback function to inject list of suggestion, and have added <em>tag into the results..
But there's no way to tell react-select consider it as html tag.
How to do that ?

A: You'll want to use the optionRenderer property for this, and define a custom method that returns your element. This can contain html.
See example of this in react-select documentation.

A: You should handle this as a string, and use Dangerously Set innerHTML to display it in your component.


text:
Q: Rails/Devise - recoverable password not working in production (works in development) I am using Devise for user authentication in my Rails app, and I am working on setting up the recoverable password feature.  I am able to get this working correctly in my local development environment, but when I deploy to Heroku, it does not work.
In config/environments/development.rb, I have
config.action_mailer.default_url_options = {:host => 'localhost'}

which works perfectly.
In config/environments/production.rb, I have
config.action_mailer.default_url_options = {:host => 'fake-name-92356.herokuapp.com'}

but this generates an error page and the message in my log:
ActionView::Template::Error (Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true)

I have tried various solutions, such as using
default_url_options[:host] = 'fake-name-92356.herokuapp.com'

but to no avail.  What am I doing wrong here, that this works in development but not in production?

A: This will not work as Heroku does not provide an email service. These are facilitated by Add-ons.

The Heroku platform itself doesn't provide an email service - but
  instead provides add-ons that act as backing services - that can be
  attached to your app to provide the service. Consult the Heroku
  Add-ons marketplace for an appropriate email service that matches your
  requirements.

Taken from https://devcenter.heroku.com/articles/smtp


text:
Q: What's the best practice way to test whether parameter is empty? I have a macro that might work either in LaTeX or in plain TeX and I'd like to test whether one of its parameters, which presumably should be just text, is empty. Currently I do it this way:
\bgroup
\setbox0=\hbox{#1}
\ifdim\wd0=0pt
    it is empty
\else
    it is not empty
\fi
\egroup

And I wonder whether this is "proper" way or whether there is some other, more "best practices like", one.
Thx.

A: Here is an alternative expandable solution:

*

*it uses

*

*no e-TeX,

*no TeX conditionals,

*no \expandafter's,

*no \string's.

*it expands in three steps in all cases (with some usual \romannumeral0 wrapper one could get it to expand in two steps), which presumably makes it reasonably fast,

*it is entirely based on expansion of suitably delimited macros, but
the tested argument should not contain at top level \IfNoTokB token (as it appears in the parameter texts of the auxiliary macros).

As with Ulrich Diez's answer, the macro only examines whether the argument has tokens or no token, with #1=\empty the argument is declared non-empty, although its expansion would be empty.
Code (for Plain or LaTeX):
% auxiliary macros
\long\def\IfNoTokA #1\IfNoTokB \IfNoTokB {}
\long\def\IfNoTokB \IfNoTokC #1#2{#1}
\long\def\IfNoTokC           #1#2{#2}% this is \@secondoftwo in LaTeX

\long\def\IfNoTokens #1{\IfNoTokA\IfNoTokB #1\IfNoTokB\IfNoTokB\IfNoTokC }

%% The definition could be simplified if it was not asked to
%% distinguish #1 = space tokens from #1 = truly no token

Alternative where the only forbidden token in #1 will now be the active backslash (a quite unlikely token, but \IfNoTokB already was):
% active \ replaces \IfNoTokB
\begingroup
\catcode`\|=0
\catcode`\\=13
|long|gdef|IfNoTokA #1\\{}
|long|gdef\|IfNoTokC #1#2{#1}
|long|gdef|IfNoTokC  #1#2{#2}% = \@secondoftwo
|long|gdef|IfNoTokens #1{|IfNoTokA\#1\\|IfNoTokC }
|endgroup

Usage:
%% \IfNoTokens
%%    {<The macro argument which is to be checked>}%
%%    {<Tokens to be delivered in case of empty argument>}%
%%    {<Tokens to be delivered in case of non emty argument>}%
%%

Tests:
\tracingmacros1

empty? (yes): \IfNoTokens {}{Yes}{No}

empty? (no): \IfNoTokens { }{Yes}{No}

empty? (no): \IfNoTokens {{}}{Yes}{No}

empty? (no): \IfNoTokens {\if}{Yes}{No}

empty? (no): \IfNoTokens {#}{Yes}{No}

empty? (no): \IfNoTokens {\A}{Yes}{No}

\bye

Here is the log showing the expansions:
#1=empty:
\IfNoTokens #1->\IfNoTokA \IfNoTokB #1\IfNoTokB \IfNoTokB \IfNoTokC
#1<-

\IfNoTokA #1\IfNoTokB \IfNoTokB ->
#1<-

\IfNoTokB \IfNoTokC #1#2->#1
#1<-Yes
#2<-No

#1=space token:
\IfNoTokens #1->\IfNoTokA \IfNoTokB #1\IfNoTokB \IfNoTokB \IfNoTokC
#1<-

\IfNoTokA #1\IfNoTokB \IfNoTokB ->
#1<-\IfNoTokB

\IfNoTokC #1#2->#2
#1<-Yes
#2<-No

#1 = {}:
\IfNoTokens #1->\IfNoTokA \IfNoTokB #1\IfNoTokB \IfNoTokB \IfNoTokC
#1<-{}

\IfNoTokA #1\IfNoTokB \IfNoTokB ->
#1<-\IfNoTokB {}

\IfNoTokC #1#2->#2
#1<-Yes
#2<-No

#1=\if:
\IfNoTokens #1->\IfNoTokA \IfNoTokB #1\IfNoTokB \IfNoTokB \IfNoTokC
#1<-\if

\IfNoTokA #1\IfNoTokB \IfNoTokB ->
#1<-\IfNoTokB \if

\IfNoTokC #1#2->#2
#1<-Yes
#2<-No

#1=#:
\IfNoTokens #1->\IfNoTokA \IfNoTokB #1\IfNoTokB \IfNoTokB \IfNoTokC
#1<-##

\IfNoTokA #1\IfNoTokB \IfNoTokB ->
#1<-\IfNoTokB ##

\IfNoTokC #1#2->#2
#1<-Yes
#2<-No

#1=\A:
\IfNoTokens #1->\IfNoTokA \IfNoTokB #1\IfNoTokB \IfNoTokB \IfNoTokC
#1<-\A

\IfNoTokA #1\IfNoTokB \IfNoTokB ->
#1<-\IfNoTokB \A

\IfNoTokC #1#2->#2
#1<-Yes
#2<-No

A: EGreg had a nice answer on that, check
https://tex.stackexchange.com/a/127506/65222
Here's the relevant part:
A clever example of \if is for testing whether an argument is empty:
  \def\cs#1{%
  \if\relax\detokenize{#1}\relax
    The argument is empty%
  \else
    The argument #1 is non empty%
  \fi
  }

It uses \detokenize which is an e-TeX feature. If the argument is empty, the comparison would be between \relax and \relax, which are equal as far as \if is concerned; otherwise, \detokenize would return a string of characters (of category code 12) and \relax is never equal to a character for \if.

A: The method of the question
\bgroup
\setbox0=\hbox{#1}
\ifdim\wd0=0pt
    it is empty
\else
    it is not empty
\fi
\egroup

has several problems, if used for a general test:

*

*\setbox0\hbox{#1} leak color specials, when #1 contains top level
\color commands, because the color macros use \aftergroup to reset the color after the current group (\hbox).
This can be fixed for both plain TeX and LaTeX by using an additional group:
\setbox0=\hbox{\begingroup#1\endgroup}

In LaTeX \sbox0{#1} can be used.

*#1 can contain material, but the overall width is zero, examples:
\hbox{$\not$}% the width of the glyph `\not` is zero so that `\not=` forms the "not equals" symbols
\hbox{\rlap{Text}}

*#1 can contain so much material, that the width overflows. TeX does not throw an error, but the width can be zero accidentally again.

*The width of the \hbox depends on the font. For example, TikZ sets \nullfont in its environments, thus the width would always be zero.

*\bgroup and \egroup are the macro form for { and }. They have a serious side effect in math, that they form a math subformula, which behaves as math ordinary atom and influences the horizontal spacing. This can be fixed by using \begingroup and \endgroup.
Test based on macro definition
#1 can be put into a macro and then the macro can be tested for emptiness:
\def\param{#1}%
\ifx\param\empty
  The parameter is empty.%
\else
  The parameter is not empty.%
\fi

This is not perfect yet, because #1 might contain #, which is problematic in macro definitions, because they need to be doubled and numbered. This can be avoided by the use of a token register:
\toks0={#1}%
\edef\param{\the\toks0}% No full expansion, the token register is unpacked only
\ifx\param\empty
...

In LaTeX \@empty can be used, but it also provides plain TeX's \empty.
The side effects of setting \toks0 and defining \param can be removed by using a group:

\begingroup
  \toks0={#1}%
  \edef\param{\the\toks0}%
\expandafter\endgroup
\ifx\param\empty
...

This solution works in both plain TeX and LaTeX; e-TeX is not used.
Because of the assignment and definition the code is not expandable.
Expandable tests
If e-TeX is available, \detokenize allows a safe expandable method,
see also the answer of PhilipPirrip:

\if\relax\detokenize{#1}\relax
  The parameter is empty.%
\else
  The parameter is not empty.%
\fi

Because \detokenize converts is argument to simple characters with category code other (same as digits) and the space (in case of the space), it does not contain any command tokens and other problematic stuff, which could break
\if.
Without e-TeX the test should not use \if, but \ifx:
\ifx\relax#1\relax
...

However, a macro with meaning \relax might be present at the start of parameter #1. Therefore \relax should be replaced by something, which is unlikely to be used in #1, examples:
\def\TestEmptyFence{TestEmptyFence}

\ifx\TestEmptyFence#1\TestEmptyFence
...

Or Donald Arseneau (url.sty, ...) often uses a character with unusual catcode:
\begingroup
  \catcode`Q=3 %
  \gdef\MyEmptyTestMacro#1{%
    \ifxQ#1Q%
    ...
   }%
 \endgroup % restore catcode of Q

However, these expandable tests without e-TeX can be broken, e.g., if #1 contains unmatched \if commands. To reduce these problems, see the much more elaborate answer of Ulrich Diez.
I have marked the best solutions, non-expandable without e-TeX and expandable with e-TeX, by adding a quote environment to the code block.
Improvement of the if branches
\def\foobar#1#2#3{%
  \if...
    #2% if true
  \else
    #3% otherwise
  \fi

can be improved, because the code has the limitation, that #2 is followed by \else and #3 is followed by \fi. Thus both #2 and #3 cannot contain macros at the end, which expect following parameters, e.g.:
\foobar{...}{\textit}{\textbf}{Hello}

Instead of Hello, \textit gets \else and \textbf gets\fi` as parameter, breaking the code.
The standard way is finishing the \if construct first and selecting the argument via \@firstoftwo and \@secondoftwo:
\def\foobar#1{%
  \if...
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
}

The \expandafter closes the current if branch first. The macros \@firstoftwo and \@secondoftwo are defined in LaTeX:
\long\def\@firstoftwo#1#2{#1}
\long\def\@secondoftwo#1#2{#2}

Plain TeX does not have an equivalent, thus they need to be defined there.

A: Try the ifmtarg package. For instance (less any typos):
...
\usepackage{ifmtarg}
\makeatletter
  \newcommand{\isempty}[1]{%
    \@ifmtarg{#1}{YES}{NO}}
  \newcommand{\isnotempty}[1]{%
    \@ifnotmtarg{#1}{YES}}
\makeatother
...

then some results are:
\isempty{}       --> YES
\isempty{  }     --> YES
\isempty{E}      --> NO
\isempty{ E }    --> NO
\isnotempty{}    -->
\isnotempty{  }  -->
\isnotempty{E}   --> YES
\isnotempty{ E } --> YES


text:
Q: Papertrail and code access security I am currently looking into papertrail and find it very interesting.
However my web application will be deployed to web servers that I don't control.
The problem is that I use this solution to send logs to papertrail:
http://help.papertrailapp.com/kb/configuration/nlog-net-logging
And the way I see it I can't send logs on a website with medium trust level:
http://technet.microsoft.com/en-us/library/cc754779.aspx
Is this right?
Do you have any experience with using papertrail on medium trust sites?

A: Yes you are right:
Medium (web_mediumtrust.config) - Specifies a medium level of code access security, which means that, in addition to High Trust Level restrictions, the ASP.NET application cannot do any of the following things by default:

 Access files outside the application directory.
 Access the registry.
 **Make network or Web service calls.**

As far as I can see is the papertrail logger using the network to do the logging to an external site/service.


text:
Q: Kotlin how to get the value of storage/space available in my application and the device (like in spotify) I would like to get so information about how much space i have left on the phone but i couldn't find how to do it.
In spotify app we got a section where you can find information about the storage, you get 4 different information : Other app, download, cache and free/avaliable

I would like to do this in kotlin but i can't find anything on it, can someone helps me ?


text:
Q: Use Cauchy formula to solve $\int _0^{2\pi} \frac{dt}{a\cos t+ b\sin t +c} $ given $\sqrt{(a^2+b^2)}=1Use Cauchy formula to solve $$\int _0^{2\pi} \frac{dt}{a \cos t+ b \sin t +c} $$ Given $\sqrt{(a^2+b^2)}=1<c$.
I tried a variable substitution, but nothing elegant. Can anyone solve it using Cauchy formula?
Edit: there are simpler solutions, but the challenge is to solve it with complex analysis.

A: Hint:
With $z=e^{it}$,
$$\int\frac{dt}{a\cos t+b\sin t+c}=\oint\frac{2\,dz}{iz(a(z+z^{-1})-ib(z-z^{-1})+2c)}$$ and you have two nice poles.

A: This can be done without taking the help of integration limits too.

Evaluate $$\int \frac{dt}{a \cos t+ b \sin t +c} $$
,where $\sqrt{(a^2+b^2)}=1<c$.

I don't know what Cauchy's formula you are talking about. But here is a nice way to do it.
Since $\sin t=\frac{2\tan(\frac x2)}{1+\tan^2(\frac x2)},\cos t=\frac{1-\tan^2(\frac x2)}{1+\tan^2(\frac x2)}$, we can write it as(You may stop and try it yourself at this point)
\begin{align*}
&\Rightarrow\int \frac{\sec^2(\frac x2)dt}{a(1-\tan^2(\frac x2))+2b\tan(\frac x2)+c(1+\tan^2(\frac x2))}\\
&=\int\frac{2du}{a(1-u^2)+2bu+c(1+u^2)}\\
&=\frac2{c-a}\int\frac{du}{\left(u+\frac{b}{c-a}\right)^2+\frac{c+a}{c-a}-\frac{b^2}{(c-a)^2}}\\
&=\frac2{c-a}\int\frac{du}{\left(u+\frac{b}{c-a}\right)^2+\frac{c^2-(a^2+b^2)}{(c-a)^2}}\\
&=\frac2{c-a}\int\frac{du}{\left(u+\frac{b}{c-a}\right)^2+K^2}\\
&=\frac2{(c-a)K^2}\int\frac{du}{\left(\frac{u+\frac{b}{c-a}}{K}\right)^2+1}\\
\end{align*}
Can you make the substitution and finish it?

A: It may still be desirable to integrate as follows,
\begin{align}
& \int_0^{2\pi} \frac{dt}{a\cos t+ b\sin t +c}\\
=& \int_0^{2\pi} \frac{dt}{\sqrt{a^2+b^2}\cos (t-\theta) +c}
= \int_0^{\pi} \frac{2dt}{\sqrt{a^2+b^2}\cos t +c}\\
= & \int_0^{\pi} \frac{2dt}{2\sqrt{a^2+b^2}\cos^2\frac t2+c-\sqrt{a^2+b^2}}\\
 = & \int_0^{\pi} \frac{2\sec^2\frac t2 dt}{(c+ \sqrt{a^2+b^2} )+( c- \sqrt{a^2+b^2} )\tan^2\frac t2}\\
=& \frac{4}{\sqrt{c^2-a^2-
b^2} }\tan^{-1} \left( \sqrt{\frac{c-\sqrt{a^2+b^2}}{c+\sqrt{a^2+b^2}}  }\tan\frac t2 \right)_0^{\pi}\\
=& \frac{2\pi}{\sqrt{c^2-a^2-b^2} }
\end{align}


text:
Q: How to find duplicate character in a string and increase its occurence after that character in Python? I have written a program to find the duplicate character of a string, as below:
string = "India";

print("Duplicate characters in a given string: ");
#Counts each character present in the string
for i in range(0, len(string)):
    count = 1;
    for j in range(i+1, len(string)):
        if(string[i] == string[j] and string[i] != ' '):
            count = count + 1;
            #Set string[j] to 0 to avoid printing visited character
            string = string[:j] + '0' + string[j+1:];

    #A character is considered as duplicate if count is greater than 1
    if(count > 1 and string[i] != '0'):
        print(string[i]);

But thats not it I just want to increase the duplicate character by putting one extra occurence of that character.
For Example:
input : "India"(Here Duplicate Character is 'i')
output : "IIndiia"(Increase one occurrence of the duplicate character)

Can any one help me in solving this?

A: Collect all counts in one go, and do so case-insensitively:
from collections import Counter

string = "India"
c = Counter(string.lower())

"".join(x * (1 + (c[x.lower()] > 1)) for x in string)
'IIndiia'

A: One easy way is to use standard python string methods:
line = "some string"
result = ""
for letter in line:
    result = result + letter
    if line.upper().count(letter.upper()) > 1:
        result = result + letter


text:
Q: WinForms Setting A label Forecolour when the next TextBox Control is focused Ok,
It is common practice to have a Label followed by a TextBox. Imagine we have three Labels and three TextBoxes like this.
Label1.Text = "User Name" TextBox1.Name = "tbUserName";
Label2.Text = "Users Sex" TextBox2.Name = "tbUserSex";
Label3.Text = "User Age" TextBox3.Name = "tbUserAge";
When TextBox1 is Focused I want Label1.Forecolor to be White, else IndianRed
When TextBox2 is focused I want Label2.Forecolor to be White, else IndianRed... etc
I thought I could do it with the TagIndex - which are correctly set. I tried TextBox1.GetNextControl(TextBox1, false); but that didn't work. Here is the code I have at present which doesn't work.
private void SetLabelFocus()
    {
        SetAllLablesToDefault();

        foreach (Control ctrl in panel1.Controls)
        {
            if (ctrl is TextBox)
            {
                TextBox tb = ctrl as TextBox;
                if(tb.Focused)
                {
                    foreach (Control ctr in panel1.Controls)
                    {
                        if (ctr is Label)
                        {
                            Label L = ctrl as Label;
                            if (label1.TabIndex == (tb.TabIndex-1))
                            {
                                label1.ForeColor = Color.White;
                            }

                        }
                    }
                }

            }
        }
    }

    private void SetAllLablesToDefault()
    {
        foreach (Control ctrl in panel1.Controls)
        {
            if (ctrl is Label)
            {
                Label c = ctrl as Label;
                c.ForeColor = defaultTextColour;

            }
        }
    }

What currently happens when the SetLabelFocus() is called in Label2.Enter() all Labels turn white ... Now one thing that May cause problems is the Labels Forecolors are Application Bound as is the TextBoxes BackColor.
Anyway, How can I get the previous label to the focused TextBox to change its forecolor?
Cheers.

A: This works:
public Form1() {
  InitializeComponent();

  textBox1.Enter += LabelFocus;
  textBox2.Enter += LabelFocus;
  textBox3.Enter += LabelFocus;
}

void LabelFocus(object sender, EventArgs e) {
  TextBox tb = sender as TextBox;
  if (tb != null) {
    foreach (Label lbl in panel1.Controls.OfType<Label>()) {
      if (lbl.TabIndex == (tb.TabIndex - 1)) {
        lbl.ForeColor = Color.White;
      } else {
        lbl.ForeColor = Color.IndianRed;
      }
    }
  }
}

But it doesn't scale too well since it does rely on the TabIndex property always being correctly set.  Heed Hans' advice, a UserControl with a TextBox and a Label makes it quite simple.


text:
Q: Recycler view doesn't update item with livedata I have a fragment where use creates a budget for a specific category like this:

Here is how it works: user adds a new budget item in NewBudgetFragment. That item gets displayed in BudgetFragment in recyclerview. Budget item has amountSpent variable that should be updated each time user adds a new transaction(this happens in another fragment). But after creating the budget item, if the user spends money on that specific category, the amountSpent doesn't get updated in the recyclerview item. I have used both LiveData and DiffUtil in the BudgetAdapter but I can't figure out why it doesn't get updated.
Here is BudgetAdapter:
class BudgetAdapter() : ListAdapter<Budget, BudgetAdapter.BudgetViewHolder>(DiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BudgetViewHolder {
        val binding =
            BudgetItemLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return BudgetViewHolder(binding)
    }

    override fun onBindViewHolder(holder: BudgetViewHolder, position: Int) {
        val currentItem = getItem(position)
        holder.bind(currentItem, position)
    }

    class BudgetViewHolder(val binding: BudgetItemLayoutBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(budget: Budget, position: Int) {
            binding.apply {
                tvBudgetName.text = budget.name
                tvBudgetLimit.text = budget.limit.toString()
                tvAmountSpent.text = budget.amountSpent.toString()
                tvPercentageSpent.text = ((budget.amountSpent/budget.limit)*100).toInt().toString() + "%"
            }
        }
    }

    class DiffCallback : DiffUtil.ItemCallback<Budget>() {
        override fun areItemsTheSame(oldItem: Budget, newItem: Budget): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: Budget, newItem: Budget): Boolean {
            return oldItem == newItem
        }

    }
}

This is how new budget item gets created:
NewBudgetFragment:
...
viewModel.transactions.observe(viewLifecycleOwner) { it ->
                            transactionList = it.filter { it.category == listCategory[selectedCategoryIndex].name }
                            amountSpent = transactionList.sumOf { it.amount }
                        }
...

if (budgetName.isNotEmpty() && budgetLimit.isNotEmpty() && budgetCategory != null) {
                            viewModel.addBudget(
                                name = budgetName,
                                limit = budgetLimit.toDouble(),
                                amountSpent=amountSpent,
                                category = budgetCategory.name)

This is BudgetFragment.kt where the adapter is:
class BudgetFragment : Fragment(R.layout.fragment_budget),BudgetAdapter.OnItemClickListener {
    private lateinit var binding: FragmentBudgetBinding
    private val viewModel: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding = FragmentBudgetBinding.bind(view)
        val budgetAdapter = BudgetAdapter(this)

        val toolbar = binding.toolbar.root
        toolbar.title = "Budget"
        (requireActivity() as MainActivity).setSupportActionBar(toolbar)

        binding.apply {
            rvBudget.apply {
                adapter = budgetAdapter
                setHasFixedSize(true)
            }
        }
        viewModel.budgets.observe(viewLifecycleOwner){
            if(it.isNotEmpty()){
                binding.rvBudget.visibility = View.VISIBLE
                binding.tvNoBudget.visibility = View.INVISIBLE
            }else{
                binding.rvBudget.visibility = View.INVISIBLE
                binding.tvNoBudget.visibility = View.VISIBLE
            }
            budgetAdapter.submitList(it)

        }

        binding.btAddBudget.setOnClickListener {
            val action = BudgetFragmentDirections.actionBudgetFragmentToNewBudgetFragment()
            findNavController().navigate(action)
        }
    }

A: Asuming that your Budget Class is a data class, then the content comparison should work, so we should not have any problems with the object itself that is being used by the Adapter and the DiffUtil.
But:
I can't see the ViewModel Code - are you submitting the same List Instance to the Adapter with submitList? For example, are you mutating the items in a private List in the ViewModel and posting the same List on the same Live Data everytime?
If yes, then this is probably the reason why the items in the RecyclerView are not being refreshed. You need to create a new Instance of the List, with the content of the old List and then post this on the LiveData.

Example ViewModel, if you don't want to override the behavior of "submitList" where you clear the previous data and add the new one and then call by yourself notifiyDatasetChanged()
class MyBudgetViewModel : ViewModel() {
    // Important that its a data class, to actually have a content sensistive equals comparison

    // if you don't have an ID, you have to work with list indexes when finding
    // and updating this item
    data class Budget(val id: Int, val amount: Double)

    private val _budgets = MutableLiveData<List<Budget>>()
    val budgets: LiveData<List<Budget>>
        get() = _budgets

    init {
        _budgets.value = listOf(Budget(1, 20.0))
    }

    fun onBudgetChanged(id: Int, newBudget: Double) {
        // depends on your setup and how you fill the initial list, this maybe should never be null
        // by the time you call onBudgetChanged or something similar
        val oldList = _budgets.value ?: emptyList()

        // unused example variable - if you want to copy the list 1 by 1, ArrayList takes another list as Constructor
        val newListUnchanged = ArrayList(oldList)

        // map returns a new instance of the list.
        val newList = oldList.map { oldItem ->
            if (oldItem.id == id) {
                oldItem.copy(amount = newBudget)
            } else oldItem
        }
        _budgets.value = newList
    }
}


text:
Q: Application of Taylor approximation I need some help to understand an equality from a paper I'm currently working on.
In a simplified version it says
\begin{equation}
\ln\left(1-\frac{\int\left(1-\exp\left(- h(x) \gamma^2\right) \right)\alpha(x)dx}{\rho} \right) = -\gamma^2 \cdot \frac{\int h(x)\alpha(x)dx}{\rho} + o(\gamma^2)
\end{equation}
as $\gamma \searrow0.$
Although I see that this resembles the Maclaurin series for $\exp(x)$ and $\ln(1-x)$ a little bit, I have no idea what is going on here.
Any help is much appreciated!


text:
Q: load wcf hosted on console app with app.config? Hello im making wcf hosted in console app is possible to load this service with app.config?
ChannelFactory<IService> service = new ChannelFactory<IService>();
service.Endpoint.Behaviors.Add(new WebHttpBehavior());
IService channel = service.CreateChannel();
Console.Read();

This is start of my wcf into console app but how to load wcf config?
Im new in wcf so please be polite for me.
--edit---
So i get errorr
s zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.
            ServiceHost serviceHost = null;
            serviceHost = new ServiceHost(typeof(Contracs.Service));
            serviceHost.Open();

and my app.config is
            <?xml version="1.0" encoding="utf-8"?>
            <configuration>
              <system.serviceModel>
<behaviors>
  <endpointBehaviors>
    <behavior name="restfulBehavior">
      <webHttp />
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<services>
  <service name="Contracs.Service">
    <endpoint address="" behaviorConfiguration="restfulBehavior"
      binding="webHttpBinding" bindingConfiguration="" contract="Contracs.IService" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost/Service" />
      </baseAddresses>
    </host>
  </service>
</services>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

A: WCF will by default try to load from the app config.
Here is some more info:
http://msdn.microsoft.com/en-us/library/ms733932(v=vs.110).aspx


text:
Q: Como crear un fondo que no sea cuadrado? Quiero crear un fondo inclinado para que mi sitio sea mas atractivo en general.
Un ejemplo bastante claro es el fondo rojo que tiene este sitio ''https://ed.team/''.
Entre en su código css pero no encuentro en donde le pone forma a ese fondo.

A: Pues inspeccionando el código, ellos tienen lo siguiente:
.main-main.main-front #block-escueladigital-content::before {
    content: "";
    -webkit-clip-path: polygon(0 6%,100% 0,100% 94%,0 100%);
    clip-path: polygon(0 6%,100% 0,100% 94%,0 100%);
    height: 90%;
    width: 100%;
    background: linear-gradient(rgba(255,60,50,.95),rgba(255,60,50,.95)),url(../img/edcamp-bogota-2017.jpg) center 40%/cover no-repeat;
    position: absolute;
    top: 5%;
}

Ahí se está usando la propiedad css clip-path, que, como se describe, recorta el div de fondo:

La propiedad CSS clip-path previene que una porción de un elemento se
  muestre definiendo una región de recorte para mostrarse, es decir,
  solo una parte específica del elemento se mostrará.

Cada valor pasado a polygon dentro de clip-path, marcará la coordenada de un vértice del polígono, en este caso:
clip-path: polygon( esquinaSuperiorIzquierda (x, y),
                    esquinaSuperiorDerecha (x, y),
                    esquinaInferiorDerecha (x, y),
                    esquinaInferiorIzquierda (x, y) );


text:
Q: Excel column auto calculation Hello i want to calculate on excel without dragging the column.

I want to make without draging down to calculate if its possible!

A: Can't be done in Excel with formula alone, but you can return an empty string instead:
=IF(OR(A2="",B2="",C2=""),"",A2*C2+B2)

Then when there is no information it remains blank.  Then when the info is included the formula resolves.

OR
one can use a table and the formula would automatically be brought down every time a new row is started:

If one has the new dynamic array formula (Currently only available to Office 365 Insiders) it can be done with a formula like:
=INDEX(IFERROR(1/(1/(A2:A100*C2:C100+B2:B100)),""),0)

That will automatically spill down with just the one entry of the formula in the first cell.  The caveat to this is that no other entry can be put in the cells below.


text:
Q: Invalid Column Name Error When Accessing Navigation Properties From View When calling a view which displays properties for ASP.NET's ApplicationUser class which I have extended, I receive the below error when the code tries to render a line where I dive into a ApplicationUser class:
@model BaseballStatTracker.Models.ApplicationUser

@foreach (var stats in Model.GameStatistics)
{

            @Html.DisplayFor(modelItem => stat.Game.GameTime)

}

...causes:

Any property accessed from within the "Game" property causes the error, and Razor gives no indication that there is a problem when editing the view. Just accessing regular properties on the GameStatistics works without issue.
I have two contexts; the standard ApplicationDbContext and my GamesContext which houses both the Game and GameStatistics entities. I have overridden the OnModelCreating method on the GamesContext per the following:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Game>().HasKey(i => i.GameId);
            modelBuilder.Entity<Game>().HasOptional(i => i.HomeTeam).WithMany(i => i.HomeGames).HasForeignKey(i => i.HomeTeamId);
            modelBuilder.Entity<Game>().HasOptional(i => i.AwayTeam).WithMany(i => i.AwayGames).HasForeignKey(i => i.AwayTeamId);
            modelBuilder.Entity<Game>().HasOptional(i => i.Diamond).WithMany(i => i.Games).HasForeignKey(i => i.DiamondId);

            modelBuilder.Entity<GameStatistics>().HasKey(i => i.GameStatisticsId);
            modelBuilder.Entity<GameStatistics>().HasRequired(i => i.Game).WithMany(i => i.GameStatistics).HasForeignKey(i => i.GameId);
            modelBuilder.Entity<GameStatistics>().HasRequired(i => i.Player).WithMany(i => i.GameStatistics).HasForeignKey(i => i.PlayerId);
...
}

The ApplicationUser, Game and GameStatistics classes look like the following:
ApplicationUser:
public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        [Required]
        [Display(Name = "First Name")]
        [StringLength(155, ErrorMessage = "First Name can only be max 155 characters in length.")]
        public string FirstName { get; set; }

        [Display(Name = "Last Name")]
        [StringLength(155, ErrorMessage = "Last Name can only be max 155 characters in length.")]
        public string LastName { get; set; }

        [Display(Name = "Full Name")]
        public string FullName
        {
            get
            {
                return FirstName + " " + LastName;
            }
        }

        [Display(Name = "Player Number")]
        public int PlayerNumber { get; set; }

        [Display(Name = "Team")]
        public virtual Guid TeamId { get; set; }
        public virtual Team Team { get; set; }

        public virtual ICollection<GameStatistics> GameStatistics { get; set; }
    }

Game:
public class Game
    {
        [Key]
        public Guid GameId { get; set; }

        public string GameName { get
            {
                return AwayTeam.Name + " @ " + HomeTeam.Name + ", " + GameDate.Value.Date.ToLongDateString();
            } }

        [DataType(DataType.Date)]
        [Display(Name = "Game Date")]
        public DateTime? GameDate { get; set; }

        [DataType(DataType.Time)]
        [Display(Name = "Game Time")]
        public DateTime? GameTime { get; set; }

        [Display(Name = "Game Location")]
        public virtual Guid? DiamondId { get; set; }
        public virtual Diamond Diamond { get; set; }

        [Display(Name = "Home Team")]
        public virtual Guid? HomeTeamId { get; set; }
        public virtual Team HomeTeam { get; set; }

        [Display(Name = "Away Team")]
        public virtual Guid? AwayTeamId { get; set; }
        public virtual Team AwayTeam { get; set; }

        public virtual ICollection<GameStatistics> GameStatistics { get; set; }
    }

GameStatistics:
public class GameStatistics
    {
        [Key]
        public Guid GameStatisticsId { get; set; }

        public Guid GameId { get; set; }
        public virtual Game Game { get; set; }

        public string PlayerId { get; set; }
        public virtual ApplicationUser Player { get; set; }

        public int AtBats { get; set; }

        public int Hits { get; set; }

        public int Walks { get; set; }
    }

I have tried redoing the OnModelCreate method but I can't see what I have done wrong with the Game<-GameStatistics relationship. Any help would be much appreciated. Thank you in advance -

A: This issue was resolved after adding a couple of "Inverse Property" annotations to my Games model on the HomeTeam and AwayTeam properties. I also moved away from using the OnModelCreating override and switched to using the annotations completely. The relevant part of the change on the code was:
    [Display(Name = "Home Team")]
    public virtual Guid? HomeTeamId { get; set; }

    [ForeignKey("HomeTeamId")]
    [InverseProperty("HomeGames")] // Added this -
    public virtual Team HomeTeam { get; set; }

    [Display(Name = "Away Team")]
    public virtual Guid? AwayTeamId { get; set; }

    [ForeignKey("AwayTeamId")]
    [InverseProperty("AwayGames")] // Added this -
    public virtual Team AwayTeam { get; set; }

I am not sure why I was not able to achieve the same result setting the configuration in the data contexts - I am sure it was just a misunderstanding on my part but I would love to know why. Should EF not have known via the configuration what the inverse properties were?
I had tried changing the configuration setup but to no effect - I could not see anything wrong with it in the first place, however. Nevertheless, it is now working using the data annotations.


text:
Q: Please explain how works java method isChecked in RadioButton I am new in programming. I am sorry for question. I can not understand what does it mean. Piese of code
  public void onRadioButtonClicked(View view) {
    boolean checked = ((RadioButton)view).isChecked();

What does this sintaxis of construction mean, how is named it to find and read.((RadioButton)view)
Thank you.

A: View class inherits from RadioButton class.
This method - onRadioButtonClicked must for various reasons,accept an object of View kind.
but for use there parent's method - .isChecked() method You have to look at him in the 'glasses' of parent class.
its use polymorephism ability.
you can see more here


text:
Q: How to switch between views using the finger touch? I made an application to navigate between views. Each view contains Different text. The navigation is done by button. But I want to replace that by the finger touch (slide right or left). I mean, becomes a movement between the views using touch by finger

A: Use the UISwipeGestureRecognizer. See this tutorial.

A: You can add swip gesture on the view or you can also implement touch delegates like
 – touchesMoved:withEvent:
    – touchesEnded:withEvent:
    – touchesCancelled:withEvent:

to implement your requirement


text:
Q: Repeatedly loading AJAX content on responsive page I've got the following website http://rangeessentials.petersenuploads.co.uk/
The page uses a slightly modified responsive framework to load auxilliary content via AJAX when the screen width is above a certain size (480px). However, if you resize the screen to a narrow width and refresh and then make it wider, I get duplicate content loaded. I'm checking if content is loaded (look in init.js), but it seems to be ignored. I can't figure out what's going on. Any ideas?
Thanks

A: It is because $.ajax is asynch. Depending on how fast the server-side function is loadLeftAux() for example will fire mutiple times before the success function has added the content and the class. The if statement won't work until the first ajax call has returned it's response and added the content. When the content is appended you've already started more ajax calls that will finish and add more content.
What you have to do is that you have to determine if yo have an ajax-call running before you're sending a new request.


text:
Q: Noexec vs chmod -R -x for malware interogation? I am setting up a Linux box to examine malware samples.  I wanted to create a directory where I could safely unzip each sample and run very basic triage commands against the file to collect information about the sample (for example, hashing the sample).  In order to make sure that I do not inadvertently execute the sample, I wanted to ensure that the directory contents is non-executable.
Is it safe to merely chmod -R -x the directory and its contents before examining or should I mount a separate partition using noexec?  Functionally they accomplish the same thing, but is one preferable over the other (or both!) in the case of malware interrogation and why?


text:
Q: How to set different bits in VBA I need to use bit operations in VBA. For example I want to set first bit in 0 second bit in 1 and so on. How can I do it?
Thanks a lot!

A: You could use masks.
If you want to set* the n-th bit, you can perform an Or operation of your original value and a mask filled with 0 except for the n-th position.
That way, 1100 Or 0001 will set the first bit resulting in 1101. 1100 Or 0010 will set the second bit, resulting in 1110.
If you want to unset* the n-th position, you can do the opposite. Perform an And operation on your original value with a mask filled with 1 except the n-th position.
That way, 0011 And 1110 will unset the first bit resulting in 0010, 0011 And 1101 will unset the second bit, resulting in 0001.
* Set means to turn the bit into 1. Unset means to turn the bit into 0.


text:
Q: Why the terminal potential difference greater than the end while charging the battery by passing current $I$? Why the terminal potential difference greater than the emf while charging the battery by passing current $I$?
When the current is drawn from the circuit terminal potential is less than the emf?

A: A battery acts like an emf in series with a resistor.  When supplying current, the resistor causes a loss of output voltage.  When being charged, the voltage drop on the resistor requires that the termnal voltage be larger than the emf.  (The emf can depend on the level of charge.)


text:
Q: Corrupted python.exe file Whenever the command "where python" is executed a path is shown that leads me to the .exe file. Problem is that whenever I try to delete the file this window pops up:

I've tried installing python from that file but to no avail. A bunch of 0 kB files spring up but again I can't delete .exe.
How can I safely delete the file?


text:
Q: Why is this jquery ajax call not returning data from my php script? I'm new to jQuery, and have not been able to debug this ajax call in Firebug:
This is my ajax call:
var styndx = $('#studylist option:selected').val();
var studyname = $('#edit_field').val();

$.post("saveStudyName.php", {'type': 'update', 'studyname':studyname, 'styndx':styndx},
    function(resultmsg) {
    $('#edit_field').val('');
    $('#savebtn').attr('disabled',true);
    refresh_studynames();
});

And this is the function refresh_studynames:
function refresh_studynames()
{
  $.ajax({
     url: 'getStudyNames.php',
     data: "",
     dataType: 'json',
          error: function() {
            alert('Refresh of study names failed.');
          },
     success: function(data)
     {
        $data.each(data, function(val, sname) {
        $('#studylist').append( $('<option></option>').val(val).html(sname) )
      });
     }
  });
}

Finally, this is the php script getStudyNames.php ($dbname,$dbconnect, $hostname are all populated, and $dbconnect works; the backend database is Postgres, and pg_fetch_all is a Postgres function in PHP that returns result as an array):
$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);
    if (!$dbconnect)    {
        showerror(0,"Failed to connect to database",'saveStudyName',30,"username=".$dbuser.", dbname=".$dbname);
        exit;
    }

    $sql = "SELECT ST.studyindex,ST.studyabrv AS studyname
            FROM ibg_studies ST
            ORDER BY studyname";

    $fetchresult = pg_exec($dbconnect, $sql);
    if ($fetchresult) {
        $array = pg_fetch_all($fetchresult);
        echo json_encode($array);
    } else {
        $msg = "Failure! SQL="+$sql;
        echo $msg;
    }

Any help much appreciated....

A: The line
$('#studylist').append( $('<option></option>').val(val).html(sname) );

looks wrong.
I'm not too sure but you could try :
var $studylist = $('#studylist').empty();
$data.each(data, function(i, record) {
    $studylist.append( $('<option/>').html(record.sname) );
});


text:
Q: Login cookieauthentication Identity with existing database credentials I am making a login function with CookieAuthentication. I want to log in with my Username only. I want this method to recognize the username in the database and login with that username and start a cookieauthentication. When I run it with the code I have now it will not give me an error, it just stays at the login view. I am really sorry for my bad English, I hope someone recognizes what I want to succeed.
My view @model SpelerDTO
  <form asp-action="login" method="post">
                    <label asp-for="SpelerNaam"></label>
                    <input type="text" name="SpelerNaam" asp-for="@Model.SpelerNaam"
                     placeholder="Gebruikersnaam" />
                    <button>Sign in</button>
                </form>

Homecontroller login function
[HttpPost]
    public async Task<ActionResult> Login(SpelerDTO speler, string ReturnUrl)
    {

        if (speler.SpelerNaam == spelerContainer.getName(speler).ToString())
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, speler.SpelerNaam)
            };
            var claimsIdentity = new ClaimsIdentity(claims, "Login");
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
            return Redirect(ReturnUrl == null ? "/Home/BeginPagina" : ReturnUrl);
        }
        else
            return View();
    }

My container class method I use to get username
 public SpelerDTO getName(SpelerDTO speler)
    {
        SpelerDTO s = _context.GetByName(speler);
        return s;
    }

My DAL function to get spelerNaam from SPELER table
 public SpelerDTO GetByName(SpelerDTO speler)
    {
        try
        {
            string sql = "SELECT * FROM Speler WHERE spelerNaam = @spelernaam";
            List<KeyValuePair<string, string>> parameters = new List<KeyValuePair<string, string>>()
            {
               new KeyValuePair<string,string>("@spelernaam", speler.SpelerNaam)
            };

            DataSet results = ExecuteSql(sql, parameters);
            SpelerDTO c = Parser.Parser.DataSetToSpeler(results, 0);
            return c;
        }
        catch (Exception e)
        {
            throw e;
        }
    }


text:
Q: Endless copying more than size of folder I'm trying to copy files from one HDD to another.
For some reason copying ''Backups.backupdb'' folder won't end.
The original size of the folder is 145gb,but when it hits 145,it is just adding more GBs.
151/151

152/152

Btw,when copying stars,after 10-15 mins mac asked my for password to copy ''Backups.backupd''.Maybe this is the problem?It doesn't ask anything for other folders.
UPD
I have ''stop'' symbol on my folder,maybe this is the problem?How do i remove it,so my mac has access to it without pass.?

A: Backups.backupdb contains the TimeMachine backup which uses hard links to preserve space (basically this ensures that files/folders only get backed up if their content changes). Wenn copying Backups.backupdb via Finder, these hard links are not rebuild, so copying it will create a folder containing a full backup for each time TimeMachine run. This is most likely not what you want (and it will need a huge amount of disk space).
To clone a TimeMachine disk, use a tool like SuperDuper! or Carbon Copy Cloner.


text:
Q: Graphics distorted in QVGA Android phone i made an application in android 2.1
when i run my application in QVGA simulator its Button,TabBars and EditText Field are Distroted from both ends
but they seems to be perfect in HVGA.
whats the problem. and how can i resolve it.
Thnk!

s
You can see in the image that the edit Text Field is Distorted from both ends
same is the case with buttons and same is the case with TabBars.. you can see both images
in comapre see the 3rd image .this is from HVGA.. this does not have any distortion in textfields or buttons or tab bars..

A: apply <uses-sdk android:minSdkVersion="7" />  in AndroidManifest.xml
refer http://developer.android.com/guide/topics/manifest/uses-sdk-element.html for risks


text:
Q: Is it possible the preselect a cell in Primefaces DataTable component? is it possible to preselect a cell in the Primefaces DataTable component? How do I do that? Tried it already with a Primefaces Cell object with a Getter, but this is not called by my data table :-(.
I need this because I have to restore the selection of the cell done a request before, if validation tells me, that a required field in the form was not filled.
This is my xhtml code snippet:
    <p:dataTable id="select-start-pos" var="item"
        selectionMode="singlecell"
        value="#{frankingController.startposItems}"
        selection="#{frankingController.selectedCell}"
        styleClass="startPosGrid">
      <p:column id="startposcol1">
        <h:outputText value=""/>
      </p:column>
      <p:column id="startposcol2" rendered="#{frankingController.startposColumns > 1}">
        <h:outputText value=""/>
      </p:column>
    </p:dataTable>

Thank you for your help!
Mike

A: No and 3.x doesn't have cell selection feature

A: You can use Sheet control instead of Datatable, it has row selection feature.
http://www.primefaces.org/showcase-labs/ui/sheet.jsf


text:
Q: How can the Apache httpd root path be rewritten to a subdirectory? While I have seen similar questions elsewhere, some of those questions ask about redirecting the exact root path or else the provided answers don't always work properly.
What I require is to rewrite all paths starting from the root to a subdirectory of the document root.
One of the possible solutions is to simply change the document root. However, depending on how you have configured your vhosts or written other rules, this may not always be the best option.

A: This may be done in different ways. Here is one simple approach using mod_rewrite.
Update:
This allows for cases where additional directories under root need to be excluded, such as phpMyAdmin. In such cases and some others, using a Last [L] rule is problematic. Add your required exclusions in place of phpMyAdmin, separated by pipes: '|'.
RewriteEngine on
RewriteRule ^/(?!phpMyAdmin|mydir).* /mydir$0 [NE]

Previous Solution:
RewriteEngine on
RewriteRule /mydir.* $0 [L]
RewriteRule /.* /mydir$0 [NE]

Note that while I have seen some try to use a single rule rewrite, I believe the middle line is necessary to prevent recursion.


text:
Q: How do I refresh a DataGrid at timed intervals in F#? I have a background thread updating an array. At timed intervals I call myDataGrid.Items.Refresh().  However nothing changes on the screen.  But when I for instance click on the column heading of the data grid on the screen the information is actualized immediately.
I like to see the changes on the screen at timed intervals, for instance every 2 seconds. What am I missing?
Here is the code fragment in F# that shows the situation:

...

let win = new Window()
let grid = DataGrid()
grid.HeadersVisibility <- DataGridHeadersVisibility.All
grid.ItemsSource <- myArray
win.Content <- new ScrollViewer(Content=grid)
win.Show()
...
// Background thread A
//  updating myArray

...

// Background thread B
let updateDataGrid =
  grid.Items.Refresh()
  Thread.Sleep(5000)
  updateDataGrid

...

[<STAThread>]
do
  let app = new Application()
  app.Run() |> ignore

A: Have you tried a DispatcherTimer? (code below is in C#)
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer1_Tick;

Prevent the usage of Thread.Sleep.

A: Can't use formatting in comments so here my response.
The timer actually works, if I write:

[<STAThread>]
do
  let app = new Application()
  let timer = new DispatcherTimer()
  timer.Interval <- TimeSpan.FromSeconds(2.)
  timer.Tick.Add (fun _ -> grid.Items.Refresh())
  timer.Start()
  app.Run() |> ignore

However now the problem is almost reversed, it automatically updates until I click on any of the column headings to sort.  After that there are no more refreshes.
However if I perform this trick:

  timer.Tick.Add (fun _ ->
                    grid.ItemsSource <- null
                    grid.ItemsSource <- myArray
                    grid.Items.Refresh())

it refreshes fine, but loses the sort ordering.
How to maintain the sort order?  I can easily sort the arrray but I do like the user to sort by himself as well.

A: Since you're already using WPF, is it possible to turn that array into an ObservableCollection?  Last I heard, the DataGrids support it.  If the objects in the collection are already DependencyObjects, then their DependancyProperties should automatically update in the grid.  If not, you can reinsert them into the collection manually.


text:
Q: C++ syntax of 2D vector Can someone explain below c++ syntax with example ?
vector <vector <int> > s(n,vector <int> ());

especially this part inside the constructor:
vector <int> ()

A: This specific constructor of vector takes two arguments:

*

*The number of elements.

*The value to assign to each element.

For example, this creates a vector containing 3 times the value 5.
std::vector<int> vec(3, 5);

vector<int>() is a default-constructed instance of vector<int>. So you are creating a vector containing n vectors, each empty.

A: #include <vector>
using namespace std;

int main()
{
    int N = 10;
    std::vector< std::vector<int> vector2DA(N, std::vector< int>(N));
    return 0;

}

This code create vector2D 10x10, first parameter constructor is size basic vector(vector2DA(size, objectWhichIsContain)), which contain other vector, which have size 10 (std::vector< int>(size)). We have vector2D 10x10.

A: First of all, vector of vectors is not exactly a "2D vector". The "rows" of vector<vector<>> are completely independent both in terms of memory layout and semantically. There are better options, e.g. Boost.Multi_array.
Then we have vector <int> (). Depending on context this could mean both temorary object initialization or a function declaration. The example in question actually does not provide enough context:
vector <vector <int> > s(n,vector <int> ());

If n happens to be a type name, then this line is a function declaration. Of course n is probably an int, but it would be better to explicitly state that you want a default-constructed vector<int> as a second argument:
vector <vector <int> > s(n,vector <int> {});

Here vector <int> {} unambiguously means "a default-constructed temporary object of type vector<int>", and you pass it to the vector<vector<int>> constructor as a value to initialize your rows with.
This brings us to another observation: std::vector value-initializes its elements by default, which means that the same result can be achieved like that:
vector <vector <int> > s(n);

Finally, the presence of vector<int>() in the original statement kind of hints that it might have been intended to set up the "width" of the 2D vector:
vector <vector <int> > s(n,vector <int> (m));

but m got lost somewhere along the lines :)