Q: DockerHub set tag alias in automated build I'm using Docker Hub's automated build system to build a docker image. That image comes in two flavors (Debian jessie and wheezy based). I like to have speaking tags for both of those (:jessie and :wheezy) but would also like to have a :latest tag pointing to the :jessie flavor.
For now I simply duplicated the jessie line in the automated build config:

But this seems to actually build the image twice. What I would need is a way to specify a tag alias, but I am not sure if that's possible. And if so how to do it.

A: It's currently not possible to have more than one docker tag name by build. Duplicating the build is the only solution.

A: You can use the tags regexp
Look at the last tag that gets created.


Q: Date string not recognized in Safari My JavaScript code is working on on Chrome, IE, and Firefox, but when it gets to safari it doesn't work. I believe I have narrowed down the problem: When creating a 'new Date' in JavaScript, all other browsers recognize my string except safari.
HTML:
<form>
<input id="timeIn" value="1:00 AM"/>
<input id="dateIn" value="1/20/2012"/>
<input id="timeOut" value="2:00 AM"/>
<input id="dateOut" value="1/21/2012"/>
</form>

JavaScript:
function calcHours() {
    // Build datetime objects and subtract
    var timeIn = new Date($('#timeIn').val() + $('#dateIn').val());
    if(!isValidDate(timeIn)) return -1;
    var timeOut = new Date($('#timeOut').val() + $('#dateOut').val());
    if(!isValidDate(timeOut)) return -1;
    var hours = (timeOut - timeIn)/(1000*60*60);
    return hours.toFixed(1);
}

function isValidDate(d) {
    console.log(d);
    if ( Object.prototype.toString.call(d) === "[object Date]" ) {
      // it is a date
      if ( isNaN( d.getTime() ) ) {  // d.valueOf() could also work
        // date is not valid
          console.log("isn't valid");
          return 0;
      }
      else {
        // date is valid
          console.log("is valid");
          return 1;
      }
    }
    else {
      // not a date
        console.log("isn't valid");
        return 0;
    }
}
var hours = calcHours();
console.log("Hours:", hours);

I have made a js fiddle: http://jsfiddle.net/mq72k/7/. If you open it up in chrome, it will work fine. If you open it up in Safari, it will say invalid date for the same inputs and not work at all. I have also tried varying the string a bit, adding spaces, different order ect.
Does any one have any ideas how to fix this cross browser compatibility issue?

A: Try using an external plugin to parse your dates, something like Datejs

A: Frankly, I'm surprised other browsers parse the string correctly, as the string you give to the date object is 1:00 AM1/20/2012. Put the date first and add a space in between.
var timeIn = new Date($('#dateIn').val() + ' ' + $('#timeIn').val());
var timeOut = new Date($('#dateOut').val() + ' ' + $('#timeOut').val());

http://jsfiddle.net/mq72k/8/

A: Javascript does not parse string dates very well at all, including ISO8601 formats. You must parse the string yourself. You especially should not expect a minor format like month/day/year to be parsed since it is used by a small minority of the global population.
Incidentally, this has nothing to do with jQuery.
Edit
To reliably parse m/d/y format:
function toDate(ds) {
  var a = ds.split('/');
  return new Date(+a[2], (a[0] - 1), +a[1]);
}

The above assumes a correct date string is supplied. To check that it's a valid date at the same time:
function toDate(ds) {
  var a = ds.split('/');
  var d = new Date(+a[2], (a[0] - 1), +a[1]);

  if (d.getDate() == a[1] && d.getFullYear() == a[2]) {
    return d;

  } else {
    return NaN; // or some other suitable value like null or undefined
  }
}


Q: jquery addClass and removeClass slow in IE 11 I'm creating an app to monitor nodes on a cluster and this is an example of the visual state. Each small box in the grid represents a node and currently, when hovering over one node, the rest in that respective rack (grid) fadeout.
Here is the link via photobucket since I can't insert images due to my minimal reputation:
visual state
In Chrome and Firefox, hovering in and out a single node will instantly fadein/out the rest of the nodes in the rack, but in IE 11 it has a noticeable lag. I know that IE's javascript engine is slower than Chrome and Firefox, but I'm throwing this out there to see if the SO community can pick apart my code and suggest better ways of doing this as I am not the greatest front end programmer. Thank you and here is snippets of my code:
from the django template (each node has id="matrix-box-<node #>"):

    visual state

        {% for row in v.22 %}
            {% if v.23 == "ca" %}
                {% if forloop.counter0|divisibleby:4 %}

                {% endif %}
            {% elif v.23 ==  "cs" %}
                {% if forloop.counter0|divisibleby:8 %}

                {% endif %}
            {% endif %}

            {% for elem in row %}
                {% if elem.1 == "#49E20E" %}

                {% elif elem.1 == "#0000CD" %}

                {% elif elem.1 == "yellow" %}

                {% elif elem.1 == "#E3170D" %}

                {% elif elem.1 == "brown" %}

                {% elif elem.1 == "orange" %}

                {% elif elem.1 == "black" %}

                {% elif elem.1 == "#cccccf" %}

                {% endif %}
            {% endfor %}

       ... other code

from css code:
    .node {
        width: 4px;
        height: 4px;
        float: left;
        border: 1px solid #B0B0B0;
        background: #cccccf;
        margin: 0 !important;
        cursor: pointer;
        filter: alpha(opacity=100);
        opacity: 1;
        }

    .faded .node-faded {
        width: 4px;
        height: 4px;
        filter: alpha(opacity=50);
        opacity: .5;
     }

    .active {
        width: 4px;
        height: 4px;
        float: left;
        border: 1px solid black;
        background: #cccccf;
        margin: 0 !important;
       cursor: pointer;
       filter: alpha(opacity=100);
       opacity: 1;
     }

