Regex workaround infinite repetition inside lookbehind

Question: I'm trying to match the text value_to_match when preceeded by a line "attribute": "type" and preceeded (at some point) by a "marketTypeId": 123456789 in Intellij regex search.
In the following text the search should match value_to_match only.
    {
      "marketTypeId": 123456789,
      "description": "Market description",
      "periodType": "MATCH",
      "periodInstance": 1,
      "feedMappingData": [
        {
          "outcomeIdFeedcodeMap": {
            "2": "123456789001",
            "1": "123456789002"
          },
          "conditions": [
            {
              "element": "Market",
              "attribute": "type",
              "condition": "EQUALS",
              "value": "value_to_match"
            },
            {
              "element": "Market",
              "attribute": "traded_pre_match",
              "condition": "EQUALS",
              "value": "true"
            }
          ]
        },
    {
      "marketTypeId": 12121212,
      "description": "Market description",
      "periodType": "MATCH",
      "periodInstance": 1,
      "feedMappingData": [
        {
          "outcomeIdFeedcodeMap": {
            "2": "12121212001",
            "1": "12121212002"
          },
          "conditions": [
            {
              "element": "Market",
              "attribute": "type",
              "condition": "EQUALS",
              "value": "value_NOT_to_match"
            },
            {
              "element": "Market",
              "attribute": "traded_pre_match",
              "condition": "EQUALS",
              "value": "true"
            }
          ]
        },

I've been trying to use lookbehind with the conditions but it seems Intellij regex search does not support infinite repetition inside lookbehind.
Is there any workaround for situations like this?
Comment: (?<=marketTypeId":\s?)(?:123456789)(?=,\n)(?:(?s).*?"attribute":\s?"type",.*?"value":\s?")(.*)(?=") matches the whole block from the markeTypeId to the value I want to match and the value_to_match is captured in a group... but it does not help...
Comment: Isn't that JSON? Why don't you use a JSON parser?
Comment: my idea is not to use it in the code, quite often i need to retrieve some strings from huge json files and i search in IntelliJ for convenience. using regex search seems the most pratical way to retrieve a bunch of those matches
Answer: Using Intellij and positive lookbehind
The regex used in Intellij:
(?s)(?<="marketTypeId":\s123456789,.{1,500}"attribute":\s"type",.{1,100}"value":\s")value_to_match(?=")

Note:

Dotall mode can also be enabled via the embedded flag expression (?s)

Read more about this flag expression and regex lookarounds in reference:
https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html
Used Intellij version 2020.2
Picture of Intellij and match:

More can be read about Intellij and matching here:
Is there a way with Regex to grab the first word and replace a quoted section?
Comment: Happy to hear :)


Dynamic Component with React Router

Question: I'm learning React Router at the moment and would like to know if it's possible to render the Topics.js into a new component and remove the links on the top on click ?.
Like let's say i want to have cards instead of the link and when i click the cards i want the links to disappear and be on a new page, so just the component Topic.js will appear on the page
https://stackblitz.com/edit/react-router-dynamic-routes?file=index.js
Comment: Are you talking about removing the navigational bar? That would just be moving the Nav bar either to its own component and put _that_ in the Home component, or just putting it in the home component directly, but I don't know why you'd want to, since it makes your page un-navigable.

Otherwise, what you're probably talking about would be a CSS problem.

Edit: It's probably a CSS problem. If you want a modal, you may look into adding https://unpkg.com/bootstrap/ to the setup
Answer: The React.lazy function lets you render a dynamic import as a regular component.
const Login = React.lazy(() => import('./views/Pages/Login'));
<Route exact path="/login" name="Login Page" render={props => <Login {...props}/>} />

Learn more
Answer: It sounds like you should make the header area its own component and then make that component a part of the Home component, but not the Topics
class App extends Component {
  render() {
    return (

          <Route exact path='/' component={Home} />
          <Route path='/topics' component={Topics} />

    );
  }
}

class AppLinks extends Component {
  render() {
    return (

              <Link to='/'>Home</Link>

              <Link to='/topics'>Topics</Link>

    );
  }
}

export default class Home extends Component {
  render() {
    return (

        <AppLinks />
        HOME

    );
  }
}

Dynamic Component with React Router


using spannable to seperate words in a String

Question: I DON'T WANT SPAN ON MY SPACES
I have a string, for example:
String items = " flowers chocolates candles ";
What I need to do is print this string like this:

Can I do this using spannable in Java? If yes, how ?
I have this RoundedBackgroundSpan class:
public class RoundedBackgroundSpan extends ReplacementSpan {

    private static final int CORNER_RADIUS = 8;
    private int backgroundColor = 0;
    private int textColor = 0;

    public RoundedBackgroundSpan(Context context) {
        super();
        backgroundColor = context.getResources().getColor(R.color.colorPrimary);
        textColor = context.getResources().getColor(R.color.white);
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        RectF rect = new RectF(x, top, x + measureText(paint, text, start, end), bottom - 2);
        paint.setColor(backgroundColor);
        canvas.drawRoundRect(rect, CORNER_RADIUS, CORNER_RADIUS, paint);
        paint.setColor(textColor);
        canvas.drawText(text, start, end, x, y, paint);
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        return Math.round(paint.measureText(text, start, end));
    }

    private float measureText(Paint paint, CharSequence text, int start, int end) {
        return paint.measureText(text, start, end);
    }
}

Comment: Does this answer your question? [Background color to spanableString in android](https://stackoverflow.com/questions/25724117/background-color-to-spanablestring-in-android)
Comment: No, I want the spannable to break with every space in the string and start again.
Answer: There's two solutions for this. You can either add a RoundedBackgrondSpan to each word, or you can modify your RoudedBackgroundSpan as currently it draws a single rectangle.
The first approach would probably be easier.
Comment: Looks like @NileshB has written the code for you!
Answer: use this function:
private Spannable spanWords(String message) {
    int start = 0;
    String[] words = message.split(" ");
    Spannable spannable = new SpannableString(message);
    for (String word : words) {
        spannable.setSpan(new RoundedBackgroundSpan(getContext()), start, (start + word.length()), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        start += word.length() + 1;
    }
    return spannable;
}


EV Nova bug, quest won't trigger

Question: I'm playing a pretty old game called Escape Velocity Nova (on windows, WIN10), and I've gotten to the wild geese storyline mission where I should proc the next mission by heading to the bar (Deliver explosives to ryll), but I can't get the mission to open up. I've tried landing, flying around, close/opening the game but nothing has worked for me. Any Nova veterans out there that have this issue and have found a workaround? I'm trying to get to the rebel storyline which branches off the end of the wild geese story, but I've gotten pretty stuck.
Answer: Does your ship have enough cargo space to pick up the explosives? They're 10 tons. (What do you need 10 tons of explosives for? I don't know either.) According to https://www.arpia.be/walkthrough/wildgeese.html, neither version of this mission has anything strange going on with the availability bits: it just says "completed the previous mission, haven't completed this one, and haven't aborted the Wild Geese storyline"; and both should have a 100% chance to appear at the Bar on New Ireland. But it does require enough storage space, and I think Bar missions won't even appear if your ship is too small (or too full) to accept them. Note that you can't put mission-critical cargo in a follower ship: your own ship must have at least 10 tons available.
If you're still stuck, you can make a pilot log by creating an empty text file named pilotlog.txt in your EV Nova directory, then launching the game and loading your save, and landing on any planet (which causes it to update). You can then look in the "Mission bits currently set" section. The bits you're looking for in this case are:

b803, which gets set if you quit any mission in the Wild Geese storyline, which effectively locks you out of the game because it doesn't also clear b511, which locks you out of all main storylines. If you've got this one, you're stuck and in fact you might as well start a new character; your current character is considered too much of a flake to be trusted by any of the major factions.
b807 or b814, which represent completion of Destroy McGowan's Drug Factory (depending on if Michaleen is alive). You should have one of these.
b808 or b815, which represent completion of Deliver Explosives to Ryll (again keeping track of Michaleen). You shouldn't have either of these.

If your ship is big enough and your bits seem right, I don't know what else could be the problem.
However, no version of the Wild Geese storyline actually leads to the Rebellion main storyline, either: if Michaleen got killed in Sol, you'll get a choice to join up with the Aurorans or the Pirates (although the Pirate choice is actually labeled "Rebels", because the Rebels don't actually talk to anyone else, so the only way to help them out is to support the Pirate Association's supply efforts). If Michaleen survived the Sol mission (this was a pure coin flip), then you'll get another coin flip later to either join the Pirates (again), or simply complete the Wild Geese storyline with no automatic entry into any major storyline. The actual Rebellion storyline is probably the hardest of the main storylines to find, because the Rebels are so insular; you can only get them to talk to you by either making a name for yourself among the Bounty Hunters, or actively betraying the Federation (neither of which are easy to get to in the first place; both the Federation and the Bounty Hunters require a relatively fearsome Combat Rating before they'll even talk to you).
Comment: Yup, that was the issue. I went and dropped off some passengers (going from 9->10 free tons in the process) and came back and the quest triggered immediately. All the other information is also very good to know, looks like I need to start blowing some ships up. I did indeed land on the pirate storyline after continuing. Is it possible to copy your pilot data before a 'decision' coin-flip to re-roll the results?
Comment: @PerplexingPies Your saved game data must be stored somewhere, that you could backup to someplace the game doesn't know about. But I don't know where, sorry.

EV Nova bug, quest won't trigger


Getting id after inserting

Question: I'm working with windows phone apps using windows azure as database and is there any windows azure script to return back to my windows phone apps an id that created automatically by windows azure? so i can catch the id value and use it in my windows phone? instead of calling these method that I think maybe slow
<code>addressItem = await addressTable
                    .Where(table => table.placeId == hereRestDetail.placeId)
                    .ToCollectionAsync();
</code>
Answer: When inserting data to a Table with autogenerated Id in Azure, once insertion finished the Id is sent back to client application. So you can simply get the Id from the same object model used for insert operation :
<code>.....
await addressTable.InsertAsync(addressModel);
var generatedId = addressModel.Id;
.....
</code>
[Reference]

Getting id after inserting


Date is returning a wrong value

Question: I want $dayleft inside the else to appear in "Y/n/j" format, but when I run it, it only returns the year, what is happening?
Code:
$select = mysqli_query($connect, $query_select);
$row = mysqli_fetch_row($select);
$idchange = $row['5'];
$date = DateTime::createFromFormat("Y-n-j", $idchange);
if (date('Y/n/j', strtotime("-60 days")) > $date){
echo "
Reset Machine_ID - Status: Available";
}
else{
$dayleft = date('Y/n/j', strtotime("+60 days")) - $date;
echo "
Reset Machine_ID - Status: Unavailable - Available Day: $dayleft";
}

Comment: You can't compare strings with `>`. Make them integers, or use the `datediff`  function.
Comment: `date()` produces a string. You're using strings in mathematical comparisons and operations. The results will be somewhat random.
Comment: @chris85 I did that: `if (date_diff(date('Y/n/j'),$date) >= 60)` and is producing this error: `Warning: date_diff() expects parameter 1 to be DateTimeInterface, string given in /home/u478317930/public_html/externalhack.php on line 92
`
Comment: @deceze how i do in the right way?
Comment: What exactly do you *want* to do? Print the difference between two dates as "X years, Y months, Z days"? Or simply subtract/add days to a date and produce a new date?
Comment: @deceze print the difference.
Comment: Use `strtotime` and PHP match functions, or use `datediff`. http://php.net/manual/en/datetime.diff.php
Answer: You have to format the final result of your calculation.
$dayleft = date('Y/n/j', strtotime("+60 days")) - $date;
$dayleft = date('Y/n/j',$dayleft);
echo "
Reset Machine_ID - Status: Unavailable - Available Day: $dayleft";

UPDATE:
Here's an example tested in PHP Fiddle:
<?php
$date = time();
echo "Today: ". date('Y/m/d h:n:s',$date)."
";

//$dayleft = date_add(date('Y/m/d h:i:s',strtotime("+60 days")), $date);
$t1 = date('Y/m/d h:i:s',strtotime('+60 day', $date));
echo "Date Available: " . $t1."
";
$dayleft = date('Y/n/j',strtotime($t1));
echo $dayleft."
";
echo "
Reset Machine_ID - Status: Unavailable - Available Day: $dayleft";
?>

And here's the output:

Today: 2017/05/08 09:5:48
Date Available: 2017/07/07 09:57:48 2017/7/7
Reset Machine_ID - Status: Unavailable - Available Day: 2017/7/7
Comment: Now it's returning ever 1970/1/1, how i can fix that?
Comment: @Francisco: Did you try the updated code?

Date is returning a wrong value


how to automate the functional testing in yii2?

Question: I use the codecept functional testing for test my APIs in yii2.I put the arguments hardcoded for testing like this
use tests\codeception\backend\FunctionalTester;
$I = new FunctionalTester($scenario);
$I->wantTo('Check when authenticated');
$I->sendPOST('/login', ['password' => '11111111', 'email'=>'email@example.com']);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();
$I->seeResponseContains('"result"');
$I->seeResponseContains('"message"');
$I->haveHttpHeader('Accept','application/json');
$I->seeResponseContains('"message":"OK"');

I wanted to give that arguments while I running the test case by codecept run functional loginCept or save that arguments in one file and assign to the test case when I run the test.How should I achieve this?
Comment: I have same problem, How to automate the functional testing in yii2?
Answer: You can create a file in path/to/your/project/tests/codeception/config  called let's say params.php. Then add params to the newly created file:
<?php
    return [
        'login.email' => 'email@example.com',
        'login.password' => '111111'
    ];

In your path/to/your/project/tests/codeception/config/config.php put this:
<?php
    return [
        'components' => [
            ...
        ],
        'params' => require(__DIR__ . '/params.php'),
    ];

Use it in your test code the same way you call params in a regular Yii application. It doesn't matter whether it is unit, functional etc.
Yii::$app->params['user.login'];


(Dual Booting) How Can I Make Windows Ignore Ubuntu EFI Partition

Question: I have two hard drives in my computer, hard drive 1 is Windows and hard drive 2 is Ubuntu. I know some people recommend only using one EFI, but I prefer having my operating systems (and therefore the EFI as well) separated physically like this.
Recently a Windows update destroyed my entire Windows install, so I've had to re-install via USB.
The problem is that even with a seperate fat32 EFI created on hard drive 1 specifically for Windows, Windows installs to the hard drive I've specified for it, but it uses the EFI on the other hard drive (my Ubuntu one). This makes it and Ubuntu share the same EFI and then I get a message every boot into my Ubuntu that says the EFI is almost full (and by almost it means a few KB).
How can I force Windows to use the EFI I've created specifically for it on hard drive 1, and prevent it from writing to the EFI on my Ubuntu hard drive 2?
Comment: You can physically disconnect the Ubuntu drive, but may have to use efibootmgr to recreate the Ubuntu entry in UEFI as it forgets disconnected drive. Or reinstall grub-efi-amd64. You probably can also just in UEFI change drive's settings to disabled. You then have logically disconnected it.
Answer: I also dual-boot Ubuntu and Windows using two separate hard drives.
The way I got everything to work properly was to install Windows without the Ubuntu drive pyhsically connected to the computer.  After Windows is installed, you can install Ubuntu onto just the one drive with both connected since Ubuntu lets you choose what disks to modify.
Hope this helps.
Comment: @KUPOinyourWINDOW Oh man.  Sorry to hear that.  This is the only way I know how to do it unfortunately.  I hope someone else can help you figure this out :)
Comment: I don't want to change EFI on previous Windows Partition /sda1. I'm installing ubunt in a usb storage /sdb and I want to select in bios the bootable medium when using Linux. Should I change in "Installation Type" the EFI partition from "Use as: EFI System Partition" to "do not use the partition"? If I mark all /sda partitions as "do not use.." will the installer change something in /sda? Should I create a new EFI partition in /sdb for ubuntu? Thanks


Programming a GUI with PyQt in Python3

Question: I'm asked to create a GUI with PyQt without using any Qtdesigner for my assignment. But now I'm facing a problem. In this pic GUI screenshoot

as you can see, there is a spinbox "Anzahl der Schicht". What I want to do is, when the user sets the value for this spinbox, the area which below it will show the corresponding rows of the input(the combination of QLineEdit,QSlider Widget,QLineEdit and 2 QSpinboxes in a row).
For example, the pic that I uploaded, means the value of spinbox "Anzahl der Schicht" is 3, so there are 3 rows below it. If the value is 4, there should be 4 rows. There is no limited value for the spinbox. How can I make this kind of dynamic effect for the GUI?
Update on 05.07.2019
Thanks for all useful replies. The following code and pic GUI version2 is my current status. So far I can't connect the Qspinbox to the class Widget() for adding or deleting the rows. So I just use a button "add widget" to implement what I want.
class ExampleWidget(QtWidgets.QGroupBox):
def __init__(self, numAddWidget):
    QtWidgets.QGroupBox.__init__(self)
    self.numAddWidget = numAddWidget
    self.initSubject()
    self.organize()
    self.setFlat(True)
    self.setStyleSheet("border: 1px solid transparent")

def initSubject(self):
    self.shiftname =QtWidgets.QLineEdit() # Eingabefeld init
    self.shiftname.setText('0')
    self.shiftpercent = QtWidgets.QSlider()
    self.shiftpercent.setOrientation(QtCore.Qt.Horizontal)
    self.carnum =QtWidgets.QLineEdit() # Eingabefeld init
    self.carnum.setText('0')
    self.start = QtWidgets.QTimeEdit()
    self.start.setDisplayFormat("HH:mm")
    self.end = QtWidgets.QTimeEdit()
    self.end.setDisplayFormat("HH:mm")

def organize(self):
    grid = QtWidgets.QGridLayout(self)
    self.setLayout(grid)
    grid.addWidget(self.shiftname, 0,0)
    grid.addWidget(self.shiftpercent, 0,1)
    grid.addWidget(self.carnum, 0,2)
    grid.addWidget(self.start, 0,3)
    grid.addWidget(self.end, 0,4)

class Widget(QtWidgets.QWidget):
def __init__(self):
    super().__init__()
    self.numAddWidget = 1
    self.initUi()

def initUi(self):
    self.layoutV = QtWidgets.QVBoxLayout(self)

    self.area = QtWidgets.QScrollArea(self)
    self.area.setWidgetResizable(True)
    self.scrollAreaWidgetContents = QtWidgets.QWidget()

    self.layoutH = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)
    self.gridLayout = QtWidgets.QGridLayout()
    self.layoutH.addLayout(self.gridLayout)

    self.area.setWidget(self.scrollAreaWidgetContents)
    self.add_button = QtWidgets.QPushButton("Add Widget")
    self.layoutV.addWidget(self.add_button)
    self.layoutV.addWidget(self.area)
    self.add_button.clicked.connect(self.addWidget)

    self.widget = ExampleWidget(self.numAddWidget)
    self.gridLayout.addWidget(self.widget)

def addWidget(self):
    self.numAddWidget += 1
    self.widget = ExampleWidget(self.numAddWidget)
    self.gridLayout.addWidget(self.widget)

if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())

Comment: Show what you have tried
Comment: This sounds like a 'variable number of variables': https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables
Comment: @S.Nick,@eyllanesc I just attached the code. Pls have a look if you're still interested in it.
Answer: Here is a way. In this example the widgets (QLineEdits in this case) are stored in a list, Widget.items. When the value of the spin box changes extra widgets are appended to this list and added to the vertical layout if necessary. The widgets are then shown or hidden depending whether the current number of visible widgets is greater or smaller than the value of the spin box.
from PyQt5 import QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__()
        self.resize(500,500)
        self.items = []
        self.item_count = 0
        self.item_factory = QtWidgets.QLineEdit

        group_box = QtWidgets.QGroupBox()
        self.item_layout = QtWidgets.QVBoxLayout(group_box)
        self.item_layout.addStretch(2)

        self.spin_box = QtWidgets.QSpinBox(self)
        self.spin_box.valueChanged.connect(self.set_item_count)

        h_layout = QtWidgets.QHBoxLayout(self)
        h_layout.addWidget(group_box, 2)
        h_layout.addWidget(self.spin_box, 0)

    def set_item_count(self, new_count:int):
        n_items = len(self.items)
        for ii in range(n_items, new_count):
            item = self.item_factory(self)
            self.items.append(item)
            self.item_layout.insertWidget(n_items, item)
        for ii in range(self.item_count, new_count):
            self.item_layout.itemAt(ii).widget().show()
        for ii in range(new_count, self.item_count):
            self.item_layout.itemAt(ii).widget().hide()
        self.item_count = new_count

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    window = Widget()
    window.show()
    app.exec()

Comment: Thank you @Heike. I extracted some idea from your code.

Programming a GUI with PyQt in Python3


Is it possible to use a heightmap like Mathf.PerlinNoise();?

Question: I am relatively new to Terrain Generation in Unity, and am currently stuck in one place.  I have followed Brackey's tutorial on terrain generation, and in that tutorial, he uses something like this:
float y = Mathf.PerlinNoise(x, z) * 2f;

To manipulate the height of the terrain.  I also followed Sebastian Lague's tutorial on this.  This is where I am stuck.
I want to use Sebastian Lague's Noise.cs file that he created (can be found on his GitHub) to manipulate the terrain height.
The reason is because this noise generator, rather than Mathf.PerlinNoise(), gives you a much better control over the texture it outputs.  The problem is, Noise.cs will return a 2D float array, while Mathf.PerlinNoise() returns a 1D float value.  Is there a way for Noise.cs to return a float value, just like Mathf's function?
Noise.cs:
using UnityEngine;
using System.Collections;

public static class Noise {

    public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity, Vector2 offset) {
        float[,] noiseMap = new float[mapWidth,mapHeight];

        System.Random prng = new System.Random (seed);
        Vector2[] octaveOffsets = new Vector2[octaves];
        for (int i = 0; i < octaves; i++) {
            float offsetX = prng.Next (-100000, 100000) + offset.x;
            float offsetY = prng.Next (-100000, 100000) + offset.y;
            octaveOffsets [i] = new Vector2 (offsetX, offsetY);
        }

        if (scale <= 0) {
            scale = 0.0001f;
        }

        float maxNoiseHeight = float.MinValue;
        float minNoiseHeight = float.MaxValue;

        float halfWidth = mapWidth / 2f;
        float halfHeight = mapHeight / 2f;

        for (int y = 0; y < mapHeight; y++) {
            for (int x = 0; x < mapWidth; x++) {

                float amplitude = 1;
                float frequency = 1;
                float noiseHeight = 0;

                for (int i = 0; i < octaves; i++) {
                    float sampleX = (x-halfWidth) / scale * frequency + octaveOffsets[i].x;
                    float sampleY = (y-halfHeight) / scale * frequency + octaveOffsets[i].y;

                    float perlinValue = Mathf.PerlinNoise (sampleX, sampleY) * 2 - 1;
                    noiseHeight += perlinValue * amplitude;

                    amplitude *= persistance;
                    frequency *= lacunarity;
                }

                if (noiseHeight > maxNoiseHeight) {
                    maxNoiseHeight = noiseHeight;
                } else if (noiseHeight < minNoiseHeight) {
                    minNoiseHeight = noiseHeight;
                }
                noiseMap [x, y] = noiseHeight;
            }
        }

        for (int y = 0; y < mapHeight; y++) {
            for (int x = 0; x < mapWidth; x++) {
                noiseMap [x, y] = Mathf.InverseLerp (minNoiseHeight, maxNoiseHeight, noiseMap [x, y]);
            }
        }

        return noiseMap;
    }

}

MeshGenerator.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(MeshFilter))]
public class MeshGenerator : MonoBehaviour
{
    Mesh mesh;

