Q: Problem with CKEditor inside a ColorBox modal popup Please can anyone help me out. I have an html page in which I have added a modal popup from ColorBox. In the ColorBox popup, I have added a CKEditor. The problem is as follows:
In IE, the CKEditor works fine, but in FF & Chrome, I get the CKEditor like in readonly mode (I can't type anything in it).
If i put the CKEditor directly into the page (and not in the modal popup), it works fine in all browsers.
I think this might be a problem with the z-index on one of the elements generated by CKEditor. But I don't know which one exactly?
I would really appreciate some help plz, thanks in advance!

A: We got around our problem by switching lightboxes, rather than use ColorBox, use Simple Modal.  I have a funny feeling it will work for you.  Good luck!

A: <script>
  $(document).ready(function() {
    initCKEditor(); //function ckeditor.
    $("#id_textarea").val(CKEDITOR.instances.id_textarea.getData());
  });
</script>

A: Render/create ckeditor on colorbox "onComplete" callback.
See callbacks here : http://www.jacklmoore.com/colorbox

A: After some debugging I found that it is because of a CSS rule.
In the skin named kama you need to change the following CSS rule in mainui.css from:
.cke_skin_kama .cke_browser_ie.cke_browser_quirks .cke_contents iframe
{
    position: absolute;
    top: 0;
}

To:
.cke_skin_kama .cke_browser_ie.cke_browser_quirks .cke_contents iframe
{
    top: 0;
}

Depending on your setup, you might need to change it in skins/kama/editor.css
I however recommend upgrading to a newer version of ckeditor.  I found this issue on version 3.6.2.


Q: JPA: relation manyToMany on the same entity I have an Entity that has two relation manyToMany with itself and I don't want to use Cascade.MERGE because I need to do some data checks to validate the data:
@Entity("device")
public class Device {
...
@ManyToMany(mappedBy = "parents", targetEntity = Device.class, fetch = FetchType.LAZY)
    public Set<Device> getChildren() {
        return this.children;
    }

    @Override
    @ManyToMany(targetEntity = Device.class, fetch = FetchType.LAZY)
    @JoinTable(name = "dem_hierarchy", joinColumns = {
        @JoinColumn(name = "CHILDREN_UUID", referencedColumnName = "UUID")},
            inverseJoinColumns = {
                @JoinColumn(name = "DEM_DEVICE_UUID", referencedColumnName = "UUID")})
    public Set<Device> getParents() {
        return parents;
    }

...
}

When I save a tree like this:
Device grandGrandPa = new Device();
grandGrandPa.setName("TEST" + counter + "_grandGrandPa");

Device grandPa = new Device();
grandPa.setName("TEST" + counter + "_grandPa");

grandGrandPa.addChild(grandPa);

Device daddy = new Device();
daddy.setName("TEST" + counter + "_daddy");

grandPa.addChild(daddy);

Device son = new Device();
son.setName("TEST" + counter + "_son");

daddy.addChild(son);
grandGrandPa = deviceService.register(grandGrandPa);

The register method is recursive and it descends the tree using the children column. When its the turn of the "grandPa" to be saved the weblogic return an exception:

Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

I cannot understand why this happens. It gives me this error when in code there are some queries on parent Device: first turn it is empty, second turn it has one value.
I'm using weblogic 12.1.3 and hibernate 4.0.0, as database Oracle 11g.

A:
It gives me this error when in code there are some queries on parent Device

By default, Hibernate will flush pending changes to the database before attempting to execute a query. At that stage, all entities referenced in all relationships should have been persisted, or else an exception will be thrown.
Also, since mappedBy is declared on the children end, the parents is the owning side of the relationship. Because of that, Hibernate will ignore children completely at persist time and look for transient entities in parents instead. Your persisting logic should therefore be reversed - save parents first, children last (alternatively, you could simply declare children the owning side).


Q: Get Google.GoogleApiException 'File not found: [404]' when trying to list files in a non-root Google Drive folder I'm trying to access files in Google Drive. I picked up code to create a Google Drive service from the Google docs...
private static DriveService GetDriveService() {
  UserCredential credential;
  using (FileStream stream = new("credentials_desktop.json", FileMode.Open, FileAccess.Read)) {
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
      GoogleClientSecrets.Load(stream).Secrets,
      Scopes,
      "user",
      CancellationToken.None,
      new FileDataStore("token.json", true)).Result;
  }
  DriveService service = new(new BaseClientService.Initializer {
    HttpClientInitializer = credential,
    ApplicationName = ApplicationName,
  });
  return service;
}

Using code found in this blog post, I can make a call to the Google Drive API and see all the files in the root folder...
private static void ListFiles() {
  DriveService service = GetDriveService();
  FilesResource.ListRequest fileList = service.Files.List();
  fileList.Q = "mimeType != 'application/vnd.google-apps.folder' and 'root' in parents";
  fileList.Fields = "nextPageToken, files(id, name, size, mimeType)";
  List<File> files = new();
  string pageToken = null;
  do {
    fileList.PageToken = pageToken;
    FileList filesResult = fileList.Execute();
    IList<File> pageFiles = filesResult.Files;
    pageToken = filesResult.NextPageToken;
    files.AddRange(pageFiles);
  } while (pageToken != null);
  // dump files to console...
}

That works fine, but if I try to list the files in a folder...
fileList.Q = "mimeType != 'application/vnd.google-apps.folder' and 'Admin' in parents";

...then when it tries to make the call to fileList.Execute() I get the following exception...
Google.GoogleApiException
  HResult=0x80131500
  Message=Google.Apis.Requests.RequestError
File not found: . [404]
Errors [
    Message[File not found: .] Location[fileId - parameter] Reason[notFound] Domain[global]
]

  Source=Google.Apis
  StackTrace:
   at Google.Apis.Requests.ClientServiceRequest`1.<ParseResponse>d__35.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Google.Apis.Requests.ClientServiceRequest`1.Execute()
   at GoogleDrivePlay.Program.ListFiles2() in d:\GoogleDrivePlay\GoogleDrivePlay\Program.cs:line 59
   at GoogleDrivePlay.Program.Main(String[] args) in d:\GoogleDrivePlay\GoogleDrivePlay\Program.cs:line 23

As you can see, the Admin folder does exist...

Anyone any idea how I can list the contents of other folders? Thanks

A: fileList.Q = "mimeType != 'application/vnd.google-apps.folder' and 'Admin' in parents";

The issue you are having is that you are using the name of the directory 'Admin' you need to use the file id of the Admin directory.
Do a file.list and search for the admin directory get its file id then pass it to that instead.
fileList.Q = "name ='Admin' and mimeType != 'application/vnd.google-apps.folder'";


Q: Get values from NSDictionaries I have the following code:
NSDictionary *dict = @[@{@"Country" : @"Afghanistan", @"Capital" : @"Kabul"},
                     @{@"Country" : @"Albania", @"Capital" : @"Tirana"}];

I want to list many countries and capitals, and then randomize i.e a country and put it on the screen, then the user should be able to pick the correct capital..

*

*How to I put the Country? Like dict.Country[0] or something like that?

*What is wrong with the code? I get the error "Initializer element is not a compile-time constant" and the warning "Incompatible pointer types initializing 'NSDictionary *_strong' with an expression of type 'NSArray *'.

*Can I make a third String in the Dictionary, containing a flag file.. for example
@"Flagfile" : @"Albania.png"
and later put it in a image view?
I want like a loop with a random number I (for example) and put like (I know this is not right, but I hope you get the point)
loop..
....

text= dict.Country[I];

button.text= dict.Capital[I];

Imageview=dict.Flagfile[I];
.....
....

A: Your top level element is an NSArray (@[], with square brackets, makes an array) of two NSDictionary's.  To access an attribute in one of the dictionaries, you would do array[index][key], e.g. array[0][@"Country"] would give you @"Afghanistan".  If you did NSArray *array = ... instead of NSDictionary *dict = ...
If you want to pick a country at random, you can get a random number, get it mod 2 (someInteger % 2) and use that as your index, e.g. array[randomNumber % 2][@"Country"] will give you a random country name from your array of dictionaries.
If you store an image name in the dictionaries, you can load an image of that name using UIImage's +imageNamed: method.

A: Here's more complete instruction on mbuc91's correct idea.
1) create a country
// Country.h

@interface Country : NSObject

@property(strong,nonatomic) NSString *name;
@property(strong,nonatomic) NSString *capital;
@property(strong,nonatomic) NSString *flagUrl;
@property(strong,nonatomic) UIImage *flag;

// this is the only interesting part of this class, so try it out...
// asynchronously fetch the flag from a web url.  the url must point to an image
- (void)flagWithCompletion:(void (^)(UIImage *))completion;

@end

// Country.m

#import "Country.h"

@implementation Country

- (id)initWithName:(NSString *)name capital:(NSString *)capital flagUrl:(NSString *)flagUrl {

    self = [self init];
    if (self) {
        _name = name;
        _capital = capital;
        _flagUrl = flagUrl;
    }
    return self;
}

- (void)flagWithCompletion:(void (^)(UIImage *))completion {

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.flagUrl]];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if (data) {
                                   UIImage *image = [UIImage imageWithData:data];
                                   completion(image);
                               } else {
                                   completion(nil);
                               }
                           }];
}

@end

2) Now, in some other class, use the Country
#import "Country.h"

- (NSArray *)countries {

    NSMutableArray *answer = [NSMutableArray array];

    [answer addObject:[[Country alloc]
                       initWithName:@"Afghanistan" capital:@"Kabul" flagUrl:@"http://www.flags.com/afgan.jpg"]];

    [answer addObject:[[Country alloc]
                       initWithName:@"Albania" capital:@"Tirana" flagUrl:@"http://www.flags.com/albania.jpg"]];

    return [NSArray arrayWithArray:answer];
}

- (id)randomElementIn:(NSArray *)array {

    NSUInteger index = arc4random() % array.count;
    return [array objectAtIndex:index];
}

-(void)someMethod {

    NSArray *countries = [self countries];
    Country *randomCountry = [self randomElementIn:countries];
    [randomCountry flagWithCompletion:^(UIImage *flagImage) {
        // update UI, like this ...
        // self.flagImageView.image = flagImage;
    }];
}

