text:
Q: show input tag for each selected dropdown with validation? here's my code for dropdown and input field's

        <select id="scl">
                <option value="10">Ten</option>
                <option value="7">Seven</option>
                <option value="4">Four</option>
         </select>

<form>

<input type="number"  required>

<input type="numbe" required>

<input type="number" required>

      <input type="submit" >
 </form>

here's my jquery code

it does not submit my form.
it show's and hide the input field for a specific drop down (i.e. if option 10 is selected it shows input field 10) but my problem is how can I remove validation from remaining two fields so that I can submit form
I need validation for selected field only.
any help is appreciated thanks in advance.

A: Maybe instead of adding "required" over here -
You can add "required" to the input field after this $("." + optionValue).show();
Use this line to add required prop to this field:
$("." + optionValue).prop('required',true);
And subsequently set the others as false.


text:
Q: Is it possible to build a dom tree with C# XmlReader only? I want to build a dom tree with XmlReader over any valid xml string without using class XmlDocument or class XDocument.
And I got difficulty in determine whether the element <tank> is the child node of element <plane>.  Because Element <plane> doesn't have the end tag.  If this difficulty is solved, then I'll be able to generate the Dom tree.
Does anyone know how to solve this issue or does anyone know how to build the DOM tree dynamically with XmlReader?
Xml Content:
<?xml version="1.0" encoding="utf-8" ?>
<root>
    <plane visible="false" />
    <tank>
        <weapon name="cannon">equipped</weapon>
    </tank>
    <ship>
        <weapon name="cannon">equipped</weapon>
    </ship>
</root>

Script to Display the Details
XmlReader xr = XmlReader.Create(xmlContent);
while (xr.Read())
{
    Logger.Log(string.Concat("[", xr.NodeType, "][", xr.ValueType, "]", xr.Name, ",(",xr.HasValue,")" + xr.Value));
}

Details
[XmlDeclaration]    [System.String] xml,(True)version="1.0" encoding="utf-8"
[Element]           [System.String] root,(False)
[Element]           [System.String] plane,(False)
[Element]           [System.String] tank,(False)
[Element]           [System.String] weapon,(False)
[Text]              [System.String] ,(True)equipped
[EndElement]        [System.String] weapon,(False)
[EndElement]        [System.String] tank,(False)
[Element]           [System.String] ship,(False)
[Element]           [System.String] weapon,(False)
[Text]              [System.String] ,(True)equipped
[EndElement]        [System.String] weapon,(False)
[EndElement]        [System.String] ship,(False)
[EndElement]        [System.String] root,(False)

A: The problem here is that the <plane> tag isn't a parent of the <tank> tag - it is a sibling of it. If the <plane> tag needs to be a parent element of the <tank> tag, it needs to wrap it in the xml.
If it isn't possible for you to change the xml, you can use xr.IsEmptyElement to determine if a tag is self-closed or not, and have custom logic to work around that accordingly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Analogue of helicity in higher dimensions and concrete formula Consider Poincare group $ISO(1,d-1)$ in some dimension $d>4$.
There are two Casimirs. Let's look at massless one-particle states: the little group is $ISO(d-2)$, and if we restrict to finite dimensional representations, it is actually $SO(d-2)$.
I'm interested in giving a concrete expression for the analogue of helicity in $d=4$, namely generalize the following formula (2.5.42 in Weinberg's book)
$$ U(\Lambda) \Psi_{p,\sigma} = N e^{i \sigma \theta} \Psi_{\Lambda p,\sigma} $$
where $N$ is normalization and $\theta=\theta(\Lambda,p)$,
to the case $d>4$, where I expect something similar to $e^{i \sigma \theta}$ factor, but involving unitary finite dimensional irreps $D(W)_{\sigma \sigma'}$ of $SO(d-2)$, depending on the little group element $W =W(\Lambda,p) \in SO(d-2)$ (we should fix a Cartan basis, and the irrep is given in terms e.g. of Young diagram), and I'm wondering whether the argument that in $d=4$ restricts $\sigma$ to be half integer (basically by requiring $e^{4\pi i \sigma}=1$) still applies, and how.
By concrete I mean that, say when $\Lambda$ itself is in some maximal 'torus' of $so(1,d-1)$, say rotations in planes $(j,j+1)$, the formula should be simple enough, possibly again just a bunch of phases.


text:
Q: How do you dismiss the keyboard when editing a UITextField I know that I need to tell my UITextField to resign first responder when I want to dismis the keyboard, but I'm not sure how to know when the user has pressed the "Done" key on the keyboard. Is there a notification I can watch for?

A: If you connect the DidEndOnExit event of the text field to an action (IBAction) in InterfaceBuilder, it will be messaged when the user dismisses the keyboard (with the return key) and the sender will be a reference to the UITextField that fired the event.
For example:
-(IBAction)userDoneEnteringText:(id)sender
{
    UITextField theField = (UITextField*)sender;
    // do whatever you want with this text field
}

Then, in InterfaceBuilder, link the DidEndOnExit event of the text field to this action on your controller (or whatever you're using to link events from the UI). Whenever the user enters text and dismisses the text field, the controller will be sent this message.

A: You can also use
 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  {

   [self.yourTextField resignFirstResponder];

  }

Best one if You have many Uitextfields :
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {
     [self.view endEditing:YES];
 }

A: I set the delegate of the UITextField to my ViewController class.
In that class I implemented this method as following:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}

A: You can also create a method in your controller
 -(IBAction)editingEnded:(id)sender{
    [sender resignFirstResponder];
}

and then in  Connection Inspector in IB connect Event "Did End On Exit" to it.

A: kubi, thanks. Your code worked.  Just to be explicit (for newbies like) as you say you have to set the UITextField's delegate to be equal to the ViewController in which the text field resides. You can do this wherever you please. I chose the viewDidLoad method.
- (void)viewDidLoad
{
    // sets the textField delegates to equal this viewController ... this allows for the keyboard to disappear after pressing done
    daTextField.delegate = self;
}

A: You will notice that the method "textFieldShouldReturn" provides the text-field object that has hit the DONE key.  If you set the TAG you can switch on that text field.  Or you can track and compare the object's pointer with some member value stored by its creator.
My approach is like this for a self-study:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"%s", __FUNCTION__);

    bool fDidResign = [textField resignFirstResponder];

    NSLog(@"%s: did %resign the keyboard", __FUNCTION__, fDidResign ? @"" : @"not ");

    return fDidResign;
}

Meanwhile, I put the "validation" test that denies the resignation follows.  It is only for illustration, so if the user types NO! into the field, it will not dismiss.  The behavior was as I wanted, but the sequence of output was not as I expected.
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    NSLog(@"%s", __FUNCTION__);

    if( [[textField text] isEqualToString:@"NO!"] ) {
        NSLog(@"%@", textField.text);
        return NO;
    } else {
        return YES;
    }
}

Following is my NSLog output for this denial followed by the acceptance.  You will notice that I am returning the result of the resign, but I expected it to return FALSE to me to report back to the caller?!  Other than that, it has the necessary behavior.

13.313 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]
13.320 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldEndEditing:]
13.327 StudyKbd[109:207] NO!
13.333 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]: did resign the keyboard
59.891 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]
59.897 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldEndEditing:]
59.917 StudyKbd[109:207] -[StudyKbdViewController doneEditText]: NO
59.928 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]: did resign the keyboard

A: Here's what I had to do to get it to work, and I think is necessary for anyone with a Number Pad for a keyboard (or any other ones without a done button:

*

*I changed the UIView in the ViewController to a UIControl.

*I created a function called
-(IBAction)backgroundIsTapped:(id)sender

This was also defined in the .h file.
After this, I linked to to the 'touch down' bit for the ViewController in Interface Builder.
In the 'background is tapped' function, I put this:
    [answerField resignFirstResponder];

Just remember to change 'answerField' to the name of the UITextField you want to remove the keyboard from (obviously make sure your UITextField is defined like below:)
    IBOutlet UITextField * <nameoftextfieldhere>;

I know this topic probably died a long time ago... but I'm hoping this will help someone, somewhere!

A: Here is a trick for getting automatic keyboard dismissal behavior with no code at all. In the nib, edit the First Responder proxy object in the Identity inspector, adding a new first responder action; let's call it dummy:. Now hook the Did End on Exit event of the text field to the dummy: action of the First Responder proxy object. That's it! Since the text field's Did End on Exit event now has an action–target pair, the text field automatically dismisses its keyboard when the user taps Return; and since there is no penalty for not finding a handler for a message sent up the responder chain, the app doesn't crash even though there is no implementation of dummy: anywhere.

A: In Swift you can write an IBAction in the Controller and set the Did End On Exit event of the text field to that action
@IBAction func returnPressed(sender: UITextField) {
    self.view.endEditing(true)
}

A: Just add
[textField endEditing:YES];

where you want to disable keyboard and display the picker view.

A: Swift 4.2 and It will work 100%
import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.textField.delegate = self

    }

    // hide key board when the user touches outside keyboard

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    // user presses return key

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

}

A: Here is a quite clean way to end edition with the Return Key or a touch in the background.
In Interface builder, embed your fields in a view of class UIFormView
What does this class :

*

*Automatically attach itself as fields delegate ( Either awaked from nib, or added manually )

*Keep a reference on the current edited field

*Dismiss the keyboard on return or touch in the background

Here is the code :
Interface
#import <UIKit/UIKit.h>

@interface UIFormView : UIView<UITextFieldDelegate>

-(BOOL)textFieldValueIsValid:(UITextField*)textField;
-(void)endEdit;

@end

Implementation
#import "UIFormView.h"

@implementation UIFormView
{
    UITextField* currentEditingTextField;
}

// Automatically register fields

-(void)addSubview:(UIView *)view
{
    [super addSubview:view];
    if ([view isKindOfClass:[UITextField class]]) {
        if ( ![(UITextField*)view delegate] ) [(UITextField*)view setDelegate:self];
    }
}

// UITextField Protocol

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    currentEditingTextField = textField;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    currentEditingTextField = NULL;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self endEdit];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([self textFieldValueIsValid:textField]) {
        [self endEdit];
        return YES;
    } else {
        return NO;
    }
}

// Own functions

