text:
Q: svg to png image download in iPhone I have one functionality on my website where I want to convert svg into png and allow user to download that png image into their local machine.
I have achieved this using the below code.
var btn = document.querySelector('#download');
var svg = document.querySelector('svg');
var canvas = document.querySelector('canvas');
console.log(jQuery.browser);

btn.addEventListener('click', function () {
  var data = (new XMLSerializer()).serializeToString(svg);
  var DOMURL = window.URL || window.webkitURL || window;

  var img = new Image();
  var svgBlob = new Blob([data], {type: 'image/svg+xml'});
  var url = DOMURL.createObjectURL(svgBlob);

  img.onload = function () {
    alert("after load");
      var canvas = document.getElementById('canvas');
      var ctx = canvas.getContext('2d');
      //set the image quality
      ctx.webkitImageSmoothingEnabled = true;
      ctx.imageSmoothingEnabled = true;
      ctx.imageSmoothingQuality = "high";

    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);

    // convert to png code
    if (canvas.msToBlob)
    { //for IE
        ctx.drawImage(img, 0, 0, 1226, 1066);
        var blob = canvas.msToBlob();
        window.navigator.msSaveBlob(blob, 'shnooks.png');
    }
    else
    {
        //other browsers
        var imgURI = canvas
            .toDataURL('image/png')
            .replace('image/png', 'image/octet-stream');

        if(jQuery.browser.safari)
        {
          saveImageInSafari(imgURI);
        }
        else
        {
          triggerDownload(imgURI);
        }
    }
  };
  img.src = url;
});

function triggerDownload (imgURI) {
  var evt = new MouseEvent('click', {
    view: window,
    bubbles: false,
    cancelable: true
  });

  var a = document.createElement('a');
  a.setAttribute('download', 'shnooks.png');
  a.setAttribute('href', imgURI);
  a.setAttribute('target', '_blank');
  a.dispatchEvent(evt);
}

function saveImageInSafari(imgURI)
{
  // download file using php
    jQuery.post("save.php", {data: imgURI}, function (file) {
      window.location.href =  "download.php?path=" + file;
    });
}

I have also written code in PHP for Safari to download image and it works too.
The only problem I am facing is for the iPhone. img.onload method is not working on the iPhone.
This code is working and download png on every other browser and android phone, even in the iPad.

A: It's a way old question, I don't get what do you mean by:  (img.onload method is not working on the iPhone.). In general I see that you need to replace the type of blob to image/png, also there is no need to differentiate between browsers now since most browsers support the Blob generation and downloading as png image without any problems.
Also no need to replace('image/png', 'image/octet-stream') just keep it as it is and pass it to the image src.
Hope this can help somebody.


text:
Q: Marketo Hidden Field update How should I update the value of a hidden field of Marketo?
What I have tried
form.setValues({"Results_PDF_URL__c":"assignedCampaignID"});

form.vals({"Results_PDF_URL__c":"assignedCampaignID"});

Both of the above options don't work.
So I checked the id, if I am using the right id, when I tried to get the id it retured blank (nothing) for hidden marketo fields.
While I can get the id for input text Marketo fileds (like FirstName, Comapany..) - I am not able to get the id of  any hidden Marketo fields.
Any idea what I should set to get this to work?

A: Either of those, as long as they're used in the right scope, should work. The form object is not global.
MktoForms2.whenReady( function (form) {
    form.vals({"Results_PDF_URL__c":"assignedCampaignID"});
});

You'll first want to make sure the MktoForms2 API is available so you don't get an error.
if( typeof MktoForms2 != "undefined" ) {
    MktoForms2.whenReady( function (form) {
        form.vals({"Results_PDF_URL__c":"assignedCampaignID"});
    });
}

In Marketo, you can get the field names under Admin > Field Management > Export Field Names. (Requires Marketo admin access.) This will download a CSV of all the field names. You will want to use the field names shown in the REST API column.
For a quick check, I usually just add the fields I want to a form and inspect them to get the correct field IDs.
Also, you can use .addHiddenFields() instead of .vals() to ensure that the fields are a) on the form b) as hidden fields and c) have the correct values that you want to pass into Marketo. If the fields already exist, this function will detect the fields and only set the values. Very handy.
if( typeof MktoForms2 != "undefined" ) {
    MktoForms2.whenReady( function (form) {
        form.addHiddenFields({"Results_PDF_URL__c":"assignedCampaignID"});
    });
}

Finally, you may want to add a brief delay to ensure that the Marketo forms library has ample time to load and that the form will be available on the page when you look for it. It's unlikely that someone will submit the form in the first two seconds on the page, so it is probably okay to delay for two seconds before adding the field/value to the form.
setTimeout( function(){
    if( typeof MktoForms2 != "undefined" ) {
        MktoForms2.whenReady( function (form) {
            form.addHiddenFields({"Results_PDF_URL__c":"assignedCampaignID"});
        });
    }
}, 2000 ); // two-second delay

Resources:

*

*Marketo forms API Reference

*Marketo forms API Examples

redpajama_set_name: RedPajamaStackExchange


text:
Q: react-i18next translation is not working for passed on Prop elements I have setup an i18 translator in my project, while it is working fine for other elements in the project, it does not seem to work well with passed on prop elements.
This is how I am using the i18:
import { useTranslation } from 'react-i18next';
const { t } = useTranslation();

//Using the translations
{t('kitchenware')} // <-- Working fine
{t(product?.name)} // <-- Error here
name={t(product.name)} // <-- No error, but translations doesn't seem to work

This is the error message that I am getting:
src/pages/product/index.tsx:48:33
TS2769: No overload matches this call.
  Overload 1 of 2, '(key: string | TemplateStringsArray | (string | TemplateStringsArray)[], options?: string | TOptions<StringMap> | undefined): TFunctionResult', gave the following error.
    Argument of type 'string | undefined' is not assignable to parameter of type 'string | TemplateStringsArray | (string | TemplateStringsArray)[]'.
      Type 'undefined' is not assignable to type 'string | TemplateStringsArray | (string | TemplateStringsArray)[]'.
  Overload 2 of 2, '(key: string | TemplateStringsArray | (string | TemplateStringsArray)[], defaultValue?: string | undefined, options?: string | TOptions<StringMap> | undefined): TFunctionResult', gave the following error.
    Argument of type 'string | undefined' is not assignable to parameter of type 'string | TemplateStringsArray | (string | TemplateStringsArray)[]'.

I will be making sure that always a product value is passed, not undefined or null.

A: I wrongly referencing the i18 scripts. This has worked after a correct reference.


text:
Q: Converting a C# class I created inside a project to a separate reusable class I'm not new to C# programming, but I suppose I'm new to programing "the right way" in C#. I've worked in C on embedded devices for years and have written desktop apps to support them. First in VB6, then in C#.
I recently started making better use of classes for reusing code (and for instantiating more than one instance of the class in a program). For example, I "wrapped" a UART interface with some additional functionality so I can use the same code for multiple ports by creating an instance of the class for each one.
It is in a separate file, but still in the same program namespace, so when I want to reuse it, I have to copy the file and change the namespace to the new project.
I'm sure there's a way to create it such that I can just reference it like everything else with either a "using..." reference at the top of the program or with a "Project | References..." checkbox. But for the life of me I can't find a good learning journey for this.
Any direction would help.

A: You want to create your reuseable class in an assembly - this is the equivalent of a dll from your C experience.
To create an assembly, have a separate project of type assembly (instead of exe) . You can reference the assembly from other projects. If your project is in the same solution you can reference the project, otherwise you can reference the compiled assembly.
C# uses a packaging system called Nuget, so you can package your assemblies into "Nugets" which you host in a Nuget Server. You can then use tooling to discover and import these.

A: Please create a Class Library project and include your class into that project. Make sure your class is public. Once you build this project you'll get an assembly which can be referenced from other projects. See Tutorial: Create a .NET class library using Visual Studio
There are different ways of referencing it.

*

*You can have the class library project in the same solution as the main project. In this case you should add a project reference.

*You can copy the compiled *.dll file to some folder in your solution (e.g. Lib) and add an assembly reference.

*If this assembly is to be used in multiple projects please consider creating a NuGet package with this library and pushing it to some repository. Then other projects can add a package reference to this package.

Details:

*

*How to: Add or remove references by using the Reference Manager

*Install and manage packages in Visual Studio using the NuGet Package Manager

A:
It is in a separate file, but still in the same program namespace, so when I want to reuse it, I have to copy the file and change the namespace to the new project.

Well, it isn't the best practice but (unfortunatly) still a common behavior. So don't worry to much about it.
What you could do to improve it place the file (and other reusable parts) in a seperated csproj.
For example name the project of the type class library and name it VinDag.Tools. Within the project create a folder UART and place the wrapper there. The namespace of the wrapper would then be VinDag.Tools.UART.
From know on you can just reference the class library instead of renaming the file. It's not necessarily required to be the same namespace as the project.
From there you can start considering (private) nugets. This would prevent you from copying files/csproj around.


text:
Q: Nesting oneOf inside allOf not working as expected (python jsonschema) OK, I'm sure there's something wrong with this jsonschema, but I just can't seem to wrap my head around the problem.
I'm not going to post the actual code, but a minimal example that reproduces the issue.
Here's what I had before, which worked fine:
person = {
    'type': 'object',
    'properties': {
        'name': {
            'type': 'string'
        }
        'auth_token': {
             'type': 'string',
        },
        'username': {
            'type': 'string'
        },
        'password': {
            'type': 'string'
        }
    },
    'oneOf': [
        {
            'required': ['auth_token']
        },
        {
            'required': ['username', 'password']
        }
    ],
    'required': ['name']
}

The idea here was that you always need to provide the name of the person, and then either an auth token or a username and password pair. As I said above, this validation worked fine, since we have parametrized tests that send all posible combinations of invalid JSON and evaluate the resulting error message, and those tests pass.
But then a new requirement came in and I needed to add a second mutually exclusive required pair of fields, which I did in this way:
person = {
    'type': 'object',
    'properties': {
        'name': {
            'type': 'string'
        }
        'auth_token': {
             'type': 'string',
        },
        'username': {
            'type': 'string'
        },
        'password': {
            'type': 'string'
        },
        'project_id': {
            'type': 'number'
        },
        'contract_date_from': {
            'type': 'string'
        }
        'contract_date_to': {
            'type': 'string'
        }
    },
    'allOf': [
        {
            'oneOf': [
                {
                    'required': ['auth_token']
                },
                {
                    'required': ['username', 'password']
                }
            ]
        },
        {
            'oneOf': [
                {
                    'required': ['project_id']
                },
                {
                    'required': ['contract_date_from', 'contract_date_to']
                }
            ]
        }
    ],
    'required': ['name']
}

