text:
Q: getting ALAssets from photos library iOS I am trying to get the time, date and location from a movie i took on my iPhone/iPad  This is the code i used
//i get the video picked and then save it to app but i think i am getting the movie's asset data before i save it.
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{   NSError *error;
 else if (picker.sourceType ==UIImagePickerControllerSourceTypePhotoLibrary) {

    NSURL * movieURL = [info valueForKey:UIImagePickerControllerMediaURL] ;
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:movieURL
                   resultBlock:^(ALAsset*asset) {
                       NSDate *myDate = [asset valueForProperty:ALAssetPropertyDate];
                       NSLog(@"Date: %@", myDate);

                   } failureBlock:^(NSError *error) {
                       NSLog(@"Error");
                   }];
    NSData * movieData = [NSData dataWithContentsOfURL:movieURL];
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [documentPaths objectAtIndex:0];
    NSString *slash = [documentsDirectory stringByAppendingPathComponent:@"/"];
    NSString *documentsDirectory2 = [slash stringByAppendingPathComponent:self.user.text];
    NSString *documentsDirectory21 = [documentsDirectory2 stringByAppendingPathComponent:@"/Movie"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory21])
        [[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory21 withIntermediateDirectories:NO attributes:nil error:&error];
    NSString *fullPath = [documentsDirectory21 stringByAppendingPathComponent:[[self imageNameTextField]text]];
    fullPath = [fullPath stringByAppendingFormat:@".mp4"];
    [ movieData writeToFile:fullPath atomically:YES];
}

however myDate is logged as null
what am i doing wrong
I just tried this code also (added 10/11)
CGImageSourceRef source = CGImageSourceCreateWithURL( (CFURLRef)movieURL, NULL);
    NSDictionary* metadata = (NSDictionary *)CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(source,0,NULL));
    NSLog(@"image data %@", metadata);

but still metadata is null;
I read that videos don't have the same metadata as images.  if this is true then how do I access the video metadata since I can see data tied to the video in photos.
any help would be greatly appreciated.
I have tried everything I could find on the internet to help me do this but nothing seems to work.
When I log my movieURL this is what I get
2016-10-13 09:58:51.045271 my little world app[2641:1388034]     movieURL;file:///private/var/mobile/Containers/Data/Application/22A178E5-74C4-    48EF-B487-5E01321508AD/tmp/trim.04F0AC8A-2960-464D-8670-7E79662EAB9B.MOV

So since it is in a temporary file can I not get the metadata.
Does the Metadata exits in the movies NSData and can I get it from that?
I am pulling my hair out.

A: So I figured this out here is the code
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
if (picker.sourceType ==UIImagePickerControllerSourceTypePhotoLibrary) {
 NSURL * movieURL = [info valueForKey:UIImagePickerControllerMediaURL] ;
 [self getMediaName:nil url:[info objectForKey:UIImagePickerControllerReferenceURL]];
}
}
- (void)getMediaName:(UIImage*)originalImage url:(NSURL*)url {
    @try {
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *asset) {
            if (asset == nil) return;
            ALAssetRepresentation *assetRep = [asset defaultRepresentation];
            NSString *fileName = [assetRep filename];
 NSDate *myDate = [asset valueForProperty:ALAssetPropertyDate];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"MM-dd-yyyy"];
            NSLog(@"%@",[dateFormatter stringFromDate:myDate]);
ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *error) {

        };

        ALAssetsLibrary *library = [ALAssetsLibrary new];
        [library assetForURL:url resultBlock:resultblock failureBlock:failureblock];
    }
    @catch (NSException *exception) {

    }
}

you can use any valueForProperty


text:
Q: How can I move a label left, paint it black, or remove it (Chart.JS)? I've got a horizontal bar chart displaying like so:

As the second data value on the bars (1.0, 0.8, etc.) are partially obscured, I would like to do one of the following things, in order of preference:

*

*Move them to the left, so that they are completely visible

*Change their font from white to back, so that they are completely visible

*Remove them altogether, so that they are completely invisible

The code that is causing them to be written in the first (second?) place is this:
    Chart.pluginService.register({
        afterDraw: function (chartInstance) {
            if (chartInstance.id !== 1) return; // affect this one only
            var ctx = chartInstance.chart.ctx;
            // render the value of the chart above the bar
            ctx.font = Chart.helpers.fontString(14, 'bold',
Chart.defaults.global.defaultFontFamily);
            ctx.textAlign = 'center';
            ctx.textBaseline = 'bottom';

            chartInstance.data.datasets.forEach(function (dataset) {
                for (var i = 0; i < dataset.data.length; i++) {
                    var model = dataset._meta[Object.keys(dataset._me
[0]].data[i]._model;
                    ctx.fillText(dataset.data[i]
(Number.isInteger(dataset.data[i]) ? ".0" : "") + "%", ((model.x
model.base) / 2), model.y + (model.height / 3));
                }
            });
        }
    });

...but I don't see just where there I can manipulate those values as desired.
For context and full disclosure, here is all the code for the chart:
        Chart.pluginService.register({
            afterDraw: function (chartInstance) {
                if (chartInstance.id !== 1) return; // affect this one only
                var ctx = chartInstance.chart.ctx;
                // render the value of the chart above the bar
                ctx.font = Chart.helpers.fontString(14, 'bold'
Chart.defaults.global.defaultFontFamily);
                ctx.textAlign = 'center';
                ctx.textBaseline = 'bottom';

                chartInstance.data.datasets.forEach(function (dataset) {
                    for (var i = 0; i < dataset.data.length; i++) {
                        var model = dataset._meta[Object.keys(dataset._met
[0]].data[i]._model;
                        ctx.fillText(dataset.data[i]
(Number.isInteger(dataset.data[i]) ? ".0" : "") + "%", ((model.x
model.base) / 2), model.y + (model.height / 3));
                    }
                });
            }
        });

        var ctxBarChart
$("#priceComplianceBarChart").get(0).getContext("2d");
        var priceComplianceData = {
            labels: [
                "Bix Produce", "Capitol City", "Charlies Portland", "Cost
Fruit and Produce",
                "Get Fresh Sales",
                "Loffredo East", "Loffredo West", "Paragon", "Piazz
Produce"
            ],
            datasets: [
            {
                label: "Price Compliant",
                backgroundColor: "rgba(34,139,34,0.5)",
                hoverBackgroundColor: "rgba(34,139,34,1)",
                data: [99.0, 99.2, 99.4, 98.9, 99.1, 99.5, 99.6, 99.2, 99.7]
            },
            {
                label: "Non-Compliant",
                backgroundColor: "rgba(255, 0, 0, 0.5)",
                hoverBackgroundColor: "rgba(255, 0, 0, 1)",
                data: [1.0, 0.8, 0.6, 1.1, 0.9, 0.5, 0.4, 0.8, 0.3]
            }
            ]
        }

        var priceComplianceOptions = {
            scales: {
                xAxes: [
                {
                    stacked: true
                }
                ],
                yAxes: [
                {
                    stacked: true
                }
                ]
            },
            tooltips: {
                enabled: false
            }
        };

        var priceBarChart = new Chart(ctxBarChart,
        {
            type: 'horizontalBar',
            data: priceComplianceData,
            options: priceComplianceOptions
        });

I am using Chart.js version 2.2.2

A: 1st solution: Move to the left
In your plugin, set the context textAlign property to right if it is the second dataset:
chartInstance.data.datasets.forEach(function(dataset) {
    for (var i = 0; i < dataset.data.length; i++) {
        var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;

        // If it is the second dataset (red color) ..
        if (dataset._meta[0].controller.index== 1) {
            // .. align to the right
            ctx.textAlign ="right";
            // .. and write it at the right bound of the chart
            ctx.fillText(parseFloat(dataset.data[i]).toFixed(2) + "%", (model.x - 2), (model.y + model.height / 3));

           // This looks like it has been moved a bit to the left
        }

        // Else ..
        else {
            // .. write as usual
            ctx.fillText(parseFloat(dataset.data[i]).toFixed(2) + "%", ((model.base + model.x) / 2), (model.y + model.height / 3));
        }
    }
});

Check the result on this jsFiddle.

2nd solution: Put the text in black
In your plugin, set the context fillStyle property to the color you want (#000 for instance):
afterDraw: function(chartInstance) {
    var ctx = chartInstance.chart.ctx;
    // render the value of the chart above the bar
    ctx.font = Chart.helpers.fontString(14, 'bold',
        Chart.defaults.global.defaultFontFamily);
    ctx.textAlign = 'center';
    ctx.textBaseline = 'bottom';

    // Here:
    ctx.fillStyle = "#000";

    chartInstance.data.datasets.forEach(function(dataset) {
        // ...
    });
});

Check the result on this jsFiddle.

3rd solution: Remove it, pure and simple
Add a condition in your plugin to check which dataset you are currently working on:
chartInstance.data.datasets.forEach(function(dataset) {
    for (var i = 0; i < dataset.data.length; i++) {

        // If it is the second dataset (red color), we break out of the loop
        if (dataset._meta[0].controller.index == 1) break;

        var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;

        ctx.fillText(parseFloat(dataset.data[i]).toFixed(2) + "%", ((model.base + model.x) / 2), (model.y + model.height / 3));
    }
});

Check the result on this jsFiddle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Binding style property outside itemsource? I've a combobox like this:
   <ComboBox x:Name="CountryMenuComboBox"
        ItemsSource="{Binding Countries}">

        <ComboBox.ItemContainerStyle>
            <Style>
                <Setter Property="IsEnabled" Value="{Binding IsRemoving}" />
            </Style>
        </ComboBox.ItemContainerStyle>

what I need to do is enable or disable the items inside the combobox using the property IsRemoving, but this property isn't located inside the itemsource Countries, so I need to access outside the itemsource. How can I do this for a style?

A: Is IsRemoving a property of the parent viewmodel that owns the Countries property? If so, try <Setter Property="IsEnabled" Value="{Binding DataContext.IsRemoving, RelativeSource={RelativeSource AncestorType=ComboBox}}" />


text:
Q: iOS app crashes when device is tilted to landscape orientation Working on an app for iOS 8 using Swift. It is only supposed to be supported in portrait orientation mode.
The app runs without issue if it starts in portrait mode and does not get tilted such that the device is in landscape mode. It also runs without issue if the device STARTS in landscape mode and either stays in this mode or is tilted to portrait mode.
When the phone moves from portrait to landscape mode the app crashes every time. The error is of type EXC_BAD_ACCESS and gives an address. The UI highlights the first line of the AppDelegate class.
info.plist has been changed to express the fact that only portrait mode is supported. In addition, I tried overriding the method shouldAutorotate() in the root view controller. However, I think this is a memory issue.
What information do I need to find a solution for this issue? Can anyone point me towards resources for dealing with memory issues in iOS 8?

A: There's nothing special about memory in iOS 8 over any other OS.  Xcode also comes with a ton of useful tools to help you out.  I suggest you use the allocations instrument in Instruments, use zombies, use guardmalloc, attach to the process with lldb, trigger the crash.
Look through the allocations to see where it was allocated and track its lifecycle.
Use lldb to figure out values and inspect the call stack.

A: This happens for us, Apple's spinning animation starts to occur, then lags, then the whole phone restarts. Seems Apple has memory management issues with their built in spinning animation during orientation change. You can disable their spinning animation, which fixed this issue for us, by placing the following method in your main ViewController
-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {//disables Apple's spinning animation when orientation changes which was causing app crashes due to memory issues

    [UIView setAnimationsEnabled:NO];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((0.01f) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//failsafe
        [UIView setAnimationsEnabled:YES];
    });

    [coordinator notifyWhenInteractionChangesUsingBlock:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        [UIView setAnimationsEnabled:YES];
    }];

    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

}