A: You cannot initialize an NSDictionary in that way.  An NSDictionary is an unsorted set of key-object pairs - its order is not static, and so you cannot address it as you would an array.  In your case, you probably want an NSMutableDictionary since you will be modifying its contents (see Apple's NSMutableDictionary Class Reference for more info).
You could implement your code in a few ways.  Using NSDictionaries you would do something similar to the following:
NSMutableDictionary *dict = [[NSMutableDictionary alloc]
    initWithObjectsAndKeys:@"Afghanistan", @"Country",
    @"Kabul", @"Capital", nil];

You would then have an array of dictionaries, with each dictionary holding the details of one country.
Another option would be to create a simple model class for each country and have an array of those.  For example, you could create a Class named Country, with Country.h as:
#import <Foundation/Foundation.h>
@interface Country : NSObject

@property (nonatomic, retain) NSString *Name;
@property (nonatomic, retain) NSString *Capital;
//etc...

@end


Q: asp.net Razor v3 jquery ajax post returns 404 not found I recently started a Asp.net Razor v3 project. It's the first time I use this (before I only used MVC and Web Forms)
I am struggling to get a code behind that gets called by a jquery ajax function to work. When debugging on Chrome I see that the script returns POST 404 (Not Found)
$.ajax({
  type: "POST",
  url: "../App_Code/GlobalSitesController/GetSiteTable",
  data: "{'siteName': 'Some Site' , 'daysDiff': '0'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (response) {
  document.getElementById("siteTable").innerHTML = response.responseText;
  },
  failure: function (response) {
  document.getElementById("siteTable").innerHTML = "ERROR" + response.responseText;
  },
  error: function (response) {
  document.getElementById("siteTable").innerHTML = "ERROR" + response.responseText;
  }
});

public class GlobalSitesController : Controller
{
 [HttpPost]
 public string GetSiteTable(string siteName, int daysDiff)
 {
  return "some string";
 }
}

First I noticed that my project didn't include System.Web.Mvc so I added Microsoft.AspNet.Mvc via Nugget
The full Chrome error is jquery-1.10.2.min.js:23 POST http://localhost:9997/App_Code/GlobalSitesController/GetSiteTable 404 (Not Found). This is the correct URL and should be working

A: It turns out the url bit needs to be in the following form
url: '@url.Action("GetSiteTable", "GlobalSitesController")',

(url needs to be initialised as in below)
System.Web.Mvc.UrlHelper url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);


Q: python 3 hex conversion I'm trying to convert some code from 2 to 3.  I have
val = str(''.join(map(chr, list(range(0, 256, 8)))))

and I need to translate
x = str(val).encode('hex')

and
x.decode('hex')

Thanks

A: In python2, your code produces:
In [4]: val = str(''.join(map(chr, list(range(0, 256, 8))))) ;  val
Out[4]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
In [5]: x = str(val).encode('hex') ; x
Out[5]: '0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
In [6]: x.decode('hex')
Out[6]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'

To get the similar output in python3:
In [19]: import codecs
In [20]: val = ''.join(map(chr, range(0, 256, 8))) ; val
Out[20]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0¨°¸ÀÈÐØàèðø'
In [21]: x = codecs.encode(val.encode('latin-1'), 'hex_codec') ; x
Out[21]: b'0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
In [22]: codecs.decode(x, 'hex_codec')
Out[22]: b'\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'

Notes:

*

*The python3 version of x above is a byte-string.  Since it is entirely ASCII, it can be converted to unicode simply via x.decode().

*The display of val toward the end of the string in the python3 code above does not match the python2 version.  For a method of creating val which does match, see the next section.

Alternatives
Use bytes to create the string.  Use binascii.hexlify to convert it to hex:
In [15]: val = bytes(range(0, 256, 8))
In [16]: val
Out[16]: b'\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
In [17]: binascii.hexlify(val)
Out[17]: b'0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'

More on unicode and character 0xf8
You wanted ø to be 0xf8.  Here is how to make that work:
>>> s = chr( int('f8', 16) )
>>> s
'ø'

And, to convert s back to a hex number:
>>> hex(ord(s))
'0xf8'

Note that 0xf8' is the unicode code point of 'ø' and that that is not the same as the byte string representing the unicode character 'ø' which is:
>>> s.encode('utf8')
b'\xc3\xb8'

So, 'ø' is the 248th (0xf8) character in the unicode set and its byte-string representation is b'\xc3\xb8'.

A: Your Python 2 code:
val = str(''.join(map(chr, list(range(0, 256, 8)))))
x = str(val).encode('hex')
x.decode('hex')

Let's make version that works on both Python 2 and 3:
import binascii

val = bytearray(range(0, 0x100, 8))
x = binascii.hexlify(val)
binascii.unhexlify(x)


Q: MonoDevelop and XCode I'm using MonoDevelop 2.8.5 and XCode 4.2.1.
Every time I'm switching to monodevelop window from anything else, it starts to update XCode project file and pops XCode window.
More over, when I switch from XCode back to monotouch, it updates the project and switches back to XCode.
Thats's really annoying. How do I disable this "feature"?

A: Problem was fixed by downloading new Monodevelop: 2.8.6 beta

A: This behavior cannot be disabled, since there is no other way that MonoDevelop can use to communicate with xcode 4. This is because MonoDevelop creates an Xcode project on the fly (when you dbl clic any xib file within MD) and then MD launches xcode with the generated xcode project.
when you do all necessary changes in xcode and you switch back to MD the OnFocus event of MD (i don't really know if thats the event's name btw) process the changes you have done on the xcode project and modifies it in order to maintain both projects (xcode and MD) on sync
My suggestion is just make all necessary changes on xcode save them and then close it, then work on MD as usual and if you need to reopen xcode again work on it, Xcode won't bother you as long as you don't focus the MD window
I hope this helps.
Alex


Q: I cannot seem to run this properly... It stucks and does not display an output Here's my script:
while [[ $startTime -le $endTime ]]
do

thisfile=$(find * -type f | xargs grep -l $startDate | xargs grep -l $startTime)
fordestination=`cut -d$ -f2 $thisfile | xargs cut -d ~ -f4`

echo $fordestination

startTime=$(( $startTime + 1 ))

done

A: I think your cut and grep commands could get stuck. You probably should make sure that their parameters aren't empty, by using the [ -n "$string" ] command to see if $string isn't empty. In your case, if it were empty, it wouldn't add any files to the command that would use it afterwards, meaning that the command would probably wait for input from the command line (ex: if $string is empty and you do grep regex $string, grep wouldn't receive input files from $string and would instead wait for input from the command line). Here's a "complex" version that tries to show where things could go wrong:
while [[ $startTime -le $endTime ]]
do

thisfile=$(find * -type f)
if [ -n "$thisfile" ]; then
    thisfile=$(grep -l $startDate $thisfile)
    if [ -n "$thisfile" ]; then
        thisfile=$(grep -l $startTime $thisfile)
        if [ -n "$thisfile" ]; then
            thisfile=`cut -d$ -f2 $thisfile`

            if [ -n "$thisfile" ]; then
                forDestination=`cut -d ~ -f4 $thisfile`
                echo $fordestination
            fi
        fi
    fi
fi

startTime=$(( $startTime + 1 ))

done

And here's a simpler version:
while [[ $startTime -le $endTime ]]
do

thisfile=$(grep -Rl $startDate *)
[ -n "$thisfile" ] && thisfile=$(grep -l $startTime $thisfile)

[ -n "$thisfile" ] && thisfile=`cut -d$ -f2 $thisfile`
[ -n "$thisfile" ] && cut -d ~ -f4 $thisfile

startTime=$(( $startTime + 1 ))

done

The "-R" tells grep to search files recursively, and the && tells bash to only execute the command that follows it if the command before it succeeded, and the command before the && is the test command (used in ifs).
Hope this helps =)


Q: How to set a threshold value from signal to be processed in wavelet thresholding in python I'm trying to denoise my signal using discrete wavelet transform in python using pywt package. But i cannot define what is threshold value that i should set in pywt.threshold() function
I have no idea what the best threshold value that should be set in order to reconstruct a signal with minimal noise
I used ordinary code:
pywt.threshold(mysignal, threshold, 'soft')
yes i am intended to do soft thresholding
I want to know if the threshold value could be determined by looking to my signal or from the other way

A: There are some helpful graphics on pywt webpage that help visualize what these thresholds are and what they do.
The threshold applies to the coefficients as opposed to your raw signal.  So for denoising, this will typically be the last couple of entries returned by pywt.wavedec that will need to be zeroed/thresholded.
I could initial guess is the 0.5*np.std of each coefficeint level you want to threshold.


Q: Convert c# date to Javascript This is how I convert .Net Datetime to Javascript. I found the code somewhere a long time ago and use it for Highcharts. Now the chart sometimes looks strange with the lines messed up. I suspect it has to do with the date.
Datetime curDate = "11/14/2013";
string jsDate = "Date.UTC(" + curDate.Year + "," + (curDate.Month - 1) + "," +     curDate.Day;
if (curDate.Millisecond > 0)
        {
            jsDate += "," + curDate.Hour + "," + curDate.Minute + "," + curDate.Second + "," + curDate.Millisecond;
            return jsDate += ")";
        }
        if (curDate.Second > 0)
        {
            jsDate += "," + curDate.Hour + "," + curDate.Minute + "," + curDate.Second;
            return jsDate += ")";
        }
        if (curDate.Minute > 0)
        {
            jsDate += "," + curDate.Hour + "," + curDate.Minute;
            return jsDate += ")";
        }
        if (curDate.Hour > 0)
        {
            jsDate += "," + curDate.Hour;
            return jsDate += ")";
        }

        jsDate += ")";

Is this a correct way to convert .Net date to javascript?
Thank you!

A: The easiest way to convert between the two is to convert the .NET time to a timespan in milliseconds from the UNIX epoch time:
public static long ToEpochDate(this DateTime dt)
{
    var epoch = new DateTime(1970, 1, 1);
    return dt.Subtract(epoch).Ticks;
}

You can then use that to generate your JS string:
DateTime current = DateTime.Now;
var jsDate = string.Format("Date.UTC({0})", current.ToEpochDate());


Q: two forms conflict with each other I have placed two forms on one page. Bothe forms work fine separately but when they are placed on one page at the same time they conflict with each other. Here are both forms:
Contact Form:
<form name="contactform" id="contactform" method="post" action="#targetAnchorPage2">

<?php
if (isset($_POST["name"])){
?>

 <?php
 require_once("contact_send.php");
 ?>

<?php
}
?>

<label for="name" class="<?=$name_class?>">name:	<input  type="text" name="name" maxlength="50" value="<?=$name?>">

<label for="email" class="<?=$emailaddress_class?>">email:	<input  type="text" name="email" maxlength="80" value="<?=$emailaddress?>">

