Q:

Terminate program when Close button is Clicked after Prompt - Visual Basic

I have two forms in my WindowsFormApplication named as Form1 and Form2. The idea is when the Program is being closed, it shows up a Dialog Box to confirm it.
 Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Form2.Show()
        Me.Close()
    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        MessageBox.Show("You are About to cancel the Setup.","Cancel Setup?",
        MessageBoxButtons.OK,
        MessageBoxIcon.Exclamation,
        MessageBoxDefaultButton.Button1)
    End Sub
End Class

Until here, my code worked fine but the problem is when I click Button1, the Message Box appears to confirm the closure of Form1.
I don't want this to happen so then I tried changing Me.Close() to Me.Hide. I was successful for preventing the message box to appear but then I got another Problem. As the Form hides, it stays active in the background and I also don't want this to happen.
Another thing I added in Form1_FormClosing is Me. Close and Form2.Close. This enables to close both the forms once the program's active Form is being closed. But Again, there's a problem. As soon as I click the close button, the Message Boxes fill up the screen and not listening to my Command. Anyone got a solution for this?

A:

So..
If the user clicks close in Form1, then the program should terminate with no messagebox.
If the user clocks close in Form2, Form3 or Form4, the program would Terminate when the user clicks Yes in the MessageBox or else nothing would get affected (Especially the Data).

The way this works is when user clicks Close in Form1, the program terminates with no MessageBox and if the user clicks Close in other Forms, A MessageBox would appear asking whether you are sure to close the Program. If the user  clicks Yes, the program will Terminate because the DialogResult is Yes and Form1.Closing Cancel goes to False and Closes Form1(As Closure type was set as First Form Closes in Program Properties, this will terminate the program) Else the Form1.Closing Cancel goes to True which will prevent the current Form from closing and losing any Data.

This code goes to Form1:
Imports System.ComponentModel

Public Class Form1
    Friend closeProgramAlreadyRequested As Boolean = False

    Private Sub Form1_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        closeProgramAlreadyRequested = False
    End Sub
End Class

This code goes to Form2 & applies to other Forms as well but except for Form1:
Imports System.ComponentModel

Public Class Form2
    Private Sub Form2_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    If Form1.closeProgramAlreadyRequested = False Then
        Dim result As DialogResult = MessageBox.Show("You are About to cancel the Setup.", "Cancel Setup?", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
        If result = DialogResult.No Then
            e.Cancel = True
        Else
            e.Cancel = False
            Form1.Close()
        End If
    End If
End Sub
End Class


Q:

Is master of the nine a solid prestige class for a swordsage?

As the title suggests, i am going to play a swordsage, and while i am not a big fan of multiclassing (many of the character optimisation builds i saw had from three to 5 classes, prestige or not), i really like the idea of a master of the sublime way that incorporates all the nince disciplines into a "formless" one (at least this will be my fluff for it).
So, what i am asking is if the Master of the Nine is a solid choise for a prestige class, on a strength based swordsage built to be a front line fighter. Also, if any one has a swordsage handbook that is complete, and does not have only two weapon fighting builds, he would be more than welcome to share it with me.

A:

Not really, until high levels. As written, it's designed to blend classes and seems to have very steep requirements such that many dips are typically necessary to enter it in any reasonable timeframe. Take a look at the shadow sun ninja, as that seems to feature in many swordsage builds.
Examining links here, here, here, and here.
The only text on master of nine seems to be:

Hypothetical builds on the boards tend to time this class for late in the build so as to acquire high level maneuvers.  But if you're not starting at a high level then entering early has its benefits (e.g. I'm a big fan of Dual Stance so would want it asap), and it gives you full progression of your likely ultiple Martial Adept classes ready to re-enter them for some higher level maneuver swaps.  In practice I would compromise, take 2/3 MoN levels as early as I could manage and then leave the rest for high level maneuver acquisition and a high level stance of choice (nb: 8th level maneuvers are often better than the 9th level ones imho).
Counter Stance + Stance of Alacrity combo
Mastery of Nine: ready at start of day from as many disciplines as possible to maximize bonus, then spend 5 minutes changing them as desired.

Looking at the literature, there seem to be no builds that are strongly Swordsage and master of nine. If you're looking to be a frontline swordsage ... Here are some builds:

The galaxy
Heaven of Nine
Master of nine/swordsage dominant, but not int-high
Another dex-high. Are you  sure you want to play a str-high swordsage?
Str high, swordsage ninja, eventually.

My suggestion, click through here and see what catches your eye.


Q:

Objective-c [iOS разработка] работа с таблицами

Доброе время суток всем пользователям данного сайта!
У меня возникла проблема при разработке под iOS одной программы, в общем у меня есть два ViewController'a, на одном из них у меня таблица с записями, а на другом детальное отображение записей, собственно переход по ячейке приводит к подробной записи с рисунком и т.д.
Собственно суть проблемы. Мне нужно сделать так как в приложении Notes на iPhon'e/iPod'e. Что бы я с детального контроллера мог переключать записи по кнопке, как это можно реализовать?
Буду очень благодарен вам за помощь!

A:

Можно попробовать следующим образом

UITableViewController со списком свех заметок
Subclass of UIPageViewController (MYNotesPageController) с кастомным методом - (id)initWithNotes:(NSArray *)items initialIndex:(NSInteger)index (либо заправшиваем все объекты MYNote из CoreData через NSFetchedResultsController или как-то еще)
MYNoteDetailsVC с методом - (id)initWithNote:(MYNote *)note - контроллер отображение каждой конкретной note
Добавляем логику в UIPageController для смены страниц - объектов MYNoteDetailsVC

в контроллере со списком заметок
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
     {
    MYNotesPageController *pageVC = [[MYNotesPageController alloc] initWithNotes:self.items initialIndex:indexPath.row];
    [self.navigationController pushViewController:pageVC];
    }

либо еще вариант вместо UIPageViewController можно использовать UICollectionViewController где каждая UICollectionViewCell и будет представлять из себя note editor. Этот метод проще, но может быть не так функционален, как через UIPageViewController
и самый просто способ:
пусть MYNoteEditorVC -  котроллер/эдитор для заметки
в нем
@property (nonatomic, string) NSArray *notes; // все заметки

добавляем метод
 - (void)reloadDataForNote:(MyNote *)note

который будет перегружать содержимое контроллера под новую заметку
дальше когда выбираем следующую или предыдущую заметку примо внутри этого контроллера
 - (IBAction)nextNotePressed
 {
if (self.currentNoteIndex + 1 < self.notes.count) {
MYNote *nextNote = self.notes[self.currentNoteIndex + 1];
self.currentNoteIndex++;
[self reloadDataForNote:nextNote];
}
}


Q:

Changing Users Context

I'm using the MVC4 Internet Application and I am trying to change the account model to use my context. I cannot seem to get it to work. I tried to delete the context and include the user profile in my context and I could log on etc but when I check for profiles by user id it returns a null value.
public DbSet<FightCard> FightCards { get; set; }
public DbSet<Fight> Fights { get; set; }
public DbSet<Fighter> Fighters { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }

}

When I try to do this:
public ActionResult Profile(int id)
    {
        UserProfile profile = uc.UserProfiles.Find(id);
        ViewBag.Name = profile.UserName;
    }

I get a null value return. Anyone know how to successfully use the simple membership with a different context?

A:

Solved it there. But to be honest I'm not exactly sure what fixed it. Here is the link I used and one part of it solved my problem.
http://dansgreenshoes.com/2013/03/10/mvc4usertable/


Q:

WPF ListView - is it better in Visual Studio 2010?

I've tried implementing a readonly grid of items using the WPF ListView.
It appears to me that this is a poorly designed and implemented control. (Unlike most of WPF which I like).
Specific issues I've come across:

Cannot make the last column expand to
fill the width of the control,
without writing extra non-XAML code.
(See  this question )
Have to override some arbitrarily hard-coded values to get a cell template to actually fill the area of a cell. (See  this blog entry)

To me, these are pretty obvious flaws, implying that this control was rushed through into Visual Studio 2008.
Does anyone know if these have been fixed in Visual Studio 2010?

A:

Have you checked out the WPF Toolkit?
It has a DataGrid control that does a lot more out of the box than ListView/GridView.
http://wpf.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=29117
Regarding your particular concerns, though, I'm not sure there's an automatic way to make the last column fill the remaining width of the container (the default is for a "blank" column to fill up the remaining space) [correction: see Edit below]. I do know you there is a Visiblity property for the columns, though, which is a huge improvement IMO.
I do have some examples of DataGrid that have specially colored cells, and the color goes right up to the edges of the cell, so I think your second concern should be doable.
Just as an example, here's my cell colorizer style:
<Style
    x:Key="Main_DataGridCellStyle"
    TargetType="mwc:DataGridCell">
    <Setter
        Property="BorderThickness"
        Value="0" />
    <Setter
        Property="Background"
        Value="{Binding XPath=@Background}" />
    <Setter
        Property="Foreground"
        Value="Black" />
</Style>

