text:
Q: how to create proper html tags in json I have a json object which looks like this:
{
    "id": "id_1636844335636",
    "title": "Emmy",
    "start": "2021-11-09",
    "end": "2021-11-10",
    "description": "",
    "allDay": true,
    "order": 1
}

When reading the json data, i got a js error "Uncaught SyntaxError: Unexpected identifier"
When i replace the \" with ' in the description, everything is fine.
// no error when changing to this:
"description": "",

I use these jsons in fullcalendar script. i really dont know why the escaping characters\" causing a problem. Is the syntax in the json wrong somehow?
By the way: this is how json is create by php:
$file = 'data/'.$id.'.json';
$jsonData = json_encode($array, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
file_put_contents($file, $jsonData);

Update: this is part of the Fullcalendar script which reads the json data:
 events: [

            <?php

            $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('data/rooster/')); // read all files from all the years dirs
            $roosterfiles = [];
            foreach ($rii as $roosterfile) {
                if ($roosterfile->isDir()){
                    continue;
                }
                $roosterfiles[] = $roosterfile->getPathname();
            }

            //$roosterfiles = glob('data/rooster/2021/*.json'); // all roosterfiles in events folder

            foreach($roosterfiles as $roosterfile) {
                $objs[] = json_decode(file_get_contents($roosterfile), true); // decode to php assoc array
            }

            foreach($objs as $key => $val) {
            ?>
            {
                // Eventdata
                id: "<?php echo $val['id']; ?>",                            // id
                groupId: "<?php echo $val['groupId']; ?>",                  // groupId integer only!
                category: "<?php echo $val['category']; ?>",                // category
                title: "<?php echo $val['title']; ?>",                      // title
                backgroundColor: "<?php echo $val['backgroundColor']; ?>",  // bg color
                textColor: "<?php echo $val['textColor']; ?>",              // textcolor
                start: "<?php echo $val['start']; ?>",                      // start
                end: "<?php echo $val['end']; ?>",                          // end
                description: "<?php echo $val['description']; ?>",          // description
                url: "<?php echo $val['url']; ?>",                          // url
                borderColor: "<?php echo $val['backgroundColor']; ?>",      // optional; same color as background
                allDay: "<?php echo $val['allDay']; ?>",                    // default all day event
                order: "<?php echo $val['order']; ?>",                      // order by category
            },

            <?php
            } // end foreach

            ?>

        ],


text:
Q: What's the relationship between AT commands and device vendor's C API? I'm doing an embedded-system project now. From my view, AT commands can be sent to a device to retrieve 4G information, dial and so on. On the other hand, we can also do that by calling APIs provided by the 4G vendor.
My question is what's the relationship between them? Is the API a wrapper for the AT commands?

A: TL;DR
Vendor's API (not only C, but also C++, Java or Python depending to the vendor and the modem model) can both be wrappers for AT commands and a wider, more powerful set of API were the user can port complex applications.
It depends on the vendor and on the model.

A jungle of modems produced by different vendors
It is impossible to define a general "rule" about API provided by a Cellular Module (not necessarily a 4G module).
First of all every vendor usually implements standard AT Commands (both Hayes commands and extended standard commands for cellular devices). In the same way every vendor has it's own implementation of the user application area where the customers can store their own application to control the modem's functionalities and to use them according to their own application requirements.
AT commands remain the interface to be used when the modem needs to be connected (and driven) by an external host. When the user application area is used, instead, a wider set of API is usually provided. They may include:

*

*A library exporting a subset of the OS capabilities (threads management, events, semaphores, mutexes, SW timers, FS access and so on)

*A library offering the capability to manage the specific HW of the device (GPIOs, SPI, I2C, ADC, DAC and so on)

*A library offering a programmatical way to perform action, related to connectivity, that would normally be executed through AT commands (registration status check, PIN code insertion, PDP context activation, SMS management, TCP/UDP/TLS sockets)

The latter usually access a base layer involving all the functionalities provided by the modem. Usually this is the same layer invoked by the AT commands sent through modem's serial interface.

Sending AT commands... from the vendor's API?
Of course it often happens that the library mentioned above provides just a subset of the functionalities usually exported with the AT commands set so, in order to "fill the gap", a further set of APIs is usually exported as well:

*

*A set of functions that allow the simulation of AT commands sent to the modem's serial port. Sending them and parsering the responses they send in the vitual internal serial/USB interface allow the user to port in the internal user application area the the application they previously run on an external host processor (with obvious BOM benefits).

As an example, please check Telit Appzone here and here. It was the inspiration of my answer because I know it very well.

A: I don't know why you name the title that there's a relationship between AT command and Linux-C API.
Regarding AT command, you can take a look at this wiki article for general information.
Each module has a specified AT command sets. Normally, the module manufacture just offers AT command set and what return values are.

Is API a wrapper of AT command?

If you can use the API provided by the manufacturer, then yes, it's a wrapper of the AT command handler.

A:
My question is what's the relationship between them? Is the API a wrapper for the AT commands?

It is impossible to be sure without having any details of the device, but probably any C API for it wraps the AT command set, either by communicating with the device directly over an internal serial interface or by going through a device driver that uses AT commands to communicate with it.
However, it is at least conceivable, albeit unlikely, that the 4G device offers an alternative control path that the C API uses (definitely via a driver in this case).
I'm not quite sure what the point of the question is, though.  If you are programming the device and its 4G component in C, and the manufacturer has provided a C API, then use it!  If you are programming in some other language then at least consider using the C API, which you should be able to access from most other languages in some language-specific way.  You should not expend effort on rolling your own without a compelling reason to reject the API already provided to you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java GUI Scaling problems How i can disable scaling (Windows 10) for java program or process this in code to fix blur on my custom components?
I had tried Dsun.java2d.uiScale.enabled=false but it didn't help.

is there any solution to this problem?

A: Depending on the Java version you are using, you may want to consider different solutions, especially if you'd like to solve it on your application's side.
In any case, and if your concern is just to disable the Windows 10 scaling, you can do so by changing your Java settings and specifying Windows compatibility settings to override DPI scaling, as Elderry mentions here: https://superuser.com/a/1207925 , and as I'm quoting:

*

*Find java.exe you installed.

*Right click -> Properties

*Go to Compatibility tab

*Check Override high DPI scaling behavior.

*Choose System for Scaling performed by:

You can refer to this link for additional answers which may resolve your problem: https://superuser.com/questions/988379/how-do-i-run-java-apps-upscaled-on-a-high-dpi-display


text:
Q: Custom Loss Function does not equal Loss Function used to train model this is my first post so I will try to detail all the relevant info. If anything is missing please let me know!
I am currently trying to create cnn (based off unet) for image segmentation on grayscale images.
I have created a custom function to calculate dice loss and Binary Cross Entropy loss, see below.
def dice_BCE_coef_loss(y_true, y_pred):
    smooth = 1
    bce_weight = 0.5

    #y_true_f = tensorflow.math.reduce_sum(y_true)
    #y_pred_f = tensorflow.math.reduce_sum(y_pred)
    y_true_f = tensorflow.reshape(y_true, [-1])
    y_pred_f = tensorflow.reshape(y_pred, [-1])

    intersection  = tensorflow.math.reduce_sum(y_true_f * y_pred_f)
    union = tensorflow.math.reduce_sum(y_true_f + y_pred_f)
    dice_coef = (2*intersection + smooth) / (union + smooth)
    dice_loss = 1 - dice_coef

    BCE =  tensorflow.keras.losses.BinaryCrossentropy(from_logits=True)(y_true, y_pred)
    dice_BCE = tensorflow.math.reduce_mean(BCE * bce_weight + dice_loss * (1 - bce_weight))
    return dice_BCE

I then add this to my model as the loss.
model.compile(optimizer=tensorflow.keras.optimizers.Adam(lr=1e-3),
              loss=dice_BCE_coef_loss,
              metrics=['accuracy']
              )

The issue comes when I calculate the dice_BCE manually the loss value is different to the output loss during training. To confirm whether this was a correct value across the whole dataset (my manual check was a single image) I reduced my dataset to a single image and mask yet they still didn't match.
Image showing the discrepancy of loss vs my expected dice_BCE loss (I hope a picture is allowed in this case) 1
This loss always remains around 0.48 after several epochs, however never really improves from there and sometimes you can see the output mask is really close (and a good expected dice_BCE to match) yet it ends up diverging because the loss it seems to train on can be improved in other ways (but increase the expected dice_loss).
The dice loss (through the loss value of the epoch) is also far lower than when calculated through the function. Around 0.001 even when the accuracy of the prediction is ~50% and it visible looks incorrect.
Can anybody explain how this loss is calculated and why it does not match what I expect it to be?
I have read through similar posts on here but can't find anything useful.
Any suggestions of what to look into next or resources to investigate further if this is obvious please do let me know! Thank you in advance


text:
Q: Relationship between entropy and information gain Based on papers :1. Deniz Erdogmus, Member, IEEE, and Jose C. Principe, An Error-Entropy Minimization Algorithm for Supervised Training of Nonlinear Adaptive Systems

*

*J. Principe, D. Xu, and J. Fisher, "Information theoretic learning," in Unsupervised Adaptive Filtering, S. Haykin, Ed. New York: Wiley, 2000, vol. I, pp. 265–319.

Entropy (Shannon and Renyis) has been used in learning by minimizing the entropy of the error as an objective function instead of the Mean Square error. Rationale is that minimizing entropy = maximizing mutual information.
Now, entropy = disorder = uncertainty. Higher the uncertainty, more is the entropy. Also,
higher entropy = high information content (used in compression), hence we cannot compress a signal with high entropy.
So, in view of the above I have questions which is Is mutual information another name for information gain? Next, if max entropy implies high information content then why do we minimize entropy of the error between output signal and the desired signal. Is there any proof which shows that minimizing entropy of error when used as a fitness function would mean that we are getting close to the true estimate of the unknown parameter?

A: // So, in view of the above I have questions which is Is mutual information another name for information gain? //
No. But MI can be expressed in terms of KL (i.e. Info Gain) http://en.wikipedia.org/wiki/Mutual_information#Relation_to_other_quantities
// Next, if max entropy implies high information content then why do we minimize entropy of the error between output signal and the desired signal. Is there any proof which shows that minimizing entropy of error when used as a fitness function would mean that we are getting close to the true estimate of the unknown parameter? //
Not sure if I fully understand the question, but there are proofs that minimizing KL is the only inference process that satisfies certain axioms one would deem reasonable from uncertain reasoning.  Suggest you read "An Uncertain Reasoners Companion" - Jeff Paris.
KL and Entropy have both been shown to be the only measures of information (relative or absolute resp.) that satisfy 3 axioms that one would reasonably expect.  Arthur Hobson proved for KL in "Concepts in Statistical Mechanics" (very expensive book), and Shannon proved for entropy (can be found in many Information Theory books).
The similarity between these 3 axioms and the proofs should hopefully help you understand the similarity in their meaning.
I believe it is the strong pure mathematical & philosophical foundation of Information Theory which is why Information Theoretic approaches perform so well and generalize like no other.