But now the second validation always fails, whether the json provided is valid or invalid. The error message I get is:
{'name': 'John Doe', 'auth_token': '9d9a324b-26de-4ac3-85eb-05566e4a7204', 'username': None, 'password': None, 'project_id': 2785, 'contract_date_from': None, 'contract_date_to': None} is valid under each of {'required': ['contract_date_from', 'contract_date_to']}, {'required': ['project_id']}

No matter what values I send in those three fields (ie. project id, contract date from and contract date to), it fails with the same error. I've tried leaving all three empty, completing all three, and all permutations in between, but the error stays the same.
I've been reading the documentation for json schema but I can't seem to grasp what's going on with this example. I'm considering trying different approaches for this, but I'd really like to understand why this is not working. Any help is appreciated!

A:
{'name': 'John Doe', 'auth_token': '9d9a324b-26de-4ac3-85eb-05566e4a7204', 'username': None, 'password': None, 'project_id': 2785, 'contract_date_from': None, 'contract_date_to': None} is valid under each of {'required': ['contract_date_from', 'contract_date_to']}, {'required': ['project_id']}

Read the error message more carefully: you requested that project_id be provided, OR contract_date_from and contract_date_to are provided, but you are providing all three of these. Providing a null value in a property is still providing a property. The error message is confusing, but you'd be failing validation anyway because null is not a string. Your evaluator is simply running the allOf->anyOfs first, so that's the error that comes back first. You should still get the type violation errors as well, though (if you don't, that's a bug: evaluators are required to provide ALL errors, not just the first.)
You can make the errors better at the expense of brevity by adding the "type" checks to live next to the "required" keywords. That will ensure the oneOf keywords produce failures rather than successes and maybe make the error messages more obvious.


text:
Q: Detecting known computer on public network in BASH Anybody know of a way through BASH (specifically OSX terminal, but I'd prefer a BASH only solution without OSX' in built functionality) to detect a known computer on a public network (that I am also located on)?
My thought was that since I know the MAC address of the computer I'm trying to find, I could simply resolve that to an IP, but I'm not sure exactly how I would go about resolving a MAC address to a local IP address on the public network using BASH commands.
My goal is to set up a scripted solution that will allow me to set up a desktop icon that when I double click, detects a known computer on the network and its corresponding local IP address, creates an SSH tunnel for VNC, and then opens the screen sharing app through the SSH tunnel. Essentially, double click to open a secure screen sharing connection on a public network with no third party software and only the tools available via BASH and OSX.
All of this happens within the same public wifi network. For example, imagine two people go to the same coffee shop. I want person A to scan for the IP of Person B given that they already know Person B's IP address.

A: They make something for this called a DNS name. If it's a public server then it more than likely has one. If it doesn't then you're going to want to make your own, if you already have a DNS name in your org then just add a new A record on your DNS server which specifies a new sub domain for that server. In general, public servers all use static IP addresses though so even this isn't really needed. The IP should never change so just use it. If the IP is changing then you're going to need to either install a dynamic dns client on the server which will keep the DNS entry up to date for you automatically or design your own system (possibly a script which keeps your host file(s) updated [I mean the host files on each of your clients; not the server]). Also, there is no need to worry about local IP vs public IP. This is something your router knows how to manage automatically. As long as your routing table is properly setup it'll find the best path to the server. If you have a home router then this will all be handled automatically behind the scenes.
Update
I actually just thought of a good solution which should work. Get a cloud drive like Google Drive. Set it up on both computers to sync correctly. Then have the other pc write a file to the sync folder which contain the local IP:
echo `ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|sed 's/addr://'` > /home/user/share/pcname_current_ip

Now you just need to read that file to find the current IP for that computer (as long as they've both synced of course).

A: Short answer: The most simple thing to do is probably to install on the laptops something like
a dynamic DNS update client  to keep track of their dynamic IP address when they are not in your Local Network.
Some words more: The problem is that with only the MAC address you are forced to scan a subnet to find an answering machine with that MAC address once you call it's IP address. Other side of the problem is that this IP change each time the remote machine connects to a provider (or the ADSL reset the connection and assign a different IP address).
It's most simple if that machine (the laptop) communicates somehow the current IP. A way to do it to use a dynamic DNS update client. It exist even a Linux daemon ddclient that help with [dynamic ip servers].(http://ubuntuguide.org/wiki/Dynamic_IP_servers)
After that you choose your name (e.g 'myname.AtFreeOrCommercialProvider.org') and enable on the laptop a program to update the IP, it will be enough to do write from the office the above line to know the current IP of the remote machine:
host myname.AtFreeOrCommercialProvider.org

after you will be able to write it in your script and use as you want.

More words on the original way
The core of your original question is
I know the MAC address of the computer I'm trying to find, I could simply resolve that to an IP, but I'm not sure exactly how I would go about resolving a MAC address to a local IP address on the public network using BASH commands.
To obtain MAC-address from the IP-address you can use,e.g., one of the following method that will give you IP and MAC-address of answering computer in the net:

*

*nbtscan, e.g.nbtscan  192.168.1.0-255 will scan the IP address group you specify answering with IP address, NetBIOS Name, Server, User, MAC address.    (If 192.168.1.xxx is your local network...)

*arp with no mode specifier will print the current content of the IPv4 network neighbour table with IP and MAC address.
From the same family of tools sudo arp-scan --interface=eth0 192.168.0.0/24 if you are using a cable connection, or sudo arp-scan --interface=wlan0 192.168.0.0/24 if you are using a wireless connection...

*nmap -sP xxx.xxx.xxx.xxx on all your local network addresses and filter them with the known MAC addresses.

*nmblookup if you know the NetBIOS names...

After that you have on the same line the IP and the MAC:address you can write your script. Some of this tools may need to be installed.
PS> You can know your current IP address from
# if you are using a cable connection on the network ineterface eth0
sbin/ifconfig eth0 | grep -E "inet:" | awk '{print $2}' | sed s/"inet:"//g
# or you are using a wireless connection on the network ineterface wlan0
sbin/ifconfig wlan0 | grep -E "inet:" | awk '{print $2}' | sed s/"inet:"//g

PPs> IMHO it's not so nice or efficient to scan all internet only to know if that specific computer is connected... It is a different case if you connect this computer to a LAN or a virtual private network (with less IP to be scanned it's possible)... :-)

A: What about setting up your own ad-hoc wireless network on one of the PCs and route the other PCs traffic through it. Secure and no need for third party ip tracking...

A: The simplest way to accomplish this is with logmein or team viewer. Yes its third party but it would work very simply.


text:
Q: Slow select from one billion rows GreenPlum DB I've created the following table on GreenPlum:
CREATE TABLE data."CDR"
(
   mcc text,
   mnc text,
   lac text,
   cell text,
   from_number text,
   to_number text,
   cdr_time timestamp without time zone
)
WITH (
  OIDS = FALSE,appendonly=true, orientation=column,compresstype=quicklz, compresslevel=1
)
DISTRIBUTED BY (from_number);

I've loaded one billion rows to this table but every query works very slow.

*

*Text fields aren't large

*Every column can be used in the WHERE clause

*No joins with other tables

*I choose this key since it's the closest one to be a PK that isn't a date field 5. I'm fetching the full row from the DB (e.g. SELECT *)

What can I do to speed up my queries?
Using PARTITION? using indexes?
maybe using a different DB like Cassandra or Hadoop?

A: As you're accessing all the columns, then consider row based rather than columnar.
Partitioning will help. Pick a column that is easy to divide into around 100 ranges, or that has 100 or so distinct values.
As you are not joining to any other tables, you might as well distribute randomly. This may be faster than hashing a text column.
Nothing beats trying it, especially as we have limited information about the content of your tables or the queries that you are running. I appreciate that repeated performance testing on billion row tables isn't easy though.


