text:
Q: Counting Methods declaration + Methods Calls in a class using JavaParser I'm trying to code rfc metric (Response for a Class), it counts the Method declarations + Method Calls.
Method declarations works fine, but I got a problem at counting method calls using JavaParser API.
Here is my code:
public class MethodPrinter {

    public static void main(String[] args) throws Exception {
        // creates an input stream for the file to be parsed
        FileInputStream in = new FileInputStream("D://test.java");
        CompilationUnit cu;
        try {
            // parse the file
            cu = JavaParser.parse(in);
        } finally {
            in.close();
        }
        // visit and print the methods names
        MethodVisitor MV =new MethodVisitor();

        cu.accept(new VoidVisitorAdapter<Void>(){
            @Override
            public void visit(final MethodCallExpr n, final Void arg){
                System.out.println("method call :"+n);
                super.visit(n, arg);

            }
        }, null);
    }
}

test.java
package test;
import java.util.*;

public class ClassA
{
  private int test;
  private ClassB classB = new ClassB();
  public void doSomething(int t){

    System.out.println ( toString());
    int i= doSomethingBasedOnClassBBV(classB.toString());
  }
  protected void doSomethingBasedOnClassB(){
    System.out.println (classB.toString());
  }
}

public class ClassB
{
  private ClassA classA = new ClassA();
  public void doSomethingBasedOneClassA(){
    System.out.println (classA.toString());
  }

  private String toString(){
    return "classB";
  }
  private String toString(){
    return "classB";
  }
  public void doSomethingBasedOneClassA(){
    System.out.println (classA.toString());
  }
  protected void doSomethingBasedOnClassB(){
    System.out.println (classB.toString());
  }
}

the result of that code:
*method call :System.out.println(toString())

method call :toString()

method call :doSomethingBasedOnClassBBV(classB.toString())

method call :classB.toString()

method call :System.out.println(classB.toString())

method call :classB.toString()

method call :System.out.println(classA.toString())

method call :classA.toString()

method call :System.out.println(classA.toString())

method call :classA.toString()

method call :System.out.println(classB.toString())

method call :classB.toString()*

indeed, that code inspects method calls, but in my case I don't want it to count libraries method calls like System.out.println(toString()), I want it to count only toString().
If you got a better code, or another API to use... any help is welcomed, thank you in advance.

A: You cannot easily resolve your issue using exclusively a parser, because you need to resolve the method call and find out if it is a call to a method part of the standard library.
You can easily do that using JavaSymbolSolver, which is a library created to complement JavaParser. In practice you call:
JavaParserFacade.solveMethodAsUsage(myMethodCallExpr)
And you get back a MethodDeclaration which tells you also the type on which that method was defined. Once you have the type you can look at the package and check if it starts with java or javax and exclude it.


text:
Q: Appending multiple returned values to different lists in Python I have function that calculates and returns 7 floats, and each value gets appended to a different list. I feel there must be something wrong if I am typing out 7 different append statements, but is there a more pythonic way todo this.
For example (I don't even like typing it here!):
a,b,c,d,e,f,g = range(7)
alist.append(a)
blist.append(b)
clist.append(c)
dlist.append(d)
elist.append(e)
flist.append(f)
glist.append(g)

According to this related question it would seem this is not possible... There must be a way using +=[a] or list comprehension or a loop or something?
One thing that comes to mind is to keep appending all those 7 values to a master list and then transpose it at the end with zip(*MasterList) to generate the individual lists?
What would people recommend?

A: appenders = range(7)
mylists = [alist, blist, clist, dlist, elist, flist, glist]
for x, lst in zip(appenders, mylists):
    lst.append(x)

A: Well one option is to create a list of arrays, for example, something like this:
    # define function like this:
    def range(7):
        ...
        return [a,b,c,d,e,f,g]

    # append to list:
    arr = range(7)
    arrList.append(arr)

    # How to call your variables:
    arrList[0][0]    # Should return first a.

You could make this option easier to work with, using dataframes from pandas, see this introduction, where you have to import pandas as pd(as pd is recomended) and could define headers to your list:
    data = arrList    # You can use data = []
    columns = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

    # Create the DataFrame
    df = DataFrame(data, columns)

    # And to add rows use*:
    df.append(range(7))

*See Documentation including DataFrame.Append()
Usage of this is the following:
    # Usage example:
    df['a']        # returns the alist
    df.loc[0,'a']  # returns first value in alist
    df.loc[0,:]    # returns row of values of all lists

And for more usage info, see this
A different option is creating a function that does all those appends in one bu you'll type the code anyway, like this:
    def range(n):
        ...
        return a,b,c,d,e,f,g

    def appendToLists(a,b,c,d,e,f,g):
        alist.append(a)
        blist.append(b)
        clist.append(c)
        dlist.append(d)
        elist.append(e)
        flist.append(f)
        glist.append(g)

    # Example:
    appendToLists(range(7))

Don't know if it's what your looking for because the list would have to be global.

A: I like @Ryne's answer because it is straightforward, but here is the option I am pondering.
# inside the loop
master_list.append(range(7))
# once you are done, transpose...
alist,blist,clist,dlist,elist,flist,glist = zip(*master_list)

A: Maybe you want a list of lists:
>>> [[item] for item in range(7)]
[[0], [1], [2], [3], [4], [5], [6]]

You could iterate over them without retyping the names.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you change the maximum upload size for a specific page? Ok.. say I have a music service, how can I increase the maximum file upload size for that specific page so it won't time out if a large file is chosen?
Ok, I know you can tinker with the php.ini file by changing
memory_limit = 32M
upload_max_filesize = 10M
post_max_size = 20M

, but then that sets that globally.

A: You may want to change the maximum upload file size for your web site. For example, you can set a lower limit to prevent users from uploading large files to your site. To do this, change the upload_max_filesize and post_max_size directives in an .htaccess file.
To change the maximum upload file size for your PHP scripts, follow these steps:
Log in to your account using SSH.
Use a text editor to add the following line to the .htaccess file. Replace xx with the maximum upload file size that you want to set, in megabytes:

php_value upload_max_filesize xxM

Add the following line to the .htaccess file. Replace xx with the maximum HTTP POST file size that you want to set, in megabytes:

php_value post_max_size xxM

Save the changes to the .htaccess file and exit the text editor.
To verify that the new setting is active, create a PHP test file that contains the following code in the same directory where the .htaccess file is located:
Load the test file in your web browser, and then search for the name of the directive. The Local Value column should display the new setting that you specified in the .htaccess file.
for more detail http://www.cyberciti.biz/faq/linux-unix-apache-increase-php-upload-limit/
or
<?php

// Define file size limit
$limit_size=50000;

  code......

$file_size=$HTTP_POST_FILES['ufile']['size'];

if($file_size >= $limit_size){
echo "Your file size is over limit
";
echo "Your file size = ".$file_size;
echo " K";
echo "
File size limit = 50000 k";
}
else {

   code............

A: See PHP change the maximum upload file size for different available methods.
You can use multiple upload pages (depending on the uploader limit you want to set), stored in different directories, with different .htaccess configurations, which would allow you to group your users by upload limit.

A: add this to your php
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M

; Must be greater than or equal to upload_max_filesize
post_max_size = 40M


text:
Q: How do I go to, and finish one sub function, and then revert back to the "menu function" that I came from? (python) Ideally, I'd like there to be a step in the "Add Movie" process that confirms that it's an integer for the year, and once it's accepted, to continue back to the main menu once the movie has been added successfully...
(I'm not going to ask or into how I'd love for it to save user input data to a file to be pulled from so it's not like I'm making a new entry every time, haha)
Here's what I've got... and again, this is my effort after maybe 4 hours of a 27 hour course.
I'm hoping you guys can understand what I'm trying to accomplish... but it's just not "finishing" correctly after the "add movie" function... you should see what I'm talking about.
import sys
import random
import os

movies = []

def menu():
    print("Welcome to 'The Movie Program!!'")
    print("(A)dd movie to your list")
    print("(L)ist movies you've added")
    print("(S)earch for movies in your list")
    user_input = str(input("Which function would you like to do?:\n\n""Selection: ").capitalize())
    while user_input != 'Q':
        if user_input == 'A':
            add_movies()
        elif user_input == 'L':
            show_movies()
        elif user_input == 'A':
            search_movies()
        else:
            print("\n\n--Unknown command--Please try again.\n")
            menu()

            #user_input = str(input("\nWhich function would you like to do?:\n"
            #                   "(A)dd movie to your list\n"
            #                   "(L)ist movies you've added\n"
            #                   "(S)earch for movies in your list\n\n""Selection: ").capitalize())

def add_movies():
    name = (input('What is the title of the movie?: ').title())
    director = str(input("Who was the director of this movie?: ").title())
    while True:
        try:
            year = int(input("What was the release year?: "))
            return year
            break
        except ValueError:
            print("Only numbers, please.")
        year = False

        #return year

        #if year < 0:
        #    print("Sorry,your response must not be negative.")
        #    continue
        #else:
        #    return year

    movies.append({
        "name": name,
        "director": director,
        "year": year
    })

def show_movies():
    movies[::3]
    for c, value in enumerate(movies, 1):
        print(c, value)
    for movie in movies:
        print(f"Name: {movie['name']}")
        print(f"Director: {movie['director']}")
        print(f"Release Year: {movie['year']}\n")
'''Not done yet
def search_movies():
    movies
    print("This is where you'd see a list of movies in your database")

'''
menu()

A: put
user_input = str(input("Which function would you like to do?:\n\n""Selection: ").capitalize())

inside of while-loop and give user_input value before loop.
like that:
print("Welcome to 'The Movie Program!!'")
print("(A)dd movie to your list")
print("(L)ist movies you've added")
print("(S)earch for movies in your list")
user_input=str(input("Which function would you like to do?:\n\n""Selection: ").capitalize())
while user_input != 'Q':
    if user_input == 'A':
        add_movies()
    elif user_input == 'L':
        show_movies()
    elif user_input == 'A':
        search_movies()
    else:
        print("\n\n--Unknown command--Please try again.\n")
        print("Welcome to 'The Movie Program!!'")
        print("(A)dd movie to your list")
        print("(L)ist movies you've added")
        print("(S)earch for movies in your list")
    user_input = str(input("Which function would you like to do?:\n\n""Selection: ").capitalize())

Also you should make movies as variable and returnvalue for functions or make it a global variable.


text:
Q: Fetching child objects belongs to parent object & put them in tableView (core-data, relationships) I have two tableViews, the main one adds the parent object, and when you click on a parent object in the tableView, it takes you to the child tableView, I did the first part successfully, but when it comes to fetching the "RIGHT" child objects I get confused, I way I do it is that I fetch ALL child object, the using enumeration I pick the right ones and put then into a NSSet, but that doesn't work, here's the child object table view.m:
 #import "MinorGoalsTableViewController.h"

 @interface MinorGoalsTableViewController ()

 @end

 @implementation MinorGoalsTableViewController
 @synthesize selectedGoal = _selectedGoal;
 @synthesize fetchedResultsController = _fetchedResultsController;
 @synthesize minorGoalsSet;

 // init with goal (for GTVC)
 - (id) initWithGoal:(Goal *)goal {
if (self = [super init]) {

    _selectedGoal = goal;

}

return self;
 }

 - (id)initWithStyle:(UITableViewStyle)style
 {
self = [super initWithStyle:style];
if (self) {
    // Custom initialization
}
return self;
 }

 - (void)viewDidLoad
 {
[super viewDidLoad];
NSError *error = nil;

// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;

NSLog(@"Minor Goals in %@ are: %lu", self.selectedGoal.title , (unsigned long)[self.selectedGoal.minorGoal count]);

 //    self.minorGoalsSet = nil;

// initializing minorGoalsSet
self.minorGoalsSet = [[NSMutableSet alloc] init];

// performing fetch
if (![self.fetchedResultsController performFetch:&error]) {
    NSLog(@"Error fetching all minor goals: %@", error);
    abort();
}

// creating NSSet that will carry all selectedGoal minor goals
NSSet *minorGoals = self.selectedGoal.minorGoal;

// creating a loop to add minor goals in minorGoalsSet
// add existing minor goals in selected goal to minorGoalsSet
for (MinorGoal *minor in minorGoals) {
    [minorGoalsSet addObject:minor];
}

NSLog(@"minor goals in set: %lu", (unsigned long) [minorGoalsSet count]);
NSLog(@"minor goals in set2: %lu", (unsigned long) [minorGoals count]);

// setting nav title to selected goal title
self.navigationItem.title = _selectedGoal.title;

// adding "add" button to nav
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewMinorGoal)];

 }

 - (void) viewWillDisappear:(BOOL)animated {
self.selectedGoal = nil;
 }

   - (void)didReceiveMemoryWarning
  {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
  }