text:
Q: Hyperlink network analysis in R - measuring the 'reachability' of a vertex within a network? I'm trying to conceptualise a network analysis problem and figure out where to start in terms of analysis techniques in R. Apologies as I'm fairly new to all this.
Basically, I have a network (1022 vertices and 9171 edges) which is a hyperlink network of different websites. I want to know if I start at a random vertex in the network (u), how many hops (i.e. clicking on hyperlinks) will it take to get to from u to my chosen vertex (v).
Hence, if I iterate this say 1000 times each with a random assignment of u, it might provide some kind of diagnostic around how 'reachable' u is. I could then run this on different networks, to see compare reachability of a particular type of vertex u.
In less abstract terms I am analysing government websites and the hyperlink networks they are part of. So I'm trying to compare different websites in terms of their reachability in the network - i.e. who's more reachable? I understand there is a wealth of network analysis techniques out there, but I'm at a loss where to start really...

A: I will assume your question is where to start looking. One of my favorite places is package sos. Another option would be www.rseek.org.
library(sos)
findFn("reachability network analysis")

found 9 matches;  retrieving 1 page

Downloaded 8 links in 3 packages.

Id  Count   MaxScore    TotalScore  Package Function    Date    Score   Description and Link
1   4   5   10  sna 00Index NA  5    Tools for Social Network Analysis
2   4   5   10  sna hierarchy   NA  2    Compute Graph Hierarchy Scores
3   4   5   10  sna reachability    NA  2    Find the Reachability Matrix of a Graph
4   4   5   10  sna prestige    NA  1    Calculate the Vertex Prestige Scores
5   3   1   3   ergm    gof.ergm    NA  1    Conduct Goodness-of-Fit Diagnostics on a Exponential Family...
6   3   1   3   ergm    plot.gofobject  NA  1    Plot Goodness-of-Fit Diagnostics on a Exponential Family...
7   3   1   3   ergm    summary.gofobject   NA  1    Summaries the Goodness-of-Fit Diagnostics on a Exponential...
8   1   1   1   latentnet   gof.ergmm   NA  1    Conduct Goodness-of-Fit Diagnostics on a Exponential Family...


text:
Q: No disk space left on root When I restarted my computer, which is running Ubuntu 12.04, I got a message that there was 0 disk space left on /.
$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda2        19G   18G     0 100% /
udev            7.8G  4.0K  7.8G   1% /dev
tmpfs           1.6G  944K  1.6G   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            7.9G  512K  7.9G   1% /run/shm
overflow        1.0M  1.0M     0 100% /tmp
/dev/sda1        89M   33M   51M  40% /boot
/dev/md127p1    917G  179G  692G  21% /mnt/data0
/dev/sda5       892G  137G  710G  17% /home

Using the Disk Usage Analyzer, I again see that / is 100% full, with 54% in /mnt and 43% in /home. I have a few questions:

*

*I have a RAID 1 array mounted at /mnt/data0. Why does this disk usage show up within /?

*I have deleted 10s of GB of unnecessary files from /home with seemingly no affect on the disk usage percent in / (it still says 100% usage). Is there somewhere else I should be looking to delete files?

A: /home is on a different filesystem (last line of your df command output) and /mnt/data0 doesn't show up within / but as 21% full.
In order to get your system back to work, you need to free space on the / filesystem only, where also your /root directory is located.
Best thing is to check, where all the space has gone with the du -s command:
I.e.:
cd /
du -s *

Then cd to the directory with the largest number in front and type:
du -s *

And so on. At some point you will find some large files and may choose to remove them to free up space.


text:
Q: ActiveDirectoryMembershipProvider and SqlRoleProvider: Maintenance? In a new project, I'm planning to use ActiveDirectoryMembershipProvider and SqlRoleProvider to provide authentication and authorization, respectively.
One thing that isn't clear to me is how maintenance is handled -- when users that have logged in and been assigned roles are removed from Active Directory, how do you remove orphaned records in the mapping table used by SqlRoleProvider?  I believe this is the aspnet_UsersInRoles table.
One could query Active Directory periodically for disabled users, then iterating through that list calling Roles.RemoveUserFromRoles(UserId, Roles.GetRolesForUser(UserId)) where UserId is also in aspnet_UsersInRoles.  Hugely slow, I would imagine, for a large organization.
Or, alternatively, for each distint UserId in UsersInRoles, query ActiveDirectory and ensure the userAccountControl attribute's bitmask doesn't indicate the account is disabled. Also very inefficient, for a large number of application users.
An even more ugly but much more efficient approach would be to store last login date and periodically purge role associations for users that haven't logged in for, say, six months.  This might cause headaches.
I'd love to hear suggestions.

A: Yes, you have to manually do the cleanup.  Do you need instantaneous update?  If you can do a batch process that runs nightly, that would be efficient since it isn't running during core operational hours.  Or, it might make sense to kick off a process in another thread to handle the deletion of the role as soon as you are aware of it.  Removing roles per user access shares the hit across users and makes them think that the application is slow.
How many times are roles removed?  If a lot, then consider a batch process, if once in a few years, then it probably isn't as much of an issue to work it into the application during some process.
As far as how too, you can use the API, but the aspnet_UsersInRoles and aspnet_roles tables could be easily wiped on their own accord too via SQL Script.
HTH.


text:
Q: NgFor only supports binding to Iterables such as Arrays. (IONIC4) Hi friends i have a problem in my code :
its showed the error : (ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.)
i wanted to show the doc from firestore that id i passed it from another page .
my code :
detail.page.ts
export class DetailsPage implements OnInit {
  id: string;

  news2: any;

  constructor(private router: ActivatedRoute, private afs: AngularFirestore) {

   }

  ngOnInit() {
    this.id = this.router.snapshot.paramMap.get('id');
    console.log(this.id);
   this.news2 = this.afs.collection('123').doc(this.id).snapshotChanges()
.subscribe(data => {
console.log(data);
});
}

details.page.html
<ion-content padding *ngFor="let hero of news2">
 {{hero.title}}

</ion-content>

A: Angular purposefully does not support iteration over object properties with *ngFor, because there's no ordering contract like arrays have - which means that the ordering of the list might be inconsistent in the view rendering. I would suggest modifying your AngularFirestone API to return an Array as news2 instead of an object, in order to provide a guaranteed ordering contract.

A: You can use the keyvalue pipe

Object key: {{pair.key}}

Object value: {{pair.value}}


text:
Q: access value of a trait such as Directory I am doing simple file I/O. I have a Directory trait SaveDir and a File trait SaveFile. How to i access the directory path entered in the GUI, or the default? e.g., i would like to print it out, as in the following example.
Do i use get_value, e.g., SaveDir.get_value? I can't figure it out...
Once I can access the value, I want to make a path string to i can open the file for writing, e.g. self.writefile = open(path,'w').
THanks,
Cosmo
class ControlPanel(HasTraits):
    SaveFile = Str("MyDAta")
    SaveDir = Directory("C:/My Documents/Data")

    view = View(Item('SaveFile',label='Save Filename',style='simple'),Item('SaveDir',label='Data Directory', style='simple'))

    print SaveDir

A: You need to create an instance of the class, then call configure_traits on it. You could then inspect its SaveDir trait. Typically you would create a change notification method and/or a button.
Please see the materials referenced here:
https://support.enthought.com/entries/22878645-Introductory-materials-for-Traits-and-Traits-UI
Then, I suggest that you start with a class that just has strings and integers, and learn how to use these. You will then be able to extend this to Directory if you like (though for real-world programs, the Directory trait is fairly inflexible, and other ways are often preferable.)
Update: You can find many useful examples in the Examples/traitsui-4.2.0 subdirectory of your Canopy User Python directory.
Update 2: For more useful file selection dialogs, see the pyface package, in particular:
https://github.com/enthought/pyface/blob/master/pyface/i_file_dialog.py

A: Following @Jon (I think this is what he meant), it is possible to access the directory as a string inside a method in the class. In particular, inside the method of a button works.
I am not clear about this, but it seams that invoking the method also creates the instance self of the the class ControlPanel. Is this correct?
class ControlPanel(HasTraits):
    SaveFile = Str("MyDAta")
    SaveDir = Directory("C:/My Documents/Data")
    start = Button("Start Measurements")

    view = View(Item('SaveFile',label='Save Filename',style='simple'),
                Item('SaveDir',label='Data Directory', style='simple'),
                UItem('start',style='custom'))

