text:
Q: How to change the value of an attribute in a new XML document? I have a database where is a ton of XML file who's waiting to get update. The update would wipe ALL files in the database. Each new file would be the same as his previous except for the attribute value.
But I want to keep each attributes type that have session as value. This attribute is in each file multiple time. But, it's doesn't work for the moment: attributes doesn't update at all).

How can I change the value of an specific attribute in an new XML file identical depending of another one?

This is what I did so far...
So I decided to find a way to get the path to these attributes using this code for each file before the wipe:
List<XmlList> dBPathTypeSession = new List<XmlList>();
/*reader*/
XmlDocument doc = new XmlDocument();
doc.LoadXml(sessionType.Parameters);

XmlNode root = doc.DocumentElement;

//I think my problem come from this line below
XmlNodeList nodes = root.SelectNodes("//node()[@type='session']");

dBPathTypeSession.Add(new XmlList("b_session_type", i, nodes));//table,row,paths

The code below this line is probably not needed to answer my question, this is just more detail.

And then correct the attributes value after the update with this:
XmlDocument doc = new XmlDocument();
doc.LoadXml(sessionType.Parameters);

foreach (XmlNode node in file.Paths)//XmlList file = new XmlList();
{
    if (node.Attributes["type"].Value == "system")
    {
        node.Attributes["type"].Value = "session";
    }
}
//push to DB

The informations for every path in each file is contain in this:
//But I think this is pointless for my question
public class XmlList
{
    public XmlList(string tablePath, int filePath, XmlNodeList paths)
    {
        this.TablePath = tablePath;
        this.FilePath = filePath;
        this.Paths = paths;
    }
    public string TablePath {get; private set;}
    public int FilePath {get; private set;}
    public XmlNodeList Paths {get;set;}
}

I'm using C# 3.0(.NET framework 3.5), I MUST use XMLDocument to make it fit with everything else in the code.
Here's an example of what the XML look like before update(short version)
<Session is_hidden="false">
    <ID is_static="true">1</ID>
    <SESSIONIDX is_static="true">0</SESSIONIDX>
    <Timing>
        <FirstPresentation display_name="FirstPresentation" type="system"/>
        <Pause display_name="Pause" type="system" datatype="float"/>
        <Feedback display_name="Feedback" type="session" datatype="float"/>
        <Answer display_name="Answer" type="system" datatype="float"/>
    </Timing>
    <Balls>
        <Indexed display_name="Indexed" type="session" datatype="pos_int"/>
        <IndexingColor1 display_name="IndexingColor1" type="system" datatype="list">
            <list>
                <ListItem>RED</ListItem>
                <ListItem>BLUE</ListItem>
            </list>
        </IndexingColor1>
    </Balls>
</Session>

Here's an example of what the XML look like after update(short version)
<Session is_hidden="false">
    <ID is_static="true">1</ID>
    <SESSIONIDX is_static="true">0</SESSIONIDX>
    <Timing>
        <FirstPresentation display_name="FirstPresentation" type="session"/>//system change for session
        <Pause display_name="Pause" type="system" datatype="float"/>
        <Feedback display_name="Feedback" type="system" datatype="float"/>//session change for system
        <Answer display_name="Answer" type="system" datatype="float"/>//system stay system
    </Timing>
    <Balls>
        <Indexed display_name="Indexed" type="session" datatype="pos_int"/>//session stay session
        <IndexingColor1 display_name="IndexingColor1" type="system" datatype="list">
            <list>
                <ListItem>RED</ListItem>
                <ListItem>BLUE</ListItem>
            </list>
        </IndexingColor1>
    </Balls>
</Session>

Here's an example of what the XML of what I'm looking for:
<Session is_hidden="false">
    <ID is_static="true">1</ID>
    <SESSIONIDX is_static="true">0</SESSIONIDX>
    <Timing>
        <FirstPresentation display_name="FirstPresentation" type="session"/>//system stay session
        <Pause display_name="Pause" type="system" datatype="float"/>
        <Feedback display_name="Feedback" type="session" datatype="float"/>//session return session
        <Answer display_name="Answer" type="system" datatype="float"/>//system stay system
    </Timing>
    <Balls>
        <Indexed display_name="Indexed" type="session" datatype="pos_int"/>//session stay session
        <IndexingColor1 display_name="IndexingColor1" type="system" datatype="list">
            <list>
                <ListItem>RED</ListItem>
                <ListItem>BLUE</ListItem>
            </list>
        </IndexingColor1>
    </Balls>
</Session>

If we compare this to boolean algebra, we have this :

For x = session & y = system
before update = after update -> What we want

x = x -> x
x = y -> x
y = x -> x
y = y -> y

If you need more information just ask in comment and I will update the post.

A: The problem is that you are searching for nodes with an attribute named type with value session -- then replacing that value if the current value is system.  That's not going to work, since the value can't be both.
You must want either:
    foreach (XmlNode node in root.SelectNodes("//node()[@type='session']"))
        node.Attributes["type"].Value = "system";

or
    foreach (XmlNode node in root.SelectNodes("//node()[@type='system']"))
        node.Attributes["type"].Value = "session";

Update
If you have two XmlDocuments that have identical element hierarchies but different sets of attributes for each element, and wish to propagate some attribute information from the first to the second, you need to walk the element hierarchies and create temporary mapping tables between them.  The following does that, assuming the elements are corresponded by name, and then by order if duplicate names exist (e.g. in a list):
    static void WalkMatchingElements(XmlElement root1, XmlElement root2, Action<XmlElement, XmlElement> action)
    {
        WalkMatchingElements(root1, root2, (element) => (element.Name), action);
    }

    static void WalkMatchingElements<TKey>(XmlElement root1, XmlElement root2, Func<XmlElement, TKey> getKey, Action<XmlElement, XmlElement> action)
    {
        if (EqualityComparer<TKey>.Default.Equals(getKey(root1), getKey(root2)))
            action(root1, root2);
        var children1GroupedByName = root1.ChildNodes.OfType<XmlElement>().GroupBy(getKey);
        var children2LookupByName = root2.ChildNodes.OfType<XmlElement>().ToLookup(getKey);
        foreach (var child1group in children1GroupedByName)
        {
            var child2group = children2LookupByName[child1group.Key];
            foreach (var pair in child1group.Zip(child2group, (el1, el2) => new KeyValuePair<XmlElement, XmlElement>(el1, el2)))
                WalkMatchingElements(pair.Key, pair.Value, getKey, action);
        }
    }

And then call it like:
        var oldDoc = new XmlDocument();
        oldDoc.LoadXml(oldXml);

        var newDoc = new XmlDocument();
        newDoc.LoadXml(newXml);

        WalkMatchingElements(oldDoc.DocumentElement, newDoc.DocumentElement, (elOld, elNew) =>
            {
                var attrOld = elOld.Attributes["type"];
                if (attrOld != null && attrOld.Value == "session")
                {
                    elNew.SetAttribute("type", "system");
                }
            });

Update2 If you don't want the entire old XmlDocument in memory at once (though I don't see why not), you can built a lookup table of elements with a type attribute, indexed by path, then use that later:
    const string AttributeName = "type";

        var lookup = oldDoc.DocumentElement.DescendantsAndSelf().OfType<XmlElement>().Where(el => el.HasAttribute(AttributeName)).ToLookup(el => el.Path(), el => el.Attributes[AttributeName].Value);

        // And then later

        WalkMatchingElements(new XmlElement[] { newDoc.DocumentElement }, lookup, (el, oldValue) =>
            {
                if (oldValue != null && oldValue == "session")
                    el.SetAttribute(AttributeName, "session");
            });

    private static void WalkMatchingElements<TValue>(IEnumerable<XmlElement> elements, ILookup<string, TValue> pathLookup, Action<XmlElement, TValue> action)
    {
        var elementsByPath = elements.GroupBy(el => el.Path());
        foreach (var elementsGroup in elementsByPath)
        {
            foreach (var pair in elementsGroup.Zip(pathLookup[elementsGroup.Key], (el, value) => new KeyValuePair<XmlElement, TValue>(el, value)))
                action(pair.Key, pair.Value);
            foreach (var element in elementsGroup)
                WalkMatchingElements(element.ChildNodes.OfType<XmlElement>(), pathLookup, action);
        }
    }

You'll need the following extension methods:
public static class XmlNodeExtensions
{
    public static string Path(this XmlElement element)
    {
        if (element == null)
            throw new ArgumentNullException();
        return element.AncestorsAndSelf().OfType<XmlElement>().Reverse().Aggregate(new StringBuilder(), (sb, el) => sb.Append("/").Append(el.Name)).ToString();
    }

    public static IEnumerable<XmlNode> AncestorsAndSelf(this XmlNode node)
    {
        for (; node != null; node = node.ParentNode)
            yield return node;
    }

    public static IEnumerable<XmlNode> DescendantsAndSelf(this XmlNode root)
    {
        if (root == null)
            yield break;
        yield return root;
        foreach (var child in root.ChildNodes.Cast<XmlNode>())
            foreach (var subChild in child.DescendantsAndSelf())
                yield return subChild;
    }
}

public static class EnumerableExtensions
{
    // Back ported from .Net 4.0
    public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
    {
        if (first == null) throw new ArgumentNullException("first");
        if (second == null) throw new ArgumentNullException("second");
        if (resultSelector == null) throw new ArgumentNullException("resultSelector");
        return ZipIterator(first, second, resultSelector);
    }