    Vector3[] vertices;
    int[] triangles;

    public int xSize = 20;
    public int zSize = 20;

    int mapWidth;
    int mapHeight;
    int seed;
    float scale;
    int octaves;
    float persistance;
    float lacunarity;
    Vector2 offset;

    // Start is called before the first frame update
    void Start()
    {
        // Initialize everything
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;

        CreateShape();
        UpdateMesh();
    }

    void CreateShape()
    {
        // Creating the grid of vertices
        vertices = new Vector3[(xSize + 1) * (zSize + 1)];

        // Setting vertex positions
        for (int i = 0, z = 0; z <= zSize; z++)
        {
            for (int x = 0; x <= xSize; x++)
            {
                //float y = Mathf.PerlinNoise(x * .3f, z * .3f) * 2f;
                float y = Noise.GenerateNoiseMap(mapWidth, mapHeight, seed, scale, octaves, persistance, lacunarity, offset);

                vertices[i] = new Vector3(x, y, z);
                i++;
            }
        }

        triangles = new int[xSize * zSize * 6];

        int vert = 0;
        int tris = 0;

        for (int z = 0; z < zSize; z++)
        {
            for (int x = 0; x < xSize; x++)
            {
                triangles[tris + 0] = vert + 0;
                triangles[tris + 1] = vert + xSize + 1;
                triangles[tris + 2] = vert + 1;
                triangles[tris + 3] = vert + 1;
                triangles[tris + 4] = vert + xSize + 1;
                triangles[tris + 5] = vert + xSize + 2;

                vert++;
                tris += 6;
            }
            vert++;
        }
    }