    def _start_fired(self):
        print self.SaveDir

Prints:
C:/My Documents/Data


text:
Q: Correct use of :disabled option for text_field in Rails 2.3? I've just updated to Rails 2.3.2 from Rails 2.1 and noticed an issue with regards to using the :disabled option on input fields.
Previously we were using this option as a boolean, so we would indicate whether or not we wanted to disable the fields based on a method on the object, e.g.
f.text_field :amount, :disabled => @my_object.is_disabled?, :class => 'my_class'

This works fine in Rails 2.1 -- if is_disabled? returns true, the form field is disabled, otherwise it's not.
In Rails 2.3 however, this isn't the case.  The form field is disabled regardless of the value of :disabled.
Does this mean I'll have to put an if statement around my f.text_field declaration such as:
<% if @my_object.is_disabled? %>
  <%= f.text_field :amount, :disabled => 'disabled', :class => 'my_class' %>
<% else %>
  <%= f.text_field :amount, :class => 'my_class' %>
<% end %>

Surely I'm missing something here?

A: They got rid of is_boolean_field? in rails 2.3. It is just boolean_field? now.
so:
f.text_field :amount, :disabled => @my_object.disabled?, :class => 'my_class'

should work fine.

A: Please ignore this thread.  The issue I was having was actually with Javascript.
Adding :disabled => false adds "disabled=''" to the form field which correctly doesn't disable the form field after all.


text:
Q: How to pass data from child action to layout in ASP.NET MVC I have a view which uses a layout, and also executes a child action.
The layout calls a partial which needs some data from the view's child action. Is there some way to pass the data up from the child action to it's parent view's layout?
I have tried solving this using sections, but it appears that sections can only be rendered in layout views.

A: In the end, I had the child action stuff the required data into the HttpContext. This was then read out by the view containing the child action, which used it to render a section in the layout.
I was concerned that the order of processing of the views would not be predictable (i.e. that I couldn't be sure that the data would be written to the HttpContext before being read from it), but it turns out the order of processing is entirely predictable.

A: In your child action, you can set up the data as data-*** attributes and then use JavaScript (or jQuery) to read them back in your partial.
E.g. child action:
<div id="somedata" data-customerid="123" data-reference="xyz">
</div>

Then in your partial:
<script>
   ....
   var customerId = $("#somedata").data("customerid");
   var reference = $("#somedata").data("reference");
</script>

Hope this helps


text:
Q: Typescript, mongoose toObject returns any interface User {
  _id: GooseTypes.ObjectId;
  email: string;

}

interface UserDoc extends User, Document {
  _id: GooseTypes.ObjectId;
}

const UserSchema = new Schema({
  email: String,
});

const UserModel = model<UserDoc>("User", UserSchema);
const userDocument = new UserModel({email: "test@test.com"}); //returns UserDoc type
const userObject = userDocument.toObject(); // returns any, have to manually cast to User

Currently I'm using @types/mongoose. I want to avoid doing toObject() as User because this introduces place for mistakes.

How can I extend toObject() method to return an object of type User/OtherType?


text:
Q: iOS: How do i prevent temporary files Visibility i am working on a app that generates temporary video from the still image. But i don't want the user to view the temporary file what i have generated. But the moment when the app is generating the video file,the video is listing out by the camera roll.
my Question is How can i generate the temporary media file that could't have access to 'camera roll,iTunes and iCloud'?
please help me. thanks in advance.
Code:
[assetWriter finishWritingWithCompletionHandler:^
     {
         NSURL *url = _outMovieURL; ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
         [library writeVideoAtPathToSavedPhotosAlbum:url
                                     completionBlock:^(NSURL *assetURL, NSError *error)
                                     {
                                         NSLog(@"Done!");
                                     }];
     }];

A: This block:
 [assetWriter finishWritingWithCompletionHandler:^
 {
     NSURL *url = _outMovieURL; ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
     [library writeVideoAtPathToSavedPhotosAlbum:url
                                 completionBlock:^(NSURL *assetURL, NSError *error)
                                 {
                                     NSLog(@"Done!");
                                 }];
 }];

Is to write file in camera roll. So don't use this while you have only created temporary video. Write that temporary video file in documentDirectory instead, (or probably it's already in documentDirectory, while you are creating it, all you need to do is to not write that file in camera roll with this code).

A: You should use NSTemporaryDirectory() and append your own affix at the end for any temporary files. Files in that directory will be cleaned by the OS or you can delete right after you are done with it.


text:
Q: using amChart Annotations and tooltips at the same time We've been using amCharts in our IoT / SCADA software Mango Automation for several years and very happy with it.
I have a requirement to use Annotations on the charts. They want us to save the data for the chart and the annotations to disk so that other users can log in and also see the annotations. I'm curious to know if this is possible? One issue I see is that when in annotation mode there is no way to go back to normal view mode without clearing the annotation. Meaning I would like to use the mouse over tooltips on the chart and see the annotations at the same time.

A: @gerric is correct. It's not possible to have the tooltips and annotations working together.

They want us to save the data for the chart and the annotations to disk so that other users can log in and also see the annotations. I'm curious to know if this is possible?

For this part of your question, please see the snippet with an example in how to get and set the annotation to a chart. Ideally the chart should have fixed dimensions so the annotations stay at the same position when re-used.
Unfortunately when you try to use the buttons in the snippets, you will get an error as I am saving the data in sessionStorage. Take a look at http://codepen.io/team/amcharts/pen/87180663e881a5dc909078b2c17301a5?editors=1010 to see it working. Have in mind you'll need to be in the annotation mode.
Also check the annotation API for information about getAnnotations and setAnnotations.

var chart = AmCharts.makeChart( "chartdiv", {
  "type": "serial",
  "theme": "light",
  "dataProvider": [ {
    "country": "USA",
    "visits": 2025
  }, {
    "country": "China",
    "visits": 1882
  }, {
    "country": "Japan",
    "visits": 1809
  }, {
    "country": "Germany",
    "visits": 1322
  }, {
    "country": "UK",
    "visits": 1122
  }, {
    "country": "France",
    "visits": 1114
  }, {
    "country": "India",
    "visits": 984
  }, {
    "country": "Spain",
    "visits": 711
  }, {
    "country": "Netherlands",
    "visits": 665
  }, {
    "country": "Russia",
    "visits": 580
  }, {
    "country": "South Korea",
    "visits": 443
  }, {
    "country": "Canada",
    "visits": 441
  }, {
    "country": "Brazil",
    "visits": 395
  } ],
  "valueAxes": [ {
    "gridColor": "#FFFFFF",
    "gridAlpha": 0.2,
    "dashLength": 0
  } ],
  "gridAboveGraphs": true,
  "startDuration": 1,
  "graphs": [ {
    "balloonText": "[[category]]: [[value]]",
    "fillAlphas": 0.8,
    "lineAlpha": 0.2,
    "type": "column",
    "valueField": "visits"
  } ],
  "chartCursor": {
    "categoryBalloonEnabled": false,
    "cursorAlpha": 0,
    "zoomable": false
  },
  "categoryField": "country",
  "categoryAxis": {
    "gridPosition": "start",
    "gridAlpha": 0,
    "tickPosition": "start",
    "tickLength": 20,
    "labelRotation": 45
  },
  "export": {
    "enabled": true
  }
} );

$('#copy-annotation-button').on('click', function () {

    var amExport = chart.AmExport;

    amExport.getAnnotations({}, function (data) {
      window.sessionStorage.setItem("annotation", JSON.stringify(data));
    });

});

$('#paste-annotation-button').on('click', function () {

    var amExport = chart.AmExport,
      data = JSON.parse(window.sessionStorage.getItem("annotation"));

    amExport.setAnnotations({
      data: data
    }, function () {
      // Do something
    });
});
#chartdiv {
 width: 700px;
 height: 300px;
 font-family: Arial;
}
<link href="https://www.amcharts.com/lib/3/plugins/export/export.css" rel="stylesheet"/>

<button id="copy-annotation-button">Copy Annotation</button>
<button id="paste-annotation-button">Paste Annotation</button>


text:
Q: How to write unittest for function in Django admin? class SystemUserAdmin(UserAdmin):
    list_display = ('get_phone',)

    def get_phone(self, obj):
        address = obj.cause.address
        return address.phone if address else '-'
    get_phone.short_description = 'Phone'

additional_admin_site.register(User, SystemUserAdmin)

How can to test function get_phone?
Do I need to get instance SystemUserAdmin for User instance?

A: from django.contrib.admin.sites import AdminSite
from django.test import TestCase

from core.admin import SystemUserAdmin
from core.models import User
from core.test.factories import UserFactory

class SystemUserAdminTestCase(TestCase):
    def setUp(self) -> None:
        self.user = UserFactory()

    def test_get_phone(self) -> None:
        user_admin = SystemUserAdmin(model=User, admin_site=AdminSite())
        response = user_admin.get_phone(self.user)
        #...


text:
Q: How to show a splash screen to kill the time while data is loaded? When starting my app I at first have to read in some data, have to init some forms and so on.
For that time the user sees just grey getting-ready to show something forms.
This lasts for a few seconds...
I thought of a Splash Screen that loads the data in a seperate Thread and also shows how long it will take. Or just a status bar?
How would you do something like this?
I'm using C# .NET 3.5 + Winforms

A: See this CodeProject article: A Pretty Good Splash Screen in C#
It implements a splash screen that:

*

*Runs on a separate thread

*Fades in as it appears, and fade out as it disappears

*Displays a running status message that is updated using a static method

*Displays and update a predictive self-calibrating owner-drawn smooth-gradient progress bar

*Displays the number of seconds remaining before load is complete

Here's an example of what it looks like - maybe yours will be prettier.  8-)

A: With WindowsForm, the easier is to use Backgroundworker.
You can disables controls during loading and display a progress bar on startus bar with label as "loading data...".
MSDN link : http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

A: If it only lasts a few seconds then displaying the wait
cursor should be fine. Perhaps it can be arranged that the
main window is shown as quickly as possible and the rest is
started after the first screen update (e.g. using a timer).
This will reduce the perceived start-up time.
In order to reduce the startup time you may also consider
postponing some of startup actions if they are not strictly
necessary. It can be done later in the background using a
timer or on-demand.

A: I recently wrote a similar splash screen using Tom Clements as a basis.  Take a look at My Splash Screen to see if it fits your needs.


text:
Q: Prompt user from bash command substitution I am looking for a one-liner to prompt user for multiple inputs and execute a command using the user inputs as arguments.
The naive approach is:
read -p shirt_size: shirt_size
read -p age: age
the_command some_complicated_arguments $shirt_size $age

Unfortunately it is verbose.
Here is a one-liner that behaves the same:
the_command some_complicated_arguments \
  `>&2 printf shirt_size:; head -n 1` `>&2 printf age:; head -n 1`

Unfortunately it is neither compact nor readable.
I would like it to be as readable as:
the_command some_complicated_arguments \
  `input shirt_size` `input age`

I would prefer the solution to use bash built-in command or programs usually available on Linux environment.

A: Sounds like a homework question to get you to look at functions.  If you had a function like:
input() { read -p "$1:" user_input; echo "$user_input"; }

Then your line:
the_command some_complicated_arguments "$(input shirt_size)" "$(input age)"

Would prompt and print the complete line.  Although this does nothing to check for valid input or no input.


text:
Q: How to step over a linearized 2D-array with a moving window Assuming I have a 4x4 array that's flatted out in row-major order and I want to collect one entry per 2x2 window in a new 1D array, that would result in:
[0, 2, 8, 10]
for 4x8 it would result in
[0, 2, 4, 6, 16, 18, 20, 22]
and for 8x4 it would result in
[0, 2, 8, 10, 16, 18, 24, 26]
simple loop for achieving this:
const int STEP = 2;
for(int i = 0; i < len; ++i)
  arr[i] =  i * STEP + (i*STEP / SIZE_Y) * SIZE_Y;

I run into problems when the array size is odd on either dimension though.
3x3 should result in
[0, 2, 6, 8] but does in [0, 2, 7, 12]
How do I have to extend my formula so it doesn't get overly complicated treating all these boundary-cases but still works for the general case?

A: I used nested loops and it worked perfectly, and it's much easier to understand:
    int width, height;
    width = (int) ceil((double)SIZE_Y/STEP);
    height = (int) ceil((double)SIZE_X/STEP);
    int[] arr = new int[width*height];
    for(int i=0; i < height; i ++){
        for(int j=0; j < width; j ++){
            arr[i*width+j] = STEP*i*SIZE_Y + STEP*j;
        }
    }

