text:
Q: Looking for pure javascript image color analysis I'm trying to set up a gallery of images that come one by one as you click the webpage. The image is displayed upfront, with a blurred version of that image as the background. But I'm finding that blur filters don't work on IE, and cause problems elsewhere. So I'm wanting an alternative for IE where the background color sets to whatever the dominant color cluster is, in hexadecimal preferably, where I can get it as a variable and supply it into a CSS change via javascript. Preferably, there would be five clusters of pixels, and the one with the highest percentage would be chosen. I'm not sure how these clusters are calculated, but I use this tool to manually get color information from images one by one, on default settings, which works perfectly:
http://mkweb.bcgsc.ca/color-summarizer/?examples
I just wish I had an automation in my own javascript.
I feel like Color Thief could be of use to me, but I apparently just don't understand how to use it or write the script to employ it I mean. I'm very new to this. Been coding for about four days. Any help with that would be very very appreciated.

A: This is not my script, but I can't find the source anymore. It returns the dominant color of a (locally hosted) image.
  function getAverageRGBa(imgEl, a) {
      var a = a || 1;

      var blockSize = 5, // only visit every 5 pixels
          defaultRGB = {r:0,g:0,b:0}, // for non-supporting envs
          canvas = document.createElement('canvas'),
          context = canvas.getContext && canvas.getContext('2d'),
          data, width, height,
          i = -4,
          length,
          rgb = {r:0,g:0,b:0},
          count = 0;

      if (!context) {
          return defaultRGB;
      }

      height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
      width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;

      context.drawImage(imgEl, 0, 0);

      try {
          data = context.getImageData(0, 0, width, height);
      } catch(e) {
          /* security error, img on diff domain */
          return defaultRGB;
      }

      length = data.data.length;

      while ( (i += blockSize * 4) < length ) {
          ++count;
          rgb.r += data.data[i];
          rgb.g += data.data[i+1];
          rgb.b += data.data[i+2];
      }

      // ~~ used to floor values
      rgb.r = ~~(rgb.r/count);
      rgb.g = ~~(rgb.g/count);
      rgb.b = ~~(rgb.b/count);

      return 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', ' + a + ')';
  }

Edit: May have found the source: https://jsfiddle.net/xLF38/


text:
Q: Simple java - looping over a txt file of numbers, counting the numbers between a range I'm using Netbeans, and I'm trying to write a code that loops over a .txt file full of numbers (numbers.txt), and output the amount of numbers that are within a range, e.g 10-100, along the lines of "There are __ numbers within the range of 10-100"
I then want the code to be able to add up all of the numbers in this range to get a total, e.g 13+33+70+90 = 206, and print this out along the lines of "The total of numbers in the range = 206"
I would give you the code I've done so far but it doesn't work at all as I can't figure out how to loop over the numbers.txt file to begin with.

A: You need to loop through the numbers one by one and calculate total and counter.
int total=0,counter=0,num; //initialize total and counter to 0

    Scanner scan=new Scanner(new File("myfile.txt")); //scanner to scan integers from file
while(scan.hasNextInt())
{
    if((num=scan.nextInt())>=10 && num <=100) //if num is in range of 10-100
    {
        total+=num; //adding num in each iteration
        counter++;  //increment counter
    }
}

System.out.println(counter+" numbers found in the range 10-100 and their sum is "+total);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sending a message to an user in moodle I am currently trying to implement what should be a simple task and send a message to one and / or more users via Moodle.
In the process I found 2 guides, which confused me at first.
Messaging 2.0 and Message API. Both have some differences and I didn't understand if my plugin needs to register as a Message Producer or not.
Unfortunately, I just can't get my message to be sent. I logged in with the user and checked the mailbox, no message there. Any help is appreciated.
What I did:
Created message.php within my db - folder and inserted the following code:
<?php
defined('MOODLE_INTERNAL') || die();

$messageproviders = array (
    'datenotification' => array (
    )
);

After that I expanded my language file with this:
$string['messageprovider:datenotification'] = 'Reminder for a presentation';

Like the guide advised, I updated my plugin to insert my messageprovider in the table mdl_message_providers. Finally, I implemented the actual sending of the message.
$eventdata = new \core\message\message();
$eventdata->component         = 'local_reminder';    // the component sending the message. Along with name this must exist in the table message_providers
$eventdata->name              = 'datenotification';        // type of message from that module (as module defines it). Along with component this must exist in the table message_providers
$eventdata->userfrom          = core_user::get_noreply_user();      // user object , no-reply
$eventdata->userto            = $user;        // user object from database
$eventdata->subject           = 'Test message';
$eventdata->fullmessage       = 'This is my test message';
$eventdata->fullmessageformat = FORMAT_PLAIN;   // text format
$eventdata->fullmessagehtml   = '
This is my test message
';
$eventdata->smallmessage      = '';
$eventdata->courseid = $course_id; // This is required in recent versions, use it from 3.2 on https://tracker.moodle.org/browse/MDL-47162

$result = message_send($eventdata);

Debugging:
var_dump($eventdata); //-> All data is included
var_dump($result); // returns int(5), id of message, no error

A: Adding the comment as an answer for future reference
Check if the message is installed and enabled via site admin > messaging > notification settings or direct to yoursite/admin/message.php


text:
Q: SetDataAndType method As documented in Android Developers page setDataAndType method can be called in this way:
auto setDataAndTypeFunctionId = env->GetMethodID(intentClassId, "setDataAndType", "(Landroid/net/Uri;Ljava/lang/String;)V");
jstring jmime = env->NewStringUTF("video/*");
env->CallVoidMethod(context, setDataAndTypeFunctionId, intentObject, UriObject, jmime);

But when i run my app this error show on output:
java.lang.NoSuchMethodError: no method with name='setDataAndType' signature='(Landroid/net/Uri;Ljava/lang/String;)V' in class Landroid/content/Intent;

A: The problem is the return type, which is not void. The setDataAndType method returns an object of type Intent.
Use the following signature:
env->GetMethodID(intentClassId, "setDataAndType", "(Landroid/net/Uri;Ljava/lang/String;)Landroid/content/Intent;");

Also, you should use CallObjectMethod instead of CallVoidMethod, although it doesn't really matter because you're not using the return value.


text:
Q: mongodb sort and regex query in efficient way     db.location.find(
     { "$or": [
         { "country_lc": /^unit/, "docType": "country" },
         { "region_lc": /^unit/, "docType": "region" },
         { "city_lc": /^unit/, "docType": "city" }
    ]},
    { "country": 1, "region": 1, "city": 1, "docType" :1 }
   ).sort({ "country_lc" :1, "region_lc": 1, "city_lc":1 })

this is query in monodb is taking very much time. How to query this efficiently ? Below is the explain() output of the above query. I have total 442161 documents in the collection location.I have to do some prefix searching.I have done indexing in (country_lc,docType) ,(region_lc,docType),(city_lc,docType) and (country_lc,region_lc,city_lc). My mongo version is 2.4.9.
{
"cursor" : "BtreeCursor country_lc_1_region_lc_1_city_lc_1",
"isMultiKey" : false,
"n" : 29,
"nscannedObjects" : 76935,
"nscanned" : 442161,
"nscannedObjectsAllPlans" : 76935,
"nscannedAllPlans" : 442161,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 79,
"nChunkSkips" : 0,
"millis" : 81531,
"indexBounds" : {
    "country_lc" : [
        [
            {
                "$minElement" : 1
            },
            {
                "$maxElement" : 1
            }
        ]
    ],
    "region_lc" : [
        [
            {
                "$minElement" : 1
            },
            {
                "$maxElement" : 1
            }
        ]
    ],
    "city_lc" : [
        [
            {
                "$minElement" : 1
            },
            {
                "$maxElement" : 1
            }
        ]
    ]
},
"server" : "prashanta:27017"

}

A: You could try creating a text index on the country_lc, region_lc and city_lc fields:
db.reviews.ensureIndex( { "country_lc": "text" } )
db.reviews.ensureIndex( { "region_lc": "text" } )
db.reviews.ensureIndex( { "city_lc": "text" } )

Text indices are a new feature in MongoDB 2.4.  They were added to support text search of string content in documents of a collection.  Please take a look at the official documentation for performance hints.
Moreover, you can give a try at rewriting the query as
db.location.find(
     { "docType": {"$in": [ "country", "region", "city" ]},
       "$or": [
         { "country_lc": /^unit/ },
         { "region_lc": /^unit/ },
         { "city_lc": /^unit/ },
       ]
    },
    { "country": 1, "region": 1, "city": 1, "docType" :1 }
   ).sort({ "country_lc" :1, "region_lc": 1, "city_lc":1 })