from js code:
    var node = null;
    var node_id = null;
    var rack = null;
    var nodes = null;

    $(document).ready(function(){
        $('[id^=matrix-box]').on({
            mouseenter: function(){
                node = $(this);
                rack = node.parent().parent();
                rack.addClass('faded');
                node.removeClass('node-faded').addClass('active');
            },
            mouseleave: function(){
                node.removeClass('active').addClass('node-faded');
                rack.removeClass('faded');
            },
            click: function(e){

            ...other code

Also, any constructive criticism (albeit helpful and not malicious) is always welcome. Thanks again!

A: As you gave no possibility to test, this is kind of a guessing game. What you do is the following:
$('[id^=matrix-box]').on({ mouseenter: function(){});

This adds a new event listener on each element with an id starting with matrix-box. Not the worst idea, but it can be slow if you have a lof of these items.
Here is demo to validate this: http://jsfiddle.net/k3mjmdzp/3/
A good idea to overcome performance issues is to use a delegated event listener.
Try to rewrite your code like this:
$(function () {
    $('#matrix').on('mouseenter mouseleave click', '[id^=matrix-box]', function (event) {
        console.log(event);
    });
});

Here you have the demo: http://jsfiddle.net/k3mjmdzp/2/
This will leave your code with having only event listeners on $('#matrix') and not on each child node. This is also nice if you append new items via ajax later on.
You can check for event listeners on the event Listeners tab in chrome developer tools.


Q: What is a type inference? Does it only exist in statically typed languages? And is it only there when the language is not strongly typed (i.e., does Java have one)? Also, where does it belong - in the compilation phase assuming it's a compiled language?
In general, are the rules when the type is ambiguous dictated by the language specification or left up to the implementation?

A: Type inference is a feature of some statically-typed languages.  It is done by the compiler to assign types to entities that otherwise lack any type annotations.  The compiler effectively just 'fills in' the static type information on behalf of the programmer.
Type inference tends to work more poorly in languages with many implicit coercions and ambiguities, so most type inferenced languages are functional languages with little in the way of coercions, overloading, etc.
Type inference is part of the language specification, for the example the F# spec goes into great detail about the type inference algorithm and rules, as this effectively determines 'what is a legal program'.
Though some (most?) languages support some limited forms of type inference (e.g. 'var' in C#), for the most part people use 'type inference' to refer to languages where the vast majority of types are inferred rather than explicit (e.g. in F#, function and method signatures, in addition to local variables, are typically inferred; contrast to C# where 'var' allows inference of local variables but method declarations require full type information).

A: A type inferencer determines what type a variable is from the context. It relies on strong typing to do so. For example, functional languages are very strongly, statically typed but completely rely on type inference.
C# and VB.Net are other examples of statically typed languages with type inference (they provide it to make generics usable, and it is required for queries in LINQ, specifically to support projections).
Dynamic languages do not infer type, it is discovered at runtime.

A: Type inferencing is a bit of a compromise found in some static languages.  You can declare variables without specifying the type, provided that the type can be inferred at compile time.  It doesn't offer the flexibility of latent typing, but you do get type safety and you don't have to write as much.
See the Wikipedia article.

A: A type inferencer is anything which deduces types statically, using a type inference algorithm. As such, it is not just a feature of static languages.
You may build a static analysis tool for dynamic languages, or those with unsafe or implicit type conversions, and type inference will be a major part of its job. However, type inference for languages with unsafe or dynamic type systems, or which include implicit conversions, can not be used to prove the type safety of a program in the general case.
As such type inference is used:

*

*to avoid type annotations in static languages,

*in optimizing compilers for dynamic languages (ie for Scheme, Self and Python),

*In bug checking tools, compilers and security analysis for dynamic languages.


Q: Cannot download card from Hyperledger Composer Playground I'm trying to export my Network Admin card from the Playground UI, but the export icon is disabled. In addition, I see the following error in my Chrome console:
Error: The current identity, with the name 'admin' and the identifier 'ddae16d6f23947e9349627051b8ca5933cef53d2918f52295352d7dd24cdabcb', must be activated.
How do I export the Network Admin card from the Playground?
Here's the full Firefox log:
Establishing admin connection ...
main.d12285adf00f2401cf60.bundle.js:1:346887
@JS : ModelManager            :addSystemModels()        [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : Resolver                :resolveRelationship()    Failed to resolve relationship [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : IdentityManager         :<ResourceManager>()      Binding in the tx names and impl
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : EngineTransactions      :createHistorianRecord()  created historian record
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : Resolver                :resolveRelationship()    Failed to resolve relationship [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : EngineTransactions      :createHistorianRecord()  created historian record
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : Resolver                :resolveRelationship()    Failed to resolve relationship [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : EngineTransactions      :createHistorianRecord()  created historian record
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : ConnectionProfileManager:getConnectionManagerByTy Looking up a connection manager for type web
main.d12285adf00f2401cf60.bundle.js:1:848811
Establishing admin connection ...
main.d12285adf00f2401cf60.bundle.js:1:346887
@JS : ConnectionProfileManager:getConnectionManagerByTy Looking up a connection manager for type web
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : IdentityManager         :validateIdentity()       Error: The current identity, with the name 'admin' and the identifier 'ddae16d6f23947e9349627051b8ca5933cef53d2918f52295352d7dd24cdabcb', must be activated (ACTIVATION_REQUIRED)
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : Engine                  :query()                  Caught error, rethrowing [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : IdentityManager         :validateIdentity()       Error: The current identity, with the name 'admin' and the identifier 'ddae16d6f23947e9349627051b8ca5933cef53d2918f52295352d7dd24cdabcb', must be activated (ACTIVATION_REQUIRED)
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : IdentityManager         :<ResourceManager>()      Binding in the tx names and impl
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : EngineTransactions      :createHistorianRecord()  created historian record
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : ConnectionProfileManager:getConnectionManagerByTy Looking up a connection manager for type web
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : ModelManager            :addSystemModels()        [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848811
connected
main.d12285adf00f2401cf60.bundle.js:1:61666

A: This is the answer I got on GitHub:

The reason that the export is greyed out is because you are using the
  bluemix staged Playground that is in the 'web-connector' mode. In
  order to meaningfully export a business network card, you will need to
  create a connection to Hyperledger Fabric. The steps you outline above
  will not create a business network in Hyperledger Fabric, but within a
  web connector.
If you follow the developer tutorial
  (https://hyperledger.github.io/composer/tutorials/developer-tutorial)
  you will be taken through the process of creating a (local) Fabric,
  from which you can connect Playground and export business network
  cards.

A: You can create the admin card via composer-cli.
composer card create
-p connection.json
-u PeerAdmin -c Admin@org1.example.com-cert.pem
-k 114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457_sk
-r PeerAdmin -r ChannelAdmin

Add connection.json file as following:
{
  "name": "fabric-network",
  "type": "hlfv1",
  "mspID": "Org1MSP",
  "peers": [
      {
          "requestURL": "grpc://localhost:7051",
          "eventURL": "grpc://localhost:7053"
      }
  ],
  "ca": {
      "url": "http://localhost:7054",
      "name": "ca.org1.example.com"
  },
  "orderers": [
      {
          "url" : "grpc://localhost:7050"
      }
  ],
  "channel": "composerchannel",
  "timeout": 300
}

The certificate file can be found in the signcerts subdirectory (fabric-tools/fabric-scripts/hlfv1/composer/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp) and is named Admin@org1.example.com-cert.pem.
The private key file can be found in the keystore subdirectory. The name of the private key file is a long hexadecimal string, with a suffix of _sk, for example 114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457_sk.
Step by step tutorial is available in Hyperledger Composer
Tutorials @ https://hyperledger.github.io/composer/tutorials/deploy-to-fabric-single-org.


Q: Unable to call locally declared scope function via ng-click in a directive
*

*I have a directive (Just a button).

*This directive has an isolated scope.

*I want to update the object in my parent scope by clicking on the button.

*But the function is not being called.

This is the plunker.
I've tried defining the function in both the link function and the controller, and they didn't work
I know I am missing something very basic. Need some form of explanation on why this is happening. Have tried looking through a lot of the other questions but I still couldn't find a clear answer.
Thanks in advance!

A: You forget to scope.$apply()! See forked plunk: http://plnkr.co/edit/zo1GrfwyQ8T82TJiW16h?p=preview
You need to call $apply() every time an external source touches Angular values (in this case the "external source" is the browser event handled by on()).


Q: display the back and next button between half the height of image android i have a problem in xml layout for displaying next and back button besides the image and should be in middle of height of image.
pls see this url
http://screencast.com/t/zE47nb0rkFE
two buttons are above the image,it is left and right but not the middle height of image.
and it should be for every resolution size of screen.
my xml is
       <?xml version="1.0" encoding="utf-8"?>

A: you can use scrollview in code like this ::
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
 android:layout_height="fill_parent"
android:background="#FFFFFF">
<ScrollView android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<WebView
android:id="@+id/imv"
android:orientation="vertical"
android:layout_width="fill_parent"
 android:layout_height="55dip"
 />

 <ImageView
 android:id="@+id/imagegallery"
 android:layout_width="70sp"
  android:layout_height="70sp"
  android:layout_alignParentRight="true"
   android:layout_below="@id/imv"/>
 <ProgressBar
  android:id="@+id/Bar"
  android:layout_width="wrap_content"
  android:layout_centerInParent="true"
  android:layout_height="wrap_content"
  android:layout_above="@id/imagegallery"
  android:layout_below="@id/imv"
 />

 <TextView android:layout_height="wrap_content"
  android:id="@+id/textView1"
  android:text="Art Gallery"
  android:textColor="#000000"
  android:layout_width="wrap_content"

  android:layout_below="@id/imv"
  />
  <TextView android:layout_height="wrap_content"
  android:id="@+id/textView2"
  android:textColor="#00C000"
  android:textSize="20dip"
  android:text=" "
  android:layout_width="wrap_content"
  android:layout_toLeftOf="@id/imagegallery"
  android:layout_alignParentLeft="true"
  android:layout_below="@id/textView1"
  />
  <TextView android:layout_height="wrap_content"
android:id="@+id/textopeningnow"
android:text="Opening Now"
android:textColor="#000000"
android:layout_width="wrap_content"
    android:layout_below="@id/textView2"
/>
 <TextView android:layout_height="wrap_content"
android:id="@+id/diosas"
 android:textSize="20dip"
android:text="Diosas/Godesses"
android:textColor="#00C000"
android:layout_width="wrap_content"
    android:layout_below="@id/textopeningnow"
/>

    <Button
     android:id="@+id/back"
     android:layout_height="wrap_content"
     android:layout_width="25dip"
     android:layout_centerVertical="true"
     android:background="@drawable/leftarrow"/>
     <Button
     android:id="@+id/next"
     android:layout_height="wrap_content"
     android:layout_width="25dip"
     android:layout_alignParentRight="true"
     android:layout_centerVertical="true"
     android:background="@drawable/rightarrow"/>

<ImageView android:id="@+id/imageLoader"
    android:layout_width="wrap_content"
    android:layout_height="200dip"
    android:layout_toLeftOf="@id/next"
    android:layout_toRightOf="@id/back"
    android:layout_below="@id/diosas"
  />

    <TextView
    android:id="@+id/artistname"
    android:textColor="#000000"
    android:text=" "
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_below="@id/imageLoader"
    android:layout_centerInParent="true"
    />
</LinearLayout>
</ScrollView>
     </RelativeLayout>

A: I'd enclose your image in a separate RelativeLayout, and add the buttons to it. It's way too hard to try to achieve what you want with just a global relative layout.


Q: Is it possible to pass an argument to a Svelte component that specifies a particular file to import? I'm building a photography site. The user can click on links to various photo album components, e.g. an album of black and white portraits, an album of black and white architecture, etc.
The displayed contents (i.e., image file paths and corresponding image captions) for each album are detailed in a json file that is imported at the top of the album component, e.g. import {images} from './albums/bwportraits.js';, import {images} from './album/bwarchitecture.js';, etc.
Apart from the album-specific imports, the rest of each album component is identical. I would like a generic <Album /> component but be able to pass the json file to import as a prop, i.e. <Album album = "bwportraits" />, <Album album = "bwarchitecture" /> and the import within the <Album /> to be something equivalent to (the non-valid) import {images} from './albums/{album}';.
That is, I would like to dynamically specify which file to import. This does not appear possible - or, at least, I do not know how to do this.
It would, of course, be possible to import every album json file into the <Album /> component; they are reasonably small and the performance hit would be negligible. But this feels a little unclean to me. Is there a 'cleaner' workaround that anyone can suggest?


Q: meaning of "Bird titi = new Swan();" I currently read a java book and I am stuck at an example including this line :
Bird titi = new Swan();

where Swan is a subclass of Bird.
I could explain this as follow:

when java executes this line, it stores memory for the value titi, and the memory stored can contain an information for an object of type Bird. next, the second part of the line call the Swan constructor without any argument, which initializes the titi value.

if I am right, I can't explain why a Swan instance can be stored in a Bird type because Swan, as a subclass, contains more information than Bird.
so I think I am something wrong. where?
and, extra-question : in which case this type of statement is useful?
thank you

A: You may have a method that only takes an instance of Bird. Since Swan is a Bird, you can use an instance of Swan and treat it as Bird.
That's the beauty of polymorphism. It allows you to change out the implementation of the class' internals without breaking the rest of your code.

A: Where it is calling new Swan(), it is creating a new Swan object in memory.
When the Swan object is assigned to the Bird variable (possible because a Swan is a sub type of Bird) the Bird variable simply has a pointer to the Swan in memory. Because titi is a verb, this object can now be accessed / treated like a bird for static time type checking and functionality... though it is always a Swan, and can be cast to a Swan to extended Swan functionality.

A: Bird titi = new Swan();

is actually known as: programming to superclass but sometimes programming to interfaces
means:
titi is a Bird, pointing to a Swan reference... note that this is only valid because of inheritance... which means in this case that Swan is a class that extends the Bird class
why: it allows modifications in the code... you can latter decide not to use a Swan but an Owl so
Bird titi = new Swan(); will be replaced with Bird titi = new Owl(); and everything will work fine
programming to interfaces is more elegant because you can do:
IFly titi = new Swan();

which is valid if the Swan implemtents the interface IFly, so it is:
titi is something that can fly, pointing to a Swan ref.

A: Bird titi = new Swan();

It's all about Polymorphism.
A Parent class/Interface type  can hold it's Child class's Object.
Here Bird is Parent class/Interface and Swan is Child.
The same example is below :
List list = new ArrayList();

Here List is Parent Interafce and ArrayList it's Child class.


Q: Using python generics and inheritance I need to implement a bunch classes, that all need to do the same modification to the parent class. As a skilled C++ programmer, I would look for a template class. But this needs to be implemented in Python. Here I am a rookie. I found the "Generic" and has constructed this example to show the core in my problem. The real program is somewhat more complicated(using ReportLab to generate PDF documents). I need to subclass to benefit from the class framework, which leads me into trying to implement a Generic using inheritance.
The problem is that cannot understand how I can pass argument to the "super" class, which here I try to make a Generic.
First attempt:
super().__init__(*argv, **kwargs)

Second attempt:
super(G, self).__init__(*argv, **kwargs)

Third attempt:
T.__init__(*argv, **kwargs)

Here is the complete example:
from typing import Generic, TypeVar

class A():
    def __init__(self, i : int):
        self.i = i

    def draw():
        print(self.i)

class C():
    def __init__(self, s : str):
        self.s = s

    def draw():
        print(self.s)

T = TypeVar('T')

class G(Generic[T]):
    def __init__(self, *argv, **kwargs):
        super().__init__(*argv, **kwargs)

    def draw():
        # Here is some special going to happen
        super().draw()

gA = G[A](5)
gB = G[B]('Hello')

gA.draw()
gB.draw()

The output that I get:
Traceback (most recent call last):
  File "<string>", line 34, in <module>
File "/usr/lib/python3.8/typing.py", line 729, in __call__
    result = self.__origin__(*args, **kwargs)
  File "<string>", line 28, in __init__
TypeError: object.__init__() takes exactly one argument (the instance to initialize)

A: You have understood Python generics wrong. A Generic, say Generic[T], makes the TypeVar T act as whatever you provide the instance with.
I found this page to be very useful with learning Generics.

A: typing.Generic is specifically for type annotations; Python provides no runtime concept equivalent to either:

*

*Template classes, or

*Function overloads by parameter count/type

The latter has extremely limited support from functools.singledispatch, but it only handles the type of one argument, and the runtime type-checking is fairly slow.
That said, you don't need a template-based class or a polymorphic inheritance hierarchy here; Python is perfectly happy to call draw on anything that provides a method of that actual name. The code you're writing here can just do:
a = A(5)
b = B('Hello')

a.draw()
b.draw()

with no use of G needed.


Q: disable component functionality based on page I a navigation where the menu items are hidden until you get to a certain point on the page then they show.
This works great on the homepage, because it is a relatively long page. But, some of my other pages are short and do not go past the height of the viewport. So when the page loads there are no navigation menu options and it shows the navigation is blank.
Is there a way in react to say disable a component conditionally according to what layout or page you are on?
Example: In Jekyll you can create an if statement and hide a class or section using somehting like {% if page.layout == 'home' %}hide{% endif %}. Is there an equivalent/similar method when using react?
Code:
import React from 'react';
import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink } from 'reactstrap';

export default class Example extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      isOpen: false,
      isTop: true,
      width: 0,
      height: 0
    };
    this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
  }
  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }

  componentDidMount() {
    this.updateWindowDimensions();
    window.addEventListener('resize', this.updateWindowDimensions);
    document.addEventListener('scroll', () => {
      const isTop = window.scrollY < window.innerHeight - 50;
      if (isTop !== this.state.isTop) {
        this.setState({ isTop })
      }
    });
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateWindowDimensions);
  }

  updateWindowDimensions() {
    this.setState({ width: window.innerWidth, height: window.innerHeight - 50 });
  }

  render() {
    return (

        <Navbar color="light" light expand="md">
          <NavbarBrand href="/">Maryland Brand</NavbarBrand>
          <NavbarToggler onClick={this.toggle} />
          <Collapse isOpen={this.state.isOpen} navbar>

              <NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
                <NavLink className="active" href="/">Our Brand</NavLink>
              </NavItem>
              <NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
                <NavLink href="/">Logos</NavLink>
              </NavItem>
              <NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
                <NavLink href="/">Color</NavLink>
              </NavItem>
              <NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
                <NavLink href="/">Typography</NavLink>
              </NavItem>
              <NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
                <NavLink href="/">Imagery</NavLink>
              </NavItem>
              <NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
                <NavLink href="/">Editorial</NavLink>
              </NavItem>
              <NavItem>
                <NavLink className="red bold uppercase show" href="/">Communicators Toolkit</NavLink>
              </NavItem>

          </Collapse>
        </Navbar>

    );
  }
}

A: Gatsby comes with reach router, so you can use it to get location.pathname and then render something conditionally.
import React from 'react'
import { Location } from '@reach/router'

const HomepageOnly = () => (
  <Location>
    {({ location }) =>
      location.pathname === '/' ? (

This is the homepage

      ) : (

This is not

      )
    }
  </Location>
)

export default HomepageOnly

Codesandbox


Q: UIDocumentInteractionController working in iOS6 but not in iOS5 I am using UIDocumentInteractionController in MonoTouch and in the iOS6 Simulator and on iOS6 devices my code half works. However it does not work at all for iOS5 simulator/devices. Here is a sample class I made to test with in a sample project.
using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;

namespace DocumentThing
{
    public class MyViewController : UIViewController
    {
        UIDocumentInteractionController documentInteractionController1;
        UIDocumentInteractionController documentInteractionController2;
        UIBarButtonItem leftButton;
        UIBarButtonItem rightButton;

        public MyViewController()
        {

        }

        public override void ViewDidLoad()
        {
            View.BackgroundColor = UIColor.White;

            leftButton = new UIBarButtonItem(UIBarButtonSystemItem.Action, null, null);
            leftButton.Clicked += delegate(object sender, EventArgs e)
            {
                InvokeOnMainThread(delegate {
                    documentInteractionController1 = new UIDocumentInteractionController();
                    documentInteractionController1.Url = NSUrl.FromFilename(@"testpdf.pdf");
                    documentInteractionController1.PresentOpenInMenu(View.Frame, View, true);
                });
            };
            NavigationItem.LeftBarButtonItem = leftButton;

            rightButton = new UIBarButtonItem(UIBarButtonSystemItem.Action, null, null);
            rightButton.Clicked += delegate(object sender, EventArgs e)
            {
                InvokeOnMainThread(delegate {
                    documentInteractionController2 = new UIDocumentInteractionController();
                    documentInteractionController2.Url = NSUrl.FromFilename(@"testpdf.pdf");
                    documentInteractionController2.PresentOptionsMenu(View.Frame, View, true);
                });
            };
            NavigationItem.RightBarButtonItem = rightButton;
        }
    }
}

The PresentOptionsMenu works fine on iOS6 but not in iOS5, and the PresentOptionInMenu fails on both iOS5 and iOS6. Not sure if this is a bug with iOS5/6 SDKs/Simulators or if it is a bug in MonoTouch. I got no idea how to debug this issue further...
Suggestions?

A: Answering my own question...
Did you check if you have any thing to open a PDF on your device which has iOS5 on it? Don't forget iBooks is not installed by default and iOS does not think to use Safari as a PDF reader.


Q: Excel/Google Sheets Offset and Transpose formula question I have a query regarding the OFFSET and TRANSPOSE formulas. I have the following two sheets set up in Google Sheets (originally in Excel):
First sheet:

Formula in cell B2: =transpose('Form responses 1'!A2:BB2) (original)
=transpose(offset('Form responses 1'!A$2:BB$2,COLUMNS($A$2:A2)-1,0)) (current)
Formula in cell C2: =transpose('Form responses 1'!A3:BB3)
Formula in cell D2: =transpose('Form responses 1'!A4:BB4)
I would like the references to increase by row (vertically down) rather than by column (horizontally right) when I drag across to copy the formula.
Second sheet:

As you can see in the first sheet, I am trying to TRANSPOSE data from the second sheet using said formula. However when I go to drag the formula across (horizontally) it references the column when instead I need it to reference the row (if I drag it downwards it works fine but that is not what I need in this particular case).
I understand I need to implement a OFFSET function, something along the lines of: =transpose(offset('Form responses 1'!A$2:BB$2,COLUMNS($A$2:A2)-1,0))
I am unsure of what the last part would need to be, COLUMNS($A$2:A2)-1,0, what should I change this to to get the desire result?
If I have not explained thoroughly enough please let me know, thanks.

A: Use arrayformula and you won't have to drag anything. Try:
=arrayformula(transpose('Form responses 1'!A$1:BB$4))


Q: Exception Safety example guarantee correct? I discuss the Exception Safety Guaratees and devised an example that I think provides the Strong Guarantee:
template<typename E, typename LT>
void strongSort(vector<E*> &data, LT lt) // works on pointers
{
  vector<E*> temp { data };  // bad_alloc? but 'data' not changed.
  sort(temp.begin(), temp.end(), lt); // 'lt' might throw!
  swap(temp, data); // considered safe.
}

Just an easy (C++0x)-example how this is used:
int main() {
  vector<int*> data { new int(3), new int(7), new int(2), new int(5) };
  strongSort( data, [](int *a, int *b){ return *a<*b;} );
  for(auto e : data) cout << *e << " ";
}

Assuming LT does not change the elments, but it may throw. Is it correct to assume thiat the code provides

*

*the Strong Exception Safety guarantee

*Is Exception Neutral, w.r.t to LT

A: Yes. Strong exception guarantee means that the operation completes successfully or leaves the data unchanged.
Exception neutral means that you let the exceptions propagate.

A: It is exception safe. To be more safe, why not use vector<shared_ptr<int>>
template<typename Type, typename Func>
void StrongSort( vector<shared_ptr<Type>>& elems, Func fun)
{
    vector<shared_ptr<Type>> temp ( elems.begin(), elems.end());
    sort(temp.begin(), temp.end(), fun);
    swap(elems, temp);
}

vector<shared_ptr<int>> ints;
ints.push_back(shared_ptr<int>(new int(3)));
ints.push_back(shared_ptr<int>(new int(1)));
ints.push_back(shared_ptr<int>(new int(2)));
StrongSort(ints, [](shared_ptr<int> x, shared_ptr<int> y) -> bool { return *x < *y; });


Q: javax.validation.ConstraintViolationException I am using JSF+JPA  iam not fix this error:

javax.validation.ConstraintViolationException: Bean Validation
  constraint(s) violated while executing Automatic Bean Validation on
  callback event:'prePersist'. Please refer to embedded
  ConstraintViolations for details.

@ManagedBean(name = "clientCon")
public class ClientController {

    @PostConstruct
    public void init() {
        System.out.println("Salam");
        clients = new Clients();
    }

    private EntityManagerFactory emf = null;

    public ClientController() {
        emf = Persistence.createEntityManagerFactory("ClinicProjectPU");
    }

    private List<Clients> clientList;
    private Clients clients;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public Clients getClients() {
        return clients;
    }

    public void setClients(Clients clients) {
        this.clients = clients;
    }

    public List<Clients> getClientList() {
        this.clientList = getEntityManager().createNamedQuery("Clients.findAll").getResultList();
        return clientList;
    }

    public void createClient() {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(clients); // the only interesting method
            em.flush();
            em.getTransaction().commit();
            System.out.println("created");
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
}

<h:form>
    <fieldset>
        <h:panelGrid  columns="2">
            <h:outputText value="Ad" style="color: #0099cc"/>
            <h:inputText class="form-client" value="#{clientCon.clients.name}" />
            <h:outputText  value="Soyad" style="color: #0099cc" />
            <h:inputText class="form-client" value="#{clientCon.clients.surname}" />
            <h:outputText value="Telefon" style="color: #0099cc" />
            <h:inputText class="form-client" value="#{clientCon.clients.phone}" />
        </h:panelGrid>

            <h:commandButton action="#{clientCon.createClient()}"  value="Saxla" style="width: 60%;margin-top: 5%;border-radius: 5px;color: #ffffff;background-color: #0099cc" />

    </fieldset>
</h:form>

javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
    at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.validateOnCallbackEvent(BeanValidationListener.java:90)
    at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.prePersist(BeanValidationListener.java:62)
    at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:748)
    at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:691)
    at org.eclipse.persistence.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:229)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectClone(UnitOfWorkImpl.java:4310)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4287)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:518)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4229)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
    at controller.ClientController.createClient(ClientController.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at javax.el.ELUtil.invokeMethod(ELUtil.java:326)
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:536)
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:269)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:724)

A: This is another way from correct answer on Sujan Sivagurunathan, i wrote not in comment because i dont have 50 reputation.
If you have AbstractFacade.java write this on create method
public void create(T entity) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    javax.validation.Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);
    if (constraintViolations.size() > 0 ) {
       System.out.println("Constraint Violations occurred..");
       for (ConstraintViolation<T> contraints : constraintViolations) {
            System.out.println(contraints.getRootBeanClass().getSimpleName()+
            "." + contraints.getPropertyPath() + " " + contraints.getMessage());
        }
        getEntityManager().persist(entity);
    }
}