However if you still insist on using a single loop -less readable- you can use this single loop instead:
for(int i=0; i<width*height; i++)
    {
        arr[i] = (i%width)*STEP + (i/width)*SIZE_Y*STEP;
    }


text:
Q: Creating triggers using embedded mysql C++ I am working with the libmysqld c library in a C++ application on windows in order to interface with an embedded mysql server i.e. a mysql server that is online for the lifetime of the process that embeds it.  The application that creates the database uses a mysql .ini file for creating the datadir relative to the application directory instead of in the global mysql install folder e.g.
[libmysqld_server]
basedir=./
datadir=./Database

I can programatically create a trigger with no problem e.g.
status = mysql_query(mysql,
        "CREATE TRIGGER del_trigger AFTER DELETE ON table FOR EACH ROW\
        INSERT INTO otherTable (col1, col2) VALUES (OLD.col1, OLD.col2)\
        ");

    if (status == 0) {
        Log(DEBUG, "Initialize():  <%p> Delete Trigger creation passed ...", this);
    }
    else {
        Log(DEBUG, "Initialize():  <%p> Delete Trigger creation failed with error %s...", this, mysql_error(mysql));
    }

The problem I run into however is that when the trigger gets called, mysql will complain that the mysql.proc table does not exist because I do not have a mysql database inside my application specific datadir.  I have tried copying the mysql folder from the installation directory in C:\Program Files\MySQL... but then I run into issues where mysql reports
Error:Cannot load from mysql.proc. The table is probably corrupted

The only advice I have seen related to the above error is to run the 'mysql_upgrade' command which does not seem to work for the case of an embedded database using its own datadir.  I'm at the point where all of the tables are created and their respective triggers are setup but just can't get around this mysql.proc error.
UPDATE:
I am also seeing some inconsistent behavior here.  My version of MySQL is "mysql-5.5.16-win32" and it comes with a mysql_embedded.exe binary that I can use to open up a console and point to the database files generated by my application when it isn't running.  When I perform operations in the mysql_embedded.exe, the triggers work without issue (no 'mysql.proc is probably corrupted' errors).  So it seems like only the libmysqld c api is having an issue with the mysql system tables.

A: The solution was as simple as verifying that the "mysql" database was the same version as mysql version embedded in libmysqld.  I verified my client version info via the following:
const char * version = mysql_get_client_info();

This returned "5.1.44" instead of the "5.5.16" that I was expecting.  Downloading the mysql ZIP archive for 5.1.44 and using the mysql database in the datadir fixed the issue that I was experiencing.


text:
Q: Converting image to Jpeg2000 does not work I try to convert an image to Jpeg2000:
convert example2.png -quality 95 example.jp2

But the output is still png:
file example.jp2
example.jp2: PNG image data, 2549 x 3507, 8-bit/color RGB, non-interlaced

What am I doing wrong?
convert -version
Version: ImageMagick 6.8.9-9 Q16 x86_64 2016-11-29 http://www.imagemagick.org

A: What am I doing wrong?
Nothing.  The command you typed in is correct.  The problem is that *.jp2 (JPEG 2000) support isn't built into the repository version of Imagemagick.  When converting to an unsupported format the resulting destination file will be the same format as the source file.
You can verify this by looking at the fourth lines of the convert -version output:
$ convert -version

Output:
Version: ImageMagick 6.8.9-9 Q16 x86_64 2016-11-29 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2014 ImageMagick Studio LLC
Features: DPC Modules OpenMP
Delegates: bzlib cairo djvu fftw fontconfig freetype jbig jng jpeg lcms lqr ltdl lzma openexr pangocairo png rsvg tiff wmf x xml zlib

Notice that jp2 isn't included.
This is a reported bug (imagemagick: missing JPEG-2000 support):
The bug report describes the problem and indicates it has been fixed in the latest release (Version 6.9.1.2-1)  which hasn't reached the repository yet.
Another test for jp2 support is:
$ identify -list format | egrep -i jp2

There is a use at your own risk PPA at:
https://launchpad.net/~isage-dna/+archive/ubuntu/imagick
Update:
As provided by SamWilson in the commands a supported PPA which I tested is located at: https://launchpad.net/~lyrasis/+archive/ubuntu/imagemagick-jp2
sudo add-apt-repository ppa:lyrasis/imagemagick-jp2
sudo apt-get update

A: Try this
convert example2.png -quality 0 example.jp2

A: This is still an issue as of February 2021. AFAIK JPEG 2000 support is disabled in Ubuntu due to a perceived risk of submarine patents.
However, there is a workaround that doesn't involve using third-party PPAs or compiling software yourself. The libopenjp2-tools package contains a decoding tool called opj_decompress that is able to convert .jp2 files into various lossless formats, including PNG, BMP, TIF, and RAW. It can even convert entire directories of files without the aid of external tools.
Convert a single file to TIF:
opj_decompress -i input.jp2 -o output.tif

Convert a directory of files to TIF:
opj_decompress -ImgDir my_jp2_images/ -OutFor TIF

Unfortunately, the native directory conversion isn't very fast due to it not being multithreaded. I've had to work on a large number of JPEG 2000 files over the years, and I've begun to use GNU Parallel to speed up the conversion process by using all the available CPU threads.
Converting all .jp2 files in a directory to .tif (need to be cd'd to the directory containing the files):
ls *.jp2 |parallel -j 10 --nice 19 --bar --will-cite "opj_decompress -i {} -o {}.tif"

Change the value of -j to however many threads want to use.
These files are very large since they don't use compression of any kind, so if you need to transfer them over a network or intend to store the them long-term, you might want to reduce their size by applying LZW compression:
ls *.tif |parallel -j 10 --nice 19 --bar --will-cite "mogrify -compress lzw {}"

In my experience, this can reduce file size by up to 50%.


text:
Q: Postgresql trigger row not affected I have try to make a trigger on a table call product. After inserting a product i get an error, that "NEW" variable  is not affected yet.
Here is the trigger and user-defind function :
CREATE OR REPLACE FUNCTION updateProduitQteInitiale() RETURNS TRIGGER AS $example_table$
    BEGIN
       IF (TG_OP = 'INSERT' OR TG_OP = 'UPDATE') THEN
       UPDATE produit set qtestock= NEW.qteinitial where produit.pid = NEW.pid ;
       return NEW ;
      END IF;
      RETURN NULL;
    END;
$example_table$ LANGUAGE plpgsql;

And here is the trigger:
CREATE TRIGGER qteInitialTrigger AFTER INSERT OR UPDATE  ON produit
FOR EACH ROW EXECUTE PROCEDURE updateProduitQteInitiale();

A: Is pid your primary id? Not sure what you want to do but I assume you want to set to the column qtestock value from column qteinitial (on the same row!). If I guessed it right then you can do this:
CREATE OR REPLACE FUNCTION updateProduitQteInitiale() RETURNS TRIGGER AS $example_table$
BEGIN
  NEW.qtestock = NEW.qteinitial;
  return NEW;
END;
$example_table$ LANGUAGE plpgsql;

CREATE TRIGGER qteInitialTrigger BEFORE INSERT OR UPDATE  ON produit
FOR EACH ROW EXECUTE PROCEDURE updateProduitQteInitiale();


text:
Q: Cant open/explore any folders after win7 to win8 upgrade I just upgraded from Windows 7 professional (32 bit) to Windows 8 pro (32 bit). But with the new OS, I can't anymore open folders on my disks by double clicking in explorer window or by right click - select open.
When I try to do so, all open folder windows just close, but all other programs just continue running(probably explorer restarts).
Another problem is that I'm not able to start any program with admin privileges.
What  is causing this & how to solve this ?
Edit:
Everything works fine in safe mode though.

A: It may be a long shot, but it is possible you had some weird folder permissions under Windows 7 which got messed up during the update.
Given your current situation, try taking ownership of a folder or two and see if it lets you into them.
If you aren't familiar with how to do that, read through this guide (there is a few steps to it.)
If taking ownership allows you to get into your folders again, I strongly recommend taking ownership of the folders with your files inside, backing them up and then performing a clean install of Windows 8 to avoid any other weird hiccups down the road.

A: I fixed this problem by just creating a new User account with admin privileges, remove my old user account that was moved from win 7 to win 8,  using safe mode & finally everything now works fine using the new user account.


text:
Q: Why won't my displayAll() method print the values stored in the ArrayList? Why does it come out with Null's and 0's? I've been working on creating a GUI to store details of gadgets such as Mobiles and MP3's. After storing some objects of these gadgets into the Array List and then hitting the displayAll() button, it does not display the values of them but rather Nulls and 0's.
I have tried everything to the point of giving up.
Just below you will find the GUI class and then the Gadget Superclass and Mobile Subclass.
import java.util.ArrayList;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GadgetShop implements ActionListener
{
    // instance variables - replace the example below with your own
    private JTextField modelTextField;
    private JTextField priceTextField;
    private JTextField weightTextField;
    private JTextField sizeTextField;
    private JTextField initialCreditTextField;
    private JTextField initialMemoryTextField;
    private JTextField phoneNumberTextField;
    private JTextField durationTextField;
    private JTextField downloadSizeTextField;
    private JTextField displayNumberTextField;
    private JButton addMobileButton;
    private JButton addMp3Button;
    private JButton clearButton;
    private JButton displayAllButton;
    private JButton makeCallButton;
    private JButton downloadMusicButton;
    private JLabel modelLabel;
    private JLabel priceLabel;
    private JLabel weightLabel;
    private JLabel sizeLabel;
    private JLabel creditLabel;
    private JLabel memoryLabel;
    private JLabel phoneNumLabel;
    private JLabel durationLabel;
    private JLabel downloadLabel;
    private JLabel dispNumLabel;
    private JFrame frame;
    private ArrayList<Gadget> gadgets;
    private int myCredit;
    private String theModel;
    private String theSize;
    private int theWeight;
    private double thePrice;
    private int theMemory;

    /**
     * The GUI is created in the constructor.
     */
    public GadgetShop()
    {
        // initialise instance variables

        gadgets = new ArrayList<Gadget>();

        frame = new JFrame("The Gadget Shop");
        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new GridLayout(7, 4));

        JLabel modelLabel = new JLabel("Model:");
        contentPane.add(modelLabel);

        JLabel priceLabel = new JLabel("Price:");
        contentPane.add(priceLabel);

        JLabel weightLabel = new JLabel("Weight:");
        contentPane.add(weightLabel);

        JLabel sizeLabel = new JLabel("Size:");
        contentPane.add(sizeLabel);

        modelTextField = new JTextField(15);
        contentPane.add(modelTextField);

        priceTextField = new JTextField(15);
        contentPane.add(priceTextField);

        weightTextField = new JTextField(15);
        contentPane.add(weightTextField);

        sizeTextField = new JTextField(15);
        contentPane.add(sizeTextField);

        JLabel creditLabel = new JLabel("Credit:");
        contentPane.add(creditLabel);

        JLabel memoryLabel = new JLabel("Memory:");
        contentPane.add(memoryLabel);

        addMobileButton = new JButton("Add Mobile");
        contentPane.add(addMobileButton);
        addMobileButton.addActionListener(this);

        addMp3Button = new JButton("Add MP3");
        contentPane.add(addMp3Button);
        addMp3Button.addActionListener(this);

        initialCreditTextField = new JTextField(15);
        contentPane.add(initialCreditTextField);

        initialMemoryTextField = new JTextField(15);
        contentPane.add(initialMemoryTextField);

        clearButton = new JButton("Clear");
        contentPane.add(clearButton);
        clearButton.addActionListener(this);

        displayAllButton = new JButton("Display All");
        contentPane.add(displayAllButton);
        displayAllButton.addActionListener(this);

        JLabel phoneNumLabel = new JLabel("Phone No:");
        contentPane.add(phoneNumLabel);

        JLabel durationLabel = new JLabel("Duration:");
        contentPane.add(durationLabel);

        JLabel downloadLabel = new JLabel("Download:");
        contentPane.add(downloadLabel);

        JLabel dispNumLabel = new JLabel("Display Number:");
        contentPane.add(dispNumLabel);

        phoneNumberTextField = new JTextField(15);
        contentPane.add(phoneNumberTextField);

        durationTextField = new JTextField(15);
        contentPane.add(durationTextField);

        downloadSizeTextField = new JTextField(15);
        contentPane.add(downloadSizeTextField);

        displayNumberTextField = new JTextField(15);
        contentPane.add(displayNumberTextField);

        makeCallButton = new JButton("Make A Call");
        contentPane.add(makeCallButton);
        makeCallButton.addActionListener(this);

        downloadMusicButton = new JButton("Download Music");
        contentPane.add(downloadMusicButton);
        downloadMusicButton.addActionListener(this);

        frame.pack();
        frame.setVisible(true);
    }

    /**
     * The main method allows the program to be run without BlueJ.
     */
    public static void main(String[] args)
    {
        GadgetShop calculator = new GadgetShop();
    }

    /**
     * Find which button triggered the event and call the appropriate method.
     */
    public void actionPerformed(ActionEvent event)
    {
        String command = event.getActionCommand();
        if (command.equals("Add Mobile")) {
            addMobile();
        }
        if (command.equals("Add MP3")) {
            addMp3();
        }
        if (command.equals("Display All")) {
            displayAll();
        }
        if (command.equals("Make A Call")) {
            makeCall();
        }
        if (command.equals("Download Music")) {
            downloadMusic();
        }
        if (command.equals("Clear")) {
            clear();
        }
    }

    public String getModel()
    {
        String model
           = modelTextField.getText();
        return model;
    }

    public String getSize()
    {
        String size
           = sizeTextField.getText();
        return size;
    }

    public String getNumber()
    {
        String phoneNumber
           = phoneNumberTextField.getText();
        return phoneNumber;
    }

    public int getWeight()
    {
        int weight
           = Integer.parseInt(weightTextField.getText());
        return weight;
    }

    public double getPrice()
    {
        double price
           = Double.parseDouble(priceTextField.getText());
        return price;
    }

    public int getCredit()
    {
        int credit
           = Integer.parseInt(initialCreditTextField.getText());
        return credit;
    }

    public int getMemory()
    {
        int memory
           = Integer.parseInt(initialMemoryTextField.getText());
        return memory;
    }

    public int getDuration()
    {
        int duration
           = Integer.parseInt(durationTextField.getText());
        return duration;
    }

    public int getDownloadSize()
    {
        int downloadSize
           = Integer.parseInt(downloadSizeTextField.getText());
        return downloadSize;
    }

    public int numberOfGadgets()
    {
        return gadgets.size();
    }

    public int getDisplayNumber()
    {
        int displayNumber = -1;

        try {
            displayNumber
              = Integer.parseInt(displayNumberTextField.getText());
            if(displayNumber < 0) {
                JOptionPane.showMessageDialog(frame,
                   "Please enter a positive number");
            }
            else if(displayNumber > numberOfGadgets()) {
                JOptionPane.showMessageDialog(frame,
                   "Please enter a number in the correct range");
            }
        }
        catch(NumberFormatException exception) {
        }
        return displayNumber;
    }

Below are the methods to create, store and display the objects in to the ArrayList
    public void addMobile()
    {
        Mobile mobile = new Mobile(myCredit, theModel, theSize, theWeight, thePrice);
        gadgets.add(mobile);
    }

    public void addMp3()
    {
        Gadget mp3 = new MP3(theMemory, theModel, theSize, theWeight, thePrice);
        gadgets.add(mp3);
    }

    public void displayAll()
    {
        for(Gadget gadget : gadgets) {
            gadget.print();
            System.out.println();   // empty line between items
        }
    }

    public void makeCall()
    {
        //Nothing here atm
    }

    public void downloadMusic()
    {
        //Nothing here atm
    }

    public void clear()
    {
        modelTextField.setText("");
        sizeTextField.setText("");
        phoneNumberTextField.setText("");
        weightTextField.setText("");
        priceTextField.setText("");
        initialCreditTextField.setText("");
        initialMemoryTextField.setText("");
        durationTextField.setText("");
        downloadSizeTextField.setText("");
        displayNumberTextField.setText("");
    }
}

