text:
Q: How to split the content of one column into two columns of csv in Ruby? I got an object of CSV, the content is like:
full_name  | phone_number  |
Mike Smith | (123)-456-7890|
Tony Davis | (213)-564-7890|

And I would like to split the column of 'full_name' into two columns, which represents 'first_name' and 'last_name':
first_name | last_name | phone_number  |
Mike       | Smith     | (123)-456-7890|
Tony       | Davis     | (213)-564-7890|

I didn't find a command to do it, how can I split it? Thank you very much!
The code for this part is:
def to_csv(options = {})
  CSV.generate(options) do |csv|
    columns = %w[ full_name phone_number ]

    csv << columns
    each do |books|
      csv << columns.map { |column| books.public_send(column) }
                    .map { |column| ActionController::Base.helpers.strip_tags(column.to_s) }
    end
  end
end

And this method is called by:
send_data(books.to_csv(col_sep: ','),filename: 'booksAuthorsInfo.csv',type: 'application/csv')

The class type of 'books' is ActiveRecord_AssociationRelation, and I don't know how to split that full_name column into two columns, it looks like the String.split is not helpful.

A: So far the question doesn't make enough sense so I expect it'll be closed eventually. Here's some information about how to split the fields so that, maybe, we can get to the real root of the problem.
Meditate on this:
ary = <<EOT
full_name  | phone_number  |
Mike Smith | (123)-456-7890|
Tony Davis | (213)-564-7890|
EOT

PIPE_DELIMITER = /\s*\|\s*/

munged_data = ary.lines[1..-1].map { |l|
  full_name, phone_number = l.split(PIPE_DELIMITER)  # => ["Mike Smith", "(123)-456-7890"], ["Tony Davis", "(213)-564-7890"]
  first_name, last_name = full_name.split # => ["Mike", "Smith"],                ["Tony", "Davis"]
  [first_name, last_name, phone_number]
}
# => [["Mike", "Smith", "(123)-456-7890"], ["Tony", "Davis", "(213)-564-7890"]]

At this point it's possible to generate some usable CSV data:
require 'csv'
CSV.open("/dev/stdout", "wb") do |csv|
  csv << %w[first_name last_name phone_number]
  munged_data.each do |row|
    csv << row
  end
end

Which results in:
# >> first_name,last_name,phone_number
# >> Mike,Smith,(123)-456-7890
# >> Tony,Davis,(213)-564-7890

Note the use of a regular expression as a parameter to split; This tells split to clean up the resulting output a bit by only splitting on zero-or-more whitespace delimited by |:
PIPE_DELIMITER = /\s*\|\s*/

full_name, phone_number = l.split('|')             # => ["Mike Smith ", " (123)-456-7890", "\n"], ["Tony Davis ", " (213)-564-7890", "\n"]
full_name, phone_number = l.split(PIPE_DELIMITER)  # => ["Mike Smith", "(123)-456-7890"],         ["Tony Davis", "(213)-564-7890"]

At that point it is easy to split the names:
first_name, last_name = full_name.split # => ["Mike", "Smith"],                        ["Tony", "Davis"]


text:
Q: Force Google Vision API to detect dates / numbers I'm trying to detect handwritten dates using the Google Vision API. Do you know if it is possible to force it to detect dates (DD/MM/YYYY), or at least numbers only to increase reliablity?
The function I use, takes an Image as np.array as input:
def detect_handwritten_text(img):
"""Recognizes characters using the Google Cloud Vision API.
Args:
    img(np.array) = The Image on which to apply the OCR.

Returns:
    The recognized content of img as string.
"""

from google.cloud import vision_v1p3beta1 as vision
client = vision.ImageAnnotatorClient()

# Transform np.array image format into vision api readable byte format
sucess, encoded_image = cv.imencode('.png', img)
content = encoded_image.tobytes()

# Configure client to detect handwriting and load picture
image = vision.types.Image(content=content)
image_context = vision.types.ImageContext(language_hints=['en-t-i0-handwrit'])

response = client.document_text_detection(image=image, image_context=image_context)
return response.full_text_annotation.text

A: After ImageAnnotatorClient.DetectDocumentText(your image), you could iterate over Blocks and words inside each block, and try to match a regular expression over each word to find dates and numbers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Searching for duplicate rows in MYSQL I'm currently running this SQL statement trying to find duplicate rows in my table.
SELECT *, COUNT(*) FROM `wp_posts` group by(post_content) having COUNT(*) > 1

However it is bring back every record in this table.
Can someone help?


text:
Q: How can I prevent Gitlab CI multiple yml includes from overriding a stage's jobs? In my Gitlab project, I'm including multiple .yml files. One of them is remote and the other is a template provided by Gitlab for Code Quality.
The .yml configuration is written like so:
include:
  - template: Code-Quality.gitlab-ci.yml
  - remote: 'https://raw.githubusercontent.com/checkmarx-ltd/cx-flow/develop/templates/gitlab/v3/Checkmarx.gitlab-ci.yml'

Both of these templates are accessible. The first is located here, and the second Checkmarx one is here.
Both of these .yml configs define jobs that run in the test pipeline stage.
I'm having an issue where only the second include's jobs are running in the test stage, and the Gitlab Code Quality job is completely ignored. If I remove the external Checkmarx include, the Code Quality job runs just fine.
Normally I would just define separate stages, but since these .yml files do not belong to me, I cannot change the stage in which they run.
Is there a way to ensure the jobs all run in the test stage? If not, is there a way to override the stage a job from an external .yml runs in?

A: Oddly, there seems to be some sort of rules conflict between the two templates, possibly due to the variables that the checkmarx template sets. Even though the CI Lint shows that all 4 jobs should run successfully, I can reproduce your issue with the above code.
Given that it's likely a rules issue, I overrode the rules for running the code_quality job and was able to get both running within the same pipeline:
include:
  - template: Code-Quality.gitlab-ci.yml
  - remote: 'https://raw.githubusercontent.com/checkmarx-ltd/cx-flow/develop/templates/gitlab/v3/Checkmarx.gitlab-ci.yml'

code_quality:
    rules:
        - when: on_success

You can lint the above changes to confirm they're successful (though GitLab will warn you that without any workflow:rules, you'll wind up with duplicate pipelines inside MRs, which is true).
You can also see the pipeline running with both jobs here though checkmarx fails because I don't have a subscription to test it with:


text:
Q: Sorting an array of objects based on string property in Typescript I have an array of objects like so:
0: {id: "743", name: "F"}
1: {id: "786", name: "S"}
2: {id: "903", name: "B"}
3: {id: "988", name: "L"}
4: {id: "1202", name: "S"}
5: {id: "1355", name: "H"}
6: {id: "1374", name: "R"}

And I need to sort the array of objects based on the 'name' property.
I have searched around for the answer and have tried each of them out but with no joy.
The two main answers I came across were:
Array.sort((leftSide, rightSide): number => {
            if (leftSide.name.toLowerCase() < rightSide.name.toLowerCase()) return -1;
            if (leftSide.name.toLowerCase() > rightSide.name.toLowerCase()) return 1;
            return 0;
        });

and
Array.sort((a, b) => a.name.localeCompare(b.name))

both of these just give me the same unsorted array output. Is there any other way to do this? I am using Angular 7.
Full code:
getDeviceBrands(): void {
        this.deviceBrands = new Array<DeviceBrand>();
        const parentNodeId = 0;

        this.chartsService.getCatalogNodes(parentNodeId, this.catalogName).subscribe(catalogNodes => {
            catalogNodes.forEach(n => {
                this.deviceBrands.push({
                    id: n.CatalogNodeId.toString(),
                    name: n.Name
                });
            });
        });

        console.log(this.deviceBrands);

        const sorted = this.deviceBrands.sort((a, b) => a.name < b.name ? -1 : 1);

        console.log(sorted);
    }

A: I'm not sure why the above doesn't work for you; but the following works for me:
const x = [
  { id: "743", name: "F" },
  { id: "786", name: "S" },
  { id: "903", name: "B" },
  { id: "988", name: "L" },
  { id: "1202", name: "S" },
  { id: "1355", name: "H" },
  { id: "1374", name: "R" },
];

const sorted = x.sort((a, b) => a.name < b.name ? -1 : 1);

console.log(sorted);

From running your code, it seems like it ought to work as well. I'm guessing from the example you've shown that you're using the array in a variable named Array, which is not a good idea, as Array is already used in javascript.

const Array = [
  { id: "743", name: "F" },
  { id: "786", name: "S" },
  { id: "903", name: "B" },
  { id: "988", name: "L" },
  { id: "1202", name: "S" },
  { id: "1355", name: "H" },
  { id: "1374", name: "R" },
];

const sorted = Array.sort((leftSide, rightSide) => {
    if (leftSide.name.toLowerCase() < rightSide.name.toLowerCase()) return -1;
    if (leftSide.name.toLowerCase() > rightSide.name.toLowerCase()) return 1;
    return 0;
});

console.log(sorted);

A: The issue was that I was doing the sort too late! If you need to edit a collection in anyway and you are using a subscribe to fill your collection then add the code within the subscribe!
I did not include my full code at first which is what caused confusion as the answers supplied all worked. This is a good example of why you should include full code.


text:
Q: Memory Allocation Error in C I am trying to get the binary representation of a big integer in GMP. I am storing 1's and 0's in an array called expBinary. I use malloc to allocate a memory of size of "int", then use realloc to increase this memory whenever a new bit is added. The conversion is running perfectly without any issues, but when I try to allocate any more memory using malloc after the while loop, it is giving me segmentation fault when I call the same code a second time, first time it gives me no segmentation fault. I have checked and the "expBinary" is not storing anything out of bounds, I have given the code below
int binarySize = 0;
int * expBinary = malloc(sizeof(int));
int i = 0;

// Run until exp == 0
while(mpz_cmp_ui(exp,0) != 0)
{
    binarySize++;
    expBinary = (int*) realloc(expBinary,(binarySize));
    // Getting LSB of exp
    if(mpz_even_p(exp) != 0)
        expBinary[i] = 0;
    else
        expBinary[i] = 1;
    // Incrmenting variables
    i++;
    // Dividing exponent by 2
    mpz_tdiv_q_ui(exp,exp,2);
}

// This line is giving error
int * temp = malloc(sizeof(int));