text:
Q: Troubles using Amazon S3 with Europe based buckets in django-storages Question is  regarding Amazon S3 buckets in EU.
I have a Django project hosted locally and decided to store media files in Amazon S3 buckets. For doing this I use Django-storages app with the following settings in settings.py:
AWS_ACCESS_KEY_ID = "xxxxxxx"
AWS_SECRET_ACCESS_KEY = "xxxxxxxxxx"
AWS_STORAGE_BUCKET_NAME = 'hadcasetest'

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

MEDIA_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/'

THUMBNAIL_DEFAULT_STORAGE = DEFAULT_FILE_STORAGE
THUMBNAIL_BASEDIR = "thumbnails"
THUMBNAIL_MEDIA_URL = MEDIA_URL

Well, it works when I use bucket from USA region and doesn't when I use buckets from Europe. I tried all possible locations in Europe – they all do not work.
Type of error I get: S3ResponseError: 400 Bad Request
Question is what should I change to get access via Django -storages to Europe based buckets to use them in Django app?
P.S. I can use AWS CLI to write in each buckets even in European ones but, Django-storages can not.
Should I obtain specific EU credentials perhaps?

A: I added these parameters in settings.py and it helped:
AWS_S3_HOST = "s3.eu-central-1.amazonaws.com"
S3_USE_SIGV4 = True
AWS_S3_REGION_NAME = "eu-central-1"


text:
Q: Event/notification of member modification in C++ class A{
  int i;
};

class B{
  // sense i is changed by A
};

If the value of i is changed by A, then B should get notified. Any suggestion how to implement this?

A: Are you looking for the Observer Design Pattern?

A: The Observer pattern is the standard way to implement this. There are lots of pointers in the Wikipedia article, and on the Web (just google "observer pattern c++").

A: Look at the observer or publisher-subscriber pattern.

A: The Observer Pattern is the main solution to your problem.
You could also use SIGNALS and SLOTS. There are two main libraries which implement them:
1) Boost
2) QT (although it's a large library for using just the SIGNAL and SLOT api)

A: You need a different implementation for your classes:
class B {

public:
  Alert(int value_changed) {
     // implement whatever you want
     // for example printf("Value has changed to %i class A!!!\n", value_changed);
       }

}

class A {
/* constructor implementation */
 A(int i) {
           internal_value = i;
           B_class = new B() //notice that B will automatically be created by A!
          }

~A() { delete B_class; }

public:

 ChangeValue(int new_value) {
           internal_value = new_value;
           B_class.Alert(internal_value);
           }

private:

int internal_value;
B *B_class;

}

int main() {

A my_A(10); // you implicitly create a pair of classes A - B;

my_A.ChangeValue(20); // you should notice that A calls B automatically

return 0;
}

A: C++ does not provide this feature out of the box, you have to program it on your own. I guess you should read into the design pattern Observer pattern to achieve this.


text:
Q: Show the data with mysql_query php I have 2 tables on database, table 'songs', and 'genre'.

*

*Table 'songs' has 3 columns: id_song (PK), song_title, lyric, id_genre

*Table 'genre' has 2 columns: id_genre (PK), genre

in table 'genre', i have:

|| id_genre | genre ||
||.......1.......|..pop...||
||.......2.......|..rock..||
||.......3.......|..jazz...||
||.......4.......|.classic.||

Relation between 2 tables:

song.id_genre FK to genre.id_genre

I have a variable like this:
$search_genre = 'pop';

and I want to search song by $search_genre.
$query = mysql_query("SELECT song.id_song, song.song_title, genre.genre FROM song WHERE genre='$search_genre' INNER JOIN genre ON song.id_genre=genre.id_genre ORDER BY id_song");

But, it doesn't work. What should I do? Thanks for your help.
Question 2: How to show the result in php?

A: First!

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Second!
If you've already started with mysql_* at the very least escape your parameters! Otherwise you're leaving a gaping SQL injection security vulnerability waiting for the next l33t wannabe hacker to hack into your site!
$search_genere = mysql_real_escape_string($search_genere);
$query = mysql_query("SELECT song.id_song, song.song_title, genre.genre FROM song INNER JOIN genre ON song.id_genre=genre.id_genre WHERE genre.genre='".$search_genre."' ORDER BY id_song");

But please please do read the link in the box above.
The reason you've had this error is because of a syntax error.

A:     $query = mysql_query("SELECT song.id_song, song.song_title, genre.genre FROM song INNER JOIN genre ON song.id_genre=genre.id_genre WHERE genre.genre='".$search_genre."' ORDER BY id_song");

    use this.it will work.

if(mysql_num_rows($query) > 0){
   while($row = mysql_fetch_array($query)){
     echo $row['id_song'];//song id
     echo $row['song_title'];//song title
     echo $row['genre'];//song genre
   }
}

A: Your JOIN query is wrong you use INNER JOIN after FROM
Try this:
 $query = mysql_query("SELECT song.id_song, song.song_title, genre.genre FROM song INNER JOIN genre ON song.id_genre=genre.id_genre WHERE genre='%$search_genre%'  ORDER BY id_song");

If you querying a search you can use wildcards such as %
e.g.
query = mysql_query("SELECT song.id_song, song.song_title, genre.genre FROM song INNER JOIN genre ON song.id_genre=genre.id_genre WHERE genre='%$search_genre%'  ORDER BY id_song");


text:
Q: How to add active marker on menu in Drupal Bootstrap 7.x-2.2 I'm trying to add a triangle on the "active" element on the menu. I've added this css:
.navbar .active::after {
content: "";
position: absolute;
bottom: -16px;
border-width: 0px 15px 15px;
border-style: solid;
border-color: #ffffff transparent;
display: block;
width: 0;
}

But for some reason I'm getting 2 triangles slightly ontop of eachother on active elements as per attached screenshot. I don't know how else to get it right....please help?

A: andregriffin over on Drupal.org answered my question "
It's probably because there are two nested elements, both with the .active class, such as the li and the a tag. You need to be more specific on which one you are applying CSS to. you should probably use
    .navbar > .active:after or .navbar a.active:after or .navbar li.active:after."
So I ended up with the following CSS and it works perfect!
    /* Active caret */
    .navbar a.active:after {
    content: "";
    margin-left: auto;
    margin-right: auto;
    padding-top: 2px;
    border-width: 0px 10px 10px;
    border-style: solid;
    border-color: #ffffff transparent;
    display: block;
    width: 0;
    }


text:
Q: Does ctags support zip or jar file? Does the ctags support zip or jar file?
I want to use ctags in vim to program java.
So I hope ctags search java file in jar.
I do not want to unzip jar, that will hard to manage file.

A: In the tags database which ctags builds, it has to refer to the indexed file, relative to the tags database. Since there is no general notation to refer to contents inside a ZIP file (what may be casually described as /path/to/archive.zip:dirs/inside/file.txt), as this is a separate filesystem within the normal filesystem, this is not possible. You have to unzip the JAR files.


text:
Q: How do you run rots in a Rails integration test? How do you run rots in a Rails integration test? I can run rots from the command line, should I run the command from Ruby or is there a method I can call to get it to run?

A: I think it's best to start rots in before(:all) block (for rspec) or def setup method (for test unit) and stop it in after(:all)/def teardown block/method respectively.
To start rots you probably should use something like:
rots = IO.popen("rots")

and then to stop it:
rots.close

but be aware this code is not tested.


text:
Q: get mouse location on screen I have the code below for getting mouse location on screen:
    NSPoint loc = [NSEvent mouseLocation];
    NSLog(@"x:%.2f y:%.2f",loc.x, loc.y);

When I clicked on my app window i set an action, where I can track this action.
But, to my surprise it gives more or less same value wherever i clicked on the window. I move window at different location on screen though.
The result are as under:
2012-07-31 12:50:08.740 MyApp[2860:d03] x:432.19 y:450.07 (when window is on top section of screen)
2012-07-31 12:50:19.042 MyApp[2860:d03] x:435.14 y:453.16 (when window is on bottom section of screen)


text:
Q: Check new hover target after hover out (Javascript/JQuery)? What is the most neatest way to check whether a user is hovering over an object after hovering out of a different object. I.e. If user mouses out of object A onto object B, how would you suggest I go about monitoring this? I don't really like the idea of continously monitoring the mouses position when it moves, though it may be the only option...

A: check out this fiddle
http://jsfiddle.net/aVz7Q/4/
A simple hover event in jQuery can accomplish this, with the help of some variable work, you can store what the previous element and current element are.

A: Events bubble up. Add en event listener for the parent element of A & B. In that listener you can record on mouseout the original target of the event as the latest object that was mousedout (using something like $(this).data("latestMouseout",latestTarget), Best way to get the Original Target). On mousein, you can check your conditions and see if latest mouseout target and mousein target meet the conditions you need.
I know this is a little vague, but so is your question. If this helps great. If not, feel free to ask clarifying questions.


text:
Q: Spring Security SAML integration with ADFS - metadata.xml I've got question, becouse i'm creating Spring Security filter for application written in EJB3. I added spring security filter chain for this app. I've got configuration from spring-security-saml2-sample.war. It's working ok, but i've got problem with metadata.xml file, which is generated every page is loaded. Question is - how to export this xml file do ADFS 2.0 server, that IDP ( ADFS 2.0 server) will see. This metadata file is required in this section:

Click Metadata information, select item with your server name in the
  Service providers list
Store content of the Metadata field to a document metadata.xml and
  upload it to the AD FS server
In AD FS 2.0 Management Console select "Add Relying Party Trust"
Select "Import data about the relying party from a file" and select
  file created earlier, select Next

I know that in example app we've got interface to generate this metadata for our service provider, but problem is with this, that in my application i didn't have this IDP selector - i'm using connection to default IDP. So, i didn't have possibility to export xml.
Is there any idea how to resolve this?
Thanks a lot ;)
Matthew
EDIT:
My metadataGeneratorFilter configuration:
    <!-- Filter automatically generates default SP metadata -->
<bean id="metadataGeneratorFilter" class="org.springframework.security.saml.metadata.MetadataGeneratorFilter">
    <constructor-arg>
        <bean class="org.springframework.security.saml.metadata.MetadataGenerator"/>
    </constructor-arg>
</bean>

A: In case you are using auto-generated metadata or pre-configured metadata from a file in Spring SAML, you can download it from scheme://host:port/context/saml/metadata