Below is the Mobile subclass
public class Mobile extends Gadget
{
    // instance variables - replace the example below with your own
    private int credit;

    /**
     * Constructor for objects of class Mobile
     */
    public Mobile(int myCredit, String theModel, String theSize, int theWeight, double thePrice)
    {
        // initialise instance variables
        super(theModel, theSize, theWeight, thePrice);
        credit = myCredit;
    }

    /**
     * This is an accessor method that allows the user to view the balance of credit remaining in the mobile phone.
     */
    public int getCredit()
    {
        return credit;
    }

    /**
     * This is a mutator method that allows the user to top up the credit on their mobile phone.
     */
    public void addCredit(int topUp)
    {
        if (topUp > 0) {
            credit = credit + topUp;
        }
        else {
            System.out.println("Please enter an amount greater than 0.");
        }
    }

    /**
     * This is a mutator method that allows the user to enter the phone number that they'd like to call and the duration of that call in minutes.
     */
    public void makeCall(String number, int minutes)
    {
        if (credit >= minutes) {
            System.out.println("You called this number: " + number + " for the duration of: " + minutes + " minute/s.");
            credit = credit - minutes;
            System.out.println(" ");
            System.out.println("You now have " + credit + " minutes of calling credit remaining in your balance.");
        }
        else {
            System.out.println("Sorry, but you have an insufficient amount of credit to make this call.");
        }
    }

    /**
     * This output method displays certain specifications of the mobile device such as the: Model, size, weight and price. The amount of credit remaining in the mobile is also displayed.
     */
    public void print()
    {
        super.print();
        System.out.println("You have " + credit + " minutes of credit remaining.");
    }
}

Below is the Gadget Superclass
public class Gadget
{
    // instance variables
    private String model;
    private String size;
    private int weight;
    private double price;

    /**
     * Constructor for objects of class Gadget
     */
    public Gadget(String theModel, String theSize, int theWeight, double thePrice)
    {
        // initialised instance variables
        model = theModel;
        size = theSize;
        weight = theWeight;
        price = thePrice;
    }

    /**
     * This is an accessor method that returns the model number of the gadget.
     */
    public String getModel()
    {
        return model;
    }

    /**
     * This is an accessor method that returns the size of the gadget.
     */
    public String getSize()
    {
        return size;
    }

    /**
     * This is an accessor method that returns the weight of the gadget.
     */
    public int getWeight()
    {
        return weight;
    }

    /**
     * This is an accessor method that returns the price of the gadget.
     */
    public double getPrice()
    {
        return price;
    }

    /**
     * This is an output method that displays the model, size, weight and price of an object to the user.
     */
    public void print()
    {
        System.out.println("Model: " + model);
        System.out.println("Size: " + size);
        System.out.println("Weight: " + weight);
        System.out.println("Price: " + price);
    }
}

I would very much appreciate all the help that I can get just to display the details correctly. Thanks.

A: You have made one major mistake in your code. According to your code addMobile method must be
public void addMobile()
{
    Mobile mobile = new Mobile(getCredit(), getModel(), getSize(), getWeight(), getPrice());
    gadgets.add(mobile);
}

The values for myCredit,theModel,theSize,theWeight,thePrice,theMemory are never assigned anywhere in your code. Various get methods have been written to get the values form the TextFields, but the methods have never been called.
The same goes for addMP3 method too. Make sure you call the constructor for Mobile and MP3 with proper values. There is nothing wrong with the rest of your code.


text:
Q: Is it necessary to declare the datatype for a Double Pointer (a Pointer to a Pointer) if we are sure that we would not dereference it twice? I was studying linked lists, and I had this question: Why would we need to declare the datatype for a double pointer? I think that, if you dereference such pointer (say dptr (a pointer to a pointer) ), you'd get a pointer to insert_datatype. Now if I were to just change this value, that is just changing where the dptr points to. And hence when I dereference this double pointer twice, I would still be dereferencing a structure (in my below code). So is it really necessary to declare the datatype for double pointers if we are using them to only dereference once? I can see why we would need to know the datatype while dereferencing the dptr twice, as *dptr would give us a pointer to insert_datatype, and when I do **dptr, it would be needed to know what is the datatype *dptr is pointing to.
#include "stdio.h"
#include "stdlib.h"
typedef struct Node{
    int data;
    struct Node* next;
}Node;

void addAtBeg(int**, int);

int main(){
    int a;
    Node* head=NULL;
    printf("Enter data:\n");
    scanf("%d",&a);
    addAtBeg(&head,a);
    printf("%#x\n",head);
    printf("%d\n",(*head).data);
    return 0;
}

void addAtBeg(int** head, int a){
    Node* p;
    p=(Node *) malloc(sizeof(Node));
    p->data=a;
    p->next=*head;
    *head=p;
}

I also can seem to just declare a long long int* head as the parameter receiving the &head in the addAtBeg, and it just works fine, as *head=p would just fetch 8 bytes, and write the memory address at that location.
So, are these both behaviors UB or are valid syntaxes?

A: Pointers to different types don't necessarily have the same representation.  On most systems you're likely to come across this will be the case, but it's not true in general.
While it is legal to convert an object pointer of one type to an object pointer to another type and back, it is not allowed to dereference the converted pointer except in a few cases which don't apply here.
So this:
*head=p;