A: If you are using an int array, then this is wrong
expBinary = (int*) realloc(expBinary,(binarySize));

it should be
expBinary = realloc(expBinary, binarySize * sizeof(*expBinary));

or equivalently,
expBinary = realloc(expBinary, binarySize * sizeof(int));

I prefer sizeof(*expBinary) for obvious reasons, and also, if realloc() fails  you loose reference to the previous pointer so I recommend this
void *tmp;
tmp = realloc(expBinary, binarySize * sizeof(int));
if (tmp == NULL)
    handleFailureHereAndDontContinueToTheNextLineAndFree_expBinary_Please();
expBinary = tmp;

Now, if you want to print the representation using any printf("%s\n", expBinary); you should use char * instead, in that case you should consider that sizeof(char) == 1 always, and you will need one extra byte at the end of the 1's and 0's with the value '\0'.


text:
Q: Popover with no size I made a popover class that I could call easily for basic popovers - you give it data and set the size and it should do the rest.
This was working fine until iOS5, now the popover opens but with just the border, no white space or content at all.
I've searched and searched, any ideas you could throw my way would be great.
@protocol BasicPickerDelegate
 - (void)basicPickerItemSelected:(NSMutableDictionary *)thisDic;
@end

@interface BasicPickerController : UITableViewController {

 // data

 IBOutlet NSMutableArray *theData;

 // stuff to set

 IBOutlet int myWidth;
 IBOutlet int myHeight;

 IBOutlet int myPopoverNum;

 // delegate
 id<BasicPickerDelegate> delegate;

}

 @property (nonatomic, retain) IBOutlet NSMutableArray *theData;

 @property (nonatomic, assign) IBOutlet int myWidth;
 @property (nonatomic, assign) IBOutlet int myHeight;
 @property (nonatomic, assign) IBOutlet int myPopoverNum;

 @property (nonatomic, assign) id<BasicPickerDelegate> delegate;

 - (void)setSize;
 - (void)checkData;

@end

Then the setSize function is viewDidLoad
- (void)setSize {

    if (!myWidth || !myHeight) {

      NSLog(@"WIDTH AND HEIGHT NOT SET, SETTING DEFAULTS");
      myWidth = 100;
      myHeight = 100;

    }

    self.contentSizeForViewInPopover = CGSizeMake(myWidth, myHeight);
}

Then I call it like this:
- (IBAction)showBasicPopover:(id)sender {

    // Show Basic Popover - can be reused

    if (basicPicker != nil) {

        self.basicPicker = nil;
        [self.basicPicker release];

    }

    self.basicPicker = [[[BasicPickerController alloc] initWithStyle:UITableViewStylePlain] autorelease];

    basicPicker.delegate = self;

    self.basicPickerPopover = [[[UIPopoverController alloc]
                                    initWithContentViewController:basicPicker] autorelease];

    // Give popover the data it needs

    NSMutableDictionary *sizeDic = [self returnPopoverSize:[sender tag]];

    self.basicPicker.myHeight = [[sizeDic objectForKey:@"height"] intValue];
    self.basicPicker.myWidth = [[sizeDic objectForKey:@"width"] intValue];
    self.basicPicker.myPopoverNum = [sender tag];

    [basicPicker viewDidLoad];

    self.basicPicker.theData = [self returnPopoverData:[sender tag]];

    NSLog(@"giving popover dic (%d) with %d derps", [sender tag], [self.basicPicker.theData count]);

    // Set display settings and show popover

    [basicPicker viewWillAppear:YES];

    CGRect popoverRect = [self.view convertRect:[sender frame]
                                       fromView:[sender superview]];

    [self.basicPickerPopover presentPopoverFromRect:popoverRect
                                             inView:self.view
                           permittedArrowDirections:UIPopoverArrowDirectionAny
                                           animated:YES];

}

When I run it, the WIDTH AND HEIGHT NOT SET, SETTIN DEFAULTS dialogue comes up.  For some reason it's not reading in the values it's given.  Though with some fiddling, even if I can get it to read them in it don't think they are valid and overrides them.
edit:  So basically:
With setSize being called in viewDidLoad it doesn't know what the width and height is.  So it sets the default.
If setSize isn't called in viewDidLoad, it comes up with "no size" - ie it has popover border but no content in it at all.
When setSize is called in viewWillAppear, viewDidAppear or anything like that (after viewDidLoad) it doesn't actually set the size of the popover.

A: Finally figured this out.
I needed to assign the width/height variables after creating the popover but before initialising it.
Revised code below:
self.basicPicker = [[[BasicPickerController alloc] initWithStyle:UITableViewStylePlain] autorelease];

// Give popover the data it needs

basicPicker.delegate = self;

NSMutableDictionary *sizeDic = [self returnPopoverSize:[sender tag]];

self.basicPicker.myHeight = [[sizeDic objectForKey:@"height"] intValue];
self.basicPicker.myWidth = [[sizeDic objectForKey:@"width"] intValue];
self.basicPicker.myPopoverNum = [sender tag];

// Now init

self.basicPickerPopover = [[[UIPopoverController alloc]
                            initWithContentViewController:basicPicker] autorelease];

[basicPicker viewDidLoad];


text:
Q: What can we do about a randomly crashing app without source code? I am trying to help a client with a problem, but I am running out of ideas. They have a custom, written in house application that runs on a schedule, but it crashes. I don't know how long it has been like this, so I don't think I can trace the crashes back to any particular software updates. The most unfortunate part is there is no longer any source code for the VB6 DLL which contains the meat of the logic.
This VB6 DLL is kicked off by 2-3 function calls from a VB Script. Obviously, I can modify the VB Script to add error logging, but I'm not having much luck getting quality information to pinpoint the source of the crash. I have put logging messages on either side of all of the function calls and determined which of the calls is causing the crash. However, nothing is ever returned in the err object because the call is crashing wscript.exe.
I'm not sure if there is anything else I can do. Any ideas?
Edit: The main reason I care, even though I don't have the source code is that there may be some external factor causing the crash (insufficient credentials, locked file, etc). I have checked the log file that is created in drwtsn32.log as a result of wscript.exe crashing, and the only information I get is an "Access Violation".
I first tend to think this is something to do with security permissions, but couldn't this also be a memory access violation?

A: You may consider using one of the Sysinternals tools if you truly think this is a problem with the environment such as file permissions.  I once used Filemon to figure out all the files my application was touching and discovered a problem that way.
You may also want to do a quick sanity check with Dependency Walker to make sure you are actually loading the DLL files you think you are.  I have seen the wrong version of the C runtime being loaded and causing a mysterious crash.

A: Depending on the scope of the application, your client might want to consider a rewrite. Without source code, they will eventually be forced to do so anyway when something else changes.

A: It's always possible to use a debugger - either directly on the PC that's running the crashing app or on a memory dump - to determine what's happening to a greater or lesser extent. In this case, where the code is VB6, that may not be very helpful because you'll only get useful information at the Win32 level.
Ultimately, if you don't have the source code then will finding out where the bug is really help? You won't be able to fix it anyway unless you can avoid that code path for ever in the calling script.

A: You could use the debugging tools for windows. Which might help you pinpoint the error, but without the source to fix it, won't do you much good.
A lazier way would be to call the dll from code (not a script) so you can at least see what is causing the issue and inspect the err object. You still won't be able to fix it, unless the problem is that it is being called incorrectly.

A: The guy of Coding The Wheel has a pretty interesting series about building an online poker bot which is full of serious technical info, a lot of which is concerned with how to get into existing applications and mess with them, which is, in some way, what you want to do.
Specifically, he has an article on using WinDbg to get at important info, one on how to bend function calls to your own code and one on injecting DLLs in other processes. These techniques might help to find and maybe work around or fix the crash, although I guess it's still a tough call.

A: There are a couple of tools that may be helpful.  First, you can use dependency walker to do a runtime profile of your app:
http://www.dependencywalker.com/
There is a profile menu and you probably want to make sure that the follow child processes option is checked.  This will do two things.  First, it will allow you to see all of the lib versions that get pulled in.  This can be helpful for some problems.  Second, the runtime profile uses the debug memory manager when it runs the child processes.  So, you will be able to see if buffers are getting overrun and a little bit of information about that.
Another useful tool is process monitor from Mark Russinovich:
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx
This tool will report all file, registry and thread operations.  This will help you determine if any you are bumping into file or registry credential issues.
Process explorer gives you a lot of the same information:
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
This is also a Russinovich tool.  I find that it is a bit easier to look at some data through this tool.
Finally, using debugging tools for windows or dev studio can give you some insight into where the errors are occurring.

A: Access violation is almost always a memory error - all the more likely in this case because its random crashing (permissions would likely be more obviously reproducible).  In the case of a dll it could be either

*

*There's an error in the code in the dll itself - this could be something like a memory allocation error or even a simple loop boundary condition error.

*There's an error when the dll tries to link out to another dll on the system. This will generally be caused by a mismatch between dll versions on the machine.
Your first step should be to try and get a reproducible crash condition.  If you don't have a set of circumstances that will crash the system then you cannot know when you have fixed it.
I would then install the system on a clean machine and attempt to reproduce the error on that.  Run a monitor and check precisely what other files (dlls etc) are open when the program crashes.  I have seen code that crashes on a hyperthreaded Pentium but not on an earlier one - so restoring an old machine as a testbed may be a good option to cover that one.  Varying the amount of ram in the machine is also worthwhile.
Hopefully these steps might give you a clue.  Hopefully it will be an environment problem and so can be avoided by using the right version of windows, dlls etc.  However if you're still stuck with the crash at this point with no good clues then your options are either to rewrite or attempt to hunt down the problem further by debugging the dll at assembler lever or dissassembling it.  If you are not familiar with assembly code then both of these are long-shots and it's difficult to see what you will gain - and either option is likely to be a massive time-sink.  Myself I have in the past, when faced with a particularly low-level high intensity problem like this advertised on one of the 'coder for hire' websites and looked for someone with specialist knowledge.  Again you will need a reproducible error to be able to do this.
In the long run a dll without source code will have to be replaced.  Paying a specialist with assembly skills to analyse the functions and provide you with flowcharts may well be worthwhile considering.  It is good business practice to do this sooner in a controlled manner than later - like after the machine it is running on has crashed and that version of windows is no longer easily available.