text:
Q: NSURLConnection, NSOperationQueue behaviour between IOS 5 and IOS6 - UI Freeze !! - I'm trying to implement a queuing mechanism for url downloads on IOS. For this I use
 NSURLConnection for the network access part, and I enqueue them into a static instance of  NSOperationQueue class (shared between UIControllers). When the download starts, I update a UI progress bar, using the callbacks from NSURLConnectionDownloadDelegate.
There is one UIControllerview, one UIView. The Queue is created at ViewLoad, and assigned to pointer defined as a UIControllerView property
//UIControllerView Code
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.myDownloadQueue = [NSOperationQueue sharedOperationQueue];
    }

and the implementation follows the suggestion here
Download is started via a button, creating a new NSURLConnection, and dispatching it to the NSOperationQueue via SetDelegateQueue:
- (IBAction)startDownload:(UIButton *)sender {
    NSString *url = @"<myURL blablabl>";

    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:30];
    NSURLConnection *urlConn = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:NO];
    [urlConn setDelegateQueue:self.myDownloadQueue];
    [urlConn start];
    NSLog(@"adding a new task for url %@",[[urlConn currentRequest] URL ]);
    //Sets the UI
    self.awProgress1.progress=0;
}

the UIViewController implements the NSURLConnectionDataDelegate protocol, for the methods
        @interface awViewController : UIViewController <NSURLConnectionDownloadDelegate>
        @end
    ...snip....
        @implementation
        - (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes
{snip.. updates the progress bar here using performSelectorOnMainThread:@selector()..
}
        - (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes{...snip...}
        - (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL{....snip...}

        @end

On IOS6, the code works fine, The UI bar gets updated as the UIViewController receives the [connection didWriteData:] calls.
On IOS5 however, when the url is fully downloaded, the UI freezes....
Step by step debugging shows that in both case, the code reaches the IOS run time when downloading is over, ie it's not stuck somewhere in my code.
The UI is fine during download, I can press buttons etc...
If I set the NSURLCOnnection to run in the main thread, ie by removing
[urlConn setDelegateQueue:self.myDownloadQueue];
[urlConn start];

Then the code works again on IOS5. But that 's not what I want, I want the download to be executed in a background thread.
What am I missing ? is there some housekeeping to be done Queue wise on IOS5 ? Really the problem seems to occur when the NSURLConnection completes, as the UI is fine during download.
thanks for your help !
-A
PS: Sample code is available, just didn't want to clutter the screen too much...


text:
Q: An almost periodic point must be a unifomly recurrent point? $(X,G)$ is a topological semi-group action, $G$ is a  topological (abelian) semigroup, and $X$ is a Hausdorff space.
$x\in X$ is called almost periodic of $(X,G)$, if for any neibourhood $U$ of $x$, $\{g\in G: gx\in U\}$ is syndetic.
$x\in X$ is called uniformly recurrent of $(X,G)$, if for any neibourhood $U$ of $x$, there exist a compact subset $K$ of $G$, such that for any $g\in G$, we can find a $k\in K$ satisfying $gkx\in U$.
$S$ is called a syndetic subset of a topologcal semigroup $G$, if we can find a compact subset of $G$, such that for any $g\in G$, there exist an $s\in S$, and a $k\in K$ satisfying $g=sk$.
My question is: if $x$ is almost periodic, then $x$ must be unifomly recurrent?


text:
Q: Load category specific to device I have an iPhone app that I'd like to make universal, most views can be kept the same, but there are some minor modifications that need to be made for the iPad.
Is it possible to load a category depending on what device the user is using?
Or is there a better way of doing this? A generic way (rather than specifically checking each time I create a new instance of a class, and choosing between 2 classes)

A: You could do this with some method swizzling at runtime. As a simple example, if you want to have a device-dependent drawRect: method in your UIView subclass, you could write two methods and decide which to use when the class is initialized:
#import <objc/runtime.h>

+ (void)initialize
{
    Class c = self;
    SEL originalSelector = @selector(drawRect:);
    SEL newSelector = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
                      ? @selector(drawRect_iPad:)
                      : @selector(drawRect_iPhone:);
    Method origMethod = class_getInstanceMethod(c, originalSelector);
    Method newMethod = class_getInstanceMethod(c, newSelector);
    if (class_addMethod(c, originalSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
        class_replaceMethod(c, newSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    } else {
        method_exchangeImplementations(origMethod, newMethod);
    }
}

- (void)drawRect_iPhone:(CGRect)rect
{
    [[UIColor greenColor] set];
    UIRectFill(self.bounds);
}

- (void)drawRect_iPad:(CGRect)rect
{
    [[UIColor redColor] set];
    UIRectFill(self.bounds);
}

- (void)drawRect:(CGRect)rect
{
    //won't be used
}

This should result in a red view on the iPad and a green view on the iPhone.

A: Look into the UI_USER_INTERFACE_IDIOM() macro, this will allow you to branch your code based on the device type.
You may have to create a helper class or abstract superclass which returns the appropriate instance if you want to keep each file iPhone or iPad only.


text:
Q: More practice on Diophantine problems Continuing with my studies in the Diophantine equations chapter, trying to get used to solving a given equation has no integral solutions.

*

*Problem 1) How can I show that $x^2+y^2=9z+3$ has no integral solutions?

*Problem 2) How can I show that $x^2+2y^2=8z+5$ has no integral solutions?
A clear proof would really help me follow and understand the steps required to do these kind of proofs, as I am still not entirely familiar in writing a proper proof  to these problems quite yet.

A: Hint: the first, $x$ and $y$ must be divisible by $3$ (you can verify that the case $x=1$ mod $3$ or $2$ mod $3$ is impossible, same with $y=1$ mod $3$ or $2$ mod $3$), this implies that $x^2+y^2$ is divisible by $9$, but $9z+3$ is not divisible by $9$.

A: For Problem 1, consider the residue of $x^2+y^2$ in mod 9. The RHS should say that the residue is 3. However, since the residue of square numbers in mod 9 is either 0, 1, 4, 7, the residue of sum of square numbers in mod 9 is either 0, 1, 2, 4, 6, 7, 8, which is a contradiction, thus no integer solution to the equation.
Problem 2 can be treated as equally as Problem 1.

A: For the problem 1 note the fact that all squares are either of the form $3k$ or $3k+1$ ( this can be easily seen by classifying integers modulo 3 classes($ 3k, 3k+1, 3k+2$ and squaring them)
Using this idea observe that R.H.S is of form$9z+3=3(3z+1)= 3k$ for some integer k.This would imply both the terms (squares ) on the L.H.S is a multiple of $3$ so this would imply the integers being squares themselves are multiple of $3$ this would imply L.H.S is divisible by $9$ but R.H.S leaves remainder $1$ when divided by 9 which is absurd hence by contradiction this equation has no solutions.
For problem 2 after such a detailed explanation of problem 1  I will only give a hint: analyze things modulo 4 the integers themselves can take forms$4k, 4k+1,4k+2,4k+3$ but their squares take only the forms    $4k,4k+1$
You will get a contradiction by similar line of reasoning.
This is my first answer on the forum so please feel free to give any suggestions.

A: The quadratic residues mod $9$ are $\{1,4,0,7,7,0,4,1\}$.  This means that $x^2+y^2$ is always going to be congruent to possible combinations of these numbers: $$\{0,1,2,4,5,7,8\}$$
Now if we put this into the context of the question, $x^2+y^2-3$ will always be congruent to $\{6,7,8,1,2,4,5\}$.  It will never be congruent to $0 \ \text{mod} \ 9$, so there are no integral solutions.
For the second question, modulo $8$, a square number will always be congruent to $\{0,1,4\}$.  Thus $x^2+2y^2$ will always be congruent to $\{0,1,2,3,4\}$.  $x^2+2y^2-5$ will be congruent to $\{3,4,5,6,7\}$ mod $8$.  We recognize that this will never be congruent to zero mod $8$, so it cannot be divisible.

A: Here is a proof for the second question, since other answers address the first one fairly well. I will write it out without using any higher-level machinery (e.g., modular arithmetic) although that mode of thought certainly undergirds the approach below. I will also omit some details, for which I include a parenthetical, and rhetorical, "why?" throughout:

Prove there are no $x, y, z \in \mathbb{Z}$ for which $x^2+2y^2=8z+5$.

Let us suppose a solution exists, and wend our way towards a contradiction, which will show that our supposition was incorrect, and no such solution can exist. So, supposing there were a solution, we observe that the right side of the equation is odd (why?) so the left side of the equation must be odd, too. In particular, $x$ must be odd (why?) so we can write $x = 2n+1$ for some $n \in \mathbb{Z}$.
We now have: $(2n+1)^2 + 2y^2 = 8z + 5$, i.e., $4n^2 + 4n + 1 + 2y^2 = 8z + 5$. Subtracting $1$ from both sides and factoring out a $4$ yields the equation: $4n(n+1) + 2y^2 = 4(2z+1)$. From here, we divide both sides by $2$ to derive the equation
$$2n(n+1) + y^2 = 2(2z+1)$$
and note that the right hand side is even, which means $y$ must be even (why?) so we can write $y = 2m$ for some $m \in \mathbb{Z}$. This yields $2n(n+1) + 4m^2 = 2(2z+1)$, which we re-divide by $2$:
$$n(n+1) + 2m^2 = 2z+1$$
which, at last, is our contradiction: The two expressions directly above cannot be equal, for the left hand side is an even number (why?) and the right hand side is an odd number (why?). Since our assumption of a solution existing led to a contradiction, we were wrong in our supposition, and, thus, we conclude that no solution exists. QED.

As a final note: This proof involved dividing by $2$ twice, i.e., dividing by $4$. So, if you are comfortable using modular arithmetic in proofs, then it may make sense - as is suggested elsewhere - to (re)consider this entire problem from a "mod $4$" perspective.


text:
Q: Testing the robustness of a flash drive: dd'ing the drive till it fails? I've been given a cheap, brandless 2GB flash drive. As I have a bigger flash drive, I have decided to use it for testing flash technology robustness.
I plan to write 1's all over the drive, check for correctness, write 0's, check and so on. I'll log the results, and seek for failures later.
I am looking for the most resource-saving technique for doing that. My current strategy includes using linux dd command for writing and reading, and comparing the result to a file of ones and zeros. Another approach would be writing ones and zeros to the drive, and calculating the md5 of its contents. This is a simple trade-off between extensive IO reads and high CPU usage; I guess I'll simply measure the running time of each method and decide.
Are there any better, more elegant ways of doing this?

A: You could also use the linux 'badblocks' command to do the tests for you. When used with the -w option it will do a write-mode test for you using various patterns, writing a block and reading it back to check it succeeded.
You can run it directly on the device without having it mounted too, to test every block of the physical device.
   -w     Use  write-mode  test. With this option, badblocks scans for bad
          blocks by writing some patterns  (0xaa,  0x55,  0xff,  0x00)  on
          every block of the device, reading every block and comparing the
          contents.  This option may not be combined with the  -n  option,
          as they are mutually exclusive.

A: Pick a random 32 bit number. Write that in every block. Read that from every block. New 32 bit number. Run the drive again. Hash algorithms like MD5 are CPU intensive. Since you know exactly the pattern and are just testing that the drive doesn't screw up the bits, simple direct comparison is the best approach. Don't use DD... write direct from a language like C or Perl (if there were ever apples standing next to oranges...)
No need to have a comparison file either... the pattern fits in memory. In fact, the whole test probably fits in the CPU cache if done neatly, but the flash drive will obviously be a bottleneck anyway. Find a number that isn't right, you know you've got your bad block.


text:
Q: How to define when show or not a loading screen So, I have this app that uses this code to show and hide a loading screen upon all the screen content while it loads some ajax request.
app.config( function( $stateProvider, $urlRouterProvider, $httpProvider )
{
    $httpProvider.interceptors.push(function( $rootScope )
    {
        return {
            request: function(config) {
                $rootScope.$broadcast('loading:show')
                return config
            },
            response: function(response) {
                $rootScope.$broadcast('loading:hide')
                return response
            }
        }
    });
})
.run(function( $state, $rootScope, $ionicLoading, $storage )
{
    $rootScope.$on('loading:show', function()
    {
        $ionicLoading.show({template: 'Loading'});
    });

    $rootScope.$on('loading:hide', function()
    {
        $ionicLoading.hide();
    });
});

When I want to loading something I use:
$http.post( "http://myexample.com.br/json-data", {param1:"1"} ).then(function(result){});

The problem is that I want, in some situations, to load something in background and not show a loading screen.

A: The way you have set it up using the interceptors, those loading events will be raised on every $http call. I'd recommend removing the event listeners from the $rootScope and only apply them on individual controller scopes that you do want the loading screen to show.

A: I put $ionicLoading.hide(); just after the $http.post. Not the best, but solve.
$http.post( "http://myexample.com.br/json-data", {param1:"1"}).then(function(result)
{

});

$ionicLoading.hide();


text:
Q: Zend Framework documentation, exceptions I'm having trouble finding my way around Zend Framework documentation.
I'm currently using the "query" member function of the Zend_Db_Adapter_Pdo_Mysql class, and want to find out what exceptions it might throw. I've looked at http://framework.zend.com/apidoc/core/Zend_Db/Adapter/Zend_Db_Adapter_Abstract.html#query , however there seems to be no info about it there. Oh I'm using version Zend Framework 1.10.

A: The Zend_Exception documentation says:

The documentation for each Zend
  Framework component and class will
  contain specific information on which
  methods throw exceptions, the
  circumstances that cause an exception
  to be thrown, and the various
  exception types that may be thrown.

You are looking at the wrong API documentation. You need to look at the docs for Zend_Db_Adapter_Pdo_Abstract query method, which Zend_Db_Adapter_Pdo_Mysql extends - and an exception is mentioned there:
throws: Zend_Db_Adapter_Exception To re-throw PDOException.


text:
Q: Is the sum of this two Normal a Normal? Let us take $X_1$ standard Gaussian and a R.V. $Z$ with $P(Z=1)=0.5$ and $P(Z=-1)=0.5$. Set $X_2 = ZX_1$. So we can verify that $X_2 ∼ N(0,1)$. Now, the question is: is $Y = X_1 +X_2$ normal?
Here is my attempt:
$P(Y \leq y)= P(X_1+ZX_1 \leq y)= P(Z(2X_1) \leq
 y|Z=1)P(Z=1)+P(Z(2X_1) \leq y|Z=-1)P(Z=-1)=P(2X_1 \leq y)0.5+P(-2X_1
\leq y)0.5$
I am stuck here. Can I claim that because the normal is symmetric,
 then $P(-2X_1 \leq y) = P(-2X_1 \leq y)=P(2X_1 \leq y)$, so that $P(Y \leq y)=P(2X_1 \leq y)$, which is the cdf of a normal?

A: Since $1+Z$ is either $0$ or $2$, each with probability $\frac12$, so $X(1+Z)$ has probability $\frac12$ of being $0$. Therefore, it isn't Normal.
For what it's worth, many sources would say $Z$ has a Rademacher distribution, not a Bernoulli distribution.

A: The question  has been  edited. I am assuming  here that $Z$ take s values $0$ and $1$ with probability $1/2$ each.
The first statement itself is false without independence. So assume that $Z$ and $X_1$ are independent so that $X_2$ is normal.
The characteristic function of $Y$ is easily calculated by conditioning on $Z$. We get $Ee^{-t^{2}(1+Z)^{2}/2}$ which is $\frac 1 2 e^{-t^{2}/2}+\frac 1 2 e^{-2t^{2}}$. This is not a normal characteristic function so the answer is NO, $Y$ is not normally distributed.
EDIT. In the modified version also it is not true that the sum is normal. The mistake in your attempt is in thinking that $X_1+ZX_1$ is either $2X_1$ or $-2X_1$. It is  either $0$ or $2X_1$.

A: Kabo Murphy and J.G. 's answers are both correct. For completeness I will also prove that $Y = X_1 + X_2$ is not normal using my initial attempt.
$P(Y \leq y)= P(X_1+ZX_1 \leq y)= P(X_1(1+Z) \leq
 y|Z=1)P(Z=1)+P(X_1(1+Z) \leq y|Z=-1)P(Z=-1)=P(2X_1 \leq y)0.5+P(
 y \geq 0)0.5=0.5\Phi(y/2)+0.5I_{y\geq0}(y)$ which is clearly not a normal Cdf


text:
Q: How to override lazy import() resolution in Webpack I have an odd request. I'm trying to implement a plugin for webpack that can dynamically resolve the CDN location of a chunk. I'm aware of the publicPath options and their behavior, however, in my case this is not possible. Because with our CDN, we don't get a URL back that includes the relative path of the file, instead it returns a magic ID we use to create a URL, regardless of the file location/name.
For example:
/static/js/chunk.1.js -> https://cdn.example/asset/1234
main.js -> https://cdn.example/asset/1122

I can create a chunk name/location map, and I'm ok with the additional bundle size overhead of including this map in my final output for runtime resolution. What I'm having difficulty finding is ideally overriding the default webpack import() behavior.
Like ideally, the same syntax:
const chunkResult = await import('/lazy-loaded');

Would essentially translate to something like:
const chunkResult = await load('https://cdn.example/assets/1234');

Any suggestions on how this might be accomplished or a "you can't do that, submit a feature request" would be great.

A: You can control the public path of webpack dynamically by __webpack_public_path__.
For example many solutions are out there which provide fallbacks from cdn to your service by changing the __webpack_public_path__ dynamiclly when the script tag for the cdn returns an error.
Write a simple:
__webpack_public_path__ = window.cdnEndpoint
and webpack will compile it to the publicPath.


text:
Q: 301 Redirect in .htaccess gives certificate warning on original URL first My site has a certificate but it's not a wildcard certificate. So it's for example.com, not for *.example.com.
Not a problem I thought, I'll just redirect any visitor to the proper URL through mod_rewrite:
 RewriteEngine On
 RewriteBase /

 # Following two lines to strip machine name
 RewriteCond %{HTTP_HOST} !^example.com [NC]
 RewriteRule ^(.*)$ https://example.com%{REQUEST_URI} [L,R=301]

 # Following two lines make sure the https version is always served
 RewriteCond %{HTTPS} off
 RewriteRule (.*) https://example.com%{REQUEST_URI}  [L,R=301]

Now, the redirect actually works. When someone types in https://www.example.com/page, he will eventually be redirected to https://example.com/page.
But...
The browser first displays a warning that https://www.example.com is insecure. Only when I add an exception, will it be redirected to https://example.com/page which does not give a certificate error...
What am I doing wrong here?

A: Nothing. SSL negotiation occurs at the transport (TCP) level, not HTTP (even when using SNI) but the point is that the certificate is not valid for the requested domain. When the connection is initiated to www. the browser will request the certificate and compare the url with the CN in the cert and since it isn't there, it'll raise the alert.
To resolve this issue you will need a certificate that includes both ServerName and ServerAlias names. You could maybe try some DNS provider that offers DNS HTTP redirection, but getting a certificate is quite easy this days.


text:
Q: Anonymous access to icCube exported permanent link I am using icCube version 5.2 Community Edition.
I created a schema + report as admin, and it all works ok. Then I am trying to provide access to this report from a web application deployed into Tomcat 7. But ideally, I would like this to be done without icCube requesting the user for authentication.
I tried so far to save the report under anonymous, but that did not work as icCube still requires authentication. icCube server is deployed on a secured server so I could do without its integrated authentication process as well if that makes things easier.
Thanks for the help.

A: The ability to add customer authentication and or authorization is part of the Enterprise features.


text:
Q: Surprising Inrush Current on a MOSFET Switch? I have the following P-ch MOSFET switch used to supply a 12V, 6-20A load:

When I enabled the switch, I measured the following voltage drops across +12VDC & +12VDC_GR. The yellow line is +12VDC (my source voltage) and the blue line is +12V_GR (my 0.5ohm load). As you can see, the +12VC has a sudden drop followed by a ripple.

I assumed this was caused by inrush current on my load, but when I removed the load and tried it again, I got an almost identical result:

I'm hoping someone in the community can give me some insight into what is going on/fix the issue:

*

*Is this actually inrush current causing the issue or something else to do with the MOSFET?

*Would adding a soft start between P-Channel gate and drain do anything to mitigate this? I'd like to understand the actual issues going on here.

Thanks!

A: It looks like your power source is on the verge of instability. Could start oscillating anytime, and you will have a bigger problem.
Keep in mind that the SQM40031EL has about 30 nF input capacitance, which can provide a good impulse kick (~30 ns) when the control transistor U28 turns on. As result the input has the same drop of ~1 V in both cases, with load, and without it. The rest is the reaction of PSU to the step load.
As a matter of fact, this kind of step load test is a must for checking stability margins of power supplies.


text:
Q: Global interior estimate complex Monge-Ampere equation Suppose u is a smooth strictly plurisubharmonic function satisfying $(i\partial \bar{\partial} u)^n =f dV_{Euc}$ on the unit ball centered at the origin, where $f>0$ is a smooth function. Let $C$ be a constant such that $\Vert f \Vert_{C^{1,a}}\leq C$.
Is some norm of $u$ over the half-ball controlled by $C$?
Note that there is no specified boundary condition


text:
Q: Request for the value rather than key/id in Laravel controller I'm fetching data from database to the invoice view page using json_encode($items); function (particularly 'price' field by it's id) from controller, it works well. But when I insert that particular field to database only the id/key is stored rather than the actual value. Any guess how to request for the value rather than key/id in controller.
Here is the controller function:
public function getPurchaseItems($id)
   {
       $items = DB::table("purchase")->where("pur_id",$id)->pluck("price","pur_id");
       return json_encode($items);

   }

Here is html code:

      Price
      <select name="price" readonly class="form-control prc" id="price">
      </select>

Here is the script:
            jQuery('select[name="state"]').on('change',function(){

               var stateID = jQuery(this).val();
               if(stateID)
               {
                  jQuery.ajax({
                     url : 'invoice/getPurchaseItems/' +stateID,
                     type : "GET",
                     dataType : "json",
                     success:function(data)
                     {

                        console.log(data);
                        jQuery('select[name="price"]').empty();
                        jQuery.each(data, function(key,value){
                           $('select[name="price"]').append('<option value="'+ key +'">'+ value +'</option>');
                        });

                     }
                  });
               }
               else
               {

                $('select[name="price"]').empty();

               }
            });

Here is the requested data and storing to database:
public function insertInv(Request $request){
       $price = $request->input('price');

        $invoiceId= DB::table('invoice')->insertGetId($invo);
        $invo_det=array('invoice_no'=>$invoiceId,'price'=>$price);

         DB::table('invoice_details')->insert($invo_det);

A: Modify Your insertInv function
Remove input() from   $price = $request->input('price');
OR dd($request->all());  and check all the values in controller are in correct format And Post the Result here


text:
Q: Unexpected results in Powershell while creating a string for base64 basic auth tokenization I'm trying to call a jira REST service using PowerShell following the instructions here, where the basic auth string username:password of fred:fred results in a hash of ZnJlZDpmcmVk.
I have not been able to recreate that value using a powershell ps1 script and am looking for help.
My function is spitting out "fred fred:", which obviously results in a different hash- ZnJlZCBmcmVkOg==
However, my operations seem to work when ran directly in the shell.
My function:
function hash-64($user,$password){
    $u=[string]$user
    $p=[string]$password
    $all="${u}:${p}"
    write-host $all
    $base64AuthInfo = [convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($all))
    return $base64AuthInfo
}

Exection:
PS H:\> hash-64('fred','fred')
fred fred:
ZnJlZCBmcmVkOg==

From Shell:
PS H:\> $u='fred'
PS H:\> $p='fred'
PS H:\> $shell_all="${u}:${p}"
PS H:\> write-host $shell_all
fred:fred
PS H:\> $base64AuthInfo = [convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($shell_all))
>>
PS H:\> $base64AuthInfo
ZnJlZDpmcmVk

Notice in the shell the string is correct AND the hash matches the expected result. As you may notice in the function i'm grasping with casting as a solution (not) and I've tried various tricks from other posts all to no avail.

A: I think you are passing an array to hash-64. Try calling it with hash-64 -user 'fred' -password 'fred' or hash-64 'fred' 'fred'


text:
Q: How to set the value of the input name "PickupDate" using VBA? I have tried the following code but obtain an Object error:
Dim g As IHTMLElement

Set g = appIE.getElementsByName("PickupDate")
    g.Value = b

    <input name="PickupDate" class="short picker__input" id="P666421526" aria-expanded="false" aria-haspopup="true" aria-readonly="false" aria-owns="P666421526_root" type="text" readonly="" placeholder="Date">

A: Give this a shot:
For a particular value:
Set post = html.getElementsByName("PickupDate")
MsgBox post(0).ID

Looping through multiple values:
For Each post In html.getElementsByName("PickupDate")
    MsgBox post.ID
Next post


text:
Q: Variations of Assouad's lemma I'm reading the paper Optimal Rates of Convergence for Sparse Covariance Matrix Estimation by T. Cai and H. Zhou.
They refer to a specific version of Assouad's Lemma (see lemma 2, p. 6 of the linked paper), which differs from the one I've found in Yu [1] and Le Cam [2]. I've also ordered van der Vaart [3], but it has yet to arrive.
Can do you know of a resource that contains a proof of the version Cai states? Or can you give a proof?
I'm especially interested because I'm having trouble with their proof of lemma 3 (p. 7 of linked paper, proof p. 21) and the lemmas seem very related. Specifically, I don't understand how the use of
$\hat{\theta} = \mbox{argmin}_{\theta \in \Theta} d(T,\psi (\theta))$
in eq. (37) is meaningful as $T$ is a random variable.
[1] B. Yu (1997). Assouad, Fano, and Le Cam. Festschrift for Lucien Le Cam. D. Pollard, E. Torgersen, and G. Yang (eds), pp. 423-435, Springer-Verlag.
[2] Le Cam, L. (1986). Asymptotic Methods in Statistical Decision Theory. SpringerVerlag, New York.
[3] van der Vaart, A.W. (1998). Asymptotic Statistics. Cambridge University Press, Cambridge.


text:
Q: How do I make the canvas display the recoloured image instead of the same image? I had an image of Canada and manually recolored its pixels to shades of blue. I then tried to make a script that would do the same(into red) without me going through all the hassle.
But for some reason, the canvas simply repaints the same image of the blue Canada in Mozilla and Chrome(sometimes not even draws it).
Mozilla says accessing ImageData is a security error. What did I get wrong and how do I fix it?
Snippet right here:

canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
var imgPath = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d8/Copper_sulfate.jpg/234px-Copper_sulfate.jpg";
var imgObj = new Image();
imgObj.crossOrigin = "anonymous";
imgObj.src = imgPath;

imgObj.onload = function() {
  context.drawImage(imgObj, 0, 0);
  map = context.getImageData(0, 0, 234, 240);
  imagedata = map.data;

  for (p = 0; p < imagedata.length; p += 4) {
    imagedata[p] = imagedata[p + 2];
    imagedata[p + 2] = 0;
    imagedata[p + 3] = 255;
  };
  context.putImageData(map, 0, 0);
};
<img id="Canada" src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d8/Copper_sulfate.jpg/234px-Copper_sulfate.jpg" />
<canvas id='canvas' width='234px' height='240px'></canvas>


text:
Q: Add +1 to p everytime the divis clicked

0

I want to increment the number inside p everytime I click on the inner div. I've tried some methods. But they only work with buttons, and I don't want to change the HTML.

A: Simply bind a click event handler and update text inside the p tag on click.

// add click event handler to the div
document.getElementById('rating').addEventListener('click', function() {
  // get p element inside the div
  var p = this.querySelector('p');
  // update the content
  p.textContent = Number(p.textContent) + 1;
});

0


text:
Q: dialogflow sys.date-time parameter format question I'm making an app on Dialogflow and need to extract date-time info from user. So I specified a required parameter called "date-time" with @sys.date-time entity in my intent. However, when I tried to extract this parameter in my fulfillment code, I found that this parameter structure is not the same every time when I extract it. For example, when I type 12:30am into the chatbot, the returned API json response contained this:
"parameters": {
      "date-time": "2019-11-27T00:30:00-08:00",
      "log": "5"
    },

So I can directly read date-time parameter value by parameters['date-time']
However, if I type "yesterday at 2pm" into chatbot, the returned parameter structure is this:
"parameters": {
      "date-time": {
        "date_time": "2019-11-25T14:00:00-08:00"
      },
      "log": "log"
    },

See that the "date-time" parameter is wrapped inside an extra "date-time" object. This is really annoying because now i need to consider these two cases in my fulfillment code. Does anyone know why this happened? And is this a bug on my side? Thanks!

A: You may have found the answer to this by now, but going through Googles documentation here I found you have to consider a variety of cases when using the @sys.date-time entity. So there's nothing wrong on your end.
An extra "date_time" is used when a date and time were specified, whereas if its a period of time there's a "startDate" and "endDate" that you have to look out for inside the original "date_time" object as well.
From looking at the examples in that document I've outlined some of the cases below.
specific time (e.g.12:30am) or specific date (e.g. December 12) = single date_time object
time period (date or time e.g. April or morning) = "startDate" and "endDate" entry in a date_time object
specific date + specific time (e.g. yesterday at 2pm) = "date_time" entry in a date_time object
date + time period (e.g. yesterday afternoon) = "startDateTime" and "endDateTime" in a date_time object
Hope that helps!


text:
Q: Changing the background image when clicking on the div? I am creating a table with div's that already have a background image in them. The classes are "sw", "sl", "so", "sa", "sn", and "su". I made that you could click on the div's and to the right will show the information for that div.
However, I tried adding a hover element to these div's, which work when I do not add the onclick function. With the onclick function, there is no hover that changes the div into a different background image. The background image stays the same when I click on a certain div.
How can you make the background image change when you click on the div?
Here is my HTML code:

And here is my JavaScript code:
function show(num) {
    var outputInfo = "";
    if(num == 0) {
        outputInfo += 'INFO HERE';
    }
    else if(num == 1) {
        outputInfo += 'INFO HERE';
    }
    ...
    document.getElementById("info").innerHTML = outputInfo;
}

Oh, and by the way, my background images are used on the CSS portion and all of the classes above share the same image but they were assigned different positions.
Is there a way to show the images as separate backgrounds if another approach to clicking on a div?

A: You can make a simple onclick function in javascript/jQuery ( I use this code with jQuery 1.7.1 ) like the following:
$('#changeMe').on('click', function() {
    $('#changeMe').css('background-image', 'url(urlhere)');
})

Where #changeMe is the div id

$('#changeMe').on('click', function() {
    $('#changeMe').css('background-image', 'url(http://firefoxzeneize.altervista.org/FirefoxLogo.png)');
})
div{
    width : 512px;
    height : 512px;
    background-image : url("https://www.notebookcheck.net/fileadmin/Notebooks/News/_nc3/20170911_Google_Chrome_logo_vector_download.png");

}

A: Well, your code should looks like:
document.getElementById("info").style.backgroundImage = "url('image.png')";

here I am assuming that info is the id of the div which you want to change background.

A: This snippet should do. I've linked a couple of random images so you can test it.
By clicking on the div, the info is displayed on the right and that div's background gets updated. By passing the 'this' keyword as argument of the show method you can avoid logics that depend on the div's id.
<!DOCTYPE html>

<title>Page Title</title>

A: Instead of using onclick, maybe try using something Tomm did. I probably encourage you to create a class for all of these id elements. Since you had a shared background image for the original background before the function is clicked, I added background-position. Here is what I did for the script by making a function that I put in the onload of the body (first portion is for backgrounds when clicked, second portion is for original background and will only show for those that are not clicked):
function onloadPage() {
    // first portion
    $('#sw').click(function() {
        $(this).css("background-position", "0 0");
        document.getElementById("info").innerHTML = 'INFO HERE';
    });
    $('#sl').click(function() {
        $(this).css("background-position", "0 0");
        document.getElementById("info").innerHTML = 'INFO HERE';
    });
    ...

    // second portion
    $('.classname').on('click', function(e) {
        if(!$(e.target).closest('#sw').length) { $('#sw').css("background-position", '0 0'); }
        if(!$(e.target).closest('#sl').length) { $('#sl').css("background-position", '0 0'); }
        ...
}

And then the HTML:

Obviously you will have to adjust your background-positions to the way you need it to look.


text:
Q: how to "sudo root" with posh-ssh (powershell) i am using posh-ssh to connect to my ssh server do some commands start with su root,but i can not switch user to root sucessfully.
PS C:\> $rootpwdSec = ConvertTo-SecureString $rootpwd -AsPlainText -Force
PS C:\> Invoke-SSHStreamExpectSecureAction -Command 'su ' -ExpectString 'Password:' -SecureAction $rootpwdSec -ShellStream $stream
True
PS C:\> $stream.read();

[root@aaaaaa-test admin]#
PS C:\> Invoke-SSHCommandStream  -SessionId $SessionId -Command 'id'
uid=500(admin) gid=500(admin) groups=500(admin) context=user_u:system_r:unconfined_t
PS C:\>

how can run my command as root?

A: What I noticed when working with posh-ssh and ubuntu was I was failing to sudo up to root using "sudo su -" due to the ExpectString. It was expecting "[sudo] password for (username):" and I was merely providing "password:"
$stream = $session.Session.CreateShellStream("PS-SSH", 0, 0, 0, 0, 100)
$user = Invoke-SSHCommand $session -Command "whoami"
$SSHusersName = $user.Output | Out-String
$SSHusersName = $SSHusersName.Trim()
$results = Invoke-SSHStreamExpectSecureAction -ShellStream $stream -Command "sudo su -" -ExpectString "[sudo] password for $($SSHusersName):" -SecureAction $secpas
$stream.Read()

This was how I was able to sudo to root. Again it may be different for you depending on what *nix variant you are connecting to.


text:
Q: Is it possible to add dependent environment variables in Google Cloud Run? I would like to specify dependent environment variables on a Cloud Run service.
If the environment variables have been defined in a .env file it would look like this
DATABASE_NAME=my-database
DATABASE_USER=root
DATABASE_PASSWORD=P4SSw0rd!
DATABASE_PORT=5432
DATABASE_HOST="/socket/my-database-socket"
DATABASE_URL="user=${DATABASE_USER} password=${DATABASE_PASSWORD} dbname=${DATABASE_NAME} host=${DATABASE_HOST}"

In this example, DATABASE_URL depends on every other environment variables.
To deploy the service I run the following command:
gcloud run deploy my-service \
--image gcr.io/my-project/my-image:latest \
--region europe-west1 \
--port 80 \
--platform managed \
--allow-unauthenticated \
--set-env-vars 'DATABASE_NAME=my-database' \
--set-env-vars 'DATABASE_USER=root' \
--set-env-vars 'DATABASE_PASSWORD=P4SSw0rd!' \
--set-env-vars 'DATABASE_PORT=5432' \
--set-env-vars 'DATABASE_HOST="/socket/my-database-socket"' \
--set-env-vars 'DATABASE_URL="user=$(DATABASE_USER) password=$(DATABASE_PASSWORD) dbname=$(DATABASE_NAME) host=$(DATABASE_HOST)"'

Here is the created YAML definition of the service (some values are omitted)
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: my-service
spec:
  template:
    metadata:
      name: ...
    spec:
      containerConcurrency: 80
      timeoutSeconds: 300
      containers:
      - image: ...
        ports:
        - name: http1
          containerPort: 80
        env:
        - name: DATABASE_NAME
          value: my-database
        - name: DATABASE_USER
          value: root
        - name: DATABASE_PASSWORD
          value: P4SSw0rd!
        - name: DATABASE_HOST
          value: /socket/my-database-socket
        - name: DATABASE_URL
          value: user=$(DATABASE_USER) password=$(DATABASE_PASSWORD) dbname=$(DATABASE_NAME) host=$(DATABASE_HOST)

The problem is that when the service is running, the env vars in DATABASE_URL seem not interpolated.
I read that Kubernetes supports dependent env vars but I can't figure out how to make this run in Cloud Run.
I am wondering if it is supported in Cloud Run in the end.

A: It's likely this may work in Knative open source (which uses Kubernetes to execute pods) but not on Google Cloud Run (fully hosted), which runs on a proprietary execution engine.


text:
Q: How do I eliminate variables with missing results in SAS? Here are my results. Since PPD has a missing result I'd like to eliminate all results for PPD. I.e. I'd like to eliminate all records where ticker='PPD' if any record where ticker='PPD' has a missing result (corr).
How can I program this in SAS? I don't want to just eliminate that missing observation but eliminate PPD altogether. Thanks.
Ticker    Day       Corr
PPD 7   -1
PPD 8
PTP 7   0.547561231
PTP 8   0.183279038

A: Lots of ways to do this, and what is most efficient depends on your data.  If you don't have too much data, then I'd use the easiest method that fits with your knowledge and other habits.
*SQL delete;
proc sql;
  delete from have H where exists (
     select 1 from have V where H.ticker=V.ticker and V.corr is null);
quit;

*FREQ for missing (or means or whatever) then delete from that;
*Requires have to be sorted.;
proc freq data=have;
 tables ticker*corr/missing out=ismiss(where=(missing(corr)));
run;

data want;
 merge have(in=_h) ismiss(in=_m);
 by ticker;
 if _h and not _m;
run;

*double DoW.  Requires either dataset is sorted by ticker,;
*or requires it to be organized by ticker (but tickers can be not alphabetically sorted); *and use norsorted on by statement;
data want;
  do _n_=1 by 1 until (last.ticker);
    set have;
    by ticker;
    if missing(corr) then _miss=1;
  end;
  do _n_=1 by 1 until (last.ticker);
    set have;
    by ticker;
    if _miss ne 1 then output;
  end;
run;

A: This is easily accomplished in PROC SQL...

proc sql ;
  create table to_delete as
  select distinct ticker
  from mydata
  where missing(corr) ;

  delete from mydata
  where ticker in(select ticker from to_delete) ;
quit ;

Unfortunately, it can't be done in a single SQL step as the delete from statement would recursively reference the source dataset.


text:
Q: How to use variables to insert data in python to a mysql database? How can I use variables directly in place of string when inserting data into the query?
import pymysql
import json

# Connect to the database
conn = pymysql.connect(host='localhost',
                       user='test',
                       password='br',
                       db='testing')
cur = conn.cursor()

json_data = json.loads(open("res.json").read())

# currently this is the query I want to execute
query = """INSERT INTO RF.candidate (
    first_name, last_name, phone, email,
    social, website
) VALUES (
    'David', 'N', '["+1 917 547 7813", "+1 917 547 7823"]',
    '["testing@gmail.com"]', '["fb.com/rtr"]', '["google.com", "sris.com"]',
    '{"Degree": {"MBA": {"Majors": [""]}}}',
);"""

cur.execute(query)

# datatypes:
# first_name : varchar
# last_name : varchar
# phone : json
# email : json
# social : json
# website: json
# education: json

The email address data is in json_data variable,
print(json_data['email'])
# returns
["testing@gmail.com"]

email_array = json.dumps(json_data['email'])

Now I want to pass the variable email_array in sql query email column rather than manually writing the json list in the query variable like I did above?
How can I do it in python?

A: query = """INSERT INTO RF.candidate (
    first_name, last_name, phone, email,
    social, website
) VALUES (
    'David', 'N', '["+1 917 547 7813", "+1 917 547 7823"]',
    '[{}]', '["fb.com/rtr"]', '["google.com", "sris.com"]'
);""".format(EMAIL_VARIABLE)

if email variable is an array use {} otherwise [{}]


text:
Q: Pandas extract substring based on another column I have 2 dataframes. Below is first df:
df1={"columnA":['apple,cherry','pineple,lemon','banana, pear','cherry, pear, lemon']}
df1=pd.DataFrame(df1)

And second df:
df2={"columnB":['lemon','cherry']}
df2=pd.DataFrame(df2)

I already got all values in df1 that appear in df2.
I'm using below code to filter:
words = [rf'\b{string}\b' for string in df2.columnB]
df1[df1['columnA'].str.contains('|'.join(words))]

and I got below:

So the next step I want to do is to remove all unwanted substring from the above result like this:

Please let me know how can i achieve this?

A: I think you need a separate method to be applied to the DataFrame:
def keep_words(cell, df):
    words = cell.split(',')
    result = []
    for word in words:
         if word.strip() in list(df.columnB):
              result.append(word)
    return ','.join(result)

words = [rf'\b{string}\b' for string in df2.columnB]
df1 = df1[df1['columnA'].str.contains('|'.join(words))]
df3 = df1.columnA.apply(lambda x: keep_words(x, df2))

Since it takes quiet a few steps to go through, define a separate method (keep_words), which takes in the string inside each cell, and the DataFrame with the accepted words, compares each word in the string against the "list" of accepted words and returns eligible ones.
I am not sure about the performance in bigger DataFrames though.


text:
Q: How to add Schema.org tags to hotel rooms? I'm creating a website for a hotel. This hotel has different types of rooms(luxury, non smoking, kids etc). How can I add schema.org tags to rooms listing? I found this one but, it gives errors when I test it using Google Structured Data Testing Tool.

  The Sunshine Hotel offers both King and
Double, both of which feature in-room Wifi.

A: You are using types and properties that don't exist in Schema.org (as of 2.2).
But types and properties for (hotel) rooms are proposed, see Markup for Hotels (work in progress, not a stable URL!). So we might see these (or something similar) in the next Schema.org release.
If you don't want to wait, the best you could come up with now might be to use the generic Place for rooms:

*

*Hotel containsPlace Place

*Place containedInPlace Hotel

A: The schema.org release of version 3.1 finally brought the hotel extension to annotate hotel rooms. The documentation (http://schema.org/docs/hotels.html) is not yet up to date, but you can find an example of how to annotate a hotel and its rooms here: https://elias.kaerle.com/annotating-a-hotel-offering-rooms-with-the-new-schema-org-version-3-1/ (this example annotates the rooms as offers of the hotel Hotel-makesOffer-Offer - Offer-itemOffered-HotelRoom).


text:
Q: Varible updated before saving I have two js files file1.js and file2.js. In file1.js i define a function save() where I am saving my data and accessing some global variables to save like this
function save(skip)
{
    var score = 1;
    var answer=1;
    if(!skip)
    {
        var res=get_answer()
        answer=res[0];score=res[1];
    } else {
        answer=0;score=-0.33;
    }
    var date = getDate();
    var Question_id = questionId;
    var difficulty = difficulty_level;
}

I have another function in file2.js algo() which I am using to update difficulty_level. Code is
function algo()
{
     // some code
     if(ans1=='0' && ans2=='0')
     {
         if(difficulty_level!=1)
         difficulty_level=difficulty_level-1;
     }
 }

Now i am calling these both function on click of skip button.
$("#CT_Skip").click(function (event) {
      save(true);
      algo();
});

Now my problem is I am getting updated value of difficulty_level in save() function. I tried setTimeout() but still getting updated value. Please help me solve this. Thank you!!!


text:
Q: AttributeError with Django Rest nested serializer I'm following the Django Rest documentation for writing nested serializer but it is giving me attribute error.
Here are my models:
class Objects(TimeStampModel):
    projects = models.ForeignKey(Projects,related_name='proj_obj',on_delete=models.CASCADE)
    object_name = models.CharField(max_length=50)
    object_description = models.TextField()
    object_main_table = models.CharField(max_length=50)
    object_primary_key = models.CharField(max_length=50)
    object_age_field = models.CharField(max_length=50)
    date_format = models.CharField(max_length=50)

    def __str__(self):
        return self.object_name

class ObjectDefinition(TimeStampModel):
    ATTRIBUTE = 'Attribute'
    RELATION = 'Relation'
    TYPE_CHOICES = (
        (ATTRIBUTE, 'Attribute'),
        (RELATION, 'Relation'),
    )
    obj = models.ForeignKey(Objects,related_name='obj_def',on_delete=models.CASCADE)
    from_table = models.CharField(max_length=50)
    from_table_field = models.CharField(max_length=50)
    to_table = models.CharField(max_length=50)
    to_table_field = models.CharField(max_length=50)
    relation_type = models.CharField(max_length=50,choices=TYPE_CHOICES)
    relation_sequence = models.CharField(max_length=50)
    value_field = models.CharField(max_length=50, blank=True, null=True)

Here is my serializers.py snippet:
class ObjectDefinitionSerializer(serializers.ModelSerializer):

    class Meta:
        model = ObjectDefinition
        fields = ('from_table','from_table_field','to_table','to_table_field','relation_type','value_field')

class ObjectSerializer(serializers.ModelSerializer):
    definition = ObjectDefinitionSerializer(many=True)
    object_description = serializers.CharField(required=False, allow_null=True, allow_blank=True
        )

    class Meta:
        model = Objects
        fields = ('projects','object_name','object_description','object_main_table','object_primary_key','object_age_field','date_format','definition')

    def validate(self, data, *args, **kwargs):
        date_format = data.get('date_format')
        if date_format not in ['YYYYMMDD', 'DDMMYYYY']:
            msg = ('Date format is incorrect')
            raise serializers.ValidationError({'error_msg': msg})
        return super(ObjectSerializer, self).validate(data, *args, **kwargs)

    def create(self, validated_data):
        definition_data = validated_data.pop('definition')
        obj = Objects.objects.create(**validated_data)
        for data in definition_data:
            ObjectDefinition.objects.create(obj=obj, **data)
        return obj

My views.py:
class CreateObject(CreateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = ObjectSerializer

After hitting POST, objects.create works fine for both the models but at return obj, it throws me this error:
Exception Value:
Got AttributeError when attempting to get a value for field definition on serializer ObjectSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Objects instance.
Original exception text was: 'Objects' object has no attribute 'definition'.
What am I missing?

A: The ObjectDefinition.obj's related_name is obj_def which doesn't match your serializer.
You can fix that by providing the source argument:
definition = ObjectDefinitionSerializer(source='obj_def', many=True)


text:
Q: how to decode the json ajax response i am having trouble with decoding the ajax reponse ,here i am sending the organisation,location and building as the inputs which in return gives 2 keys as entrance/exit and key ,now my ajax call is working fine and i can alert the response ,now my reqiurement is to decode the json array i have got and then take the value of entrance/exit into a form field called entrance/exit in the form and type into type field in the form .I have tried to decode the json in the php phage which is executed when the ajax is called and stored the 2 values into sessions but it was not showing up in the form fields when i give the value =$_SESSIN[type] and $_SESSION[entrance/exit] after that i have tried to decode the json script with javascript using console can any one figure out what i a doing wrong.
the code upto this is
 //ajax
 function ajax()
{
var org=document.getElementById('category_id').value;
alert(org);
var loc=document.getElementById('category_id1').value;
alert(loc);
var bui=document.getElementById('category_id2').value;
alert(bui);
var req;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
   req=new XMLHttpRequest();
}
else
{// code for IE6, IE5
   req=new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("POST", "ajax.php?&org="+org+"&loc="+loc+"&bui="+bui+"", true);
req.send();
req.onreadystatechange=function(){
   if(req.readyState==4&&req.status==200){
       //$(".error").hide();
       result=req.responseText
       alert(result);
       var strJSON = 'result';
       var objJSON = eval("(function(){return " + strJSON + ";})()");
       alert(objJSON.name);
       alert(objJSON.type);

       }
   }
}
 <form name="theForm" method="post" action="addmachine.php" enctype="multipart/form-data" onSubmit="return validate();">
      Organisation Name
                <select style="width: 305px;text-align:left ;"  name="category_id" id="category_id" onchange="OrganisationName(this);">
                <option value="">Select</option>
                 <option value="1">1</option>
                 <option value="2">2</option>
                                  </select>

    Location

                 <select style="width: 305px;" name="category_id1" id="category_id1" onchange="LocationName(this);" >
                 <option value="">Select</option>
                 <option value="1">1</option>
                 <option value="2">2</option>

                 </select>

    Building

                <select style="width: 305px" name="category_id2" id="category_id2" onchange="BuildingName(this);" onchange="ajax(this);">
                <option value="">Select</option>
                <option value="1">1</option>
                <option value="2">2</option>
                </select>

                Entrance/Exit
                <input type="text" name="ent" id="ent" value="objJSON.name" placeholder="enter entrance/exit"/>

                Type
                <input type="text" name="type" value="objJSON.type" placeholder="enter your work station"/>

      Name
      <input type="text" id="workstnname" name="workstnname" placeholder="enter your work station" onblur="return name();" onkeypress="return onKeyPressBlockNumbers(event);">
      Description
      <textarea name="description" style="height:150px;width:300px;"></textarea>
      Machine Type
                <select style="width: 305px;text-align:left;"  name="machinetype">
                <option value="">Select</option>
                <option value="kiosk">kiosk</option>
                <option value="workstation">workstation</option>

              </select>

                <input type="submit" name="submit" value="Submit">

    </form>

i am not getting the value of the keys entance or exit and type
the json iam getting in response and is alerted is
[{"name":"Default Entrance + Exit","type":"both"}]

i dont know whether i have did some bluders in the code or not,as i have only started with javascript
thank you

A: For the security and workflow reasons it's better to parse json by JSON.parse
var objJSON = JSON.parse(strJSON);

not by eval

A: Try this,
  var objJSON = JSON.parse(result);
  alert(objJSON.name);
  alert(objJSON.type);

A: Please try this one
 JSONObject obj = new JSONObject(result);

    List<String> list = new ArrayList<String>();
    JSONArray array = obj.getJSONArray("interests");
    for(int i = 0 ; i < array.length() ; i++){
        list.add(array.getJSONObject(i).getString("interestKey"));
    }

using  org.json library


text:
Q: How should we handle wholly non-English comments? Ok, I've read through Do posts have to be in English on Stack Exchange? and How should we handle non-English answers?. They encourage new posts in just English, but I didn't see a decision about how to handle existing content in other languages.
On one of the Beta SEs, we have a member who semi-regularly posts comments in what I assume to be a dialect from India.  For example, his most recent comment reads as follows:

gupta ji apne last question pe bhi najar daalo..

Should non-English comments...

*

*be flagged not constructive / off topic?

*be flagged other (with a comment)?

*be left as-is?

*be dealt with some other way?

I understand the official policy is to post questions in English.  What should be done with existing comments that are in other languages?

A: I'd flag as "other" and leave a comment. You can also leave a comment explaining the policy to the user.

A: I'd add a comment explaining that posts on SE sites need to be in english and flag it as "other". Flags are the correct way if you think that a comment should be removed for any reason.

A: From what I've read, my understanding of the matter is that: English should be used. I never saw anywhere where it stated that other languages are not to be used, yet from what I did read is that its just implying that answers should be in English.
With handling comments: If the comment is relevant to the question, and not just some conversation between two people (unfortunately, if we don't know  the language we can't tell what the heck they are talking about ^_^) I would just ignore it... or ask them to translate their comment. Depending on the relevance of the question to my needs.


text:
Q: toLocalDateString function to return a date in format DD MMM YYYY is throwing an "is not a function" error in browser console I have a date which is in the string format of 2021-03-31T00:00:00. I want this date to be in the format DD MMM YYY so it appears like 31 Mar 2021.
I have used the following code in the typescript file:
const formattedDate = i.SuspensionEndDate.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });

When I run in the browser, I get this error in the console:

jQuery.Deferred exception: date.toLocaleDateString is not a function
TypeError: date.toLocaleDateString is not a function

I get a similar error when using the following code to extract only the DD element using getDate():
const formattedDate = i.SuspensionEndDate.getDate();

jQuery.Deferred exception: date.getDate is not a
function TypeError: date.getDate is not a function

I've not seen these errors before even though I have been able to do the same thing with JavaScript in the past. Though it's the first time doing it in a .ts TypeScript file.

A: Convert i.SuspensionEndDate to Date object before format.
const formattedDate = new Date(i.SuspensionEndDate).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });

Here's working example:

const exDate = "2021-03-31T00:00:00";

const date = new Date(exDate).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });

console.log(date);


text:
Q: Receive asynchronous events from a web application to a desktop application in Actionscript 3 I want to build a simple web 2.0 collaborative website using asp.net MVC2 or Flash  and I want to  receive events from a web based interface to a desktop AIR application. For e.g, someone makes a comment on a blog post, I want that information to be passed on to a desktop air application showing that a new comment has been made. What would be a good technique to receive asynchronous events?

A: The easy way is to set a timer that will request the XML from your webservice each XXXX miliseconds.
An optimization tip could be ask if there are new items to load before call the complete XML.

A: Two flash applications on same machine can communicate via LocalConnection (even in one is AIR-based). To listen for call, it must be connected using some name. Use two different names in AIR and Flex app (one is to listen, second to send to).


text:
Q: AngularJS $resource append full webdir path to request I have the following
var API = $resource('/api/:object/:action', {
            action: '@action',
            object: '@object'
        },
        save:  { method: 'POST'},
        delete:{ method: 'DELETE'},
        update:{ method: 'PUT'}
});

a = new API({object: 'test',id: 2, name: 'name2'});
a.$save(function(u){ console.log(u); });

the request have the following url  http://mylocalhost/home/rkmax/myproject/api/test/ and the correct http://mylocalhost/api/test/, the weirdest thing is that when I run my app showing the file into the route, like http://mylocalhost/myapp.php works fine.
my project is in the /home/rkmax/myproject path but i dont understand why $resource append that to the path
can help me with this weird error, my app uses html5Mode for all UI
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix('!');

the url of the app is http://mylocalhost/app and the API is http://mylocalhost/api


text:
Q: Divide page with iframe Hello I am new developer in Korea.
I do not speak English. ... As of this writing.So there may be a mistranslation. (T.T)
I was wondering.If you look at the images on the current page via Google API script injection screen two of the iframe or the area, adding to the'd like to share a Google developer tools like...
Is It Possible?
Thank you obtain the advice of senior developers worldwide nimdeul ... ^^

A: Try frameset insead...
for example:
<frameset cols="25%,*,25%">
  <frame src="frame_a.htm">
  <frame src="frame_b.htm">
  <frame src="frame_c.htm">
</frameset>

(though its not supported in html5)


text:
Q: postgres pg_basebackup can't find .pg_pass file I have successfully setup replication streaming from a primary to a secondary postgres docker container, each running as tasks on separate ec2 instances.
However, I did this by leaving the replication user on the primary server as trust  in its pg_hba.conf:

host  replication replication 0.0.0.0/0 trust

Then, when I switched it to md5, I thought I would be able to simply set a password on the secondary for the replication user and everything would be fine.  Nope.
In my initialization script on the secondary, when I call

pg_basebackup -h #{primary_ip} -p 5432 -D $PGDATA -U #{repl_user} -v -P -w --xlog-method=stream

I initially got the password prompt.
Then I added the -w. Which would give me the error:

pg_basebackup: could not connect to server: fe_sendauth: no password supplied

Then I found out there is no postgres home directory on the generic postgres 9.6 image, so I added a $PG_PASSFILE variable. That didn't work (Permissions were fine, I even put it in /tmp as well as passed the PG_PASSFILE=... right on the pg_basebackup line as in this question: .pgpass for PostgreSQL replication in Dockerized environment (see Raphael's comment))
No matter what I do, the pg_basebackup ignores the .pg_pass file.
I then tried mounting a volume as /home/postgres but with AWS, I can't seem to gosu to root inside the entry point init script I have created.  Everything is as the postgres user.
Has anybody overcome this?
I am running my secondary initialization code as an entrypoint script.  Like I said, it works fine as trust but adding that password is killing me.