<label id="tworows" for="message" class="<?=$message_class?>">your message:

<textarea  name="message" cols="22" rows="6" value="<?=$message_class?>"></textarea>

<input class="button" type="submit" value="">

</form>

Subscribe Form:
<form name="subscribeform" id="subscribeform" method="post" action="#targetAnchorPage3">

<?php
if (isset($_POST["name"])){
?>

 <?php
 require_once("subscribe_send.php");
 ?>

<?php
}
?>

<label for="name" class="<?=$name_class?>">name:	<input type="text" name="name" maxlength="50" value="<?=$name?>">

<label for="email" class="<?=$emailaddress_class?>">email:	<input type="text" name="email" maxlength="80" value="<?=$emailaddress?>">

<input class="button" type="submit" value="">

</form>

How can this be solved? Is it caused by the "required_once" command?

A: I am guessing that since you are showing the required files based on the same criteria isset($_POST['name']) and since both forms have the name field you end up showing the code in both requires regardless of which form is submitted.  You should simply change the form field names on on of the forms such that they are different.

A: Both forms have the same action attribute, they both point back to the same page (note that the hash is not sent to the server). As they both have a field called name and you are checking for that, both actions get executed regardless of which form was sent in.
You can do either:

*

*use different scripts / form processors (don't post back to the same page)

*use a different check for each form, for example by adding a hidden input that will allow you to distinguish between the forms.

A: Add
  formaction="Your_URL"

Attribut  in Button


Q: Loading a whole mySQL table into a PHP array I have a table with 4 columns and 23 rows. I need all 92 values in the the table as PHP variables (whether that be one array, 4 arrays, 92 individual variables, or whatever).
The rows are:
ID
Category
Summary
Text
I need to build a series of select boxes where the items are grouped by the category, the options available are the summaries, and the resulting text is passed on for processing.
I've been searching, but all the examples I can find are about printing the table out, and I need to continue working with the variables.
I really appreciate any help!
Billy

A: Just a SELECT * FROM table_name will select all the columns and rows.
$query = "SELECT * FROM table_name";
$result = mysql_query($query);

$num = mysql_num_rows($results);
if ($num > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        // You have $row['ID'], $row['Category'], $row['Summary'], $row['Text']
    }
}

A: OK, I found my answer with better search terms.  I'm still new here, so let me know if this is not a fair way to handle the situation.  I upvoted @Indranil since he or she spent so much time trying to help me.
Anyway...
    $content = array();
    while($row = mysql_fetch_assoc($result)) {
      $content[$row['id']] = $row;
    }

Puts my whole entire table into one huge, multidimensional array so that I can use it throughout my code.  And it even names the first level of the array by the ID (which is the unique identifier).
Thank you to those that tried to help me!
Billy

A: $pdo = new PDO(
    'mysql:host=hostname;dbname=database;charset=utf-8',
    'username',
    'password'
);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );

$stmt = $pdo->query('SELECT ID, Category, Summary, Text FROM Table');
if ( $stmt !== false )
{
   $data = $stmt->fetchAll( PDO::FETCH_ASSOC );
}

In the case if the SQL query has no conditions, use query() , otherwise, you should be using prepare() ans bind the parameters.
Oh .. and please stop using the ancient mysql_* functions, they are in the process of being deprecated and no new code should written with them.


Q: trouble scraping data from an html table I'm trying to scrape data, in the form of a table, and the hrefs from within that table from a town assessor website using the R package rvest. Despite having luck scraping tables from other websites (e.g. wikipedia), I'm unable to get anything from the town assessor.
I am using RStudio v1.1.442 and R v3.5.0.
sessioninfo()
R version 3.5.0 (2018-04-23)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.6

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] rvest_0.3.3 xml2_1.2.0  V8_2.2

loaded via a namespace (and not attached):
 [1] httr_1.4.0     compiler_3.5.0 selectr_0.4-1  magrittr_1.5   R6_2.4.0       tools_3.5.0    yaml_2.2.0
 [8] curl_3.3       Rcpp_1.0.1     stringi_1.4.3  stringr_1.4.0  jsonlite_1.6

I have tried to follow a few examples. First, the wikipedia state population example, which works fine.
url <- "https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States_by_population"
population <- url %>%
  read_html() %>%
  html_nodes("#mw-content-text > div > table:nth-child(11)") %>%
  html_table()
population <- population[[1]]

I've also been able to scrape data from yelp without issue. This, for example, gives me the names of the restaurants.
url <- "https://www.yelp.com/search?find_loc=New+York,+NY,+USA"
heading <- url %>%
  read_html() %>%
  html_nodes(".alternate__373c0__1uacp .link-size--inherit__373c0__2JXk5") %>%
  html_text()

The website I'm having trouble with is like this one, which is the output of a search for properties on a specific street.
url <- "https://imo.ulstercountyny.gov/viewlist.aspx?sort=printkey&swis=all&streetname=Lake+Shore+Dr"
helpme <- url %>%
  read_html() %>%
  html_nodes("#tblList > tbody") %>%
  html_table()

I would also like to be able to pull out the hrefs using something like this
helpme <- url %>%
  read_html() %>%
  html_nodes("#tblList > tbody") %>%
  html_attr('href') %>%
  html_text()

Unfortunately, my attempts to scrape the table and the href are empty.
Is there something strange about this website. I've used the chrome browser inspector and SelectorGadget to help find the right copy selectors. I've also tried it with the xpath. The result is the same either way.


Q: Hibernate EntityManager is getting closed, in wildfly 10 I use container managed JPA where  inject the EntityManager instance. With the injected entitymanager instance, when I use find() method it says entity manager is closed.
I use wildfly 10.
How can I overcome this issue? What I do wrong here?
I create entity manager like this;
        @PersistenceContext
        protected EntityManager em;

    @Stateless
    public class CustomerService  CrudService<Customer> {

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void update(Customer entity) {

    Customer item = em.find(Customer.class,entity.getId()); //ISSUE
    if (entity.getParentId()!=null) {
        item.setParent(em.find(CRMEntity.class , entity.getParentId()));
    item.setParentId(entity.getParentId());
    }
....

super.update(item);
}

public abstract class CrudService<T extends BaseEntity>  {
public void update(T entity) {
        Session session = null;

        try {
            session = getSession();
            session.update(entity);
            session.flush();

        } catch (HibernateException ex) {
            log.error("Error when update." + entity.getCode(), ex);
            if (session != null) {
                session.cancelQuery();
            }
        } finally {
            if (session != null && session.isOpen()) {
                session.clear();
                session.close();
            }
        }
    }
public Session getSession() {
        if (session == null || !session.isOpen()) {
            session = getEntityManager().unwrap(Session.class);
        }
        return session;
    }

}

I get issue at this line;
Customer item = em.find(Customer.class,entity.getId());

Error
Caused by: java.lang.IllegalStateException: Session/EntityManager is closed
    at org.hibernate.internal.AbstractSharedSessionContract.checkOpen(AbstractSharedSessionContract.java:326)
    at org.hibernate.engine.spi.SharedSessionContractImplementor.checkOpen(SharedSessionContractImplementor.java:126)
    at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3312)
    at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3297)
    at org.jboss.as.jpa.container.AbstractEntityManager.find(AbstractEntityManager.java:213)
    at com.leightonobrien.lob2.service.autogen.CustomerService.update(CustomerService.java:412)
    at sun.reflect.GeneratedMethodAccessor249.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)

A: Issue here is I closed the session. After removing it, everything works fine


Q: Allow only numeric value in textbox using Javascript I want to allow only numeric values to be entered into the text and if user enters alphabetic character it should warn the user.
Any suggestion for optimized and short javascript code?

A: function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

from here

A: use following code
function numericFilter(txb) {
   txb.value = txb.value.replace(/[^\0-9]/ig, "");
}

call it in on key up
<input type="text" onKeyUp="numericFilter(this);" />

A: Here is a solution which blocks all non numeric input from being entered into the text-field.
html
<input type="text" id="numbersOnly" />

javascript
var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
    var k = e.which;
    /* numeric inputs can come from the keypad or the numeric row at the top */
    if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
        e.preventDefault();
        return false;
    }
};

A: Please note that, you should allow "system" key as well
    $(element).keydown(function (e) {
    var code = (e.keyCode ? e.keyCode : e.which), value;
    if (isSysKey(code) || code === 8 || code === 46) {
        return true;
    }

    if (e.shiftKey || e.altKey || e.ctrlKey) {
        return ;
    }

    if (code >= 48 && code <= 57) {
        return true;
    }

    if (code >= 96 && code <= 105) {
        return true;
    }

    return false;
});

function isSysKey(code) {
    if (code === 40 || code === 38 ||
            code === 13 || code === 39 || code === 27 ||
            code === 35 ||
            code === 36 || code === 37 || code === 38 ||
            code === 16 || code === 17 || code === 18 ||
            code === 20 || code === 37 || code === 9 ||
            (code >= 112 && code <= 123)) {
        return true;
    }

    return false;
}

A: // Solution to enter only numeric value in text box
$('#num_of_emp').keyup(function () {
    this.value = this.value.replace(/[^0-9.]/g,'');
});

for an input box such as :
<input type='text' name='number_of_employee' id='num_of_emp' />