text:
Q: How to get div id in cocoa webview xcode anyone tell me how to get div id from a script webview i used this code but this is not working
NSString *strTitle1=[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('div_indicator').innerHTML;"];
NSLog(@"strtil:%@",strTitle1);

A: Try this code Objective-C-HMTL-Parser
and this hpple
and you have this tutorial How to parse html on iOS


text:
Q: How to install Fedora from an .iso file?
Possible Duplicate:
How to install fedora 12 iso file?

I just downloaded Fedora from here.
How do I install Fedora from the .iso file that is downloaded?
Also, I have Vista already installed on my machine.

A: The easiest way, assuming the machine you're installing it on has an optical drive, is burning the ISO to a CD. ISO is the standard for CD/DVD images, so whatever burning program you're using should be willing to handle .iso files.
Then restart the computer and boot it from the disc, this will fire up the Fedora installer.

A: You can BURN the ISO file you've just downloaded with WinV to a CD or DVD and boot it from there.
That's the easiest way, in my opinion.


text:
Q: hf-tikz doesn't box around equation within align environment The problem I have is fundamentally the same that was treated here in a very neat way, but for the specific case in which the equations are listed within an align environment.
(I recently opened a similar question here but this is an additional problem so I thought it's ok to open a new thread)
I tested the different solutions of @Qrrbrbirlbel but they don't seem to work as they do for equations defined within \[ \].
This is the result:

obtained with the following code
\documentclass{beamer}
\usepackage{pgfplots}
\usepackage{tikz}                       %inline graphics
\usetikzlibrary{calc}

\usepackage[customcolors,markings,shade]{hf-tikz}

\tikzset{nodeStyleGreen/.style={
    draw=green!40!black,
    fill=green!50!lime!30,
    align=left,
    very thick,
    rounded corners
}}

\tikzset{nodeStyleRed/.style={
    draw=red!40!black,
    fill=red!50!lime!30,
    align=left,
    very thick,
    rounded corners
}}

\tikzset{nodeStyleBlue/.style={
    draw=blue!40!black,
    fill=blue!50!lime!30,
    align=left,
    very thick,
    rounded corners
}}

\tikzset{lineStyleRed/.style={
    color=red!40!black,opacity=0.75,line width=2pt,
}}

\tikzset{lineStyleGreen/.style={
    color=green!40!black,opacity=0.75,line width=2pt,
}}

\tikzset{lineStyleBlue/.style={
    color=blue!40!black,opacity=0.75,line width=2pt,
}}

\begin{document}
    \begin{frame}
   %
    \begin{align*}
        \tikzmarkin[nodeStyleRed,mark at=0.5]{firsteq} a &= \int_A^B b \tikzmarkend{firsteq}\\
        %
        \tikz[remember picture,overlay]{
            \node[nodeStyleRed] (firsteq-aa) at ($(firsteq)+(-3.0cm,-1.0cm)$) {
                \begin{minipage}{3cm}
                    My content:\\[-0.5cm]
                    \begin{itemize}
                        \item item 1 of a
                        \item item 2 of a
                    \end{itemize}
                \end{minipage}
                };
                \path [lineStyleRed,use marker id=1] (firsteq-aa.east) edge[out=0,in=185,-stealth] (0,0);
        }
        \tikzmarkin[nodeStyleGreen,mark at=0]{secondeq} b &= c \tikzmarkend{secondeq}\\
        %
        \tikz[remember picture,overlay]{
            \node[nodeStyleGreen] (secondeq-aa) at ($(secondeq)+(5.0,1.0)$) {
                \begin{minipage}{4cm}My other content:\\[-0.5cm]
                    \begin{itemize}
                        \itemsep-0.25em
                        \item item 1
                        \item item 2
                        \item item 3
                    \end{itemize}
                \end{minipage}
            };
            \path [lineStyleGreen,use marker id=1] (secondeq-aa.west) edge[out=180,in=0,-stealth] (0,0);
        }
        %
        \tikzmarkin[nodeStyleBlue,mark at=0.0]{thirdeq} c &= d \tikzmarkend{thirdeq}
        %
        \tikz[remember picture,overlay]{
            \node[nodeStyleBlue] (thirdeq-aa) at ($(thirdeq)+(4.0,-3.0)$) {
                \begin{minipage}{3cm}My final content:\\[-0.5cm]
                    \begin{itemize}
                        \itemsep-0.25em
                        \item item 1
                        \item item 2
                        \item item 3
                    \end{itemize}
                \end{minipage}
            };
            \path [lineStyleBlue,use marker id=1] (thirdeq-aa.west) edge[out=180,in=0,-stealth] (0,0);
        }
    \end{align*}
    %
    \end{frame}
\end{document}

A: In this kind of case where everything is being highlighted, it really makes work for no reason to write the equations and then add highlighting and annotations and everything else afterwards. It would be simpler to just put the equations in a tikzpicture in the first place.
One way to do this would be to use a matrix of math nodes. If three nodes are used for each equation, they can be aligned using the column <number> styles, as illustrated in the examples in the TikZ manual. Because nodes in matrices automatically get names, the highlighting can then be added around the nodes, together with the annotations afterwards. Using layers, the fill behind the equations can be added using the fit library. Naming these nodes then provides a basis for placing the list of items. I used the positioning library to do this as it seemed simpler than messing around with calc, but you can obviously use that if you prefer. (I've left the library loaded in the example even though I don't actually need it here.)

\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{calc,matrix,backgrounds,fit,positioning}
\tikzset{%
  nodeStyleGreen/.style={
    draw=green!40!black,
    fill=green!50!lime!30,
    align=left,
    very thick,
    rounded corners
  },
  nodeStyleRed/.style={
    draw=red!40!black,
    fill=red!50!lime!30,
    align=left,
    very thick,
    rounded corners
  },
  nodeStyleBlue/.style={
    draw=blue!40!black,
    fill=blue!50!lime!30,
    align=left,
    very thick,
    rounded corners
  },
  lineStyleRed/.style={
    color=red!40!black,opacity=0.75,line width=2pt,
  },
  lineStyleGreen/.style={
    color=green!40!black,opacity=0.75,line width=2pt,
  },
  lineStyleBlue/.style={
    color=blue!40!black,opacity=0.75,line width=2pt,
  },
}

\begin{document}
\begin{frame}[fragile]
  \begin{tikzpicture}
    \matrix (m) [matrix of math nodes, row sep=2.5pt, column 3/.style={anchor=mid west}, column 2/.style={anchor=mid}, column 1/.style={anchor=mid east}]
    {
      a & = & \int_A^B b\\
      b & = & c\\
      c & = & d\\
    };
    \begin{scope}[on background layer, every node/.style={inner sep=0pt}]
      \node (firsteq) [nodeStyleRed, fit=(m-1-1) (m-1-3)] {};
      \node (secondeq) [nodeStyleGreen, fit=(m-2-1) (m-2-3)] {};
      \node (thirdeq) [nodeStyleBlue, fit=(m-3-1) (m-3-3)] {};
    \end{scope}
    \node [nodeStyleRed, text width=27.5mm, below left=of firsteq.mid west] (firsteq-aa)  {
        My content:
        \begin{itemize}
          \item item 1 of a
          \item item 2 of a
        \end{itemize}
    };
    \path [lineStyleRed] (firsteq-aa.east) edge[out=0,in=185,-stealth] (firsteq);
    \node [nodeStyleGreen, text width=32mm, right=of firsteq.north east] (secondeq-aa) {
      My other content:
        \begin{itemize}
          \itemsep-0.25em
          \item item 1
          \item item 2
          \item item 3
        \end{itemize}
    };
    \path [lineStyleGreen] (secondeq-aa.west) edge[out=180,in=0,-stealth] (secondeq);
    \node [nodeStyleBlue, text width=30mm, below right=of thirdeq.mid east] (thirdeq-aa)  {
      My final content:
        \begin{itemize}
          \itemsep-0.25em
          \item item 1
          \item item 2
          \item item 3
        \end{itemize}
    };
    \path [lineStyleBlue] (thirdeq-aa.west) edge[out=180,in=0,-stealth] (thirdeq);
  \end{tikzpicture}
\end{frame}
\end{document}

Note that you can just set text width rather than messing around with minipages.


text:
Q: Android how to update progress bar in the listview, while uploading file to Amazon using aws sdk Am using the aws SDK to upload set of images. I have a ListView with each list item containing a ProgressBar(Style:Horizontal), I need to set the progress to it based on the file uploaded.
I used the TransferManager from the aws SDK (http://aws.amazon.com/releasenotes/Java/3538638977238478) to get the uploaded data.
I tried this, But its not working:
public class SyncFragment extends Fragment {

    ListView uploadList;
    public UploadAdapter uploadAdapter;

    public ArrayList<QueueItem> queueList = new ArrayList<QueueItem>();

    AWSCredentials myCredentials = new BasicAWSCredentials(Constants.ACCESS_KEY_ID, Constants.SECRET_KEY);
    TransferManager tm = new TransferManager(myCredentials);

    // Empty cons as per documentation of Fragments
    public SyncFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        // Set the queue list
        queueList = ((NSApplication) getActivity().getApplication()).queueList;
        // Init Adapter
        uploadAdapter = new UploadAdapter(getActivity());
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.upload_list, container, false);

        uploadList = (ListView) view.findViewById(R.id.uploadList);
        uploadList.setAdapter(uploadAdapter);

        return view;
    }

    class UploadAdapter extends ArrayAdapter<QueueItem> {

        private LayoutInflater layoutInflater;
        private BitmapFromId bitmapFromId;
        QueueItem item;

        public UploadAdapter(Context context) {
            super(context, 0);
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            bitmapFromId = new BitmapFromId(context);
        }

        @Override
        public int getCount() {
            // Set the total list item count
            return queueList.size();
        }

        @Override
        public QueueItem getItem(int position) {
            return queueList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;
            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.listitem_upload, null);
                holder = new ViewHolder();

                holder.albumName = (TextView) convertView.findViewById(R.id.albumTitle);
                holder.thumb = (ImageView) convertView.findViewById(R.id.thumb);
                holder.progressBar = (ProgressBar) convertView.findViewById(R.id.progressbar_Horizontal);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            item = getItem(position);

            item.progress = 0;

            // load bitmap from id
            bitmapFromId.DisplayImage(Long.parseLong(item.itemId), holder.thumb);

            holder.albumName.setText(item.itemName);

            S3PutObjectTask task = new S3PutObjectTask();
            task.execute(item.itemActualPath, item.itemId);

            holder.progressBar.setProgress(item.progress);

            return convertView;
        }

        private class S3PutObjectTask extends AsyncTask<String, Integer, S3TaskResult> {

            int progress;

            protected void onPreExecute() {
                progress = 0;
            }

            protected S3TaskResult doInBackground(String... params) {

                S3TaskResult result = new S3TaskResult();
                // The file location of the image selected.
                String imagePath = params[0];

                // Put the image data into S3.
                try {

                    File image = new java.io.File(imagePath);

                    Transfer myUpload = tm.upload(Constants.getPictureBucket(), params[1] + ".jpg", image);

                    while (myUpload.isDone() == false) {
                        progress = (int) (myUpload.getProgress().getBytesTransfered() * 100 / image.length());
                        publishProgress(progress);
                    }

                    myUpload.waitForCompletion();

                } catch (Exception exception) {

                    result.setErrorMessage(exception.getMessage());
                }

                return result;
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                item.progress = values[0];
                uploadAdapter.notifyDataSetChanged();
            }

            protected void onPostExecute(S3TaskResult result) {

                Toast.makeText(getActivity(), "uploaded sucessfully!", Toast.LENGTH_SHORT).show();

                if (result.getErrorMessage() != null) {

                    Toast.makeText(getActivity(), "upload failed...", Toast.LENGTH_SHORT).show();
                }
            }

        }

        public class S3TaskResult {
            String errorMessage = null;
            Uri uri = null;

            public String getErrorMessage() {
                return errorMessage;
            }

            public void setErrorMessage(String errorMessage) {
                this.errorMessage = errorMessage;
            }

            public Uri getUri() {
                return uri;
            }

            public void setUri(Uri uri) {
                this.uri = uri;
            }
        }
    }

    public static class ViewHolder {
        ImageView thumb;
        TextView albumName;
        ProgressBar progressBar;
    }

}

A: Here is what I see from your code:

*

*The way you use TransferManager and the idea to update transfer progress are correct. However I suggest you update the progress once more outside the while loop to get the finish state right.

*"QueueItem item" in UploadAdapter is very suspicious. All your S3PutObjectTask objects share one item whose value is assigned in getView and is overwritten when Android draws every list item. I believe the progress will mess up when there are more than one tasks running. It's better to associate a queue item and a task together, so that the task can update its progress via associated queue item.

*Due to view recycling in Android, tasks can be restarted when a list item is redrawn.

I hope the above helps you diagnose the problem.


text:
Q: Compilers give different answers for Project Euler #22 I'm doing Project Euler #22:

Using names.txt (right click and 'Save Link/Target As...'), a 46K text
  file containing over five-thousand first names, begin by sorting it
  into alphabetical order. Then working out the alphabetical value for
  each name, multiply this value by its alphabetical position in the
  list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN,
  which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the
  list. So, COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?

Compiling my code below with Cygwin's gcc-g++ compiler, the answer is 871129635. But with Visual Studio 2008, the answer is correct, 871198282. Why is this the case?
#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;

bool strCmp(string x, string y) {
    if(x.compare(y) == -1)
        return true;
    else
        return false;
}

int getScore(string s) {
    int score = 0;
    for(unsigned int i = 0; i < s.length(); i++)
        score += (((int) s.at(i)) - 64);
    return score;
}

int getTotalScore(vector<string> names) {
    int total = 0;
    for(unsigned int i = 0; i < names.size(); i++)
        total += (getScore(names[i]) * (i+1));
    return total;
}