A: To know what caused the constraint violation, you can use the following validator and logger.
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();

Set<ConstraintViolation<Clients>> constraintViolations = validator.validate(clients);

if (constraintViolations.size() > 0 ) {
  System.out.println("Constraint Violations occurred..");
  for (ConstraintViolation<Clients> contraints : constraintViolations) {
    System.out.println(contraints.getRootBeanClass().getSimpleName()+
    "." + contraints.getPropertyPath() + " " + contraints.getMessage());
  }
}

Put the logger before persisting the entity. So between
em.getTransaction().begin();
//here goes the validator
em.persist(clients);

Compile and run. The console will show you, just before the exception stack trace, which element(s) caused the violation(s).
You can but should catch your try block containing any persistence method with ConstraintViolationException (to avoid further problems and/or inform the user an error occurred and its reason). However, in a well built system there shouldn't be any constraint violation exception during persistence. In JSF, and other MVC framework, the validation step must be totally or partially done at the client side before submit/persistence. That's a good practice I would say.


Q: Read and write structure containing std::string to .dat file using std::write and std::read C++ I have a structure
struct details
{
   std::string username;
   std::string password;
   bool isActive;
};

struct details v_Details;

i wish to write these data into a file and then read it at some other point in the code as means of storing details. I have tried using std::write which seems to do its job
std::ofstream out_file;
out_file.open ("db.dat" , ios::out | ios::binary)
out_file.write((char*)&v_details , sizeof (struct details))