    void UpdateMesh()
    {
        // Clear mesh data, reset with above vars and recalculate normals
        mesh.Clear();

        mesh.vertices = vertices;
        mesh.triangles = triangles;

        mesh.RecalculateNormals();
    }

    private void OnDrawGizmos()
    {
        if (vertices == null) return;

        Gizmos.color = Color.red;

        // Draw Vertex Gizmos
        for (int i = 0; i < vertices.Length; i++)
        {
            Gizmos.DrawSphere(vertices[i], .1f);
        }
    }
}

Comment: Noisemap returns an array of floats in a map format. Just use x/y accordingly to pick out your float.
Comment: I understand the principle, but as I said, I am new to this, so would you mind writing this as an answer, possibly with modified code snippets?
Comment: im on a phone so no. Use it just like the perlin noise. Get from array [x,y] as its a float
Comment: What have you already tried? Please share your research effort.
Answer: I've figured it out, I would've had to put vertices[i] = new Vector3(x, y[x, z], z);  Now I've already tried this, but I suppose visual studio bugged and did not save it properly.  Anyways, yes, I just needed to use x/y to pick out my float.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Scaling the regex backreference

Question: I need to convert a font-size pt value to a font-size px value.  Since I have a 96dpi screen I need to scale up the pt value by 1.33 so that the px value has the same size on the screen as the pt value.  So far I have
$pattern = "/(\d+)pt/";
$replacement = "$1px";
$data = preg_replace($pattern, $replacement, $data);

But this just replaces 'pt' with 'px'. The replacement line needs to be something like  $replacement = "(1.33*$1)px";
How can I do this?
Comment: look at `preg_replace_callback`. http://php.net/manual/en/function.preg-replace-callback.php
Answer: You need to use preg_replace_callback function.
$data = "5pt";
$pattern = "~(\d+)pt~";
$data = preg_replace_callback($pattern, function($m) {
    return 1.33*$m[1]."px";
}, $data);
echo $data;

Output:
6.65px

Scaling the regex backreference


Close AVPlayer when movie is complete

Question: I am making a simple iPad app to play a movie when a button is pressed. The movie plays and when the movie is finished I want to close AVPlayerView so it goes back to the main screen.
Currently when the video finishes it stays on the last frame.
My ViewController.Swift at the moment.
import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {
//MARK : Properties

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
//MARK: Actions

@IBAction func playButton(_ sender: AnyObject) {

    let movieURL = Bundle.main.url(forResource: "ElephantSeals", withExtension: "mov")!
    let player = AVPlayer(url: movieURL as URL)

    let playerViewController = AVPlayerViewController()

    playerViewController.player = player

    self.present(playerViewController, animated: true) {
        playerViewController.player!.play()
        }
//    player.actionAtItemEnd = playerViewController.dismiss(animated: true)
}
}

As you can see, I think there might be something in actionAtItemEnd, but I'm not sure how to implement it.
Thank you.
Answer: This is working code in swift 5.3 and iOS 14.2, try this and let me know...:)
import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    let playerViewController = AVPlayerViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func playButton(_ sender: AnyObject) {

        let movieURL = Bundle.main.url(forResource: "ElephantSeals", withExtension: "mp4")!
        let player = AVPlayer(url: movieURL as URL)

        playerViewController.player = player
        NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerViewController.player?.currentItem)

        self.present(playerViewController, animated: true) {
            self.playerViewController.player!.play()
        }
    }

    @objc func playerDidFinishPlaying(note: NSNotification) {
        self.playerViewController.dismiss(animated: true)
    }
}

You can download sample project for same from here
https://github.com/deepakiosdev/AVPlayerViewControllerDemo
Comment: Thank you very much, very clear to understand. This worked for me!
Comment: When the player finishes playing, the current time is not set to zero, if the user tries to play the video again it will start at the end. In the playerDidFinishPlaying call seek(to: CMTime(seconds: 0.0, preferredTimescale: 1) on the player.currentItem. Also, the .AVPlayerItemDidPlayToEndTime Notification carries a warning "This notification may be posted on a different thread than the one on which the observer was registered." So dismissing the AVPlayerViewController should be done on the main thread.
Answer: Swift 4
let playerController = AVPlayerViewController()

private func playVideo() {
    guard let path = Bundle.main.path(forResource: "p810", ofType:"mp4") else {
        debugPrint("video.m4v not found")
        return
    }
    let player = AVPlayer(url: URL(fileURLWithPath: path))
    playerController.player = player
    NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerController.player?.currentItem)

    present(playerController, animated: true) {
        player.play()
    }
}

@objc func playerDidFinishPlaying(note: NSNotification) {
    playerController.dismiss(animated: true, completion: nil)
}

Answer: Using NSNotificationCenter you can do this .
 NotificationCenter.default.addObserver(self, selector: #selector(ViewController.playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object:  videoPlayer!.currentItem)

@objc func playerDidFinishPlaying(note: NSNotification) {
    // here you can do your dismiss controller logic
    AVPlayerViewController.dismiss(animated: true)
    print("Video Finished")
}

Comment: Xcode told me two things on the first line of this code:
'NSNotificationCenter' has been renamed to 'NotificationCenter'
Answer: here is objective c code
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(nextVideo:)  name:AVPlayerItemDidPlayToEndTimeNotification object:playerViewController.player.currentItem];

Answer: Invoke AVPlayerViewControllerDelegate.
In viewDidLoad initialize the delegate and implement this method
func playerViewControllerDidStopPictureInPicture(AVPlayerViewController) {
      AVPlayerViewController.dismiss(animated: true)
}