Triggers undefined behavior.

A: Using either int** head or long long int* head in addAtBeg's prototype is undefined behavior (specifically, the moment you do *head = p;, assigning a Node* to something that is thought to be a non-Node*). long long int* head is worse, in that it's far more likely to trigger a size mismatch (e.g. on 32 bit systems, the Node* you're dereferencing to will typically be 32 bits, while long long int is 64 bits, so the assignment would overwrite four bytes from neighboring value(s) on the stack). Both will probably work just fine (assuming you disable/ignore all warnings) up until the point where it turns out sizeof(long long int) != sizeof(Node*) or (less commonly) sizeof(int*) != sizeof(Node*).
The real question is why you would do this? You still need to pass &head (that's unavoidable, head needs to be reassigned by the callee). There's no performance benefit. Since you're passing by pointer, you don't need the definition of Node, just a forward declaration if the declaration/definition isn't in that file. The function is replacing the pointer entirely, and is clearly aware it's working with a Node, so no information hiding or implementation details are being hidden from anyone. So what are you getting out of violating the type system?


text:
Q: Reading lines from c file and putting the int into an array(prev line has a integer that's the size of next line having different integers We need to make an integer array from a file such a way that the upper line of file would be size and the next line of numbers would be in an array having size of upper line integer value.
We read integers from the file.
I am trying to solve by using a counter in a while loop that increments if we move to next line. odd number lines(1,3,5,7..) have only one integer which is size for an array and even number lines(2,4,6,8...) will have numbers intended to be in an array.
Now, when counter is odd(when 1) its looking on first line in file. This will determins the size of an array which numbers are in the 2nd line.
Example if a file has
 3        //(line1) count=1(odd) -this case-> array size found is 3
 5 6 2    //(line2) count=2(even) -this case-> array of size 3 is made
 5        //(line4) count=3(odd) -this case-> array size found is 5
 3 5 7 1 6 //(line4) count=4(even) -this case-> array of size 5 is made

3 will be used as a key to allocate the array of size 3 for [5 6 2]
then,
5 will be used as a key to allocate the array of size 3 for [3 5 7 1 6]

int main()
{
    int count=1;
    FILE* file = fopen("file.txt", "r");

    int num ,i, element;
    while (!feof (file) && num > 0){
        if (count%2==0){
            fscanf (file, "%d", &num);
        }
        else{
            int *arr = (int *)malloc(num*(sizeof(int)));

            fscanf (file, "%1d", &element);

            arr[i] = element;

            free(arr);

        }
        count++;
    }
    fclose (file);

    return 0;
}

I don't know how should i use the (count) to find the number of line we are iterating in a file.


text:
Q: Entity Framework with many-to-many deleting I'm trying to wrap my head around Entity Framework 4. This is probably an easy question ;)
I have the following entities: Article, Comment and Picture. Articles have a one-to-many association with Comments. Articles have also a many-to-many relationship with Pictures.
My question is what would be the proper approach to deleting an Article that has Comments and Pictures. Mind you there are the following scenarios:

*

*Article has neither Comments, nor Pictures associated.

*Article has Comments but no Pictures.

*Article has Comments and Pictures that aren't shared with other Articles.

*Article has Comments and Pictures that are shared with other Articles. (Only Pictures can be shared, the comments are exclusive).

I've already noticed that just executing:
_db.DeleteObject(art);

does not work and I have to first delete the Comments and the Pictures in advance. Also if the Picture is shared, I only wanted to delete the association to the particular Article not all the associations.
I'm sure there is easier way to achieve this - is there like a "cascade delete" that would take care of this scenario?
I appreciate your help!

A: Yes, there is on delete cascade but not in the entity framework. However you can just put them on your foreign keys to your many-to-many link tables.


text:
Q: Running a Google Sheets App script function from an HTML page with form values returned I'm trying to return the values that a user enters into a form on a webpage in a google app script to a function and then notify the user with a response.
Here is my app script
function onOpen() {
   openLogin();
   SpreadsheetApp.getUi()
     .createMenu('Dialog')
     .addItem('Open', 'openLogin')
     .addToUi()
}

function openLogin() {
   var html = HtmlService.createHtmlOutputFromFile('index');
   SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
       .showModalDialog(html, 'Login Form');
}

function checkLogin() {
   SpreadsheetApp.getUi().alert('Hello, world!');
}

I'm trying to get checkLogin to fire off. Here is the HTML code.
<!DOCTYPE html>

   <base target="_top">

  <form>
    First name:
    <input type="text" name="user_name">

    Last name:
    <input type="password" name="user_password">

    Staff or Student?

    <input type="radio" name="staff" value="staff" checked> Staff

    <input type="radio" name="student" value="student"> Student

    <input type="button" value="OK"
    onclick="google.script.host.close()" />

    <input type="button" value="Close"
    onclick="google.script.run.checkLogin()" />

  </form>

A: My mistake,
I had the OK and Close function calls mixed up. It should have been
<input type="button" value="OK"
onclick="google.script.run.checkLogin()" />

<input type="button" value="Close"
onclick="google.script.host.close()" />


text:
Q: UITableViewCell animate height issue in iOS 10 My UITableViewCell will animate it's height when recognizing a tap. In iOS 9 and below this animation is smooth and works without issues. In iOS 10 beta there's a jarring jump during the animation. Is there a way to fix this?
Here is a basic example of the code.
- (void)cellTapped {
    [self.tableView beginUpdates];
    [self.tableView endUpdates];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.shouldExpandCell ? 200.0f : 100.0f;
}

EDIT: 9/8/16
The issue still exists in the GM. After more debugging I have discovered the issue is related to the cell immediately jumping to the new height and then will animate the relevant cells offset. This means any CGRect based animation which is dependent on the cells bottom will not work.
For instance if I have a view constrained to the cells bottom, it will jump. The solution would involve a constraint to the top with a dynamic constant. Or think of another way to position your views other then related to the bottom.

A: Better Solution:
The issue is when the UITableView changes the height of a cell, most likely from -beginUpdates and -endUpdates. Prior to iOS 10 an animation on the cell would take place for both the size and the origin. Now, in iOS 10 GM, the cell will immediately change to the new height and then will animate to the correct offset.
The solution is pretty simple with constraints. Create a guide constraint which will update it's height and have the other views which need to be constrained to the bottom of the cell, now constrained to this guide.
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        UIView *heightGuide = [[UIView alloc] init];
        heightGuide.translatesAutoresizingMaskIntoConstraints = NO;
        [self.contentView addSubview:heightGuide];
        [heightGuide addConstraint:({
            self.heightGuideConstraint = [NSLayoutConstraint constraintWithItem:heightGuide attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:0.0f];
        })];
        [self.contentView addConstraint:({
            [NSLayoutConstraint constraintWithItem:heightGuide attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f];
        })];

        UIView *anotherView = [[UIView alloc] init];
        anotherView.translatesAutoresizingMaskIntoConstraints = NO;
        anotherView.backgroundColor = [UIColor redColor];
        [self.contentView addSubview:anotherView];
        [anotherView addConstraint:({
            [NSLayoutConstraint constraintWithItem:anotherView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:20.0f];
        })];
        [self.contentView addConstraint:({
            [NSLayoutConstraint constraintWithItem:anotherView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeLeft multiplier:1.0f constant:0.0f];
        })];
        [self.contentView addConstraint:({
            // This is our constraint that used to be attached to self.contentView
            [NSLayoutConstraint constraintWithItem:anotherView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:heightGuide attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.0f];
        })];
        [self.contentView addConstraint:({
            [NSLayoutConstraint constraintWithItem:anotherView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeRight multiplier:1.0f constant:0.0f];
        })];
    }
    return self;
}

Then update the guides height when needed.
- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];

    if (self.window) {
        [UIView animateWithDuration:0.3 animations:^{
            self.heightGuideConstraint.constant = frame.size.height;
            [self.contentView layoutIfNeeded];
        }];

    } else {
        self.heightGuideConstraint.constant = frame.size.height;
    }
}

Note that putting the update guide in -setFrame: might not be the best place. As of now I have only built this demo code to create a solution. Once I finish updating my code with the final solution, if I find a better place to put it I will edit.
Original Answer:
With the iOS 10 beta nearing completion, hopefully this issue will be resolved in the next release. There's also an open bug report.

*

*https://openradar.appspot.com/27679031

*https://forums.developer.apple.com/thread/53602
My solution involves dropping to the layer's CAAnimation. This will detect the change in height and automatically animate, just like using a CALayer unlinked to a UIView.
The first step is to adjust what happens when the layer detects a change. This code has to be in the subclass of your view. That view has to be a subview of your tableViewCell.contentView. In the code, we check if the view's layer's actions property has the key of our animation. If not just call super.
- (id<CAAction>)actionForLayer:(CALayer *)layer forKey:(NSString *)event {
    return [layer.actions objectForKey:event] ?: [super actionForLayer:layer forKey:event];
}

Next you want to add the animation to the actions property. You might find this code is best applied after the view is on the window and laid out. Applying it beforehand might lead to an animation as the view moves to the window.
- (void)didMoveToWindow {
    [super didMoveToWindow];

    if (self.window) {
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"bounds"];
        self.layer.actions = @{animation.keyPath:animation};
    }
}

And that's it! No need to apply an animation.duration since the table view's -beginUpdates and -endUpdates overrides it. In general if you use this trick as a hassle-free way of applying animations, you will want to add an animation.duration and maybe also an animation.timingFunction.

A: I don't use auto layout, instead I derive a class from UITableViewCell and use its "layoutSubviews" to set the frames of the subviews programmatically. So I tried to modify cnotethegr8's answer to fit my needs, and I came up with the following.
Reimplement "setFrame" of the cell, set the cell's content height to the cell height and trigger a relayout of the subviews in an animation block:
@interface MyTableViewCell : UITableViewCell
...
@end

@implementation MyTableViewCell

...

- (void) setFrame:(CGRect)frame
{
    [super setFrame:frame];

    if (self.window)
    {
        [UIView animateWithDuration:0.3 animations:^{
            self.contentView.frame = CGRectMake(
                                        self.contentView.frame.origin.x,
                                        self.contentView.frame.origin.y,
                                        self.contentView.frame.size.width,
                                        frame.size.height);
            [self setNeedsLayout];
            [self layoutIfNeeded];
        }];
    }
}

...

@end

That did the trick :)

A: So I had this issue for a UITableViewCell that used layout constraints and a UITableView that used automatic cell heights (UITableViewAutomaticDimension). So I'm not sure how much of this solution will work for you but I'm putting it here as it's closely related.
The main realisation was to lower the priority of the constraints that cause the height change to happen:
self.collapsedConstraint = self.expandingContainer.topAnchor.constraintEqualToAnchor(self.bottomAnchor).priority(UILayoutPriorityDefaultLow)
self.expandedConstraint = self.expandingContainer.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor).priority(UILayoutPriorityDefaultLow)

