iOS Dateformatter Timezone

Question: Im trying to convert a String without timezone value like "31.05.2015" to NSDate.
Whats wrong with my DateFormatter? It returns the date 2015-05-31 22:00:00 +0000
and when I try to print it with the same formatter it prints: 01.06.2015
-(NSDateFormatter*) dateFormatter{
    if(!_dateFormatter){
        _dateFormatter = [[NSDateFormatter alloc]init];
        [_dateAndTimeFormatter setDateFormat:@"dd.MM.yyyy"];
        [_dateAndTimeFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CEST"]];
        _dateFormatter.dateStyle = NSDateFormatterShortStyle;
        _dateFormatter.timeStyle = NSDateFormatterNoStyle;
    }
    return _dateFormatter;
}

EDIT
I updated it to
-(NSDateFormatter*) dateAndTimeFormatter{
    if(!_dateAndTimeFormatter){
        _dateAndTimeFormatter = [[NSDateFormatter alloc]init];
        [_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS Z"];
        _dateAndTimeFormatter.dateStyle = NSDateFormatterShortStyle;
        _dateAndTimeFormatter.timeStyle = NSDateFormatterShortStyle;
    }
    return _dateAndTimeFormatter;
}

and call it with
NSDate *startDate = [self.dateFormatter dateFromString:@"31.05.2015"];
self.beginningValueLabel.text = [self.dateFormatter stringFromDate:startDate];

The result still is 01.06.2015.
startDate is 2015-05-31 22:00:00 +0000
Comment: Are you using `NSLog()` or the debugger to see the resulting date?  A little searching might find the 1000+ other questions relating to this on this site.
Comment: I'm using the debugger and I print the result in my app. And I parse it to an NSDate to print it correctly for each culture.
Comment: This is a very common issue.
Answer: When you use [NSDateFormatter setTimeZone:] the formatter will adjust the date for display based on that new timezone, so it's adding the timezone offset to the date before formatting it for display.
The NSDateFormatter defaults to the timezone of the device, so it would have had the same effect as setting the timezone manually. Tell the DateFormatter to use the same timezone as the date (+0000).
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]

Comment: What does "adjust the date for display" mean?
Comment: @Droppy check the edited answer, I think I see the problem.

iOS Dateformatter Timezone


How to mark that I want Ubuntu to be upgraded to the newer release so it can run in unattended mode?

Question: How to mark that I want Ubuntu to be upgraded to the newer release so it can run in unattended mode?
As per this article upgrade is done using do-release-upgrade tool but I simply want to mark somehow that I want system upgraded (so unattended-upgrade or apt-get dist-upgrade will do its job), not do this manually.
Synonyms for question title so it's easier to find it in search:
How do I upgrade Ubuntu (Kubuntu) without using do-release-upgrade app?
How to always have latest Ubuntu (Kubuntu) release installed (similarly to Arch) without manually running do-release-upgrade all the time?
Comment: It's not so simple. A release upgrade may and often need user input.
Answer: Set these options in "Software and Updates" > Updates Tab.
The "Download and Install automatically" option does unattended upgrades. Options to "Display" either immediately or weekly give you notification first.
also change the "notify me" to any newer version.
You will automatically be notified when an update will be available(given you have an active internet connection). You just need to click upgrade/continue and you will be upgraded to the newer release
Answer: In this guide, we will assume an upgrade is done from version 16.04 (xenial) to 17.10 (artful). This can be easily changed to your versions.
We will make default apt-get dist-upgrade to handle release upgrade as a result.
The following is needed to be done to automate release upgrades:

Add repos of release you want to install:
TARGET_RELEASE=artful
/usr/bin/add-apt-repository -y \
  -u 'deb http://archive.ubuntu.com/ubuntu $TARGET_RELEASE restricted multiverse universe main'
/usr/bin/add-apt-repository -y \
  -u 'deb http://archive.ubuntu.com/ubuntu $TARGET_RELEASE-updates restricted multiverse universe main'
/usr/bin/add-apt-repository -y \
  -u 'deb http://archive.ubuntu.com/ubuntu $TARGET_RELEASE-security restricted multiverse universe main'

Change "artful" to the version you want to have installed. I used
"artful" since I needed version 17.10.
Create or change /etc/apt/apt.conf.d/01ubuntu file to have the following content:
APT::Default-Release "artful";

Change "artful" to the version you want to have installed. I used
"artful" since I needed version 17.10.
dist-upgrade will resolve dependencies but will have some packages removed it can't resolve. Usually, it's because these packages are installed from non-default release repositories. We can find repositories of these packages like this:
CURRENT_RELEASE=xenial
awk '/^deb .* $CURRENT_RELEASE .*/ { print $0 }' /etc/apt/sources.list /etc/apt/sources.list.d/*.list

(Change xenial to the release version you are trying to upgrade).
Now you should change in these files "xenial" to "arful" (or the version to which you are trying to upgrade.
Run sudo apt-get update.

Then dist-upgrade would handle an upgrade to a new release on its own. No need for manual do-release-upgrade anymore.
You can manually run sudo apt-get dist-upgrade or wait until your unattended upgrades setup will do its job automatically in the background.


singleton ejb mixing concurrency issue

Question: I read few articles on the Internet about @Singleton and how it has by default the container managed concurrency however I cant figure out following issue:
@Singleton
@Startup
public class MySBean {

    @Lock(WRITE)
    private void load() {
    ...
    }

    @Lock(READ)
    public Data getData(String match, ...) {
        ...
        load();  // does singleton syncs all calls from getData() to load()?
        ...
    }
}

All those simple articles online described how once a client calls a method annotationed with READ for instance many @Stateless beans inject @Singleton it allows multple access to that method at the same time because of READ. Does a client access a method annotationed with WRITE the @Singleton instance forces other threads/stateless beans to wait. But what happens when you mix them?
What happens when there are two or more calls at same time to getData method?
Answer:
As long as getData is entered by any thread, load is blocked for other threads, but getData is allowed.
As long as load is entered by one thread, both load and getData are blocked for other threads.

See: Managing Concurrent Access in a Singleton Session Bean
Comment: your answer is not exactly what I was looking for
Comment: I answered to: "What happens when there are two or more calls at same time to getData method?" what is yet open? Is blocked means, the thread waits for a certain time, until the blocking is removed or the Timeout occurs. The timeout happens after 5 seconds, then the thread will get an Exception.
Comment: to sum up - getData() method may be called by different threads as long one of them is NOT the first to enter load() method. Once that happens, nobody can call geData() anymore means thread are waiting and those threads who did access getData but werent first are also waiting for load() to finish, right?
Comment: if that includes, that: load must wait as long as any other thread has entered getData(), then yes. Example: A is in getData(), B is in getData() and tries load .. B must wait until A has left getData(). If A meanwhile tries to enter load .. deadlock because of both waiting for each other to leave getData(). Which should either be detected or both wait until the first of them encountered a timeout.
Comment: B and A are both inside getData and B is the first who enters load() method. That would mean to me that B runs normally and A waits for B to finish load() the it enters load() for iteself and proceeds with the rest of getData() method. Did I get it wrong?
Comment: no B must not enter load() as long as A has not left getData(). Otherwise it would not make sense to let anybody wait at getData as long as another thread is working in load()
Comment: I dont get you sorry maybe its because of my english. Lets keep it simple. There are two threads A and B.. both may enter getData() since its marked as @Read annotation. However only one of them will enter load() first from getData().. Lets say B enters load() from getData(). what happens with A? it must enter load too since its also inside getData() just B was faster, no?
Comment: Sorry, I can only repeat the same. If the call to load() happens during getData() then this call will will **blocked** until all **other** threads have **left** getData(). if that is not possible because of another thread trying to enter load() inside getData() -- **Deadlock** -- which will be solved by exception thrown by the container either immediately or after the timeout.

singleton ejb mixing concurrency issue


How to parse datetime like this

Question: I understand that it sounds weird but I have datettime 2018-04-04 12:59:575Z.
Let's assume it is real, not a mistake and I can't find any standard for parsing this.
Is there a way to parse it in Java? What 3 numbers 575 at the end could mean?
edit:
There is strong doubt, that it is correct date time in my samples. I'm going to report a bug to creator. Thanks everyone for good advices.
Comment: milliseconds come after seconds. this looks like someone misused a formatter.
Comment: Unless you have a huge number of examples confirming the guess that `575` stand for milliseconds, it can be anything. `yyyy-MM-dd HH:mm:SS5z` with literal `5` would also produce similar output.
Answer: It probably means there's a bug in wherever this string came from. I would investigate there if I had access to that code or report a bug to its owner.
There's no point parsing buggy data and guessing what the numbers mean. Bad data is worse than no data.
Comment: nice idea, but at that time I don't have access to their code
Comment: Report a bug then if you can. There's no point parsing buggy data and guessing what the numbers mean. Bad data is worse than no data.
Answer:
What 3 numbers 575 at the end could mean?

My guesses include:

It's 12:59:57.5 (the .5 signifying half a second; assuming that the decimal point has been left out from the format).
575 are millisecond of the second, and seconds have been forgot. So it's 12:59:ss.575 where we don't know what ss should have been.
It's 59,575 minutes past 12 o'clock (the same as 12:59:34.5). In defense of this option, ISO 8601 does allow decimals on the minutes, but then the decimal "point" should be either a comma or a period, not a colon.

I can't find any standard for parsing this.

I am pretty convinced that there isn't any.

Is there a way to parse it in Java?

No, sorry, not as long as we don't know what the string means.
Answer: There could be two possible options for 59 at the end. It could be minutes or seconds. I think, that minutes is more likely, because seconds could be not valuable. 575 is definitely millisecond.
DateTimeFormatter dfMinutes = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:SSS");
DateTimeFormatter dfSeconds = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:ss:SSS");

P.S. It could be yyyy-dd-MM instead of yyyy-MM-dd. But as I can see, we're in same locale.
Comment: It'd probably be better to recommend using [`DateTimeFormatter`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.html) from the newer `java.time` API.
Comment: It's not so much the old date-time API doesn't work, it's that the new date-time API is better in pretty much every way. Since OP gives no indication of already using the old API, it seems more appropriate to direct him towards the more modern, better implemented API.
Comment: For starters, count the questions on Stack Overflow about unexpected results from `SimpleDateFormat`. Other relevant Stack Overflow questions: [Why is the Java date API (java.util.Date, .Calendar) such a mess?](https://stackoverflow.com/questions/1571265/why-is-the-java-date-api-java-util-date-calendar-such-a-mess) and [What's wrong with Java Date & Time API?](https://stackoverflow.com/questions/1969442/whats-wrong-with-java-date-time-api)
Comment: Please don't teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`.
Answer: You can use joda time api to parse the input String like below:-
String strDate="2018-04-04 12:59:575Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:SSSZ");
DateTime dt = formatter.parseDateTime(strDate);
System.out.println(dt); //2018-04-04T08:59:00.575-04:00

575 in your input string is milliseconds.

But you need to find out whats the point of precision till
  milliseconds if you are not including seconds.

How to parse datetime like this


Maven using pomInclude

Question: I am completely new baby into Maven and got stuck on this tutorial.
There is an element pomInclude which is used for including another POM files.
When I build bus-core-api with command
mvn package -U

it just works for current project. The others are not called during the build.
pom.xml in bus-core-api:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>bus-core-api</groupId>
<artifactId>bus-core-api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-invoker-plugin</artifactId>
<version>1.6</version>
  <configuration>
     <debug>true</debug>
     <pomIncludes>
        <pomInclude>app-web-ui/pom.xml</pomInclude>
        <pomInclude>app-desktop-ui/pom.xml</pomInclude>
     </pomIncludes>
  </configuration>
  <executions>
     <execution>
        <id>build</id>
        <goals>
           <goal>run</goal>
        </goals>
     </execution>
  </executions>
  </plugin>
  </plugins>
  </build>
  </project>

Part of output:
[INFO] Compiling 1 source file to c:\apache-maven-3.3.3\bus-core-api\target\clas
ses
The others are missing. Can you tell me why?
Comment: Why are you using such an ancient version of Maven-Invoker-Plugin (2.0.0) is the current version...
Comment: Ok I will try to change to 2.0. Missing is the compilation for the included modules 'app-web-ui' and app-desktop-ui. According to the tutorial they should be called and compiled according to the specified POM. This is the problem. I just receive compilation in the folder bus-core-api. Any thoughts?
Answer: pomIncludes is an element configuring the maven-invoker-plugin. Quoting from the documentation, this parameter is used to:

Include patterns for searching the integration test directory for projects.

What this means is that during integration testing of your project, Maven will run both the app-web-ui and app-desktop-ui projects and output the result to the command line.
The run goal of that plugin binds by default to the Maven phase integration-test. Since you did not specify a phase, it keeps that default. Looking at the lifecyle reference, you can see that the integration-test phase comes after the package phase. Therefore, when you run mvn package, Maven does not execute the integration-test phase, hence the plugin is never invoked.
If you want to invoke that phase, you can run mvn install or mvn verify (or any phase that comes after the integration-test, this phase included).
Another solution would be to specify another phase inside the configuration of the maven-invoker-plugin (like test), but I recommend that you keep the default.
Comment: I invoked both phases and no changes has been made. The output is almost the same. The included modules are not compiled (called).
Shortened output:
[INFO] Compiling 1 source file to c:\apache-maven-3.3.3\bus-core-api\target\clas
ses
Comment: May I miss something in the folders to be compiled? [INFO] No projects were selected for execution.
**I just defined pom.xml files and no java source,etc..** Can it be the cause?
Answer: Actually, I'am following the same tutorial and stucking in the same problem. After some hours surffing on the web I find this question, so I start reading  @Tunaki resources pomincludes. And now I can obtain the three jars (app-desktop-ui-1.0.jar, app-web-ui-1.0.jar and bus-core-api-1.0-SNAPSHOT.jar). To do that, first, I create a folder inside src called 'it' and inside it move app-desktop-ui and app-web-ui projects. Based on @Tinaka comments I run the commands mvn install and mvn verify then it works for both. But the output on the cli is different that is showed on tutorial.
[INFO] --- maven-invoker-plugin:2.0.0:run (build) @ bus-core-api ---
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[WARNING] Filtering of parent/child POMs is not supported without cloning the projects
[INFO] Building: app-desktop-ui\pom.xml
[INFO] ..SUCCESS (3.0 s)
[INFO] Building: app-web-ui\pom.xml
[INFO] ..SUCCESS (3.1 s)

So, I'm also new in Maven, but I think the tutorial omits some steps and also can be differences on maven implementation since the tutorial was made.

Maven using pomInclude


Is there a way to render an SVG string to an OffscreenCanvas in a web worker?

Question: I am developing a web page that does some fairly heavy processing of SVG string data. Because these strings could get to be m/bs in size I would like to move the rendering of the SVGs (browser dependant) to a worker in order to avoid blocking the UI.
My problem is that no DOM elements are accessible in workers - is there any way to draw the SVG to an OffscreenCanvas's 2D context using the SVG string alone? Or is there a way of converting the string to a data format that can be passed to the worker?
Answer: No native way yet.
Per the specs, you should be able to create an ImageBitmap from a Blob holding your SVG image even in a Worker.
In reality, no browser has implemented it, and when I talked about it with the implementers, it seems it's not on anyone's track to do so.
In Chrome you have access to the Path2D constructor, which can somehow help with <path>'s d attributes, but that's really just a very small part of rendering an SVG.
So the best will probably be to use a library for this.
Notabily, I think canvg is the most appropriate here. I don't use it myself but they're here for a long time now, and it seems the latest version does work with OffscreenCanvas in a Worker (in Chrome).
Comment: I thought I was probably pushing the limits of the web a bit. Wasn't aware of canvg - it looks interesting - can't imagine it's particularly fast, but I guess if it's off the main thread that's not a huge deal. Thanks for your help.


Solving linear equations involving many variables

Question: I know that to solve a linear equation involving $n$ variables for example, we need $n-1$ other independent equations to form a system and then solve that system. Is there a formal proof for this?
Comment: It depends on the type of equation.  Are they all linear?  Occurring over a field?
Comment: I'm talking about linear equations
Comment: The solution can only be unique , if we have at least as many equations than variables. This can be shown by looking at the poosible ranks of the coefficient matrix.
Answer: If it's a system of linear equations, then you can use Gauss-Jordan elimination to get the solutions. You can also take the determinant of the coefficient matrix first to check whether or not you'll have a single solution, infinitely many solutions, or zero solutions.
Answer: Proof: if we didn't have n equations for n unknowns, then the matrix representing the system would either be rectangular (meaning no unique solution) or have zero rows (also no unique solutions). Therefore there must be n equations for n unknowns in order for a unique solution to exist.


Generating items in ListVIew

Question: I need to generate a listview with data I have in an array
my  XAML is:
<Page.Resources>
        <DataTemplate x:Key="IconTextDataTemplate">
            <StackPanel Orientation="Horizontal" Width="220" Height="60">
                <Border Background="#66727272" Width="40" Height="40" Margin="10">
                    <Image Source="/SampleImage.png" Height="32" Width="32" Stretch="UniformToFill"/>
                </Border>
                <StackPanel Orientation="Vertical" VerticalAlignment="Center">
                    <TextBlock x:Name="Name" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis" Loaded="Name_Loaded"/>
                    <TextBlock x:Name="Description" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis" Loaded="Description_Loaded"/>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
</Page.Resources>
<ListView x:Name="IconTextGrid" Height="400" ItemTemplate="{StaticResource IconTextDataTemplate}" Grid.Row="4" Margin="40,40,40,10" HorizontalAlignment="Stretch">
                    <ListView.ItemsPanel>
                        <ItemsPanelTemplate>
                            <ItemsWrapGrid MaximumRowsOrColumns="8"/>
                        </ItemsPanelTemplate>
                    </ListView.ItemsPanel>
                </ListView>

And the C# code:
private async void SearchBox_QuerySubmitted(SearchBox sender, SearchBoxQuerySubmittedEventArgs args)
    {
        foreach (var item in results)
        {
            IconTextGrid.Items.Add("");
            nameStr = item.FirstName + " " + item.LastName;
            descriptionStr = item.Email;
        }
    }

    public T FindElementByName<T>(DependencyObject element, string sChildName) where T : FrameworkElement
    {
        T childElement = null;
        var nChildCount = VisualTreeHelper.GetChildrenCount(element);
        for (int i = 0; i < nChildCount; i++)
        {
            FrameworkElement child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;

            if (child == null)
                continue;

            if (child is T && child.Name.Equals(sChildName))
            {
                childElement = (T)child;
                break;
            }

            childElement = FindElementByName<T>(child, sChildName);

            if (childElement != null)
                break;
        }
        return childElement;
    }

    private void Name_Loaded(object sender, RoutedEventArgs e)
    {
        TextBlock Name = FindElementByName<TextBlock>(this, "Name");
        Name.Text = nameStr;
    }

    private void Description_Loaded(object sender, RoutedEventArgs e)
    {
        TextBlock Description = FindElementByName<TextBlock>(this, "Description");
        Description.Text = descriptionStr;
    }

This code should generate a list view with some items (in the array size) and put in every item the data from the cell in the array.
The problem is that only in one item I see the data from the array and in the other items there is nothing.
Wish for help, thanks
Comment: @NextInLine IconTextGrid is a listview where the results from a search are displayed in, I see the correct number of items, but only one item caontains data, the others are empty, and my question is why?
Comment: @NextInLine FindElementByName Finds the textBlocks inside the DataTemplate (They are not accessible without this function)
Comment: Ah, I missed the vertical scrollbar on your code snippet.
Answer: Your code is failing for at least one reason:
    foreach (var item in results)
    {
        IconTextGrid.Items.Add("");
        nameStr = item.FirstName + " " + item.LastName;
        descriptionStr = item.Email;
    }

you appear to be storing nameStr and descriptionStr into fields. But you are only storing the last item in results.
The good news is you can simplify and fix your code all at once. Using
    foreach (var item in results)
    {
        var nameStr = item.FirstName + " " + item.LastName;
        var descriptionStr = item.Email;
        IconTextGrid.Items.Add(new { Name = nameStr, Description = descriptionStr });
    }

That will create anonymous types with Name and Description properties for the ListView elements. You can then use:
    <DataTemplate x:Key="IconTextDataTemplate">
        <StackPanel ...>
                <Image .../>
            </Border>
            <StackPanel ...>
                <TextBlock Text="{Binding Name}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis"/>
                <TextBlock Text="{Binding Description} Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis"/>
            </StackPanel>
        </StackPanel>
    </DataTemplate>

And remove your FindElementByName, Name_Loaded, and Description_Loaded methods.

Generating items in ListVIew


size of machine 64 or 32 bit

Question: If I am working on a Unix machine, how could I know the size of the machine whether it is 64-bit or 32-bit machine?
Comment: Check the size of pointers if available in you language. Be more specific.
Answer: AIX you can do this:
getconf KERNEL_BITMODE

HP-UX you can do this:
getconf KERNEL_BITS

or just:
getconf -a | grep KERN

Sun Solaris you can do this:
isainfo -v

For Linux, yes, the uname -a should do the trick
Comment: as i am working on hp...getconf -a is not working... but getconf KERNEL_BITS is working fine.
Comment: android ? :D ... i manage to install LinuxOnAndroid (rooted device) and getconf -a | grep KERN returns nothing :( also uname -m, or arch returns armv71
Comment: These commands only show the installed kernel bit size mode. For possible CPU modes, look in `lscpu` or at [another question's answer](https://stackoverflow.com/a/246014).
Answer: You can type
uname -m

if i686 or i386 is appearing, you are working with 32 bit
if X86_64 is appearing, you are working with 64 bit
Answer: I have to deal with a lot of Unix platforms and generally the best way I have found is to look at the output of "uname -a". For example, if you see something like  "i686 i686 i386 GNU/Linux" in the output you know it's a 32 bit machine. If "amd64" shows up it's a 64. Sometimes it's a matter of trying to run a 64 bit programme. Sometimes it's RTFM.
Answer: If you're just looking to check the architecture of a machine you're on,
  %> uname -a

from the command line usually contains an indication in the output.
Answer: You can also try sizeof(int *). Should be 4 on 32 bit machines and 8 on 64 bit machines.
Comment: There's no reason why I can't target a 32-bit executable on a 64-bit computer.  Where I work, we haven't bothered changing some apps to 64 bits (although some eat memory by the gigabyte, and need to be run on 64-bit machines).
Answer: Assuming you want to do this at compile time - take a look here for architecture macros you can test. You are probably looking for __x86_64__.

size of machine 64 or 32 bit


How do you send workers to a friend on Tiny Towers?

Question: I don't know how to send workers to someone else on Tiny Towers. I sent a request to my sister but she doesn't know how to send them to me... Can someone help me out!
Comment: How do you request a bitizen?
Answer: Menu > Bitizens > Select which Bitizen to send > Select "SEND TO FRIEND"
the button is located just under the Bitizen stats area


Can I use 4 x 4 to extend the space from the wall with a tv mount?

Question: I have my 60" tv mounted on a tv mounted to the wall per the instructions.  However, I do not get enough swivel before the edge of the tv hits the wall.  So I want to attach two 4x4's from the ground up to about 6 inches higher than the top of the mount.  My plan is to attach the 4x4's to the studs in the wall and then attach the mount to the 4x4's.  And if I still need a little more space from the wall, I was going to use 2x6 across the two 4x4's and attach the mount to the 2x6's.  My guess would be that if the 4x4's are attached top, middle and bottom to the stud and with the 4x4's touching the floor, there should be no problem???
Comment: Working with 4x4 is difficult. stack out with 2x4 and 1x4 for easier fastening to the studs
Comment: Hello, and welcome to Home Improvement. @Kris is right: 4x4s are serious overkill for your needs, but if you add a diagram it could help us be more specific. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Comment: @DanielGriscom What makes you say it's "serious overkill" for a 60" TV?
Comment: @LeeSam A 4x4 post could support over three tons; how heavy do TVs get?
Comment: @DanielGriscom Actually, my book shows an 8' 4x4 can support almost 5 tons - vertically. This is for rotation. A 60" TV on a 4' moment arm is a different animal. Trying to put a lag bolt into the edge of a 2x4 with proper edge distance so it can withstand the pullout load of about 80 lbs. standing 12" off the face of the wall. (Good luck novice homeowner hitting that perfectly.)
Answer: That'd work. there are easier ways though.
If your TV mount is already mounted to studs  you could just pack your 4" or  6" of wood behind it and screw that wood to the studs then screw the mount to the wood. there's no need to have the wood extend all the way down to the floor.
I'd use 2x4s drilled half-way through with a spade bit and then screwed through the bottom of the holes to the studs with 4" chip-board or drywall screws
Answer: All that wood will weigh more than your TV. I like @Kris comment about the 2x4's. Stack two on each side, they don't need to go to the ground, just the height of the TV. Drill through them with a 5/16 or 3/8" drill and use 5" lag bolts with washers into the studs. Make sure you hit the center of the studs. you can then add your 1x4's for additional distance if needed. Good luck.


I changed the window type of an application in KDE to "Desktop". How can I get it back?

Question: This question could be rephrased to "What is the keyboard shortcut for accessing special window option in KDE?" because I cannot access them after blocking myself out. Is there a keyboard shortcut for this?
Answer: If you open "System Settings", you can open the "Window Behavior" program and see and modify all your existing window rules in the "Window Rules" tab.


Crosswalk Java to Javascript in shared mode

Question: As mentioned here and there an Android Java application may call Javascript functions using the load method from XWalkView class.
But I didn't find how to use this feature in shared mode. (as described here : https://crosswalk-project.org/documentation/getting_started/run_on_android.html#shared-vs-embedded-mode)
Is there a way to retrieve the XWalkView class ?
May Crosswalk's extensions be a solution ?
Edited : in order to better explain this problem a sample project was created : https://github.com/gbourel/SampleCWShared
So the actual issue is how to call Javascript function from the XWalkRuntimeView returned by getRuntimeView() of XWalkRuntimeActivityBase class ?
Comment: I answered here

http://stackoverflow.com/questions/24601087/crosswalk-call-js-function-from-java-on-android
Answer: Class XWalkView is in the same package with your web resources and additional java code. In Crosswalk Library, there is class XWalkViewInternal communicating with XWalkView.
Comment: I agree but my first explanation wasn't sufficiently clear : the question is how to access the XWalkView class. I just add a comment to explain this issue.
Answer: The method in runtime view has another name : the XWalkRuntimeView.loadAppFromUrl() method refers actually to the XWalkView.load() method.
Therefor calling loadAppFromUrl('javascript:anyFunction()') works as expected.


Indenting the tasks in mpp file (Ms project file) in vba (excel to mpp file)

Question: I am a VB developer working with MPP files for the first time.
My code reads data from Excel and writes to the mpp file successfully for some set of columns and rows.
1) How to select the single cell in the MPP file, because I have a scenario where I compare with next row cell and do some operation
2) Why can't we have customized  columns in mpp file (Like Computer name, Disc name etc) its giving an error
3) How to indent the cells keep one cell as master others underneath it and it should traverse through loop
code to delete the all tasks
For Each oSubTasks In oTasks
    If Not oSubTasks Is Nothing Then
        oSubTasks.Delete
    End If
Next oSubTasks

code to get the column value
For Each oSubTasks In oTasks
'if the frist row is blank
    If oSubTasks.GetField(FieldNameToFieldConstant("Duration")) = "" Then Exit For
    If oSubTasks.GetField(FieldNameToFieldConstant("Duration")) <> "" Then
         Mpplastrow = Mpplastrow + 1
    End If
Next oSubTasks

code for customized column getting error
If oSubTasks.GetField(FieldNameToFieldConstant("computer name")) = sh1.Cells(rw, primecol).Value Then
'    oTask.SetField FieldID:=oApp.FieldNameToFieldConstant("computer name"), Value:=sh1.Cells(rw, primecol).Value
'Else
'    oTask.SetField FieldID:=oApp.FieldNameToFieldConstant("computer name"), Value:=sh1.Cells(rw, primecol).Value
'End If

Comment: have you read my answer and code below ? did you mean something like that ?
Answer: To read the Indent level of each MSP tasks, and to be able to Indent inside (or outside), try something like the code below:
Option Explicit

Sub IndentTasks()

Dim Tsk As Task

For Each Tsk In ThisProject.Tasks
    Select Case Tsk.OutlineLevel '<-- read the current taks Outline Level
        Case 1
            If Tsk.ID <> 1 Then
                Tsk.OutlineIndent '<-- indent inside (to the right)
            End If

        Case Is > 6 '<-- don;t want your Project to be too indented inside
            Tsk.OutlineOutdent '<-- indent outside (to the left)

    End Select
Next Tsk

End Sub

Comment: Thank you Shai Rado, it was very help full.
Comment: to add, how can i get the column names and value of the columns fields.


xbrl into google spreadsheets using google script

Question: Can anybody show me how to get XBRL data into google spreadsheets using google script?
http://www.fossil.com/attachments/en_US/financials/2013/fosl-20130330.xml
here is the link.
function XBRLexplore() {
  var target = "http://www.fossil.com/attachments/en_US/financials/2013/fosl-20130330.xml";
  var pageTxt = UrlFetchApp.fetch(target).getContentText();
  var pageDoc = Xml.parse(pageTxt,true);

//var temp=getDivById( pageDoc.getElement(), 'Tag204' );
//var temp=getElementById('Tag204')
}

I can't seem to get to "tag204" the first element. not sure how to use the get by id functions correctly.
Comment: What have you tried ? It would help if you post some code of your attempt and seek help on a specific problem you are facing rather than ask "give me the code"
Comment: ha. I would but I don't know how. that's why I'm asking. I just need some starting code. Like what this guy provided here. You can see from my previous posts that I do include what code i have. http://stackoverflow.com/questions/14805527/grabbing-table-from-html-using-google-script
Comment: https://developers.google.com/apps-script/reference/xml-service/ provides a start for you
Comment: @DavidF. ok thanks. I just want the first element. It has a "Tag204" for ID. How do i grab that? i've tried the code above.
Answer: Look at previous questions about parsing XML documents, since XBRL is an application of XML using a standardized taxonomy of business terms. (Remember - HTML documents are XML with tag, or element, types specific to web page design.)
For example, this answer shows some very basic navigation of xml elements. And you should recall this one that explained it in greater detail.
The same techniques apply, but with element types such as AntidilutiveSecuritiesExcludedFromComputationOfEarningsPerShareAmount (The element containing id="Tag204" is one of these.)
<us-gaap:AntidilutiveSecuritiesExcludedFromComputationOfEarningsPerShareAmount id="Tag204" decimals="0" contextRef="D2013Q1" unitRef="Shares">201000</us-gaap:AntidilutiveSecuritiesExcludedFromComputationOfEarningsPerShareAmount>

The XML element name consists of two parts, a required name prefixed by an optional namespace. In this case, the namespace is us-gaap, which tells us the vocabulary source.
Here's how you could get that one element, using the getElementByVal() utility introduced in this answer, and write it to a spreadsheet:
function xbrl() {
  var target = "http://www.fossil.com/attachments/en_US/financials/2013/fosl-20130330.xml";
  var pageTxt = UrlFetchApp.fetch(target).getContentText();
  var xbrl = Xml.parse(pageTxt,true).getElement();

  var Tag204 =
      getElementByVal( xbrl,
                      'AntidilutiveSecuritiesExcludedFromComputationOfEarningsPerShareAmount',
                      'id',
                      'Tag204' );

  var data = [];
  var row = [];
  var name = Tag204.getName().getLocalName();
  row.push(name);
  var attributes = Tag204.getAttributes();
  for (var j=0; j<attributes.length; j++) {
    row.push(attributes[j].toXmlString())
  }
  data.push(row);

  var sheetId = '---Sheet-Id---';
  var sheet = SpreadsheetApp.openById(sheetId).getSheetByName("XBRL");
  sheet.getRange(1,1,data.length,data[0].length).setValues(data);
}

Comment: SOAP is a protocol for exchanging objects (using XML), Javascript is a programming language. You can work with SOAP using Javascript, certainly.
Comment: If I wanted to retrieve all of the data into a google spreadsheet, what's the best way to do it? I'm learning about SOAP, should I use that? or is javascript good enough?
Comment: can you show me a few lines of code to get all the data? I can do the spreadsheet part. I think I can handle that now. I just need a way to most efficiently get the data into a format that I can place into the spreadsheet.
Comment: What I'm essentially trying to do is drop all of the "us-gaap" related elements in one sheet, while dropping all of the "fosl:" elements in another sheet. If you show me how to do one, I can do the other.
Comment: I've flatten the structure. But I'm having trouble with the namespace and local name. quick pointer on how to do it would be appreciated. http://stackoverflow.com/questions/18040867/google-script-xml-get-parent


Derive PropertyGrid dropdown list from property that is an object class, not just a string

Question: How do I have properties which are objects (not just a string) dropdown in property grid? I got so far, but then got stuck! Consider the code below:
Public Class mOrganisation

    Public Property ID as String
    Public Property Name as String

End Class

Public Class mSystem

    Public Property ID as string
    Public Property Name as String
    Public Property Developer as mOrganisation

     Public Overrides Function ToString() As String
        Return Name
    End Function

End Class

Public Class mGame

    Public Property ID as string
    Public Property Name as String

    <TypeConverter(GetType(SystemConverter))>
    Public Property System as mSystem

End Class

Public Class Main

    Public Systems as List(of mSystem) = [...list gatehring code here]

End Class

Public Class SystemConverter
Inherits TypeConverter

    Public Overrides Function GetStandardValuesSupported(ByVal context As ITypeDescriptorContext) As Boolean
        Return True
    End Function

    Public Overrides Function GetStandardValuesExclusive(ByVal context As ITypeDescriptorContext) As Boolean
        Return False
    End Function

    Public Overrides Function GetStandardValues(ByVal context As ITypeDescriptorContext) As TypeConverter.StandardValuesCollection
        Return New StandardValuesCollection(Main.Systems)
    End Function

End Class

mOrgnisation is there just to introduce some complication to the mSystem Class. Now this code does drop down the values:

But when I select a value, I get a PropertyGrid error "Object of type 'System.String' cannot be converted to type 'mSystem'"
This had led me down a rabbit hole, particularly trying to apply various permutations of Convert From and Convert To. However, I couldn't find a decent solution. One attempt via ConvertFrom had the drop down menu loading very slowly, one item at a time (I think it was being fired for each and every item).
I would make a custom UITypeEditor but I can't find a way to get the PropertyGrid inherent resize method/handle like on the standard dropdown (and tried coding my own resize routine, but proved sticky and flickery I think because of the interaction of PropGrid + the control)
What is the best/most elegant way to achieve this?
Answer: There are some ways to to tell system "What to pick from object"
1) Use DisplayMemberPath on the ComboBox:
<ComboBox ItemsSource="{Binding Path=mSystem}"
      DisplayMemberPath="Name"/>

2) Set ItemTemplate on the ComboBox. This is like #1, except allows you to define a template to display:
<ComboBox ItemsSource="{Binding Path=mSystem}">
<ComboBox.ItemTemplate>
    <DataTemplate>
        <Border BorderBrush="Green" BorderThickness="1" Padding="5">
            <TextBlock Text="{Binding Path=Name,StringFormat='Name: {0}'}" />
        </Border>
    </DataTemplate>
</ComboBox.ItemTemplate>

3) Add a DataTemplate to the XAML resources. This is useful for associating a given class:
<UserControl xmlns:local="CLASS_CONTEXT_HERE">
<UserControl.Resources>
    <DataTemplate DataType="local:mSystem">
        <TextBlock Text="{Binding Name}" />
    </DataTemplate>
</UserControl.Resources>

4)If you want to display NAME and ID :
Public Overrides Function ToString() As String
    Return string.Format("{0} ({1})", Name, ID)
End Function

Comment: Thanks for taking the time to construct this answer SHoaib. It'll prove useful for WPF scenarios. My fault - didn't mention I'm on winforms + found my own answer eventually. Thanks, though.
Answer: Eventually ditched TypeConverter and found a solution. Like most coding nightmares, it was 5 simple lines put in exactly the right place! The key was accessing the PropertyGrid built-in resize handle. You can adjust the code below to include building in handling custom objects, as value is any object. However, example below is a string, for simplicity:
Public Overrides ReadOnly Property IsDropDownResizable As Boolean
    Get
        Return True
    End Get
End Property

Here's how to achieve:
Step 1: Create a new UITypeEditor
This interfaces the property to the custom editor. value contains the value passed from the property. It can be of any object type. You can therefore pass this to your custom control to inform any editing functions therein.
Create a new class:
Imports System.ComponentModel
Imports System.Drawing.Design
Imports System.Windows.Forms.Design

Public Class TestUIEditor
    Inherits UITypeEditor

    ' Indicate that we display a dropdown.
    Public Overrides Function GetEditStyle(ByVal context As ITypeDescriptorContext) _
        As UITypeEditorEditStyle

        Return UITypeEditorEditStyle.DropDown

    End Function

    Public Overrides Function EditValue(ByVal context As ITypeDescriptorContext, ByVal provider As IServiceProvider, ByVal value As Object) As Object

        ' Get an IWindowsFormsEditorService object.
        Dim editor_service As IWindowsFormsEditorService = CType(provider.GetService(GetType(IWindowsFormsEditorService)), IWindowsFormsEditorService)
        If editor_service Is Nothing Then
            Return MyBase.EditValue(context, provider, value)
        End If

        'Setup the editor
        Dim editorService As IWindowsFormsEditorService = Nothing
        If provider IsNot Nothing Then
            editorService = TryCast(provider.GetService(GetType(IWindowsFormsEditorService)), IWindowsFormsEditorService)
        End If

        If editorService IsNot Nothing Then

            Dim testUI As New TestPropGridUI(editorService)
            'Populate the existing value to the dropdown control
            testUI.Text = value
            'Drop down the control
            editorService.DropDownControl(testUI)
            'Update property value once dropdown closed
            value = testUI.Text

        End If

        Return value

    End Function

    Public Overrides ReadOnly Property IsDropDownResizable As Boolean
        Get
            'Ensures control is resizable
            Return True
        End Get
    End Property

End Class

Step 2: Create your custom editor:
In this example, I have just used a custom class that inherits TextBox . However, you can use any controls, even a custom  UserControl.
Imports System.Windows.Forms.Design

Public Class TestPropGridUI
    Inherits TextBox

    ' The editor service displaying this control.
    Private m_EditorService As IWindowsFormsEditorService

    Public Sub New(ByVal editor_service As IWindowsFormsEditorService)
        MyBase.New()

        m_EditorService = editor_service
        Dock = DockStyle.Fill

    End Sub

    Public Sub returnPressed(sender As Object, e As KeyEventArgs) Handles Me.KeyDown

        'Closes the dropdown when Enter pressed
        If e.KeyCode = Keys.Enter Then
            m_EditorService.CloseDropDown()
        End If

    End Sub

End Class

Note m_EditorService.CloseDropDown . Put this wherever you want the dropdown to close itself (e.g. after a value selection).
Step 3: Tell your class property to use the custom editor:
Public Class TestObject

    Public Property ID as String
    Public Property Quantity as Integer

    <Editor(GetType(TestUIEditor), GetType(UITypeEditor))>
    Public Property TestText As String

End Class

And that's it!


c# linear regression given 2 sets of data

Question: I have 2 sets of data - one is an average position and the other a score so for every position, i have the predicted score of an item -
double[] positions = {0.1,0.2,0.3,0.45,0.46,...};
double[] scores = {1,1.2,1.5,2.2,3.4,...};

I need to create a function that predicts the score for average position, so given a new item with position 1.7.
I under stand the function should be something like y=a*x + b but how do i get to it?
Any help will be appreciated!
Answer: Yes, you have to build a linear function
  y = a * x + b

in order to do this you have to compute the sums (x is predictor's values and y - is corresponding results):
 sx  - sum of x's
 sxx - sum of x * x
 sy  - sum of y's
 sxy - sum of x * y

So
 a = (N * sxy - sx * sy) / (N * sxx - sx * sx);
 b = (sy - a * sx) / N;

Comment: Thanks Dmitry! If i want a logarithmic regression i simply add log to the equation? so its y = a * log(x) + b
Comment: @Chen: if you want to *fit* `y` into `y = a * log(x) + b` then, yes, just take *logarithms* (just use `log(x)` instead of `x`).


Modding Morrowind

Question: First of all, this is not the same of this question.
I finally decided to buy Morrowind, even against all my personal opinions about old graphics games so in order to minimize this I'm researching, without success so far, about mods.
My question is, plain and simple, what is the proper way to install and manage Morrowind mods?
Maybe due its age, I'm having serious difficulty in finding good and detailed articles (with screenshot, preferably) about this matter. Not like I'm expecting to find something like S.T.E.P. for Skyrim, but, you know.
I already found some mods recommendations and so but I haven't found yet a detailed guide on how exactly apply them. I've gather informations, though. Informations that said modding Morrowind is "old-school style", which means, manually.
It seems there is no "Mod Organizer" for Morrowind, that keeps the install directory clean, but I would really like to know that there is something better than Nexus Mod Manager.
Comment: Reading both this question and the linked one, it honestly does seem like you're asking the same thing.  Why isn't it a dupe?
Comment: This does seem like a duplicate, and the answer to your question would be the Nexus Mod Manager. It's a great manager for mods for all different kinds of games and it makes installing and managing them really easy.
Comment: Well... it is disputable, but imo this question feels like "what other thing except the Nexsus MM can I use" while the other feels like" how do I make Nexsus MM work properly".
Comment: iirc the something awful forums has a good topic on modding morrowind, with a lot of info in the first post. Sadly SA periodically closes its forums to outside (non paying) viewers. Today is one of those days. And, you might need the archives upgrade to see it. (Full disclosure, im not a goon (goon = user of SA)).
Comment: I don't need exactly a personal opinion, mainly because such kind of topics are usually cannon-fired quickly. I just need a reliable, and for god's sakes well written, source of information. @Ids: I didn't understand a word of what you said. O_O
Comment: There is a website, something awful (http://forums.somethingawful.com/forumdisplay.php?forumid=44) that site has forums, and part of the forum is about games. They have pretty good guides usually about modding open world rpgs. (Like morrowind, oblivion, fallout etc). So I would look there.
Comment: Sadly something awful (SA for short), is a site where you need to pay to post on the forums. And some times you even need to pay to read certain subjects. (You get a vague message, and some sort of annoying movie clip with a kid and a window, etc). To read old posts (archived) you need to pay even more. So, if the morrowind topic has been archived you cannot read it. Is this a bit more clear?
Comment: http://forums.somethingawful.com/showthread.php?threadid=3430891 try this link. (currently it is not working for me, it redirects me to 'buy a forum account'. But in a few days it will work again for me). SA has a kind of bad reputation. (Like 4chan) but their game guides are usually well written. And a lot of the guides on modding are also not bad. So I hope that helps.
Comment: There are mod managers. Wrye Mash is probably the best and cleanest, but it has a steep learning curve.
Comment: Should the title be "Adding mods to Morrowind"? I thought you were implying you wanted to personally mod Morrowind yourself.
Comment: WHat you linked is a duplicate. Frank should flag this as duplicate.
Answer: Wrye Mash is a very, very powerful modding and game tweaking tool I've used myself when I used to mod Morrowind a lot. It let's you modify your saves, it can try to repair your savegames if something is broken and so forth.
It's not like Mod Organizer for Skyrim, so you can't keep your data files clean (It's been a while since I used it, there might be a way to do it nowadays.) but it is by far the best mod manager for Morrowind.
It does take a while to learn, since it's a bit complex.

Modding Morrowind


Can't resolve all parameters for Class: (?) although it has been provided

Question: I'm currently writing some test cases for services which are using ngxs for state management. I can't seem to figure out what's wrong with the code below:
// auth.service.ts
@Injectable({
    providedIn: 'root'
})
export class AuthService {
    @Select(SessionState) session$;
    constructor(private http: HttpClient, private store: Store) {
    }
}

// session.state.ts
export interface SessionStateModel {
    user: User | null;
    token: string | null;
    state: 'authenticated' | 'guest' | 'invalid.credentials' | 'error' | 'pending';
    response?: HttpErrorResponse | string | any;
}

export const defaultSessionState: SessionStateModel = {
    user: null,
    token: null,
    state: 'guest',
    response: null
};

@State<SessionStateModel>({
    name: 'session',
    defaults: defaultSessionState
})
export class SessionState {
    constructor(private auth: AuthService) {
    }
}

// session.state.spec.ts
describe('should handle login, logout and errors properly', () => {
    let store: Store;
    let backend: HttpTestingController;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule,
                NgxsModule.forRoot([SessionState])
            ],
            providers: [
                AuthService
            ]
        });

        backend = TestBed.get(HttpTestingController);
        store = TestBed.get(Store);
    });

    afterEach(() => {
        // After every test, assert that there are no more pending requests.
        backend.verify();
    });

    it('should handle successful login', () => {
        // oversimplified...
        expect(true).toBe(true);
    });
});

When I run this with ng test, karma returns the following exception:
Error: Can't resolve all parameters for SessionState: (?).
This doesn't make any sense to me because I'm already providing what's necessary for the SessionState (which is the AuthService) in the TestBed.configureTestingModule. I can't seem to figure out what am I missing here?
Answer: At the time of this answer, ngxs does not work with Ivy if a state class has injected dependencies (but see edit below). You can turn off Ivy by setting the following compiler option in tsconfig.json:
{
  "angularCompilerOptions": {
    "enableIvy": false
  }
}

Edit: Ngxs provides a migration guide for Ivy. Following this guide, you need to add the @Injectable decorator in addition to your @State decorator:
@State<SessionStateModel>({
    name: 'session',
    defaults: defaultSessionState
})
@Injectable()
export class SessionState {
    constructor(private auth: AuthService) {
    }
}

Comment: Thanks for your answer. At the time of my question I was not using Ivy, but will have it in mind when I'm upgrading to 9! :)
Answer: Probably you are missing @Injectable() for SessionState service. This could throw the error as well.
@Injectable()
export class SessionState {
    constructor(private auth: AuthService) {
    }
}

Comment: That's what I initially though as well, but it's not the case. The problem is that the `AuthService` is not being injected in the `SessionState` class - not the other way around and the `AuthService` has an `Injectable` decorator.


Vuejs Datepicker enable a disabled element

Question: I have 2 instances of the <date-picker>, in which the first captures the start date (starts_at) and the second captures the end date (ends_at).
As per the design I have in mind, I would like to disable the ends_at instance and then re-enable it once the starts_at has been applied.
This is my starts_at instance:
<date-picker v-model="starts_at" @input="enableEndsAt()" valueType="format"></date-picker>

This is my ends_at instance:
<date-picker id="endsAt" v-model="ends_at" disabled @input="checkDate()" valueType="format"></date-picker>

This is what I have tried so far. When you change the input, it calls the enableEndsAt() function, which looks like this:
enableEndsAt(){
  if(this.starts_at === "") {
    return
  }
  var element = document.querySelector('#endsAt')
  element.removeAttribute('disabled')
  console.log(element)
}

Comment: Is date-picker our own custom component, or are you using external component libraries?
Answer: You can use disabled as a reactive property:
<date-picker id="endsAt"
     v-model="ends_at"
     :disabled="disableDatePicker"
     @input="checkDate()"
     valueType="format"></date-picker>

So, to use this, you could create a property disableDatePicker in your data declaration, and then set it inside your method:
data(){ return { disableDatePicker: false }},
...
methods: { ....
enableEndsAt(){
  if(this.starts_at === "") {
    return
  }
  this.disableDatePicker = true;
}

Comment: Thanks, worked like a charm, waiting for 6 minutes so that I can mark is as correct!
Comment: Great. Glad it helped!
Answer: Assuming your <date-picker> can accept disabled property, you can simply bind it to a condition:
<date-picker id="endsAt" v-model="ends_at" :disabled="this.starts_at === ''" @input="checkDate()" valueType="format"></date-picker>

so you don't need to put @input="enableEndsAt()" on your starts_at date picker, and you don't need enableEndsAt() function


Where to aim with the grappling hook?

Question: If I use the grappling hook and aim at a ledge of a building there is a 50/50 chance that "Crane" (the guy you play) won't climb up but will fall down instead.

Where exactly do I have to aim so that he will definitely climb up the ledge?
Do I have to hold or keep clicking the climb button so that he might catch himself on another ledge on his way down?
Is this normal or just a kind of bug?
Comment: It is sometimes fiddly like that, I keep pressing space in the hopes he catches on, but that doesn't happen as often as I would like :p. Best way to check is to mouse over the target, if you see the square snap on to a ledge then you'll be able to climb it.
Answer: There is no absolutely guaranteed way to shoot the hook.
No matter what you do, it seems that sometimes Crane just is not willing to grab onto ledges after using the hook. But there are a few things you can do to improve your chances:

When aiming the hook at a ledge, there will come a point where it snaps to the ledge and the white dot in the center disappears. This offers your best chance of grappling, and Crane will almost always pull himself up the ledge if this happens.
Hold space as you approach the ledge so that if you hit it and begin to fall, there's a chance you'll grab it on the way down and pull yourself up anyway.
Aim for part of the ledge with nothing right above it, such as cars, zombies, etc. I've noticed my chances seem to be much better in those situations.
Avoid ledges which are very close to out-of-bounds areas. Avoid rock ledges (such as near the Infamy Bridge, or Alexei's radio antenna) completely unless you're okay with falling from them. I've noticed I fall off of these ledges far more often than other types, probably because they're not a simple flat line like others.
Backup plan: choose a part of the ledge where falling would be safe. Areas with something to land on, or at least less zombies than the other choices, are a good pick.
If you're a high enough Agility level to have the Forward Roll skill, be ready to press the crouch button in case you miss.

You will still fall some small percentage of the time following these tips, but you should be able to die less often, which will make the misses much less frustrating.

Where to aim with the grappling hook?


Windows Forms C#: Resize Label image on runtime when resizing the label

Question: This is my issue:
I add labels to a form programmatically, including some properties to resize them on runtime by clicking and dragging them with the mouse right click event.
My situation is, that I add a label programmatically containing an image from a given file through OpenDialog, and I would like to resize this image to fill the label size as I stretch the label. Unfortunately, I cannot set the size on runtime by accessing the image.Size  property in the label, since it's read only... any ideas?
This is the affected piece of code:
Point _oldPosition;
public static Label _ctrlActiveControl;

if (e.Button == MouseButtons.Right)
{
    _ctrlActiveControl.Cursor = Cursors.SizeNWSE;

    //Code to resize the control based on the mouse position
    Point newPosition = new Point(e.X, e.Y);
   _ctrlActiveControl.Width += (newPosition.X - _oldPosition.X);
   _ctrlActiveControl.Height += (newPosition.Y - _oldPosition.Y);

    //Some security to make sure I don't shrink the control too much
    if (_ctrlActiveControl.Width < 10) _ctrlActiveControl.Width = 10;
    if (_ctrlActiveControl.Height < 10) _ctrlActiveControl.Height = 10;

    //Here I check if the label contains an image and, if so, I should resize
    //The image to "Autofill" the label
    if (_ctrlActiveControl.Image != null)
    {
      Image image = _ctrlActiveControl.Image;
      image.Size = new Size(_ctrlActiveControl.Width, _ctrlActiveControl.Height);
    }

    _oldPosition = newPosition;
}

I wonder if there's any way to do this, or should I instead use other control type (I know I can use others, but I'd like to know if there's any available workaround before adding more variables).
Comment: You are trying to change the Image size thus you could find some useful examples here http://stackoverflow.com/questions/1922040/resize-an-image-c-sharp but I think you should use a PictureBox for this task not a label
Comment: The PictureBox has a property for SizeMode which can be set to Stretch or Zoom which would do what you want automatically.
Comment: That's the point... if it were a PicBox it'd be much easier. Problem is that later on in code I make quite some stuff with a list of the labels created, and I would like to keep the properties standarised so I can cope with one object type instead of too many, in terms of their null values mainly...
Answer: You can convert it to a Bitmap and redraw it with Graphics. Then replace the old image with the newly created one. I don't know if this is viable performance-wise, but I guess it could be worth a shot.
Bitmap newImage = new Bitmap(_ctrlActiveControl.Width, _ctrlActiveControl.Height);
using (Bitmap bm = new Bitmap(_ctrlActiveControl.Image))
{
    using (Graphics g = Graphics.FromImage(newImage))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        Point[] corners = { new Point(0, 0), new Point(newImage.Width, 0), new Point(0, newImage.Height) };
        g.DrawImage(bm, corners);
    }
}
_ctrlActiveControl.Image = newImage;

You'll need usings for System.Drawing and System.Drawing.Drawing2D.
Comment: Thanks Hjalmar. I also had problems with Graphics since object is in a child panel from another panel... long story short, Graphics DrawImage method was also another issue since the object would disappear and I didn't want to multply my issues... Thanks for the tip though!
Comment: Haha. Well the whole idea is to make some customized, simple to use report designer. Users click here and there to add images, literal text, system data etc., as well as fields in an SQL query so they create a template. Once the template is done, I store all labels with properties in an XML file to be used for different purposes. Since most of the objects are labels, I wanted to (if possible) always used this type of object to keep it simple.
Answer: As per Steve's recommendation, I have substituted
if (_ctrlActiveControl.Image != null)
{
  Image image = _ctrlActiveControl.Image;
  image.Size = new Size(_ctrlActiveControl.Width, _ctrlActiveControl.Height);
}

and wrote instead:
if (_ctrlActiveControl.Image != null)
{
     _ctrlActiveControl.Image = ResizeImage(_ctrlActiveControl.Image, _ctrlActiveControl.Width, _ctrlActiveControl.Height);
}

.....

public static Bitmap ResizeImage(Image image, int width, int height)
{
    var destRect = new Rectangle(0, 0, width, height);
    var destImage = new Bitmap(width, height);

    destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    using (var graphics = Graphics.FromImage(destImage))
    {
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        using (var wrapMode = new ImageAttributes())
        {
            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
            graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
            graphics.Dispose();
        }
    }

    return destImage;
}

If you play too much with the label by stretching and shrinking, it will become useless (image quality will degrade if the label is too small and then we try to re - enlarge the label). However, as a start point it could work. I could recode to reference the file directly as per the image source so I get always a fresh file... Thanks for the tip.


How to POST multiple images to FastAPI server using Python requests?

Question: I would like to send multiple images to FastAPI backend using Python requests.
Server side
from fastapi import FastAPI, UploadFile, File
from typing import List
app = FastAPI()

@app.post("/")
def index(file: List[UploadFile] = File(...)):
    list_image = []
    for i in file:
        list_image.append(i.filename)
    return {"list_image": list_image}

Client side
Currently, I can only send a request with a single image. However, I would like to be able to send multiple images.
import requests
import cv2

frame = cv2.imread("../image/3.png")
imencoded = cv2.imencode(".jpg", frame)[1]
file = {'file': ('image.jpg', imencoded.tostring(),
                    'image/jpeg', {'Expires': '0'})}

response = requests.post("http://127.0.0.1:8000/", files=file)

Answer: You would need to pass the files/images as shown in the example below. See here and here and here for more details.
Example
import requests

url = 'http://127.0.0.1:8000/'
files = [('file', open('images/1.png', 'rb')), ('file', open('images/2.png', 'rb'))]
resp = requests.post(url=url, files=files)

or, you could also use:
import requests
import glob

path = glob.glob("images/*", recursive=True) # images' path
files = [('file', open(img, 'rb')) for img in path]
url = 'http://127.0.0.1:8000/'
resp = requests.post(url=url, files=files)


Java Program throws NullPointerException

Question: I'm trying to write a program to create a media object, I created the Cassette class which inherits from Audio which inherits from Media. I'm getting a null pointer exception and I have been trying for hours to fix it but I have no idea why it's being thrown. I appreciate your help in advance, thank you.
In my application class I initiate the following:
static Media[] collection = new Media[100];
And later on in the code I try to create a new Cassette object but it gives me the said null pointer exception.
The code I have is:
  collection[collection[0].getNumItems()] = new Cassette(cTitle, cMajorArtist, cPlayingTime, cNumPlays, cNumGroupMembers, cGroupMembers, pArtist, cNumSongs, cSongs);

All of the items being passed into the Cassette are all user input data.  It compiles fine but it's just when I run it that I get an error.
EDIT
Here is the numItems value in my media class.
static int numItems = 0;
And the method to return the number of items:
public int getNumItems()
   {
      return numItems;
   }

Thanks.
Comment: What do you think `collection[0]` should be and why do you think so?
Comment: What value do you think it has and why do you think so?
Comment: It's being used to get the number of items and creating a new Cassette
Comment: It should give me 0 because that's the value that `numItems` has in my Media class.  And I looked at an example from someone close to me and that's what they had in their piece of code which worked.
Answer: I suggest you use a Collection like ArrayList. With the diamond operator that would look something like,
static List<Media> collection = new ArrayList<>();

Then you can use List#add(E)
collection.add(new Cassette(cTitle, cMajorArtist, cPlayingTime,
    cNumPlays, cNumGroupMembers, cGroupMembers, pArtist, cNumSongs, cSongs));

Edit If you want to use the array type, then this
collection[collection[0].getNumItems()]

Should be
collection[Media.getNumItems()]

To call the static getNumItems() in Media. Which should be
public static int getNumItems()
{
  return numItems;
}

Comment: Thank you for the array answer, it saved me from having to rewrite my code.  It did the trick! Thank you!


Safe way to terminate exposed electrical during remodel?

Question: I have a few exposed electrical wires that were cut in order to remove wiring in the area being remodeled. Is there a safe alternative to terminating all these points inside boxes? I need them safely capped off with wire nuts for about 3 months, and adding boxes seems overkill.
Maybe I'm just wishing there was some sort of product that was a bit lighter duty for short-term applications. Before I go buy a bunch of boxes and spend a good number of hours, I just want to be sure I couldn't get away with something simpler. Any ideas?
Comment: I take it you're trying to childproof this, since otherwise wire nuts -- plus electrical tape if you want. Or need additional protection -- would be an adequate solution.
Answer: I would also do wire nuts with electrical tape if I knew who was working in the area and they were competent.
The boxes you put your wires into don't need to be mounted anywhere. They can just be hanging around. But yes I understand cost and driving to get the boxes and covers can be a nuisance.
I know some people like to wire nut the hot and neutral together. That way if somebody turned the breaker on by accident, they would short out and not electrocute anybody. Again that would be wire nut and tape...
Comment: They *should* short out and not electrocute anybody.  If you're unlucky, the breaker isn't up to snuff, and they short out and start a fire.
Comment: Never thought of it that way.


Getting MFC DIalog close reason

Question: What is the MFC equivalent of System.Windows.Forms.CloseReason for a CDialog?
How to capture FormClosing event in MFC CDialog?
Answer: There is no way to distinguish the reason that closed a Dialog, after it is closed.
When I look at the list of CloseReasons most of the reasons create different Messages (like shutdown). The only way I see is to implement message handler for the events/situations that are important for you.
Note: That some of the CloseReasons don't make sense for a modal Dialog in an MFC application (like FormOwnerClosing)...
Answer: CDialog::DoModal returns a value, depending on how it is closed (could be IDOK, IDCANCEL or other value - see this reference: http://msdn.microsoft.com/en-us/library/619z63f5%28v=vs.90%29.aspx).
You can use various messages from the dialog to tell when it is closing - OnCancel (http://msdn.microsoft.com/en-us/library/kw3wtttf%28v=vs.90%29.aspx) or OnOK (http://msdn.microsoft.com/en-us/library/66b3y2ab%28v=vs.90%29.aspx) being a couple of the more interesting ones.
Comment: This does not help. I kill it via task manager, press ESC key, press cancel button. All of these give me return code 2. I cannot distinguish.

Getting MFC DIalog close reason


find ip address using hostname

Question: I have two linux servers and i'm trying to access them remotely. I know the ip of the first server but i forgot the ip of the other one.
I'm trying to use nslookup, I did
nslookup server2

and the output was:
Server:         192.168.2.1
Address:        192.168.2.1#53

Non-authoritative answer:
Name:   server2
Address: 18.104.22.168

and then i tried to use it again but with server1 and I got the same output...
Anyway, why is the output the same for both server? is nslookup the better option to find out the ip of the other linux server that i have? What other option can I use?
Comment: What protocol are you using to access the remote server..all common protocols allow both hostname and IP addresses to access them..also `server1`, `server2` are not FQDN and the response is coming from `192.168.2.1`..use `nslookup server2.whatever.com 220.127.116.11` to check from Google's DNS, replace `whatever.com` with the actual domain name..
Comment: how can i know what the domain name is?
Comment: does server1 and server2 have the same doman name ? if so use `nslookup IP_of_server1 220.127.116.11` and you should get the domain name if it has one entered..
Comment: i only got this output
Server:         188.8.131.52
Address:        18.104.22.168#53

** server can't find 188.8.131.52.in-addr.arpa: NXDOMAIN
Comment: that means it is not configured in the zone file..by the way it seems you have run `nslookup 220.127.116.11 126.96.36.199` that means the IP of server1 is `22.214.171.124` and hence the IP of server2 should be `18.104.22.168` ..right ?
Comment: To facilitate accessing servers, domain names are usually assigned and added to appropriate domain zones. Sure, you can access some servers by IP as well, but you have to remember their IPs then and embed them into links/commands. It is a responsibility of a box's administrator to know its IP and conduct all related maintenance.
Answer: Try using ping instead:
$ ping server2

nslookup and ping use different techniques for name resolution.
An in-depth explanation for this can be found here:
http://cbfive.com/ping-vs-nslookup/
Comment: i also tried that but its taking too long to ping

find ip address using hostname


Error with 'import xlwt' and 'import xlrd' in Python 2.7 after installation with anaconda

Question: I want to create xls and for that I installed xlwt and xlrd modules with easy_install xlwt.
But every installation, is related to C:\Anaconda and not to C:\python27. Maybe thats why:

Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import xlwt

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import xlwt
ImportError: No module named xlwt
>>>

How can I install in C:python27? Or isn't it the problem?
Answer: Anaconda is first on your PATH, so when you run easy_install it uses the one in the Anaconda directory. If you use the one in the C:\Python27 directory it will install it there.


What is the cubic foot capacity of my Maytag washing machine?

Question: My washing machine is over 21 years old.
I am going to buy a new one with a larger   capacity but I don't know the cubic ft capacity of mine.
It is  a Maytag MAV6057AWW.
Answer: From a  Google search   this website says, about 2.9 cu.ft.
As Ed Beal suggested,  the washer is listed as being 3.1 cu.ft. but usable size is 2.9.  Added in case link is not read or works.
Comment: Since the link states that that model is 3.1 cu ft you should suggest searching for one larger than that. All manufactures play the same games with actual size vs usable size of 2.9 in that answer. If the op got a 3.1 thinking it would be larger and ended up with the same size it would not be a very good answer based on that link alone. Revise for the larger size and it would be worth an up vote.


Limit of $\lim \limits_{x \to 0} \frac{\sin(5x)}{\sin(4x)}$

Question: I was trying to solve this problem, but couldn't figure it out. The solution goes like this:

I don't understand the first step. Why is the limit multiplied by $\frac{4x}{5x}$? and $\frac{5}{4}$ ?
Comment: It is a clever way of writing $1$: $$1 = 1\cdot1\cdot1= {4\over4}\cdot{5\over5}\cdot{x\over x} = {4x\over 4} \cdot {5\over 5x} = {4x\over5x} \cdot {5\over 4}.$$ When you multiply by $1$, you don't change the original expression, but doing so allows us to make some algebraic manipulations that help us involve other identities. Namely: $$\lim_{x\to0}{\sin x\over x} = 1$$
Comment: Thanks a lot! It was hard for me to see that.
Answer: Alternatively, you could use L'Hopital's rule:
$\lim \limits_{x \to 0} \frac{\sin(5x)}{\sin(4x)}$=$\lim \limits_{x \to 0} \frac{\frac{d}{dx}\sin(5x)}{\frac{d}{dx}\sin(4x)}$=$\lim \limits_{x \to 0} \frac{5\cos(5x)}{4\cos(4x)}=\frac{5}{4}$
Comment: This is correct, but L'Hopital's Rule may be a tool not within OP's reach yet.
Comment: This is incorrect according to Wikipedia, since the derivative of $\sin(x)$ is computed using  L'Hopital's rule, so you've essentially fallen into a chicken-egg paradox.
Comment: @barakmanos what do you mean?
Comment: @StephanCasey: I'm trying to find the Wikipedia page which describes this oxymoron...
Comment: @StephanCasey: Sorry, I am unable to find the English version of this Wikipedia page. Perhaps it is wrong, but it says that if you're using the geometric definition of Sine, then in order to prove that the derivative of $\sin(x)$ is $\cos(x)$, you need to rely on the fact that $\lim\limits_{x\to0}\frac{\sin(x)}{x}=1$. Hence, any attempt to prove that $\lim\limits_{x\to0}\frac{\sin(x)}{x}=1$ by relying on the fact that the derivative of $\sin(x)$ is $\cos(x)$ is essentially a chicken-egg paradox.
Comment: @barakmanos but we are not trying to prove that with the L'Hopitals method. We are proving the result in a different way but of course there is no problem with relying on this fact because the OP's method relies on it as well?
Comment: @StephanCasey: I'm not really sure, I'm just (kinda) quoting what I understand from reading this on Wikipedia. Of course, I might be misunderstanding things here.
Answer: $$\lim \limits_{x \to 0} \frac{\sin(5x)}{\sin(4x)}$$
$$\lim \limits_{x \to 0} \frac{\sin(5x)}{x} . \frac{x}{\sin(4x)}$$
$$∵\lim \limits_{\theta \to 0}\frac{ \sin(a\theta)}{\theta}=a$$
$$=\frac54$$
Answer: $\lim\limits_{x\to0}\frac{\sin(5x)}{\sin(4x)}=$
$\lim\limits_{x\to0}\frac{\sin(5x)\cdot5x\cdot4x}{\sin(4x)\cdot5x\cdot4x}=$
$\lim\limits_{x\to0}\frac{\sin(5x)\cdot4x\cdot5x}{5x\cdot\sin(4x)\cdot4x}=$
$\lim\limits_{x\to0}\left(\frac{\sin(5x)}{5x}\cdot\frac{4x}{\sin(4x)}\cdot\frac{5x}{4x}\right)=$
$\left(\lim\limits_{x\to0}\frac{\sin(5x)}{5x}\right)\cdot\left(\lim\limits_{x\to0}\frac{4x}{\sin(4x)}\right)\cdot\left(\lim\limits_{x\to0}\frac{5x}{4x}\right)=$
$\left(\lim\limits_{x\to0}\frac{\sin(5x)}{5x}\right)\cdot\left(\lim\limits_{x\to0}\frac{4x}{\sin(4x)}\right)\cdot\left(\lim\limits_{x\to0}\frac{5}{4}\right)=$
$1\cdot1\cdot\frac54=$
$\frac54$
Answer: They were using the Squeeze theorem but I don't think it is necessary (https://www.khanacademy.org/math/differential-calculus/limits-from-equations-dc/squeeze-theorem-dc/v/proof-lim-sin-x-x)
$$\lim_{x \to 0} \frac{\sin5x}{\sin4x}$$
$$= \frac{\lim_{x \to 0} \sin5x}{\lim_{x \to 0} \sin4x}$$
where $\lim_{x \to 0} \sin4x$ not equal to $0$
but it is equal to zero so we can't do this so we can use L'Hopitals Rule where you differentiate top and bottom. We will be using chain rule here as well because $\frac{d}{dx}\sin5x = \cos5x \times \frac{d}{dx}5x = 5\cos 5x$
$$\lim_{x \to 0} \frac{\sin5x}{\sin4x}$$
$$=^{L'H} \lim_{x \to 0} \frac{5\cos5x}{4\cos4x}$$
Now just substitute zero
$$= \frac{5\cos(5(0))}{4\cos(4(0))}$$
$$=\frac{5(1)}{4(1)}$$
$$=\frac{5}{4}$$


How to get image from one screen to another screen?

Question: i have implemented galleryview in one screen named display_image.xml in which i have shown various images available on sdcard now when user selects picture and presses save image button on same screen display_image.xml then selected image should be changed in his/her profile picture in another screen.
My question is that how would i be able to get that image from one screen to change picture of user in another screen and that selected image should also inserted in database for later retrival when user logs in later. Let me tell you that my image dont come from any webservice.
Please help me out......... Thanking You.........
Answer: You can do this by two ways :
1) Pass the path of SD card of selected image and directly load that image from path in imageview.
2) you can convert image to byes[] and passing bytes[] and get back the image.
Hope u get me.
Best of Luck
Answer: Use "activityForResult".Concept is start your image choosing activity by calling
startActivityForResult(INTENT_OF_YOUR_IMAGECHOOSING_ACTIVITY);
Now in this activity, when user clicks on any of the image handle that event as follows:some OnClick(){
Intent resultIntent = new Intent();
in this intent set byte array of your image in extras OR the sd card path of your image
then call setResult(RESULT_OK, resultIntent);
This is gonna return the call to the previous activity in the method onActivityResult(int resultCode, ..., Intent data) HERE use the data as the intent to fetch the info you require
Answer: First thing you need to do is declare an Intent
Intent i_cp = new Intent(this,ImagePicker.class);

and use startActivityForResult(i_cp, 111); which will be looking for some result. in our case for position of image; an integer value.
by specifying request_code (111) that will be used to identify result when returned by started intent. Here we wont use setAction(i_cp.ACTION_PICK); and setType("image/*"); because we are not going to return image we will just return the position of image. Our use of Intent will be limited to just passing and retrieving the integer value(position of value).
Now how about to get that position of image that user has selected. position is got in onItemClick method of GalleryView by one of the parameters
public void onItemClick(AdapterView parent, View v, int position,long rid)

now declare one variable such as int pos; and assign -1 to identify whether the image is selected or not and if the image is selected then in onclick event of button saveimage pass value position as
retIntent.putExtra("SelectedImage", pos);

and in onActivityForResult identify intent by passed requestcode and extract that position as
int pos = data.getExtras().getInt("SelectedImage");

and set it as
usr_im.setImageResource(ImagePicker.pics[pos]);

and this array of pics[] which holds all ids of images stored in one of the res/drawable folder of your application, declare it as
public static Integer[] pics={values};

Otherwise you wont able to set the image.


Why is the route not executed in the following code?

Question: I want to make the server console log any fetch that it receives in the third app.use but this makes the routes after it not executed. Why? Is this not the ideal way for doing general response on any request?..
const express = require('express');
const bodyParser = require('body-parser');
const bbdb = require('./database/bbDB');
const sql = require('./database/sql');

const app = express();
const port = process.env.PORT || 5000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); //keep this to true to be able to post nested object
app.use((json)=>{
  console.log('receiving fetch at: ' + json.originalUrl);
});

app.get('/api/hello', (req, res) => {
  res.send({express: 'Hello'});
});

app.get('/api/hello/data', async (req, res) =>{
    try{
      console.log('receiving fetch at: ' + req.originalUrl);
      const reqQuery = req.query;
      let results = await bbdb.queryProducts(sql.all_home_desc);
      res.send(results);
    } catch(err) {
      console.log(err);
      res.sendStatus(500);
    }
});

app.listen(port, () => console.log(`Listening on port ${port}`));

Answer: You have to call the next middleware manually. Try the following:
app.use((req, res, next) => {
  console.log(`receiving fetch at: ${req.url}`);
  next();
});

Comment: It works now. Thanks. Another weird behaviour that i get from this is now that whenever it receives a new http request, it always `log` the same `req.originalUrl` from the first request. Any idea why?
Comment: For that I'm not sure to be honest, try assembling the full URL using:
`var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;`
Answer: As vitor said, your middleware needs to call next(), this calls the next function in your server's stack, either the next middleware in order or the function that handles the request.
This is so that you can optionally stop the request from passing through, like for authentication middleware, if someone requests a delete, if the auth middle finds out he's not allowed, it shouldn't call next.


POCO C++ Encryption / Decryption

Question: I am working with the POCO C++ API and using the CRYPTO module for encryption and decryption. I am having an issue with decryption not working and retuning the following error:
<code>   RSA_padding_check_PKCS1_type_2:pkcs decoding error; error:04065072:rsa
   routines:rsa_ossl_private_decrypt:padding check failed"
</code>
I am using an RSA key/pair. The generation of the Key pair
<code>void Support::GenerateKeyPair(std::string& PublicKey, std::string& PrivateKey)
{
    Poco::Crypto::RSAKey key(Poco::Crypto::RSAKey::KL_1024, Poco::Crypto::RSAKey::EXP_SMALL);

    std::ostringstream strPub;
    std::ostringstream strPriv;

    key.save(&strPub, &strPriv); // EmailEncryptionPassphrase);
    PublicKey = strPub.str();
    PrivateKey = strPriv.str();
}
</code>
These keys are placed within a file - and will be explicitly retrieved as strings for encryption/decryption activity -- i.e. encryption/decryption in not using the file directly
My encryption operation is the following:
<code>    std::istringstream iPub(PublicKey);
    Poco::Crypto::RSAKey MulaRSAKey(&iPub);

    Poco::Crypto::CipherFactory& factory = Poco::Crypto::CipherFactory::defaultFactory();
    Poco::Crypto::Cipher* MulaCipherImpl = factory.createCipher(MulaRSAKey);

    //encrypt using RSA (keys prepped with RSA)
    EncryptedData = MulaCipherImpl->encryptString(Data, Poco::Crypto::Cipher::Encoding::ENC_NONE);
</code>
And again -- the public key is a string that is retrieved from a configuration file. This operation does not fail - encryption appears to be working.
I decrypt the data like the following:
<code>   std::istringstream iPub(Keys.PublicKey);
   std::istringstream iPriv(Keys.PrivateKey);
   Poco::Crypto::RSAKey MulaRSAKey(&iPub, &iPriv); // EmailEncryptionPassphrase);
   Poco::Crypto::CipherFactory& factory = Poco::Crypto::CipherFactory::defaultFactory();
   Poco::Crypto::Cipher* MulaCipherImpl = factory.createCipher(MulaRSAKey);

   DecryptedData = std::make_shared<std::string>(MulaCipherImpl->decryptString(EncryptData,
         Poco::Crypto::Cipher::Encoding::ENC_NONE));
</code>
This is where the failure is occuring. The decryption is failing with the padding error I mentioned above. The decryption operation also uses strings for the key pair from the configuration file.
I was unsure if the key pair was valid so I used a RSA Key (online) tester to validate the key pair - and the test was able to encrypt and decrypt. So looks like the key is valid.
I was able to change the encoding from  Poco::Crypto::Cipher::Encoding::ENC_NONE to Poco::Crypto::Cipher::Encoding::ENC_BINHEX and decryption did pass -- generated a hex output - but did pass. The confusing aspect of this is that the encryption operation was still using the Poco::Crypto::Cipher::Encoding::ENC_NONE. My understanding was that encrypt and decrypt should be using the same encoding. This though does not clarify why the NONE based encoding is failing on decryption.
If anyone could clarify what is configured incorrectly - would be a great help.
thx
Peter
Comment: why are you making a shared pointer to a std::string ? it's effectively shared pointer to char* buffer anyway ?
Answer: OK -- question is mute. Realized that the encrypted data (to unencrypt) was invalid. Got modified within JSON operations used to migrate the data to remote servers.
Peter
Comment: As the problem was resolved in a way that probably won't help future readers, you may want to delete it.

POCO C++ Encryption / Decryption


How do I install requirements in Go? "cannot find package"

Question: I'm new to Go and I'm trying to set up a Go project with minimal documentation: https://github.com/alphagov/metadata-api
I've cloned it, but when I try go build I get the following warnings:
main.go:8:2: cannot find package "github.com/Sirupsen/logrus" in any of:
    /usr/local/Cellar/go/1.3.3/libexec/src/pkg/github.com/Sirupsen/logrus (from $GOROOT)
    /Users/me/go/src/github.com/Sirupsen/logrus (from $GOPATH)
main.go:14:2: cannot find package "github.com/alphagov/metadata-api/content_api" in any of:
    /usr/local/Cellar/go/1.3.3/libexec/src/pkg/github.com/alphagov/metadata-api/content_api (from $GOROOT)
    /Users/me/go/src/github.com/alphagov/metadata-api/content_api (from $GOPATH)

I'm guessing this is because I haven't installed the Go equivalent of requirements?
My GOPATH is set:
metadata-api$ echo $GOPATH
/Users/me/go

And the Go executable is in
metadata-ape$ echo $PATH
....:/Users/me/go/bin

What do I need to do to help Go find these packages?
Comment: Update: I added Go to my path `export PATH=$PATH:/Users/anna/go` and now `go build` does not produce any errors... but nor does it seem to generate anything.
Answer: You should install package first:
try
$ go get github.com/Sirupsen/logrus

and check you $GOPATH dir
This project use gom as the package manager,
Make sure you have installed gom
or try this command
$ gom install

I think your $GOPATH and $PATH settings are incorrect, the $GOPATH environment variable specifies the location of your workspace, these are my path settings:
export GOROOT=$HOME/bin/go
export GOBIN=$GOROOT/bin
export GOPATH=$HOME/golang
export PATH=$PATH:$GOBIN

Comment: I also tried simly `go get` and I think it got all of my dependencies at the same time.
Comment: Thanks. `gom install` seems to be doing the trick, but how did you know this project used `gom`?
Comment: $GOPATH environment variable specifies the location of your workspace? Does that mean i have to export all of these variables everytime i create a new workspace-project?
Comment: This is the closest to the answer and provides the correct directions to reach the fix, other answers should not be approached. But it is important to specify, why we are doing this.
- GO has a concept of WORKSPACE, so whenever we do `go build` , the go compiler will search for the two `environment` variables, `GOPATH` and `GOROOT` to find the `src` path to compile the package and generate the binaries
- So do we always need to have a `WORKSPACE` set, yes. Unless.... you would want to stuff everything (meaning every package) in the `GOPATH`  or

read - https://go.dev/doc/gopath_code
Comment: The `gom` project is now archived.
Answer: I had similar issue and
export GO111MODULE=on

helped.
Comment: This is what I needed too. Went looking for why - here's a rundown: https://dev.to/maelvls/why-is-go111module-everywhere-and-everything-about-go-modules-24k
Comment: Just spent way too long trying to figure out why. Thank you for this!!!
Comment: You saved my life.
Answer: When you need your code to do something that might have been implemented by someone else (in Github or a package somewhere else), You should initialize a go mod file inside of your folder.)
For the purposes of this example, I'll just use example.com/module.
go mod init example.com/module

Add new module requirements and sums:
go mod tidy

Run your program:
go run .

For more details, see https://golang.org/doc/tutorial/getting-started.
Answer: Was able to fix the similar issue in Go 1.13.7 by typing:
 export GOPATH=~/go
 go get github.com/profile/repository
 (e.g. github.com/Sirupsen/logrus)

Answer: "...Starting in Go 1.13, module mode will be the default for all development..."
"...When using modules, GOPATH is no longer used for resolving imports. However, it is still used to store downloaded source code (in GOPATH/pkg/mod) and compiled commands (in GOPATH/bin)..."


Design application using Apache Spark

Question: Its a bit architectural kind of question. I need to design an application using Spark and Scala as the primary tool. I want to minimise the manual intervention as much as possible.
I will receive a zip with multiple files having different structures as an input at a regular interval of time say, daily. I need to process it using Spark . After transformations need to move the data to a back-end database.
Wanted to understand the best way I can use to design the application.
What would be the best way to process the zip ?
Is the Spark Streaming can be considered as an option looking at the frequency of the file ?
What other options should I take into consideration?
Any guidance will be really appreciable.
Comment: It's off topic for SO. However you can try to implement steps and ask for help with them
Comment: Leaving the architectural part , how can I work with a zip in Spark with multiple files having different structures as an input.
Answer: Its a broad question, there are batch options and stream options not sure your exact requirements. you may start your research here: https://jaceklaskowski.gitbooks.io/spark-structured-streaming/spark-sql-streaming-FileStreamSource.html

Design application using Apache Spark


An error happened while reading data from the provider. The remote certificate is invalid according to the validation procedure

Question: I'm trying to connect Postgres Database on AWS EC2 instance to Microsoft PowerBI. I tried various method available on internet but its showing the above error. Although I've done this connection on AWS RDS. I installed required dependencies (GAC) and all the certificates required for PowerBI.
Comment: I was also afraid of this error
Comment: have you found any solution @YashPokar
Answer: Following worked for me:
File / Options and settings / Data source settings
then select data source
and Edit Permissions and uncheck encrypt connections
Comment: Thank you for that solution! Luckily there is some PowerBI solutions on StackOverflow since I never can get any help on the PowerBI forum
Comment: Didn't work for me. My database is a Postgres one from Heroku. I can see from the DNS that it is an AWS database though.
Answer: I've came across the same issue, unfortunately I didn't find solution to resolve it. But I found an alternative.
You can connect PostgreSQL using ODBC Connection.
Setup ODBC for PostgreSQL: https://www.postgresql.org/ftp/odbc/versions/msi/
After Installation, Select ODBC Connection under "Get Data"
Select "None" under Data Source Name and
add following statement under connection string:
Driver={PostgreSQL ANSI(x64)};Server=<host>;Port=5432;Database=<dbname>

Click "Next"
Enter Username and Password, Click Connect.
If credentials are correct, you will see list of tables available in database.
Follow this reference for detailed description:
http://niftit.com/connecting-power-bi-to-postgresql/
Comment: you might want to use "PostgreSQL Unicode" as driver, we can find other options for connection strings at https://www.connectionstrings.com/postgresql-odbc-driver-psqlodbc/
Comment: Thanks a lot Chirag. I was really afraid and tried loads of ways.
Answer: Two hours wasted, so writing in full.
Download and install postgresql ODBC driver
Goto below URL

URL: https://www.postgresql.org/ftp/odbc/versions/msi/
Scroll down
Click on a zip file to download  (i took psqlodbc_12_00_0000-x64.zip)
Unzip file
Run the .MSI file
   Take all defaults given and install it

Create ODBC data source
Find the ODBC data source using below (I took "ODBC Data Sources (64-bit)"):
Windows > Start button > search for "ODBC Data Sources"
User DSN > PostgreSQL ANSI(x64) > Finish
Give details
  Data source name : PostgreSQL30                ###
  DB name *** , server, port, username, pwd
  SSL mode = disabled (default)
click on Test button
  "Connection successful" message will come, else re-check details above.

We now have a new User DS, with PostgreSQL30 created
Download Power BI
Windows > Start button > Microsoft Store
Search for "Power BI Desktop" > Get/Install

Source: https://learn.microsoft.com/en-us/power-bi/desktop-get-the-desktop#download-power-bi-desktop
Running the Power BI
Get Data (On the left)
Search for "odbc" > Select "ODBC" on right pane > Connect
  DSN > PostgreSQL30 ( --- this is same as above ### --- )
  OK

"Navigator" dialog is shown, with "Display Options"

ODBC ... PostgreSQL30
> DB name   ( --- this is same as above *** --- )
  Open the > button on left of DB name
  select the tables
  click "Load" button

Done.
You have successfully connected Power BI (PBI) to your postgres or other database.
Hope this helps.
Comment: ODBC also dont validate SSL certificate, then is almost equals no encryption
Answer: For AWS look at this case https://community.powerbi.com/t5/Desktop/The-remote-certificate-is-invalid-according-to-the-validation/td-p/531475
For non-AWS issue you should configure SSL according to Npgsql documentation https://www.npgsql.org/doc/security.html or you can disable SSL option in postgresql.conf on postgresql server.
Answer: adding onto @chirag sanghvi answer
You may get an error
ERROR: character 0xefbfbd of encoding "UTF8" has no equivalent in "WIN1252"
because your database is encoded in UTF-8
Install this driver
https://github.com/npgsql/npgsql/releases/tag/v4.1.3
then in your connection string use the Unicode driver
Driver={PostgreSQL Unicode(x64)};Server=;Port=5432;Database=
Answer: I got the same error, but at least in my case the problem was due to the fact that the certificate I was using was self-signed. Once I generated a new one with certbot/letsencrypt properly signed by a CA, Power BI didn't give me any more trouble to connect.


Confluence XML-RPC: Set the "creation" date

Question: I am trying to migrate some existing blog entries into our confluence wiki using XML-RPC with Python. It is currently working with such things as title, content, space etc but will not work for created date.
This is what was currently attempted
import xmlrpclib

proxy=xmlrpclib.ServerProxy('<my_confluence>/rpc/xmlrpc')
token=proxy.confluence1.login('username', 'password')

page = {
    'title':'myTitle',
    'content':'My Content',
    'space':'myspace',
    'created':sometime
}

proxy.confluence1.storePage(token, page)

sometime is the date I want to set to a time in the past. I have tried using Date objects, various string formats and even the date object returned by a previous save, but no luck.
Answer: If you would try to store the existing content as actual blog entries in Confluence, then you could use the "publishDate" parameter:
import xmlrpclib
import datetime

proxy=xmlrpclib.ServerProxy('<my_confluence>/rpc/xmlrpc')
token=proxy.confluence1.login('username', 'password')

blogpost = {
    'title' : 'myTitle',
    'content' : 'My Content',
    'space' : 'myspace',
    'publishDate' : datetime.datetime(2001, 11, 21, 16, 30)
}

proxy.confluence1.storeBlogEntry(token, blogpost)

The XML-API for pages ignores the "created" parameter.
Answer: You can use strptime because type will not match directly. Hope this works.
new_sometime = datetime.strptime(sometime, '%Y-%m-%d')
page = {
    'title':'myTitle',
    'content':'My Content',
    'space':'myspace',
    'created':new_sometime
}

Comment: I have tried various string formatting options and they dont seems to work. I think the problem might be that confluence is overwriting the created time to when it is actually created, which kind of makes sense I guess...
Comment: when u will fetch old value it will in string format and u want 2 overwrite then u need to convert in datetime format.
Comment: first print and chack new_sometime. are u getting it properly. may be if your datetime format is diff then also possible u can not do it
Comment: Thanks for the comment, but it doesnt work. I have treid many different formats, and as I said in the question, I even tried the actual date object returned from a previous save (which is set by confluence)