Java 8 , JCE Unlimited Strength Policy and SSL Handshake over TLS

Question: With Java 8, server which only supports TLSv1, it fails to make secure socket connection from cent OS
Version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

Source
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by jigar.joshi on 6/10/15.
 */
public class SSLTester {
    public static void main(String[] args) throws Exception {
        SSLSocketFactory f =
                (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket socket = (SSLSocket) f.createSocket("efm.sandbox.vovici.com", 443 );
        try {
            printSocketInfo(socket);
            socket.startHandshake();
            System.out.println("----------------------------------SUCCESS----------------------------------");

            BufferedReader r = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            String m = null;
            while ((m = r.readLine()) != null) {
                System.out.println(m);

            }
            r.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println(e.toString());
        }
    }

    private static void printSocketInfo(SSLSocket s) {
        System.out.println("Socket class: " + s.getClass());
        System.out.println("    Remote address = "
                + s.getInetAddress().toString());
        System.out.println("    Remote port = " + s.getPort());
        System.out.println("    Local socket address = "
                + s.getLocalSocketAddress().toString());
        System.out.println("    Local address = "
                + s.getLocalAddress().toString());
        System.out.println("    Local port = " + s.getLocalPort());
        System.out.println("    Need client authentication = "
                + s.getNeedClientAuth());
        SSLSession ss = s.getSession();
        System.out.println("    Cipher suite = " + ss.getCipherSuite());
        System.out.println("    Protocol = " + ss.getProtocol());
    }

}

With same version of JVM, it makes handshake successfully on OSX, it fails on centOS, Failure reason is it only tries to use TLSv1.2 (default in JVM 8) and doesn't try lower protocol
debug notes:
-Ddeployment.security.TLSv1.0=true

-Ddeployment.security.TLSv1=true

-Ddeployment.security.TLSv1.1=false

-Ddeployment.security.TLSv1.2=false

-Djavax.net.debug=ssl:handshake:verbose

Question:

Why it is able to choose TLSv1 on OSX and not on CentOS?
How can I tell JVM to use protocols in specific order or if it considers order by the version then how can I tell it to also try with v1

Edit:
I have unlimited strength JCE policies installed with JRE that is causing this, it works without that so OSX and CentOS difference is gone, How can I still make it work ?
Edit:
Output
Socket class: class sun.security.ssl.SSLSocketImpl
    Remote address = efm.sandbox.vovici.com/18.104.22.168
    Remote port = 443
    Local socket address = /10.10.152.143:50376
    Local address = /10.10.152.143
    Local port = 50376
    Need client authentication = false
    Cipher suite = SSL_NULL_WITH_NULL_NULL
    Protocol = NONE
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
    at sun.security.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.java:1529)
    at sun.security.ssl.SSLSocketImpl.checkWrite(SSLSocketImpl.java:1541)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1375)
    at SSLTester.main(SSLTester.java:24)
Caused by: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:980)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1363)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1391)
    at sun.security.ssl.SSLSocketImpl.getSession(SSLSocketImpl.java:2225)
    at SSLTester.printSocketInfo(SSLTester.java:56)
    at SSLTester.main(SSLTester.java:23)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
    at sun.security.ssl.InputRecord.read(InputRecord.java:505)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:961)
    ... 5 more
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake

Comment: What is the exception exactly? Why do you call `startHandshake()` manually? SSLSocket performs a handshake transparently, furthermore, `getSession()` in `printSocketInfo` already initiates a handshake.
Comment: Thanks @apangin, added output, handshaking explicitly can be ignored here I think
Answer: Try limiting the protocols to just TLSv1 using:
-Djdk.tls.client.protocols=TLSv1

See this page for more details: https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#descPhase2
Hope this helps,
Yuri


JS Two Decimal Places .toFixed(2)

Question: .toFixed is not working in my code. I am using it with .toLocaleString()
JS / Fiddle: https://jsfiddle.net/8b6t90f5/

$(function() {
  var value = 5000.3269588;

  $("#process").click(function() {

    $('#amount').text("Total: $" + value.toLocaleString().toFixed(2));

  });
});

<input id="process" class="button_text" type="submit" name="submit" value="SHOW VALUE">
Comment: @NickA because it's a different question?
Comment: Use `toFixed` on the number, not the string
Comment: `I am using it with .toLocaleString()`
That is why it is not working.
Comment: @NickA - His previous question involved the correct number to use as an argument to `.toFixed()`.  This one invloves an error he saw when chaining `.toLocaleString()` with `toFixed()`.
Comment: @BadZen Sure, but if OP was already aware that using `toFixed` worked when used on a number, why would using `toLocaleString` *before* `toFixed` be the first thing that came to mind, the question is essentially asking how to use `toFixed`, the solution, on a number
Comment: You'd have to ask him.   But it's still a different question.
Comment: @BadZen Yes, it is
Answer: Strings do not have a toFixed(), only numbers do.
      $('#amount').text("Total: " + value.toLocaleString("en-US", {maximumFractionDigits:2, currency:"USD", style:"currency"}));

is possibly what you're after.
Comment: Thank you for the answer. now `.toLocaleString()` is not working.
Comment: It should show 5000.33 as 5,000.33 with thousand separator
Comment: Why the downvote, guy who just replayed my previous answer?
Comment: @YOU - Now I see what you are looking for.   Edited my answer, try that.
Answer: toFixed() is a Number method. toLocaleString() turns it into a string. You need to use toFixed() first, then parse that back to float and use toLocaleString():
parseFloat(value.toFixed(2)).toLocalString('en-BR');

const num = 50023.357289357;
console.log(parseFloat(num.toFixed(2)).toLocaleString());
Comment: `toLocaleString()` isn't working in your code above.
Comment: .toFixed() returns a string. You could try replacing the second line with `console.log(parseFloat(num.toFixed(2)).toLocaleString()));`
Comment: Indeed. Adding `parseFloat()` will fix it. I've updated my answer.
Comment: Strings and indeed all objects have `.toLocaleString()`.
Comment: This answer does not give the correct locale-specific representation of the currency value; you need to add the currency symbol by hand in a one-for-all-locales way.  And parseFloat() returns the value as Number, making the toLocaleString() pointless.  And it can also break if parseFloat does not handle the locale's numeric representation, which is absolutely the case for some locales.
Comment: My short snippet had a `)` in the wrong place. The `toLocaleString()` should have come after it. And yes, you do need to add the currency symbol, but the question wasn't strictly about the currency symbol. If you supply the values to get the currency symbol to show up, you are effectively hard-coding which locale it'll use anyways, so you might as well just concat the symbol and keep it a bit simpler.
Answer: You continue to use string methods for numbers and vice versa. Try this:

const num = 5000.3269588;
console.log(num.toLocaleString(undefined, {maximumFractionDigits: 2}));
Comment: Where did that `num` value come from?
Comment: There's a current browser inconsistency bug using `undefined` as the first argument.   You should try to avoid that.
Comment: (also OP is trying to format a currency in locale, his original code outputs a currency symbol - determining that symbol is part of the locale functionality)

JS Two Decimal Places .toFixed(2)


Reduce the size of website

Question: My website's homepage is about 8MB. Is there easy way to figure out, what all can be removed from it.
I know the slider itself has about 2.5MB of images in it. I am trying to reduce that. but still the size is too big.
the link to the website is: http://prelaunch.biocarve.com/
Please, any guidance would be helpful.
Thanks in advance.
Comment: Also, run the google page insights.They will help with specific details on how to go about optimizing.I went through the console network tab for your website. A large chunk of your size seems to be due to images.The next is also js files.Try and minify them?
Comment: Compress all images in [TinyPNG](https://tinypng.com/) to start with.
Comment: Images are compressed!
Answer: Google Pagespeed Insights gives a nice overview in how to improve the speed of your website.
It also gives compressed CSS, JavaScript and images. It also gives overall solutions to make your site a little speedier.
https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fprelaunch.biocarve.com%2F
You currently score a 7/100, so I would look at some of the corrections that Google provides.
https://developers.google.com/speed/pagespeed/insights/
Answer: 1.Compress all images.
2.Remove comments from code.
3.Minify CS,Javascript and HTML files.
4.Remove Unused CSS and Javacript code.
5.Put all your javacript code in a single JS file. Do it for css also.
Answer: I have checked your site on this page.
This page gives you insight in the size of all the components that are loaded.
As you can see, it's mainly your images:

banner_1.jpg (619 kB)
banner_2.jpg (468 kB)
banner_3.jpg (614 kB)
banner_4.jpg (447 kB)
banner_5.jpg (588 kB)
cosmos_bright_light_1.jpg (524 kB)
kochia2.jpg (305 kB)
etc

You can reduce the size of these images by resizing them with an editor like paint, photoshop, etc or an online tool like this.

Reduce the size of website


finding bounds of PDF Y given Y = aX + b, where X ∼ Exp(λ)

Question: i know the bounds of PDF X is 0 to infiniti where X ∼ Exp(λ), λ > 0 and a, b ∈ R
but how would i find out the bounds of PDF Y given Y = aX+b?
Answer: The support of $X$ is $~[0;\infty)~$, so the support of $~aX+b~$ is $~[\color{silver}{a{\cdot}0{+}}b;\infty)~$.
Now, can you tell us how the density if affected by the linear (scale and shift) transformation?


Fix bootloader after removing Ubuntu from a dual boot system?

Question: I have installed a Ubuntu alongside Pre-installed Windows-8...
And now I have uninstalled Ubuntu. But the problem is that after removing Ubuntu and typing "bootrec/Fixmbr" in Command Prompt, there is still showing a boot manager with only one option Windows-8. How can I get rid of this mess?
Answer: What boot manager appears? The Windows boot manager? If so, you can try the one of the following methods. (The first one is probably easier.)
Basically, you need to tell the Windows Boot Manager to boot the Windows Boot Loader by default (unless it's already doing this), and then tell the Windows Boot Manager to stop displaying the boot menu.
Please note that if you make a mistake during this process, you may no longer be able to boot into Windows. If this happens, your best bet may be to boot into a Windows disc and use the recovery options there. Especially in the case that you were using Method 2, you can even open a command prompt from the disc and try using BCDEdit again.
Method 1: Control Panel Options

Open the Control Panel (Start -> Control Panel)
Go to "System and Security"
Go to "System"
Go to "Advanced System Settings"
Go to the "Advanced" tab
Under "Startup and Recovery", click "Settings"
Under "System Startup" -> "Default operating system", choose something like "Windows 8"
Uncheck the option "Time to display list of operating systems". You'll notice that the number of seconds changes to 0.

I found some of the information for Method 1 here: How to change Windows 7 Boot manager options to start the OS automatically?
Method 2: BCDEdit
BCDEdit is a built-in utility in Windows Vista, 7, & 8 that you should also be able to use to solve your problem.
1) Make sure Windows is your default boot entry.

In Windows, open a command prompt. (e.g. Hold the Windows key and press R.
In the "Run" window that appears, type cmd and press Enter.)
In the command prompt, run the command bcdedit to display current boot information. There should be an entry called "Windows Boot Loader" (NOT "Windows Boot Manager"!) followed by a line with "identifier" and a long string of characters enclosed by { }. This string is the GUID (or just "id" or "identifier") of that boot entry.
Run the command BCDEdit /default id, where where you replace id with the long identifier of the Windows boot entry, to make that boot loader the default one.

2) Skip the boot menu so you no longer see it.
Use the following BCDEdit command to skip the boot menu so you don't see it:
bcdedit /timeout 0.
In this command, 0 is actually the number of seconds the Windows  to display the boot selection screen.
I found some of the information for Method 2 here:
BCDEdit Command-Line Options
Changing the Default Boot Entry
Comment: Thank you for your reply.It is a Windows boot manager.I have an Easy BC.Can you please suggest me the way through it?Because I am not used to with Command Line.
Comment: Please see my revised answer above. I added a way to access boot manager settings from the Control Panel (just discovered this) and added more detail to the BCDEdit instructions.