A: If you set replication you dont need to run pg_basebackup any more. adding -w will always give you fe_sendauth: no password supplied if you set anything but trust or peer for local to corresponding connection - just because -w stands for --no-password.
https://www.postgresql.org/docs/current/static/libpq-envars.html

PGPASSFILE specifies the name of the password file to use for lookups.
  If not set, it defaults to ~/.pgpass (see Section 32.15).

so default is .pgpass, not .pg_pass, of course you can use .pg_pass, setting export PGPASSFILE=.pg_pass , but you use PG_PASSFILE variable - right?..
So postgres ignores it, and it should.
I would first try creating right .pgpass in home directory with 600 permissions.
Also mind different primary_conninfo if you want to use password file.
https://www.postgresql.org/docs/current/static/standby-settings.html

in a separate ~/.pgpass file on the standby server (use replication as
  the database name). Do not specify a database name in the
  primary_conninfo string.


text:
Q: Rails: List all the items from a table to drop-down list using Devise I'm new to Rails.
I use devise for authentication in my Rails 5.0.1 project.
# Here is my Helper Module

module CategoriesHelper
 def categories_for_select
   Category.all.collect { |m| [m.name] }
 end
end

in _form.html.erb page
<div class="field">
<%= f.label :category_name %>
<%= f.select(:category_name, categories_for_select, :prompt => 'Select') %>
<%= link_to 'Create New Category', new_category_path %>