A: You may want to try using Resource Hacker you may have luck de-compiling the in house application.  it may not give you the full source code but at least maybe some more info about what the app is doing, which also may help you determine your culrpit.

A: Add the maximum possible RAM to the machine
This simple and cheap hack has work for me in the past. Of course YMMV.

A: Reverse engineering is one possibility, although a tough one.
In theory you can decompile and even debug/trace a compiled VB6 application - this is the easy part, modifying it without source, in all but the most simple cases, is the hard part.
Free compilers/decompilers:
VB decompilers
VB debuggers
Rewrite would be, in most cases, a more successful and faster way to solve the problem.


text:
Q: Find computers that are not members of a specific GG group I use a script to export users that are not in specific GG groups in active directory but I want to do the same with computers.
This is the example that works with users:
$groups = 'GG_LCS_UsersType4', 'GG_LCS_UsersType3', 'GG_LCS_UsersType2', 'GG_LCS_SpecialUsers'
$whereFilter = $groups | Foreach-Object {
    $g = (Get-ADGroup -server $domain $_).DistinguishedName
    "{0} '{1}'" -f '$_.memberOf -notcontains',$g
}
$whereFilter = [scriptblock]::Create($whereFilter -join " -and ")
$users = (Get-ADUser -server $Domain -filter {objectclass -eq "user"} -properties memberof).where($whereFilter)
$users | Select-Object SamAccountName,Enabled |
    Export-Csv "${Domain}_Users_withoutGG.csv" -NoTypeInformation -Encoding UTF8 -Append

And I tried this in order to do the same with computers, but this doesn't work:
$groups = 'GG_LCS_ComputersType2', 'GG_LCS_ComputersType3', 'GG_LCS_ComputersType4'
$whereFilter = $groups | Foreach-Object {
    $g = (Get-ADGroup -server $domain $_).DistinguishedName
    "{0} '{1}'" -f '$_.memberOf -notcontains',$g
}
$whereFilter = [scriptblock]::Create($whereFilter -join " -and ")
$users = (Get-ADComputer -server $Domain -filter {objectclass -eq "computer"} -properties memberof).where($whereFilter)
$users | Select-Object SamAccountName,Enabled |
    Export-Csv "${Domain}_Computers_withoutGG.csv" -NoTypeInformation -Encoding UTF8 -Append

Could you help me? Thanks!

A: Try adding the -SearchBase
$AD = Get-ADComputer  -Filter *  -Properties $properties -SearchBase "DC=subdomain,DC=domain,DC=com" -Server $server
$AD | Select-Object * | Export-Csv -NoTypeInformation $filePath -Encoding UTF8


text:
Q: How to know if timeout occurred in cypher query? I'm using apoc.cypher.runTimeboxed https://neo4j.com/labs/apoc/4.1/cypher-execution/cypher-timeboxed/
I'm using the HTTP API of neo4j. I'm making HTTP post requests like below.

Here I do NOT see any difference if the results are really empty or if the results are empty because TIMEOUT OCCURRED. I think there should be a warning or error message.

A: An APOC enhancement request was created for this in 2019.
And there were a couple of commits addressing this, but they have not been merged for some reason. You may want to add comments to that request.