https://developer.apple.com/reference/avkit/avplayerviewcontrollerdelegate
Comment: This method is not called when the video finishes playing in the normally manner.
Answer: You don't need to setup notification observer.
Just use exitsFullScreenWhenPlaybackEnds property of the player controller:
let playerViewController = AVPlayerViewController()
playerViewController.exitsFullScreenWhenPlaybackEnds = true
playerViewController.player = AVPlayer(url: url)
navigationController.present(playerViewController, animated: true, completion: nil)
playerViewController.player?.play()

https://developer.apple.com/documentation/avkit/avplayerviewcontroller/2875793-exitsfullscreenwhenplaybackends

Close AVPlayer when movie is complete


VSTS Label Sources not reading Build Phase Output Variable

Question: I'm trying to tag a build using the built-in, tag sources functionality of team foundation server, the tag is created during the build phase and outputted as an output variable. However the label sources step never evaluates the variable and the step fails. Why does the label sources step not evaluate the value of the tag variable ?
Tag sources has been setup like this

The Tag step creates and outputs the tag

Both the "Tag Step Logs" and the "PRINT ENV VARS" show the value of the variable that is created.

The label sources then fails as it's not able to read the tag value from the variable
Answer: That is because the Output Variable is only available in the next session, that means it only can be read from the steps which behind the step Tag variable creates.
But as you can see, the Label source is in the fist Get sources step, it's before the step Tag variable creates.
So, the Output Variable can not be read. We can not label sources with the customized variable.
We can only use the predefined and user defined variables on the variables tab to Label sources. See Label sources for details.
Comment: @polydegmon Have you resolved the issue? any update?
Comment: I have gotten a solution to the issue. I am updating the variable Build.BuildNumber and using this in the Tag sources. This is working as this variable is available to the label sources step.

I added the following line, to update the build variable
 Write-Host ("##vso[build.updatebuildnumber]$tag")

This updated number is then accessed by the label sources step
 $(Build.BuildNumber)
Answer: A solution to the issue has been found.
I am updating the variable Build.BuildNumber and using this in the Tag sources. This is working as this variable is available to the label sources step.
I added the following line, to update the build variable
Write-Host ("##vso[build.updatebuildnumber]$tag")

This updated number is then accessed by the label sources step using the variable
$(Build.BuildNumber)

Thanks Alexey, for figuring this out.


A mathematical function for: Adding one to x if x is decimal

Question: I was wondering if there is a mathematical function for this:
If x is a decimal value, we subtract all decimal values from x and add 1.
Allow me to demonstrate:
1.00000000000001 = 2
2013.00123456789 = 2014
5.5 = 6
5.1 = 6
3.333333 = 4
7 = 7 <------ This is not a decimal value

If a math function does not exist for this, how do we mathematically do it?
Answer: It's called the ceiling function and is usually denoted by $\lceil x \rceil$.
Comment: Before you agree that the ceiling is your answer, you should tell us what you want to happen for negative numbers.
Comment: Perfect answer! Thank you. I learned something new today! Oh how much I love learning.


regex not replacing word starting with "." or ending with "+" like ".NET" or "C++"

Question: I am trying to replace '.net' in 'i like .net' with .NET. Expected output: 'i like .NET'.
Also 'c++' in 'i like c++' with Cpp. Expected output: 'i like Cpp'.
There are more cases with special characters like 'c++'
import re

regex_match = re.compile(r'\bnet\b')
print(regex_match.sub('NET', 'I like .net'))
# output I like .NET Which works but I need boundary match also.

regex_match = re.compile(r'\b.net\b')
print(regex_match.sub('NET', 'I like .net'))
# output I like .net

regex_match = re.compile(r'\b\.net\b')
print(regex_match.sub('NET', 'I like .net'))
# output I like .net

regex_match = re.compile(r'\b' + re.escape('.net') + '\b')
print(regex_match.sub('NET', 'I like .net'))
# output I like .net

regex_match = re.compile(r'\b' + re.escape('.net') + '\b')
print(regex_match.sub('NET', 'I like \.net'))
# output I like \.net

print(re.sub(r'\b' + re.escape('.net') + '\b', '.NET', 'I like .net'))
# output I like .net

regex_match = re.compile(r'\b' + re.escape('.net') + '\b')
print(regex_match.sub('NET', re.escape('I like .net')))
# output I\ like\ \.net

UPDATE:
regex_match = re.compile(r'\b' + re.escape('c++') + '\b')
print(regex_match.sub('cpp', 'I like c++'))
# output `I like c++` expected `I like cpp`

I went through a lot of stackoverflow questions on regex replace. and everywhere its suggested escape '.', which i tried as you can see above. still its not working. Any help is much appreciated.
Comment: It is a common question. `\b` before `.`  requires a word char before `.`. You have none.
Comment: You should escape the dot, otherwise it matches any character, i.e. `.net` will match `anet`, which `\.net` won't. You will want to escape characters when they have a special meaning but you just want to represent the character itself.
Answer: Don't place \b (word boundary) before dot since dot is not a word character.
You can use:
>>> regex_match = re.compile(r'\.net\b')
>>> print(regex_match.sub('.NET', 'I like .net'))
I like .NET

EDIT:
Based on your comments you can probably use this regex:
>>> print(re.sub(r'(^|\s)\.net(?=\s|$)', r'\1.NET', 'I like .net'))
I like .NET

>>> print(re.sub(r'(^|\s)\.net(?=\s|$)', r'\1.NET', 'I like.net'))
I like.net

Comment: @Zinki: Yes, that's what I have in edited answer and I believe that should work for OP.
Comment: fair point. but it doesn't solve the case for `print(regex_match.sub('.NET', 'I like my.net'))` will output `I like my.NET` Which it seems can't be solved.
Comment: @VikashSingh then what about `r'\s+\.net\b'`, which will match only when ".net" follows a whitespace.
Comment: @anubhava yes. That's the idea. Only a mention of `.net` should be replaced. @WiktorStribiżew looking..
Comment: @Zinki Then it won't match at the start of a string.
Comment: issue with `\s+` means the word has to have a space right before it. and it does not match the start of the sentence. so i can do something like `[^\s]\.net`, something of that sort.
Comment: @anubhava No, it won't work because OP already commented: *issue with `\s+` means the word has to have a space right before it*.
Comment: @Zinki See my answer.
Comment: @anubhava thanks for all the help :) My upvote for the effort and all the cases your code handles. But what Wiktor did makes more sense for my use case. :)
Answer: A \b before . requires a word char before .. A \b\. will match a . in ASP.NET, but not in In .NET.
If you want to match whole words regardless of the characters at the start/end of the search words, the best bet is to use lookarounds:
import re
regex_match = re.compile(r'(?<!\w){}(?!\w)'.format(re.escape('.net')))
print(regex_match.sub('NET', 'I like .net, not  my.net.'))
# => I like NET, not  my.net.