A: @Shane, you could code break anytime, any user could press and hold any text key like (hhhhhhhhh) and your could should allow to leave that value intact.
For safer side, use this:
$("#testInput").keypress(function(event){

instead of:
$("#testInput").keyup(function(event){

I hope this will help for someone.

A: or
function isNumber(n){
  return (parseFloat(n) == n);
}

http://jsfiddle.net/Vj2Kk/2/

A: This code uses the event object's .keyCode property to check the characters typed into a given field. If the key pressed is a number, do nothing; otherwise, if it's a letter, alert "Error". If it is neither of these things, it returns false.
HTML:
<form>
    <input type="text" id="txt" />
</form>

JS:
(function(a) {
    a.onkeypress = function(e) {
        if (e.keyCode >= 49 && e.keyCode <= 57) {}
        else {
            if (e.keyCode >= 97 && e.keyCode <= 122) {
                alert('Error');
                // return false;
            } else return false;
        }
    };
})($('txt'));

function $(id) {
    return document.getElementById(id);
}

For a result: http://jsfiddle.net/uUc22/
Mind you that the .keyCode result for .onkeypress, .onkeydown, and .onkeyup differ from each other.

A: Javascript For only numeric value in textbox ::
<input type="text" id="textBox" runat="server" class="form-control" onkeydown="return onlyNos(event)" tabindex="0" />

    <!--Only Numeric value in Textbox Script -->
        <script type="text/javascript">
            function onlyNos(e, t) {
                try {
                    if (window.event) {
                        var charCode = window.event.keyCode;
                    }
                    else if (e) {
                        var charCode = e.which;
                    }
                    else { return true; }
                    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                        return false;
                    }
                    return true;
                }
                catch (err) {
                    alert(err.Description);
                }
            }
        </script>
        <!--Only Numeric value in Textbox Script -->


Q: Spring Data JPA Self Join with Nullable foreign key I have problem with Spring Data JPA. I want to create a category that have parent category with the same table. Some categories don't need to have parent category, so parent category can be null. but when I do that, and save it, it shown error as below:
org.hibernate.TransientPropertyValueException: object references an unsaved
transient instance - save the transient instance before flushing :
com.ltech.solutions.ecom.models.category.Category.parent ->
com.ltech.solutions.ecom.models.category.Category

Here is my model:
@Entity
@Table(name = "tb_category")
public class Category extends BaseEntity {

    @Column(name = "name", nullable = false)
    private String name;

    @JsonIgnore
    @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id", referencedColumnName = "id")
    private Category parent;

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    @JsonProperty(value = "sub_categories")
    private Set<Category> subCategories;

    @Column(name = "is_visible", insertable = false, columnDefinition =
    "BOOLEAN DEFAULT TRUE")
    @JsonProperty(value = "is_visible")
    private Boolean isVisible;

    @Column(name = "is_enable", insertable = false, columnDefinition = "BOOLEAN
    DEFAULT TRUE")
    @JsonProperty(value = "is_enable")
    private Boolean isEnable;

    @Column(name = "desc_attribute")
    private String descAttribute;
 }

*

*When saving object, I use save method of CRUDRepsoitory.

Here is my view:
<form th:object="${createCategoryForm}" th:action="@{/category/save}"
method="post">
        <fieldset>
            <legend>Create Category</legend>

                Name
                <input class="form-control" th:field="*{name}" />

                Code
                <input class="form-control" th:field="*{code}" />

                Description (English)
                <input class="form-control" th:field="*{descEn}" />

                Description (Khmer)
                <input class="form-control" th:field="*{descKh}" />

                Attributecs
                <input class="form-control" th:field="*{descAttribute}" />

                Parent of
                <select class="form-control" th:field="*{parent.id}">
                    <option value="">None</option>
                    <option th:each="parent : ${parentCategories}" th:value="${parent.id}" th:text="${parent.name}"></option>
                </select>

            <input type="submit" />
        </fieldset>
    </form>


Q: How to import one column to a new worksheet? I have a workbook which has individual worksheets detailing client stock trading data, and a master worksheet which has month to date and week to date totals for the clients.
I would like to set up a new worksheet titled week to date which will import the week to date column from the master worksheet and save it.
Additionally, I would like it to update every time I run the macro so it has an up to date record of the week to date figures.
My current code provides sum totals for specified columns on each worksheet, and embeds the contents of the active worksheet into the body of an outlook email.
Sub AutoSum()

    Dim wscount As Long
    wscount = ActiveWorkbook.Worksheets.Count

    Dim i As Long
    For i = 1 To wscount
        Sheets(i).Select
        Range("K3").Select
        Selection.End(xlDown).Select
        ActiveCell.Offset(2, 0).Select
        Dim cel1 As String, cel2 As String
        cel1 = ActiveCell.Offset(-2, 0).End(xlUp).Address
        cel2 = ActiveCell.Offset(-1).Address
        ActiveCell.Value = "=sum(" & (cel1) & ":" & (cel2) & ")"
    Next i

    'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    'Don't forget to copy the function RangetoHTML in the module.
    'Working in Excel 2000-2016
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    Set rng = Nothing
    On Error Resume Next
    'Only the visible cells in the selection
    Set rng = Selection.SpecialCells(xlCellTypeVisible)
    'You can also use a fixed range if you want
    'Set rng = Sheets("YourSheet").Range("D4:D12").SpecialCells(xlCellTypeVisible)
    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected" & _
               vbNewLine & "please correct and try again.", vbOKOnly
        Exit Sub
    End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = "nabil.hure@dnb.no"
        .CC = ""
        .BCC = ""
        .Subject = "Today's Trades" & Date
        .HTMLBody = RangetoHTML(rng)
        .Send                                    'or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)
    ' Changed by Ron de Bruin 28-Oct-2006
    ' Working in Office 2000-2016

    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing

End Function

A: It sounds like you're just asking how to cut a column across into another worksheet. This will move everything in the K column in the master sheet and copy it to the A column in wtd. Obviously this can be changed to any column you want.
Sheets("wtd").Range("A:A").Value = Sheets("master").Range("K:K").Value


Q: Overloading functions not compiling I am following the book C++ Cookbook from O'Reilly and I try one of the examples, here is the code:
#include <string>
#include <iostream>
#include <cctype>
#include <cwctype>

using namespace std;

template<typename T, typename F>
void rtrimws(basic_string<T>& s, F f){
    if(s.empty())
        return;

    typename basic_string<T>::iterator p;
    for(p = s.end(); p != s.begin() && f(*--p););

    if(!f(*p))
        p++;

    s.erase(p, s.end());
}

void rtrimws(string& ws){
    rtrimws(ws, isspace);
}

void rtrimws(wstring& ws){
    rtrimws(ws, iswspace);
}

int main(){
    string s = "zing            ";
    wstring ws = L"zonh     ";

    rtrimws(s);
    rtrimws(ws);

    cout << s << "|\n";
    wcout << ws << "|\n";
}

When I try to compile it, I get the following error
trim.cpp: In function ‘void rtrimws(std::string&)’:
trim.cpp:22: error: too many arguments to function ‘void rtrimws(std::string&)’
trim.cpp:23: error: at this point in file

and I don't understand what's wrong. If I don't use the char version (string) but the wchar_t version only, everything runs smooth.
By the way, I am using g++ 4.4.3 in an ubuntu machine 64 bits

A: isspace is also a template in C++ which accepts a templated character and also a locale with which it uses the facet std::ctype<T> to classify the given character (so it can't make up its mind what version to take, and as such ignores the template).
Try specifying that you mean the C compatibility version: static_cast<int(*)(int)>(isspace). The differences between the compilers could come from the inconsistent handling of deduction from an overloaded function name among the compilers - see this clang PR. See the second case in Faisal's first set of testcases for an analogous case.

Someone pointed out on IRC that this code would call isspace using a char - but isspace takes int and requires the value given to be in the range of unsigned char values or EOF. Now in case that char is signed on your PC and stores a negative non-EOF value, this will yield to undefined behavior.
I recommend to do it like @Kirill says in a comment and just use the templated std::isspace - then you can get rid of the function object argument too.

A: Try rtrimws(ws, ::isspace);.
Also, just as a note, you should be using the reverse iterator.

A: That's because isspace is a template function in c++. It cannot deduce F. If you want to use C variant of isspace you could fully qualify its name as follows:
void rtrimws(string& ws){
    rtrimws(ws, ::isspace); // this will use isspace from global namespace
                            // C++ version belongs to the namespace `std`
}

This is one more good sample why you shouldn't use using namespace std.


Q: how to remove child(html elements) of div Id using jQuery I have

aa

hellow

So how to remove all content of Id "myId" Using jQuery?
The result must be this:

A: *

*Use .empty()

Description: Remove all child nodes of the set of matched elements from the DOM.

$("#myId").empty()

console.log($("#myId").get(0).outerHTML)

aa

hellow

A: You could use different ways:
// ref: https://api.jquery.com/empty/
$("#myId").empty()

// ref: https://api.jquery.com/html/
$("#myId").html('')

A: you can use remove() method. .empty()
$( "#myId" ).empty()

A: In order to remove or empty all the elements of a container div in this case, you can:
$("#myId").empty();

OR
$("#myId").html('');

Reference link to empty()


Q: jQuery status indication by file on web server I have a web server. On the web server there is a process running that is doing something. While the process (or program) is running it will post updates on the status of the task it is doing that should indicate more or less when it will be finished. (Like a status bar indicator for example with percentage number)
The process (or program) will write to a file called busy.html - Inside busy.html the following will be written by the process: Processing: 50%
busy.html is located at: http://www.somewhere.com/temp/busy.html for example.
The process on the web server will intermittently write to busy.html while it is working until 100% is reached. When 100% is reached busy.html will be removed.
On a web page I would like to have jQuery code that displays the contents of  busy.html to indicate the status or progress of the process the web server is busy with.
So in other words, Jquery should poll and display the contents of busy.html inside an existing web page until busy.html does not exist anymore.
How would the Jquery code for this look like? Perhaps there is a much easier way of passing on the progress status to jQuery instead of using a file to indicate the existing status like explained here.
Update to my question:
Also, would this be the proper way (using jQuery) to indicate the status of a process running on the server? I would like to enter a URL that is password protected and the web page that loads should tell me the status of the process running on the server. The tech that is running the process is a Perl script or program that is busy indexing the contents of files into a database.

A: You can use this code:
var place = $('#foo');
var delay = 3 * 1000; // 3 seconds
var url = 'http://www.somewhere.com/temp/busy.html';
(function recur() {
   $.ajax({url: url, success: function(page) {
      place.html(page);
      setTimeout(function() {
          recur();
      }, delay);
   }, error: function() {
     place.hide();
   }});
})();

A: Here are the steps you need.

*

*Read JQuery post or get method and see simple example.

*Inside document ready call a post or get request (get would do with your scenario) and url will point to busy.html

*In response you will get data that is your html or text written inside busy.html

*You can then use the last three letters of that text to fetch percentage and show a chart, guage or simple text as you wish.

Its not complicated.


Q: Use Regular Expressions to find a date in a String I am trying to use regular Expressions to extract the dates from a string using VBA in Excel.
The string is:
Previous Month: 9/1/2015 - 9/30/2015

Or it can be :
Custom: 9/1/2015 - 9/30/2015

Do you have any idea how can I achieve that? I have never used Regular Expressions before.

A: RegEx is a poor choice for dates. You could look for : and examine the remaining tokens:
Sub Foo()
    Dim result() As Variant

    result = GetDates("Previous Month: 9/1/2015 - 9/30/2015")

    If UBound(result) Then
        Debug.Print result(0)
        Debug.Print result(1)
    End If
End Sub

Function GetDates(str As String) As Variant()
    Dim tokens() As String
    tokens = Split(Mid$(str, InStr(str & ": ", ":")), " ")

    If (UBound(tokens) = 3) Then
        If IsDate(tokens(1)) And IsDate(tokens(3)) Then
            GetDates = Array(CDate(tokens(1)), CDate(tokens(3)))
            Exit Function
        End If
    End If

    ReDim GetDates(0)
End Function

A: Try this:
([1-9]|1[012])[/]([1-9]|[1-2][0-9]|3[01])[/](19|20)[0-9]{2}

A: search a commandtext string for dates and then replace them with a new date
dim regex as object
 Set regex = CreateObject("VBScript.RegExp")
 regex.Pattern = "\d{1,2}[-/]\d{1,2}[-/]\d{2,4}"
 regex.Global = True
 Set regexMatches = regex.Execute(CommandText)
 for i=0 to regexMatches.Count()
        date1 = regexMatches(i)
 next


Q: Image create using gd I am creating image using GD library all the functions are working fine. But the main problem where i stucked that i want to merge png image over an other image but after overlapping it cannot merge properly and looking like jpg or other instead of png. I cannot upload my image here due to low reputation so click on these links below to see the image.
The image which i want to merge is this
Png image

The image where i merge above image is:

My code is here:
<?php
$im = imagecreate(288,288);
$background_color = imagecolorallocate($im, 230, 248, 248);
$file = 'images/smiley/smile'.$_POST['smiley'].'.png';
$bg = imagecreatefrompng($file);
imagealphablending($im, true);
imagesavealpha($bg, true);
imagecopyresampled($im, $bg, 80, 80, 0, 0, 50, 50, 185, 185);

                           header("Content-Type: image/png");
            $filename = $_SESSION['rand'].'.png';
            imagepng($im,$filename);
            echo '<img src="'.$filename.'" alt="" />';
?>

A: Your background image doesn't have an alpha channel. This makes the PHP GD library do all of it's copying operations without using an alpha channel, instead just setting each pixel to be fully opaque or transparent, which is not what you want.
The simplest solution to this is to create a new image of the same size as the background that has an alpha channel, and then copy both the background and face into that one.
$baseImage = imagecreatefrompng("../../var/tmp/background.png");
$topImage = imagecreatefrompng("../../var/tmp/face.png");

// Get image dimensions
$baseWidth  = imagesx($baseImage);
$baseHeight = imagesy($baseImage);
$topWidth   = imagesx($topImage);
$topHeight  = imagesy($topImage);

//Create a new image
$imageOut = imagecreatetruecolor($baseWidth, $baseHeight);
//Make the new image definitely have an alpha channel
$backgroundColor = imagecolorallocatealpha($imageOut, 0, 0, 0, 127);
imagefill($imageOut, 0, 0, $backgroundColor);

imagecopy($imageOut, $baseImage, 0, 0, 0, 0, $baseWidth, $baseHeight); //have to play with these
imagecopy($imageOut, $topImage, 0, 0, 0, 0, $topWidth, $topHeight); //have to play with these

//header('Content-Type: image/png');
imagePng($imageOut, "../../var/tmp/output.png");

That code produces this image:


Q: 404 Response with Retrofit POST request with Headers parameters I am new to Retrofit Library. When I sending post request with headers parameters using hashMap using @HeaderMap annotation.
Below is my code
 @POST(Constants.UrlPath.POST_CLOSE_EVENT)
Call<ResponseBody> callDeleteEventRequest(@HeaderMap Map <String, String>id);

I am sending the headers using HashMap here like this.
 HashMap<String, String> headers = new HashMap<>();
                 headers.put("eventId", String.valueOf(1));

I am getting 404 error response. Please some one help me.
I have reviewed some Stack Overflow links, but again I am getting this error.

A: Try this:
@FormUrlEncoded
@POST(Constants.UrlPath.POST_CLOSE_EVENT)
Call<ResponseBody> callDeleteEventRequest(@FieldMap Map <String, String>id);

A: add headers in your interface class:
 @Headers({"Content-Type: application/json",
        "eventId: 1"})
@POST(Constants.UrlPath.POST_CLOSE_EVENT)
Call<ResponseBody> callDeleteEventRequest();

A: check your path Constants.UrlPath.POST_CLOSE_EVENT is right or not.
try to call using postman if it is working fine in that or not.


Q: Harmonic Average Yields incorrect Result As a homework assignment we are required to calculate the harmonic mean using an assembly program being driven by a C program.
We are using 64-bit linux machines and are required to use 64-bit floating point numbers.
I am new to Assembly. I apologize for any bad coding practices or if my code is just flat out wrong.

The problem with the code is the result returns only the last number entered in floating-point format. I do not know where the error occurs, although I believe it to lie in the addDen function.
As an example: If you were to enter the numbers 5, 6, 7, 8 the result would return 8.0000.
Here is my code for the assembly program:
;Assembly function that computs the harmonic mean
;of an array of 64-bit floating-point numbers.
;Retrieves input using a C program.
;
;Harmonic mean is defined as Sum(n/((1/x1) + (1/x2) + ... + (1/xn)))
;
;   expects:
;       RDI - address of array
;       RSI - length of the array
;   returns
;       XMMO - the harmonic average of array's values

global harmonicMean

section .data
    Zero dd 0.0
    One dd 1.0

section .text
    harmonicMean:
        push rbp
        mov rbp, rsp                    ;C prologue

        movss xmm10, [Zero]     ;Holds tally of denominator
        cvtsi2ss xmm0, rsi      ;Take length and put it into xmm0 register

        .whileLoop:
            cmp rsi, 0                  ;Is the length of array 0?
            je .endwhile
            call addDen                 ;Compute a denominator value and add it to sum
            add rdi, 4                  ;Add size of float to address
            dec rsi                         ;Decrease the length
            jmp .whileLoop
        .endwhile:

        divss xmm0, xmm10

        leave
        ret

    ;Calculates a number in the denominator
    addDen:
        push rdi
        movss xmm8, [One]
        movss xmm9, [rdi]
        divss xmm8, xmm9
        addss xmm10, xmm8
        pop rdi
        ret

In order to recreate the logic error, i will also include my driver program:
/*
* Harmonic Mean Driver
* Tyler Weaver
* 03-12-2014
*/
#include<stdio.h>

#define ARRAYSIZE 4

double harmonicMean(double *, unsigned);

int main(int argc, char **argv) {
    int i;
    double ary[ARRAYSIZE];
    double hm;

    printf("Enter %d f.p. values: ", ARRAYSIZE);

    for (i = 0; i < ARRAYSIZE; i++) {
        scanf(" %lf", &ary[i]);
    }

    hm = harmonicMean(ary, ARRAYSIZE);
    printf("asm: harmonic mean is %lf\n", hm);

    return 0;
}

Any help will be much appreciated!

A: Yes there seems to be float vs double confusion. You pass in a double array, but pretty much all of the asm code expects floats: you use the ss instructions and you assume size 4 and you return a float too.
                    – Jester
There was an issue with floats and doubles! I really appreciate both of your responses. I was confused because the instructor had told us to use floats in our assembly program he had used doubles in an example driver. I spoke with the instructor and he had fixed his instructions. I thank you again! – Tyler Weaver

A: here is the algorithm, is a mix between C and pseudo code
My suggestion is to write this program in C.
Then have the compiler output the related asm language
then use that asm output as a guide in writing your own program

! ----------------------------------------------------------
! This program reads a series of input data values and
! computes their arithmetic, geometric and harmonic means.
! Since geometric mean requires taking n-th root, all input
! data item must be all positive (a special requirement of
! this program , although it is not absolutely necessary).
! If an input item is not positive, it should be ignored.
! Since some data items may be ignored, this program also
! checks to see if no data items remain!
! ----------------------------------------------------------

PROGRAM   ComputingMeans
   IMPLICIT  NONE

   REAL    :: X
   REAL    :: Sum, Product, InverseSum
   REAL    :: Arithmetic, Geometric, Harmonic
   INTEGER :: Count, TotalNumber, TotalValid

   Sum        = 0.0                     ! for the sum
   Product    = 1.0                     ! for the product
   InverseSum = 0.0                     ! for the sum of 1/x
   TotalValid = 0                       ! # of valid items

   READ(*,*)  TotalNumber               ! read in # of items
   DO Count = 1, TotalNumber            ! for each item ...
      READ(*,*)  X                      ! read it in
      WRITE(*,*) 'Input item ', Count, ' --> ', X
      IF (X <= 0.0) THEN                ! if it is non-positive
         WRITE(*,*) 'Input <= 0.  Ignored'   ! ignore it
      ELSE                              ! otherwise,
         TotalValid = TotalValid + 1    ! count it in
         Sum        = Sum + X           ! compute the sum,
         Product    = Product * X       ! the product
         InverseSum = InverseSum + 1.0/X     ! and the sum of 1/x
      END IF
   END DO

   IF (TotalValid > 0) THEN             ! are there valid items?
      Arithmetic = Sum / TotalValid     ! yes, compute means
      Geometric  = Product**(1.0/TotalValid)
      Harmonic   = TotalValid / InverseSum

      WRITE(*,*)  'No. of valid items --> ', TotalValid
      WRITE(*,*)  'Arithmetic mean    --> ', Arithmetic
      WRITE(*,*)  'Geometric mean     --> ', Geometric
      WRITE(*,*)  'Harmonic mean      --> ', Harmonic
   ELSE                                 ! no, display a message
      WRITE(*,*)  'ERROR: none of the input is positive'
   END IF

END PROGRAM  ComputingMeans


Q: How to call d3 pie chart on button click in angularjs? I am trying to display pie chart using d3.js charts in angularjs . As far as the examples i have seen so far implements pie chart on load . But here i want to display pie chart based on the response from service which is called on a button click . Need some guidance to start
my user.html

Group by users

<select name="users" id="search" ng-model="searchItem">
<option value="">Search By</option>
<option value="admin">admin</option>
<option value="superAdmin">superAdmin</option>

</select>

<button ng-click="search()">Search</button>

my user.js
'use strict';

 angular.module('myApp.employee',['ngRoute'])

 .config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/employee', {
  templateUrl: 'employee/employee.html',
  controller: 'EmployeeCtrl'
  });
    }])

   .controller('EmployeeCtrl', ['$scope','$http',function($scope,$http) {
    $scope.search = function(){

    var   search=angular.element(document.getElementById("search"));
    //var data ;

    $scope.searchItem =search.val();
    console.log($scope.searchItem);

    $http.get("/assets/empDetails.json").then(function(response){

     // $scope.empDetail=response.data
      console.log(response.data);
      console.log();
    //   function groupBy(arr, prop) {
    //     const map = new Map(Array.from(arr, obj => [obj[prop], []]));
    //     arr.forEach(obj => map.get(obj[prop]).push(obj));
    //     return Array.from(map.values());
    // }

   // console.log(groupBy(response.data,$scope.searchItem ));

    var rows = response.data;
    var keyName =$scope.searchItem;
    groupBy(keyName);

    function groupBy(keyName) {
      console.log("Group By :: ", keyName)

      var occurences = rows.reduce(function (r, row) {
          r[row[keyName]] = ++r[row[keyName]] || 1;
          return r;
      }, {});

      var result = Object.keys(occurences).map(function (key)       {
          return { key: key, value: occurences[key] };
      });

      console.log(result);
      //data = result ;
      $scope.data = [
        {
          name : "Blue",
          value : 10,
          color : "#4a87ee"
        },
        {
          name : "Green",
          value : 40,
          color : "#66cc33"
        },
        {
          name : "Orange",
          value : 70,
          color : "#f0b840"
        },
        {
          name : "Red",
          value : 2,
          color : "#ef4e3a"
        }
      ];
  }

    })

    }

   }])

   .directive ("pieChart", function () {
     return {
    restrict : "A",
    scope : {
        data : "="
    },
    link : function (scope, element) {
        var width,
            height,
            radius,
            pie,
            arc,
            svg,
            path;

        width = element[0].clientWidth;
        height = element[0].clientHeight;
        radius = Math.min (width, height) / 2;

        pie = d3.layout.pie ()
                .value (function (d) {return d.value;})
                .sort (null);

        arc = d3.svg.arc ()
                .outerRadius (radius - 20)
                .innerRadius (radius - 80);

        svg = d3.select (element[0])
                .append ("svg")
                .attr ({width : width, height : height})
                .append ("g")
                .attr ("transform", "translate(" + width * 0.5 + "," + height * 0.5 + ")");

        path = svg.datum (scope.data)
                .selectAll ("path")
                .data (pie)
                .enter ()
                .append ("path")
                .attr ({
                    fill : function (d, i) {return scope.data [i].color;},
                    d : arc
                });

        scope.$watch (
            "data",
            function () {
                pie.value (function (d) {return d.value;});
                path = path.data(pie);
                path.attr("d", arc);
            },
            true
        );
    }
};

})
i have used this https://embed.plnkr.co/plunk/jDvdSh as reference . All i want to implement is on search i want perform the service call and then manipulate the response and render it as a pie chart.or someone please explain how the pie chart directive is called in the above plnkr reference that would be more helpful