pragma mark - Table view data source
   - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  {
return [self.selectedGoal.minorGoal count];
//    id <NSFetchedResultsSectionInfo> secInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
//    return [secInfo numberOfObjects];
  }

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

cell.accessoryType = UITableViewCellAccessoryNone;

// Configure the cell...
MinorGoal *minor = [self.fetchedResultsController objectAtIndexPath:indexPath];

// well see about that later
if ([minorGoalsSet containsObject:minor]) {
    cell.textLabel.text = minor.title;
}

// setting cell's title to minor goal's title
 //    cell.textLabel.text = minor.title;

return cell;
 }

pragma mark - fetched results controller method
 - (NSFetchedResultsController*) fetchedResultsController {
if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}

// creating fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
     NSEntityDescription *entity = [NSEntityDescription entityForName:@"MinorGoal"
                                             inManagedObjectContext:self.selectedGoal.managedObjectContext];
[fetchRequest setEntity:entity];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                               ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

// setting _fetchedResultsController
   _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.selectedGoal.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

// performing fetch
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
    NSLog(@"Error fetching minors: %@", error);
}

// returning
return _fetchedResultsController;

    }

pragma mark - Table view delegate
   - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {

 }

 - (void) addNewMinorGoal {

// code to show UIAlertView that will add new minor goal
// creating UIAlertView
    UIAlertView *addMinorGoalAlert = [[UIAlertView alloc] initWithTitle:@"Add Minor Goal" message:@"Minor Goal Title" delegate:self cancelButtonTitle:@"Cancel"      otherButtonTitles:@"Save", nil];

// Adding plain textfield for minor goal title
addMinorGoalAlert.alertViewStyle = UIAlertViewStylePlainTextInput;

// showing UIAlertView
[addMinorGoalAlert show];
}

pragma mark - UIAlertView for Add New Minor Delegation
  - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

      if (buttonIndex == 0) {
          NSLog(@"Adding Minor Goal Canceled!");
     }

      else

     {

    // creating string will carry textField value
    NSString *minorTitle = [[alertView textFieldAtIndex:0]text];

    // creating new minor goal
    MinorGoal *newMinorGoal = [NSEntityDescription
                               insertNewObjectForEntityForName:@"MinorGoal"
                                  inManagedObjectContext:self.selectedGoal.managedObjectContext];

    // setting title of new minor goal
    newMinorGoal.title = minorTitle;

    [self.selectedGoal addMinorGoalObject:newMinorGoal];

    // saving
    NSError *error = nil;
    if (![self.selectedGoal.managedObjectContext save:&error]) {
        NSLog(@"Error saving new minor goal: %@", error);
    }
    NSLog(@"we save %@ to %@ and theres %lu in it", newMinorGoal.title,      self.selectedGoal.title, (unsigned long) [self.selectedGoal.minorGoal count]);

    // fetching
    [self.fetchedResultsController performFetch:&error];

    // reloading tableView data
    [self.tableView reloadData];

   }
  }

 @end

Just tell me the right way to fetch the right child object, and should i put them in a NSSet?

A: It appears that you are using a NSFetchedResultsController to get ALL MinorGoal instances, but you just want to show the child MinorGoals.  If you want to use an NSFetchedResultsController then you need to add a predicate to the fetch so that it only returns the MinorGoals that are children of the selected Goal. Assuming that you have created a relationship between MinorGoal and Goal called "parentGoal":
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"self.parentGoal = %@", self.selectedGoal];

Alternatively, don't us the NSFetchedResultsController and instead use the relationship.  You will need to convert the NSSet to an array and sort it as the previous answer.

A: Store your parent object somewhere in your child view controller, typically it should be like
.h file:
@property (nonactomic, strong) ParentObject *parentObject;

.m file
- (id)initWithObject:(ParentObject *)parent {
…
_parentObject = parent;
…
}

then fetching:
(you should have @property (nonatomic, strong) NSFecthedResultsController *fetchedResultController)
- (NSFetchedResultsController*)fetchedResultController {
    if (_fetchedResultController) {
        return _fetchedResultController;
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:NSStringFromClass([ChildObject class])];
    [request setEntity:entity];
    NSSortDescriptor *sortDescription = [NSSortDescriptor sortDescriptorWithKey:@"sortOrder" ascending:YES];
    [request setSortDescriptors:@[sortDescription]];
    request.predicate = [NSPredicate predicateWithFormat:@"(parent == %@)", self.parentObject];
    NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:[NSManagedObjectContext mainThreadContext] sectionNameKeyPath:nil cacheName:nil];
    controller.delegate = self;
    _fetchedResultController = controller;
    return _fetchedResultController;
}

then implement method
- (void)performFetch {
    NSError *error = nil;
    [self.fetchedResultController performFetch:&error];
    if (![self.fetchedResultController performFetch:&error]) {
        [self showAlertWithError:error];
    }
    else {
        [self.tableView reloadData];
    }
}

thats it basically you will receive all child objects you need sorted and filtered by predicate

A: seems like I was doing it the hard way, simply create new array that will hold the child objects.
NSMutableArray *minors = self.selectedGoal.minorGoals.allObjects.

and when you obtain change or add, do it two times, once to the array, and another time with the "self.selectedGoal.managedObjectContext".


text:
Q: polymer iron-ajax body received in express extra object I am trying to send a JSON object from my polymer application to my express API.
I do the following on the client:
<iron-ajax
    id="createRoomAjax"
    url="{{url}}{{roomRoute}}"
    handle-as="json"
    method="POST"
    on-response="onRoomCreated"
    debounce-duration="300">
</iron-ajax>

createRoom: function() {
  this.$.createRoomAjax.body = {
    'name': roomname.value
  };
  this.$.createRoomAjax.generateRequest();
  // console.log(this.$.createRoomAjax);
},

On the express side I print the following:
function(req, res, next) {
   console.log(req.body);
}

Which gives me the following output:

{
      '{"name":"jljk"}': ''  }

I would expect that in my express app I would receive a req with a body: {name: '...'} instead of an extra object that surrounds it. Could someone explain to me why this happens?

A: You could try using params instead of body like so:
  this.$.createRoomAjax.params = {
    'name': roomname.value
}

This works well for me using Polymer and Express.

A: I just found the solution to my problem. It seems that I need to set the contentType of my iron-ajax request to json otherwise it sends the body-payload differently.
new HTML:
  <iron-ajax
        id="createRoomAjax"
        url="{{url}}{{roomRoute}}"
        method="POST"
        content-type="application/json"
        on-response="onRoomCreated"
        debounce-duration="300">
    </iron-ajax>


text:
Q: Location of development solutions on disk - Common or upto the individual In our team meeting today a senior member brought up the proposal that we should be having a common location/structure for our development solutions.
A couple of his points were:

*

*Making it common meant when talking about projects and emailing stuff everyone is on the same wavelength and knows where to look.

*If there is ever the need to hard code a location path then it will work across all developers pc's.

He had a more few points to back up his suggestion but I unfortunately got distracted during the discussion and so didn't hear all of them.  I have no issue with the idea and can see it's merits but I was wondering if it is common or even recommended that all developers place their code in the same folder structure.  Or do developers like to have the flexibility of location solutions where-ever they want?  We currently use SVN for our version control.
In this case his recommendation was to place all code in:
c:\Work\Development\<Customer>\<project>\Code\<solution>\ the code

I guess actual path is irrelevant for this question but added for completeness.

A: I'd say that the developer's particular set-up is down to the developer. I'm not sure if I agree with the "everyone being on the same wavelength idea" - it seems a little vague to me, and this has never been brought up at any company I have ever worked at. But none of that particularly mattered to me, until I read this:

If there is ever the need to hard code a location path then it will work across all developers pc's.