    static IEnumerable<TResult> ZipIterator<TFirst, TSecond, TResult>(IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
    {
        using (IEnumerator<TFirst> e1 = first.GetEnumerator())
        using (IEnumerator<TSecond> e2 = second.GetEnumerator())
            while (e1.MoveNext() && e2.MoveNext())
                yield return resultSelector(e1.Current, e2.Current);
    }
}

(I had forgotten that Zip is not in .Net 3.5.)

A: The problem with the code in the question is the XmlNodeList:it creates a list of object that is link to the XML files. So when the files get wipe, XmlNodeList means nothing. So, changing this list of XmlNode for a list of string to these XPath would work.
XmlNodeList nodes = root.SelectNodes("//node()[@type='session']");
List<string> xPathList = new List<string>();
foreach (XmlNode node in nodes)
{
    xPathList.Add(getXPath(node));
}

dBPathTypeSession.Add(new XmlList("b_session_type", i, xPathList));//table,row,paths

Where the getXPath function is something like this:
static public string getXPath(XmlNode _xmlNode)
{
    Stack<string> xpath = new Stack<string>();

    while (_xmlNode != null)
    {
        if (_xmlNode as XmlElement != null)
            xpath.Push(_xmlNode.Name);

        _xmlNode = _xmlNode.ParentNode as XmlElement;
    }
    return string.Join("/", xpath.ToArray());
}

The writer would modify the string to XMLNode that will have the link to the good files now.
foreach (string path in file.Paths)
{
    XmlNode node = doc.SelectSingleNode(path);
    if (node.Attributes["type"].Value == "system" && node.Attributes["type"].Value != null)
    {
        node.Attributes["type"].Value = "session";
    }
}
//push to DB

The XmlList class would need to be change to take List instead of XmlNodeList


text:
Q: Is an integral itself a function or a constant? Is an integral itself a function or a constant?
I have three cases:
Q1:
Say I have $f:\mathbb R \rightarrow \mathbb R$ and $\int_a^bf(t)\, dt$. Should I write
$$
g(t)=\int_a^bf(t)\, dt \tag 1
$$
where $g:\mathbb R\rightarrow \mathbb R$. Or should I write
$$
a=\int_a^bf(t)\, dt \tag 2
$$
where $a$ is a constant, $a\in \mathbb R$.
Q2: If I have $x:\mathbb R\rightarrow \mathbb R$ and an improper integral $\int_{-\infty}^{\infty}x(t)\, dt$, should I write
$$
h(t)=\int_{-\infty}^{\infty}x(t)\, dt \tag 3
$$
where $h:\mathbb R\rightarrow \mathbb R$. Or with a constant $b\in \mathbb R$
$$
b=\int_{-\infty}^{\infty}x(t)\, dt \tag 4
$$
Q3: Also an improper integral of $y:\mathbb R\rightarrow \mathbb R$, so $\int_{-\infty}^{\infty}\lvert y(t)\rvert ^2\, dt$. Is the following correct
$$
p(x)=\int_{-\infty}^{\infty}\lvert y(t)\rvert ^2\, dt \tag 5
$$
where $p:\mathbb R\rightarrow \mathbb R$. Or with a constant $c\in\mathbb R$
$$
c=\int_{-\infty}^{\infty}\lvert y(t)\rvert ^2\, dt \tag 6
$$
Thanks!

A: Three cases:
We use the integral sign without bounds to mean the 'antiderivative' or the 'Newton integral' of a function, the function whose derivative is equal to the original function. This is a function, we usually use the same name for the argument as the integration parameter. This is sometimes called the indefinite integral, but strictly speaking is not (see below).
$$ g(x) = \int f(x) dx $$
We use the integral sign with bounds (finite or infinite), to mean the definite integral between those bounds. This is a number. As @Rahul points out in a comment, improper definite integrals (those with infinite bounds) are also numbers.
$$ a = \int_{0}^{\infty} f(x) dx $$
We use the integral sign with two bounds, one of which is a variable, to mean the integral between a fixed bound and a variable bound. This defines a function. The function's argument is the variable bound, which can't also be the integration parameter. This is the 'indefinite integral' in the strict sense. This function is probably an antiderivative of the original function, but is not defined to be one. It is a theorem that the antiderivative and the indefinite integral are the same, and holds only under certain conditions.
$$ g(t) = \int_{-1}^{t} f(x) dx $$

A: In $Q_1, Q_2$ and $Q_3$, the integrals are constants.

A: Assuming $a$ and $b$ are constants, in all three cases you've noted the integral is a constant.
It can be a function, if the function "under" the integral sign depends on $t$ and something else, or if the limits are variable. For example:

*

*$\int_a^b f(x,t)dt$ is a function of $x$.

*$\int_x^y f(t)dt$ is a function of $x$ and $y$.

*Sometimes you can have a combination, e.g. $\int_{g(x,y)}^{h(y,z)}f(x,y,z,t)dt$ is a function of $x, y, z$.

Crucially, the integral it is never a function of $t$ - $t$ is "bound" by $dt$.

A: Definite integrals as in your examples are a way to denote a number, exactly like a sum or a limit. In this sense
$$\int _a^b f(t)\,\mathrm dt$$
is a constant. The variable $t$ has no meaning outside of the integral. However, stuff like this exists:
$$g(x):=\int_a^b f(x,t)\,\mathrm dt.$$
Here the integrand depends on $x$ and $t$ but the integral is only over $t$, hence the $x$ exists outside the integral and can be used to define the function $g(x)$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL trigger if condition exists I'm trying to write an update trigger that will only update a password when a new password is set in the update statement but I'm having a terrible time trying to nail down the syntax.  This should be a no-brainer but I'm just not finding the solution.
Here's my code:
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
  IF (NEW.password <> '') THEN
        SET NEW.password = PASSWORD(NEW.password);
  END IF;
END;

I've tried:
IF (NEW.password <> NULL) THEN

IF (NEW.password) THEN

IF NEW.password <> NULL THEN

IF (NEW.password > 0) THEN

IF (NEW.password != NULL) THEN

And I'm sure many other combinations but it's just not working.  Does anyone have any insight?

A: I think you mean to update it back to the OLD password, when the NEW one is not supplied.
DROP TRIGGER IF EXISTS upd_user;

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '') THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

However, this means a user can never blank out a password.

If the password field (already encrypted) is being sent back in the update to mySQL, then it will not be null or blank, and MySQL will attempt to redo the Password() function on it. To detect this, use this code instead

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

A: Try to do...
 DELIMITER $$
        CREATE TRIGGER aumentarsalario
        BEFORE INSERT
        ON empregados
        FOR EACH ROW
        BEGIN
          if (NEW.SALARIO < 900) THEN
             set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
          END IF;
        END $$
  DELIMITER ;


text:
Q: How do I use PHP to encode a string containing quotes to make it safe for inline 'onclick'? I have a variable in a database that could potentially contain single or double quotes. When I retrieve the variable from the database, it is written with PHP into an inline "onclick" hander:
echo '
';echo ' Duplicate assignment
';

This produces HTML that looks like this in the page source:

 Duplicate assignment

However, clicking the link produces the following error in the console:

Uncaught SyntaxError: missing ) after argument list

I thought using the PHP function "htmlspecialchars" would mitigate this issue, but it doesn't seem to work.
Any help greatly appreciated.
P.S. It is not possible in this case to use a Javascript "onclick" handler - it has to be inline HTML. Also, it is not possible to ban the use of quotation marks in the variable value.

A: Try using the function:
addslashes()

EDIT: This method will take care of the quotes in the string itself, but may not be suitable if you need to retain quotes for HTML insertion. Read the docs carefully.
http://php.net/manual/en/function.addslashes.php