int main() {
    vector<string> names;
    ifstream namesFile("names.txt");

    char curChar;
    string curName = "";

    //get names from file
    if(namesFile.is_open()) {
        while(!namesFile.eof()) {
            curChar = namesFile.get();

            if(isalpha(curChar))
                curName.push_back(curChar);
            else {
                if(!curName.empty()) {//store finished name
                    names.push_back(curName);
                    curName.clear();
                }
            }
        }
    }
    namesFile.close();

    //alphabetize
    sort(names.begin(), names.end(), strCmp);

    //count up name scores
    cout << getTotalScore(names) << endl;
    return 0;
}

A: Here:
if(x.compare(y) == -1)

You are assuming that std::string::compare will return -1 for a less-than result, but it can in fact return any negative value. You can fix this by using x.compare(y) < 0, but it's better to just write x<y. In fact, you don't even need the strCmp function because the default behavior of std::sort is to compare the elements using operator<.


text:
Q: Count values from another layer based on value of current feature I have two layers. One is a shapefile of U.S. states where each state is labeled with the attribute STATE_NAME, and the other is a CSV data layer named rid with many points that are labeled with a State attribute. In this CSV data layer, there are many points for each state.
I want to create a column in the shapefile that contains the count of points per state.
Using the field calculator in the shapefile, I've attempted
aggregate(layer:= 'rid',
          aggregate:= 'count',
          expression:='State',
          filter:=attribute($currentfeature, 'STATE_NAME'))

but this results in 0 for each state. If I attempt without the filter, I get the total number of points regardless of state, resulting in the same number for each state.
Is there a filter that will allow me to count the number of points per state?

A: What I ended up doing:

*

*Layer > Create Layer > New Virtual Layer…

*Import rid CSV layer. Set query as select "State", count(*) AS "TERPS" from rid group by "State".

*Click 'Add'. This creates a virtual layer that counts the number of points per date. Close dialog.

*Go to the properties of the shapefile layer. Create a new join that joins to the virtual layer on "State", with the target field being STATE_NAME. This moves that data from the virtual layer over to the shapefile.


text:
Q: ASP Menu Position Please note, I am a beginner when it comes to web page coding so please go easy on me!
I have a simple master page that contains a banner at the top and an ASP menu control down the left hand side. I want the page to be be centre justified and so I have div "outer_div" with the CSS attributes: text-align:center margin-left:auto, margin-right:auto.
This "outer_div" contains the "menu" div (containing the ASP menu control) which has CSS attributes: text-align:left. However I cannot get the menu control to position at the left of the outer div, I only seem to be able to get it at the extreme left of the screen or bang in the centre.
I've pasted the .master and the CSS believe. I guess that I've made a simple mistake - but it's not proving simple to find it! Any help greatly appreciated,
Rob...

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

        <asp:Label ID="lblHeader" runat="server" CssClass="header_image" Width="1024px" Height="121px"></asp:Label>

            Arcadia

            Reference Data Load Manager

        <asp:Label ID="lblPageName" runat="server" CssClass="top_panel" Width="1024" Height="30"></asp:Label>

    <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />

            <asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" DynamicHorizontalOffset="2"
                Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284E98" Orientation="Vertical"
                StaticSubMenuIndent="10px" StaticDisplayLevels="5">
                <DynamicHoverStyle BackColor="#284E98" ForeColor="White" />
                <DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
                <DynamicMenuStyle BackColor="#B5C7DE" />
                <DynamicSelectedStyle BackColor="#507CD1" />
                <StaticHoverStyle BackColor="#284E98" ForeColor="White" />
                <StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
                <StaticSelectedStyle BackColor="#507CD1" />
            </asp:Menu>

            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>

    </form>

and now the css...
body
{
    font-family: Verdana;
    font-size: small;
    background-color: #808080;
}

#standard
{
    font-family: Verdana;
    font-size: small;
    background-color: #FFCC99;
}

#menu {
    background-color: #FDA343;
    position:relative;
    left:0px;
    top:0;
    width: 161px;
}

#content
{
    width: 600px;
    float: left;
    text-align: left;
}

.button
{
    font-family: Verdana;
    font-size: small;
    background-color: #6699FF;
    color: #FFFFFF;
}

.top_panel
{
    background-color: #FDA343;
    font-family: Tahoma;
    font-size: large;
    text-align: center;
}

.header_image
{
    background-color: #B5C7DE;
    font-family: Tahoma;
    font-size: large;
    text-align: left;
    vertical-align: middle;
    background-image: url('Images/SmallOrangeRig.jpg');
    color: #FFFFFF;
}

.cenx
{
    text-align: center;
}
.ceni
{
    clear: both;
}
.bxcen
{
    margin-left: auto;
    margin-right: auto;
    border: none;
    padding: 0;
}

.left_align
{
    text-align:left;
}

#branding {
    position: absolute;
    right: 20px;
    top: 20px;
    z-index: 1000;
    text-align: left;
    color: #9f0f0e;
    font-family: "Arial", Courier, monospace;
}

#companyName {
    color: #FFF9E9;
    font-size: 40px;
}

A: My CSS was way over complicated. I picked up a great book called "Getting StartED with CSS" by David Powers. Chapter 11 gives a sample CSS for a simple two column layout page. From this, I was able to build just what I needed.
The basic css is:
#wrapper {
  width: 760px;
  margin: 0 auto;
}
#sidebar {
  width: 220px;
  padding: 10px;
  float: left;
}
#mainContent {
  margin-left: 240px;
}

The thing that makes the real difference for my problem is float.


text:
Q: How to get the selected value with es6 onchange Im using semantic-ui's react dropdown. I cant seem to get the selected value in my function (using redux).
The setup:
Module:
const types = [ { value: 'Rails', text: 'Rails' }, ... ]

const DropdownMenu = (props) => (
  <Dropdown placeholder='Select...' fluid selection options={types} onChange={(e) => props.backendSelect(e)} />
)

Action:
export const backendSelect = (text) => ({
  type: BACKEND_TYPE_SELECT,
  text,
})

Reducer:
const backendTypeSelect = (state = '', action) => {
  console.log(action)
  switch (action.type) {
    case BACKEND_TYPE_SELECT:
      return action.text;
    default:
      return state;
  }
};

Is my function correct: onChange={(e) => props.backendSelect(e)}?
const mapStateToProps = (state) => ({ backendTypeSelect: state.backendTypeSelect })

export default connect(mapStateToProps, actions)(<APP>);

A: Try to extract value from the event like this:
onChange={(e) => props.backendSelect(e.target.value)}

A: You are not using connect properly.

*

*You need to dispatch the actions, for that you can use mapDispatchToProps with bindActionCreators

*You are notconnecting it to the component correctly
Code:
mapDispatchToProps(dispatch) {
   return {
       backendSelect: bindActionCreators(actions.backendSelect, dispatch)
   }
}

connect(mapStateToProps, mapDispatchToProps)(APP);

Then try
onChange= {(e, data} => props.backendSelect(e, data)}


text:
Q: CSS Grid - Align-self just above the center I have the following HTML code

Childhood

Early years

End

About this

Henry Charles Bukowski Jr.

"Find what you love and let it kill you."

8/16/1920

3/09/1994

      next section

Which presents this page with the CSS:
https://prnt.sc/qx4qim
CSS:
/* Montserrat font import */
@import url('https://fonts.googleapis.com/css?family=Montserrat:100,300,400,600,700&display=swap');

* {
  margin: 0;
  padding: 0;
}

body {
  background-color: #2F2E2E;
}

#main {
  font-family: 'Montserrat', sans-serif;
  color: #E0E1DD;
}

header,
section {
  padding: 40px 60px;
  height: calc(100vh - 80px);
}

#childhood,
#end {
  background: #31303B;
}

ul {
  list-style: none;
}

/* text style */

h1 {
  font-weight: bold;
  font-size: 80px;
}

h2 {
  font-weight: 100;
  font-size: 60px;
}

h3 {
  font-weight: 600;
  font-size: 60px
}

h4 {
  font-weight: 600;
  font-size: 50px;
}

p {
  font-weight: 400;
  font-size: 45px;
}

/* text style end */

/* nav link */

nav ul {
  display: flex;
  justify-content: space-between;
  font-weight: 300;
  font-size: 50px;
}

nav ul li a {
  text-decoration: none;
  color: #E0E1DD;
  transition: .3s color;
}

nav ul li a:hover {
  color: rgb(138, 128, 128);
}

/* nav links end */

#header-content {
  display: flex;
}

#info-title{
  align-self: center;
}

header figure img {
  height: auto;
  max-height: 850px;
  max-width: 630px;
}

I align the texts on the page with the align-self: center property; but if I want to upload these texts a bit to look like this: https://prnt.sc/qx4qol
Is there a property that allows me to enter numeric values for vertical alignment?
The top property does not work since the display is set to flex

A: I think if you move:

8/16/1920

3/09/1994

into the header-content element then modify the css to this, should do the trick:
.header { position: relative; }
.tribute-info { position: absolute; bottom: 15px; left: 15px; }

A: *

*add display: flex; and flex-direction: column; to header

*add margin: auto 0; to #header-content

/* Montserrat font import */
@import url('https://fonts.googleapis.com/css?family=Montserrat:100,300,400,600,700&display=swap');

* {
  margin: 0;
  padding: 0;
}

body {
  background-color: #2F2E2E;
}

#main {
  font-family: 'Montserrat', sans-serif;
  color: #E0E1DD;
}

header,
section {
  padding: 40px 60px;
  height: calc(100vh - 80px);
}

#childhood,
#end {
  background: #31303B;
}

ul {
  list-style: none;
}

/* text style */

h1 {
  font-weight: bold;
  font-size: 80px;
}

h2 {
  font-weight: 100;
  font-size: 60px;
}

h3 {
  font-weight: 600;
  font-size: 60px
}

h4 {
  font-weight: 600;
  font-size: 50px;
}

p {
  font-weight: 400;
  font-size: 45px;
}

/* text style end */

/* nav link */

nav ul {
  display: flex;
  justify-content: space-between;
  font-weight: 300;
  font-size: 50px;
}

nav ul li a {
  text-decoration: none;
  color: #E0E1DD;
  transition: .3s color;
}

nav ul li a:hover {
  color: rgb(138, 128, 128);
}

/* nav links end */

#header-content {
  display: flex;
  margin: auto 0; /*add this*/
}

#info-title{
  align-self: center;
}

header figure img {
  height: auto;
  max-height: 850px;
  max-width: 630px;
}

/* add flex*/
header {
  display: flex;
  flex-direction: column;
}

Childhood

Early years

End

About this

Henry Charles Bukowski Jr.

"Find what you love and let it kill you."

8/16/1920

3/09/1994

      next section


text:
Q: How to pass python variables to an html/template file? I have some code to generate a list-like tree diagram to show relationships between items. The code to generate the diagram is in item.py so that I can call on the function as an attribute of the item in the html file. Code below:
item.py
    def get_trace_tree(self):
        trace_tree = '<button type="button" class="myBtn">⊛</button>