I have never found the need to hard-code a location path, aside from in prototype code, which would never normally get committed (or at least not to the shared development branch). Every standard programming language library should have a method to get the location of the currently executing binary.
Sometimes, that's just not possible, like a document store for a web application for example. In which case, you can use a configuration file to direct your application to the correct location. Once again, most standard programming language libraries will have something appropriate to solve this issue with minimal fuss.
Hard-coding paths will only lead to issues later on. What if your application will be deployed to a server which has it's massive RAID array on the D: drive? Will you maintain two separate branches for this? Will you remember to edit a source file every time you deploy a new version? I'd be very interested to hear about a use case that would demand this.

A: I would suggest you not enforce or enact such a standard because the only benefit will be that it allows you to hide problems in the code base where everything works using this hard coded path right up until the program is deployed to a clients site and they keep getting an error
FileNotFoundException 'c:\work\Development\...
People say it will help building the system because you can hard code these paths, but what you end up with when you have hard coded stuff in your build system is a slow-growth of fixed garbage making it harder for you to restructure or refactor your system. Ultimately these hard-coded bits in build systems always have to be replaced over time, and are unnecessary.
So there's one risk, and the potential benefits are exactly ? I've seen this tried at places I've worked and I have seen these errors crop up and I have yet to see a single benefit whatsoever in those places...

A: I don't think it really matters where a given developer's working set goes.  The source control system can still keep track of it.   Visual Studio puts them in
c:\documents and settings\<user name>\My Documents\Visual Studio 20xx\Solution folder

Where <user name> differs for each developer machine.


text:
Q: Slow copying of files from Bricked NAS to computer via USB 3.0 to SATA Unfortunately I bricked my "Western Digital MyBookLive 3TB" network hard drive. (Only had an ethernet port to access files via network)
After realising it was not going to work again, I decided to take it apart and order a USB 3.0 to SATA adapter to get my important files back.
Using a MacBook Air with 3.0 USB ports and using fuse-ext2 I am able to read access my files. I am trying to copy the files I need but there is a serious bottleneck somewhere.
Currently I am trying to copy 6GB of photos to my laptop, it has been copying for 5 hours and it has only copied 450MB so far with an estimated 2 days remaining. Here's an image
Could anyone explain anyway of making copying a bit faster, and what might be causing the snail pace transfers. I was able to copy my files over the network 100x faster (before it broke :P)!
Also I was reading somewhere that WD made the block size 64k instead of 4k... I must admit I have no idea what this means and how it might effect copying data.


text:
Q: Use Post to change page I've been using Selenium for some time to scrape a website but for some reasons it doesn't work anymore. I was using Selenium because you need to interact with the site to flip through pages (ie: click on a next button).
As a solution, I was thinking of using Post method from Requests. I'm not sure if its doable since I've never used the Post method, and since I not familiar with what it does (though I kind of understand the general idea).
My code would look something like that:
import requests
from bs4 import BeautifulSoup

headers = {"User-Agent":
           "Mozilla/5.0 (Macintosh; Intel Mac OS X 10 11 5) "
           "AppleWebKit/537.36 (KHTML, like Gecko) "
           "Chrome/50.0.2661.102 Safari/537.36"}

url = "https://www.centris.ca/fr/propriete~a-vendre?view=Thumbnail"

def infinity():
    while True:
        yield

c = 0
urls = []
for i in infinity():
    c += 1
    page = list(str(soup.find("li",{"class":"pager-current"}).text).split())
    pageTot = int("".join(page[-2:])) # Check the total number of page
    if c <= pageTot: # Scrape the first page
        if c <= 1:
            req = requests.get(url, headers=headers)
        else:
            pass
            # This is where I'm stuck but ideally I'd be using Post method in some way
        soup = BeautifulSoup(req.content,"lxml")
        for link in soup.find_all("a",{"class":"a-more-detail"}):
            try: # For each page scrape ads url
                urls.append("https://www.centris.ca" + link["href"])
            except KeyError:
                pass
    else: # When all pages are scrape exit the loop
        break

for url in list(dict.fromkeys(urls)):
    pass # do stuff

This is what is going on when you click next on the webpage:
This is the Request (the startPosition begins at 0 on page 1 and increase by leaps of 12)

And this is part of the Reponse:
{"d":{"Message":"","Result":{"html": [...], "count":34302,"inscNumberPerPage":12,"title":""},"Succeeded":true}}

With that information is it possible to use the Post method to scrape every pages ? And how could I do that ?

A: The following should do the trick. I've added duplicate filtering logic to avoid printing duplicate links. The script should break once there are no more results left to scrape.
import requests
from bs4 import BeautifulSoup

base = 'https://www.centris.ca{}'
post_link = 'https://www.centris.ca/Property/GetInscriptions'
url = 'https://www.centris.ca/fr/propriete~a-vendre?view=Thumbnail'
unique_links = set()

payload = {"startPosition":0}

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
    s.headers['content-type'] = 'application/json; charset=UTF-8'

    s.get(url) #Sent this requests to get the cookies

    while True:
        r = s.post(post_link,json=payload)
        if not len(r.json()['d']['Result']['html']):break
        soup = BeautifulSoup(r.json()['d']['Result']['html'],"html.parser")
        for item in soup.select(".thumbnailItem a.a-more-detail"):
            unique_link = base.format(item.get("href"))
            if unique_link not in unique_links:
                print(unique_link)
            unique_links.add(unique_link)

        payload['startPosition']+=12


text:
Q: pytorch embedding index out of range I'm following this tutorial here https://cs230-stanford.github.io/pytorch-nlp.html. In there a neural model is created, using nn.Module, with an embedding layer, which is initialized here
self.embedding = nn.Embedding(params['vocab_size'], params['embedding_dim'])

vocab_size is the total number of training samples, which is 4000.  embedding_dim is 50.  The relevant piece of the forward method is below
def forward(self, s):
        # apply the embedding layer that maps each token to its embedding
        s = self.embedding(s)   # dim: batch_size x batch_max_len x embedding_dim

I get this exception when passing a batch to the model like so
model(train_batch)
train_batch is a numpy array of dimension batch_sizexbatch_max_len.  Each sample is a sentence, and each sentence is padded so that it has the length of the longest sentence in the batch.

File
  "/Users/liam_adams/Documents/cs512/research_project/custom/model.py",
  line 34, in forward
      s = self.embedding(s)   # dim: batch_size x batch_max_len x embedding_dim   File
  "/Users/liam_adams/Documents/cs512/venv_research/lib/python3.7/site-packages/torch/nn/modules/module.py",
  line 493, in call
      result = self.forward(*input, **kwargs)   File "/Users/liam_adams/Documents/cs512/venv_research/lib/python3.7/site-packages/torch/nn/modules/sparse.py",
  line 117, in forward
      self.norm_type, self.scale_grad_by_freq, self.sparse)   File "/Users/liam_adams/Documents/cs512/venv_research/lib/python3.7/site-packages/torch/nn/functional.py",
  line 1506, in embedding
      return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse) RuntimeError: index out of range at
  ../aten/src/TH/generic/THTensorEvenMoreMath.cpp:193

Is the problem here that the embedding is initialized with different dimensions than those of my batch array?  My batch_size will be constant but batch_max_len will change with every batch. This is how its done in the tutorial.

A: Found the answer here https://discuss.pytorch.org/t/embeddings-index-out-of-range-error/12582
I'm converting words to indexes, but I had the indexes based off the total number of words, not vocab_size which is a smaller set of the most frequent words.

A: You've got some things wrong. Please correct those and re-run your code:

*

*params['vocab_size'] is the total number of unique tokens. So, it should be len(vocab) in the tutorial.

*params['embedding_dim'] can be 50 or 100 or whatever you choose. Most folks would use something in the range [50, 1000] both extremes inclusive. Both Word2Vec and GloVe uses 300 dimensional embeddings for the words.

*self.embedding() would accept arbitrary batch size. So, it doesn't matter. BTW, in the tutorial the commented things such as # dim: batch_size x batch_max_len x embedding_dim indicates the shape of output tensor of that specific operation, not the inputs.

A: embedding size in nn.embedding should be max(input_data). check your datatypes of the input_data, as this have to be integer for deterministic.

A: If you are using tokenizer from huggingface transformers this is how you will set up your embedding.
The torch.nn.Embedding accepts two mandatory parameters, Pytorch Documentation

*

*num_embeddings

*embedding_dim

your num_embeddings is the vocab size associated with your tokenizer and your embedding_dim can be the max sequence length (or anything you like, try not to unnecessarily use values that are too big)
So you define your embedding as follows.
embedding = torch.nn.Embedding(num_embeddings=tokenizer.vocab_size,
                               embedding_dim=embedding_dim)
output = embedding(input)

Note that you may add additional parameters as per your requirement and adjust the embedding dimension to your needs.


text:
Q: Create match queue from list of javascript array I have list of jobs that needs to be perform based on the data and device.
This is my sample data
device = [ device0, device1, device2 ]
device0 = {
    group: [MATCH1, MATCH2]
}
device1 = {
    group: [MATCH1, MATCH2, MATCH3]
}
device2 = {
    group: [MATCH2, MATCH3]
}
data = {
  "destination": "destination",
  "text": "Test send message",
  "hlr": "MATCH2"
}

How can i fix my code so that my data can match and perform task to device. I'm sorry this is my first question. I'm still learning programming and I'm not fluent in english.
This is my sample code :
const jobs = []
jobs.push(data)
        if (jobs.length > 0) {
            let task= jobs.shift()
            device.push(device.splice(0, 1)[0]); // swap device position
            dataLoop: for (var i = 0; i < device.length; i++) {
                itemLoop: for (var j = 0; j < device[0].group.length; j++) { // cycle through until find match
                    if (device[0].group[j].toString() === data.hlr.toString()) {
                        console.log(device[0].group[j] + ':' + data.hlr.toString()); // output should be MATCH2 : MATCH2
                        break dataLoop;
                    }
                }
                device.push(device.splice(0, 1)[0]);
            }
            device[0].sendData({ // using first device to perform task
                receiver: data.destination,
                text: data.text,
                request_status: true
            }, function(err, ref) {
                setTimeout(function() {
                   if (err) { console.log(err) }
                   console.log(ref)
                }, 5000)
            });
        }