Also, the DataGrid sorts automatically, although I did have to do some pretty heavy template editing to get the arrows to appear correctly :( Hopefully this will be fixed by the time VS10 comes out--I'm pretty sure the community is aware of it.
Edit
I stand corrected (in a good way). I just tried Width="*" with the last column in a test DataGrid and it worked like a charm.
Also, this link confirms that DataGrid will be part of WPF 4.0, which is part of VS 2010:
http://weblogs.asp.net/scottgu/archive/2009/10/26/wpf-4-vs-2010-and-net-4-0-series.aspx


Q:

Perl modifying hash reference in subroutine

I am having trouble understanding the hash references and changing the hash in place, instead of returning it. I want to write a sub routine which will return a value from hash and also modify the hash. I was facing some issues while coding for it. So, I wrote the following basic code to understand modifying the hash in place.
#!/usr/local/bin/perl
#Check hash and array references
#Author: Sidartha Karna
use warnings;
use strict;
use Data::Dumper;

sub checkHashRef{
   my ($hashRef, $arrVal) = @_;
   my %hashDeref = %{$hashRef};

   $hashDeref{'check'} = 2;
   push(@{$arrVal}, 3);

   print "There:" ;
   print Dumper $hashRef;
   print Dumper %hashDeref;
   print Dumper $arrVal

}

my %hashVal = ('check', 1);
my @arrVal = (1, 2);

checkHashRef(\%hashVal, \@arrVal);

print "here\n";
print Dumper %hashVal;
print Dumper @arrVal;

The output observed is:

    There:$VAR1 = {
          'check' => 1
        };
    $VAR1 = 'check';
    $VAR2 = 2;
    $VAR1 = [
          1,
          2,
          3
        ];
    here
    $VAR1 = 'check';
    $VAR2 = 1;
    $VAR1 = 1;
    $VAR2 = 2;
    $VAR3 = 3;

From the output, I inferred that, changes to hashDeref are not modifying the data in the reference. Is my understanding correct? Is there a way to modify the hash variable in place instead of returning it.

A:

This is making a (shallow) copy of %hashVal:
my %hashDeref = %{$hashRef};

The hash-ref $hashRef still points to %hashVal but %hashDeref doesn't, it is just a copy. If you want to modify the passed hash-ref in-place, then work with the passed hash-ref:
sub checkHashRef{
   my ($hashRef, $arrVal) = @_;
   $hashRef->{'check'} = 2;
   #...

That will leave your changes in %hashVal. In the array case, you never make a copy, you just dereference it in-place:
push(@{$arrVal}, 3);

and the change to $arrVal shows up in @arrVal.


Q:

Table-per-type inheritance insert problem

I followed this article on making a table-per-type inheritance model for my entities, but I get the following error when I try to add an instance of a subclass to the database.
Here is how I create the subtype:
var cust = db.Users.CreateObject<Customer>(); // Customer inherits User
db.Users.AddObject(cust);
db.SaveChanges();

I get the following error when I make that last call:
"A value shared across entities or associations is generated in more than one location. Check that mapping does not split an EntityKey to multiple store-generated columns."
With the following inner exception:
"An item with the same key has already been added."
Any ideas on what I could be missing?
UPDATED WITH REPRO STEPS
Created a blank MS SQL Server 2008 R2 database, and added the following two tables:
Users

Id : bigint (PK and set it as the identity column)
Name : nvarchar(25) NOT NULL (whatever, some random property

Customers

Id : bigint (PK, identity column, and FK on Users.Id)
Title : nvarchar(25) NOT NULL (also whatever, some random property)

Next I generated the .edmx entity model from the database, and followed the link at the top verbatim. That is to say, I deleted the association between User and Customer, set User as the base class of Customer, deleted the Id property from the Customer entity, and made sure that the Customer.Id column was mapped to the inherited User.Id property. I then ran the following small program:
using (var db = new EF_Test.testEntities())
{
    var cust = db.Users.CreateObject<Customer>();
    db.Users.AddObject(cust);
    db.SaveChanges();
}

I get the same exceptions I described above. Please let me know if this repro works for you, and if it does, what I'm doing wrong. I'm blocked on this issue.

A:

I finally found the source of my troubles. For those still interested, in the Customers table, the Id column should not have been set to the identity column of the table (PK and the FK dependency are fine though).


Q:

imageview not showing

I have this code to save the Uri of and image in shared preferences:
    // Save to settings
// imageReturnedIntent is the intent of selecting the image from the gallery
Uri selectedImage = imageReturnedIntent.getData();
    SharedPreferences sharedPref = getSharedPreferences("myfile", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("bannerImage2" , selectedImage.toString());
    editor.commit();

I have an imageview in the main activity, when the above code runs in the setting page, I go back to the main page the image is displayed correctly, but if I close the application and open it again, the image is not displayed even though that the Uri is loaded correctly.
I load the image in onResume() and I tried:
// IMAGE_LOGO is of type Uri
    imgLogo.setImageURI(IMAGE_LOGO);
Also tried to use Picasso library,
Also I tried to validate the image view again using
 imgLogo.invalidate();

The Uri returned is :
content://media/external/images/media/102124

A:

Your code is working you just need to get Read_External_Storage Permission as API level 23 requires this. To request permission on runtime you can referr to this document https://developer.android.com/training/permissions/requesting.html.


Q:

With ember-data is there a method for querying locally available objects?

I have created a model that is populated locally on the client, upon initializing the application.
The findQuery method always does an ajax request, for example:
App.store.find(App.Person, {name: 'John'})

even in the case where an App.Person with name:John has already been loaded. The find method which takes an id, looks at the local storage first. But I need to be able to perform queries by attribute.
My question is whether there exists a method for performing queries strictly on locally available data.

A:

Use the DS.Store#filter method. A basic example is shown in the README on https://github.com/emberjs/data, section Filtering Loaded Records.


Q:

OBSOLETE - Stack Exchange Notifier Chrome Extension

Obsolete: Links are dead; no source code.

About
Stack Exchange Notifier is a handy extension for Google Chrome browser that displays your current reputation, badges on Stack Exchange sites and notifies you on reputation's changes. You will now get notified of comments on your own posts (questions and answers) and of any comments that refer to you by @username in a comment, even if you do not own the post (aka mentions).
All Stack Exchange sites are supported.
Screenshots

Access
Install extensions from Google Chrome Extension Gallery
Platform
Google Chrome browser extension
Contact
Created by me (Vladislav Tserman). I'm available at: vladjan (at) gmail.com
Follow Stack Exchange Notifier on twitter to get notified about news and updates: http://twitter.com/se_notifier
Code
Written in Java, Google Web Toolkit under Eclipse Helios.
Stack Exchange Notifier uses the Stack Exchange API and is powered by Google App Engine for Java.
Changelog
I will be porting extension to not use app engine back-end due to some limitations.  New versions of the extension will be making direct calls to Stack Exchange API right from your browser. Please do not expect new versions of the extension any time soon. Sorry.
Read more about limitations here Google App Engine [app]s - We are all on the same quota! and here https://stackoverflow.com/questions/3949815
Currently, you may sometimes experience some issues using extension, but most users will have no problems. You may notice too many errors in the logs, but there is nothing I can do with this now.  Thanks for using my little app,  thanks to all of you it still works in spite of many issues with API
Version 1.2.9.3 - Thursday, October 14, 2010
- Bug fix release (back-end improvements)
Version 1.2.9.2 - Thursday, October 07, 2010
- Bug fix release (high rate of occasional API errors were noticed so some fixes added to handle them were possible)
Version 1.2.9.1 - Tuesday, October 05, 2010
- Mostly bug fix release, back-end performance improvements
- You will now get notified of comments on your own posts (questions and answers) that are not older than 1 year and of any comments that refer to you by @username in a comment, even if you do not own the post (aka mentions). This is experimental feature, let me know if you like/need it.
- New 'All sites' view displays all websites from Stack Exchange network (part of new feature that is not finished yet)
Version 1.2.9 - Saturday, September 25, 2010
- Fixes an issue when some users got empty Account view.
- When hovering on @Username on account view the title now displays '@Username on @SiteName' to easily understand the site name
Version 1.2.7 - Wednesday, September 22, 2010
- Fixed an issue with notifications.
- Minor improvements
Version 1.2.5 - Tuesday, September 21, 2010
- Fixed an issue where some characters in response payload raised an exception when parsing to JSON.
v1.2.3 (Sunday, September 19, 2010)
- Support for new OpenID providers was added (Yahoo, MyOpenID, AOL)
- UI improvements
- Several minor defects were fixed
v1.2.2 (Thursday, September 16, 2010)
- New types of notifications added. Now extension notifies you on comments that are directed to you. Comments are expandable, so clicking on comment title will expand height to accommodate all available text.
- UI and error handling improvements
Future

Application still in beta stage. I hope you're not having any problems, but if you are, please let me know. Leave your feedback and bug reports in comments. I'm available at: vladjan (at) gmail.com.
I'm working on adding new features.
I want to hear from the users and incorporate as much feedback as possible into the extension.
Any suggestions for improvements/features to add?

A:

I'm new to SEApps, and given the design of it, I apologize if bug reports are not supposed to be "Answers". Please let me know and I'll move it to the OP comments.
That having been said, I just installed this extension, and have a problem. Why can't I manually specify an OpenID in the extension configuration? I don't use a common vendor, I have my own.

A:

I think it is better to change the title of the "username" from "username" to "site name" in the "Accounts" page. It will help peoples to understand the site name easily.

A:

This is a very slick, awesome-looking extension with lots of potential.
My main feature request would be for the ability to be notified of changes to any question (not just your own), the way that StackStalker does it. This would be great since it looks like StackStalker's author has lost interest in it and hasn't added support for arbitrary Stack Exchange sites yet.
Keep up the great work!


Q:

How to use HttpWebRequest to login to website?

I am trying to rewrite some server php code which logs into a website, using the canonical HttpWebRequest usage found all over the net on C# sites:
HttpWebRequest BuildPOST(string url, string parameters)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    byte[] bytes = Encoding.ASCII.GetBytes(parameters);
    Stream os = null;
    try
    {
         request.ContentType = "application/x-www-form-urlencoded";
         equest.ContentLength = bytes.Length;
         os = request.GetRequestStream();
         os.Write(bytes, 0, bytes.Length);
    }
    catch (WebException ex)
    {
         Console.WriteLine("{0} HttpPost: Request error", ex.Message);
    }
    finally
    {
         if (os != null)
         {
              os.Close();
         }
    }
    return request;
}

called using:
string login_url = "http://www.sailonline.org/community/accounts/login/";
string login_post_data = "next=/windy/run/{0}/&password={1}&username={2}";  // race, pwd, boat
HttpWebRequest req = BuildPOST(login_url, string.Format(login_post_data, race, pwd, user));

The original php is:
include 'phplib.php';

$url = "http://www.sailonline.org/community/accounts/login/";
$postdata = sprintf("next=/windy/run/%s/&password=%s&username=%s", $race, $key, $boat);
$html = get_pipe_output(build_post_url($url, $postdata));

However, the C# code does not generate the same response from the server as the php code. Instead I get a page asking for login details (which were correctly input in the post to begin with).
I am somewhat new to network programming, and just cannot seem to figure out why this is happeneing. I have snooped the packets from my code, the page serving the php and the original login page on the website in question and cannot see any difference betwen the requsts, only that the one issued from C# code does not have the expected response.
All I can think is perhaps the php functions do something I am unaware of ??

A:

You need to create and set a CookieContainer on the request. Without that your request wont succeed. Looks like the page is sending cookies with the response.
HTTP/1.1 200 OK
Date: Mon, 31 Jan 2011 23:53:23 GMT
Server: Apache
Expires: Mon, 31 Jan 2011 23:53:23 GMT
Vary: Cookie
Last-Modified: Mon, 31 Jan 2011 23:53:23 GMT
ETag: "ad806aa693ed8187c278f0fadfa92d01"
Cache-Control: max-age=0
Content-Type: text/html; charset=utf-8
Set-Cookie:  sailonlinesid=bcc2b5fe9980df3e741e8fe7279d61d4; Domain=.sailonline.org; expires=Mon, 14-Feb-2011 23:53:23 GMT; Max-Age=1209600; Path=/
Connection: close


Q:

Rename causes "You can't open the application "XXXXX" because it may be damaged or incomplete." after updating to Xamarin.Mac

Edit: Turns out this was not a codesigning issue, so I'm updating to help anyone who runs into the same problem.
After updating a MonoMac app to Xamarin.Mac, if I changed the name of the app, I would get the message "You can't open the application "XXXXX" because it may be damaged or incomplete." It looks like it could be a codesigning issue because when I would run codesign --verify I would get code object is not signed at all.
Original question:
I recently updated a MonoMac app to Xamarin.Mac. In the process, something in the codesigning step seems to have changed. Specifically, now when I rename the app bundle, I get codesigning signature errors, both from the GUI and from the command line tools. It seems that if the app bundle does not match CFBundleName, the signature isn't valid.
For example, if I run codesign --verify --deep -vvvv Program.app (where Program matches the CFBundleName, I get
Program.app: valid on disk
Program.app: satisfies its Designated Requirement

However if I change the name to Program2.app and run codesign --verify --deep -vvvv Program2.app, I get:
Program2.app: code object is not signed at all

Move it back, and I get a successful signature again.
From looking at the MonoMac app vs. the Xamarin.Mac app, there are a few differences:

archived-expanded-entitlements.xcent is now placed in Contents/Resources
Info.plist gets compiled to some binary-ish version.
Contents/MonoBundle now includes libMonoPosixHelper.dylib, which apparently needs signing.
PkgInfo is now included in Contents, with contents APPL????

Why do the codesigning tools care about the name of the app all of a sudden? How can I make it not care about the name?

A:

It turns out that the problem was a change in the update from MonoMac to Xamarin.Mac that somehow set it to look for the executable to be named the same as the app bundle, so if you changed Program.app to Program2.app, OS X would look to run Contents/MacOS/Program2 instead of Contents/MacOS/Program. I'm still not sure why the MonoMac version worked when renamed, but clearly it had some other pointer to the correct executable file.
The solution for Xamarin.Mac is to add
<key>CFBundleExecutable</key>
<string>[Original app name]</string>

to Info.plist. This tells OS X where to look for the executable, and allows you to rename the app without issue.


Q:

"But I copied that from a book-reference you gave! How can that be wrong?", or how can you grade homework which is solved poorly in some book?

Sometimes when assigning homework, it is possible that the homework can be found in some books or lecture notes, sometimes even referenced by yourself.
As long as the proofs and arguments there are good and/or students bring up their own thoughts about the question, there is nothing bad in grading it.
The problem comes up if there is a bigger part missing in reference book or if there is even something wrong there and students copy that without adding the missing parts (One time, a whole course with more than 80 students did exactly copy a solution which was solved in some lecture note with a contradiction proof, but the contradiction did only cover a small part of the statement. Only very few students got that.).
The question is now: How should one grade such solutions? If you do not give full credit, how can you explain that the students without making them angry (Since you gave that particular book as reference)?
The question is related to How to assign homework when answers are freely available or attainable online?.

A:

Students are used to other people being the source of truth.
Even in an algebra class, they will do something (incorrect, at least in the common context) like this:

$(x + 3)^2 = x^2 + 9$

and then ask me if it is correct, or if it actually goes a different way. The implication is that I know the truth and they cannot know it without me. My goal then becomes the following: show the students that they can independently identify objective truths.
So, I think the answer here is the same as it is there: Regardless of what is printed in some book or another, the correctness of a proof is essentially an objective fact -- one that they must learn to measure themselves. This is a difficult point! The students may rebel and use the book as evidence that the truth is in fact subjective, determined by a semi-arbitrary grader. This is the underlying misunderstanding to dispel.

A:

Make clear that the "make sure the proof is correct" is part of the work to be done in the homework. If it is my proof, or yours, or from <famous textbook> that is wrong, the answer is wrong.
(Yes, need to emphasize that even the above cited authorities get it wrong sometimes).

A:

By recommending some book you implicitly acknowledge all of its contents (unless specified otherwise). In fact it would be similar if the student used a solution you presented, which happens to be wrong, but you only discovered the flaw when grading the exam. What would you do?
First, I would not penalize the student for copying the solution from the book, actually I would deal with it as if the student happen to write exactly the same solution by himself/herself. The reason is that the modern math is built upon previous results and reinventing the wheel is not a good strategy.
Then, there are three solutions I would consider:

Give full credit. The solution might be wrong, but you don't expect the students to recognize the difficulty (perhaps even the teacher missed it at first). One can give bonus points to those who did.
Give partial credit. The fact that some respectable author got it wrong is some indication that it might be a "reasonable mistake", that is, the approach could be mostly correct but for some subtlety that is non-intuitive and hard to spot. Partial credit is always tricky, though.
Grade it like everything else (perhaps no credit). Wrong solution is not a valid solution independent of where it comes from. If the students think the solution is good enough to copy it, they are wrong and should be graded accordingly.

My preferred one is the third: in math the meaning of authority is slightly different than in other areas and students should understand that nobody is exempt from following only valid inferences. On the other hand, it would be weird to enforce this rule unless you told the students about it.
Partial credit is the most common solution from my experience. Many professors grade not only what was written down, but also what kind of understanding the work implies. The solution might be incorrect, but the intuition behind it might be still valid. However, it is inherently hard to grade understanding and what is obvious from one perspective might be difficult from another point of view. The fact that the book's author got it wrong suggests that there is some other intuition that works just as good as yours (e.g. the rest of the book is great), but handles this particular case badly. Therefore, it could still seem like an obvious mistake to me, but I might opt to give some more points nevertheless.
Rarely, but it happens, you may want to give full credit. I don't like it, but I see why someone might want to use this solution. One case is when you don't want to bother students with subtleties, for example

in some engineer classes, where theory is secondary at best, you could accept solutions that miss the fact that some matrix could be singular in a problem where a random distortion of input data fixes the problem;
in a discrete math course, some series-related theorems work only with proper convergence arguments, however, appropriate techniques/formalizations might be too hard or not that important (e.g. the topic wasn't covered in depth); a correct, formal solution would be to guess the result using the incorrect derivation, and then proceed by induction (or whatever), but some deem such a level of scrutiny unnecessary.

Another case is when the problem set wasn't tested enough. There was an exam once in my student times where the lecturers did a mistake about what works and what does not. In result, one task came out much, much harder than it was meant to be. Most students missed the subtlety (i.e. used the same solution that the lecturers thought it worked), others did notice and presented a counterexample. There was an announcement and both types were accepted with a perfect score.
I hope this helps $\ddot\smile$


Q:

Sharing photo on FB's latest apk

I am trying to share a photo on Facebook.
I have login working, and the share dialog will pop up with sharelinkcontent but not with photo.
It will not pop up at all, but it is running and hitting this code.
Here is my code:
if (ShareDialog.canShow(SharePhotoContent.class)) {
//            ShareLinkContent linkContent = new ShareLinkContent.Builder()
//                    .build();
//            shareDialog.show(linkContent);

        Bitmap icon = BitmapFactory.decodeResource(this.getResources(),
                R.drawable.common_plus_signin_btn_text_light);

        SharePhoto photo = new SharePhoto.Builder()
                .setBitmap(icon)
                .build();

        SharePhotoContent photoContent = new SharePhotoContent.Builder()
                .addPhoto(photo)
                .build();

        shareDialog.show(photoContent);

    }

A:

Facebook SDK's versions 4.0+ have changed the way you can share content on facebook.
For photos, you need to use PhotoShareContent.
For links, the ShareLinkContent.
A requirement of the SharePhotoContent is that you must have installed the native faceboook app in order to share photos.
From Facebook Doc

Photos
People can share photos from your app to Facebook with the Share
  Dialog or with a custom interface.

The photos must be less than 12MB in size
People need the native Facebook for Android app installed, version 7.0 or higher

On the other hand, to share a link is not necessary the facebook app, that's why your code works when you use ShareLinkContent


Q:

ERT, equality test fails due to different symbols which must be considered same

So, I'm trying to get familiar with ERT, the unit-testing package in Emacs. I want to test macro expansion which uses gensym. I can make sure that gensym produces symbols with the same name, but they are not the same symbol, which causes failure. Below is the code to give you better idea:
(ert-deftest i-test-repreat ()
  "Tests the expansion of i-iterate macro, repeat driver."
  (require 'i-iterate)
  (should
   (equal
    (macroexpand '(++ (repeat 100) (message "")))
    '(let* ((--0 0)) ;; `--0' is a result of a custom-made `gensym'
       (while (< --0 100)
         (incf --0)
         (message "")) nil))))

Here's the fail message:
(list-elt 1
  (list-elt 0
    (list-elt 0
      (different-symbols-with-the-same-name --0 --0))))

Fair enough, it is a different symbol, but it is expected to be so. How can I allow this to succeed?
EDIT
This is what I could come up with so far:
(defun i/test-equals-ignore-gensym (a b)
  "Tests trees A and B for equality, but considers symbols
equal if their names are equal (this allows symbols generated
by `i-gensym' to pass)."
  (or (equal a b)
      (cond
       ((and (null a) (null b)) t)
       ((and (consp a) (consp b))
        (and (i/test-equals-ignore-gensym (car a) (car b))
             (i/test-equals-ignore-gensym (cdr a) (cdr b))))
       ((and (symbolp a) (symbolp b))
        (string= (symbol-name a) (symbol-name b)))
       ((and (atom a) (atom b)) (eql a b))
       (t nil))))

(defun i/test-explainer-equal (a b)
  "Explains why `i/test-equals-ignore-gensym' failed."
  ;; TODO: Write our own explanation, this will trigger when
  ;; necessary, but will not always display the correct message.
  (ert--explain-equal-rec a b))
(put 'i/test-equals-ignore-gensym
     'ert-explainer 'i/test-explainer-equal)

(ert-deftest i-test-repreat ()
  "Tests the expansion of i-iterate macro, repeat driver."
  (require 'i-iterate)
  (should
   (i/test-equals-ignore-gensym
    (macroexpand '(++ (repeat 100) (message "")))
    '(let* ((--0 0))
       (while (< --0 100)
         (incf --0)
         (message "")) nil))))

But I would be happier if there was a better way to do it.

A:

You can attack the problem differently: do not check whther the code is the one you expect, but instead only check whether the code behaves as you expect.  I.e. run the (++ ...) expression and check the output.
BTW, the comparison you want to do on those chunks of code is called "equality modulo alpha-conversion" or just alpha equivalence


Q:

Efficient implementation of a "constant" Set ADT

I need to implement a "constant" set. That is, a data structure that only supports membership test. Additionally (of course), I need a factory routine that, given a list of elements, constructs a constant set.
Notice that not only is mutation not allowed on the constant set, but additionally I don't need an "add" operation that returns a new constant set (that is, once initialization takes place, I'm only interested in testing whether an element is in the set or not).
Goold old hash tables are an obvious choice here, but I wonder, can we somehow take advantage of the fact that we need to support only a single operation (and, when constructing the set, we know what all its elements will be)? Is there a data structure (a specialized type of hash table, perhaps) that would perform particularly well here?

A:

As @Alexandre C. mentioned in a comment, this is an excellent spot to use a perfect hash table. A perfect hash table is a hash table that uses a hash function that guarantees no collisions among its elements. There are various schemes for accomplishing this; one of the most common and simplest options is to use the FKS perfect hash table, which uses a two-layer hash table. It guarantees worst-case O(1) membership tests and is extremely efficient in practice.
Hope this helps!


Q:

why can't i include a static library into a cpp file?

Is there a way to #include "library.a" or it's .so or it's .o inside a cpp or cc file?
I would like to do this because I am using this file inside another file.

A:

#include is for C++ code.
.a, .so and .o files are not C++ code.
It's more likely that you want to #include a C++ header file (typically ending in .h or .hpp), and link an object file.


Q:

C# Azure functions translator

I began to study the azure function
An interesting question is how to implement the function of translating text into any language
I searched for books and googled, and watched the training videos on YouTube, but could not realize it
Also in the future, the process of testing functions is interesting.
For example, how to send a million requests and track errors
Can anyone tell me how to implement this function-translator? Or someone has similar.
Thanks

A:

You can use Cognitive Services (Text API) which will perform the translations for you.
Here's a sample about how to do it: https://docs.microsoft.com/en-us/azure/cognitive-services/translator/quickstart-translate?pivots=programming-language-csharp
Another good example in here: https://anthonychu.ca/post/realtime-captioning-translation-cognitive-services-signalr-azure-functions/ (this one with Azure Functions)
and more info about the supported languages: https://docs.microsoft.com/en-us/azure/cognitive-services/translator/language-support


Q:

Stable Conjugacy for Integer Matrices

Let $F$ be a field, and $E$ an extension field.  Then two matrices in $GL_n(F)$ are conjugate if and only if they are conjugate in $GL_n(E)$.  I'm curious whether the analogous fact holds for rings of integers.
Is the following true?
Two matrices in $GL_n(\mathbb Z)$ are conjugate if and only if they are conjugate in $GL_n(\mathbb A)$, where $\mathbb A$ is the ring of algebraic integers.

A:

Well, I think the answer is "no".  Here's a construction:  let R be the ring of integers of a real quadratic field K of class number > 1, let M be an invertible R-module of rank one which is not isomorphic to R, and let x be a fundamental unit in R.  Then the action of x on M (viewed as a Z-module) determines a well-defined conjugacy class C_M in GL_2(Z), and similarly the action of x on R determines a conjugacy class C_R.  I claim that these conjugacy classes are distinct, but become equal in GL_2(A).
They are distinct:  indeed, M is recovered up to isomorphism from C_M since R identifies with the commutant algebra of x acting on the Z-module M.
They become equal in GL_2(A):  in fact they become equal in GL_2 of the ring of integers in the Hilbert class field of K, since M and R become isomorphic there.

A:

Here is an explicit realization of the counterexample suggested by Dustin. The field ${\mathbf Q}(\sqrt{10})$ has class number 2 and its Hilbert class field is obtained by adjoining $\sqrt{2}$. The ring of integers ${\mathbf Z}[\sqrt{10}]$ has (fundamental) unit $u:=3+\sqrt{10}$, whose minimal polynomial over ${\mathbf Q}$ is $T^2 - 6T - 1$. The two ideal classes in ${\mathbf Z}[\sqrt{10}]$ are represented by the ideals $(1)$ and $(2,\sqrt{10})$, which have ${\mathbf Z}$-bases $\{1,u\}$ and $\{2,\sqrt{10}\}$. Multiplication by $u$ on  these two ideals is represented, using the indicated $\mathbf Z$-bases, by the respective matrices $A = (\begin{smallmatrix}0&1\\1&6\end{smallmatrix})$ and $B = (\begin{smallmatrix}3&5\\2&3\end{smallmatrix})$. These matrices are both in ${\rm GL}_2({\mathbf Z})$, they are not conjugate in this group, but they are conjugate by the matrix $U = (\begin{smallmatrix}\sqrt{2}&5+3\sqrt{2}\\1&3+2\sqrt{2}\end{smallmatrix})$, which lies in ${\rm GL}_2({\mathbf Z}[\sqrt{2}])$. That is, $UAU^{-1} = B$. This conjugating matrix $U$ has determinant $-1$. A matrix with determinant 1 and algebraic integer entries that satisfies $VAV^{-1} = B$ is
$V = (\begin{smallmatrix}2\sqrt{2}&6\sqrt{2}+5\sqrt{3}\\\ \sqrt{3}&4\sqrt{2}+3\sqrt{3}\end{smallmatrix})$.
Quite generally, the matrix $M = (\begin{smallmatrix}a&b\\c&d\end{smallmatrix})$ satisfies $MA = BM$ if and only if $b=3a+5c$ and $d = 2a+3c$, and then $\det M = 2a^2 - 5c^2$. We can't solve $2a^2 - 5c^2 = \pm 1$ in ${\mathbf Z}$ (look at it mod 5), but we can solve it in ${\mathbf Z}[\sqrt{2}]$ using $a = \sqrt{2}$ and $c = 1$. That is how I found $U$. We can solve $2a^2 - 5c^2 = 1$ using $a = 2\sqrt{2}$ and $c = \sqrt{3}$, which is how I found $V$.


Q:

Regex to filter numbers after a text

Can you help me with this example please:
BUILTIN\s+\d{1,2}

https://regex101.com/r/w7A3H7/1
I only want to filter out the numbers after text BUILTIN and before the x character. Now the result also contains the word BUILTIN, what I want to be removed.
I also can't simply use \d{1,2}x because I must make sure it is after the second occurance of the word BUILTIN. Thank you

A:

You can use the following pattern:
BUILTIN\s+\K\d+(?=x)

BUILTIN Literal substring.
\s+ Match whitespace, one or more occurrences.
\K Reset operator which resets the match.
\d+ Match digits.
(?=x) Positive lookahead which ensures that after the digits a x is present.

You can try it here:

If you are working with a regex flavor which does not support the reset operator, you can use:
(?<=BUILTIN\s{11})\d+(?=x)

(?<=BUILTIN\s{11}) Lookbehind for literal substring followed by 11 whitespaces.
\d+ Match digits.
(?=x) Positive lookahead which ensures that after the digits a x is present.

You can try it here

Match 1
Full match  57-59   `48`
Match 2
Full match  137-138 `4`
Match 3
Full match  283-285 `24`
Match 4
Full match  363-365 `48`


Q:

Getting an enum from backend and use it as a string in javascript

Today I had a rather heathed discussion with a java backend developer. I do the frontend side with jsangular. His rest service sends me an object that includes an enum. I get this as a string and need to show it in an angular grid.
The enums are very self explainable.
Examples what I get:
Person = {gender: "MAN", position: "IS_EMPLOYED"}
In the view I have to show the following:
man is employed
So i solved it in a simple and generic way:
Person.gender.toLowerCase () + ' ' + Person.position.toLowerCase ().replace ('_', ' ')
He found this terrible programming and demanded that I would make a mapper with if else or switch
So: If(Person.gender==="MAN") return "man"
Else if....
The label name is always the same as the enum name (only lower case and space instead of underscore)
He went on a rampage that it was bad coding and basically  terrible and a sin against god...
So my question is this bad/good practice (so a b/w story) or rather acceptable and defendable in some cases?
Typed on my phone so I couldn't  put the code examples in the right tags..

A:

There are a few ways to look at this:
Mapping is more robust:
He is right in saying that there should be a complete mapping function. This allows you to handle errors (i.e. if the response you get for position is "banana", you should probably not just throw that out there). This is especially important in backend development when you are probably working with a strict schema.
Scale Matters:
There is nothing technically wrong with your approach. If there are a small number of entries or if the user base or application scope is small, it may not matter much. It doesn't really conform to best practices, but it works, and if that is all that matters, it might be enough. Although you should always strive for best practices, you need to keep the big picture in mind.
Efficiency:
One approach may be more efficient than the other. The difference may be negligible. In web dev, speed is a priority, and if both approaches get the same result but one is much faster, choose that one.


Q:

Issues with async blocking GUI thread, WinForms

I am having a strange issue with code that should work (to my best understanding), but it doesn't.
I have a windows forms application. It has a button that scans through a selected directory, which can result in a very high amount of files found. When scanning ~50k files, it took about 10 seconds.
I tried to implement async, to run the file scanning itself asynchronously to the main GUI, however this is causing trouble. The task itself runs fine, but it still blocks the GUI, resulting in freezing the whole application.
This is the code I have for the button
private async void BeginScanButton_Click(object sender, EventArgs e)
    {
        if (_osuDirectory == null)
            MessageBox.Show("You have not chosen an Osu! directory yet.");
        else
        {
            await ScanFilesTask();
        }

There is a lot more but this is the relevant part of it.
The task itself is
 private Task ScanFilesTask()
    {
        FileList.Clear();
            return Task.Run(() =>
            {
                if (_jpgFilesChecked)
                    FileParser.ParseFiles(_osuDirectory, "*.jpg");
                if (_pngFilesChecked)
                    FileParser.ParseFiles(_osuDirectory, "*.png");
                if (_wavFilesChecked)
                    FileParser.ParseFiles(_osuDirectory, "*.wav");
                if (_aviFilesChecked)
                    FileParser.ParseFiles(_osuDirectory, ".avi");
            });
    }

And finally, the FileParser class is just
        public static void ParseFiles(string dir, string extension)
        {
            Form1.FileList.AddRange(Directory.GetFiles(dir, extension, SearchOption.AllDirectories));
        }

(All of the code is up on a github repo if anyone wants to have a look. The relevant async code is in the AsyncTest branch.)
Any help here would be very much appreciated. This is my first real C# project, and would very much appreciate any pointers in the right direction. Thanks in advance!

A:

Things to read:
Task.Run Etiquette and Proper Usage
Task.Run vs BackgroundWorker, Round 1: The Basic Pattern
A Tour of Task, Part 0: Overview
Excerpt:

Developers who have used Task and the TPL (Task Parallel Library) since it was introduced in .NET 4.0. These developers are familiar with Task and how it is used in parallel processing. The danger that these developers face is that Task (as it is used by the TPL) is pretty much completely different than Task (as it is used by async).
Developers who have never heard of Task until async came along. To them, Task is just a part of async - one more (fairly complicated) thing to learn. “Continuation” is a foreign word. The danger that these developers face is assuming that every member of Task is applicable to async programming, which is most certainly not the case.

There is no point in Async, what you want is to run things in Parallel.  They are extremely different.  What you're looking for is:
button:
private void BeginScanButton_Click(object sender, EventArgs e)
{
    BeginScanButton.Enabled = false;
    if (_osuDirectory == null)
        MessageBox.Show("You have not chosen an Osu! directory yet.");
        BeginScanButton.Enabled = false;
    else
    {
        ScanFilesInParallel();
    }
}

ScanFiles
private void ScanFilesInParallel()
{
    FileList.Clear();
    Task.Run(() =>
    {
      var result = new List<string>();

      if (_jpgFilesChecked)
        result.AddRange(FileParser.ParseFiles(_osuDirectory, "*.jpg"));
      if (_pngFilesChecked)
        result.AddRange(FileParser.ParseFiles(_osuDirectory, "*.png"));
      if (_wavFilesChecked)
        result.AddRange(FileParser.ParseFiles(_osuDirectory, "*.wav"));
      if (_aviFilesChecked)
        result.AddRange(FileParser.ParseFiles(_osuDirectory, ".avi"));

      return result;
     })
     .ContinueWith((task) => {
       FileList.AddRange(task.Result);
       BeginScanButton.Enabled = true;
     }, TaskScheduler.FromCurrentSynchronizationContext());
}

ParseFiles
public IEnumerable<string> ParseFiles(string dir, string extension)
{
  var result = Directory.GetFiles(dir, extension, SearchOption.AllDirectories).ToList();

  return result;
}


Q:

how to fix 'Warning Error loading module file (). Please restore the file or disable the module.' error message?

I'm using civicrm 4.5.5 in drupal 6
I enabled tracing to explore another problem and when I removed the defines in the settings.php file that setup the query logging, this error appeared.
How do I get rid of it?

A:

Visit your Extensions page @ civicrm/admin/extensions?reset=1.
Click Refresh.
If visible, uninstall the extension which is currently not found.
Worth trying Cleanup Caches too @ civicrm/admin/setting/updateConfigBackend?reset=1


Q:

Concatenating in JQuery from 2 table columns

So I have pieced together the below and I'm not getting the expected outcome I am looking for
    /* Build SQL string */
$(".ConvertSQL").click(function () {

    $(".TableQuery").children("tbody").children("tr").each(function (i) {

        $("#SQLstring").val("")

        var $this = $(this);
        var my_td = $this.children("td");
        var first_col = my_td.eq(0);
        var second_col = my_td.eq(1);
        var query = "SELECT "
        var text = $("#SQLstring").val()

        query = query + "[" + first_col.html() + "].[" + second_col.html() + "],";
        first_col = ""
        second_col = ""

        $("#SQLstring").val(text + query)

    });

    /* Remove some text from the start of the string thats not needed */
    $('#SQLstring').contains('SELECT [undefined].[undefined],').remove();

});

There are no errors I'm receiving as such.
The code loops through the first 2 columns in my table and build an SQL query
The current outcome is:

SELECT [Test Table].[Test Field],

It should be basically concatenating eat row together to show something like:

SELECT [Test Table].[Test Field], [Test Table].[Test Field],

A:

The issue is because you define query within each iteration of the loop. You need to define it outside then add to it as the loop progresses.
Similarly you need to only update the '#SQLstring field after the loop completes. The setting of #SQLstring to empty can be removed along with the code to retrieve and concatenate it's value (which is redundant as the first thing the loop does is empty the value, so it's always empty). Try this:

$(".ConvertSQL").click(function() {
  var query = "SELECT ";

  $(".TableQuery").children("tbody").children("tr").each(function(i) {
    var $td = $(this).children("td");
    query += "[" + $td.eq(0).html() + "].[" + $td.eq(1).html() + "],";
  });

  $("#SQLstring").val(query.slice(0, -1)); // slice is used to remove trailing comma
});
input {
  width: 300px;
}

      Foo
      Bar

      Lorem
      Ipsum

<button class="ConvertSQL">Convert SQL</button>
<input type="text" id="SQLstring" />

That being said a better approach would be to use map() to build an array from the values which you can then join() back together, like this:

$(".ConvertSQL").click(function() {
  var query = $('.TableQuery > tbody > tr').map(function() {
    var $td = $(this).children('td');
    return `[${$td.eq(0).html()}].[${$td.eq(1).html()}]`;
  }).get().join(', ');

  $("#SQLstring").val(`SELECT ${query}`);
});
input {
  width: 300px;
}

      Foo
      Bar

      Lorem
      Ipsum

<button class="ConvertSQL">Convert SQL</button>
<input type="text" id="SQLstring" />


Q:

Android SQLite wont add values to the db

I'm just trying to figure out how to work with android SQLite and I've followed many different tutorials. But for some reason i cannot get anything to work.
Here is the code im using:
DBHandler.java
package com.example.deathtrackkevin;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHandler extends SQLiteOpenHelper  {

    // All static variables
    //Database Version
    private static final int DATABASE_VERSION = 1;

    //Database Name
    private static final String DATABASE_NAME = "DeathTrackDB";

    //DeathTrack Table Name
    private static final String TABLE_DEATHTRACK = "DeathTrack";

    //Deathtrack Table Column Names
    private static final String COL_GAME_ID = "Game_ID";
    private static final String COL_GAME_NAME = "Game_Name";
    private static final String COL_KILLS = "kills";
    private static final String COL_DEATHS = "Deaths";
    private static final String COL_DATE = "date";
    private static final String COL_MATCH = "Match";

    public DbHandler(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    //Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_DEATHTRACK_TABLE =
                "CREATE TABLE" + TABLE_DEATHTRACK + "("
                + COL_GAME_ID + "INTEGER PRIMARY KEY,"
                + COL_GAME_NAME + "TEXT,"
                + COL_KILLS + "TEXT,"
                + COL_DEATHS + "TEXT,"
                + COL_DATE + "TEXT,"
                + COL_MATCH + "TEXT" + ")";
        db.execSQL(CREATE_DEATHTRACK_TABLE);
    }

    //Upgrading Database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop Older Table If Exists
        db.execSQL("DROP TABLE IF EXISTS" + TABLE_DEATHTRACK);
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    //Adding New Deathtrack TODO Create array for deathtrack
    void addDeathtrack(DeathTrack deathtrack) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COL_GAME_ID, deathtrack.get_game_id());
        values.put(COL_GAME_NAME, deathtrack.get_game_name());
        values.put(COL_KILLS, deathtrack.get_kills());
        values.put(COL_DEATHS, deathtrack.get_Deaths());
        values.put(COL_DATE, deathtrack.get_Date());
        values.put(COL_MATCH, deathtrack.get_match());

        //Inserting Row
        db.insert(TABLE_DEATHTRACK, null, values);
        db.close();
    }
    //TODO Getting Single Deathtrack
    DeathTrack getDeathtrack(int id){
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_DEATHTRACK, new String[] {COL_GAME_ID, COL_GAME_NAME, COL_KILLS, COL_DEATHS, COL_DATE, COL_MATCH}, COL_GAME_ID + "=?", new String[] {String.valueOf(id)}, null, null, null, null);
        if(cursor != null)
            cursor.moveToFirst();

        DeathTrack deathtrack = new DeathTrack(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1),
                cursor.getString(2),
                cursor.getString(3),
                cursor.getString(4),
                cursor.getString(5));

        return deathtrack;
    }

    //TODO Get all deathtrack values
    public List<DeathTrack> getAllDeathtrack(){
        List<DeathTrack> deathtrackList = new ArrayList<DeathTrack>();
        //Select all Query
        String selectWhere = "SELECT * FROM" + TABLE_DEATHTRACK;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectWhere, null);

        //Looping through all rows and adding to list
        if(cursor.moveToFirst()){
            do{
                DeathTrack deathtrack = new DeathTrack();
                deathtrack.set_game_name(cursor.getString(0));
                deathtrack.set_kills(cursor.getString(1));
                deathtrack.set_Deaths(cursor.getString(2));
                deathtrack.set_Date(cursor.getString(3));
                deathtrack.set_match(cursor.getString(4));
                //Add deathtrack to list
                deathtrackList.add(deathtrack);
            } while (cursor.moveToNext());
        }
        return deathtrackList;
    }
    //TODO Delete deathtrack value by game name
    public void deleteDeathtrack(DeathTrack deathtrack){
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_DEATHTRACK, COL_GAME_NAME + "= ?", new String[]{            String.valueOf(deathtrack.get_game_name())});
        db.close();
    }

}

SQLTester.java
package com.example.deathtrackkevin;

    import java.util.List;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;

    public class SQLTester extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.sqltester_layout);

            DbHandler db = new DbHandler(this);

            /**
             * CRUD Operations
             * */
            // Inserting Contacts
            Log.d("Insert: ", "Inserting ..");
            db.addDeathtrack(new DeathTrack(1, "cod2", "4", "2", "02-02-12", "1"));
            db.addDeathtrack(new DeathTrack(2, "cod3", "4", "2", "02-02-12", "1"));
            db.addDeathtrack(new DeathTrack(3, "cod4", "4", "2", "02-02-12", "1"));
            db.addDeathtrack(new DeathTrack(4, "cod5", "4", "2", "02-02-12", "1"));

            // Reading all contacts
            Log.d("Reading: ", "Reading all contacts..");
            List<DeathTrack> contacts = db.getAllDeathtrack();

            for (DeathTrack cn : contacts) {
                String log = "Game_Id: "+cn.get_game_id()+" ,Game_Name: " + cn.get_game_name() + " ,Kills: " + cn.get_kills()+ " ,Deaths: " + cn.get_Deaths()+ " ,Date: " + cn.get_Date()+ " ,Match: " + cn.get_match();
                    // Writing Contacts to log
            Log.v("dt", "name "+log);
        }
        }
    }

Question
Basically all i need is someone to tell me if there is something wrong..Im not getting any logcat errors or any other type of errors so i cannot use those to figure out whats going on
Regards
Joe

A:

It seems like your spacebar is broken...
    String CREATE_DEATHTRACK_TABLE =
            "CREATE TABLE" + TABLE_DEATHTRACK + "("
            + COL_GAME_ID + "INTEGER PRIMARY KEY,"
            + COL_GAME_NAME + "TEXT,"
            + COL_KILLS + "TEXT,"
            + COL_DEATHS + "TEXT,"
            + COL_DATE + "TEXT,"
            + COL_MATCH + "TEXT" + ")";

And
String selectWhere = "SELECT * FROM" + TABLE_DEATHTRACK;

Won't work.
Instead, you need to write
    String CREATE_DEATHTRACK_TABLE =
            "CREATE TABLE " + TABLE_DEATHTRACK + " ("
            + COL_GAME_ID + " INTEGER PRIMARY KEY, "
            + COL_GAME_NAME + " TEXT, "
            + COL_KILLS + " TEXT, "
            + COL_DEATHS + " TEXT, "
            + COL_DATE + " TEXT, "
            + COL_MATCH + " TEXT)";

And
String selectWhere = "SELECT * FROM " + TABLE_DEATHTRACK;

[EDIT]
You are using the reserved KeyWord MATCH.
You better change it to something like Round or Challenge.
For your reference: https://www.sqlite.org/lang_keywords.html


Q:

Question about QAM

I'm trying to understand QAM transmission and I'm struggling to understand this sentence, 'The advantage of using QAM is that it is a higher order form of modulation and as a result it is able to carry more bits of information per symbol. By selecting a higher order format of QAM, the data rate of a link can be increased. Article here'
Could someone explain what the term 'higher order form of modulation' means. Does it mean that the carrier frequency is higher?

A:

Higher order modulation means with each use of the channel, you transmit more bits. For example, in $8-$ary QAM, 3 bits are transmitted in each channel use. In other words, each 3 bits are mapped to one of the 8 available waveforms to be transmitted over the channel. If you use $16-$ary QAM, then 4 bits are transmitted with each channel use. In general, for $M-$ary QAM, $\log_2(M)$ bits are transmitted with channel use. The larger $M$, the more bits are transmitted per channel use. However, as $M$ increases, the distance between the constellation points decreases, and this means that the probability of error increases. So, there should be a trade-off between the constellation size, and the probability of error.


Q:

Как выключить input type=radio?

При нажатии на input type=radio он включается, но при повторном нажатии на тот же input ничего не происходит, можно ли как то сделать, чтобы при повторном нажатии он отключался? В первую очередь желательно, если бы это можно было сделать либо через атрибут в html, либо в css, если же вариантов таких нет, то уже пример кода на js.

A:

Первый вариант:

    var check1,check2;
    function radioClick(c) {
        if (check1 != c) {
            check2 = 0;
            check1 = c
        }
        check2 ^= 1;
        c.checked = check2
    }
<input type="radio" name="radio" value="1" onclick="radioClick(this)"/>
<input type="radio" name="radio" value="2" onclick="radioClick(this)"/>

Второй вариант:

    function clickRadio(param) {
        var value = document.querySelectorAll("input[type='radio'][name='" + param.name + "']");
        for (var i = 0; i < value.length; i++) {
            if (value[i] != param)
                value[i].BeforeCheck = false;
        }

        if (param.BeforeCheck)
            param.checked = false;
        param.BeforeCheck = param.checked;
    }
Первый radio<input type="radio" onclick="clickRadio(this)" name="radio" />
Второй radio<input type="radio" onclick="clickRadio(this)" name="radio" />


Q:

Cannot find SSISDB Catalog when trying to execute SSIS Package programmatically

So I've been trying to execute an SSIS Package from my SharePoint Event Receiver for this past 2 days and almost went crazy.
The SSIS Package is deployed into Integration Service Catalogs in my dev environment (the SQL Server 2014 and its Integration Services is installed on the same machine as the SharePoint Server and my VS2013 Community Edition).
Successfully open SSISDB Catalog from SSMS
Here is my code so far, basically following steps in this blog -> http://microsoft-ssis.blogspot.co.id/2013/01/call-ssis-2012-package-within-net.html
connString = @"Data Source=PIRSRV03;Initial Catalog=master;Integrated Security=SSPI;";

                using (SqlConnection sqlConnection = new SqlConnection(connString))
                {

                    IntegrationServices integrationServices = new IntegrationServices(sqlConnection);

                    PackageInfo myPackage = integrationServices.Catalogs[integrationServiceCatalog].Folders[integrationServiceFolder].Projects[integrationServiceProject].Packages[integrationServicePackage];

                    Collection<PackageInfo.ExecutionValueParameterSet> executionValueParameterSet = new Collection<PackageInfo.ExecutionValueParameterSet>();

                    executionValueParameterSet.Add(new
                    PackageInfo.ExecutionValueParameterSet { ParameterName = "ExcelFilePath", ParameterValue = TempDirectory, ObjectType = 30 });

                    long executionIdentifier = myPackage.Execute(false, null, executionValueParameterSet);

                    ExecutionOperation executionOperation = integrationServices.Catalogs["SSISDB"].Executions[executionIdentifier];

                    // Workaround for 30 second timeout:
                    // Loop while the execution is not completed
                    while (!(executionOperation.Completed))
                    {
                        // Refresh execution info
                        executionOperation.Refresh();

                        // Wait 5 seconds before refreshing (we don't want to stress the server)
                        System.Threading.Thread.Sleep(5000);
                    }
                }

Everything goes fine until the line of code where it accessed the catalog SSISDB and throw an error,
after a little debugging session I figured out that the integrationServices object didn't have any catalog, by observing the Catalogs.Count property which in this case equals to zero.
Is there any hint on why this happens?
Any help would be so much appreciated, Thanks!

A:

After some hours spent trying to figure out the problem with the help from my DBA,
it turns out that the SharePoint Services account that runs my Event Receiver does not have the access to my integration services catalogs, hence the zero count of catalogs.
All we did to solve this was just giving sysadmin permission to the SharePoint Services account.
Hope this helps someone some hours, thanks!


Q:

What is dereferenced error?

I executed the following code and I got the following errors.
I make some edit for last part in order to make it in code format.
RunUnitConvert.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;

/**
*
*  This is a test driver for the UnitConverter class
*  Write a unit conversion program that asks users to
*  identify the unit from which they want to convert and
*  the unit to which they want to convert. Legal units
*  are in, ft, mi, mm, cm, m, and km. Define two
*  objects of a class UnitConverter that convert
*  between meters and a given unit.
*
*/
public class RunUnitConverter
{
  public static void main(String[] args)
   {
           BufferedReader br;
           char fromUnit = '\0';
           char toUnit = '\0';
           double value = 0;

    //  prompt the user to enter unit to convert from
        System.out.print("Convert from: ");
    //  open up standard input
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            fromUnit = (char)br.read();
        } catch (IOException ioe) {
            System.exit(1);
        }
    // prompt user to enter unit to convert to
        System.out.print("Convert to: ");
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            toUnit = (char)br.read();
        } catch (IOException ioe) {
            System.exit(1);
    }

    // create new UnitConvert objects
         UnitConverter from = new UnitConverter(fromUnit);
        UnitConverter to = new UnitConverter(toUnit);

    // prompt user to enter initial value to convert
        System.out.print("Value: ");
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            value = Double.parseDouble(br.readLine());
        } catch (IOException ioe) {
        System.exit(1);
        }

        double metric = from.toMetric(value);
        double converted = to.fromMetric(metric);

        if (converted < 0) {
            System.out.println("ERROR: Bad Input");
        }
        else {
            System.out.println(value + " " + fromUnit + " = " + converted +    " " + toUnit);
        }
    }
}