Q: Finding 2D points reachable with short intermediate hops I have a list allNodes of around 60,000 nodes that correspond to 2D points. I'm constructing an adjacency list like
for(i in allNodes)
  for(j in allNodes)
    if(distance(i, j) <= 10) addEdge between i and j

and then performing a depth-first search from a set of sourceNodes to find the set of nodes reachable from sourceNodes. How can I make this faster than quadratic? I'm using C++.

A: The easy approach is to divide the plane into d-by-d where d > 10 bins and put each point in the bin indexed by floor(x/d), floor(y/d). Then, instead of iterating over all pairs of points,
for bin1 in bins:
   for i in bin1:
      for bin2 in bins neighboring bin in nine directions (including bin):
         for j in bin2:
            if(distance(i, j) <= 10) addEdge between i and j

This will make things faster if the points are well spread, but the worst case is still quadratic.
For a guaranteed O(n log n)-time algorithm, compute the Delaunay triangulation and throw away the edges longer than 10. This may remove some direct connections between nodes at distance less than or equal to 10, but they will still be connected indirectly.

A: The binning approach suggested by David Eisenstat's answer works if you expect points to be homogeneously distributed, which is not a property you specified about your data. Additionally, as noted, the Delaunay triangulation still requires local search on the induced graph to ensure that all nodes within the specified distance are found.
One way to get guaranteed performance is with a kd-tree. You can build one in O(2n log n) time (or faster if you don't care as much about guarantees and use randomization) and use it for performing range searches with a total time of O(2n√n).
It's unclear to me whether the Delaunay triangulation or the kd-tree would be faster in practice, but it seems to me that finding and using an appropriate kd-tree library would be a fast and simple solution, if you are worried about development time.


Q: Java auto-update jar files- Eclipse I have designed a Desktop based GUI on Eclipse using Windows Builder and I have added few external jar files.
Now, I am looking to implement a mechanism which checks the updated version of those external jar files and download automatically. Replacement of these .jar files will be done manually.
Can anyone give me an advice which technique will be suitable ?
Your advice will be highly appreciated.


Q: DNA micro satelite counter I wrote a code to run over the letters in a variable fragile_x_test
and count the number of "CGG". as long as the while loop encounter "CGG" it will add it into the counter variable repeat, otherwise, it will break from the while loop and go for the "if" loop below.
After the if loop, I want the code to go back to the while loop and continue running over the letters. But I don't want it to go back to the for loop at the beginning because it will reset the i.
Does anyone have a clue how to do that? many thanks!
this is the code:
fragile_x_test = "CGGCGGCGGCGGCGGACTTCACGGCGGCGGCGGCGGCGGCGG"

for i in range(0,len(fragile_x_test)):
    repeat = 0
    tandem = 0
    while fragile_x_test[i:i+3] == "CGG":
        repeat += 1
        i = i+3
    if repeat >= 5:
        tandem +=1
        i = i+3

A: 1st method :
With .split(), you can directly get the number of 'CGG' in your string.
len(fragile_x_test.split('CGG'))-1

It should also be easier to calculate the tandem variable with it.
2nd method :
If you don't need to work on the non 'CGG' part of the string, you can use .count()
fragile_x_test.count('CGG')

3rd method :
This method only counts 1 occurrence for each one or more "CGG" in a row and will add one to tandem variable each time there is more than 5 "CGG" in a row.
example="|CGGCGGCGGCGGCGG|ACTACT|CGGCGGCGGCGGCGGCGGCGG|"

count , repeat , tandem = 0 , 0 , 0
for element in example.split('CGG')[1:-1]:
    if element == '':
        count+=1
        if count==4: tandem+=1
    else:
        count=0

    if count==1:
        repeat+=1

print("Number of CGG in a row : ",repeat)
print("Number of CGG tandems : ",tandem)

It will print repeat=2 and tandem=2.


Q: Automatically Update Work Item Status within Visual Studio (From 'New' to 'Active') Is there a way to automatically update the status of a Work Item within Azure DevOps from 'New' to 'Active' when the item is added to my 'In Progress Work' from within the 'Available Work Items' section of Visual Studio?
Brief context: I'm using the Kanban board within Azure DevOps and I'd like to move work items along the columns / stages in as automated a way as possible via Visual Studio.
This synchronisation seems to be working fine for items going from 'Active' to 'Resolved', e.g. when I add items to my 'In Progress', amend some code, and perform a check in, I can visually see the item move over to the next column of my Kanban board - it's also changing it's status from 'Active' to 'Resolved'.

A:
Is there a way to automatically update the status of a Work Item
  within Azure DevOps from 'New' to 'Active' when the item is added to
  my 'In Progress Work' from within the 'Available Work Items' section
  of Visual Studio?

The status of the work items in Azure DevOps is not a one-to-one relationship with the work item status of My work in Visual Studio.
The status of work item in Visual Studio is used to classify the work items not change the status of the work item, so that we can more clearly distinguish which work items are being processed.
You can view the description of In Progress Work in Visual Studio is：

drag a work item here to get started

This looks more like a swim lanes, giving developers a clearer idea of which workitems are associated with development.
Besides, when we commit the code and status of work items, there is option which we could select only with Associate and Resolve:

Only if we confirm that the currently associated work item is completed, we will choose the option to Resolve, otherwise it will be Associate.
On the other hand, we could add a custom status of work item on the Azure DevOps. Obviously, we could not match our new custom state to the status of work item in Visual Studio.
Hope this helps.


Q: Python Replace Quoted Values In External SQL Query I use the simple query below to select from a table based on the date:
select * from tbl where date = '2019-10-01'

The simple query is part of a much larger query that extracts information from many tables on the same server. I don't have execute access on the server, so I can't install a stored procedure to make my life easier. Instead, I read the query into Python and try to replace certain values inside single quote strings, such as:
select * from tbl where date = '<InForceDate>'

I use a simple Python function (below) to replace  with another value like 2019-10-01, but the str.replace() function isn't replacing  when I look at the output. However, I tried this with a value like  that wasn't in quotes and it worked.  I'm sure I'm missing something fundamental, but haven't uncovered why it works without quotes and fails with quotes.
Python:
def generate_sql(sql_path, inforce_date):
    with open(pd_sql_path, 'r') as sql_file:
        sql_string = sql_file.read()
        sql_final = str.replace(sql_string, r'<InForceDate>', inforce_date)

    return(sql_final)

Can anyone point me in the right direction?

A: Nevermind folks -- problem solved, but haven't quite figured out why. File encoding is my guess.


Q: Custom tabs with duplicate tab label name not getting filled in According to: Custom tag in documents uploaded using API, multiple tabs with the same tab label should all be getting filled in with the same value, however, for me, only the first instance is getting that value.  I have multiple text tabs with the same tab label, and am creating the envelope with: "text" + "tabLabel" + kvp.Key + "tabLabel" + "value" + kvp.Value + "value" + "text" , yet only the first occurrence of that tab label gets the value.  Any suggestions ?

A: In your API request, try prefacing the tabLabel with \\*.  For example, if multiple text tabs have the label "address", the portion of the API request to populate those tabs (each with the value '123 Main Street') would look like this:
"tabs":{
    "textTabs":[
       {
          "tabLabel":"\\*address",
          "value":"123 Main Street"
       },
    ],
}


Q: PhpMyAdmin Create Database No Privileges issue on Mac I have just installed the PhpMyAdmin on my Mac (Yosomite 10.10.5), Everything looks fine, But when I log in to PhoMyAdmin as root and try to create a new database, It shows No Privileges
Screenshot here: https://i.stack.imgur.com/YNfSs.png
Thanks in Advance

A: Log in via phpMyAdmin with a MySQL account that has sufficient privileges (like root). If you don't have such account, ask this MySQL server's manager about it.


Q: How to use EF4 as a DAL I am currently using EF 4 with my ASP.NET Website to access a MySql database. This works fine. However I now want another Web Site project to access the same entities. How do I set this up?
I can't just reference the original website as it's a Web Site, not a Web Application. So presumably, I need to put the Entity Data Model in its own project and compile to a DLL. But...

*

*Which project type?

*Do I just cut and paste the DataModel.edmx and DataModel.Designer.cs, compile and add a reference in both websites? What about namespaces?

*Where do I put the connection string? At the moment it's in my project's Web.config.

I really have no idea where to begin - I've just followed tutorials to get EF working up to now! I'd really appreciate step-by-step instructions if anyone has time. Thanks.

A: The model should be placed in a new class library project. My preference would be to recreate the model at this point based on the existing model. For the namespace I like to use {CompanyName}.DataAccess. Remove the old model from your web site project, add a reference to the new class library project and build the web site project. The website project will break in many places, but it should be a simple matter of changing the namespace to the new data access assembly. I prefer this method as to cut/paste because now you have nice clean namespaces. Be careful of any places you may have strings with entity names in them, like if you were using Include (if you are using EF 4 and lazy loading, this should not be a problem). Leave the connection string in web.config for both of the web site projects. When you create the model in the class library, it will add a connection string in app.config. That is OK, it is just there so the model knows how to connect to the database when you refresh it.


Q: Windows Store app submission is non-compliant (not accepting applications submitted through the DreamSpark developer program) I submitted my app updates for certification, but the certification process failed:

Thanks for your interest in Windows Store. Unfortunately, at this
  time, we are not accepting applications submitted through the
  DreamSpark developer program.  We apologize for any inconvenience this
  may cause. We also encourage you to read a recent blog on how to make
  your app more visible in the Store
  (https://blogs.windows.com/buildingapps/2016/01/15/give-your-apps-more-visibility-six-recommendations-for-2016)
  to build quality apps that customers want. Please reach out to
  Developer Support if you have any questions.
Locations: Metadata

DreamSpark developers won't be able to submit apps to windows store?
PS: many people have the same problem - https://social.msdn.microsoft.com/Forums/en-US/3f90fbf2-42a3-4c85-8fc3-6ac8bb06c173/is-app-submission-from-dreamspark-developers-postponed

A: The message received is correct.  There have been issues with misuse of Dreamspark accounts that were causing severe issues with the Store.  However, we realize that many of you are not part of this activity and as such we can help you by contacting Developer Support.  Please contact them directly so that they have your account information and can get your apps set up for success!
Thanks
Jo
Windows App and Catalog Operations


Q: Spring Doc: swagger-ui.html giving Whitelabel Error Page 404 I am using springdoc-open api for swagger integration in my springboot project.
I have added below property in application.yml
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_mathcher

and added below  dependency in build.gralde file
implementation "org.springdoc:springdoc-openapi-ui:1.6.9"

I am able to access /v3/api-docs , but /swagger-ui/index.html and /swagger-ui.html giving 404 Whitelabel Error Page

A: After googling so many thins, I found a solution to this issue. I had to add an additional configuration class that is OpenApiConfig.java to make it work.
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"org.springdoc"})
@Import({org.springdoc.core.SpringDocConfiguration.class,
org.springdoc.webmvc.core.SpringDocWebMvcConfiguration.class,
org.springdoc.webmvc.ui.SwaggerConfig.class,
org.springdoc.core.SwaggerUiConfigProperties.class,
org.springdoc.core.SwaggerOAuthProperties.class,
org.springframework.autoconfigure.jackson.JacksonAutoConfiguration.class})
class OpenApiConfig implements WebMvcConfigurer {
}