(Caution: This is, or isn't, equivalent to your query, depending on the structure of the documents.)

A: Now I happen to know you are running 2.4.9 which means you do not have index inter-sectioning and $ors cannot use sorted index. This answer might be different with that, which is in 2.6.
There are multiple problems with your query and it is considered a "bad" query in MongoDB, aside from the regex.
Ok, let's take the sort, in 2.4.9 sorts on $or will not use an index correctly ( https://jira.mongodb.org/browse/SERVER-1205 ) which means that you do not have scanAndOrder but you do have a nscanned count going on multiple times of your collection size.
The nscanned is 442,161 to be precise, since an $or is in fact many queries run ( http://docs.mongodb.org/manual/reference/operator/query/or/#or-clauses-and-indexes ) at the same time whose results are merged and then returned, you can see this proof in using more than one index on a $or even in 2.4.9.
I cannot see what indexes your clauses are using but I will assume those might not be fitting into an index either.
The problem is that 2.4.9 simply cannot do $or and sort with proper indexes. You must choose between either indexing the $or or the sort and even then only partially covering the query.
You have a couple of things you can do to fix this:

*

*Upgrade to 2.6 where $or and sort can use an index

*Even in 2.6 you might have problems due to the added docType field. You could try adding it to your index right after country_lc, however you might also be able to add it to the end of the index and it will work OK, but bare in mind that it will scan all entries below your matches in country_lc.

*You might be able to take advantage of index inter-sectioning in 2.6 to get around this problem with each or clause but as the documentation states ( http://docs.mongodb.org/manual/reference/operator/query/or/#or-and-sort-operations ) $or specific indexes will be dropped so I don't think this will work.

A: It doesn't matter which way you shake it, this is a horrible query that will always result in a full collection scan, or at least a full index scan.
Simply on this one document:
{
    "country_lc" : "unitize",
    "region_lc" : "unitmost",
    "city_lc" : "unitleast"
}

The query cannot possibly anchor on any position in the index as no matter how you organize the order of the fields as indexed none of them will ever match due to the "exclusive" ( as in excluding everything ) nature of the $or operator.
So none of these approaches or other combinations will actually include an index:
db.location.ensureIndex({
    "country_lc" : 1,
    "region_lc" : 1,
    "city_lc" : 1
})

db.location.ensureIndex({
    "region_lc" : 1,
    "city_lc" : 1,
    "country_lc" : 1
})

db.location.ensureIndex({
    "region_lc" : 1,
    "country_lc" : 1,
    "city_lc" : 1
})

Even if you .hint() the query it cannot possibly find a range,and this is again due to the "exclusive" nature:
db.location.find(
    { "$or": [
        { "country_lc": /^unit/ },
        { "region_lc": /^unit/ },
        { "city_lc": /^unit/ }
    ]}
).hint(
    { country_lc: 1, region_lc: 1, city_lc: 1 }
).explain()

All I can think is that you really do not actually mean "words that begin as 'unit'" and you actually mean something else.
This is not just a MongoDB thing, this is a horrible thing to ask of any database engine.
You probably really want a "text search" engine that is specialized instead.
EDIT
Some people have posted uninformed responses so I think I will actualy post the explain output from the queries that are suggested:
{
    "cursor" : "BtreeCursor country_lc_1_region_lc_1_city_lc_1",
    "isMultiKey" : false,
    "n" : 1,
    "nscannedObjects" : 1,
    "nscanned" : 1,
    "nscannedObjectsAllPlans" : 1,
    "nscannedAllPlans" : 1,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 0,
    "indexBounds" : {
            "country_lc" : [
                    [
                            {
                                    "$minElement" : 1
                            },
                            {
                                    "$maxElement" : 1
                            }
                    ]
            ],
            "region_lc" : [
                    [
                            {
                                    "$minElement" : 1
                            },
                            {
                                    "$maxElement" : 1
                            }
                    ]
            ],
            "city_lc" : [
                    [
                            {
                                    "$minElement" : 1
                            },
                            {
                                    "$maxElement" : 1
                            }
                    ]
            ]
    },
    "server" : "ubuntu:27017",
    "filterSet" : false
}

This clearly shows that even with an index selected you cannot possibly match anything within the index bounds.
And in further regard to the false comments that have been made, this query explain response comes from the 2.6 release of MongoDB. And is also repllicated in the current nightly builds.


text:
Q: Meteor Package Management Conflict I am getting this error when I try to run my meteor app:
Problem installing iron-router
  ✘ [0.6.4] conflicts with [tag: https://github.com/EventedMind/iron-router.git#v0.6.4]
Can't resolve dependencies! Use --force if you don't mind mrt taking a wild guess and running your app anyway.

This only started happening recently when I ran mrt add {{package_name}} and then mrt took it upon itself to upgrade all of the packages. I've deliberately not upgraded this app to Meteor's .8 release yet, so that broke everything because most of the packages had upgraded and were not backwards compatible.
To fix this, I decided to change the top level smart.json to reflect the package state before I upgraded. I then rm -rf'ed iron-router as well as accounts-entry (depends on iron-router), ran mrt remove on them, and then try adding them back again. This works on the package level - it yields the right ones - but I still get that error above and my app does not run.
{
  "packages": {
    "iron-router": {
      "git": "https://github.com/EventedMind/iron-router.git",
      "tag": "v0.6.4"
    },
    "accounts-entry": {
      "git": "https://github.com/BeDifferential/accounts-entry.git",
      "tag": "v0.6.2"
    },
    "accounts-t9n": {
      "git": "https://github.com/softwarerero/meteor-accounts-t9n.git",
      "tag": "v0.0.2"
    },
    "typeahead": {},
    "roles": {
      "git": "https://github.com/alanning/meteor-roles.git",
      "tag": "v1.2.6"
    },
    "bootstrap-themes": {},
    "font-awesome": {}
  }
}

A: I solved this by a convoluted process of deleting the ~/.meteorite directory, then re-installing everything in a particular order.


text:
Q: UISearchDisplayController with no results tableView? Usually, a UISearchDisplayController, when activated, dims the tableView and focuses the searchBar. As soon as you enter text into the searchBar, it creates a searchResultsTableView that displays between the searchBar and the keyboard. The searchDisplayController's delegate gets called when this second UITableView is loaded/shown/hidden/unloaded. Usually it shows live search results or autocompletion entries while typing.
In my app, I want to search a webservice and I don't want to call the webservice for each letter the user enters. Therefore, I want to entirely disable the searchResultsTableView and keep the dimmed black overlay while he enters text. I would then trigger the search (with a loading screen) once he hits the search button.
Just returning zero rows for the searchResultsTableView doesn't look nice since it displays an empty searchResultsTableView with a "no results" message. I tried to hide the table when it appears (searchDisplayController:didLoadSearchResultsTableView:) which works, but the blacked dimmed overlay is also hidden so that the underlying tableView is completely visible again.
Any ideas besides recreating the UISearchDisplayController functionality from scratch?

A: Nothing of the above seemed to work well in the end, so I came up with the following (you have to call removeTableHeader when you are ready to display your results):
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    [self setTableHeader];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self setTableHeader];
}

- (void)setTableHeader {
    UIView *headerView = [[UIView alloc] initWithFrame:self.searchDisplayController.searchResultsTableView.frame];
    headerView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];

    [self.searchDisplayController.searchResultsTableView setBackgroundColor:[UIColor clearColor]];
    [self.searchDisplayController.searchResultsTableView setScrollEnabled:NO];
    [self.searchDisplayController.searchResultsTableView setTableHeaderView:headerView];

    [headerView release];
}

- (void)removeTableHeader {
    [self.searchDisplayController.searchResultsTableView setBackgroundColor:[UIColor whiteColor]];
    [self.searchDisplayController.searchResultsTableView setScrollEnabled:YES];
    [self.searchDisplayController.searchResultsTableView setTableHeaderView:nil];
}

Obviously, it make the table transparent, adds a black/translucent table header with the same size as the table, and disables scrolling on the table so you cannot get above or past the header. As a bonus, you could add something to the header view ('please wait...' or an activity indicator).

A: Had the same problem as you, I handled it by a) setting the alpha of the searchResultsTableView to 0 when beginning searching, and then by b) adding/removing the overlayView to the viewController's view. Works like a charm for me.
@interface MyViewController()
//...
@property(nonatomic, retain) UIView *overlayView;
//...
@end

@implementation MyViewController
@synthesize overlayView = _overlayView;

//...

- (void)viewDidLoad
{
    //...

    //define your overlayView
    _overlayView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, 320, 480)];
    _overlayView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
}

//hide the searchResultsTableView
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    self.searchDisplayController.searchResultsTableView.alpha = 0.0f;
}

//when ending the search, hide the overlayView
- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
    [_overlayView removeFromSuperview];
}

//depending on what the user has inputed, add or remove the overlayView to the view of the current viewController
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{

    if ([searchString length]>0)
    {
        [self.view addSubview:_overlayView];
    }
    else
    {
        [_overlayView removeFromSuperview];
    }

    return NO;
}

@end

A: here is a little trick that i just figured out
and also you have to return 0 results while editing searchstring
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    savedSearchTerm = searchString;

    [controller.searchResultsTableView setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.8]];
    [controller.searchResultsTableView setRowHeight:800];
    [controller.searchResultsTableView setScrollEnabled:NO];
    return NO;
}

- (void)searchDisplayController:(UISearchDisplayController *)controller didHideSearchResultsTableView:(UITableView *)tableView
{
    // undo the changes above to prevent artefacts reported below by mclin
}

i think you'll figure out what to do next

A: it should be sufficient to implement the following method in your UISearchDisplayDelegate (which usually is your custom UITableViewController subclass)
- (BOOL) searchDisplayController: (UISearchDisplayController *) controller shouldReloadTableForSearchString: (NSString *) searchString
{
    [self startMyCustomWebserviceSearchAsBackgroundProcessForString: searchString]; //starts new NSThread
    return NO;
}

have you tried this?

A: Based on user182820's code below is my version. I hide the UISearchDisplayController's table view. When a character is entered in the search box I place a 'dimmed view' so it looks like UISearchDisplayController's 'dimmed view' never went away and then remove it when the search is finished. If you enter some characters and press cancel, the table view briefly goes all white and I don't know how to get around this.
- (void)viewDidLoad {
    ...
    tableViewMask=[UIView new];
    tableViewMask.backgroundColor = [UIColor blackColor];
    tableViewMask.alpha = 0.8;
}

- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller{
    tableViewMask.frame=CGRectMake(self.tableView.frame.origin.x, self.tableView.frame.origin.y+controller.searchBar.frame.size.height, self.tableView.frame.size.width, self.tableView.frame.size.height-controller.searchBar.frame.size.height);
    controller.searchResultsTableView.hidden=YES;
}

- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller{
    [tableViewMask removeFromSuperview];
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    if (searchString.length==0)
        [tableViewMask removeFromSuperview];
    else
        [self.tableView addSubview:tableViewMask];
    [searchText autorelease];
    searchText=[searchString retain];
    return NO;
}

A: What about just doing it as simple as this:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
self.searchDisplayController.searchResultsTableView.hidden=YES;
return YES;
}

Works fine for me..

A: Have you tried this:
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_lookup:) object:nil];
[self performSelector:@selector(_lookup:) withObject:txt afterDelay:0.20];

This way, if the user types another char within 1/5sec, you only make one web call.

A: I foud a better way, since there is a bug with the "best answer" - the separator and the "No Results" will be shown when scrolling the black background table.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {

    controller.searchResultsTableView.backgroundColor = [UIColor blackColor];
    controller.searchResultsTableView.alpha = 0.8;
    controller.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    for(UIView *subview in tableView.subviews) {
        if([subview isKindOfClass:UILabel.class]) {
            subview.hidden = YES;
        }
    }

    return NO;
}

- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {

    self.searchDisplayController.searchResultsTableView.backgroundColor = [UIColor whiteColor];
    self.searchDisplayController.searchResultsTableView.alpha = 1;
    self.searchDisplayController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

    for(UIView *subview in tableView.subviews) {
        if([subview isKindOfClass:UILabel.class]) {
            subview.hidden = NO;
        }
    }

    // search results and reload data ....
}

A: All of the existing answers are overly complicated.  You can get away by just hiding the results table view immediately.
-(void)searchDisplayController:(UISearchDisplayController *)controller didShowSearchResultsTableView:(UITableView *)tableView
{
    tableView.hidden = YES;
}

A: I think I found a better implementation for this problem. All the previous answers correctly show a dimmed view identical to what the UITableView looks like before a search, but each solution lacks the functionality to tap the area in order to cancel the search.
For that reason I think this code works better.
First of all, create a BOOL such as searchButtonTapped to indicate whether the search button was tapped. By default it is NO.
Then:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
if (!searchButtonTapped) {
    // To prevent results from being shown and to show an identical look to how the tableview looks before a search
    [controller.searchResultsTableView setBackgroundColor:[UIColor clearColor]];
    [controller.searchResultsTableView setRowHeight:160];
    self.searchDisplayController.searchResultsTableView.scrollEnabled = NO;
} else {
    // Restore original settings
    [controller.searchResultsTableView setBackgroundColor:[UIColor whiteColor]];
    [controller.searchResultsTableView setRowHeight:44];
    self.searchDisplayController.searchResultsTableView.scrollEnabled = YES;
}

return YES;
}

This should be clear now based on the other answers. Make sure to also restore the original settings when the user taps on the Search button.
Furthermore, in the cellForIndexPath method add:
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.contentView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.8];

In order to create the same dimmed view that is shown before text is entered. Make sure you apply these properties to the right cell, i.e., check which UITableView is active and that the user has not tapped the Search button.
Then, crucially, in didSelectRowAtIndexPath:
if (tableView == self.searchDisplayController.searchResultsTableView) {
    if (searchButtonTapped) {
           // Code for when the user select a row after actually having performed a search
    {
else
    [self.searchDisplayController setActive:NO animated:YES];

Now the user can tap the dimmed area, which will not result in a visible selection of a UITableViewCell, but instead cancels the search.


text:
Q: PyQt5 draggable icons from a listview to another I struggle to drag and drop icons from a listview (ViewMode set to IconMode) to another. It's similar to what I've found in the docs.

Scenario: A user drags the QIcon 1 from ListView 1 and drops it to ListView 2. ListView 2 should add QIcon 1 to its model. Moreover I want to do some background work when a specific QIcon is added to ListView 2. How do I know that QIcon 1 was dropped to ListView 2 and not QIcon 2?
mainwindow (sets up the layout, loads the images into listview 1):
class Ui_MainWindow(object):
...
    def loadImages(self):
        model = QStandardItemModel()
        images = Path("images").glob("*.*")
        for image in images:
            item = QStandardItem()
            item.setIcon(QIcon(str(image)))
            model.appendRow(item)

        self.listView1.setModel(model)

listview 1:
class ListView1(QListView):
    def __init__(self):
        super().__init__()
        self.setAcceptDrops(False)
        self.setViewMode(QtWidgets.QListView.IconMode)
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.setIconSize(QSize(50, 50))
        self.setResizeMode(QtWidgets.QListView.Adjust)
        self.setDragDropMode(QAbstractItemView.DragOnly)

listview 2:
class ListView2(QListView):
    def __init__(self):
        super().__init__()
        self.setViewMode(QtWidgets.QListView.IconMode)
        self.setDragDropMode(QAbstractItemView.DropOnly)
        self.setIconSize(QSize(50, 50))
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        event.accept()

    def dragMoveEvent(self, event):
        event.accept()

    def dropEvent(self, event):
        event.accept()
        event.setDropAction(QtCore.Qt.MoveAction)
        event.acceptProposedAction()

How can I drag and drop an icon from listview 1 to listview 2 and access its properties?

A: It is not necessary to overwrite dragEnterEvent, dragMoveEvent or dropEvent since those implementations already exist and work correctly, the example you point out is for other types of widgets that do not have those events implemented.
from pathlib import Path
from PyQt5 import QtCore, QtGui, QtWidgets

class LListView(QtWidgets.QListView):
    def __init__(self, parent=None):
        super(LListView, self).__init__(parent)
        self.model = QtGui.QStandardItemModel(self)
        self.setModel(self.model)

        self.setAcceptDrops(False)
        self.setViewMode(QtWidgets.QListView.IconMode)
        self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
        self.setIconSize(QtCore.QSize(50, 50))
        self.setResizeMode(QtWidgets.QListView.Adjust)
        self.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly)

class RListView(QtWidgets.QListView):
    def __init__(self, parent=None):
        super(RListView, self).__init__(parent)
        self.model = QtGui.QStandardItemModel(self)
        self.setModel(self.model)

        self.setAcceptDrops(True)
        self.setViewMode(QtWidgets.QListView.IconMode)
        self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
        self.setIconSize(QtCore.QSize(50, 50))
        self.setResizeMode(QtWidgets.QListView.Adjust)
        self.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        central_widget = QtWidgets.QWidget()
        self.l_view = LListView()
        self.r_view = RListView()

        self.setCentralWidget(central_widget)
        lay = QtWidgets.QHBoxLayout(central_widget)
        lay.addWidget(self.l_view)
        lay.addWidget(self.r_view)
        self.loadImages()

    def loadImages(self):
        images = Path("images").glob("*.*")
        for image in images:
            item = QtGui.QStandardItem()
            item.setIcon(QtGui.QIcon(str(image)))
            self.l_view.model.appendRow(item)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

Update:
If you want to add an identifier this can be done through a role that you pass when creating the item, and then in the dropEvent() get all the roles, then get the role you want and through it the identifier:
from pathlib import Path
from PyQt5 import QtCore, QtGui, QtWidgets

class LListView(QtWidgets.QListView):
    def __init__(self, parent=None):
        super(LListView, self).__init__(parent)
        self.m_model = QtGui.QStandardItemModel(self)
        self.setModel(self.m_model)

        self.setAcceptDrops(False)
        self.setViewMode(QtWidgets.QListView.IconMode)
        self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
        self.setIconSize(QtCore.QSize(50, 50))
        self.setResizeMode(QtWidgets.QListView.Adjust)
        self.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly)

class RListView(QtWidgets.QListView):
    def __init__(self, parent=None):
        super(RListView, self).__init__(parent)
        self.m_model = QtGui.QStandardItemModel(self)
        self.setModel(self.m_model)

        self.setAcceptDrops(True)
        self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
        self.setIconSize(QtCore.QSize(50, 50))
        self.setResizeMode(QtWidgets.QListView.Adjust)
        self.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly)

    def dropEvent(self, event):
        last_row_count = self.model().rowCount()
        super(RListView, self).dropEvent(event)
        # check if an item is added
        if self.model().rowCount() > last_row_count:
            md = event.mimeData()
            fmt = "application/x-qabstractitemmodeldatalist"
            if md.hasFormat(fmt):
                encoded = md.data(fmt)
                stream = QtCore.QDataStream(encoded, QtCore.QIODevice.ReadOnly)
                datas = []
                item = {}
                while not stream.atEnd():
                    row = stream.readInt32()
                    column = stream.readInt32()
                    map_items = stream.readInt32()
                    for i in range(map_items):
                        key = stream.readInt32()
                        value = QtCore.QVariant()
                        stream >> value
                        item[QtCore.Qt.ItemDataRole(key)] = value
                    datas.append(item)
                for data in datas:
                    identifier = data[QtCore.Qt.UserRole+1].value()
                    print("identifier: ", identifier)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        central_widget = QtWidgets.QWidget()
        self.l_view = LListView()
        self.r_view = RListView()

        self.setCentralWidget(central_widget)
        lay = QtWidgets.QHBoxLayout(central_widget)
        lay.addWidget(self.l_view)
        lay.addWidget(self.r_view)
        self.loadImages()

    def loadImages(self):
        images = Path("images").glob("*.*")
        for i, image in enumerate(images):
            item = QtGui.QStandardItem()
            identifier = "img_{:06d}".format(i+1)
            item.setData(identifier, QtCore.Qt.UserRole+1)
            item.setIcon(QtGui.QIcon(str(image)))
            self.l_view.m_model.appendRow(item)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())