-(void)endEdit
{
    if (currentEditingTextField) {
        [currentEditingTextField endEditing:YES];
        currentEditingTextField = NULL;
    }
}

// Override this in your subclass to handle eventual values that may prevent validation.

-(BOOL)textFieldValueIsValid:(UITextField*)textField
{
    return YES;
}

@end

*

*By subclassing the form and overriding the
textFieldValueIsValid: method, you
can avoid end of edition if the value is not correct for the given
field.

*If a field has a delegate set in Interface Builder, then the form does not change it. I don't see many reasons to set a different delegate to a particular field, but why not…
There is many ways to improve this form view class - Attach a delegate, do some layout, handle when the keyboards covers a field ( using the currentEditingTextField frame ), automatically start edition for the next field, ...
I personally keep it in my framework, and always subclass it to add features, it is quite often useful "as-is".
I hope it will helps. Cheers all

A: if you want all editing of in a UIViewController you can use.
[[self view]endEditing:YES];

and if you want dismiss a perticular UITextField keyboard hide then use.
1.add delegate  in your viewcontroller.h
<UITextFieldDelegate>

*make delegation unable to your textfield .
self.yourTextField.delegate               = self;

*add this method in to your viewcontroller.
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
[textField resignFirstResponder];
return YES;}

A: Anyone looking for Swift 3
1) Make sure your UITextField's Delegate is wired to your ViewController in the Storyboard
2) Implement UITextFieldDelegate in your ViewController.Swift file (e.g class ViewController: UIViewController, UITextFieldDelegate  { )
3) Use the delegate method below
func textFieldShouldReturn(textField: UITextField) -> Bool {
   textField.resignFirstResponder()
return false }

A: Programmatically set the delegate of the UITextField in swift 3
Implement UITextFieldDelegate in your ViewController.Swift file (e.g class ViewController: UIViewController, UITextFieldDelegate { )
 lazy var firstNameTF: UITextField = {

    let firstname = UITextField()
    firstname.placeholder = "FirstName"
    firstname.frame = CGRect(x:38, y: 100, width: 244, height: 30)
    firstname.textAlignment = .center
    firstname.borderStyle = UITextBorderStyle.roundedRect
    firstname.keyboardType = UIKeyboardType.default
    firstname.delegate = self
    return firstname
}()

lazy var lastNameTF: UITextField = {

    let lastname = UITextField()
    lastname.placeholder = "LastName"
    lastname.frame = CGRect(x:38, y: 150, width: 244, height: 30)
    lastname.textAlignment = .center
    lastname.borderStyle = UITextBorderStyle.roundedRect
    lastname.keyboardType = UIKeyboardType.default
    lastname.delegate = self
    return lastname
}()

lazy var emailIdTF: UITextField = {

    let emailid = UITextField()
    emailid.placeholder = "EmailId"
    emailid.frame = CGRect(x:38, y: 200, width: 244, height: 30)
    emailid.textAlignment = .center
    emailid.borderStyle = UITextBorderStyle.roundedRect
    emailid.keyboardType = UIKeyboardType.default
    emailid.delegate = self
    return emailid
}()

// Mark:- handling  delegate textField..
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    if textField == firstNameTF {

        lastNameTF.becomeFirstResponder()
    }

    else if textField == lastNameTF {

        emailIdTF.becomeFirstResponder()
    }
    else {
        view.emailIdTF(true)
    }
    return true
}

A: Create a function hidekeyboard and link it to the textfield in the .xib file and select DidEndOnExit
-(IBAction)Hidekeyboard
{
      textfield_name.resignFirstResponder;
}

A: If you have created the view using Interface Builder, Use the following
Just create a method,
-(IBAction)dismissKeyboard:(id)sender
{
[sender resignFirstResponder];
}

Just right click the text field in the view , and set the event as Did End on Exit, and wire it to the method "dismissKeyboard".
The best guide for beginners is
      "Head First iPhone and iPad Development, 2nd Edition"

A: try this
- (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

A: //====================================================
//                  textFieldShouldReturn:
//====================================================
-(BOOL) textFieldShouldReturn:(UITextField*) textField {
    [textField resignFirstResponder];
    if(textField.returnKeyType != UIReturnKeyDone){
        [[textField.superview viewWithTag: self.nextTextField] becomeFirstResponder];
    }
    return YES;
}

A: This is how I dismiss the keyboard in Swift 4.2 and it works for me:
    override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action:
    #selector(dismissKeyboard))

    view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {
    numberField.resignFirstResponder()
    }

A: textField.returnKeyType = UIReturnKeyDone;

A: Swift 3, iOS 9+
@IBAction private func noteFieldDidEndOnExit(_ sender: UITextField) {}
UPD: It still works fine for me. I think guy that devoted this answer just didn't understand that he needs to bind this action to the UITextField at the storyboard.


text:
Q: CSS ::marker pseudo-element why only couple of CSS properties work? why not all? why ::marker pseudo-element not support all CSS properties like other pseudo-elements?
can anyone explain me in brief.
Found out today that ::marker pseudo-element not support all CSS properties like background, display, etc but "font-size", "color", and "content" properties are working like charm.

A: The CSS Lists specification explains:

NOTE: It is expected that future specifications will extend this list of properties and relax the restriction on which properties can take effect. However at the moment outside marker box layout is not fully defined, so to avoid future compatibility problems only these properties are allowed.

A: Because this selector selects marker of a list item. Like the buller for example. That means that it allows you only to customize the bullet, not the list itself. Thats why you cant apply properties like display, because you are effecting the marker itself. This can be helpful


text:
Q: Unable to down load XLS file on with https on IE 8 but working fine withh other browser I am unable to download xls file in Internet with SSL(https)
i am using following header information in jsp page.same is downloading fine with other browser.please help if i can add any thing extar in header information.
response.setHeader("Cache-Control","no-cache")
response.setHeader("Pragma","no-cache")
response.setDateHeader ("Expires", 0)

A: You can try these headers:
Content-Type: application/vnd.ms-excel
Content-Disposition: attachment; filename="my_file.xls"
Cache-Control: max-age=0
Pragma: public

It works for me!


text:
Q: xml sel -t -m does not work for me at all I have the following file log.xml:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<EntryList xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/">
  <Entries>
    <RankedEntry>
      <Entry>
        <id>1</id>
        <code1>001</code1>
        <displayName>Entry 1</displayName>
        <code2>003</code2>
        <code3>0100000000000005203</code3>
        <actualName>Entry Number 1</actualName>
        <entryType>1</entryType>
        <metaScore>1</metaScore>
        <usage>81</usage>
      </Entry>
      <factor>30.738496780395508</factor>
      <virtualFactor>45.738494873046875</virtualFactor>
    </RankedEntry>
    <RankedEntry>
      <Entry>
        <id>2</id>
        <code1>001</code1>
        <displayName>Entry 2</displayName>
        <code2>003</code2>
        <code3>0200000000000005203</code3>
        <actualName>Entry Number 2</actualName>
        <entryType>26</entryType>
        <metaScore>1</metaScore>
        <usage>61</usage>
      </Entry>
      <factor>40.738496780395508</factor>
      <virtualFactor>55.738494873046875</virtualFactor>
    </RankedEntry>
    <RankedEntry>
      <Entry>
        <id>3</id>
        <code1>001</code1>
        <displayName>Entry 3</displayName>
        <code2>003</code2>
        <code3>0300000000000005203</code3>
        <actualName>Entry Number 3</actualName>
        <entryType>3</entryType>
        <metaScore>1</metaScore>
        <usage>41</usage>
      </Entry>
      <factor>50.738496780395508</factor>
      <virtualFactor>65.738494873046875</virtualFactor>
    </RankedEntry>
  </Entries>
</EntryList>

On Window 7 using xmlstarlet 1.6.1 if I run the following command,
xml sel -t -m "/EntryList/Entries/RankedEntry/Entry/entryType" -v "." log.xml
Expected result is:
1
26
3

Actual:
But I do not get anything back
Any ideas how to fix it?

A: You have to account for the namespace.  Define a namespace prefix using the XMLStarlet -N option:
  -N <name>=<value>         - predefine namespaces (name without 'xmlns:')
                              ex: xsql=urn:oracle-xsql
                              Multiple -N options are allowed.

Then this XMLStarlet command:
xml sel -N s=http://schemas.datacontract.org/2004/07/ -t -v "/s:EntryList/s:Entries/s:RankedEntry/s:Entry/s:entryType" log.xml

Will produce the requested output:
1
26
3

A: Starting with version 1.2.1 you can use de default namespace _
(drop the -N argument)
xml sel -t -v "/_:EntryList/_:Entries/_:RankedEntry/_:Entry/_:entryType" log.xml

As explained here:

1.3. A More Convenient Solution
XML documents can also use different namespace prefixes, on any
  element in the document. In order to handle namespaces with greater
  ease, XMLStarlet (versions 1.2.1+) will use the namespace prefixes
  declared on the root element of the input document. The default
  namespace will be bound to the prefixes "_" and "DEFAULT" (in versions
  1.5.0+).


text:
Q: Why MySQL CHAR datatype has no preceding length byte? In MySQL documentation you can find that CHAR datatype has no preceding byte with string length.
In contrast VARCHAR datatype has 1 or 2 preceding bytes where string length is stored. Which is understandable. Database engine needs to know what is the string length in order to read it.
How does database engine know what is CHAR datatype length? What logic/algorithm is behind it?


text:
Q: UIButton in navigation item does not respond to click i am trying to add three button to the navigation item and i wrote these code:
let customNavigationItemView : UIView = UIView()
let trendbutton : UIButton = UIButton(type: .Custom)
size = myString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)])
size.width = size.width * 1.5
nearbybutton.frame.size = size
...
let nearbybutton : UIButton = UIButton(type: .Custom)
...
let squarebutton : UIButton = UIButton(type: .Custom)
...
trendbutton.frame.origin = CGPointMake(-trendbutton.frame.size.width - nearbybutton.frame.size.width / 2, 0)
...
customNavigationItemView.addSubview(trendbutton)
customNavigationItemView.addSubview(nearbybutton)
customNavigationItemView.addSubview(squarebutton)
self.navigationItem.titleView = customNavigationItemView