Alternatively, if you want to use EasyBCD (as you mentioned), I would recommend looking for instructions in the program itself or on their website. I don't have EasyBCD, so I can't guide you through that.
Comment: I have done with Easy BCD,and thnx for ur help
Answer: If you have a Windows installation DVD or repair CD, you can boot to a repair command prompt and run:(repair/advanced/cmdprompt)
enter:
bootrec /fixmbr
This command installs the Windows bootloader. If you have a dual boot it would boot straight to Windows and you can then do what you want with the linux partitions.
That worked for me.


How to parse req.body in node js

Question: I am passing 10.0.0.12 value in axios get from react side to node , When I am trying to print req.body on node side it displays [object,object] how to get value from object?
This How I am sending req:
     axios
  .get("/ashjg/GetTfsItem",
       {BuildNumber:event.target.value[event.target.value.length-1].BuildNumber},{headers: {'Content-Type':'application/json'}},
    )
     .then(response => {
         console.log("responce data"+response.data);
       if(response.status==200){
           this.setState({TfsItemdata : response.data});
       }else{
           this.setState({errorMessage:"Data Not Available "})
       }
     })
     .catch(error => {
       this.setState({errorMessage:"Data Not Available for Crash Id  "})
     });

    }

Node Js Side :
router.get("/GetTfsItem",function(req,res,next){
    console.dir( "Inside GetTfsItem " + Jreq.body );
}

Comment: Show your code.
Comment: Please include a [mcve]. What are you using in the backend? Express?
Comment: console.log(req.body) or console.log(JSON.stringify(req.body))
Comment: Tried but not working
Answer: Try using body-parser like this:

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})

Remember you need to install body-parser:

npm i body-parser
Answer: In case if you are using express.js then you can do it like this:
const express = require('express')
const app = express()
const port = 3000

app.use(express.json())
app.use(express.urlencoded({ extended: false }))

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Answer: app.post('/handle',function(request,response){
var query1=request.body.var1;
var query2=request.body.var2;
});

How to parse req.body in node js


Mapview not displaying Title or subtitle from pin annotation

Question: App returns error when clicking the annotation pin. However it does not crash. It just does not show the title or subtitle.
Error is (lldb) then list a string of numbers like 0x3516b5a0.
plist example:
<dict>
        <key>cellName</key>
        <string>Abingdon Lodge No. 48</string>
        <key>cellSubtitle</key>
        <string>Abingdon, VA</string>
        <key>address</key>
        <string>325 W Main Street Abingdon, Virginia 24210</string>
        <key>latitude</key>
        <real>36.708649</real>
        <key>longitude</key>
        <real>-81.981184</real>
        <key>webSite</key>
        <string>http://www.grandlodgeofvirginia.org/lodges/48/</string>
        <key>statedCom</key>
        <string>Abingdon Lodge No. 48 holds it's stated communication on the 2nd Monday of the month at 7:30 PM. If there are any exceptions to the regular meeting day or time, they are posted on the Lodge website.</string>
        <key>history</key>
        <string>According to the earliest records the Abingdon Lodge had its origin "At a meeting held at the house of James White in the town.</string>
    </dict>