Q: How to update(refresh) JTable with data from a database I'm trying to update a JTable after I add or remove a record from the database (MS Access), but it doesn't seem to work.  Also, I don't understand why my column names do not show up. Here's my code:
package Administrator13_03_13;

public class Arsti2 {
JFrame main = new JFrame("Ārst");
JPanel tP = new JPanel();
JPanel bP = new JPanel();
JButton one = new JButton("Test");
JTable table = new JTable();
DefaultTableModel model;
Vector columnNames = new Vector();
Vector data = new Vector();

Arsti2() {
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.setSize(840,300);
    try {

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        String Base = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=SL.mdb";
        Connection con = DriverManager.getConnection(Base,"","");
        Statement st = con.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM Arsti");
        ResultSetMetaData rsmd = res.getMetaData();
        int column = rsmd.getColumnCount();
        columnNames.addElement("ID");
        columnNames.addElement("Vards");
        columnNames.addElement("Uzvards");
        columnNames.addElement("Dzimums");
        columnNames.addElement("Personas kods");
        columnNames.addElement("Telefona numurs");
        columnNames.addElement("Nodalas ID");
        columnNames.addElement("Amata ID");
        while(res.next()) {
            Vector row = new Vector(column);
            for(int i=1; i<=column; i++) {
                row.addElement(res.getObject(i));
            }
            data.addElement(row);
        }
        model = new DefaultTableModel(data,columnNames);
        table.setModel(model);
        //model.fireTableDataChanged();
        tP.add(table);
        bP.add(one);
        main.add(tP,BorderLayout.NORTH);
        main.add(bP,BorderLayout.SOUTH);
    } catch(Exception e) {
        e.printStackTrace();
    }
    main.setVisible(true);
    one.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evnt1) {
            model.fireTableDataChanged();
        }
    });
}