A: Theres a typo:
itemLoop: for (var j = 0; j < device[i].group.length; j++) {

must be
itemLoop: for (var j = 0; j < device[0].group.length; j++) { //


text:
Q: "InvalidDataException: Form value count limit 1024 exceeded." model null when post more then 1000 values from view to controller in asp.net core I'm trying to sent bulk email to selected candidates based on roles. When I'm selected limited options then model pass properly, but once I select more then 1000 option from multiselect dropdown and post from the model passed null.
Very Strang, Is there any reason for that?
Email Template View model
public class EmailTemplateViewModel
{
    public EmailTemplateViewModel()
    {
        LstEmailTemplate = new List<EmailTemplateModel>();

        SendEmailModel = new SendEmailModel();
    }
    public List<EmailTemplateModel> LstEmailTemplate { get; set; }

    public Pager Pager { get; set; }
    public SendEmailModel SendEmailModel { get; set; }
}

View
    @model Practise.Models.EmailTemplateViewModel
@using (Html.BeginForm("SentBulkEMail", "EmailTemplate", FormMethod.Post, new { @class = "form-horizontal" }))
                {
                    @Html.HiddenFor(x => x.SendEmailModel.EmailTemplateId, new { id = "hdnEmailTemplateId" })

                        User Type

                            @Html.DropDownListFor(x => x.SendEmailModel.Roles, new SelectList(Roles, "Value", "Text"), new { id = "Roles", @class = "form-control select2", multiple = "multiple", @required = "required" })

                        Recipients

                            @Html.DropDownListFor(x => x.SendEmailModel.Recipient, new SelectList(ViewBag.Recipient as IEnumerable<SelectListItem>), "", new { id = "Recipients", multiple = "multiple", @required = "required", @class = "form-control" })

                        Subject

                            @Html.TextBoxFor(x => x.SendEmailModel.Subject, new { id = "subject", @class = "form-control", @required = "required" })

                        Message

                            @Html.TextAreaFor(x => x.SendEmailModel.Description, new { id = "hdndescription", @class = "form-control", @required = "required" })

                            <button class="btn btn-primary" type="submit">Send</button>
                            <button class="btn btn-danger" type="button" data-dismiss="modal">Close</button>

                }

Controller
[HttpPost]
        public async Task<IActionResult> SentBulkEMail(EmailTemplateViewModel emailTemplateViewModel)
        {
            CustomResponseModel response = new CustomResponseModel();
            response = await _emailTemplateService.SentBulkEmail(Request);
            if (response.IsSuccess)
            {
                TempData[Constant.Success] = response.Message;
            }
            else
            {
                TempData[Constant.Error] = response.Message;
            }
            return RedirectToAction("List");
        }

You can get better idea from below image:
1st I select only 4 option from multi select

Controller when select 4 options

2nd  select more then 1000

Controller when I select more than 1000 options

A: Finally I found an answer.
The default request value is limited up to 1024 .
For that we need to set the request limit using RequestFormLimits attribute like follows:
[HttpPost]
[RequestFormLimits(ValueCountLimit = Int32.MaxValue)]
public async Task<IActionResult> SentBulkEMail(SendEmailModel emailModel)
{
}

After adding this attribute with ValueCountLimit allow request value up to Int32.MaxValue or you can set as per your requirement.


text:
Q: How to move a Tag in SVN This question can be rephrased as:
How can I include a single change in the trunk of a specific file into an existing TAG.
A simple question, but one I was not able to resolve to satisfaction myself.
The concept comes from other SCM tools, where you just move a tag over the different revisions and "stick it" to the exact revision you need. Those other tools have the native understanding of what a Tag is, where SVN generalized everything as a copy-branch.
Below answers I have seen on other bulletin boards and posts on this same, and as such were already considered and rejected:

*

*This is not the proper use of SVN

*

*Actually, SVN was designed to be generic, and accomplish many use patterns

*This is a mission to find an answer. I understand the challenges, and the
possibility of never finding an answer. Maybe I will switch to a different tool.

*Why are you using SVN such our so, it is better to do this and that.

*

*There are many use patterns or SCM models that can be adopted. In my case
specifically:

*

*The Trunk represents ongoing development, and small patches are applied to it.

*Production is a single TAG

*the turn-around from development is very short and aggressive, and as such we cannot
work with several complete production releases. That means I can not every-time create
a new tag for every little sub-change deployed in production.

*So in short "Complete Packaged Production releases do not exist in my scenario".

*This is my Use case scenario I need.

Well, I wont be presumptuous, and I will read every single solution provided and reconsider as needed.

A: Tags and branches in Subversion are really just directories. The concept of what they are isn't embedded in Subversion, but your brain.
As others have stated, tags are snapshots of your repository at a certain point in time, and should not be changing. If you plan on changing a tag, it really should be a branch.
For example,

*

*I want a tag showing the approved changes: Make it a branch instead of a tag.

*I want to show what files have been used for the last build: Ditto.

*I want to show what code has been reviewed: Ditto.

But these aren't branches! you whine claim.
Very well, the suggested structure of a repository is just that: A suggestion. You could add another directory besides trunk, tags, and branches for these moveable tags:
$repo/trunk
$repo/branches
$repo/tags
$repo/moveable_tags

Now, you can put the tags you change under moveable_tags, and the tags that people use for releases, snapshots, etc. under tags.
I've modified the suggested repository layout before at one location where I worked. I wanted to delete obsolete branches and tags from the repository, but management and the developers objected.
I said that deleting these weren't deleting it from the repository. I could easily get them back if needed, but by removing them, I eliminate a lot of unnecessary clutter from these two directories. However, the developers didn't feel secure in this. Sure, I can find them, but can they?
Instead, I added an obsolete/tags and an obsolete/branches directories to the trunk, tags, and branches directory level. Instead of deleting obsolete tags and branches, I just moved them. tags and branches weren't cluttered, and the managers and developers felt better that they knew were to find these obsolete branches and tags if they ever needed them.

Let's say that you're not doing anything fancy with tags. You use tags as snapshots and anything you expect to be changed and updated is a branch. There are still times when a tag might need to be changed.
And, Subversion is better at handling this than most other version control systems. That's because tags contain the entire history of their creation and changes. In most other version control systems, the history of that tag is a second class citizen if it is even kept at all. You can see the tag. You can see what files and version are under that tag, but you can't see who created that tag and how it had been changed. Under Subversion, tags contain their entire history.
To make a change in a tag:

*

*Check out the tag.

*Make the change.

*Commit your change.

Or, even better, use svn cp, svn mv, or svn delete against the repository URL and not against a working directory. For example, I created a tag for release 2.0. Suddenly, we realized we forgot one very important change that's going out in this release. Instead of a checkout, you do this:
$ svn cp -r 23933 -m"This change in this file should have been included in the tag" \
    $repo/trunk/foo/src/foo.java $repo/tags/2.0/foo/src/foo.java

When you look at the history of this tag, you will now see.
 $svn log -v $repo/tags/2.0
 ------------------------------------------------------------------------
 r23945 | david | 2013-04-03 11:21:55 -0400 (Wed, 3 Apr 2013) | xxx lines
 Changed paths:
 M /tags/2.0/foo/src/foo.java (from /trunk/foo/src/foo.java:23933)

 This change in this file should have been included in the tag

 ------------------------------------------------------------------------
 r23932 | david | 2013-04-10 11:18:40 -0400 (Wed, 10 Apr 2013) | 1 line
 Changed paths:
 A /tags/2.0 (from /trunk:23921)

 Created release 2.0

I see that the tag was created a week ago from revision 23921 on trunk. Then I see that the file foo.java was updated a week later from revision 23933 on trunk.

A: Tags and branches do not differ in SVN. All the difference is in policies that teams follow for how to work with tags and branches.
So you can merge changes into a tag and commit a new revision the same way you would do it with a branch. It's understandable that usually you don't want to do that, in order to "tag" the exact versions of files that you used for a release. But if it is really required, you can make an exception from this rule once.
Alternatively, you can remove the tag, and then re-create it using the right revision(s).
A couple of links to the SVN book: "Tags", "Branch Maintenance"

ADDED: So, it sounds that such re-tagging is not a rare, untypical use case but rather a regular practice in your team. Seems with tags you do not just give a name to a particular snapshot of your files, but want that name to follow subsequent updates of the files, forgetting its previous place. Also it seems you find branches inconvenient for your workflow.
Well, I do not think there is a simple and clean way to achieve what you want with SVN. In my opinion, it's better to "embrace" branches and learn how to use them efficiently.

A: I have found 1 easy way to do this (I.e. move a tag for a file) using tortoise SVN.

*

*browse your repo by right clicking on your checked out project dir and selecting "Tortoise SVN->Repo-browser"

*Navigate to the file you want to change within your tags/ directory

*right click on the file and select "checkout".

*Select a temporary directory on your HD and hit ok.

*Overwrite this file with your updated version (using your local file exporer, not the SVN repo browser)

*right click on the file and select "SVN checkin".

Job Done.
To do the same thing using CVS is trivial, just go to the required directory and type:
  "cvs tag -F tagname filename"
SVN doesnt really have tags, which makes it painful to use (In my opinion).
Not sure why this has been down voted - it is how we solve the exact problem set in the question.

A: Your comment on @Alexey Kukanov's answer indicates to me that what you really want is a branch, not a tag.  A tag is historical record of a single, unchanging point in time.  A branch is a copy of the code that will undergo further changes as time goes on.  You're talking about the latter.  It's standard practice to create "bugfix" or "production" branches for each release that you're supporting, and either commit changes directly on the branch[1] or merge them from the trunk.
Tags, in this case, would be used to create "copies" of the branch to indicate "exactly this code was in production at this particular time".  So you can easily go back and compare against it if the need arises.
[1] ... and later merge them to the trunk as appropriate

A: I also need to do that sometime. What you do you check out your svn file from the tag, not the branch (so something like svn://blahblah/tags/mytag, not svn://blahblah/branches/mybranch), then you commit the changed file in there, and it will have the updated tag.


text:
Q: Python exception because of invalid environment setup? Disclaimer: .net developer trying to setup python environment.
I have .py files trying to call the following line:
from paramiko import SSHClient, SSHConfig

However I get error saying
ImportError: No module named paramiko

I believe this is because I have missed to install something? I start python command prompt and type
import paramiko without any problem.

Anyone familiar with this issue? (Using python 2.7.6)
Edit: Python command prompt recieves and understands the command "import paramiko..." but my cygwin terminal does not. I believe cygwin has invalid python install path.

A: If you are getting ImportError: No module named paramiko please install it. If you already installed, please check path of the module and check same path exists in PYTHONPATH environment variable.


text:
Q: How to add title attribute at CKEditor images Is there a way to add the title attibute to CKEditor images? I'm using v4.1.2 and CKEditor is removing it automatically each time it's added from the HTML source view. I haven't found anything about this!

A: You got to define config.extraAllowedContent = 'img[title]' if you want title attribute to be accepted into editor contents (see: official guide).

A: I have ultimate solution for this issue..
1) Open this file: ckeditor\plugins\image2\plugin.js
At the line number 343 (in my case) add below code
title: this.data.alt
just below "alt: this.data.alt," and enjoy..


text:
Q: Infinite Loop while using react hook I'm learning react for past few days and while using useEffect hook i'm getting infite loop over setting my state variable.
Can anyone tell me what's going on and how to overcome this
Here's my code
import React, { useState, useEffect } from "react";
import axios from "axios";

const TodoEntry = () => {

  const [todos, setTodos] = useState('');

  useEffect(() => {
    axios.get('http://localhost:5000/api/todos')
     .then(res => { setTodos(res.data); console.log(todos) })
     .catch(err => console.log(err))
  },[todos]);

  return (

Todo App

  );
};

export default TodoEntry;

A: Couple of problems in your code:

*

*Since getTodos function is a dependency of useEffect hook, every time state updates, new getTodos function is created which then triggers the useEffect hook.

*You don't need to chain then function when using async-await syntax. You can just await the result of axios.get(...).
To fix the first problem of infinite loop, use one of the following options:

*

*Wrap the getTodos function in useCallback hook. For details, see useCallback.
Since, getTodos function calls displayTodos, you will need to wrap it in useCallback hook and add displayTodos in the dependency array of useCallback hook that wraps getTodos function. In my opinion, it is better to just remove the displayTodos function and update the state inside getTodos function
const getTodos = useCallback(async () => {
   try {
      const res = await axios.get('http://localhost:5000/api/todos')
      setTodos(res.data);
   } catch(err) {
      console.log(err);
   }
}, [setTodos]);

Demo

*Put the code inside getTodos inside useEffect hook and remove the getTodos function.
useEffect(() => {
  axios.get("http://localhost:5000/api/todos")
   .then(res => setTodos(res.data))
   .catch(err => console.log(err));

}, [setTodos]);

Demo

A: This is because the dependency list for your useEffect call is a function. You probably meant to add the todos data itself.
  useEffect(() => {
    getTodos();
  },[todos]);


text:
Q: Asynchronicity within a loop I'm using jQuery's $.getJSON() API to retrieve data from a given URL for a set of utilities. I'd really like to find a way to reuse the code (it's all exactly the same) for each utility. Since the loop is executing without respect to the ajax call, I haven't been able to find a way to retain the looping value.
That description sucks, I know, so here'a a code snippet that defines it a little better:
var utility_types = [ 'Electricity', 'Gas', 'Water' ];

/** Retrieve known utility providers for the given zip code */
for( var i = 0; i < utility_types.length; i++ ) {
  var type = utility_types[i];

  $.getJSON( '/addresses/utilities/' + zip + '/' + type + '.json', null, function( data, status ) {
    alert( 'Processing ' + type );
  });
}

I need to find a way to pass the type value into the callback so I can apply the correct syntax. Without that, all 3 loops are executing against the "Water" utility. I know why it's not working, I'm just wondering whether there's a reasonable workaround.
Thanks.

A: Create a closure
var utility_types = [ 'Electricity', 'Gas', 'Water' ];

function getCallBack(type){
   return function(data,status){
     alert( 'Processing ' + type );
   }
}

/** Retrieve known utility providers for the given zip code */

for( var i = 0; i < utility_types.length; i++ ) {
  var type = utility_types[i];

  $.getJSON( '/addresses/utilities/' + zip + '/' + type + '.json', null, getCallBack(type));
}

A: The canonical way of doing this whilst still using an anonymous closure is to create a new anonymous closure which is invoked immediately and passed the loop variable which then returns the real callback.
This anonymous closure has its own scope which contains its own variables (including the passed parameter) which may override the outer loop's variables, e.g.:
..., success: (function(type) {
    return function() {
        alert(type);
    }
}(type))

The type in the parentheses at the outside is the loop variable.  The type in the function declaration is a parameter which is in scope of the new closure.  When alert is called it uses the one that's closest in scope, i.e. the parameter.
Of course, the parameter can have its own variable name, it doesn't have to be the same as the one in the outer scope!  If it were different then both would be available, but the outer scoped version would always have the same value.

A: you can assign the 'type' value to a member variable for each ajax request, and test it using the this keyword in the callback success function:
var utility_types = [ 'Electricity', 'Gas', 'Water' ];

/** Retrieve known utility providers for the given zip code */
for( var i = 0; i < utility_types.length; i++ ) {
  var type = utility_types[i];

  var jsonReq = $.getJSON( '/addresses/utilities/' + zip + '/' + type + '.json', null, function( data, status ) {
    alert( 'Processing ' + this.utilityType );
  });
  jsonReq.utilityType = type;
}


text:
Q: UISlider alpha issue I'm want to figure out such an issue:
I have a UIView dervied class in which there are several controls. Some of them must appear and disappear depending on selected mode. This is made by means of setting aplha value to respected component.
All controls adds procedurally through code in initWithFrame in normal way. All controls works as expected but UISlider! Setting its initial alpha to 0.0f in initWithFrame have no effect. This is especially strange because futher setting of its alpha in code works OK. This component already exists and NSLog displays it's address and setted alpha correctly. But real alpha is 1.0f!
If I replace UISlider to arbitrary other view its works properly. Why?
My guess - this is because of internal animation processes which is interfere alpha value upon creation.
The only workaround I use - to place slider on dummy view and set it's transparency.
Does anybody knows another solution?

A: uislider.hidden = YES;


text:
Q: Android Jetpack Navigation Component too slow. What's the problem? Today I was changing from ViewPager to Navigation Component (with Bottom Navigation View) on my Android project. The problem is that, when using ViewPager all is fast as lightning but using Navigation Component it's very laggy (2 seconds later after you pressed the view appears and specially with RecyclerView fragments).
Is there any way to pre-load fragments and improve transitions?
Thanks in advance !

MainActivity.java
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupWithNavController(binding.bottomBar, navController);

A: I too had the same issue. I believe its a bug in their latest dependency.
Changing to androidx.navigation:navigation-fragment-ktx:2.3.4 and androidx.navigation:navigation-ui-ktx:2.3.4 solved my issue.
Might also work for higher versions than 2.3.4. I haven't checked yet.


text:
Q: ht access issue, with examples My end goal is to have something like this.
127.0.0.1/site/search/search-term
Rather than,
127.0.0.1/site/search.php?term=
I have tried two pieces of code, first being.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ../search.php?term=$1

And i put this inside a folder called /search. The HTACCESS works perfectly but the css gets messed up for my website, it just shows everything as plain text without any styling.
Secondly i tried
RewriteEngine On
RewriteBase /search/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ../search.php?term=$1

And put that in 127.0.0.1/site/ root. But when i tried 127.0.0.1/site/search/searchterm I get a 404.
Can anyone see where i am going wrong? I am guessing the first option is the best one to work towards getting fixed as it is so close, i look through the source of the page i receive after using the vainty url and i think it might be something to do with how im linking the style sheet? It works if i put the full address in for the link (127.0.0.1/site/main.css) But then all it fails on all my jquery includes etc. Is it wise to just put the full address in when ever i want to use vanity urls?

A: First make sure you're using absolute paths in CSS, JS and images files. That means path to these resources should either start with a slash / or http://. If you don't already have it then please make necessary code changes. Once that is done use following .htaccess in $DOCUMENT_ROOT (not in $DOCUMENT_ROOT/site):
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^site/search/(.+)/?$ site/search.php?term=$1 [L,QSA,NC]

EDIT: As per your comments here is the code to make a URI in lowercase:
First add this line in  section OR at the end of your httpd.conf file:
RewriteMap lc int:tolower

Then have your rules like this:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^site/search/(.+)/?$ site/search.php?term=${lc:$1] [L,QSA,NC]


text:
Q: For MS Access SQL, want to use EXCEPT in Access for three columns in table1 to 1 column in table 2 I have 3 columns in table A. I am trying to design a query that will call out all the values (in the three columns) that do not apepar in the 1 column I have in table B. If it helps to make it more clear, table B is a list of currencies in ISO codes and table A is three columns of currencies being used, I am identifying all those values that are NOT using ISO codes to denote their currency.
Currently, I can't seem to get them all to match to the one column, so I made 2 more columns in table B so I can match them individually. My constraints are, I cannot change table A and I must do this in one query. What I got so far is below.
SELECT m.Currency1, i.ISO_Code, m.Currency2 , i.ISO_Code1, m.Currency3, i.ISO_Code2
FROM A AS m
LEFT JOIN B AS i
ON m.Currency=i.ISO_Code
AND m.Currency2=i.ISO_Code1
AND m.Currency3=i.ISO_Code2

WHERE i.ISO_Code is NULL
OR i.ISO_Code1 is NULL
OR i.ISO_Code2 is NULL;

A: I wouldn't bother making multiple columns in 'B'. I played with this in SQLFiddle and got it to work.
Something like this:
SELECT
m.Currency1, i.ISO_Code,
m.Currency2, j.ISO_Code AS ISO_Code1,
m.Currency3, k.ISO_Code AS ISO_Code2
FROM A AS m
LEFT JOIN B as i
ON m.Currency1 = i.ISO_Code
LEFT JOIN B as j
ON m.Currency2 = j.ISO_Code
LEFT JOIN B as k
ON m.Currency3 = k.ISO_Code
WHERE
i.ISO_Code IS NULL OR
j.ISO_Code IS NULL OR
k.ISO_Code IS NULL


text:
Q: Copy labels to multiple variables from different variables I am working with a df with many versions of the same variables, so they need similar, but different labels. For example, bev_1 is "water category" and bev_1_amt is "water ounces" and. T original variables have a label already, all new transformations do not. With hundreds of variables, I would like to assign any variable name containing text e.g. "bev_1" to be assigned the label from the original bev_1 variable.
library(dplyr)
library(labelled)

bev.df<- data.frame(
  bev_1=c(5, 3, 2, 5, 4),
  bev_2=c(6, 4, 4, 5, 5),
  bev_1_amt=c(2, 2, 3, 3, 2),
  bev_2_amt=c(3, 4, 5, 5, 4)) %>%
  set_variable_labels(bev_1 = "water", bev_2= "juice")

I've tried many versions of the below code and just can't get it to run. Any help appreciated.
bev.df %>%
  set_variable_labels(select(., contains("bev_1"))= var_label(select(., bev_1)))

I would like any variable with name containing the text "bev_1" to have the same label as the variable bev_1.


text:
Q: Trying to figure out this JavaScript bookmarklet I`m a JavaScript/programming newbie trying to figure out the new bookmarklet that's been released to help overcome the new NY Times paywall, available at this blog http://euri.ca/2011/03/21/get-around-new-york-times-20-article-limit/
It`s only the following 3 lines of JavaScript....
 //Prototype is already installed on NYTimes pages, so I'll use that:
    $('overlay').hide();
    $('gatewayCreative').hide();
    $(document.body).setStyle( { overflow:'scroll' } );

so I thought it would be a not overly complex way to learn about practical uses of JavaScript
When I click on the source code for the actual bookmarklet, it revealed this
NYTClean

The three lines of JavaScript above are located at 'http://toys.euri.ca/nyt.js'
My questions are
a) when he says that Prototype is already installed on NYTimes page, is he referring to the Prototype library, so his code is just altering what they did with the library?
b) in the source code for the bookmarklet, where he does document.getElementsByTagName('head')[0].appendChild(s);})();" does the document refer to the NY Times page that the reader will be on? and 'head' refer to an Element in the NYTimes home page, to which he is appending the child s?
c) is the source code for the bookmarklet wrapped in the link  so that appendChild(s) only happens when you click on the link/bookmarklet. Is a bookmark essentially a link which runs code?
d) do you know of a resource that explains how to make the actual bookmarklet which can be dragged from a webpage to the bookmark bar? That drag-to-the-bookmark bar feature is obviously separate from the code it contains, so do you know where I can learn it if I wanted to make my own bookmark to experiment with JavaScript.