UnitConvert.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;

/**
*
 *  This is a test driver for the UnitConverter class
*  Write a unit conversion program that asks users to
*  identify the unit from which they want to convert and
*  the unit to which they want to convert. Legal units
*  are in, ft, mi, mm, cm, m, and km. Define two
*  objects of a class UnitConverter that convert
*  between meters and a given unit.
*
*/
public class RunUnitConverter
{
    public static void main(String[] args)
    {
        BufferedReader br;
        char fromUnit = '\0';
        char toUnit = '\0';
    double value = 0;

    //  prompt the user to enter unit to convert from
        System.out.print("Convert from: ");
    //  open up standard input
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            fromUnit = (char)br.read();
        } catch (IOException ioe) {
            System.exit(1);
        }
    // prompt user to enter unit to convert to
        System.out.print("Convert to: ");
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            toUnit = (char)br.read();
        } catch (IOException ioe) {
            System.exit(1);
        }

    // create new UnitConvert objects
        UnitConverter from = new UnitConverter(fromUnit);
        UnitConverter to = new UnitConverter(toUnit);

    // prompt user to enter initial value to convert
        System.out.print("Value: ");
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            value = Double.parseDouble(br.readLine());
        } catch (IOException ioe) {
        System.exit(1);
       }

        double metric = from.toMetric(value);
       double converted = to.fromMetric(metric);

        if (converted < 0) {
            System.out.println("ERROR: Bad Input");
        }
        else {
        System.out.println(value + " " + fromUnit + " = " + converted + " " + toUnit);
     }
    }
}