public static void main(String[] args) {
    new Arsti2();
}
}

A:
also I don't understand why doesn't my column names show up

Column names won't show up unless you add a container (like a JScrollPane) to it.
add(new JScrollPane(table));
should be enough.

A: Just  model.fireTableDataChanged();wont work you have to reload your model from database
This should work:
public class Arsti2 {
JFrame main = new JFrame("Ārst");
JPanel tP = new JPanel();
JPanel bP = new JPanel();
JButton one = new JButton("Test");
JTable table = new JTable();
DefaultTableModel model;
Vector columnNames = new Vector();
Vector data = new Vector();

Arsti2() {
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.setSize(840,300);
    try {

        reloadData();
        model = new DefaultTableModel(data,columnNames);
        table.setModel(model);
        //model.fireTableDataChanged();
        tP.add(table);
        bP.add(one);
        main.add(tP,BorderLayout.NORTH);
        main.add(bP,BorderLayout.SOUTH);
    } catch(Exception e) {
        e.printStackTrace();
    }
    main.setVisible(true);
    one.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evnt1) {
            try {
                reloadData();
                 model.fireTableDataChanged();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
}

private void reloadData() throws ClassNotFoundException, SQLException {
    columnNames.clear();
 data.clear();
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String Base = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=SL.mdb";
    Connection con = DriverManager.getConnection(Base,"","");
    Statement st = con.createStatement();
    ResultSet res = st.executeQuery("SELECT * FROM Arsti");
    ResultSetMetaData rsmd = res.getMetaData();
    int column = rsmd.getColumnCount();
    columnNames.addElement("ID");
    columnNames.addElement("Vards");
    columnNames.addElement("Uzvards");
    columnNames.addElement("Dzimums");
    columnNames.addElement("Personas kods");
    columnNames.addElement("Telefona numurs");
    columnNames.addElement("Nodalas ID");
    columnNames.addElement("Amata ID");
    while(res.next()) {
        Vector row = new Vector(column);
        for(int i=1; i<=column; i++) {
            row.addElement(res.getObject(i));
        }
        data.addElement(row);
    }
}

public static void main(String[] args) {
    new Arsti2();
}
}


Q: How To Create JPanels at runtime and show its name when user click on it I am creating Chess game , for this i am creating 64 JPanels using Loop. and changing background color, here is the example code that i am using to create panel and changing its background color.
for(int i=0;i<8;i++)
    {
        for( int j=0;j<8;j++)
        {
            jp[i][j]=new JPanel();
            p.add(jp[i][j]);
            this.allSquares.add(jp[i][j]); // adding panel in arraylist of type Jpanel
            if(j%2==0&&i%2==0)// code to change background color of panels for chess board
            {
            jp[i][j].setBackground(Color.DARK_GRAY);
            }
            if(j%2!=0&&i%2!=0)
            {
            jp[i][j].setBackground(Color.DARK_GRAY);
            }
        }
    }

i need code to get name of the JPanel when user click on it in chess board

A: extend JPanel and add a name property that you want to save and read
   class MyPanel extends JPanel {
        public final int i;
        public final int j;
        public MyPanel(int i,int j){
            super();
            this.i = i;
            this.j = j;
        }
    }

and
for(int i=0;i<8;i++)
    {
        for( int j=0;j<8;j++)
        {
            jp[i][j]=new MyJPanel(i,j);
            p.add(jp[i][j]);
            jp[i][j].addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    MyPanel p = (MyPanel)e.getSource();
                    // p.i p.j
                }
            });
            this.allSquares.add(jp[i][j]); // adding panel in arraylist of type Jpanel
            if(j%2==0&&i%2==0)// code to change background color of panels for chess board
            {
            jp[i][j].setBackground(Color.DARK_GRAY);
            }
            if(j%2!=0&&i%2!=0)
            {
            jp[i][j].setBackground(Color.DARK_GRAY);
            }
        }
    }

and on click listener, cast panel to MyPanel
MyPanel p = (MyPanel)object;
String name = p.name;


Q: Inserting a string between certain characters in another string Say I have a string, say String stringy = "<Monkey><Banana><Raffle/>"
and another string String stringier = <Cool stuff to add/>
How can I insert stringier between the closing > of <Banana> and the opening < of <Raffle/>? I can't use the index of the string either, because stringy could have more or less characters before the <Raffle/> and will likely never be the same thing. Any ideas?

A: Are you just looking for a find and replace? If not, can you expand on your question?
stringy = stringy.replace("<Banana><Raffle/>", "<Banana>"+ stringier +"<Raffle/>")

A: This can be another option:
stringy = stringy.substring(0, stringy.indexOf("<Banana>") + "<Banana>".length())
      + stringier
      + stringy.substring(stringy.indexOf("<Banana>") + "<Banana>".length());

A: You can use String.indexOf to find an occurrence of a string within another string. So, maybe it would look something like this.
    String stringy = "<Monkey><Banana><Raffle/>";
    String stringier = "<Cool stuff to add/>";

    String placeToAdd = "<Banana><Raffle/>";
    String addAfter = "<Banana>";
    int temp;

    temp = stringy.indexOf(placeToAdd);
    if(temp != -1){
        temp = temp+addAfter.length();

        stringy = stringy.substring(0, temp) + stringier + stringy.substring(temp+1, stringy.length());

        System.out.println(stringy);
    } else {
        System.out.println("Stringier \'" + stringier+"\" not found");
    }