MapviewController.M
- (void)viewDidLoad
{

    // Do any additional setup after loading the view, typiclly from a nib.
    //Create the region
    MKCoordinateRegion myRegion;

    //Center
    CLLocationCoordinate2D center;
    center.latitude = VA_LATITUDE;
    center.longitude = VA_LONGITUDE;

    //Span
    MKCoordinateSpan span;
    span.latitudeDelta = THE_SPAN;
    span.longitudeDelta = THE_SPAN;

    myRegion.center = center;
    myRegion.span = span;

    //Set our mapView
    [myMapView setRegion:myRegion animated:YES];

    NSString *path = [[NSBundle mainBundle] pathForResource:@"lodges" ofType:@"plist"];
    NSMutableArray* lodgelist = [[NSMutableArray alloc] initWithContentsOfFile:path];

    for(int i = 0; i < [lodgelist count]; i++) {
        float realLatitude = [[[lodgelist objectAtIndex:i] objectForKey:@"latitude"] floatValue];
        float realLongitude = [[[lodgelist objectAtIndex:i] objectForKey:@"longitude"] floatValue];

        CLLocationCoordinate2D mypoint;
        mypoint.latitude = realLatitude;
        mypoint.longitude = realLongitude;
        Annotation *lodgepoint =[Annotation alloc];
        lodgepoint.coordinate = mypoint;
        lodgepoint.title = [[lodgelist objectAtIndex:i] objectForKey:@"cellName"];
        lodgepoint.subtitle = [[lodgelist objectAtIndex:i] objectForKey:@"cellSubtitle"];
        [self.myMapView addAnnotation:lodgepoint];

    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

MapViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface AWCMapViewController : UIViewController

@property (strong, nonatomic) IBOutlet MKMapView *myMapView;

-(IBAction)findmylocation:(id)sender;
-(IBAction)setmaptype:(id)sender;

@property (strong, nonatomic) NSArray *tabledata;

@end

Comment: i think you need to implement annotation's methods like viewForAnnotation, didSelectAnnotation and canShowCallout Property should be set to YES to show callout..
Comment: try my answer.It should work
Comment: thanks guys, ill try this when I get home..
Answer: In your
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation

add the following under your MKAnnottionView
customPinView.canShowCallout=YES;

Regards
Comment: CLLocationCoordinate2D mypoint;
        mypoint.latitude = realLatitude;
        mypoint.longitude = realLongitude;
        Annotation *lodgepoint =[Annotation alloc];
        lodgepoint.coordinate = mypoint;
        lodgepoint.title = [[lodgelist objectAtIndex:i] objectForKey:@"cellName"];
        lodgepoint.subtitle = [[lodgelist objectAtIndex:i] objectForKey:@"cellSubtitle"];
        [self.myMapView addAnnotation:lodgepoint];
Comment: -(MKAnnotationView *)myMapView:(MKMapView *)mV viewForAnnotation:(id )annotation {
    MKPinAnnotationView *pinView = nil;

    pinView.pinColor = MKPinAnnotationColorPurple;
    pinView.canShowCallout = YES;
    pinView.animatesDrop = YES;

    return pinView;
Comment: unrecognized selector sent to instance 0x20872620
Comment: is your UIView's userinteraction enabled?
Comment: Yes, and after replacing the Mapkit VC, its not showing the subtitle but not the tile.. the title is labled satellite... this prob is driving me nuts
Answer: @interface Annotation : NSObject <MKAnnotation>

@property(nonatomic, assign) CLLocationCoordinate2D coordinate;
@property(nonatomic, copy) NSString *title;
@property(nonatomic, copy) NSString *subtitle;

I had to change the title from assign to copy. :P


Unable to start x11vnc on Ubuntu 16.04 LTS as service

Question: I am trying to run x11vnc as service to start it on boot. Below is the code that I am using drawn from the two answers here.
[Unit]
Description=VNC Server for X11
Requires=display-manager.service
After=display-manager.service

[Service]
Type=forking
ExecStart=/usr/bin/x11vnc -auth guess -forever -loop -noxdamage -repeat -rfbauth /etc/vnc.passwd -rfbport 5902 -shared
ExecStop=/usr/bin/x11vnc -R stop
Restart=on-failure
RestartSec=2

[Install]
WantedBy=multi-user.target

Then I run:
 sudo systemctl daemon-reload
 sudo systemctl enable x11vnc.service
 sudo systemctl start x11vnc.service

On the last command, I get the following error message.
Job for x11vnc.service failed because a timeout was exceeded. See "systemctl status x11vnc.service" and "journalctl -xe" for details.

There is no conclusive answer on systemctl status x11vnc.service or journalctl -xe but I can supply if needed.
Another thing I noticed is that the ports 5900, 5901 could be open or closed in different boots. I don't know which process is taking them.
The code below works but it can't start when integrated in the service above.
When restarting Ubuntu, it works initially and stops working after few minutes.
exec /usr/bin/x11vnc -auth guess -forever -loop -noxdamage -repeat -rfbauth /etc/vnc.passwd -rfbport 5902 -shared

Ubuntu Version: Ubuntu 16.04.6 LTS
Release:    16.04
Codename:   xenial
Is there anything I am missing that prevents x11vnc from starting?
Comment: Thank you @guiverc I have updated my question and title. Do you think updating it will solve the problem?
Comment: You might want to ensure you're fully-up-to-date with packages, a fully-upgraded Xenial system will report itself as 16.04.7 (16.04.6 implies you're behind on upgraded packages & security fixes).  Do I think it'll help, NO (they'll be security fixes, which in itself is worthwhile to most of us where security matters).
Comment: I will update. Thank you!
Answer: This is not a fix but a workaround. I used sudo crontab -e to store run the x11vnc at startup. I just needed to add this below at the end of crontab.
@reboot exec /usr/bin/x11vnc -auth guess -forever -loop -noxdamage -repeat -rfbauth /home/geodev/.vnc/passwd -rfbport 5900 -shared

Running it in sudo is important to start x11vnc before login of any user.
Answer: if you have installed another version of vncserver
you'll need to remove it then reboot the machine
and start the service again


How to increase station storage?

Question: I have super large station in a city of 175,000, so coverage of station is fully covered by buildings. But I never seen more than 1,500 passengers in my station. That's bad, because if some Airbus A380 land on the linked airport, they will totally drain my station. I made some feeder services by buses, but passengers from there won't remain longer than couple of seconds and I still only have around 1,500.
Is there any way to "store" more passengers in station?
Comment: 1,500 passengers waiting at a station already seems excessive and I've experienced British Rail.
Comment: I think the amount people will wait depends on your ratings.  What's your rating for passengers at this station?  If it's low, get your trains or planes to wait until they're completely full.  If all your trains or other transports are already always full, there's your answer.
Comment: I already got it. I had to increase station's coverage via bus stops randomly placed in that city. Now there are 17,000 and more. But anyway, thanks for quick answers..
Answer: In general, you don't want to do this.  Having 1500+ units of cargo waiting at a station means you're losing a third or more of your potential station rating (and thus, cargo generation).  Instead, you want to increase your rate of flow, both in and out, so that vehicles will load quickly and completely even without cargo waiting.
That said, there are ways of doing this.

The easiest is to have feeder routes.  Cargo deposited in a station to be moved onwards by another vehicle tends to stick around for a while.  Make sure that your feeder vehicles use the instruction "transfer and leave empty", otherwise they'll pick up the cargo they just dropped off.
The harder option is to increase the rate of cargo generation.  For industries, this means placing a station where it can accept cargo from more than one industry of a given type (eg. two coal mines within a rail station's coverage can generate cargo fast enough to have 1500+ waiting, as could a steel mill fed by a dozen iron mines).  For passengers/mail, you can connect a station component with a high radius (eg. a bus station with a radius of 3 connected to an international airport with its radius of 10 will get all the passengers and mail from within the airport's coverage area).
The cheap option is to play games with the rules for catchment areas.  Place disconnected station components (say, drive-through bus stops or loading bays) strategically around the actual station to give it a much larger catchment area (and thus, rate of cargo generation) than it normally would have.
Answer: another way to increase the cargo stored in the station is by increasing the rating of the station. The easiest way to do this is by placing the station in an advertisement area and advertise regulary. This is a lot of work but there are some openttd clients available which can do this automatically for you.
here you can find how stationrating is calculated:
https://wiki.openttd.org/Game_mechanics
I already read some people answered about a lot of busstop to increase catchment area. Another way to do this is by adding tiles with a bigger catchment area to the station. All tiles of the station will get this catchmentarea. See the following link:
http://wiki.citymania.org/index.php?title=Enlarge_catchment_area(trick)
here I found an external link how to store 33k of goods in a station:
http://wiki.citymania.org/index.php?title=Quest:IKEA
this in general holds for any cargo you want to have in a station.

How to increase station storage?


Can a breaker for a sub-panel be located at the bottom of the main panel?

Question: I will be installing a subpanel with a 100A coming off my main panel which is a standard 200A panel. Is it fine to put that 100A breaker at the bottom of the panel or should I move everything down 2 slots and put that breaker at the top if there is enough slack in the lines to do so?
I heard one time that if you put large draw items on the bottom it can cause excessive heat to the bus bar and lead to failure over time to the whole panel.
Answer: The bus bars, bus stabs, in the main panel will handle the maximum current allowed by the main breaker so where that current comes from doesn't matter. The 100 amp breaker can be at the top or the bottom. In new construction, I've always started at the top and worked my way down so I did the large breakers first to get the larger wires in the panel and out of the way. Since your main panel is existing, install the breaker where it's most convenient.
Comment: "The bus bars, bus stabs, in the main panel are rated for the maximum current allowed by the main breaker" That is absolutely **not** true in general. Stab limits are a thing - check your panel label.
Comment: Limits are usually in the 100A to 150A range, so putting a 100A breaker across from another 100A breaker would likely be forbidden even though they wouldn't exceed the overall panel rating. They'd need to be in different rows.
Comment: @nobody  Bad choice of words on my part.
Answer: Nope, that'll make you "zig" when you should've "zagged".

I heard one time that if you put large draw items on the bottom it can cause excessive heat to the bus bar and lead to failure over time to the whole panel.

That idea leads to a conclusion, which is that the breakers should be down the panel largest first, with the 2 largest breakers opposite each other. However, this is nonsense.
What is definitely not nonsense is "stab limits". The stab is the little blade or bar that the breaker clips onto, and serves the breaker on the left and the breaker on the right.  We can tell stab limits aren't nonsense because they're stated right on the panel labeling, and must be followed per NEC 110.3(B).
So you can see: there's an inherent conflict between the "pop logic" of bunching big breakers at the top, vs UL/Code requirements of stab limits.  Your 100A would be opposite another large breaker of 30-60A, and you'd have 130-160A on that bus stab.
The best thing to put opposite a 100A breaker is a generator interlock or a surge suppressor. In generator mode, the stab cannot exceed generator output x 2 even if it was all going to the garage. After that, lightly-used circuits which for some reason need to be dedicated, such as a 1 amp fridge (common sense) or a 6 amp gas furnace (Code).
Note that the loads in the subpanel need to be included in the main panel's NEC 220.82 Load Calculation.  If this is for EV charging, there's a "50A misconception" which is bonkers overkill for home needs. Technology Connections has a first rate video on the topic.
Comment: @isherwood No, it's "bus stab".  Try searching * stab limits* and you'll see the term "bus stab" or "buss stab" widely used.


Take one specific auto-generated ID of a document in Cloud firestore

Question: I'm new to making a simple website that use cloud firestore as a database. When the user add new data, I let firestore generating the document ID automatically (as the image). Now I want to get that document ID but I have no idea about that. Here is my code:
  db.collection("todos").add({
    content: input.value,
    name: name.value,
    time_update: time
  })
  .then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
    return documentId = docRef.id // i try to do this but it does not return the documentID outside this promise
  })
  .catch(function(error) {
    console.error("Error adding document: ", error);
  });

when I use console.log(documentId) outside that promise, it returned "undefined". Please help, thank you!
Comment: I think that this is not a duplicate as the real problem here is understanding how promises work, not how to get the ID.
Short explanation for OP: JS likes to be asynchronous, so promises and callbacks are everywhere. The problem in your code is that the ".then()" can be executed long time after other instructions are processed. So, you should place your console.log in the callback of your .then().
You would have given a more detailed explanation, but the question was closed, so you could have a read about promises here: https://www.freecodecamp.org/news/javascript-promises-explained/
Comment: This should be your actual question: https://stackoverflow.com/questions/47559836/how-can-i-access-a-variable-outside-a-promise-then-method
Answer: You don't need to wait for the callback.  You can get a random ID immediately:
const docRef = db.collection("todos").doc()
const id = docRef.id

Then add the data using set():
docRef.set(...)

The random IDs are generated on the client, not on the server.


neo4j full text search get property that contain keyword

Question: Referring to the documentation https://neo4j.com/docs/cypher-manual/3.5/schema/index/#schema-index-fulltext-search-query
Consider below full text search query
CALL db.index.fulltext.queryNodes("titlesAndDescriptions", 'Full Metal Jacket') YIELD node, score
RETURN node
How do I get which property matches the search keyword keyword. (i.e in above example 'Full Metal Jacket' found in title or description ?)
Answer: you could do something like:
<code>WITH 'Full Metal Jacket' AS searchString

CALL db.index.fulltext.queryNodes("titlesAndDescriptions", searchString) YIELD node, score
WITH node,
     node.title CONTAINS searchString AS inTitle,
     node.description CONTAINS searchString AS inDescription

RETURN node,inTitle,inDescription
</code>
Comment: Thanks you for the suggestion. This partially solve my problem. However if searchString contains wildcards then this won't work.


Discrete Fourier transform of shifted N-periodic sequence

Question: I'm trying to show that if f[n] is an N-periodic sequence then the Discrete Fourier Transform of the shifted sequence f[n-m] for some constant $m\in\mathbb{Z}$ is

$e^{\frac{-2\pi i mk}{N}} F[k]$