This is the errors that I have
The output and error were the following:
javac RunUnitConverter.java
 char cannot be dereferenced
switch (strUnit.charAt(0)){
                           ^
char cannot be dereferenced
 switch (strUnit.charAt(0)){
                           ^
2 errors

A:

Your problem is exactly as the error message says. "strUnit" is of type char, it is not an Object, and thus has no methods.


Q:

Add and Remove Input Field

I find two bugs at here:

The number will not continue counting, like will be 4 in next input value. Currently when add new input, the value is 1.
The remove button not working if have 3 input field there. But the remove button working if add one more input field. Anyway, only one can be delete.

HTML

        <input type="text" value="1"/>

Remove

        <input type="text" value="2"/>

Remove

        <input type="text" value="3"/>

Remove

Add

JQuery
    $(document).ready(function() {

    var MaxInputs       = 99;
    var InputsWrapper   = $("#add_form table");
    var AddButton       = $("#add_field");

    var x = InputsWrapper.length;
    var FieldCount=1;

    $(AddButton).click(function (e) {

        if(x <= MaxInputs) {

            FieldCount++;

            $(InputsWrapper).append('
<input type="text" value="' +  x + '"/>
Remove

');
            x++;

        }

        return false;

    });

    $("body").on("click",".removeclass", function(e) {

        if( x > 1 ) {

            $(this).closest('tr').remove();
            x--;

        }

        return false;

    })

});

http://jsfiddle.net/hxbc7/

A:

I have updated the fiddle that you created. http://jsfiddle.net/hxbc7/12/
There was a mistake in your code that I rectified.
Instead of this line
var InputsWrapper   = $("#add_form table");

it should be
var InputsWrapper   = $("#add_form table tr");


Q:

Check for multiple words in a string and show found/not found words

I am checking for multiple words in a string using using the example by anubhava here. However, I am not sure how to show the words that are found and ones that are not found in the string. Any ideas how to achieve that. The code I am using looks like below.
$bad_words = array("yo","hi");
$sentence = "yo you your";

preg_match_all('/\w+/', $sentence, $m);
echo ( array_diff ( $m[0], $bad_words ) === $m[0] ) ? "no bad words found\n" :
                                                      "bad words found\n";

A:

First, you need to define what a word is in this context. For example, is "pancake" one word or two? If you search for "pan" should it return true if "pancake" is found? Also, is "A.I." a word? Is "2020" a word? What about "fast-track"? Should the search be case-sensitive? Should it include partial finds? If you just want a simple, needle/haystack search like strpos then the solution is trivial.
$searchWords = ["yo","hi"];
$sentence    = "yo you your";
$wordsFound  = [];

foreach ($searchWords as $word) {
    if (stripos($sentence, $word) !== false) {
        $wordsFound[$word] = true;
    }
}

echo "Words found: ", implode(",", array_keys($wordsFound)); // Words found: yo

To find the words that weren't found in $searchWords you'd just do $wordsNotFound = array_diff($searchWords, array_keys($wordsFound)).


Q:

Wrong decode result in python

Can't figure out by debugging, why I got b in front of my hidden string?
I get this string in my result:
 '1101000011001010110110001101100011'
def retr(filename):
    img = Image.open(filename)
    binary = ''

    if img.mode in ('RGBA'):
        img = img.convert('RGBA')
        datas = img.getdata()

        for item in datas:
            digit = decode(rgb2hex(item[0], item[1], item[2]))
            if digit == None:
                pass
            else:
                binary = binary + digit
                if (binary[-16:] == '1111111111111110'):
                   # print("Success")
                    return bin2str(binary[:-16])

        return str(bin2str(binary))
    return "Incorrect Image Mode, Couldn't Retrieve"

But result in console is: b'hello'. Where is b from?
Doing some pre fucntion before retr():
def rgb2hex(r, g, b):
    return '#{:02x}{:02x}{:02x}'.format(r, g, b)

def hex2rgb(hexcode):
     return int(hexcode[1:3], 16), int(hexcode[3:5], 16), int(hexcode[5:7], 16)

def str2bin(message):
    binary = bin(int(binascii.hexlify(message.encode("ascii")), 16))
    return binary[2:]

def bin2str(binary):
    message = binascii.unhexlify('%x' % (int('0b' + binary, 2)))
    return message

help ,please, to catch that b..

A:

bin2str is returning a byte literal. You can use .decode() to return a string instead.
def bin2str(binary):
    message = binascii.unhexlify('%x' % (int('0b' + binary, 2)))
    return message.decode("utf-8") # or encoding of choice


Q:

Convergence of a certain series where the ratio test fails

I have spent many hours on this problem without success : We need to determine the convergence or divergence of the infinite series
$$\sum_{n=2}^{\infty} \frac{\sqrt{n+1}}{(2n^2 - 3n+1) (\ln n + (\ln n)^2)}.$$
A simple application of the ratio test yields the inconclusive Limit=1 . Any help is much appreciated...

A:

For large $n$ we have
$$\ln n>1$$
and so
$$\frac{\sqrt{n+1}}{(2n^2 - 3n+1)(\ln n + (\ln n)^2)}
  <\frac{\sqrt{2n}}{(n^2)(2)}=\frac{1/\sqrt2}{n^{3/2}}\ .$$
So the series converges by the comparison test.
Note that the logs in this problem are actually quite unimportant, probably your teacher just put them in to annoy you ;-)


Q:

How can I access the instantiated user within the user model itself (without creating another relationship)?

I want to create a custom method by accessing the instantiated users id, like:
public function ware(){
    return File::where('owner', $this->user->id);
}

same could be a accessor or scope. and then being able to call
$user = User::find(5);
$user->ware()->all()...

A:

You would define relationships using PK/FK as outlined in the Laravel documentation here and then could access them via relationship like:
Make sure your file table has a column for user_id which would allow the relationship to function as outlined above.
Add to User Model:
/**
 * Get the files for the user.
 */
public function files()
{
    return $this->hasMany('App\File');
}

Add to File Model:
/**
 * Get the user for the file.
 */
public function user()
{
    return $this->hasOne('App\User');
}

You could then access it like User::find(5)->files (to get user files) or File::find(5)->user to return the file user.


Q:

Need horizontal menu option on mouseover on a particular div

My requirement is to make a horizontal menu in the end of a paragraph where on mouseover a menu should appear

On mouse over it should show an option to add an item like this

On clicking the add option the menu should appear like this

Please suggest any jQuery or javascript plugin for this functionality. My preference is a plugin for this other than writing custom script.

A:

Here is what I have: http://jsfiddle.net/cbARJ/4/
I don't have such background for your Add here buttons, so you will need to add it.


Q:

Параллельная передача POST запроса и адресация на другую страницу

На странице имеется форма с данными:
<form name="SendOrder" method="post" action="https://testpay.kkb.kz/jsp/process/logon.jsp">
   <input type="hidden" name="Signed_Order_B64" size="100" value="{$bookingpay}">
   <input type="hidden" name="email"  value="{$val.email}">
   <input type="hidden" name="Language" value="rus">
   <input type="hidden" name="BackLink" value="http://suite/?page=payed">
   <input type="hidden" name="PostLink" value="http://suite/?page=success">

После нажатия форма отправляется на оплату https://testpay.kkb.kz/jsp/process/logon.jsp в форме передается xml с моей стороны
После прохождения проверки и оплаты, банк на url PostLink отправляет xml "response". А пользователь возвращается по BackLink на сайт.
На странице маршрутизации описано так:
case 'success':
        $response = successpay($_POST["response"]);
        $smarty->display('booking.tpl');
    break;
    case 'payed':
        $smarty->display('successpay.tpl');
        break;
    case 'failpay':
        $smarty->display('failure.tpl');
        break;

successpay находится в файле функций common.php
Вопросы: 1. Будет ли происходить обработка $_POST["response"]? Т.к. пользователь обращается не к странице page=success, а к page=payed

A:

Разумеется, "посмотреть параллельный POST запрос" нельзя. посмотреть в данном случае можно и нужно в базу данных.
Скрипт, который обрабатывает ПОСТ запрос из банка не должен ничего никому выводить, и назначать переменные для смарти в нем бессмысленно. Все что он должен сделать - это записать в БД информацию, принятую из банка, об успешности или неуспешности платежа.
А скрипт по бэклинку уже должен смотреть в БД и искать там эту информацию.


Q:

Accessing Laravel Api using POSTMAN (404 not found)

I wrote an API for User Login using Laravel 5.8
When I tested the Login on Postman, it generated an error.

Status: 404 Not Found.

The File Path is Http->Controllers->UserController->Login
The project is laravelapi. I used POST in Postman and added this:
http://localhost/laravelapi/public/user/api/login

But when I run php artisan serve and used:
http://localhost:8000/api/login

Status was OK.
Controller
public function login(Request $request)
{
    $credentials = $request->json()->all();

    try {
        if(! $token == JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'invalid_credentials'], 400);
        }
    } catch(JWTException $e) {
            return response()->json(['error' => 'could_not_create_token'], 500);
    }

    return response()->json(compact('token'));
}