How can I list all the items from the Category table to a drop-down list that is associated with the current_user.
UPDATE:
Schema
create_table "categories", force: :cascade do |t|
 t.string   "name"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.integer  "user_id"
end

A: Assuming your User has_many categories, you can simply do:
current_user.categories.pluck(:name)


text:
Q: javascript refresh page 5 seconds after form submit The form I am working with is an embedded js form, so I don't have direct access to the code.
I am at a tradeshow, and I want the page with the form to refresh 5 seconds after the form has been submitted.
I am using this code, but not getting a refresh. What am I missing?
<script type="text/javascript">
// Reload page 5 seconds after form submission
$("form").onsubmit = setTimeout(function () {
    window.location = "/tradeshow/";
    }, 5000);
</script>

Thanks!

A: You will have to use the location.reload() function for this.
Try this:
<script type="text/javascript">
// Reload page 5 seconds after form submission
$("form").onsubmit = setTimeout(function () {
        location.reload(true); //MODIFICATION
    }, 5000);
</script>

A: You can only meta tag to update user page without submiting form:
meta http-equiv="Refresh" content="0.5"


text:
Q: Is the past simple tense used correctly here? Look at this sentence: Before the twentieth century, more than a thousand people tried to reach the pole.
Is the present simple tense used correctly there? It seems (to me) that the past perfect tense should be used instead. If I'm wrong, please, give me an explanation. I'm really confused.