After looking at other answers, replace is probably a better option than the substring stuff.

A: Java strings are immutable, but StringBuilder is not.
public class StringyThingy {
  public static void main(String[] args) {
    StringBuilder stringy = new StringBuilder("<Monkey><Banana><Raffle/>");

    System.out.println(stringy);

    // there has to be a more elegant way to find the index, but I'm busy.
    stringy.insert(stringy.indexOf("Banana")+"Banana".length()+1,"<Cool stuff to add/>");

    System.out.println(stringy);
  }
}

// output
<Monkey><Banana><Raffle/>
<Monkey><Banana><Cool stuff to add/><Raffle/>


Q: Pandas Create Percentages from Category Sums I have a dataset of website traffic, for about 2000 websites over a period of a month, tabulated by the type of device from which the traffic originated:
In [12]: df.sample(10)
Out[12]:
         date                  device  nb_uniq_visitors  site_id
11 2017-10-31                     Tv               0.0   3331.0
6  2017-10-22            Car browser               0.0    503.0
7  2017-10-22                 Camera               0.0   3259.0
7  2017-10-08            Car browser               0.0    630.0
3  2017-10-23                 Camera               0.0    118.0
0  2017-10-12                Desktop               1.0   4769.0
11 2017-10-31                     Tv               0.0    361.0
5  2017-10-12                Phablet               0.0   2999.0
9  2017-10-17  Portable media player               0.0   1725.0
0  2017-10-13                Desktop            2410.0   1004.0
4  2017-10-13                all                 900.0   1271.0

Note that the all category of the device column represents the total of all devices, therefore it could serve as the denominator of the percentage calculation.
I want to see the percentages of device types for each website, I'm imagining the output looking like this (I manually calculated the below for example):
                               nb_uniq_visitors
site_id device
74.0    Camera                         0.00
        Car browser                    0.00
        Console                        0.00
        Desktop                        0.56
        Feature phone                  0.00
        Phablet                        0.01
        Portable media player          0.00
        Smart display                  0.00
        Smartphone                     0.37
        Tablet                         0.05
        Tv                             0.00
        Unknown                        0.00
        all                            1.00
96.0    Camera                         0.00
        Car browser                    0.00
        Console                        0.00
        Desktop                        0.64
        Feature phone                  0.00
        Phablet                        0.01
        Portable media player          0.00
        Smart display                  0.00
        Smartphone                     0.29
        Tablet                         0.06
        Tv                             0.00
        Unknown                        0.01
        all                            1.00

I used groupby to group by site_id and device:
In [23]: sl = df.groupby(['site_id', 'device']).sum()

In [24]: sl.head(25)
Out[24]:
                               nb_uniq_visitors
site_id device
74.0    Camera                              0.0
        Car browser                         0.0
        Console                             1.0
        Desktop                         10534.0
        Feature phone                       0.0
        Phablet                           178.0
        Portable media player               4.0
        Smart display                       0.0
        Smartphone                       6955.0
        Tablet                           1022.0
        Tv                                  1.0
        Unknown                            62.0
        all                             18757.0
96.0    Camera                              0.0
        Car browser                         2.0
        Console                             6.0
        Desktop                        118157.0
        Feature phone                       0.0
        Phablet                          1061.0
        Portable media player              73.0
        Smart display                       0.0
        Smartphone                      53292.0
        Tablet                          11060.0
        Tv                                  2.0
        Unknown                          1717.0
        all                            185370.0

How do I translate the above from aggregate values to percentages? Or is there a better way entirely?

A: Use DataFrame.xs for select all rows with dividing by DataFrame.div:
sl = df.groupby(['site_id', 'device']).sum()
a = sl.div(sl.xs('all', level=1))
print (a)
                               nb_uniq_visitors
site_id device
74.0    Camera                         0.000000
        Car browser                    0.000000
        Console                        0.000053
        Desktop                        0.561604
        Feature phone                  0.000000
        Phablet                        0.009490
        Portable media player          0.000213
        Smart display                  0.000000
        Smartphone                     0.370795
        Tablet                         0.054486
        Tv                             0.000053
        Unknown                        0.003305
        all                            1.000000
96.0    Camera                         0.000000
        Car browser                    0.000011
        Console                        0.000032
        Desktop                        0.637412
        Feature phone                  0.000000
        Phablet                        0.005724
        Portable media player          0.000394
        Smart display                  0.000000
        Smartphone                     0.287490
        Tablet                         0.059664
        Tv                             0.000011
        Unknown                        0.009263
        all                            1.000000

Detail:
print (sl.xs('all', level=1))
         nb_uniq_visitors
site_id
74.0              18757.0
96.0             185370.0


Q: Array item completion in a UITextView I'm trying to accomplish an autocomplete of my own for matching array items while typing. So, I already have the logic done for matching what's being typed with what's in the array, but my question is related to displaying the proposed correction in the UITextView like this screenshot
I was trying by splitting the text in the textview and replacing the last word into attributed strings, but that makes the proposed correction part of the actual contents. Any ideas of how this is accomplished in this app?

A: What you currently do is good , when you set the text of the textView to attributed string make bool flag say it's name is textEdited = true with a string part that the user types say it's name userStr , when textView change method is triggered check that bool and according to it make the search if it's true proceed search with userStr if it's not proceed search with whole textView text , don't forget to make textEdited= false after every zero suggested result
Edit: regarding the cursor put a label under the textfield with the same font as the textView and make it's background darkGray , also make background of the textview transparent and every attributed string assign it to the label so plus part of the label will be shown and cursor will be as it is in the textView


Q: String Replacement Combinations So I have a string '1xxx1' and I want to replace a certain number (maybe all maybe none) of x's with a character, let's say '5'. I want all possible combinations (...maybe permutations) of the string where x is either substituted or left as x. I would like those results stored in a list.
So the desired result would be
>>> myList = GenerateCombinations('1xxx1', '5')
>>> print myList
['1xxx1','15xx1','155x1','15551','1x5x1','1x551','1xx51']

Obviously I'd like it to be able to handle strings of any length with any amount of x's as well as being able to substitute any number. I've tried using loops and recursion to figure this out to no avail. Any help would be appreciated.

A: How about:
from itertools import product

def filler(word, from_char, to_char):
    options = [(c,) if c != from_char else (from_char, to_char) for c in word]
    return (''.join(o) for o in product(*options))

which gives
>>> filler("1xxx1", "x", "5")
<generator object <genexpr> at 0x8fa798c>
>>> list(filler("1xxx1", "x", "5"))
['1xxx1', '1xx51', '1x5x1', '1x551', '15xx1', '15x51', '155x1', '15551']

(Note that you seem to be missing 15x51.)
Basically, first we make a list of every possible target for each letter in the source word:
>>> word = '1xxx1'
>>> from_char = 'x'
>>> to_char = '5'
>>> [(c,) if c != from_char else (from_char, to_char) for c in word]
[('1',), ('x', '5'), ('x', '5'), ('x', '5'), ('1',)]

And then we use itertools.product to get the Cartesian product of these possibilities and join the results together.
For bonus points, modify to accept a dictionary of replacements. :^)

A: Generate the candidate values for each possible position - even if there is only one candidate for most positions - then create a Cartesian product of those values.
In the OP's example, the candidates are ['x', '5'] for any position where an 'x' appears in the input; for each other position, the candidates are a list with a single possibility (the original letter). Thus:
def candidates(letter):
    return ['x', '5'] if letter == 'x' else [letter]

Then we can produce the patterns by producing a list of candidates for positions, using itertools.product, and combining them:
from itertools import product

def combine(candidate_list):
    return ''.join(candidate_list)

def patterns(data):
    all_candidates = [candidates(element) for element in data]
    for result in product(*all_candidates):
        yield combine(result)

Let's test it:
>>> list(patterns('1xxx1'))
['1xxx1', '1xx51', '1x5x1', '1x551', '15xx1', '15x51', '155x1', '15551']

Notice that the algorithm in the generator is fully general; all that varies is the detail of how to generate candidates and how to process results. For example, suppose we want to replace "placeholders" within a string - then we need to split the string into placeholders and non-placeholders, and have a candidates function that generates all the possible replacements for placeholders, and the literal string for non-placeholders.
For example, with this setup:
keywords = {'wouldyou': ["can you", "would you", "please"], 'please': ["please", "ASAP"]}

template = '((wouldyou)) give me something ((please))'

First we would split the template, for example with a regular expression:
import re

def tokenize(t):
    return re.split(r'(\(\(.*?\)\))', t)

This tokenizer will give empty strings before and after the placeholders, but this doesn't cause a problem:
>>> tokenize(template)
['', '((wouldyou))', ' give me something ', '((please))', '']

To generate replacements, we can use something like:
def candidates(part):
    if part.startswith('((') and part.endswith('))'):
        return keywords.get(part[2:-2], [part[2:-2]])
    else:
        return [part]

That is: placeholder-parts are identified by the parentheses, stripped of those parentheses, and looked up in the dictionary.
Trying it with the other existing definitions:
>>> list(patterns(tokenize(template)))
['can you give me something please', 'can you give me something ASAP', 'would you give me something please', 'would you give me something ASAP', 'please give me something please', 'please give me something ASAP']

To generalize patterns properly, rather than depending on other global functions combine and candidates, we should use dependency injection - by simply passing those as parameters which are higher-order functions. Thus:
from itertools import product

def patterns(data, candidates, combine):
    all_candidates = [candidates(element) for element in data]
    for result in product(*all_candidates):
        yield combine(result)

Now the same core code solves whatever problem. Examples might look like:
def euler_51(s):
    for pattern in patterns(
        s,
        lambda letter: ['x', '5'] if letter == 'x' else [letter],
        ''.join
    ):
        print(pattern)

euler_51('1xxx1')

or
def replace_in_template(template, replacement_lookup):
    tokens = re.split(r'(\(\(.*?\)\))', template)
    return list(patterns(
        tokens,
        lambda part: (
            keywords.get(part[2:-2], [part[2:-2]])
            if part.startswith('((') and part.endswith('))')
            else [part]
        ),
        ''.join
    ))

replace_in_template(
    '((wouldyou)) give me something ((please))',
    {
        'wouldyou': ["can you", "would you", "please"],
        'please': ["please", "ASAP"]
    }
)