api.php
use Illuminate\Http\Request;

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('login', 'UserController@login');

What do I do to make http://localhost/laravelapi/public/user/api/login work and have Status: OK
Thanks.

A:

link must be localhost/laravelapi/public/api/login


Q:

how does frame of a UILabel gets changed on changing anchor point

I have a UIView object with frame (50, 50, 100, 100).
on this view object, I am adding a label with frame (50, 50, 50, 10)
Then I am changing the anchor point from default (0.5, 0.5) to (1.0, 0.5)
But surprisingly, the frame gets changed after that. Below is the code snippet for the same
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width/2, 10)];
NSLog(@"Label frame for %d label before anchor point shift is %@", i, NSStringFromCGRect(label.frame));

label.layer.anchorPoint = CGPointMake(1.0, 0.5);
NSLog(@"Label frame for %d label after anchor point shift is %@", i, NSStringFromCGRect(label.frame));

Gives output :
Label frame for 0 label before anchor point shift is {{50, 50}, {50, 10}}
Label frame for 0 label after anchor point shift is {{25, 50}, {50, 10}}

A:

The frame of a UIView is a derived quantity based on the center and bounds properties.  If you change the center or bounds, then the frame is adjusted accordingly. Likewise, changing the frame adjusts the center and/or bounds as necessary.
Ok, that's great, except that you're changing the anchorPoint of the layer. When you change the anchorPoint of the layer, that changes the center point of the layer, which changes the center point of the UIView, which then changes the frame. Hence, the label moves.