A: Past perfect would have been possible but not required. You tend to use past perfect when there is an established narrative at a particular time and then you describe an event that occurred before that time.  There is no narrative here. There is just a phrase which describes a past time, and a past tense clause.  That is consistent and correct.


text:
Q: Active Directory field mapping The 'company' and 'department' fields in an AD user's profile, are they mapped in any way? Must a department belong to a company? Or are they just text fields with no rules..

A: Those are just regular string text fields - they are no relations or checks or anything behind those - just put whatever you like into those.


text:
Q: Why does GNU script use two forks instead of select and one fork? I just realised that the "script" binary on GNU linux is using two forks instead of one.
It could simply use select instead of doing a first fork(). Why would it use two forks ?
Is it simply because select did not exist at the time it has been coded and nobody had the motivation to recode it or is there a valid reason ?
man 1 script: http://linux.die.net/man/1/script
script source: http://pastebin.com/raw.php?i=br8QXRUT

A: The clue is in the code, which I have added some comments to.
child = fork();
sigprocmask(SIG_SETMASK, &unblock_mask, NULL);

if (child < 0) {
    warn(_("fork failed"));
    fail();
}
if (child == 0) {
            /* child of first fork */
    sigprocmask(SIG_SETMASK, &block_mask, NULL);
    subchild = child = fork();
    sigprocmask(SIG_SETMASK, &unblock_mask, NULL);

    if (child < 0) {
        warn(_("fork failed"));
        fail();
    }
    if (child) {
                    /* child of second fork runs 'dooutput' */
        if (!timingfd)
            timingfd = fdopen(STDERR_FILENO, "w");
        dooutput(timingfd);
    } else
                    /* parent of second fork runs 'doshell' */
        doshell();
} else {
    sa.sa_handler = resize;
    sigaction(SIGWINCH, &sa, NULL);
}
    /* parent of first fork runs doinput */
