Delete all rows in sqlite database not working - iOS

Question: Im having an issue deleting all the rows in a sqlite table I created, I can delete from this table based on a condition, (name, date etc) however when I try to delete all the contents in the table it fails: Here is what I've tried:
-(void) deleteFromDB{
    NSLog(@"delete from DB method being called");

    NSString * deleteQuery = @"DELETE * FROM CLUB";
    [self deleteData:deleteQuery];
}

-(void)deleteData:(NSString *)deleteQuery{
    char *error;
    NSLog(@"Enter deleteData");

    if (sqlite3_exec(clubDB, [deleteQuery UTF8String], NULL, NULL, &error)==SQLITE_OK) {
        NSLog(@"CLUB info deleted");
    }else{
        NSLog(@"Failed");
       NSLog(@"Failed with %s", error);

    }
}

I get an output of failed.
NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
        return;
    }

cant delete is never printed
The error message is:
X"¿

*Update**
clubDB is of type sqlite3 (declared in .h as sqlite3*clubDB
error string updated above
**Update2*****
Here is the code for opeing/creating the database:
-(void) createOrOpenDB{
NSArray * path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * docPath = [path objectAtIndex:0];

dbPathString = [docPath stringByAppendingPathComponent:@"club.db"];
NSLog(@"path = %@",dbPathString);

char*error;

NSFileManager*fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:dbPathString]){

    const char * dbPath = [dbPathString UTF8String];

    //create db here
    if (sqlite3_open(dbPath, &clubDB)==SQLITE_OK) {
        NSLog(@"success");
        const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CLUB (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SUBJECT TEXT)";
        sqlite3_exec(clubDB, sql_stmt, NULL, NULL, &error);
        sqlite3_close(clubDB);
    }
}

}

Comment: Try setting `char *error = NULL;`.
Comment: You pass in a buffer for the error message, what does the buffer say?
Comment: You didn't try printing the error message???
Comment: Here's a hint: `NSLog(@"Failed with %s", error)`.
Comment: the error message is : Failed with X"¿
Comment: Update your code to show how you use the error string. What type is clubDB, is it a valid handle?
Comment: please see above for the update
Comment: I've never seen SQLite fail to give a good error message when it fails.  But of course it may not have "failed".  You need to capture the return code and print it.
Comment: (Wherever you copied that SQLite example from was not a particularly good source.)
Comment: @ott-- the error message that is returned is (null)
Comment: @HotLicks- how would I return the return code? the example I used is working mostly apart from what I want (deleting all from CLUB)
Comment: `sqlite_exec()` should return 0 on success, can you check that instead of `SQLITE_OK`?
Comment: @HotLicks- strangley enough, when i got into /library/application support/iPhone Simulator and then the relevant app, the database is not in the documents folder (where it should be), however it is working...have you ever come across this?
Comment: @ott-- unfortunately it says "sqlite_exec() is invalid in C99" and the application fails, not too sure what that means
Comment: Instead of simply testing the return code of sqlite3_exec (and effectively throwing it away if not "OK"), assign it to an int, and then test the int.  If you get a "bad" value, print it.
Comment: @ott-- the NSLog "CLUB info deleted is performed" - however it hasnt been removed from the DB
Comment: Where is the DB you're actually opening?  Print out the path you use in the SQLite open operation.
Comment: The table should still be there, only all rows should be deleted.
Comment: Sorry hot licks its there, i was looking at an old version in its path
Comment: @ott-- Yes I understand but the information is still within the rows, it hasnt been deleted.
Comment: @HotLicks- the error number is 21
Comment: `#define SQLITE_MISUSE      21   /* Library used incorrectly */` - got feeling 21 is a bad year.
Comment: @ott-- hmmmm interesting...ive no idea, its been a method that has not left me down till now.
Comment: We need more, like opening the database.
Comment: @ott-- updated above!
Comment: Don't close the DB when you want to do other actions later.
Answer: Your delete statement isn't valid SQL. To delete everything from CLUB it would be:
delete from CLUB

You don't need the star as it obviously affects the whole record.
Comment: Thanks for the reply however it is still failing


Can't enable user interaction with NSNotification

Question: I got a button, when I click this it set userInteraction: self.view.userInteractionEnabled = NO; this works, and if I click the button I can't click on it anymore. Then I got a receiveNotification that I call in another class.
- (void) receiveNotification:(NSNotification *) notification
{
   if ([[notification name] isEqualToString:@"EnableUI"]){
       self.view.userInteractionEnabled = YES;
       NSLog(@"Successfully received the %@ notification!",[notification name]);
   }
}

The program output tells me that the notification is received, since it prints out Successfully received the EnableUI notification! However, I still cannot click on the UI button...
Comment: first thing to test in this case, is self.view != nil ? (I assume so, but I always begin by testing trivial things) I would also make sure to perform the work on the main thread. You could also try a [self.view becomeFirstResponder]; after setting userInteractionEnabled to yes
Comment: self.view is nil, I tried the becomeFirstResponder, but this doesn't work
Comment: if self.view is nil, no wonder becomeFirstResponder does not work, try to know why the view isn't set, maybe put a NSLog("viewDidLoad") in the viewDidLoad method of your controller and look which is first (successfully received the %@ notification or viewDidLoad)
Answer: Instead of trying to set userInteraction on the view, which you don't seem to need in this case, why not set the interaction on the button itself?
.H
@property (strong, nonatomic) IBOutlet UIButton *buttonA;
@property (strong, nonatomic) IBOutlet UIButton *buttonB;
@property (strong, nonatomic) IBOutlet UIButton *buttonC;

.M
@synthesize buttonA, buttonB, buttonC;

- (void) receiveNotification:(NSNotification *) notification
{
   NSArray *buttonArray = [[NSArray alloc] initWithObjects:buttonA,buttonB,buttonC,nil];
   if ([[notification name] isEqualToString:@"EnableUI"]){
      for(UIButton* button in buttonArray) {
         UIButton *tempElement = [buttonArray objectAtIndex:i];
         tempElement.userInteractionEnabled = YES;
      }
      NSLog(@"Successfully received the %@ notification!",[notification name]);
   }
}

Comment: @nonuma The array solution is better and quicker. Put all the buttons in an array, and use a for-loop to set i in array.length as enabled or disabled
Comment: There must be another problem with your code, because this will work. Try using this as the for loop instead - for (UIView *view in self.view.subviews) view.userInteractionEnabled=YES;
Comment: I got some other buttons on the view that I also want to disable
Comment: @nonuma Have you even connected the view up to anything? What is it's value?
Comment: I'm using storyboard, the view is actually a navigation controller
Comment: Can you give me an example of putting the button that are on my storyboard in an array?
Comment: @nonuma self.navigationController.view.userInteractionEnabled = YES;
Comment: Actually it inherit from UIViewController
Comment: I've just tried the above code, but still, the notification is successfully received but I cannot click on the buttons...
Comment: Yes, I've connected the storyboard buttons with the property code
Comment: I've tried: if(self.view != nil) NSLog(@"view is not nil"); and the view is NOT nil...
Comment: I justt ried it, I've put a NSlog in the for loop and it prints it out twice, but it still doesn't work, I still cannot click on the buttons
Comment: @nonuma There is another problem with your code/subviews etc. if this isn't working..
Answer: UIOperations have to be done in main thread.
I suspect you are not on main thread. Please check it in notification method
NSLog(@"%i", [NSThread isMainThread]);

If not
Please check if you call postNotification method on main thread.
If it is the issue follow the link
When responding to NSNotifications, what is the best practice for updating UIViews
Answer: Use UIButton.tag to mark buttons which should be disabled.
#define BUTTON_TAG_UNAUTH 123

- (void)disableButtonWithReason:(NSUInteger)reason
{
    NSArray *views = [self.view subviews];
    for (UIView *button in views) {
        //first checking tag cause more efficiently
        if (button.tag == reason && [button isKindOfClass:[UIButton class]]) {
            ((UIButton*)button).enabled = false;
        }
    }
}

- (void)disableButtonsDueToUnauthorized
{
    [self disableButtonWithReason:BUTTON_TAG_UNAUTH];
}


Use flake8 on SConstruct files (from scons)

Question: I want to use flake8 to verify scons files (SConstruct, SConscript). Because scons implicitly imports the SCons module some names are available by default, like Program, Glob, Command. flake8 does not know about them and drops "undefined name 'Glob' [F821]" warnings.
How could I solve this?
Answer: For the implicit imports I've used, you can make them explicit with, e.g.:
from SCons.Script import (Command,
                          Glob,
                          Program)


Nest needs C wire - Goodman PGB024075-1