text:
Q: Namedtuple error I am trying to serialize a Python object into JSON using namedtuple. But I get this error. Google does not help.
Traceback (most recent call last):
 File "cpu2.py", line 28, in <module>
 cpuInfo = collections.namedtuple('cpuStats',('cpu.usr', ('str(currentTime) + " "
 +str(cpuStats[0]) + " host="+ thisClient')), ('cpu.nice', ('str(currentTime) + " "
 +str(cpuStats[1]) + " host="+ thisClient')), ('cpu.sys',('str(currentTime) + " "
 +str(cpuStats[2]) + " host="+ thisClient')), ('cpu.idle',('str(currentTime) + " "
 +str(cpuStats[3]) + " host="+ thisClient')))
 TypeError: namedtuple() takes at most 4 arguments (5 given)

A: Here is a link to the documentation for namedtuple. You aren't initializing it properly.
How I'm guessing you should initialize it:
cpuInfo = collections.namedtuple('cpuStats', ['usr', 'nice', 'sys', 'idle'])

# In this case, usr=str(currentTime) + " " +str(cpuStats[0]) + " host=" + thisClient
# You can figure the rest out...
info = cpuInfo(usr='fill',
               nice='this',
               sys='your',
               idle='self')

Also, you might want to read this question which talks about serializing namedtuples in json.


text:
Q: Create new folder in topmost opened Windows Explorer I am writing a console application.
it has to do the following

*

*I'll place(pin) EXE of this application in Task-bar of the window.

*I'll open  windows explorer or there may be already many opened
windows before.

*I'll select a window where I want to create a folder
(folder hierarchy)

*I'll click on the icon from Task-bar of my EXE
pinned in step 1.
I have tried following code.
It is working when I am scheduling it by using windows scheduler. after every 5 minutes a new folder will be created in the topmost window.
However when I am trying with executing exe after pinning it to taskbar, it is not working..
Please let me know if there is any solution.
NOTE - Helpful if you tell me how to create a new option of Create New Custom Folder after right click
using System;
using System.Text;

namespace CreateNewFolders
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // get the active window
                IntPtr handle = GetForegroundWindow();

                // Required ref: SHDocVw (Microsoft Internet Controls COM Object) - C:\Windows\system32\ShDocVw.dll
                SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();

                // loop through all windows
                foreach (SHDocVw.InternetExplorer window in shellWindows)
                {
                    Console.WriteLine(((int)handle).ToString());
                    Console.WriteLine(window.HWND.ToString());
                    if (window.HWND == (int)handle)
                    {
                        // Required ref: Shell32 - C:\Windows\system32\Shell32.dll
                        var shellWindow = window.Document as Shell32.IShellFolderViewDual2;

                        // will be null if you are in Internet Explorer for example
                        if (shellWindow != null)
                        {
                            // Item without an index returns the current object
                            var currentFolder = shellWindow.Folder.Items().Item();

                            // special folder - use window title
                            // for some reason on "Desktop" gives null
                            if (currentFolder == null || currentFolder.Path.StartsWith("::"))
                            {
                                // Get window title instead
                                const int nChars = 256;
                                StringBuilder Buff = new StringBuilder(nChars);
                                //if (GetWindowText(handle, Buff, nChars) > 0)
                                //{
                                //    return Buff.ToString();
                                //}
                            }
                            else
                            {

                                System.IO.Directory.CreateDirectory(currentFolder.Path + "//NewFolder//Db_Scripts");
                                System.IO.Directory.CreateDirectory(currentFolder.Path + "//NewFolder//Documents");
                                System.IO.Directory.CreateDirectory(currentFolder.Path + "//NewFolder//SourceCode");
                                // return currentFolder.Path;
                            }
                        }

                        break;
                    }
                }

            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
                Console.Read();
            }
            //Console.Read();
        }
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

    }
}

References to be added C:/windows/system32/Shell32 and Microsoft Internet Controls from COM.

A: This code works for me, just 2 lines added. Before it executes changes back the last accessed window.
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace lastActiveWindow
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // New lines..
            SendKeys.SendWait("%{Tab}");
            Thread.Sleep(500);
            try
            {
                // get the active window
                var handle = GetForegroundWindow();

                // Required ref: SHDocVw (Microsoft Internet Controls COM Object) - C:\Windows\system32\ShDocVw.dll
                SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();

                // loop through all windows
                foreach (SHDocVw.InternetExplorer window in shellWindows)
                {
                    Console.WriteLine(((int) handle).ToString());
                    Console.WriteLine(window.HWND.ToString());
                    if (window.HWND == (int) handle)
                    {
                        // Required ref: Shell32 - C:\Windows\system32\Shell32.dll
                        var shellWindow = window.Document as Shell32.IShellFolderViewDual2;

                        // will be null if you are in Internet Explorer for example
                        if (shellWindow != null)
                        {
                            // Item without an index returns the current object
                            var currentFolder = shellWindow.Folder.Items().Item();

                            // special folder - use window title
                            // for some reason on "Desktop" gives null
                            if (currentFolder == null || currentFolder.Path.StartsWith("::"))
                            {
                                // Get window title instead
                                const int nChars = 256;
                                var Buff = new StringBuilder(nChars);
                                //if (GetWindowText(handle, Buff, nChars) > 0)
                                //{
                                //    return Buff.ToString();
                                //}
                            }
                            else
                            {
                                Directory.CreateDirectory(currentFolder.Path + "//NewFolder//Db_Scripts");
                                Directory.CreateDirectory(currentFolder.Path + "//NewFolder//Documents");
                                Directory.CreateDirectory(currentFolder.Path + "//NewFolder//SourceCode");
                                // return currentFolder.Path;
                            }
                        }

                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
                Console.Read();
            }
            //Console.Read();
        }

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
    }
}


text:
Q: How Pragma UDF works? Recently, I have read about UDF Pragma optimization method in Oracle Database 12.
I'm very interested in how exactly it works. I've only found very short description in the Oracle documentation.
As I understand, every Pragma in PL/SQL is some kind of compiler directive (I could be wrong here) similar to C++ Pragma Directives.
Maybe someone can explain to me in more details (or provide links :) ) how the internal mechanism of UDF Pragma works?

A: The internals are not made available to us, but essentially the pragma is an instruction to the compiler to focus on reducing the cost of the PL/SQL => SQL context switch overhead. If I had to hypothesise I would say that it takes advantage of a different 12c feature which allow PL/SQL directly within a CTE (common table expression), e.g.:
WITH
  function myfunction(x int) return int as
  begin
    ...
    return ...
  end;
select myfunction(col) from my_table

PL/SQL functions coded like the above exist solely for the duration of the SQL execution and also execute with improved performance characteristics over that of standalone functions. So I suspect the UDF pragma allows invocation of a standalone function via the same code path as the inline example above.
(But all just hypothesis on my part)


text:
Q: creates and starts a game from answers written in a file in Ruby I am currently working on improving my ruby skills.
I am working on a guess game and the game is playing well without writing it on a file.
And now I have introduced a file and the answers to the game are written on a file.
My problem now is that I am looking for a way to "starts the game from answers written in a file".
The from_file method is where I want to implement the solution to the problem. Though I have started with it but stucked and I need someone to assist me.
Below is the main code while the RSPEC test is below the code
class Game
  def initialize(answers:, input: $stdin, output: $stdout, max_attempts: 3)
    @answers = answers
    @correct_answers = 0
    @input = input
    @max_attempts = 3
    @output = output
  end

  def start
    if answers.size == 1
      word_anagram = "anagram"
    else
      word_anagram = "anagrams"
    end
    output.puts "Let's play a game. You will have to guess #{answers.size} #
    {word_anagram}."
    answers.each.with_index(1) do |answer, index|
      output.puts "#{index}/#{answers.size}. Guess a word from an anagram #
      {Anagram.create("#{answer.upcase}")}"
      evaluate_user_guesses(answer)
    end
    output.puts "Your final score: #{correct_answers}/#{answers.size}."
  end

  def evaluate_user_guesses(answer)
    guess = nil
    current_attempt = 1
    while guess != answer.upcase && current_attempt <= max_attempts
      guess = input.gets.to_s.strip
      if guess.upcase == answer.upcase
        output.puts "Correct! The answer is #{answer.upcase}."
        @correct_answers += 1
        return output.puts "So far you have correctly guessed #{correct_answers} out of
        #{answers.size}."
      else
        output.puts "The answer is not #{guess.upcase}."
        if current_attempt < max_attempts
          output.puts "Try again. Attempts left: #{max_attempts - current_attempt}"
        else
          output.puts "You lost."
        end
      end
      current_attempt += 1
    end
  end

  def self.from_file(path:, input: $stdin, output: $stdout, max_attempts: 3)
    self.new(answers: [], input: input, output: output, max_attempts: max_attempts)
  end

  private

  attr_reader :answers, :correct_answers, :input, :max_attempts, :output
end

This is an RSPEC test for how to create and start a game from an answer written in a file. I will appreciate your input.
describe "#from_file" do
    let(:output) { StringIO.new }
    it "creates and starts a game from answers written in a file" do
      file = Tempfile.new
      answers = %w(alpha beta)
      file_contents = answers.join("\n")
      begin
        file.write(file_contents)
        file.rewind
        guesses = %w(alpha beta)
        input = StringIO.new(guesses.join("\n"))
        game = Game.from_file(
          path: file.path,
          input: input,
          output: output,
          max_attempts: 3
        )

        game.start

        game_output_lines = output.string.split("\n").map(&:strip)

        aggregate_failures do
          expect(game_output_lines.size).to eq 8
          expect(game_output_lines[0]).to eq "Let's play a game. You will have to guess
          2 anagrams."
          expect(game_output_lines[1]).to match(/^1\/2. Guess a word from an anagram
          [ALPH]{5}$/)
          expect(game_output_lines[2]).to eq "Correct! The answer is ALPHA."
          expect(game_output_lines[3]).to eq "So far you have correctly guessed 1 out of
          2."
          expect(game_output_lines[4]).to match(/^2\/2. Guess a word from an anagram
          [BETA]{4}$/)
          expect(game_output_lines[5]).to eq "Correct! The answer is BETA."
          expect(game_output_lines[6]).to eq "So far you have correctly guessed 2 out of
          2."
          expect(game_output_lines[7]).to eq "Your final score: 2/2."
        end
      ensure
        file.close
        file.unlink
      end
    end
  end

A: According to your comments, you need to read your answers: [] from the file, so for a text file containing one answer per line
#answers.txt
one
two
three

> answers = File.read("answers.txt").split
=> ["one", "two", "three"]

  def self.from_file(path:, input: $stdin, output: $stdout, max_attempts: 3)
    answers = File.read("answers.txt").split
    self.new(answers: answers, input: input, output: output, max_attempts: max_attempts)
  end


text:
Q: Can Advanced Filter criteria be in the VBA rather than a range? After trying in vain to set more than 2 criteria in a normal AutoFilter fashion via VBA, I have come to learn that it must be done via advanced filter.
offending example:
Worksheets(1).Range("A1").AutoFilter Field:=ColNum, Criteria1:="A*", Operator:=xlOr, Criteria2:="B*", Operator:=xlOr, Criteria3:="C*"

I am hoping to pass the criteria through to a function (rather than a macro) from a PowerShell script. I have it all working fine and as expected for 1 criteria, but now I'd like 3.
I suppose I could instead write a macro to insert a new sheet, write in the criteria then filter on that new range but I'd rather check the preferred way first.

A: To filter on multiple wildcards, create a variant array of wildcard matches and then use the array of full values with the standard AutoFilter method. You can minimize the array by putting a dictionary object to use with its unique index property.
Consider the following sample data.