A: a) Yes, he's referring to the Prototype javascript library.
b&c) The way bookmarklets work is by running javascript in the context of a given website by using the "javascript:" protocol. You can run anything you want this way (try typing "javascript:alert('the title is: ' + document.title);" in your address bar and hitting enter. You should get an alert showing you the title of the page you're on. You might consider reading up a bit on how they work on wikipedia.
d) The drag-bookmarklet-to-bar functionality that bookmarklets depend on is actually built in to your web browser. To make an installable bookmarklet that will work on any modern browser, all you have to do is have:
Drag to bookmark bar to install!


text:
Q: Volley Request not giving any reponse I am new to Android. I am figuring out how to make network calls. I am trying to send Headers along with JSON data. I tried debugging the code but it's not going to onResponse(). Can someone tell me what am i doing wrong .
Below is my code.
 String url = "https://api.....";
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("image", "https://i.imgur.com/5KdM.jpg");
        jsonObject.put("subject_id", "Elixabeth");
        jsonObject.put("gallery_name", "MyGallery");
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                if (response != null){

                }
                // do something...
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // do something...
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                final Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                headers.put("app_id", "");
                headers.put("app_key", "");
                headers.put("Content-Length", "124");

                return headers;
            }
        };
        requestQueue.add(jsonObjectRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    }