' \
                     '
×'
        focal_item = self
        ancestors = []

        if self.links:
            ancestors = self.get_ancestors(ancestors)
            for ancestor in ancestors:
                trace_tree = trace_tree + '
'
                trace_tree = ancestor.trace_from_item(focal_item, trace_tree)
            trace_tree = trace_tree + '
'
        else:
            trace_tree = trace_tree + '
'
            trace_tree = self.trace_from_item(focal_item, trace_tree)
            trace_tree = trace_tree + '
'

        trace_tree = trace_tree + '

'
        return trace_tree

    def get_ancestors(self, ancestors):
        parents = []
        for uid in self.links:
            parents.append(self.tree.find_item(uid))
        for parent in parents:
            if parent.links:
                ancestors = parent.get_ancestors(ancestors)
            else:
                if parent not in ancestors:
                    ancestors.append(parent)
        return ancestors

    def trace_from_item(self, focal_item=None, trace_tree=None):
        if self.child_items:
            if self.uid == focal_item.uid:
                trace_tree = trace_tree + '{{!
{item}
.format(' \
                                          'document=item.document.prefix, item=item.uid)}} '
            else:
                trace_tree = trace_tree + '{{!
{item}
.format(' \
                                          'document=item.document.prefix, item=item.uid)}} '
            trace_tree = trace_tree + '
'
            for child in self.child_items:
                trace_tree = child.trace_from_item(focal_item, trace_tree)
            trace_tree = trace_tree + '
'
        else:
            if self.uid == focal_item.uid:
                trace_tree = trace_tree + '{{!
{item}
.format(' \
                                          'document=item.document.prefix, item=item.uid)}} '
            else:
                trace_tree = trace_tree + '{{!
{item}
.format(' \
                                          'document=item.document.prefix, item=item.uid)}} '
        return trace_tree

And then in the index.tpl file, I call on the function as I'm cycling through items.
index.tpl
%for document in documents:

    %for item in document:

        %if item.child_items or item.links:
            %trace_tree = item.get_trace_tree()
            {{!trace_tree}}
        %end

    %end

%end

This is running with no server errors, but the trace_tree string is storing python variables as characters instead of actual objects - correctly showing a modal button, but displaying {item} instead of the actual item, and then spewing out the rest of the .format() statement in the text of the modal, which obviously should not be displayed. Is there a way of passing the variables through yield or other means to get those variables into the index template file?


text:
Q: form personalization to restrict alphanumeric in a field in oracle apps 11i I am new to oracle apps and need some help in restricting alphanumerics to be entered in a field.If any entered a warning message should be displayed like "no alphanumeric characters are allowed in this field."
Oracle apps 11i.
Thanks and Regards,
Sainadh Vennapusa

A: If you need only numbers ()
In Form Personalization,
Trigger Event: WHEN-VALIDATE-RECORDS,
Condition:
(select nvl( (select 1 from dual
where regexp_like(column, '^[^a-zA-Z0-9]*$')) , '0') as t  from dual)  = '1'

In Actions, Type: 'Message' , Message Type: Error, Message Text: 'Provide the error message'


text:
Q: Logistic regression: controlling variables not significant, what should I conclude/further test? I ran annual logisitic regression on time-series datas. The most important independant variable have coefficient that are significant in a lot of years, that's a relief. But the "controlling variables", have non-significant coefficients. I'm far from an expert in stats.
My sample is very small compared to the litterature that made that test, because I'm analysing a sub-industry that has very few companies in it. But I can't change my sample.
In the literature, the authors that made this precise analysis on bigger samples found significant coefficients to controlling variables too, fact they use to state that: "the effect of the main variable is therefore a separate effect than the ones of controlling variables".
As I can't say that, should I test the correlation between these variables and the main one, and eliminate some of them that present a very high correlation with it every year, stating that these are redundant variables ? If so, which level is considered high ? 0.75, 0.8 ?
I'm planning to say:

*

*Main variable is significant, but not controlling variable

*There are two potential reasons:
1) My yearly samples are too small
2) The effect of the main variable is the same as the effect of some of these controlling variables

*To try to rule out 2), I tested correlation and found that bla bla bla (if low correlations, probably the samples are just too small, if high, I eliminate some variables and re-run regressions)

------------------------------------------------------------
Following Peter's answer (thank you !), I think I should add some details about what I'm testing my study:
Is the propensity to distribute dividends (1 or 0) dependant of the firm's life-cycle stage (using a ratio) ?
Controlling for profitability, asset growth rate, size (market cap.), and lagged dividends (1 or 0).
In every year, the coefficient for lagged dividend is highly significant. And for some of the years (sufficiently for my student thesis), the coefficient of firm's life-cycle stage is significant. The signs of all the other controlling variables are as predicted (most of the time), but always far from significant. I'm hoping that doesn't make my model irrelevant. My pseudo-R square are pretty high. (By the way, does this pseudo-R take in account the variables that are non-significant, or is it the value of the model including only variables that have a significant coefficient ?)

A: There are reasons to include control variables even if they are not significant. E.g.
1) Including them may affect the parameter on the main independent variable (to my mind, this is the true meaning of a "control" variable).
2) Finding a small effect may be important, if others have found a large one.  The idea that the null hypothesis always has to be "something" = 0 is not right. Maybe you want to test if the covariates are the same as in some other work?
3) They may be so standard in the field that not including them would lead to lots of skepticism about the model.


text:
Q: Return variant type from method So I have a resource manager that is basically a dictionary of void* objects that have some metadata describing their type (basic metadata like a string). I have a template method right now that returns an object:
class ResourceManager
{
    template<typename Type>
    Type RetrieveResource( Text name );
};

My question is how can I make this method not a template method? I've done some research into trailing return types and using that funky syntax. The idea is that at some point I have the data as the correct type and I want to return it as that type without additional casting on the end user's part.
I'm shooting for something like this:
auto RetrieveResource( Text name)
{
    return _dictionary[ name ]; // There's more to this, but imagine it returns varying type objects.
}