doinput();

There are thus three process running:

*

*dooutput()

*doshell()

*doinput()
I think you are asking why use three processes, not one process and select(). select() has existed since ancient UNIX history, so the answer is unlikely to be that select() did not exist. The answer is more prosaic. doshell() needs to be in a separate process anyway, as what it does is exec the shell with appropriately piped fds. You thus need at least one fork. Writing dooutput() and doinput() within a select() loop looks to me perfectly possible, but it is actually easier to use blocking I/O rather than have to worry about using select etc. As fork() is relatively lightweight (given UNIX's CoW semantics) and there is little need for communication between the two processes, why use select() when fork() is perfectly good and produces smaller code? IE the real answer is 'why not?'


text:
Q: Finding two constants in a cumulative distribution function I have been trying to do this problem for the last hour and cannot find anything on how to find two constants in a CDF. The Problem is:

A random variable X has cumulative distribution function F(x) = A/x + B for 1 <= x <= 4. Find A and B.

I am seriously at a loss and this is only the first problem. Please help.

A: Is this a homework problem?
By definition of the CDF, $F(1)=0$ and $F(4)=1$. From the first condition, $A+B=0$ so $B=-A$ and from the second condition $A/4+B=1$ so $-3A/4 = 1$ and thus $A=-4/3$. Hence
$$
F(x)=\frac{4}{3}-\frac{4/3}{x}.
$$


text:
Q: Trying to understand a remark from Atiyah and Macdonald's *Introduction to Commutative Algebra* Can someone explain the following remark from page 52 of Atiyah and Macdonald's Introduction to Commutative Algebra book.

The names isolated and embedded come from geometry. Thus if $A=k[x_1,...,x_n]$, where $k$ is a field, the ideal $\mathfrak a$ gives rise to a variety $X \subset k^n$. The minimal primes $p_i$ corresponds to the irreducible components of $X$ and the embedded primes corresponds to subvarieties of these, i.e., varieties embedded in the irreducible components.

Moreover, is the above remark useful in finding primary decomposition of an ideal? How do we use this in finding a decomposition?

A: Let $\mathfrak a=\mathfrak q_1\cap\cdots\cap\mathfrak q_n$ be a reduced primary decomposition. Then $V(\mathfrak a)=V(\mathfrak q_1)\cup\cdots\cup V(\mathfrak q_n)$. Let $\mathfrak p_i=\sqrt{\mathfrak q_i}$. Now we have $X=V(\mathfrak p_1)\cup\cdots\cup V(\mathfrak p_n)$. If $\mathfrak p_i\subset\mathfrak p_j$, then $V(\mathfrak p_j)\subset V(\mathfrak p_i)$, so an embedded prime gives rise to a subvariety of a minimal (isolated) prime. In fact, $X=\bigcup V(\mathfrak p_i)$ where $\mathfrak p_i$ is running through the minimal primes over $\mathfrak a$.
I doubt that in general this can be useful to find out a primary decomposition since you loose a lot of information when passing from $\mathfrak a$ to $V(\mathfrak a)$.


text:
Q: Select columns in WHERE clause based on a value? Today i have been asked to re-build a webpage that collects and displays statistics based on students grading each lesson. There are three grades. Each day on the schedule is comprised of four lessons, starting at 8.45 to 10:05, next one starting 10:20 to 11:40. The students select a grade on an ipad on the wall, and each grade is saved in db. The ipad shows a page with the three grades and load these based on which lesson it is:
Short:
select
from [table]
where curtime() > pass_tb.pass_start and curtime() < pass_tb.pass_stop

This works ok, then clock strikes 08:45, the corrent class shows up on the ipad and the students can grade the lesson. When lesson ends, students cannot grade that lesson.
Problem is, i need to rebuild a few things since the school needs to be able to change start and stop time on each lesson. The DB is not build correctly but the solution COULD be to change the SELECT statement above using IFs in the where-clause if applicable? Ie selecting where on another column instead based on a value?
Like this?
IF klassrumsstat_tb.av_tid = 0
then WHERE curtime() > pass_tb.pass_start and curtime() < pass_tb.pass_stop
ELSE if klassrumsstat_tb.avtid = 1
then WHERE curtime() > klassrumsstat_tb.av_tid_start and curtime() < klassrumsstat_tb.av_tid_stop

The entire SELECT:
select klassrumsstat_tb.*,
       pass_tb.pass_namn,
       pass_tb.pass_start,
       pass_tb.pass_stop,
       klasser_tb.klassnamn,
       personer_tb.förnamn,
       personer_tb.efternamn,
       klassrum_tb.rumsnamn,
       ämnen_tb.ämne
from klassrumsstat_tb
inner join pass_tb on pass_tb.pasid = klassrumsstat_tb.pasid
inner join klasser_tb on klasser_tb.klassid = klassrumsstat_tb.klass
inner join personer_tb on personer_tb.uid = klassrumsstat_tb.uid
inner join klassrum_tb on klassrum_tb.klaid = klassrumsstat_tb.klaid
inner join ämnen_tb on ämnen_tb.aid = klassrumsstat_tb.aid
where klassrumsstat_tb.klaid = 1
  and dag = 'Mon'
  and curtime() > pass_tb.pass_start
  and curtime() < pass_tb.pass_stop;

The klassrumsstat_tb contains a column (klassrumsstat_tb.av_tid) that is 0 if time does not differ and 1 if times differ. klassrumsstat_tb also contains two columns (av_tid_start and av_tid_stop) which is the new times the lesson should start.
English is not my native language, i hope you understand.
I have searched and googled on how to use IF-statements in the where-clause, but i cannot seem to find a solution to get my desired results. Is it even possible? I dont want to rewrite the entire product.

A: case expression may be what you're after, something like this
CASE WHEN klassrumsstat_tb.av_tid = 0
then curtime() > pass_tb.pass_start and curtime() < pass_tb.pass_stop
WHEN klassrumsstat_tb.avtid = 1
then curtime() > klassrumsstat_tb.av_tid_start and curtime() < klassrumsstat_tb.av_tid_stop
END

https://www.w3schools.com/sql/sql_case.asp