Question: Complete novice here trying to install a Nest thermostat in our new home. I hooked everything up according to the Nest guide, but the thermostat gave a power/battery error message. I've gathered that it needs a C wire, but it doesn't look like one is available from the older outside unit - Goodman PGB024075-1.
Photos of the outside unit wiring and diagrams here: https://photos.app.goo.gl/CqgssCF3EULeR7YY8
Edit: I think I finally found an applicable manual - https://drive.google.com/file/d/1RLIEJSde4Kr5889qODMiiCYcrvHgTp0G/view?usp=drivesdk
I've read through a good number of similar posts, and I understand that if no C connecter is available on the board (at least I couldn't find one), I should be able to splice(?) into one of the wires coming out of the 24v side of the transformer (Pic 2). Not the red wire though. If correct, where exactly would I do this?
There are already spare small wires running into the house to the thermostat (Pic 5), so I should just need a short length of extra wire (Google says 18/5?) and to know where to connect it.
Oddly, the two capped white wires at the bottom are seemingly not connected to anything (Pic 5). They appear to run back into the unit somewhere (Pic 6). Unsure if one of those could be used?
Haven't been able to find a manual online, so hopefully the photos of the wiring diagrams inside the panels are helpful.
I'd really appreciate any additional guidance on this!
Comment: Do you have an economiser fitted to your unit?
Comment: Hmm I'm not sure. I can take some additional photos of the outside of the unit tomorrow. Unless there is a better way to tell? Google was not too helpful
Comment: Take photos of the economizer plug (it's part of the control wiring in the unit, and sits in between the Y to the compressor contactor and the Y/Y2 going to the t-stat) and post them here
Comment: I think it's this? Pics 7a and 7b - https://photos.app.goo.gl/CqgssCF3EULeR7YY8. Tried to get two angles since the wires are bunched up against it.
Comment: That's not the connector I'm after, although it may be that your unit lacks it for some reason or another...
Comment: It's pouring rain here, so I won't be able to get more pictures for a bit. I think I finally found an applicable manual though: https://drive.google.com/file/d/1RLIEJSde4Kr5889qODMiiCYcrvHgTp0G/view?usp=drivesdk
Comment: Good find -- that rules out the economizer plug being an issue, at least.  Can you trace where both wires connected to the compressor contactor's coil go...? One of them should connect to the Y wire from your thermostat, while the other's connected to the various C wires in the unit...
Comment: Ok, added photos 8-13: https://photos.app.goo.gl/CqgssCF3EULeR7YY8
A
Pic 8 shows the larger yellow wire that's attached below to the tiny yellow wire going to the thermostat. From that plug, another yellow wire goes down into what's shown in Pic 9. The other yellow wire below that in Pic 9 goes down and outside the unit into some gray tube.A
Comment: Pic 10 shows three white wires that are attached on the other side of where the yellow wire is attached. a goes to a hole in the sidewall just above it (Pic 11). b goes down and then way back into the unit (Pic 12). And c goes up to the transformer (Pic 13)
Comment: Can you get us photos of the thing in the back of the unit wire b goes to?
Comment: Added pics 14-16. Oddly, once it gets towards the back it fades into light blue. And looks like it goes to a plug that's not connected to anything. I checked 6 times XD, 100% sure that's the white wire b. https://photos.app.goo.gl/CqgssCF3EULeR7YY8
Comment: OK, different approach -- do either of the unused white wires at the thermostat-cable-connection location have continuity to the chassis of the unit?
Comment: Added pics 17-18. Looks like they run back to the same empty plug. And they are actually orange and pink - https://photos.app.goo.gl/CqgssCF3EULeR7YY8
Answer: You'll need to do a bit of wiring work
Unfortunately, your unit doesn't expose the C terminal in a convenient place, so you'll have to do a bit of wiring to add it.  You'll need a ¼" "piggyback" tab terminal suitable for 18AWG wire like the Panduit one depicted below, a 3' length of 18AWG blue TFFN wire, and a wirenut suitable for 2 18AWG wires for this.

Crimp the tab terminal onto the 18AWG TFFN, then stuff it down through the grommet in the bottom of the wiring compartment alongside the other thermostat wires. Once that's in place, slide one of the tab terminals off of the C terminal (the one with the three white-ish wires on it) of the 24V transformer in your unit and slide the "piggyback" terminal on where the terminal you removed went, then slide the terminal you removed onto the tab provided by the "piggyback" terminal.  You can then wirenut the other end of that new blue wire to the wire in your thermostat cable you wish to use as a C wire.
Comment: Got it. Will get out to home depot and give this a shot. Thank you, I really appreciate all your help. Have a great rest of your weekend!
Comment: Is it alright to use 18 awg THHN wire? I haven't been able to find anywhere that will cut only a few feet of TFFN
Comment: @MikeSharp -- 18AWG THHN isn't a thing -- any building wire you get in that size will be either TFN or TFFN

Nest needs C wire - Goodman PGB024075-1


Do we have OpenGL shaders write out the intermediate *.o-esque file on first compile so that we can skip compiling them in run-time every single time?

Question: Shaders get compiled during runtime every single time an app starts. I understand the reasoning for this is that there are so many GPU architectures out there that it does not make sense to ship pre-compiled shaders. However, I wonder if the designers have explored the possibility of storing out the compiled shader during the first run and load the compiled version from the next run. This is akin to having the intermediate "*.o" as in C/C++ compilation and just linking them when we're building the app. If this is possible, is it a bad idea to do this?
Answer: OpenGL 4.1's glGetProgramBinary and glProgramBinary exist for this purpose. The first one retrieves a binary that represents the compiled program in its entirety (though none of the state stored within it. It, and its implementation-defined format, can be stored and reloaded via glProgramBinary.
Of course, there are limitations. Implementations are not required to be able to load the format they gave you. That is, a driver change could cause implementations to switch to a different versions, leaving all of your binaries obsolete and un-loadable. So you have to be ready to recompile from the source.
Alternatively, GL 4.6 allows you to employ SPIR-V, an intermediate shader language. The idea here is that you compile your code to SPIR-V, then load that SPIR-V into a shader, where you can move forward from there. There are no version changes that could break your code.
Of course, SPIR-V is an intermediate language, so it still has to be compiled to some degree, along with all of the error checking and the like needed to make the final GPU code. It won't be faster than program binaries, but it's a bit more reliable (for implementations that support it).


select sysdate from dual returns only date, not time

Question: In SqlDeveloper, when I run this query:
select sysdate from dual

I see only 15-FEB-16,
but not the time portion. I suppose that there is time portion, but somehow I can not see it. How to fix this?
Thanks.
Comment: http://stackoverflow.com/questions/8134493/how-can-i-set-a-custom-date-time-format-in-oracle-sql-developer
Answer: If you don't want/can't change the NLS settings, use the to_char function, but note that since then its a varchar type, not a date anymore! changing it back to date would display it according to NLS settings again
SELECT to_char(SYSDATE, 'yyyy-mm-dd hh24:mm:ss') from dual

this way you can define the format (using the mask) anyway you want
Answer: Change your NLS settings: Tools -> Preferences -> Database -> NLS
Changing Default Date Format settings


Pass Field from one page to another page in WPF using MVVM

Question: We are making a project where we have one page of our WPF application which will choose a save game out of three, and then it navigates to the next page. We whould like to know how to pass the GameInstance we load from the first page, to the second.
We have already implemented this in the Code Behind, but we dont like having logic in code behind, since we are using the MVVM architecure.
Code Behind of save window
public SaveGameWindow()
{
    InitializeComponent();
}

private void LoadGame1_Click(object sender, RoutedEventArgs e)
{
    var comb = new SaveGameViewModel();
    comb.LoadGame1();
    this.NavigationService.Navigate(comb.TempCombatWindow);
}

private void LoadGame2_Click(object sender, RoutedEventArgs e)
{
    var comb = new SaveGameViewModel();
    comb.LoadGame2();
    this.NavigationService.Navigate(comb.TempCombatWindow);
}

private void LoadGame3_Click(object sender, RoutedEventArgs e)
{
    var comb = new SaveGameViewModel();
    comb.LoadGame3();
    this.NavigationService.Navigate(comb.TempCombatWindow);
}

What we would like to know, is how to implement the same thing as above, but in our ViewModel for the save game.
The issue is when we change pages, we use the NavigationService, but this is not available in the ViewModel, and we have not found a way to bind this property to said ViewModel so we can use some kind of delegate.
I hope the question was not to confusing.
Answer: You can do this using an ICommand and command parameter in your view model and using an event.
You can implement an interface like this one for your commands.

In your View Model implement the interface and create a function like this:
private void LoadGame(object parameter)
{
   switch (parameter.ToString())
   {
       case "1":
           LoadGame1();
           break;
       case "2":
           LoadGame2();
           break;
       case "3":
           LoadGame3();
           break;
   }
   ComabtWindowHandler();
}
The handler will be the event handler that you will be implementing in code behind. But first you need an ICommand like this one:
public ICommand Load
 {
    get
    {
       RelayCommand<object> load= new RelayCommand<object((parameter) =>     LoadGame(parameter));
       return load;
    }
 }

This Property will be Bound in your xaml inside the Command property of your Save Buttons.

For the handler, first declare an abstract event handler in your View model
public EventHandler ComabtWindowHandler;
In your Main Window, when you load your View model just add the delagate that will handle the event, so add this piece of code(let's suppose that comb is the instance of your viewmodel):
comb.ComabtWindowHandler += delegate
{
   this.NavigationService.Navigate(comb.TempCombatWindow);
};
Finally in the xaml, in your 3 buttons bind Command and define the CommandParameter properties (in my example, the command parameter are simply "1" or "2" or "3". Of course button 1 will have parameter = "1" ecc...) but you can do more complicated stuff
Comment: Worked like a charm. Thanks alot mate


Does The Wither have preferred targets?

Question: I want to make a "custom" and special Wither cage. For that, I want to know: Of any of the passive mobs, which one would be most likely to be targeted by wither?

Dog
Snow Golem
Iron Golem
something else, like a villager

The cage shouldn't be closed, because I want to be able to keep the wither as focused on its target as possible.
Comment: Minecraft version? It might not matter but would help when testing.
Comment: The last one, 1.11 I think
Answer: It seems that Withers prioritize Iron Golems over other mobs. I tested this by spawning a bunch of different mobs far apart from each other, then spawning a few Withers. All of them attacked the Iron Golems before heading towards other mobs.
Video 1: Do Withers attack mobs closest to them?
Result: Yes
Video 2: Pigs VS Iron Golems
Result: Iron Golems > Pigs
Video 3: Wolves VS Iron Golems
Result:  Iron Golems > Wolves
Video 4: Pigs VS Wolves
Result: Closest mob

Does The Wither have preferred targets?


mvc 4 Model is null

Question: i'm using razor's listboxfor for the first time, but my Model is always null.
after reading similar posts and tryouts it still won't work.
Person.cshtml
@model SampleApp.Web.ViewModel.PersonViewModel

@{
     ViewBag.Title = "Welcome";
}

      Welcome to example page.

 //Post data works as expected, controllers create method write to db successfully
 @using (Html.BeginForm("Create", "Person", FormMethod.Post, new { enctype =   "multipart/form-data" }))
 {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Personen</legend>

           @* @Html.LabelFor(model => model.Name)

            @Html.EditorFor(model => model.Age)
            @Html.ValidationMessageFor(model => model.Age)

            @Html.LabelFor(model => model.Surrname)

</fielset>

    <input type="submit" value="Create" />

}

//binding to Model fails, Model is null. Not be able to debug anything in    controller action, it stops when "loading" the page
@using (Html.BeginForm("GetListBoxData", "Person"))
{
   @Html.AntiForgeryToken()
   @Html.ValidationSummary(true)
   @Html.ListBoxFor(model => model.ListboxData, Model.ListboxData);
}

PersonController.cs
[AcceptVerbs(HttpVerbs.Get)]
    [ValidateAntiForgeryToken]
    public ActionResult GetListBoxData()
    {
        var data = new List<PersonViewModel>();
        data.Add(new PersonViewModel{Name = "Test", Surrname="testsurrname", Age=30});

        var viewModel = new PersonViewModel()
        {
            ListboxData = data.AsEnumerable().Select(s=> new SelectListItem{Value=s.Name ,Text = s.Surrname}),
        };

        return View(viewModel);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    [ValidateAntiForgeryToken]
    public ActionResult GetListBoxData(PersonViewModel persondata)
    {
        //TODO: handle values from View
        return View(this);
    }

    [ValidateAntiForgeryToken]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create([Bind(Include = "Name, Surrname, Age")]  PersonViewModel persondata)
    {
        try
        {
            PersonService personDataProvider = new PersonService();
            personDataProvider.SavePerson(persondata);

            return new RedirectResult("SomewhereToGo");
        }
        catch (DataException ex)
        {
            //TODO: Log
        }

        return View(this);
    }

PersonViewModel
public class PersonViewModel
{
    public int PersonId{ get; set; }
    public int Age { get; set; }
    public string Name { get; set; }
    public string Surrname { get; set; }
    public IEnumerable<SelectListItem> ListboxData { get; set; }
}

writing values from editFor to db works as expected without code for listboxfor.
after adding it to my html it should be filled from db on page loading, but I get a ReferenceNotSet Exception on page loading. Model.ListboxData is null, before GetListBoxData action is called.
Thanks a lot for your help!
Comment: Person.cshtml?  Your controller is Index.... do you have a Person action?  because by default it will route through that.  Normally you'd have index.cshtml
Comment: Why is there a "" in your view file after the model declaration?
Comment: oh sorry, there is some html code before, copy&pasted from cshtml
Answer:
Your form should submit the data via POST, not GET. And, you don't need to use enctype = "multipart/form-data", unless you want to upload files through your from.
You need two Index Actions in your Controller, one is for sending the data from your Controller to the View, and the other one is for getting the data back from the View, when the form is submitted (POST) to the server.
The first argument you pass to your ListBox (the expression) refers to the Property in your Model that the selected item from your ListBox will be stored in, which in this case is PersonId.

So, your View should look like this:
@model MVCApplication.Web.ViewModel.PersonViewModel

@using (Html.BeginForm("Index", "Person"))
{
    @Html.ListBoxFor(model => model.PersonId, Model.ListBoxData)

    <input type="submit" value="Save" />
}

Then, in your Controller, you'll have two Actions like this:
public ActionResult Index()
{
    var viewModel = new PersonViewModel()
    {
        ListboxData = data.Select(s => new SelectListItem { Value = s.PersonId.ToString(), Text = s.PersonId.ToString() }).AsEnumerable();
    };

    return View(viewModel);
}

[HttpPost]
public ActionResult Index(PersonViewModel viewModel)
{
  // code to save the data in the database or whatever you want to do with the data coming from the View
}

By the way, in your ViewModel, you don't have to define your ListBoxData property like that, just do this:
public class PersonViewModel
{
    public int PersonId{ get; set; }
    public IEnumerable<SelectListItem> ListBoxData { get; set; }
}

Comment: thanks for clarification but problem still exists (Model is null). I've a few EditorFor Elements in my Html which are wired with a create method in controller -> database.this works fine. Debugging in Controllers Index methods doesn't work, it crashes before when initializing the page, model is null.Does it has to be set explicitly somewhere for null check? thanks for your time
Comment: What do you mean it crashes?
Comment: it stops in my cshtml with a reference not set exception (because Model is null)
Comment: Are your Actions exactly like the ones in my answer?  Do you get the correct data from the database in your Action?
Comment: The Model being null doesn't have anything to do with the ListBox.
Comment: they are nearly the same, I've updated my question and html with full code and comments. yes model bindin has nothing to do with listboxfor, but that's the only time I would like to use Model property (currently).
Comment: Why do you have two forms in your View? How come this is even nearly close to my answer?
Comment: sorry there's a curly brace at the end of first form. Why shouldn't work it with two forms?
Comment: It should work, but it doesn't make sense. There's no submit button in the second form, so how do you expect the form to be posted to your Controller. It's not clear what you want to do with your second form.  Please update your question, and explain what you want to achieve.
Comment: What I need to know is what you want to do with your ListBox? What do you expect to happen when you select an option from the ListBox? You shouldn't have two forms like that in your View.
Comment: Also, post your PersonViewModel completely. You've just posted a porting of it.
Comment: there're only two properties in my viewmodel, as much as I currently need for my html
Comment: So, what's this: `@Html.EditorFor(model => model.Age)`? It seems like you don't have any idea what you are doing.
Comment: again, problem is in ListBoxFor that Model.ListboxData -> MODEL is null! it has nothing to to with first form (where i'm using some editorFor fields). when i comment out all except of second form (where i'm using listboxfor), it's still not working.

mvc 4 Model is null


recent nvidia-304 upgrade broke system

Question: Ubuntu 16.04
nvidia-304 proprietary driver installed and updated via the Nvidia ppa
(for GT 620)
The system was running fine for 6 months  but recently broke (not possible to get past login screen) with an nvidia-304 update failing to build. any advice on how to fix this would be very much appreciated
apt purge nvidia* && apt install nvidia-304

.........
[output truncated for clarity]
Loading new nvidia-304-304.137 DKMS files...
First Installation: checking all kernels...
Building only for 4.15.0-24-generic
Building for architecture x86_64
Building initial module for 4.15.0-24-generic
Error! Bad return status for module build on kernel: 4.15.0-24-generic (x86_64)
Consult /var/lib/dkms/nvidia-304/304.137/build/make.log for more information.
Setting up nvidia-opencl-icd-304 (304.137-0ubuntu0~gpu16.04.1) ...
Setting up nvidia-settings (396.24-0ubuntu0~gpu16.04.1) ...
Processing triggers for libc-bin (2.23-0ubuntu10) ...
Processing triggers for initramfs-tools (0.122ubuntu8.11) ...
update-initramfs: Generating /boot/initrd.img-4.15.0-24-generic

tail -20 /var/crash/nvidia-304.0.crash
      nvl->rc_timer.data = (unsigned long) nv;
                   ^
 cc1: some warnings being treated as errors
 scripts/Makefile.build:332: recipe for target '/var/lib/dkms/nvidia-304/304.137/build/nv.o' failed
 make[3]: *** [/var/lib/dkms/nvidia-304/304.137/build/nv.o] Error 1
 Makefile:1552: recipe for target '_module_/var/lib/dkms/nvidia-304/304.137/build' failed
 make[2]: *** [_module_/var/lib/dkms/nvidia-304/304.137/build] Error 2
 NVIDIA: left KBUILD.
 nvidia.ko failed to build!
 Makefile:261: recipe for target 'module' failed
 make[1]: *** [module] Error 1
 makefile:59: recipe for target 'module' failed
 make: *** [module] Error 2
DKMSKernelVersion: 4.15.0-24-generic
Date: Fri Jul  6 23:06:48 2018
DuplicateSignature: dkms:nvidia-304:304.137-0ubuntu0~gpu16.04.1:/var/lib/dkms/nvidia-304/304.137/build/nv.c:3032:5: error: implicit declaration of function 'init_timer' [-Werror=implicit-function-declaration]
Package: nvidia-304 304.137-0ubuntu0~gpu16.04.1
PackageVersion: 304.137-0ubuntu0~gpu16.04.1
SourcePackage: nvidia-graphics-drivers-304
Title: nvidia-304 304.137-0ubuntu0~gpu16.04.1: nvidia-304 kernel module failed to build

tail -20 /var/lib/dkms/nvidia-304/304.137/build/make.log
/var/lib/dkms/nvidia-304/304.137/build/nv.c:3032:5: error: implicit declaration of function 'init_timer' [-Werror=implicit-function-declaration]
     init_timer(&nvl->rc_timer);
     ^
/var/lib/dkms/nvidia-304/304.137/build/nv.c:3033:28: error: assignment from incompatible pointer type [-Werror=incompatible-pointer-types]
     nvl->rc_timer.function = nv_kern_rc_timer;
                            ^
/var/lib/dkms/nvidia-304/304.137/build/nv.c:3034:18: error: 'struct timer_list' has no member named 'data'
     nvl->rc_timer.data = (unsigned long) nv;
                  ^
cc1: some warnings being treated as errors
scripts/Makefile.build:332: recipe for target '/var/lib/dkms/nvidia-304/304.137/build/nv.o' failed
make[3]: *** [/var/lib/dkms/nvidia-304/304.137/build/nv.o] Error 1
Makefile:1552: recipe for target '_module_/var/lib/dkms/nvidia-304/304.137/build' failed
make[2]: *** [_module_/var/lib/dkms/nvidia-304/304.137/build] Error 2
NVIDIA: left KBUILD.
nvidia.ko failed to build!
Makefile:261: recipe for target 'module' failed
make[1]: *** [module] Error 1
makefile:59: recipe for target 'module' failed
make: *** [module] Error 2

Answer: Never did find an answer to this one except that it was a fairly wide-spread issue. Purging the nvidia drivers so as to fall back on the open source nouveau drivers got the system back up and running
Comment: Another option is to use the kernel provided by linux-generic package.
Answer: Had similar problems. You need patched drivers for Bionic.
It turns out that that driver is marked EOL for 20.04 fossa.

For NV4x and G7x GPUs use nvidia-304 (304.137) End-Of-Life!

So I recommend also for that if you have graphics card of that family to not to use latest Linux.
The latest working for me was kernel 4.15 which comes with Ubuntu Bionic Beaver 18.04. The default kernel if you install 18.04 is 5.4 so it must be downgraded.
Resources for further research was the most helpful here:
https://bugs.launchpad.net/ubuntu/+source/nvidia-graphics-drivers-304/+bug/1737750
Links helped me a lot

https://adufray.com/blog/2018/06/02/nvidia-304-127-on-bionic
https://www.if-not-true-then-false.com/2015/fedora-nvidia-guide/4/

to create my own patched binary.
If you need it without going too much into details - it can be found here
https://sites.google.com/view/tpanj/files/nvidia-legacy

recent nvidia-304 upgrade broke system


Why do Ionic Lifecycle hooks (ionViewWillEnter, ionViewWillLeave) not fire when used as HTML Selector?

Question: I am working on an Angular Project, with Ionic 4.
When Child Page is called from Parent Page's HTML using HTML Selector, child page's Ionic Lifecycle Hooks do not fire.
Why is it so? How do I use these hooks?
Child Page:
<code>@Component({
  selector: 'app-child',
  templateUrl: './child.page.html',
  styleUrls: ['./child.page.scss']
})

export class ChildPage {

     ionViewWillEnter() {
         console.log(`ionView-Will-Enter`);
         // Code goes here...
     }

     ionViewWillLeave() {
         console.log(`ionView-Will-Leave`);
         // Code goes here...
     }
}
</code>
Parent HTML:
<code><ng-container>
    <app-child></app-child>
</ng-container>
</code>
Answer: Ionic Page lifecycles executes on routing components, so you have to use routes in order to this work. Chek it here.
Of course you can use the Angular lifecycle hooks in this case.
Note that you can load components/pages to your template via selector and via routes.
EDIT:
Here you have a stackblitz to make some test. Note the logs provided by execution of Angular example component lifecycle hook OnInit and the Ionic pages lifecycles.
I've added logs for ngOnInit, ngAfterViewInit, and ngOnDestroy Angular lifecycles hooks to the stackblitz. You can see that works fine and maybe this ones fits your needs.
Comment: Is not posible that the Ionic life cycles got executed with that structure. The render of the component happens via selector and the Ionic life cycles of a component occurs when that component renders hitting to its corresponding route. Is not the same thing Angular lifecycle hooks and Ionic life cycles. In your case you could still using Angular lifecycle hooks for ChildComponent, but not Ionic life cycles.
Comment: How do I add a child's page to parent's template via routes?
Comment: Remember that he outlet acts as a placeholder to load the page that match the current route. Normally you have an `` on the top of your app so if you define a new route pointing a page, when you hit that route the page loads in that outlet, but if you want to load the page inside a specific parent page, you have to include an outlet in this parent page. I'm going to add an example to the answer.
Comment: I want my code to route to the child page, when the condition is true for the ng-container, in the Parent Page. I don't want an click event, or anything manually, for the routing to happen. Can that be done?
Comment: You could `import { Router } from '@angular/router';` in your parent component, inject it `constructor(private router: Router) { ... }` and then use `this.router.navigateByUrl('urlString');` or `this.router.navigate(['routeSegment']);`  to navigate to a specific route programatically. You also need to include the route for that component in the array of routes in the module or routing module that you choose to load the component. `{path: 'child', component: ChildComponent}`. For more info you could check the oficial doc at https://angular.io/guide/router
Comment: But how do I do it from the parent's html ?
Comment: In the html you can show/hide elements (via selector) with Angular *ngIf directives. The use case of this directive is show/hide parts of your page, not to simulate navigation to another page.
Comment: I understand it is to show/hide.
Based on my condition, I wanted to show the child component (example added below), but the ionic lifecycle hooks did not fire, so I wanted to know if it is possible (from the Parent's html page itself) to call the Child component and also have the hooks.


Check if the first css file of a link tag exists in pure javascript

Question: This code is used to refresh the current page if the first <link /> could not be opened or if it has changed path.
Old path: /v1/css/main.min.1614693445663.css
New path: /v1/css/main.min.16146934488888.css
This is due to a cache problem in order to avoid losing the user.
// refresh if the client (in nodejs) does not find the first css file because of an old cache for example
$.ajax({
  url: $("link[rel='stylesheet']").attr('href'), //This can be the first <link of the page
  type: 'HEAD',
  error: function() {
    setTimeout(function() {
      document.location.reload();
    }, 3000);
    //file not exists
  },
  success: function() {
    //file exists
  }
});

How to convert this Jquery code into pure JavaScript?
Comment: Please don't ask us to rewrite this from jQuery to plain JS for you. This is a very basic AJAX request, and how those work in plain JS, you can go read up on yourself. Make a proper attempt, and if you run into trouble with that, then show us what you tried - then we can try and help you figure out, what went wrong.
Comment: While what you're trying to do may well be possible through client-side JS, why not set caching rules on your CSS on the server side (ie. via headers, not the actual filename) to avoid the issue in the first place?
Answer: Content page:
<link href="/v1/css/main.min.1614781878390.css" rel="stylesheet" />
New code:
// refresh if the client does not find the first css file
var qs = document.querySelector("link[rel='stylesheet']");
var MrChecker = new XMLHttpRequest(),
  CheckThisUrl = qs.getAttribute('href');

MrChecker.open('get', CheckThisUrl, true);
MrChecker.onreadystatechange = checkReadyState;

function checkReadyState() {
  if (MrChecker.readyState === 4) {
    if ((MrChecker.status == 200) || (MrChecker.status == 0)) {
      //alert(CheckThisUrl + ' page is exixts');
    }
    else {
      //alert(CheckThisUrl + ' not exists');
      setTimeout(function(){document.location.reload();}, 2000);
      return;
    }
  }
}

MrChecker.send(null);

I got there, I was inspired by https://jsfiddle.net/pu3antasyah/v95Loyvu/


store array of cllocation value in userdefaults iphone sdk

Question: hi i have an array of cllocation values, i need to store that array in userdefaults...how do i do it...?
hi these where i add object to my array:
 [AM_locationMP.favArray addObject:[AM_locationMP.locationData objectAtIndex:AM_locationMP.indexno]];
where location data is array of location placemark values .
where maplocationVO class is for placemark
MapLocationVO *currentMapLocation;
[AM_delegate.locationData addObject: currentMapLocation];
Answer: Why do people post on here when they clearly don't know the answer, or understand what you can and cannot store in NSUserDefaults?

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide. -- From the documentation

You need to use NSKeyedArchiver to turn the CLLocation data into NSData. Then use NSKeyedUnarchiver to turn the NSData back into CLLocation data.
The next problem to solve is when you archive CLLocation objects and store them in UserDefaults, the don't unarchive properly. The only solution may be to save them to file instead.
Answer: this should be enough to write it:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:yourArray forKey:@"clArray"];
[defaults synchronize];

Comment: i tried that but it gives  *** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '( "" )' of class '__NSArrayI'.
Comment: post your code then, where you declare yourArray and all the object you insert in it... the problem seems to be an inappropriate object somewhere...
Comment: yep the problem was an inappropriate object, what i was tring to do was inserting an nsobject class object into an array and storing that array into nsuserdefault, hence which according to doc does not come in userdefault specified list, hence solution was to archive the nsobject class. and it worked like charm thks ...for pointing me to rt direction
Answer: use this
for setting array
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

  [standardUserDefaults setObject:yourArray forKey:@"array"];
  [standardUserDefaults synchronize];

and for getting array
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

  [standardUserDefaults setObject:yourArray forKey:@"array"];

NSMutableArray *array=[standardUserDefaults objectForKey:@"array"];

Comment: have tried doing that but it gives *** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '(
    ""
)' of class '__NSArrayI'.
Comment: make array mutable by using mutableCopy function.
Comment: still am getting *** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '(
    ""
)' of class '__NSArrayM'.
Comment: you need to check your objects present in Array try to manage those objects and also make array as property of the class.
Comment: i am setting the property of array as nonatomic retain, and i do chk object of my array thn also same error ...
Comment: @devonsmith sorry bro without debugging i cant help you more than this.good luck


How do I get Gajim to show up in Unity's system tray?

Question: I know how to whitelist most other applications, but adding 'Gajim' and 'gajim' doesn't seem to work.
Does it have an appindicator?
Answer: Well, in a strange twist, killing Gajim and restarting it seems to have worked.
Apparently the correct value is Gajim.
Answer: Maybe it'd be a better idea to install "Ubuntu Ayanta Integration" or a similar plugin instead.  See http://trac-plugins.gajim.org/wiki/UbuntuIntegrationPlugin for instance.
Comment: Welcome to Ask Ubuntu! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


Converting XLL addin functionality to a native VB module : Problem refreshing formulae

Question: I have a .xll plugin that registered a few functions which we use in our excel sheets in a number of places. The performance was very poor, and we didn't have the original code, so we replicated the functionality by writing the functions in VB in a module. The functions work as expected and performance is much better.
The problem is the sheets do not automatically recognize the new functions. For example, suppose a cell's formula is "=CustomFunction()" which was earlier defined in the xll, and now has been defined in the VB. This will keep showing as "#NAME" unless I manually edit the cell, and press enter. It then correctly picks up the VB formula and calculates.
The standard tricks of recalculating formulaes : Ctrl/Alt/Shift/F9 haven't worked.
Has any one experienced this? Any idea how to solve this?
Answer: I would do a global search and replace from =CustomFunction to =TempCustomeFunction.  Then a global rename back to =CustomFunction.  This will force Excel to re-evaluate the functions.  (I have a vague idea that you might need to save, shutdown and restart after he first replace, but try it first to be sure).
I am pretty sure I have encounted a similar problem and doing that fixed it for me.  I guess if you have a lot of workbooks to fix, you might need to do this via automation.


Constraints are not allowed on not generic environment error while casting

Question: I am trying to cast Java lang object to particular class type(Account).
public static T Cast(Object obj) where T : class
{
    var propertyInfo = obj.GetType().GetProperty("Instance");
    return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
}

It is throwing an error

Constraints are not allowed on not generic environment.

I've been stuck here for the past two days.
Comment: @mok The param he is passing is a `Java.Lang.Object`, a `Xamarin.Android` MCW to a JNI wrapped C# class. In this case, nothing to due with his actual problem.
Comment: @mok https://developer.xamarin.com/guides/android/advanced_topics/java_integration_overview/working_with_jni/#Class_Binding
Comment: You have not defined T anywhere, you are just using it.
Comment: this question has nothing to to with Xamarin and it's not a Java lang object as you use C#.
Comment: @slfan Yes, I was thinking where is the Java part?!
Comment: @SushiHangover Oh, great. I've never used that, and I should give it a try if you can pass Java Object (the root of everything in Java) like that to a c# method.
Answer: You have to add the generic type parameter <T> to your method
public static T Cast<T>(Object obj) where T : class
{
    var propertyInfo = obj.GetType().GetProperty("Instance");
    return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
}


RefineryCMS - Custom Image Engine using Dragonfly for Multiple Resize on upload - MassAssign Error when trying commit uid to database

Question: I've learnt much from the invaluable resource stackoverflow is. I am exceedingly greatful for the many excellent contributions made. Long live open source and those that make it real!
For all the great information here already, I have not been able to find the right approach to my issue here. Let me explain.
Using RefineryCMS v. 2.0.9 I have generated an engine within a rails app for presentation of 'Portfolios'. A 'Portfolio' has_many ':exhibits'. ':exhibit' belongs_to ':portfolio' as per models below.
It is intended that model attribute :img_orginal - contains the uid for the Dragonfly image upload. This works as it should, image upload uid is commited to database and can be called to views/portfolios/show.html.erb view as intended. It is intended the site be responsive. If it is to be responsive, it needs a suite of resized thumbs generated from the original. These need to be generated by Dragonfly when :img_original is uploaded and commited via the backend form. So far I have been unable to achieve this using the Dragonfly image_accessor within the exhibits model. I receive the followin exception upon creation attempt.
Can't mass-assign protected attributes: img_original
ActiveModel::MassAssignmentSecurity::Error in Refinery::Portfolios::Admin::ExhibitsController#create
Both databases exist and are linked correctly via ':portfolio_id' foreign key in the 'exhibits' model. All model attributes are whitelisted as per current rails best practice.
What am I missing? The controller methods aren't right I assume, I cannot figure out how they should be. Is it necessary to ammend the engine controller to call in an instance the Page Image class, or Dragonfly itself? Do I need to change routes.rb. Could someone advise how I'd define the Controller's create and update methods. Is it even necessary, given they should already be defined by page_images controller of the main refinery app.
I have experimented with methods suggested in the Dragonfly documentation using image_accessor to no avail. Here are some of the approaches taken thus far.
ie.
image_accessor :img_original do
after_assign :crop_thumb     #method defined below
            #:resize_mobile,
            #:resize_tablet,
            #:resize_desktop
# OR
#  copy_to(:img_thumb) do
#    |a| a.thumb('100x100')
#    end
# OR different block syntax
#  copy_to(:img_thumb) do {|a| a.thumb('100x100')}
end

def crop_thumb
  @exhibit.img_thumb = @exhibit.img_original.process(:resize_and_crop,
                                                     :width => 100,
                                                     :height=> 100,
                                                     :x => :x_focus,
                                                     :y => :y_focus).encode(:jpg, '-quality 60').apply
end

#def resize_mobile,
   @exhibit.img_mobile = @exhibit.img_original.process(etc.
#end

#def resize_tablet,
   etc.

I'm very new to this, I've persisted thus far researching all I can to achieve it. And yet I come to this and cannot crack it. I would appreciate any assistance one might offer.  Thank you.
Code examples and environment info below.
Environment;
Ubuntu 12.10
RubyMine IDE
Ruby 1.9.3
RVM to handle gems
Rails 3.2.9
SQLite dev database
RefineryCMS (including page_images and inquiries plugins)
Dragonfly 0.9.14
Portfolio Engine generated with these migrations
 # This migration comes from refinery_portfolios (originally 1)
 class CreatePortfoliosPortfolios < ActiveRecord::Migration

 def up
 create_table :refinery_portfolios do |t|
  t.string :title
  t.integer :year
  t.text :description
  t.integer :publication_id
  t.integer :commentary_id
  t.integer :position
  t.timestamps
end
end

def down
if defined?(::Refinery::UserPlugin)
  ::Refinery::UserPlugin.destroy_all({:name => "refinerycms-portfolios"})
end

if defined?(::Refinery::Page)
  ::Refinery::Page.delete_all({:link_url => "/portfolios/portfolios"})
end

drop_table :refinery_portfolios
end
end

And
# This migration comes from refinery_portfolios (originally 2)
class CreatePortfoliosExhibits < ActiveRecord::Migration

def up
create_table :refinery_portfolios_exhibits do |t|
  t.string :title
  t.integer :cat_num
  t.integer :year
  t.string :medium
  t.integer :width
  t.integer :height
  t.integer :img_original_id
  t.string :img_thumb
  t.string :img_mobile
  t.string :img_tablet
  t.string :img_desktop
  t.integer :x_focus
  t.integer :y_focus
  t.text :history
  t.integer :portfolio_id
  t.boolean :sold
  t.integer :position

  t.timestamps
  end

  end

def down
 if defined?(::Refinery::UserPlugin)
  ::Refinery::UserPlugin.destroy_all({:name => "refinerycms-portfolios"})
end

if defined?(::Refinery::Page)
  ::Refinery::Page.delete_all({:link_url => "/portfolios/exhibits"})
end

drop_table :refinery_portfolios_exhibits

end

end

And refinery_portfolios_exhibits table column headers changed
 Exhibits table column header changed via migration
 class FixColumnName < ActiveRecord::Migration
  def change
   rename_column :refinery_portfolios_exhibits, :img_original_id, :img_original_uid
   rename_column :refinery_portfolios_exhibits, :img_thumb, :img_thumb_uid
   rename_column :refinery_portfolios_exhibits, :img_mobile, :img_mobile_uid
   rename_column :refinery_portfolios_exhibits, :img_tablet, :img_tablet_uid
   rename_column :refinery_portfolios_exhibits, :img_desktop, :img_desktop_uid
  end
 end

Portfolio Model contains portfolio metadata, called 'portfolio.rb'
has_many exhibits
    module Refinery
    module Portfolios
    class Portfolio < Refinery::Core::BaseModel
      self.table_name = 'refinery_portfolios'
  attr_accessible :title,
                  :year,
                  :description,
                  :publication_id,
                  :commentary_id,
                  :position

  acts_as_indexed :fields => [:title]

  validates :title, :presence => true, :uniqueness => true

  belongs_to :publication, :class_name => '::Refinery::Resource'
  belongs_to :commentary, :class_name => '::Refinery::Resource'

  # destroy all exhibits when a portfolio is destroyed
  has_many :exhibits, :dependent => :destroy

end
end
end

Exhibit Model contains image link and associated metadata, called 'exhibit.rb';
belongs_to portfolio
require 'dragonfly/rails/images'

module Refinery
module Portfolios
class Exhibit < Refinery::Core::BaseModel

attr_accessible   :title,
                  :cat_num,
                  :year,
                  :medium,
                  :width,
                  :height,
                  :img_original_uid,   #image upload uid from refinery_images table
                  :img_thumb_uid,      #commit resize uid here
                  :img_mobile_uid,     #here
                  :img_tablet_uid,     #here
                  :img_desktop_uid,    #and here
                  :x_focus,
                  :y_focus,
                  :history,
                  :portfolio_id,   #foreign key, associates exhbit with portfolio
                  :sold,
                  :position

  acts_as_indexed :fields => [:title, :medium, :year, :cat_num]

  validates :title, :presence => true, :uniqueness => true
  validates :year, :length => { :is => 4,
                                :message => "Four digit year format,(yyyy) eg. 2013"}
  validates :img_original_uid, :presence => true, :uniqueness => true
  validates :portfolio_id, :presence => true
  validates_associated :portfolio
  validates :x_focus, :presence => true
  validates :y_focus, :presence => true
  validates :sold, :inclusion => {:in => [true, false]}

  belongs_to :img_original, :class_name => '::Refinery::Image'
  belongs_to :portfolio, :class_name => 'Portfolio', :foreign_key => 'portfolio_id'
  end
  end
  end

Controller 'admin/exhibit.rb'
 module Refinery
  module Portfolios
   module Admin
    class ExhibitsController < ::Refinery::AdminController
      before_filter :find_all_portfolios

      crudify :'refinery/portfolios/exhibit', :xhr_paging => true

      protected

      def find_all_portfolios
        @portfolios = Refinery::Portfolios::Portfolio.all
      end

    end
  end
 end
end

Controller 'exhibit.rb'
 module Refinery
 module Portfolios
  class ExhibitsController < ::ApplicationController

   before_filter :find_all_exhibits
   before_filter :find_page

  def index
    #@exhibits = Exhibit.all(:include => :portfolio)

    # you can use meta fields from your model instead (e.g. browser_title)
    # by swapping @page for @exhibit in the line below:
    present(@exhibit)
  end

  def show
    @exhibit = Exhibit.find(params[:id])

    # you can use meta fields from your model instead (e.g. browser_title)
    # by swapping @page for @exhibit in the line below:
    present(@exhibit)
  end

  protected

  def find_all_exhibits
    @exhibits = Exhibit.order('position ASC')
  end

  def find_page
    @page = ::Refinery::Page.where(:link_url => "/exhibits").first
  end

   end
  end
 end

Answer: I am guessing you don't really care about this any more since you asked 10 months ago, but in your exhibit model have you tried changing
attr_accessible :img_original_uid

to
attr_accessible :img_original

The error comes on the img_original field, yet you are giving accessibility to img_original_uid. I am new to dragonfly as well...


How to parcel class object that contains hash map? Kotlin

Question: I'm trying to pass a custom array list from one activity to another using  intent.putParcelableArrayListExtra.
So I implemented Parcelable in my class object:
class AudioModel(audioTitle:String,map:HashMap<String, Any>):Parcelable{

    var title:String=""
    var artistName:String=""
    var urlLink:String=""

    init{
        title=audioTitle
        urlLink=map["url"].toString()
        artistName=map["artist"].toString()
    }
}

and after adding parcelable implementation, I have:
class AudioModel(audioTitle: String, map: HashMap<String, Any>) : Parcelable {

    var title: String = ""
    var artistName: String = ""
    var urlLink: String = ""

    constructor(parcel: Parcel) : this(
            TODO("audioTitle"),
            TODO("map")) {
        title = parcel.readString()
        artistName = parcel.readString()
        urlLink = parcel.readString()
    }

    init {
        title = audioTitle
        urlLink = map["url"].toString()
        artistName = map["artist"].toString()
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(title)
        parcel.writeString(artistName)
        parcel.writeString(urlLink)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<AudioModel> {
        override fun createFromParcel(parcel: Parcel): AudioModel {
            return AudioModel(parcel)
        }

        override fun newArray(size: Int): Array<AudioModel?> {
            return arrayOfNulls(size)
        }
    }

}

My problem is that I'm getting warning at constructor with

unreachable code message

and because of that I can't pass my data using  intent.putParcelableArrayListExtra. Does anyone know how to fix this?
Answer: Your code is actually just fine. It's just that the TODO doesn't work in this case. Replace the TODO's with actual code and it should work.
For example:
constructor(parcel: Parcel) : this(
            parcel.readString(),
            hashMapOf<String, Any>()) {


Can hacked language markers affect Masuda?

Question: Does a Ditto from an American cartridge with a JPN language marker still work with Masuda method? I don't want to trade for one if people can just make JPN Ditto that won't work.
I've been trying forever to get my shiny Rockruff but I'm way over odds. Did I trade for a garbage fake JPN ditto? Or am I just really unlucky?
Comment: Friendly reminder that just because you have a 1 in 6 chance for a die to land on 6, it doesn't mean you're guaranteed to get a 6 after 6 throws, nor after 12 throws, or even after 60 throws. It may be incredibly unlikely to never get a 6 in 60 throws, but the probability is never 0. In fact, you have a ~0.002% chance of never getting a single 6 in 60 throws. To put it in another way: out of 8 Billion humans, 141 976 would likely not get a single 6 after 60 throws.
Comment: Welcome to Arqade! Please, consider accepting the answer if it solved your problem.
Answer: The Masuda method involves breeding two Pokémon created in games of different languages, and as long as that Ditto has JPN tag the game will accept it as Japanese, even if it's legit or not.
According to Bulbapedia:

An internal marker on each Pokémon identifies their "original language". If the game recognizes the two Pokémon in the daycare as having different languages, then when an Egg is generated, the game will generate extra personality values in an attempt to find one that results in a Shiny Pokémon.

So your Ditto is suitable, imho. Also because quite every 6IV Ditto out there is a hacked one.
You may just be unlucky, I hatched hundreds of eggs obtained from my Japanese Ditto in Pokemon Y, and I never managed to get a shiny.


How to open shared folder within xp?

Question: Can you describe me how to view files on xp machine after i made shared folder based on this article
browser method preferable
Answer: What you did was enabled sharing of your files in Ubuntu, whereas you need to enable sharing in your Windows OS to be able to reach it.

How to open shared folder within xp?


Do different Coordinate Systems refer to the same elements?

Question: Wikipedia defines the Real Coordinate Space as follows:

For any natural number $n$, the set $\mathbb{R}^n$ consists of all n-tuples of real numbers ($\mathbb{R}$). It is called (the) $n$-dimensional real space

Now, let $C_i, 1 ≤ i ≤ n$, be $n$ sets. Wikipedia defines a coordinate space of $n$ dimensions as a set $S$ together with a surjective partial mapping $$ \varphi : C_1 \times \dots \times C_n \to S $$
If I understand it correctly, converting one Coordinate system into  another, e.g. Cartesian coordinates into Spherical coordinates is just using sets that are different to $C_i, 1 ≤ i ≤ n$ together with a different mapping $\varphi$. However, both coordinate systems still index the same set of elements e.g. the elements from $S$ or the elements / tupels from $\mathbb{R}^n$
Q: Is my assumption that two different coordinate system can refere to the same set of elements correct or am I misunderstanding something?
Answer: Yes, even if you work with one space, a coordinating system could vary.
$\mathbb{R}^n$ as a real vector space it is already parametrized by itself, $\phi:\mathbb{R}^n \to \mathbb{R}^n$ is identity and therefore could be omitted. On the other hand, when more general vector space $V$ of dimension $n$ is given, then coordinate system that is also linear isomorphism is substantial: $\phi:\mathbb{R}^n\to V$. Note, that any $n\times n$ invertible matrix $M$ yields new coordinate system $\phi \circ M:\mathbb{R}^n\to V$ that is also an isomorphism.
In calculus switch between polar and cartesian coordinate system can help with solving integral. Interesting example is Gaussian integral: $\int e^{-x^2}dx$. Indefinite integral can not be expessed in terms of elementary functions, but $\int_{-\infty}^{\infty} e^{-x^2}dx=\sqrt\pi$ and the proof uses polar coordinates.
Both spherical and cylindrical coordinate spaces describe the same set: $\mathbb{R}^3$.
By these examples I've tried to compensate vague wikipedia article, that you have mentioned. With definition that broad nearly everything is coordinate space: permutation of a set, group epimorphism, projection, n-ary relation, graph coloring etc. From my experience "coordinates" always means "elements of $\mathbb{R}^n$ (or $\mathbb{R}$ in particular)", but it's just an opinion.


Latest Xamarin forms ver3 above Error: Specified cast is not valid

Question: I m using Vs for mac: 7.5.1(Build 22). I try to build a Master Detail page with ListView binding to a simple class.
Problem encountered: Specified cast is not valid.
In the code behind: I have red underline for InitializeComponent as well as for the ListView. Why?
In the SideMenu.xaml: Do I need to add this?
  xmlns:local="clr-namespace:MyNavigationSideMenu"

Here the code:
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  xmlns:local="clr-namespace:MyNavigationSideMenu;assembly=MyNavigationSideMenu"
                  x:Class="MyNavigationSideMenu.MySideMenu">

<MasterDetailPage.Master>

   <ContentPage Title="Menu">

    <Grid BackgroundColor ="Transparent">
         <Grid.RowDefinitions>
             <RowDefinition Height ="200"/>
             <RowDefinition Height ="*"/>
         </Grid.RowDefinitions>

         <Grid>
          <Image Source="bg.png" Aspect="AspectFill" />
          <StackLayout Padding="0,20,0,0" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
          <Image Source="home.png" Aspect="AspectFit" WidthRequest="60" HeightRequest="60" />

          </StackLayout>
        </Grid>

        <StackLayout Grid.Row="1" Spacing="15">
        <ListView x:Name ="navigationLV"
                  RowHeight ="60"
                  SeparatorVisibility ="None"
                  BackgroundColor ="#e8e8e8"
                  ItemSelected="OnMenuItemSelected">
                <ListView.ItemTemplate>
                   <DataTemplate>
                      <ViewCell>
                          <StackLayout>
                           <StackLayout VerticalOptions="FillAndExpand"
                                      Orientation="Horizontal"
                                      Spacing="20">
                              <Image Source="{Binding Icon}"
                                     WidthRequest="30"
                                     HeightRequest="30"
                                     VerticalOptions="Center"/>

                            </StackLayout>
                               <BoxView
                             HeightRequest="1"
                             BackgroundColor="Gray"/>
                          </StackLayout>
                       </ViewCell>
                   </DataTemplate>
                </ListView.ItemTemplate>
         </ListView>
        </StackLayout>
     </Grid>
    </ContentPage>
</MasterDetailPage.Master>

<MasterDetailPage.Detail>
<NavigationPage>
</NavigationPage>
</MasterDetailPage.Detail>

here the code behind of SideMenu:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using MyNavigationSideMenu.MenuItems;

namespace MyNavigationSideMenu
{
  public partial class MySideMenu : MasterDetailPage
  {
      public List<MasterPageItem> menuList { get; set; }

     public MySideMenu()
     {
          InitializeComponent();

          menuList = new List<MasterPageItem>();

// Adding menu items to menuList and you can define title ,page and icon
menuList.Add(new MasterPageItem() { Title = "Home", Icon = "home.png", TargetType = typeof(HomePage) } );

         navigationLV.ItemsSource = menuList;

       // Initial navigation, this can be used for our home page
        Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(HomePage)));
    }

    private void OnMenuItemSelected(object sender, SelectedItemChangedEventArgs e)
   {
    var item = (MasterPageItem)e.SelectedItem;
    Type page = item.TargetType;
    Detail = new NavigationPage((Page)Activator.CreateInstance(page));
    IsPresented = false;

      }

    }
}

Comment: We can't read your code become of how it is formatted. Please fix your pasted code.
Comment: @Andres castro please help. I try my best to include the XML page with anchor tags. Please advise
Answer: You need to check all these 3 steps:
1.Save the MySideMenu.xaml file & check red underline has gone.
2.Right click on MySideMenu.xaml & click on Properties & check Build Action should be set to "Embedded resource".
3.Add Try Catch for Initialize component in MySideMenu.xaml file & check which line the error is getting displayed.


Lubuntu 14.04 Sylpheed email retrieves old deleted mail

Question: Just installed Lubuntu 14.04 on a Dell Dimension 4700. On Sylpheed email when I retrieve mail It retrieves old deleted email from more than two (2) years ago. Is there a particular way to set it to where it won't retrieve old deleted mail? Thank you!
Comment: You are receiving old mail because they are still on your mail server. If you do another fresh install, you will receive all the mail again, unless you change the settings in sylpheed to delete the mail once you downloaded it. I can look up for you how to do that, but I have to know if your account is a pop account or something else?
Comment: Thanks for the quick reply. OK, It's a Gmail account if that helps for now. I can look as soon as I get home.
Answer: You are receiving the mail (again) because on your last system, you must have unchecked "remove messages on the server after download". In Sylpheed, you can do that in settings > accountsettings:

As you can see in this pop account example, you can do that by checking the option ("remove messages after x days", make it 0 to remove immediately).
If you use Gmail, you can use it as a pop account as wel for convenience reasons, with the same settings options.

Additional information:
If you make the settings as above, the email will not be downloaded again via your pop account, not even on a fresh install. However, they will continue to be available using Gmail in your webbrowser, unless you change some settings on the Gmail website. If you want to completely remove the mail you downloaded via your pop account, go to the Gmail website, click on the settings icon (the gear wheel in the top right of the window) and change the settings in the pop section to
if the messages are opened with pop, remove Gmail copy (see below)
Comment: I'll do that! Thanks again! I'll let you know the results. By the way, once I do the set-up, will have to delete the old messages again?
Comment: @MoRenteria That depends on the situation, if you did not remove them from the server, the will appear again when you create a new account :). BUT the next time you install, they won't.
Comment: OK, I'll do that :)


How to group consecutive integers in a scala array?

Question: Let's say I have an array like the following:
1 2 3 4 5 6 7 8 9 1 2 3 4 5 1 2 3 4

I want many sub-arrays of contiguous numbers whose sum of every contiguous pair is less than 10
1 2 3 4 5, 6, 7, 8, 9, 1 2 3 4 5 1 2 3 4

How do I code it in scala in a functional idiomatic way?
// example no. 1
>Array(1, 2, 3, 4, 5, 6)...???
res0: List(Array(1, 2, 3, 4, 5), Array(6))
// example no. 2
>Array(3, 8, 1, 9, 1, 3)...???
res1: List(Array(3), Array(8, 1), Array(9), Array(1, 3))

Comment: What does it have to do with reactivex and category-theory?
Comment: It can be solved with reactivex or category-theory
Comment: I see no relevance. Also it's unclear what are you trying to achieve, do you want to split array into elements that are below or above given threshold?
Comment: No I want to split an array into sub-arrays of consecutive elements whose sum of every contiguous pair is less then 10, see above question for details and examples
Answer: Doing a foldRight makes it easier to use head and tail to build the resulting List.
val grouped = Array(3,8,1,9,1,3).foldRight(List.empty[Array[Int]]){case (n,acc) =>
  if (acc.isEmpty) List(Array(n))
  else if (acc.head.head + n < 10) n +: acc.head :: acc.tail
  else Array(n) :: acc
}  // List(Array(3), Array(8, 1), Array(9), Array(1, 3))

Answer: This should work (although it's a very inefficient way):
def group(threshold: Int)(seq: Seq[Int]): Seq[Seq[Int]] =
  seq.reverse.tails.find(_.sum < threshold) match {
    case None => Nil
    case Some(Nil) => Nil
    case Some(subSeq) =>
      subSeq.reverse +: group(threshold)(seq.drop(subSeq.size))
  }

group(10)(Array(3, 8, 1, 9, 1, 3))
List(Array(3), Array(8, 1), Array(9), Array(1, 3))


Is it possible to disable wireless networking using the Android SDK or NDK?

Question: Is it possible to disable wireless networking on an Android device using the Android SDK or NDK?
Answer: In order to enable / disable the WiFi state, you have to grant the following permission in the application manifest
android.permission.CHANGE_WIFI_STATE

You can then use the WifiManager to set enable/disable the WIFI.
WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(enabled);

More info on http://developer.android.com/reference/android/net/wifi/WifiManager.html
For a complete sample, check the following post : http://android-er.blogspot.com/2011/01/turn-wifi-onoff-using.html
Answer: Yes you can disable the wifi programmatically:

Retrieve a WifiManager object from Context.getSystemService(Context.WIFI_SERVICE)
Set setWifiEnabled to true or false as you wish

Look up for the permission settings. You will probably need to add some in the AndroidManifest.xml


How do I avoid triggering the base alarm?

Question: In my first playthrough, I was able to get out of the ship without setting off the alarm.  In my second playthrough, despite knocking out every guard and never triggering an alarm, when I passed the security checkpoint I was notified that the base was put on an heightened alert state due to some alarms from the ship.  What did I do differently?  The only thing I remember is a turret seeing me for a few seconds.
Comment: IIRC, _any_ turret sightings count as an alarm, even if it doesn't set off the rest of the guards.
Comment: @JeffMercado hmm... the weird thing is I got ghost and smooth operator on all the missions
Comment: Funny, when I reached the first mission with the turret, I remember not getting  those bonuses because I tried to be cute and just jump past the hall. Fortunately I saved beforehand and reloaded and dispatched of the turret and got those bonuses. It might have changed since then with all the patches.
Comment: Also, if a turret or camera spots a dead/unconscious body, it will usually trigger and alarm.
Comment: Yesterday I tried the Factory Zero achievement and though I failed (whyever?) the base wasn't alarmed. Now I entered it and saw the huge amount of soldiers and the robot that was never active during my first playthrough... i am so annoyed by this and have to go back a few savegames to try out where I failed... did you actually find out, what you did wrong?
Comment: @ChristianIvicevic no, I have no clue either.  I'm absolutely positive I knocked out everyone without causing a single alarm.
Comment: I tried another run but the Steam servers are currently down for an hour and I don't want to risk ruining everything by unsynced achievements. I hope they'll soon come back online so I can try to finish this and see whether it's a bug or not because I have only picked up Secs for the codes and the quest items therefore everything should be fine for now.
Answer: Being spotted by a turret will immediately alert it, but as long as it doesn't shoot at you and alert guards, who then trigger alarm panels, it doesn't affect whether or not you get the Smooth Operator bonus.
Your problem, however, might be that some guard that you missed was patrolling and stumbled upon one of your victims. Depending on where you are in the game, you can also trigger guards or robots to spawn, and if one of these are in the vicinity of your handiwork, they can be alerted. A camera can also pick up dead or knocked out bodies, and if it goes past "Suspicious", it will cause an alarm.

How do I avoid triggering the base alarm?

The answer to this question is simply: avoid being spotted by guards or cameras and prevent them from seeing dead or knocked out bodies.

What did I do differently?

This question calls for speculation and can't really be answered with the information you have given.


Extjs Comobobox duplicate display field not allowed to be set?

Question: I'm a newbie using Extjs 4.07. I have created a combobox (remote) queryMode. The combobox displays a list of courses. However, the institution I work for recently recoded their entire courses. So, I end up having two records with the same display field. My JSON looks like this:
{"result":[{"id":"90223","code":"CM12","description":"Introduction to C Programming","creditHours":"3.00","numberOfLabs":"0","contactHours":null,"chargeableCredits":null},
{"id":"2094","code":"CMPS1302","description":"Introduction to C Programming","creditHours":"3.00","numberOfLabs":"0","contactHours":null,"chargeableCredits":null}],"total":2}

the display field is description and the value field is id. When I select one of the items in the combobox and submit everything works fine. The problem occurs if later I selected the incorrect course and select the other one.
I have tried setting the idProperty: 'id' but to no avail. When I submit the form the value that will be sent is the one that was selected first after. Note: This only happens for duplicate course descriptions, everything else works fine.
here is some code to help explain the problem:
Ext.define('SIS.model.ManageCourse', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'id', type: 'int'},
        {name: 'code', type: 'string'},
        {name: 'description', type: 'string'},
        {name: 'creditHours', type: 'float'},
        {name: 'contactHours', type: 'float'},
        {name: 'chargeableCredits', type: 'float'},
        {name: 'numberOfLabs', type: 'float'},
        {name: 'selected', type: 'bool'} //for update course pre-requisites
    ]
});