Q:

Evaluating a trace with two factors of $\gamma^5$

In the process of calculating a spin-averaged square amplitude in QFT, I came across the following expression:
$$ \text{Tr}\left[\gamma^\mu\gamma^5\gamma^\alpha\gamma^\nu\gamma^5\gamma^\beta\right] $$
How can I evaluate this? The usual identities (eg the ones on Wikipedia) don't seem to be of much use - I can't see any way to do it with those, since there are two factors of $\gamma^5$.

A:

I just realised that I can use the fact that $\gamma^5$ anticommutes with the others (twice):
$$=\text{Tr}\left[\gamma^\mu\gamma^\alpha\gamma^\nu\gamma^5\gamma^5\gamma^\beta\right]$$
then note that $\gamma^5\gamma^5$ is just the identity, giving:
$$=\text{Tr}\left[\gamma^\mu\gamma^\alpha\gamma^\nu\gamma^\beta\right]$$
which can be expanded by the usual identity, resolving my issue.


Q:

Convert floating-point number to words

How do I get the word-equivalent of a floating-point number? E.g.

10.24 → ten point twenty-four
5.113 → five point hundred and thirteen

A:

There's a gem called numbers_and_words for that! I've used it in several projects without any problems so far.


Q:

Calculate 3D coordinates from 2D Image plane accounting for perspective without direct access to view/projection matrix