but when i try to read the data it reads only username and password and then it crashes.
My read part of the code is as below
std::ifstream in_file;
in_file.open (fileName.c_str() , std::ifstream::in);

std::string readFileLine = "\0";

if (in_file.is_open())
{
    do
    {
        in_file.read ((char*)&details , sizeof(details));
        cout << "\nDEBUG message-> " << __FILE__ <<" : " << __func__ << " : " << __LINE__ << " : Read - "<< details.username << " " << details.password << " " << isActive ;
    }while (!in_file.eof());

in_file.close();
}

Anybody who can help and provide me a fix on this.

A: You cannot directly write the object and expect it to store everything properly when you have members that don't have a fixed size.
If it were char array you could use this way.
Given this situation, I would manually write the details, like length of username first, then write characters in username so that while reading I can read the length of username and read that number of characters from file.


Q: Syncing objects imported at runtime using PUN In our multiplayer project on Unity, each user imports model at runtime, then joins room, and then configures runtime imported object as networked object. The problem is, the imported model gets destroyed when host leaves. Here is my code snippet:
 private void Start()
    {
        pView = GetComponent<PhotonView>();
        pView.ownershipTransfer = OwnershipOption.Takeover;
        pView.ObservedComponents = new List<Component>();

        photonTransformView = transform.GetComponent<PhotonTransformView>();
        pView.ObservedComponents.Add(photonTransformView);
        pView.synchronization = ViewSynchronization.UnreliableOnChange;

        photonTransformView.m_PositionModel.SynchronizeEnabled = true;
        photonTransformView.m_RotationModel.SynchronizeEnabled = true;

        if (GetComponent<OVRGrabbable>() != null)
            transform.GetComponent<OVRGrabbable>().runtimeObj = this;
        partInfo = transform.GetComponent<PartInfo>();
        if (partInfo)
            partInfo.dynamicDync = this;

        if (PhotonNetwork.isMasterClient)
        {
            int objId = PhotonNetwork.AllocateViewID();
            // pView.viewID = objId;
            //TakeOwnership(PhotonNetwork.player);

            MSetPhotonViewId(PhotonNetwork.player.ID, gameObject.name, objId);
        }
    }

    public void MSetPhotonViewId(int id, string objName, int objId)
    {
        //pView.RPC("SetOwnerForObject", PhotonTargets.Others, id);
        object[] content = new object[3];
        content[0] = id;
        content[1] = objName;
        content[2] = objId;
        PhotonNetwork.RaiseEvent(ownerId, content, true, new RaiseEventOptions() { Receivers = ReceiverGroup.All, CachingOption = EventCaching.AddToRoomCache });
    }

    private void OnEvent(byte eventcode, object content, int senderid)
    {
        if (eventcode == ownerId)
        {
            object[] data = (object[])content;
            if (gameObject.name == (string)data[1])
            {
                if (!pView)
                    StartCoroutine(MGetPhotonViewId(content, senderid));
                else
                {
                    pView.viewID = (int)data[2];
                    //Debug.Log("transfering ownership of: " + gameObject.name + " to: " + ((int)data[0]).ToString());
                    pView.TransferOwnership((int)data[0]);
                }
            }
        }
    }

    IEnumerator MGetPhotonViewId(object content, int senderid)
    {
        while (!pView)
        {
            yield return null;
        }

        object[] data = (object[])content;
        if (gameObject.name == (string)data[1])
        {
            pView.viewID = (int)data[2];
            //Debug.Log("transfering ownership of: " + gameObject.name + " to: " + ((int)data[0]).ToString());
            pView.TransferOwnership((int)data[0]);
        }
    }