Ext.define('SIS.store.ClassCourse', {
    extend: 'Ext.data.Store',
    autoLoad: true,
    autoSync: true,
    model: 'SIS.model.ManageCourse',
    pageSize: 7,
    remoteFilter: true,
    idProperty: 'id',
    proxy: {
        type: 'ajax',
        api: {
            read: 'course/select'
        },
        reader : {
            type : 'json',
            root : 'result',
            totalProperty  : 'total',
            successProperty : 'success'
        }
    }
});

Ext.define('SIS.view.class.ClassCourseCombo', {
    extend: 'Ext.form.ComboBox',
    alias: 'widget.ClassCourseCombo',
    name: 'courseId',
    fieldLabel: 'Course',
    store: 'ClassCourse',
    queryMode: 'remote',
    pageSize: 7,
    displayField: 'description',
    valueField: 'id',
    allowBlank: false,
    hideTrigger: true,
    forceSelection: true,
    minChars: 1,
    lazyInit: false,
    listConfig: {
        getInnerTpl: function () {
            return '
{description}
\

{code}
';
        }
    }
});

Comment: Could you explain your problem with the example "The problem occurs if later I selected the incorrect course and select the other one." is confusing.
Comment: Let's say I wanted to select Intro to C Programming (CM12) but I selected Intro to C Programming (CMPS1302) by mistake. Even though I make the correction my first selection will be submitted. However, If I select another course, eg. Software Engineer, and then select Intro to C Programming (CMPS1302) it is acceptable.
Answer: Having same display value for different rows in combo box is confusing at least for the end user. Why don't you create a calculated field like this:
fields: [
  { name: 'id', type: 'int' },
  { name: 'description', type: 'string' },
  { name: 'display', type: 'string', convert: function(v, r) {
     return r.get('id') + ' ' + r.get('description');
  }}
}]