trendbutton.addTarget(self, action:  "circleNavigationBar_trendButton_clickUp:", forControlEvents: .TouchUpInside)
nearbybutton.addTarget(self, action: "circleNavigationBar_nearbyButton_clickUp:", forControlEvents: .TouchUpInside)
squarebutton.addTarget(self, action: "circleNavigationBar_squareButton_clickUp:", forControlEvents: .TouchUpInside)

and this:
func circleNavigationBar_trendButton_clickUp(sender : UIButton) {
    print("trend click")
}

but when i click the button in the navigation item, print nothing.
anyone can tell me the reason? thank you all the same.

A: You have to set the frame of your customNavigationItemView to the a size that contains the 3 buttons. Otherwise it has a zero size and does not pass touch events to its subviews because they occur outside of the view.
So if your buttons have a size of 20 x 20 and are touching each other this will work:
let customNavigationItemView : UIView = UIView()
customNavigationItemView.frame = CGRectMake(0, 0, 60, 20)

let trendbutton : UIButton = UIButton(type: .Custom)
trendbutton.frame = CGRectMake(0, 0, 20, 20)
...
let nearbybutton : UIButton = UIButton(type: .Custom)
nearbybutton.frame = CGRectMake(20, 0, 20, 20)
...
let squarebutton : UIButton = UIButton(type: .Custom)
squarebutton.frame = CGRectMake(40, 0, 20, 20)

A: i think maybe i found the answer, i changed my code like this:
trendbutton.frame = CGRectMake(0, 0, trendSize.width, trendSize.height)
nearbybutton.frame = CGRectMake(trendSize.width, 0, nearbySize.width, nearbySize.height)
squarebutton.frame = CGRectMake(trendSize.width + nearbySize.width, 0, squareSize.width, squareSize.height)
customNavigationItemView?.frame = CGRectMake(self.circleTable_tableView.frame.width / 2, 0, trendSize.width + nearbySize.width + squareSize.width, max(trendSize.height, nearbySize.height, squareSize.height))

it works great now but i do not understand the difference between these two ways to set frame:
one is:
someView.frame = CGRectMake(0,0,10,10)

the other one is:
someView.frame.origin = CGPointMake(0,0)
someView.frame.size = CGSizeMake(10,10)


text:
Q: VS code debug - is replacing object values with ellipses. How to show object values in debug? How can I get the debug console to display the actual values of the sorted object?
The result in the VS Code debug console display as below and are non expandable:
[{…}, {…}, {…}, {…}, {…}, {…}]
No debugger available, can not send 'variables'

Here is a simple program outputting a sorted object that I have written in VS Code.
const items = [
    { name: 'Edward', value: 21 },
    { name: 'Sharpe', value: 37 },
    { name: 'And', value: 45 },
    { name: 'The', value: -12 },
    { name: 'Magnetic', value: 13 },
    { name: 'Zeros', value: 37 }
  ];

// sort by value
items.sort(function (a, b) {
    return a.value - b.value;
  });

// console.log(items);

Here is the launch.json file:
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": []
}

A: Important: This solution only works if you are using Node.js.
If you are using Node.js, you can use the built-in util.inspect() function.
First, you have to import it using require().
const util = require("util");

Then, you can call the inspect function. You need to pass in your object as a parameter.
const inspected = util.inspect(obj);
console.log(inspected);

Then, you can easily see the object without it being condensed! For more information, see the util.inspect() documentation.

If you are not using Node.js, you can use JSON.stringify(). You can simply use it as so, passing the object as a parameter.

const obj = [
  { name: "Edward", value: 21 },
  { name: "Sharpe", value: 37 },
  { name: "And", value: 45 },
  { name: "The", value: -12 },
  { name: "Magnetic", value: 13 },
  { name: "Zeros", value: 37 }
];

console.log(JSON.stringify(obj));

This should allow you to inspect it properly.

A: Stringify worked but the output for mine is ugly AF! vscode really sucks in this regard!


text:
Q: ¿Cuál es la forma más efeciente de reemplazar una palabra por otra en un archivo muy muy grande utilizando python? Quiero reemplazar las palabras en ingles por sus traduciones en español en un texto muy muy extenso, cual seria la forma mas eficiente de hacer esto utlizando python ?

A: Me parece que esta sería la forma mas optima, evitando usar read() o readlines() :
with open("datos.txt") as miArchivo:
    for line in miArchivo:
         traducir(line)

Tu texto al ser traducido debería ser guardado a un archivo evitando almacenarlo en la memoria.


text:
Q: Parsing data in iphone I m using NSURLRequest to get and post data from server.
but after processing returned is in html format how i parse it.

Untitled Document

30

please give any refrence.
i want use 30 in my code.

A: Use libxml2, which is part of the iOS SDK.


text:
Q: Automatically adding link to related work for tasks? I'm using VSTS for task and issue tracking and committing to a git repo hosted on VSTS.
Is there a way to automatically show commits in the 'Development' section of a Task in VSTS without having to manually add it?
In Jenkins I believe there's a plugin where it looks for the commit ID in the commit message to automatically link to the related task in Jira.

A: There are several options.

*

*Enter the work item ID in the commit message, like Implemented a frobulator #1234.

*Create a branch for the task from within the work item, which will automatically associate the branch (and thus all commits to that branch) with the work item.


text:
Q: по моему исходнику не получается, помогите пожалуйста На вход программе подается натуральное число nn. Напишите программу, которая для каждого из чисел от 00 до nn (включительно) выводит фразу: «Квадрат числа [число] равен [число]» (без кавычек).
Формат входных данных:
На вход программе подается натуральное число nn.
Формат выходных данных:
Программа должна вывести текст в соответствии с условием задачи.
Sample Input 1:

9
Sample Output 1:

Квадрат числа 0 равен 0
Квадрат числа 1 равен 1
Квадрат числа 2 равен 4
Квадрат числа 3 равен 9
Квадрат числа 4 равен 16
Квадрат числа 5 равен 25
Квадрат числа 6 равен 36
Квадрат числа 7 равен 49
Квадрат числа 8 равен 64
Квадрат числа 9 равен 81

a = int(input())
for i in range(10):
print('Квадрат числа', i , 'равен',a ** 2)

A: Вам надо возводить в квадрат число i а не a
в цикле for надо проходить от 0 до a а не до десяти
a = int(input())
for i in range(a + 1):
    print('Квадрат числа', i , 'равен',i ** 2)

В одну строку
[print(f"Квадрат числа {i} равен {i ** 2}") for i in range(int(input()) + 1)]


text:
Q: Passing values from second view to firstView in Xcode I have been stuck here.
I have a NSString in Appdelegate. And I have two views called firstview,second view.In first view I have a label and set text from stringvariable which is in Appdelegate .When I click on the button in first view,It goes to the secondview(added the second view to first view as a subview).In second view I have a back button.when I click the back button it is displaying the first view ( Here I am setting the value which is in the appdelegate.And then used this [self.view removeFromSuperview]).The Problem is  first view is appearing but label value is not updating.Can any body tell me how to update the Labeltext.Kindly tell me.
Appdelegate.h
#import <UIKit/UIKit.h>

@class FirstView;

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    NSString *str1;
}

@property (nonatomic,retain)  NSString *str1;

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@end

Appdelegate.m
#import "AppDelegate.h"

#import "FirstView.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;
@synthesize str1;