where $F[k]$ is the DFT of f[n].
I've started out with expanding the definition of a DFT, giving the DFT of f[n-m] to be
$G[k] = \sum_{n_1=0}^{N-1} f[n_1] e^{\frac{-2\pi i nk}{N}} e^{\frac{2\pi imk}{N}}$
for some dummy variable of summation $n_1$. I am really stuck as to how to continue though - can someone point me in the right direction?
With many thanks,
Froskoy.
Answer: This is not the quickest or easiest proof, but I think it shows conceptually what's really going on here.  You can also just do a direct calculation, which you may prefer to what follows.
Perhaps the most basic reason the discrete Fourier basis is important is that it is an eigenbasis for the shift operator $S:\mathbb{C}^N \to \mathbb{C}^N$ which maps $\begin{bmatrix} x_0 \\ x_1 \\ x_2 \\ \vdots \\ x_{N-1} \end{bmatrix}$ to $\begin{bmatrix} x_{N-1} \\ x_0 \\ x_1 \\ \vdots \\ x_{N-2} \end{bmatrix}$.
For example, one of the (unnormalized) discrete Fourier basis vectors is $v_1 = \begin{bmatrix} 1 \\ \omega \\ \omega^2 \\ \vdots \\ \omega^{N-1} \end{bmatrix}$, where $\omega = e^{\frac{2 \pi i}{N}}$ is an $N$th root of unity.  What happens when you apply $S$ to $v_1$?  You get
\begin{align*}
S v_1 &= \begin{bmatrix} \omega^{N-1} \\ 1 \\ \omega \\ \omega^2 \\ \vdots \\ \omega^{N-2} \end{bmatrix} \\
&= \frac{1}{\omega} v_1 \\
&=\bar{\omega} \,v_1.
\end{align*}
This shows that $v_1$ is an eigenvector of $S$, with eigenvalue $\frac{1}{\omega} = \bar{\omega}$.  You can show similarly that the other discrete Fourier basis vectors are also eigenvectors of $S$, and you will find that the eigenvalue of the $k$th discrete Fourier basis vector is
\begin{align*}
\lambda_k &= \frac{1}{\omega^k} \\
&= \bar{\omega}^k \\
&= e^{\frac{- 2 \pi i k }{N}}.
\end{align*}
It follows that the discrete Fourier basis vectors are also eigenvectors of $S^m$, and the $k$th eigenvalue is $\lambda_k^m = e^{\frac{- 2 \pi i m k }{N}}$.
Suppose the discrete Fourier transform of $x \in \mathbb{C}^N$ is $c$, so that
\begin{equation}
x = \sum_{k=0}^{N-1} c_k v_k.
\end{equation}
($v_k$ is the $k$th discrete Fourier basis vector.)  Then
\begin{align*}
S^m x &= \sum_{k=0}^{N-1} S^m c_k v_k \\
&= \sum_{k=0}^{N-1} c_k S^m v_k \\
&= \sum_{k=0}^{N-1} c_k \lambda_k^m v_k \\
\end{align*}
which shows that the $k$th Fourier coefficient of $Sx$ is
\begin{align*}
\lambda_k^m c_k &=e^{\frac{-2\pi i m k}{N}} c_k.
\end{align*}
This is what we wanted to show.
Comment: Wow! Thank you so much for your help. This really helped me to understand what was going on.
Answer: Hint: For fixed $m\in\mathbb Z$, define $g[n]=f[n-m]$ as another $N$-periodic sequence. Then, $$\begin{align*}G[k] &=\sum_{n=0}^{N-1}g[n]e^{-i2\pi nk/N}\\&=\sum_{n=0}^{N-1}f[n-m]e^{-i2\pi nk/N}\\&=\sum_{\ell=-m}^{N-1-m}f[\ell]e^{-i2\pi (m+\ell)k/N}\\&=e^{-i 2\pi mk/N}\sum_{\ell=-m}^{N-1-m}f[\ell]e^{-i2\pi \ell k/N}\end{align*}$$ Can you now use periodicity of $f$ and $e^{-i2\pi \ell k/N}$ to prove that that last sum is $F[k]$?


Minimize $\| A \cdot x\|$ with coupled $x$

Question: Let $y \in \mathbb{R}^n, B \in \mathbb{R}^{m\times n}$. First we concat $y$ with 1 minus itself to get  $x:=[y, 1-y] \in \mathbb{R}^{2n}$. Here $1$ is the constant one vector.
And we create a block diagonal matrix to get
$$
A = \begin{pmatrix}
        B\\&B
 \end{pmatrix}
$$.
Now my question is given $B$, how can I find $y$ efficiently such that $\|Ax\|$ is minimized? Here $\|\cdot\|$ is the l2 norm.
Comment: Can you elaborate? There is no residual here.
Comment: Just minimise $\|By\|^2 + \|B(e-y)\|^2$. Or wrote $A$ a little differently and express it as a least squares problem directly.
Answer: Solve the least squares problem $\min_y \|\begin{bmatrix} B \\  -B \end{bmatrix}y - \begin{bmatrix} 0 \\ -B e \end{bmatrix}\|^2$.
$e=(1,...,1)^T$.
Comment: Thank you very much! I wonder if adding a constraint $y \in \{0, 1\}^n$ would make the problem harder?
Comment: Probably, depends on $B$ but basically you are moving from solving the first order conditions to a combinatorial problem.
Answer: $A x = \begin{bmatrix} B y \\ B (\mathbf{1} - y) \end{bmatrix} $
$ \| A x \|^2 = y^T B^T B y + (\mathbf{1} - y )^T B^T B (\mathbf{1} - y ) \\
= 2 y^T B^T B y - 2 y^T B^T B \mathbf{1} + \mathbf{1}^T B^T B \mathbf{1} $
So the minimum of this quadratic function occurs at
$ y = \dfrac{1}{2} (B^T B)^{-1} (B^T B) \mathbf{1} = \dfrac{1}{2} \mathbf{1} $
Comment: how did you get the minimum of this quadratic function that occurs right away?
Comment: If $Q$ is positive definite, then $f(x) = x^T Q x + b^T x + c $ has a minimum at $x_0= -\frac{1}{2} Q^{-1} b $.  This can be shown by completing the square, i.e. by showing that $f(x) = (x - x_0)^T Q (x - x_0) + c - x_0^T Q x_0 $


how to loop three variable in javascript

Question: Hello would like to ask how do I loop this javascript.
looks like if I put some for loop into it, it will overwrite my first variable.
$('#select-box1').change(function(){
    $('#changing-img1').attr('src',$('#select-box1').val());
});
$('#select-box2').change(function(){
    $('#changing-img2').attr('src',$('#select-box2').val());
});
$('#select-box2').change(function(){
    $('#changing-img3').attr('src',$('#select-box3').val());
});

Sorry for the silly question.
Comment: It's not clear what you want. Why do you need loops?
Comment: What HTML are you using this with?  What goal are you trying to achieve?
Comment: Why do you think you need to loop? Is the image not being replaced? If so try adding a unique variable (like time in seconds) to the src of the image field. eg `$('#changing-img1').attr('src',$('#select-box1').val() + '?' + Date.now() );`
Answer: Rather than a loop, consider data attributes and a common class.
By attaching your change event to the common class, you can then use the changed element's data-id attribute to determine which image should change.

$('.select-box').change(function() {
  const imgId = $(this).attr("data-id");
  $(`#changing-img${imgId}`).attr('src', $(this).val());
}).change();
img { display: block; width: 50px; height: 50px; }

<select class="select-box" data-id="1">
  <option value="https://picsum.photos/id/123/100/100">One</option>
  <option value="https://picsum.photos/id/841/100/100">Two</option>
</select>

<select class="select-box" data-id="2">
  <option value="https://picsum.photos/id/123/100/100">One</option>
  <option value="https://picsum.photos/id/841/100/100">Two</option>
</select>

<select class="select-box" data-id="3">
  <option value="https://picsum.photos/id/123/100/100">One</option>
  <option value="https://picsum.photos/id/841/100/100">Two</option>
</select>

Comment: wow this is so cool, this is exactly what I need it. looks silly to keep repeat the same script so am trying to improve it. Thank you very much


How can I decode a base64 string in Adaptive-Cards payload?

Question: I need to decode a base64 string being sent from an external service to an MS-Teams Adaptive-Card via a webhook.
I have the webhook setup, tested with postman, all very easy, but I need to somehow decode a base64 string included in the payload, for example;
{
"@context": "https://schema.org/extensions",
"@type": "MessageCard",
"themeColor": "0072C6",
"title": "How to decode a base64 string?",
"text":"eg 'aGVsbG8='"
}
Anyone know if this is possible please?
TIA.
Jarrod.
Comment: Thats not possible inside AdaptiveCards as far as i know...
Answer: It seems like there is no way to decode the code inside the Adaptive card.


iOS Document Imaging APIs

Question: The number of iOS applications that scan, crop, edge detect, and OCR documents has proliferated. Also I am aware of the number of programming APIs that have these features for desktop applications, like Nuance OmniPage, AtlasSoft, and GDPicture.
Is there a popular API or cloud service that an iOS developer should consider using when attempting to build such an app?  Or is this the wrong way to ask this question?
Comment: I'm looking for the same thing... did you find anything useful? I don't need OCR, but I would like to be able to do scanning, edge detection, cropping and image adjustment "offline" (i.e. without requiring a server).
Comment: @jksoegaard have you found any library. i am also looking for same
Comment: @Hasham Found multiple commercial cloud APIs for this. However, haven't found any free libraries.
Comment: OpenCV will be my choice for free.
Comment: @jksoegaard You might check out [Dynamsoft Camera SDK for iOS](https://www.dynamsoft.com/Products/mobile-imaging-sdk.aspx).
Comment: @Rachel That SDK is not only commercial, but also requires Windows on the server. It's not going to work for me.
Comment: @jksoegaard The iOS SDK doesn't require a Windows server. It is a commercial option though. I'm sorry that doesn't work for you.
Comment: Commercial would work fine for me, but these APIs usually do not have pricing on their websites, which means that the prices are generally very high. In my case out of reach as they cost more than the total income expected for the apps due to them not being general purpose apps for everyone in the world, but specialized apps that are used by few hundreds.
Answer: I have been making some progress getting those features out of OpenCV. It might be the easiest route to achieving this on iOS.
If anyone got tips or tricks, they would be greatly appreciated.

iOS Document Imaging APIs


How many EVs do the Festival Plaza services give?

Question: In the Festival Plaza you can have restaurants and bouncy houses that offer services to increase the EVs of a stat you want. I'm wondering how much each option increases EVs by. It's supposed to be a controlled way to raise EVs but it doesn't give you any numbers to control it properly.
Comment: Balloon castles? You mean bouncy houses?
Comment: Yes, im spanish and didnt know the english term XD
Comment: No worries. Just making sure we have the good terms to make the question clearer for everyone.
Answer: For the Bouncy Houses, the lowest level course gives 4 EVs to a Pokémon, doubling with each level.

Level 1 course: 4 EVs
Level 2 course: 8 EVs
Level 3 course: 16 EVs
Level 4 course: 32 EVs
Level 5 course: 64 EVs
Level 6 course: 128 EVs
Level 7 course: 252 EVs

Restaurant values are unknown, but from the description they should be either 16 or 32 EVs.
Comment: Keep in mind that the Friendship Cafe & Friendship Parlor actually *lower* EVs, through the Sweets Sets and the Secret Meals.


Compiling android native app calling ndk-build from eclipse, on ubuntu

Question: On ubuntu 11.10 I installed eclipse from repositories, installed adt and cdt plugins. I am able to compile the hello-jni example using command line, but i would like to use eclipse for the task.
I followed the guide here: http://mhandroid.wordpress.com/2011/01/23/using-eclipse-for-android-cc-development/ and defined a PATH variable in eclipse preferences  (window->preferences->c/c++->environment), pointing to the ndk-r7b folder. But the project won't buid. I get this error:
<code>(Cannot run program "ndk-build"
(in directory "/home/athos/android/ndk-r7b/samples/hello-jni"):
java.io.IOException:
error=2, File o directory non esistente)
</code>
(last line should be "no such file or directory" in english)
If I specify "${PATH}/ndk-build" or "/home/athos/android/ndk-r7b/ndk-build"  as the build command. i get this:
<code>/home/lavoro/android/ndk-r7b/ndk-build
ERROR: Cannot find 'make' program. Please install Cygwin make package
/home/lavoro/android/ndk-r7b/ndk-build: 40: dirname: not found
or define the GNUMAKE variable to point to it.
</code>
If I define the GNUMAKE variable in window->preferences->c/c++->environment i get this:
<code>ERROR: Your GNUMAKE variable is defined to an invalid name: /usr/bin/make
Please fix it to point to a valid make executable (e.g. /usr/bin/make)
</code>
Which is funny, since It suggests the exact same directory I indicated. Make is installed and present at the indicated location.
What am I missing?
Comment: did you get the solution to  this ?
Comment: no, and in the meanwhile I became used to the command line interface :/
Answer: It's a bit ugly, but you can always put
<code>/fully/qualified/path/to/ndk-build
</code>
In your build command.
Comment: sorry for the delay, i just saw this. As i said, I already tried with the fully qualified path (/home/athos/android/ndk-r7b/ndk-build)


How to start uploading photo when the user clicks submit button?

Question: I have one form on the page for addition and it is related with 2 tables in the database.
Eg. Say i have a table named event and one table named eventphotos. The uploadify plugin of jquery for eventphotos works just fine, however, event is the master table and eventphotos is the child table. Thus when i upload the photo due to asynchronous behaviour of uploadify the photo gets submitted on server but there is no EventId present for this photo which throws exception when i try to insert the photo into evenphotos. I hope you got the idea what the problem is.
I want that when the user clicks on the submit button on the form, the photo uploading process should start and it should only get inserted into database once the master record is inserted into table.
How do i make this happen?
Thanks in advance :)
Answer: One solution: Save the image somewhere in a temorary folder using a random generated name, then send this random name back and insert into your form as hidden field. When the form gets submitted you check if the file still exists and load it.
Another solution: Create a table called "temporary_photos" or similar, insert your picture. And send back the ID of the record and insert it as hidden field in your form. Don't forget timestamps so that you can delete images which have never been used. And delete records if you have saved the event!
Comment: The 2nd solution is exactly how I managed this issue. Nice one @sled