And use this display as your displayField.
Comment: I thought about that but if that is done then when editing the combo no results will be returned since the display field is used as the query to fetch results from server. I decided to use getInnerTpl instead to format the display.
Answer: This is a bug identified since version 3 I found the solution in sencha forum provided by Condor.
I changed the line
if(val.length > 0 && val != this.emptyText)

with
if(val.length > 0 && val != this.emptyText && typeof this.emptyText != 'undefined')

when there is no emptyText defined the result is just as if forceSelection was set to false even when explicitly set to true. small fix.


Are norms of solutions to two Lyapunov matrix equations comparable?

Question: Let $A \in \mathcal M(n \times n; \mathbb R)$ with $\rho(A) < 1$. Suppose $X_1$ is the solution to following Lyapunov matrix equation
\begin{align*}
A^T X_1 A + Q_1 = X_1,
\end{align*}
where $Q_1 \in \mathcal M(n \times n; \mathbb R)$ and no particular structure of $Q_1$ is assumed. Suppose $X_2(t)$ is the solution to the Lyapunov matrix equation
\begin{align*}
A^T X_2 A + tQ_2 = X_2,
\end{align*}
where $Q_2 \succ 0$ is positive definite and $t$ is a free parameter.
I am wondering whether there exists some choice of $t$ such that $\|X_1\|_F \le \|X_2\|_F$? I think the choice of $t$ should exist since if $t \to \infty$, $X_2$ should be unbounded in the entries while $X_1$ should have a fixed norm. I am interested in getting conditions on $t$ in terms of $Q_1, Q_2$ (without $A$) if possible such that $\|X_1\|_F \le \|X_2\|_F$.
Answer: We stack the matrices row by row, and we put $q_i=vec(Q_i),x_i=vec(X_i)$. Then $x_1=(I-A^T\otimes A^T)^{-1}q_1,x_2=t(I-A^T\otimes A^T)^{-1}q_2$.
${||X_1||_F}^2={x_1}^Tx_1=tr(q_1^T(I-A\otimes A)^{-1}(I-A^T\otimes A^T)^{-1}q_1)=tr(q_1q_1^T(I-A\otimes A)^{-1}(I-A^T\otimes A^T)^{-1})\leq \sqrt{tr((q_1q_1^T)^2)}\sqrt{tr(((I-A\otimes A)^{-1}(I-A^T\otimes A^T)^{-1})^2)}$
Let $\sigma_1\leq\cdots\leq \sigma_n$ be the singular values of $I-A\otimes A$; they are $>0$.
then ${||X_1||_F}^2\leq \sqrt{tr((q_1q_1^T)^2)}\sqrt{\sum_i{\sigma_i}^{-4}} \leq \sqrt{tr((q_1q_1^T)^2)}\dfrac{\sqrt{n}}{{\sigma_1}^2}$.
${||X_2||_F}^2={x_2}^Tx_2=t^2{q_2}^T(I-A\otimes A)^{-1}(I-A^T\otimes A^T)^{-1}q_2$.
Let $(e_i)$ be an othonormal basis of eigenvectors of $(I-A\otimes A)(I-A^T\otimes A^T)$ associated to the eigenvalues $({\sigma_i}^2)$ and $q_2=\sum_i\alpha_ie_i$. Then ${||X_2||_F}^2=t^2\sum_i\dfrac{\alpha_i^2}{\sigma_i^2}\geq t^2\dfrac{\alpha_1^2}{\sigma_1^2}$.
Conclusion. We obtain (for $t$) a condition that does not depend on $A$ under the condition that $\alpha_1^2$ has a positive lower bound.