See the Python demo. It will still work the same if you use net instead of .net (see another Python demo).
Here, (?<!\w) will require a non-word char or start of string immediately before the search word, and (?!\w) will require a non-word char or end of string immediately after the search word.
Comment: For that matter `.net` is whole word even in `I like.net`
Comment: @anubhava fair point. but that is as expected. Think of it like when someone writes `'I like my..net'` they mean `.net` as a term. but not in `i like net` or 'i like inet` or 'my .network` or `i.net` then the context wont be `.net`. I hope it makes sense.
Comment: @anubhava fair point. your example is more semantic, Human interpretation of the sentence will reveal `I like.net` to have `.net` keyword. But something like `i.net` could be a different term and not `.net` at all. that's why the question was bothering me for a while.
Comment: seems like this can handle most cases. Thanks a lot for this. if it works out for all my cases it will be awesome. I have words with no special character also. I was looking for a solution that can work across all conditions.
Comment: @VikashSingh It will handle all the cases, be it `.net`, `net.` or `net`.
Comment: Won't it replace `'I like my..net'` into `I like my..NET` ?
Comment: @anubhava Of course it will because `.net` in `...net` is a whole word, i.e. `.net` is not preceded with a word char.


Floor Joist Cracked

Question: Crack along floor Joist in crawl space. Another similar on the same joist further down. Major issue or simple fix? Suggestions?
Comment: If it's sagging you can just use a jack with a post to carefully lift the joist back to level (make a T-bar to cross several joists and lift until they come to the same plane).  You can then sister a joist to one or both sides - drill and lag bolt with big washers and construction adhesive.  Job done.  From the pictures it doesn't look worth the effort, to be honest.
Comment: Also curious about the dirt line to the left...
Comment: I didn't mean the pipe. There's a brownish horizontal line that corresponds with the crack. I initially saw that as a shadow in a rabbet. Now I see that it's just discoloration or maybe the crack itself.
Comment: I doubt it's 2 inches thick unless your home is more than 80 years old. What am I seeing along the bottom if not a rabbet? Just a dirt line?
Comment: "It's the soup of the day." I realize the joist spans the house. How many feet and inches is that?
Comment: There is a metal strap around the cast iron pipe, is that strap fastened to that joist? Is there anything else supporting that cast iron pipe?
Comment: The cast iron pipe appears to have been strapped to the joist. It appears the strap was secured below the weakness in the joist mentioned by @isherwood. The force exerted by the pipe settling was sufficient to cause the joist to break along the already existing weak line/point. A solution would need to have the strap secured higher on the joist, preferably at multiple locations along the width of the joist, in addition to repairing the joist as J... suggested. You would need to determine if the cast iron pipe should be secured at it's original elevation, or is OK now (a flow/code issue?).
Comment: Hard to tell from the fuzzy photos. Is it rabbeted (notched on the bottom? What thickness is the board? What's the total height of the board and the joist span.
Comment: Not rabbited and it runs the width of house. Is about 2 inches thick
Comment: I think that's a knot that caused the weakness initially. But how far back does it crack? Does the cracked off section get bigger? And what is the height of the remaining wood? (I'm expecting a number somewhere in the 8-10" range.)
Comment: Ha sorry I'm sure you can tell this is not my territory. Width of house is 12 feet. Not sure about question about bottom unless pics are fuzzy. All the beams are same as this cracked one.
Comment: Dirt line to left you are referring to is copper water pipe. Does not get bigger but same similar crack about 6 feet down on same piece of wood.
Comment: Yes and could be beam right behind it. About 2-3 feet until end of Joist
Comment: It is fastened to it and it is also attached to other beams. That is what I thought caused the crack.
Comment: FYI, a "beam" is something we don't have in this scenario. Beams are typically perpendicular to joists and support them. I realize that you're using the term in a more generic sense, but it can be confusing.
Comment: It would also be a good idea to determine why the cast iron pipe sagged, as it doing so *may* indicate that there's a problem with how it's secured after it turns vertical.
Answer: tl;dr It's probably just a localized weakness and not a serious problem.
I suspect that the joist cracked due to 1) the off-color streak we see, which may be heartwood, and 2) the knot. Both are very weak points in the wood that wouldn't normally be a problem, but their unfortunate proximity combined to dramatically weaken the wood.
The outstanding question is whether there's undue stress on that particular joist, causing sag and severe tension on the bottom edge. We can't say much about that through this little hole in the internet.
Comment: Thanks for feedback! Appreciate it. I will have my handyman check it out next time as well. Just moved into older house so checking off some things I see. We had water in crawl space (same area) this week due to heavy rain. Not standing but just wanted to make sure structure is sound.
Answer: I'm always surprised how people can look at a structural failure and determine that it's "not a serious problem." I have to calculate the load to determine if it's serious.  YOU HAVE A FAILURE. Do not ignore it.
A 12' span is not extreme, but those joist seem extra large for normal construction. If they're more than 2x12 at 16" o.c., then the designer was trying to do something special.
Is there something special above those joist: like a hot tub, waterbed, etc.? Make sure you follow through and have it checked out. At a minimum I'd fix the support for the pipe. That sagging could put stress on other joints.

Floor Joist Cracked


Google App engine - need to use userService in each page

Question: On Google app engine, do I need to import & initialize the object userService to log-in the user through Gmail in each page (jsp), or is there a better way to achieve this? Using filters for example?
Answer: Use sessions, when you login store the user id and get appropriate data to sessions that you will frequently use. Then only check sessions before the userService.
Comment: If you mean `Servlet` sessions, according to another post I have to add `true` to `web.xml`.


Create dictionary conditionally based on separate dictionary

Question: I found similar questions but most are for Python 2 and earlier.
I have a column with 5000+ values and I am creating a dictionary out of it. I want to list out some rows with certain words and if the value doesn't contain it, it will be saved to 'Others'.
I have done the following:
my_groups = {
    'Group 1' : r'utilities|cleaning',
    'Group 2' : r'cooking|kitchen',
    'Group 3' : r'decorations|planning',
    'Group 4' : r'conceirge|guest|information|attendants',
    #...there are 300 groups in the dataset
}

But since the data is so large, I need to divide the groups into 2 categories: frontline and backdoor. I can do:
group_cat = {
    'Frontline' : r'conceirge|guest|information|attendants|waiter|MC',
    'Backdoor' : r'utilities|cleaning|cooking|kitchen|chef|event|decorations|planning',
    #...there are 300 groups in the dataset
}

But the list will be so long since there are around 300 groups with different descriptions. Is there a way that I can just specify the first one and assign other else automatically in the other?
#something like this
group_cat = {
    'Frontline' : r'conceirge|guest|information|attendants|waiter|MC',
    'Backdoor' : r'OTHER_KEYWORDS_HERE',
}

Answer: If I understand the question correctly, the following code should work:
Code:
my_groups = {
    'Group 1' : r'utilities|cleaning',
    'Group 2' : r'cooking|kitchen',
    'Group 3' : r'decorations|planning',
    'Group 4' : r'conceirge|guest|information|attendants',
}

group_cat = {
    'Frontline' : r'conceirge|guest|information|attendants|waiter|MC'
    }

group_cat['Backdoor'] = '|'.join(set(x
                                     for val in my_groups.values()
                                     for x in val.split('|')
                                     if x not in group_cat['Frontline'])
                                 )

Output:
>>> group_cat
{'Frontline': 'conceirge|guest|information|attendants|waiter|MC',
 'Backdoor': 'cooking|utilities|planning|cleaning|decorations|kitchen'}


Red, yellow and green area while recruiting armies

Question: When I use my pre-made army models to recruit, my provinces changing color to green, yellow or red.
It's obvious that green means you have enough ressources to buy your model and red you don't.
But what does it means precisely when my provinces are yellow ?
Comment: I'm not sure, I thought yellow means the province is either already occupied with production, which is not the case or already has the building you are trying to build, which is obviously not the case as you are trying to build troops. How much manpower do you have available? Maybe it means, there isn't enough manpower for all regiments available; but I honestly can't recall ever having seen a yellow colored province during army production.
Comment: The number of provinces used to produce the army is defined, when you create the template(model) though. Perhaps it shows yellow, because it would take an extraordinary amount of time to build such a large army in one province.
Comment: I have enough manpower available (30k). I can create a model with 2 armies and an other with 20, both will be yellow. Also, I can only use ONE province to build the model, and they will be enrolled one after one in the same province. It's really strange...
Comment: I'll try to reduce the number of provinces needed. It could be the problem.
Comment: @Galabyca Did you create a template which recruits troops only from one province?
Answer: When creating an army/navy template, if all provinces are

Green that means that the provinces are all connected and there are enough of them that it will either match or have more provinces than units being queued, and will be able to create them all at the same time.
Yellow means that there are not enough connected provinces to create them all at the same time, and some will double or triple up in unit queue.
Red obviously means that there is a building being produced, or there is another reason that it usually will tell you when you hover over the province.

All of these are applicable to both army, navy, and mercenary recruitment. If you have more questions like these the EU4 wiki usually has all the answers and there are several tutorials on YouTube or other platforms that teach people these tips.


Ubuntu 14.04 32bit OS with 4g physical ram and pae still shows 3.2g ram

Question: I upgraded 2gb memory to 4gb on Lifebook 6025. I followed instructions for pae to recognize the 4gb by doing

sudo apt-get install linux-headers-server linux-image-server linux-server
edit grub by adding forcepae -- forcepae
reboot

But still it shows the same as before with 3.2gb as below.

jmin@jmin-LifeBook-A6025:~$ free -h
             total       used       free     shared    buffers     cached
Mem:          3.2G       966M       2.3G        60M        51M       530M
-/+ buffers/cache:       384M       2.8G
Swap:         3.9G         0B       3.9G
jmin@jmin-LifeBook-A6025:~$ dmesg | grep -i pae
[    0.000000] Kernel command line: BOOT_IMAGE=/boot/vmlinuz-3.13.0-74-generic root=UUID=2fca00b1-5199-4d2d-bb5f-9728c10d7a05 ro quiet splash forcepae -- forcepae vt.handoff=7
[    0.004596] PAE forced!
[    0.008000] PAE forced!

What am I doing wrong?  How can I make it use all 4GB memory?  Thank you.
Comment: @Pilot6 is correct. Free shows the usable RAM. Video RAM and generally "locked" kernel memory is not accounted. I have 16G and free says `total 14G`. You system is ok and using all the RAM.
Comment: The rest is used by the video adapter.
Comment: Thank you. But shouldn't the total say 4.0G instead of 3.2G?
Comment: Thank you for the comment. Please see my comments below.  BTW, before I added the 2g memory, it had 2g memory and I think the free -h showed the total 2g, not like 1.4g for the totals.  Why is it that way?  Thank you.
Answer: Part of the memory is allocated to the on-board Video card. You may be able to adjust the amount of memory the card can use, in the system BIOS, but you will never see the full 4GB, as the video card must be allocated some amount. You could theoretically disable on-board video if your BIOS allows it, but then your system would have no video, as it's a laptop.
You do not need to force PAE to on. Ubuntu now only supports PAE for 32-bit Intel systems. So forcepae doesn't actually do anything, but give you some extra messages in the log about it being forced.
Installing the linux-image-server packages was also not necessary. You only seeing 3.2GB vs 4GB, is unrelated.
On my system, with Intel video, I have 32GB of RAM installed, which is  33554432 kilobytes, while free shows I have 31860640 kB total, which is 30.39 GB. Some of that difference is the allocated video memory, and some of that difference is the kernel memory.
Comment: Thank you for your comment. Actually even before installing pae as I did, the free -h shows 3.2g. And I thought due to the lack of the pae, it shows 3.2 not 4.0g. So, I installed for pae as shown above, but then still the same.  Did I need to install pae at all on Ubuntu 14.04 version, or is the pae already included? BTW, I have fedora21 desktop with 8g ram, and free -m shows 7981, which is close to 8gb ram. Does it mean that ubuntu and fedora shows different totals for the memory size?  Or is that because fedora21 video has its own memory, not using the system memory?  Thank you very much.
Comment: I just looked at my fedora21 video memory by doing 'lspci -v -s 01:00.0 ' and it shows 256M prefetchable.  Is that why the 'free -h' on the fedora21 shows near 8g ram because the video card does not use system memory?  Is that because the laptop video card does not have its own memory and borrows from the system memory unlike the fedora21 desktop?  Thank you very much.
Comment: PAE is on by default. If your hardware doesn't support PAE, Ubuntu 14.04 won't even boot.
Comment: Right, if you have a discrete video card on your workstation PC, like an NVidia card, it has memory on the card, and it is not shared with the system RAM. The laptop graphics are part of the CPU, and it shares memory with the system RAM, which means available system RAM appears as less that what you have installed.
Comment: dobey, thank you very much.  One last question.  I think I saw 2g for the total when I did 'free -h' on the a6025 laptop before I installed 2 modules of  2g memory to make the total of 4g memory. Shouldn't it have shown something like 1.4g instead of 2g?  How can that be explained?  Or did I see that incorrectly, I mean it was not 2g that I saw?  Thank  you.
Comment: @user1026669 You will have to swap back to the old memory, boot, and then run free -h to see what it says. I don't know what it says, and you are probably misremembering.
Answer: To address more than 3GB of RAM using PAE on Intel-based systems, you must have support from the chipset. The Intel 945 and older chipsets for example don't support this.
Answer: Unfortunately, a 32 bit operating system can only address 4GB of memory. Your swap space and graphic memory space will be included in this address block, so you might only be able to see 3.2GB memory; if this is insufficient, I'd recommend using the x64 version of 14.04. I've had no problems with compatibility.
Comment: Thank you for your comment. For now the a6025 cpu is , I think, for 32bit. So, 64bit OS is out of the question. So, there is no way to get all 4g?
Comment: This is not quite true. 32-bit non-PAE can only address up to 4GB of memory. However, Ubuntu 14.04 only supports PAE-enabled 32-bit systems, so any 32-bit system running 14.04 can address more than 4GB. However, if you only have 4GB, you obviously can't address more than 4GB, no matter what architecture you're on. :)
Comment: dobey, thank you for your comment.  If 14.04 has only pae-enabled 32bit OS version, I did not have to install pae by doing "sudo apt-get install linux-headers-server linux-image-server linux-server".  Is this true?  Thank you.
Comment: @user1026669 Yes, as described in my answer, that was unnecessary.
Comment: dobey, thank you very much.  Can I undo what I did then? Is there any damage to be done to the laptop?  Thank you.


Default text in Angular select

Question: By default angular uses an empty value if nothing has been selected in a <select>. How can I change this to a text that says Please select one?
Answer: You didnt provide any code so I can't give an example relative to your code, but try adding an option element, e.g.
<select ng-model="item" ng-options="item.category for item in items"
        ng-change="doSomething()">
    <option value="">Please select one</option>
</select>

Comment: To add:  Having value="" is important.  It won't work if you just omit the value attribute.
Answer: Via the ng-selected attribute:
<select>
  <option>Hello!</option>
  <option ng-selected="selected">Please select one</option>
  <option>Another option</option>
</select>

Check out the reference: https://docs.angularjs.org/api/ng/directive/ngSelected

Default text in Angular select


How to Implement OnClickListener to inner child dynamically created RecyclerView?

Question: I have a root recyclerview of items in a fragment. Onclick of each items in the recyclerview, it generates a dynamic recyclerview list using the same Adapter as the root recyclerview. I want to implement the OnClick  listener to the child recyclerview and generate the next level of items with the second level recyclerview. I have looked for many answers but what I find is the click listener implemented for root items. I have implemented my listener in viewholder in my adapter.
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder>{
private Context context;
private List<ItemgroupDb> itemgroupDbs;
private ItemgroupDb PItemID;
private RecyclerViewClickListener itemListener;

public ItemAdapter(Context context, List<ItemgroupDb> itemgroupDbs, RecyclerViewClickListener itemListener) {
    this.context = context;
    this.itemgroupDbs = itemgroupDbs;
    this.itemListener = itemListener;
}

public ItemAdapter(Context context, List<ItemgroupDb> itemgroupDbs) {
    this.context = context;
    this.itemgroupDbs = itemgroupDbs;
}

public ItemAdapter(Context context, List<ItemgroupDb> itemgroupDbs, ItemgroupDb PItemID, RecyclerViewClickListener itemListener) {
    this.context = context;
    this.itemgroupDbs = itemgroupDbs;
    this.PItemID = PItemID;
    this.itemListener = itemListener;
}

@Override
public int getItemViewType(int position) {
    return super.getItemViewType(position);
}

@Override
public int getItemCount() {
    return itemgroupDbs.size();
}

@Override
public void onBindViewHolder(ItemAdapter.ItemViewHolder itemViewHolder, int i) {
    ItemgroupDb itemgroupDb = itemgroupDbs.get(i);
    itemViewHolder.vName.setText(itemgroupDb.getItemName());
    Log.e("Itemname", String.valueOf(itemgroupDb.getItemName()));
}

@Override
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View itemView = LayoutInflater.
            from(viewGroup.getContext()).
            inflate(R.layout.child3_row, viewGroup, false);
    return new ItemViewHolder(itemView);
}

public class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    protected TextView vName;
    protected ImageView vImage;

    public ItemViewHolder(View v) {
        super(v);
        vName = (TextView) v.findViewById(R.id.childname);
        vImage=(ImageView)v.findViewById(R.id.iv_item_image);
        v.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        itemListener.recyclerViewListClicked(v, 1, this.getLayoutPosition(), itemgroupDbs.get(this.getLayoutPosition()).getLevel());
        notifyDataSetChanged();
    }
}

Interface for clicklistener
public interface RecyclerViewClickListener {
public void recyclerViewListClicked(View v, int id, int level, int position);

}
Comment: Post your code here too
Comment: @AdnanAmjad here is my code.
Answer: You can try this
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder>{

    public static class ViewHolder extends RecyclerView.ViewHolder {

        //your other views
        private View parentView;

        public ViewHolder(View v) {
            super(v);
            parentView = v;
        }

        public View getParentView(){
            return parentView;
        }
    }

    @Override
    public void onBindViewHolder(final ViewHolder vh, final int position) {
        View.OnClickListener anOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aMethodThatAddNewRecyclerViewDynamicallyToThisRecyclerView();
            }
        };
        vh.getParentView().setOnClickListener(anOnClickListener);
    }
}

Comment: Thankyou, but when I use this method, the click responds to only the first item of the recyclerview and not other recyclerviews. Is there other ways


bash empty variable command substitution leads to a single quote

Question: The following is a script where the empty variable is replaced by single quotes. If the variable is not empty then we have the correct substitution.
$ set -x;  aa=""; bb=`curl "$aa" -vvv`; set +x
+ aa=
++ curl '' -vvv

The thing to notice is the single quotes in place of the empty variable.
When variable is not empty, everything works fine as in:
$ set -x;  aa="google.com"; bb=`curl "$aa" -vvv`; set +x
+ aa=google.com
++ curl google.com -vvv

Q1: Why is an empty variable or a variable with space resulting in single quotes being introduced?
Q2: How do I prevent the single quotes in lieu of the empty variable?
Now, I can remove the double quotes and everything works fine but I need to preserve spaces if there are any.
Thanks.
Answer: Single quotes are not being introduced, they are just being used to show you that you are passing an empty argument.  The double quotes you use are causing the empty argument to be passed.  If you want no argument but want to allow whitespace in the variable, you'll have to do something like:
curl ${aa:+"$aa"} -vvv

This is different than curl ${aa+"$aa"} -vvv when aa is the empty string, but from your description it appears you want the former.
Comment: If you pass the empty string as an argument, then that is the argument that is passed.  Why should curl ignore it?  It's neither a shell issue nor a curl issue; it's a usage error.  You are passing curl an empty argument, and curl (IMO correctly) doesn't treat that argument in a special manner, but tries to use the empty string as a url.
Comment: Thanks. Why would curl interpret an empty argument or space with an actual argument? Should it not ignore it? Is this a curl issue or shell issue?
Answer: You are seeing the single quotes because you used double quotes around $aa, so curl sees the empty string as your parameter.  You won't get this effect if you drop the double quotes like this:
 set -x;  aa=""; bb=`curl $aa -vvv`; set +x

Comment: Note that leaving the double-quotes off also means the variable's value will be subject to word splitting and wildcard expansion, which can cause unexpected behavior.
Answer: This is because you enclosed variable substitution into double quotes. $aa expands to empty string, which is placed into quotes, therefore producing quotes with nothing. In this case curl will see 3 arguments in that order: curl, <empty string>, -vvv.
If you remove double quotes round $aa, the second argument will not be passed to curl, and it will see only curl and -vvv in argv parameter in it's main function:
$ set -x;  aa=""; bb=`curl $aa -vvv`; set +x
+ aa=
++ curl -vvv


JavaParser - Get typed AST

Question: I want to get typed AST from JavaParser or another parser of Java code. It means I would be able to get the type for a specific variable or parameters+returning type of a method. I googled a lot about this feature of JavaParser, but didn't find anything, I assume this is because JavaParser makes untyped AST. So, advise me how I can get this. But please don't say to parse all the code and make my own set of types, I tried and this is very hard, I think this is harder than making my own AST parser.
Comment: I have no idea what you are trying to achieve (and this might be interesting to precise that in your question) but you may want to have a look at sonar-java-plugin of sonarqube : https://github.com/SonarSource/sonar-java as we parse and construct a Syntax Tree.
Comment: OP was very clear that a "pure syntax tree" was not what he wanted.
Comment: "Making your own AST parser" and adding what it necessary to compute types for language like Java is much bigger exercise than you might guess; my company has done this for our own tools.  Building the AST is by far the easier part.    I suggest you find something that already does this and use it.    The Java compiler has some kind of internal API for accessing parsed programs; I would assume it has type information somewhere, too.
Answer: I am a JavaParser contributor and I just did that in Clojure, on top of JavaParser. I explain how implement that in one post How to build a symbol solver for Java, in Clojure
JavaParser, or any other parser just build an Abstract Syntax Tree (AST) of the code, then you have to resolve symbols to understand which references are associated to which declarations.
Suppose you have in your code something like:
<code>a = 1;
</code>
Now, to understand the type of a you should find where it is declared. It could be a reference to a parameter, to a local variable, to field declared in a current class or to a field inherited. If it is a field inherited you should find the code (or the bytecode) of the parent class and look there for the declaration of a. A parser does not do that, a parse just take a string (or a file) and build an AST.
Build a symbol resolver is not rocket science but it requires a bit of work. The solution I described in the post linked above is available on GitHub and I would be glad to help you use it if you want (even if it is written in Clojure you can call it from Java quite easily)
Comment: Ira, I am not talking about realizing a fully feature-complete solution nearly as powerful as yours. I am talking about solving the 95% simple cases in which you basically need to consider local variables, parameters, fields and inheritance.
Comment: For software, most people don't want an answer that is 95% correct, especially if that last 5% is a vast amount of work (import lookup, generics, type erasure, anonymous classes,  class files,  ...)   That was not clear from your answer.   Yes, one needs something like what you have done as a starting place.
Comment: Yes, I want looking each inner block to find variable declaration, but it's a public static variable of another class, it doesn't work. So, I find the solution with JDT, it resolves variable types by itself

JavaParser - Get typed AST


Is it safe to use a 50W light in a 35W hood range?

Question: One of the halogen lights on my hood fan just stopped working. The existing fan, and the enclosure, mention that it should be a GU10 120V 35W light. I replaced it with a GU10 120V 50W light.
Is this safe?
Comment: Here's [a similar question](http://diy.stackexchange.com/questions/4849/is-it-generally-safe-to-use-a-lower-wattage-bulb-in-a-light-fixture-specifical) that asks about using a lower-wattage bulb. [Here's](http://www.walmart.ca/en/ip/ge-35w-gu10-indoor-flood-1pk/6000016953225) what the bulb looks like.
Comment: Why not just use the right lamp?
Answer: Probably, but you don't want to.
As comments mention, there are several factors which play into the maximum wattage. You don't know which factor(s) was/were the driving factor(s) in that rating so you have no guarantee.
The consequences of ignoring it could be as benign as a fuse breaking, or as bad as the insulation cooking and releasing toxic chemicals which cause health effects, or just getting it done with and burning down your house.
Buying the right bulb is probably a lot cheaper.


How to send picture on mail automatically in android

Question: I am developing an app in which I want to click Image and automatically after capturing image, the app should send the picture to mail.
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imgSaved));
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image"));

Comment: show us the code which you tried??
Comment: Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imgSaved));
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image"));
Answer: You need to create an intent which will be fired on selection of the image
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("application/image");
intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{strEmail});
intent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Any subject you want to give");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "text you want");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///mnt/sdcard/imageYouSelected.jpeg"));
startActivity(Intent.createChooser(emailIntent, "sending youer email"));

OR
You can use the JAVA API approach like here
Comment: Using your code, will attach the picture on Gmail, but I want that the picture should be send automatically to the given Gmail.
Comment: [What  about JAVA api approach?](http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-built-in-a)
Answer: try like this may help you,
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_EMAIL,
                new String[] { "email@example.com" });
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "text of email");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imgSaved));
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image"));

Comment: thanks for the answer, but I want that that Image should be send on Mail automatically without any user Interaction.


LoRaWAN DevEUI, AppEUI and AppKey

Question: I'm trying to understand the three magic LoRaWAN IDs from the LoRaWAN 1.2 specification. My understanding is:

DevEUI is like a MAC address
AppKey is like a public key (roughly...)
AppEUI is like a port number

Now I'm having problem understanding who is responsible for creating these IDs:

DevEUI can be generated from the LoRa chip internal ID registers (I'm using Murata's type ABZ chip)
AppKey: should it be unique for each end node? Should I choose a random one or ask one from the LoRaWAN provider (e.g. Objenious)?
AppEUI: should be common to each end node (I guess it should)? Should I choose a random one or ask one from the LoRaWAN provider?
Answer: The DevEUI is an ID in the IEEE EUI64 address space used to identify a device. It is supplied by the device manufacturer. A deprecated algorithm exists to convert 48bit MAC addresses to EUI64. For MAC addresses with 6 bytes (e.g. 01 02 03 04 05 06) put ff fe in the middle (e.g. 01 02 03 ff fe 04 05 06). This algorithm has been deprecated as it may lead to collisions with other DevEUIs. During over the air activation a DevAddr is assigned to the device. This DevAddr is used in the LoRaWAN protocol afterwards. The DevEUI is sent unencrypted.
The JoinEUI (formerly called AppEUI) is a global application ID in  the IEEE EUI64 address space identifying the join server during the over the air activation. For non-private networks it corresponds to a subdomain of joineuis.lora-alliance.org. This server name is used to find the IP address of the join server via DNS. This is described in LoRaWAN™ Back-End Interfaces v1.0.
AppKey is the encryption key used for messages during every over the air activation. After the activation the AppSKey is used. A listener knowing the AppKey can derive the AppSKey. So you want to keep the AppKey secret. Which side of the communication channel creates it is not important. You simply want to be sure that it is random.
Comment: As the JoinEUI identifies the join server it can only be provided by the owner of the join server.
Comment: As the DevEui is not relevant for encryption and the one supplied by the manufacturer is globally unique I would stay with that one.
Comment: Thanks. Who is generating the JoinEUI/AppEUI? Is it me or the LoRaWAN network provider? I heard I should ask for a kind of OUI range to IEEE for that...
Comment: Ok, that's clear. So I should register to IEEE for the DevEUI or use the ID from the LoRa chip manufacturer?
Comment: thanks for confirming that. As I now have enough rep to upvote, +1 from me :)
Answer: The DevEUI is a global end device ID in IEEE EUI64 address space that uniquely identifies the end device.

The user can derive their own DevEUI

The AppKey is an AES128 root key specific to the end device. Whenever an end device joins a network via over the air activation(OAT), the AppKey is used to derive the session keys NwkSKey and AppSKey specific for that end device to encrypt and verify network communication and application data.

The AppKey should be unique for each device.The user can derive their own AppKey

The AppEUI is a global application ID in IEEE EUI64 address space that uniquely identifies the entity able to process the JoinReq frame.
The AppEUI is stored in the end-device before the activation procedure is executed

The AppEUI can be different for each device or it can also be same for all device. It also depends on what kind of application server you are using.
  For example in loraserver.io you can have unique AppKey,AppEUI and DevEUI but in TheThingsNetwork you can register many devices for one application or AppEUI. But note that AppKey and DevEUI should always be unique for each end node.
Comment: I understand that the join server provides the AppEUI and that the end node device includes this in the join request. But if I buy a off the shelf LoRa device, how do I get the AppEUI into that device?
Answer: You get the AppEUI into your LoRa device by including it in the sketch you upload into the device (eg murata or arduino with lora etc.)
Comment: Sure, but who tells you *what* to use as an AppEUI?
Comment: The entity managing the join server has to setup the AppEUI in that server and provide it to you.

LoRaWAN DevEUI, AppEUI and AppKey


How to read NetCDF "global attribute" in C++

Question: This is my first question:
I am trying to read "global attributes" from a NetCDF file (using the C++ legacy API). By "global attribute" I mean an attribute that was added to a NcFile, not to a NcVar.
For most things the "Example netCDF programs" are useful -- but there is no example for "global attributes".
Consulting the "netcdfcpp.h" I find a few things:

NcFile has a member function: NcAtt* get_att(NcToken) const;
NcAtt has NO public constructor
NcAtt is friends with NcFile: friend class NcFile;
NcAtt has a private constructor: NcAtt( NcFile*, NcToken);
NcAtt has a public member function NcValues* values( void ) const;
NcValues has an API defined through the ncvalues.h header

My coding skills are insufficient to understand how I get back at the string/int/float stored as NcValue, in an NcAtt class within NcFile.
Attached is a example code of my problem "NetCDF_test.cpp", with the critical part missing from the implementation of the "LoadNetCDF" function.
The code compiles OK with: (edit: also, "TestFile.nc" is created correctly)
g++ -c NetCDF_test.cpp -o NetCDF_test.o
g++ -o NCTEST NetCDF_test.o -lnetcdf_c++ -lnetcdf
Example code:
#include <iostream> // provides screen output (i.e. std::cout<<)
#include <netcdfcpp.h>

struct MyStructure {
    std::string MyString;
    int MyInt;
    float MyFloat;

    MyStructure();      // default constructor
    int SaveNetCDF(std::string);  // Save the struct content to "global attributes" in NetCDF
    int LoadNetCDF(std::string);  // Load the struct content from "global attributes" in NetCDF

};

MyStructure::MyStructure(void)
{
    MyString = "TestString";
    MyInt = 123;
    MyFloat = 1.23;
}

int MyStructure::SaveNetCDF(std::string OUTPUT_FILENAME)
{
    NcError err(NcError::silent_nonfatal);
    static const int NC_ERR = 2;
    NcFile NetCDF_File(OUTPUT_FILENAME.c_str(), NcFile::Replace);
    if(!NetCDF_File.is_valid()) {return NC_ERR;}

    if(!(NetCDF_File.add_att("MyString",MyString.c_str()))) {return NC_ERR;}
    if(!(NetCDF_File.add_att("MyInt",MyInt))) {return NC_ERR;}
    if(!(NetCDF_File.add_att("MyFloat",MyFloat))) {return NC_ERR;}

    return 0;
}

int MyStructure::LoadNetCDF(std::string INPUT_FILENAME)
{

    NcError err(NcError::silent_nonfatal);
    static const int NC_ERR = 2;

    NcFile NetCDF_File(INPUT_FILENAME.c_str(), NcFile::ReadOnly);
    if(!NetCDF_File.is_valid()) {return NC_ERR;}

    // ???? This is where I am stuck.
    // How do I read the global attribute from the NetCDF_File ??
    return 0;
}

int main()
{
    std::cout<< "START OF TEST.\n";

    MyStructure StructureInstance;  // datamembers initialized by constructor
    StructureInstance.SaveNetCDF("TestFile.nc");

    StructureInstance.MyString = "Change string for sake of testing";
    StructureInstance.MyInt = -987;
    StructureInstance.MyFloat = -9.87;

    StructureInstance.LoadNetCDF("TestFile.nc");    // data members are supposed to be read from file

    std::cout<< "Now the data members of StructureInstance should be TestString, 123, and 1.23\n";
    std::cout<< StructureInstance.MyString << " ; " << StructureInstance.MyInt << " ; " << StructureInstance.MyFloat <<"\n";
    std::cout<< "END OF TEST.\n";
}

Answer: It's pretty clearly spelled out in the C++ users guide: http://www.unidata.ucar.edu/software/netcdf/docs/netcdf-cxx/Class-NcAtt.html#Class-NcAtt
"Because attributes are only associated with open netCDF files, there are no public constructors for this class. Use member functions of NcFile and NcVar to get netCDF attributes or add new attributes."
global attributes are attributes on the file (as opposed to variable attributes which are, well, attributes on the variable)
NetCDF_File.num_atts() returns how many global attributes.  The get_att() methods (overloaded in various ways) will get you an attribute.
consult http://www.unidata.ucar.edu/software/netcdf/docs/netcdf-cxx/Class-NcFile.html#Class-NcFile
Answer: Many thanks to Rob Latham for the links to a commented description of the NetCDF API (legacy C++). With the information given there I was able to figure it out:
NcAtt inherents form NcTypedComponent a set of member functions for accessing data stored within a given NcAtt: (int n == n-th element)

ncbyte as_ncbyte( int n ) const
char as_char( int n ) const
short as_short( int n ) const
int as_int( int n ) const
nclong as_nclong( int n ) const // deprecated
long as_long( int n ) const
float as_float( int n ) const
double as_double( int n ) const
char* as_string( int n ) const

But still, the constructor for NcAtt is private and the only access point to an existing NcAtt is through the NcFile member function NcVar* get_var(NcToken name) const -- which only returns a pointer. Hence the straight forward usage does not work:
int MyInt = MyNcFile.get_att("MyInt").as_int(0); // DOES NOT COMPILE
However, dereferencing the pointer returned by get_att does the trick.
int MyInt = (*MyNcFile.get_att("MyInt")).as_int(0); // WORKS
For sake of completeness I include below the implementation of MyStructure::LoadNetCDF for the example code of my original question.
int MyStructure::LoadNetCDF(std::string INPUT_FILENAME)
{
    NcError err(NcError::silent_nonfatal);
    static const int NC_ERR = 2;

    NcFile NetCDF_File(INPUT_FILENAME.c_str(), NcFile::ReadOnly);
    if(!NetCDF_File.is_valid()) {return NC_ERR;}

    // NcAtt constructor is private, but one can obtain the pointer to an existing NcAtt
    NcAtt* PointerToMyIntNcAtt = NetCDF_File.get_att("MyInt");
    // Now, using the dereferencing operator one has access to the member functions that NcAtt inherents from NcTypedComponent
    if(!(*PointerToMyIntNcAtt).is_valid()) {return NC_ERR;}
    std::cout<< "Is MyInt a valid NcAtt? "<< (*PointerToMyIntNcAtt).is_valid()<<"\n";

    // The concise way of writing the access to NetCDF "global attributes"" of type int/float/string
    MyInt = (*NetCDF_File.get_att("MyInt")).as_int(0);
    MyFloat = (*NetCDF_File.get_att("MyFloat")).as_float(0);
    MyString = (*NetCDF_File.get_att("MyString")).as_string(0);

    return 0;
}

Comment: Shouldn't you be able to replace `(*NetCDF_File).as_int(0)` with `NetCDF_File->as_int(0)` ?
Comment: This is how to read attributes associated with NcVar I believe -- but it does not work with "global attributes" as the operator is apparently not implemented. When I compile using the "->" operator get the following error: `error: base operand of '->' has non-pointer type 'NcFile'`
Comment: Ooops, that should be: `NetCDF_File.get_att("MyInt")->as_int(0)`...or does that fail?
Comment: Yes, I confirm that this method works as well. So here we have it: two methods work. (1) an "INDIRECTION" using the dereferencing operator (*a.b(); "object pointed to by a has member b"); and (2) "STRUCTURE DEREFERENCE" (a->b(); "member b of object pointed to by a"). I think I just learned a nugget of C/C++. Cool.


Striation in my shadows

Question: I'm casting shadows across a screenspace texture based on the values in another texture.
My "depth" texture, it's not really depth, just colour values that are sampled for heights, looks like this:

We can say that the red channel is my heightmap.
I draw this alongside a grass texture on a fullscreen quad with the following frag shader:
#version 400

layout(location=0) out vec4 frag_colour;

in vec2 texelCoords;

uniform sampler2D uTexture;
uniform sampler2D uTextureHeightmap;
uniform float uSunDistance = -10000000.0;
uniform float uSunInclination;
uniform float uSunAzimuth;
uniform float uQuality;

void main()
{
    vec4 c = texture(uTexture,texelCoords);

    vec2 textureD = textureSize(uTexture,0);
    float d = max(textureD.x,textureD.y);
    float aspectCorrection = textureD.x / textureD.y;

    vec3 sunPosition = vec3(textureD.x/2,textureD.y/2,0) + vec3(    uSunDistance*sin(uSunInclination)*cos(uSunAzimuth),
                                                                    uSunDistance*sin(uSunInclination)*sin(uSunAzimuth),
                                                                    uSunDistance*cos(uSunInclination)   );

    vec4 heights = texture(uTextureHeightmap, texelCoords);
    float height = max(max(heights.r,heights.g),heights.b);
    vec3 direction = normalize(vec3(texelCoords,height) - sunPosition);
    direction.y *= aspectCorrection;

    float sampleDistance = 0;

    float samples = d*uQuality;

    float stepSize = 1.0 / ((samples/d) * d);

    for(int i = 0; i < samples; i++)
    {
        sampleDistance += stepSize;

        vec3 newPoint = vec3(texelCoords,height) + direction * sampleDistance;
        if(newPoint.z > 1.0)
            break;

        vec4 h = texture(uTextureHeightmap,newPoint.xy);
        float base = h.r;
        float middle = h.g;
        float top = h.b;

        if(newPoint.z < base)
        {
            c *= 0.5;
            break;
        }
        if(newPoint.z >= middle && newPoint.z <= top)
        {
            c *= 0.5;
            break;
        }
    }

    frag_colour = c;
}

A sample of the output is:

The striation is not wanted. I can use this same method with sharper "edges" instead of smooth contours, and everything looks great. It's the gradients like this that cause problems.
Comment: Can you explain what you want to achieve and how your shader works? Figuring this out without any hint is quite hard.
Comment: @NicoSchertler the shader is stepping along the direction to the sun; determining whether the next pixel in this step is above or below the original pixel. If it's above, it says that the original pixel must therefore be in shadow and sets it's color slightly darker.

The desired effect is shadows
Comment: Aren't you stepping away from the sun (`direction` points from sun to texel position)? Shouldn't the step size depend on `direction.z` (you want `samples` steps to result in the maximum height)? Are your texture coordinates the x/y components of the world position? And do the map heights directly represent world heights (without any scaling)?
Comment: @NicoSchertler i may be stepping away from the sun, but i can reverse that easily. I'm unsure why the step size would depend on the Z direction? (The samples is just how many steps I'm taking which I'm calculating as a factor of my overall quality.) Texture coords are the texel coords, I'm drawing a fullscreem quad. The heightmap is the world height, there's no scaling, it is actually a `GL_RGB32F` format texture so the values could exceed 1.0
Comment: If heights can exceed 1.0, why do you have `if(newPoint.z > 1.0) break;`? What happens if you leave that away? Also, shouldn't you check if you move out of the texture?
Comment: Thanks @NicoSchertler, but none of these things affect the striation.
Comment: Then I'm out of ideas, sorry. Maybe you could try a shader debugger (e.g. NSight if you have an nVidia GPU) to see what the fragment shader does. Or output the texture coordinate where it recognizes the hit as a color. It might be a floating point problem where the sun ray hits the height field almost tangentially and some pixels recognize the hit and some don't.
Comment: Thanks for your help anyway @NicoSchertler. I suspect you're right and it's a accuracy thing
Answer: To improve the quality of the algorithm, of course the number of samples can be increased. Buy a quality improvement can also be achieved, by a limitation of the stride distance.
The minimum meaningful distance of a step is determined by the resolution of the height map, because it makes no sense to test the same height of the height map twice.
float d = max(textureD.x,textureD.y);
float minStepSize = 1.0 / d;

The maximum meaningful distance is reached, if the distance, of the beam from the position on the ground to the sun position, reaches a height of 1.0.

The distance of one step is given, by dividing the maximum distance by the number of samples, but it should be at least the minimum distance given by the resolution of the height map:
float minStepSize = 1.0 / d;
float maxDist     = (1.0 - height) * length(direction.xy) / abs(direction.z);
float stepSize    = max( minStepSize, maxDist / samples );
float shadow      = 1.0;
vec3  startPoint  = vec3( texelCoords, height );
for ( float sampleDist = stepSize; sampleDist <= maxDist; sampleDist += stepSize )
{
    vec3 samplePoint   = startPoint + direction * sampleDist;
    vec4 sampleHeight  = texture( uTextureHeightmap, samplePoint.xy );
    if ( samplePoint.z < sampleHeight.r )
    {
        shadow *= 0.5;
        break;
    }
}
frag_colour = vec4( c.rgb * shadow, c.a );

For a soft shadow algorithm it has to be distinguished between full shadow and a shadow transition. For this the distance of the light beam, to to the height map has to be investigated.
If there is a large distance, then the fragment is in full shadow:

But in the case of a tiny distance, there is a shadow transition:

The indication of the strength of the shadow is the maximum distance, between the light beam and the height of the height map. This distance can be calculated by the maximum height difference of a sample point to the height map. A smooth shadow transition can be calculated by the GLSL function smoothstep.
vec3  startPoint  = vec3( texelCoords, height );
float maxHeight   = 0.0;
for ( float sampleDist = stepSize; sampleDist <= maxDist; sampleDist += stepSize )
{
    vec3 samplePoint   = startPoint + direction * sampleDist;
    vec4 sampleHeight  = texture( uTextureHeightmap, samplePoint.xy );
    maxHeight          = max(maxHeight, sampleHeight.r - samplePoint.z);
}
const float minShadow        = 0.5;
const float transitionHeight = 0.05;
shadow    = smoothstep(1.0, minShadow, clamp(maxHeight / transitionHeight, 0.0, 1.0 ));
fragColor = vec4( height, height * shadow, height, 1.0 );

In the code above, the variable maxHeight contains the maximum distance, between the light beam and the height of the height map. If it is greater than 0.0 and less than transitionHeight, there is a shadow transition. If it is greater than transitionHeight, there is a full shadow. The strength of full shadow is set by minShadow.
Comment: Thanks for all the info @Rabbid76, but it doesn't actually solve the striation problem

Striation in my shadows


Created a child page and got a 500

Question: As the title states, I created a 'child' page and BAM: 500. Following is what I believe is the actual traceback, and a bit of information on the 500 page that I believe is germane to the topic.
Is there anything I can do? I attempted to manually remove the page afterwards to no prevail. (Don't worry, I modified a copy of the database).
AssertionError at /admin/cms/page/
Negative indexing is not supported.
Request Method: GET
Request URL:    http://192.168.56.101:8080/admin/cms/page/
Django Version: 1.3.1
Exception Type: AssertionError
Exception Value:
Negative indexing is not supported.
Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/query.py in __getitem__, line 157
Python Executable:  /usr/bin/python
Python Version: 2.7.3

Environment:

Request Method: GET
Request URL: http://192.168.56.101:8080/admin/cms/page/

Django Version: 1.3.1
Python Version: 2.7.3
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.admin',
 'django.contrib.staticfiles',
 'cms',
 'menus',
 'mptt',
 'south',
 'cms.plugins.text',
 'cms.plugins.picture',
 'cms.plugins.link',
 'cms.plugins.file',
 'cms.plugins.snippet',
 'cms.plugins.googlemap',
 'sekizai',
 'registration',
 'cms_themes']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'cms.middleware.page.CurrentPageMiddleware',
 'cms.middleware.user.CurrentUserMiddleware',
 'cms.middleware.toolbar.ToolbarMiddleware')

Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper
  307.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
  93.                     response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  79.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
  197.             return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/cms/admin/pageadmin.py" in changelist_view
  657.         cl.set_items(request)
File "/usr/local/lib/python2.7/dist-packages/cms/admin/change_list.py" in set_items
  198.                     children[-1].last = False
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __getitem__
  157.                 "Negative indexing is not supported."

Exception Type: AssertionError at /admin/cms/page/
    Exception Value: Negative indexing is not supported.

Answer: Make sure your version of django-mptt is 0.5.1.
Comment: I ran 'sudo pip install django-mptt --upgrade' on my ubuntu machine and got 'Requirement already up to date: django mptt in *', Should I try to manually reinstall this? Or is it dangerous to do so?

Created a child page and got a 500