First time asking a question on the stack exchange, hopefully this is the right place.
I can't seem to develop a close enough approximation algorithm for my situation as I'm not exactly the best in terms of 3D math.
I have a 3d environment in which I can access the position and rotation of any object, including my camera, as well as run trace lines from any two points to get distances between a point and a point of collision. I also have my camera's field of view. I do not have any form of access to the world/view/projection matrices however.
I also have a collection of 2d images that are basically a set of screenshots of the 3d environment from the camera, each collection is from the same point and angle and the average set is taken at about an average of a 60 degree angle down from the horizon.
I have been able to get to the point of using "registration point entities" that can be placed in the 3d world that represent the corners of the 2d image, and then when a point is picked on the 2d image it is read as a coordinate with range 0-1, which is then interpolated between the 3d positions of the registration points. This seems to work well, but only if the image is a perfect top down angle. When the camera is tilted and another dimension of perspective is introduced, the results become more grossly inaccurate as there no compensation for this perspective.
I don't need to be able to calculate the height of a point, say a window on a sky scraper, but at least the coordinate at the base of the image plane, or which if I extend a line out from my image from a specified image space point I need at least the point that the line will intersect with the ground if there was nothing in the way.
All of the material I found about this says to just deproject the point using the world/view/projection matrices, which I find straightforward in itself except I don't have access to these matrices, just data I can collect at screenshot time and other algorithms use complex maths I simply don't grasp yet.
One end goal of this would be able to place markers in the 3d environment where a user clicks in the image, while not being able to run a simple deprojection from the user's view.
Any help would be appreciated, thanks.
Edit: Herp derp, while my implementation for doing so is a bit odd due to the limitations of my situation, the solution essentially boiled down to ananthonline's answer about simply recalculating the view/projection matrices.

A:

Between position, rotation and FOV of the camera, could you not calculate the View/Projection matrices of the camera (songho.ca/opengl/gl_projectionmatrix.html) - thus allowing you to unproject known 3D points?


Q:

How can I authenticate to my applications webservice after using Facebook SSO on Android?

I am creating an Android app that uses Facebook SSO to login and I'm not sure how to authenticate with my own webservices after I login to FB.  When a user first opens my app they login to Facebook, authorize my application some privileges, and continue into my app.  This part works great, but now to use my app they need to create an account on my server and talk to my webservices.
Right now I have a call to an authenticate webservice on my server that adds their Facebook ID and other basic info into a database and at the same time does a Diffie–Hellman key exchange so any future calls to webservices can be encrypted by a shared key.  But the problem is that very first initial call to create this account and create this shared key, how do I authenticate that?  How do I know this person is really the one who just authenticated with Facebook and not just someone who found the URL for my webservice and is creating accounts and saving the keys?