How do I avoid object getting destroyed on other systems, when host leaves?

A: When a player quits a game, usually his/her actions are no longer relevant for new players. To avoid congestion on join, Photon server by default automatically cleans up events that have been cached by a player, that has left the room for good.
If you want to manually clean up the rooms' event cache you can create rooms with RoomOptions.CleanupCacheOnLeave set to false.
See the docs.


Q: Runspace Dispose in Powershell (GUI specific) I'm an active reader of StackOverflow as it usually helps me resolve all my issues.
But for my first question ever I'll ask your help about runspaces in Powershell, specifically for memory management.
I created some PS apps with GUI and now I use runspaces to avoid hang of the GUI when big operations are running.
My problem is that I can't manage to dispose my runspaces when they are finished.
Regarding the code below, it's a simple script to try to understand how I can dispose of my runspaces. I tried to incorporate a unique runspace to monitor and dispose the app runspaces, I inspired myself from a proxb's script (huge fan btw) but it doesn't seems to work.
Everytime I execute the runspace I gain 10Mb of memory, huge leak!

Can you help me to resolve this problem please ?
[xml]$xaml = @'
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Runspace" FontFamily="Calibri" Height="400" Width="400" FontSize="14">
    <Grid Margin="10,10,10,10">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="10"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <TextBox x:Name="TB_Results" Grid.Row="0" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto"/>
        <Button x:Name="BT_Run" Grid.Row="2" Content="Run" Height="30"/>
    </Grid>
</Window>
'@

# Inits
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase
$gui = [hashtable]::Synchronized(@{})
$reader = (New-Object Xml.XmlNodeReader $xaml)
$gui.Window = [Windows.Markup.XamlReader]::Load($reader)
$xaml.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | ForEach-Object { $gui.Add($_.Name,$gui.Window.FindName($_.Name)) }
$Script:Jobs = [system.collections.arraylist]::Synchronized((New-Object System.Collections.ArrayList))
$Script:JobCleanup = [hashtable]::Synchronized(@{ Host = $host })

# Test function
function RunFunc {
        $newRunspace = [runspacefactory]::CreateRunspace()
        $newRunspace.ApartmentState = "STA"
        $newRunspace.ThreadOptions = "ReuseThread"
        $newRunspace.Open()
        $newRunspace.SessionStateProxy.SetVariable("gui",$gui)
        $Code = {
            $memupdate = "Memory: $($(Get-Process -Id $PID).PrivateMemorySize64 / 1mb) mb"
            $gui.Window.Dispatcher.invoke("Normal",[action]{
                $gui.TB_Results.Text = "$memupdate`r`n" + $gui.TB_Results.Text
            })
        }
        $Powershell = [powershell]::Create().AddScript($Code)
        $Powershell.Runspace = $newRunspace
        [void]$Script:Jobs.Add((
            [PSCustomObject]@{
                PowerShell = $PowerShell
                Runspace = $PowerShell.BeginInvoke()
            }
        ))
}

# Background Runspace to clean up jobs
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("jobs",$Script:Jobs)
$Code = {
    $JobCleanup = $true
    do {
        foreach($runspace in $jobs) {
            if ($runspace.Runspace.isCompleted) {
                $runspace.powershell.EndInvoke($runspace.Runspace) | Out-Null
                $runspace.powershell.dispose()
                $runspace.Runspace = $null
                $runspace.powershell = $null
            }
        }
        $temphash = $jobs.clone()
        $temphash | Where-Object { $_.runspace -eq $Null } | ForEach-Object { $jobs.remove($_) }
        Start-Sleep -Seconds 1
    } while ($JobCleanup)
}
$Powershell = [powershell]::Create().AddScript($Code)
$Powershell.Runspace = $newRunspace
$PowerShell.BeginInvoke()

# gui events
$gui.BT_Run.add_Click({ RunFunc })
$gui.Window.ShowDialog() | Out-Null

A: When you call $runspace.PowerShell.Dispose(), the PowerShell instance is disposed, but the runspace that it's tied to is not automatically disposed, you'll need to do that first yourself in the cleanup task:
$runspace.powershell.EndInvoke($runspace.Runspace) | Out-Null
$runspace.powershell.Runspace.Dispose() # remember to clean up the runspace!
$runspace.powershell.dispose()


Q: Rest API Consumption in flutter Problem
I'm trying to receive data from a rest API in my flutter app, inside a future function but i keep getting the following error:
type 'CastList<dynamic, List>' is not a subtype of type 'List'.
The function I'm using to fetch the data is as follows:
static Future<List<Questionnaire>> fetchQuestionnaires() async {
    try {
      final response =
          await http.get('http://10.0.2.2:4010/phone/questionnaires');
      if (response.statusCode == 200) {

        List<Questionnaire> resp =
            json.decode(response.body).cast<List<Questionnaire>>();

        List<Questionnaire> questionnaires = resp
            .map<Questionnaire>((dynamic item) => Questionnaire.fromJson(item))
            .toList();

        log(
          questionnaires.toString(),
        );

        return questionnaires;
      } else {
        throw Exception('Unable to fetch questionnaires');
      }
    } catch (error) {
      log(error.toString());
    }
  }

I don't understand why this is. Why does using cast, cast to CastList<dynamic, Type> and not the original Type? What changes do I do to get my data?
The data model is given below.
Data Model
The Data i expect from my backend is like this. An array called questionnaires, containing multiples of a questionnaire, each containing an id and a displayQuestion. A displayQuestion in turn has the question text and the answers Array_.
For this, I have the following structure in my Json.
[
    {
        "questionId": 1,
        "displayQuestions": [
            {
                "question": "how old are you",
                "answers": [
                    "1",
                    "2",
                    "3",
                    "4"
                ]
            }
        ]
    }
]

This is my questionnaires.dart model
class Questionnaires {
  List<Questionnaire> _questionnaires;
  Questionnaires.fromJson(this._questionnaires);
}

This is questionnaire.dart model
class Questionnaire {
  int questionnaireId;
  List<DisplayQuestion> displayQuestions = [];
  Questionnaire(this.questionnaireId, this.displayQuestions);
  Questionnaire.fromJson(Map<String, dynamic> json)
      : questionnaireId = json['questionnaireId'],
        displayQuestions = json['displayQuestions'];
}

The code from display-question.dart model
class DisplayQuestion {
  String _question;
  List<String> _answers;
  String get question => this._question;

  List get answers => this._answers;

  DisplayQuestion(this._question, [List<String> answers])
      : this._answers = answers ?? [];

  DisplayQuestion.fromJson(Map<String, dynamic> json)
      : _question = json['question'],
        _answers = json['answers'];
}

A:
Why does using cast, cast to CastList<dynamic, Type> and not the original Type?

From the docs, myList.cast<MyType> returns a List<MyType>. In your case you're calling resp.cast<List<Questionnaire>>, so the return will be List<List<Questionnaire>>, which is not what you want.
If you're asking about CastList<dynamic, Type>, it's a subclass of List<Type>, see the source code. It's useful because CastList doesn't need to create a new list, it's just a wrapper around the original list where each element is cast with as Type before being returned.

What changes do I do to get my data?

The problem is you're calling resp.cast<Type> where resp is not a list that constains Type.
Here's a working sample based on the code you provided:
import 'dart:convert';

final sampleJson = """[
    {
        "questionId": 1,
        "displayQuestions": [
            {
                "question": "how old are you",
                "answers": [
                    "1",
                    "2",
                    "3",
                    "4"
                ]
            }
        ]
    }
]
""";

class DisplayQuestion {
  String question;
  List<String> answers;
  DisplayQuestion.fromJson(Map<String, dynamic> json)
      : question = json["question"],
        answers = json["answers"].cast<String>();

  String toString() => 'question: $question | answers: $answers';
}

class Questionnaire {
  int questionnaireId;
  List<DisplayQuestion> displayQuestions;
  Questionnaire.fromJson(Map<String, dynamic> json)
      : questionnaireId = json['questionnaireId'],
        displayQuestions = (json['displayQuestions'] as List<dynamic>)
            .map((questionJson) => DisplayQuestion.fromJson(questionJson))
            .toList();