I tried the same in Postman with same data and I am getting response.

A: Put the log inside
onResponse(JSONObject response) method Log.d("Response", response.toString()); and in
onErrorResponse(VolleyError error) method Log.e("Error", error.getMessage());.
Then check the logcat,you can find what goes wrong...


text:
Q: Adding Class files to Google App Engine Wave Bot in Java using Eclipse Yeah quite a specific question. I'm making a bot for Google Wave and I'm a bit confused.
I have some Java class files of a separate package I want to implement. I put them in the lib directory but they're not found by Wave when its uploaded.
Eclipse compiles them fine, as it has the directory, but I guess it doesn't upload it to appspot.

A: Is Wave contacting the server at all? If so, the problem isn't Wave-specific, it's AppEngine-specific - so you don't need to worry much about the Wave documentation, just AppEngine.
How have you packaged the class files? Are they just "loose" or have you bundled them into a jar file?
What error are you getting, exactly?
Have you tried following the Wave tutorial to build the Parroty application? Did that work? If so, that's a good starting point for adding your own classes.


text:
Q: JQUERY - Methods not working after for loop Background
I am learning JQUERY/JAVASCRIPT. I have come across a bizarre issue if someone could explain why it is happening. Essentially I have a simple 4 item list. Code is meant to do the following:

*

*Using .remove() remove Item Four