Run this code.
Sub multiWildcards()
    Dim v As Long, vVALs As Variant, dVALs As Object
    Dim colNum As Long

    Set dVALs = CreateObject("Scripting.Dictionary")
    dVALs.comparemode = vbTextCompare
    colNum = 2 'column B

    With Worksheets(1)
        If .AutoFilterMode Then .AutoFilterMode = False
        With .Cells(1, 1).CurrentRegion
            vVALs = .Columns(colNum).Cells.Value2
            For v = LBound(vVALs, 1) To UBound(vVALs, 1)
                If Not dVALs.exists(vVALs(v, 1)) Then
                    Select Case UCase(Left(vVALs(v, 1), 1))
                        Case "A", "B", "C"
                            dVALs.Add Key:=vVALs(v, 1), Item:=vVALs(v, 1)
                        Case Else
                            'do nothing
                    End Select
                End If
            Next v

            If CBool(dVALs.Count) Then
                'populated the dictionary; now use the keys
                .AutoFilter Field:=colNum, Criteria1:=dVALs.keys, Operator:=xlFilterValues
            Else
                Debug.Print "Nothing to filter on; dictionary is empty"
            End If

            '.CurrentRegion is now filtered on A*, B*, C* in column B
            'do something with it
        End With
    End With

    dVALs.RemoveAll: Set dVALs = Nothing
End Sub

Results should be:

These results can be duplicated with many other wildcard scenarios. The Select Case statement is ideal as it supports the Like keyword for building your collection of matches. By starting with a value dump into a regular variant array, cycling through even large rows of data can be done quickly.


text:
Q: Using a dataset as "index" to change values in another datasets I have a first dataset "index"
ID     Trial      RT
 1        1       500
 1        2       400
 2        1       200
 2        2       100
[etc...]

A second dataset "Experiment", much more longer than "index"
 ID     Trial      RT
 1        1       1500
 1        1       2000
 1        2       1400
 1        2       3000
 2        1       1200
 2        1       4000
 2        2       1100
 2        2       5000
[etc...]

I want to subtract RT values in "index" from RT "values" in "Experiment", based on a match between ID and Trial across datasets, to obtain a "revised" version of "Experiment":
ID     Trial      RT
 1        1       1000
 1        1       1500
 1        2       1000
 1        2       2600
 2        1       1000
 2        1       3800
 2        2       1000
 2        2       4900

Many thanks in advance!


text:
Q: Toggle lodash orderBy ascending and descending I have a method in my vue.js that is sorting my items by the date they registered in ascending but what I really wanted is for 1 unique button to be clicked and toggle between ascending and descending.
JS
sortAsc(customers) {
  // Click and sort registered customers by ascending
  let sort = _.orderBy(this.customers, 'registered', 'asc')
  this.sortedCustomers = sort
}

How can I make the above so when I click 1x sorts by ascending and click 2x sorts by descending?
Thanks

A: Add another property to the object (sortOrder) that saves the current sort order. Toggle it when you call the function - use asc if it's undefined or set to desc:
sortAsc(customers) {
  this.sortOrder = this.sortOrder !== 'asc' ? 'asc' : 'desc'

  const sort = _.orderBy(this.customers, 'registered', this.sortOrder)
  this.sortedCustomers = sort
}

A: You can use .sortBy, it will always return an ascending list:
_.sortBy([2, 3, 1], function(num) {
    return num;
}); // [1, 2, 3]

But you can use the .reverse method to get it descending:
var array = _.sortBy([2, 3, 1], function(num) {
    return num;
});

console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]

Or when dealing with numbers add a negative sign to the return to descend the list:
_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
    return -num;
}); // [3, 2, 1, 0, -1, -2, -3]

Under the hood .sortBy uses the built in .sort([handler]):
// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]

// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
    // a = current item in array
    // b = next item in array
    return b - a;
});

A: One way you can achieve this, is by having a variable which keeps changing its value on each call
let toggler = true;

Then in your sortAsc function assign the value "asc" or "desc" based on this toggler
sortAsc(customers){
      // Click and sort registered customers by ascending
     toggler = !toggler ;  //change the value based on the current value
     let order = !toggler ? "asc": "desc";
     let sort = _.orderBy(this.customers, 'registered', order)
     this.sortedCustomers = sort
}

I hope this helps


text:
Q: Jquery UI: Button on dynamically created elements I would like to add jQuery UI button to all my input submits.
$('input:submit').button();

That works great for normal buttons but it doesn't work for buttons I create dynamically.
Anybody know how to do this?

A: The easiest thing would to add this line when creating the new buttons.
$(this).button();

for example
(jQuery to create button) function(){
    $(this).button();
}

I believe you could also just call this again but it might be slower.
$('input:submit').button();

EDIT:
after looking at what jQuery.tmpl is you might be able to do something like
$("#sometmpl")
    .render( arrayOfDataObjects ) // Returns multiple LIs with data filled in
    .appendTo("ul" function(){
    $("#sometmpl input:submit").button();
)};

but don't hold me to it.
OR take a look at the jquery ui css and just add the classes you need to the submit buttons.  Hover may not work though
class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only"

A: Thought it would be useful to show how I fixed it in my application. It's a concise version of my real code that I didn't test and there might be typos.
var app = (function(){
    var general = (function(){

        function init(){
            init_jquery_ui();
        };

        function init_jquery_ui(){
            //init stuff

            $('body').bind('added_tmpl', function(){
                //init stuff
            });
        };

        function add_tmpl(tmpl_node, append_to_node, data){
            tmpl_node.tmpl(data).appendTo(append_to_node);
            append_to_node.trigger('added_tmpl');
        };

        return{
            init: init,
            add_tmpl: add_tmpl
        };

    })();

    var somepage = (function(){

        function init(){
            load_some_form();
        };

        function load_some_form(){
            var data = { name: 'hello', age: 15 };
            general.add_tmpl($('#some_form_tmpl'), $('#some_form'), data);
        };

        return{
            init: init
        };

    })();

    return{
        general: general,
        somepage: somepage
    };

})();

app.general.init();

if(page=='somepage'){
    app.somepage.init();
};


text:
Q: How to put the Y-axis of a chart to the right-side of it I created a chart in Billboard.js which looks like this:
var chart = bb.generate({
    "data": {
        "type": "line",
        "x": "x",
        "columns": columns
    },
    "point": {
        "show": false
    },
    "legend": {
        "show": false
    },
    "axis": {
        "x": {
            "localtime": false,
            "type": "timeseries",
            "tick": {
                count: 7,
                "format": "%b %d, %Y",
                "rotate": 45,
                "multiline": true
            },
             "label": {
                "text": label,
                "position": "outer-center"
            },
        },
        "y": {
            "label": {
                "text": "Energy (kWh)",
                "position": "outer-middle"
            },
        },
    },
    "bindto": "#main-chart"
});