- (void)dealloc
{
    [_window release];
    [_viewController release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.viewController = [[[FirsView alloc] initWithNibName:@"FirstView" bundle:nil] autorelease];

    self.str1 = @"view1";

    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

    return YES;
}

FirstView.h
#import <UIKit/UIKit.h>
#import "secondView.h"

@interface FirstView : UIViewController
{
    IBOutlet UILabel *btn;
    secondView *cont;
}

-(IBAction)gotoView2:(id)sender;

@end

FirstView.m
#import "FirstView.h"

-(IBAction)gotoView2:(id)sender
{
    cont = [[secondView alloc] initWithNibName:@"secondView" bundle:nil];
    [self.view addSubview:cont.view];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    AppDelegate *del = [[UIApplication sharedApplication] delegate];

    [btn setTitle:del.str1];

}

**SecondView.h**

#import <UIKit/UIKit.h>

@interface SecondView : UIViewController
{

}

-(IBAction)goBack:(id)sender;

@end

SecondView
#import "SecondView.h"
#import "AppDelegate.h"

@implementation SecondView

-(IBAction)gotoView1:(id)sender
{

    AppDelegate *del = [[UIApplication sharedApplication] delegate];
    [del setStr1:@"Home"];

    [self.view removeFromSuperView];
}

A: There is a pattern how to do such things. You should define a protocol like this:
@protocol FirstViewDelegate <NSObject>

- (void)didDismissSecondView;

@end

Your first view should conform to this protocol:
@interface FirstView: UIViewController <FirstViewDelegate> {
...

in its implementation add function didDismissSecondView:
- (void) didDismissSecondView
{
    AppDelegate *del = [[UIApplication sharedApplication] delegate];

    [btn setTitle:del.str1];
}

Your second view has to have a property
@interface SecondView : UIViewController
{
     id<FirstViewDeledate> delegate;
}
@property (nonatomic, retain) id<FirstViewDeledate> delegate;

When you show your second view from the first view set its delegate to self of first view
in your function:
-(IBAction)gotoView2:(id)sender
{
    SecondView *aView = [[SecondView alloc] init] // or whatever
    ...//other initialization code
    aView.delegate = self;
    ... // show it

}

and before you dismiss the second view:
-(IBAction)gotoView1:(id)sender
{

    AppDelegate *del = [[UIApplication sharedApplication] delegate];
    [del setStr1:@"Home"];

    [self.delegate didDismissSecondView];

    [self.view removeFromSuperView];
}

And you done.
A bit long, but works.


text:
Q: How to to setup an optimization in MATLAB which gives new set of variables for each iteration of my problem? In MATLAB, as far as I know, I should pass the handle of a cost function to the optimization function in order to optimize my problem. In my situation, I do not want to create a cost function and pass its handle to the optimization. I would like to setup an optimization and ask the optimization object for best new set of variables at each iteration. I, myself, calculate the cost and pass its value to the optimization object. I mean the algorithm might be as follows
1- setup the optimization object (optimization method, optimization sense, ...).
2- introduce the variables and their bounds and constraints to the optimization object
3- ask the optimization object for a set of variables
4- implement the variables to the physical black box and obtain the outputs
5- calculate the cost function for the monitored output
6- if the cost function does not satisfy my goal, inform the optimization object about the calculated value of the cost function and go to step 3.
7- end
As far as I checked the functions of MATLAB optimization toolbox, all of them need the handle of the cost function.


text:
Q: How to scale images using display: inline-block when resizing browser?

WORK

CSS
h1{
font-family: 'rex_bold_bold';
font-size: 40px;
margin-top: 60px;
letter-spacing: 15px
}
.pagework{
height: 1500px;
background-color:#FFF;
margin: 0 auto
}
.pageworkgallery{
height:1500px;
margin: 70px 70px 70px 70px;
max-width:100%
}
.pageworkgallery ul{
list-style:none
}
.pageworkgallery ul li{
display:inline-block;
padding: 4px
}

When I resize browser smaller the images go under one another into 1 column instead of staying at 2.
I want it to stay at 2 column.
When the broswer window is big:
http://oi60.tinypic.com/15wgz1x.jpg
When I resize browser smaller:
http://oi60.tinypic.com/2n8as1c.jpg

A: Chage
 structure to this

& css to this
.pageworkgallery ul{
    list-style:none
}

.pageworkgallery ul li{
    display:inline-block;
    width:50%;
    float:left;
}

.pageworkgallery ul li .wrapper{
    display:block;
    padding:4px;
    text-align:center;
}

.pageworkgallery ul li img{
    display:inline-block;
    width:100%;
    height:100%;
    max-width:500px;
}


text:
Q: How to dividie entries into different pages in Rails? For example, I have 30 entries, and I wish to divide them so that it only displays 3 of them on each page (and having many pages of course).
Currently, I have implemented it by passing a parameter in the URL and writing Ruby code in the action.
x = params[:id]
if x
  @problems = []
  x = params[:id].to_i
  t = Problem.all.count
  i = 1
  problem_numbers = -3 * (x - 1)
  while t > 0 do
    if Problem.exists?(i)
      problem_numbers += 1
      t -= 1
      if problem_numbers > 0
        @problems = @problems + [Problem.find(i)]
      end
    end
    if problem_numbers == 3
      break
    end
    i += 1
  end
end

It works quite well, but I think this piece of code might a bit complicated for such a feature; also if there are many entries, visiting pages would be slow because I counted through all the entries.
Is there a more convenient way to do this? Thanks in advance.

A: Displaying items across multiple pages is called pagination. will_paginate and Kaminari are two very popular gems that provide this functionality in a way that is very easily integrated into Ruby on Rails applications.


text:
Q: How to Pass Email Addresses into Recipient Emails Array - AWS SES I am having issues with passing an array of email addresses into AWS SES email recipients. I have a MySql query that generates an array $emails_array_from_query of email addresses:
for ($i=0; $i <$numrows; $i++) {
    $stmt->fetch();
    array_push($emails_array_from_query, $emailAddress);
};

I need to pass this array into SES client. AWS requires this format:
$recipient_emails = ['recipient1@example.com','recipient2@example.com'];

I tried to implode and json_encode the array that I received from MySQL query but none of it works and I am not sure what else to do. Here is what I tried:
$recipient_emails_to_pass =  "'" . implode("','",$emails_array_from_query) . "'";

and then I pass this this way:
$recipient_emails = [$recipient_emails_to_pass;]

I also tried this approach:
$recipient_emails_to_pass =  json_encode($emails_array_from_query);

$recipient_emails = [$recipient_emails_to_pass;]

None of these work. Any help would be greatly appreciated!


text:
Q: eclipse package with dot not representing directory structure In Eclipse you can create a package name with dots in it.
I.e danny.com.app
I would have thought this would create a directory structure of  app/com/danny, but eclipse create a package name call danny.com.app with with no directory structure representing this
Please can some explain this to me?

A: Of course, package names always go "a.b.c"
I guess: your package is simply empty so far. I think that some settings control if eclipse creates an empty directory as soon as you create a package.
Thus: see what happens when you add something into that package. I am pretty sure eclipse will then create the a/b/c directory in your filesystem.
But maybe your problem is that you are using the eclipse package view to look at your project.
Thing is: eclipse has different views that you can use to inspect your project. The package explorer ... shows packages, whereas the file explorer shows the actual file system folders, contents.


text:
Q: Amount of data needed for a statistically relevant regression analysis Trying to determine if a logarithmic regression analysis is valid. With good R2 values, does it matter that there are ony 7 data points?

A: In my opinion 7 observations is too small no matter what kind of regression you are running. I would recommend increasing the sample size to get more precise estimates.
It heavily depends on the specification that you are running though, as well as the model. With a logarithmic regression you mean OLS but with the log of the variables I assume. In either case, if you have many regressors and are dealing with a low sample size you'll have problems with low degrees of freedom, translating in a lack of significance. Also if the effect sizes that you are dealing with are small, you'll need more observations.
If you are working with experimental data try to do a power analysis beforehand to get an idea of the sample size needed.
Hope this helps.


text:
Q: In Regex, is it possible to use variable name rather than pure string? My case:
String TARGET1 = "abc";
String TARGET2 = "def";

I want to find the string that contains either "-abc" or "-def". (If the string is "-xyzabc", than this is not valid).
I know I can use a pure string to do this: ".*-(abc|def).*", but can I use the variable name to do the similar thing?
something like: String pattern = ".*-" + (TARGET1 || TARGET2) + ".*"; Is there a way to do so?
Thanks a lot!


text:
Q: Hidden div visible on reload, jQuery timing I'm working on a Wordpress theme for my blog and I have a kind of overlay-container. If you klick on a button it slides in from the top and pushes the whole page down.
I use jQuery for it, with this little code:
$(document).ready(function () {

// variables
var overlay = $('#layout-overlay'); // Overlay ID

 // hide overlay-container
     overlay.css({
         display: 'block',
         marginTop: -overlay.height()
     });

...and more code...

As you can see, I just hide the container by assigning a negative margin-top depending on height of the container which itself depends on the content.
As long as I put together the layout, everything worked fine. Now that I started to put it into an actual Wordpress theme, the overlay-container is visible on page-load and page-reload on every page it is included. It may be just for some milliseconds, but it is clearly noticeable. It is there for the blink of an eye and then it is gone as it is supposed to be from the very beginning.
Any ideas how I can retime the whole thing?
I put the JS in the <head> tag and I made sure it is the first code to be fired.

A: If you want to get rid of the glitch, first set the overlay's regular CSS to display: none. If the problem occurs, try displaying it after the page is fully loaded using load.
Bit more about ready vs load:
jQuery - What are differences between $(document).ready and $(window).load?


text:
Q: Initial Interface Orientation to Landscape iOS 9 Technical Note TN2244: Launching your iPhone Application in Landscape states:

The values of the UISupportedInterfaceOrientations key determine how the status bar is positioned while the the app is launching. In iOS 7 and below, if the UIInterfaceOrientationPortrait value is present, the status bar will always be positioned for portrait orientation. Otherwise, the status bar will be positioned according to the first orientation that appears under the UISupportedInterfaceOrientations key.

So in iOS 8 it was perfectly fine to put UIInterfaceOrientationLandscape first in the UISupportedInterfaceOrientations list to have your app to start in Landscape.
It does not work anymore in iOS 9. Having UIInterfaceOrientationPortrait in the list at any position forces app to start in Portrait.
Question
Is there a known workaround for this? I need my app to start in Landscape.
Note: Using viewControllers' supportedInterfaceOrientations() method is not an option as it takes effect after the LaunchScreen is presented.

A:
Having UIInterfaceOrientationPortrait in the list at any position forces app to start in Portrait.

That is absolutely correct — very good detective work. It took me a lot of experimentation to figure this out! This is certainly a huge change from iOS 8. You have summed up the situation very well.
Fortunately, the workaround is simple. In your Info.plist, include only the two landscape orientations. Now the app will launch into whichever one is first.
Now implement application:supportedInterfaceOrientationsForWindow: in the app delegate to return All. That way, when the time comes to show a portrait view controller, it will be legal to do so.
In other words, think of the Info.plist as what the launching app needs to know, and application:supportedInterfaceOrientationsForWindow: as what the running app needs to know.


text:
Q: Aforge Выдает ошибку и неправильно ищет образы Имеется метод:
public static Blob[] FindObject(Bitmap bitmap) {
        // locate objects using blob counter
        BlobCounter blobCounter = new BlobCounter();
        blobCounter.ProcessImage(bitmap);
        Blob[] blobs = blobCounter.GetObjectsInformation();

        // create Graphics object to draw on the image and a pen
        SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

        Graphics g = Graphics.FromImage(bitmap);
        Pen redPen = new Pen(Color.Red, 2);
        Pen invis = new Pen(Color.Transparent, 2);
        Pen yellowPen = new Pen(Color.Yellow, 2);
        Pen greenPen = new Pen(Color.Green, 2);
        Pen bluePen = new Pen(Color.Blue, 2);

        for (int i = 0, n = blobs.Length; i < n; i++)
        {
            List<IntPoint> edgePoints =
                blobCounter.GetBlobsEdgePoints(blobs[i]);

            AForge.Point center;
            float radius;

            if (shapeChecker.IsCircle(edgePoints, out center, out radius))
            {
                g.DrawEllipse(yellowPen,
                    (float)(center.X - radius), (float)(center.Y - radius),
                    (float)(radius * 2), (float)(radius * 2));
            }
            else
            {
                List<IntPoint> corners;
                    if (shapeChecker.IsQuadrilateral(edgePoints, out corners))
                    {
                        if (shapeChecker.CheckPolygonSubType(corners) ==
                            PolygonSubType.Rectangle)
                        {
                            g.DrawPolygon(greenPen, ToPointsArray(corners));
                        }
                        else
                        {
                            g.DrawPolygon(bluePen, ToPointsArray(corners));
                        }
                    }
                    else
                    {
                        corners = PointsCloud.FindQuadrilateralCorners(edgePoints);
                        g.DrawPolygon(invis, ToPointsArray(corners));
                    }
            }
            //Console.WriteLine(blobs[i].Rectangle);
        }

        redPen.Dispose();
        greenPen.Dispose();
        bluePen.Dispose();
        yellowPen.Dispose();
        g.Dispose();
        return blobs;
    }

Возникает ошибка
Необработанное исключение: System.ArgumentOutOfRangeException: Индекс за пределами диапазона. Индекс должен быть положительным числом, а его размер не должен превышать размер коллекции.

Имя параметра: index
в System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
в AForge.Math.Geometry.PointsCloud.FindQuadrilateralCorners(IEnumerable1 cloud) в AForge.Math.Geometry.SimpleShapeChecker.IsQuadrilateral(List1 edgePoints, List`1& corners)
После фрагмента кода else { List corners;...
Ошибка возникает не со всеми картинками. Например эта выходит с ошибкой:
https://ibb.co/By7WFJN
Я добавлял ошибочный код в try{} catch{}. И сохранял результаты. По итогу вместо 6-7 объектов библиотека находила 12 среди которых непонятные образы. Так же я вычислил, что ошибка из-за того что edgePoints.Count имеет слишком маленькое значение. Я бы хотел удалять такие элементы из blobs[] массива, но никак не могу это сделать. Прошу помощи с удалением таких объектов. Либо другой библиотекой и небольшим простым примером для вычисления объектов на изображении. Спасибо!!


text:
Q: Xlsxwriter making a chart which skips blank cells I am parsing a list of data from Python to Excel. I need to graph the relationship between the objects and time. The objects, however, do not have all column filled. It looks something like below:

Using XLSXWriter, I was able to graph both Object A and Object B versus Time. My code is something like this:
chart.add_series({
            'name': 'Object A',
            'categories': ['Sheet1', 1, 0, 17, 0], # Row 2 -> 18, column 0 (Time)
            'values': ['Sheet1', 1, 1, 17, 1]})    # Row 2 -> 18, column 1 (Object A)
chart.add_series({
            'name': 'Object B',
            'categories': ['Sheet1', 1, 0, 17, 0],
            'values': ['Sheet1', 1, 2, 17, 2]})
chart.show_blanks_as('span')

The line "chart.show_blanks_as('span')" has helped me to connect existed data with a line, meaning the "blank" cells are treated as some values on that linear line. But, in the x-axis still displays all value of the x-axis, from 1 to 9.
Is there a way so that the x-axis will only display "Time" values when at least one of the objects has data? (For this example: 1, 2, 2.5, 3, 4.5, 6, 6.5, 7.5). This will make it easier for other users who view the Excel file to know the time when there is actual data.


text:
Q: How to run Node-Red on Docker with multiple environments with git I'm running Node-Red on my server, and I want it to follow the deployment process like we are doing with code- working locally, making changes, commit and push.
Here is the list of the requirements:

*

*Run Node-Red on Docker.

*Track and backup tasks, configurations, all with Git

*Ability to clone the repository and start Node-Red, without any configurations.

*Make the changes on my local machine, and deploy them by pushing to Git.

To be more accurate, I need to add the flows.json, settings.json and package.json to the git.
And one of the main issues is when I'm adding a new package to the package.json, the NodeRed will not install it automaticlly.

A: The solution (workaround) I found is based on adding npm install to the docker entrypoint, how does it work?
Mount to local folder
First, we want to run the Node-Red, and mount its /data volume to our local folder:
docker run -p 1880:1880 -v $(pwd)/node-red:/data nodered/node-red

Now, if you're running from your local git repo, you will get a folder called node-red and it will include all the Node-Red workspace.
Add Node-Red data to Git
To track only the Node-Red configuration files, you need to add the next entries to your .gitignore file:
node-red/*
!node-red/package.json
!node-red/package-lock.json
!node-red/flows.json
!node-red/flows_cred.json
!node-red/settings.js

All the other files are auto-generated.
Install the missing packages on startup
Now, the hard part. If you added a new library in your local environment, and you pushed the changes, you want Node-Red to install the new library before it starts.
We will take the original Node-Red start command from Node-Red Dockerfile:
npm --no-update-notifier --no-fund start --cache /data/.npm -- --userDir /data

And before this command, we will take the npm install command suggested for a custom docker:
npm install --unsafe-perm --no-update-notifier --no-fund --only=production

Here is my final docker-compose.yml file, which includes a docker run commandline to run only this image in the development environment:
node-red:
  # port 1880
  # Dev: docker run -p 1880:1880 -v $(pwd)/node-red:/data --entrypoint="" --env-file .env nodered/node-red /bin/sh -c "npm install --prefix /data --unsafe-perm --no-update-notifier --no-fund --only=production && npm --no-update-notifier --no-fund start --cache /data/.npm -- --userDir /data"
  image: nodered/node-red
  env_file:
    - shared.env
  network_mode: host
  entrypoint: >
    sh -c "
    npm install --prefix /data --unsafe-perm --no-update-notifier --no-fund --only=production
    && npm --no-update-notifier --no-fund start --cache /data/.npm -- --userDir /data"
  environment:
    NODE_RED_CREDENTIAL_SECRET: ${NODE_RED_CREDENTIAL_SECRET}
  volumes:
    - ./node-red:/data
  restart: unless-stopped

A: You may consider using the new (preview) feature called Projects.
With this feature, the Git source control is integrated into your Node-Red instance, and shows you the changes, the missing packages, the commit history, and all.
To enable this feature, you need to turn it on in the settings.json file.
Since it is a solution that is officially supported by Node-Red (in preview), it's highly recommended. AFAIK, it will not solve your problem to auto-install newly added packages, but on the other hand, it giving you a better control about what is changed, what needs to be installed, and what is missing, in complex systems.


text:
Q: How Linux system calls interact with filesystem Lately I faced this excercise:

Given this sequence of system calls in a Linux C language program:

fd = open("f123", O_RDWRT | O_CREAT, 0777);
lseek(fd, 0x1000000L, 0);
write(fd, &fd, sizeof(int));

draw the file system data structures and disk blocks that are modified by these operations, considering a 4 KByte block size, and index block pointers of 4 bytes.

For the first system call (open) I realized how it works and schematized it in this way:

Now, skipping the draw part (I realize it would make difficult to answer), I'd like to understand how lseek and write works in term of inodes and index blocks (whatever they are).
I tried figuring that lseek computes the correct inode (as block size is known), but still no clue on how it actually works.

A: In Linux, these system calls interact with Virtual File System(VFS). VFS builds an abstraction over real filesystems, it defines some useful data structures to organize filesystem.

*

*inodes represents real file on the disk. Through inodes structure can access not only the inode block, but also data blocks on disk.

*directory entry represents part of a path. A d_entry doesn't always refer to a real file on the disk. If it refers to a directory on disk, there will be a pointer to the inode struct of the directory file.

*file represents files open by processes. There's also a pointer to its d_entry in the struct.

Here are snippets from file struct:
struct file {
    // ... other attributes
    struct path     f_path;
    #define f_dentry    f_path.dentry
    #define f_vfsmnt    f_path.mnt
    const struct file_operations    *f_op;
};
struct file_operations {
    // ... other operations
    struct module *owner;
    loff_t (*llseek) (struct file *, loff_t, int);
    ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
    ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
}

These objects all has an operation list field. VFS defines these operations and underlaying filesystems implement these operations or use general implementations provided by VFS.
Syscall open() creates the file object, other syscalls like lseek() simply get file object (through Fd) and call the corresponding function in the operation list, like write() will call f->f_op->write(f, ...), then filesystem may follow the file -> d_entry -> inode path to access file on disk.


text:
Q: Firebase :: Cannot read property of 'uid' of null I have created a basic project in NextJS using Firebase. The user has to create an account using email and password. During the signup process, a "patient" (patient name) field, which is a string, also has to be entered which is saved in the Cloud Firestore during the sign-up process with the same uid as that of the user.
I am trying to access the "patient" field from the Cloud Firestore on another page (random.js) but it is not working as expected. How do I fix it?
P.S: I am wrapping the entire thing in an AuthProvider Context as mentioned in this tutorial.
signUp.js:
import { useState } from "react";
import firebaseClient from "../firebaseClient";
import "firebase/compat/auth";
import {
  getAuth,
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
} from "firebase/auth";
import { useRouter } from "next/router";
import { setDoc, getFirestore, doc } from 'firebase/firestore'

export default function SignUp() {
  const router = useRouter();
  const db = getFirestore();

  firebaseClient();

  const auth = getAuth();

  const [values, setValues] = useState({
    email: "",
    password: "",
    patient: "",
  });

  const handeChange = (e) => {
    setValues({ ...values, [e.target.name]: e.target.value });
  };

  return (

      <form type="submit" onSubmit={handleForm}>
        <input
          type="email"
          value={values.email}
          name="email"
          autoComplete="off"
          onChange={handeChange}
          placeholder="Email"
        />

        <input
          type="password"
          value={values.password}
          name="password"
          onChange={handeChange}
          autoComplete="off"
          placeholder="Password"
        />

        <input
          type="text"
          value={values.patient}
          name="patient"
          onChange={handeChange}
          autoComplete="off"
          placeholder="Patient Name"
        />

        <button
          type="submit"
          disabled={values.email === "" || values.password === ""}
          onClick={async () => {
            createUserWithEmailAndPassword(auth, values.email, values.password)
              .then( async (userCredential) => {
                const user = userCredential.user
                await setDoc(doc(db, "Users" , user.uid ), {
                    patient: values.patient
                })
                router.push("/")
              })
              .catch(function (error) {
                const message = error.message;
                console.log(message);
              });
          }}
        >
          Register
        </button>
        <button
          type="submit"
          disabled={values.email === "" || values.password === ""}
          onClick={async () => {
            signInWithEmailAndPassword(auth, values.email, values.password)
              .then( function (userCredential) {
                   const user = userCredential.user;
                router.push("/");
              })
              .catch(function (error) {
                const message = error.message;
                console.log(message);
              });
          }}
        >
          Login
        </button>
      </form>

  );
}

auth.js:
import firebaseClient from './firebaseClient'
import {useState, useEffect, useContext, createContext} from 'react'
import nookies from 'nookies'
import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'

const AuthContext = createContext({});

export const AuthProvider = ({children}) => {

        firebaseClient();
        const [user, setUser] = useState(null);

        useEffect(() => {
            return (firebase.auth().onIdTokenChanged(async (user) => {
                if(!user){
                    setUser(null);
                    nookies.set(undefined, "token", "", {});
                    return
                }

                const token = await user.getIdToken();
                setUser(user);
                nookies.set(undefined, "token", token, {});
            }))
        },[])

    return(<AuthContext.Provider value={{user}}>{children}</AuthContext.Provider>);
}

export const useAuth = () => useContext(AuthContext)

random.js:
import {doc, onSnapshot, getFirestore} from 'firebase/firestore'
import { useAuth } from '../auth'
import { getAuth, onAuthStateChanged } from "firebase/auth";
import Link from 'next/link'

export default function Random (){
    const db = getFirestore();

    const {user} = getAuth();
    const unsub = onSnapshot(doc(db, "Users", user.uid), (doc) => {
        console.log("Current data: ", doc.data());
    });

  return (

      {
        user ? `Patient value goes here` : `No patient`
      }

  )
}

I am getting the following error in random.js:
error - pages\random.js (10:51) @ random
TypeError: Cannot read property 'uid' of null
   8 |
   9 |     const {user} = getAuth();
> 10 |     const unsub = onSnapshot(doc(db, "Users", user.uid), (doc) => {
     |                                                   ^
  11 |         console.log("Current data: ", doc.data());
  12 |     });
  13 |

A: The object returned by getAuth() has a property currentUser and not user. So try refactoring the code as shown below:
const user = getAuth().currentUser;

Also the value of user can be null so you must check for that:
if (user) {
  // proceed
}

Make sure the random.js component is loaded after the Firebase user state has loaded. It'll be best if you use onAuthStateChanged() just like you are using onIdTokenChanged() in auth.js
onAuthStateChanged(auth, (user) => {
  if (user) {
    const unsub = onSnapshot(doc(db, "Users", user.uid), (doc) => {
        console.log("Current data: ", doc.data());
    });
  }
})


text:
Q: Reactivate error message in Eclipse In Eclipse, some Java project's pom.xml caused an error message to occur. I selected an option similar to "hide error message" or "ignore". Since then, the message disappeared.
As the project doesn't build, I want the error message to reappear again to understand the problem. How do I make ignored messages visible again?


text:
Q: Comparing 2 objects, wrong equals() and hashcode? can somebody tell me why it returns "not equal"? Im searching for this for a long time and nothing... I think there is problem with my hashcode or/and equals method.
public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setFirstName("Kamil");
        s1.setLastName("Witam");
        s1.setMark(3.0);
        s1.setAge(12);

        Student s2 = new Student();
        s2.setFirstName("Kamil");
        s2.setLastName("Witam");
        s2.setMark(3.0);
        s2.setAge(12);

        if( s1.equals(s2)){
            System.out.println("równe");
        }
        else{
            System.out.println("sraka");
        }
    }
}

And my hashCode:
public int hashCode()
{
    final int prime = 31;
    int result = 1;

    result = prime * result + age;
    result = prime * result + ( ( firstName == null ) ? 0 : firstName.hashCode() );
    result = prime * result + ( ( lastName == null ) ? 0 : lastName.hashCode() );

    long temp;
    temp = Double.doubleToLongBits( mark );
    result = prime * result + (int) ( temp ^ ( temp >>> 32 ) );

    return result;
}

And equals:
public boolean equals( Object obj )
{
    if ( this == obj )
        return true;

    if ( obj == null )
        return false;

    if ( getClass() != obj.getClass() )
        return false;

    Student other = (Student) obj;

    if ( age != other.age )
        return false;

    if ( firstName == null )
    {
        if ( other.firstName != null )
            return false;
    }
    else
        if ( !firstName.equals( other.firstName ) )
            return false;

    if ( lastName == null )
    {
        if ( other.lastName != null )
            return false;
    }
    else
        if ( !lastName.equals( other.lastName ) )
            return false;

    if ( mark != other.mark )
        return false;

    return true;
}

Can somebody explain it to me :/? Thanks


text:
Q: WPF Animation to all rectangles in a grid I am a starter in wpf programming. The following code shows an error when I tried to animate colour of all rectangles used in grid 2. Do you know why?
<ColorAnimation Storyboard.TargetName="grid2"
                Storyboard.TargetProperty="Rectangle.Fill.Color"
                To="Indigo"/>

A: Try this
<Window x:Class="WpfApplication2.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1">

<Window.Resources>
    <Style x:Key="AniamateRectangle" TargetType="Grid">
        <Style.Resources>
            <Style TargetType="Rectangle">
                <Style.Triggers>
                    <EventTrigger RoutedEvent="Rectangle.Loaded">
                        <BeginStoryboard>
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetProperty="Fill.Color" BeginTime="0:0:0.2" Duration="0:0:0.5"  To="Indigo"/>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
        </Style.Resources>
    </Style>
</Window.Resources>

<Grid Style="{StaticResource AniamateRectangle}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Rectangle Height="100" Fill="Transparent" Width="100"/>
    <Rectangle Height="100" Fill="Transparent" Width="100" Grid.Column="1"/>
    <Rectangle Height="100" Fill="Transparent" Width="100" Grid.Column="2"/>
</Grid>


text:
Q: what the difference between kill the webloigc pid and run the stopWeblogic.sh in the linux os ,what is  the difference  between  kill the weblogic porcess and run the stopWeblogic.sh?

A: Without seeing the contents of stopWeblogic.sh my assumption would be that the script shuts down the service gracefully, but killing the pid in the OS just kills it, ungracefully.
Perhaps post some code and the answer could be better suited to your particular case.


text:
Q: Is there any way to instruct PHP XMLReader to *not* normalize carriage returns in elements I am processing XML with PHP's XMLReader, and I need to preserve white space characters, including carriage returns in the data I am parsing. However, the reader is replacing carriage returns with new line characters. Is there a way to instruct it not to do that?

A: XMLReader will automatically normalize \r\n\ to \n. Although you want to preserve those, it is actually required by the XML Specification (2.11 End-of-Line Handling).
You can probably work around that by afterwards replacing \n with \r\n.
str_replace("\n", "\r\n", $reader->value)

For white space handling XMLReader passes whitespace unaltered and differs between WHITESPACE and SIGNIFICANT_WHITESPACE nodes.
Generally speaking, as you need to "preserve white space characters, including carriage returns in the data" XML is not the right technology to handle and process your data.
Depending on your use-case you can decide to encode the binary data you have in a way so that it is preserved in XML, e.g. with base64_encode.


text:
Q: Can I use Ruby Cucumber Watir to Solve a Key Pass to URL puzzle? I am a NEWBIE. Any help is appreciated.
I've been given the challenge of automating a Key Pass challenge.
a URL is provided (this is an example, I don't think the creator of the challenge wants it in public): www.guessmypasskey.com
When you visit the site, the body text simple returns, Key Denied:
If you add the following path, www.guessmypasskey/?key=a the site will return: Key Denied:00
The key is only alphanumeric and of unknown length...through manual testing I was able to find the key by determining that the binary code returns meant the following: 00 not a character used, 01 character used, wrong position, 11 correct character, correct position.
I envision, opening a browser to the URL with watir, checking a-a, A-Z, 0-9, in the first position...if 00 is displayed on page, delete character from possibility, if 01 is present write the number to a file (this will determine the character length needed.
Basic question, Am I going the wrong direction? Trying to automate with Ruby Cucumber Watir?
I know additional steps will be needed t determine the order of the characters....I'm just trying to get started on the first step, confirming the validity of the characters and the length of the pass key.

A: Kind of disappointed that the URL the real one. =p
Anyways, that approach would work... but I would imagine it being massive overkill.
Instead, what I would do is simply create a simple Node.js script (using JavaScript) which basically just loops through all possible combinations for each character, stepping through as you move.
You can just use the simple "request" module to request the web page. Then just build up your string like that.
var request = require('request');

// Gets content of one call... add this to your loop somehow.
request({uri: 'http://guessmypasskey.com?key=' + key}, function (err, response, body) {
   // body has the result to check
});

This is probably going to be infinitely easier than setting up the tech stack you were talking about... not to mention a lot faster.
Your general approach (ignoring technology) sounds pretty spot on.


text:
Q: Why does my derivation of $\mathcal{L(\frac{f(t)}{t})}$ lead to a wrong answer? I'm trying to prove that
$$\mathcal{L(\frac{f(t)}{t})(s)} = \int_s^{\infty}\mathcal{L(f(t))}(u)du$$
Here's my attempt:
$$\mathcal{L(\frac{f(t)}{t})}(s)=\int_{0}^{\infty} \frac{f(t)}{t}e^{-st}dt$$
By using Leibnitz' differentiation under the integral sign, we get:
$$ \dfrac{d\mathcal{L(\frac{f(t)}{t})}(s)}{ds}=-\int_{0}^{\infty} f(t)e^{-st}dt=-\mathcal{L(f(t))(s)}$$
$$\mathcal{L(\dfrac{f(t)}{t})}(s)= - \int \mathcal{L(f(t))(s)} ds$$
It can be rewritten as:
$$\mathcal{L(\dfrac{f(t)}{t})}(s)= - \int_{0}^{s} \mathcal{L(f(t))(u)} du$$
But this is apparently wrong. I can't figure out what I'm doing wrong on my own.

A: Don't you insert your integration limits in a wrong way? Why are you taking the one limit as $0$ instead of $\infty$? Take your intermediate result
$$ \frac{d}{du}\mathcal{L(f(t)/t)}(u)=-\mathcal{L(f(t))(u)}$$
then integrate from $k\to\infty$ to $s$ to get
$$
\mathcal{L(f(t)/t)}(s)-\lim_{k\to\infty}\mathcal{L(f(t)/t)}(k) = \int_s^\infty\mathcal{L(f(t))(u)}du
$$
Finally you have to show that
$$
\lim_{k\to\infty}\mathcal{L(f(t)/t)}(k) = \lim_{k\to\infty}\int_{0}^{\infty} \frac{f(t)}{t}e^{-kt}dt \overset{?}{=} 0
$$
Now under certain conditions (which I don't remember, but which probably are fulfilled here) you can interchange the limit and the integration and note that "$e^{-\infty}=0$" to get the result

A: This is frequency integration.
Hint: RHS  = $\int_{s}^{\infty} F(u) du$ = $\int_{s}^{\infty} \int_{0}^{\infty} f(t)e^{-ut} dt du$
If you give up:
http://www.eee.hku.hk/~u3500898/LTProperty.pdf
I think the justification for the double integral swap is the same as the justification for your swapping of derivative and integral in your attempt.

A: The hitch is at the end :
$\mathcal{L(\dfrac{f(t)}{t})}(s)= - \int \mathcal{L(f(t))(s)} ds$ + constant
It can be rewritten as:
$\mathcal{L(\dfrac{f(t)}{t})}(s)= - \int_{0}^{s} \mathcal{L(f(t))(u)} du +C$
Now, you will have to determine $C$ as
$C=  \int_{0}^{\infty} \mathcal{L(f(t))(u)} du $


text:
Q: how to use opencv Mat reserve? with push_back I want to use the opencv cv::Mat function push_back to add new rows to a matrix, but I want to precache the size of the matrix so that the data doesn't need to be constantly reallocated. The cv::mat::reserve function has a number of rows parameter, but that implies that you have to specify the number of columns (and data size first). So the code below I assume would give me one empty row at the beginning which I don't want. Is there a proper way to do this using reserve and push_back??
cv::Mat M(1, size_cols, CV_32FC1);
M.reserve(size_rows);
for (int i = 0; i < size_rows; i++)
{
  GetInputMatrix(A);
  M.push_back(A.row(i));
}

Note: though the example code doesn't show it I'm not sure of the exact size of the final matrix, but I can get a max value size to reserve.

A: Using an empty mat in the beginning will be just fine. The column number and type will be determined via the first push_back.
cv::Mat M;  // empty mat in the beginning
M.reserve(size_rows);
for (int i = 0; i < size_rows; i++) {
    GetInputMatrix(A);
    M.push_back(A.row(i));
}

A: Well, according to documentation,
reserve does:

The method reserves space for sz rows. If the matrix already has enough space to store sz rows, nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method emulates the corresponding method of the STL vector class.

That being said, as long as you don't that huge amount of data to store, nothing will happen.


text:
Q: Accessing existing session data from a subdomain in CodeIgniter I have two websites on the same server -
1) subdomain.example.com where users log in. I setup a session cookie with domain as .example.com
2) my second website is at example.com which is a brand new CI powered website and no functionality has been added yet. I added a plain php file at example.com/plain.php to test if I am able to access data across all domain variations.
In subdomain.example.com/login.php I setup session cookie as
session_name('mysess');
session_set_cookie_params(0, '/', '.example.com');
session_start();

In http://example.com/Plain.php
session_name('mysess');
session_set_cookie_params(0, '/', '.example.com');
session_start();
echo '<pre>'; print_r($_SESSION);

In My CodeIgniter website http://subdomain.example.com/application/config.php
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'mysess';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '.example.com';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;

Once users login at subdomain.example.com I can see the session data at example.com/plain.php without any issues but as soon as I view any page on example.com/mycontroller/mymethod it overwrites the session data and I lose all the session data set after login at subdomain.example.com
I need that same session data on both of the sites to see if a user is logged in or not.
What changes do I need to make in CI config to be able to get that data?


text:
Q: MySQL Join Query to Sum a Field in One Table based on Its Corresponding Login ID in another Table I have a MySQL table comment with the following fields:
loginid submissionid points

I have a MySQL table called submission with the following fields:
loginid submissionid

For a given submissionid, the loginid in the two tables represent different things and therefore do nor correspond.
I would like a join to sum up points by loginid.  However, not by the loginid in comment, but rather the loginid in submission.  The connection between the two tables is made via the submissionid
I can't get this to work.  Below is what I have so far.  I'm trying to get this desired sum for each loginid pulled from another, third table, which is what the l.loginid represents.
How can I do this?
LEFT JOIN (
    SELECT C2.submissionid, C2.loginid SUM(points) AS total
    FROM comment C2
    INNER JOIN submission S2
    ON S2.submissionid = C2.submissionid
    GROUP BY C2.submissionid
) cscs ON cscs.loginid = l.loginid

A: SELECT S2.loginid, SUM(points) AS total
FROM submission S2
INNER JOIN comment C2
ON S2.submissionid = C2.submissionid
GROUP BY S2.loginid

This will give you a points sum for each loginid in the submission table.


text:
Q: I have been trying to figure out how to make video of selected images with FFmpeg I am working with Android videos and  I know how to determine the series  of images using gallary View. But I'm stuck on FFmpeg now.
With the below code I am getting some images from gallery:
btnSelect.setOnClickListener(new View.OnClickListener() {

  public void onClick(View v) {
    final int len = thumbnailsselection.length;
    int cnt = 0;
    String selectImages = "";

    for (int i = 0; i < len; i++) {
      if (thumbnailsselection[i]) {
        cnt++;
        selectImages = selectImages + arrPath[i] + "|";
      }
    }

    if (cnt == 0) {
      Toast.makeText(getApplicationContext(), "Please select at least one image", Toast.LENGTH_LONG).show();
    } else {

      Log.d("SelectedImages", selectImages);
      Intent i = new Intent();
      i.putExtra("data", selectImages);
      setResult(Activity.RESULT_OK, i);
      finish();
    }
  }
});

Any clues?
Thanks.


text:
Q: Splitting every character of a string? I want to split a string into each single character. Eg:
Splitting : "Geeta" to "G", "e", "e" , "t", "a"
How can I do this? I want to split a string which don't have any separator
Please help.

A: String.ToCharArray()
From MSDN:

This method copies each character (that is, each Char object) in a string to a character array. The first character copied is at index zero of the returned character array; the last character copied is at index Array.Length – 1.

A: You can iterate over the string like this:
foreach (char c in myString)
{
       Console.WriteLine(c);
}

A: you can use a simple for-loop with chars:
foreach (char ch in stringVar)
{
  Console.WriteLine(ch.ToString());
}

I fact you don't need to split it, because you already can acces every single char element in a string of its own.

A: You can do the following. Though it is not an effective way to do.
public class Main {
public static void main(String[] args) {
String str ="Noman";
for(int i = 0; i<str.length(); i++){

System.out.println(str.charAt(i) +" ");
}
}
}


text:
Q: Unexpected Error while using the predict() function in R for time series Data The data has half hourly load data (electricity demand) from 7/21/2009 11:30 to 7/23/2014 23:30. The variable "LOAD.MW" is measured sequentially in time at a fixed interval of time, so the resulting data may be considered to be a time series.
I have converted the data into "ts" class
data.ts <- ts(data$LOAD.MW, start=c(as.numeric(as.Date("2009/07/21")),26),
              end=c(as.numeric(as.Date("2014/7/23")),48),frequency=48)

Then I have fitted the arima model:
 data.fit1 <- arima(data.ts, order = c(2,0,0))
 data.fit1

# Call:
# arima(x = data.ts, order = c(2, 0, 0))

# Coefficients:
#          ar1      ar2  intercept
#       1.8421  -0.8765  2675.7445
# s.e.  0.0016   0.0016     5.5789

# sigma^2 estimated as 3222:  log likelihood = -479024.8,  aic = 958057.7

Now I want to do some prediction. So, I have used the predict function:
data.pred1 <- predict(data.fit1,n.ahead=100)   #Making 100 half hour prediction

Error in predict(data.fit1, n.ahead = 100) :
  unused argument (n.ahead = 100)

It is giving me an error. I am not able to understand why I am getting this error. Why the argument n.ahead=100 is said unused? I used this function before also but then I worked for me. In fact I have also experienced that sometimes it works and sometime it does not.
Also when I tried to forecast using the forecast() function I got the same error.
forecast(data.fit1,5)

Error in predict(object, n.ahead = h) : unused argument (n.ahead = h)

Please give ur expert opinion and help me to correct this error.


text:
Q: How to switch to another user on the terminal in SLES 12? I created a user (useradd -d /home/newuser -c "My new user" -s /bin/true newuser), set a password (su newuser), and want to work under this username. But I cannot switch to this user. No error messages, no warnings -- the switch just does not succeed:
olduser@mymachine$ su - newuser
Password:
olduser@mymachine$ whoami
olduser@mymachine$ olduser

or
olduser@mymachine$ su newuser
Password:
olduser@mymachine$ whoami
olduser@mymachine$ olduser

How to switch the user on the CLI in SUSE Linux Enterprise Server 12?

A: I assume it is the way you created newuser assigning it a /bin/true shell by specifying -s /bin/true.
From the useradd man page:
https://linux.die.net/man/8/useradd
-s, --shell SHELL
    The name of the user's login shell. The default is to leave this field blank, which causes the system to select the default login shell specified by the SHELL variable in /etc/default/useradd, or an empty string by default.

As you set it to /bin/true the exit status is 0 and therefore not producing any error message. Setting such shell is only common for users which should not be allowed to login to the system. Typically /bin/false is used, as this would lead to an error message similar to cannot create shell which at least gives an idea what fails.
It can be resolved by usermod -s /bin/bash newuser.


text:
Q: Android-GCM: How to take care of a logged out user? In my app, once I register a device, it's stored as persistent data in order to check whether the device is already registered.
On the server side I store them in a database along with a user_id which is a unique id for a user.

[user_id] [gcm_registration_id]

Now I am unable to tackle this case:
If the User logs out:

*

*The registration_id which is stored in SharedPreferences must be cleared because another user might log in the next time the app is launched.

*In addition, I have to delete the row corresponding to that registration_id from my database because that device (which has no currently logged in user) must not receive any more notifications.
The problem is that my database gets updated using the canonical_ids or say the latest registration_ids I get when calling
https://android.googleapis.com/gcm/send
So, there is a chance that I cannot find the old registration_id of the logged out user to delete, which still allows sending notifications to a non logged in user.
Also I cannot delete a row my DB matching the user_id because a user might have logged out from only 1 device and there are few more devices on which he/she is still logged in.
How will I know that for this particular user and device, the registration id is changed?
Should I store all the old registration ids and their corresponding canonical_ids in my database?

A: You have two options :

*

*As suggested in the comments - keep the registration ID of the user that logged-out in your DB, but mark it with a flag that indicates it's a logged-out user. Your server won't send notifications to registrations IDs marked as logged-out.

*When a user logs out from your app on a device, the app on that device will un-register from GCM and send a log-out request to your server with the user-id and the registration ID. The server will delete that user-id/registration-id combination from the DB. Even if for some reason your server contains a newer registration ID for that device (causing the delete attempt to fail), you won't be able to send notifications to the device with that registration ID, since the app unregistered the device from the GCM service. But this case is not likely to happen anyway, since whenever GCM changes the registration ID for a given app on a given device, is sends that registration ID to the app, and the app should send in to your server. Only failing to do so may cause the situation in which your server sends a notification with an old registration ID and gets a new canonical registration ID in the response.

A: private String android_id = Secure.getString(getContext().getContentResolver(),Secure.ANDROID_ID);
This line will return an unique android_id for any device (thx) For any user you could store an array of devices, when logging send a message from the client or check every several minutes.
Hope


text:
Q: Upgrade jboss fuse oracle driver to 19c compatible driver I am using jboss fuse with oracle 11g. We are planning to upgrade the database to oracle 19c and the 11g jdbc driver is not compatible with 19c database. I copied 19c drive to lib directory but did not work. Am I missing anything here ?

A: Hope you are using the 19c JDBC drivers from Central Maven or from OTN. Can you specify the error that you are getting?


text:
Q: Can I use a url to view my workbench application by browser like i use for phpmyadmin Hi I am new to workbench and I have migrated from phpmyadmin to workbench recently and I want my workbench to be accessed from my laptop which is connected with my system. I usually do by logging it with the ip address of my system like 192.164.xx.xx/phpmyadmin. Is it possible for me to view like the same in workbench please any help is appreciated.

A: You can't show workbench in a browser. It is a seperate program. You have to install workbench on your notebook too.


text:
Q: C# xml document find value by attribute I did research and found around 10 different threads asking similar questions. I also found different ways to do it: linq, xpath, etc.
I tried all of them but I never get any result. It is always 'null'.
So here is my xml; I want the OpCorrelation as a string:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
  <Provider Name="Microsoft-Windows" Guid="{123}" />
  <EventID>12</EventID>
  <Version>0</Version>
  <Level>0</Level>
  <Task>1</Task>
  <Opcode>0</Opcode>
  <Keywords>0x1110000000000000</Keywords>
  <TimeCreated SystemTime="2017-07-26T11:08:06.899918600Z" />
  <EventRecordID>3333</EventRecordID>
  <Correlation />
  <Execution ProcessID="2" ThreadID="3" />
  <Channel>Security</Channel>
  <Computer>test</Computer>
  <Security />
</System>
<EventData>
  <Data Name="OpCorrelationID">{abc}</Data>
  <Data Name="AppCorrelationID">-</Data>
  <Data Name="SubjectUserSid">123-S-123</Data>
  <Data Name="SubjectUserName">TestUser</Data>
  <Data Name="SubjectDomainName">TEST</Data>
  <Data Name="SubjectLogonId">0x3a111</Data>
  <Data Name="DSName">test.local</Data>
  <Data Name="DSType">%%14111</Data>
  <Data Name="ObjectDN">cn=bbbbb bb. bbb,OU=test,OU=Test123,DC=test,DC=local</Data>
  <Data Name="ObjectGUID">{DF0F5628-70DA-4AC4-B72E-111111111}</Data>
  <Data Name="ObjectClass">user</Data>
  <Data Name="AttributeLDAPDisplayName">pwdLastSet</Data>
  <Data Name="AttributeSyntaxOID">2.5.5.16</Data>
  <Data Name="AttributeValue">131455408816821756</Data>
  <Data Name="OperationType">%%14675</Data>
</EventData>

And here is the code I tried:
string OpCorrelationID = (string)XDocument.Parse(record.ToXml()).Descendants("Data").FirstOrDefault(d => (string)d.Attribute("Name") == "OpCorrelationID");

and
string OpCorrelationID = XDocument.Parse(record.ToXml()).XPathSelectElement("descendant::Data[@Name='OpCorrelationID']").Value;

A: can you try using dynamic  XML DOCUMENT TO A DYNAMIC OBJECT IN .NET

A: Just add Value to Attribute("Name") - Attribute("Name").Value == "smth"

A: Removed the "Data" from Descendants and it works.


text:
Q: how can i animate this marker? can anyone help me please? I want to animate the "bus" marker I've seen a lot of videos and tutorials but I can't make it work I'm newbie to android, this is the only thing i'm missing for the completion of my app,i want the marker to move through the polyline thank you very much for your help!
This is the code:
package com.example.alejandro.integradora2;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

public class RutaUtd extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
        LocationListener,
        OnMapReadyCallback {

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    TextView info;

    LatLng latLng;
    GoogleMap mGoogleMap;
    Location mLastLocation;
    Marker mCurrLocation, bus,finr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }

    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mGoogleMap.setMyLocationEnabled(true);

        buildGoogleApiClient();

        mGoogleApiClient.connect();

        // Add a marker in Sydney and move the camera
        LatLng inicio = new LatLng(23.989444, -104.617897);
        LatLng fin = new LatLng(24.032782, -104.639596);
        mGoogleMap.addMarker(new MarkerOptions().position(inicio).title("Inicio Ruta").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
        mGoogleMap.addMarker(new MarkerOptions().position(fin).title("Fin Ruta"));
        bus= mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(23.996506, -104.638496)).title("Ubicacion del Bus").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus)));
        //mMap.animateCamera(CameraUpdateFactory.zoomTo(10));

        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(24.005651, -104.600266), 12));

        PolylineOptions RutaIda = new PolylineOptions()
                .add(new LatLng(23.989444, -104.617897),new LatLng(23.996506, -104.638496),new LatLng(23.996741, -104.638694),new LatLng(23.998000, -104.638673),new LatLng(23.998720, -104.639027),
                        new LatLng(24.000460, -104.640336),new LatLng(24.001126, -104.641189),new LatLng(24.001479, -104.642369),new LatLng(24.002038, -104.643131),new LatLng(24.004086, -104.644274),
                        new LatLng(24.005674, -104.644124),new LatLng(24.006680, -104.644261),new LatLng(24.021361, -104.645530),new LatLng(24.026858, -104.645884),new LatLng(24.032508, -104.639628),
                        new LatLng(24.032831, -104.638727),new LatLng(24.032851, -104.636989),new LatLng(24.033086, -104.636957),new LatLng(24.033194, -104.639135),new LatLng(24.032782, -104.639596))
                .width(5)
                .color(Color.RED);
        Polyline polyline = mGoogleMap.addPolyline(RutaIda);

        PolylineOptions RutaVuelta = new PolylineOptions()
                .add(new LatLng(24.032782, -104.639596),new LatLng(24.027185, -104.645781),new LatLng(24.025901, -104.645888),new LatLng(24.006594, -104.644299),new LatLng(24.004761, -104.644396),
                        new LatLng(24.003761, -104.644267),new LatLng(24.002016, -104.643237),new LatLng(24.001085, -104.641488),new LatLng(24.000634, -104.640619),new LatLng(23.998919, -104.639366),
                        new LatLng(23.998203, -104.638894),new LatLng(23.997017, -104.638862),new LatLng(23.996596, -104.639184),new LatLng(23.989328, -104.618017)

                )
                .width(8)
                .color(Color.parseColor("#802E2EFE"));
        //.color(Color.BLUE);

        Polyline ruta = mGoogleMap.addPolyline(RutaVuelta);

    }

    @Override
    public void onPause() {
        super.onPause();
        //Unregister for location callbacks:
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    protected synchronized void buildGoogleApiClient() {
        Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    public void onConnected(Bundle bundle) {
        Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            //place marker at current position

            latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title("Posicion Actual");
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
            mCurrLocation = mGoogleMap.addMarker(markerOptions);
        }

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(5000); //5 seconds
        mLocationRequest.setFastestInterval(3000); //3 seconds
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        //mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLocationChanged(Location location) {

        //remove previous current location marker and add new one at current position
        if (mCurrLocation != null) {
            mCurrLocation.remove();
        }
        latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocation = mGoogleMap.addMarker(markerOptions);

        //Toast.makeText(this,"Location Changed",Toast.LENGTH_SHORT).show();

        //If you only need one location, unregister the listener
        //LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        info= (TextView) findViewById(R.id.distancia);

        LatLng autobus=bus.getPosition();
        // LatLng markerLatLng = marker.getPosition();
        Location bus = new Location("");
        bus.setLatitude(autobus.latitude);
        bus.setLongitude(autobus.longitude);
        float distancia=mLastLocation.distanceTo(bus)/1000;

        info.setText("El camion se encuentra a "+distancia+" km aproximadamente de tu ubicacion");

    }

}


text:
Q: Is there any way to enable or disable the Spring bean definition in applicationContext.xml file? Is there any way to enable or disable a java bean definition in application context?
<bean id="enBean" classs="com.en.bean.BeanName">
   <property name="prop1"/>
</bean>

Or, is there any way to load the bean conditionally defined in application context?

A: There is a new feature @Profile in spring 3.1 that would do the job
From here

Spring 3.1 introduces the concept of environment profiles. A common
  use case is the setting up of beans that are different between
  development, QA and production environments. A typical example is
  going against a standalone DataSource in development versus looking up
  the DataSource from JNDI in production. Another example is a beans
  profile for profiling that can easily be turned on or off. You can add
  a profile attribute on a beans element in XML or add @Profile
  annotation in code. Note that a Spring bean can be assigned to
  multiple profiles.

<beans profile="dev">
    ...
</beans>
@Profile("dev")
public class Bean {
    ...
}

These profiles can be activated through the spring.profiles.active
  property which may be specified through an environment variable, a JVM
  system property, a Servlet  in web.xml or JNDI. These
  profiles can also be activated through code using
  Environment.setActiveProfiles(String ...). To make bean profiles work,
  nested beans elements are now allowed in the Spring XML, although
  constrained only at the end of the file. Note that it's recommended to
  keep your bean topology as close as possible between environments, so
  your application gets properly tested across environments. You also
  use the Environment.containsProperty() method to search for properties
  across the different property sources. This property resolution also
  works for ${placeholder} variables in XML bean definitions.