*Using JS For loop go throughlist change the content matching the condition (content of li#three).

*Using .remove(), li#one is removed

*Using .text() change li#three text content to Change3

Problem
My problem is steps 1 and 2 work. But the methods after the loop ie .remove() and text() do not work. Also if I put these methods infront of the loop it works.
Can anyone please tell me what am I doing wrong and possible work-arounds? Thank you in advance.
PS I am using Dreamweaver as my editor.
Ka Tech
Code
<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>

 List

Item One

Item Two

Item Three

Item Four

A: It is because you have a script error Uncaught TypeError: Cannot read property 'textContent' of undefined. That is because var $length = $('li').length will give you 3, and your for loop iterate from i=0 to i<=3 but when i==3 there is no li element at index 3 so $('li')[i] will return undefined causing the error
$(document).ready(function () {
    var $length = $('li').length;
    for (var i = 0; i < $length; i++) {
        var $item = $('li')[i].textContent;
        if ($item === "Item Two") {
            $('li')[i].textContent = "Change2";
        }
    }
    $('li#one').remove();
    $('li#three').text('Change3');

});

Another way

$(document).ready(function () {
    $('li').each(function () {
        if ($(this).text() === "Item Two") {
            $(this).text('Change2')
        }
    })

    $('#one').remove();
    $('#three').text('Change3');
});

 List

Item One

Item Two

Item Three

A: Try this:
Demo
var $length = $('li').length;
for (var i = 0; i <= $length; i++) {
    var $item = $('li').eq(i).text();
    if ($item === "Item Two") {
        $('li').eq(i).text("Change2");
    }
}
$('#one').remove();
$('#three').text('Change3');


text:
Q: Javascript date validation for PDF-form I've got an PDF-form with required fields.
One field is "Valid from" the other "Date of expiry".
Todays date or earlier must be entered into "Valid from".
I'm new into coding with Javascript. I'm using Adobe Acrobat for creating contracts with required fields.

A: I would recommend the JavaScript guide published by Adobe.
It contains examples and detailed instructions on what you can and can't include in a pdf (with regards to JavaScript).
http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/acro7jsguide.pdf
If you are going to do this for a lot of documents, please consider using iText.
I can certainly imagine a corporate workflow where you want to generate these kinds of forms automatically and provide all of them with the required validation. In which case doing it by hand is going to be a bottleneck.
For more information about how to do this with iText, have a look at
http://developers.itextpdf.com/examples/itext-action-second-edition/chapter-7


text:
Q: Make  invisble if there no content I am currently redisigning a page - making it so JS handles the upload of the content from a txt file and CSS formats the layout of divs and HTML contains the divs. What i am trying to do is hide the DIVs that DO NOT have any content in it - currently if tehre is no content it will still display the div as a long thin line. I've tried several suggestion, however having trouble of making it work properly. Have tried 'empty cell' option in CSS, but that ruins the layout for some reason.
Here is my HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>BROADCAST</title>
    <link rel="stylesheet" href="BCdata/WebStyles.css">

Here is my CSS
#CurrentDate
{
position: absolute;
top:15px;
left: 210px;
width:700px;
text-align: center;
z-index: 8;
color:white;
font-family:Arial;
font-size:35px;
text-transform: capitalize;
}

.main
{
background-color: #FFFFFF;
background-image: url(backbox.gif);
color: #000000;
text-align: center;
position: relative;
overflow: auto;
margin-top: 0px;
margin-left: auto;
margin-right: auto;
top: 10px;
}

.main #content_divs
{
position: relative;
text-align: left;
z-index: 1;
width: 960px;
margin: 0 auto;
border-style : solid;
border-width: 3px;
border-color: white;
overflow: hidden;
}

h1
{
font-family: Arial;
    font-size: 20px;
font-weight: bold;
position: relative;
text-transform: capitalize;
font-weight: bold;
z-index: 5;
}

h2
{
    font-family: Arial;
    font-size: 13px;
font-weight: bold;
position: relative;
z-index: 5;
}

p
{
    font-family: Arial;
    font-size: 13px;
position: relative;
z-index: 5;
margin-left: 20px;
margin-right: 20px;
}

#buttons_div
{
position: relative;
}

#Image35
{
position:relative;
border: 0px #000000 solid;
width: 960px;
height: 96px;
z-index: 2;
}

#Image2
{
border: 0px #000000 solid;
position: relative;
left:30px;
width: 90px;
height: 34px;
z-index: 3;
}

#Image3
{
border: 0px #000000 solid;
position: relative;
left:30px;
width: 86px;
height: 34px;
z-index: 4;
}

#Image4
{
border: 0px #000000 solid;
position: relative;
left:-30px;
width: 236px;
height: 34px; z-index: 5;
}

#Image5
{
border: 0px #000000 solid;
position: relative;
left:-30px;
width: 236px;
height: 34px;
z-index: 6;
}

#Image6
{
border: 0px #000000 solid;
position: relative;
left:-30px;
width: 236px;
height: 34px;
z-index: 7;
}

This is JS (content handler)
$(function()
{
    $("#div1").load("BCdata/Content061114.txt .Div1 #p1");
});

$(function()
{
    $("#div2").load("BCdata/Content061114.txt .Div2 #p1");

});

$(function()
{
    $("#div3").load("BCdata/Content061114.txt .Div3 #p1");

});

$(function()
{
    $("#CurrentDate").load("BCdata/Content061114.txt #CurrentDate");

});

onload=function()
{
    var content_divs=document.getElementById('Div2');
    if(!div2.hasChildNodes()){content_divs.style.display='none'}
}

And this is a TEXT file where content is located
thursday 6th november 2014, wk 40

Congratulations to 66!

PDFs of 'Record Weeks' are now available on the Intranet.

Heading 1

Content is here

Heading 2

Content is here

Click the link on the right to view PDFs

Poster

Poster Content

heading Content is here

Content is ehre blabla

Any help is much apreciated - sorry if it seems that i am asking to fix the problem for me, but i am new to this and very keen to learn. Been stuck on this for a while now

A: You could try :empty pseudo-class.

div:empty {
  display: none;
}

div with content

Reference: MDN

A: Something like this would work.
elementList = document.querySelectorAll('div');
for(var i = 0; i < elementList.length; i++)
{
var element = elementList[i];
(element.children === 0) ? element.style.display = "none": element.style.display = "block";
}

What this does it get all Div elements, puts them in an array, then checks each one, if it does not have a child it sets display to none, if it does it sets display to block.
EDIT
If you don't want it to mess with divs with children atall, just change if statement to:
 (element.children === 0) ? element.style.display = "none": "";

We use .children because this only returns Element objects (aka HTML tagged stuff) and not 'absolutely' every child.

A: demo - http://jsfiddle.net/y7mgmm2u/
thanks to @emmanuel

*:empty {
    display:none;
}

test

test


text:
Q: Trouble with anonymous functions in matlab I am having trouble with printing out h_a_b. I am able to get functions f and g but not this one. I need to use h_a_b function so i can do h(f(x),g(x)) and calculate the sqrt of h(a,b). see equations
I am always getting this error
Undefined function 'h_a_b' for input arguments of type 'function_handle'.

I am suppose to write a program that create 3 anonymous functions representing the function
Equations needed
f(x) = 10*cos x ,
g(x) = 5*sin * x, and
h(a,b) = \sqrt(a^2 + b^2).
Here is my code
f = @ (x) 5*sin(x);

g = @ (x) 10*cos(x);

h_a_b = @ (a,b) sqrt(a.^2 + b.^2);

then I plot it with this function that was given to me.
function plotfunc(fun,points)
%PLOTFUNC Plots a function between the specified points.
% Function PLOTFUNC accepts a function handle, and
% plots the function at the points specified.
% Define variables:
% fun -- Function handle
% msg -- Error message
%

msg = nargchk(2,2,nargin);
error(msg);
% Get function name
fname = func2str(fun);
% Plot the data and label the plot
plot(points,fun(points));
title(['\bfPlot of ' fname '(x) vs x']);
xlabel('\bfx');
ylabel(['\bf' fname '(x)']);
grid on;

end

A: Because your function (h_a_b) takes a vector as input and gives scalar as output it represents a surface, thus plot cannot be used to visualize it (that is only for 2D, scalar-scalar plots).
Are you looking for something like this?:
f       = @ (x) 5*sin(x);
g       = @ (x) 10*cos(x);
h_a_b   = @ (a,b) sqrt(a.^2 + b.^2);

z       = @(a,b) sqrt(h_a_b(f(a),g(b)));

[A, B]  = meshgrid(0:0.1:8, 0:0.1:9);
Z       = z(A,B);

surfc(A,B,Z)
xlabel('a')
ylabel('b')
figure
contourf(A,B,Z)
xlabel('a')
ylabel('b')

Second option, considering z as scalar-scalar function and using your plotfunc function:
f       = @ (x) 5*sin(x);
g       = @ (x) 10*cos(x);
h_a_b   = @ (a,b) sqrt(a.^2 + b.^2);

z       = @(x) sqrt(h_a_b(f(x),g(x)));

points = 0:0.1:8;
plotfunc(z,points)

Which is one slice of the above surface.


text:
Q: Homeomorphic open sets have homeomorphic open balls If $U$ and $V$ are open sets in $R^n$, how to prove that there are two open balls $B_U$ and $B_V$ in $U$ and $V$ such that these two open balls are homeomorphic?

A: Any two open balls in $\mathbb{R}^n$ are homeomorphic (to the whole space $\mathbb{R}^n$ and thus to each other too). And any non-empty open set contains an open ball.
$B(0,1)$ is homeomorphic to $\mathbb{R}^n$ using the homeomorphism $f(x) = \frac{x}{1+\|x\|}: \mathbb{R}^n \to B(0,1)$. The rest is scaling and translating.


text:
Q: Induction on two variables? I am trying to prove that:
$(1+x)^n \ge 1 + nx$ for every $n \in \mathbb N^+ $ and $\ x \in (-1, \infty)$
I have never seen induction on more that one variable.
Since $(-1, \infty)$ has no least element can I even induct on this? Would strong induction be preferable?
Here is my proof for all $n \in \mathbb N^+$ by inducting on $n$.

Proof:
Suppose $P(n) : (1+x)^n \geq 1 + nx$.
$P(1) = 1+x \ge 1+x$

$P(n) \Rightarrow p(n+1)$
$(1+x)^n \ge (1+nx)$
$(1+x) (1+x)^n \ge (1+nx)(1+x)$
$(1+x)^{n+1} \ge 1+ x + nx + nx^2 $
Since $nx^2 \ge 0 $ for all $n,x$ then:
$1+ x + nx + nx^2 \ge 1 +xn + x$ .
Therefore:
$(1+x)^{n+1}\ge 1 +xn + x$
$(1+x)^{n+1}\ge 1 + x (n+1) $
Therefore:
$(1+x)^n \ge (1+nx) \Rightarrow (1+x)^{n+1} \ge (1+(n+1)x)$

Is this correct? Can anyone provide any guidance on how to approach induction on the interval? Is it even possible?
Cheers Guys!

A: There is no "double induction". You just do the same induction proof for all $x$. All you are using in your proof is that $x\geq-1$, so any $x\in[-,1\infty)$ would work.


text:
Q: Adding characters to the beginning and end of a line starting with a specific string I have quite a few html files where I need to comment out a specific line of JavaScript:
<script src="/common/javascript/jquery/jquery.tools-1.2.4.min.js" type="text/javascript"></script>

What I would like to do via command line, is search .htm files in the directory for the string: "/common/javascript/jquery/jquery.tools-1.2.4.min.js" and add <!-- to the beginning of the respective line containing the string, and
--> to the end of the line.
Some files include type= and some do not, which is why I'd like to search using the src value and add to the beginning and end of line.
Thanks for the help. I appreciate it.

A: This will output a modified file if you replace "that whole line" with that entire js line you want to comment out.
sed 's/\(that whole line\)/<<!--\1-->/' file.htm
Now just iterate that over all the files in the dir
for f in *htm; do
   sed 's/\(that whole line\)/<<!--\1-->/' $f > $f.new
done
I'll let you figure out how to handle moving them back to the right filenames. (Maybe a new dir? Maybe a mv command? Whatever's best in your situation.)

A: Is this what you want?
for f in *.htm*; do
  mv "$f" "$f.tmp"
  sed 's#^\(.*common/javascript/jquery/jquery.tools-1.2.4.min.js.*\)#<!-- \1 -->#' "$f.tmp" > "$f"
  rm "$f.tmp" ;
done


text:
Q: Expected Value of a Ratio of Log-Normal Variables Suppose $a$ and $b$ are constants (with $a\neq b$) and $X$ is a log-normal random variable, i.e. $\ln(X) \sim \mathcal N(\mu,\sigma^2)$. Suppose that
$$ \mathbb E \left[ \frac{X-a}{X-b} \right]=0.$$
Is it possible to solve for $\mu$ as an explicit function of $a$, $b$ and $\sigma^2$?

A: I think that you'd need to restrict the potential values of $b$ such that $b \le 0$ as otherwise the expectation doesn't exist.
And I'm not convinced that there is a closed-form solution other than for $b=0$.  Here is some Mathematica code to find $\mu$ in terms of $a$ and $\sigma^2$ when $b=0$:
b = 0
expectation = Integrate[E^(-((-\[Mu] + Log[x])^2/(2 \[Sigma]^2)))/(
   Sqrt[2 \[Pi]] x \[Sigma]) (x - a)/(x - b), {x, 0, \[Infinity]},
  Assumptions -> {a \[Element] Reals, \[Sigma] > 0, \[Mu] \[Element]
     Reals}]

$$1-a e^{\frac{\sigma ^2}{2}-\mu }$$
This means that
$$\mu=\log (a)+\frac{\sigma ^2}{2}$$
where $a>0$.


text:
Q: Solve $\log_{4}3x+1,+\log_{3}16x+1=\log_{2}12x+4$ Here is a basic logarithmic problem that I am struggling to solve:
$\log_{4}(3x+1)+\log_{3}(16x+1)=\log_{2}(12x+4)$
Here is my step:
$\log_{4}(3x+1)+\log_{4}(\frac{16x+1}{3})=\log_{2}(12x+4)$
Since the bases are the same now, we can multiply the arguments.
$\log_{4}(3x+1)*(\frac{16x+1}{3})=\log_{2}(12x+4)$
$\log_{4}\frac{48x^2+19x+1}{3}=\log_{2}(12x+4)$
The next thing to do is to change the base of 2 to base 4 on the right side.
Therefore,
$\log_{4}\frac{48x^2+19x+1}{3}=\log_{4}\frac{12x+4}{\frac{1}{2}}$
The right side can be simplified further, so
$\log_{4}\frac{48x^2+19x+1}{3}=\log_{4}24x+8$
Since the bases are the same on both sides, the arguments are also the same.
$\frac{48x^2+19x+1}{3}=24x+8$
$48x^2+19x+1=72x+24$
$48x^2-53x-23=0$
Using the quadratic formula, I get
$x=\frac{-(-53)\pm\sqrt{(-53)^2-4*48*-23}}{2*48}$
$x=\frac{53\pm\sqrt{2809+4116}}{96}$
$x=\frac{53\pm\sqrt{7225}}{96}$
$x=\frac{53\pm85}{96}$
$x=\frac{23}{16}$
or
$x=\frac{-1}{3}$
Since log argument cannot be negative, the second solution will not work. But when I checked the solution, $x=5$, which is not the answer that I have. A seemingly easy problem is driving me crazy. Can anyone point out what I'm doing wrong?

A: The issue with your solution, as already noted in the comments, is when you converted $$\log_3(16x+1)$$ to $$\log_4\left(\frac{16x+1}3\right)$$
The log base rule states that:
$$\log_ba=\frac{\log_da}{\log_db}$$
In this case, $$\log_3(16x+1)$$
would convert to $$\frac{\log_4(16x+1)}{\log_43}$$
which is not equal to $$\log_4\left(\frac{16x+1}3\right)$$
Take, for example, $$\frac{\log_4{16}}{\log_44}=\frac21=2$$
But,
$$\log_4\left(\frac{16}4\right)=\log_44=1$$
Which is obviously not the same as $2$.