Now it looks like the classic style, X axis on the bottom and Y axis on the left. I want to move the Y axis on the right of the table.
I've tried many ways to do it but without success like these ones:
-changing its name from y to y2
-adding the same code but with y2:
"y": {
    "label": {
    "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},

"y2": {
    "label": {
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},

I addied show attribute inside the label like this:
"y": {
    "label": {
        "show": false,
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},
"y2": {
    "label": {
        "show": true,
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},

Any ideas?

A: Try
var chart = bb.generate({
  "data": {
    "columns": [
    ["data1", 30, 200, 100, 400, 150, 250],
    ["data2", 50, 20, 10, 40, 15, 25]
    ],
    "axes": {
      "data1": "y2" // set additional y axis
    }
  },
  "axis": {
    "y": {
      "show": false // hide default y axis
    },
    "y2": {
      "show": true
    }
  },
  "bindto": "#AdditionalYAxis"
});

I have tried it on their demo from github. There is an option axis where you can simply hide the axis. Hope this helps.
Working Example: https://jsfiddle.net/k3o1ws47/

A: I think, @Nouphal pointed exactly what to do.
The key point is set data.axes options to bound datas to y2 axis.

*

*https://naver.github.io/billboard.js/release/latest/doc/Options.html#.data:axes
I made working demo with your code(except the data value), so replace it setting with your data and will work.

var chart = bb.generate({
    "data": {
        "type": "line",
        "x": "x",
        "columns": [
          // replace with your data value
          ['x', '2017-10-01', '2017-10-02', '2017-10-03', '2017-10-04', '2017-10-05', '2017-10-06'],
          ["data1", 30, 200, 100, 400, 150, 250],
          ["data2", 50, 20, 10, 40, 15, 25]
        ],
        "axes": {
          "data1": "y2",
          "data2": "y2"
        }
    },
    "point": {
        "show": false
    },
    "legend": {
        "show": false
    },
    "axis": {
        "x": {
            "localtime": false,
            "type": "timeseries",
            "tick": {
                count: 7,
                "format": "%b %d, %Y",
                "rotate": 45,
                "multiline": true
            },
             "label": {
                "text": "label",
                "position": "outer-center"
            },
        },
        "y": {
          "show": false
        },
        "y2": {
            "show": true,
            "label": {
                "text": "Energy (kWh)",
                "position": "outer-middle"
            },
        },
    },
    "bindto": "#main-chart"
});
<!doctype html>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.css">


text:
Q: Heat.exe why does it create different Registry keys to Regasm? I am trying to use heat to create the necessary registry keys.  The assembly is a simple dummy Shell Context handler it adds a context menu to a .txt ending.
If I use Regasm to register it then a registry key (not the only one but the one that is different) is added at this.  Note that it is at txtfile.

  [HKEY_CLASSES_ROOT\txtfile\shellex]
  [HKEY_CLASSES_ROOT\txtfile\shellex\ContextMenuHandlers]
  [HKEY_CLASSES_ROOT\txtfile\shellex\ContextMenuHandlers\{1e25bcd5-f299-496a-911d-51fb901f7f40}]
    @="VBShellExtContextMenuHandler.FileContextMenuExt Class"
If I use heat then this txtfile is not used.  It uses .txt

  [HKEY_CLASSES_ROOT\.txt\shellex]
  [HKEY_CLASSES_ROOT\.txt\shellex\ContextMenuHandlers]
  [HKEY_CLASSES_ROOT\.txt\shellex\ContextMenuHandlers\{1e25bcd5-f299-496a-911d-51fb901f7f40}]
    @="VBShellExtContextMenuHandler.FileContextMenuExt Class"
The other keys that regasm makes seem to be the same as Heat but this one is not and it means that the menu fails with the Heat keys.
Is this a known problem with heat?
I know I could simply change it but this is a test and I need to add about 15 extensions.

A: Take a look at a gotcha in the help topic Regasm.exe (Assembly Registration Tool).

Note that the .reg file does not contain any registry updates that can
  be made by user-defined register functions. Note that the /regfile
  option only emits registry entries for managed classes. This option
  does not emit entries for TypeLibIDs or InterfaceIDs.

I'm not 100% certain on Heat's interaction with Regasm but I know InstallShield's .NET Com Interop calls Regasm /regfile so this gotcha would apply.
Personally I only use these tools as one of many tools at my disposal to gather the requirements, sort it all out and then author it by hand.


text:
Q: Hereditary product of non-hereditary cardinal functions Does there exists two cardinal functions in topology, each of them not hereditary but their product is hereditary?
For cardinal function i mean a rule to associate a cardinal number to every topological space such that for homeomorphic spaces the result is the same, for example the weight (the minimal cardinality of a base), the density (the minimal cardinality of a dense subset), the Lindelöf degree (the minimal infinite cardinal $\kappa$ such that every open cover has a subcover of cardinality $\leq\kappa$) etc...
A cardinal function $\varphi$ is called hereditary if whenever $Y\subseteq X$, $\varphi(Y)\leq\varphi(X)$ holds. Examples of hereditary cardinal functions are the weight, the cardinality, examples of non-hereditary ones are the density, the Lindelöf degree, etc...


text:
Q: Create list of nodes by copying from another lists I have a XSLT template where I need to merge two lists of nodes conditionally. I have the following two XML fragments:
<vo>
    <field name="userLoginName"       nameLDAP="uid"              type="String"/>
    <field name="displayName"         nameLDAP="displayName"      type="String"/>
    <field name="firstName"           nameLDAP="givenName"        type="String"/>
    <field name="lastName"            nameLDAP="sn"               type="String"/>
    <field name="mail"                nameLDAP="mail"             type="String"/>
    <field name="userPassword"        nameLDAP="userPassword"     type="String" hidden="true"/>
    <field name="center"              nameLDAP="center"           type="String"/>
</vo>

<input>
    <field name="userPassword"/>
    <field name="oldPasswordInQuotes" nameLDAP="unicodePwd"       type="byte[]"/>
</input>

I want to  create a xml fragment  that will have the same nodeas as input/field. For each one of those nodes I want to check if there is a node with the same name in the list vo/field. If there is, then it should be copied to the new list. Otherwise, it should copy the same node we are iterating over. In this case the output should be something like this:
<field name="userPassword"        nameLDAP="userPassword"     type="String" hidden="true"/>
<field name="oldPasswordInQuotes" nameLDAP="unicodePwd"       type="String"/>

So far I've the following transformation:
    <xsl:variable name="fields" select="vo/field" />

    <xsl:variable name='allParameters'>
        <xsl:for-each select="input/field">
            <xsl:variable name="inputFieldName" select="@name"/>
            <xsl:choose>
                <xsl:when test="$fields[@name = $inputFieldName]">
                    <xsl:copy-of select="$fields[@name = $inputFieldName]"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:copy-of select="."/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>
    </xsl:variable>

    <xsl:message>Parameters <xsl:copy-of select="$allParameters" /> </xsl:message>

    <xsl:for-each select="$allParameters">
        <xsl:message>Parameter <xsl:value-of select="@name" /> found !!! </xsl:message>
    </xsl:for-each>

The output is
Parameters <field name="userPassword" nameLDAP="userPassword" type="String" hidden="true"/><field name="oldPasswordInQuotes" nameLDAP="unicodePwd" type="byte[]"/>
Parameter  found !!!

The first xsl:message seems to show that the copy worked fine, but when I try to iterate over it, it is obviously not working(there is only one message "Parameter found" and it is not showing the parameter name). What am I missing?

A: I think you want something like:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:key name="vo" match="vo/field" use="@name" />

<xsl:template match="/">
    <xsl:for-each select="root/input/field">
        <xsl:choose>
            <xsl:when test="key('vo', @name)">
                <xsl:copy-of select="key('vo', @name)"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy-of select="."/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Applied to a wel-formed input:
<root>
    <vo>
        <field name="userLoginName"       nameLDAP="uid"              type="String"/>
        <field name="displayName"         nameLDAP="displayName"      type="String"/>
        <field name="firstName"           nameLDAP="givenName"        type="String"/>
        <field name="lastName"            nameLDAP="sn"               type="String"/>
        <field name="mail"                nameLDAP="mail"             type="String"/>
        <field name="userPassword"        nameLDAP="userPassword"     type="String" hidden="true"/>
        <field name="center"              nameLDAP="center"           type="String"/>
    </vo>
    <input>
        <field name="userPassword"/>
        <field name="oldPasswordInQuotes" nameLDAP="unicodePwd"       type="byte[]"/>
    </input>
</root>

results in:
<field name="userPassword" nameLDAP="userPassword" type="String" hidden="true"/>
<field name="oldPasswordInQuotes" nameLDAP="unicodePwd" type="byte[]"/>

Edit:
To answer your question regarding the number of messages in your test: there is only one $allParameters node; to iterate over its inner nodes (assuming XSLT 2.0), try:
<xsl:for-each select="$allParameters/field">
    <!-- your code here -->
</xsl:for-each>


text:
Q: Javascript compare appended true/false value I have my JS code as below;
var editable = isNameEditable(this.get("status"));
return "
" + this.get("name") + "
";

The function isNameEditable just returns boolean value (true/false)
I then append it to my div using data-editable attribute.
I use the above value for comparision later and use below code;
if ($(this).attr('data-editable'))

However, the appended value becomes a string ("true"/"false") and hence the above condition does not work as expected.
Is there any way by which I can append a boolean value, so that I do not have to change my comparison
i.e.
if ($(this).attr('data-editable'))

A: String boolean values to boolean conversion methods are explained in this post:
How can I convert a string to boolean in JavaScript?
For example, you can use
if(!!$(this).data('editable'))

to check if the div is editable.


text:
Q: Check whether attachment ID is associated with more than one post? Is there a function to check whether an attachment ID (=get_post_thumbnail_id(..)) is associated with more than one post?
With "associated" I mean that a posts's meta value for the meta_key _thumbnail_id equals the attachment ID.
I know that get_post_meta() returns an empty array if it does not find anything, but I would have to somehow loop over all posts.

A: you can use following way
$attachment_id = 5; //put here you attachment id
$sql = "SELECT count(DISTINCT pm.post_id) FROM $wpdb->postmeta pm JOIN $wpdb->posts p ON (p.ID = pm.post_id) WHERE pm.meta_key = '_thumbnail_id' AND pm.meta_value = '$attachment_id' AND p.post_type = 'post' AND p.post_status = 'publish'";
$count = $wpdb->get_var($sql);


text:
Q: Getting an absolute path on the local file system from an IResource What is the better approach to get an absolute path on the local file system from an IResource?
IResource res;
...
res.getLocation().makeAbsolute().toString();

or
IResource res;
...
new File(res.getLocationURI()).getAbsolutePath();

(I skipped null checks in this example.)

A: Probably:
res.getLocation().toOSString();

The location should always be absolute so no need to call makeAbsolute (although it will not cost much when the path is already absolute).
Use toOSString() to get the path in the format used by the OS (so \ on Windows, / on Mac, Linux).
You can also use toPortableString() to get a standard format path which is useful for data interchange but is not suitable for use with File.


text:
Q: Approximation of a function with a polynomial of degree n. Let $f\in{L_{loc}^{1}}$ such that $\int_{a}^{b}{f(x)}{\phi}^{(n)}(x)dx=0$ for all $\phi\in{C_{0}^{\infty}}(a,b)$. Then how do we show there exists a polynomial $P(x)$ of degree less or equal to $n-1$ such that $f=P$ a.e.?
My try is: I showed the basic case that is if $\int_{a}^{b}{f(x)}{\phi}'(x)dx=0$ for all $\phi\in{C_{0}^{\infty}}(a,b)$ then $f$ is a.e. equal to a constant function. But I have no idea how to generalize this base result to the case for $n$ in general.

A: Set $X_+=\{x:f(x)>0\}$ and $X_-=\{x:f(x)<0\}$. If any of them, say $X_+$, has positive measure, then it contains inner points and thus an open interval $(c,d)\subset [a,b]$. Now select a non-trivial non-negative $ϕ∈C^∞_0(a,b)$ with support inside $(c,d)$ and draw conclusions from $\int^b_af(x)ϕ^n(x)dx=0$.
Maybe there is something missing in the assumptions.

The corrected assumption is that $\int^b_af(x)ϕ^{(n)}(x)dx=0$ for any $ϕ∈C^∞_0(a,b)$. For the distributional interpretation see the comments.
Try a more elementary approach. Let $b_h$ be the box function that has value $1$ from $0$ to $h>0$. Then the convolution product $b_h*ϕ∈C^∞_0(a,b)$ inherits smoothness from $ϕ$ and the compact support from both factors united.
$$
(b_h*ϕ)'(x)=(b_h*ϕ')(x)=\int_0^h b_h(t) ϕ'(x-t)\,dt=\int_{x-h}^x ϕ'(s)\,ds=ϕ(x)-ϕ(x-h)
$$
and so
$$
\int_{\Bbb R}g(x)\,(b_h*ϕ)'(x)\,dx=\int_{\Bbb R}(g(x)-g(x+h))\,ϕ(x)\,dx=\int_{\Bbb R}((-Δ_h) g)(x)\,ϕ(x)\,dx
$$
Repeated application of this identity results in
$$
\int_{\Bbb R}f(x)\,((b_h*)^nϕ)^{(n)}(x)\,dx=\int_{\Bbb R}((-Δ_h)^n f)(x)\,ϕ(x)\,dx
$$
which means that $Δ_h^n f=0$ a.e. resulting in $f(x+kh)=p_{x,h}(x+kh)$ a.e., where $p_{x,h}$ is a polynomial of degree less than $n$.
Next to prove: $p_{x,h}$ is, a.e., independent of $x$ and $h$. Perhaps include some smoothing kernel in the convolution product, making the smoothed version of $f$ continuous and thus one polynomial everywhere...


text:
Q: glob.iglob Remove path from filename I am trying to get the most recent file added to a directory using python 2.7 os and glob modules.
import os
import glob

path = "files/"
newestFile = max(glob.iglob(path + '*.txt'), key=os.path.getctime)

print newestFile

When I print the newestFile variable I get the path included i.e.

files\file.txt

I just want the filename but my .txt file and .py script are not in the same directory. The text file is one directory down under the files directory. How do I refer to the directory and get the newest .txt file added to that directory.

A: You can use os.path.basename to just get the filename:
newestFile = os.path.basename(max(glob.iglob(path + '*.txt'), key=os.path.getctime))

os.path.getctime is going to need the full path so one way or another you would have to use the full path.


text:
Q: What condition is causing this program to leave the for loop early due to a EOF character? Go ahead and look to the bottom of this post for the actual question
I may be trying to understand the really simple things a bit too much, but I just cannot continue until I figure this out.
While reading K&R 1.9 Character Arrays, you come across an example program which takes input and determines which line was the longest, then it reprints it.
In order to understand the getline function of this program, I have modified it slightly to print some information during its progression. Now I have found some input which, once I understand, should greatly enhance my understanding of getchar().

On a side note, when I try to read source code from the libraries I get completely overwhelmed. For example I tried hunting down getchar() and ended up staring dumbfounded at a tower of 18 #endif somewhere on line 300ish of stddef.h. I am going to save that headache by discontinuing the pursuit of functions in stdio.h for the near future. Is it normal that the libraries are extremely hard to find something? Shouldn't the function exist as readable source, or do I just have my hopes up?

I will just go ahead and post the entire modified program from K&R for convenience sake:
#include <stdio.h>
#define MAXLINE 5   /* maximum input line length */

int getline(char line[], int maxline);
void copy(char to[], char from[]);

/* print the longest input line */
main()
{
    int len;            /* current line length */
    int max;            /* maximum length seen so far */
    char line[MAXLINE];    /* current input line */
    char longest[MAXLINE]; /* longest line saved here */
    max = 0;
    while ((len = getline(line, MAXLINE)) > 0)
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 0)  /* there was a line */
        printf("%s\n", longest);
        printf("INFO: max = %d\n", max);
        printf("INFO: sizeof s[] = %d", sizeof longest);
    return 0;
}

/* getline:  read a line into s, return length  */
int getline(char s[],int lim)
{
    int c, i;
    for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i){
        s[i] = c;
        printf("INFO: s[%d] = %c\n", i, c);
    if (c == '\n') {
        printf("INFO: %d\n", i);
        printf("INFO: s[%d] = \\n\n", i);
        s[i] = c;
        ++i;}
    }
    s[i] = '\0';
    return i;
}

/* copy:  copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
    int i;
    i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
}

Here is some example input/output: I am using CodeBlocks and Windows 7

Finally, my question is why does the for loop in the getline() function leave the loop after it gets to F and therefore places the null terminator after F as \0
My hypothesis is that perhaps putting the EOF character shown as ^Z in the windows terminal, the array is truncated to a length of 4 characters plus a null terminator. It turns out if I put the EOF character inside a line to be read, the saved line s[] will only contain a maximum size of 5. What also confuses me is that the variable len will always be 0, is that because len is assigned during the while loop in main(), and does not have its value saved once that while loop is broken?
Something interesting to me, but probably not to experienced C users, is that the if statement right after the for loop in getline() can either be inside the for loop, or outside and it does not change the program. Interesting, because won't that mean that whether or not the for loop executes any code in the body, at the very least (c=getchar()) is executed?
Sorry the question is so wordy, I appreciate any helpful comments/answers.

A: Because MAXLINE is 5, and the getline function never reads more than MAXLINE - 1 characters.


text:
Q: IKAnalyzer loadExtendWords I got a question when I use the IKAnalyzer as a Chinese Segmentation
and I just want to load my own extend words to dictionary, but it does not seem to work:
code follows:
        Dictionary dic = Dictionary.getInstance();
        Dictionary.loadExtendWords(Arrays.asList("abc"));
        Dictionary.loadExtendWords(Arrays.asList("abc2013"));
        Dictionary.loadExtendWords(Arrays.asList("学校2013"));
        String testString = "test abc abc2013 Chineses:学校2013";
        Analyzer analyzer = new IKAnalyzer(true);
        TokenStream ts = analyzer.tokenStream("demo", new StringReader(testString));
        ts.reset();
        StringBuilder sb = new StringBuilder();
        String t = null;
        while (ts.incrementToken()) {
            t = ts.getAttribute(CharTermAttribute.class).toString();

            sb.append(t).append(" ");
            System.out.print(t + "|");

        }
        ts.end();
        ts.close();

the output is "test|abc|abc2013|chineses|学校|2013|", as you can see the self-defined word "学校2013" does not work.
it seems that IKAnalyzer is not useful for mix of Chineses and English.


text:
Q: Negating values in asymptote How do I negate values in Asymptote? I tried using not(true) but there does not seem to be an inbuilt not function for this.
Sure, I can define a function to do this, but I just want to know if there is standard way to do this in Asymptote

A: You're looking for the ! negation operator.
bool b = true; // b now equals true
b = !b;        // b now equal false

This operator and others can be found in section 6.9 of the documentation.


text:
Q: string manipulation in bash ${@:1:$#-1} May you please explain what does this mean:
@:1:$#-1
can you provide an exact explanation?

A: That's a parameter expansion that returns all the positional parameters but the last one.
It's based on ${parameter:offset:length}, where using @ as parameter makes it work on positional parameters. The length $#-1 is the number of positional parameters ($#) minus one.
Here's a showcase : https://ideone.com/HKcaNj


text:
Q: Using SPF for spoof protection I'm trying to work through properly configuring SPF for my domain. We have two MX servers that only receive mail, and two outbound relay servers which we expect to list in our SPF record.
We also have a mail server in a subdomain called mail.sub.example.com. It only sends mail for this subdomain. The two MX servers are also responsible for incoming mail for this domain.
The problem I'm having is users often forward their mail off this subdomain server and on to Gmail and other providers, where they use the features of these remote providers to send mail as user@sub.example.com.
Would it then be advisable to add Google's SPF record as an include?
I'm concerned that doing this will open up all of Google to be able to spoof my domain. If it's not listed, we lose the benefit of maintaining the security SPF provides throughout the entire email chain.
I'd also like to benefit from the SPF protection when receiving an email to one of the MX servers from my own domain, and using it to protect my own users from receiving a forged email from a user in our domain.

A: Sub and example should have separate SPF records, include the servers that you send email FROM:
I would suggest using the ip4: mechanism, not the A, MX, or PTR, save those DNS lookups for include: if you add 3rd party ESPs later on.
-all to reject
Also look into DMARC as it will have a higher success rate of spoof protection with large mailbox providers.
Gmail will send email from gmail but on behalf of user@example.com, so it will use the SPF for gmail and not example.com


text:
Q: Order of code in Clojure I have a simple yet frustrating problem in Clojure, I have a function (let's call it read-function) which figures out what the user wants to do from his input then calls another function that does that (let's call it action-function).  This action-function calls the read-function when it's done so the user can perform another task.
Now my problem is that if I put the code for read-function before the code for action-function, I get an error in read-function saying that it doesn't know what action-function is (because the code for it is further down) and if I do the opposite, well I get a similar error obviously, saying that read-function cannot be resolved etc.
Is there a simple way to fix this ?
The actual code:
(defn ajout [botin]
  (def botin botin)
  (readCmd botin)
)

(defn readCmd [botin]
  (println "Entrez une commande svp ")
  (def botin botin)
  (let [cmd (read-line)]
    (if (.equals cmd "a") ((println "Ajout 8o") (ajout botin))
      (if (.equals cmd "e") ((println "Elim 8o") (eliminer botin))
        (if (.equals cmd "i") ((println "Imprim 8o") (imprimer botin))
          ((println "Commande invalide, nous vous rapellons que les commandes possibles sont : ") (print-les-cmd) (readCmd))))))

)

like this, I get an error at the   (readCmd botin)    line in the ajout function saying :
Unable to resolve symbol: readCmd in this context
If I put the code for these two functions in the reverse order I will get an error saying :
Unable to resolve symbol: ajout in this context

A: You can use forward declarations in Clojure so you can call functions that haven't been defined yet.
(declare readCmd)

should work!
In Clojure, the order in which you define functions is important, a function can't call another function (or anything for that matter) that hasn't been defined yet. That's why we have forward declarations.

A: There's a thread on the Clojure google group about this that provides some interesting considerations, in particular on how the use of declare can trip up some tools in the ecosystem:
thread
Of course, you could argue good tools should work with all the constructs of the language :)
IMO, you kind of get used to the bottom-up style and just read in reverse. It's a bit of a different story your telling where you build things up rather than decompose them.
And of course, as others have said, you can forward declare with
(declare my-function)

A: As the others already answered, you need to (declare readCmd) to fix your immediate problem.
However, there are still problems with this code, because it actually implements iterative process using mutual recursion (readCmd -> ajout -> readCmd -> imprimer -> readCmd -> ...) which will consume stack and will you'll get (on) stack overflow.  A better way to organize this, would be to make readCmd tail recursive, and make it call the actions.  When an action returns, readCmd tail recursively calls itself.
Also this code snippet:
((println "Ajout 8o") (ajout botin))

probably is not what you want to do: it'll call println and will try to use the result as a function.  Use "do" instead:
(do (println "Ajout 8o") (ajout botin))

You may also consider reading about case or cond, they will simplify the nested ifs.
Another strange thing about your code is
(def botin botin)

what it is about?

A: At the top of your code put:
(declare readCmd)


text:
Q: CURL DOMXPath different values I have this curl function that extracts the html from a website.
function curl($url){
    $headers[]  = "User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
    $headers[]  = "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    $headers[]  = "Accept-Language:en-us,en;q=0.5";
    $headers[]  = "Accept-Encoding:gzip,deflate";
    $headers[]  = "Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $headers[]  = "Keep-Alive:115";
    $headers[]  = "Connection:keep-alive";
    $headers[]  = "Cache-Control:max-age=0";

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_ENCODING, "");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

And in order to retrieve the data I use :
$html = curl($USE_URL);
$doc = new DOMDocument();
$doc->loadHTML($html);
$data = new DOMXPath($doc);

$date_list= $data->query('............');
$name_list= $data->query('............');

echo $date_list->length;
echo $name_list->length;

If I run this code in the 'localhost' it works smoothly (giving me length 52,52): . but if I use the exactly same code on my altervista website it gives me that the date_list length is zero! (length 0,52)
The date_list format that I extract is a string like "08-09-2018 12:47"
Is there something wrong the the curl $headers maybe?

A: Weirdly I solved this by changing the query: I had to work my way around it: so basically my new query extracts a larget set of data (eg "abcd deddeh dede 12:30 dhhh") and manually extract my real data by manipulating the string (using split methods..)
$date_list= $data->query('.....HERE......');

I think that when CURL downloads the page it doesn't let it completely unvaried.


text:
Q: jQTouch _webapp link I have one main page and other sources on other pages. Since I can't use ajax loading because of the server limitation, I have to use target="_webapp" attribute to load on new page

Link to external page

... content ...

Since normal back button (        a href="#") doesn't work with external page, I'm using javascript:history.go(-1)

The External Page

Back

Internal page

Internal page

... content ...

Page 1

Back

.. content...

Page 2

Back

.. content...

It works if user navigate #home -> #the-external-page -> #home
but since the other pages have multiple link within it when user visit #page1, #page2 all the history stack and the back button doesn't work until pressed multiple time.
I can't put absolute link in the back button either because the list of original pages are dynamically generated.
Is there way to go back to resolve this ?

A: Did not test with your code, but I suspect .goBack() in the jQtouch object may be what you're looking for: https://code.google.com/p/jqtouch/wiki/PublicObject
Relevant section:

goBack( to:object )
Forces jQTouch to go back to a certain page in the history. You can pass a specific page ID, a number of pages to go back, or nothing to go back one page. If the specified page can not be found, jQTouch will go back one page by default.


text:
Q: In Flutter, is it possible to use Provider to create a listener function So I have this provider
import 'package:flutter/material.dart';
import 'package:gotaxi_flutter/enums.dart';
import 'package:gotaxi_flutter/models/google_places_models/google_places_models.dart';

class PlaceInfo {
  GooglePlace place;
  bool isDestination;
  PlaceInfo(this.place, this.isDestination);
}

class RideInfoProvider with ChangeNotifier {
  CurrentRideScreen _currentRideScreen = CurrentRideScreen.none;
  PlaceInfo? _place;

  PlaceInfo? get place => _place;

  CurrentRideScreen get currentRideScreen => _currentRideScreen;

  void setCurrentRideScreen(CurrentRideScreen screen) {
    _currentRideScreen = screen;
    notifyListeners();
  }

  //set origin or destination locations
  void setPlace(GooglePlace place, bool isDestination) {
    _place = PlaceInfo(place, isDestination);
    notifyListeners();
  }
}

How can I create something similar to the following inside my widget:
@override
  void initState() {
    super.initState();

    _rideInfoProvider = RideInfoProvider();

    _rideInfoProvider.addListener(() {
      print("RideInfoProvider changed");
      if (_rideInfoProvider.place != null) {
        print(_rideInfoProvider.place);
        //run other functions or instances that exist in this widget and may utilize the place variable
      }
    });

}

Because otherwise, I have to move the whole listener logic and variables to the provider.

A: You could add and remove your listener based on the stateful widget lifecycle.
This means that myListenerFunction will be called on each call to notifyListeners() from RideInfoProvider until the widget gets disposed.
Do add the listener as a separate function in order to be able to remove it later passing the same reference (to the function).
And as @josip-domazet commented I would not recommend using a consumer for this as that would call the myListenerFunction from inside the build method of a widget, so it would be called each time flutter repaints that widget, instead of only when a new change is made in the notifier.
@override
  void initState() {
    super.initState();

    _rideInfoProvider = context.read<RideInfoProvider>();

    _rideInfoProvider.addListener(myListenerFunction);

}

@override
  void dispose() {
    super.dispose();

    _rideInfoProvider.removeListener(myListenerFunction);

}


text:
Q: How do I fix this code to sent to #reported A relatively simple command that takes 3 arguments (reportedTag, reporterTag, and reasons) with the simple intent of deleting the message from #report and sending one to #reported my issue is that it doesn't see the original command and hence does not send the reported message
I've tried using the channel ids, the channel names but to no avail
#---Report Command---#
@bot.command(pass_context=True)
async def report(ctx,  reportedTag, reporterTag, *reasons):

  if int(ctx.message.channel.id) == 416164062901305345:
    reason = ' '.join(reasons)
    await bot.delete_message(ctx.message)
    mesg = "Report by "+ reporterTag +  " for " + reportedTag + "Reason is: " + reason
    return await bot.say("Report recieved. Staff have been notified :)\nEnjoy your day and we'll take care of this")
    return await bot.send_message(bot.get_channel("534496148149370900"), mesg)
  else:
      print ("Something went wrong")

Expected result: command line deleted from #report and message sent to #reported
Actual result: "Something went wrong"

A: Two things wrong:
There's a problem in the return statement you used in the code. return exits a subroutine, so the line bot.send_message(bot.get_channel("534496148149370900"), mesg) is never actually called. So your code should change to something like this:
#---Report Command---#
@bot.command(pass_context=True)
async def report(ctx,  reportedTag, reporterTag, *reasons):

if int(ctx.message.channel.id) == 416164062901305345:
    reason = ' '.join(reasons)
    await bot.delete_message(ctx.message)
    mesg = "Report by "+ reporterTag +  " for " + reportedTag + "Reason is: " + reason
    await bot.send_message(bot.get_channel("534496148149370900"), mesg)
    return await bot.say("Report recieved. Staff have been notified :)\nEnjoy your day and we'll take care of this")
else:
    print ("Something went wrong")

Apart from that, if "Something went wrong" is actually outputted, that means that int(ctx.message.channel.id) == 416164062901305345 is false. Please check the ID and the channel you're writing in.


text:
Q: ayuda con group by en mysql Tengo que sacar el monto total por cada unidad que tengo en mi tabla, el problema esta que un registro que supuestamente es de la unidad 3 pertenece a la unidad 1, no se como agrupar para que quede de manera correcta, esta es mi consulta.
select SUM(TOTAL) as total, SUBSTRING(UNIDAD,1,1) as unidad from estruc_programatica group by unidad;

solo puedo obtener lo de la tercer tabla, que muestro en la imagen pero quiero la tabla de en medio, el registro que tengo que agrupar  con la unidad 1 es el 3180, seria {1100,1200, 3180} la unidad 1, {2300} la unidad 2 y {3900, 3050} la unidad tres. Ya llevo rato intentando sacarlo, pero no puedo.

A: Según lo que indicas, quieres agrupar por el primer caracter de unidad salvo la unidad == 3180 que correspondería a la unidad 1. Deberías hacer algo así:
select  SUM(TOTAL) as total,
        CASE WHEN UNIDAD = 3180 THEN 1 ELSE SUBSTRING(UNIDAD,1,1) END as unidad
        from estruc_programatica
        group by CASE WHEN UNIDAD = 3180 THEN 1 ELSE SUBSTRING(UNIDAD,1,1) END;

Aclaración: Si no lo tienes, es recomendable contar con una tabla secundaria que haga la relación entre las unidades originales y la "unidad" que estas buscando, de esta forma podrías manejar mas elegantemente estas excepciones, por ejemplo: (3180, 1)


text:
Q: Pytrends error: failed on_status, TrendReq.trending_searches() missing 1 required positional argument: 'self' I would like to get the latest Google Trends with Pytrends. I have installed a completely new system with Python 3.10.1 and Pytrends. The code is quite simple:
#pip install pytrends

from pytrends.request import TrendReq

pytrends = TrendReq.trending_searches(pn='US')
print(pytrends.head(20))

However, I still get this error message:
TypeError: TrendReq.trending_searches() missing 1 required positional argument: 'self'

I can't find any help with googeling. Do any of you have an idea what the problem is here?

A: I have found a solution for me. With the examples on the github page of Pytrends:
from pytrends.request import TrendReq

pytrend = TrendReq()

trending_searches_df = pytrend.trending_searches(pn = "united_states")
print(trending_searches_df.head())

I can't explain why so many tutorials on the Internet have the wrong code. But with this it works without problems.


text:
Q: Callback function in xtend How can I call a callback function in xtend?
I am looking for something similar to the one in C.
Example:
    struct callbacks
    {
      char name[10];
      boolean (*pfState)();
    };

    static const struct callbacks call[] = {
      {"YOURS", &isOwner},
      {"OURS", &our_owner}
    };

So, I will just call it like this: call[0].pfState().
I have created a similar ArrayList in xtend.
    val you = new youModule()
    val our = new ourModule()
    val callbacks = newArrayList('YOURS' -> you.isOwner, 'OURS' -> our.isOwnder);

Am I doing this correctly? How can I execute the function call in the pair?

A: Currently you create a list of Pairs which map strings to the result of the method invocation, e.g. assuming #isOwner returns a boolean, your list callbacks is currently a List<Pair<String, Boolean>>.
Instead, you have to wrap the invocation of #isOwner in a lambda expression:
val callbacks = newArrayList(
  'YOURS' -> [| you.isOwner ],
  'OURS' -> [| our.isOwnder ]
);

Now, callbacks has the type List<Pair<String, ()=>boolean>>, or in other words: List<Pair<String, Functions.Function0<Boolean>>>.

A: If you have a "callback" stored in a variable, you need to invoke the function by calling apply on it.
Here is a simple example showing a hash map that contains two callbacks stored under 'YOURS' and 'OURS' key. When called, each callback function prints a different message and returns a boolean value.
    val callbacks = newHashMap(
      'YOURS' -> [| println("calling the first callback");  true  ],
      'OURS'  -> [| println("calling the second callback"); false ]
    )

    val result = callbacks.get("YOURS").apply

// result is: true
// console output is: calling the first callback