A: its because your Unicode (') is also being treated as '
use this

 Duplicate assignment

A: Use json_encode to convert a value to a JavaScript literal (with all necessary escaping).
Use htmlspecialchars to convert a value (such as a JavaScript program) to something safe to place in an HTML attribute value.
$id = $this_assignment['id'];
$title = $this_assignment['title'];
$url = "/assignments/$type/";

$js_id = json_encode($id);
$js_title = json_encode($title);
$js_url = json_encode($url);
$js = "a4e.duplicate_assignment($js_id, $js_title, $js_url);

$html_js = htmlspecialchars($js, ENT_QUOTES);
?>

    <a href="javascript:void(0);" onclick="<?php echo $html_js; ?>">

        Duplicate assignment

A better approach would be to use progressive enhancement and non-inline JS. You've ruled that out, but you should try to remove that restriction.
$id = $this_assignment['id'];
$title = $this_assignment['title'];
$url = "/assignments/$type/";

$html_id = htmlspecialchars($id, ENT_QUOTES);
$html_title = htmlspecialchars($title, ENT_QUOTES);
$html_url = htmlspecialchars($url, ENT_QUOTES);
?>

    <a href="<?php echo $html_url; ?>" data-title="<?php echo $html_title; ?>" data-id="<?php echo $html_id; ?>">

        Duplicate assignment

</script>


text:
Q: Passing data to custom modal dialog in Angular I've been having some issues lately trying to get a custom modal window with an carousel component functioning correctly. I'm pretty new to Angular, so I'm having issues achieving the desired effect. My goal is to receive data from a service that could have an array of images. If images are present, a glyphicon button will be displayed that will open the custom modal dialogue. I want to pass that array of images on to the modal carousel window for browsing.
As of right now, I can open the modal window, however if it does show the images, it will be the same set of images for each row regardless if it has different images associated with that row or not. Some won't even display the images at all.
catalog-list.component.html

                        {{ catalog.Catalog }}
                        {{ catalog.Description }}
                        {{ catalog.OnHand }}
                        {{ catalog.InTransit }}
                        {{ catalog.CustomerHold }}
                        {{ catalog.NetInventory }}
                        {{ catalog.Scheduled }}

 0'>

                        <cm-image-gallery [gallery]='catalog.Images'></cm-image-gallery>

image-gallery.component.ts
import { Component, Input } from "@angular/core";
import { IGallery } from "./image-gallery";
import { OnInit } from "@angular/core/src/metadata/lifecycle_hooks";

@Component({
    selector: 'cm-image-gallery',
    templateUrl: './image-gallery.component.html'
})
export class ImageGalleryComponent implements OnInit{
    @Input() gallery: IGallery[];

    ngOnInit(){
        console.log(this.gallery);
    }
}

image-gallery.component.html

Catalog Viewer

            <button type="button" class="close" data-dismiss="modal" title="Close"> </button>

                        Previous

                        Next

            <button class="btn-sm close" type="button" data-dismiss="modal">Close</button>

A: I ended up solving this particular issue by creating an output in catalog-list.component.ts
catalog-list.component.ts
@Output() //used so that the image gallery gets the catalog the user selects in the table
selectedCatalog: EventEmitter<ICatalog> = new EventEmitter<ICatalog>();

setCurrentCatalog(catalog: ICatalog) : void{
    this.selectedCatalog.emit(catalog);
}

And then listening for it in image-gallery.component.ts
image-gallery.component.ts
constructor(private _catalogList : CatalogListComponent){
    this._catalogList.selectedCatalogGallery
        .subscribe(catalogs => {
            this.gallery = catalogs.Images;
        },
        error => console.log(error));
}

This ensures that the image gallery is getting the correct row object instead of always defaulting to the first row.


text:
Q: Most efficient way to retrieve pixel distributions inside many polygones (custom zonal stats) I want to get the distribution of pixels from a 1 band raster that fall in each polygon of a shapefile to proceed to some statistics. I guess a zonal statistics does it in some kind of way but I need other statitsics that the ones provided by the tools.
Specifically, I want to sort the pixels inside the polygons and retrieve the 50th value (if exists).
Converting my raster to points and joining them spatially to my polygons and exporting my table for the statistical analysis would do it but I will obtain more than 80M points and I estimate that it will take more than 4 days if no issues.
Does anyone know how to perform this in a more efficient way ?

A: Convert polygons to integer raster, same cell size and extent as value raster, snap raster=v.raster. Use rastertonumyarray on both. Create dictionary. Go through both arrays using integer as key of dictionary and updating list of values from main raster. When done go through dictionary, pick associated list, sort, etc. I've done similar thing on 5000×6000 rasters, think can be done on 9000×9000


text:
Q: How to modify category tree in Magento admin? I want to add custom icon/text in category at selected place in screenshot. I don't know which file I need to edit to modify the category tree. Can anyone help me in getting out of this?

A: if you want to add a text with the category name you can just over ride the class Mage_Adminhtml_Block_Catalog_Category_Tree.
In that class you can find a function like
public function buildNodeName($node)
{
    $result = $this->escapeHtml($node->getName());
    if ($this->_withProductCount) {
         $result .= ' (' . $node->getProductCount() . ')';
    }
    return $result;
}

You can just add your text like.
$result.='Your Text';


text:
Q: Site resilience with MSSQL Servers What I'm trying to do is set up a failover system between two MS SQL Servers. It needs to be active/passive, and allow weighting (so Site 1 is preferable, before Site 2).
I've done this between our sites before, but on Linux, using Keepalived and HAProxy to use a VIP and proxy MySQL connections.
I'm looking for something similar that can run on Windows servers, and provide roughly the same functionality.
Bonuses would be to prevent flapping.
Application wise, we are using mostly ODBC connections stored on each server, so I could always do it from the application level. However, our subsystems can rely on each other, so we'd need everything to switch at once.
Environment

*

*Windows Server 2003

*MSSQL 2005

*Two machines

*On different sites, with a 10-20ms routed link between the subnets.

A: SQL doesn't have a mechanism for this natively.  The only way to do this that I know of would be to set up merge replication between the 2 SQL servers and round robin DNS requests to each.


text:
Q: Search through column for multiple matching integers I'm trying to search through a database with a column that can have one or more integer values, to match one or more given integers. I just started using Python and Pandas.
The integers in the database has a '-' in between For example
--------------------------------------------------
| Customer 1     | 1143              |
--------------------------------------------------
| Customer 2     |1124-1123|
--------------------------------------------------
| Customer 3     |1254-1234-1642      |
--------------------------------------------------

I can't quite figure out how to parse the values, and at the same time make it so that order doesn't matter too. So let's say I have 1123 and 1124 as the two integers to find a match to, end goal here is to display the customer with the matching integers.
Any input would be greatly appreciated!

A: Consider the following approach:
In [174]: x
Out[174]:
         name              id
0  Customer 1            1143
1  Customer 2       1124-1123
2  Customer 3  1254-1234-1642

In [175]: pat = '|'.join(['1123', '1642'])

In [176]: x[x['id'].str.contains(pat)]
Out[176]:
         name              id
1  Customer 2       1124-1123
2  Customer 3  1254-1234-1642

In [177]: pat
Out[177]: '1123|1642'

A: You can convert to sets and use set logic then filter
s = set(['1123', '1642'])
df[df.id.str.split('-').apply(set) & s]

         name              id
1  Customer 2       1124-1123
2  Customer 3  1254-1234-1642

pd.Series.str.split creates a list of strings split on '-'
df.id.str.split('-')

0                [1143]
1          [1124, 1123]
2    [1254, 1234, 1642]
Name: id, dtype: object

Using pd.Series.apply with set converts those lists to sets
0                {1143}
1          {1123, 1124}
2    {1642, 1254, 1234}
Name: id, dtype: object

Then using & in a set context performs an element by element intersection
df.id.str.split('-').apply(set) & s

0    False
1     True
2     True
Name: id, dtype: bool

Which we then use to filter.

A: Based on your clarification, I believe a full regex match is necessary. You can use df.str.match with a regex pattern:
numbers = ['1124', '1123']
df

     Customer          Number
0  Customer 1            1143
1  Customer 2       1124-1123
2  Customer 3  1254-1234-1642
3  Customer 4  1124-1123-1125

df[df['Number'].str.match(f'{"-".join(numbers)}$')]

     Customer     Number
1  Customer 2  1124-1123

A: try using pd.series.contains()
df1 = df[df['column_name'].str.contains('1123')]

if you want to find for 1123 and 1124 use join
list1 =['1123','1124']
listRegex = '|'.join(list1)
df1 = df[df['column_name'].str.contains(listRegex)]

A: You could parse the string using regex. I made an example using c# which you should have no problem porting over to python.
        Regex regex = new Regex("[1-9]+");

        string example = "1221-1231-4311-1236";

        Match match = regex.Match(example);

        while (match.Success)
        {
            Console.WriteLine(match);
            match = match.NextMatch();
        }

Output is posted below, which you can do anything with.


text:
Q: FluentAssertions Equivalency Comparison Behavior and IMemberInfo I am using FluentAssertions (v6.2.0) to test API's that return table-like data. I want to change comparison behavior for one of the field, and tried to use method described in documentation.
orderDto.Should().BeEquivalentTo(order, options => options
    .Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation, 1.Seconds()))
    .When(info => info.Name == "Date"));

The issue is that IMemberInfo class that When extension method is expecting doesn't have Name property, it has property called Path. Was Name replaced by Path and this is a typo in documentation, or do I need to import another namespace to use Name property?

A: From a quick look at the FluentAssertions source code, I'm seeing that the info argument is of type IObjectInfo and it has a Path property. A quick test with this code shows the Path property working as you would expect:
void Main()
{
    var orderDto = new OrderDto { Date = DateTime.Now };
    var order = new Order { Date = DateTime.Now };
    //var order = new Order { Date = DateTime.Now.Subtract(TimeSpan.FromSeconds(2)) };

    orderDto.Should().BeEquivalentTo(order, options => options
        .Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation, 1.Seconds()))
        .When(info => info.Path == "Date"));
}

class OrderDto {
    public DateTime Date { get; set; }
}

class Order
{
    public DateTime Date { get; set; }
}

In fact, the FluentAssertions test for that code also uses path. See https://github.com/fluentassertions/fluentassertions/blob/master/Tests/FluentAssertions.Specs/Equivalency/ExtensibilityRelatedEquivalencySpecs.cs#L394
There is also an IMethodInfo interface with both Name and Path properties. However, that is used by the Include* and Exclude* methods.
So it appears to be a documentation bug.


text:
Q: Como salvar os dados em um arquivo? Estou consumindo uma API do Facebook business e preciso colocar os dados em um arquivo TXT ou CSV.
Quando imprimo o resultado com print, sai como esperado, mas não consigo colocar as linhas em um arquivo txt.
Saída com print:
[Anhanguera] - VALINHOS/SP - Saldo : R$ 5755
[Anhanguera] - PASSO FUNDO/RS - Saldo : R$ 58157
[Anhanguera] - CAXIAS DO SUL/RS - Saldo : R$ 108708
[Anhanguera] - JARAGUA DO SUL/SC - Saldo : R$ 117410
[Anhanguera] - RIO CLARO/SP - Saldo : R$ 36804
[Pitagoras] - JABOATAO DOS GUARARAPES/PE - Saldo : R$ 40744
[Pitagoras] - IRECE/BA - Saldo : R$ 59997
[Anhanguera] - SAO JOSE DO RIO PRETO/SP - Saldo : R$ 34776
[Pitagoras] - JUIZ DE FORA/MG - Saldo : R$ 45540
[Anhanguera] - MANAUS/AM - Saldo : R$ 118413
[Anhanguera] - ERECHIM/RS - Saldo : R$ 50044
[Anhanguera] - NOVA IGUACU/RJ - Saldo : R$ 103828
[Anhanguera] - FRANCA/SP - Saldo : R$ 18543
[Pitagoras] - ITABIRA/MG - Saldo : R$ 118318
[Anhanguera] - ASSIS/SP - Saldo : R$ 47249

Preciso por esses dados em um aquivo TXT bem como está apresentado.

A: Para solucionar este problema, você deve criar um arquivo, e escrever a saída do seu print no arquivo. Em meu exemplo inputdata seria o seu array de dados
with open('data.txt', 'w') as f:
    for linha in inputdata:
        f.write(linha)

Neste exemplo o parâmetro w quer dizer que estamos criando um arquivo e desejamos escrever dados.
Recomendo a documentação para entender como funciona o comando open, e verificar outras opções para escrever em arquivo.
Documentação open


text:
Q: Is $x \sim y$ iff $y - x \in \mathbb Q$ an equivalence relation? I can easily show that the relation $x\sim y$ iff $y - x \in \mathbb Q$ and $x,y \in (0,1]$ is an equivalence relation since it is reflexive (the number zero is rational), symmetric (the negative of a rational number is rational) and transitive as the sum/difference of two rational numbers is rational but I get stuck in what follows. Specifically, I know that equivalence relations induce mutually disjoint equivalence classes but I can't verify that here. My silly counterexample is that if $x=\frac{1}{3}$ then clearly $y=\frac{3}{3}$ is in the equivalence class but $y=\frac{3}{3}$ is also in the equivalence class of $x=\frac{2}{3}$ as that difference too is rational. My question therefore is, what have I misunderstood here? Thank you.

A: The numbers $\frac{1}{3}, \frac{2}{3}, \frac{3}{3}$ are all in the same equivalence class, they are all equivalent to each other.


text:
Q: to make a slide with navigation arrow I'm having trouble creating a navigation control to a slide.
the problem is the arrow to return to previous.
Demo: http://jsfiddle.net/joseferreira/ka47jo7z/10/
var gridwidth = $("#special").width();
        var itens = $("#special .grid-special").length;
        var b = 0;

        $(".hidden-grid").css("width", gridwidth * itens);

        var animate = function () {
            $(".hidden-grid").stop().animate({
                marginLeft: -b * gridwidth
            }, {
                duration: 1000,
                specialEasing: {
                    marginLeft: "linear",
                }
            });
        }

        $(".next, .prev").click(function (e) {
            e.preventDefault();
            if ($(this).hasClass('next')) {
                b++;
                console.log(b);
                if (b < itens) {
                    animate();
                } else {
                    alert('end');
                }
            } else {
                b--;
                console.log(b);
                if (b >= 0) {
                    animate();
                } else {
                    alert('begin');
                }
            }
        });

A: You can do even better using 2dtransform (jquery.transform2d.js) plugin. I have created a working example on fiddle.
I have also animated the navigation arrows using CSS transitions.
To better understand CSS Transforms Matrix, visit this page.

A: Check this fiddle
Ive edited the JS such that if value of b becomes negative ,i incremented b after showing the alert and for the next button i've decremented b after showing the alert..Thus the problem is solved for both the buttons.
JS
$(".next, .prev").click(function(e) {
            e.preventDefault();
            if ($(this).hasClass('next')) {
                b++;
                console.log(b);
                if (b < itens) {
                    animate();
                } else {
                    alert('chegou no fim');
                    b--;
                }
            } else {
                b--;
                console.log(b);

                if (b >= 0) {
                    animate();
                }else{

                    alert('voltou para o inicio');
                    b++;

                }
            }
        });