Matching ID between two pandas series

Question: I have, I guess a simple question but I cannot find the right answer. I have two pandas series (let's say "A" and "B") with ID in there (string). Series A is bigger than series B. What I am looking for is a way to have a resulting dataframe with 2 columns where the matching elements are on the same row and if there is a value in A that don't exist in B, to add a NaN.
A            B
10368        10368
12567        NaN
13456        13456
...          ...

and so on.
I guess the merge function in pandas can be helpful but I could not manage to make it work
Thanks in advance
Comment: What have you tried? Demonstrate the effort by providing the code.
Comment: I tried many things. Merge, concat, intersection,.. but it resolves only part of the problem.
Comment: Fine. Where is the code demonstrating the effort?
Comment: Probably best to create a dictionary and use map canyou post a better sample of your input data?
Answer: You can try this:
df.loc[df['A'].isin(df['B']), 'B'] = df['A']
df.loc[~df['A'].isin(df['B']), 'B'] = np.nan

Before:
   A  B
0  1  2
1  2  1
2  3  4
3  7  0

After:
   A    B
0  1  1.0
1  2  2.0
2  3  NaN
3  7  NaN

Comment: Many thanks, this was exactly what I was looking for. I'll check now exactly what it's doing.
Answer: You could use pd.concat and boolean index using isin:
a = pd.Series(['10368', '12567', '13456'])
b = pd.Series(['10368', '13456'])

pd.concat([a, a[a.isin(b)]], axis=1)

[out]
       0      1
0  10368  10368
1  12567    NaN
2  13456  13456

Comment: Thanks too. It's pretty handy. I'll keep both solutions

Matching ID between two pandas series


Change the value of the variable used to disbled the button in Angular

Question: In my project application, there are two buttons named "verify" and "cancel verification". I have used two boolean-type variables to set the disable property when the page loads.
I want to achieve this scenario: when the verify button is clicked it should be immediately disabled and the cancel verification button gets enabled and vice versa.
Here is my code:
.ts file
     verified: boolean;
     notVerified: boolean;

   ngOnInit() {
      // setting the value from the API call response
      this.verified = // logic
      this.notVerified = // logic
   }

  valiadtionoftherapist(value) {
    if (value === 'true') {
      var data = {
        'verifiedBadge': true,
        '_id': this.id
      };
      document.getElementById('validation').setAttribute('src', 'assets/img/verified-copy-3.png');
      this.verified = false;
      this.notVerified = true;
    }
    if (value === 'false') {
      var data = {
        'verifiedBadge': false,
        '_id': this.id
      };
      document.getElementById('validation').setAttribute('src', 'assets/img/notverified-copy.png');
      this.notVerified = false;
      this.verified = true;
    }

    // API call

  }

.html file

            <button class="btn green-button"  (click)="valiadtionoftherapist('true');" [disabled]="verified" translate>
              Verify User
            </button>

            <button class="btn red-button"  (click)="valiadtionoftherapist('false');" [disabled]="notVerified" translate>
              Cancel Verfication
            </button>

Where am I mistaken?
Answer: You have your true/false in the if conditions mixed up, you can change it to the following it should work:
if (value === 'true') {
      var data = {
        'verifiedBadge': true,
        '_id': this.id
      };
      document.getElementById('validation').setAttribute('src', 'assets/img/verified-copy-3.png');
      this.verified = true;
      this.notVerified = false;
    }
    if (value === 'false') {
      var data = {
        'verifiedBadge': false,
        '_id': this.id
      };
      document.getElementById('validation').setAttribute('src', 'assets/img/notverified-copy.png');
      this.notVerified = true;
      this.verified = false;
    }

    // API call

Comment: You can add a third variable like ìnProgress`. Set this to true if you click a button as example
Comment: By doing this, I will not achieve what I want!! If verify button is clicked then it should immediate gets disable!! so that the same user cannot be verify multiple times or in other words user should be verified only once not multiple times by clicking on it several times!! Hope you aer getting my point! Thank you
Comment: I understand what you mean now. Apologies I thought it was a bug in the code logic. What Flo suggested above will work. Adding an isLoading or inProgress value and disabling the button immediately (very start of the valiadtionoftherapist function) will disable any additional button clicks. Then just enable it again after the API call has finished.
Comment: By doing this, it is disabling the clickable button but the other button is not getting enabled!
Comment: @JaynaTanawala did you change the true/false values like I showed in the answer? There was an issue with that too when I tested it.
Comment: @DubDJ, yes, I have changed it


Pass parameter to ng-template is underfined with nbpopover

Question: I am using nbPopover and I just want to pass context to nbPopover. usually its working but now I would like to use this inside *ngIf and after that all pass data are undefined. here is sample=>

            Box {{i+5}}

 <ng-template #templateRef let-work="passdata">

            Name

            : {{work}}

  </ng-template>

I already used this nbPopoverContext without ngfor and it's working but after I use this inside ngfor, it's not working anymore. How can I solve this issue? thanks, guys.
Comment: wouldn't passing the index too in the context work?
Comment: Theres no need for ngFor here.
Comment: @GaurangDhorda, May I know why it's not needed?
Comment: @eko, not working also
Comment: can You share `valueList` object  ?
Comment: @Loran nbPopoverContext is used to pass context to custom component and not for ng-template. If you declare custome component and used @Input() prop then you will get context from popover context
Comment: If you want example then I can share here.
Comment: @GaurangDhorda, Thank you. If u can share the example, it will be great. but I also check here => [https://github.com/akveo/nebular/blob/master/src/playground/with-layout/popover/popover-test.component.ts] .Also, use the ng-template but not with ngfor.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/231572/discussion-between-gaurangdhorda-and-loran).
Comment: Come to discussion panel by clicking over above link https://chat.stackoverflow.com/rooms/231572/discussion-between-gaurangdhorda-and-loran
Answer: I bumped on this example and it worked:
https://github.com/akveo/nebular/blob/master/src/playground/with-layout/popover/popover-template-ref.component.html
So for your snippet, it should be something like:

            Box {{i+5}}

 <ng-template #templateRef let-passdata>

            Name

            : {{passdata.work}}

  </ng-template>


onCameraReady function is triggered on camera close

Question: The problem is, when I open camera the function inside onCameraReady isn't executed.
My Component:
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { type BarCodeScannedCallback, PermissionStatus } from 'expo-barcode-scanner';
import { Camera } from 'expo-camera';
import { useState, useCallback, useRef } from 'react';
import { View, StyleSheet, Platform, Pressable, Linking } from 'react-native';
import ScannerMarker from '@screens/CodeScanner/ScannerMarker';
import Button from '@components/Button';
import CustomText from '@components/CustomText';
import Layout from '@layouts/Layout';
import CloseIcon from '/assets/closeModal.svg';
import useCameraPermission from '@hooks/useCameraPermission';
import { globalStyles } from '@constants/styles';
import { moderateScale } from '@utils/dimensions';
import { barCodeScannerSettings, chooseBestRatio } from './helpers';
import { styles } from './styles';

const closeButtonSize = moderateScale(30);

const CodeScanner = () => {
  const [cameraRatio, setCameraRatio] = useState('16:9');
  const [scanned, setScanned] = useState(false);
  const cameraRef = useRef<Camera>(null);
  const { goBack } = useNavigation();
  const { t } = useTypedTranslation();
  const { status, canAskAgain, requestPermissions } = useCameraPermission();

  const isCameraPermission = status === PermissionStatus.GRANTED;
  const buttonText = canAskAgain ? "grant permission" : "open settings";

  useFocusEffect(
    useCallback(() => {
      requestPermissions();

      return () => setScanned(false);
    }, [])
  );

  const handleBarCodeScanned: BarCodeScannedCallback = ({ data }) => {
    setScanned(true);
    goBack();

    alert(`Bar code scanned! Received: ${data}`);
  };

  const onCameraReady = async () => {
    if (Platform.OS === 'android') {
      const cameraRatios = await cameraRef.current?.getSupportedRatiosAsync();
      const chosenRatio = chooseBestRatio(cameraRatios);
      setCameraRatio(prevState => chosenRatio ?? prevState);
    }
  };

  if (!status) {
    return null;
  }

  if (status === (PermissionStatus.DENIED || PermissionStatus.UNDETERMINED)) {
    return (
      <Layout>
        <View style={styles.permissionDeniedContainer}>
          <CustomText style={styles.permissionDeniedText} fontWeight="semi-bold">
            No access to the camera
          </CustomText>
          <Button
            onPress={canAskAgain ? requestPermissions : Linking.openSettings}
            type="secondary"
            containerStyle={styles.buttonContainer}
            textStyle={styles.buttonText}
          >
            {buttonText}
          </Button>
        </View>
      </Layout>
    );
  }

  return (
    <View style={styles.container}>
      <Camera
        ref={cameraRef}
        barCodeScannerSettings={barCodeScannerSettings}
        onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
        style={[StyleSheet.absoluteFill, styles.codeScanner]}
        ratio={cameraRatio}
        onCameraReady={onCameraReady}
      >
        {isCameraPermission && (
          <>
            <ScannerMarker />
            <View style={styles.closeContainer}>
              <Pressable style={styles.closeButton} onPress={goBack}>
                <CloseIcon
                  width={closeButtonSize}
                  height={closeButtonSize}
                  color={globalStyles.colors.white}
                />
              </Pressable>
            </View>
          </>
        )}
      </Camera>
    </View>
  );
};

export default CodeScanner;

The function executes when I closed the Camera components. The most interesting thing is when I add console.log() before if check inside onCameraReady function - it works and executes correct when Camera component is open
Modified function:
const onCameraReady = async () => {
    console.log('trigger setting camera Ratio');

    if (Platform.OS === 'android') {
      const cameraRatios = await cameraRef.current?.getSupportedRatiosAsync();
      const chosenRatio = chooseBestRatio(cameraRatios);
      setCameraRatio(prevState => chosenRatio ?? prevState);
    }
};

In the first case without console.log - the ratio isn't set correctly and the camera preview is distorted, and in second case the ratio is set correctly and preview looks good.
Is it possible to trigger function by execute console.log() ?
I have never met with problem like above. Maybe someone can help?
I want add this CodeScanner component to scan QR Codes, I have been tried expo-barcode-scanner, but it have problem with fit camera preview to all the screen, and I stay with expo-camera.
I need to detect supported ratios, and pick the best fit, becuase this app would be use by different customers with different devices
Answer: I don't have a solution to your problem per se. But I myself was working on android expo camera ratios and decided to mix your code with mine.
The following elementary code works just fine for me, onCameraReady is triggered at startup, as it should be. I hope this will help you :
import { Camera, CameraType } from "expo-camera";
import React, { useEffect, useRef, useState } from "react";
import { Button, Dimensions, Platform, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import MyAppText_Italic from "./components/appFontsTextWrappers/MyAppText_Italic";

const phoneScreenWidth = Dimensions.get("window").width;
const phoneScreenHeight = Dimensions.get("window").height;

function convertRatioToNumber(ratio) {
  const [numerator, denominator] = ratio.split(":").map(Number);
  return numerator / denominator;
}

export default function CameraScreen_Expo_Test() {
  const [type, setType] = useState(CameraType.back);
  const [permission, requestPermission] = Camera.useCameraPermissions();
  const cameraRef = useRef<Camera>(null);
  const [cameraRatio, setCameraRatio] = useState("4:3");

  if (!permission) {

    return <View />;
  }

  if (!permission.granted) {

    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "black" }}>
        <MyAppText_Italic style={{ textAlign: "center", fontSize: 17, color: "white", marginBottom: 15 }}>We need access to the camera</MyAppText_Italic>
        <Button color={"#5C0272"} onPress={requestPermission} title="Authorize" />
        <MyAppText_Italic style={{ textAlign: "center", fontSize: 12, marginTop: 15, maxWidth: "80%" }}>
   If the button does not work, please allow the app to use the camera in your phone settings
        </MyAppText_Italic>
      </View>
    );
  }

  const onCameraReady = async () => {
    console.log("onCameraReady");

    if (Platform.OS === "android") {

      const cameraRatios = await cameraRef.current?.getSupportedRatiosAsync();
      console.log("cameraRatios", cameraRatios);

      const chosenRatio = findBestCameraRatio(cameraRatios);
      console.log("chosenRatio", chosenRatio);
      setCameraRatio((prevState) => chosenRatio ?? prevState);
    }
  };

  function findBestCameraRatio(cameraRatios) {

    if (!cameraRatios || cameraRatios.length === 0) {
      return null;
    }

    const targetRatio = 4 / 3;
    let closestRatio = cameraRatios[0];

    let smallestDifference = Math.abs(convertRatioToNumber(cameraRatios[0]) - targetRatio);

    cameraRatios.forEach((ratio) => {

      const [width, height] = ratio.split(":").map(Number);
      const currentRatio = width / height;
      const currentDifference = Math.abs(currentRatio - targetRatio);

      if (currentDifference < smallestDifference) {
        closestRatio = ratio;
        smallestDifference = currentDifference;
      }
    });
    return closestRatio;
  }

  function toggleCameraType() {
    setType((current) => (current === CameraType.back ? CameraType.front : CameraType.back));
  }

  return (
    <View style={styles.container}>
      <Camera
        style={[styles.camera, { width: phoneScreenWidth, height: phoneScreenWidth * convertRatioToNumber(cameraRatio) }]}
        type={type}
        ratio={cameraRatio}
        ref={cameraRef}
        onCameraReady={onCameraReady}
      >
        <View style={styles.buttonContainer}>
          <TouchableOpacity style={styles.button} onPress={toggleCameraType}>
            <Text style={styles.text}>Flip Camera</Text>
          </TouchableOpacity>
        </View>
      </Camera>
    </View>
  );
}

By the way, the way you handle camera permission looks much cleaner than my method, would you mind sharing your @hooks/useCameraPermission ?


python quicksort - Can this code be improved?

Question: Can you give me advice about how to improve this code?
<code>def qsort(arr):
    if len(arr) < 2:
        return arr
    else:
        root =  arr[round(len(arr)/2)]
        arr.remove(root)
        min_  = [i for i in arr if i <  root]
        max_  = [i for i in arr if i >  root]
        oth_  = [i for i in arr if i == root]
        return  qsort(min_) + [root]+oth_ + qsort(max_)
</code>
Comment: Better asked on [codereview.se].
Answer: I can think of two things that may improve the efficiency of this code. The first is to use one loop with the three i < root, i > root, and i == root conditions as if/elif/else statements as the body instead of using list comprehension for each condition. That will cut down the amount of times you are touching each element of the array from around 3 to around 1.
The second thing is deleting the root from the array. You don't accomplish too much by doing this (you could just get the root index and reference arr[root_index] whenever you need the root), and removing an element from the middle of an array can be somewhat of a costly operation in Python (since you're not getting the index, you are actually searching the array for the root again, then deleting it, then shifting everything in an index higher than the root down an index). Remember not to double count it though if you decide not to remove it from the array.


Check if a system admits solutions of period 2

Question: I have the following problem.

Let $r \geq 0$ be a parameter in the discrete time system $x(k + 1) = r − rx(k)$.
Verify whether there exist $r \geq 0$ such that this system admits solutions of period 2.

I do not quiet understand how I should solve this problem. I already determined that the fixed points of the system are $x^* = \frac{r}{r + 1}$ and that $0 \leq r < 1$ for the system to converge.
Answer: You should write $x(k+2)=r-rx(k+1)$, substitute in your expression for $x(k+1)$ and see if there are solutions with $x(k+2)=x(k)$
Comment: Ohhh is it that easy. Thanks!