  String toString() => '$displayQuestions';
}

List<Questionnaire> parseQuestionnaires() {
  List<Questionnaire> questionnaires =
      (json.decode(sampleJson) as List<dynamic>)
          .map((questionnaireJson) => Questionnaire.fromJson(questionnaireJson))
          .toList();
  return questionnaires;
}

void main() {
  print(parseQuestionnaires());
  // => [[question: how old are you | answers: [1, 2, 3, 4]]]
}


Q: Server Error 500 .htaccess I have this working on my dedicated server but it fails on my shared hosting please what can be wrong? Thank you.
AddHandler phpini-cgi .php
#Action phpini-cgi /cgi-bin/php5-custom-ini.cgi

Options -Indexes

Options  FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /404.php

# Set the default handler.
DirectoryIndex index.php

<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^([^/]+)$ index.php?q=$1 [L]

 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^([^/]+)/([^/]+)$ index.php?q=$1&r=$2 [L]

 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ index.php?q=$1&r=$2&s=$3 [L]

 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)$ index.php?q=$1&r=$2&s=$3&t=$4 [L]

</IfModule>

A: I figure out the problem. I noticed the hosting company do not configure Php to display error thus making it difficult for you to know where the problem is. The problem is actually the database connection to the server. Once I fix the database connection my website came on fine.