text:
Q: Parse.com - secure sending data with javascript SDK I'm building right now simple game with Angular JS and Parse.com cloud as my database.
My goal is in the and of the game, to store user score inside Parse cloud.
But how can i do this securly, when anyone can get access to my Parse keys, becouse they are visible in my js file, and simply recreate Parse Object with some fake data, and then store it in my database ?
ACL's it's not the point in this particular case - right now i just turn of write acl before save, to prevent users from changing they scores before save.
In my game i don't have any Parse Users - i want to all peaople play my game, without logging in.
What do you think about idea to make 'fake' user like in first answer in this post ( becouse Anonymous anonymous can't be create in JS parse SDK ), and then track the session and the user ?
Is it even helpful in my case ?
Maybe i should make some check in Cloude Code - like comparison Cookies or local storage data before saving in Parse ( it will make cheating in game harder but still possible ) ?
Below i present my whole service to show you what is all about:
angular.module('Parsedb', [])
.provider('Parsedbmanager', function() {
  this.$get = function($q, $http) {

    // new Parse constructor
    var ParseHighScore = Parse.Object.extend('ParseHighScore');

    // create new obj
    var parseHighScore = new ParseHighScore();

    this.parseInit = function() {
        Parse.initialize('myKey', 'myKey');
    };

    this.setParsedb = function(newScore) {
      // set val
      parseHighScore.set('HighScore', newScore);
      // save score to cloud
      parseHighScore.save(null, {
        success: function (parseHighScore) {

          // protect from change saved obj
          var acl = new Parse.ACL();
          acl.setPublicReadAccess(true);
          acl.setPublicWriteAccess(false);
          parseHighScore.setACL(acl);

          return parseHighScore.save();
        },
        error: function (parseHighScore, error) {
          console.log('Failed to create new object, with error code: ' + error.message);
        }
      });
    };

    this.getParsedb = function() {
      // need q to get this asynch
      var deferred = $q.defer();
      var query = new Parse.Query(ParseHighScore);
      query.limit(5);
      query.descending("HighScore");
      query.find({
         success: function(results) {
          console.log("Successfully retrieved " + results.length + " scores.");
          // resolve, if you have results
          deferred.resolve(results);
        },
        error: function(error) {
           deferred.reject(error.message);
        }
      });

      return deferred.promise;
    };

    return this;
  };

});

A: If you let the user to write to db then there will always be a situation where user can change data .. i think all you can do is, to abstract it from user


text:
Q: Prove $\det(A - nI_n) = 0$. Problem: Prove that $\det(A - n I_n) = 0$ when $A$ is the $(n \times n)$-matrix with all components equal to $1$.
Attempt at solution: I tried to use Laplace expansion but that didn't work. I see the matrix will be of the form \begin{align*} \begin{pmatrix} 1-n & 1 & \cdots & 1 \\ 1 & 1-n & \cdots & 1 \\ \vdots \\ 1 & 1 & \cdots & 1-n \end{pmatrix} \end{align*} I want to somehow get two equal rows or columns here, or a row/column of zero using elementary operations. But I don't see what I should do?

A: Hint: Add all other rows to the first row. What row you'll obtain after that?

A: The eigenvalue of the $n \times n$ matrix in which every entry is $1$ is $n$ (of multiplicity $1$) and $0$ (of multiplicity $n-1$). Proof here
So, for such a matrix $A$, we have $\det(A - \lambda I_n) = 0$, and $\lambda = n$.


text:
Q: How can I detect if my two images are touching in Pygame? I'm making a game where ASL handsigns fall down and you need to catch them in a bucket. When the sign touches the bucket, I want it to print that they are touching. If they aren't, I want it to print that they are not touching.  How do I detect if the images are touching? I have some rect collision code already in, but it just constantly prints out that they are touching one of the signs even when they aren't. Thanks in advance for any help you can give me! P.S. Sorry for putting in all my code but I'm not sure what is needed to see to help solve my problem.
I looked at many questions and answers involving image collision but I can't seem to make it work in my code. I '''highlighted''' the code that I think is causing the problem.
import random
import pygame
pygame.init()
pygame.mixer.init()
#define functions
def newPlacement():
    screen.blit(choiceASL, (x,y))
    screen.blit(choiceASL2, (x2,y2))
    screen.blit(choiceASL3, (x3,y3))
def bucketStuff():
    screen.blit(bucketPic, (bucketX, bucketY))
'''
def ifCollided():
    if bucketRect.colliderect(choiceASLRect):
        print("You collided with choice1!")
    elif bucketRect.colliderect(choiceASL2Rect):
        print("You collided with choice2!")
    elif bucketRect.colliderect(choiceASL3Rect):
        print("You collided with choice3!")
    else:
        print("Not touching.")
'''

#define stuff below: var, funct, def, etc.
aslABCSList = ("AslA.png", "AslB.png", "AslC.png", "AslD.png")
randHandsign = random.choice(aslABCSList)
randHandsign2 = random.choice(aslABCSList)
randHandsign3 = random.choice(aslABCSList)
choiceASL = pygame.image.load(randHandsign)
choiceASLRect = choiceASL.get_rect()
choiceASL2 = pygame.image.load(randHandsign2)
choiceASL2Rect = choiceASL2.get_rect()
choiceASL3 = pygame.image.load(randHandsign3)
choiceASL3Rect = choiceASL3.get_rect()
bucketPic = pygame.image.load("bucketPic.png")
bucketRect = bucketPic.get_rect()

screen = pygame.display.set_mode((700, 600))
Black = [0, 0, 0]
White = [255, 255, 255]
y = 0
y2 = 0
y3 = 0
x = int(random.randrange(1,650,25))
x2 = int(random.randrange(1,650,25))
x3 = int(random.randrange(1,650,50))
bucketX = 300
bucketY = 540

#to make the main work
done = False
#allows fps rate
clock = pygame.time.Clock()

#basically main, put anything that you want to run consistently until the user exits below.
while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
        #vvv Put all main code here! vvv
        screen.fill(White)
        bucketStuff()
        newPlacement()
        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_LEFT]: bucketX -= 3
        if pressed[pygame.K_RIGHT]: bucketX += 3
        ifCollided()

        y+=1
        y2+=2
        y3+=3

        #below is basically a refresh, so that everything is updated. Put code before this!
        pygame.display.flip()
        #60 fps
        clock.tick(50)

A: The .get_rect() of a pygame.Surface object returns a rectangle with the size of the surface, but at location (0, 0).
You've to set the location of the image (pygame.Rect):
e.g.:
choiceASL = pygame.image.load(randHandsign)
choiceASLRect = choiceASL.get_rect()

# [...]

bucketPic = pygame.image.load("bucketPic.png")
bucketRect = bucketPic.get_rect()

# [...]

while not done:

    # [...]

    if pressed[pygame.K_LEFT]: bucketX -= 3
    if pressed[pygame.K_RIGHT]: bucketX += 3

    bucketRect.topleft = (bucketX, bucketY)
    choiceASLRect.topleft = (x, y)
    # [...]

    ifCollided()

Once the location of the rectangles is proper set, then the collision test will work as expected.


text:
Q: How to select specific fields from main table in Laravel when selecting with relationship I'm trying to select specific fields from relationships like so:
return Product::whereIn('id', $product_ids)
          ->with([
            'variations' => function($query) {
              $query->select('product_id', 'id', 'variation_name', 'variation_value', 'variation_price', 'variation_qty');
            },
            'customizations' => function($query) {
              $query->select('product_id', 'id', 'group_id', 'customization_price', 'customization_qty');
            }
          ])
          ->get();

That works, and that's all I find in the internet. Not how to select specific fields from the main table. I tried the following but none of them worked:
->get(['price', 'qty', 'variations', 'customizations']);

Product::select('price', 'qty', 'variations', 'customizations');

->select('price', 'qty', 'variations', 'customizations');

Any ideas?


text:
Q: Exe file says - cannot import name chardet I'm trying to make an exe file using py2exe. The problem is that when I try to run created exe file, it returns that it cannot import name chardet.
Traceback (most recent call last):
  File "orsr_parser.py", line 10, in <module>
  File "requests\__init__.pyc", line 58, in <module>
  File "requests\utils.pyc", line 26, in <module>
  File "requests\compat.pyc", line 7, in <module>
ImportError: cannot import name chardet

I use requests module in one of the py files in the program.
Setup.py:
from distutils.core import setup
import py2exe
packages = ['requests']
setup(console=['my_script.py'])

Do you know where could be the problem? Is there something with setup.py file?
EDIT: There is only one answer for this problem: Stackoverflow answer, but I probably don't get it. There is no directory called requests in my project.


text:
Q: Equivalent to "shorten <=" for intermediate points Halo everybody,
I try to plot a data set using tikz & pgf. I want that the points in the plot are connected, but the line shouldn't touch the points. I can achieve this for the first and the last point by using shorten <= and shorten >= but the line runs still directly all other points. How can I achieve a gap around each point?
Here a minimalist example of my current attempt:
\documentclass[10pt]{article}
\usepackage{pgf,tikz,pgfplots}
\begin{document}

\begin{tikzpicture}
\begin{axis}[
    xmin=0,
    xmax=100,
    ymin=0,
    ymax=100,
    grid=major
]
\addplot [mark=*, line width=1pt, shorten <= 5pt, shorten >= 5pt] table {
    10 10
    20 30
    30 25
    40 31
    50 32
    60 45
};
\end{axis}
\end{tikzpicture}

\end{document}

A: You can use mark options like mark options={draw=white,}:
\documentclass[10pt]{article}
\usepackage{pgfplots}
\begin{document}
%\tikzset{every mark/.append style={draw=white}}
\begin{tikzpicture}
\begin{axis}[
    xmin=0,
    xmax=100,
    ymin=0,
    ymax=100,
    grid=major
]
\addplot [mark=*,mark options={draw=white,}, line width=1pt] table {
    10 10
    20 30
    30 25
    40 31
    50 32
    60 45
};
\end{axis}
\end{tikzpicture}

\end{document}

With mark options={draw=white,line width=3pt,scale=2} we get,

Adjust parameters as suitable for you.
If you need custom o mark, you can define one
\pgfdeclareplotmark{h}{
    \fill[white](0,0) circle (1.5\pgfplotmarksize);
    \draw (0,0) circle (\pgfplotmarksize);
}

Change the 1.5 here as desired.
Code:
\documentclass[10pt]{article}
\usepackage{pgfplots}
\begin{document}
%\tikzset{every mark/.append style={draw=white}}
\pgfdeclareplotmark{h}{
    \fill[white](0,0) circle (1.5\pgfplotmarksize);
    \draw (0,0) circle (\pgfplotmarksize);
}
\begin{tikzpicture}
\begin{axis}[
    xmin=0,
    xmax=100,
    ymin=0,
    ymax=100,
    grid=major
]
\addplot [mark=h,mark options={line width=0.6pt},line width=1pt] table {
    10 10
    20 30
    30 25
    40 31
    50 32
    60 45
};
\end{axis}
\end{tikzpicture}

\end{document}


text:
Q: How to add wildcard to CSS selectors? I am working on a website and I am trying to figure out how to add a wildcard to the following code for author1_name:
$(function() {
  var num = 2;
  var id = 'author' + num;
  var uni_id = 'university' + num;
  $("#AuthorFieldButton").click(function() {
    var name = 'Author ' + num;
    var uni_name = 'University ' + num;
    id = 'author' + num;
    $('.author-group').last().after('
 ' + name + ':
<input type="text" id="' + id + '" name="' + id + '" class="form-control input-md" maxlength="40" >

' + uni_name + ':
<input type="text" id="' + uni_id + '" name="' + uni_id + '" class="form-control input-md" maxlength="55" >

')
    num++;
  });
  $("#article_name").autocomplete({
    source: 'articlesearch.php'
  });

  $("#author1_name").autocomplete({
    source: 'authorsearch.php'
  });
  $("#author2_name").autocomplete({
    source: 'authorsearch.php'
  });
  $("#author3_name").autocomplete({
    source: 'authorsearch.php'
  });
  $("#author4_name").autocomplete({
    source: 'authorsearch.php'
  });
  $("#author5_name").autocomplete({
    source: 'authorsearch.php'
  });
  $("#author6_name").autocomplete({
    source: 'authorsearch.php'
  });
  $("#author1_university").autocomplete({
    source: 'universitysearch.php'
  });
  $("#author2_university").autocomplete({
    source: 'universitysearch.php'
  });
  $("#author3_university").autocomplete({
    source: 'universitysearch.php'
  });
  $("#author4_university").autocomplete({
    source: 'universitysearch.php'
  });
  $("#author5_university").autocomplete({
    source: 'universitysearch.php'
  });
  $("#author6_university").autocomplete({
    source: 'universitysearch.php'
  });
});

I'd like it to place a wildcard to the number in the author1_name and author1_university so that I don't have to repeat the selector multiple times in my code. Your help is greatly appreciated.

A: Use the selector like this:
$("[id^=author]").autocomplete({
    source: 'universitysearch.php'
  });

This finds the ids which starts with author.
To find the ids that end with _university :
$("[id$=_university]").autocomplete({
    source: 'universitysearch.php'
  });

Adding a separate class to all the elements you need to select also is a solution. You can add the class author_of_university to the elements and select like:
$(".author_of_university").autocomplete({
        source: 'universitysearch.php'
 });

A: You have two routes here:

*

*You can put a single class on each of the like elements.
class="author_university"
JQuery: $(".author_university")

*Or use a selector for id like so:
$("[id^='author'][id$='_university']")
This selects any element with an id starting with "author" and ending with "_university".

A: Jquery has a "starts with" selector:
$( "[id^='author']" ).autocomplete({});


text:
Q: Apache serve files from git repo branches Is there any way to serve files from branches in a git repo without checking them out into different directories?
I'd love the convenience of being able to create a new branch, push it to a test server repo and then do something like browse to http://branchname.test.com.  I can use rewrite rules to handle branch name subdomain to point to different root paths but Apache can't read  bare repos of course.
gitfs might work, but seems abandoned.
I don't especially need Apache either.

A: The simplest approach would be checking out each branch and creating clones for each branch in subdirectories. It's very easy to do that with a script runned by cron (or in a post-commit hook) like:
#!/bin/sh
ROOT=/srv/repos/control
cd ${ROOT} # it's an internal repo
git fetch
for ref in .git/refs/remotes/origin/*; do
  BRANCH=`basename ${ref}`
  if ! [ -d ../${BRANCH} ]; then
    git clone --local ${ROOT} ../${BRANCH}
    cd ../${BRANCH}
    git branch --track ${BRANCH} remotes/origin/${BRANCH}
    git checkout ${BRANCH}
  else
    cd ../${BRANCH}
    git pull
  fi
done

After it's work you will get a bunch of directories with branches in /srv/repos.
git clone --local is very fast and optimal even on huge repositories like Linux kernel because it does not create all the objects in repository but instead creates hardlinks to them, so you won't waste any space on repository copies. You will, through, waste space on checked-out copies, but a) they're probably not very big and b) this will make web-based access much easier and faster.

A: You can serve content directly from the repository using a combination of git-show (or git cat-file) and Apache CGI or similar. I have set up an example using .htaccess and a simple zsh script, as follows:
.htaccess
Options +ExecCGI
AddHandler cgi-script .sh

RewriteEngine On
RewriteRule ^(?!index.sh)(.*)$ /index.sh [L]

index.sh
#!/bin/zsh

# Strips the initial slash, as git show ain't got time for that!
# REQUEST_URI is set by Apache when executing the script.
# You may also be interested in HTTP_HOST which is the request host.
# Don't get confused with HOST which is a default shell variable.
function get_request_uri {
    if [ $REQUEST_URI[0,1] = '/' ]
    then
        REQUEST_URI=$REQUEST_URI:s#/##
    fi

    echo $REQUEST_URI
}

# You may not want to show the folders (represented by trees).
# Or you may want to manipulate the output to produce a proper directory index.
function is_file_folder {
    [ $(git cat-file -t HEAD:$1) = 'tree' ]
}

# Just gets the content of the file.
# For trees will produce a directory listing, one line per file.
# To show different branches, pass them to git show in place of HEAD
function get_file_content {
    local file=$1

    git show HEAD:${file}
}

# Attempts to determine the file type without writing the data to a file.
# Has to resort to manually looking up the type in /usr/share/mime/globs
# to test by extension, you may have to adjust that code to your environment.
function get_file_type {
    local file=$1
    local content=$2

    mime_type=$(echo ${content} | mimetype -b --stdin)
    if [ -e /usr/share/mime/globs ]
    then
        file_mime_type=$(
            grep "\*.${file:e}\$" /usr/share/mime/globs |
                sed -ne 's/:.*$//' -e '1p'
                    )

        # Conflict resolution is also something you should work on.
        if [ $file_mime_type != '' ]
        then
            mime_type=$file_mime_type
        fi
    fi

    echo $mime_type
}

function do_404 {
    echo 'Status: 404 Not Found'
    echo ''
}

# Just does the header because there can be problems
# getting binary data to the client by echoing it.
# A little something for you to explore a fix for :)
function do_200 {
    mime_type=$1

    echo "Content-Type: $mime_type"
    echo ''
}

cd site.git

uri=$(get_request_uri)
file_content=$(get_file_content $uri)

# A non zero exit status from git show probably means the file does not exist.
# Even if the error was something else, you still have nothing to show for it.
if [ $? -ne 0 ]
then
    do_404
fi

# You may not want to do the directory listing. Even if you do, you may
# not want to use the default directory listing (which is very primitive).
# If you wanted to redirect to index or similar, you would also handle that
# here.
if is_file_folder $uri
then
    file_type='text/plain'
else
    file_type=$(get_file_type $uri "$file_content")
fi

do_200 $file_type

# Doing this twice is not optimal, but it is very easy to
# mangle binary data accidentally when passing around the
# $file_content. Just reading the file directly to the client
# seems to sidestep this. Another thing for you to fix :)
get_file_content $uri

# You might want to uncomment the two lines below (commenting out
# any response code from above first), to show all of the variables
# available to you. This list will include the variables set by this
# script - to filter them out just run this earlier, with an exit after.

# do_200 'text/plain'
# set

# vim: set ai et sw=4 syntax=zsh :

This assumes that your site is in site.git in the same folder as the two files above. There are plenty of improvements that can be made to the script - as commented. This is more of a proof of concept.

A: Also have a look at Divergence, a rack application that maps git branches to subdomains. I haven't used it my self yet, but it seems to fit your needs quite well.


text:
Q: Elementary proof that $|x|^p$ is convex. I'm writing some notes about analysis and want to use the fact that $|x|^p$ is convex for every $p>1$ to prove Minkowski's inequality. However I didn't wrote anything about derivatives nor limits yet. Is there a simple way to prove this?
EDIT: The only non-trivial inequalities proved yet are the triangular inequality and the Cauchy-Schwarz inequality.

A: Update
I let the solution stand as is, even though it uses non-allowed tools. Maybe someone in the future will find it useful.
Old solution
Here is a solution using the Hölder inequality. If that one is not allowed I suggest that you specify more clearly what is and what is not allowed to use among the "standard tools".
We want to show that (here $w_1$ and $w_2$ are non-negative numbers with $w_1+w_2=1$ and $x$ and $y$ are real numbers)
$$
|w_1x+w_2y|^p\leq w_1|x|^p+w_2|y|^p,
$$
that is
$$
|w_1x+w_2y|\leq \bigl(w_1|x|^p+w_2|y|^p\bigr)^{1/p}
$$
(If any of the involved quantities is $0$ we just note that the inequality is true).
We let $q$ be the dual exponent, i.e. defined such that $1/p+1/q=1$. Then, we have, using first the triangle inequality and then the Hölder inequality,
$$
\begin{aligned}
|w_1x+w_2y|&\leq w_1|x|+w_2|y|\\
&=\bigl(w_1^{1/p}|x|\bigr)(w_1)^{1/q}+\bigl(w_2^{1/p}|y|\bigr)(w_2)^{1/q}\\
&\leq\bigl(w_1|x|^p+w_2|y|^p\bigr)^{1/p}\bigl(w_1+w_2\bigr)^{1/q}\\
&=\bigl(w_1|x|^p+w_2|y|^p\bigr)^{1/p}.
\end{aligned}
$$
Since requested, by Hölder inequality, I mean
$$
a_1b_1+a_2b_2\leq(a_1^p+a_2^p)^{1/p}(b_1^q+b_2^q)^{1/q},
$$
where
$$
a_1=w_1^{1/p}|x|,\quad a_2=w_2^{1/p}|y|,\quad b_1=w_1^{1/q},\quad\text{and}\quad b_2=w_2^{1/q}.
$$
Another for a request about obtaining strict convexity.
If $x$ and $y$ have different signs, then we have strict inequality in the triangle inequality. Thus, we can assume that $x$ and $y$ have the same sign.
Further, one has equality in the Hölder inequality precisely when there exists a constant $c$ such that
$$
|b_1|=c|a_1|^{p-1},\quad\text{and}\quad |b_2|=c|a_2|^{p-1}.
$$
In our case this simplifies to
$$
w_1^{1/q}=cw_1^{(p-1)/p}|x|^{p-1},\quad\text{and}\quad w_2^{1/q}=cw_2^{(p-1)/p}|y|^{p-1}.
$$
Since $1/q=(p-1)/p$ this simplifies to
$$
1=c|x|^{p-1},\quad\text{and}\quad 1=c|y|^{p-1},
$$
and hence to $|x|=|y|$. Since we assumed that $x$ and $y$ had the same sign, we conclude that we have equality precisely when $x=y$. All this implies that we have strict convexity.

A: I think yes. The composition of a convex function with an increasing convex one is still convex. More precisely, if $f$ is convex and $g$ is convex and increasing, then $(g\circ f)(x)=g\bigl(f(x)\bigr)$ is convex. Now $f(x)=|x|$ is convex by a triangle inequality and $g(x)=x^p$ is increasing and convex. Here we could use derivatives.

A: I think you might consider starting with the generalised AM–GM inequality $$x^{\alpha}y^{1-\alpha} \leq \alpha x + (1-\alpha)y \qquad x,y>0, \quad 0 \leq \alpha \leq 1, \tag{1} $$
then go directly to Hölder's inequality (of which Cauchy–Schwarz is a simple special case), and then use it for Minkowski as in the answer by mickep.

Now, how to prove (1)? My preference would be to prove Jensen's inequality first and show the logarithm is concave using differentiation, since both of these are useful things in any analysis course, but it's not necessary, nor, I believe, what you want.
One can instead start by proving the unweighted AM–GM inequality for $n$ variables (various elementary proofs are available on the Wikipedia page, or one can simply iterate the near-triviality $x_1x_2<\left( \frac{x_1+x_2}{2} \right)^2 \iff x_1 \neq x_2$ to obtain the strict inequality for $2^n$ variables, and replace "rational" with "dyadic rational" in the next part). We then take rational approximations $ q_n/n \to \alpha$, and setting $q_n$ of the $x_i$ to $x$, $1-q_n$ to $y$. The case of equality is then obtained by careful juggling with the exponents and the fact that we have the strict result for (possibly dyadic) rational exponents. For the rest of the details, the easiest place to look is Hardy, Littlewood and Pólya, Inequalities, pp. 16–18.

Another method uses the logarithm: we have the inequality $\log{y} < y-1 $ for $y \neq 1$. Depending on your definition of the logarithm, this is either trivial ($n(x^{1/n}-1)$ is decreasing, or $\int_1^x dt/t < 1 \cdot (t-1)$) or a consequence of the even more obvious "$1+x<e^x$ unless $x=0$". Then writing $A=\alpha x + (1-\alpha)y$,
$$ \alpha (\log{x}-\log{A}) + (1-\alpha) (\log{y}-\log{A}) < \alpha \left(\frac{x}{A}-1\right)+(1-\alpha)\left(\frac{y}{A}-1\right) = 0, $$
and rearranging gives
$$ \log{x^{\alpha}y^{1-\alpha}} < \log{A}. $$
(C.f. HLP p. 138). This needed that the logarithm satisfies the inequality, $a\log{x} = \log{(x^a)}$, $\log{x}+\log{y}=\log{xy}$, and the increasingness of the logarithm. In particular, convexity itself is not required. The nice thing about this proof is that it trivially extends to more $x$s, and even to functions, with no modification.

A: Here is an elementary argument which uses only MVT: Claim: for $x \geq 0$ we have $x^{p}=\sup \{a^{p}+(x-a)pa^{p-1}: a\geq 0\}$. To prove that apply MVT to $x^{p}-a^{p}$ and consider the cases $a<x$ and $a \geq x$ separately. [ The idea for this comes from the geometric fact that a convex function is the upper envelope of the tangent lines]. Now define $f_a(x)=a^{p}+(x-a)pa^{p-1}$. [MVT gives $a^{p}+(x-a)pa^{p-1}\leq x^{p}$. To show that the supremum of the left side equals $x^{p}$ you just have to note that $a^{p}+(x-a)pa^{p-1}=x^{p}$ when $a=x$].  Then $f_a(\frac {x+y} {2})=\frac {f_a(x)+f_a(y)} 2$ (since $f_a$ is an affine function ). Just take supremum over $a \geq 0$ to get the desired inequality.


text:
Q: How to write LINQ to convert datatypes and to concatenate strings? I am new to LINQ, and I wish to convert from one datatype to another in C#, as well as concatenate a string. How would I accomplish this?
For example, what would the SQL statement
SELECT IPv4 = CONVERT(varchar(3), IPv4_octet1) + '.' +
              CONVERT(varchar(3), IPv4_octet2) + '.' +
              CONVERT(varchar(3), IPv4_octet3) + '.' +
              CONVERT(varchar(3), IPv4_octet4) FROM table;

be in LINQ? (The IPv4_octet's are stored as tinyints in the SQL table.)

A: In this case I suspect you could just write:
var query = data.Select(x => x.IpV4Octet1 + "." +
                             x.IpV4Octet2 + "." +
                             x.IpV4Octet3 + "." +
                             x.IpV4Octet4);

More generally you'd call ToString, e.g.:
// You wouldn't want to actually do this, but...
var query = data.Select(x => x.IpV4Octet1.ToString() + x.IpV4Octet4.ToString());

If you want more control, and you're not using the result in the rest of the query, you may well want to do the formatting on the .NET side - simply use AsEnumerable when you've selected all the information you want from the database, and then do the rest in LINQ to Objects. For example:
var query = db.Select(x => new { x.HostName, x.IpV4Octet1, x.IpV4Octet2,
                                 x.IpV4Octet3, IpV4Octet4 })
              .AsEnumerable() // Switch to LINQ to Objects for rest of query
              .Select(x => new { x.HostName,
                                 Address = string.Format("{0}.{1}.{2}.{3}"),
                                                         x.IpV4Octet1,
                                                         x.IpV4Octet2,
                                                         x.IpV4Octet3,
                                                         x.IpV4Octet4) });

A: try this:
string ipv4 = string.Join('.',octets.Select(o => o.ToString()).ToArray());


text:
Q: How to use WFS Request CreateStoredQuery I would like to filter by WFS.
I started with the request CreateStoredQuery.
I created this file.
<html>
    <head>
        <title>WFS Test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    <body>
        Press<br>
        <input type="button" value="doit" onclick="doit()"/>
        <script language="JavaScript">
            function doit() {

                    var data = ''
                    + '<wfs:CreateStoredQuery service="WFS" version="2.0.0" xmlns="http://www.opengis.net/wfs/2.0" xmlns:wfs="http://www.opengis.net/wfs/2.0" xmlns:fes="http://www.opengis.org/fes/2.0" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'
                    + ' <wfs:StoredQueryDefinition id="SucheFlur">'
                    + '     <wfs:Title>SucheFlur</wfs:Title>'
                    + '     <wfs:Parameter name="gemarkungsname" type="xsd:String"/>'
                    + '     <wfs:QueryExpressionText returnFeatureTypes="KRE_ALKIS:sg_flurstueck_f" language="urn:ogc:def:queryLanguage:OGC-WFS::WFS_QueryExpression" isPrivate="false">'
                    + '         <wfs:Query xmlns:wfs="http://www.opengis.net/wfs/2.0" xmlns:fes="http://www.opengis.net/fes/2.0" xmlns:aixm="http://www.aixm.aero/schema/5.1" typeNames="KRE_ALKIS:sg_flurstueck_f" handle="Q01">'
                    + '             <fes:Filter>'
                    + '                     <ogc:Function name="gemarkungsname">'
                    + '                         <ogc:PropertyName>gemarkungsname</ogc:PropertyName>'
                    + '                     </ogc:Function>'
                    + '                     <fes:Literal>${gemarkungsname}</fes:Literal>'
                    + '                 </fes:PropertyIsEqualTo>'
                    + '             </fes:Filter>'
                    + '         </wfs:Query>'
                    + '     </wfs:QueryExpressionText>'
                    + ' </wfs:StoredQueryDefinition>'
                    + '</wfs:CreateStoredQuery>';
                    console.log(data);

                $.ajax({type: 'POST',
                    url: 'http://172.16.206.128:8080/geoserver/KRE_ALKIS/wfs?',
                    data: data,
                    contentType: "text/xml",
                    dataType: "text",
                    error: function (xhr, ajaxOptions, thrownError) {
                        console.log(xhr.status);
                        console.log(thrownError);
                    }
                });
            }
        </script>
</body>

When the request is sent, I get an Error 400 - bad request and the GeoServer logs these errors.
07 Dez 21:05:58 ERROR [geoserver.ows] -
org.geoserver.wfs.WFSException: Request parsing failed
        at org.geoserver.wfs.xml.v2_0.WfsXmlReader.read(WfsXmlReader.java:56)
        at org.geoserver.ows.Dispatcher.parseRequestXML(Dispatcher.java:1606)
        at org.geoserver.ows.Dispatcher.dispatch(Dispatcher.java:700)
        at org.geoserver.ows.Dispatcher.handleRequestInternal(Dispatcher.java:254)
        at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:177)
        at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:52)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:998)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:901)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
        at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:865)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1655)
        at org.geoserver.filters.ThreadLocalsCleanupFilter.doFilter(ThreadLocalsCleanupFilter.java:26)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1642)
        at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:69)
        at org.geoserver.wms.animate.AnimatorFilter.doFilter(AnimatorFilter.java:73)
        at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:66)
        at org.geoserver.filters.SpringDelegatingFilter.doFilter(SpringDelegatingFilter.java:41)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1642)
        at org.geoserver.platform.AdvancedDispatchFilter.doFilter(AdvancedDispatchFilter.java:37)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1642)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
        at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:70)
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
        at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:74)
        at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:91)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:70)
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
        at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:74)
        at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:91)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.geoserver.security.filter.GeoServerAnonymousAuthenticationFilter.doFilter(GeoServerAnonymousAuthenticationFilter.java:51)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:70)
        at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:74)
        at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:91)
        at org.geoserver.security.filter.GeoServerBasicAuthenticationFilter.doFilter(GeoServerBasicAuthenticationFilter.java:81)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:70)
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
        at org.geoserver.security.filter.GeoServerSecurityContextPersistenceFilter$1.doFilter(GeoServerSecurityContextPersistenceFilter.java:52)
        at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:74)
        at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:91)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
        at org.geoserver.security.GeoServerSecurityFilterChainProxy.doFilter(GeoServerSecurityFilterChainProxy.java:142)
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1642)
        at org.geoserver.filters.LoggingFilter.doFilter(LoggingFilter.java:90)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1642)
        at org.geoserver.filters.XFrameOptionsFilter.doFilter(XFrameOptionsFilter.java:79)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1642)
        at org.geoserver.filters.GZIPFilter.doFilter(GZIPFilter.java:42)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1642)
        at org.geoserver.filters.SessionDebugFilter.doFilter(SessionDebugFilter.java:46)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1642)
        at org.geoserver.filters.FlushSafeFilter.doFilter(FlushSafeFilter.java:42)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1642)
        at org.eclipse.jetty.servlets.CrossOriginFilter.handle(CrossOriginFilter.java:311)
        at org.eclipse.jetty.servlets.CrossOriginFilter.doFilter(CrossOriginFilter.java:265)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1642)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1634)
        at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:533)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:146)
        at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
        at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:257)
        at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1595)
        at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255)
        at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1340)
        at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:203)
        at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:473)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1564)
        at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:201)
        at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1242)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:144)
        at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:220)
        at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:126)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
        at org.eclipse.jetty.server.Server.handle(Server.java:503)
        at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:364)
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:260)
        at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:305)
        at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)
        at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:118)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:765)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:683)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 969; The prefix "ogc" for element "ogc:Function" is not bound.
        at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
        at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
        at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
        at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
        at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
        at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
        at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
        at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
        at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
        at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
        at org.apache.xerces.jaxp.SAXParserImpl.parse(Unknown Source)
        at org.geotools.xsd.Parser.parse(Parser.java:235)
        at org.geoserver.wfs.xml.WFSXmlUtils.parseRequest(WFSXmlUtils.java:69)
        at org.geoserver.wfs.xml.v2_0.WfsXmlReader.read(WfsXmlReader.java:52)
        ... 98 more

Because I read "Request parsing failed" on the begin of this log I checked the syntax very often. But I find no error.
Why is it not possible to create a StoredQuery?


text:
Q: Test AdMob banner adViewWillPresentScreen method without creating false ad impressions I've implemented AdMob in to my application, but I'd like to ensure that the logic in the adViewWillPresentScreen: and adViewDidDismissScreen: methods are correct.
I have added my device's ID as a test device, so that I am only displayed test adverts. However, when I tap on the test advert, I am taken directly out of the app, rather than a screen (such as the App Store) being displayed. This means that the above methods are not being fired, and I am unsure how to test them without removing my device from the array of test devices and creating a false impression by tapping on one of my own ads - potentially repeatably while debugging.
Code creating banner:
let bannerView = GADBannerView(adSize: size)
bannerView.delegate = self
bannerView.adUnitID = "<redacted>"
bannerView.rootViewController = rootViewController
let request = GADRequest()
request.testDevices = [
    kGADSimulatorID,
    "<redacted>" // Test device
]
bannerView.loadRequest(request)

I have also tried an example adUnitID (ca-app-pub-3940256099942544/6300978111), which even when my device is not in the array of test devices displayed the example advert.


text:
Q: Can I get the number of Facebook Likes a page that is not on my domain received? Is it possible to get the number of Facebook Likes made on any url, even if I don't own that url's domain?

A: You can always try by searching the social graph.
For example, the Apple's Facebook page has about 162K likes
https://graph.facebook.com/108521342513509
But if you try to get the "likes" number directly, you don't get anything.
http://graph.facebook.com/108521342513509/likes
Here is the link to the documentation. You might try use the "search" URL.
http://developers.facebook.com/docs/api

A: Yes, you can query specific URLs:
https://api.facebook.com/method/fql.query?query=select%20like_count%20from%20link_stat%20where%20url=%27https://stackoverflow.com/%27&format=json

A: But ofcourse you can sir:
Page likes
If it's a page you're wanting the amount of likes of, try such a thing as this:
http://graph.facebook.com/[Page name or ID here without the brackets]?fields=likes
Example:
http://graph.facebook.com/Facebook?fields=likes
Result:
{
    "likes": 90064323,
    "id": "20531316728"
}

Specific URL likes
If it's a specific URL you want to get the likes of, try Facebook's FQL.
You can query the Facebook databases this way and get some info on URL's, here's an Example:
https://api.facebook.com/method/fql.query?query=select like_count from link_stat where url='https://www.facebook.com/'&format=json
Result:
[{"like_count":1433567}]

The format in which this is returned can either be XML or JSON, where XML is the default. You can chance the format by adding the
&format=json
at the end.
There are multiple fields and tables that can be queried from, you can see all that good stuff in the sources.
Hope this helped some people, cause I was searching quite abit for it.
Have a nice day.
Sources:
Graph API: http://developers.facebook.com/docs/reference/api/
FQL: http://developers.facebook.com/docs/reference/fql


text:
Q: Django error: save() got an unexpected keyword argument 'force_insert' I have been following along with the book Practical Django Projects. Very nice book, but it seem to have a lot of bugs. Luckily this website has some fixes: https://bitbucket.org/philgyford/practical-django-projects/src. My latest error is: save() got an unexpected keyword argument 'force_insert'
The original code was:
class Snippet(models.Model):
    title = models.CharField(max_length=255)
    language = models.ForeignKey(Language)
    author = models.ForeignKey(User)
    description = models.TextField()
    description_html = models.TextField(editable=False)
    code = models.TextField()
    highlighted_code = models.TextField(editable=False)
    pub_date = models.DateTimeField(editable=False)
    updated_date = models.DateTimeField(editable=False)
    objects = managers.SnippetManager()
    tags = TagField()

    class Meta:
        ordering = ['-pub_date']

    def __unicode__(self):
        return self.title

    def save(self, force_insert=False, force_update=False):
        if not self.id:
            self.pub_date = datetime.datetime.now()
        self.updated_date = datetime.datetime.now()
        self.description_html = markdown(self.description)
        self.highlighted_code = self.highlight()
        super(Snippet, self).save(force_insert, force_update)

    @models.permalink
    def get_absolute_url(self):
        return ('cab_snippet_detail', (), { 'object_id': self.id })

    def highlight(self):
        return highlight(self.code,
                         self.language.get_lexer(),
                         formatters.HtmlFormatter(linenos=True))

# See http://blog.sveri.de/index.php?/categories/2-Django
tagging.register(Snippet, tag_descriptor_attr='etags')

I changed the save method (trying to get rid of the error) to:
   def save(self, *args, **kwargs):
      if not 'force_insert' in kwargs:
         kwargs['force_insert'] = False
      if not 'force_update' in kwargs:
         kwargs['force_update'] = False
      # del kwargs['force_insert']
      if not self.id:
         self.pub_date = datetime.datetime.now()
      self.updated_date = datetime.datetime.now()
      self.description_html = markdown(self.description)
      self.highlighted_code = self.highlight()
      super(Snippet, self).save(*args, **kwargs)

I even tried uncommenting the # del bit, which also does not help. Im'm using Django 1.3.1. Any ideas why I'm getting this error?

A: The second version of your save override should be fine, though I would get rid of the two if statements and the del line.
If it still doesn't work, make sure you the development server is actually reloading the models.py file. The quickest way is to CTRL+C the running one and then call python manage.py runserver again. Although it shouldn't matter, you might want to also get rid of models.pyc as well (compiled version of models.py), just to be extra sure that the new code is running.
While Practical Django Projects is an excellent book overall, it's very outdated at this point. You might want to look for newer resources to learn from.


text:
Q: Navigate from @ondblclick event handler in Blazor (Server-Side) composing route dynamically I'm trying to navigate from a @ondblclick handler on a  element on Server Side Blazor, trying to open a detail page for each row.
This is the relevant code:
@inject NavigationManager nm
...
@for (var elem in elements)
{
    <tr @ondblclick="@(() => nm.NavigateTo("Cuenta/" + elem.Id.ToString()))">
    ...
    </tr>
}

but I'm always getting this exception:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot implicitly convert type 'void' to 'object''

I've also tryed this ways:
<tr @ondblclick="@(() => nm.NavigateTo("Cuenta/" + @elem.Id.ToString()))">
<tr @ondblclick="nm.NavigateTo("Cuenta/" + elem.Id.ToString())">
<tr @ondblclick="@(nm.NavigateTo("Cuenta/" + elem.Id.ToString())">
<tr ondblclick="@(() => nm.NavigateTo("Cuenta/" + elem.Id.ToString()))">

and probably others, but none seems to be correct, but extrangely if I do the following it works (but it's not usable=:
 <tr @ondblclick="@(() => nm.NavigateTo("Cuenta/123"))">

So, how can I use navigation manager to navigate directly from the template?
Edit: It seems it has something to do with "elem" being a dynamic object, since elements is a List of dynamics...

A: I think you need to instantiate a new instance of the elem.Id.ToString() inside the for loop something like
@inject NavigationManager nm
...
@for (var elem in elements)
{
    string tmpString  = elem.Id.ToString();
    <tr @ondblclick="@(() => nm.NavigateTo("Cuenta/" + tmpString))">
    ...
    </tr>
}

Hope this helps.
This is a standard C# behavior, not related to Blazor, where the lambda expression @(() => DoSomething(i)) has access to a variable and not to its value. You've got to define a variable which is local to your loop.


text:
Q: css: animate border on hover I'm trying to create menu with border (see http://multijuice.org/), and I need to move border on hover from active element to hovered. How I can do this? Maybe, anybody know some tutorials?
UPD: Done! See this js file for answer. Thanks all!

A: demo - http://jsfiddle.net/victor_007/gujrud4y/
You can use something like this but you need to change the position of underlined on every page or you can use jQuery to check which
 has active class and set accordingly

nav {
  text-align: center;
}
ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: inline-block;
  position: relative;
  font-size: 0px;
}
ul li {
  display: inline-block;
  padding: 8px 0;
  width: 80px;
  text-align: center;
  font-size: 15px;
  cursor: pointer;
}
span.border {
  height: 2px;
  background: red;
  width: 80px;
  position: absolute;
  left: 80px;
  bottom: 0;
  transition: .5s linear;
}
li:nth-child(1):hover ~ span.border {
  left: 0px;
}
li:nth-child(2):hover ~ span.border {
  left: 80px;
}
li:nth-child(3):hover ~ span.border {
  left: 160px;
}
li:nth-child(4):hover ~ span.border {
  left: 240px;
}

one

two

three

four

A: Try to change this css class in your code :
Changes this
#main-nav .current-menu-item a, #main-nav .current_page_item a, .selected{
     border-bottom: 3px solid #f5503b;
     padding-bottom: 72px;
     padding-left: 10px;
     padding-right: 10px;
}

to
#main-nav .current-menu-item a, #main-nav .current_page_item a, .selected, #main-nav li a:hover {
    border-bottom: 3px solid #f5503b;
}

And give the padding to the class .#main-nav li a like this :
#main-nav li a {
   border: 0 none;
   color: #111;
   display: block;
   height: 36px;
   line-height: 36px;
   margin: 0 10px;
   padding-bottom: 72px;
   padding-left: 10px;
   padding-right: 10px;
}


text:
Q: Inserting each element of array associated to an ID into a database table using codeigniter I have the following array with items selected from a multiple select box.
array (size=2)
    0 => string 'CABLES' (length=6)
    1 => string 'PCR' (length=3)

I'm trying to insert these values into a table "relacionproveedorfamilia" with the following structure
`idProveedor` int(11) NOT NULL,
`idFamilia` int(11) NOT NULL

So for idProveedor = 1, I need to insert the array values for all the items selected.
idProveedor         idFamilia
1                   1
1                   2
1                   ...

The thing is the values from the array (CABLES, PCR, etc) are stored in a different table called "familia" in which the have a different ID number then the numbers they have in the array.
id         clave        description
1          PCR          ...
2          CABLES       ...

In my controller, I get the ID for idProveedor and the array $nombresFamilia and I call the function $relacion_proveedor
$idProveedor = $this->Proveedormodel->get_idConsecutivo();
$nombresFamilia = $this->input->post('nombresFamilia');
$relacion_proveedor = $this->Proveedormodel->add_uk_proveedor_familia($idProveedor, $nombresFamilia);

This is the function I have in my model. First I get the id value from the table "familia" using the strings in the array and than I insert the value in the table "relacionproveedorfamilia".
function add_uk_proveedor_familia($id, $params){
    foreach($params as $clave){
        $valor = $this->db->query("SELECT id FROM familia WHERE clave= '$clave'");
        $vl = mysql_fetch_array($valor);
        $familia = $vl['id'];
        $this->db->query("INSERT INTO 'relacionproveedorfamilia' ('idProveedor', 'idFamilia') VALUES ('$id', '$familia')");
    }

}

When I try to submit the information I get the warning message:
Message: mysql_fetch_array() expects parameter 1 to be resource, object given
Filename: models/Proveedormodel.php
Line: $vl = mysql_fetch_array($valor);

Definitely the function in my model is wrong, how could I fix it?

A: CodeIgniter's $this->db object takes care of all the database stuff for you.  You don't need to call mysql_fetch_array().
function add_uk_proveedor_familia($id, $params){
    foreach($params as $clave){
        $valor = $this->db->query("SELECT id FROM familia WHERE clave= '$clave'");
        $vl = $valor->row_array();
        $familia = $vl['id'];
        $this->db->query("INSERT INTO 'relacionproveedorfamilia' ('idProveedor', 'idFamilia') VALUES ('$id', '$familia')");
    }
}

(See their documentation: https://www.codeigniter.com/user_guide/database/index.html)
I also suggest you use their "query builder" (previously called "active record") class.  Manually inserting variables into an SQL query is just asking for trouble.
function add_uk_proveedor_familia($id, $params){
    foreach($params as $clave){
        $this->db->select('id')->from('familia')->where('clave', $clave);
        $valor = $this->db->get();

        $vl = $valor->row_array();
        $familia = $vl['id'];

        $this->db->insert('relacionproveedorfamilia', array(
            'idProveedor' => $id,
            'idFamilia' => $familia
        ));
    }
}


text:
Q: Hanami rake task does not load repositories I have hanami 1.3.0 app named booking. There is rake task in /rakelib/motel.rake :
require_relative '../lib/booking' # it requires booking/motel/booker file

namespace :motel do
  task :book do
    Booking::Motel::Booker.new.book
  end
end

booking/motel/booker requires booking_repository file, and tries to instantiate BookingRepository, but fails with error:
NameError: uninitialized constant Hanami::Repository
<root>/lib/booking/repositories/booking_repository.rb:1:in <top (required)>'

However, when I run Booking::Motel::Booker.new.book in hanami console, it loads BookingRepository without problems.
Looked at numerous stack questions regarding hanami rake, but couldn't find an answer.

A: As it turns out, it was a foolish mistake. I forgot to add :environment to my task.
namespace :motel do
  task book: :environment do
    Booking::Motel::Booker.new.book
  end
end

That fixed it and dropped the need to use manual file loading, of course.


text:
Q: Simple Neural Network built from scratch is not learning I have implemented a neural network class that always has just a single hidden layer, using no libraries - not even numpy. I have done everything such the way that I understood it should be, but it is not learning at all, the loss is actually continuously increasing and I cannot find where I have gone wrong, even after looking at many examples online.
Here is my MLP class and a demo of it attempting to learn the XOR function:
import random
from math import exp

class MLP:

    def __init__(self, numInputs, numHidden, numOutputs):
        # MLP architecture sizes
        self.numInputs = numInputs
        self.numHidden = numHidden
        self.numOutputs = numOutputs

        # MLP weights
        self.IH_weights = [[random.random() for i in range(numHidden)] for j in range(numInputs)]
        self.HO_weights = [[random.random() for i in range(numOutputs)] for j in range(numHidden)]

        # Gradients corresponding to weight matrices computed during backprop
        self.IH_gradients = [[0 for i in range(numHidden)] for j in range(numInputs)]
        self.HO_gradients = [[0 for i in range(numOutputs)] for j in range(numHidden)]

        # Input, hidden and output neuron values
        self.I = None
        self.H = [0 for i in range(numHidden)]
        self.O = [0 for i in range(numOutputs)]

        self.H_deltas = [0 for i in range(numHidden)]
        self.O_deltas = [0 for i in range(numOutputs)]

    # Sigmoid
    def activation(self, x):
        return 1 / (1 + exp(-x))

    # Derivative of Sigmoid
    def activationDerivative(self, x):
        return x * (1 - x)

    # Squared Error
    def calculateError(self, prediction, label):
        return (prediction - label) ** 2

    def forward(self, input):
        self.I = input
        for i in range(self.numHidden):
            for j in range(self.numInputs):
                self.H[i] += self.I[j] * self.IH_weights[j][i]
            self.H[i] = self.activation(self.H[i])

        for i in range(self.numOutputs):
            for j in range(self.numHidden):
                self.O[i] += self.activation(self.H[j] * self.HO_weights[j][i])
            self.O[i] = self.activation(self.O[i])

        return self.O

    def backwards(self, label):
        if label != list:
            label = [label]

        error = 0
        for i in range(self.numOutputs):
            neuronError = self.calculateError(self.O[i], label[i])
            error += neuronError
            self.O_deltas[i] = neuronError * self.activationDerivative(self.O[i])
            for j in range(self.numHidden):
                self.HO_gradients[j][i] += self.O_deltas[i] * self.H[j]

        for i in range(self.numHidden):
            neuronError = 0
            for j in range(self.numOutputs):
                neuronError += self.HO_weights[i][j] * self.O_deltas[j]
            self.H_deltas[i] = neuronError * self.activationDerivative(self.H[i])
            for j in range(self.numInputs):
                self.IH_gradients[j][i] += self.H_deltas[i] * self.I[j]

        return error

    def updateWeights(self, learningRate):
        for i in range(self.numInputs):
            for j in range(self.numHidden):
                self.IH_weights[i][j] += learningRate * self.IH_gradients[i][j]

        for i in range(self.numHidden):
            for j in range(self.numOutputs):
                self.HO_weights[i][j] += learningRate * self.HO_gradients[i][j]

        self.IH_gradients = [[0 for i in range(self.numHidden)] for j in range(self.numInputs)]
        self.HO_gradients = [[0 for i in range(self.numOutputs)] for j in range(self.numHidden)]

data = [
    [[0, 0], 0],
    [[0, 1], 1],
    [[1, 0], 1],
    [[1, 1], 0]
]

mlp = MLP(2, 5, 1)

for epoch in range(100):
    epochError = 0
    for i in range(len(data)):
        mlp.forward(data[i][0])
        epochError += mlp.backwards(data[i][1])
    print(epochError / len(data))
    mlp.updateWeights(0.001)

A: If I understood your implementation correctly, then your problem I believe is in the calculation of the weight updates in the backwards function, the update should be the error (not error squared) multiplied by the sigmoid derivative, so I would take a look/redo the calculations.

A: How did you go with this?  I showed it to a friend - we both found your goal of doing the algorithm without much abstraction was edifying, although trying to find errors is difficult.
The improvement he found is that updateWeights needs to be a negative feedback loop, so change "+=" to "-=" in two lines giving:
self.IH_weights[i][j] -= learningRate * self.IH_gradients[i][j]

and
self.HO_weights[i][j] -= learningRate * self.HO_gradients[i][j]

The other factor is increasing the learning rate. With these changes, the error descends to about 16% (for me, I may have made another change that I am not seeing) before it begins to climb asymptoting to 27% - maybe due to overtraining with a learning rate that is too high.
I made the learning rate dependent on the epoch
mlp.updateWeights(0.1/(0.01 * (epoch+1)))

and its decreases steadily and stabilizes at 0.161490...
But if you get the prediction from 'forward', its always predicting 0.66 - the inputs have been wiped away.  So... that's bad.
 - Input Data: [0, 0] | Prediction: [0.6610834017294481] |Truth: 0
 - Input Data: [0, 1] | Prediction: [0.6616502691118376] |Truth: 1
 - Input Data: [1, 0] | Prediction: [0.6601936411430607] |Truth: 1
 - Input Data: [1, 1] | Prediction: [0.6596122207209283] |Truth: 0


text:
Q: Remove the page title from the taskbar, but not the tabs Is there a setting, tweak, script, plugin or whatever that allows me to remove the active page title from the Windows XP task bar, but at the same time keep the titles of all pages in the tabs?
So, I want to keep this title:

But, I'd ideally like this one to just be reset to "Mozilla Firefox":

A: You can change your window title with Nightly Tester Tools.
There is also Customize Titlebar but you have to manually edit some files in .xpi package to work with firefox 4. And it may cause some troubles because it is not natively compatible with firefox 4.

A: This might be a little more than you want to spend, but Windows 7 does this quite well. The Home Premium upgrade is $129.99 and if you have a fairly modern system and at least 2GB of RAM, I think you'll enjoy that tweak among others without having to load too many auxiliary programs to get the same functionality under XP.
;)


text:
Q: Don't stop the Chronometer when I change the activity For example: in the Activty A I have a Chronometer, I click on play to start it and when it arrives at 00:00:10 I decide to go to Activity B. I stay on it for 30 seconds before returning to A. I would find the timer paused still displaying 00:00:10, but I'd like to see  it still running and then at 00:00:40. How can I do this? How can I avoid the timer pausing on  the change of Activity?

A: (Based on the answer given for Get time of chronometer widget, with code for and extra activity added.)
The main activity:
package com.so.chilledrat.chronoexample;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.LinearLayout;
import android.widget.Toast;

public class ChronoExampleActivity extends Activity {
    Chronometer mChronometer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

        mChronometer = new Chronometer(this);
        layout.addView(mChronometer);

        Button startButton = new Button(this);
        startButton.setText("Start");
        startButton.setOnClickListener(mStartListener);
        layout.addView(startButton);

        Button stopButton = new Button(this);
        stopButton.setText("Stop");
        stopButton.setOnClickListener(mStopListener);
        layout.addView(stopButton);

        Button resetButton = new Button(this);
        resetButton.setText("Reset");
        resetButton.setOnClickListener(mResetListener);
        layout.addView(resetButton);

        Button switchButton = new Button(this);
        switchButton.setText("Switch Activity");
        switchButton.setOnClickListener(mSwitchListener);
        layout.addView(switchButton);

        setContentView(layout);
    }

    private void showElapsedTime() {
        long elapsedMillis = SystemClock.elapsedRealtime() - mChronometer.getBase();
        Toast.makeText(this, "Elapsed milliseconds: " + elapsedMillis, Toast.LENGTH_SHORT).show();
    }

    View.OnClickListener mStartListener = new OnClickListener() {
        public void onClick(View v) {
            mChronometer.start();
            showElapsedTime();
        }
    };

    View.OnClickListener mStopListener = new OnClickListener() {
        public void onClick(View v) {
            mChronometer.stop();
            showElapsedTime();
        }
    };

    View.OnClickListener mResetListener = new OnClickListener() {
        public void onClick(View v) {
            mChronometer.setBase(SystemClock.elapsedRealtime());
            showElapsedTime();
        }
    };

    View.OnClickListener mSwitchListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(ChronoExampleActivity.this.getBaseContext(), OtherActivity.class);
            startActivityForResult(myIntent, 0);
        }
    };
}

The other activity to switch to:
package com.so.chilledrat.chronoexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class OtherActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

        Button switchButton = new Button(this);
        switchButton.setText("Switch Back");
        switchButton.setOnClickListener(mSwitchListener);
        layout.addView(switchButton);

        setContentView(layout);
    }

    View.OnClickListener mSwitchListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // Intent myIntent = new Intent(OtherActivity.this.getBaseContext(),
            // ChronoExampleActivity.class);
            // startActivityForResult(myIntent, 0);
            finish();
        }

    };
}

And finally the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.so.chilledrat.chronoexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="7" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ChronoExampleActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="OtherActivity"></activity>
    </application>

</manifest>


text:
Q: SQL check if a record has a reference from another table and if so do something I have two tables, users and friendships
id   |  name   | password
-------------------------
 1    |  Dave   | 1234
-------------------------
 2    |  John   | abcd
-------------------------
 3    |  Bob    | xyz
-------------------------

and the friendships
 friend_one   |  friend_two   | status
 -------------------------------------
       1      |      1        |   me
 -------------------------------------
       2      |      2        |   me
 -------------------------------------
       3      |      3        |   me
 ------------------------------------
       1      |      2        | pending
 -------------------------------------
       3      |      1        | active

Now whenever a user logged in to the system, I need to fetch all the users in the database, also I need to add an extra column to the result from the select query, which shows the friendship status with currently logged in user.
For example, user id 1 , Dave logged in to the system and request for users list, select query should be output as below,
id   |  name   | password  | friend_status
------------------------------------------
 1    |  Dave   | 1234     |   me
------------------------------------------
 2    |  John   | abcd     |   pending
------------------------------------------
 3    |  Bob    | xyz      |   active
------------------------------------------

When the user id 2, John logged in to the system, he need to get the below table,
 id   |  name   | password  | friend_status
------------------------------------------
 1    |  Dave   | 1234     |   pending
------------------------------------------
 2    |  John   | abcd     |   me
------------------------------------------
 3    |  Bob    | xyz      |   null
------------------------------------------

Is this even possible ? I tried to join tables and use a nested query
For example, with the below query I can get all the friendships for the currently logged in user,
select * from friendships
where friend_one = 2 or friend_two = 2

But I don't understand what to do next. I tried to put this as a nested query of the main select query and tried to join tables but I'm not getting what I wanted.
Can anyone give me an idea?

A: You need to CROSS JOIN the list of id values from users with the users table to get all distinct pairs of id values, then LEFT JOIN that to the friendships table to get the friend status for each user:
SELECT u1.id, u.name, u.password,
       f.status
FROM users u
CROSS JOIN (SELECT DISTINCT id
            FROM users) u1
LEFT JOIN friendships f ON f.friend_one = u.id  AND f.friend_two = u1.id
                        OR f.friend_one = u1.id AND f.friend_two = u.id
ORDER BY u1.id, u.id

Output:
id  name    password    status
1   Dave    1234        me
1   John    abcd        pending
1   Bob     xyz         active
2   Dave    1234        pending
2   John    abcd        me
2   Bob     xyz         (null)
3   Dave    1234        active
3   John    abcd        (null)
3   Bob     xyz         me

Demo on SQLFiddle
To get a specific user, just add WHERE u1.id = ? before the ORDER BY clause.