Make nose test runner show logging even if tests pass

Question: I am using nosetests test.py to run unit tests:
import unittest
import logging

class Test(unittest.TestCase):
    def test_pass(self):
        logging.getLogger('do_not_want').info('HIDE THIS')
        logging.getLogger('test').info('TEST PASS')
        self.assertEqual(True, True)

    def test_fail(self):
        logging.getLogger('do_not_want').info('HIDE THIS')
        logging.getLogger('test').info('TEST FAIL')
        self.assertEqual(True, False)

When test fails, it prints out all logging info. I can use --logging-filter to filer out only some loggers:
nosetests test.py --verbosity=2 --logging-filter=test
test_fail (test.Test) ... FAIL
test_pass (test.Test) ... ok

======================================================================
FAIL: test_fail (test.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".../test.py", line 14, in test_fail
    self.assertEqual(True, False)
AssertionError: True != False
-------------------- >> begin captured logging << --------------------
test: INFO: TEST FAIL
--------------------- >> end captured logging << ---------------------

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)

However, it does not show anything when tests pass.
I would like to see output of one specific logger when tests pass. I have found that I can use -s to show all stdout / stderr text which is not exactly what I need - it prints everything. I tried to play with various settings such as --nologcapture, --nocapture, or --logging-filter but I was not able to get desired effect.
Comment: The logcapture plugin is only ~250 lines. You can probably subclass or adapt it quite easily to do what you want. You can find it [here](https://github.com/nose-devs/nose/blob/master/nose/plugins/logcapture.py).
Comment: @Fenikso Did you find a solution for the problem?
Comment: @Stefan No, it does not seem to exist in Nose. I am using a few ugly workarounds when needed, such as writing to file.
Comment: @Fenikso Thank you for your answer. It's a shame that nose doesn't support that...
Answer: nosetests --help does not make this obvious AT ALL, but the answer is the --debug flag. This flag takes as an argument the name of the logger that you'd like to receive messages from.
Here's a slightly modified version of the OP's code:
# test.py
import unittest
import logging

class Test(unittest.TestCase):
    def test_pass(self):
        logging.getLogger('hide.this').info('HIDE THIS')
        logging.getLogger('show.this').info('TEST PASS')
        self.assertEqual(True, True)

    def test_fail(self):
        logging.getLogger('hide.this').info('HIDE THIS')
        logging.getLogger('show.this').info('TEST FAIL')
        self.assertEqual(True, False)

For this example, nosetests test.py --debug=show.this should do the trick.
Comment: How would you do this for the root logger (e.g. `logging.debug('HELP')`) -- I tried `--debug=root` and that didn't seem to work.
Comment: `--debug=root` works for me with nosetests version 1.3.7. I have NO `logging.basicConfig` in my sources, maybe that is important.
Comment: @JonathonReinhart try `--nocapture` to not capture anything
Answer: I'm not sure if this is what you want.
In my case I use:

nosetest -v -s

-s, --nocapture
Don't capture stdout (any stdout output will be printed immediately) [NOSE_NOCAPTURE]
HTH


QLabel & Word Wrap : How to break line base on a comma (vs space)

Question: I am trying to make a multi line QLabel with a text without space but delimited by comma.
ex : 'Cat,Dog,Rabbit,Train,Car,Plane,Cheese,Meat,Door,Window'

I have found that multiline is possible with setWordWrap but it breaks based on spaces.
How would it be possible to break line based on comma ?
Here is an example of code :
from PySide2.QtWidgets import *

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setGeometry(500,100,50,100)

        line = QLabel()
        line.setMaximumWidth(150)
        line.setText('Cat,Dog,Rabbit,Train,Car,Plane,Cheese,Meat,Door,Window')
        line.setWordWrap(True)

        self.setCentralWidget(line)

        self.show()

if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    app.exec_()

Comment: @Pythmalion A quick and dirty fix is to insert a [zero-width-space](https://en.wikipedia.org/wiki/Zero-width_space) (`\u200b`) after every comma, since word-wrapping breaks after *any* kind of whitespace.
Comment: You need the words to be all on separate lines or to act like word wrap and fit the container?
Comment: I would like to have the same mechanism than word wrap. In this example, it should break after Car,
Comment: @ekhumoro Thanks, maybe a bit dirty but it makes the job. To my opinion this is a/the solution !
Answer: One way of doing it would be to edit the text according to QLabel size.
The following triggers on every line size event, making this a costly solution.
First we add a signal :
class MainWindow(QMainWindow):
    resized = QtCore.pyqtSignal()

Then we connect signal with a method ,set wordwrap to False and add custom resize event that triggers every time label gets a new size:
self.line.setWordWrap(False)
self.line.resizeEvent = self.on_resize_event
self.resized.connect(self.add_spaces)

on_resize_event which handles size changes and triggers add_spaces :
def on_resize_event(self, event):
    if not self._flag:
        self._flag = True
        self.resized.emit()
        QtCore.QTimer.singleShot(100, lambda: setattr(self, "_flag", False))
    print(f"Resized line: {self.line.size()}")
    return super(MainWindow, self).resizeEvent(event)

Lastly we have a add_spaces method which calculates maximum line length and splits on comma.
def add_spaces(self):
    size = self.line.size()
    text = self.mystring
    result_string = ""
    temp_label = QLabel()
    temp_text = ""

    #Split the chunks by delimiter
    chunks = text.split(",")

    for i,chunk in enumerate(chunks):
        temp_text += chunk + ",";
        if len(chunks) > i+1:
            temp_label.setText(temp_text + chunks[i+1] + ",")
            width = temp_label.fontMetrics().boundingRect(temp_label.text()).width()
            if width >= size.width():
                result_string += temp_text + "\n"
                temp_text = ""
        else:
            result_string += temp_text

    self.line.setText(result_string)

Full code:
from PyQt5 import QtCore
from PyQt5.QtWidgets import QMainWindow, QLabel, QApplication

class MainWindow(QMainWindow):
    resized = QtCore.pyqtSignal()
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self._flag = False

        self.line = QLabel()
        self.line.setStyleSheet("background-color: grey;color:white;")
        self.line.setMaximumWidth(300)
        self.line.setMinimumWidth(20)

        self.mystring = 'Cat,Dog,Rabbit,Train,Car,Plane,Cheese,Meat,Door,Window,very,long,list of words,list of words,word,word,word,list of word,word,list of word,list of word'

        self.line.setText(self.mystring)

        self.setCentralWidget(self.line)

        self.line.setWordWrap(False)
        self.line.resizeEvent = self.on_resize_event
        self.resized.connect(self.add_spaces)

        self.show()
        self.add_spaces()

    def on_resize_event(self, event):
        if not self._flag:
            self._flag = True
            self.resized.emit()
            QtCore.QTimer.singleShot(100, lambda: setattr(self, "_flag", False))
        print(f"Resized line: {self.line.size()}")
        return super(MainWindow, self).resizeEvent(event)

    def add_spaces(self):
        size = self.line.size()
        text = self.mystring
        result_string = ""
        temp_label = QLabel()
        temp_text = ""

        #Split the chunks by delimiter
        chunks = text.split(",")

        for i,chunk in enumerate(chunks):
            temp_text += chunk + ",";
            if len(chunks) > i+1:
                temp_label.setText(temp_text + chunks[i+1] + ",")
                width = temp_label.fontMetrics().boundingRect(temp_label.text()).width()
                if width >= size.width():
                    result_string += temp_text + "\n"
                    temp_text = ""
            else:
                result_string += temp_text

        self.line.setText(result_string)

if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    app.exec_()

Comment: Be amare that changing geometry within a `resizeEvent` is not suggested, as it can easily lead to recursion especially with widgets that have adapting size hints just like QLabel.
Comment: @musicamante Yea thats true. How should the `resizeEvent` be handled? At the moment i changed it to have a 100ms delay to prevent that.
Comment: Thanks for the time spent on your answer. Might not be the answer but I learned other things and it show me how to overcome another of my problems :)
Comment: @BlueGhost it should not call a resize at all, and a good (but *far from easy*) implementation would require proper subclass of QLabel, at least overriding `resizeEvent` to compute the correct word wrapping, `hasHeightForWidth` and `heightForWidth` for appropriate "ratio" hint, `sizeHint` for the possible "final" hint, `setText` for the minimum size and probably even paintEvent; all this would obviously work better if keeping an internal QTextDocument (which is what QLabel actually does).


Where should I put common background sync tasks in an MvvmCross project?

Question: My application needs to sync data from an online source.  It then stores it so it can be used offline.  I am currently calling this from a custom class implementing IMvxAppStart.
<code>public class AppStart: MvxNavigatingObject, IMvxAppStart
{
    private readonly IUpdateLocationsService _updateLocationsService;

    public AppStart(IUpdateLocationsService updateLocationsService)
    {
        _updateLocationsService = updateLocationsService;
    }

    public void Start(object hint = null)
    {
        _updateLocationsService.Update();
        ShowViewModel<MainMenuViewModel>();
    }
}
</code>
The issue I am running into is there is no good, cross-platform way to check if I have connectivity or not, and my code crashes if there is no connectivity.  I would like it to just not update.  Where should I perform this type of background task if not here?
I'll probably just catch the error, log it, and move on.  But it seems like a better approach would be to check for connectivity prior.
Answer: Have you tried to use Network plugin of MvvmCross?
IMvxReachability.IsHostReachable seems does the job
Comment: It's worth remembering that mvx is a community project ... So people can always contribute ... eg one droid reachability implementation is https://github.com/zleao/MvvmCross/commit/e39827639e126b6da22272e43e8f4a3a4fc871d0
Comment: That looks like just what I need.. so many different nuget packages.. is there one to check gps availability too?
Comment: hmm it appears this plugin doesn't work like the others.. IMvxReachability is unable to be resolved from ioc.. all other plugins it's worked
Comment: it seems that it works only in iOs

`#warning TODO - WINDOWS STORE SHOULD ADD IMvxReachability!
            // Mvx.RegisterType();`
`#warning TODO - DROID SHOULD ADD IMvxReachability!`


How to change proxy settings in Android (especially in Chrome)

Question: Could you please help me: is it possible to set proxy settings in Android (especially in Chrome)? I have to change IP on Android during the testing. Or there is some soft which can help me to solve this issue...
Answer: Found one solution for WIFI (works for Android 4.3, 4.4):

Connect to WIFI network (e.g. 'Alex')
Settings->WIFI
Long tap on connected network's name (e.g. on 'Alex')
Modify network config-> Show advanced options
Set proxy settings
Comment: This is solution not only for browser, but for all device's apps.
Comment: How can we do it programmatically
Comment: It is working for Wi-Fi. What in case of Mobile data? Please mention.
Comment: I tried this but only my webbrowser could connect internet while other apps couldn't. how to fix it
Comment: Is there any app tool to do this job more easily?
Comment: Helps to setup a ssh proxy first with sshtunnel then use localhost as the proxy address. No root access required either...
Comment: @maksim Alekseychik, When you do that, it says it will change your IP for only browsers, not for apps. Is there a way to change the IP that apps on the android work?
Comment: It is not working for 10.87.*.* local IPs in android chrome. I just want to bypass proxy server and directly connect to this 10.87.*.* IPs. working in native android browser not in chrome.
Comment: How do you set the proxy credentials?
Comment: It doesn't work for me, as I don't connect to a wifi network - I tether mobile data to via wifi to a PC and want the PC to be proxy for my phone :(
Comment: The global proxy setup on Android can be done via [ADB](https://gist.github.com/rwp0/a7d3f258ff0a50ef2bcdcd4a50485755) but there seem to be no native Android UI for it.


Can I safely mount a 150lb punching bag to the bottom chords of the trusses in my garage?

Question: I'd mount a 2x4 or 2x6 on the other side of the drywall perpendicular across the chords pictured and hang the punching bag to that. These chords span about 50-60 feet.
(Click image to enlarge)

If these chords aren't suitable for supporting this type of load, my plan is to fasten 2x4s to the studs in the garage directly beneath and run several 2x4 "joists" across the garage supported by them. I know my terminology isn't great, hopefully it still makes sense.
Thanks
Comment: It is the `150 pounds that moves that causes problems, swinging back and forth.
Comment: In the first picture are we looking down, and seeing the back of the garage ceiling and some flooring attached to the truss?
Comment: @jay613 Yes, exactly. This Picture is taken from the garage attic looking down at the exact spot that I propose mounting a 2x4 or 2x6 perpendicular.
Comment: I'm not sure the truss is meant to support any of that.  All the weight of the ceiling and floor and I think you, are supported by a couple of nails in the vertical member.  Definitely don't add anything.
Comment: Damn. That makes sense. Hopefully the storage area up there is safe. I've been walking up there a decent bit.
Answer: It's probably fine, but I'd install a beam (or beams) across the bottom chords of several trusses and pack down from that to the back of the drywall and bolt through the packing into the beam.
Comment: Sorry, I understand installing a beam across several cords and then bolting the mounting hardware through both the cord and the new beam, but I do not understand what I'm supposed to pack? Thank you for the reply.
Comment: fill the gap between the drywall and the beam with wood in the location where you want to install the eye bolt to hold the punchbag.


How much does driver quality affect Vulkan and DX12 compared to OpenGL and DX11?

Question: Considering the fact that Vulkan and DX12 delegate most of the memory management / work scheduling tasks to the application itself, how much do drivers affect performance?
To put my question into context, people on the internet talk a lot about NVIDIA drivers being more finely tuned and optimized (especially for the most popular games) compared to AMD drivers. Now that DX12/Vulkan are becoming more common, is it safe to assume that AMD video cards will become more competitive even if they have less optimized drivers?
Answer: TL;DR:  There's some room for optimization in Vulkan drivers, but not nearly to the degree that there is in GL / DX11 drivers.

how much do drivers affect performance?

It depends a great deal on how the application is written and the hardware.  Specifically it depends on whether you're using features where there are large opportunities for optimization on the driver side.
For example, if an application is written to take full advantage of renderpass subpasses and properly specifies the subpass dependencies and properly sets up transient attachments for intermediate work, then the difference between an extremely naive Vulkan driver and a well written one could easily be an order of magnitude.  But at the same time, this is basically the difference between naive client code and well written code both running on a well written driver.

people on the internet talk a lot about NVIDIA drivers being more finely tuned and optimized (especially for the most popular games)

This isn't just a matter of driver tuning.  It's arguably a form of cheating.  It's pretty well known that in the case of certain AAA games, nVidia will actually swap out functionality from the game with baked functionality from it's own drivers, doing things like swapping out shaders that were bundled in the game with their own customized shaders, or toggling internal flags that conventional developers have no access to.
The problem is that DX11 and GL are both very old APIs with lots of legacy functionality.  Their very design in some places is at odds with modern GPU hardware, especially in the area of bundling individual commands together before actually sending them to be executed.  This is why all modern APIs like Metal, Vulkan and DX12 have the concept of a command buffer or batch.  So that the developer can actually be involved in the process of bundling lots of small bind and draw commands together in a logical way.  Older API's like OpenGL have to guess at where the command buffer boundaries should be and (one assumes) drivers tend to have a variety of strategies for doing this depending on how the client application is calling functions.
This is where the driver level optimizations come in, where nVidia or AMD can look at how a given game is calling functions and decide that strategy A is better than the strategy B (the one that driver version X is using), and so they release driver X + 1, and it forces the use of strategy A, or even a new strategy C that they came up with for this specific game.
The end result is that OpenGL (and I assume DX < 12) drivers end up being monstrously complex, not just because of the enormous amount of legacy functionality they have to support, but also because of this per-game baggage that they accumulate (although I suspect that such per-game baggage has some kind of finite lifetime.... no one is going to be benchmarking a RTX 2080 with Battlefield 1942).


How to test for people in a radius not centered on command block?

Question: Is it possible to use the testfor command in Minecraft to test for people in a radius not centered on the command block?
Answer: You can use testfor @p[r=5,x=1,y=65,z=89]
If you use then in front you can leave the x, y, z and r out
testfor @p[5,65,89,5]


JavaScriptSerializer.Deserialize does not accept a date that was serialized by JavaScriptSerializer.Serialize

Question: How can I find the source of this problem, where a date value serialized by
JavaScriptSerializer cannot be deserialized by the JavaScriptSerializer?
In the calling application:
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(model);

// generates this json
{'Guid':'guid','OrderNumber':'1','OrderDate':'\/Date(1299456000000)\/',
   'OrderStatus':'Completed','DiscountRate':0.0000}

In the receiving application:
string json = @"{'Guid':'guid','OrderNumber':'1','OrderDate':'\/Date(1299456000000)\/',
                 'OrderStatus':'Completed','DiscountRate':0.0000}";
var serializer = new JavaScriptSerializer();
var model = serializer.Deserialize(json);

Throws a String was not recognized as a valid DateTime exception.
If a date is serialized by JavaScriptSerializer then why can it not be deserialized by JavaScriptSerializer?
Comment: I read that and lots of other questions but still don't understand why .NET can't deserialize something that was serialized by .NET? And I'm still unsure what I need to do.  The client app is not mine, so I cant always tell them to change how they serialize it.
Comment: Have you seen this related question: http://stackoverflow.com/questions/1224793/javascript-serialization-of-datetime-in-asp-net-is-not-giving-a-javascript-date?
Comment: Try using `System.Runtime.Serialization.Json.DataContractJsonSerializer` instead. I just tried it and it didn't have any problems serializing and deserializing dates.
Answer: If model is of type Model then try specifying the type in the call to Deserialize.
string json = @"{'Guid':'guid','OrderNumber':'1','OrderDate':'\/Date(1299456000000)\/',
             'OrderStatus':'Completed','DiscountRate':0.0000}";
var serializer = new JavaScriptSerializer();
var model = serializer.Deserialize<Model>(json);

I'm able to serialize and deserialize dates with no errors this way.


Add customview in navigation bar like whatsapp

Question: I want to create custom navigation bar like WhatsApp uses to display call indicator in the application as given below.

I have successfully added view like above but it's not responsive because I am not able to detect touch on status bar. I can touch only part below "Touch to return to call".
Code is as given below.
@property (nonatomic) UIView *navigationBarTopView;

UIWindow *window = [UIApplication sharedApplication].keyWindow;
if (_navigationBarTopView == nil) {
    _navigationBarTopView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, window.frame.size.width, 60.0)];
        [_navigationBarTopView setBackgroundColor:[UIColor colorWithRed:76.0/255.0 green:217.0/255.0 blue:100.0/255.0 alpha:1]];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, _navigationBarTopView.frame.size.height - 15, window.frame.size.width, 10)];
    [label setText:@"Touch to return to call"];
    [label setTextColor:[UIColor whiteColor]];
    [label setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]];
    [label setTextAlignment:NSTextAlignmentCenter];
    [_navigationBarTopView addSubview:label];

    //The setup code (in viewDidLoad in your view controller)
    UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [_navigationBarTopView addGestureRecognizer:singleFingerTap];

    UITapGestureRecognizer *singleFingerTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [label addGestureRecognizer:singleFingerTap1];
}

[window addSubview:_navigationBarTopView];

I have also tried to add touch on status bar as give below but it doesn't work.
How do I detect touches on UIStatusBar/iPhone
Also navigation bar is not coming downside. I have tried to set keyWindow frame. But that is also not working.
Comment: Are you sure this is not system `call bar`?
Comment: try this `[self.navigationController.view addSubview: _navigationBarTopView];`
Comment: It is a system generated navigation bar. It appears automatically while connected a call with anyone. The call can be normal or VoIP(Manage by SDK). You can add a custom view to the navigation bar if required.
Comment: its the default behaviour provided by apple, if you want to create the same like  add subview to  navigationController.view on your top viewcontroller
Comment: @iMHiteshSurani I am not getting it into the application. I have implemented Twilio Voice SDK for the same. So I have created custom view and added it as a  UIWindow on top of the screen.
Comment: @ManWithBear Yes this is not a system call bar, I have added a custom view.
Comment: @Anbu.Karthik Even I want default one but not sure why it's not appearing.
Comment: Twilio voice SDK do not have this type of feature. I am sure about voice call but no idea with a video call. You can go with a @Anbu.Karthik solution but it is very tricky and difficult to manage for all device. By using below solution you cannot achieve output like WhatsApp so be careful and happy coding.
Answer: UIStatusBar has higher priority than your application's window, so you won't get any touch event through status bar.
To get touch event through status bar you need a window with higher window level than UIStatusBar.
Try below code:
#import "AppDelegate.h"

@interface AppDelegate ()

@property (nonatomic) UIWindow *buttonWindow;
@property (nonatomic) UIWindow *textWindow;
@property (nonatomic) CGFloat callViewHeight;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
        if (@available(iOS 11.0, *)) {
        if (([[[UIApplication sharedApplication] delegate] window].safeAreaInsets.top > 20.0)) {
            self.callViewHeight = 55.0f;
        } else {
            self.callViewHeight = 35.0f;
        }
    } else {
        self.callViewHeight = 35.0f;
    }
    return YES;
}

-(void)showVideoCallButton{
    self.textWindow = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.callViewHeight)];
    self.textWindow.windowLevel = self.window.windowLevel + 1;
    self.textWindow.hidden = FALSE;

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.callViewHeight)];
    view.backgroundColor = [UIColor colorWithRed:76.0/255.0 green:217.0/255.0 blue:100.0/255.0 alpha:1];
    view.clipsToBounds = TRUE;
    UILabel *lblName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.callViewHeight)];
    lblName.textAlignment = NSTextAlignmentCenter;
    [lblName setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]];
    lblName.text = @"";

    UILabel *lblTouch = [[UILabel alloc] initWithFrame:CGRectMake(0, self.callViewHeight - 20.0f, [UIScreen mainScreen].bounds.size.width, 20.0f)];
    lblTouch.textAlignment = NSTextAlignmentCenter;
    [lblTouch setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]];
    lblTouch.text = @"Touch to return to call";
    lblTouch.textColor = UIColor.whiteColor;

    [view addSubview:lblTouch];
    [view addSubview:lblName];

    [self.textWindow addSubview:view];

    self.buttonWindow = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.callViewHeight)];
    self.buttonWindow.windowLevel = UIWindowLevelStatusBar + 1;
    self.buttonWindow.hidden = FALSE;

    UIButton *button = [[UIButton alloc] initWithFrame:lblName.bounds];
    [button setTitle:@"" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonTouched) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonWindow addSubview:button];

    self.textWindow.transform = CGAffineTransformMakeTranslation(0, -self.callViewHeight);
    self.buttonWindow.transform = CGAffineTransformMakeTranslation(0, -self.callViewHeight);

    [UIView animateWithDuration:0.25
                     animations:^{
                         self.textWindow.transform = CGAffineTransformIdentity;
                         self.buttonWindow.transform = CGAffineTransformIdentity;
                         if (@available(iOS 11.0, *)) {
                             if (([[[UIApplication sharedApplication] delegate] window].safeAreaInsets.top > 20.0)) {
                                 self.window.frame = CGRectMake(0, self.callViewHeight - 40.0f, self.window.bounds.size.width, self.window.bounds.size.height - self.callViewHeight + 40.0f);
                             } else {
                                 self.window.frame = CGRectMake(0, self.callViewHeight - 20.0f, self.window.bounds.size.width, self.window.bounds.size.height - self.callViewHeight + 20.0f);
                             }
                         } else {
                             self.window.frame = CGRectMake(0, self.callViewHeight - 20.0f, self.window.bounds.size.width, self.window.bounds.size.height - self.callViewHeight + 20.0f);
                         }
                     }];
}

-(void)hideVideoCallButton{

    [UIView animateWithDuration:0.25
                     animations:^{
                         self.textWindow.transform = CGAffineTransformMakeTranslation(0, -self.callViewHeight);
                         self.buttonWindow.transform = CGAffineTransformMakeTranslation(0, -self.callViewHeight);
                         self.window.frame = [UIScreen mainScreen].bounds;
                     } completion:^(BOOL finished) {

                         dispatch_async(dispatch_get_main_queue(), ^{
                             self.buttonWindow.hidden = TRUE;
                             self.buttonWindow = nil;

                             self.textWindow.hidden = TRUE;
                             self.textWindow = nil;
                         });

                     }];
}

-(void)buttonTouched{
    NSLog(@"Button Touched");
}

@end

Comment: Thanks @iDhaval this solution worked. I have made some changes to make it compatible with iPhone X+ devices.
Comment: hello, is there any solution for swift?
Comment: @iDhaval, i tried it and it doesnt work in xcode 11.6
Comment: @swift2geek what issue you are facing?
Answer: I tried in singleViewcontroller and UITabbar Controller also, the sample project I attached here, for status bar Tap action I followed Flar answer
 - (void)viewDidLoad {
[super viewDidLoad];

dispatch_async(dispatch_get_main_queue(), ^(void){
    //Run UI Updates
     [self createDummyView];
});

}

 -(void)createDummyView{

if (_navigationBarTopView == nil) {
     float statusBarHeight = [self statusBarHeight];
    CGFloat width = [UIScreen mainScreen].bounds.size.width;

    _navigationBarTopView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, self.navigationController.navigationBar.frame.size.height +  statusBarHeight)];
    [_navigationBarTopView setBackgroundColor:[UIColor colorWithRed:76.0/255.0 green:217.0/255.0 blue:100.0/255.0 alpha:1]];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, _navigationBarTopView.frame.size.height - 15,width, 10)];
    [label setText:@"Touch to return to call"];
    [label setTextColor:[UIColor whiteColor]];
    [label setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setUserInteractionEnabled:YES];
    [_navigationBarTopView addSubview:label];

    UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [_navigationBarTopView addGestureRecognizer:singleFingerTap];

    [self.navigationController.view addSubview:_navigationBarTopView];

}

-(float) statusBarHeight
{
CGSize statusBarSize = [[UIApplication sharedApplication] statusBarFrame].size;
return MIN(statusBarSize.width, statusBarSize.height);
}

-(void)handleSingleTap:(UITapGestureRecognizer*)recognizer{
NSLog(@"recognizer == %@", recognizer.view.tag);
}

Comment: @Anbu.Karthik I have already implemented this code but using that code I am not able to get touch on status bar. Also I have complex structure which consist a tabbar and which consist 4 navigation bar controllers. So It's very difficult to manage in the application.
Comment: FYI: The device with safe-area available calling functionality does not work like non-safe-area device. It will display a small calling icon in the status bar
Comment: To have touch event on status bar I am using this solution. But it doesn't work on tab bar. https://stackoverflow.com/questions/2470562/how-do-i-detect-touches-on-uistatusbar-iphone It works well with single view controller.
Comment: Please use this library for the same. I know, maybe some customization required but it will easy to use and ratings are good.  https://github.com/huri000/SwiftEntryKit
Comment: @JayeshSojitra - I updated the answer , it works fine for single view controller and UITabbar controller also, please check
Comment: @JayeshSojitra - I have complex structure which consist a tabbar and which consist 4 navigation bar controllers. So It's very difficult to manage in the application : use extension ,
Comment: @HiteshSurani this is different. Your lib is more like notifications, but the question here is about more like a system bar, which moves down from the top and pushes all content below.


can I put this cable inside the wall to hide it

Question: Theres this cable popping out of my wall and it looks ugly, i bought a cover and was wondering if it should be ok to just push this cable inside the wall and close it with the cover
Comment: If the box is covered, why would it matter if the cable is pushed inside the wall or not?
Comment: Fernanda Ribeiro, Tip, consider trimming the coax and center conductor so they do not touch.
Answer: Yes, you can cover that box with a cover without any issues, and paint it to match the wall if you so desire.  Regardless of what type of wire it is, code permits this.
If you wanted to actually remove the box and permanently cover the hole, you'd want to be more certain about what the wire is and where it comes from.  It appears to be coax, which could connect anywhere in the house, or could connect to an old antenna (TV or radio), or a variety of other places.


Some questions regarding Xbox Live Service

Question: I recently bought Xbox 360 with Kinect in US and brought it to India and I haven't yet created a Xbox Live account. I have some questions regarding how Xbox Live will work with regards to the different countries I purchased and am using my Xbox in.

Since my Xbox was bought in US do I need to create Xbox Live account with my country as the US? Or do I create an account with my country as India? India has the Xbox Live Arcade but I am not sure if the content is the same. Pros and cons of both approaches?
Will games bought in India work? Or do I need to buy them from the US?
Any other issues that I might face? Or any suggestions I should follow?
Answer: You can create your X-Box account for any country, however you can only change countries once every 12 months. This can be done via the X-Box live website. You have to however copy all your downloaded content to a backup USB since you can't re-download these. Also the country on your Live account and the X-Box account must match, otherwise it will create some havoc. To access the change your region options on X-Box live look for the following on your account:

Unfortunately I am getting the following screen since I recently did this, however you will get the option to choose a country:

Gamercards can only redeemed for the country they are bought for, as they are linked to the Live store for each country.
The only reason I can imagine your games won't work bought in India, is if they are not PAL/NTSC compatible depending on what you use. South Africans for a long time bought Australian and UK X-Boxes and bought games locally and they worked fine.
Comment: @Andy. It's a fairly new service, and I know they said they will be adding more countries. As with everything XBox related it will just be a case of time. I couldn't confirm countries myself since I already did a switch from a UK account.
Comment: i finally checked it out today and your info is only partly true. You can only change to one of the following countries: Rusia, Poland, Brazil, Hungary, greece, Tsjechië, South Africa, Colombia en Chili. (i translate dthese countries from dutch hope i spelled it right.) So you cant change it to the uk (my case) or to india (In his case if he makes a usa account.)
Comment: Well, i hope my attempted translations are any help to people trying to decide. Still, after all these years it is a step in the right direction. but forfeiting the ability to redownload all the things i bought is a steep price. I'd say thinking carefully about your country for xboxlive is important since i doubt they will remove that consequence.
Comment: @Andy. Backing it up to a USB devices solves the problem. If you ever need to replace the XBox completely, just copy it from the USB. I recently switched from the original XBox to the new Slim and it worked fine. Incidentally it was around the same time I realised I could change countries.
Answer: Be carefull, if you register your xboxlive in the usa you need to buy your gold cards in the usa. gold cards from india will not work.
luckly america is a big country so you could buy your gold cards on ebay, but be aware that me moving from Belgium to the UK means i have to travel back to belgium or let someone buy an xboxlive card in belgium.
On the same note, i need a belgian bank card to buy anything for xboxlive, i can't use a UK one since thats not my home country.
At this time it is only possible to change to certain countries, and usa, uk nor India are some of them.
I know that certain content is Region limited, however, they are checking the country you are in with ip as well, cause i know a french guy that had to use a proxy to avoid that.
Last warning about games on demand on xbox live, i am not sure how india is in official languages and so, but i downloaded CoC: WaW from xbox live, with an english description and interface, however, once downloaded, the game was in french. be carefull about it all
Comment: Actually your wrong. Your allowed to change your country on your Xbox Live account once every 12 months and keep all your content etc, however you can't re-download content from another region once you've done the change. I just did this recently when they finally launched XBLA in South Africa, to change from a UK account. You can do this through the Xbox live website on your account. You keep all gamer points you've gained etc.
Comment: I have just bought the Xbox so i really don't have any achievements to worry about. So you are saying that i can create a account here in India , I can use it with my US bought XBox?
Comment: yes, the country you buy the xbox i is unrelated to the country of your live account. You will need an email to create an xboxlive account and it will default it to the country of email when signing up but this can be changed before the signup is complete.
Comment: @Diago: That would be great news. and relativly new. i will check on this as soon as i can.


Export an angular element as module

Question: I have created a widget using Angular element successfully, which is working fine in HTML.
But how do I export it as a module so that it can be used in another Angular, React, Vue web applications as well to import import { acmaModule } from package-name instead const acmaModule = require('widge.js')
Angular
export class AppModule {
  initWidget(options: any){
    console.log('options received', options)
  }

  constructor(private injector: Injector) {
    // Expose Window function
    (<any>window).acmeWidget = { initWidget: this.initWidget  };

     // Survey Widget
    const surveyComp: any = createCustomElement(SurveyComponent, { injector: this.injector });
    customElements.define('acme-survey', surveyComp);
  }

  ngDoBootstrap() {}
}

HTML

....

....

Comment: I would go for generating a web component if I were you :)
https://blog.kalvad.com/export-your-angular-component-as-a-web-component/
Answer: You can create an export file and declare the exporting for all modules you want to package for external references in there.
For example, you can add a file export.ts to the src folder and then add something like this to the content of the file, assuming your AppModule is under src\AppModule.ts:
//content of export.ts
export * from './AppModule';
...

then in your ng-package.json file, you need to declare export.ts as entry file there. Something like:
//content of ng-package.json
{
  "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
  "dest": "../../dist/<your built package name>",
  "lib": {
    "entryFile": "src/export.ts"
  }
}

then after you build your project, you can run npm publish to create the artifact that you can install through npm and import later. Assuming your project's name is test-project, it will be something like:
ng build test-project --prod

# after build is done:
cd dist/test-project
npm publish

see references for npm publish
Comment: By using the ng-packager, that will generate an angular library, and that one cannot be used directly in react/vue, for this one you could use webpack 5 module federation feature.
Comment: I will test this and update you

Export an angular element as module


executing a python code located in a subfolder

Question: I have a directory called NHOME. In this directory there is a folder named subFolder. It's like this:
/NHOME/subFolder

In NHOME directory I'm executing a bash script which intends to execute a python code located in subFolder. I have problem doing this. I tried something like this:
./subFolder/file.py

but it didn't work. Is this possible?
Comment: Have you tried `python ./subFolder/file.py`?
Comment: Yes, I got this error: ImportError: No module named parse, while it works when I  execute it inside subFolder.
Answer: Use pwd to get the script's location instead of the relative ./
pythonScript="$PWD/subFolder/file.py"

To run:
#!/bin/bash
"$PWD"/subFolder/file.py

Note: The " around $PWD are needed if the path contains spaces ()
Comment: The working directory is available in the variable `PWD`. This gives the directory where the script itself is stored, which may or may  not be the same as the working directory.
Comment: `$PWD` is more efficient than `$(pwd)` -- the former is just a variable lookup inside the shell instance that's already running, the latter forks off a child process and reads its stdout.
Comment: How should I run this inside the script now? `PWD/subFolder/file.py`? The python code is not supposed to return anything.
Comment: The `$` is not optional. Anyhow, `"$PWD"/subFolder/file.py` will work if this answer is correct (and Python does module lookups relative to a source file given as an absolute path).
Comment: @0stone0, not `${pwd}`, `$PWD`. The variable is all-caps, which puts it in the namespace POSIX reserves for use of the shell and other POSIX-defined tools, whereas other names are guaranteed not to have unintended conflicts on the behavior of standard-defined tools when used by applications for their own purposes. See https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
Comment: Yea, caps for sure, but the `{}` don't matter right?
Comment: Correct, the curly braces don't matter at all in this case; you're not trying to parameterize the expansion, and the character immediately after it isn't valid in a name itself.
Comment: @0stone0, ...that said, I'm curious -- is there a difference in Python module loading behavior between the two cases that leads you to suggest that this answer will make a difference?
Comment: Not `$PWD/someFolder/file.py` but `"$PWD"/someFolder/file.py` -- if you don't have the quotes it'll fail when your directory name has spaces.
Comment: Nah, just included it for readability, but it's probably just a bad habit.


How can I disable plugin version compatibility checking in Eclipse?

Question: When I try to install Eclipse plugins, I often get an error with details like:

An error occurred while collecting
  items to be installed   No repository
  found containing:
  org.eclipse.equinox.concurrent/osgi.bundle/1.0.0.v20090520-1800

This is clearly a bug in Eclipse. The bundle I'm installing doesn't need any special version of anything, it's just a profiler plugin that works in literally any build of Eclipse 3.4. Refusing to install my plugin is not an acceptable course of action. Eclipse should stop showing this message and install the plugin.
I'm not sure exactly what error the Eclipse developers made, but I can see that the version compatibility checker is absolutely strict, and it should not be. Either it is incorrectly evaluating the required bundles, and failing as a result of its own blunder, or the version requirements of the bundles are loosely defined in a way that the version checker does not really understand.
So, is there a way to simply disable this version checker? The thing is crippling my Eclipse install. Frankly, Eclipse would be better if the thing were completely deleted from the application. We only need it to choose the correct version of existing plugins for binding OSGi services. We don't need our development tools to kibitz about whether a plugin seems proper.
Thanks in advance for any suggestions.
Byron
Answer: As mentioned in the wiki

The message indicates that the Eclipse provisioning system P2 has found meta data to install a plug-in but can not locate an artifact repository that provides the required downloads

It is suggested to remove update sites and re-add the same update sites, to trigger a refresh, but in your case, it is not your plugin update site which is involved.
There is indeed a bug (236437) with Eclipse 3.4 about "Lost artifact repositories". It has been solved in Eclipse3.5, but if you cannot use that version, there may be a workaround:

1) export the update site listing to bookmarks.xml file (Software Updates->Manage Sites->Export)
    2) stop eclipse
    3) remove configuration/.settings/org.eclipse.equinox.p2.*.prefs files
    4) start eclipse
    5) import the bookmarks.xml file (Software Updates->Manage sites->Import) that was exported in step 1

Comment #59 helped me fix my updating problem, thanks!
Though, I think maybe it was enough to just delete the configuration/.settings/org.eclipse.equinox.p2.*.prefs files as I have a feeling that the problem was already resolved before I imported the bookmarks file (things happened a bit in parallel for me here).

Note for Eclipse3.5 users:

I am seeing this in 3.5.1 when trying to install stuff from an old style update
  site when I include site.xml:

http://www.perforce.com/downloads/http/p4-wsad/install/site.xml

If I remove site.xml I can install things fine.


Combine two different Selects into same result table in my procedure?

Question: I'm trying to write a procedure with two selects. Is there any way to combine two selects into same result table?
Right now I get results in two different tables.

Here's my procedure
ALTER PROCEDURE [dbo].[GetMachineStatus] (@MachineID int) as
begin
    set nocount on
    declare @Availabilitytime datetime, @TimeNow datetime, @queryMachineStatus nvarchar(250)

    select
          @Availabilitytime =
                (select AvailabilityTime from machines where MachineID = @MachineID)
        , @TimeNow = getDate()
        , @queryMachineStatus = N'select avg(effectively) As Availability, (MAX(Counter)-MIN(counter)) As Counter from '
                + quoteName(convert(nvarchar, @MachineID))
                + N' where [time] between '
                + quoteName(convert(nvarchar, @Availabilitytime, 120), nchar(39))
                + N' and '
                + quoteName(convert(nvarchar, @TimeNow, 120), nchar(39))
                + N'select top (1) effectively as effectively from'
                + quoteName(convert(nvarchar, @MachineID))
                + N' Order by time DESC'

    execute sp_executesql @queryMachineStatus

End

Comment: TIP: If you are going to use `convert(nvarchar` you should always specify the length, else you get the default length (30).
Answer: Assuming you want wanting to add an additional column, and assuming your first result is only ever one row, then a simple sub-query should do the job e.g.
set @queryMachineStatus = N'select avg(effectively) as Availability, (MAX(Counter)-MIN(counter)) as Counter'

+ N', (select top (1) effectively as effectively from'
+ quotename(convert(nvarchar(30), @MachineID))
+ N' Order by time DESC) as Effectively'

+ ' from '
+ quotename(convert(nvarchar(30), @MachineID))
+ N' where [time] between '
+ quotename(convert(nvarchar(30), @Availabilitytime, 120), nchar(39))
+ N' and '
+ quotename(convert(nvarchar(30), @TimeNow, 120), nchar(39));

Comment: Thank you Dale it works, it seems so easy when you know how to do..
Comment: @OscarLarsson certainly doing it as dynamic SQL is more complex... its easier to solve the problem in static SQL and then convert it.


Matching values in a column of one data frame with subsets of a column in another data frame

Question: I am trying to match the values in a column of one data frame with the values in a column of a second data frame. The tricky part is that I would like to do the matching using subsets of the second data frame (designated by a distinct column in the second data frame from the one that is being matched). This is different from the commonly posted problem of trying to subset based on matching between data frames.
My problem is the opposite - I want to match data frames based on subsets. To be specific, I would like to match subsets of the column in the second data frame with the entire column of the first data frame, and then create new columns in the first data frame that show whether or not a match has been made for each subset.
These subsets can have varying number of rows. Using the two dummy data frames below...
DF1 <- data.frame(number=1:10)

DF2 <- data.frame(category = rep(c("A","B","C"), c(5,7,3)),
                  number = sample(10, size=15, replace=T))

...the objective would be to create three new columns (DF1$A, DF1$B, and DF$C) that show whether the values in DF1$number match with the values in DF2$number for each of the respective subsets of DF2$category. Ideally the rows in these new columns would show a '1' if a match has been made and a '0' if a match has not. With the dummy data below I would end up with DF1 having 4 columns (DF1$number, DF1$A, DF1$B, and DF$C) of 10 rows each.
Note that in my actual second data frame I have a huge number of categories, so I don't want to have to type them out individually for whatever operation is needed to accomplish this objective. I hope that makes sense! Sorry if I'm missing something obvious and thanks very much for any help you might be able to provide.
Answer: This should work:
sapply(split(DF2$number, DF2$category), function(x) DF1$number %in% x + 0)

      A B C
 [1,] 0 0 1
 [2,] 1 1 0
 [3,] 1 1 1
 [4,] 0 1 0
 [5,] 0 0 1
 [6,] 0 1 0
 [7,] 1 1 0
 [8,] 1 0 0
 [9,] 1 0 0
[10,] 0 1 0

You can add this back to DF1 like:
data.frame(
   DF1,
   sapply(split(DF2$number, DF2$category), function(x) DF1$number %in% x + 0)
          )

   number A B C
1       1 0 0 1
2       2 1 1 0
3       3 1 1 1
4       4 0 1 0
5       5 0 0 1
6       6 0 1 0
7       7 1 1 0
8       8 1 0 0
9       9 1 0 0
10     10 0 1 0

Comment: Yes, that works perfectly. Thanks very much! Thanks also to Andy for the edit to improve the clarity of my original post.
Comment: @user2093526 - no problems, glad to help - if this answers the question please tick the "tick mark" next to the up/down vote arrows to signal this.
Comment: Can use _tapply_ instead, `tapply(DF2$number, DF2$category, function(x) DF1$number %in% x+0)`


What is the "Mint-Effect"?

Question: The tooltip of the Mint says

0,007 mintEffect

But what does that mean?
Answer: Per Brilliand's answer in this question, Mints give a certain amount of furs and ivory per tick in exchange for a cost in gold and catpower.
The reason it doesn't just say "x.xx furs per second" or something like that is because the amount of furs and ivory gained is based on your maximum catpower, rather than being a particular amount.  Thus, you get a certain amount of "mintEffect" which then translates through your maximum catpower and becomes ivory and furs.  The linked question includes the exact amounts (and the points that mints become a more effective use of catpower than manual hunting, although you'll likely still be best served doing both).

What is the "Mint-Effect"?


How do I run the system commands in JavaScript?

Question: I need to list all the files in the JavaScript thingy, such as using "ls".
Comment: You are talking about executing commands server-side, correct? Not on the client browser?
Answer: Unprivileged JavaScript in a browser can neither list files nor execute programs for security reasons.
In Node.js, for example, executing programs works like this:
var spawn = require('child_process').spawn,
var ls  = spawn('ls', ['-l']);
ls.stdout.on('data', function (data) {
   console.log(data);
});

And there is a direct way to list files using readdir().
Comment: I suppose this is going to run on a server. What about pure JavaScript to run on the client? Just for security testing.
Answer: You can't run system commands on the client with JavaScript since it works inside a browser sandbox. You'd need to use some other client-side tech like Flash, ActiveX or maybe applets.
Comment: I think Applets also run in a sandbox.
Answer: An even easier way in node.js is:
var fs = require('fs');
var ls = fs.readdirSync('/usr');

The variable ls now contains an array with the filenames at /usr.
Answer: AFAIK, you can not run any system command. This will violate the security model. You can do send a print command, but I wonder anything beyond that is possible.
Comment: Is that an heresy to say that if someone can access the stdout then somehow other system calls also could be invoked after passing some security barrier?
Answer: The short answer is: you should not do this as it opens a huge attack vector against your application. Imagine someone running "rm -rf" :).
If you must do this and you are 1000% sure you allow only a few commands which cannot cause any harm you can call a server page using Ajax. That page could run the specified command and return response. Again I emphasize this is a huge security risk and should better not be done.
Comment: Related conversation: http://stackoverflow.com/questions/41088671/asp-net-c-sharp-mvc-website-how-can-i-mount-a-drive-upon-button-click
Answer: If you'd like the program you run give out output that uses ANSI escape sequences (for example, to print out the progress percentage on the screen):
I wasn't able to do that on macOS unless I use the following (I am using macOS v13 (Ventura)):
const { spawn } = require("node:child_process");

const commandProcess = spawn(
  "node",
  ["someScript.js", "someArg1", "someArg2"],
  {
    stdio: "inherit"
  }
);

This will show all the standard output, standard error, etc., on screen, as if it is a command typed into a shell.  This is the documentation.


How can I mass cage quickly?

Question: When I have unpastured animals and I mass assign them to a pasture, there is a massive flurry of activity and the fortress goes into "pasture all the animals" mode. However when I do the same thing but mass assign animals to a cage, only random dwarves will perform the job and seemingly only randomly.
Is there a particular labour that needs to be activated? If so what?
Or alternatively how can I mass cage quickly?
Answer: I believe this is due to the cage generating only a single animal hauling job at a time. While pastures can create multiple animal hauling jobs at once (one for each square in the pasture?), cages will only create a new job, for a different animal, after the previous job has been completed.
If getting all your animals in different cages is not a problem, you can split your animals in small groups and bring each to a different cage. Since each cage will be handling the hauling jobs separately, it becomes possible to have multiple dwarves caging your animals at the same time.
Comment: So to cage faster I need more cages, and allocate less animals to each cage.
Comment: Well, unless you want all animals in the same cage. I thought that was your intention.
Comment: I just want them caged, they can be in multiple cages. When I have a clutch of chicks/poults I cage them to stop the FPS dying. They grow up in the cages and then I slaughter all the old chickens/turkeys plus most of the new birds. Then I pasture the remainder to breed and lay eggs.

How can I mass cage quickly?


Http 401 along with Http 500 in blackberry app development

Question: I am developing a Blackberry Application With Oauth Webservice.
While I am sending a GET request, I am getting HTTP 401 status code first
although i am sending authorization header properly.When i am invoking same webservice
again its giving HTTP 500 error.
I am confused to, to trace the error, whether Its from client side or server error.
I am running MDS simulator too.
Please help me regarding this.
Here us my code snippet:
<code>private HttpConnection HttpRequestCreate(boolean post) throws IOException,MalformedURIException,PINException, net.rim.device.api.crypto.InvalidKeyException,UnsupportedEncodingException,net.rim.device.api.crypto.NoSuchAlgorithmException ,IllegalStateException,NullPointerException,IllegalArgumentException, CryptoTokenException, CryptoUnsupportedOperationException
{
String Authhdr=null;

uthScheme authScheme = new AuthScheme.Builder(HTTPVerb,URI,Date,Keys)
.setContentMD5(ContentMD5)
.setContentType(ContentType)
.build();

Authhdr = authScheme.getAuthorizedHeader();

if(Authhdr ==null)
    throw new NullPointerException("Authorization header cannot be null.Please check whether authorization header is properly generated or not.");
HttpConnection ConnectionHandle = null;
ConnectionHandle=(javax.microedition.io.HttpConnection)
Connector.open(URI, Connector.READ_WRITE, true);
ConnectionHandle.setRequestMethod(HTTPVerb);
ConnectionHandle.setRequestProperty("Date",Date);
ConnectionHandle.setRequestProperty("Host",Host);
ConnectionHandle.setRequestProperty("Authorization", Authhdr);
if(ContentLength!=null)
    ConnectionHandle.setRequestProperty("Content-Length",ContentLength);

if(ContentMD5!=null)
    ConnectionHandle.setRequestProperty("Content-MD5",ContentMD5);

if(ContentType!=null)
    ConnectionHandle.setRequestProperty("Content-Type",ContentType);

return ConnectionHandle;
}
</code>
thanks...
Answer: This could help you
401 Error on Blackberry Device
or there may be TLS 1.2 issue. Because apparently bb has some issue with non TLS 1.0 connections


Take same value from table for different variables

Question: I'm working with Teradata and SQL and have a problem.
I have an order number, where I can have two different payers, one for  shipping, and one for the product and tax.
I want, from the order number, find the account numbers for the payers and the names for the payers.
The Order numbers and account numbers can be found in one table and then the names and account numbers can be found in another table.
Right now I have this;
Sellect a.order_num,
a.account_ship,
a.account_tax ||' ('||b.account_name||')' as Tax_account_name

from order a
inner join account b
on a.account_tax = b.account_number
where a.order_num in ('1');

I want to be able to show the account name for the shipping account in the same way as the tax account.
Anyone having any idea?
Sorry if the question is a but confusing...
Thanks,
Answer: You need another join to the accounts table for the shipment account number:
Select o.order_num,
   o.account_ship,
   o.account_tax ||' ('||tax.account_name||')' as Tax_account_name
   o.account_ship ||' ('||ship.account_name||')' as Shipment_account_name
from order as o
join account as tax  -- tax account
  on o.account_tax = tax.account_number
join account as ship -- shipment account
  on o.account_ship = ship.account_number
where o.order_num in ('1');

Comment: Works perfect! Thanks!


best file to use for configuration with a multiline support

Question: I am having a java program which is configurable by .properties file.
But one of the config key , I need a multi line value.
For eg:
<code>#proerties file start
key1=value1
desc=a long long line /
next line/
and again next line with a very long desc
/(need to give some new line)
/
something else
from path D://myfile.txt
</code>
Now as you can see this is very tiresome and user needs to be educated about escaping.
So I want to know is there any better and elegant way to solve this?
Answer: Yes java properties must escape multiline text as:
<code># The following is a multi-line description.
desc=Mi ne scias,\
    chu chi tio funkcias, chu ne.\
    Chu vi havas ideon?
</code>
Furthermore special characters may need to be u-escaped.
But there are some properties editors around. Too many to just name one. Search for one with multiline capabilities, u-escaping special characters, handling comments, and maybe providing good i18n support (different languages side-by-side).
Comment: I prefer the properties editor in the NetBeans IDE, with either Open or Edit. In one case you get side by side editing. You can add a locale (language). With others I would not have much experience without trying them out. Sorry.


Select Table A minus Table B where condition consists of two columns

Question: I have two tables. Table A and table B.
I would like to select everything from table A which is NOT in table B.
Sounds easy the catch is I need to select it based on two values (two columns)
revision AND casetype. Something like this.
select a.revision, a.casetype from A a
minus
select b.revision, b.casetype from B b;

The problem is I won't get back ID from table A.
Is it possible to select whole table A minus table B where conditions consist of two columns ? I would like to stick to SQL (no PL/SQL)
I also tried to write something like query below but I guess I can't do it since I need to check revision AND casetype altogether
select * from A a where a.casetype IN (select...) and a.revision IN (select...)

Any idea how to work around ? Thanks
Answer: Sure, I believe a basic not exists check should work.
select a.id, a.revision, a.casetype
from A a
where not exists (
    select 1
    from B
    where revision = a.revision and casetype = a.casetype
);

Answer: Oracle supports tuples, so if you wanted you could do:
select a.*
from a
where (a.revision, a.casetype) in (select a.revision, a.casetype from A a
                                   minus
                                   select b.revision, b.casetype from B b
                                  );

I would normally go for not exists, but this is the solution that builds on what you have already done.
Answer: except should work
select a.revision, a.casetype from A a
except
select b.revision, b.casetype from B b;


Does Java internally use Hashing technique to manage all objects

Question: new to the hashing concept, I have read that HashMap, HashTable etc use hashing, and we need to specify a key while storing a value with it
But, since every object has a hashCode() method, doest java internally use hashCode for a object via a particular field while managing it (other than the lists)
Comment: This isn't entirely clear; are you asking whether Java uses the `hashCode` method for its own internal purposes?
Comment: What sort of thing are you thinking of?
Answer: This is answered by the javadoc of Object.hashCode():

As much as is reasonably practical, the hashCode method defined by
  class Object does return distinct integers for distinct objects. (This
  is typically implemented by converting the internal address of the
  object into an integer, but this implementation technique is not
  required by the JavaTM programming language.)

(emphasis mine)
So no, there is no additional field to store the hashCode (unless some class decides to override it and implement it by using a dedicated field).
And the hashCode is not used by the JVM, but by hash-based collections (Hashtable, HashMap, HashSet, ...)
Comment: You can't use the internal address of an object because that changes on every modern generational or compacting GC because these operations move objects around in memory.

In addition the default hash code is part of the mark word of the object header http://hg.openjdk.java.net/jdk7/jdk7/hotspot/raw-file/1ee8caae33af/src/share/vm/oops/markOop.hpp so it's sort of a field on every object.
Comment: I don't think the javadoc meant the physical memory address, but only the JVM-internal "logical" memory address. I see it as something like the path of a file, which uniquely identifies a file on the file system, and could be considered as its "internal address" in the file system, although it isn't the physical address on the disk.
Comment: There is no JVM-interal "logical" memory address. OOPs are straight native pointers http://java.sun.com/products/hotspot/docs/whitepaper/Java_HotSpot_WP_Final_4_30_01.html#pgfId=1082238
Answer: No, the hashCode() method is used to define a key used to associate it with an instance of an object.
It is used to identify a particular instance of an object, and does not imply that a hashing technique is used to manage Java objects.
You can override the hashCode() method to define your own way of assigning keys to identify an instance of an object.
Answer: If you are asking "does Java use hashCode() in order to do behind-the-scenes management of objects?", I would imagine the answer is "no".  Consider what would happen if you wrote a really bad override of hashCode(); would you expect the JVM internals to be hampered by this?
Answer: public native int hashCode();

hashCode is native implementation. But no field is associated with it.
This is typically implemented by converting the internal address of the
object into an integer, but this implementation technique is not required
by the JavaTM programming language.

In the OpenJDK/Oracle JVM the usual method of computing the initial hash code is based on the memory address at the time of the first request. Objects move about in memory, so using the address each time would not be a good choice. The hash code isn't the actual address - that would typically be a multiple of eight which isn't great for using straight in a hash table particularly with a power of two size. Note identity hash codes are not unique.
As per documentation
jvmtiError GetObjectHashCode(jvmtiEnv* env, jobject object, jint* hash_code_ptr)

and
For the object indicated by object, return via hash_code_ptr a hash code.
This hash code could be used to maintain a hash table of object references,
however, on some implementations this can cause significant performance
impacts--in most cases tags will be a more efficient means of associating
information with objects. This function guarantees the same hash code value
for a particular object throughout its life.

Comment: You're probably looking at the wrong file, you're probably looking at `jvmtiEnv.cpp`, this JVMTI which is for tools like debuggers and profiles. This will just read the hash code from the mark word http://hg.openjdk.java.net/jdk7/jdk7/hotspot/raw-file/1ee8caae33af/src/share/vm/oops/markOop.hpp. You want to look at `synchronizer.cpp` http://blogs.tedneward.com/2008/07/16/ObjecthashCode+Implementation.aspx


MediatR not finding Handlers on IIS

Question: I am writing a simple application in .NET Core 3.0 with different layers and using MediatR to make my code clean.
I have 5 different layers: API, Application, Application.IO, Domain and Infrastructure with my IRequestHandler in Application and my IRequest in Application.IO and registering my handlers happens in the Startup class in the API layer.
When running this locally I have no issues but when I deployed this to an IIS server I keep getting the error:

Error constructing handler for request of type
  MediatR.IRequestHandler`2[WerfRegistratie.Application.IO.Queries.GetPersonQuery,WerfRegistratie.Application.IO.Queries.GetPersonQueryResponse].
  Register your handlers with the container. See the samples in GitHub
  for examples.
Comment: Show how you register handlers, i.e. your `ConfigureServices`. And describe how you publish the site.
Comment: At first I just used this             services.AddMediatR(typeof(CreatePersonCommandHandler).GetTypeInfo().Assembly);
But I have since then tried multiple other ways (including adding startup). The publish just happens through downloading the publish profile from azure and manually deploying it
Comment: Add your code into the question: handler class, query, registration and how you call it.
Answer: To register Mediatr you can use:
services.AddMediatR(typeof(Startup);

To register your handlers you can use:
services.AddMediatorHandlers(typeof(CreatePersonCommandHandler).GetTypeInfo().Assembly);

Both should be present in your startup.cs file in the ConfigureServices method
public void ConfigureServices(IServiceCollection services){
    services.AddMediatR(typeof(Startup);
 services.AddMediatorHandlers(typeof(CreatePersonCommandHandler).GetTypeInfo().Assembly);
}

Answer: After a lot of searching it seems the issues wasn't with the registration of the handlers (which were correct) but with dependency injection of a repository in my handler. After fixing this everything worked as expected
Comment: Originally I had set up my startup so my handlers got registered first and then I added the dependency injection for my entityframework. Switching them around ended up being enough
Comment: How did you fix the issue? Can u please mention some details?

MediatR not finding Handlers on IIS


applying external .css for html created using XSL from asp.net

Question: My scenario is, when a user clicks on a "button" from webform i have to create html file [using xsl tranformation of xml] and open it as a pop upwindow in client side.
xml transformation is done and i am ready with html.
I have created PopUpReport.aspx and popping up this page using below code.
Session["reportHtml"] = htmlReport;//this contains the transformed html
ScriptManager.RegisterStartupScript(this, typeof(string),
 "Showing Modalpopup", "window.open('PopUpReport.aspx',  'Report',
'width=800,height=600,scrollbars=1,resizable=1');",true);

and inside PopUpReport.aspx
protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Session["reportHtml"]);
    }

now my problem is,
i have a seperate .css file and which needs to be applied to the above HTML page, how should I link that in html?
specifying below in xsl file is not working.

and i dont want inline style as it contains huge lines of code.
is there any way to achieve this? should we use themes for this PopUpReport.aspx page? please help me...
Answer: In the .aspx file you are calling, link the CSS file in the head like this:
<link href="your.css" rel="stylesheet" type="text/css">

see http://www.w3.org/TR/html401/present/styles.html for more details.
Comment: thanks for reply.. i was trying to inject the .css file to the html using string.replace. now i have changed my implementation and it started working fine.


Wifi not working in fresh ubuntu 16.04 with acpi=off

Question: I know similar questions are already there, but I went through almost many of those and could not figure out how to solve it. I badly need my wifi up and running.
I could load ubuntu by using "acpi=off" in boot parameters and then even in live ubuntu and even after installation, wifi networks are not showing up and my airplane mode is always on even if I turn it off, later it will toggle to on.
rfkill list
0: phy0: Wireless LAN
Soft blocked: no
Hard blocked: yes

I looked for any hardware switch, but mine is "hp pavillion 13 a201", has only airplane mode switch which doesn't do anything.
sudo lshw -class network
   *-network DISABLED
   description: Wireless interface
   product: Wireless 3160
   vendor: Intel Corporation
   physical id: 0
   bus info: pci@0000:03:00.0
   logical name: wlo1
   version: 83
   serial: 34:e6:ad:b5:9a:c3
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
   configuration: broadcast=yes driver=iwlwifi driverversion=4.8.0-52-generic firmware=17.352738.0 latency=0 link=no multicast=yes wireless=IEEE 802.11
   resources: irq:26 memory:c1100000-c1101fff
  *-network
   description: Ethernet interface
   product: RTL8101/2/6E PCI Express Fast/Gigabit Ethernet controller
   vendor: Realtek Semiconductor Co., Ltd.
   physical id: 0
   bus info: pci@0000:04:00.0
   logical name: eno1
   version: 08
   serial: d0:bf:9c:9e:54:99
   size: 100Mbit/s
   capacity: 100Mbit/s
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress msix vpd bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd autonegotiation
   configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=full firmware=rtl8106e-2_0.0.1 04/23/13 ip=192.168.0.105 latency=0 link=yes multicast=yes port=MII speed=100Mbit/s
   resources: irq:23 ioport:3000(size=256) memory:c1004000-c1004fff memory:c1000000-c1003fff

lsmod | grep -e lap -e wmi
snd_rawmidi            32768  1 snd_seq_midi
snd_seq_device         16384  3 snd_seq,snd_rawmidi,snd_seq_midi
snd                    snd_hda_intel,snd_hwdep,snd_seq,snd_hda_codec,snd_timer,snd_rawmidi,snd_hda_codec_hdmi,snd_hda_codec_generic,snd_seq_device,snd_hda_codec_realtek,snd_pcm

lspci -knn | grep Net -A3; rfkill list
Network controller [0280]: Intel Corporation Wireless 3160 [8086:08b3] (rev 83)
DeviceName: Intel Dual Band Wireless-AC 3160 802.11ac 1x1 WiFi + BT 4.0 Combo Adapter
Subsystem: Intel Corporation Dual Band Wireless-AC 3160 [8086:0070]
Kernel driver in use: iwlwifi
0: phy0: Wireless LAN
Soft blocked: no
Hard blocked: yes

lsmod
Module                  Size  Used by
intel_rapl             20480  0
x86_pkg_temp_thermal    16384  0
intel_powerclamp       16384  0
coretemp               16384  0
kvm                   598016  0
irqbypass              16384  1 kvm
crct10dif_pclmul       16384  0
crc32_pclmul           16384  0
ghash_clmulni_intel    16384  0
aesni_intel           167936  0
aes_x86_64             20480  1 aesni_intel
lrw                    16384  1 aesni_intel
arc4                   16384  2
glue_helper            16384  1 aesni_intel
iwlmvm                360448  0
ablk_helper            16384  1 aesni_intel
mac80211              761856  1 iwlmvm
snd_hda_codec_realtek    86016  1
uvcvideo               90112  0
snd_hda_codec_hdmi     45056  1
snd_hda_codec_generic    73728  1 snd_hda_codec_realtek
cryptd                 24576  3   ablk_helper,ghash_clmulni_intel,aesni_intel
hid_sensor_accel_3d    16384  0
hid_sensor_incl_3d     16384  0
hid_sensor_rotation    16384  0
hid_sensor_magn_3d     16384  0
hid_sensor_gyro_3d     16384  0
videobuf2_vmalloc      16384  1 uvcvideo
hid_sensor_trigger     16384  10       hid_sensor_incl_3d,hid_sensor_accel_3d,hid_sensor_magn_3d,hid_sensor_gyro_3d,hid_sensor_rotation
videobuf2_memops       16384  1 videobuf2_vmalloc
industrialio_triggered_buffer    16384  5  hid_sensor_incl_3d,hid_sensor_accel_3d,hid_sensor_magn_3d,hid_sensor_gyro_3d,hid_sensor_rotation
videobuf2_v4l2         24576  1 uvcvideo
kfifo_buf              16384  1 industrialio_triggered_buffer
intel_cstate           16384  0
videobuf2_core         40960  2 uvcvideo,videobuf2_v4l2
intel_rapl_perf        16384  0
snd_hda_intel          36864  5
snd_hda_codec         135168  4   snd_hda_intel,snd_hda_codec_hdmi,snd_hda_codec_generic,snd_hda_codec_realtek
industrialio           65536  8   hid_sensor_incl_3d,hid_sensor_accel_3d,hid_sensor_trigger,hid_sensor_magn_3d,hid_sensor_gyro_3d,hid_sensor_rotation,industrialio_triggered_buffer,kfifo_buf
snd_hda_core           86016  5   snd_hda_intel,snd_hda_codec,snd_hda_codec_hdmi,snd_hda_codec_generic,snd_hda_codec_realtek
videodev              180224  3 uvcvideo,videobuf2_core,videobuf2_v4l2
snd_hwdep              16384  1 snd_hda_codec
snd_pcm               110592  4   snd_hda_intel,snd_hda_codec,snd_hda_core,snd_hda_codec_hdmi
hid_sensor_iio_common    16384  6   hid_sensor_incl_3d,hid_sensor_accel_3d,hid_sensor_trigger,hid_sensor_magn_3d,hid_sensor_gyro_3d,hid_sensor_rotation
hid_multitouch         20480  0
media                  40960  2 uvcvideo,videodev
snd_seq_midi           16384  0
snd_seq_midi_event     16384  1 snd_seq_midi
joydev                 20480  0
iwlwifi               229376  1 iwlmvm
snd_rawmidi            32768  1 snd_seq_midi
snd_seq                69632  2 snd_seq_midi_event,snd_seq_midi
input_leds             16384  0
mac_hid                16384  0
snd_seq_device         16384  3 snd_seq,snd_rawmidi,snd_seq_midi
snd_timer              32768  2 snd_seq,snd_pcm
cfg80211              581632  3 iwlmvm,iwlwifi,mac80211
snd                    86016  21     snd_hda_intel,snd_hwdep,snd_seq,snd_hda_codec,snd_timer,snd_rawmidi,snd_hda_codec_hdmi,snd_hda_codec_generic,snd_seq_device,snd_hda_codec_realtek,snd_pcm
rtsx_pci_ms            20480  0
memstick               20480  1 rtsx_pci_ms
soundcore              16384  1 snd
mei_me                 40960  0
mei                   102400  1 mei_me
serio_raw              16384  0
shpchp                 36864  0
lpc_ich                24576  0
parport_pc             32768  0
ppdev                  20480  0
lp                     20480  0
parport                49152  3 lp,parport_pc,ppdev
autofs4                40960  2
hid_sensor_custom      20480  0
hid_sensor_hub         20480  8    hid_sensor_incl_3d,hid_sensor_accel_3d,hid_sensor_iio_common,hid_sensor_trigger,hid_sensor_magn_3d,hid_sensor_gyro_3d,hid_sensor_rotation,hid_sensor_custom
hid_generic            16384  0
usbhid                 53248  0
hid                   122880  4   hid_sensor_hub,hid_generic,usbhid,hid_multitouch
i915                 1314816  112
video                  40960  1 i915
rtsx_pci_sdmmc         24576  0
i2c_algo_bit           16384  1 i915
drm_kms_helper        167936  1 i915
syscopyarea            16384  1 drm_kms_helper
sysfillrect            16384  1 drm_kms_helper
sysimgblt              16384  1 drm_kms_helper
fb_sys_fops            16384  1 drm_kms_helper
drm                   368640  5 i915,drm_kms_helper
psmouse               139264  0
r8169                  81920  0
ahci                   36864  3
libahci                32768  1 ahci
mii                    16384  1 r8169
rtsx_pci               57344  2 rtsx_pci_sdmmc,rtsx_pci_ms

iwconfig
lo        no wireless extensions.

wlo1      IEEE 802.11  ESSID:off/any
      Mode:Managed  Access Point: Not-Associated   Tx-Power=off
      Retry short limit:7   RTS thr:off   Fragment thr:off
      Power Management:on

eno1      no wireless extensions.

I have tried
rfkill unblock all

but nothing, Is it because I turned off acpi?
also
sudo ifconfig wlo1 up
SIOCSIFFLAGS: Operation not possible due to RF-kill

sudo modprobe hp-wmi
modprobe: ERROR: could not insert 'hp_wmi': No such device

++added
dmesg | grep iwl
[    9.728583] iwlwifi 0000:03:00.0: can't find IRQ for PCI INT A; please try using pci=biosirq
[   10.435598] iwlwifi 0000:03:00.0: loaded firmware version 17.459231.0 op_mode iwlmvm
[   10.969645] iwlwifi 0000:03:00.0: Detected Intel(R) Dual Band Wireless AC 3160, REV=0x164
[   10.973894] iwlwifi 0000:03:00.0: L1 Enabled - LTR Enabled
[   10.974192] iwlwifi 0000:03:00.0: RF_KILL bit toggled to disable radio.
[   10.974240] iwlwifi 0000:03:00.0: L1 Enabled - LTR Enabled
[   11.067718] ieee80211 phy0: Selected rate control algorithm 'iwl-mvm-rs'
[   12.214623] iwlwifi 0000:03:00.0 wlo1: renamed from wlan0

I would appreciate a lot if someone could look in to it. Thanks in advance.
Comment: Airplane mode turns all radios off, that's what it does.
Comment: Ya,  but I cant turn it off since it just toggle back to on. I need my wifi up and running.  Any suggestion to solve this?
Comment: Please run: `sudo modprobe hp-wmi` and then see if the airplane mode switch works. If there is an error or warning, please post it.
Comment: I have edited my question with the result.It says: modprobe: ERROR: could not insert 'hp_wmi': No such device
Comment: @chili555 and MichaelBay . Thank you for spending your quality time for me.
Answer: After a day long search and troubleshoot, I finally found a hack for all my problems.
Since I used
acpi=off

in boot parameters, I didn't have battery status and those power management options. In some computers like mine it turns off the wifi also.
So instead of using acpi=off, another parameter has to be found out. This could depend on your system, but in my case no other parameter mentioned through out the net worked, thats why I installed with "acpi=off". But
acpi_osi=

replacing acpi=off will solve the problem, atleast in my case. Yes, There is nothing to the right of =.
Hope this will help someone in future.


Get all information between the same multiple tags from XML file in C

Question: Summary:

I developed an app which is supposed to: read an XML File (without using any XML library), get some words between specific tags and print those words on the screen using the basic printf().

My XML File looks like this:
<Server>
    <Host>ip1</Host>
    <User>user1</User>
    <Pass>pass1</Pass>
</Server>
<Server>
    <Host>ip2</Host>
    <User>user2</User>
    <Pass>pass2</Pass>
</Server>

Now, my code is able to get: ip1, user1, pass1.
How can I modify my code, so that I can also get ip2, user2, pass2 then ip3, user3, pass3 and so on until I reach the end of the file ?
The code is the next one:
int getContent()
{
    //variables for reading the XML file
    char *buffer=0;
    long length;
    FILE *xmlFile=fopen("C:/Users/IEUser/AppData/Roaming/recentservers.xml","r");

    //constants for parsing XML
    const char *HOSTSTART = "<Host>";
    const char *HOSTEND = "</Host>";

    const char *USERSTART = "<User>";
    const char *USEREND = "</User>";

    const char *PASSSTART = "<Pass encoding=\"base64\">";
    const char *PASSEND = "</Pass>";

    char *target_host = NULL,*target_user = NULL,*target_pass = NULL, *start, *end;

    //read the xml file
    if(xmlFile)
    {
        fseek(xmlFile,0,SEEK_END);
        length=ftell(xmlFile);
        fseek(xmlFile,0,SEEK_SET);

        buffer=malloc(length);
        if(buffer)
        {
            fread(buffer,1,length,xmlFile);
        }
        fclose(xmlFile);
    }

    //get the HOST
    if(buffer)
    {
        if(start=strstr(buffer,HOSTSTART))
        {
            start += strlen(HOSTSTART);
            if(end=strstr(start, HOSTEND))
            {
                target_host = (char *)malloc(end-start+1);
                memcpy(target_host,start,end-start);
                target_host[end-start]='\0';
            }
        }
        if(target_host)
            printf("%s\n",target_host);
        //free(target_host);
    }

    //get the USER
    if(buffer)
    {
        if(start=strstr(buffer,USERSTART))
        {
            start += strlen(USERSTART);
            if(end=strstr(start, USEREND))
            {
                target_user = (char *)malloc(end-start+1);
                memcpy(target_user,start,end-start);
                target_user[end-start]='\0';
            }
        }
        if(target_user)
            printf("%s\n",target_user);
        //free(target_user);
    }

    //get the PASS
    if(buffer)
    {
        if(start=strstr(buffer,PASSSTART))
        {
            start += strlen(PASSSTART);
            if(end=strstr(start, PASSEND))
            {
                target_pass = (char *)malloc(end-start+1);
                memcpy(target_pass,start,end-start);
                target_pass[end-start]='\0';
            }
        }
        if(target_pass)
            printf("%s\n",target_pass);
        //free(target_pass);
    }
    // here I would like a for which will printf as many target information as they are in that XML File
    printf("%s | %s | %s",target_host,target_user,target_pass);
    printf("\n\n");
    return 0;
}

int main()
{
    getContent();
    return 0;
}

//EDIT1:
int readTag(char *buffer, const char *tagStart, const char *tagEnd){
    int start, end;
    char *target = NULL;
    start = 0;
    end = 0;
    if(start=strstr(buffer,tagStart))
    {
        start += strlen(tagStart);
        if(end=strstr(start, tagEnd))
        {
            target = malloc(end-start+1); //don't cast malloc
            memcpy(target,start,end-start);
            target[end-start]='\0';
            printf("Target between tag %s and %s = %s", tagStart, tagEnd, target);
            //sendTargetToGET(tagStart, tagEnd, target);
            free(target);
        }
    }
    return (end - start); // returns nr characters between the tags
}

int getTagID(char *buffer){
    const char *HOSTSTART = "<Host>";
    const char *HOSTEND = "</Host>";

    const char *USERSTART = "<User>";
    const char *USEREND = "</User>";

    const char *PASSSTART = "<Pass encoding=\"base64\">";
    const char *PASSEND = "</Pass>";

    if(strstr(buffer, HOSTSTART) != NULL && strstr(buffer, HOSTEND) != NULL)
    {
        return 1;
    }
    else if(strstr(buffer, USERSTART) != NULL && strstr(buffer, USEREND) != NULL)
    {
        return 2;
    }
    else if(strstr(buffer, PASSSTART) != NULL && strstr(buffer, PASSEND) != NULL)
    {
        return 3;
    }
    else
        return 0;
}

int main()
{
    char *buffer=0;

    const char *HOSTSTART = "<Host>";
    const char *HOSTEND = "</Host>";

    const char *USERSTART = "<User>";
    const char *USEREND = "</User>";

    const char *PASSSTART = "<Pass encoding=\"base64\">";
    const char *PASSEND = "</Pass>";
    FILE *xmlFile=fopen("C:/Users/IEUser/AppData/Roaming/recentservers.xml","r");

    int tagID = 0;
    while (fgets(buffer, sizeof(buffer), xmlFile) != NULL)
    {
         tagID = getTagID(buffer);

         if(tagID == 1)
         {
             readTag(buffer, HOSTSTART, HOSTEND);
         }
         else if(tagID == 2)
         {
             readTag(buffer, USERSTART, USEREND);
         }
         else if(tagID == 3)
         {

         }
    }
    return 0;
}

I've got an assertion failure unfortunately and I don't know what is the reason
Comment: Why can't you use any XML library? If you want a robust solution you will end up with writing one on your own.
Comment: Why don't you use any existing `xml` parser? For your parser, search for tags (anything betwee `<...>`) and text i.e. everything else and use a recursive function to store it in a tree format.
Comment: @MohitJain there are more tags not only `host`, `user`, `pass`but I just simplified it for the sake of example and because the only ones that I need. Could you please provide a detailed answer ?
Comment: Have you ever heard of function arguments and loops? You are doing fine, just make another function that searches for  `` first
Answer: What I would suggest is:
1) Put the tag read parts in a function so you can don't have the same code for every tag:
int readTag(char *buffer, const char *tagStart, const char *tagEnd){
    int start, end;
    char *target = NULL;
    start = 0;
    end = 0;
    if(start=strstr(buffer,tagStart))
    {
        start += strlen(tagStart);
        if(end=strstr(start, tagEnd))
        {
            target = malloc(end-start+1); //don't cast malloc
            memcpy(target,start,end-start);
            target[end-start]='\0';
            printf("Target between tag %s and %s = %s", tagStart, tagEnd, target);
            //sendTargetToGET(tagStart, tagEnd, target);
            free(target);
        }
    }
    return (end - start); // returns nr characters between the tags
}

2) Read the file line by line, check if the line contains tags you need (maybe with a function) and call the associated tag read function.
int tagID = 0;
while (fgets(buffer, sizeof(buffer), xmlFile) != NULL){
     tagID = getTagID(buffer);

     if(tagID == 1){//or use an enum here
         readTag(buffer, HOSTSTART, HOSTEND);
     }else if(tagID == 2){
         readTag(buffer, USERSTART, USEREND);
     }else if(tagID == 3){ //and so on
     }
}

int getTagID(char *buffer){
    if(strstr(buffer, HOSTSTART) != NULL && strstr(buffer, HOSTEND) != NULL){
        return 1;
    }else if(strstr(buffer, USERSTART) != NULL && strstr(buffer, USERSTART) != NULL){
        return 2;
    }else if(/*and so on*/){
    }else return 0;
}

Comment: nice. What happens to `target`? It's allocated, printed, but not freed. It' unclear what the OP wants to do with it
Comment: @Pynchia Whoops forgot the freeing.. thanks for pointing that out! Well in his question he tells he only wants to print it so I guess this is OK as far as I am informed.
Comment: @moffeltje I don't have any `getTagID()` function (could you help me a little bit with that too ?). More, for now I just want them printed. LAter, I will send this information in a GET request.
Comment: The naming "*Tag ID*" is missleading. It's about the "*element's name*" which **is** the "*tag*".
Comment: @Alexander I've just provided some idea's with some untested code to give you an idea how to write your program. The task of get it working is yours now, I do not have the time to write and debug a program you need.
Comment: @moffeltje Yes, I know. I don't want you to do this. I was just wondering if I wrote the `main()` and other functions as you were expecting to be writen.
Comment: @Alexander Well yeah, that is indeed the way I think your program can be implemented. Of course it is your decision and you should consider if it meets the criteria of your program. Good luck and if this answered your question, you can accept it!
Comment: @moffeltje. I accepted your answer. Thanks very much for your collaboration. I have a last question if that's possible and you have time: how would the `main()` of the program look like ? I'm mostly interested in the arguments of the functions.


Laravel casting not working on double and decimal setting to zeros

Question: I have 2 decimal(10,8) fields on mysql with this migration:
$table->decimal('lat', 10, 8)->nullable();
$table->decimal('lng', 10, 8)->nullable();

Via an API endpoint I find the latitude and longitude.
The API returns this:
$geo->lat = 46.0081326;
$geo->lng = 8.9761892;

BUT when setting my model field like so
$estate->lat = $geo->lat;
$estate->lng = $geo->lng;

in the DB the fields gets set to 46.00000000 and 8.00000000.
Because of this I tried setting the cast in the model like so
protected $casts = ['lat' => 'double', 'lng' => 'double'];

I also tried casting to specific decimal
protected $casts = ['lat' => 'decimal:8', 'lng' => 'decimal:8'];

But no luck. I still get 46.00000000 and 8.00000000 inside the DB.
I also tried removing Laravel casts and forcing the type like this
$estate->lat = (double) $geo->lat;

But I still get empty decimal points.
These are 2 new brand new columns but I tried checking if the App has some setLatAttribute() mutator but it does not.
Comment: So `$geo->lat == 42.9856226` but when you set `$estate->lat` to `$geo->lat` the digits after the decimal get turned to 0s?
Comment: @CalebAnthony exactly
Comment: Which model has the `$casts` variable (did you know it has an "s" at the end)? The Estate model?
Comment: I also noticed your database stores the values as decimal, why not cast the variable as a decimal as well? In changing data types it might be breaking. Lat/Lng are generally better to be used as decimals in PHP anyway.
Comment: @CalebAnthony yes Estate model. Casts with an s, was a typo in the question.
Answer: Your database is holding the data type as a decimal (which is good!), but your application tries to read that decimal as a float.
You should be able to tell your application to continue reading the data as a decimal:
protected $casts = ['lat' => 'decimal:8'];

If you're relying on Laravel's $casts functionality, you shouldn't be forcing type anywhere else in your code, this can get you into all sorts of nasty problems that are incredibly hard to debug.
Comment: Same problem... I have another project which worked fine and did not use casts nor typing and just worked. I took the same migration and for some reason I don't know it fails ini placing decimals. Same machine, same DB... :(
Answer: The problem was not related to the casting or typing but rather to the wrong class name.
I forgot to rename the Class name into the correct one (SmootherCommand in SmootherCommand.php) and this caused misbehaviour.


IKEA recessed lights: extreme clearance requirements?

Question: I'm finishing the ceiling on my basement.  I'm planning to insulate the ceiling with the Roxul Safe'n'Sound Fire & Soundproofing Insulation.  It is 3 inches thick so it only occupies the upper 3 inches of the bay.
I was planning to use IKEA's BLIXT recessed spotlight.  However, I have a concern with its clearance requirements: top of luminaire to overhead building member 0.5"; luminaire center to side building member: 12".  My joist spacing is b/n 11" and 15" so I can't possibly satisfy that.  Those requirements sound a bit extreme, don't they?
From what I could quickly research I think these fall into the "Marked Spacing Type Luminaries" category, according to:
http://www.iaei.org/magazine/2001/07/installation-clearance-requirements-for-recessed-luminaries/
Any thoughts?  Can I make it work?  I like these lights: they look great, are only 35W and cost $19 for 3 pack which is an unbeatable price.
Answer: I personally would abandon them for something with better requirements - there's a reason that IKEA stuff is low in price, and that reason is compromises. For instance, the GORM shelving units are strong and flexible, but take a while to assemble and are kinda ugly.
In this case it looks like the compromise is the required spacing. My guess is that the heat load they produce (especially the temperature of the fixture itself) is high enough that they need the extra space to cool (a different, more expensive, fixture might have some other way to ditch the heat that would require less space).
That said, any engineer worth his salt (and his lawyer) isn't going to skimp on the required spacing. It's very likely that you could get away with shaving a few inches off of it, but there are no guarantees if you start violating the spacing requirements.
The biggest worry in my mind would be that if something went wrong (even if it had nothing to do with these fixtures), the insurance company would balk because these fixtures were installed 'improperly'.
Comment: Alright, I have to agree.  I think I'm going to get something like this instead: http://www.homedepot.com/buy/lighting-fans/recessed-lighting/commercial-electric/6-in-ic-airtight-recessed-lighting-contractor-6pack-c1-40826.html.  My other concern is that the halogen lights produce heat and burn often.
Answer: As said above, the motivation is the heat dissipation and risk of fire. With today's LED technology this risk is no more as long as LED bulbs are used. The insurance issue would still remain, and you could be held responsible in case someone later install an halogen bulb.
These lights are also no more sold by IKEA as far as I can see today.


Is pickpocketing large amounts of gold in Skyrim bugged?

Question: I've been experimenting a fair bit with... let's call it, "reducing the chance of future spinal issues due to excess load" of various townsfolk. While engaging in this public-health improvement activity, I've noticed that while my pickpocket chances for most items are perfectly stable, anytime an NPC is carrying large amount of gold (over 1000), the rules for relieving them of their gold stash seem to become truly bizarre and unstable.
Example:

Target: Giraud Gemane, Solitude Bardic College
Gold: 1610
My stats:
Pickpocket: 100
Light Fingers: rank 2 (+40% bonus)
Cutpurse: Yes (+50% bonus)
Attempt 1: No gear
Displayed success chance: 15%
Attempt 2: Closed pickpocket window, reopened without changing anything or either character moving.
Displayed success chance: 65%
Attempt 3: Closed window, equipped Fine Boots enchanted with +40% pickpocket
Displayed success chance: 55%
Attempt 4: Closed window, reopened; still have boots equipped.
Displayed success chance: 5%
Attempt 5: Closed window, equipped Gloves enchanted with +40% pickpocket bonus.
Displayed success chance: 0%

From tinkering around a lot with different NPCs and gold amounts it feels like every time I open the pickpocket window, I will either get a "good" base pickpocket chance of 65% or a "bad" base pickpocket chance of 15%. From there, every pickpocket bonus item I equip actually reduces my chance of success by about 10%.
Again, this only appears to kick in for NPCs with over 1000-ish gold. Under that amount, I have a 90% success chance every single time regardless of equipment.
Can anyone offer an explanation for this behavior, or is this a bizarre bug of some kind?
Comment: The good vs. bad chance is the difference between you attempting this while seen/unseen by your mark. You say neither of you is moving, but he's swiveling his head around I'm sure, and theres a pulse of some sort as well.
Comment: That strikes me as odd since I'm not "detected" (full closed-eye indicator for stealth) when trying this.
Comment: You know how much weights 1000 septims?
Comment: @M'vy — According to Skyrim, [nothing at all](http://cloud.steampowered.com/ugc/648745380530960858/56D0FCC82AA152803DC120621FD8FC280E93EC8A/)! :-)
Comment: i also have the problem people saying its the light or whatever havent done this, it seems like a screw up in the formula, because after 1000 or so gold it gets buggy and u have to open and close the pickpocketing window to get a non zero percent number aswell as pickpocketing enchants making u less likely to steal the gold
Comment: I agree it seems bugged to an indecipherable degree.. My pickpocketing is 85, and as a max enchanter I have a ring and necklace on each with +40% pickpocket success and the thieves guild boots adding another 15% on top of that.. and I still get 0% for no reason sometimes.. ok I thought, maybe he's just extremely perceptive (downs a pickpocketing potion for another 50% on top of that.. still getting 0%) it's actually happened with the "quest item" on the repeatable "fishing quest" several times as well.
Answer: This is probably due to your stealth meter changing due to NPCs moving, or dynamics lights touching you or not.   The closer you are to being detected the less likely you are to succeed.
Comment: I took care to watch the light and shadow, and the direction the NPC was looking. I don't think that was it, unfortunately. And even if it was, it would not explain why putting on pickpocket bonus items consistently reduces the chance to succeed.
Comment: Well, as with many RPG's  there could be %chance of getting a good base roll.  There is a perk that allows you to steal gold easily.  If you get this perk and seem to get more stables results, then I would guess that 1000g is the limit for your thieving skill, where you get lower results more often than not regardless of equipment.  The only way to test this would be to try it a lot, record the results then compare.  I am currently beating the game.  When I am done I will do some testing.  When ModKit is realeased, we will probably get accurate formulas.
Answer: This is a glitch and it's probably bugged. What you're wearing might do the opposite effect. Unequip the enchanted gear to see if the chances of taking gold are possible. If that doesn't work, place a paralyze potion or use Unrelenting Force on them, when theyare getting up, pickpocket them and you can take the gold even when it's a 0% chance.