Q: After IORegisterForSystemPower failing to call IODeregisterForSystemPower I have an application, written in Objective-C for MacOS 10.10+ which registers for sleep/wake notifications (code sample below, but the code isn't the question). What I am wondering is, if I call IORegisterForSystemPower at App initialisation, but during debugging I kill the app before it has a chance to call IODeregisterForSystemPower, what are the implications? Does the app get de-registered automatically when it dies in any case? Is there a system dictionary I need to clear out (a plist somewhere, etc.)? Thanks in advance for any help.
io_object_t                 root_notifier = MACH_PORT_NULL;
IONotificationPortRef       notify = NULL;

DebugLog(@"App: Logging IORegisterForSystemPower sleep/wake notifications %@", [NSDate date]);

/* Log sleep/wake messages */
powerCallbackPort = IORegisterForSystemPower ((__bridge void *)self, &notify, sleepWakeCallback, &root_notifier);
if ( powerCallbackPort == IO_OBJECT_NULL ) {
    DebugLog(@"IORegisterForSystemPower failed");
    return;
}

self.rootNotifierPtr = &(root_notifier);  // MARK: deregister with this pointer

if ( notify && powerCallbackPort )
{
    CFRunLoopAddSource(CFRunLoopGetCurrent(),IONotificationPortGetRunLoopSource(notify), kCFRunLoopDefaultMode);
}

A: To be honest, I don't know the exact answer. But it may help you.
First of, if you call IORegisterForSystemPower, you need to make two calls in this order: - Call IODeregisterForSystemPower with the 'notifier' argument returned here. - Then call IONotificationPortDestroy passing the 'thePortRef' argument returned here (Please visit apple's document for more detail).
In case of port binding, if I use CFSocketSetAddress, before releasing this socket no other can use this port for binding. But in case of app terminate/closed without releasing this socket this port is available. That means after terminated the app system automatically releasing this.

Does the app get de-registered automatically when it dies in any case?

I think it will automatically de-registered by system.
I also used similar code as you in one of my project. But recently replaced with below codes:
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self selector: @selector(receiveWakeNotification:) name: NSWorkspaceDidWakeNotification object: nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self selector: @selector(receiveSleepNotification:) name: NSWorkspaceWillSleepNotification object: nil];


Q: JPA ObjectOptimisticLockingFailureException on an Insert sql execution followed by an Update sql execution I'm using Spring-data-jpa with Kotlin and I faced this error:
org.springframework.orm.ObjectOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; statement executed

Here is my parent entity (unnecessary parts are omitted):
@Entity
class Parent(
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  val id: Long = 0L,

  @OneToMany(mappedBy = "parent", cascade = [CascadeType.ALL], orphanRemoval = true)
  val children: MutableList<Child> = mutableListOf()
) {

  fun addChild(child: Child) {
    this.children.add(child)
    child.parent = this
  }
}

Here is my child entity (omitted too):
@Entity
@Table(uniqueConstraints = [UniqueConstraint(columnNames = ["parent_id"])]
class Child(
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  val id: Long = 0L,
) {

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "parent_id")
  lateinit var parent: Parent
}

Transactional code is simple as follows:
@Transactional
fun saveChildren() {
  ...
  val parent: Parent = parentRepo.findById(parentId)
  parent.addChild(Child())
  parent.addChild(Child())
  validateSavedChildren()   // select all children data to validate for some business reason
  parentRepo.save(parent)
}

I turn on the sql log for debugging and the sqls are like (It assumes the parent's id = 4):
insert into
  child
  (... parent_id)
  values
  (... 4)
enter code here

...

select
  .... parent_id
from Child
where parent_id = 4

...

update Child
set
 parent_id = 4
 ...
where id = 1

The query parameters are just correct. As I guess, the error occurred by the last update sql and also know what the error means. I think the data in insert sql is not yet visible when the update sql is executed. Why I'm thinking this way is because I tried to reproduce the error with debug mode with my IDE(IntelliJ) and I executed the codes line by line, and the error is disappeared. Is this common case in JPA??
What I really wonder is the reason why the update sql is executed. It seems useless because the setting data in update sql is just the same as insert sql. After some Internet research, I found out some cases that update happens after insert, but none of them fits my case.
I also tried to change one line of code:
parentRepo.saveAndFlush(parent)

It made the upate sql disappear and the error is gone forever.
Why does this happen?? What am I missing??
UPDATE
Here is the function validateSavedChildren code:
fun validateSavedChildren() {
  val parents: List<Parant> parentRepo.findAll()  // it select all parents in DB
  var childrenCount = 0
  parents.forEach { parent ->
    childrenCount += parent.children.size
  }
  if (childrenCount > CHILDREN_LIMIT) {
    throw ChildrenCountExceededLimitException()
  }
}

Following a comment by @XtremeBaumer, It seems like the above function has the key point because the update sql execution is removed by erasing the above function call.


Q: Unable to locate a link using xpath I am unable to locate a link on a page using the xpath. When I use the Inspect Element command, the page source for the object is as follows:
<a id="TreeView1_LinkButtonMore" href="javascript:__doPostBack('TreeView1$LinkButtonMore','')">
    See more
</a>

My Selenium Code is as follows:
driver.FindElement(By.XPath("//*[@id='TreeView1_LinkButtonMore')")).Click();

Error I get is as follows:
The given selector //*[@id='TreeView1_LinkButtonMore') is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: Unable to locate an element with the xpath expression //*[@id='TreeView1_LinkButtonMore')

Thanks in Advance

A: Try this:
driver.FindElement(By.XPath("//*[@id='TreeView1_LinkButtonMore']")).Click();

However, it might be worth pointing out that the shortcut for this exact same thing is:
driver.FindElement(By.Id("TreeView1_LinkButtonMore")).Click();

A: There is syntax error in your xpath. The closing should be square bracket not the curve bracket
Syntax: //tag-name[@attribute='value']
Try this:
driver.FindElement(By.XPath("//a[@id='TreeView1_LinkButtonMore']")).Click();


Q: Does each apple developer has to pay $99 fee? We have Apple Developer Account and we invited new guy,
does he have to pay $99 to become a member and get certificates?

A: To share access with new guy I had to add him to https://developer.apple.com/account/#/people/ , not only to https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/users_roles


Q: HtmlAgilityPack set node InnerText  I want to replace inner text of HTML tags with another text.
I am using HtmlAgilityPack
 I use this code to extract all texts
HtmlDocument doc = new HtmlDocument();
doc.Load("some path")

foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//text()[normalize-space(.) != '']")) {
    // How to replace node.InnerText with some text ?
}

But InnerText is readonly. How can I replace texts with another text and save them to file ?

A: The HtmlTextNode class has a Text property* which works perfectly for this purpose.
Here's an example:
var textNodes = doc.DocumentNode.SelectNodes("//body/text()").Cast<HtmlTextNode>();
foreach (var node in textNodes)
{
    node.Text = node.Text.Replace("foo", "bar");
}

And if we have an HtmlNode that we want to change its direct text, we can do something like the following:
HtmlNode node = //...
var textNode = (HtmlTextNode)node.SelectSingleNode("text()");
textNode.Text = "new text";

Or we can use node.SelectNodes("text()") in case it has more than one.

* Not to be confused with the readonly InnerText property.

A: Try code below. It select all nodes without children and filtered out script nodes. Maybe you need to add some additional filtering. In addition to your XPath expression this one also looking for leaf nodes and filter out text content of <script> tags.
var nodes = doc.DocumentNode.SelectNodes("//body//text()[(normalize-space(.) != '') and not(parent::script) and not(*)]");
foreach (HtmlNode htmlNode in nodes)
{
    htmlNode.ParentNode.ReplaceChild(HtmlTextNode.CreateNode(htmlNode.InnerText + "_translated"), htmlNode);
}

A: Strange, but I found that InnerHtml isn't readonly. And when I tried to set it like that
aElement.InnerHtml = "sometext";

the value of InnerText also changed to "sometext"


Q: aws serverless - exporting output value for cognito authorizer I'm trying to share cognito authorizer between my stacks for this I'm exporting my authorizer but when I try to reference it in another service I get the error
Trying to request a non exported variable from CloudFormation. Stack name: "myApp-services-test" Requested variable: "ExtApiGatewayAuthorizer-test".
Here is my stack where I have authorizer defined and exported:
    CognitoUserPool:
  Type: AWS::Cognito::UserPool
  Properties:
    # Generate a name based on the stage
    UserPoolName: ${self:provider.stage}-user-pool
    # Set email as an alias
    UsernameAttributes:
      - email
    AutoVerifiedAttributes:
      - email

    ApiGatewayAuthorizer:
  Type: AWS::ApiGateway::Authorizer
  Properties:
    Name: CognitoAuthorizer
    Type: COGNITO_USER_POOLS
    IdentitySource: method.request.header.Authorization
    RestApiId: { "Ref": "ProxyApi" }
    ProviderARNs:
      - Fn::GetAtt:
          - CognitoUserPool
          - Arn

    ApiGatewayAuthorizerId:
  Value:
    Ref: ApiGatewayAuthorizer
  Export:
    Name: ExtApiGatewayAuthorizer-${self:provider.stage}

this is successfully exported as I can see it in stack exports list from my aws console.
I try to reference it in another stack like this:
  myFunction:
handler: handler.myFunction
events:
  - http:
      path: /{userID}
      method: put
      cors: true
      authorizer:
        type: COGNITO_USER_POOLS
        authorizerId: ${myApp-services-${self:provider.stage}.ExtApiGatewayAuthorizer-${self:provider.stage}}

my env info
  Your Environment Information ---------------------------
 Operating System:          darwin
 Node Version:              12.13.1
 Framework Version:         1.60.5
 Plugin Version:            3.2.7
 SDK Version:               2.2.1
 Components Core Version:   1.1.2
 Components CLI Version:    1.4.0

A: Answering my own question
it looks like I should have imported by output name not output export name, which is bit weird and all the docs I have seen point to export name, but this is how I was able to make it work
replaced this -
authorizerId:${myAppservices-${self:provider.stage}.ExtApiGatewayAuthorizer-${self:provider.stage}}
with -
authorizerId: ${myApp-services-${self:provider.stage}.ApiGatewayAuthorizerId}

A: If you come across Trying to request a non exported variable from CloudFormation. Stack name: "myApp-services-test" Requested variable: "ExtApiGatewayAuthorizer-test"., when exporting profile i.e.,
export AWS_PROFILE=your_profile

It must be done on the terminal window where you are doing sls deploy not on  another terminal window. It is a silly mistake but I don't want anyone else waste their time around that


Q: Use sed with special character I try to use sed with special character:
sed -i -e "1i$jtempo" $file

$file is my file.
$jtempo is my variable with special character like: " or [ or (
But, when I run this script, I have this error:
sed: -e expression #1, char 17: unknown command: `"'

My file:
"desc_test":[
"id",
"name",
],

In my script bash:
jtempo=`cat myfile`

An idea ?
Thanks you !

A: $ cat f1
"desc_test":[
"id",
"name",
],
$ cat ip.txt
1
2
3

I would suggest to avoid i command and use r command which will be robust regardless of file content
$ # to insert before first line
$ cat f1 ip.txt
"desc_test":[
"id",
"name",
],
1
2
3

$ # to insert any other line number, use line_num-1
$ # for example, to insert before 2nd line, use 1r
$ # r command will read entire contents from a file
$ sed '1r f1' ip.txt
1
"desc_test":[
"id",
"name",
],
2
3


Q: Update a custom field on "Update Cart" click in WooCommerce Cart I added a custom <select> field to each product in cart page to be able to update variation, but when I change it's value and click "Update Cart", nothing updates unless quantity field has also been changed.
Is there a way to avoid this?

My code:
functions.php file:
add_filter( 'woocommerce_update_cart_action_cart_updated', 'on_action_cart_updated', 20, 1 );
function on_action_cart_updated( $cart_updated ){

    if ($cart_updated) {
        $cart_content = WC()->cart->get_cart_contents();
        $update_cart = false;
        $cart_totals  = isset( $_POST['cart'] ) ? wp_unslash( $_POST['cart'] ) : '';

        if ( ! empty( $cart_content ) && is_array( $cart_totals ) ) {

            foreach ($cart_content as $key => $item) {

                $lease_period = $cart_totals[$key]['lease'];

                if ( ! empty( $lease_period )) {
                    $cart_content[$key]['variation']['attribute_pa_lease-period'] = $lease_period;
                    $update_cart = true;
                }
            }

            if ($update_cart) {
                WC()->cart->set_cart_contents($cart_content);
            }
        }
    }
}

cart.php file:
<td class="product-lease-period" data-title="<?php esc_attr_e( 'Lease Period', 'woocommerce' ); ?>">

                                <select name="cart[<?php echo $cart_item_key ?>][lease]">

                                    <?php
                                        $lease_periods = ['6-months'=> '6 Months',
                                                            '12-months' => '12 Months',
                                                            '18-months' => '18 Months',
                                                            '24-months' => '24 Months'];

                                        foreach ($lease_periods as $key => $period) {

                                            $selected = '';

                                            if ($cart_item['variation']['attribute_pa_lease-period'] == $key) {
                                                $selected = 'selected="selected"';
                                            }

                                            echo "<option value=" . $key . " $selected>" . $period . "</option>";
                                        }
                                    ?>
                                </select>

My conclusions so far:
I believe it's because of these pieces of code inside the class-wc-form-handler.php :
// Skip product if no updated quantity was posted.
if ( ! isset( $cart_totals[ $cart_item_key ] ) || ! isset( $cart_totals[ $cart_item_key ]['qty'] ) ) {
    continue;
}

and a bit below:
if ( '' === $quantity || $quantity === $values['quantity'] ) {
    continue;
}

A: I extended the WC_Form_Handler class in my functions.php file, copied a method I needed and edited it, and gave it higher hook priority in my extended class than it's in the original class:
class WC_Form_Handler_Ext extends WC_Form_Handler {

    /**
     * Hook in method.
     */
    public static function init() {
        add_action( 'wp_loaded', array( __CLASS__, 'update_cart_action' ), 30 );
    }

    /**
     * Remove from cart/update.
     */
    public static function update_cart_action() {
        // method content edited
    }
}

WC_Form_Handler_Ext::init();

UPDATE:
To make price change after variation value in cart is updated, this function needs to be added to the functions.php
function find_matching_product_variation_id($product_id, $attributes)
{
    return (new WC_Product_Data_Store_CPT())->find_matching_product_variation(
        new WC_Product($product_id),
        $attributes
    );
}

And it should be called from the loop in functions.php I mentioned in my question this way:
$attributes = $cart_content[$key]['variation'];
$variation_id = find_matching_product_variation_id($product_id, $attributes);
$price = get_post_meta($variation_id, '_price', true);
$item['data']->set_price($price);


Q: Remove string after specific character from list using powershell I am attempting to clean up (reformat) a list of servers that has been provided to me containing the full domain name so that I can use it elsewhere. The list of servers arrive formatted like: servername.domain.com. I read the list into a variable using import-csv and remove the other columns of data not needed using the format-table command. My resulting command looks something like this:
$l=Import-Csv .\filename.csv | Format-Table TARGET

TARGET is the column name containing the server names.
When I use the following to remove the domain name portion of the server name, the resulting value is "Microsoft" repeated for each line containing the server name. I have confirmed the server names are being read into the variable correctly.
$l -replace '(.+?)\..+','$1'

The command does work if there is only one server name in the variable. I know I was able to trim the names of the servers down at one point but I think I had a brain lapse that day and just did not write down the command I used. :(
Any suggestions? My end goal is to incorporate the commands into a script for scheduled processing.

A: There are a few considerations here. Firstly, as matt has said, objects are destroyed by formatting commands. Only use them if you are trying to achieve a pretty view of the properties of objects, otherwise use select.
I would argue that you would be doing that unnecessarily: why throw away information that you might later want? I've lost count of the number of times that I've realised I can do something new and useful with the script or function I've just written, if I just expand it a little.
When you import a .csv file, you create objects with the property names of the column headings, so you can just refer to that property by name later.
Your problem with the replace command is related to the fact that you need to loop through the objects stored in $l, when there is more than one, Foreach-Object will do that.
So, for the file servers.csv:
TARGET,VALUE2,VALUE3
server1.domain.com,2,3
server2.domain.com,2,3
server3.domain.com,2,3
server4.domain.com,2,3
server5.domain.com,2,3

The import gives us a nice array of objects (nicely formatted in a table):
Import-Csv .\servers.csv | ft -a

TARGET             VALUE2 VALUE3
------             ------ ------
server1.domain.com 2      3
server2.domain.com 2      3
server3.domain.com 2      3
server4.domain.com 2      3
server5.domain.com 2      3

We can use Foreach-Object (% is the alias) to get the 'TARGET' property of each object (equivalent to each line the in file), use the 'Split' method to split on the dots of the FQDN and then take the first token of that split:
Import-Csv .\servers.csv | % {$_.TARGET.Split('.')[0]}
server1
server2
server3
server4
server5

You can import to a variable first and then pipe that to the loop if you want.
Cheers

A: ALWAYS: If you plan on doing data manipulation remove the | Format-Table TARGET as it destroys the objects.
One approach would be to extract a string array of the column TARGET which you could then process.
$l=Import-Csv .\filename.csv | Select -Expand TARGET

Assuming you have a properly formed CSV your code could be simplified. Since it does not require regex you could also do.
$l=Import-Csv .\filename.csv | Select -Expand TARGET | ForEach-Object{$_ -Split "." | Select -First 1}

$l should contain just the server names at this point. You regex is not wrong however in order to use it you would have to refine it or use it in a loop similar to how I use -split.
$l=Import-Csv .\filename.csv | Select -Expand TARGET
$l | ForEach-Object{$_ -replace '(.+?)\..+','$1'}


Q: how to parse json data recieved as a string [
    {"CityName":"Jaipur","CityId":1},
    {"CityName":"Jodhpur","CityId":2},
    {"CityName":"Ajmer","CityId":3},
    {"CityName":"Bikaner","CityId":4}

]

I want to get all the citynames and their id but i don't know how to do that. As I new to android any answer will be a great help for me..Thanks in advance

A: Try this..
Your getting response as JSONArray like below
JSON
[                                  //JSONArray  array
    {                              //JSONObject jObj
        "CityName": "Jaipur",      //optString cityName
        "CityId": 1                //optInt CityId
    },
    {
        "CityName": "Jodhpur",
        "CityId": 2
    },
    {
        "CityName": "Ajmer",
        "CityId": 3
    },
    {
        "CityName": "Bikaner",
        "CityId": 4
    }
]

Code
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
  JSONObject jObj = array.optJSONObject(i);
  String cityName = jObj.optString("CityName");
  int CityId = jObj.optInt("CityId");
  Log.v("cityName :",""+cityName);
  Log.v("CityId :",""+CityId);
}

A: try this one
JSONArray jarray   =new JSONArray(response);
 String[] cityName = new String[jarray.length()]
JSONObject jObject=null;
for(int j=0;j<jarray.length();j++){
  jObject=jarray.getJSONObject(j);
  cityName[j]=jObject.getString("CityName");
}

A: Do like this
ArrayList<String> cityname=new ArrayList<String>();

   JSONArray jsonarr=new JSONArray(string);
    for(i=0;i<jsonarr.length();i++){

    cityname.add(jsonarr.getJSONObject(i).getString("CityName"));

    }

A: Use JSON classes for parsing e.g
JSONObject mainObject = new JSONObject(Your_Sring_data);
String  CityName= mainObject .getJSONObject("CityName");
String CityId= mainObject .getJSONObject("CityId");

...

A: Try this:
JSONArray jsonArray= jsonResponse.getJSONArray("your_json_array_name");
for (int i=0; i<jsonArray.length(); i++) {
    JSONObject jsonObject= jsonArray.getJSONObject(i);
    String name = jsonObject.getString("CityName");
   String id = jsonObject.getString("CityId");
}

A: You can use json-path library it will simplifies the JSON parsing.
You can download json-path lib from here
Then add this library to your project /libs/ folder.
Then import the project name like this
import com.jayway.jsonpath.JsonPath;

Then parse your JSON data like this
JSONArray jsonData= new JSONArray(JsonPath.read(jsonStringData,"$..CityId[*]").toString());


Q: Unable to send mail to more than 200 member at at a time using php mail function Hello guy i am using php mail function to deliver my mails if i run the code locally with 5 email id then it working fine without any error but if i run the same code with more than 400 email id then it show the warning messages link
Warning: mail() [function.mail]: Could not execute mail delivery program '/usr/sbin/sendmail -t -i' in /home/sendInvite.php on line 147

i am using this code :
$sqlquery1 = "select employee from empl where sstatus != 'C'";
 $sqlmath1 = mysql_query($sqlquery1) or die("Error: (" . mysql_errno() . ") " . mysql_error());
     $cnt = mysql_num_rows($sqlmath1);
     if($cnt !="0") {
     while($query1 = mysql_fetch_array($sqlmath1))
     {
    $email1=$query1['employee'];
    $emid1=base64_encode($email1);
    $sid1 =base64_encode($sidtest);
    $email_from1 = "admin@gmail.com";
     $link1="http://www.xx.php?mid=$emid1&sid=$sid1";
    //send mail
    $emailto_web1     = $email1;
    $email_headers1   = "From: ".$email_from1;
    num_sent_web1    = 0;
    $email_message21  = "Dear Employee, \n";
    $email_message21 .= "\n";
    $email_message21 .= "If you cannot click on the URL, copy the URL and paste it on your address bar.\n";
    $email_message21 .= "\n";
    $email_message21 .= $link1."\n";
    $email_message21 .= "\n\n\n";
    $email_message21 .= "Regards,\n";
    $email_message21 .= "Admin Team. \n";

    $mail_web1 = mail($emailto_web1,$email_subject1,$email_message21,$email_headers1);
    if($mail_web1)
        {    $err = "Remainder Send Successfully";
                }
                else
                    {  $err=$email." Try Again";
                        }
      }
      } // not equal to zero condition

I dont know the exact reason why i receive this warning message, Please Post your valuble suggestion. Thanks in advance !!!

A: Use cron job for this and send mails in chunks instead of sending all mails in one time.

A: Please see the php mail function documentation:
It is worth noting that the mail() function is not suitable for larger volumes of email in a loop. This function opens and closes an SMTP socket for each email, which is not very efficient.
 For the sending of large amounts of email, see the » PEAR::Mail, and » PEAR::Mail_Queue packages.
Also, see the related questions on serverfault: https://serverfault.com/questions/67154/sending-an-email-to-about-10k-users-not-spam, where PHPlist is mentioned, along with others. And here - https://serverfault.com/questions/68357/whats-the-best-way-to-send-bulk-email,https://stackoverflow.com/questions/1543153/is-there-a-limit-when-using-php-mail-function

A: I think there is no problem with your script but its rather an installation issue with your operating system or sending mail program is poorly configured or perhaps missing. Try all possibilities, from php side its okay.

A: Your best option is to use a cron job. Doing it like this, your server will have a lot of stress. The mail() function isn't meant for a large volume of emails. It will slow done your server if your using a large amount.
This will explain how to make a cron job on your server.
Hope it helps!


Q: Caused by: io.cucumber.datatable.UndefinedDataTableTypeException: Can't convert DataTable to List I am updating cucumber version from 3x to 7x and I faced following exception:
Caused by: io.cucumber.datatable.UndefinedDataTableTypeException: Can't convert DataTable to List

There was no table entry or table row transformer registered for com.x.config
   Please consider registering a table entry or row transformer.

and code is as follows:
    @And("^configurations$")
    public void configurations(List<Config> configs) {
        initialConfigs = configs.stream().map(cfg -> Config.builder()
}

A: I found how to solve it, by adding Transformer in step definition that should be as follows:
 @DataTableType
    public Config entryTransformer(Map<String, String> row) {

        return Config.builder()
                .id(Integer.parseInt(row.get("id")))
                .active(row.get("active"))
                .build();
    }


Q: Accessing an Audio File From a Different Folder I am doing a project for my computer science class in which I am adding audio into my website. I am doing this in cloud 9. And I have a folder of different songs on a different folder. I need to be able to access the song from the higher folder. People have been saying to use this code:
    <source src="../folder/filename.mp3" type=mpeg">

But the code was given to me fro images, I have not been able to do it with a song. When I use this code I get the normal looking play button on my website, but it is grayed out. I have been able to get it to work, but only if I take the song out of the folder and put it at the same level as the file. I have also tested different audio files to see if that is the problem.

A: Use absolute site URI routing whereby your sound file address starts with a / and so indicates the path from the root of the URL.
For instance:
Your current output file is, say, www.site.com/output/file.html, and you want to load a sound from, say, www.site.com/sounds/laugh.mp3 then you simply use the /sounds/laugh.mp3 part of the address as your reference. Becauseit starts with a / this indicates it's an absolute site URL and indicates the root HTML directory, rather than a page specific url.
 <source src="/sounds/filename.mp3" type=mpeg">

If you used a relative path such as ../sounds/filename.mp3 this would break if you used it in the base folder (www.site.com/index.html) or in a deeper directory tree such as www.site.com/sounds/silly/horses.html. But the absolute path would always work (as long as the destinaton file exists and is accessible).

Tip: Make sure you've also uploaded your sound file!


Q: How to create a model instance that has a belongsTo property? var attr = DS.attr,
hasMany = DS.hasMany,
belongsTo = DS.belongsTo;

Admin.Category = DS.Model.extend({
    name: attr(),
    mstore: belongsTo('mstore')
});

console.log(mstore); // this is a PromiseObject object passed from "{{action createCategory mstore}}" tag
var newCategory = this.store.createRecord('category', {
    name: 'nn',
    mstore: mstore
});

I get an error like:
   Assertion failed: You can only add a 'mstore' record to this relationship.
How can I set a belongsTo property using a PromiseObject object? Thanks.

A: In your {{action...}} you should pass a real model, not a promise. To get a model from a promise you need to do something like this:
var myMstore;

that.store.find('mstore', mstoreId).then(function(mstore) {
  myMstore = mstore;
});