I've given some thought to implementing a Boost::Any type of object, but it's kind of complicated (not that I'm lazy). I'm trying to avoid template syntax on the end user's part.
Any help would be great. Also I cannot use Boost library structures like variant or any (project specs). Thanks in advance!
I understand I'm kind of asking for magic here, but I figured that's what S/O is for: finding magic. If it's not possible, I understand. But if someone has an innovative solution, that would be awesome.

A: In addition to the other answers, you could do something like this, assuming that every Text key corresponds uniquely to a resource with a known, different Type:
class BaseText
{
    // constructors that take const char *, std::string, etc.
    // .. whatever else you currently have in class Text
};

template<typename Type>
class Text : public BaseText
{
   // constructors that take const char *, std::string, etc.
};

Then change ResourceManager to be:
class ResourceManager
{
    template<typename Type>
    Type RetrieveResource( Text<Type> name );
};

Note this still requires compile-time polymorphism, but means that as long as your user can obtain the correctly-typed version of Text<Type>, they can use it to obtain the correctly typed resource without having to explicitly provide the Type argument again, so it'll look like a normal function call.
This works easily if the set of possible Text<Type> objects can be statically declared and initialized with the right types, which I'm not sure is true in your case.  If, instead, the user must be able to create them at runtime, though, they'll need to know the correct type to create, so it just pushes the problem back a bit further: however, it might be convenient enough if the same Text<Type> object is going to be used over and over again.
Note that you're also out of luck if you or the client need to store different Text<Type> objects together in some kind of data structure, since that will require some sort of type erasure (i.e. upcasting to BaseText). So this is somewhat of a specialized solution but it's possible it could be useful, depending on how things are structured (I really can't know without seeing more of your code).
EDIT: As per the comment below, it seems like the type of the object is determined by the client when they insert an object, so you could possibly do something like this:
class ResourceManager
{
    BaseText PutResource( const BaseText& name, BaseResource& resource );

    template<typename Type>
    Text<Type> PutResource( const BaseText& name, Type& resource );

    BaseResource& RetrieveResource( const BaseText& name );

    template<typename Type>
    Type& RetrieveResource( const Text<Type>& name );
};

So the client is required to hold on to the unique typed key object in order to retrieve the resource later; if they choose to type erase it by upcasting it back to BaseText, then they'll be responsible for recovering the type information correctly, either by downcasting the key before retrieval or downcasting the resource afterwards.
Note that this is just an extra option on top of what you will have to do anyway: if you want to provide access to resources using a non-type-specific key, the only way to do so is by returning a non-specific resource type (i.e. BaseResource, boost::any, boost::variant<...>, or one of their moral equivalents.) However, creating a type-specific subclass of BaseText allows you to obtain a correctly typed resource, using the exact same syntax (i.e. with no explicit template parameter required). Furthermore, this allows the following usage:
// tree is a resource of type `Tree`
auto key = manager.PutResource("Tree01", tree);

// ...

const BaseText& basekey = key; // lose type information

// ...

// these are all equivalent
Tree& tree = dynamic_cast<Tree&>(manager.RetrieveResource("Tree01"));
Tree& tree = dynamic_cast<Tree&>(manager.RetrieveResource(basekey));
Tree& tree = manager.RetrieveResource(key); // no casts required
Tree& tree = manager.RetrieveResource<Tree>("Tree01")

The dynamic_cast versions are basically what you'll need to do without these templated overloads, but the others two versions are extra options on top of that that you can use with this approach without any runtime cost.

A: I'm afraid that would be to ambiguous. You can't overload by return type and you can't use auto as the return type.

A: I think, that the best choice will be returning some base class pointer. The minus is that you force anyone to derive from it, but with smart architecture of base class there could be more pluses


text:
Q: Collection navigation properties may NOT be set on ICollection property I have two clases in relation one-many:
public class ClasssA
  {
    public int Id { get; set; }

    public int ClassBId { get; set; }

    public virtual ClassB ClassB { get; set; }
  }

  public class ClassB
  {
    public int Id { get; set; }

    public string Example { get; set; }

    public virtual ICollection<ClassA> ClassACollection { get; set; }
  }

when I execute query:
var query = EntityQuery.from('ClassB');

I get exception: "Collection navigation properties may NOT be set" in q.js during map to entity property 'ClassACollection'. How to execute query properly?

A: I don't think that your problem has to do with how you are querying, I think it has to do with something else in your code.  The exception seems fairly straight forward - are you trying to pass a value into your collection property?
You are probably trying to use Knockout's setter to set the value of a navigation property like such somewhere in your code -
ClassAObservable.ClassACollection(data.results);

Where you are meaning to push each object like so -
ClassAObservable.ClassACollection.push(result);

And a better option for you is to properly map your ClassA results back to ClassB entities so you don't have to explicitly do this.  Without seeing where you are doing this it is hard to determine which method to take.


text:
Q: Live Audio & Video Streaming with orientation change handling in android I am going to implement live audio and video streaming but unable to play audio and video can  any one help me out??
There is also problem with orientation change.when orientation changes it will restart.
Thanks in advance
please any one help

A: Add android:configChanges="orientation" in you AndroidManifest file;
Add:
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

In your activity;

A: android:configChanges="orientation" - is considerably "bad practice" since you'll have to deal with all kinds of "configuration changes" (not only screen orientation change) all by yourself, when Android otherwise deal with it for you. In your case I'd create a fragment with all music controls in it and set it to:
setRetainInstance(true);

Then add in in the activity startup as:
if (savedInstanceState == null) {
   getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, MyMusicFragment.newInstance())
                .commit();
}

Or even from your xml, depend on your case, and if you want to say have different layouts for tablet and phone type of devices.
Fragments are much flexible/modular and will pay back in future when you'll decide to move things arond


text:
Q: velocity.js duration different when animated two properties I'm trying to animate scale and rotation of an element (which works), but the scale animation is done way before the rotation finishes. The div keeps rotating while the scale animation is done after about 300ms.
I haven't found a syntax in which one can specify the duration for separate properties (I thought the duration should be for all specified properties).
Here's the code, any tips appreciated:
$('#el').velocity({
   rotateZ:[ 1440, 'easeInOut', 0 ],
   scale:[ 1, 'spring', 0 ]
},{
    duration:1000
});

A: Technically, the animation doesn't end at 300ms, it's just the spring easing makes it look like. The spring easing function doesn't move much in the second hald od the animation. Try spring easing with some other parameters, like:
$('#el').velocity({
  rotateZ:[ 360, 'easeInOut', 0.001 ],
  scale:[ 1, [20,0.2], 0.001 ]
},{
  duration:1000
});

Also note that velocity seems to handle 0 values as undefined parameters, so I use 0.001 instead. (it only makes difference on subsequent animations)


text:
Q: How to change the background color or a Table cell depending on other column value in Jquery Datatable? How to change the background color or a Table cell depending on other column value in Jquery Datatable ??
In this fiddle http://jsfiddle.net/5fbo72rm/4/
The table has got three coulmns Name ,Price and Quantity .
How can i change the background color of that  Name cell if the quantity is greater than 40000

    Price
    Volume
    Quantity

var dataSet = [
    [
        "1441.75",
        "100"],
    [
        "1614.45",
        "50"

    ],
    [
        "834.15",
        "3000"]

];

var array_names = ["APPLE", "WHIRLPOOL", "SAMSUNG"];

for (var key in dataSet) {
    if (dataSet.hasOwnProperty(key)) {
        dataSet[key].splice(0, 0, array_names[key]);
    }
}

$(function () {
    $('#allwl').dataTable({
        "iDisplayLength": -1,
            "data": dataSet,
            "columns": [{
            "title": "Name"
        }, {
            "title": "Price"
        }, {
            "title": "Quantity"
        }]
    });
})

I have tried with createdcell , but that is only working with that particuarlar cell ,not for other cell
Could anybody please help me ,how to resolve this ??
http://jsfiddle.net/5fbo72rm/6/

A: $(document).ready(function(){
$('#allwl tr').each(function() {
    var abc = $(this).children('td').eq(2).html();
    if(!abc) {
    return false;
    }
    else {
        if(abc > 40000) {
            $(this).children('td').eq(0).css('background-color', 'red');
        }
    }
});
});

here is your jsfiddle
http://jsfiddle.net/sjkurani/5fbo72rm/9/


text:
Q: Remove Span Tag on adding a text On dropdown change event i am making a column mandatory. if you see the below pic for the first time when TypeofRequest="508web" what format should be return as becomes mandatory. The below code works fine for the first time when i change the dropdown. Once i change the value and come back it is adding 2 stars to the nobr text (refer screen shot below).
how can we over come this
Function for the same
function MandateColumn(ColNames, mandatory)
{for(var i=0;i<ColNames.length;i++)
    {
    if(mandatory=="True"){ var controlvalidate= $("[id^='"+ColNames[i]+"']").prev('td').text();
       var spanTag =" *";
       var newHtml1 = controlvalidate;
           newHtml =newHtml1 + spanTag;
           $("nobr").filter(function()
              {return $(this).text() === controlvalidate;}).html(newHtml);}else{ }}}

Calling the above function (
var BPHCMandateCols= ['FormatShouldReturnas'];
                      MandateColumn(BPHCMandateCols,"True")

A: I was able to achieve this by removing the span tag.
$("[id^='"+ColNames[i]+"']").prev('td').find('.ms-formvalidation').remove();
function MandateColumn(ColNames, mandatory)
{
    for(var i=0;i<ColNames.length;i++)
    {

    if(mandatory=="True")
    {
     $("[id^='"+ColNames[i]+"']").prev('td').find('.ms-formvalidation').remove();
       var controlvalidate= $("[id^='"+ColNames[i]+"']").prev('td').text();
       var newHtml1 = controlvalidate;
       $("nobr").filter(function()
              {return $(this).text() === controlvalidate;}).html(newHtml1);
       var spanTag ="*";

           newHtml =newHtml1 + spanTag;
           $("nobr").filter(function()
              {return $(this).text() === controlvalidate;}).html(newHtml);

    }
      else{

      }
    }
}


text:
Q: How can I target an id inside an specific class? I am constructing a Hanoi Tower, but I'm coming across problems involving parenting elements. I am trying to move the disks using remove a child and append child. Every tower and disk has an ID, but when I try to target a tower ID I get a disk ID.

const container = document.querySelector(".container")
const towers = document.querySelectorAll(".tower")
const disks = document.querySelectorAll(".disk")

let chosenDisc = ""
let chosenTower = ""

towers.forEach(choice => choice.addEventListener("click", (e) => {
    chosenTower = e.target.id
}))

disks.forEach(choices => choices.addEventListener("click", (e) => {
    chosenDisc = e.target
    chosenTower.removeChild(chosenDisc)
    container.appendChild(chosenDisc)
}))

I did not put all IDs selections there, just classes to not long too much, but they are just the name plus numbers.

A: chosenTower is a string and you need to convert it as Element while chosenDisc is a Element object because e.target return Element object. You can use querySelector function to convert it an Element like following
You should replace
chosenTower = e.target.id

to
chosenTower = document.querySelector('#' + e.target.id);

A: Easiest way out is to ask JS for parent element of Disk ID like this:
disks.forEach((choice) =>
  choice.addEventListener(
  "click",
   (e) => {
       chosenDisk = e.target.id;
       chosenTower = e.target.parentElement.id;
       console.log(chosenDisk, " is in ", chosenTower);
     },
   )
);


text:
Q: Is there a way to listen to a div overflow event?
Possible Duplicate:
How to detect overflow in div element?

Is there a cross-browser way to listen to div overflow?
Something like: $('#myDiv').bind("divOverflow", function(){alert('div overflowed!')})

A: You can do that by comparing scrollHeight with clientHeight.
<script type="text/javascript">
function GetContainerSize ()
{
    var container = document.getElementById ("tempDiv");
    var message = "The width of the contents with padding: " + container.scrollWidth + "px.\n";
    message += "The height of the contents with padding: " + container.scrollHeight + "px.\n";

    alert (message);
}
</script>

For more info: How to detect overflow in div element?

A: You could set an interval and check if the element's scrollHeight > offsetHeight. There is no built-in event for this.


text:
Q: Operator norm vs spectral radius for positive matrices I believe the following statement should be true but somehow I don't see an argument:
For every integer $d>1$ there exists a constant $C=C(d)>1$ such that whenever $A$ is a $d \times d$ matrix with all entries integers $>0$, then
$$ \frac{1}{C} \|A\| \le \sigma(A) \le C \|A\|.$$
Here $\sigma(A)$ is the spectral radius of $A$ (which in this case is the Perron-Frobenius eigenvalue of $A$), and $\|A\|=\sup_{\|v\|=1} \|Av\|$
is the operator norm of $A$.
Does anyone see how to prove (or disprove) this statement?
Many thanks,
Ilya.

A: In fact, one can improve a little bit Terry's bound to show that
$\|A\|\le(\sigma(A))^2$, and therefore
  $$ \sigma(A) \le \|A\| \le (\sigma(A))^2. $$
Indeed, this is an immediate consequence of the fact that for a
matrix $A=(a_{ij})_{1\le i,j\le n}$ with positive integer entries one has
$(\sigma(A))^2\ge\sum_{i,j=1}^n a_{ij}$, and the observation that if
$x=(x_1,\ldots,x_n)$ is a unit-length vector, then
  $$ \|Ax\|^2 = \sum_{i=1}^n \Big( \sum_{j=1}^n a_{ij} x_j \Big)^2
              \le \sum_{i=1}^n \Big( \sum_{j=1}^n a_{ij} \Big)^2
              \le \Big( \sum_{i,j=1}^n a_{ij} \Big)^2, $$
implying $\|A\|\le \sum_{i,j=1}^n a_{ij}$.
Notice that by Mike Jury's example above, with $\sigma(A)=\sqrt n+1$
and $\|A\|>n$, the estimate $\|A\|\le(\sigma(A))^2$ is
essentially best possible.
Also notice that the argument just presented actually works for any matrix $A$ with all entries greater than or equal to $1$; the assumption that the entries are
integer is not really used.


text:
Q: Unetbootin stops at 0% extracting bootloader configuration I'm running debian 7 stable release with unetbootin 575-1
If I run 'sudo unetbootin' and select my ISO image (boot-rescue-32bit.iso) and select my newly formatted USB drive click ok, then unetbootin gets stuck on Extracting and Copying Files at 0%.
I've tried the latest unetbootin 608 version as well, same problem.
I've also tried a different ISO, still no joy. Both of the ISO files I know work as I've burnt them to CD and booted them on a computer.
I've also tried a different USB flash drive and a different USB slot (on-board instead of through a USB hub)

A: Be patient :) The file is unpacking and seems to take a while.
I had the same problem and in the time it took me to find and read through all the comments on this page, 0.hfs was unpacked and the installation continued!

A: Do these ISOs contain a distribution that UNetbootin normally supports? The Unetbootin site says:

UNetbootin doesn't use distribution-specific rules for making your
  live USB drive, so most Linux ISO files should load correctly using
  this option. However, not all distributions support booting from USB,
  and some others require extra boot options or other modifications
  before they can boot from USB drives, so these ISO files will not work
  as-is. Also, ISO files for non-Linux operating systems have a
  different boot mechanism, so don't expect them to work either.

A: I'm not sure how this translates to Linux (I'm sure it's somehow applicable, I'm just not sure how it translates exactly), but I was having the same problem on Mac, and I believe it was because of how I'd formatted my USB stick.  Originally I had just created a partition as FAT and was able to load many different ISOs onto the device.  Then I made a mistake and had to re-format(?) the whole device, which included re-making the file/partition table.  Originally I just chose the default "Scheme", "GUID Partition Map".  From this point on I was having trouble.  I had a hunch that it might require the "Master Boot Record" scheme, so I erased the whole USB stick again with that setting.  Then when I ran unetbootin again it worked without issue.
So maybe try recreating the entire partition table on the USB first and see if that helps.
Example of Erase settings in Mac Disk Utility