What is the benefit to Linguistics SE of banning script or language identification questions?

Question: This question here was recently closed:

I need help identifying this language

The close reason given was:

Questions seeking help with translation and localization are off-topic here unless specifically concerning the linguistic reasons for different translations.

Unless localization is meant to refer to the identification of scripts, I don't see why the question falls under this close reason.
However, more importantly, I don't understand why such questions - solid questions which will have definitive answers, are not beneficial to the site.
Why are such questions not welcome here?
Answer: Well, I think the biggest reason is that this question and its answers wouldn't help any further visitors.
The bottom line is that SE is designed as a storage for quality questions and answers. Quality, obviously, means usefulness (quantified by persons). Being answered, it is definitely useful for the asker, but nobody else would learn from this.
Compare, for example, a question on step-by-step methodology of identifying a language/script, which would be, most certainly, useful for many. Look at this diagram. It is not very scientific, but, for sure, is useful at the beginner's level. (Gujarati is at the right-bottom here)

The same logic, BTW, applies questions on drawing syntax diagrams and language-to-language translations.
Comment: I think your answer is not very helpful or accurate. If the question wasn't closed a good answer could easily explain how and why the script could be identified as whatever script that is. And the descriptors and the name of the language would show up in general searches  on the internet and help a host of people and help  future users here. However, closing the question has prevented this from being the case, reduced the benefit for readers, made the site less likely to be helpful for future users, it seems to me.
Comment: It's also a matter of keeping the floodgates closed. A question about a concrete and unique individual problem *might* elicit useful answers which attempt to generalize a method, but permitting anyone and everyone with a question of this type will inevitably lead to a degradation of overall quality and usefulness of this site. On the other hand, a question specifically about solving this *type* of problem would unequivocally invite answers which will be broadly applicable to others with this problem, and also touch on actual linguistic matters.
Answer: The problem is that this site is named "Linguistics" and not "Language Fans". If this were Language Fans, then such questions plus ones of the form "What does vittu mean?" or "What's the plural of ugali?" would be on topic. Instead, it was set up for linguists and others with an interest in linguistic research and theory. So there's a fundamental divide between scientific questions about language, and fun-facts questions about language. Simply asking "what script is this" is a fun-fact question with no scientific value. It doesn't even lead to describing a property of a script. A question like "how do you determine what the script is" is a method question.
That particular question at least could be answered. Most script questions that we get here have the additional defect of being unanswerable because the pictures are of degenerate examples, so that even if the text is in Russian, the writing is so bad that you can't tell that it's Russian, or writing for that matter.
Comment: No, that is not what I'm saying. I'm saying that given the purpose of LSE, such questions are off-topic, and should not be asked at all. All *you* are saying is that you don't care about the purpose of LSE, you just want it to be a place for Language Fans, where any question even vaguely about language is appropriate. In other words, we disagree on whether LSE has a specific purpose.
Comment: Yes, but all your saying is the same thing that applies to all questions, that when they need turning into a proper question you prompt the OP to do so, not rob future readers of the opportunity of gleaning other linguists' knowledge.
Answer: I am comparatively new here, so I would like to re-open the debate on the language identification (henceforth LI) related questions. Some random thoughts.

LI obviously falls among a linguist's tasks. Who else would do that, otherwise? Imagine a government that needs to know the origin and identity of a written document. Whom would they ask for an expertise? No one but a linguist or a philologist. History and identification of writing systems is something that a historical linguist is supposed to know. People who submit most of the proposals to the Unicode consortium for the standardization of certain scripts or glyphs are either script freaks or linguists (often both).
Sometimes LI is indeed tough. Not because the picture is blurred but because the inscription is too ancient, non-standard or badly written. Or, there could be two different languages using the same writing system and only a specialist could be able to tell the difference between them. To sum up, I can imagine many situations when a LI would be a tough task to accomplish even for a linguist.
Questions concerning LI might seem naïf and useless, but, let me say this: a good percentage of questions submitted to Linguistics Stack Exchange are naïf and totally unscientific. What non specialists know, presume to know, or ask about language is always naïf and wrong, from the viewpoint of a linguist. Are we here for helping people or just for telling them to shut up because they cannot formulate meaningful questions on linguistics?
However stupid a question might be, there is always something intelligent and useful that a specialist can say as an answer. And indeed this is what usually happens: the answers take the inspiration form questions to teach something of general interest. Including the cases of LI questions.
Comment: But this is not a forum like Reddit or Quora. People are expected to go through previous answers and get used to the Stackexchange format. What was happening with LI was that new users would login, make no effort to see if their question may have been answered already, post a question, and disappear forever. If a question were more abstract, let's say, like how to tell European languages apart on sight when most use a latin-based script, it would be more appropriate for this site.
Comment: I used to agree with your first point, but [my new post](https://linguistics.meta.stackexchange.com/questions/1747/any-objections-to-my-formal-addition-of-language-identification-to-our-list-of-o) explains why I've changed my mind. I not against naïve questions either, as shown by [my answer here](https://linguistics.stackexchange.com/questions/20517/why-doesnt-hindi-evolve-to-suit-modern-times), and I can provide many more examples.
Answer: The main reason would be as bytebuster said: there is no reuse value.
But identifying random scraps of written language does not really have anything to do with linguistics. If you disagree, then please tell me which field you think would it fall under? Phonology, semantics, syntax, socio-, language change, computational, translation, pragmatics, discourse...?
However I have been meaning to write up a question and answer for how to use Google Translate to identify languages. If I did that then all these questions could perhaps be closed as duplicates rather than just closed.
Comment: @Janus If Linear A is deciphered it won't be announced first on this site ;) I think there's a difference between a linguist deciphering a script, with all of the work, hypotheses, logic and arguments that would take, and a person recognising by sight what a language is. By all means lets have the first category of question, but the second category do not belong.
Comment: There's loads of reuse value if the answers are good (an impossibility if the question has been swiftly closed). Describing languages, including their writing systems, is an inherently linguistic thing to do, it seems to me. Or am I missing something? What fields might it fall under? Well you seem to have already mentioned computational linguistics, but there's also anthropological linguistics, forensic linguistics, relevance theory and so on and so forth. There are, of course linguistic texts about [writing systems](http://www.citeulike.org/group/214/article/214722).
Comment: « But identifying random scraps of written language does not really have anything to do with linguistics. » — So you wouldn't consider the longstanding philological work of, say, deciphering Linear B or the Rosetta Stone counts as linguistic work? I would definitely call philology an aspect of linguistics.
Comment: @Araucaria Language description is of course on-topic, but simply identifying languages is not language description. Orthography is on-topic, but I see no reason for identifying an orthography to be on-topic.


getting packages into Ubuntu during Debian freeze

Question: I am the developer of an application found in the Ubuntu repos. A few months ago I released a new version which I packaged and submitted to Debian. The  package was accepted and uploaded to experimental because Debian was and still is frozen for release. This package has not been picked up by 13.04 because Ubuntu imports from unstable which still has the old version.
How do I get my package into Ubuntu 13.04, given that Debian is frozen?
Answer: I needed to request a package sync.
The information for how to do this is located here:
https://wiki.ubuntu.com/SyncRequestProcess
I followed the recomendations there and used the requestsync commandline tools as follows:
<code>sudo apt-get install ubuntu-dev-tools
requestsync -d experimental widemargin
</code>
This raised a bug request on launchpad which can be seen here:
https://bugs.launchpad.net/ubuntu/+source/widemargin/+bug/1146015
The bug was fixed within 3 hours by Julian Taylor (jtaylor) who uploaded it to ubuntu 13.04
Julian Taylor you ROCK!!!
That is all.
Comment: Posting a problem and then posting your solution to a problem are the best questions! Great job! All up vote! :)


Splitting bits in Java

Question: I want to split 16 bits into two 8 bit sections, but I can not think an idea how to do it.
Ex. 1111111000011111
Output: 11111110 and 00011111
Here's my code so far:
while (scan.hasNextLine()){

        bin = scan.nextLine();
        String[] memory = new String[] bin.length()/8;
        for (int i = 0; i < memory.length; i++){
            memory[i] = bin.substring(i*8, i*8 + 8);
        }

but its error.
Comment: What are these bits stored in?  An `int`? A `char`?
Comment: Actually I will get a value on a textfile.
Comment: I posted my code, but its error
Comment: @user6051183 what kind of error do you get?
Comment: It says, missing an array dimension and an illegal start of expression.
Comment: Thankyou. theres no error, but how I gonna print it?
Answer: When instantiating an array, you have to specify the size inside the brackets, so replace:
String[] memory = new String[] bin.length()/8;, by
String[] memory = new String[bin.length()/8];
Comment: @user6051183 print it to where?
Comment: In console. Or by system.out println();
Comment: @user6051183, you could do it inside the main loop, by adding `System.out.println(memory[i])` at the end of the loop body. Or start a new loop after you finished populating your `memory` array
Comment: Thankyou, last Question. what if I have '1000010100000011' is it possible that I will get an output of 00000011 and 10000101 instead of 10000101 and 00000011?
Comment: The way your code is, it will get the bytes from left to right, so you would get 10000101 and 00000011. If you want the order to change, you could code that in
Comment: Yeah because I dont have an idea how to reverse it  by the way can i store it on array of 256 items of sting of length 8? I cant understand it.
Comment: Hahaha. yeah, im confused becuase 1 byte is equal to 8bits. But, 256. Well ;)

Splitting bits in Java


How do you find the partial derivative of $F(u, v) = f(x(u, v), y(u, v))$?

Question: Suppose that $F(u, v) = f(x(u, v), y(u, v))$, where $f$ is a function satisfying $f(1, 2) = 3$,
$f_x(1, 2) = 1$ and $f_y(1, 2) = −2$. Suppose further that $x(u, v) = u + v − 1$ and $y(u, v) = 3uv − 1$. Find $F_u(1, 1)$. (Note: likely this is a typo.)
Can someone please explain how to solve this because I really don't know how?
The answer is supposedly    $-5$.
Comment: You can't. You could possibly find $F_u(1,2)$, but you don't have enough information for $x=1, y=1$.
Answer: Given $F(u, v) = f(x(u, v), y(u, v))$, we want to first find $F_u(u, v)$ in order to evaluate it. We know that $f$ depends on both $x,y$ and each of those depend on $u$.
$$F_u(u, v) = f_u(x(u, v), y(u, v)) = f_x(x,y) x_u(u,v) + f_y(x,y) y_u(u,v)$$
Or with less notation,
$$F_u = f_u = f_x x_u + f_y y_u$$
This should give you a start, though as Thomas said in the comments, you can't hope to find $F_u(1,1)$! $F_u(1,2)$ on the other hand does indeed equal -5.
Comment: Thanks! This question is from my exam review I guess it was just a mistake then.


upgrade manager just closes

Question: I keep on trying to upgrade this PC, but after getting the upgrade tool the distribution window closes and does not remember that I have tried upgrading. Is their any solution to this problem? I am upgrading form 10.04 to 10.10. Thank you.
Comment: Updated the Ubuntu 9.10 and rebooted now Update Manager disappears when you try to use it
Answer: I would suggest you report a bug by pressing Alt+F2 and then entering ubuntu-bug update-manager. This will allow the developers to help improve Ubuntu. (The same procedure is used for any application.)
Answer: I will commit a small heresy and say, upgrades don't always work. If you have lots of outside sources from PPAs and have applications on your system that are not standard releases, perhaps obtained by PPA or compiled yourself, it causes problems with the upgrade. Then you may have no alternative but to identify those packages and roll back to the standard Ubuntu versions. Then try again. In the worst case, you may need to do a fresh installation.
See: http://www.howtogeek.com/howto/29584/safely-remove-ppas-and-roll-back-to-stable-versions-in-ubuntu/
Fresh installations are nothing to be feared. You get a clean slate. I always do them and it is a piece of cake.
My method is to first have a separate home partition. If you don't have this then you have to go through the added step of copying the files from your home folder to another device, such as a usb stick (make sure that you get the hidden files too, Ctrl+H). My home partition is at least five years old and I have re-used it at least 20 times and never backed up or saved anything, without any data loss. So much for the advantage of re-using a separate home...
The next step is to save your list of installed applications. You can use the commandline, but I prefer Synaptic. You open Synaptic and go to File, Save Markings (tick the box for full state). Give it a name and put it in a safe place, such as on your usb stick. Re-install. Re-boot. If necessary re-copy files back to home. Open Synaptic. Go to File, Read Markings and navigate to the text file. Apply and do something else till it is done.
Try the roll back idea first, if fresh installations scare you (it's almost Hallowe'en afterall). Booh! :)
Comment: The upgrade tool already disables PPAs before attempting an upgrade.