self.expandedConstraint?.active = self.expanded
self.collapsedConstraint?.active = !self.expanded

Secondly, the way in which I animate the tableview was very specific:
UIView.animateWithDuration(0.3) {

    let tableViewCell = tableView.cellForRowAtIndexPath(viewModel.index) as! MyTableViewCell
    tableViewCell.toggleExpandedConstraints()
    tableView.beginUpdates()
    tableView.endUpdates()
    tableViewCell.layoutIfNeeded()
}

Note that the layoutIfNeeded() had to come AFTER beginUpdates/endUpdates
I think this last part might be helpful to you....

A: The solution for iOS 10 in Swift with AutoLayout :
Put this code in your custom UITableViewCell
override func layoutSubviews() {
    super.layoutSubviews()

    if #available(iOS 10, *) {
        UIView.animateWithDuration(0.3) { self.contentView.layoutIfNeeded() }
    }
}

In Objective-C:
- (void)layoutSubviews
{
    [super layoutSubviews];

    NSOperatingSystemVersion ios10 = (NSOperatingSystemVersion){10, 0, 0};
    if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:ios10]) {
        [UIView animateWithDuration:0.3
                         animations:^{
                             [self.contentView layoutIfNeeded];
                         }];
    }
}

This will animate UITableViewCell change height if you have configured your UITableViewDelegate like below :
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return selectedIndexes.contains(indexPath.row) ? Constants.expandedTableViewCellHeight : Constants.collapsedTableViewCellHeight
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
    tableView.beginUpdates()
    if let index = selectedIndexes.indexOf(indexPath.row) {
        selectedIndexes.removeAtIndex(index)
    } else {
        selectedIndexes.append(indexPath.row)
    }
    tableView.endUpdates()
}

A: Swift 4^
Had the jump issue when I was at the bottom of the table and tried on expanding and collapsing some rows in my tableView. I tried this solution first:
var cellHeights: [IndexPath: CGFloat] = [:]

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cellHeights[indexPath] = cell.frame.size.height
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return cellHeights[indexPath] ?? UITableView.automaticDimension
}

But then, the issue recurred when I try to expand the row, scrolled up, then suddenly collapse the row. So I tried this:
let savedContentOffset = contentOffset

tableView.beginUpdates()
tableView.endUpdates()
tableView.layer.removeAllAnimations()

tableView.setContentOffset(savedContentOffset, animated: false)

This somehow fix it. Try both solutions and see what works for you. Hope this helps.

A: Faced the same issue on iOS 10 (everything was fine on iOS 9), the solution was to provide actual estimatedRowHeight and heightForRow via UITableViewDelegate methods implementation.
Cell's subviews positioned with AutoLayout, so I used UITableViewAutomaticDimension for height calculation (you can try set it as a tableView's rowHeight property).
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {

    CGFloat result = kDefaultTableViewRowHeight;

    if (isAnimatingHeightCellIndexPAth) {
        result = [self precalculatedEstimatedHeight];
    }

    return result;
 }

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

A: Can't comment because of reputation but sam's solution worked for me on IOS  10.
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    EWGDownloadTableViewCell *cell = (EWGDownloadTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];

    if (self.expandedRow == indexPath.row) {
        self.expandedRow = -1;
        [UIView animateWithDuration:0.3 animations:^{
            cell.constraintToAnimate.constant = 51;
            [tableView beginUpdates];
            [tableView endUpdates];
            [cell layoutIfNeeded];
        } completion:nil];
    } else {
        self.expandedRow = indexPath.row;
        [UIView animateWithDuration:0.3 animations:^{
            cell.constraintToAnimate.constant = 100;
            [tableView beginUpdates];
            [tableView endUpdates];
            [cell layoutIfNeeded];
        } completion:nil];
    } }

where constraintToAnimate is a height constraint on a subview added to the cells contentView.


text:
Q: vi is frozen after search on arch linux I'm on Arch Linux live USB. I'm using vi to open an 18kb text file containing a single line of json. I did a search with / and hit a block partway through the file represented by an @ symbol. Then, when I press n to go to next match, the editor freezes. The cursor is on the command line with / highlighted and the cursor is glitching.
The editor doesn't respond to :q, esc, Ctrl+Q, Ctrl+C, Ctrl+Z, Ctrl+D, Ctrl+L, Ctrl+/
When I press Ctrl+S, the cursor begins blinking normally but Ctrl+Q makes it start glitching again.
Alt+F2 then kill -9 [pid] works to get out. But I'd like to know what the problem with the file is.
Upon opening the file, I noticed an incomplete last line error message displayed on the command line. But no line too long error. Also, vi would not scroll past the @.
The file is on an HDD mounted externally through USB. The OS is on a USB stick.

A: The @ mark indicates a line too long to display.  vi still has to keep track of the position before/after the line, and if it's long enough you will certainly notice "some" slowdown as it reads the data and tries to move past that line.
Further reading:

*

*How do you prevent vim from showing an at symbol (@) when a line doesn't fit on screen?

*vi : Line too long

*Line too long on VI. Commands alternatives to navigate last lines of a file


text:
Q: Radio Buttons Selectable While Moving Consider a scenario where your form utilizes custom radio buttons. These radio buttons have the following CSS applied to them - which creates the illusion of selectable images - no js at all.
#ImageSelector label > input{ /* HIDE RADIO */
    display:none;

}
#ImageSelector label > input + img{ /* IMAGE STYLES */
    cursor: pointer;
    border: 2px solid transparent;
    opacity: 0.5;
    filter: alpha(opacity=50);
}
#ImageSelector label > input + img:hover{ /* (CHECKED) IMAGE STYLES */
    opacity: 1.0;
    filter: alpha(opacity=100);
    border:2px solid #00a8ff;
}

#ImageSelector label > input:checked + img{ /* (CHECKED) IMAGE STYLES */
    opacity: 1.0;
    filter: alpha(opacity=100);
    border:2px solid #0184c8;
}

The problem occurs when the user attempts to click on an image and the cursor is still moving - the item won't become clicked. This is expected behavior of typical radio buttons. Is there a quick way to make the radio buttons more 'sensitive' to the click action or clickable while the mouse cursor is moving?
UPDATE: https://jsfiddle.net/7aLbgqr6/
Also, the solution can definitely include jQuery - but it MUST as simple as possible.
Thanks!

A: Modified your fiddle to attach mousedown events to the buttons using jQuery. Additionally, I converted the images to use background-image instead so that the ghost image does not appear when the mouse cursor moves. Just a slight optional improvement.
https://jsfiddle.net/kpLLr03y/6/


text:
Q: Can't set properties on a cloned dateinterval object in PHP Why doesn't this work?
// works
$date = new DateInterval( 'P1Y' );
$date->y = '2';

// crashes
$date_clone = clone $date;
$date_clone->y = '2';

I get a "The connection was reset" in my browser when attempting to run this.