A: check your antivirus software
i oonce had this issue, it was blocking an autorun file


text:
Q: How to insert many rows into a table, after modifying each line after select? I have a table with one field of type varchar
I want to transfer data from the table to the other, in which a change type of varhar to double
INSERT INTO test_table2 (
        ....
        convert(values, DECIMAL(10, 2)),
      )  SELECT values FROM test_table1;

Why it does not work? I guess that after select have an array of data and change type to double the entire array, I can not.

A: I think this might be the syntax you want:
insert into test_table2(columnname)
    select cast(values as decimal(10, 2))
    from test_table1;


text:
Q: Add certificate to certdata.txt and build firefox with them I have to add some certificates to firefox before building it. Then test it with this certificates. I know that certificates are hardcoded into the certdata.txt, in this location:
mozilla-source\mozilla-central\security\nss\lib\ckfw\builtins
I've tried to add certificates into the certdata.txt using addbuilit from nss-tools. But after building it I get errors.
Compiler shows this errors when reading certdata.txt:

0:49.23 c:/mozilla-source/mozilla-central/obj-x86_64-pc-mingw32/security/nss/lib/ckfw/builtins/builtins_nssckbi/certdata.c(20983,1): warning: missing terminating '"' character [-Winvalid-pp-token]
   0:49.23 "\152\270\202\165\004\122\100\146\207\136\301\151\270\325\275\134

A: Actually it's pretty easy to do.
Firstly you need a nss and nspr, because of nss that is built in to mozilla installer does not have addbuiltin function that we need.
Download NSS for windows
Download Nspr for windows
Second step
unpack both of these files.
Then copy the contents of the NSPR /lib folder to the NSS /bin folder
Copy your certificate and certutil.txt to the NSS /bin folder.
Note: Your certificate should be in .der format!
Third step
Run this code bellow:
addbuiltin -n "My certificate name" -t "CT,C,C" < CAcert.der >> certdata.txt

My certificate name - The name of the certificate that will be added to the certutil.txt.
CT,C,C - Is the trusted properties of the certificate.
CAcert.der - Certificate itself.
certdata.txt - Certificates containing file.

But before copying certutil.txt back to the source code you have to do one more thing.
Open certutil.txt in Notepad++ and turn on hidden characters by Menu View → Show Symbol → Show All Characters. Then change /r/n to /n.
And you've done!


text:
Q: Presetting a result for a particular column in mysql? My app's javascript is set up to display certain columns of mysql data, but if a particular column (col3) has no data in it, the js won't display col3's data, just the rest from the mysql SELECT statement ie if col3="", don't display col3.
In some circumstances, I'd like the js to not display it regardless if there is data in it, but I'd prefer to code the logic in php.
Currently, if I just leave col3 out of the select statement, js displays it as "undefined".
I'm wondering if there is a way in a mysql SELECT statement to make col3 equal an empty string regardless if it has data in it?
Or must I set each of the col3 results to "" in...
while ( $row=$result->fetch_assoc() ) { $row['col3']=""; $resultArray[]=$row; }

Thank you.

A: Your best bet is probably ISNULL or related functions.

On the PHP side, you can use array_merge:

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

For instance:
$defaults = array( 'col3' => '' );
$row = array_merge( $defaults, $row );

If you know your values are going to be NULL (and not nonexistant), then use the following function (untested):
function array_merge_isset() {
  $args = func_get_args();
  $result = array();
  foreach( $args as $arr ) {
    if( !is_array( $arr ) ) {
      continue;
    }

    foreach( $arr as $k=>$v ) {
      if( isset( $v ) ) {
        $result[ $k ] = $v;
      }
    }
  }
  return $result;
}


text:
Q: InvalidOperationException fbauth2 missing I'm facing this issue consistently... before making it as duplicate question I gone through many sites but I didn't find any answer.
Here is the exception on that I got
"fbauth2 is missing from your Info.plist under LSApplicationQueriesSchemes and is required for iOS 9.0"
Here is my Info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fbapi</string>
    <string>fb-messenger-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
</array>

I added all key for ios 9 but its showing above exception while sharing some content at facebook with ShareDialog its really frustrating :|
Can someone please help to resolve this
Thanks


text:
Q: JS fake trusted events - automatic login after autofill by browser I want my site to automatically log the user in once the browser auto-filled the credentials in the login form.
I'm able to detect those auto-fill events via CSS transitions and onAnimationStart on the JS side but I can't receive the credentials until a trusted event is fired by the user.
Is there any way to spoof this? Or even a completely different approach to achieve this?


text:
Q: Percent code for file name in C G'day!
It's a pretty aesthetic warning flag, but I don't like it.
holiday.c:39:37: warning: format specifies type 'char *' but the argument has
      type 'FILE *' (aka 'struct __sFILE *') [-Wformat]
                printf("Error opening file %s\n", fp);
                                       ~~     ^~

This is a copy from the gcc output. Is there a % something for printing a file name, where fp is declared as
FILE *fp;

and opened as:
fp=fopen(argv[1],"r");

from a command line input.
I had trouble finding any literature about it through, but not overly thorough google search.
Thanks! :)


text:
Q: Understanding Shared_ptr with cyclic references? I want to understand the way shared_ptr increments or decrements the reference counts?
 #include <iostream>
 #include <memory>

class B;

class A
{
  public:
  std::shared_ptr<B> b_ptr_;
};

class B
{
  public:
  std::shared_ptr<A> a_ptr_;
};

void func(std::shared_ptr<A> &aptr)
{
  std::shared_ptr<B> bptr = std::make_shared<B>(); //Creating shared pointer
  bptr->a_ptr_ = aptr; // Creating cyclic dependency
  aptr->b_ptr_ = bptr;

  std::cout<<"\nFunc::a_ptr_ use_count = "<<bptr->a_ptr_.use_count();
  std::cout<<"\nFunc::b_ptr_ use_count = "<<aptr->b_ptr_.use_count();
}

int main()
{
  std::shared_ptr<A> aptr = std::make_shared<A>();
  std::cout<<"\nBefore func::a_ptr_ use_count = "<<aptr.use_count();
  func(aptr);
  std::cout<<"\nAfter func::a_ptr_ use_count = "<<aptr.use_count();
  std::cout<<"\nAfter func::b_ptr_ use_count = "<<aptr->b_ptr_.use_count();
  return 0;
}

Output:
This is the output I see:
Before func::a_ptr_ use_count = 1
Func::a_ptr_ use_count = 2
Func::b_ptr_ use_count = 2
After func::a_ptr_ use_count = 2
After func::b_ptr_ use_count = 1

However I was expecting this "After func::a_ptr_ use_count = 1". After bptr goes out of scope in func() the reference counts should have decremented.
What am I missing here?
The question mentioned to be a duplicate does not explain about how the reference counts are incremented/decremented. I am more interested in the internal mechanics of how this is done(in shared_ptr) which is not explained in the answer of the other question attached.

A: Why should the reference count have decremented? bptr may be out of scope, but bptr only affects the reference count for your B object. There are still two references to your A object:

*

*The shared pointer still in scope in main

*The shared pointer stored in your B object