upgrade manager just closes


Sqlite database couldnt found when run in the device

Question: In my application i m using sqlite database.when i run it in iphone simulater it works fine.but it cant connect database with device.the path for that database is:
 /Users/taxsmart7/Library/Application Support/iPhone Simulator/4.3/Applications/A644750D- 5175-4FF1-BDA7-6EDF65895180/Documents/BillSplitter.sqlite

when i connect with my device the database display blank.
Comment: are you bundling a pre-prepared .sqlite file with the app, or is the app creating a fresh db?
Comment: yup i am using pre-prepaid sqlite file
Answer: That's normal, this is the path of the database when running on simulator, saying differently : on your mac. The path to your application, and the whole "file system" hierarchy when running on device is totally different.
You shouldn't use any absolute path in your application, and work only from the application root folder, which is something like :
/private/var/mobile/Applications/A644750D-5175-4FF1-BDA7-6EDF65895180/
So if you wanna use a database in your application, you'll have to copy it in the bundle and find the right path to it, or to create one when excuting on device.
HTH
EDIT : the path scheme above may be wrong, I suspect it's just the path to the "Documents" folder reserved to the application. Anyway, my advice stays the same : use relative pathes.
Comment: How can I set this this path?
Comment: You don't have to, you have to use a relative path. Have a look on your bundle structure, and just use something like `./Data/mydb.sqlite`.
Comment: where to give the relative path?
Comment: In addition, knowing you use a pre-prepared file, think about checking bundle options like "copy to output folder" or something like that (can't be more precise since I use MonoTouch only, sorry), otherwise you could set the right path but no result because the file wouldn't be present on device.
Comment: You have to use this relative path when opening your DB connection. I think you use some string like `Data Source=/path/to/DB.sqlite`, no? Here is the path to be replaced.
Answer: If you need only read sqlite3 database it makes sense to work with database in app bundle.
You open database as in example:

NSString *pathname = [[NSBundle mainBundle] pathForResource:@"nameOfYourDatabase" ofType:@"sqlite3"]; // extension could not be .sqlite3!!! Have a look on your db file.
sqlite3 *database;
int res = sqlite3_open_v2([pathname UTF8String], &database, SQLITE_OPEN_READONLY, NULL);
if (res != SQLITE_OK) {
    NSLog(@"Error opening database %@", pathname);
    sqlite3_close(database);
}

If you need to write in database on first run of your app you need to copy database file from app bundle into app documents directory and then open database for read and write access.


Missing cookies on iframe in safari 5.1.5

Question: This is for Safari 5.1.4 and 5.1.5 only. It works on older Safari versions.
if you go to:
http://gemal.dk/test/restob.html
and click on the button you get a Online Booking inside a iframe
If you the click on a green day and then a time you are presented with a "Your session has expired".
If you check the cookies you dont have any cookies.
Safari is rejecting the session cookies and this started around the Safari/Google issue where Safari became more strict about 3rd party cookies. Version 5.1.4+
How can I solve this? How can I set the cookies in the iframe?
I send the correct P3P headers. I've tried a lot of things I just cant get it working.
It works in all other browsers than Safari 5.1.4+
Answer: Maybe ,The following link would be helpful to you .
http://www.reizbombardement.de/archives/safari-5-1-4-enforces-cookie-policy
Safari 3rd party cookie iframe trick no longer working?
Certainly, To set a cookie for your domain and refresh the opener and then closes,
you must prepare dummy page(ex...safari_cookie_fix.php)
But...
In Our project , We prepare its dummy page as Good-looking(Not bad usability!) loading page.
Answer: I experimented a similar problem.
A web "parent" page open my "child" website in a jquery fancybox i-frame cross-domain.
Not problem at all with Explorer, Chrome, Firefox, Opera and even with Safari (5.8.1) on MAC.
But with iPhone, iPad and mini iPad, the session in the i-frame is lost.
That's mean that at every click on an element in the i-frame (web site is in aspx) a new session started.
We solve the problem in a very simple way:
when the parent website start, it call a page in the child site directly (not in an i-frame). In this page I just set a session variable and I redirect to the parent website.
Now when the child website is open in an iframe, the session is kept.


Different coloured print strings in python - IDLE

Question: I'm using IDLE to just create a short, basic text adventure game. the methods I try work in other editors such as Repl.it or canopy, but I prefer the use of IDLE as I just like the simplicity of it, and that it doesn't require an Internet connection to access.
I won't mention the methods I tried, as I may have just been approaching them in the entirely wrong way, or maybe IDLE just simply doesn't have the functionality of other editors, but I just want to make the text in the game clearer to distinguish. For example, below is a short segment:
import time

print ("Welcome Traveller!")
time.sleep(1)
def name_identify():
    print ()
    name_input = input ("What is your name? ").lower()
    name_input = name_input.title()
    time.sleep(0.75)
    def name_confirm():
        print ()
        print ("So %s is your name then?" % name_input)

Where the questions such as
name_input = input ("What is your name? ").lower()

appear in a different colour, or bold/italic even. As things similar to
print ("\x1B[3mHello World\x1B[23m")

and
print ("\033[1;31m""Hello world")

don't work, I assume this function is not naturally supported, so I ask, if it is possible to either A, make it supported, so this method, or similar work, or B, another option which does make changes at least similar to what I seek?
It would be very helpful if anyone could provide me with a way to do this, or at the very least an editor which is close in simplicity (design wise) to IDLE and does support the functions I seek. The version of python I am currently using is 3.6.1.
Thanks in advance, and I apologise if my wording confuses you, just ask about what confused you and I will attempt to clarify. Using Windows with the Idle Shell.
Due to the limitations of some python environments, I just used Tkinter to create an interactive procedurally generated script which you can scroll along as if it were the shell, with the added bonus of adding pictures for more depth.
Comment: Your commands work in the linux terminal. You probably need to verify for the kind of console you are using.
Comment: The issue is not the editor but the terminal or console where you direct your output.  IDLE's shell is designed for developing programs, not for running them.  You should specify your OS.  If you run your program (without IDLE) in unix, color is, as 'silgon' said, usually no problem as the console window should emulate a *color* terminal.  On Windows, the console window (Command Prompt) emulates a decades-old black and white terminal.  The workaround has been described in answers to other questions.
Answer: I know what you are going through right now, but there is no benefit to make text colored or bold in python without GUI. If somehow you manage to do it it will turn back to normal text when you make the file to exe format. I have wasted a week on this.
It only makes sense when you are reach GUI programming. Tkinter would be a good place to start.
Its does not matter on the IDE but on the compiler.
In tkinter its a matter of seconds
  lab_practice = label(text = "practice",fg = "red#the foreground color",bg = "yellow",font = ("Arial",40))

Comment: even without a GUI, the clarity of different colored text helps while looking over the text of the game in tests, even if it doesn't last when turned into an executable file.

And suppose I did end up with a GUI using Tkinter(as I was looking as using it to add some images and clickable buttons), even then how would I change the color of the text, as I didn't look too deeply into it.
Comment: If one runs a program in a color terminal emulator that responds to text color change commands, coloring text makes complete sense.  The color is in the output, as commanded, and the coding for the color does *not* disappear when the code is saved.  If one edits python code in a programming editor, such as IDLE, color syntax is *very* helpful even though the color disappears when the window is closed.  The editor's color generating code does not disappear.  That said (or your opening paragraph removed), a gui is a great way to make a Windows or cross-platform colored application.


Installing software to another root

Question: I am running Ubuntu 15.10 32-bit on my computer. I am building a minimal kernel + busybox system from inside Ubuntu. I can already boot that system and run all busybox tools from it. But now I want to go further: I want to install the X Window System and a tiny window manager (probably IceWM). But I do not have internet connection in my minimal system yet and my computer is very, very slow, so compiling X from source is a big pain. My best bet is to use APT to download the X Window System and all its dependencies from Ubuntu repositories and install it to my minimal system's root filesystem, which is in /dev/sda2 (Ubuntu is in /dev/sda1). Is there a way to install packages with apt-get (or even dpkg, if needed) to another root, including all dependencies/libs?
Thanks in advance.
Comment: Are you dual-booting with GRUB? Why don't you have internet connectivity from within your minimal system?
Answer: Since you seem to have internet connectivity from /dev/sda1, the approach I would try first is:
<code>sudo mount /dev/sda2 /mnt
sudo chroot /mnt
  apt-get update
  apt-get install xorg icewm
  exit
sudo umount /mnt
</code>

Installing software to another root


Can I short live Rc and Rh terminals together as R?

Question: I have separated HVAC system with 24V on Rc and Heating system with 24V on Rh. The nest thermostat 2020 has only R terminal. The voltage difference between Rc and RH is about 2V. Can I short Rc and Rh together, put into R terminal?
Comment: Do you want the heating and the cooling to come on at the same time?
Answer: You need to return it and get a different 'stat
The thermostat you have is a refresh of the Nest "E" model, and thus is a stripped-down version that doesn't support more sophisticated systems, such as your two-transformer system, or multi-stage systems of any sort for that matter.  You will need to return it and get a full-fledged 3rd generation Nest, or some other thermostat for that matter, that has separate Rh and Rc terminals.


Why I can't redirect to another URL when I close a modal dialog in SharePoint?

Question: very new in SharePoint and I have the following problem implementing a specific modal dialog behavior in SharePoint 2013.
I have the following situation. In a webpart I am opening another webpart into a modal dialog (and this is not a problem). Then, when the modal dialog is closed, I have to refresh the parent page (not the dialog that is closed) into another webpart. I am trying to implement this behavior via JavaScript, in this way:
string javascript = "function openEdit(link) {"         +
                        "var options = {"               +
                                        "url: link,"    +
                                        "dialogReturnValueCallback: Callback"   +
                                       "};"             +
                        "SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);"  +
                     "}"                                +
                     "function Callback(dialogResult, ret)  {"          +
                        "alert('TEST');"                +
                        "window.frameElement.commitPopup();"            +
                        //"window.location.replace(\"" + linkRed + "\");" +
                        "window.parent.location.herf = 'http://www.google.com'" +

                     "}"                                +
                     "openEdit(\"" + linkPrint + "\");";

ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "CallJS", javascript, true);

