paths from tsconfig.json doesn't work after tsc

Question: In my Express project, I import from paths like @common/foo. Thanks to paths in tsconfig.json, it's just an alias to ../common/src/foo. That's awesome and works in development with this script in nodemon.json:
{
    "watch": ["src", "../common/src"],
    "ext": "ts",
    "ignore": ["src/public"],
    "exec": "ts-node -r tsconfig-paths/register src/index.ts"
  }

The problem is that I can't make it work in production mode.
I build the project with tsc, and if I inspect the generated files, they import stuff from @common/ and not from ../common/src/. At first I thought it's fine, since tsconfig-paths works in runtime, so I just need to include it in the start script as such:
node -r tsconfig-paths/register dist/index.js

Unfortunately it didn't work, and I get those Cannot find module '@common/foo error messages in console.
What's the problem? Did i configured it wrong?

My package.json (dropped all irrelevant parts):
{
  "main": "index.js",
  "scripts": {
    "start": "cross-env NODE_ENV=prod node dist/index.js",
    "build": "rimraf ./dist/ && cross-env NODE_ENV=prod tsc"
  },
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "@types/express": "^4.17.4",
    "@types/node": "^13.11.0",
    "cross-env": "^6.0.3",
    "rimraf": "^3.0.2",
    "ts-node": "^8.8.2",
    "tsconfig-paths": "^3.9.0",
    "typescript": "^3.8.3"
  }
}

My tsconfig.json (dropped all irrelevant parts):
{
  "compilerOptions": {
    "module": "commonjs",
    "baseUrl": "./",
    "outDir": "dist",
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "noImplicitAny": false,
    "target": "es6",
    "emitDecoratorMetadata": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "types": [
      "node"
    ],
    "typeRoots": [
      "node_modules/@types"
    ],
    "paths": {
      "@common/*": [
        "../common/src/*"
      ]
    }
  },
  "include": [
    "./src/**/*.ts"
  ],
  "exclude": [
    "./src/dist/"
  ],
  "references": [
    {
      "path": "../common"
    }
  ]
}

Answer: for anyone still stuck on this:
node -r ts-node/register/transpile-only -r tsconfig-paths/register dist/index.js

this is what you need to do.
Comment: It works, but isn't bad practice to use ts-node in production environment?
Comment: @hananhamza You should submit your suggestion as legitimate answer, as it is by far the most effective and performant way to transpile TS.
Answer: This was asked around in many places, and apparently Typescript can make path aliases for development, but not production (Don't quote me on that, have been working with it for barely a month).
To work around that, I installed 'module-alias', a package that solves the path issue after build, without interfering with development.
I was building an Express-js app, and had these files:
server.js:
import env from '@env';
import app from './app';

app.listen(env.SERVER_PORT || 3000);

tsconfig.json (relevant parts):
{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@env": ["path/to/env"]
    }
  }
}

This resolved the path during development runtime, but not after building with 'tsc'. To work around it, I added the 'module-alias' package and did the following changes:
server.js:
import './paths';
import env from '@env';
import app from './app';

app.listen(env.SERVER_PORT || 3000);

paths.js
import 'module-alias/register';
import { addAliases } from 'module-alias';

addAliases({
  '@env': `${__dirname}/path/to/env`,
});

This ensured that @env would resolve in both dev runtime and after building.
Hope it helps!
Answer: Also tried to build with tsc but failed due aliases.
After reading a comment from the ts-node author, I skip the build phase and run in production
ts-node --transpileOnly -r tsconfig-paths/register src/server.ts

Answer: If you don't want to use ts-node in production environment, you can create a new js file to map your paths at runtime:
// tsconfig-paths.js

const tsConfig = require('./tsconfig.json');
const tsConfigPaths = require('tsconfig-paths');

let { baseUrl, paths } = tsConfig.compilerOptions;

// Replacing "src" by "dist" in typescript paths map
for (path in paths) {
  paths[path] = paths[path].map((path) => path.replace("src", "dist"));
}

tsConfigPaths.register({ baseUrl, paths });