As long as there is live reference to your A object, your B object continues to exist, and vice versa (that's what you triggered intentionally by making cyclic shared references). To make your B object disappear, you'd need one reference in the reference cycle to be weak/raw, and clear the pointer stored in your main method so no top-level references persist.


text:
Q: The space of all Borel probability measures is connected w.r.t. the topology induced by weak convergence Let $E$ be a topological space and $\mathcal P (E)$ the space of all Borel probability measures on $E$. We endow $\mathcal P (E)$ with the topology of weak convergence. Could you have a check on my attempt of below theorem?

Theorem: $\mathcal P (E)$ is connected.

Proof: Fix $\mu, \nu \in \mathcal P (E)$ and Consider the map
$$
\varphi: [0, 1] \to \mathcal P(E), t \mapsto t \mu + (1-t) \nu.
$$
Then $\varphi (1) = \mu$ and $\varphi (0) = \nu$. Let's prove that $\varphi$ is continuous. Let $(t_n) \subset [0, 1]$ such that $t_n \to t \in [0, 1]$. Let $f:E \to \mathbb R$ be bounded continuous. Then
$$
\begin{align}
\int f \mathrm d [t_n \mu + (1-t_n) \nu] &= t_n \int f \mathrm d \mu + (1-t_n) \int f \mathrm d \nu \\
&\xrightarrow{n \to \infty} t \int f \mathrm d \mu + (1-t) \int f \mathrm d \nu \\
&= \int f \mathrm d [t \mu + (1-t) \nu].
\end{align}
$$
Hence $t_n \mu + (1-t_n) \nu \rightharpoonup t \mu + (1-t) \nu$. It follows that $\mathcal P (E)$ is path-connected and thus connected.


text:
Q: Restrict User Access to only upload & view their own files in a SharePoint Site I'm trying to restrict user access on a SharePoint site. This user must be able to upload to SharePoint and view their own files, but they cannot have access to see any other folders or files.
There doesn't seem to be an easy way to do this in permissions, and add & view access allows them to see everyone's uploads. Any help would be greatly appreciated!

A: As a workaround, you could use go to Library Settings -> Versioning settings -> Set "Require Check Out" as "Yes".
When users upload files for the first time, don't check in files. At this time, they can only see their own files.


text:
Q: Unknown seg fault I am getting a seg fault before main even runs. I am rusty with c and cannot find the error. Previous searches have said that if a struct is too large this can happen. I am using addrinfo, and as you can see I've tried malloc'ing it and I still seg fault before main
#include <stdio.h>
/* for printf() and fprintf() */
#include <sys/socket.h>
/* for socket(), connect(), send(), and recv() */
#include <arpa/inet.h>
/* for sockaddr_in and inet_addr() */
#include <stdlib.h>
/* for atoi() and exit() */
#include <string.h>
/* for memset() */
#include <unistd.h>
/* for close() */
#include <sys/types.h>

#include <netinet/in.h>

#include <netdb.h>

#define RCVBUFSIZE 32
/* Size of receive buffer */

void DieWithError(char *errorMessage){};  /* Error handling function */

int main(int argc, char *argv[])
{
    int sock;                         /* Socket descriptor */
    struct addrinfo hints, *servInfo; /*holds the result of getaddrinfo */
    int rttOption;      /* Echo server port */
    char *servIP;                     /* Server IP address (dotted quad) */
    char *portNumber;                 /* String to send to echo server */
    char echoBuffer[RCVBUFSIZE];      /* Buffer for echo string */
    unsigned int echoStringLen;       /* Length of string to echo */
    int bytesRcvd, totalBytesRcvd;    /* Bytes read in single recv() and total bytes read */
    int status;

    servInfo = (struct addrinfo *) malloc (sizeof(struct addrinfo));

    char *httpGetRequest = "GET /";
    char *partOfRequest = "HTTP/1.0\r\nConnection: keep-alive\r\n\r\n";
    strcpy(httpGetRequest, servIP);
    strcpy(httpGetRequest, partOfRequest);

    echoStringLen = strlen(httpGetRequest);
    if ((argc < 3) || (argc > 4))    /* Test for correct number of arguments */
        {
            fprintf(stderr, "Usage: %s <Server URL/IP> <Port Number> [<Option -p>]\n",
                argv[0]);
            exit(1);
        }
    printf("Check after parsing");

    servIP = argv[1];         /* First arg: server IP address (dotted quad) */
    portNumber = argv[2];     /* Second arg: string to echo */
    if (argc == 4 && *argv[3] == 'p')
    {
        rttOption = 1; //print out the rtt
    }

    /* Construct the server address structure */
    memset(&hints, 0, sizeof(hints));     /* Zero out structure */
    hints.ai_family      = AF_UNSPEC;             /* Internet address family */
    hints.ai_socktype    = SOCK_STREAM;

    //getting the linked list?
    if(status = getaddrinfo(servIP, portNumber, &hints, &servInfo) < 0)
        {
            DieWithError("getaddrinfo() failed");
        }

    /* Create a reliable, stream socket using TCP */
    if ((sock = socket(servInfo->ai_family, servInfo->ai_socktype, servInfo->ai_protocol)) < 0)
    {
         DieWithError("socket() failed");
    }

    /* Establish the connection to the echo server */
    if (connect(sock, servInfo->ai_addr, servInfo->ai_addrlen) < 0)
    {
       DieWithError("connect() failed");
    }
    printf("Check");
    /* Send the string to the server */
    if (send (sock, httpGetRequest, echoStringLen, 0) != echoStringLen)
    {
        DieWithError("send() sent a different number of bytes than expected");
    }
    /* Receive the same string back from the server */
    totalBytesRcvd = 0;
    printf("Received: ");   /* Setup to print the echoed string */

    while (totalBytesRcvd < echoStringLen)
    {
        /* Receive up to the buffer size (minus 1 to leave space for a null terminator) bytes from the sender */
        if ((bytesRcvd = recv(sock, httpGetRequest, RCVBUFSIZE -1, 0)) <= 0)
        {
            DieWithError("recv() failed or connection closed prematurely");
        }
            totalBytesRcvd += bytesRcvd;   /* Keep tally of total bytes */
            echoBuffer[bytesRcvd] = '\0';  /* Terminate the string! */
            printf("%s", httpGetRequest);      /* Print the echo buffer */
    }
    printf("\n");    /* Print a final linefeed */
    close(sock);
    exit(0);
    return 0;
}

I expect getting at least hitting the error catch for command line inputs. But instead we are core dumping before we get there.

A: You don't initialize servIP before using it.
This line causes the issue:
strcpy(httpGetRequest, servIP);

You also cannot modify httpGetRequest.
The line above also causes this issue.
Allocate memory for httpGetRequest in some way, and, combined with the other change, your code is fine.


text:
Q: pthread_create() fails with EAGAIN at 291 cycle I had this code:
int main(int argc, char** argv)
{
  pthread_t thread[thr_num];
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  // just for debugging //
    struct rlimit rlim;
    getrlimit(RLIMIT_NPROC, &rlim);
    printf ("soft = %d \n", rlim.rlim_cur);
    printf ("hard = %d \n", rlim.rlim_max);
  ////

  for ( i = 1 ; i <= thr_num ; i++) {
    if(pthread_create( &thread[i], &attr, loggerThread, (void*)argv ) ) {
      printf("pthread_create failure, i = %d, errno = %d \n", i, errno);
      exit(1);
    }
  }

  pthread_attr_destroy(&attr);

  for ( i = 1 ; i <= thr_num ; i++) {
    if( pthread_join(thread[i], (void**)&status ) ) {
      exit(1);
    }
  }

  return 0;
}

void* loggerThread(void* data)
{
  char** sthg = ((char**)data);
  pthread_exit(NULL);
}

I don't understand why when I run this code with thr_num=291, I got an error:
    pthread_create failure, i = 291, errno = 11   (EAGAIN)
with thr_num=290 worked fine. I run this code on a Linux 2.6.27.54-0.2-default (SLES 11)
The rlim.rlim_cur has value 6906 the rlim.rlim_max also. The same I saw with 'ulimit -a' for 'max user processes'.
I checked also /proc/sys/kernel/threads-max  (it was 13813) guided by pthread_create man page.
Did not find any parameters with value 290 for 'sysctl -a' output either.
Ocassionally I found out from this link:
pthread_create and EAGAIN
that: "Even if pthread_exit or pthread_cancel is called, the parent process still need to call pthread_join to release the pthread ID, which will then become recyclable"
so just as a try I modified my code to this:
for ( i = 1 ; i <= thr_num ; i++) {
  if(pthread_create( &thread[i], &attr, loggerThread, (void*)argv ) ) {
    printf("pthread_create failure, i = %d, errno = %d \n", i, errno);
    exit(1);
  }

  if( pthread_join(thread[i], (void**)&status ) ) {
    printf("pthread_join failure, i = %d, errno = %d \n", i, errno);
    exit(1);
  }
}
pthread_attr_destroy(&attr);

and then everything worked: I didn't get the error at 291 cycle.
I would like to understand why with my original code I got the error:
1. because of a wrong programing with threads
2. or I hit some system limit what I couldn't identify
Also would like to know if my correction is good for this problem or what hidden things, pitfalls I eventually introduced with this solution ?
Thanks !

A:
I would like to understand why with my original code I got the error: 1. because of a wrong
  programing with threads 2. or I hit some system limit what I couldn't identify

You likely hit a system limit. Likely you ran out of address space. Default, each thread gets 8-10Mb of stack space on linux. If you create 290 threads, that's using nearly 3Gb of address space - the max for a 32 bit process.
You get EAGAIN in such a case, since there arn't enough resources to create the thread just now (since there isn't enough address space available at the time).
When a thread exits, not all resources of the thread is released (on linux, the entire stack of the thread is kept around).

*

*If the thread is in a detached state, e.g. you called pthread_detach() or specified a detached state when it was created as an attribute to  pthread_create(), all resources are release when the thread exits - but you can't pthread_join() a detached thread.

*If the thread is not detached, you need to call  pthread_join() on it to release the resources.
Note that the modified code of yours where you call pthread_join() inside the loop will:

*

*spawn a thread

*Wait for that thread to finish

*go to 1

i.e. only one other thread is running at a time - which seems a bit pointless.
You can certainly spawn more than one thread that run concurrently - but there's a limit. On your machine, you seem to have found the limit to be around 290.

A: I initially wrote this as a comment, but just in case...
Your code:
  for ( i = 1 ; i <= thr_num ; i++) {
    if(pthread_create( &thread[i], &attr, loggerThread, (void*)argv ) ) {
      printf("pthread_create failure, i = %d, errno = %d \n", i, errno);
      exit(1);
    }
  }
...
  for ( i = 1 ; i <= thr_num ; i++) {
    if( pthread_join(thread[i], (void**)&status ) ) {
      exit(1);
    }
  }

In both the for() loops you check from 1 - thr_num. This means you are out of bounds in your array thread[thr_num] since arrays start at index 0. You should thus iterate from 0 to one less than thr_num:
for ( i = 0 ; i < thr_num ; i++)

I'm actually surprised you didn't get a segmentation fault before hitting 291 as thr_num.


text:
Q: How to know about user id in sessions in rails I have a rails app. Now I want to fetch the users id to store it into the database. But system is showing error saying that id value is nill.
How can I store the user id in a integer or string variable?
 def create
    user = User.authenticate(params[:email], params[:password])
    @data=Information.all
    @num=Information.count()
    @tym=Time.now.getutc
    if user
      session[:user_id] = user.id
      @val=session[:user_id]               # is it possible to store user id in variable @val
      #redirect_to root_url, :notice => "Logged in!"

      #this part is for showing the content of the information table

      respond_to do |format|
        format.html
        format.xml { render xml: @data }
      end
    else
     flash.now.alert = "Invalid email or password"
     render "new"
    end
 end


text:
Q: What special symmetries is this subset of diffeomorphisms? To make a general diffeomorphism I can make an infinitessimal transformation to the coordiante $x^\mu$ to $x^\mu + \delta f^\mu(x)$.
Now I want to restrict it so I only allow transformations such that:
$$\partial_\mu f^\nu(x) + \partial_\nu f^\mu(x) = 0$$
This is because a certain identity I was working on only works if this is the case. (To do with a transformation of the vierbein).
I have checked that all Lorentz symmetries, scale symmetries and special conformal symmetries respect this condition. Do you know if this condition has a name? I have a hunch that this might be the set of general conformal (angle preserving) symmetries or something similar. But I think that has a more complicated expression.

A: This condition defines Killing vectors of the Minkowski metric. To see this, note that for an arbitrary metric, the action of a diff. $x^\mu\rightarrow x^\mu+\xi^\mu(x)$ on the metric is
$$
\mathcal{L}_\xi g_{\mu\nu}=\nabla_\mu\xi_\nu+\nabla_\nu\xi_\nu,
$$
which incidentally is also where the Killing equation comes from.
For the Minkowski metric, of course the Christoffel symbols vanish so the vanishing of the Lie derivative is going to look like $\partial_\mu\xi_\nu+\partial_\nu\xi_\mu=0$.
Since you mention you are working in a Vierbein formulation, this should not be surprising at all. In such a formulation we have a local $SO(3,1)$ symmetry corresponding precisely to those transformations which leave the Minkowski metric invariant, and hence will also leave the metric computed from the Vierbeins invariant, which is to be expected from a frame field formulation of any field theory.


text:
Q: How do I calculate a fee percentage to a transaction upon submit to Paypal? I'm trying to calculate a fee on an amount that users want to pay via paypal.  If they want to donate $20 I need to be able to calculate 2.9% fee so that when the user clicks the donate button to launch paypal they can see the amount with the fee included. I haven't been able to figure it out reading the various questions/answers.  Here is the code for the button.  Any help would be greatly appreciated!  After clicking save it doesn't look like the code is being displayed.  It's html code so that's what I'm looking for, the code to calculate the fee percentage.  Thanks again!

A: (donation amount * fee percentage) / 100
This will give the fee amount based on the percentage. That'll be...
($20 * 2.9) / 100 = $0.58