text:
Q: "Quite" American vs British English In looking at the answers for this question, Using "quite" with a noun, it occurred to me that "quite," although having a dictionary definition, might be used differently by AmE and BrE speakers such that it is not correct to speak about "the correct" use of "quite."
Case in point, WS2's example sentence:

There were quite a few hundred at the gathering

to my ear (AmE) sounds "wrong," but in the UK this might be everyday usage.
Also the following:

There were quite 50 people at the house

is something I would express using about / actually / around instead of quite.

*

*Is there a significant usage difference between BrE and AmE usage of "quite?"

This could be viewed as "opinion based" but perhaps there is an objective answer.

A: Mari-Lou A asked Dan if he could provide dated evidence of a usage of 'quite' in the form: _'..quite 50 people.'   Here are a couple.
From 'The Missionary Herald at Home and Abroad Vol 51 from 1855:

http://preview.tinyurl.com/ojz24nf
And James Fennimore Cooper's 'Wynadotte' from 1800:

http://preview.tinyurl.com/or7wonw
My own little theory is that 'quite' is derived from 'quit' (which the OED happily asserts without further comment), and that 'quit' in its original Latin sense was a balancing or restoring of order to accounts or arrangements, either by keeping them in balance, or in closing them.  Hence in former times to say 'quit' was to refer to some ledger or accounting system.  'Not quit fifty' simply means it hasn't added up to fifty, while 'quit fifty' meant that it had added up to fifty.  Since the latter assertion usually  didn't need confirmation or reinforcement the use of 'quit' or 'quite' wasn't called for, but if one was addressing a doubting audience one would say, 'Yes, quit fifty acres!', meaning 'Yes, and I've checked!'.

A: I (UK) use quite a to qualify magnitude in two simple but contradictory ways (so British!) depending on emphasis -
There were quite a few people there (i.e. there were more people than expected).
There were quite a few people there (i.e. you are (tactfully) suggesting that the turnout was disappointing).
I also use quite to underline the intensity of extreme adjectives -
He was quite the best pianist I have heard;
the jugglers were quite fantastic;
quite extraordinary, the way he behaved ...
The second example in the OP  ...quite 50 people ... is close to my second usage, although this way of using quite (with numbers) sounds dated to my ears.  Nevertheless the meaning is clear - there were easily 50 people and possibly quite a few more.


text:
Q: Netty Deployment Process Can i ask the reason why i cant deploy netty 3.6.1.final on Eclipse
And the Version i download is netty-3.6.1.Final-dist.tar.bz2
As i have follow this in pom.xml in dependencies tab and i cant resolve the error
<dependency>
  <groupId>io.netty</groupId>
  <artifactId>netty</artifactId>
  <version>3.6.1.Final-dist</version>
  <scope>compile</scope>
</dependency>

The step i follow is https://netty.io/Main/Downloads

A: The file is supposed to be downloaded from maven website, not netty.io, don't put -dist in your version.
This works for me
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty</artifactId>
    <version>3.5.11.Final</version>
</dependency>

And then you Run As pom.xml in Eclipse using Maven plugin.

A: Try setting the dependency as:
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty</artifactId>
    <version>3.5.11.Final</version>
</dependency>

As suggested by Nikolay.
Then go to the project root and run from the command line: mvn compile. That should download your dependency. Then refresh eclipse project and you should be good.
Otherwise, please provide more specific information about the error.


text:
Q: Why can I use a service without importing its provider module? I am trying to work myself into how multiple NgModules in an angular application work together, especially I am trying to understand how to properly import a SharedModule that provides commonly used services, into lazily loaded feature modules.
Step by step:

*

*I create a new angular app: ng new playground --routing

*I create a SharedModule which is meant to provide services and commonly used declarables: ng generate module shared

*I create a service inside the shared module: ng generate service shared/foo

*Now I have a FooService inside my SharedModule's directory, but I want the service to be provided by the SharedModule. So, I change the @Injectable annotation to:
@Injectable({
    providedIn: SharedModule
})

*Because I want to keep my AppModule and its service injector as clean as possible (in the real world later, I will also be using a CoreModule but that's not the scope of my question so let's get back on track)

*Now, I want to add a new feature, so I generate a new FeatureModule that I want to load lazily: ng generate module feature --routing

*Now, I have a FeatureModule

*Let's lazy-load the feature module by adding a route to the AppRoutingModule:
const routes: Routes = [
  {
    path: 'feature',
    loadChildren: './feature/feature.module#FeatureModule'
  }
];

*I assume that somewhere in the AppModule's template, I have a <router-outlet> and a routerLink that navigates to /feature.

*In the FeatureModule, we still have to generate a component that we want to show when navigating there: ng generate component feature/start

*To make my new StartComponent the initial component that is showed when routing to my FeatureModule, I will adjust the routes in the FeatureRoutingModule:
const routes: Routes = [{
  path: '',
  component: StartComponent
}];

*Now, I want to use my FooService, that I added to the SharedModule, inside my StartComponent. So I inject it there.
export class StartComponent implements OnInit {

  constructor(private foo: FooService) { }

  ngOnInit() {
  }

}

*ng serve

*Navigate to the FeatureModule and see a runtime error! That's what I expected, because I did not import the SharedModule in the FeatureModule, so the injector does not know the FooService.

*So far so good, let's now come to the main point of my question:

*I will create one more module, that is not lazily loaded, which is going to be the CoreModule. To keep the AppModule as clean and as small as possible, I will implement the initial app in the CoreModule. ng generate module core

*Of course we also need some component in the CoreModule: ng generate component core/core-main

*Now, I also want to use the FooService in my new CoreMainComponent. So, let's also inject it there:
export class CoreMainComponent implements OnInit {

  constructor(private foo: FooService) { }

  ngOnInit() {
  }

}

*This time I will not forget to import the SharedModule inside my CoreModule. But remember I still forgot and did not import SharedModule in FeatureModule. Of course I have to use the CoreMainComponent somewhere, so I export it. So this is the new CoreModule decoration:
@NgModule({
  imports: [
    CommonModule,
    SharedModule
  ],
  declarations: [CoreMainComponent],
  exports: [CoreMainComponent]
})
export class CoreModule { }

*Also import the CoreModule into the AppModule and add an <app-core-main></app-core-main> in the AppModule's template.

*ng serve

*My expectation: As soon as I click the link to lazily load and navigate to my FeatureModule, I would still expect a runtime error. The CoreModule imports the SharedModule, but the FeatureModule doesn't. But in both modules, the FooService is used.

*In fact, it works. I can use the component from the feature module without any errors. So the injector seems to know the FooService even in the FeatureModule, although I did not import it there. I would have expected it to fail

*Can someone help me out to understand why this works?

A: This is how it is supposed to work, whenever you import any non-lazy-loaded module in your AppModule then the services of that non-lazy loaded module are available throughout the app.
The reason besides this, in Angular Parent and child module, share the same Injector!. But in the case of the FeatureModule (lazy loaded module), they have their own injector so any service provided in the lazy loaded module is only available to that module.
In your case, you can say that CoreModule is a child module for the AppModule and in turns SharedModule is a child of CoreModule since both are non-lazy loaded module that's why your FooService is available in FeatureModule automatically.


text:
Q: Time Delay for deck cards I am trying to create a deck game in Java. I want to show four cards, one after another, then wait for a few seconds and display another four cards, and so on. I created the code below, but card number #4 does not show at all. For example, it displays 3 cards then waits for a few seconds, then it displays other 3 cards.
First part of code:
class ButtonListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        int hideCount = 0;
        addFirstCenterLabel();
        addSecondCenterLabel();
        addThirdCenterLabel();
        addForthCenterLabel();
        for (int i = 0 ; i < 32 ; i++) {
            if (button[i] == e.getSource()) {
                if (button[i] == button[0] || button[i] == button[1] ||
                    button[i] == button[2] || button[i] == button[3] ||
                    button[i] == button[4] || button[i] == button[20] ||
                    button[i] == button[21] || button[i] == button[22]) {
                    southPanelbutton.remove(button[i]);
                    southPanelbutton.validate();
                    southPanelbutton.repaint();

                    labelThirdCenter.setIcon(showCard[i]);

                }
            }
            if (button[i] == e.getSource()) {
                if (button[i] == button[5] || button[i] == button[6] ||
                    button[i] == button[7] || button[i] == button[8] ||
                    button[i] == button[9] || button[i] == button[23] ||
                    button[i] == button[24] || button[i] == button[25]) {
                    eastPanelbutton.remove(button[i]);
                    eastPanelbutton.validate();
                    eastPanelbutton.repaint();

                    labelForthCenter.setIcon(showCard[i]);
                }
            }
            if (button[i] == e.getSource()) {
                if (button[i] == button[10] || button[i] == button[11] ||
                    button[i] == button[12] || button[i] == button[13] ||
                    button[i] == button[14] || button[i] == button[26] ||
                    button[i] == button[27] || button[i] == button[28]) {
                    northPanelbutton.remove(button[i]);
                    northPanelbutton.validate();
                    northPanelbutton.repaint();

                    labelSecondCenter.setIcon(showCard[i]);
                }
            }
            if (button[i] == e.getSource()) {
                if (button[i] == button[15] || button[i] == button[16] ||
                    button[i] == button[17] || button[i] == button[18] ||
                    button[i] == button[19] || button[i] == button[29] ||
                    button[i] == button[30] || button[i] == button[31]) {
                    westPanelbutton.remove(button[i]);
                    westPanelbutton.validate();
                    westPanelbutton.repaint();
                    labelFirstCenter.setIcon(showCard[i]);
                    hideCount++;
                }
            }
            if (button[i] == e.getSource()) {
                if (button[i] == button[15] || button[i] == button[16] ||
                    button[i] == button[17] || button[i] == button[18] ||
                    button[i] == button[19] || button[i] == button[29] ||
                    button[i] == button[30] || button[i] == button[31]) {
                    hideCount++;
                    timeDelay();
                    if (hideCount == 1 || hideCount == 2 || hideCount == 3 ||
                        hideCount == 4 || hideCount == 5 || hideCount == 6 ||
                        hideCount == 7 || hideCount == 8) {
                        hideCards();
                    }
                }
            }
        }
    }
}

Second part of code:
public void addFirstCenterLabel() {
    // centerPanelLabel.add(labelFirstCenter);
    // centerPanel.add(centerPanelLabel);
    // down table
    centerPanel.setLayout(new GridBagLayout());
    c.gridx = 1;
    c.gridy = 3;
    centerPanel.add(labelThirdCenter, c);
    add(centerPanel);
}