And then add it to the node params:
// package.json
// ...
  "scripts": {
    "build": "tsc",
    "start": "node -r ./tsconfig-paths.js dist/main.js",
// ...


security constraint doesn't open pages via HTTPS

Question: i want some of my pages to be opened securely. most of those pages are
started with the name "my_Account_"
as example one of those page is "my_account_add_credit_card.xhtml"
in order to do this i have put below code in to web.xml
<security-constraint>
    <web-resource-collection>
        <web-resource-name>my account</web-resource-name>
        <description>my account</description>
        <url-pattern>/my_account_*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <description/>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

but it did not work. i also changed the URL patterns like below
<url-pattern>/*</url-pattern>

then it worked but the problem is that this will open the every page in
HTTPS, i don't want it to be open all the pages in HTTPS. i only need
to open the pages which are starts with "my_account_"
im using glassfish
Answer: tldr; According to specs, your <url-pattern> does not do what you expect it to do. See below for possible solutions.

In Servlet 3.0 spec, section 13.8.3 Processing requests (under the "Security" chapter), it describes how the security constraints for a request are selected:

When a Servlet container receives a request, it shall use the algorithm described in
  "Use of URL Paths" on page 95 to select the constraints (if any) defined on the urlpattern
  that is the best match to the request URI.

The section pointed by the above describes how URLs are matched. Specifically in section 12.2 however, the mappings are specified:

A string beginning with a '/' character and ending with a '/*' suffix is used for
  path mapping.
A string beginning with a '*.' prefix is used as an extension mapping.
A string containing only the '/' character indicates the "default" servlet of the
  application. In this case the servlet path is the request URI minus the context path
  and the path info is null.
All other strings are used for exact matches only.

According to this your mapping of /my_account_* falls in the LAST category (it does not end with /* to fall in the first). This is why the mapping is not working.
What can you do?

I would suggest changing you directory layout and instead of (e.g.)
/my_account_file1.jsp
/my_account_file2.jsp

Make a directory and put those files inside:
/my_account/
    file1.jsp
    file2.jsp

And the mapping should become:
<url-pattern>/my_account/*</url-pattern>

You can use a 3rd party security library, like Spring Security, Apache Shiro or JBoss Picketlink.
You can add a filter to /* and programmatically enforce security (NO, DON'T DO IT YOURSELF, SEE POINT 2, INCLUDED HERE JUST FOR THE SAKE OF COMPLETENESS). Similar approaches can be accomplished using servlets, but I recommend AGAINST this.


USB Ports In Wrong Mode, How To Use usbmodeswitch?

Question: I haven't had access to my USB ports as media devices for a couple days now. I've been reading and researching everything I can find but I can't find a good guide for usbmodeswtich or usbms that I can decipher.  The USB's are fine for power, but won't support my android phone as a media device, which is killing me because I use adb everyday, and won't support my plug and play mouse any longer.  Not sure what caused the switch, though I think it may be related to the suspend issue I've read about, but the solutions in those threads I read also didn't work. Below is my system information and details.

System: Ubuntu 12.04, 64-bit, Dedicated Machine
Machine: HP-Pavillion g6 notebook, AMD A6 Quad Core Processor
USBs used for: Cooling dock, Android Debug Bridge, Wireless Mouse
Attempted Mod Probe, udev restart, unable to attempt lsusb due to my own lack of knowledge. :)
Last Attempt Readout:
ncandiano@ncandiano-HP-Pavilion-g6-Notebook-PC:~$ sudo modprobe -r usbhid && sleep 5 && sudo modprobe usbhid
ncandiano@ncandiano-HP-Pavilion-g6-Notebook-PC:~$ sudo modprobe -r usb-storage
ncandiano@ncandiano-HP-Pavilion-g6-Notebook-PC:~$ sudo modprobe usb-storage
ncandiano@ncandiano-HP-Pavilion-g6-Notebook-PC:~$ sudo restart udev
udev start/running, process 2624
ncandiano@ncandiano-HP-Pavilion-g6-Notebook-PC:~$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 002: ID 0461:4de7 Primax Electronics, Ltd webcam

Any help would be greatly appreciated!
Answer: There is a manpage for usb_modeswitch I would suggest studying that, it looks helpful. If I recall correctly usb_modeswitch is intended for switching the attached USB device, not the port itself. The manpage confirms this. USB by default should work universally and shouldn't keep a specific state when a device is unplugged on a specific port.
I think the issue you are experiencing is more related to the notebook itself and you are on the wrong track, that's why it is so hard to find a good answer. I have heard about dead USB ports on some HP notebooks from colleagues at work, the exact model number and may be product number might help. Something like: g6-1101sg (LS281EA)
If the USB ports are not dead due to some firmware misbehavior you mouse should work as well as adb. What Android Phone are you using? Does is really use UMS or MTP/PTP like the Galaxy Nexus? If it uses UMS, it should work just fine, just like plugging a dedicated USB storage stick in and out, no mode switch required. MTP is different because most the software out there is in an immature state.


Opening gnuplot using a bash script file and then plotting a csv file

Question: I'm new to gnuplot and scripting and having trouble plotting a csv file.
I am trying to have a user that has a csv file have the ability to plot columns of his choice using gnuplot. This is what I have so far:
echo "Welcome Let's get started"
echo "Lets get started with the data set"
echo "How many x-value data sets will be used in the plot?"
read totxvalues #For now we are starting with one data set
echo "What Column in the Data file will be the xvalue?"
read xcolumn
echo "What column in the Data set will be the yvalue?"
read ycolumn
echo "Name of xlabel"
read xlabel
echo "Name of ylabel"
read ylabel
echo "Name of Graph"
read graphTitle

for FILE in "example.csv"*; do
gnuplot
set datafile separator ","
set xlabel "xlabel"
set ylabel "ylabel"
set title "graphTitle"
plot "$FILE" using $($xcolumn):$($ycolumn)
EOF
done

I am currently running this script and it gets to the point where it opens gnuplot but it does not enter the variables that the user entered.
Is this the best approach to opening gnuplot and having the user inputs be plotted? The data that will be analyzed will have a lot of data columns and that's why I only want to choose a couple at a time.
Answer: The main issue is a malformed here-document: it needs to look like
gnuplot << EOF
commands
EOF

Also, if you want your plots to persist on the screen (using the default gnuplot terminal type) then you likely want to add the -p (persistent) option.
I don't recognize the syntax $($xcolumn):$($ycolumn) that you have used: I suspect this should just be $xcolumn:$ycolumn
Finally I suspect you likely want a shell glob more like *.csv than "example.csv"*.
So:
for FILE in *.csv; do
gnuplot -p << EOF
set datafile separator ","
set xlabel "xlabel"
set ylabel "ylabel"
set title "graphTitle"
plot "$FILE" using $xcolumn:$ycolumn
EOF
done

Your script should also have an appropriate shebang at the top i.e. #!/bin/bash or #!/bin/sh


Is this substance drywall joint compound?

Question: I need to get a sample of some drywall joint compound for asbestos testing in a house I'm renovating. I pulled away some of the base boards in the corner and found something that I believe to be joint compound, but I need someone to verify before I take a sample and send it in.

I'm looking at the tan colored substance by the nail in the corner (I highlighted it in the picture). Is this drywall joint compound?
FYI, we have already had some lab tests done and found asbestos (chrysotile) in the popcorn ceiling in one room and the linoleum flooring in the kitchen (currently covered up by laminate). The abatement company recommended checking the joint compound in the wall.
Update
This substance was indeed drywall joint compound and it did contain asbestos, which is a bummer. Now on to abatement...
Comment: Asbestos wouldn't be added to joint compound, mastic, or adhesives. Those things aren't fuel sources, so there's no need to fireproof them.
Comment: That would have been good info to have included in the question initially. If you look at the [tag:asbestos] tagged questions, you'll see that there's lots of (likely) needless paranoia. Providing the context that you've got a very credible reason to be concerned will avoid lots of wondering from those looking at your question.
Comment: Are you trying really hard to not damage the drywall above the baseboard line? If that's not a concern, put a putty knife between the paper and the mud in that L shaped divot on the right. Push toward the corner and you should get mud, texture and paper tape.
Comment: No it's fine to damage this area since this wall is going away. So the stuff with the L shaped divot is joint compound?
Comment: The stuff around the L shaped divot is probably a combination of texture and joint compound. If you dig to the corner, you'll probably get both. (In a perfect world, the paper corner would be in there as well, as that would indicate that the stuff under it and the first layer over it is joint compound.)
Comment: What makes you think there's asbestos in the joint compound, or anywhere in your house, for that matter? When was it built?
Comment: @FreeMan We had lab tests done and they came back positive for chrysotile in both the popcorn ceiling in one room and the linoleum under the kitchen floor. The abatement company recommended that we also test the joint compound so here we are. The house was build in 1969.
Comment: @dandavis The abatement company said that there can definitely be asbestos present in the joint compound and it needs to be tested.
Comment: @FreeMan Trying not to be a jerk here but I provided you with that info as soon as you asked for it. I can't control what assumptions you're making about my situation. I didn't ask "do you think I should test this substance for asbestos?", I asked if that substance was joint compound.
Comment: I saw that you quickly updated your question, and that's good. Unfortunately, we get a _lot_ of questions that are missing a lot of details. Some get updated promptly (as you did - THANK YOU!!), others never do. As noted, there is a lot of hype and fear around asbestos (and other things) as I noted, and much of the concern in unwarranted. Your situation _is_ different and that was very obvious to you, but not to us.
Comment: That's fair, I appreciate the help.
Answer: I believe what I see is the paper for the drywall. There are adhesives but I see wrinkled paper if there is a filler in that point not the paper a clear photo of the tan material would be needed to make a guess. Over the years I have seen everything from sheetrock mud to modeling clay used to patch drywall with even mortar in a few cases.
Note sheetrock or drywall mud can discolor yo a brown or iron oxide color when metal corners are used and if there is moisture in the room other than the torn paper to the left of the nail I don't see tan.
Comment: Sorry, I realize that I wasn't being clear about what I was referring to in the pic. I put a border around the material I'm thinking is the joint compound.
Comment: That's just mud that was put on thick.
Comment: Sorry, I guess I'm confused, isn't "mud" the same thing as drywall joint compound?
Comment: There are many different types topping, hot, and standard most pros refer to them all all as mud.
Answer: Yes in the loosest sense of the term.   Yes it was something that was used just like joint compound.   So it is either joint compound or a relative.
You can tell that it was gradually increased towards the corner, probably to get things closer to a 90 degree angle and just feathered out from the corner.


insert string from textarea having comma same like csv using php

Question: inserting data from csv containing comma in name is working fine . that inserts same as i want e.g "test,name"
i am inserting data into database from a text area. using this code
 $addmult = nl2br($_POST['textarea']);
    $data1 = explode('
',$addmult);
    foreach($data1 as $dataline)
                {
                    $line   = explode(',',$dataline);
                    $name   = $line[0];
                    $partno = $line[1];
                    $detail = $line[2];
                    $qty    = $line[3];
                    $price  = $line[4];
    $sql = "insert into tablename set name=$name, partno=$partno, detail=$detail, qty=$qty, price=$price";

}

it's working, but what if i want to insert the "name" having comma in it.
for example i wnant to insert this data (name="test,name")
test,name,123,testdetails,2,100
test,name2,321,testdetails2,22,200

the code above will split the name but i wnat name as "test,name" and "test,name2"
thanks
Comment: Unless you enforce some sort of quoting, there is no way to determine where the split should be.  Either you need to quote your name or use a different way of splitting values.
Comment: Try using extract() http://php.net/manual/en/function.extract.php which automatically convert array to variable.
Comment: @AleksG thanks. for your comment. when i use a csv file containing comma in name. that is saved exactly how i want. "test,name"
Comment: @Ali can you give me some sample code or example
Comment: [The Great Escapism (Or: What You Need To Know To Work With Text Within Text)](http://kunststube.net/escapism/)
Comment: why then dont try separating with something else, like ";" for each field, so you can use the , in the middoe lf a name.
Answer: Will str_getcsv() work for you? It will parse a CSV string into an array...
See: http://php.net/manual/en/function.str-getcsv.php
The following:
<?php
    $stringAry = "\"test,name\",123,testdetails,2,100";
    print_r(str_getcsv($stringAry));
?>

Note, "test,name" is surrounded by quotes in the CSV line, otherwise it is two columns and not one.
Outputs...
Array
(
    [0] => test,name
    [1] => 123
    [2] => testdetails
    [3] => 2
    [4] => 100
)

So you could do something like
<?php
    $stringAry = "\"test,name\",123,testdetails,2,100";
    $sql = "insert into tablename set name={stringAry[0]}, partno={stringAry[1]}, detail={stringAry[2]}, qty=$qty, price={stringAry[3]}";
?>

If the user forgets to quote the name or the details you could figure out that you have more columns that you should and combine all adjacent non-numeric columns seeing as you only have two non-numeric columns and they are separated by a numeric column.
Also, I know the above is an example so you probably have considered this, but just in case: consider using mysqli_real_escape_string() for user input, or the equivalent for the DB you're using...
Comment: Thanke for your reply . this is gonna work for me . but having a little problem with this.

the above code do exactly what i want. but wehn i enter the same string in text area and process it, then it doesn't work.
Comment: when i enter "test,name",123,testdetail,2,100 in text area this is not woking like the above string in your example
Comment: the difference is may be in the the commas you i code in string and in text area
Answer: This is such a poorly worded question, I can't really tell what you are asking. I assume you want to take input from a textarea and split it up based on commas - if one of the values has a comma in it, it treats it as two fields.
As the comments suggest, you could escape it, or, even simply, replace ',' in your input. E.g.
$input = $_POST['input'];

$replacedInput = str_replace(',', '-', $input);

NOTE: This will replce ',' with '-' in your input. You could then pick this character up the other end when outputting so that it replaces '-' with ',' - or a less used character. This code is not tested.
After reading your question again, you need something like this:
 $sql = "insert into tablename set name='".$name."', partno='".$partno."', detail='".$detail."', qty='".$qty."', price='".$price."'";

Comment: thanks. you understood exactly what i wanted to ask. then how can you say that this is poorly worded question.
Comment: Sorry. No offence intended - It was just an awkward question to answer. If this has helped you, mark it as helpful.
Comment: this was clearly not helpful. and i have marked another answer .


video 100% width and height 220px

Question: I have a video, and I want it to FULL 100% of the width, and 220px of the height
<video  controls="controls">
   <source src="video/sport.m4v" type="video/mp4" />
   <source src="video/sport.ogg" type="video/ogg" />
   <source src="video/sport.flv" type="video/flv" />

but the problem when i change the height to 220px also width change as well
video {
 width: 100% !important;
 height:220px !important;
}

Comment: I think you are looking this answer http://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php
Answer: If you literally gave it a width of 100% and a height of 220px your video would likely look very stretched, horizontally. A better idea is to contain the video in a container div that with overflow hidden set that has the dimensions you want. For example:

  <video  controls="controls">
    <source src="video/sport.m4v" type="video/mp4" />
    <source src="video/sport.ogg" type="video/ogg" />
    <source src="video/sport.flv" type="video/flv" />

video{
  width: 100%;
}
#container{
  width: 100%;
  height: 220px;
  overflow: hidden;
}

This way, the video will have a normal aspect ratio, but will have the correct width. Then, the containing div just hides whatever part of the video exceeds 220px in height.

video 100% width and height 220px


The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) error in xamarin forms UWP?

Question: I have created a project with SQLiteConnection in xamarin.Forms. In UWP, I have implemented the following interface to return the SQLiteConnection
<code> public class SQLiteImplementation : ISQLite
{
    public SQLiteConnection GetConnection()
    {
        var dbName = "db_sqlnet.db";
        var path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, dbName);
        return new SQLiteConnection(path);
    }
}
</code>
I have referred sqlite-net-pcl in my UWP project. But I have got the following error while running the project , "System.IO.FileLoadException: The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)    at Windows.UI.Xaml.Controls.Frame.Navigate(Type sourcePageType, Object parameter)    at Sample.UWP.App.OnLaunched(LaunchActivatedEventArgs e)" error in xamarin forms UWP"
How to resolve the above error? am I doing wrong in my code or it is because of reffered assembly?
Comment: I think it is one of the assemblies referenced is the wrong version
Comment: Have you tried updating `Microsoft.NETCore.UniversalWindowsPlatform` version?
Comment: news on this post?
Answer: This issue is due to a regression bug that has been fixed in https://www.nuget.org/packages/sqlite-net-pcl/1.5.166-beta
Try to update to that beta version and it should work.


CGAffineTransformInvert: singular matrix swift

Question: I've encountered the following error:

CGAffineTransformInvert: singular matrix swift

I use UIImagePickerController and, when I do photo or choose photo from library, I get this error. I also try to present my photo using firstImageView.
Here is my code:
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        firstImageView.image = image
    } else{
        print("Something went wrong")
    }
    picker.dismiss(animated: true, completion: nil)
}

Answer: It is an Xcode bug. Don't worry about it. There is nothing wrong with that piece of code.
It's just a console error. You just need to ignore it. Otherwise, try cleaning and deleting derived data, remove the app from the phone, and re-run it.
Comment: but I tested on device (5s)
Comment: But it's just a console error, right? Then you just need to ignore it. Otherwise, try cleaning and deleting derived data, remove the app from the phone, and re-run it.
Comment: not JUST console, with console error I haven't result, that I hoped
Comment: but thanks! I'll try do all you sayed!


Wordpress JSON API Plug-in: How can I put the output of a JSON query into a PHP string?

Question: I installed the JSON API Plug-In for my wordpress site. I want to display on an external site how many posts I have in a certain category.
For example, I have a URL like this: http://mywordpress.com/?json=get_category_posts&slug=press%20releases
Along the output, I almost immediately see a field "post_count" and a number right after it. I want to encapsulate this number into a string so I can output that number onto a table. But in order for me to be able to do that I need to have the entire output in a variable.
But I can't have something like
<code>$json-output = http://mywordpress.com/?json=get_category_posts&slug=press%20releases;
echo $json-output;
</code>
That's just gonna output the URL, not the result of the JSON query.
I hope the question is making sense. Any guidance would be appreciated.
Answer: You will need to use CURL to get the json result from the URL, then parse the json with PHP, then echo the item you would like displayed.
The parts you seem to be missing are the CURL and JSON parsing, but you are on the right track.
This might help, a pretty simple example:
http://www.katcode.com/http-requests-using-curl-and-decoding-json-responses/


What does swords icon mean after attack in Might and Magic Heroes VI?

Question: sometimes after an attack in combat in HoMM VI, I see not only damage dealt/units died counts, but also Swords icon with a number appear.
What does it mean?
Answer: The 2 crossed swords icon means might damage. Certain abilities will reduce or increase the might damage of a stack of monsters.
My guess is you saw for example -1 X (crossed swords icon), meaning each creature in the stack will do 1 might damage less as long as the ability applies.
Answer: The sword icons shows that the damage done was melee damage
Comment: hm, but isn't all the other damage done by melee troops (like sentine) melee aswell? besides, it usually only shows like "2" while total damage is like 200.
Comment: I could be wrong. It's been a while since I played MM
Comment: Just re-read your response. You misunderstood. I didn't say that the icons **how much** damage was done, only that it was **melee** damage. Ranged get their own icons (dependant on what kind of ranged attack was used)
Comment: no, it's not like that. Now that I played more, there are more icons.

The normal icons just show a number and skull with number (how many units has died). Then sometimes I also get swords icon (with a +2 for example), a green cross icon, etc.. what do these mean?


MLB 2K12 PAL Xbox360 Not Available?

Question: It appears MLB2K12 was not produced this year to work outside of the United States?
I cannot find any reference to a PAL version for use here in Australia and also Europe. Last year 2K11 was available.
This seems ridiculous especially considering NBA, NHL and NFL are all available in PAL as well. Why would they stop a whole audience region?
Can anyone please prove me wrong?
Answer: Doing a quick GameFAQs search for the relevant game shows that it does not have any data available for EU.
Looking at the release data for the previous game shows a release gap of about three months between US and EU.  It may be that it's just not released yet.
Comment: Interesting, the AU date didn't come long after but the EU and JP did. Either way I see there could still be hope, even if it could stupidly be not towards the end of the season. Heck, I'd even settle for a digital download release. Thanks for the links, you can have the bounty!

MLB 2K12 PAL Xbox360 Not Available?


In how many ways can four students take two exams if none of the students can take both exams at the same time?

Question:
Four students are about to take two oral exams. Each exam is exactly 20 minutes long. In how many ways can those exams be conducted, if none of the students can take both exams at the same time?

I don't really know how to calculate all the possibilities of two "simultaneous" events. How can I combine them into one problem and solve this?
Edit: I think I came up with a solution: first I decide how the first exam will be conducted - there are $4!=24$ possible ways. Let's say it's the order ABCD. Then, using the inclusion-exclusion principle, I calculate that there are $9$ possibilities, in which none of the letters is in the same position as previously. So, the final answer is then $24 \cdot 9=216$?
Comment: I think I came up with a solution: first I decide how the first exam will be conducted - there are $4!=24$ possible ways. Let's say it's the order $ABCD$. Then, using the inclusion-exclusion principle, I calculate that there are $9$ possibilities, in which none of the letters is in the same position as previously. So, the final answer is then $24*9=216$?
Comment: Can you clarify the question? Does each exam happen one at a time (8!) or can multiple students take different exams at the same time?
Comment: @greenturtle3141 only one student can take a particular exam at a time, but two different exams are conducted at the same time; in other words - two students are examined by two professors at a time
Answer: Your result is correct.
There are $4!$ ways of scheduling the first examination for the four students.  For each such schedule, the second examination must be scheduled so that none of the students have both oral examinations in the same time slot.  Therefore, the schedule for the second examination must be a derangement of the schedule for the first examination.
There are $4!$ possible schedules for the second examination, but we must exclude those in which one or more students has two examinations scheduled simultaneously.  There are $\binom{4}{k}$ ways in which $k$ students could be scheduled to have the second examination at the same time as the first examination, and $(4 - k)!$ ways to schedule the remaining students for the second examination.  Hence, by the Inclusion-Exclusion Principle, the number of ways to schedule the second examination so that no students have a conflict with the first examination is
$$4! - \binom{4}{1}3! + \binom{4}{2}2! - \binom{4}{3}1! + \binom{4}{0}0!$$
Consequently, the number of ways to schedule the two examinations so that no students are scheduled to complete the two examinations at the same time is
$$4!\left[4! - \binom{4}{1}3! + \binom{4}{2}2! - \binom{4}{3}1! + \binom{4}{0}0!\right]$$


Get the element of an array that has an index given by a variable in JavaScript

Question: I have the following code:
var items = [item1, item2, item3];

var index = Math.random() * items.length;

I expect the statement
items[index]

to return a random item from my array, however it always returns undefined. How do I get the item indexed by the index variable?
Comment: The `Math.random()` function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1)
Answer: You need an integer value index, because an Array is organized by positive integer values.
If you use a not integer value, the value is converted to a string (this applies to the integer value, too) and used as property accessor. An in this case, for example 1.22, the value does not exist in the array and you get undefined.
BTW, arrays are objects in Javascript, so all values could be used as key for the array.

var items = ['item1', 'item2', 'item3'];
var index = Math.floor(Math.random() * items.length);

console.log(items[index]);
Answer: You should floor the number befaore using it as subscript:
var index = Math.floor(Math.random() * items.length);

That way you'll get integer values for index and not floating ones.
Comment: I forgot to get an integer, my bad. Thanks
Answer: Use Math.round() to round up the index
var index = Math.round(Math.random() * (items.length - 1));

Otherwise it could point to something like 2.3 which isn't incöuded in the array


Adjust width of vuetify datatable "rows per page" menu width because text is truncated

Question: How do I ensure that text in the rows per page menu isn't truncated?
In firefox 60.5 with vuetify 1.4.1, when I go to change the rows per page, I noticed that the menu was cutting off "100".
I tried changing it from this:
<v-data-table
  ...
  :rows-per-page-items="[5,10,25,50,100]"
  ...
/>

to this:
<v-data-table
   ...
   :rows-per-page-items="[{text:'5', value:5},...,{text:'100', value:100}]"
  ...
/>

thinking that having the text would make a difference--it didn't.
UPDATE:
Also, within , I tried many combinations of the following with no success:
/deep/ .v-list__tile__title {min-width: 30px;}
/deep/ .v-list__tile {min-width: 30px;}
/deep/ .v-list__tile__content {min-width: 30px;}
/deep/ .v-list__tile__title {min-width: 30px;}
/deep/ .v-select-list {min-width: 80px;}
/deep/ .v-menu__content{min-width: 80px;}

Answer: You should set it in your data and access it in the table. Like so:
data: () => ({
  pagination: {
    descending: true,
    page: 1,
    rowsPerPage: 5,
    totalItems: 0,
    rowsPerPageItems: [5, 10, 25, 50, 100],
  },
})

then when you set your data table:
<v-data-table
  ...
  :pagination.sync="pagination"
  :rows-per-page-items="pagination.rowsPerPageItems"
  :total-items="pagination.totalItems"
  ...
>

Comment: Perhaps I wasn't clear. `"[{text:'5', value:5},...,{text:'100', value:100}]"` was just shorthand. Kind of like in a math proof. Also, I actually have it set in data...I just didn't feel like typing it all out.  My problem is that when I click on the menu to select rows per page, the rest of the numbers show up just fine, but 100 show up as "1..."
Answer: Although not ideal, I made a global style instead of a scoped one.  In other words, I went from  to .
In this particular case I used:


Errors when update

Question: I wanted to manually do:
sudo apt-get upgrade

and I have errors at the end:
/usr/sbin/grub-mkconfig: 34: /etc/default/grub: Syntax error: EOF in backquote substitution
run-parts: /etc/kernel/postrm.d/zz-update-grub exited with return code 2
dpkg: error processing package linux-image-5.0.0-23-generic (--remove):
 installed linux-image-5.0.0-23-generic package post-removal script subprocess returned error exit status 1
Errors were encountered while processing:
 linux-image-5.0.0-23-generic
E: Sub-process /usr/bin/dpkg returned an error code (1)

Content of /etc/default/grub:
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
#   info -f grub -n 'Simple configuration'

GRUB_DEFAULT=0
GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash resume=UUID="ef1f8271-5d94-4706-9904-61c9cd7da3ba"
GRUB_CMDLINE_LINUX=""

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)
#GRUB_BADRAM="0x01234567,0xfefefefe,0x89abcdef,0xefefefef"

# Uncomment to disable graphical terminal (grub-pc only)
#GRUB_TERMINAL=console

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command `vbeinfo'
#GRUB_GFXMODE=640x480

# Uncomment if you don't want GRUB to pass "root=UUID=xxx" parameter to Linux
#GRUB_DISABLE_LINUX_UUID=true

# Uncomment to disable generation of recovery mode menu entries
#GRUB_DISABLE_RECOVERY="true"

# Uncomment to get a beep at grub start
#GRUB_INIT_TUNE="480 440 1"

Comment: Have you made changes to `/etc/default/grub`?
Comment: No, I have another OS, but I don't think that I edit grub myself. That is why I am asking as I don't want to make mess and not have access to any of OS. Thanks.
Comment: Please add contents of `/etc/default/grub`  to the question.
Comment: It looks like the file was edited in Windows.
Comment: No, i just open it under Ubuntu in edit mode on Double Commander
Comment: You have an unclosed quote in `"quiet splash resume=UUID="ef1f8271-5d94-4706-9904-61c9cd7da3ba"` Remove the second quote.
Comment: So it must look like this ? : "quiet splash resume=UUID="ef1f8271-5d94-4706-9904-61c9cd7da3ba
Comment: I don't think that is a problem as they are four altogether: GRUB_CMDLINE_LINUX_DEFAULT="quiet splash resume=UUID="ef1f8271-5d94-4706-9904-61c9cd7da3ba"
GRUB_CMDLINE_LINUX=""
Comment: @Pilot6 - you were right!!!
Answer: Line should look like this:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash resume=UUID=ef1f8271-5d94-4706-9904-61c9cd7da3ba"

That solve the problem.
Thanks @Pilot6

Errors when update


PHP image upload issue?

Question: I have the following code [x]:
    <form action="#" method="get" enctype="multipart/form-data">
    Filename:

    <input type="text" name="type" placeholder="Type">

    <input type="file" name="file">

    <input type="submit" name="submit" value="Submit">
    </form>
<?
if($_GET['type']!="") {
    $type = $_GET['type'];
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    if($_FILES["file"]["type"] == "image/gif") {
        $encryptfile = md5(substr($_FILES["file"]["name"], 0, -4));
        $filename = $encryptfile. ".gif";
    } else if($_FILES["file"]["type"] == "image/jpeg") {
        $encryptfile = md5(substr($_FILES["file"]["name"], 0, -5));
        $filename = $encryptfile. ".jpeg";
    } else if($_FILES["file"]["type"] == "image/jpg") {
        $encryptfile = md5(substr($_FILES["file"]["name"], 0, -4));
        $filename = $encryptfile. ".jpg";
    } else if($_FILES["file"]["type"] == "image/pjpeg") {
        $encryptfile = md5(substr($_FILES["file"]["name"], 0, -6));
        $filename = $encryptfile. ".pjpeg";
    } else if($_FILES["file"]["type"] == "image/x-png") {
        $encryptfile = md5(substr($_FILES["file"]["name"], 0, -6));
        $filename = $encryptfile. ".x-png";
    } else if($_FILES["file"]["type"] == "image/png") {
        $encryptfile = md5(substr($_FILES["file"]["name"], 0, -4));
        $filename = $encryptfile. ".png";
    }
    $temp = explode(".", $filename);
    $extension = end($temp);
    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 2097152)
    && in_array($extension, $allowedExts))
    {
    if ($_FILES["file"]["error"] > 0) {
        echo '' .$_FILES["file"]["error"]. '';
    } else {
        echo "Upload: " . $filename . "
";
        echo "Type: " . $_FILES["file"]["type"] . "
";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB
";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
";
        if (!($stmt = $con->prepare("INSERT INTO `cat_images` (`title`,`path`) VALUES (?,?)")) || !is_object($stmt)) {
            die( "Error preparing: (" .$con->errno . ") " . $con->error);
        }
        $stmt->bind_param('ss', $type, $filename);
        if($stmt->execute()) {
            move_uploaded_file($_FILES["file"]["tmp_name"], "./assets/uploads" . $filename);
            echo "Stored in: " . "./assets/uploads/" . $filename . "
";
            echo 'Home';
        } else {
            echo 'SQL command could not be Executed, Contact a Staff Member';
            echo 'Try Again';
        }
        $stmt->close();
    }
    }
}
?>

I get no response from the page or server, so I don't know what the issue is.
Do any of you know of the solution?
I am attempting to make an image upload form, but I don't get a response from the server for a website.
Comment: Method should be post ?
Comment: first thing first `method="get"` to `method="POST"`
Answer: From the php documentation of the superglobal $_FILES you can read the following sentence:

An associative array of items uploaded to the current script via the HTTP POST method.

So you should change your method="get" to method="post" and retrieve your $_GET['type'] by using $_POST['type'].
Answer: i think problem is here...your code is...
 move_uploaded_file($_FILES["file"]["tmp_name"], "./assets/uploads" . $filename);

replace it with following line
 move_uploaded_file($_FILES["file"]["tmp_name"], "/assets/uploads/".$filename);

make sure all directory is exist that is /assets/uploads/

PHP image upload issue?


Does leveling reduce how much super training you can complete?

Question: This question is very close to this: How does Super Training work?, but I would like to know one thing in particular: Does leveling your pokemon also reduce the amount of super training one can complete?
I would assume that EV training does, but using the newly-upgraded EXP share (that now affects your entire team), could I accidentally cut how much EV I can accomplish? My friend was playing for a while, and he saw that, although he hadn't done any Super Training, some of the green bar on the right had filled. I don't think he was thinking of EV impacting it (it was on one of his main fighters that he noticed this), but I would like to be sure just in case.
Comment: sending them into battle does but i dont know about the exp share
Comment: @qwertyk31 I believe sending them into battle does affect EV, but as long as they don't participate the EV doesn't change I think
Comment: @dlras2 ok, I probably should do that first, I'll make sure to in the future
Comment: Do note that there are "Reset Bag"s that can be obtained through super training that will completely reset *all* of a single pokemon's EVs to 0, allowing you to train it properly.
Comment: If I use that on a level 100 pokemon, it will still gain stats from EV it gets afterwards, right?
Answer: Leveling does not directly affect a Pokemon's EVs (and therefore Super Training.) In prior generations (before V, I believe,) EVs were only calculated upon leveling, so a level 100 Pokemon could not be EV trained. Now, however, EVs are calculated after each battle (and probably between battles, in the case of Super Training.)
However, leveling via battle affects Super Training because it grants EVs based on the Pokemon fought. So leveling via rare candies won't affect super training, but leveling through battle will.
I believe that EXP Share grants EVs to all Pokemon—confirmed by UnderscoreZero in the comments.
Comment: Exp share does share EV's (not sure how much but probably all). My HM mule is fully ev trained without being in a single battle.
Comment: Ok, thank you! I hadn't considered exp share distributing EV, but I guess it might make sense. One thing though: leveling via rare candy? It's nice at like level 99 and things, when 1 more level could take ages, but going the whole way would both be incredibly awesome and ridiculously expensive, even if you can buy them. If that's what floats your boat, I guess :)
Comment: @TheUgly Just pointing it out. Since Rare Candies don't increase EVs, it's a good way to check a Pokemon's IVs. I wouldn't recommend it as a long-term solution, tho. =P
Comment: @UnderscoreZero Thanks for the confirmation - that's what I was going to check. I asked a more detailed question [here](http://gaming.stackexchange.com/q/136956/9350) if you have more info.


import data from another table with same id

Question: User (id, name, surname,cod)
UserNew (uid, uname, usurname, ucod)
The first table has data the second no.
I have to copy the data of the User table in the UserNew table.
I've tried with a insert query but uid (primary key) value changes.
How can i do to mantaince the same values?
thanks
Answer: I'm guessing that uid of the UserNew table is an identity (autoincrement) column. So you could issue a SET IDENTITY_INSERT UserNew ON statement, then insert the data (including the correct id) and then issue a SET IDENTITY_INSERT UserNew OFF
Answer: You need to enable
SET IDENTITY_INSERT tablename ON
http://msdn.microsoft.com/en-us/library/aa259221(SQL.80).aspx


calculate proportion of salt and sand

Question: suppose that we have  following question:
there is two mixture of salt and sand,in the first the proportion of salt to sand is $2:1$ and in second mixture  $1:4$;if we take equal quantities of both mixture,we are interested what would be ration of salt and sand in new mixture?
my attempt is following,let us take  quantity $x$ from both mixture,then in total we will have $2*x$; in each  part when we take from two mixture ,proportion is following;
in the first half the amount of salt is $2x/3$ and sand is $x/3$;
in the second half we have $x/5$ salt and $4*x/5$;
now if we add we will get
 salt is $13*x/5$ and sand  is $21*x/20$;
the proportion is $52/63$; is it correct? In the answer it says  $13:17$. Please help me see what is wrong with my calculation.
Comment: Make up your mind whether it is sugar or sand which is mixed with the salt!
Comment: i have updated sorry
Answer: You added the fractions incorrectly. The total amount of salt is $\frac23x+\frac15x=\frac{13}{15}x$, not $\frac{13}5x$, and the total amount of sand is $\frac13x+\frac45x=\frac{17}{15}x$, not $\frac{21}{20}x$, so the ratio is
$$\frac{\frac{13}{15}x}{\frac{17}{15}x}=\frac{13}{17}\;.$$
Comment: i see my typo,thanks very much
Comment: @dato: You're very welcome.
Answer: Let's call the quantity of the final mixture $30u$ - I got 30 because I wanted half the mixture to be easily divisible into $3=2+1$ units and also $5=1+4$ units.
In the first half $(15u)$ we have $10u$ salt and $5u$ sand.
In the second half we have  $3u$ salt and $12u$ sand.
This makes $13u$ salt and $17u$ sand.
You seem to have added the fractions incorrectly - $$\frac {2x}3+\frac x5=\frac {13x}{15}$$$$\frac x3+\frac {4x}5=\frac {17x}{15}$$

calculate proportion of salt and sand


Why do Fibonacci Digits always return to either 11 or 14?

Question: I recently posed a question on Code Golf on what I'm terming "Fibonacci Digits", where each number is the sum of the previous two digits, not necessarily the previous two numbers. So, for instance, the series beginning $1,1$ is $1,1,2,3,5,8,13,4,7,11,2\dots$ and cycles from there.
As I note in the various examples I bring there, unless something in the series manages to add to either $0$ or $14$, the series seems to always loop to some rotation of $2,3,5,8,13,4,7,11$. Further, it always reaches $0$ or $14$ no later than the third entry in the series. For instance, $S_1=7,7,14,5,9\dots$, $S_2=14,5,9\dots$, $S_3=68,14,5,9\dots$.
In other words, it seems that for $0\le(a,b)\le9$, then, for $a+b=c$:

If $c<10$, let $d=b+c$
If $c\ge10$, $c=10x+y$ for some integers $0\le(x,y)\le9$. Let $d=x+y$.
Repeat the above using $c$ and $d$.

Eventually, assuming that you don't start with $0$, this algorithm will yield either $11$ or $14$. Seemingly.
My question is two parts:

Is my assessment correct?
If so, why?
Comment: Your example of the loop shows that it can avoid $14$.  How can you get $0$ unless you start with $0$?
Comment: If I do not miss something, it is sufficient to show the claim for every pair $(a,b)$ with $a,b\le 18$. Have you checked this ? When $14$ must occur, is another question.
Comment: @RossMillikan That's it, as far as I can tell. Assuming that $a,b$ aren't *both* $0$, the cycle always finds its way to $11$ or $14$.
Comment: I have shown that is correct, but $14$ can occur as late as the sixth position.  I didn't look at how late $11$ can come up, but it is later than that.
Comment: @RossMillikan I'm curious, for what input does $14$ come up so late?
Comment: I said it was $(3,1)$ in my answer
Answer: I'll assume you do not allow negative starting values (it makes sense not to, since we're interested in digits).
Let's start with the second question: Why are 0 and 14 always reached early?
Let's start with 14. How can we reach 14? Let's start with 14, and reconstruct the sequence backwards, digit by digit.
The only two-digit numbers possible are $10$ to $18$, so we need to take care of the case of having two-digit numbers only if the digit-by-digit reconstruction generates a one after a digit 0-8 (remember, we're reconstructing backwards).

$14, 9, 5, 4, 1$. This makes two options

The 4, 1 actually comes from 14 (backwards), so the forward sequence is $14, 5, 9, 14$ and we're already in a cycle.
The sequence is $14, 9, 5, 4, 1, 3$. We can't continue beyond the 3 unless we allow negative numbers.

$14, 8, 6, 2, 4$. We can't proceed without allowing negative numbers.
$14, 7, 7, 0, 7$
$14, 6, 8$
$14, 5, 9$

So 14 can't come later than position 6.
The only way to get 0 is if you start with 0, 0. Otherwise you can get 10, but then you have 10, 1, 1, 2, and you get into the standard sequence.
Now, to the first question. Again, we have only 9 possible 2-digit numbers that we can reach, so we can easily confirm that each eventually sends us to the standard sequence $1, 1, 2, \dots$:

$10, 1, 1$
$11$ done :)
$12$ done :)
$13, 4, 7, 11$
$15, 6, 11$
$16, 7, 13$ and we know $13$ sends us to 11
$17, 8, 15$ and we know $15$ sends us to 11
$18, 9, 17$ and we already know 17
$19, 10, 1, 1$.

Now, this brute force check is simple enough, but it's boring. That said, there is some intuition behind why (almost) all Fibonacci digit sequences eventually send us to the standard sequence 1, 1, 2... And it's because 10 and 11 send us there. If you consider sums of digits, then there's only 1 way to get 0: 0 + 0. Similarly, we have only 1 way to get 19. However, we many more ways to get 10 and 11 as a sum of two digits. In fact, if you take 2 random digits, the most likely outcome is 10, followed shortly by 11 (and 9). So, eventually, you're very likely to reach either 10 or 11.
Answer: From the second entry on, no entry can be larger than $9+9=18$.  As an entry only depends on the previous two entries, there must be one or more cycles that can be created.  I have found $(2,3,5,8,13,4,7,11)$, $(5,9,14)$, and $0$ as cycles.  We can just try all $100$ pairs of single digits to start the sequence.  Starting with a two digit number is the same as starting with the two individual digits, so we don't have to try that.
$0$ only comes from starting $(0,0)$
$5,9,14$ comes from $ (0,7),(1,4),(2,6),(3,1),(4,2),(4,5),(5,9),(6,8),(7,0),(7,7),(8,6),(9,5)$
Note that $(3,1)$ only gets to $14$ at the sixth term.
All other starting pairs go to $2,3,5,8,13,4,7,11$ eventually.  The latest $11$ comes up is the sixteenth term starting from $(0,2)$


asp.net add checklist to li dynamatically

Question: I have a div campaignDiv
and I want to add li to that div and inside that li i want to add checkbox
i tried this
 List<string> comps = getCompainNames();
                for (int i = 0; i < comps.Count(); i++) {
                    HtmlGenericControl newLi = new HtmlGenericControl("li");
                    newLi.InnerText = comps[i];
                    campaignDiv.Controls.Add(newLi);
                }

but really I don't know how to add checkbox to that li could u help please?
I would prefer input type checkbox rather than asp.net checkbox controller
Answer: You should be able to do something like this, without using any ASP.NET Checkbox controls:
Default.aspx

    <title></title>

    <form id="form1" runat="server">

    </form>

Default.aspx.cs
string html = "
";
html = html + CreateLiCheckbox("MyCheckbox1");
html = html + CreateLiCheckbox("MyCheckbox2");
html = html + CreateLiCheckbox("MyCheckbox3");
html = html + "
";
campaignDiv.InnerHtml = html;

private string CreateLiCheckbox(string checkBoxText)
{
    return string.Format("
<input value=\"{0}\" type=\"checkbox\">{0}
", checkBoxText);
}

Comment: in this case you have added checkboxes without values, right? could you add the valuese please? the value is the same and the test that appears beside the checkbox. In other word, the values should be `MyCheckBox1` and `MyCheckBox2` and `MyCheckBox3`
Answer: You should use a CheckBoxList instead.
aspx

    <asp:CheckBoxList
        id="somecheckboxes"
        RepeatLayout="UnorderedList"
        runat="server" />

code-behind
foreach (var campaign in getCompainNames())
{
    somecheckboxes.Items.Add(new ListItem(campaign));
}


Ansible: How to pip install with --upgrade

Question: I want to pip install with --upgrade, using Ansible.
What's the syntax?
Answer: - name: install the package, force upgrade
  pip:
    name: <your package name>
    state: latest

Or with:
- name: install the package, force reinstall to the latest version
  pip:
    name: <your package name>
    state: forcereinstall

Comment: Excellent solution, note however that "forcereinstall" will only work for ansible >= 2.1 as http://docs.ansible.com/ansible/latest/pip_module.html
Answer: Eventually found the answer here:
https://groups.google.com/forum/#!topic/ansible-project/a19JEpdXzck
this is the syntax:
- name: install the package, force upgrade
  pip:
    name: <your package name>
    extra_args: --upgrade

Comment: Thank you, I was using ```shell: > pip install --upgrade pip``` and this is better due I am avoid the ansible-lint rule for shell commands.
Answer: If you need upgrade pip for other python version, you can use executable parameter:
- name: install the package, force upgrade
  pip:
    name: pip
    executable: pip3
    state: latest


Inner join same table in SQL Server

Question: I checked this page INNER JOIN same table
for my answer. I got part of it.
I need select id and referral link of parent(main) account which has less 7 referrals. I have this query, but it works for all parent(main) account (all account has same amount of referrals)
select
      id,
      referralLink
   from
      accs
   where
      ( 3 > (select
                   count(*)
                from
                   accs as acc
                      join accs as mainAcc
                         on mainAcc.id = acc.mainID
                 where
                    acc.paymentCompleted = 1)
      and referralLink is not null)

My table:
Comment: [Please do not upload images of code/data/errors.](//meta.stackoverflow.com/q/285551)
Answer: Looks like you need to aggregate the records by the referrer / parent / main id and then select the records that match the conditions (id = mainid and count < 7).
You need a group by and then a count.
You will need to join back to a sub-query that aggregates the records.
The query would look like this:
SELECT id, referralLink
FROM
    accs
    INNER JOIN
    (
        SELECT mainId AS parent, count(*) as num_referral
        FROM accs
        GROUP BY mainId
    ) referral_counts ON referral_counts.parent = accs.id
WHERE
    num_referral < 7

Answer: Yes, doing a self-join from the ID to the main, but not nested within the outer.  This might be closer to what you are looking for.
select
      a.id,
      a.referralLink,
      count(*) ChildRecs
   from
      accs a
         join accs child
            on a.id = child.mainid
   where
      a.referralLink is not null
   group by
      a.id,
      a.referralLink
   having
      count(*) > 3

From your sample data, the PARENT ID is the ID column.  The CHILD records are the ones pointing to a "MainID" of the parent.  In the sample of your data, Parent "ID" of 4, but the child ID entries of 5 through 13 are all associated with the MAIN ID of 4.
So, in this case, the returned result of this query would show
ID  ReferralLink      ChildRecs
4   3adc0039f8ff2970  9

No other IDs would be returned since the parent "ID" have no entries with MAINID pointing to anything else.  Id #s 4, 36 and 38 all appear to be parents, but no additional data shows child entries with MAINID populated otherwise.
Now, based on your issue of having LESS than 7, just change the HAVING clause portion to what you want.  You could remove the HAVING clause just to see what IS returned... or even having count(*) > 2 just to see SOMETHING with child entries for a given parent

Inner join same table in SQL Server


Why does NextValue call of performanceCounter change thread affinity mask

Question: I have a C# project, where I have to both access the current workload of my processor, and ensure, that I run some specific code on every kernel of the processor. My problem is, that accessing the workload of my processor seems to prevent me from correctly assigning a thread affinity mask. I have some code here, that illustrates the problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace KernelAffinitySpike
{
    class Program
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern UIntPtr SetThreadAffinityMask(IntPtr hThread, UIntPtr dwThreadAffinityMask);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern IntPtr GetCurrentThread();

        private static PerformanceCounter cpuUsage;
        private static UIntPtr oldMask, newMask, testMask; // thread-level processor affinity masks.

        static void Main(string[] args)
        {
            InitPerformanceCounter();

            Console.WriteLine("Pre: thread affinity: " + CurrentThreadAffinityMask());
            if (AllKernelsAccessible())
                Console.WriteLine("Pre: all kernels accessible");
            else
            {
                Console.Write("Pre: some kernels not accessible: ");
                foreach (UInt32 kernel in InaccessibleKernels())
                    Console.Write(kernel + " ");
                Console.WriteLine();
            }

            float load = cpuUsage.NextValue();

            Console.WriteLine("Post: thread affinity: " + CurrentThreadAffinityMask());
            if (AllKernelsAccessible())
                Console.WriteLine("Post: all kernels accessible");
            else
            {
                Console.Write("Post: some kernels not accessible: ");
                foreach (UInt32 kernel in InaccessibleKernels())
                    Console.Write(kernel + " ");
                Console.WriteLine();
            }

            Console.ReadLine();
        }

        static void InitPerformanceCounter()
        {
            cpuUsage = new PerformanceCounter();
            cpuUsage.CategoryName = "Processor";
            cpuUsage.CounterName = "% Processor Time";
            cpuUsage.InstanceName = "_Total";
        }

        static UInt32 CurrentThreadAffinityMask()
        {
            oldMask = SetThreadAffinityMask(GetCurrentThread(), (UIntPtr) 3); // 3 just enables all processors on a dual core. I'm only interested in the return value.
            SetThreadAffinityMask(GetCurrentThread(), oldMask);
            return (UInt32) oldMask;
        }

        static List<UInt32> InaccessibleKernels()
        {
            List<UInt32> inaccessible = new List<UInt32>();
            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                newMask = (UIntPtr)(1 << i);
                oldMask = SetThreadAffinityMask(GetCurrentThread(), newMask);
                testMask = SetThreadAffinityMask(GetCurrentThread(), oldMask);
                if (newMask != testMask)
                    inaccessible.Add((UInt32) newMask);
            }
            return inaccessible;
        }

        static bool AllKernelsAccessible()
        {
            return InaccessibleKernels().Count == 0;
        }
    }
}

Running this code yields the following output:
Pre: thread affinity: 3
Pre: all kernels accessible
Post: thread affinity: 2
Post: some kernels not accessible: 1

So, it seems that the cpuUsage.NextValue call somehow changes the thread affinity mask, and also makes it impossible to change the mask to 1. It does make sense, that the Nextvalue call would have to interact with the thread affinity mask in some way, if it is aggregating a performance count from each kernel, but I cannot understand, why it should affect future changes to the thread affinity mask. Does anybody have an explanation, or a workaround to this problem?
Answer: Here is some other guy with same problem
Seems like an unsolved issue from Microsoft.
Here is statement of the problem - Performance Counters change the affinity of the thread. Microsoft support.
They suggest calling to SetThreadAffinity. ) Obviously, their solution, is not working.


Ubuntu Server 14.04.1 USB freezes on Startup screen

Question: I'm not exactly an expert when it comes to linux.
Anyway, I'm trying to install Ubuntu Server 14.04.1 onto an old machine I use as a test platform. It will reach the screen that gives me the options to install Ubuntu, check disk etc but then it freezes. I let it sit for maybe 3 or so minutes then it gave me green gibberish text on the top of the screen. Not sure exactly what's going on. The desktop boots fine with PFsense on the HDD.
Comment: The first thing you should try: compare the md5 hash of your iso to the ones in http://releases.ubuntu.com/14.04/MD5SUMS. It **might** be a bad download.
Comment: Could your clarify you question. What exactly installer doing while freezing, I mean on what step or after what step? Could you make a photo of your frozen screen. Are you able to run **Try Ubuntu without install** without errors?
Answer: You can try pressing F6 in the boot screen of the image and selecting the nomodeset option. Other options added may be necessary.
http://ubuntuforums.org/showthread.php?t=1613132
Comment: This doesn't seem to help. :/
Comment: This doesn't seem to help. :/


Write I/O file to shared network drive using credentials

Question: I want to drop a .txt file on a shared network drive. The path is a map on a networkdrive which requires credentials (login and password). Can i pass these parameters using FileOutputStream?
FileOutputStream fos;
DataOutputStream dos;

try {
    File file= new File(path + "/" + fileName + ".txt");
    fos = new FileOutputStream(file);
    dos=new DataOutputStream(fos);
    dos.writeChars(stringContent);
    dos.close();
    fos.close();
}
catch(IOException eio){
}

Thank you.
Answer: No. Use java CIFS Client library. you can connect remote windows machine through java. example -
String user = "user:password";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
String path = "smb://my_machine_name/D/MyDev/test.txt";
SmbFile sFile = new SmbFile(path, auth);
SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
sfos.write("Test".getBytes());
sfos.close();

Thanks
EDIT: JCIFS only supports the unsecure SMB1 protocol and has been in maintainance mode for some years. Use jcifs-ng for SMB2/SMB3 support which is required from Windows 10.
Comment: if you have domain then you have to use domain;user:password
Comment: Download jcifs-1.1.11.jar jar from [http://jcifs.samba.org/src/](http://jcifs.samba.org/src/) and add this jar to your build path.
Comment: You say it can connect remote windows machine through java, but can it connect a Ubuntu machine to a remote windows server?
Answer: This code worked for me:
  public void downloadFromNetworkDrive3() throws MalformedURLException, SmbException, IOException {
      String user = "domain;username:password";//domain name which you connect
      NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
      String path = "smb://126.96.36.199/D$/MICROS/opera/export/OPERA/dinaamum/audit/Thumbs.db";

      SmbFile sFile = new SmbFile(path, auth);
      SmbFileOutputStream sfos;
      SmbFileInputStream sfis;
      try {
//        sfos = new SmbFileOutputStream(sFile);
          sfis = new SmbFileInputStream(sFile);

//        sfos.write("hihowareyou".getBytes());
          File tempFile = null;
          String filePath = null;
          filePath = "c://usr/local/cache/leelafiles";
          tempFile = new File(filePath);
          if (tempFile.exists()) {
          } else {
              tempFile.mkdirs();
          }
          tempFile = new File(filePath);
//        File[] allFilesAndDirs = tempFile.listFiles();
          FileOutputStream writer = new FileOutputStream(tempFile + File.separator + "Thumbs.db");
          byte[] b = new byte[8192];
          int n;
          while ((n = sfis.read(b)) > 0) {
              System.out.write(b, 0, n);
              writer.write(b, 0, n);
          }
          sfis.close();
          writer.close();

      } catch (UnknownHostException ex) {
          Logger.getLogger(ReportSchedulerJob.class.getName()).log(Level.SEVERE, null, ex);
      }

  }

Comment: Please do not just dump code , explain in context for the OP .. You have also included a third party jar [CIFS Client library](https://jcifs.samba.org/)
Comment: Sorry! Yeah i forgot to write the context however this code for reading any files from network drive using username and password and it's require third party jar CIFS Client library


Mounting disk automatically on terminal and persist across users and restarts

Question: On the GUI, we can click on the File > Devices > HDD-Name to automatically mount the disks to /media/.
I could mount them one by one manually, i.e. https://superuser.com/questions/467170/how-do-i-mount-internal-hdds-in-ubuntu-via-the-command-line
But is there a way to do the same automatically on the command line?
Also, how can these mounted drive persists after I restart the machine or across users?. E.g. if the way to do it automatically is a single command, I can put it in .bashrc to mount them automatically whenever I log on to the user.
Comment: `/etc/fstab` is for mounting devices permanently
Comment: Put mount command into /etc/bash.bashrc and mount in a shared directory between user to let all user to access that partition.
Answer: To mount a device at boot and have it visible in terminal you need to edit /etc/fstab
You can find explanation on how to edit and examples at this link
https://help.ubuntu.com/community/Fstab


Updating enum in Rails ActiveRecord model by end user

Question: Looking for the best strategy in the following scenario.
Consider Rails 4 online store app that has model Order that has a status
class Order
  enum status: [ :placed, :processed, :shipped ]
end

We ship the app to the customer and a month later they come back to us saying the want to add one more status - backordered. We go in and update code / test / and deploy.
class Order
  enum status: [ :placed, :processed, :shipped, :backordered ]
end

A few months later they come back again and want one more status - :work_in_progress . Etc
In the past we avoided the problem by having an aggregate model - Status - that would be an STI model and hold things like
OrderStatus < Status

and
CustomerStatus < Status

This makes is trivial for customer to add  statuses or change names of the status, but it makes for slower SQL look ups and cumbersome joins especially on complex queries.
So I was wondering is there a good strategy of dealing with this problem? Right now we have a combination of two - on the model we don't think customer would want to add / remove status - we keep it enum, otherwise we do belongs_to to a some kind of Status / Category model.
Answer:
a month later they come back to us saying the want to add one more
  status

Changing one line of code, even if it happens once a month, should not be a painful experience. You already have the best strategy: when the customer asks for a change, grit your teeth, add the new value, test and deploy. If that is too onerous I'd say the problem lies with the deployment process rather than the customer.
After a few rounds of this the customer will run out of new values to add and move on to other annoying requests.
Comment: :-) I guess I was too specific. Let's say you are creating an open source rails store app, that's going to be used by hundreds of users. Or your customer doesn't want to come back to you for every little thing. I'm more a of a programmer than a people person in this case - I'd rather not deal with a customer for something as trivial as adding a new status. My gut feeling is there is gotta be a better way. No?
Comment: Fair enough. Your alternate approach is the one I would use if the changes are frequent or numerous. I see no magic bullet here: you trade the simplicity of the enum for the more complex model association and need to validate/sanitize user input.
Comment: That's the logical conclusion I came to. I guess my gut was wrong. :-) Just wanted to check it. I'll leave it open for a few days and if noone comes up with a better suggestion will mark it answered. Thanks zetetic
Comment: For posterity: I ended up going with a mixed approached some are defined as enums and some are defined in a db.


GRUB not loading properly when external SSD is disconnected

Question: I have an internal SSD on which I have my primary Windows installed. I also have an external SSD where I installed my secondary Windows and Ubuntu OS. I mostly use both the Windows OS and sometimes the Ubuntu. Since my second Windows is in the external SSD, if I need to boot it, I need to boot to Windows boot manager, then select one of the OS (I know about default os.) The issue here is that the computer gets restarted (It might have obvious reasons for that I guess) and then boots up into the secondary Windows OS. I could not find a way to make an OS selection before the initial boot so I decided to use the GRUB loader. Now I get the OS selection (and the grub customization which I liked a lot) before an initial loading and I can have a fast boot into my secondary windows and my Ubuntu too (Previously with the Windows boot manager, I had to go to the BIOS to boot into ubuntu). So to make things easier, I chose the Ubuntu loader as the top order in the BIOS boot order. So everything is perfect for me except when the external SSD is not present, I cannot log into my primary windows without going to BIOS. GRUB loading is failed and an empty full-screen linux terminal is what I get. I need to go to BIOS every time to load my windows. (Of course I can make the Windows boot manager on top but I don't want to go back.)
Things I understood so far.

When we install grub, grub gets installed onto the first EFI
partition, but the /boot files are stored on my external SSD. So the
GRUB loads but fails to load its configuration files as the external
SSD is not present.
If anyhow I can move my GRUB configuration files onto the internal SSD, I can use the GRUB loader without the external SSD, and my primary windows can be loaded.
I read about installing grub on the internal EFI partition, But I cannot afford to lose any data on the internal SSD. Does installing GRUB on internal ESP remove any existing data on it? Will it affect the Windows boot manager? I don't want that. (I would go with this if it is "Add" and not "Replace").

My disk configurations are given in the picture. By the way, all the partitions in internal SSD are made by the laptop manufacturer. I never touched it. And all the partitions in external are made by me. Disk 0 is internal and Disk 1 is external.
Directory structure from Linux POV (First one is the external SSD)
<code>Model: Samsung PSSD T7 (scsi)
Disk /dev/sda: 1000GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags:

Number  Start   End     Size    File system     Name                          Flags
 1      17.4kB  16.8MB  16.8MB                  Microsoft reserved partition  msftres
 2      16.8MB  367GB   367GB                   Basic data partition          msftdata
 3      367GB   367GB   273MB   fat32           EFI System Partition          boot, esp
 6      367GB   734GB   367GB   ntfs            Ext Shared                    msftdata
 7      734GB   839GB   105GB   ext4            Linux system
 5      839GB   983GB   144GB   ext4            Ub-Home
 4      983GB   1000GB  16.8GB  linux-swap(v1)  Swap                          swap

Model: PM9A1 NVMe Samsung 512GB (nvme)
Disk /dev/nvme0n1: 512GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags:

Number  Start   End    Size    File system  Name                          Flags
 1      1049kB  200MB  199MB   fat32        EFI system partition          boot, esp
 2      200MB   334MB  134MB                Microsoft reserved partition  msftres
 3      334MB   493GB  492GB                Basic data partition          msftdata
 4      493GB   494GB  1038MB  ntfs                                       hidden, diag
 5      494GB   511GB  16.8GB  ntfs                                       hidden, diag
 6      511GB   512GB  1488MB  ntfs
</code>
Image link (I'm sorry I cannot post images directly as I'm newbie)
Comment: What we really need is a partition listing from Linux's POV as you're booting from Grub. So please plug in and start the external disk, boot to Ubuntu and run and  post the output of **sudo parted -l**. Copy the output from the terminal, then paste it here, remembering to highlight it, then hit the 'braces' icon. so it all lines up.
Comment: Sorry @PaulBenson I've edited the answer.
Comment: You missed out an important bit shown before the partitions listing. Without having to list them all again run *sudo parted -l* and tell me what is shown against the title 'partition table' for each disk. Can you also clarify exactly what you mean by the term "when the external SSD is not present'?
Comment: @PaulBenson Did so. Please not that I am having some severe issues now as I cannot boot into my original OS too without the external disk. The problem is I don't understand why this is happening. Who is deciding which drive to choose for boot configuration? How can I modify that? (But I can NEVER risk the PC not booting up. Any way I could learn this without hard issues?)
Answer: While it's certainly possible to install grub to your internal disk on a FAT partition (even the EFI), there is an easier way to almost get what you want (boot Windows when external SSD is not present, get grub and a choice of OS when SSD is attached).  The basic problem is that both your Windows installs are bitlocker encrypted, so grub will not be allowed to boot them.
Copy all the files and directory structure from the internal EFI to the external EFI.  Nothing needs to be changed.  The only thing to check is that the EFI/Boot/bootx64.efi 's size is the same as EFI/ubuntu/shimx64.efi (or maybe grubx64.efi if you don't use secure boot).  bootx64.efi is the default device bootloader, and that will give you grub's menu when run. The grub installer usually replaces the existing bootx64.efi (a copy of the Windows bootloader, with shimx64.efi.  Now, check the internal disk's EFI/Boot/bootx64.efi's size, and ensure it is the same size as the internal disk's EFI/Microsoft/bootmgfw.efi.  If not, there should be a "bkp" backup of the original, or just copy the bootmfgw.efi to the bootx64.efi to ensure it is a Windows boot.
Select how you want to boot:
If you put the external SSD first in the boot-order using your machine's UEFI settings for changing the bootorder, your machine will boot the external grub, and from it you can (only) boot Ubuntu. Override this to boot Windows by using the EFI menu (some key at powerup to allow you to select the device or Os to boot). Select Windows from the choices (or even the internal disk since it should have the bootx64.efi as a copy of bootmgfw.efi.
Put Windows second in the bootorder, so when the external SSD is absent, Windows will boot.
The internal disk's EFI/ubuntu files will no longer be used, but wont hurt anything if left there.

The external device's bootloader, ERI/Boot/bootx64.efi, you say is the same size as shim -- that's good.  I like to have the file grubx64.efi in the same directory, but for 23.04 that didn't seem to be a requirement.  The UEFI boot order should have the device at the top of the boot order, not the "ubuntu" entry.  The "ubuntu" entry is in non-volatile ran (nvram), and deleting the UEFI files will not delete the nvram entry (which definitely cannot work without the files)

With bitlocker enabled, grub wont boot either Windows, so try putting the internal hard disk Windows first in the boot list, which should allow windows booting with or without the second disk  -- no grub  involved.  To boot Ubuntu, when the second disk is attached, use the EFI menu key at powerup (some function key or del or esc...) to allow you to select device or Os to boot). Select Ubuntu from that (or device if the rootx64 default is shim/grub).  grub should then run, and should be able to boot Ubuntu (but not Windows even if it is present in the menu, since bitlocker is enabled).

To repeat, I don't think you can boot a bitlocked Windows from grub, so if that's really what you want to do, consider disabling bitlocker on your Windows installs.
Comment: I'm sorry but this did not worked. I'm still getting a minimal bash window when boot up with ubuntu as the top order in UEFI settings. Is it because my computer still loads up with the old ubuntu boot files in the internal drive? Also one more thing is I saw both shimx64.efi and grubx64.efi in EFI/ubuntu. shimx64 was of the same size. but grubx64.efi  was not. If I delete the ubuntu boot files in the internal, then my ubuntu option in UEFI will never come is that right? So I should not do that should I?
Comment: Now I am having serious issues. After copying, there were some random issues. I think my original windows boot up configuration is completely taken from external ssd than the internal. The computer now never works without the external ssd. Its a mess. How can I debug this? What is the proper way to check what the computer is loading and from where? How to change its behaviour according to my need? Where is the proper documentation for that? (It would be much helpful if I didn't need to spend a lot of time to understand this by the documentation)
Comment: @oraterlee Can you still boot into Ubuntu? If so, boot up ubuntu and then run `sudo grub-install /dev/sdX` where `/dev/sdX` is the internal disk. For example, if your internal disk is `/dev/sda` and your external disk is `/dev/sdb` then you would run `sudo grub-install /dev/sda` to install grub to the internal disk. Then, run `sudo update-grub` and hopefully this will install everything correctly to your internal disk so that you can remove the external disk and still boot up the system.
Comment: No use @mchid, I tried adding boot entry manually. Located bootx64 entry in my internal and it don't even boot up. I am kind of stuck here. I think I shouldn't have copied the boot files at the first place
Comment: @oraterlee So you can't boot into Ubuntu? And if I understand correctly, you copied some files to your internal drive? If so, then replace the files that were in your internal drive back to normal.
Comment: I found the issue!. This answer is not correct. Initially my second OS boot files was present in the external drive. After copying the files as mentioned in this answer, the files of the second os was replaced by the first OS. But then somehow the grub updates the entries in UEFI boot list and entries pointing to internal boot files was removed. I manually added and now the primary windows loads up without external SSD. But I am unable to locate the boot files of the second OS as it has been replaced. How to recreate that? (I can boot into ubuntu @mchid)
Comment: @oraterlee The second OS is Windows? If you can boot into Ubuntu, just run `sudo update-grub` first to see if that fixes the issue. Later, if you want grub installed to the internal drive, you can tell grub to install to the internal drive using the commands in my previous comment.


Flutter - Calling persistent bottom sheet from another class

Question: I have a persistent bottom sheet in Flutter which currently exists inside an icons onPressed(){} property.
I would like to move this persistent bottom sheet to a new class on its own but I can't seem to get it working. I am still new to flutter and can't work out how to build the structure for the persistent bottom bar.
I have currently tried the below but when I run my code, I get an exception that is thrown.
main.dart
@override
Widget build(BuildContext context) {
return Scaffold(
  key: _scaffoldKey,
  appBar: AppBar(
    title: Text('Test App'),
    actions: <Widget>[
      IconButton(
        icon: Icon(Icons.open_in_new),
        onPressed: (){
          ShowBottomSheet(context);
        },
      )
    ],
  ),

bottom_modal_sheet.dart
final GlobalKey<ScaffoldState> _scaffoldKey = new
GlobalKey<ScaffoldState>();

void ShowBottomSheet(BuildContext context) {
  _scaffoldKey.currentState.showBottomSheet<Null>((BuildContext context)
{
return new Container(
  width: double.infinity,
  child: new Column(
    mainAxisSize: MainAxisSize.min,
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      Padding(
        padding: EdgeInsets.only(left: 24.0, top: 16.0),
        child: Text('Site Location',
          style: TextStyle(fontSize: 24.0, color: Color(0xFF1181A1), fontWeight: FontWeight.bold,),
        ),
      ),
      Padding(
        padding: EdgeInsets.only(left: 24.0, top: 16.0),
        child: Text('11 Carr Road, Three Kings, Auckland 1042',
          textAlign: TextAlign.left,
          style: TextStyle(fontSize: 16.0, color: Color(0xFF8596AC)),
        ),
      ),
      Padding(
        padding: EdgeInsets.only(left: 24.0, top: 24.0, right: 24.0, bottom: 16.0),
        child: RasiedGradientButton(
          child: Text('Set Location', style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold, color: Colors.white)),
          gradient: LinearGradient(
            colors: <Color>[Color(0xFFFCCF58), Color(0xFFFEAA00)]
          ),
          onPressed: (){
            print('button clicked');
          },
        )
      ),
    ],
));
  });
}

I am getting the error:
I/flutter (19024): ══╡ EXCEPTION CAUGHT BY GESTURE
╞═══════════════════════════════════════════════════════════════════
I/flutter (19024): The following NoSuchMethodError was thrown while
handling a gesture:
I/flutter (19024): The method 'showBottomSheet' was called on null.
I/flutter (19024): Receiver: null
I/flutter (19024): Tried calling: showBottomSheet<Null>(Closure:
(BuildContext) => Container)
I/flutter (19024):

Answer: You just need call  showBottomSheet in your screen widget that you want show the bottom sheet and return the widget of your custom bottom sheet. The snippet show how to do this. Read the source comments.
// our Screen widget class
class MyScreen extends StatefulWidget {
  @override
  _MyScreenScreenState createState() => _MyScreenScreenState();
}

class _MyScreenState extends State<MyScreenScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
        title: Text('Test App'),
      actions: <Widget>[
        IconButton( icon: Icon(Icons.open_in_new),
        onPressed: (){
          _showMyBottomSheet();
        },
        )
      ],
        ),
    );
  }

  void _showMyBottomSheet(){
    // the context of the bottomSheet will be this widget
    //the context here is where you want to showthe bottom sheet
    showBottomSheet(context: context,
        builder: (BuildContext context){
          return MyBottomSheetLayout(); // returns your BottomSheet widget
        }
    );
  }
}

//your bottom sheet widget class
//you can put your things here, like buttons, callbacks and layout
class MyBottomSheetLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(); // return your bottomSheetLayout
  }
}


4 wire Samsung Dryer Cord Cross Wired - Dryer not working after corrected

Question: Just bought a used Samsung front loading dryer, and the guy we bought it from swapped his long cord out for the original short cord, but apparently had the red wire in the middle and white on the left...when I plugged it in, it sparked and the Elec. Panel Circuit Breakers tripped.
I assumed it might be cross wired, saw a video and moved the red wire to the outside and white wire to the middle, plugged it back in, CB tripped once...reset it, but nothing.  No power to dryer, at least it's not responding and CB doesn't trip anymore.  The dryer was working when we picked it up.  What can we do to get the dryer working, now that the cord is wired correctly?
OK, just had an Appliance Repair guy out to the house...and we sorta lucked out...he said I reattached the cord properly, and the circuit board checks out OK.  It appears the surge killed the power in the line.  So either my Master Panel Dryer Circuit Breakers tripped, permanently, or there is a short in the wall outlet, as he got no power out of the outlet.  My money is on the CB now being inop.  Now we need an Electrician to most likely replace those breakers in the panel, and check the path to the dryer.
Comment: Find the wiring diagram for that exact model, probably online, and make sure it is wired correctly.  Sparks and tripping might have caused damage inside, maybe just a fuse, maybe burned out control board.  Also make sure your house circuit is wired correctly.  Test for voltage.
Comment: Wait, has NEC 110.3(B) been revised to no longer require following the approved manufacturer instructions, and just watch Youtube videos from some random yutz whose sole qualification is playing the Youtube ranking game?
Comment: I think you've successfully blown the "fuse" consisting of all the 120V electronics in the dryer after applying 240V to them. **Always triplecheck wiring before connecting appliances to power.** Or at least do that next time.
Comment: Please take the [tour] to learn how to follow up when you receive answers. We don't mark questions [solved] here.
Comment: Again, please take the [tour]. We're playing edit-pong here.
Answer: One possibility is that the previous connection was a 3-wire connection (NEMA 10-30) and you now have a 4-wire connection (NEMA 14-30). If that is the case and the neutral-ground bond in the dryer was not removed then a miswire could easily cause a breaker trip. For example, if one of the hots and neutral are reversed but neutral still connected to ground, then when you plug it in you get hot (receptacle) to neutral (dryer) to ground (dryer) to ground (receptacle) which will cause an immediate trip. There are a bunch of other possibilities as well.
There is no industry-standard arrangement of wires. Lookup the manual for your model to find out the correct arrangement. Then double-check the neutral-ground bond. You should be using a 4-wire NEMA 14-30 receptacle and the neutral-ground bond in the dryer should be removed.
Also double-check your receptacle configuration. Unplug the dryer. Reset the breaker. (If it won't reset with the dryer unplugged then you have bigger problems.) You should have 240V between the hots, 120V between each hot and neutral, 120V between each hot and ground, 0V between neutral and ground. If any of those readings is wrong, fix that before fixing the dryer.
If you have a 3-wire receptacle, replace that before proceeding.
Answer: It's possible that the control electronics inside has been fried.  If they are intended to run on 120V (hot to neutral), but the mis-wire put 240V (hot to hot), then there could be any amount of damage.
You'd need someone expert enough to diagnose the problem and maybe replace the main circuit board.
Answer: Answer was edited into the question
Electrician checked the outlet, inspected the Breaker Box and noticed the Breakers were still in the Tripped position. He properly shut the breakers off and back on. Problem solved. The Breakers worked, they protected the Dryer, which works just fin again. But so glad I started with the Cord, and found the correct wiring pattern, and corrected it. We are good to go now! Thank you all!
Had some help look at the power issue. Turns out I did not completely reset the panel circuit breaker. Flipped it all the way off and back on, and everything works correctly. So, didn't fry anything, CB did it's job...reset and good to go! Good advice, double check everything, especially wiring and Circuit Breakers! Thank you all!


Why aren't my javascript functions running?

Question: I have several functions on my web page that aren't working, here is one -

 Change background color

    <input name="bg" value="cyan" id="cyan" type="radio" onclick="changebgcolor(this);">"Cyan"
    <input name="bg" value="magenta" id="magenta" type="radio" onclick="changebgcolor(this);">"Magenta"
    <input name="bg" value="lightsalmon" id="lightsalmon" type="radio" onclick="changebgcolor(this);">"Light Salmon"

        function changebgcolor(element){
            document.body.style.backgroundColor = element.value;
        };

Console is telling me my elements are not defined?
The other one is a similar function intended to change text color, the rest are form validations.
and here is the web page I am working on -
http://www.acsu.buffalo.edu/~mariaroo/validation.html
Comment: Did you view the console? Their is a lot of errors.
Comment: There is an `if` missing in the line `else (color == "lightsalmon"){`
Comment: Thanks, I fixed a lot of it, the text color still isn't working but I don't see any errors in the console...
Comment: Your validate zip method needs brackets `if zip.length < 5` to `if (zip.length < 5)`
Answer: An else statement is not followed by a condition. You need to change your last else to an else if or remove the condition altogether:
// if you plan on adding more color options go this route
else if (color == "lightsalmon"){
    document.body.style.backgroundColor = "lightsalmon"
}

// if you're not going to add any more color options this will work as well
else {
    document.body.style.backgroundColor = "lightsalmon"
}

EDIT
It looks like you've updated your code and the new issue is that when your HTML is parsed the changebgcolor and changetextcolor functions don't exist yet (they are at the bottom of your page). To fix this move them up into the  portion of your document so they are already initialized before your radio buttons and their onclick event handler is registered. See my example below:

... // you have meta, title and styling here


how to create OSLC docs using Jena?

Question: I need to create RDF/XML documents containing objects in the OSLC namespace.
e.g.
<oslc_disc:ServiceProviderCatalog
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:dc="http://purl.org/dc/terms/"
    xmlns:oslc_disc="http://open-services.net/xmlns/discovery/1.0/"
 rdf:about="{self}">

  <dc:title>{catalog title}</dc:title>
  <oslc_disc:details rdf:resource="{catalog details uri}" />

what is the simplest way to create this doc using the Jena API ?
( I know about Lyo, they use a JSP for this doc :-)
Thanks, Carsten
Answer: Here's a complete example to start you off. Be aware that this will be equivalent to XML output you want, but may not be identical. The order of properties, for example, may vary, and there are other ways to write the same content.
import com.hp.hpl.jena.rdf.model.*
import com.hp.hpl.jena.vocabulary.DCTerms;

public class Jena {

    // Vocab items -- could use schemagen to generate a class for this
    final static String OSLC_DISC_NS = "http://open-services.net/xmlns/discovery/1.0/";
    final static Resource ServiceProviderCatalog =
        ResourceFactory.createResource(OSLC_DISC_NS + "ServiceProviderCatalog");
    final static Property details =
        ResourceFactory.createProperty(OSLC_DISC_NS, "details");

    public static void main(String[] args) {

        // Inputs
        String selfURI = "http://example.com/self";
        String catalogTitle = "Catalog title";
        String catalogDetailsURI = "http://example.com/catalogDetailsURI";

        // Create in memory model
        Model model = ModelFactory.createDefaultModel();
        // Set prefixes
        model.setNsPrefix("dc", DCTerms.NS);
        model.setNsPrefix("oslc_disc", OSLC_DISC_NS);

        // Add item of type spcatalog
        Resource self = model.createResource(selfURI, ServiceProviderCatalog);
        // Add the title
        self.addProperty(DCTerms.title, catalogTitle);
        // Add details, which points to a resource
        self.addProperty(details, model.createResource(catalogDetailsURI));

        // Write pretty RDF/XML
        model.write(System.out, "RDF/XML-ABBREV");
    }

}

how to create OSLC docs using Jena?


event bus vuejs not emit event to pass data to component

Question: I'm using for the first time the Vue event bus to pass data to child components from the main vue instance. After some testing I'm not able to get the data inside my components, I think the code is correct, but I'm not sure of this. Is something wrong in the code?
I have three separate file (I'm not using webpack). Two js files that will hold the main vue instance and the components and a file that will hold the template. I'm developing a wordpress theme.
Any help?
// app.js file
Vue.prototype.$eventHub = new Vue(); // Global event bus

Vue.directive('prlx', VuePrlx.VuePrlxDirective);

new Vue({
  el: '#ume',
  router,
  data: {
    pageData: [],
    feedImg: []
  },
  watch: {
    $route( to, from ){
      console.log('main instance:'+ to, from);
      this.getPage();
    }
  },
  methods: {
    getPage: function(){
      //console.log(this.$route);
      var slug = this.$route.fullPath.replace(/\//g, "")
      axios.get(uptheme.pages_rest_url+'?slug='+ slug)
        .then( (response) => {
        console.log(response.data);
        response.data.forEach( (item, i) => {
          this.pageData = [item];
          if( item.embedded.gallery_images ){
            item.embedded.gallery_images.forEach( (img) => {
              this.feedImg.push(img);
            });
          }
        });
      });
      this.$eventHub.$emit('page_data', this.pageData);
    },
  }
});

components.js file:
Vue.component('ume-about',{
  template: '#about-tpl',
  data() {
    return {
      pageData: [],
      feedImg: []
    }
  },
  created() {
    this.$eventHub.$on('page_data', (data) => {
      console.log(data);
      this.pageData.push(data);
    });
  },
  beforeDestroy() {
    $eventHub.$off('page_data');
  }
});

about-template.php file
// This file will only hold the template

Comment: I've added an answer which was too long for a comment which could help
Comment: Are you getting any errors?
Comment: No, there is no error. The console will not log nothing, I'm logging the data only for the component now to see if data are passed, but nothing showed!
Answer: this.$eventHub.$emit('page_data', this.pageData); is not in your axios function and so will return nothing
axios.get(uptheme.pages_rest_url+'?slug='+ slug)
    .then( (response) => {
        console.log(response.data);
        response.data.forEach( (item, i) => {
          this.pageData = [item];
          if( item.embedded.gallery_images ){
            item.embedded.gallery_images.forEach( (img) => {
              this.feedImg.push(img);
            });
          }
        });

        this.$eventHub.$emit('page_data', this.pageData);
    });

Comment: I'm inspecting the vue debug console in chrome and the event is emitted. Do I need to move the event inside the `.then()` callback of axios?
Comment: @guggio yes, the event is being trigger immediately after the axios call is made so it's not waiting for the response and just returns nothing (I've moved the emit into the `.then()` in my answer
Comment: I will test and let you know.
Comment: Thanks for the help, I've solved. Now to retrive the data inside the data I need only to add the event payload into the `pageData` array right? Nothing to change inside the component?
Comment: I'm not sure I understand what you mean. Right now it looks like you are overwriting the pageData with `[item]` each time in your `response.data.forEach` function. What you may need to do is for that is `this.pageData.push(item)`
Comment: The data are passed correctly into the payload, `.push()` will give me problems sometime. What I need to do now is get the data in the component and pass them to the `pageData` that is defined inside it
Comment: In the about-template.php file? That will need to be a vue component and you use the same code that you have for components.js just have the about-template.php as the template. What I normally like to do to keep things tidy is create a single file component [here](https://vuejs.org/v2/guide/single-file-components.html) and then to call that file I use, using yours as an example, `Vue.component('ume-about', require('./components/umeAbout.vue').default)`. I hope that makes sense and answers your query
Comment: I'm not using webpack at the moment but all seems to working fine. Thanks for the help