A: I don't see any error with your statement.
Try updating php to the latests available version
if problem still appears (if you using linux - I don't know how debug this in windows environment) run: gdb php -a, and type your statement.
when php crashes, type bt and report bug on https://bugs.php.net/


text:
Q: Error in Archiving the app after updating xcode to 4.5 before updating the archiving process work good but after updating when i archiving the app it gives a linker error to TestFlight Library error is:-
ld: file is universal (3 slices) but does not contain a(n) armv7s slice: /Users/dhirajchoudhary/Documents/MyWorldOfExpo/HRWeekIndia/TestFlightSDK1.0/libTestFlight.a for architecture armv7s
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Is any one know how to link the testflight library in Xcode 4.5, iOS 6.0

A: It's pretty much exactly what the error message says: your app supports multiple architectures, including armv7s. You're trying to link with the TestFlightSDK which doesn't include the armv7s architecture.
You need to either:

*

*Use a newer version of the TestFlight SDK which includes the new armv7s architecture. I'm not sure if this exists yet

*Remove the armv7s architecture from your application. It should still work on the iPhone 5 (which is the only device to use armv7s currently) but you would need to test

A: You need to install Test Flight SDK 1.1, which with support for arm7


text:
Q: opf:file-as not allowed in EPUB 3.0? I'm coding an Ebook and can't seem to get the file-as attribute to work.
Here is what my opf file looks like (minified, of course):
<package
  xmlns='http://www.idpf.org/2007/opf' version='3.0'
  xmlns:dc='http://purl.org/dc/elements/1.1/' unique-identifier='uuid'>

  <metadata
    xmlns:opf='http://www.idpf.org/2007/opf'
    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>

    …

    <dc:creator opf:file-as='Surname, Forename'>Forename Surname</dc:creator>

    …

  </metadata>

  …

</package>

Are opf attributes not allowed in EPUB 3.0 or am I specifying the namespace falsely?

A: You are looking for something like
<meta refines="#author" property="file-as">Author, John</meta>

Where 'author' is the ID of the dc:creator element.


text:
Q: scipy.stats.multivariate_normal error: input matrix must be symmetric positive definite i'm trying to compute the cumulative distribution function of a multivariate normal using scipy.
i'm having trouble with the "input matrix must be symmetric positive definite" error.
to my knowledge, a diagonal matrix with positive diagonal entries is positive definite (see page 1 problem 2)
However, for different (relatively) small values of these diagonal values, the error shows up for the smaller values.
For example, this code:
import numpy as np
from scipy.stats import multivariate_normal
std = np.array([0.001, 2])
mean = np.array([1.23, 3])
multivariate_normal(mean=mean, cov=np.diag(std**2)).cdf([2,1])

returns 0.15865525393145702
while changing the third line with:
std = np.array([0.00001, 2])

causes the error to show up.
i'm guessing that it has something to do with computation error of floats.
The problem is, when the dimension of the cov matrix is larger, the accepted positive values on the diagoanal are bigger and bigger.
I tried multiple values on the diagonal of the covariance matrix of dimension 9x9. It seems that when other diagonal values are very large, small values cause the error.

A: Examining the stack trace you will see that it assumes the condition number as
1e6*np.finfo('d').eps ~ 2.2e-10 in _eigvalsh_to_eps
In your example the difference the smaller eigenvalue is 5e-6**2 times smaller than the largest eigenvalue so it will be treated as zero.
You can pass allow_singular=True to get it working
import numpy as np
from scipy.stats import multivariate_normal
std = np.array([0.000001, 2])
mean = np.array([1.23, 3])
multivariate_normal(mean=mean, cov=np.diag(std**2), allow_singular=True).cdf([2,1])


text:
Q: Index of matching bracket character within a lambda function? I'm more curious than in dire need. Would it be possible to pass a lambda function two arguments s, and i. Where s is the string in question and i is the index of the first bracket; and have it return the index of the complimentary bracket?
I should note that it only needs to work for the brackets (), and not {} or [].
For example
>>> f( '(() foo ) bar' , 0)
8

f is defined by a lambda function
Edit: I'm aware that numerous methods exist for finding the matching bracket. I, however, am curious if it can be simplified into a lambda expression.

A: I'm far too lazy to worry about corner cases, but using itertools.accumulate it's relatively straightforward:
f = lambda s,i: next((i for i,x in enumerate(accumulate
    ({'(': 1, ')': -1}.get(c,0) for c in s[i:]), i) if not x), None)

In [31]: s = '(() foo ) bar'

In [32]: f(s, 0)
Out[32]: 8

In [33]: f(s, 1)
Out[33]: 2

In [34]: f(s, 2)

This works by tracking the height of the string, counting ( as +1 and ) as -1:
In [36]: list(accumulate({'(': 1, ')': -1}.get(c,0) for c in s))
Out[36]: [1, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]


text:
Q: How do I convert '$ -' from a string to a float using pandas? I have some financial information that I've kept on an excel document for a while and I'd like to run some python code on it, but I'm having some issues converting the objects types to floats. The problem seems to be the '$ -'
This is how the data looks when loaded in:
import pandas as pd
dfData = {'Item': ['Product 1','Product 2','Product 3'],
        'Cost': [14.87,'-9.47','$ -']
       }
df = pd.DataFrame(dfData,columns=['Item','Cost'])
df

         Item   Cost
0   Product 1   14.87
1   Product 2   -9.47
2   Product 3   $ -

I've tried:
df['Cost'] = df['Cost'].str.replace('$','').str.replace(' ','').astype('float')

...as well as other similar str.replace commands, but I keep getting the following error:
ValueError: could not convert string to float: ''

This is my first stack overflow post, so go easy on me! I have looked all over for a solution, but for some reason can't find one addressing this specific problem. I can't replace the '-' either, because row 1 has it indicating a negative value.

A: You don't need to chain str.replace, you can just use replace:
df['Cost'] = df['Cost'].replace({'\$': '', '-': '-0'}, regex=True).astype(float)
print(df)

# Output
        Item   Cost
0  Product 1  14.87
1  Product 2  -9.47
2  Product 3  -0.00


text:
Q: Get images from other website I am trying to get images, but the problem is that the thing I am getting are not all images and some images are too small to see.
def webService(url: String) = Action.async { implicit request =>
    WS.url("http://" + url).get().map { response =>
      val s = " src=\""                      //src also on the jquery path
      var all = response.body
  var state = true
  var set = Set[String]()
  while (state) {
    val ix = all.indexOf(s) + s.length();
    var imageUrl = all.substring(ix, all.indexOf("\"", ix + 1))
    all = all.substring(ix, all.length())
    state = all.contains("<img") || all.contains("< img")
     if (imageUrl.contains(".jpg")) {
        set=set+(imageUrl.split(".jpg")(0)+".jpg")
      } else if (imageUrl.contains(".jpeg")) {
        set=set+(imageUrl.split(".jpeg")(0)+".jpeg")
      } else if (imageUrl.contains(".png")){
        set=set+(imageUrl.split(".png")(0)+".png")
      }
    }
    Ok(views.html.webService("", url,set))
    }
}

I want all images with their dimensions, so I can remove unwanted images.

*

*I am using play framework 2.2 with scala

A: To parse HTML I would use an HTML Parser - something like jsoup.
import java.net.URL
import org.jsoup.Jsoup
import scala.collection.JavaConversions._

val timeout = 1000
val url = new URL("http://www.stackoverflow.com")

val imgTags = Jsoup.parse(url, timeout).select("img[src]").toList
val imgSources = imgTags.map(_.attributes.get("src"))
scala:> imgSources: List[String] = List(http://i.stack.imgur.com/tKsDb.png, ...

To get the dimensions of an image, you can use javax.imageio.ImageIO:
case class ImageDimension(heigth: Int, width: Int)

def imageDimension(imageUrl: String): ImageDimension = {
  import javax.imageio.ImageIO
  import java.net.URL
  val img = ImageIO.read(new URL(imageUrl))
  ImageDimension(img.getHeight, img.getWidth)
}

scala> imageDimension("https://www.google.de/images/srpr/logo11w.png")
res0: ImageDimension = ImageDimension(190,538)


text:
Q: .htaccess redirect root and index.php to https root Please help
How redirect HTTP root and index.php to HTTPS root.
Styles and Scripts are on par with index.php.
RewriteEngine On

RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

Thanks!

A: One way could be:
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be              included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI}   [L,R=301]
# Now, rewrite any request to the wrong domain to use   www.
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.%{HTTP_HOST}%.   {REQUEST_URI} [L,R=301]


text:
Q: How do I run an installed program? (Command line) (This is all in the command line/prompt)
Hi!
So, my problem is MOST BASIC in nature, and it's like this:
If I want, for an example, to install and run 'cowsay' -program, I assume I do it like:
sudo apt-get install cowsay

BUT now, if I just try to use it, like:
cowsay "Cow goes moo"

I get:  command not found
So, ok, maybe the program is not installed..?
So I type:
dpkg -L cowsay

And, no, it is installed alright, maybe it's just not registered into some default library cache of programs...(if that even is a thing)?
In short, I have no idea how to proceed. The objects listed via dpkg are a lot of files with .cow -format, a few .gz -packages and a README file, aka no .exe .bin executables that I can find. The readme file has, as far as I can tell, nothing of use. It's just copyright information and short history of the program.
Thank you for your time! :)

A: Generally when you install a program, you will be able to run it from the command line by typing the name of the program installed. Note that this name will not always match the name of the package (e.g. alsa-tools provides as10k1, hda-verb, sbiload and us428control).
As discussed in the comments by George and Terrance, the program must also be in your PATH variable so that you don't require the full path to run it. For some reason "cowsay" is not, so you can temporarily add it as described by Terrance using:
PATH=$PATH:/usr/games

If this works, you can permanently add this location to your path variable. This can be done by modifying .profile, .pam_environment, or other locations as described in the references below. For example, adding the following to ~/.profile should work:
export PATH="$PATH:/usr/games"

The above will take effect on the next login.
References:

*

*How to add a directory to the PATH?

*https://help.ubuntu.com/community/EnvironmentVariables#Persistent_environment_variables


text:
Q: Can my iBook use any PC2700 DDR-SDRAM RAM? My iBook currently has a stick of 256MB DDR PC2700 RAM installed.
I want to bump this up to a gigabyte (because programs these days take a lot of RAM to link). I was wondering if an iBook G4 can use any brand of PC2700 or only RAM made specifically for iBooks.
For example, there was a time when graphics card needed to be specially flashed to work for Apple computers.

A: It does not need a specific ram (like any other computers).
But be sure to buy SO-DIMM ram and not DIMM.


text:
Q: how to pass variables to Orderby Clause using Doctrine I am getting an error while trying to achieve dynamic sorting in DQL's ORDER BY clause with Doctrine 2 ORM.
Here is my code snippet:
$queryBuilder = $categoryEntity->createQueryBuilder('category');

$queryBuilder->distinct();
$queryBuilder->join('Category\Entity\CategoryName', 'category_name', 'WITH', 'category.id = category_name.category');

if($column == 'status'){
    $queryBuilder->orderBy("category.status $order");
}else{
    $queryBuilder->orderBy("category_name.name $order");
}

This produces the following error:

[Syntax Error] line 0, col 189: Error: Expected end of string, got 'ASC'

A: The correct API is Doctrine\ORM\QueryBuilder#orderBy($field, $direction):
// assuming $order is either 'ASC' or 'DESC'

if($column == 'status'){
      $queryBuilder->orderBy('category.status', $order);
}else{
     $queryBuilder->orderBy('category_name.name', $order);
}


text:
Q: C# WPF RichTextBox как переопределить вывод текста? Как сделать чтобы строки выводились не вниз , а наоборот чтобы текст опускался а новая строка вставлялась на первую позицию,
как в окне чата , последнее сообщение всегда вверху , а остальные строки скролятся в низ

A: Во FlowDocument, контейнером для которого является RichTextBox, новую строку вверх можно добавлять так:
// Инициализация документа скорее всего будет снаружи
if (RichTextBox.Document == null)
    RichTextBox.Document = new System.Windows.Documents.FlowDocument();

// Добавляется первая строка
if (RichTextBox.Document.Blocks.Count == 0)
{
    RichTextBox.Document.Blocks.Add(new Paragraph(new Run("Новая строка")));
    return;
}

// Вторая и следующие строки добавляются перед первой
RichTextBox.Document.Blocks.InsertBefore(RichTextBox.Document.Blocks.FirstBlock,
    new Paragraph(new Run("Новая строка вверху")));


text:
Q: not able to change class within id although no errors I don't understand why my extraInfo variable isn't being printed out onto the webpage.
The information is being retrieved correctly (I've tested this with alert()) but I just cannot figure out why it isn't replacing the span text with the returned value.
I've tried sending it out wrapped in P tags too and although no errors come out, it still doesn't amend the text.
https://github.com/ralam87/Quote-generator
Where am I going wrong?
document.getElementById("source").getElementsByClassName("citation")[0] = extraInfo;

A: I gone through your example.
Note: when you are trying to assign the citation to first element with .citation class that time the there are no elements present with the class citation because it get replaced when you set the value to source element just before citation document.getElementById("source").innerHTML = author;.
This are possible solution

*

*change this document.getElementById("source").getElementsByClassName("citation")[0] = extraInfo; to document.getElementsByClassName("citation")[0].innerHtml = extraInfo;

*remove the id from

*create another  or
 or
 element inside the existing
 and assign the id=source to that inner element. for example

.
If you want to have the , after the source name then at the time of assigning the document.getElementById("source").innerHTML = author + ',';.

If you allow me i can also contribute this directly to you git
  repository.


text:
Q: gcloud disk snapshot - how to restore? I created a snapshot of one of my disks in gcloud. I can see the new snapshot listed in the "snapshots" tab.
How can I now recreate this disk? - I want to test the recovery of an backup.
I followed this instructions and created a new instance with the disk attached:
https://cloud.google.com/compute/docs/disks/restore-and-delete-snapshots

I ssh´ed to the instance then and tried to find the disk, but it seems not to be attached? What am I doing wrong?

A: Ok found it out. The disk needs to be mounted:
mkdir /demo-mount
sudo mount -o discard,defaults /dev/sdb /demo-mount