A:

Facebook SSO returns an access token. If you'd like, you can pass that along to your server and your server can make a call to the Facebook APIs to check that it's a valid access token for that user (eg by calling  https://graph.facebook.com/me?access_token=ACCESS_TOKEN) -- if it is, you're good and have verified that the user is who they say they are (or is a hacker with enough access to have a valid auth token for your app for Facebook, at which point their identity has been compromised on Facebook's end).


Q:

Serial port get memory command

Could anyone tell me how to format the serialport.write method in c# for the following get memory command of a digital multimeter?
DLE
 STX
 Command
 arg1
 arg2
 arg3
 DLE
 ETX
10h
 02h
 4Eh
 00h
 00h
 00h
 10h
 03h
Many thanks

A:

Try creating a byte array, and writing this to the port.
byte[] data = new byte[] {0x10, 0x02, 0x4E, 0x0, 0x0, 0x0, 0x10, 0x03};

port.Write(data, 0, data.Length);


Q:

WindowsError: [Error 2] The system cannot find the file specified, cannot resolve in Python

I have made a Python program which will clean up the unnecessary names present in my downloaded torrent files+folders, so that I can upload it to my unlimited Google Drive Storage Account without much hassle.
However, it gives me the: WindowsError: [Error 2] The system cannot find the file specified after certain number of iterations.If I run the program again, it works fine for a certain iterations and then the same error pops up.
Note that I have taken precautions using os.path.join to avoid this error but it keeps coming up. Because of this error, I have to run the program tens of times over a selected folder/drive.
Here is my program:
import os
terms = ("-LOL[ettv]" #Other terms removed
)
#print terms[0]
p = "E:\TV Series"
for (path,dir,files) in os.walk(p):
    for name in terms:
        for i in files:
            if name in i:
                print i
                fn,_,sn = i.rpartition(name)
                os.rename(os.path.join(path, i), os.path.join(path, fn+sn))
        for i in dir:
            if name in i:
                print i
                fn,_,sn = i.rpartition(name)
                os.rename(os.path.join(path, i), os.path.join(path, fn+sn))

And the Error Traceback:
Traceback (most recent call last):
File "E:\abcd.py", line 22, in <module>
os.rename(os.path.join(path, i), os.path.join(path, fn+sn))
WindowsError: [Error 2] The system cannot find the file specified

A:

Probably it's the problem with subdirectories due to the way os.walk works, namely path on next iteration after the first with subdirectories. os.walk gathers subdirectories' names to visit on further iterations on it's first iteration in current directory...
E.g., on first call to os.walk you get:
('.', ['dir1', 'dir2'], ['file1', 'file2'])

now you rename the files (this works ok), and you rename: 'dir1' to 'dirA' and 'dir2' to 'dirB'.
On next iteration of os.walk, you get:
('dir1', ['subdir1-2', 'subdir1-2'], ['file1-1', 'file1-2'])

And what happens here is there's no 'dir1' anymore, as it is already renamed on the file system, but os.walk still remembers it's old name in the list inside and gives it to you. Now, when you try to rename 'file1-1' you ask for 'dir1/file1-1', but on the file system it's actually is 'dirA/file1-1' and you get the error.
To solve this issue, you need to change the values in the list that is used by os.walk on further iterations, e.g. in your code:
for (path, dir, files) in os.walk(p):
    for name in terms:
        for i in files:
            if name in i:
                print i
                fn, _, sn = i.rpartition(name)
                os.rename(os.path.join(path, i), os.path.join(path, fn+sn))
        for i in dir:
            if name in i:
                print i
                fn, _, sn = i.rpartition(name)
                os.rename(os.path.join(path, i), os.path.join(path, fn+sn))
                #here remove the old name and put a new name in the list
                #this will break the order of subdirs, but it doesn't
                #break the general algorithm, though if you need to keep
                #the order use '.index()' and '.insert()'.
                dirs.remove(i)
                dirs.append(fn+sn)

This should do the trick and in described above scenario, will lead to...
On first call to os.walk:
('.', ['dir1', 'dir2'], ['file1', 'file2'])

now rename: 'dir1' to 'dirA' and 'dir2' to 'dirB' and change the list as shown above... Now, on next iteration of os.walk it should be:
('dirA', ['subdir1-2', 'subdir1-2'], ['file1-1', 'file1-2'])


Q:

Alamofire .POST encoding (.URL)

So, I'm trying to do a .POST request with Alamofire with the default option:
    Alamofire.request(.POST, url, parameters: parameters).validate().responseJSON

This one works just fine. As the documentation says, the default encoding for parameters is .URL.
Now I'm trying to improve my code creating routers following this guide:
https://grokswift.com/router/
In the end of the implementation is needed to encode the parameters manually. So, if the default was working, I'm using the .URL encoding here now, like so:
    let encoding = Alamofire.ParameterEncoding.URL
    let (encodedRequest, _) = encoding.encode(urlRequest, parameters: parameters)

Now the request won't work, as the parameters are apparently are being sent in the wrong format.
I'm pretty sure the API is functional, I'm testing it in Postman and the parameters are being sent with the form-data option.
Thanks in advance to anyone that can help me!

A:

If it was working before, double-check that it was using URL encoding:
let postRequest = Alamofire.request(.POST, url, parameters: parameters)
  .validate()
  .responseJSON { ... }
debugPrint(postRequest)

That should show you the equivalent cURL statement for your request.
Then change the router to use .URL encoding and see if debugPrint output changes.


Q:

Run multiple commands passed as an argument to a bash script

Here's the very simple file test.sh.
#!/usr/bin/env bash

$1

When I run ./test.sh "pwd; mkdir a;", it returns
./test.sh: line 3: pwd;: command not found

I tried to use '&' / '&&' / ';', but all don't work.
How can I run multiple command by arugment?

A:

You're trying to make bash interpret a string ($1) as if it were a script or typed commands. There are two ways to do that:

Use eval builtin: eval $1 instead of $1.
Run separate bash to evaluate the commands: bash -c "$1" instead of $1. Mind the quotes.


Q:

What is the difference between "Arduino Remote" and "Arduino Wiring"

When accessing an Arduino from Windows running on Intel chip (devices: Lattepanda, Udoo, Laptop) or Windows IoT running on Raspberry 3, what is the difference between "Arduino Remote" and "Arduino Wiring"?
Does Visual Micro's plugin for Visual Studio play any role in this decision?
thx!

A:

What is the difference between "Arduino Remote" and "Arduino Wiring"?

"Arduino Wiring" is to enable the use(port) of existing Arduino Wiring sketches(projects) on IoT Core devices, with little efforts. Eventually, you deploy and runs your code on IoT devices, no Arduino devices is involved. Under the hood, it makes use of the direct memory mapped driver of your IoT device, so you need to have that enabled in the device portal or likewise.
Here is a nice tutorial to get started from https://developer.microsoft.com/en-us/windows/iot/win10/lightning
"Arduino Remote", on the other hand, is to control your Arduino board through some means of communication protocols, USB, bluetooth, Wifi etc. It enables your UWP projects to have access to the various Arduino sensors with real ease by making use of the Windows Remote Arduino library.
You can find more information from  https://developer.microsoft.com/en-us/windows/iot/win10/wralanding.
and
https://github.com/ms-iot/remote-wiring


Q:

Zabbix Comparing Hashes of 4 different hosts

I currently have 4 web nodes that should all have the same contents. But i would like to create a trigger when any of the 4 contents changes. I currently monitor the hashes of the folders that the contents are in, this returns a hash value that i would like to compare using a trigger.
However the most recent solution that i've been able to find was from 2017, and i was wondering if there was a better way of doing this.
Also would i be able to do this using a discovery (LLD) trigger prototype?
Thanks in advance

A:

Monitoring the hash is a good way to ensure content is consistent. You can manually create a trigger confronting the items, but i don't think you can use a LLD.
The LLD can find all the needed items, but cannot create a trigger with multiple items in the way you need it.
The trigger would be something like
{host1:hash.last()} <> {host2:hash.last()} or {host2:hash.last()} <> {host3:hash.last()}

and with n hosts, you'll need n-1 conditions. I'm afraid that with many hosts, your best option is building a script to create the trigger, through API.


Q:

Can node modules read protractor parameters?

Is it possible for a node module to read a protractor parameter? I need to set a parameter in protractor conf.js and only run a particular part of the node module js file which is shared between 5 projects.
For example, in my conf.js:
exports.config = {
    runtime:'default'
}

I want to call protractor conf.js --runtime docker
And in my node_modules, I have an if condition:
if(browser.runtime==='docker') {
  //do something
}

I want to access the runtime parameter set in my protractor command line call inside the node module I have created. Is there anyway to do so?

A:

I figured it out.
For other files to use the command line arguments in protractor, they have to be defined in the params config and not anywhere else.
exports.config = {
    params: {
         runtime : 'default'
    }
}

And I can then do protractor conf.js --params.runtime docker and access this inside my node module as browser.params.runtime


Q:

Get list of phrases contained in a both a string and Array

Given a list:
let words = ["Apple", "the Banana", "Cherry"]

and a string:
let string = "The Apple was eaten before the Banana"

is it possible to easily get a list of phrases in the string that are in the array?
E.g. the result for the above would be:
let result = ["Apple", "the Banana"]

The follow is close, but only returns true or false:
let combinedResult = words.contains(where: string.contains)

A:

For my usecase, this took 27 seconds to run:
var words: [String] { Words.all.filter { self.contains($0) } }

whereas this took 1.5 seconds:
var words: [String] {

    var words = [String]()
    for word in self.components(separatedBy:" ") {

        if WordDictionary.all[word] != nil {
            words.append(word)
        }
    }
    return words
}


Q:

wrong css media syntax

What is wrong here?
<link rel="stylesheet" href='index-02.css'
      media="screen and (min-width: 481px and max-width:959px)">

Validating the code on this page I got an error:

Error: Bad value screen and (min-width: 481px and max-width:959px) for attribute media on element link: Expected whitespace or ) but saw a instead.

A:

Your syntax is slightly off.  Each expression needs to be contained within parentheses:
<link rel="stylesheet" href='index-02.css'
      media="screen and (min-width: 481px) and (max-width:959px)">

From the documentation:

Parentheses are required around expressions; failing to use them is an error.


Q:

Load desktop application on Windows startup

I have Java desktop application, which runs fine. I can double click on exe or run jar file and runs properly.
I want to load this application whenever system starts. How can I achieve this programmatically?
Or is there any tool available to create exe in such a manner, that once we install it creates shortcut in system startup folder.
I want it be system or code driven rather than individually placing exe in startup folder.

A:

You can set up the exe as a windows service with these steps:

open command prompt as administrator
type this:

sc.exe create <service_name> binPath= "<path to your exe> --service" DisplayName= "<somename>" start= "auto"