As you can see, in my parent webpart I am using the openEdit() JS function to open the link (represented by the value of the linkPrint string variable (it works).
I am also declaring callback function that is called when my modal dialog is closed. It correctly enter into this Callback() function (I see it because I put the alert()) but then I expected to be redirected to google.com (or to the URL on another webpart changing this value) but it is not working. It is redirecting and refreshing the parent page from where I opened my modal dialog window.
Why? What is wrong? What am I missing? How can I fix this issue?
Comment: what the commitPopup do . may be yu should try an alert after that too . and may look into this ! https://stackoverflow.com/questions/9889459/which-one-is-better-approach-window-parent-location-href-or-window-top-location
Answer: Modify the code as below. Note: In you code replace "herf" with "href" and use window.location.href to redirect other page.
var linkPrint = "http://sp2013/sites/team/Lists/Test/EditForm.aspx?ID=1";
string javascript = "function openEdit(link) {" +
            "var options = {" +
                            "url: link," +
                            "dialogReturnValueCallback: Callback" +
                           "};" +
            "SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);" +
         "}" +
         "function Callback(dialogResult, ret)  {" +
            "alert('TEST');" +
            "window.location.href= 'http://www.google.com';" +
         "}" +
         "openEdit(\"" + linkPrint + "\");";

ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "CallJS", javascript, true);


How do I track apps downloaded with "sudo apt-get"?

Question: Since using Linux mainly for developer purposes, I often encounter running various sudo apt-get commands downloading different tools.
These also install many dependency libraries.
Now is there a solution, through command-line or GUI, whereby it shows all apt-get commands executed for downloaded apps listing its required dependency tree?
That way it would be lovely to simply track what all stuff you did with your system.
Comment: Do I understand correctly that your real problem is as follows? Apps need dependencies, so apt installs them. When you uninstall an app you also want to uninstall the dependencies.
Answer: TL;DR: Look in the package manager's logs, especially /var/log/apt/history.log.
To see what package management operations have been performed, I recommend consulting the APT and dpkg logs.

/var/log/apt/term.log shows the APT operations that have been performed. It is essentially the same text shown on the terminal when you run commands like apt-get, and date and timestamps are provided so it's clear when each operation was done.
/var/log/apt/history.log shows each package management operation performed by APT, who did it, what command was run to do it, and what packages and versions were affected. (This seems  very similar to what you are asking for.)
/var/log/dpkg.log is the log for dpkg, which is the lower-level utility called by apt-get and other tools. It gives a list of operations on and statuses for each package that was added, removed, or modified, and the relevant versions.

To see the list of packages that a particular package needs (its dependencies), the packages that depend on it (its reverse dependencies), and some other information, you can run:
apt-cache showpkg package
Replace package with the actual name of the package.
Comment: `/var/log/apt/history.log` is much more useful. But it shows recent commands. Any script that would save its output time-to-time for a more historical overview?
Comment: @arjun Are you looking for information about what happened prior to the earliest entries in `history.log`? As logs grow and age, they're [rotated](https://en.wikipedia.org/wiki/Log_rotation) into compressed `.gz` files: `history.log.1.gz`, `history.log.2.gz`, and so forth. The higher the number in the filename, the older the log. These are ordinary `.gz` files and you can open and read them the same way as any such file, but if you like using `less` to view `.log` files, then I suggest the `zless` command, e.g., `zless history.log.1.gz`. (There's also `zcat`.) Is that what you're looking for?
Comment: Linux is cool! Sure there must be a command or tool which separates this list between system and user softwares.
Comment: @arjun There isn't really a clear definition of user and system software — if by user software you mean software installed locally *only for that user*, then such local one-user-only softwares cannot be installed through apt (unless you manually edit the package's install script).


Are the Stormcloaks or Imperial Legion the "Official" winners of the civil war?

Question: I've finished the Stormcloaks and Imperial Legion, and both seem to have endings which could support an Elder Scrolls sequel in which a war occurs with the Thalmor.
I'm used to seeing Bethesda make games with choices that end up achieving the same thing, are inconsequential to a sequel, or are the "right" way to finish. I don't think the civil war's winner would be ignored in the inevitable "The Brief History of Skyrim" series or similar in-game books. It seems like a very important development.
Is there any additional dialogue or hints as to what side was intended to win the war that I might have missed? I've noticed in my current game that while the Stormcloaks have supposedly ousted the Legion from Skyrim, the Imperial Legion still appears to hold certain towns on their strategic maps.

 Does that mean that while Tullius is dead, the Imperial Legion will just promote a new leader who will return to annex Skyrim?