public void addSecondCenterLabel() {
    // centerPanelLabel.add(labelSecondCenter);
    // centerPanel.add(centerPanelLabel);
    // right table
    c.gridx = 2;
    c.gridy = 1;
    centerPanel.add(labelForthCenter, c);
    add(centerPanel);
}

public void addThirdCenterLabel() {
    // centerPanelLabel.add(labelThirdCenter);
    // centerPanel.add(centerPanelLabel);
    // top label
    c.gridx = 1;
    c.gridy = 0;
    centerPanel.add(labelSecondCenter, c);
    add(centerPanel);
}

public void addForthCenterLabel() {
    // centerPanelLabel.add(labelForthCenter);
    // centerPanel.add(centerPanelLabel);

    // left table
    c.gridx = 0;
    c.gridy = 1;
    centerPanel.add(labelFirstCenter, c);
    add(centerPanel);

    // to count the round of the game. each four cards count as 1.
    for (int j = 0 ; j <= 7 ; j++) {
        if (rounds[j] == 0) {
            rounds[j] = 1;
            break;
        }
    }
}

Third part of code:
public void hideCards() {
    for (int j = 0 ; j <= 7 ; j++) {
        // System.out.println(rounds[j]);
        // if the round ==1, make the four cards unvisible
        if (rounds[j] == 1) {
            labelThirdCenter.setIcon(emptyCard[0]);
            labelForthCenter.setIcon(emptyCard[0]);
            labelSecondCenter.setIcon(emptyCard[0]);
            labelFirstCenter.setIcon(emptyCard[0]);
        }
    }
}

public void timeDelay() {
    try {
        Thread.sleep(2500); // one second
    }
    catch (InterruptedException e) {
        throw new RuntimeException("Don't know how to handle this", e);
    }
}

A: Calling Thread.sleep on the UI thread is not a good idea. It will disable all UI updates while the thread is sleeping.
I did not check in detail but it seems that the drawing of card 4 is scheduled, but not yet executed when the thread goes to sleep.


text:
Q: End date must be equal and greater than start selected date in boostrap Requirements - End date must be equal and greater then start selected start date in boostrap datepicker and before selected start date disable.
Problem - its possible in jquery date but I want to know how to make in boostrap date.
my boostrap code is
 $('#start_date').datepicker({autoclose: true,startDate: new Date()});
 $('#end_date').datepicker({autoclose: true,startDate: new Date()});

for reference check jquery code
Fiddle
Note - I want exact implemention of this picker in bootstrap
Can anyone help me?

A: Please check out this JSFiddle demo. I have placed the code below that uses bootstrap datepicker.
$(".from_date").datepicker({
  format: 'yyyy-mm-dd',
  autoclose: true,
}).on('changeDate', function (selected) {
    var startDate = new Date(selected.date.valueOf());
    $('.to_date').datepicker('setStartDate', startDate);
}).on('clearDate', function (selected) {
    $('.to_date').datepicker('setStartDate', null);
});

$(".to_date").datepicker({
   format: 'yyyy-mm-dd',
   autoclose: true,
}).on('changeDate', function (selected) {
   var endDate = new Date(selected.date.valueOf());
   $('.from_date').datepicker('setEndDate', endDate);
}).on('clearDate', function (selected) {
   $('.from_date').datepicker('setEndDate', null);
});


text:
Q: How to scroll down an element on page I would like to scrape names of companies from https://justjoin.it/, however my scraper has a problem with page scrolling. I usually use the following method to scroll down page:
driver.execute_script("window.scrollTo(0, x)")

Unfortunately, on this page execute_script method doesn't work.
I tried also to manipulate the element with table od names by send_keys method, but my script raises error:
elem = driver.find_element_by_xpath('//*[@id="root"]/div[2]/div[1]/div/div[2]/div[1]/div')
elem.send_keys(Keys.END)

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

Does anyone have an idea how to handle with this?

A: Try this
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")

A: As you wrote, you first have to click on the element with the list of jobs offers and after that scroll to the desired element.
The scrolling will work fine in this case


text:
Q: Mocking the return-value of a helper method I'm trying to test this segment of code using Mockito
if (writeToDisk(filename, byteArray)){
    return "URI1"
} else {
    return "URI2"
}