text:
Q: Paging in Classic ASP I'm having some trouble with my asp paging. It's able to show the 6 records on each page. However, when i move on to the second page, it's showing the same 6 records on every different page.
Below is my code. Any suggestions?
 Dim iPageSize,iPageCount , iPageCurrent , strOrderBy,strSQL,iRecordsShown,I
    iPageSize = 6
    set registerRS=server.CreateObject("ADODB.recordset")
    registerRS.PageSize = iPageSize
    ' Retrieve page to show or default to 1
    If Request.QueryString("page") = "" Then
        iPageCurrent = 1
    Else
        iPageCurrent = CInt(Request.QueryString("page"))
    End If
    qry="SELECT * FROM "dbo.CustomerOrders;"

    registerRS.CacheSize = iPageSize
    registerRS.open qry,ObjConn,3
    iPageCount = registerRS.PageCount
    If iPageCurrent > iPageCount Then iPageCurrent = iPageCount
    If iPageCurrent < 1 Then iPageCurrent = 1
    If iPageCount = 0 Then
        Response.Write "No records found!"
    Else
        registerRS.AbsolutePage = iPageCurrent
    end if
    %>

        Page <%= iPageCurrent %>
        of <%= iPageCount %>

    <%
    x=registerRS.recordcount
    if registerRS.recordcount > 0 Then
    registerRS.movefirst
    End If
        Do While iRecordsShown < iPageSize And Not registerRS.EOF
                counter=counter+1
                if counter=41 then
                    counter=0
                    counter=counter+1
                end if
                r = r + 1
                If r = 1 then
                    Response.write "
"
                End if
                %>

                        <%=registerRS.Fields("Address")%>
>

        <%
            If r = 2 then
            Response.write "
"
            End if
            If r = 3 then r = 1
            ' Increment the number of records we've shown
                iRecordsShown = iRecordsShown + 1
            registerRS.movenext
            loop
        %>

<%
    If iPageCurrent > 1 Then
%>
    <a href="add.asp?page=<%= iPageCurrent - 1 %>&SchoolId=<%=registerRS.Fields("Add")%>">[<< Prev]
<%
    End If
    ' You can also show page numbers:
        For I = 1 To iPageCount
        If I = iPageCurrent Then
%>
<%= I %>
<%Else%>
    <a href="add.asp?page=<%= I %>&SchoolId=<%=registerRS.Fields("Add")%>"><%= I %>
<%
    End If
    Next 'I
    If iPageCurrent < iPageCount Then
%>
    <a href="add.asp?page=<%= iPageCurrent + 1 %>&SchoolId=<%=registerRS.Fields("Add")%>">[Next >>]
<%
    registerRS.close
    set registerRS=nothing
    End If
    end sub
%>

A: Do a view source on the web page and verify that this line of code:
<a href="add.asp?page=<%= iPageCurrent + 1 %>&SchoolId=<%=registerRS.Fields("Add")%>">[Next >>]

is producing the correct result.  If not then you will need to backtrack to find out where the correct page reference is not being generated.
Compare your code to this example for possible error sources.
http://www.asp101.com/samples/viewasp.asp?file=db_paging.asp
I did some testing and I see a couple of things that may be causing problems.
1] You need to initialize iRecordsShown = 0 before the Do-Loop.
2] You are also trying to retrieve database values into you links after the loop.  This won't likely work because the loop has already reached the end of records by that time.  You'll need to capture the database values before the end of loop is reached.
Otherwise it worked for me.

A:
The following condition block moves cursor to the first record if the number of records greater than zero (should be already). And then loop starts at first record without affecting the page number. This is not sensible, remove that block.
if registerRS.recordcount > 0 Then
registerRS.movefirst
End If


text:
Q: LINQ Select from two Collections with same length var listA = new List<string> {"One", "Two", "Three"};
var listB = new List<int> {1, 2, 3};
var listC = new List<Tuple<string, int>>();

Here I've got two Lists with the same length. Is there a way to fill third listC with LINQ?
"One", 1
"Two", 2
"Three", 3

A: I think you are looking the Zip extension method:
var listA = new List<string> { "One", "Two", "Three" };
var listB = new List<int> { 1, 2, 3 };
var listC = listA.Zip(listB, (s, i) => new Tuple<string, int>(s, i)).ToList();


text:
Q: Android Intent BroadcastReceiver Example I am using a Zebra Android Scan-Gun and need to capture the hard-keyboard (not soft) keystrokes for P1, P2, F1, F2, etc... keys.  Since Maui doesn't have events for KeyUp/KeyDown/KeyPressed there is nothing to inform me of a special keys being pressed.  Not to mention I also have to put an Entry field on screens where there are only buttons because you can't catch a TextChanged event without an Entry.
My current solution involves Zebra StageNow to remap the P1 key to the "+" key and then strip it out of the Entry/TextBox (which is not a very elegant solution)
What I'm trying now is using the Windows app Zebra StageNow in Admin mode to remap the F11 key to send an Intent, OnKeyUp, Broadcast as seen in this screenshot.

Then I generate the bar-codes to program the scan-gun.
In the Android Scan-gun I then run StageNow and scan the bar-codes which programs the F11 key.
Then within my android app I added a class in the Platforms\Android folder called SpecialKeypress.cs
namespace myapp.Platforms.Android
{

    [BroadcastReceiver(Enabled = true, Exported = true)]
    [IntentFilter(new[] { "com.mycompany.myapp.F11" })]

    public class SpecialKeypress : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            var value = intent.GetStringExtra("Key"); // <-- I set a breakpoint here
            throw new NotImplementedException();
        }
    }
}

Then I added the following to my AndroidManifest.xml
    <application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true">

    <activity android:exported="true" android:name="com.mycompany.myapp.F11" >
      <intent-filter>
        <action android:name="com.mycompany.myapp.F11" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
      </intent-filter>
    </activity>

  </application>

I debug the app on the device and press F11 but alas my breakpoint is not hit in the OnReceive function.
I expect I'm missing something fundamental but I tried to keep it as simple as possible for this example.  Also, there are no good examples of how to do this with Maui on the internet (yet).

A: You may need to register a receiver in your AndroidManifest.xml, and put some intent filters that define what type of messages this receiver will get.
For example:
<receiver android:name=".SpecialKeypress">
<intent-filter>
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>


text:
Q: How do I set up a Java Environment Variable in a Spring Boot / Gradle / IntelliJ Environment? I'm trying to set up a configuration on my development environment to load DATABASE_URL that will also work on Heroku, with Heroku's DATABASE_URL. Unfortunately, non of the techniques I'm trying to create local environment variables seem to work in my Gradle/Boot/IntelliJ environment. Here is what I tried:

*

*Adding a export DATABASE_URL=jdbc:postgresql... to /etc/environment

*Adding -DDATABASEURL=jdbc:postgresql... to my gradle task VM options (with bootRun.systemProperties = System.properties)

*My make shift answer below, that I really don't like.

A: Firstly, Spring can resolve environment variables automatically and, secondly, will resolve variables according to the order defined here (which is a Spring Boot doc page however the same should hold true for non Boot projects):
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
Setting the variables as an environemt vars in Heroku will then override the version in the properties file without any further coding required:
    //these properties will be resolved automatically from Heroku env vars if present
    //otherwise will be resolved from properties file bundled in the WAR
    @Value("${database.url}")
    String databaseUrl;

    @Value("${database.user}")
    String databaseUser;

    @Value("${database.password}")
    String databasePassword;

    @Bean
    public BasicDataSource dataSource() throws URISyntaxException {

        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setUrl(databaseUrl);
        basicDataSource.setUsername(databaseUser);
        basicDataSource.setPassword(databasePassword);

        return basicDataSource;
    }
}

Add the vars from your local properties file that you wish to override to your app's Heroku settings by some means:

A:
I'm answering my own question with the best answer I have, but really
  hoping for a better one to accept!

I have a different properties file for each of my environments. In development.properties I added
localDatabaseUrl=postgres://postgres:postgres@127.0.0.1:5432/Nitro

And if I didn't find a DATABASE_URL environment variable, then I just read that one from the properties file:
@Configuration
public class DatabaseConfig {

    @Value("${localDatabaseUrl}")
    String localDatabaseUrl;

    private static final Logger log = LoggerFactory.getLogger(DatabaseConfig.class);

    @Bean
    public BasicDataSource dataSource() throws URISyntaxException {

        URI dbUri;
        try {
            dbUri = new URI(System.getenv("DATABASE_URL"));
            log.info("Connecting via DATABASE_URL environment variable");
        } catch (NullPointerException ex) {
            dbUri = new URI(localDatabaseUrl);
            log.info("Connecting via localDatabaseUrl properties key/value ***");
        }

        String username = dbUri.getUserInfo().split(":")[0];
        String password = dbUri.getUserInfo().split(":")[1];
        String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();

        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setUrl(dbUrl);
        basicDataSource.setUsername(username);
        basicDataSource.setPassword(password);

        return basicDataSource;
    }

}

A: First off, you might prefer using JDBC_DATABASE_URL as described in Heroku DevCenter.
That said, either variable is fine. I also think fallback logic is fine too. But I would probably do it like this:
if (null == System.getenv("JDBC_DATABASE_URL")) {
  dbUri = new URI(System.getenv("JDBC_DATABASE_URL"));
} else {
  dbUri = new URI(localDatabaseUrl);
}

Another approach is to use a .env file and the heroku local command. Your .env file would contain:
JDBC_DATABASE_URL=postgres://...

The heroku local command will use the command in your Procfile to run your app. But this doesn't help when using ./gradlew bootRun and other such tasks.

A: You can actually pretty easily setup Heroku system variables that are "visible" by Spring using this command:
heroku config:set database.url=myDatabaseUrl -a myHerokuApp


text:
Q: devexpress aspxListBox in detailsView validation Is it possible to validate in insert or edit mode in detailsView AspxListBox control so that it has at least one value selected ?
code below doesnt work:
<requiredfieldvalidator ID="lbValidator" runat="server" ControlToValidate="lbMyListBox">
                    </requiredfieldvalidator>

thanks for any help,
bye

A: try this:
<dxe:ASPxListBox ID="liListBox" runat="server">
 <ValidationSettings CausesValidation="true" ErrorDisplayMode="Text">
  <RequiredField IsRequired="true" ErrorText="Required" />
 </ValidationSettings>
</dxe:ASPxListBox>