Will the soldiers in the hidden wilderness camps continue to fight for the various garrisons around Skyrim?
If you intend to include dialogue or plot which could be considered a spoiler, please use the >! spoiler tag.
Comment: [Daggerfall had six endings occur simultaneously.](http://elderscrolls.wikia.com/wiki/The_Elder_Scrolls_II:_Daggerfall#Continuity)
Comment: The Thalmor will probably invade anyway and, as victors, will get to write the history books.  "4E 201: The silly kids in Skyrim started shouting at each other again.  We put an end to that nonsense."
Comment: Bethesda themselves probably don't know, considering how they've handled continuity in the past (i.e., they don't bother until they start on the sequel). I'm not sure if that makes this inherently speculative, but I'm pretty sure it will attract (er, *has* attracted) speculation. :-/
Comment: Both sides lose. The Thalmor invade and easily conquer the divided and weakened empire.
Comment: I believe we will have to wait for the next The Elder Scrolls game to be released to have this answer. ESO doesn't count because it's story happens in a far away past.
Comment: @Ullallulloo Wow, having read that, I really, really want to play Daggerfall.
Comment: @Thaumajig TES VI should tell us the canon conclusion of Skyrim.
Answer: I think it will turn out that both sides are the official "answer."  Whatever side the Dragonborn sides with will turn out to be the right one.  If the Dragonborn sides with the empire, s/he will eventually lead the empire back to health and defeat the Aldmeri Dominion as a great hero. If the Dragonborn sides with Skyrim, then s/he will eventually lead Skyrim into the collapsing sections of the empire and defeat the Aldmeri Dominion.
The Dragonborn has impressed gods and dealt with daedra.  No matter who you side with as the Dragonborn, I don't think you're going to play second fiddle for long.  Ulfric would soon be overshadowed by a Dragonborn who will come to lead Skyrim (if sided with Stormcloaks) and I think it is inevitable you lead the empire if you side with them (especially since

 the Emperor is assassinated by the Dark Brotherhood no matter who wins).

As another poster mentioned, in the end it won't matter who 'won' this war.  All the histories will record is the return and rise of The Dragonborn.  After I beat the game (which I've done a few times now), I'm itching to go frag some Altmeri butt.  Hopefully I won't have to wait until Elder Scrolls VI to do it!
Comment: Interestingly I am working through the Civil war quest line now but I wiped the dark brotherhood out instead of joining them. I wonder if the emperor will still be assassinated.
Comment: @Colin Can't actuall wipe them out really... seeing as there's a member who cannot die. The Night Mother's been dead for over a thousand years. She'll just restart the brotherhood with another listener.
Comment: Which of the 4 people in the Abandoned Shack you decide to kill does have an effect on your spoiler.  ;)
Comment: Based on TES lore much of this answer is beyond speculation pertaining to the future of the Dragonborn. If we look at past heroes (Hero of Kvatch, Nerevarine, Agent and the Eternal Champion - not to mention those from the lesser games) their story begins and ends with the main plot of their respective game and the main plots of subsequent DLC's. There's no indication that the hero of Skyrim would go on to be anything more than the killer of Alduin, Harkon and Miraak. To say the DB has "impressed gods" you may as well say they also murdered the entire Skyrim population of chickens.
Answer: Bethesda has already written into the lore as it stands that other provinces have broken away from the Empire - Black Marsh and Elsweyr seceded after the Oblivion Crisis, Hammerfell refused to submit to the White Gold Concordat, etc.  Future lore can sum up the Skyrim era with a simple "The Empire fragmented as provinces seceded or fell to infighting before finally being restored."  So long as they don't list which provinces left the Empire, there's no need to specifically state how the Stormcloak Rebellion turned out.
Answer: I'm extremely late to this party but I wanted to document a little evidence form within the game that hasn't been mentioned elsewhere in the answers here; the Stormcloak Missive in Fort Neugrad (transcript below).

Lord Ulfric,
Though we drove the Emperor's dogs from Fort Neugrad, they still nip at our heels. The chaos in Helgen is bad enough, but now I have word of a new Imperial force assembling in the south, ready to advance on our position as Pale Pass is clear. Send reinforcements, or all our gains will be for naught.

This only appears under certain conditions which I believe are that the Dragonborn handed Falkreath to the Stormcloaks during Season Unending and then joined the Imperial Legion to retake Falkreath.
This missive indicates that there is a "new Imperial force assembling in the south" which is preparing to move in to attack the rebels in Skyrim. The desperate wording could indicate either; the soldier is worried about losing their foothold in Falkreath or, he is worried about losing the war. The fact that the Emperor has assembled a Cyrodiilic Legion force with the purpose of sending them to quell the rebellion in Skyrim demonstrates that the Emperor does indeed take the civil war seriously, despite assertions to the contrary from some NPC's. As such, since the Legion isn't being used to fight battles within Cyrodiil at the moment it would be quite reasonable for the Emperor to send a large force to assist the army in Skyrim.
How is this a relevant factor given that the Stormcloaks are already in a stalemate with the Empire? The Skyrim Legion is composed primarily of local Nord recruits - individuals not much better (if at all) than any Stormcloak soldier, except with arguably better equipment. Likewise, some Legion veterans since joined the rebellion, leaving both sides with a number of experienced soldiers and novice recruits. The tipping point is the force from Cyrodiil being a full Imperial Legion of well-trained soldiers, not local Nordic farmers.
While we can but speculate the outcome of a Stormcloak vs Cyrodiilic Empire war it would be fair to assume that the Cryodiilic Legion would be more effective than it's Skyrim counterpart and able to overcome a rebel force, leading Skyrim to an Imperial victory.
Thus, whether the war is left unresolved or as a Stormcloak victory the southern Legion force would still (re)take Skyrim for the Empire.
Further thoughts
Other answers have mentioned the Dragonborn becoming some kind of leader or overshadowing the events of the Civil War - this would be very out of character for Bethesda lore. Historically, every TES hero has played a role which is equivalent to the respective game's main quest line (and subsequent DLC quest lines). No more, no less. To say the Dragonborn will become a heroic leader of an entire army is very speculative since, based on all previous heroes the Dragonborn's story ends with the defeat of Miraak on Solstheim.
Answer: As the Empire's power may be fluctuating throughout the game, it is still very obvious that the Thalmor wish for the Rebels to be the victors. The Dominion would prefer if Ulfric and his insurrectionists even temporarily overthrew the Empire that was started by the very man who destroyed one of their previous Dominions. Bethesda would most likely not choose the side of the Thalmor, due to the face that they made them the villains. (Don't deny it Dominion fanboys.) The Empire is truly the free Tamriel's only hope from either the Dominion or eventually those of Akivir or Alduin again.
Comment: Welcome to Arqade! This is really a comment, not an answer. With a bit more rep, [you will be able to post comments](http://gaming.stackexchange.com/privileges/comment). However, be aware that Arqade is not a discussion forum.
Answer: It doesn't matter which side you back, there will continue to be skirmishes in the field that you can come across. Both sides will mention this when you complete the final phase of their campaign and deal with the opposing faction's leader.
It's not really defined who Bethesda will pick as the canon victor until some DLC or more likely, the next game in the series. It stands to reason that the Empire/Altmeri would continue to attack Skyrim until they controlled it barring some other problem arising that demanded their attention.
Answer: Officially, the Civil War ended with the truce atop High Hrothgar. I think Skyrim and Cyrodill will fight the Altmer together and and in doing so, Skyrim will win its independence from the Empire.
Comment: Do you have any sources for this claim?
Answer: if you side with stormcloaks you well reform a new empire after you kill the thalmor if you side with the empire you well kill the thalmor. so it like 2 doors that lead to the same room but the stormcloak hall is longer. so either way what the stormcloaks want well happen. in elder scrolls 6 it likely wont say who won the civil war, but the thalmor well be defeated.
Comment: but if you go with the stormcloaks you well restor talos faster even thow it will take longer to kill the thalmor.
Answer: In my point of view, I would probably say that the Empire will most likely be the official victor in the game for several reasons.
First and foremost, and as mentioned before from a variety of people, Talos (the first ruler as well as founding father of the empire) was a dragonborn and so the last dragonborn (your character in the game) has to be the rightful ruler of the empire, who will eventually restore peace throughout Tamriel and wipe out the Aldmeri dominion once and for all (after dealing with the rebels).
Secondly, there are numerous rumors throughout the game, that point out that there will be a second great war.
Last but not least, Jarl Balgruff of Whiterun is a close friend of the dragonborn, simply because the dragonborn helped him out with his dragon problem, which he was trying to deal with. As far as my knowledge is concerned, Balgruff joined the empire, and I personally do not think that the dragonborn will choose to betray him instead of signing with the empire and helping him out once again.
Answer: I would say that there is no conclusion to the conflict, regardless of which side you choose. If you choose the Stormcloaks, the dialogue at the end clearly indicates that the empire will try to reassert control over Skyrim, and if you choose the Imperial Legion, the rebellion is thwarted, but not completely crushed into non-existence.
I found the ending quite unsatisfying in that the Elderscrolls games are about the destiny of the character, and while defeating Alduin might be a grand heroic feat, it is only the beginning of the story for the "Dragonborn", just as banishing Alduin was only the beginning for Talos. (Talos went on to forge the Empire).I personally would pay another $50 or $60 for an expansion that allows us to explore the full destiny of the "Dragonborn". I was hoping (too ambitiously) that we would get to see the Dragonborn take up his mantle as the rightful heir to the throne of the Empire. Talos, the first Dragonborn founded the Empire; it seems that it should be the destiny of the last Dragonborn to restore it.
Picture this: After you defeat Alduin, you meet with all the surviving members of the Akavari. There are more than just two. Maybe a couple dozen. They are there to convince you of your destiny to restore the Empire. After you agree, you get on a dock at one of the Port Cities (regardless of which faction you chose, Imperials or Stormcloaks). At the dock a ship awaits you and the game renders a big fleet out on the water to make it look like you are joining an invasion fleet. Destination: Cyrodil and the Imperial city from Oblivion. You and the army land and must fight all the way to the palace, fighting combined legions of Altmeri and Imperials. Either the Imperials, or the stormcloaks from Skyrim fight beside you, along with the Akavari who serve as your personal bodyguard. You must penetrate to the Imperial city and destroy the puppet on the throne, and then YOU are crowned as the rightful Emperor, the DRAGONBORN.
That is how it should have ended.
Comment: This posting is 20% answering the question and 80% fanfiction.
Answer: If you look at the two sides of the war, you will see that the empire is most likely the winner.  For one, no matter which side you choose, Jarl Balgruuf and Whiterun will go with the empire.  Assume that if the Dragonborn sides with the Stormcloaks, he is most likely a Nord. So there is a 1 in 10 chance of the Dragonborn being a Stormcloak (the 10 being the total number of playable races). So the only way we can beat the Aldmeri Dominion's hatred towards humans is to hate all Mer kind after raising our strength after crushing the rebellion.


Calculate percentage between two numbers?

Question: I have these two numbers original one is 1000 the new one is 440
I need to calculate the percentage between them as follow:
1000
440

The percentage that getting is 44% and left is 56%

my helper function:
function calculatePercentage($original, $given)
{
    $percentChange = (($original - $given) / $original) * 100;

    return round(abs($percentChange)) . '%';
}

This gives me the reset percentage!
Answer: Wouldn't it be like
function calculatePercentage($original, $given)
{
    $percentChange = ($given / $original) * 100;

    return round(abs($percentChange)) . '%';
}

If I am wrong, I probably didn't understand ques enough
Comment: that gives me `227%`!
Answer: use this
    function calculatePercentage($original, $given)
    {
        $percentageOfGiven = round(abs( ($given * 100) / $original ));

        return [
            'getting' => $percentageOfGiven . '%',
            'left' => (100 - $percentageOfGiven) . '%'
        ];
    }

The output will be like [ 'getting' => "44%", 'left' => "56%"] .
The principle used is that if the original is 100% then what would be the given value.