Since that writeToDisk is intended to be run on a unix server, so using a buffered+fileWriter it writes to "/tmp/upload".
The issue is that i'm writing unit tests on a windows machine, and writeToDisk always returns false, because java cannot find "/tmp/upload on windows.
Is there any way I can mock the result of writeToDisk, a pacakge private method?
This is what writeToDisk does:
boolean writeToDisk(String filename, byte[] data){
    boolean writeSuccessful = false;
    try (BufferedWriter writer = new BufferedWriter(new FileWriter("/tmp/upload"+ filename"))){
        for (byte current : data){
            out.write(current);
        }
        writeSuccessful =true;
    } catch (IOException e) {
        LOG.debug(e);
    }
    return writeSuccessful;
}

A: The real answer is here:
try (BufferedWriter writer = new BufferedWriter(new FileWriter("/tmp/upload"+ filename"))){

You are hardcoding a ton of things here, like that (OS specific) path, and the exact kind of writer. That makes this client (that only wants to write stuff somewhere) extremely dependent on all these aspects. Thus it becomes really hard to test!
You could easily turn all these aspects into some sort of service, where you only go:
try (Writer writer = service.getWriterFor(filename))

(or something alike, just giving some inspiration here)
That service you could easily mock, directly enabling you to unit that this code as well.
It would be just a very small abstraction (probably some @FunctionalInterface, that can be initialised in the production with a nice lambda or method reference).

A: One of the advantages of unit testing is that it forces you to improve on your design.
So yes, as suggested by other people, you need to add dependency injection.
I would suggest that you create a class named FileCreator and give it a method boolean createFile(byte[]) and maybe if you need it String getCreatedFileName().
As an added advantage, looks like the file name needs not be part of the call and may be converted into a property of the new class.
Another potential advantage: if your code becomes mutltithreaded, you can have a creator-per-thread, all writing to different files.


text:
Q: iOS JSON auth token request says missing parameter I have been looking all over and cannot seem to figure this out.
none of the JSON examples i see have the method name in the url so i think that may be an issue.
here is my code:
NSString *username = @"xxxx";
NSString *password = @"xxxx";
NSString *loginURL = @"http://www.xxxxxx.com/services/api/rest/json?method=xxxxxx.auth.gettoken";

NSURL *url = [NSURL URLWithString:loginURL];

NSString *JSONString = [NSString stringWithFormat:@"{\"username\":\"%@\",\"password\":\"%@\"}", username, password];

NSData *JSONBody = [JSONString dataUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *loginRequest = [[NSMutableURLRequest alloc] initWithURL:url];
loginRequest.HTTPMethod = @"POST";
loginRequest.HTTPBody = JSONBody;

NSOperationQueue *queue = [NSOperationQueue new];

[NSURLConnection sendAsynchronousRequest:loginRequest
                                   queue:queue
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){

                           // Manage the response here.
                           NSString *txt = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
                           NSLog(@"%@", txt);
                       }];

i am snooping the reuest using SquidMan and i noticed that the access log lists:
www.xxxxx.com/services/api/rest/json? - DIRECT/.....
the method name is not there, this is my first time using SquidMan for this but i would assume it would be there.
the message i get back is that parameter username is missing.
thank you in advance.

A: I found the issue, i did not write the webservice and apparently sending it the data in JSON format is wrong.
if i post the data in the format "&param=value&param2=value2" it works.
    NSString *JSONString = [NSString stringWithFormat:@"&username=%@&password=%@",
                      [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                      [password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *JSONBody = [JSONString dataUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *loginRequest = [[NSMutableURLRequest alloc] initWithURL:url];
loginRequest.HTTPMethod = @"POST";
loginRequest.HTTPBody = JSONBody;

A: It might be because you haven't specified the Content-Type for your request, so the server doesn't know how to interpret the data. Try adding this line to your code after you allocate your loginRequest:
[loginRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

Hope that helps.


text:
Q: One To One Relationship With EF Code First - Foreign Keys Aren't Correct I am trying to create a 1 to 1 relationship between two entities where both ends are required.  They're basic entities, like this
public class EntityA
{
    public int? EntityAID {get; set;}
    public virtual EntityB EntityB {get; set;
}

public class EntityB
{
    public int? EntityBID {get; set;}
    public virtual EntityA EntityA {get; set;
}

I have an EntityTypeConfiguration object for EntityA that I use to configure the relationship.  I want entityA to be the principal in the relationship, which, if I understand this process correctly, means EntityB will have a foreign key to EntityA in its database table.  Here is my configuratoin statement
HasRequired(e=>e.EntityB).WithRequiredPrincipal(e=>e.EntityA);

I am updating my database with Code First Migration.  When I generate the migration that will setup this relationship, the migration is correctly identifying the fact it needs to put a foreign key on the table for EntityB, however it is creating the foreign key to the table for EntityA with the primary key for EntityB, like this:
.ForeignKey("dbo.TableForEntityB", t => t.EntityBID)

It should be using the ID for EntityA as the foreign key.
Does anybody see what I'm doing wrong?  I'm stumped.  I've tried using WithRequiredDependent, and all that does is create an identical situation on TableForEntityA.
Thanks.

A: I am doing guess work here but I think the foreign key being created is not on primary key for EntityB table as well. EntityBID in the EntityB class is not the primary key for EntityB obviously because you are specifying it as a Nullable type, so what is it?

A: This stemmed from my misunderstanding of the one to one relationship as implemented by EF.  I read up and found out that EF used a shared primary key relationship when making one to one relatoinships.  So I changed EntityB to look like this:
public class EntityB
{
    public int? EntityAID {get; set;}
    public virtual EntityA EntityA {get; set;
}

And then configured the relationship like this:
HasRequired(c => c.EntityA).WithRequiredDependent(p => p.EntityB);
when configuring EntityB.


text:
Q: Creating a web shortcut on user desktop programmatically There are quite a few resources for programmatically creating .lnk type shortcuts to files and programs on the desktop but I'm wondering how to create a shortcut to a web URL.
From what I can gather, the web URL shortcut is a text file ending in .URL and contains a ini-like definition such as:
[InternetShortcut]
URL=http://www.google.com/

However, it's not enough to just create the file, it seems you also need to change its meta URL properties to include the same link.
Any idea how to create these?
Any sample code from .Net/Perl/batch is welcome.

A: You can create .lnk shortcuts to any URI, including web addresses.  Just create the shortcut and make the target your web address instead of a file location.
See this other question for how to do it programmatically:
Creating application shortcut in a directory


text:
Q: Count and column name in same query My query
SELECT COUNT(DISTINCT alloc.[code4]) AS countcode4,code4, table2.itemid  as tbitemid2
   FROM table1,table 2
WHERE table1.id=table2.id
GROUP BY code4, tbitemid2

I want the query to give me the count and return only 1 instance of 'code4'
How do I do this?
Thanks
Mithil

A: Remove code4] from thegroup by`, and use an aggregation functions:
SELECT COUNT(DISTINCT alloc.[code4]) AS countcode4, min(code4) as code4,
       table2.itemid  as tbitemid2
FROM table1 join
     table2
     on table1.id = table2.id
GROUP BY tbitemid2;

I don't know what alloc is; it is from your sample query.


text:
Q: Select a value in a Django Query I've a Django Query:-
obj = ABC.objects.filter(column1 = value)
a_list = []
for x in obj:
   a_list.append(x.column2)

I want to fetch the list of values of column2 in one go., ie dont want to use the for loop. Is there any 1 straight forward query for this?

A: ABC.objects.filter(column1=value).values_list('column2', flat=True)

A: https://docs.djangoproject.com/en/1.6/ref/models/querysets/#values-list
If you don't pass any values to values_list(), it will return all the fields in the model, in the order they were declared.
Note that this method returns a ValuesListQuerySet. This class behaves like a list. Most of the time this is enough, but if you require an actual Python list object, you can simply call list() on it, which will evaluate the queryset.


text:
Q: How to update GUI timer before long-run code starts? Program is about counting words in txt files.
I have two forms. Form1 is about selecting files and words. Those data im passing to form2 where im starting GUI timer and algorithm for counting words. But algorithm is executed faster than GUI timer loaded.
private void Form2_Load(object sender, EventArgs e)
{
    CountWords();
}

Form2 class

A: Instead of blocking the UI Thread with CountWords, run this method on a background thread using the Threadpool
    private void Form2_Load(object sender, EventArgs e)
    {
        ThreadPool.QueueUserWorkItem(
            new WaitCallback(CountWords));
    }

Then, make sure to marshal ANY calls to UI controls back to the UI thread that you make from the background thread:
        foreach (KeyValuePair<string, int> word in words)
        {
            // Need to marshal this back onto the UI thread
            var itemToAdd = word.Key + " " + word.Value + "x";
            this.BeginInvoke(new Action<string>(AddItemToListView), itemToAdd);
        }

And then our AddItemToListView method will add the item on the UI thread:
    private void AddItemToListView(string item)
    {
        listView1.Items.Add(item);
    }


text:
Q: Best methods to reference a user function in a macro Afternoon,
I currently have this User Function saved:
Function AlphaNumericOnly(strSource As String) As String
    Dim i As Integer
    Dim strResult As String

    For i = 1 To Len(strSource)
        Select Case Asc(Mid(strSource, i, 1))
            Case 48 To 57, 65 To 90, 97 To 122: 'include 32 if you want to include space
                strResult = strResult & Mid(strSource, i, 1)
        End Select
    Next
    AlphaNumericOnly = strResult
End Function

I call this User Function in some macros that I run (checking that it is open in the macro). The issue I'm having is when I need to share a macro that references this with another user.
I could of course copy the User Function and send that along with a copy of the macro, they could then save it locally and adjust the macro to check their local copy is open. But this seems quite long winded.
Could anybody offer any suggestions? I am wondering if I could somehow embed the User Function in the macro, or store it centrally some how. Some web searching and asking around has drawn a blank on this one.
Thank you.
Please see the complete macro along with the user function at the end:
Option Explicit
Public Const csFORMULA = "=concatenate(""AGSBIS"",IF(I2=0,"""",CONCATENATE(UPPER(AlphaNumericOnly(LEFT(I2,3))),UPPER(AlphaNumericOnly(RIGHT(I2,3))))),IF(O2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(O2,""0"","""")))),IF(R2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(R2,""0"","""")))),IF(W2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(W2,""0"","""")))),IF(AC2=0,"""",AlphaNumericOnly(SUBSTITUTE(AC2,""0"",""""))),IF(AD2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AD2,""-"",""X""),""."",""Y""),""0"",""Z"")),IF(AF2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AF2,""-"",""X""),""."",""Y""),""0"",""Z"")),IF(AH2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AH2,""-"",""X""),""."",""Y""),""0"",""Z"")))"

Sub AgeasBIS()

    Dim lr                      As Long
    Dim cl                      As Range
    Dim Rng                     As Range
    Dim mssg                    As String
    Dim WS                      As Worksheet
    Dim SaveToDirectory         As String
    Dim DateFormat              As String
    Dim StatementName           As String
    Dim Organisation            As String
    Dim ErrorMessage            As String
    Dim ErrorMessageTitle       As String
    Dim CompleteMessage         As String
    Dim CompleteMessageTitle    As String
    Dim UserFunctionsLocation   As String
    Dim SaveLocation            As String

    DateFormat = Format(CStr(Now), "yyyy_mm_dd_hhmmss_")

    ErrorMessageTitle = "Invalid Date Format"
    ErrorMessage = "There are invalid date value(s) in the following cell(s). Please check these cells."

    CompleteMessageTitle = "Statement Preparation"
    CompleteMessage = "Statement preparation is complete. Your file has been saved and will be processed as part of the next scheduled upload."

    StatementName = "age_bts"
    Organisation = "BTS"

    ' save locations
    '*location of the old user function* UserFunctionsLocation = "C:\Users\user.name\AppData\Roaming\Microsoft\AddIns\UserFunctions.xla"
    SaveLocation = "S:\MI\gre_cac\statement_feeds\waiting_to_upload\"

    Set WS = ActiveSheet

        Application.ScreenUpdating = False

    Workbooks.Open Filename:=UserFunctionsLocation

'clears any formats from the sheet
    With WS
        .Cells.ClearFormats
    End With

'standardises all fonts
    With WS.Cells.Font
        .Name = "Calibri"
        .Size = 10
        .Bold = False
    End With

    With WS
'cleans all non_printable characters from the data (excluding date columns) & removes "'" & ","
'trims the insurer comments field to ensure it is a maximum of 500 characters

        lr = .Range("I" & Rows.Count).End(xlUp).Row

        Set Rng = Union(.Range("C2:AA" & lr), .Range("AD2:AO" & lr), .Range("AM2:AM" & lr))
        For Each cl In Rng
            If cl.Column = 39 Then 'column AM gets Left() truncation as well
                cl = Left(WorksheetFunction.Trim(WorksheetFunction.Clean(cl.Value)), 500)
                cl = WorksheetFunction.Substitute(cl.Value, "'", "")
                cl = WorksheetFunction.Substitute(cl.Value, ",", "")
            Else
                cl = WorksheetFunction.Trim(WorksheetFunction.Clean(cl.Value))
                cl = WorksheetFunction.Substitute(cl.Value, "'", "")
                cl = WorksheetFunction.Substitute(cl.Value, ",", "")
            End If
            Next cl

'format invoice_date, effective_date & spare_date to dd/mm/yyyy
            Union(.Range("AB1:AB" & lr), .Range("AC1:AC" & lr), .Range("AP1:AP" & lr)).NumberFormat = "dd/mm/yyyy"

'formats all numerical fields to "0.00"
            Union(.Range("AD2:AL" & lr), .Range("AO2:AO" & lr)).NumberFormat = "0.00"

'add the statement name
            Range("A2:A" & lr).FormulaR1C1 = StatementName

'add the organisation name
            Range("D2:D" & lr).FormulaR1C1 = Organisation

'adds the formula to generate the unique key (from the declared constant)

            Range("B2:B" & lr).Formula = csFORMULA
            Range("B2:B" & lr) = Range("B2:B" & lr).Value

'auto-fit all columns
    With WS
        .Columns.AutoFit
    End With

'checks that only date values as present in the invoice_date, effective_date & spare_date
            Set Rng = Union(.Range("AB2:AB" & lr), .Range("AC2:AC" & lr), .Range("AP2:AP" & lr))
            For Each cl In Rng
                If Not IsDate(cl.Value) And Not IsEmpty(cl) Then _
                mssg = mssg & cl.Address(0, 0) & Space(4)
                Next cl

            End With

'If non-date values are found display a message box showing the cell locations
            If CBool(Len(mssg)) Then
                MsgBox (ErrorMessage & Chr(10) & Chr(10) & _
                mssg & Chr(10) & Chr(10)), vbCritical, ErrorMessageTitle

'Otherwise display a message that the statement preparation is complete
            Else
                MsgBox CompleteMessage, , CompleteMessageTitle
            End If

'save location for the .csv
SaveToDirectory = SaveLocation

'uses the set dateformat and save lovation

        WS.SaveAs SaveToDirectory & DateFormat & StatementName, xlCSV

      Set Rng = Nothing
            Set WS = Nothing
            Application.ScreenUpdating = True

         ActiveWorkbook.Close SaveChanges:=False

        End Sub

Function AlphaNumericOnly(strSource As String) As String
    Dim i As Integer
    Dim strResult As String

    For i = 1 To Len(strSource)
        Select Case Asc(Mid(strSource, i, 1))
            Case 48 To 57, 65 To 90, 97 To 122: 'include 32 if you want to include space
                strResult = strResult & Mid(strSource, i, 1)
        End Select
    Next
    AlphaNumericOnly = strResult
End Function

A: Working through the comments:
Try adding a tempValue before the Select Case
Function AlphaNumericOnly(strSource As String) As String
    Dim i As Integer
    Dim strResult As String
    Dim tempValue As Integer

    For i = 1 To Len(strSource)
        tempValue = Asc(Mid(strSource, i, 1))
        Select Case tempValue
            Case 48 To 57, 65 To 90, 97 To 122: 'include 32 if you want to include space
                strResult = strResult & Mid(strSource, i, 1)
        End Select
    Next
    AlphaNumericOnly = strResult
End Function

A: Using Regular Expressions offers a shorter more efficient solution then examining each character:
Function AlphaNumericOnly(strIn) As String
    Dim objRegex As Object
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
        .Global = True
        .ignorecase = True
        .Pattern = "[^\w]+"
        AlphaNumericOnly = .Replace(strIn, vbNullString)
    End With
End Function


text:
Q: Why Javascript else statement is not returning the value? So I am a beginner at Javascript so please help me understand this!
I was just testing out different things with if/else and prompt(), and when I wrote the codes below:

let ask = Number(prompt("Type a number"));

if (ask != NaN) {
  alert(`You typed ${ask}`);
} else {
  alert("You typed a word")
}

so the code is working well until I type in a word. when I type a number (for instance: 12) it shows "You type 12" but when I typed a word (for instance "cat"), it shows "You typed NaN". but why? I know "cat" is a NaN but why is it not showing the else statement? (You typed a word).
please help!


text:
Q: Maximizing entropy of summation of unknown distributions Let the random variable $Y = X_1+X_2$, where $X_1$ follows an unknown distribution and $Y$ has finite variance.
Assuming as measurement of normality the entropy, is it correct to support that the entropy of $Y$ is maximized if and only if $X_2$ follows the normal distribution?

A: I interpret the problem as follows:

Let $Y=X_1+X_2$, where $X_1$  and $X_2$ are independent random variables (r.v.'s). We want to maximize the entropy of $Y$ with respect $X_2$ given a finite variance of $Y$, with the r.v. $X_1$ fixed. Is it true that the entropy of $Y$ is maximized if and only if $X_2$ has a normal distribution?

The answer to this question is no. Indeed, suppose that $P(X_1=1)=P(X_1=-1)=1/2$ and $Var\,Y=1+s^2$ for some real $s>0$, so that $Var X_2=s^2$. Suppose that $X_2$ is normally distributed, with a pdf $g$. Since the entropy of a pdf is invariant with respect to shifts, without loss of generality $X_2\sim N(0,s^2)$.
Let now $h$ be another pdf with mean $0$ and variance $s^2$. For $t\in[0,1]$, let
$$f_t:=(1-t)g+th,$$
which is the pdf of a r.v. $X_{2,t}$ with variance $s^2$ such that $X_{2,t}$ is independent of $X_1$. So, the pdf $p_t$ of $Y_t:=X_1+X_{2,t}$ (with the same variance, $1+s^2$, as $Y$) is given by the formula
$$p_t(y)=\tfrac12\,f_t(y+1)+\tfrac12\,f_t(y-1)
$$
for real $y$. The entropy of $Y_t$ is
$$H(t):=-\int_{\mathbb R}p_t(y)\ln p_t(y)\, dy,
$$
and $H(0)$ is the entropy of $Y$.
Next,
$$H'(0)=-\int_{\mathbb R}[1+\ln p_0(y)]\,\frac\partial{\partial t}\,p_t(y)\Big|_{t=0}\, dy \\
=\int_{\mathbb R}\left[\frac{g(y+1)+g(y-1)}2-\frac{h(y+1)+h(y-1)}2\right]\,
\ln\frac{g(y+1)+g(y-1)}2\,  dy.
$$
To disprove the conjecture, it is enough to find a suitable pdf $h$ such that $H'(0)>0$. In view of Chebyshev's integral inequality, it is then natural to choose $h$ which is almost mutually singular with $g$, so that $h$ is small where $g$ is large, and vice versa. With this in mind, let $h$ be the half-and-half mixture of the pdf's of $N(s\sqrt{1-u^2},u^2s^2)$ and $N(-s\sqrt{1-u^2},u^2s^2)$ with $u\in(0,1)$, so that the mean and variance of $h$ are indeed $0$ and $s^2$, respectively. Then
$H'(0)=0.05121\ldots>0$ if $s=1/2$ and $u=1/20$, and we are done.
Here are graphs of the almost mutually singular $g$ (blue) and $h$ (yellow):


text:
Q: How to get dimensions of dynamically inserted video on ipad? JavaScript I'm dynamically inserting an html5 video tag with unknown dimensions onto a page. I'm getting the dimensions with the loadedmetadata event which works like a charm on all browsers.
However, from what I understand this event won't fire until the user touches the video on the ipad. This makes it really difficult to get the actual dimensions of the video which I need in order to size it's container.
Is there

*

*Another way to get dimensions of a video which would work in this
scenario? or

*A way to trigger the loadedmetaevent?

Thanks!
CODE:
 var src=fullPathToVideoWithoutExtension;

 // DETECT WHICH FILE FORMAT TO USE
 if($.support.browser.h264||$.support.mpeg4){
     var supportedSRC=supportedSRC+'<source src="'+src+'.mp4" type="video/mp4">';
  };

  if($.support.browser.ogg){
     var supportedSRC=supportedSRC+'<source src="'+src+'.ogv" type="video/ogg">';
  };

  // SETUP THE VIDEO ELEMENT
  var $Video=$('<video id="Box_Video" controls>'+supportedSRC+'</video>');

  $Video[0].src=src+'.mp4';
  $Video[0].addEventListener('loadedmetadata',function(){
     var width=this.videoWidth;
         height=this.videoHeight;
   },false)

Here's a fiddle:
http://jsfiddle.net/Fv4XG/1/
Notice that in the browser it will immediately alert the video dimensions, but on the ipad you have to wait until there is user interaction before it pulls the dimensions. How can I get the dimensions when the video is inserted into the DOM like in all other browsers?

A: I don't believe there is a way to get the loadedmetadata event (which you need in order to read the dimensions of the dynamically loaded video) to fire on iOS without user interaction. For reasons explained in a fairly detailed answer here, Apple disabled autoplay from iOS version 6.01. I'll include the quote from the Apple documentation here.

"Apple has made the decision to disable the automatic playing of video
  on iOS devices, through both script and attribute implementations.
In Safari, on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and
  auto-play are disabled. No data is loaded until the user initiates it." - Apple documentation.

I think the only solution available to you, therefore, is to hide the video initially and display a button which prompts the video to load when clicked. This will cause the loadedmetadata event to fire, at which point you can set the size of your container based on the video dimensions, start playing the video, and finally reveal it.
I did the following in plain old JavaScript for ease. It hopefully demonstrates both the issue and the workaround I'm suggesting (jsfiddle here):
    var video = document.getElementById('video');
    video.load(); // In desktop browser this will cause loadedmetadata event to fire

    // Hide the video initially
    video.style.visibility = 'hidden';

    document.getElementById('button').addEventListener('click', function() {
        video.load(); // on iOS we need user interaction to prompt load
    });

    video.addEventListener('loadedmetadata', function() {

        // console log is much less intrusive than window.alert
        // you can see the log statements in Safari developer tools if you plug in a device
        window.alert(this.videoWidth);
        window.alert(this.videoHeight);

        // Now we can set container size, reveal and play
        video.width = this.videoWidth;
        video.height = this.videoHeight;

        video.play();
        video.style.visibility = 'visible';
    });

I've found this page from the W3 to be useful in the past for playing around with the HTML5 video API.


text:
Q: How to skip to the next iteration in case of an error In Netlogo Behavior space, if one of the runs is throwing an error, how to skip that run and ask netlogo to proceed with the next run?
Is it even possible?

A: From the docs,

If you do want spreadsheet output, note that if anything interrupts
  the experiment, such as a runtime error, running out of memory, or a
  crash or power outage, no spreadsheet results will be written. For
  long experiments, you may want to also enable table format as a
  precaution so that if something happens and you get no spreadsheet
  output you'll at least get partial table output.)

So, I'll assume this isn't possible and the best way to fix this would be to handle the situation where your code has an error. Alternatively, you could use the carefully command to handle the error messages.


text:
Q: get the list of checkbox post in django views I have this code in my template:
{% for email in emails %}
  {%if email%}
     <input type="checkbox" name="email" value="{{email}}" /> {{email}}<br />
  {% endif %}
{% endfor %}

so the output in the template is:
email1@sample.com
email2@sample.com
email3@sample.com
...

in my views I printed my request.POST about this.
print request.POST
print request.POST['email']
for email in request.POST['email']:
 print email

i got this output:
<QueryDict: {u'email': [u'email1@sample.com', u'email2@sample.com', u'email3@sample.com'], ..., u'csrfmiddlewaretoken': [u'05e5bdb542c3be7515b87e8160c347a0', u'05e5bdb542c3be7515b87e8160c347a0']}>
email3@sample.com
e
m
a
i
l
3
@
s
a
m
p
l
e
.
c
o
m

my question is, how can I get the list of emails in my views?
I wanted the output will be like this..
email1@sample.com
email2@sample.com
email3@sample.com
...

A: Use request.POST.getlist:

Returns the data with the requested key, as a Python list. Returns an empty list if the key doesn't exist and no default value was provided. It's guaranteed to return a list of some sort unless the default value provided is not a list.


text:
Q: Nativescript Loading Images Here is my scenario: On my main view I am loading a list of items.  Each item has an imageURL property.  I am binding an Image component to the ImageURL property.  Everything works well, but the image takes an extra second or two to load during which time the Image component is collapsed.  Once the image is loaded, the Image component is displayed properly. This creates an undesirable shift on the page as the image is rendered.
The same images are going to be rendered on 2 other views.
What is the best practice to handle this scenario?  I tried loading the base 64 string instead of the image url, which worked, but it slowed down the loading of the initial view significantly.
How can I pre-fetch the images and reuse them as I navigate between the views?  I was looking at the image-cache module which seems to be addressing the exact scenario, but the documentation is very vague and the only example I found (https://github.com/telerik/nativescript-sample-cuteness/blob/master/nativescript-sample-cuteness/app/reddit-app-view-model.js) did not really address the same scenario.  If I understood the code correctly, this is more about the virtual scrolling.  In my case, I will have only 2-3 items, so the scrolling is not really a concern.
I would appreciate any advise.
Thank you.

A: Have you tried this?
https://github.com/VideoSpike/nativescript-web-image-cache
You will likely want to use a community plugin for this. You can also take a look at this:
https://docs.nativescript.org/cookbook/ui/image-cache

A: So after some research I came up with a solution that works for me.  Here is what I did:

*

*When the app start I created a global variable that contained a list of observable objects

*then I made the http call to get all the objects and load them into the global variable

In the view I displayed the image as (the image is part of a Repeater item template):

<Image loaded="imageLoaded" />

in the js file I handled the imageLoaded events as:

var imageSource = require("image-source");

function imageLoaded(args) {
    var img = args.object;
    var bc = img.bindingContext;

    if (bc.Loaded) {
        img.imageSource = bc.ImageSource;
    } else {
        imageSource.fromUrl(bc.ImageURL).then(function (iSource) {
            img.imageSource = iSource;
            bc.set('ImageSource', iSource);
            bc.set('Loaded', true);
        });
    }
}

So, after the initial load I am saving the imageSource as part of the global variable and on every other page I am getting it from there with the fallback of loading it from the URL is the image source is not available for this item.
I know this may raise some concerns about the amount of memory I am using to store the images, but since in my case, I am talking about no more than 2-3 images, I thought that this approach would not cause any memory issues.
I would love to hear any feedback on how to make this approach more efficient or if there is a better approach altogether.

A: You could use the nativescript-fresco plugin-in. It is an {N} plugin that is wrapping the popular Fresco library for managing images on Android. The plugin exposes functionality like: setting fade-in length, placehdler images, error images (when download is unsuccessful), corner rounding, dinamic sizing via aspect ration etc. for the full list of the advanced attributes you can refer this section of the readme. Also the plugin exposes some useful events that you can use to add custom logic when images are being retrieved from remote source.
In order to use the plugin simply initialize it in the onLaunch event of the application and call the .initialize() function:
var application = require("application");
var fresco = require("nativescript-fresco");

if (application.android) {
    application.onLaunch = function (intent) {
        fresco.initialize();
    };
}

after that simply place the FrescoDrawee somewhere in your page and set its imageUri:
<Page
    xmlns="http://www.nativescript.org/tns.xsd"
    xmlns:nativescript-fresco="nativescript-fresco">
    <nativescript-fresco:FrescoDrawee width="250" height="250"
                                      imageUri="<uri-to-a-photo-from-the-web-or-a-local-resource>"/>
</Page>


text:
Q: NSURLSessionDownloadTask file removed before reading contents I have the following piece of code which has been working for several months and has just started becoming intermittently broken.
I am making changes to the way that it is being called, so it's not totally unsurprising, but the symptoms are baffling me.  The temporary file being downloaded by some requests, is seemingly being deleted before the data is read.
I have attributes about the file, it's location, and when running in a simulator I've even confirmed the file contains the correct data, while in a breakpoint.  However as soon as [NSData dataWithContentsOfFile:[location path]] or [NSData dataWithContentsOfURL:location] is called, the file is removed from the filesystem and if I use the method with an NSError passed in, the error I get is Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn't be completed.
My Code:
- (void)makeSoapRequest:(NSURL *)url soapRequest:(NSString *)soapRequest completionBlock:(void (^)(NSData *xmlToParse, int error))completionBlock attemptNumber:(int)attemptNumber
{
    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:nil delegateQueue:nil];
    NSData *bodyData = [soapRequest dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"" forHTTPHeaderField:@"SOAPAction"];
    [request addValue:[NSString stringWithFormat:@"%d",(int)[bodyData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:bodyData];

    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    if (!(location == nil))
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error)
            {
                NSLog(@"nsurl error was: %@", error);
            }
            else
            {
                NSError* errorObj;
                NSString *path = [location path];

                NSDictionary* attribs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&errorObj];
                NSData *xmlData= [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:&errorObj];
                if (errorObj != nil) {
                    NSLog(@"Attributes of file: %@", attribs);
                    NSLog(@"Error reading the downloaded data, error was: %@", errorObj);
                }
                completionBlock(xmlData, 0);
                return;
            }
        });
    }
    else
    {
        if (error)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock(nil,-1);
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock(nil,-1);
            });
        }
    }
}];
[downloadTask resume];
}

My Attributes printout:
Attributes of file: {
NSFileCreationDate = "2016-11-23 13:15:00 +0000";
NSFileExtensionHidden = 0;
NSFileGroupOwnerAccountID = 501;
NSFileGroupOwnerAccountName = mobile;
NSFileModificationDate = "2016-11-23 13:15:00 +0000";
NSFileOwnerAccountID = 501;
NSFileOwnerAccountName = mobile;
NSFilePosixPermissions = 384;
NSFileReferenceCount = 1;
NSFileSize = 947;
NSFileSystemFileNumber = 534146;
NSFileSystemNumber = 16777218;
NSFileType = NSFileTypeRegular;
}

Error log:
2016-11-23 13:27:43.285 GCMMobile[2780:829109] Error reading the downloaded data, error was: Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn't be completed. (Cocoa error 260.)" UserInfo=0x1704605c0 {NSFilePath=/private/var/mobile/Containers/Data/Application/BF6BE574-AA1A-492E-A1DD-04334F33E2D7/tmp/CFNetworkDownload_VHyKp6.tmp, NSUnderlyingError=0x17024ce10 "The operation couldn't be completed. No such file or directory"}

Any help most appreciated...

A: The problem is that you are returning from the NSURLSessionDownloadTask completion handler before moving or opening the downloaded file. As the documentation states:

You must move this file or open it for reading before your completion
  handler returns. Otherwise, the file is deleted, and the data is lost.

By dispatching to the main queue and returning you are postponing your file-reading code to some indefinite time in the future. You should move or open the file in the completion handler itself, and only then dispatch to another queue for subsequent processing.


text:
Q: domain user accessing share as administrator I have very strange situation (can't find on the web), let me explain it:
In my network I have File Server(SERV1, Windows Server 2003) and Domain Controller with AD (SERV2, Windows Server 2008)
On the File Server there is shared folder with subfolders for each employee
TOPLEVELFOLDER > emp1, emp2, emp3...
Each user has full control to only his own folder and read permission to other users' folders.
Share permissions on toplevelfolder look like this: SERV1\Administrators=full control, Authenticated Users=Change, Read
NTFS Security Settings: SERV1\Administrators=full, Everyone=read, SYSTEM=full, %MYDOMAINUSERNAME%=full
Every subfolder has all these settings inherited from toplevelfolder + full control for particular user.
All users in AD are from Domain Users group, NO ONE of these users are in Local Administrators group or in SERV1\Administrators group.
The problem is there are some users (absolutely no logic here) who has full access to all subfolders and files of toplevelfolder, when I look via SERV1 > Computer Management > Shared Folders > Sessions or Open Files then I see these users show ACCESSED BY ADMINISTRATOR, but other users show ACCESSED BY %DOMAINUSERNAME% as should be.
Before everything was fine, this problem occured on some random day.
I can't understand why some users authenticate as administrator.
Any ideas?
:)

A: Ok guys, here is the solution, it was born right after asking the question I struggled many day for now.
It appeared that I logged into that shared resource from random users' computers with my Domain Admin account and Windows remembered that account and password. Everything I needed to do is to remove remembered info.
First I run "control userpasswords2" from user's computer and saw the list is empty under Advanced > Manage Passwords then I run "control keymgr.dll" and VIOLA!!! here is the remembered info, simply removed it and the problem gone away :)
Maybe this practice/story will help others in the future too.
Thank you all!


text:
Q: C++ Error: no match for call to '(std::string {aka std::basic_string}) (std::string&)' I'm new to C++. I search many times, but still can't get the answer. I'm writing a class named Course to describe the courses students taking at school. The Course class has 3 fileds:
protected:
    string courseName;
    int courseNum;
    float score;

And I have a public method "setName" to set the course name:
Course &setName(string name)
{
    this->courseName(name);
    return (*this);
}

However, when I tried to compile, the compiler complains that:
C++ Error: no match for call to '(std::string {aka std::basic_string}) (std::string&)'
I also tried to modify the code to Course &setName(string &name)... And the compiler keeps complaining about the same error.
But if I change the code to:
Course &setName(string name)
{
    this->courseName = name;
    return (*this);
}

Then it works well. I couldn't understand what the compiler is complaining about and why I can't use the direct initialization?

A:
I couldn't understand what the compiler is complaining about and why I can't use the direct initialization?

Because that's not an initialization. That's an assignment. Both assignment an (copy-)initialization make use of the = sign, but don't let that fool you: the two things are fundamentally different.
Initialization is what gives a value to an object upon construction. When your setName() member function gets called, the object on which it is invoked (as well as its data members) have already been constructed. If you want to initialize them there, you're late: you've missed the train.
In a constructor's initialization list, on the other hand, you could initialize your data members as follows:
Course::Course(std::string name) : courseName(std::move(name)) { }
//                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                                 This would be initialization

A: You are attempting to assign the value of one string to another, which has already been initialized. The syntax for that is
std::string s1 = ....;
std::string s2 = ....;
s2 = s1; // OK, assignment

whereas you are attempting the equivalent of
s2(s1); // error, this is no way to assign s1 to s2

and that is just invalid syntactically in this context. You cannot initialize objects that have already been constructed.


text:
Q: pushReplacement or pushAndRemoveUntil(Route route) => false not Working A page-based route cannot be completed using imperative api, provide a new list without the corresponding Page to Navigator.pages instead.
'package:flutter/src/widgets/navigator.dart':
Failed assertion: line 3075 pos 7: '!hasPage || isWaitingForExitingDecision'
Only Navigator.push works. Before Flutter 2 it was working.
Navigator.pushAndRemoveUntil(
                    context,
                    PageRouteBuilder(
                      transitionDuration: const Duration(milliseconds: 3300),
                      transitionsBuilder: (BuildContext context,
                          Animation<double> animation,
                          Animation<double> secondaryAnimation,
                          Widget child) {
                        return _CustomPageTransition(
                            routeAnimation: animation,
                            fullscreenDialog: false,
                            child: child);
                      },
                      pageBuilder: (_, __, ___) => LoginScreen(),
                    ),
                    (route) {
                      print(route.settings.name);
                      return false;
                    });

A: It's an old question that nowaday I solved it by using auto_route package. But I think if you use Navigator.replace it will work.
AutoRouter.of(context).replaceNamed(LoginScreenRoute().path);

Or
AutoRouter.of(context).replace(LoginScreenRoute());

In the MaterialAutoRouter:
@MaterialAutoRouter(routes: <AutoRoute>[
AutoRoute(page: RouteAuthentication, initial: true),
CustomRoute(
    page: LoginScreen,
    fullscreenDialog: true,
    transitionsBuilder: TransitionsBuilders.slideLeftWithFade,durationInMilliseconds: 3300
),])

In my case I wanted to animate with the Hero widget. But the code below doesn't work.
AutoRouter.of(context).pushAndPopUntil(LoginScreenRoute(),
                  predicate: (_) => false);


text:
Q: Conditional remote: true depending on validation I have a form in a partial _donation_form.html.haml which is rendered as a modal. I am trying to do the following:

*

*If the record can be saved, redirect to a different page

*Else render the modal with validation error messages.

Everything works except that when the record is invalid, redirection to a different page does not work.
I have the following in _donation_form.html.haml which is rendered as a modal.
= bootstrap4_form_for([:admin, donation], remote: true, html: { multipart: true, id: 'manual_donations', autocomplete: 'nope'}) do |f|
 # form with submit_button which calls `create` action of `donations_controller.rb`

This is my new.js.erb which renders the above modal:
$('#newDonation').modal('hide');
$('#newDonation, .modal-backdrop').remove();
$('body').append("<%= j render partial: 'donation_modal' %>");
$('#newDonation').modal('show')

I added remote: true in _donation_form.html.haml as when the validation fails I want to render new.js.erb.
Following is donations_controller.rb:
def index; end

def new
  donation.cause_id = cause.id if entity.causes.count == 1
  donation.event_id = params[:event_id]
end

def create
    # some code
    begin
      ActiveRecord::Base.transaction do
        donation.recorded_offline!
        respond_with(:admin, donation, :location => admin_donations_path)
      end
    rescue ActiveRecord::RecordInvalid
      render :new
    end
end

When I click on submit button of the modal with a valid record, page does not redirect and I get the following message on console:
Processing by Admin::DonationsController#index as JS
-----------
No template found for Admin::DonationsController#index, rendering head :no_content

I have the view index.html.haml under app/views/admin/donations/. When I remove remote: true from _donation_form.html.haml, redirection works just fine. However, in that case rendering new.js.erb with validation error messages does not work. I am not really sure how to tackle this situation.